Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

4.2 KB
Raw Blame
/**
 * Generate src/hooks/ambient-dts.generated.ts from src/hooks/public.ts.
 *
 * The output is the declaration text `claudish hooks init` writes as
 * `claudish-hooks.d.ts`: the public hook contract wrapped in
 * `declare module "claudish/hooks"`, so a hook file gets editor types with no
 * package installed. It is a TS module exporting a string so the compiled
 * binary embeds it. Runs before `build` and `build:binary`, beside
 * generate-version.ts.
 *
 *   bun run scripts/generate-hooks-dts.ts          write the file
 *   bun run scripts/generate-hooks-dts.ts --check  exit 1 if it is stale
 */
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import ts from "typescript";

const root = join(import.meta.dir, "..");
const publicPath = join(root, "src/hooks/public.ts");
const outPath = join(root, "src/hooks/ambient-dts.generated.ts");

/** The declaration emit of public.ts, exactly as tsc produces it. */
function declarationOf(file: string): string {
  let dts: string | null = null;
  const program = ts.createProgram([file], {
    declaration: true,
    emitDeclarationOnly: true,
    target: ts.ScriptTarget.ES2022,
    module: ts.ModuleKind.ESNext,
    moduleResolution: ts.ModuleResolutionKind.Bundler,
    strict: true,
    skipLibCheck: true,
    types: [],
  });
  const result = program.emit(undefined, (name, text) => {
    if (name.endsWith(".d.ts")) dts = text;
  });
  const errors = ts
    .getPreEmitDiagnostics(program)
    .concat(result.diagnostics)
    .filter((d) => d.category === ts.DiagnosticCategory.Error);
  if (errors.length > 0) {
    const host = {
      getCanonicalFileName: (f: string) => f,
      getCurrentDirectory: () => root,
      getNewLine: () => "\n",
    };
    throw new Error(ts.formatDiagnostics(errors, host));
  }
  if (dts === null) throw new Error("tsc emitted no declaration for public.ts");
  return dts;
}

/** Wrap a module declaration as an ambient `declare module "claudish/hooks"`. */
function ambient(dts: string): string {
  const body = dts
    .split("\n")
    // `declare` is not allowed inside an ambient module; the wrapper is ambient.
    .map((line) => line.replace(/^export declare /, "export ").replace(/^declare /, ""))
    .filter((line) => line.trim() !== "export {};")
    .map((line) => (line.length > 0 ? `  ${line}` : line))
    .join("\n")
    .trimEnd();
  return [
    "// claudish hook types — written by `claudish hooks init`. Do not edit: run",
    "// `claudish hooks init` from a newer claudish to refresh it.",
    "// With this file beside your hook, `import type { HookDefinition } from",
    '// "claudish/hooks"` type-checks with nothing installed.',
    'declare module "claudish/hooks" {',
    body,
    "}",
    "",
  ].join("\n");
}

/**
 * Format with the repo's own biome, so the generated file passes `bun run lint`
 * as written (biome picks the quote style with fewer escapes, among others).
 */
function biomeFormat(source: string): string {
  const bin = join(root, "node_modules/.bin/biome");
  const proc = Bun.spawnSync([bin, "format", `--stdin-file-path=${outPath}`], {
    cwd: root,
    stdin: new TextEncoder().encode(source),
  });
  if (proc.exitCode !== 0) {
    throw new Error(`biome format failed: ${proc.stderr.toString()}`);
  }
  return proc.stdout.toString();
}

function render(text: string): string {
  return biomeFormat(
    [
      "// Auto-generated by scripts/generate-hooks-dts.ts from src/hooks/public.ts — do not edit",
      "",
      "/** The text `claudish hooks init` writes as `claudish-hooks.d.ts`. */",
      "export const HOOKS_AMBIENT_DTS =",
      `  ${JSON.stringify(text)};`,
      "",
    ].join("\n")
  );
}

const next = render(ambient(declarationOf(publicPath)));

if (process.argv.includes("--check")) {
  let current = "";
  try {
    current = readFileSync(outPath, "utf-8");
  } catch {
    // missing counts as stale
  }
  if (current !== next) {
    console.error(
      "[generate-hooks-dts] src/hooks/ambient-dts.generated.ts is stale: run bun run scripts/generate-hooks-dts.ts"
    );
    process.exit(1);
  }
  console.log("[generate-hooks-dts] up to date");
} else {
  writeFileSync(outPath, next);
  console.log("[generate-hooks-dts] src/hooks/public.ts → src/hooks/ambient-dts.generated.ts");
}