iterate.com / ui

git clone https://git.iterate.com/repos/ui

ui / scripts / shadcn-registry.tsmain at d68d7e1

// scripts/shadcn-registry.ts — THE SHADCN REGISTRY (AGENTS.md): an app in another
// repo gets one of our rendered components with `npx shadcn add iterate/packages/<item>` and keeps its
// own copy. That is shadcn's GitHub registry (https://ui.shadcn.com/docs/registry/github): Copybara
// copies packages/ to github.com/iterate/packages after each deploy, and copybara/packages/registry.json
// becomes that repo's root registry.json, which includes packages/ui/registry.json. The CLI reads the
// items and their files from there; nothing is built or published.
//
// packages/ui/registry.json names each item and its files. `update` works out the rest from the files
// themselves and writes it back: each file's type, the packages the files import (`dependencies`) and
// the items they import through `#/` (`registryDependencies`: shadcn's by name, `button`, and ours by
// their GitHub address, `iterate/packages/<item>`). It also writes packages/ui/package.json's
// publishConfig.exports, the modules a no-build page imports from the published package: one per item
// and per vendored shadcn component (packages/ui/browser-entries.ts). Lint and Typecheck fails when
// registry.json or that map is not what `update` writes.
//
// A component item that uses packages/ui's own tokens (src/styles/tokens.css: `text-success`,
// `text-2xs`) carries them as `cssVars` (packages/ui/scripts/component-tokens.ts).
//
// One item is not files: `theme` (`"type": "registry:theme"`), iterate's look, whose fields `update`
// writes from packages/ui/src/styles/iterate.css (packages/ui/scripts/iterate-look.ts), so an app gets the
// look with `npx shadcn add iterate/packages/theme`.
//
// `update` throws where an app installing an item would get a file that imports something it does
// not have: a relative import of another item's file (the app's copy of that item may live elsewhere,
// or not exist), a `#/` import of a file that is in no item, or a private `@iterate-com/*` package. A
// file in src/components (shadcn's ui/ aside) or src/lib that no item lists throws too.
//
// `round-trip` (.depot/workflows/shadcn-drift.yml; it needs shadcn's registry for `button` and the
// rest) installs this commit's items before they are public: it builds them as the public copy lays
// them out, serves them locally, and asks the CLI's dry run what `shadcn add` of every item writes into
// an app with packages/ui's own components.json. That must be packages/ui's own bytes: the CLI
// rewrites `#/` imports to the app's aliases, which here are packages/ui's.
//
//   node scripts/shadcn-registry.ts update
//   node scripts/shadcn-registry.ts round-trip
import { execFile, spawnSync } from "node:child_process";
import {
  copyFileSync,
  mkdirSync,
  mkdtempSync,
  readdirSync,
  readFileSync,
  rmSync,
  symlinkSync,
  writeFileSync,
} from "node:fs";
import { createServer } from "node:http";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join, posix, relative, resolve } from "node:path";
import { promisify } from "node:util";
import { parseSync } from "oxc-parser";
import { createCli } from "trpc-cli";
import { z } from "zod";
import { browserEntries, publishExports } from "../browser-entries.ts";
import { componentTokens, TOKENS_SOURCE } from "./component-tokens.ts";
import { fontFilesOf, LOOK_SOURCE, themeAppliedProblems, themeItem } from "./iterate-look.ts";
import { parseView } from "./shadcn-drift.ts";

const ui = resolve(import.meta.dirname, "..");

/** The root registry.json of a GitHub registry that includes this one, as github.com/iterate/packages
 *  had it: the round trip builds the items in that layout. */
const ROOT_REGISTRY = {
  $schema: "https://ui.shadcn.com/schema/registry.json",
  name: "iterate",
  homepage: "https://github.com/iterate/packages",
  include: ["packages/ui/registry.json"],
};

/** registry.json's hand-written part: each item's name, description and files, or the theme
 *  item's name, description and type. `update` derives the rest, so parsing drops it. */
const Registry = z.object({
  $schema: z.string(),
  name: z.string(),
  homepage: z.string(),
  items: z.array(
    z.union([
      z.object({
        name: z.string(),
        description: z.string(),
        type: z.literal("registry:theme"),
      }),
      z.object({
        name: z.string(),
        description: z.string(),
        files: z.array(z.object({ path: z.string() })),
      }),
    ]),
  ),
});
type Registry = z.infer<typeof Registry>;

/** An item as `shadcn build` writes it, its other fields kept as they are. */
const BuiltItem = z.looseObject({ registryDependencies: z.array(z.string()).optional() });

/** The public copy's GitHub address. A GitHub registry names an item of its own by its full address. */
const GITHUB_REGISTRY = "iterate/packages";

/** Every package an app already has: shadcn's own items leave them out too. */
const ASSUMED_PACKAGES = new Set(["react", "react-dom"]);

/** `registry` with each item's file types, `dependencies` and `registryDependencies` worked out from
 *  `source` (every file under packages/ui/src, by its path in packages/ui, `src/components/…`), and
 *  the theme item's fields from the look's file there (`read` gives a file it imports from
 *  `iterate`). Throws listing every file an app could not install as is (the header). Pure. */
export function withDependencies(
  registry: Registry,
  source: Map<string, string>,
  read: (specifier: string) => string,
) {
  const problems: string[] = [];
  const itemOf = new Map<string, string>();
  for (const item of registry.items)
    for (const { path } of filesOf(item)) {
      if (!source.has(path)) problems.push(`${item.name}: ${path} does not exist`);
      const other = itemOf.get(path);
      if (other) problems.push(`${path} is in both ${other} and ${item.name}`);
      itemOf.set(path, item.name);
    }
  for (const path of source.keys())
    if (belongsInRegistry(path) && !itemOf.has(path))
      problems.push(`${path} is in no item: add it to one in registry.json`);

  const items = registry.items.map((item) => {
    if (!("files" in item))
      return { ...item, ...themeItem({ css: source.get(LOOK_SOURCE)!, read }) };
    const dependencies = new Set<string>();
    const registryDependencies = new Set<string>();
    for (const { path } of item.files) {
      if (!/\.tsx?$/.test(path) || !source.has(path)) continue;
      for (const specifier of importsOf(path, source.get(path)!)) {
        const found = resolveImport({ path, specifier, item: item.name, source, itemOf });
        if (!found) continue;
        if ("problem" in found) problems.push(`${path}: ${found.problem}`);
        else if ("dependency" in found) dependencies.add(found.dependency);
        else registryDependencies.add(found.registryDependency);
      }
    }
    const files = item.files.map(({ path }) => ({ path, type: fileType(path) }));
    const tokens = componentTokens({
      tokensCss: source.get(TOKENS_SOURCE) || "",
      sources: item.files.map(({ path }) => source.get(path) || ""),
    });
    return {
      name: item.name,
      type: files.every((file) => file.type === "registry:lib")
        ? "registry:lib"
        : "registry:component",
      description: item.description,
      ...(dependencies.size > 0 && { dependencies: [...dependencies].sort() }),
      ...(registryDependencies.size > 0 && {
        registryDependencies: [...registryDependencies].sort(),
      }),
      ...tokens,
      files,
    };
  });
  if (problems.length > 0)
    throw new Error(
      `packages/ui/registry.json: an app installing these items would get files that import what it does not have:\n${problems.map((problem) => `- ${problem}`).join("\n")}`,
    );
  return { ...registry, items };
}

function filesOf(item: Registry["items"][number]) {
  return "files" in item ? item.files : [];
}

/** Every file in src/components (but shadcn's own ui/) and src/lib is in some item; tests, test
 *  fixtures and a folder's agent notes (AGENTS.md) are not. */
function belongsInRegistry(path: string) {
  return (
    (path.startsWith("src/components/") || path.startsWith("src/lib/")) &&
    !path.startsWith("src/components/ui/") &&
    !/\.test\.tsx?$/.test(path) &&
    !/\.fixture\.json$/.test(path) &&
    posix.basename(path) !== "AGENTS.md"
  );
}

/** Where `shadcn add` writes the file: the app's lib alias, or its components alias (an svg goes
 *  beside the component that imports it). */
function fileType(path: string) {
  return path.startsWith("src/lib/") ? "registry:lib" : "registry:component";
}

/** Every module a file imports: static, re-exported and dynamic. */
function importsOf(path: string, content: string) {
  const { module, errors } = parseSync(path, content);
  if (errors.length > 0) throw new Error(`${path} does not parse: ${errors[0]!.message}`);
  return [
    ...module.staticImports.map((entry) => entry.moduleRequest.value),
    ...module.staticExports.flatMap((entry) =>
      entry.entries.flatMap((exported) =>
        exported.moduleRequest ? [exported.moduleRequest.value] : [],
      ),
    ),
    ...module.dynamicImports.map(({ moduleRequest }) => {
      const literal = /^(["'])(.*)\1$/.exec(content.slice(moduleRequest.start, moduleRequest.end));
      if (!literal) throw new Error(`${path}: a dynamic import of something other than a string`);
      return literal[2]!;
    }),
  ];
}

/** What one import asks of the app installing `item`: a package, a registry item, or nothing (a
 *  file of the same item, which travels with it, or a package every app has). */
function resolveImport(input: {
  path: string;
  specifier: string;
  item: string;
  source: Map<string, string>;
  itemOf: Map<string, string>;
}): { problem: string } | { dependency: string } | { registryDependency: string } | undefined {
  const { path, specifier, item, source, itemOf } = input;
  if (specifier.startsWith(".")) {
    const target = posix.normalize(posix.join(posix.dirname(path), specifier));
    if (!source.has(target)) return { problem: `${specifier} does not exist` };
    if (itemOf.get(target) === item) return;
    return {
      problem: `${specifier} is ${itemOf.get(target) || "in no item"}'s, not ${item}'s: import it as #/${target.slice("src/".length)}`,
    };
  }
  if (specifier.startsWith("#/")) {
    const target = `src/${specifier.slice("#/".length)}`;
    if (!source.has(target)) return { problem: `${specifier} does not exist` };
    if (target.startsWith("src/components/ui/"))
      return { registryDependency: posix.basename(target).replace(/\.tsx?$/, "") };
    const owner = itemOf.get(target);
    if (!owner)
      return { problem: `${specifier} is in no item, so an app installing ${item} lacks it` };
    if (owner === item) return { problem: `${specifier} is ${item}'s own: import it relatively` };
    return { registryDependency: `${GITHUB_REGISTRY}/${owner}` };
  }
  if (specifier.startsWith("@iterate-com/"))
    return {
      problem: `${specifier} is a private workspace package, which an app outside the monorepo cannot install`,
    };
  const name = specifier.startsWith("@")
    ? specifier.split("/").slice(0, 2).join("/")
    : specifier.split("/")[0]!;
  if (ASSUMED_PACKAGES.has(name)) return;
  return { dependency: name };
}

/** Each item file (`files`, by repository path) the dry run did not write, or wrote differently
 *  from `current`. The CLI drops a file's leading comment (it returns ts-morph's
 *  `sourceFile.getText()`, which starts at the first statement: shadcn-ui/ui#9206, fixed by the
 *  open shadcn-ui/ui#11920), so that is all a file may lose. shadcn's own items it writes are
 *  shadcn-drift.ts's to check: which "use client" lines they get depends on the batch. Pure. */
export function roundTripProblems(input: {
  files: string[];
  written: { path: string; content: string }[];
  current: (path: string) => string;
}) {
  const written = new Map(input.written.map((file) => [file.path, file.content]));
  return input.files.flatMap((path) => {
    if (!written.has(path)) return [`${path} (not written)`];
    const expected = /\.tsx?$/.test(path)
      ? input.current(path).replace(/^(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*/, "")
      : input.current(path);
    return written.get(path) === expected ? [] : [`${path} (differs)`];
  });
}

/** Every file under packages/ui/src, by its path in packages/ui. */
function readSource() {
  return new Map(
    readdirSync(join(ui, "src"), { recursive: true, withFileTypes: true })
      .filter((entry) => entry.isFile())
      .map((entry) => {
        const file = join(entry.parentPath, entry.name);
        return [relative(ui, file), readFileSync(file, "utf8")] as const;
      }),
  );
}

function readRegistry() {
  return Registry.parse(JSON.parse(readFileSync(join(ui, "registry.json"), "utf8")));
}

/** Writes each item's file types and dependencies into registry.json, and the published package's
 *  exports into package.json, and has the CLI validate the registry. */
export async function update() {
  const require = createRequire(join(ui, "package.json"));
  const read = (specifier: string) => readFileSync(require.resolve(specifier), "utf8");
  const registry = withDependencies(readRegistry(), readSource(), read);
  writeFileSync(join(ui, "registry.json"), `${JSON.stringify(registry, null, 2)}\n`);
  const manifest = JSON.parse(readFileSync(join(ui, "package.json"), "utf8"));
  manifest.publishConfig.exports = publishExports(
    browserEntries(),
    fontFilesOf({ css: readFileSync(join(ui, LOOK_SOURCE), "utf8"), read }),
  );
  writeFileSync(join(ui, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
  const run = spawnSync("pnpm", ["exec", "shadcn", "registry", "validate", "registry.json"], {
    cwd: ui,
    stdio: "inherit",
  });
  if (run.status !== 0) throw new Error(`shadcn registry validate exited ${run.status}`);
}

/** Fails when `shadcn add` of every item, as this commit has them, writes anything but packages/ui's
 *  own bytes. */
export async function roundTrip() {
  const work = mkdtempSync(join(tmpdir(), "shadcn-registry-"));
  const server = createServer((request, response) => {
    const name = /^\/([\w-]+\.json)$/.exec(request.url || "")?.[1];
    if (!name) return response.writeHead(404).end();
    try {
      response.writeHead(200, { "content-type": "application/json" });
      response.end(readFileSync(join(work, "r", name)));
    } catch {
      response.writeHead(404).end();
    }
  });
  await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
  const { port } = server.address() as { port: number }; // listening on a TCP port, never a pipe
  try {
    // The public copy's layout: its root registry.json, including packages/ui's. `shadcn build`
    // writes each item as the CLI assembles it from GitHub: every file's content, at its path there.
    const copy = join(work, "copy");
    mkdirSync(join(copy, "packages"), { recursive: true });
    writeFileSync(join(copy, "registry.json"), `${JSON.stringify(ROOT_REGISTRY, null, 2)}\n`);
    symlinkSync(ui, join(copy, "packages/ui"));
    const built = spawnSync(
      "pnpm",
      ["exec", "shadcn", "build", "registry.json", "-o", join(work, "r"), "-c", copy],
      { cwd: ui, encoding: "utf8" },
    );
    if (built.status !== 0)
      throw new Error(`shadcn build exited ${built.status}:\n${built.stdout}${built.stderr}`);
    // An item's `iterate/packages/<item>` dependencies would be read from the public copy, which
    // does not have this commit yet: they point at this commit's own build instead.
    const registry = readRegistry();
    for (const item of registry.items) {
      const file = join(work, "r", `${item.name}.json`);
      const built = BuiltItem.parse(JSON.parse(readFileSync(file, "utf8")));
      built.registryDependencies = built.registryDependencies?.map((dependency) =>
        dependency.startsWith(`${GITHUB_REGISTRY}/`)
          ? `http://127.0.0.1:${port}/${dependency.slice(GITHUB_REGISTRY.length + 1)}.json`
          : dependency,
      );
      writeFileSync(file, JSON.stringify(built));
    }
    // an app with packages/ui's aliases (package.json's `#/*` imports, components.json), compiler
    // options and stylesheet
    const app = join(work, "app");
    mkdirSync(join(app, "src/styles"), { recursive: true });
    copyFileSync(join(ui, "package.json"), join(app, "package.json"));
    copyFileSync(join(ui, "components.json"), join(app, "components.json"));
    copyFileSync(join(ui, "src/styles/globals.css"), join(app, "src/styles/globals.css"));
    writeFileSync(
      join(app, "tsconfig.json"),
      JSON.stringify({ extends: join(ui, "tsconfig.json") }),
    );
    const items = registry.items.map((item) => `http://127.0.0.1:${port}/${item.name}.json`);
    // async: this process's server answers the CLI's fetches while it runs
    const run = await promisify(execFile)(
      "pnpm",
      ["exec", "shadcn", "add", ...items, "--dry-run", "--view", "src/", "--cwd", app],
      { cwd: ui, env: { ...process.env, NO_COLOR: "1" }, maxBuffer: 64 * 1024 * 1024 },
    ).catch((error: { stdout: string; stderr: string; code: number }) => {
      throw new Error(`shadcn add --dry-run exited ${error.code}:\n${error.stdout}${error.stderr}`);
    });
    const output = `${run.stdout}${run.stderr}`;
    if (!/^└ Run without --dry-run to apply\.$/m.test(output))
      throw new Error(`shadcn add --dry-run printed no files:\n${output}`);
    const problems = roundTripProblems({
      files: registry.items.flatMap((item) =>
        filesOf(item).map((file) => `packages/ui/${file.path}`),
      ),
      written: parseView(output, "packages/ui"),
      current: (path) => readFileSync(join(ui, path.slice("packages/ui/".length)), "utf8"),
    });
    if (problems.length > 0)
      throw new Error(
        `shadcn add of every item does not write packages/ui's files back:\n${problems.map((problem) => `- ${problem}`).join("\n")}`,
      );
    // The theme item writes no files: `add` it for real (its font package is in this package.json
    // already, so nothing installs) and look for each of its values where the app's stylesheet
    // needs them.
    const theme = registry.items.find((item) => !("files" in item));
    if (theme) {
      await promisify(execFile)(
        "pnpm",
        [
          "exec",
          "shadcn",
          "add",
          `http://127.0.0.1:${port}/${theme.name}.json`,
          "--yes",
          "--cwd",
          app,
        ],
        { cwd: ui, env: { ...process.env, NO_COLOR: "1" } },
      );
      const require = createRequire(join(ui, "package.json"));
      const applied = themeAppliedProblems({
        item: themeItem({
          css: readFileSync(join(ui, LOOK_SOURCE), "utf8"),
          read: (specifier) => readFileSync(require.resolve(specifier), "utf8"),
        }),
        css: readFileSync(join(app, "src/styles/globals.css"), "utf8"),
      });
      if (applied.length > 0)
        throw new Error(
          `shadcn add ${theme.name} leaves the app without the look:\n${applied.map((problem) => `- ${problem}`).join("\n")}`,
        );
    }
    console.log(
      `shadcn add of ${items.length} items writes their files back as packages/ui has them, and the theme's values into the app's stylesheet`,
    );
  } finally {
    server.close();
    rmSync(work, { recursive: true, force: true });
  }
}

void createCli(import.meta).run();