import { readFile, writeFile } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const schemaDirectory = resolve(packageRoot, "protocol/schemas"); const outputPath = resolve(packageRoot, "src/protocol/generated/schema-bundle.ts"); const schemaNames = [ "identity", "capabilities", "command", "terminal", "request", "result", "event", "fixture", ]; const schemas = await Promise.all( schemaNames.map(async (name) => ({ name, value: JSON.parse(await readFile(resolve(schemaDirectory, `${name}.schema.json`), "utf8")), })), ); const declarations = schemas .map(({ name, value }) => `export const ${name}Schema = ${JSON.stringify(value, null, 2)} as const;`) .join("\n\n"); const bundle = schemaNames.map((name) => ` ${name}: ${name}Schema,`).join("\n"); const generated = `// Generated by scripts/generate-protocol-schema-module.mjs. Do not edit.\n\n${declarations}\n\nexport const prpSchemaBundle = {\n${bundle}\n} as const;\n`; if (process.argv.includes("--check")) { const current = await readFile(outputPath, "utf8").catch(() => ""); if (current !== generated) { process.stderr.write("Generated PRP schema module is stale. Run pnpm generate:protocol-types.\n"); process.exitCode = 1; } else { process.stdout.write("Generated PRP schema module matches the JSON Schema sources.\n"); } } else { await writeFile(outputPath, generated); process.stdout.write("Generated src/protocol/generated/schema-bundle.ts.\n"); }