import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { cp, mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join, relative } from "node:path"; import { fileURLToPath } from "node:url"; import { CODEX_PROTOCOL } from "../../src/protocol/codex/version.ts"; // Replaces protocol-conformance/codex with the TypeScript types that the Codex binary on PATH // generates, keeping only the files that protocol-conformance/check.ts imports, directly or through // other generated files. The binary must be the release in CODEX_PROTOCOL. const conformance = fileURLToPath(new URL("../../protocol-conformance/", import.meta.url)); const output = join(conformance, "codex"); const scratch = await mkdtemp(join(tmpdir(), "codex-types-")); // An empty CODEX_HOME keeps the user's configuration and feature flags out of the output. const environment = { ...process.env, CODEX_HOME: join(scratch, "home") }; await mkdir(environment.CODEX_HOME); const codex = (args) => execFileSync("codex", args, { encoding: "utf8", env: environment, stdio: ["ignore", "pipe", "pipe"], }); /** Returns the relative module specifiers that `source` imports or re-exports. */ const specifiers = (source) => [...source.matchAll(/\bfrom\s+"(\.{1,2}\/[^"]+)"/gu)].map(([, specifier]) => specifier); try { const version = codex(["--version"]).trim(); assert.equal( version, `codex-cli ${CODEX_PROTOCOL.version}`, `Install Codex CLI ${CODEX_PROTOCOL.version}, the release in src/protocol/codex/version.ts`, ); const generated = join(scratch, "types"); codex(["app-server", "generate-ts", "--experimental", "--out", generated]); const checkSource = await readFile(join(conformance, "check.ts"), "utf8"); const pending = specifiers(checkSource) .filter((specifier) => specifier.startsWith("./codex/")) .map((specifier) => join(generated, specifier.slice("./codex/".length))); assert(pending.length > 0, "protocol-conformance/check.ts imports nothing from ./codex/"); const files = new Set(); while (pending.length > 0) { const module = pending.pop(); const file = module.endsWith(".ts") ? module : `${module}.ts`; if (files.has(file)) continue; files.add(file); const source = await readFile(file, "utf8"); for (const specifier of specifiers(source)) pending.push(join(dirname(file), specifier)); } await rm(output, { recursive: true, force: true }); for (const file of files) await cp(file, join(output, relative(generated, file))); console.log(`Wrote ${files.size} files from ${version} to ${relative(process.cwd(), output)}`); } finally { await rm(scratch, { recursive: true, force: true }); }