Files
crosscode-platform/packages/contracts/scripts/json-schemas.cjs
T
joshuaandClaude Opus 5.5 90a98a4306 contracts 1.3.0: agent jobs, reports, stats, join/poll, env templates, church export
Jobs of fixed types with strict argument schemas, signed by the Hub with
Ed25519 over canonical JSON. Agent requests signed with the server's
Ed25519 key. Config sealed to the server's X25519 key (X25519 + HKDF +
AES-256-GCM; Node has no XSalsa20). Exports encrypted with a key that
only travels in the download link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:02:24 +02:00

113 lines
5.0 KiB
JavaScript

// Generates the JSON Schema files in `schemas/` from the zod schemas (ROADMAP-v3 §2), for
// consumers that don't use TypeScript or zod. Run after the build (`npm run build` does it):
// node scripts/json-schemas.cjs write schemas/
// node scripts/json-schemas.cjs --check fail if schemas/ is out of date
// The test (tests/json-schemas.test.ts) uses `buildSchemas` with the source, so the files in git
// always match the zod schemas.
const { z } = require("zod");
const fs = require("node:fs");
const path = require("node:path");
const BASE_ID = "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/";
/** File name (without .json) → schema, from the package exports (`c`) and `c.hub`. */
function contracts(c) {
return {
"event": c.eventSchema,
"event-feed": c.eventFeedSchema,
"event-changed": c.eventChangedSchema,
"church": c.churchSchema,
"identity-claims": c.identityClaimsSchema,
"accounts-call": c.accountsCallSchema,
"user-updated": c.userUpdatedSchema,
"user-updated-reply": c.userUpdatedReplySchema,
"user-deleted": c.userDeletedSchema,
"user-deleted-reply": c.userDeletedReplySchema,
"user-export": c.userExportSchema,
"user-export-reply": c.userExportReplySchema,
"hub-register-request": c.hub.registerRequestSchema,
"hub-register-response": c.hub.registerResponseSchema,
"hub-heartbeat-request": c.hub.heartbeatRequestSchema,
"hub-heartbeat-response": c.hub.heartbeatResponseSchema,
"hub-licence-payload": c.hub.licencePayloadSchema,
"hub-public-key-response": c.hub.publicKeyResponseSchema,
"hub-update-request": c.hub.updateRequestSchema,
"hub-update-request-response": c.hub.updateRequestResponseSchema,
"hub-update-request-cancel": c.hub.updateRequestCancelSchema,
"hub-update-request-cancel-response": c.hub.updateRequestCancelResponseSchema,
"hub-ai-status-request": c.hub.aiStatusRequestSchema,
"hub-ai-status": c.hub.aiStatusSchema,
"hub-ai-complete-request": c.hub.aiCompleteRequestSchema,
"hub-ai-complete-response": c.hub.aiCompleteResponseSchema,
"hub-error": c.hub.hubErrorSchema,
"health": c.hub.healthSchema,
"agent-job": c.agent.agentJobSchema,
"agent-report": c.agent.agentReportSchema,
"script-report": c.agent.scriptReportSchema,
"agent-stats": c.agent.agentStatsSchema,
"agent-join-request": c.agent.joinRequestSchema,
"agent-join-response": c.agent.joinResponseSchema,
"agent-poll-request": c.agent.pollRequestSchema,
"agent-poll-response": c.agent.pollResponseSchema,
"agent-job-config": c.agent.jobConfigSchema,
"env-template": c.agent.envTemplateSchema,
"church-export": c.churchExportSchema,
};
}
// zod writes .startsWith() / .endsWith() / .includes() as a `format` that isn't a JSON Schema
// format (strict validators such as Ajv refuse it) next to a `pattern` that does the real check.
const ZOD_ONLY_FORMATS = new Set(["starts_with", "ends_with", "includes"]);
function dropZodFormats(ctx) {
const json = ctx.jsonSchema;
if (ZOD_ONLY_FORMATS.has(json.format) && json.pattern) delete json.format;
}
/**
* name → JSON Schema (draft 2020-12). `io: "input"` describes what may be sent: unknown fields
* are allowed (consumers drop them, never refuse them) and defaults are optional.
* Checks zod can't express in JSON Schema (refinements, e.g. startsAt matching the sessions)
* only run in zod.
*/
function buildSchemas(c) {
const out = {};
for (const [name, schema] of Object.entries(contracts(c))) {
if (!schema) throw new Error(`json-schemas: no schema exported for "${name}"`);
out[name] = { $id: `${BASE_ID}${name}.json`, ...z.toJSONSchema(schema, { io: "input", override: dropZodFormats }) };
}
return out;
}
const serialise = (json) => `${JSON.stringify(json, null, 2)}\n`;
function main() {
const dir = path.join(__dirname, "..", "schemas");
const schemas = buildSchemas(require("../dist/index.js"));
const check = process.argv.includes("--check");
const stale = [];
if (!check) fs.mkdirSync(dir, { recursive: true });
const wanted = new Set(Object.keys(schemas).map((n) => `${n}.json`));
for (const [name, json] of Object.entries(schemas)) {
const file = path.join(dir, `${name}.json`);
const text = serialise(json);
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
if (current === text) continue;
if (check) stale.push(`${name}.json`);
else fs.writeFileSync(file, text);
}
for (const file of fs.existsSync(dir) ? fs.readdirSync(dir) : []) {
if (!file.endsWith(".json") || wanted.has(file)) continue;
if (check) stale.push(`${file} (no longer generated)`);
else fs.unlinkSync(path.join(dir, file));
}
if (check && stale.length) {
console.error(`schemas/ is out of date: ${stale.join(", ")}. Run npm run build.`);
process.exit(1);
}
console.log(check ? "schemas/ is up to date" : `Wrote ${Object.keys(schemas).length} JSON Schema files to schemas/`);
}
if (require.main === module) main();
module.exports = { buildSchemas, serialise };