parseRecord

tcmts.cli.libraries.parseRecord · #qq76dgp6 · term · runs anywhere

A record's entries, by mount name: what isn't one (not JSON, or an entry without a namespace and a source) is left out.

import type { LibraryEntry } from "#codebase/tcmts/cli/libraries";

export function parseRecord(text: string): Record<string, LibraryEntry> {
  let v: unknown;
  try {
    v = JSON.parse(text);
  } catch {
    return {};
  }
  if (!v || typeof v !== "object" || Array.isArray(v)) return {};
  const out: Record<string, LibraryEntry> = {};
  for (const [name, e] of Object.entries(v)) {
    if (!e || typeof e !== "object" || !/^[A-Za-z_$][\w$]*$/.test(name)) continue;
    const { namespace, release, sources, did, handle } = e as Record<string, unknown>;
    const kept = Array.isArray(sources)
      ? sources.filter((s): s is string => typeof s === "string")
      : [];
    if (typeof namespace !== "string" || !kept.length) continue;
    out[name] = {
      namespace,
      ...(typeof release === "string" ? { release } : {}),
      sources: kept,
      ...(typeof did === "string" ? { did } : {}),
      ...(typeof handle === "string" ? { handle } : {}),
    };
  }
  return out;
}

uses

used by