findOnRegistry

tcmts.cli.libraries.findOnRegistry · #uvbr2hxo · term · runs anywhere

Ask a registry what its libraries hold that matches query (a name, words in docs, or :a type): the registry registryToAsk says, and the libraries it found, each with what matched and its tcm lib add line.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { registryToAsk } from "#codebase/tcmts/cli/libraries";
import type { FoundLibrary } from "#codebase/tcmts/cli/libraries";

export async function findOnRegistry(
  cb: Codebase,
  o: { query: string; registry?: string | undefined },
): Promise<{ registry: string; found: FoundLibrary[] }> {
  const registry = registryToAsk(cb.store, o.registry);
  let res: Response;
  try {
    res = await fetch(`${registry}/api/search?${new URLSearchParams({ q: o.query })}`, {
      headers: { accept: "application/json" },
    });
  } catch (e) {
    throw new Error(`couldn't reach ${registry}: ${(e as Error).cause ?? (e as Error).message}`);
  }
  const body = (await res.json().catch(() => undefined)) as
    | { libraries?: FoundLibrary[] }
    | undefined;
  if (!res.ok || !Array.isArray(body?.libraries))
    throw new Error(
      `${registry} answered ${res.status}${body?.libraries ? "" : ", not as a registry does"}: is it a tcm registry?`,
    );
  return { registry, found: body.libraries };
}

uses

used by