searchRegistry

tcmts.cli.libraries.searchRegistry · #flw7meoc · term · runs on the server

uses tcmts.cli.style.bold, which uses node:util

tcm lib search <query> [--registry <url>]: ask a registry what its libraries hold that matches query (a name, words in docs, or :a type), and say each library with what matched and its tcm lib add line: the registry registryToAsk says.

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

export async function searchRegistry(
  cb: Codebase,
  o: { query: string; registry?: string | undefined },
): Promise<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?`,
    );
  const found = body.libraries;
  for (const l of found) {
    const counts = [
      `${l.dependents} dependent${l.dependents === 1 ? "" : "s"}`,
      ...(l.stars ? [`★ ${l.stars}`] : []),
    ].join(" · ");
    console.log(`${bold(`@${l.handle ?? l.did}/${l.package}`)} ${l.version}  ${dim(counts)}`);
    if (l.description) console.log(`  ${l.description}`);
    const width = Math.max(...l.hits.map((h) => h.name.length));
    for (const h of l.hits)
      console.log(
        `  ${h.name.padEnd(width)}  ${dim(h.signature)}${h.detail ? `  ${dim(h.detail)}` : ""}`,
      );
    if (l.more) console.log(dim(`  and ${l.more} more`));
    console.log(`  ${l.add}`);
  }
  const n = found.reduce((k, l) => k + l.hits.length + l.more, 0);
  console.log(
    found.length
      ? dim(
          `${n} definition${n === 1 ? "" : "s"} in ${found.length} librar${found.length === 1 ? "y" : "ies"}, from ${registry}`,
        )
      : `nothing in ${registry}'s libraries matches ${o.query}`,
  );
  return found;
}

uses

used by