All files / src/storage/get-file zone-file-to-profile.ts

72.72% Statements 16/22
60% Branches 3/5
100% Functions 1/1
80% Lines 16/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 383x 3x 3x 3x 3x             3x 3x 3x   3x   3x   3x   3x 3x 3x 3x   3x                      
import { parseZoneFile, ZoneFileObject } from 'micro-stacks/zone-file';
import { getTokenFileUrl } from '../common';
import { getPersonFromLegacyFormat } from '../profile/schemas';
import { extractProfile } from '../profile/tokens';
import { fetchPrivate } from 'micro-stacks/common';
 
/**
 * Resolves a profile from a zonefile string
 * @param zoneFile - the string zonefile to parse
 * @param publicKeyOrAddress - the public key or address of the keypair that is thought to have signed the token
 */
export async function resolveZoneFileToProfile(zoneFile: string, publicKeyOrAddress?: string) {
  let zoneFileJson: ZoneFileObject | null = parseZoneFile(zoneFile);
  Iif (!zoneFileJson.hasOwnProperty('$origin')) zoneFileJson = null;
 
  const hasKeys = zoneFileJson && Object.keys(zoneFileJson).length > 0;
 
  Iif (!hasKeys) return getPersonFromLegacyFormat(JSON.parse(zoneFile));
 
  const tokenFileUrl: string | null = getTokenFileUrl(zoneFileJson);
 
  if (tokenFileUrl) {
    try {
      const response = await fetchPrivate(tokenFileUrl);
      const tokenRecords: any[] = await response.json();
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
      return extractProfile(tokenRecords[0].token, publicKeyOrAddress);
    } catch (e) {
      console.error(
        `[micro-stacks] resolveZoneFileToProfile: error fetching token file ${tokenFileUrl}: ${e}`
      );
      throw e;
    }
  }
  console.debug('[micro-stacks] Token file url not found. Resolving to blank profile.');
  return {};
}