Skip to content

Code-first video & image, rendered natively on WebGPU.

24.1 KB
Raw Blame
#!/usr/bin/env -S tsx --conditions development
// Generates the framefields authoring surface from the node packages.
//
//   pnpm run generate:effects             # write the generated files
//   pnpm run generate:effects -- --check  # fail if a committed file is stale
//
// Sources of truth (spec/sync-node.md):
//   - nodes/<node>/package.json   `framefields: { type, kind, schema, ... }`  -> op, class name
//   - nodes/<node>/src/shared/config.ts  zod schema + `.meta()`             -> props, defaults, ranges
//
// Output (never edit by hand):
//   packages/framefields/src/effects/generated/{classes,meta,registry,index}.ts
//   packages/framefields/src/effects/generated/catalog.json
//   plugins/framefields/skills/framefields-effects/references/effects-catalog.md (via sync-effects-catalog.mjs)
//
// A node takes part once its package.json names a `schema`. Nodes without one
// are not migrated yet and keep their hand-written class in effects/classes.ts.
import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
	loadNodeManifests,
	type NodeManifest,
} from "../packages/renderer/src/node-manifest.ts";

const repoRoot = path.resolve(
	path.dirname(fileURLToPath(import.meta.url)),
	"..",
);
const NODES_DIR = path.join(repoRoot, "nodes");
const EFFECTS_DIR = path.join(
	repoRoot,
	"packages",
	"framefields",
	"src",
	"effects",
);
const OUT_DIR = path.join(EFFECTS_DIR, "generated");
const CUSTOM_DIR = path.join(EFFECTS_DIR, "custom");
const BANNER =
	"// @generated by scripts/generate-effects.mts — do not edit.\n" +
	"// Source of truth: nodes/*/package.json (`framefields`) and nodes/*/src/shared/config.ts.\n" +
	"// Regenerate with `pnpm run generate:effects`.\n";

// ---------------------------------------------------------------------------
// JSON Schema (the subset zod emits) and the intermediate model
// ---------------------------------------------------------------------------

interface JsonSchema {
	type?: string | string[];
	properties?: Record<string, JsonSchema>;
	required?: string[];
	additionalProperties?: boolean | JsonSchema;
	items?: JsonSchema;
	enum?: unknown[];
	const?: unknown;
	anyOf?: JsonSchema[];
	oneOf?: JsonSchema[];
	$ref?: string;
	$defs?: Record<string, JsonSchema>;
	default?: unknown;
	minimum?: number;
	maximum?: number;
	title?: string;
	description?: string;
	// FieldMeta keys (packages/node-sdk/shared/config-builder.ts)
	label?: string;
	bindable?: boolean;
	signal?: boolean;
	editorOnly?: boolean;
	tsType?: { name: string; from: string };
}

interface PropMetaModel {
	min?: number;
	max?: number;
	enum?: (string | number | boolean)[];
	props?: Record<string, PropMetaModel>;
}

interface MemberModel {
	key: string;
	type: string;
	optional: boolean;
	doc: string[];
}

interface InterfaceModel {
	name: string;
	members: MemberModel[];
}

interface FieldModel {
	key: string;
	/** Type as written in the Props interface. */
	propType: string;
	/** Type of the resolved value, used for the `declare` property. */
	valueType: string;
	optional: boolean;
	signal: boolean;
	hasDefault: boolean;
	default: unknown;
	doc: string[];
	meta: PropMetaModel;
	description?: string;
}

interface EffectModel {
	manifest: NodeManifest;
	className: string;
	factory: string;
	op: string;
	fields: FieldModel[];
}

class GeneratorError extends Error {}

const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
const pascal = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
const lowerFirst = (s: string) => s.charAt(0).toLowerCase() + s.slice(1);
const literal = (value: unknown) => JSON.stringify(value);

// ---------------------------------------------------------------------------
// Loading: the node's schema, and the zod instance that built it
// ---------------------------------------------------------------------------

type ZodModule = {
	z: {
		toJSONSchema: (
			schema: unknown,
			options: Record<string, unknown>,
		) => JsonSchema;
	};
};

const zodCache = new Map<string, Promise<ZodModule>>();

/**
 * `.meta()` writes to the registry of the zod instance that built the schema,
 * so the JSON Schema must be produced by that same instance. Resolve zod from
 * the node package rather than from this script.
 */
function loadZodFor(nodePath: string): Promise<ZodModule> {
	const require = createRequire(path.join(nodePath, "package.json"));
	let dir = path.dirname(require.resolve("zod"));
	while (!fs.existsSync(path.join(dir, "package.json"))) {
		const parent = path.dirname(dir);
		if (parent === dir)
			throw new GeneratorError(`cannot locate zod for ${nodePath}`);
		dir = parent;
	}
	const pkg = JSON.parse(
		fs.readFileSync(path.join(dir, "package.json"), "utf-8"),
	);
	const root = pkg.exports?.["."];
	const esm =
		typeof root?.import === "string" ? root.import : root?.import?.default;
	const entry = path.join(dir, esm ?? pkg.module ?? pkg.main ?? "index.js");
	let loaded = zodCache.get(entry);
	if (!loaded) {
		loaded = import(pathToFileURL(entry).href) as Promise<ZodModule>;
		zodCache.set(entry, loaded);
	}
	return loaded;
}

async function loadJsonSchema(manifest: NodeManifest): Promise<JsonSchema> {
	const configFile = path.join(manifest.path, "src", "shared", "config.ts");
	if (!fs.existsSync(configFile)) {
		throw new GeneratorError(`${manifest.dir}: src/shared/config.ts not found`);
	}
	// Import the config module by path. The package main also re-exports the
	// WebGPU renderers, which the generator has no reason to load.
	const mod = (await import(pathToFileURL(configFile).href)) as Record<
		string,
		unknown
	>;
	const exportName = manifest.schema as string;
	const schema = mod[exportName];
	if (!schema || typeof schema !== "object" || !("_zod" in schema)) {
		throw new GeneratorError(
			`${manifest.dir}: framefields.schema names "${exportName}", which is not a zod schema exported by src/shared/config.ts`,
		);
	}
	const { z } = await loadZodFor(manifest.path);
	const json = z.toJSONSchema(schema, { io: "input", unrepresentable: "any" });
	if (json.type !== "object" || !json.properties) {
		throw new GeneratorError(
			`${manifest.dir}: ${exportName} must be an object schema`,
		);
	}
	return json;
}

// ---------------------------------------------------------------------------
// JSON Schema -> model
// ---------------------------------------------------------------------------

class Context {
	readonly interfaces = new Map<string, InterfaceModel>();
	readonly typeImports = new Map<string, Set<string>>();
	metaKeysSeen = 0;

	addInterface(model: InterfaceModel, where: string): void {
		const existing = this.interfaces.get(model.name);
		if (existing && literal(existing) !== literal(model)) {
			throw new GeneratorError(
				`${where}: interface "${model.name}" is declared twice with different shapes`,
			);
		}
		this.interfaces.set(model.name, model);
	}

	addTypeImport(name: string, from: string): void {
		if (!this.typeImports.has(from)) this.typeImports.set(from, new Set());
		this.typeImports.get(from)?.add(name);
	}
}

function resolveRef(
	node: JsonSchema,
	root: JsonSchema,
	where: string,
): JsonSchema {
	if (!node.$ref) return node;
	const match = node.$ref.match(/^#\/\$defs\/(.+)$/);
	const target = match ? root.$defs?.[match[1]] : undefined;
	if (!target)
		throw new GeneratorError(`${where}: unresolved $ref ${node.$ref}`);
	// Keywords next to `$ref` (default, description, meta) belong to the use site.
	const { $ref: _ref, ...siblings } = node;
	return { ...target, ...siblings };
}

function bound(value: number | undefined): number | undefined {
	// `z.number().int()` emits ±MAX_SAFE_INTEGER; that is "no bound".
	if (value === undefined || Math.abs(value) >= Number.MAX_SAFE_INTEGER)
		return undefined;
	return value;
}

function describeRange(min?: number, max?: number): string | undefined {
	if (min !== undefined && max !== undefined) return `Range ${min} to ${max}.`;
	if (min !== undefined) return `Minimum ${min}.`;
	if (max !== undefined) return `Maximum ${max}.`;
	return undefined;
}

function docFor(node: JsonSchema, signal: boolean): string[] {
	const doc: string[] = [];
	const text = node.description ?? node.label;
	if (text) doc.push(text.trim().replace(/\*\//g, "*\\/"));
	const facts = [
		describeRange(bound(node.minimum), bound(node.maximum)),
		signal ? "Accepts a signal." : undefined,
	].filter(Boolean);
	if (facts.length > 0) doc.push(facts.join(" "));
	if (node.default !== undefined) doc.push(`@default ${literal(node.default)}`);
	return doc;
}

function metaFor(
	node: JsonSchema,
	root: JsonSchema,
	where: string,
): PropMetaModel {
	const meta: PropMetaModel = {};
	const min = bound(node.minimum);
	const max = bound(node.maximum);
	if (min !== undefined) meta.min = min;
	if (max !== undefined) meta.max = max;
	if (
		node.enum?.every(
			(v) =>
				typeof v === "string" ||
				typeof v === "number" ||
				typeof v === "boolean",
		)
	) {
		meta.enum = node.enum as (string | number | boolean)[];
	}
	if (node.type === "object" && node.properties) {
		meta.props = {};
		for (const [key, raw] of Object.entries(node.properties)) {
			const child = resolveRef(raw, root, `${where}.${key}`);
			if (child.editorOnly) continue;
			meta.props[key] = metaFor(child, root, `${where}.${key}`);
		}
	}
	return meta;
}

function tsTypeOf(
	raw: JsonSchema,
	root: JsonSchema,
	ctx: Context,
	nameHint: string,
	where: string,
): string {
	const node = resolveRef(raw, root, where);

	if (node.tsType) {
		ctx.addTypeImport(node.tsType.name, node.tsType.from);
		return node.tsType.name;
	}
	if (node.const !== undefined) return literal(node.const);
	if (node.enum) return node.enum.map(literal).join(" | ");

	const union = node.anyOf ?? node.oneOf;
	if (union) {
		const parts = union.map((member, i) =>
			tsTypeOf(member, root, ctx, `${nameHint}Option${i + 1}`, where),
		);
		return [...new Set(parts)].join(" | ");
	}
	if (Array.isArray(node.type)) {
		const parts = node.type.map((type) =>
			tsTypeOf({ ...node, type }, root, ctx, nameHint, where),
		);
		return [...new Set(parts)].join(" | ");
	}

	switch (node.type) {
		case "number":
		case "integer":
			return "number";
		case "string":
			return "string";
		case "boolean":
			return "boolean";
		case "null":
			return "null";
		case "array": {
			if (!node.items) return "unknown[]";
			const item = tsTypeOf(
				node.items,
				root,
				ctx,
				`${nameHint}Item`,
				`${where}[]`,
			);
			return item.includes(" | ") ? `(${item})[]` : `${item}[]`;
		}
		case "object": {
			if (!node.properties) {
				if (typeof node.additionalProperties === "object") {
					const value = tsTypeOf(
						node.additionalProperties,
						root,
						ctx,
						`${nameHint}Value`,
						where,
					);
					return `Record<string, ${value}>`;
				}
				break;
			}
			const name =
				node.title && IDENTIFIER.test(node.title) ? node.title : nameHint;
			const members: MemberModel[] = [];
			for (const [key, rawMember] of Object.entries(node.properties)) {
				const member = resolveRef(rawMember, root, `${where}.${key}`);
				if (member.editorOnly) continue;
				members.push({
					key,
					type: tsTypeOf(
						member,
						root,
						ctx,
						`${name}${pascal(key)}`,
						`${where}.${key}`,
					),
					// A member with a default is always present on the resolved value.
					optional: !(
						node.required?.includes(key) || member.default !== undefined
					),
					doc: docFor(member, false),
				});
			}
			ctx.addInterface({ name, members }, where);
			return name;
		}
	}
	throw new GeneratorError(
		`${where}: cannot map this schema to a TypeScript type (${literal(node).slice(0, 120)}). ` +
			"Use a concrete zod type, or add `.meta({ tsType: { name, from } })`.",
	);
}

function buildEffect(
	manifest: NodeManifest,
	json: JsonSchema,
	ctx: Context,
): EffectModel {
	const className = manifest.className ?? manifest.type;
	const fields: FieldModel[] = [];

	for (const [key, raw] of Object.entries(json.properties ?? {})) {
		const where = `${manifest.dir}.${key}`;
		const node = resolveRef(raw, json, where);
		if (node.label !== undefined || node.bindable !== undefined)
			ctx.metaKeysSeen += 1;
		if (node.editorOnly) continue;

		const valueBase = tsTypeOf(
			node,
			json,
			ctx,
			`${className}${pascal(key)}`,
			where,
		);
		const hasDefault = node.default !== undefined;
		// An object default is merged one level deep with the supplied value, so
		// callers may pass any subset of its members.
		const partial =
			hasDefault &&
			typeof node.default === "object" &&
			node.default !== null &&
			!Array.isArray(node.default) &&
			node.type === "object";
		const valueType = partial ? `Partial<${valueBase}>` : valueBase;
		const signal = node.signal ?? node.bindable ?? false;

		fields.push({
			key,
			propType: signal ? `EffectProp<${valueType}>` : valueType,
			valueType,
			optional: !json.required?.includes(key),
			signal,
			hasDefault,
			default: node.default,
			doc: docFor(node, signal),
			meta: metaFor(node, json, where),
			description: node.description ?? node.label,
		});
	}

	return {
		manifest,
		className,
		factory: manifest.factory ?? lowerFirst(className),
		op: manifest.type,
		fields,
	};
}

// ---------------------------------------------------------------------------
// Emit
// ---------------------------------------------------------------------------

function jsdoc(doc: string[], indent: string): string {
	if (doc.length === 0) return "";
	if (doc.length === 1 && !doc[0].startsWith("@"))
		return `${indent}/** ${doc[0]} */\n`;
	return `${indent}/**\n${doc.map((line) => `${indent} * ${line}`).join("\n")}\n${indent} */\n`;
}

const key = (name: string) => (IDENTIFIER.test(name) ? name : literal(name));
const customFile = (effect: EffectModel) =>
	`${effect.manifest.dir.replace(/^node-/, "")}.ts`;
const baseName = (effect: EffectModel) =>
	effect.manifest.custom ? `${effect.className}Base` : effect.className;

function emitClasses(effects: EffectModel[], ctx: Context): string {
	const out: string[] = [BANNER];
	out.push('import { Effect } from "@framefields/core";');
	for (const [from, names] of [...ctx.typeImports].sort(([a], [b]) =>
		a.localeCompare(b),
	)) {
		out.push(`import type { ${[...names].sort().join(", ")} } from "${from}";`);
	}
	out.push('import type { EffectProp } from "../types.js";');
	out.push('import { withDefaults } from "../with-defaults.js";');
	out.push('import { effectMeta } from "./meta.js";');
	out.push("");

	for (const model of [...ctx.interfaces.values()].sort((a, b) =>
		a.name.localeCompare(b.name),
	)) {
		out.push(`export interface ${model.name} {`);
		for (const member of model.members) {
			out.push(
				`${jsdoc(member.doc, "\t")}\t${key(member.key)}${member.optional ? "?" : ""}: ${member.type};`,
			);
		}
		out.push("}", "");
	}

	for (const effect of effects) {
		const name = baseName(effect);
		const props = `${name}Props`;
		const defaults = `${lowerFirst(effect.className)}Defaults`;

		out.push(`export interface ${props} {`);
		for (const field of effect.fields) {
			out.push(
				`${jsdoc(field.doc, "\t")}\t${key(field.key)}${field.optional ? "?" : ""}: ${field.propType};`,
			);
		}
		out.push("}", "");

		out.push(`const ${defaults}: ${props} = {`);
		for (const field of effect.fields) {
			if (field.hasDefault)
				out.push(`\t${key(field.key)}: ${literal(field.default)},`);
		}
		out.push("};", "");

		const domain = effect.manifest.kind === "audio" ? "audio" : "visual";
		if (effect.manifest.custom) {
			out.push(
				`/** @internal Extended by \`effects/custom/${customFile(effect)}\`, which exports \`${effect.className}\`. */`,
			);
		}
		out.push(
			`export class ${name} extends Effect<${props}, ${literal(effect.op)}, ${literal(domain)}> {`,
		);
		out.push(`\tpublic readonly op = ${literal(effect.op)} as const;`);
		out.push(
			`\tpublic override readonly domain = ${literal(domain)} as const;`,
			"",
		);
		for (const field of effect.fields) {
			const type = field.valueType + (field.hasDefault ? "" : " | undefined");
			out.push(`\tpublic declare ${key(field.key)}: ${type};`);
		}
		out.push("");
		out.push(`\tconstructor(config: ${props} = {}) {`);
		out.push(
			`\t\tsuper(withDefaults(${literal(effect.op)}, ${defaults}, config, effectMeta.${effect.className}));`,
		);
		out.push("\t}", "}", "");
	}
	return out.join("\n");
}

function emitMeta(effects: EffectModel[]): string {
	const meta = Object.fromEntries(
		effects.map((effect) => [
			effect.className,
			Object.fromEntries(effect.fields.map((field) => [field.key, field.meta])),
		]),
	);
	return [
		BANNER,
		'import type { EffectMeta } from "../with-defaults.js";',
		"",
		"/** Ranges and allowed values per effect prop, used by `withDefaults()` checks. */",
		`export const effectMeta = ${JSON.stringify(meta, null, "\t")} as const satisfies Record<string, EffectMeta>;`,
		"",
	].join("\n");
}

function importsFor(
	effects: EffectModel[],
	keyword: "import" | "export",
): string[] {
	const lines: string[] = [];
	for (const effect of effects.filter((e) => e.manifest.custom)) {
		lines.push(
			`${keyword} { ${effect.className}, type ${effect.className}Props } from "../custom/${customFile(effect).replace(/\.ts$/, ".js")}";`,
		);
	}
	const generated = effects
		.filter((e) => !e.manifest.custom)
		.flatMap((e) => [e.className, `type ${e.className}Props`]);
	if (generated.length > 0) {
		lines.push(`${keyword} { ${generated.join(", ")} } from "./classes.js";`);
	}
	return lines;
}

function emitRegistry(effects: EffectModel[]): string {
	return [
		BANNER,
		...importsFor(effects, "import"),
		"",
		"/** `Effect.<factory>(config)` helpers, one per generated effect class. */",
		"export const effectFactories = {",
		...effects.map(
			(e) =>
				`\t${key(e.factory)}: (config?: ${e.className}Props) => new ${e.className}(config),`,
		),
		"} as const;",
		"",
	].join("\n");
}

function emitIndex(effects: EffectModel[], ctx: Context): string {
	const interfaces = [...ctx.interfaces.keys()]
		.sort()
		.map((name) => `type ${name}`);
	const visualEffects = effects.filter((e) => e.manifest.kind !== "audio");
	const audioEffects = effects.filter((e) => e.manifest.kind === "audio");
	const visualUnion =
		visualEffects.map((e) => e.className).join(" | ") || "never";
	const audioUnion =
		audioEffects.map((e) => e.className).join(" | ") || "never";

	return [
		BANNER,
		...importsFor(effects, "import"),
		...importsFor(effects, "export"),
		...(interfaces.length > 0
			? [`export { ${interfaces.join(", ")} } from "./classes.js";`]
			: []),
		'export { effectMeta } from "./meta.js";',
		'export { effectFactories } from "./registry.js";',
		"",
		"/** Discriminated unions of all generated effects by domain. */",
		`export type AnyGeneratedVisualEffect = ${visualUnion};`,
		`export type AnyGeneratedAudioEffect = ${audioUnion};`,
		"export type AnyGeneratedEffect = AnyGeneratedVisualEffect | AnyGeneratedAudioEffect;",
		"",
		"export interface GeneratedEffectConfigMap {",
		...effects.map((e) => `\t${literal(e.op)}: ${e.className}Props;`),
		"}",
		"",
	].join("\n");
}

function emitCatalog(effects: EffectModel[]): string {
	const catalog = {
		$comment:
			"Generated by scripts/generate-effects.mts. Machine-readable description of every generated effect class.",
		effects: effects.map((effect) => ({
			name: effect.className,
			op: effect.op,
			kind: effect.manifest.kind,
			factory: effect.factory,
			node: effect.manifest.dir,
			aliases: effect.manifest.aliases,
			custom: effect.manifest.custom ? `custom/${customFile(effect)}` : null,
			props: effect.fields.map((field) => ({
				name: field.key,
				type: field.propType,
				signal: field.signal,
				...(field.hasDefault ? { default: field.default } : {}),
				...(field.meta.min !== undefined ? { min: field.meta.min } : {}),
				...(field.meta.max !== undefined ? { max: field.meta.max } : {}),
				...(field.meta.enum ? { enum: field.meta.enum } : {}),
				...(field.description ? { description: field.description } : {}),
			})),
		})),
	};
	return `${JSON.stringify(catalog, null, "\t")}\n`;
}

/** Runs the repo's own formatter so generated files are stable under `biome check`. */
function format(file: string, content: string): string {
	const biome = path.join(repoRoot, "node_modules", ".bin", "biome");
	try {
		return execFileSync(
			biome,
			[
				"check",
				"--write",
				`--stdin-file-path=${path.relative(repoRoot, file)}`,
			],
			{
				cwd: repoRoot,
				input: content,
				encoding: "utf-8",
				stdio: ["pipe", "pipe", "pipe"],
			},
		);
	} catch (err) {
		const detail = (err as { stderr?: string }).stderr ?? String(err);
		throw new GeneratorError(
			`biome rejected ${path.relative(repoRoot, file)}:\n${detail}`,
		);
	}
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

async function generate(): Promise<Map<string, string>> {
	const manifests = loadNodeManifests(NODES_DIR).filter(
		(m) => (m.kind === "effect" || m.kind === "audio") && m.schema,
	);
	const ctx = new Context();
	const effects: EffectModel[] = [];
	for (const manifest of manifests) {
		effects.push(buildEffect(manifest, await loadJsonSchema(manifest), ctx));
	}
	effects.sort((a, b) => a.className.localeCompare(b.className));

	const problems: string[] = [];
	for (const [label, pick] of [
		["class name", (e: EffectModel) => e.className],
		["factory", (e: EffectModel) => e.factory],
	] as const) {
		const seen = new Map<string, string>();
		for (const effect of effects) {
			const value = pick(effect);
			const owner = seen.get(value);
			if (owner)
				problems.push(
					`${effect.manifest.dir}: ${label} "${value}" is already used by ${owner}`,
				);
			else seen.set(value, effect.manifest.dir);
		}
	}
	for (const effect of effects.filter((e) => e.manifest.custom)) {
		const file = path.join(CUSTOM_DIR, customFile(effect));
		if (!fs.existsSync(file)) {
			problems.push(
				`${effect.manifest.dir}: framefields.custom is true but ${path.relative(repoRoot, file)} does not exist`,
			);
		}
	}
	if (effects.length > 0 && ctx.metaKeysSeen === 0) {
		problems.push(
			"no field metadata (label/bindable) was found on any schema. The generator and the nodes are probably resolving different zod instances.",
		);
	}
	if (problems.length > 0)
		throw new GeneratorError(problems.map((p) => `  - ${p}`).join("\n"));

	const files = new Map<string, string>();
	const add = (name: string, content: string) => {
		const file = path.join(OUT_DIR, name);
		files.set(file, format(file, content));
	};
	add("classes.ts", emitClasses(effects, ctx));
	add("meta.ts", emitMeta(effects));
	add("registry.ts", emitRegistry(effects));
	add("index.ts", emitIndex(effects, ctx));
	add("catalog.json", emitCatalog(effects));
	return files;
}

try {
	const files = await generate();
	const check = process.argv.includes("--check");
	const expected = new Set([...files.keys()].map((f) => path.basename(f)));
	const stray = fs.existsSync(OUT_DIR)
		? fs.readdirSync(OUT_DIR).filter((name) => !expected.has(name))
		: [];

	if (check) {
		const stale = [...files].filter(
			([file, content]) =>
				!fs.existsSync(file) || fs.readFileSync(file, "utf-8") !== content,
		);
		if (stale.length > 0 || stray.length > 0) {
			for (const [file] of stale)
				console.error(`stale: ${path.relative(repoRoot, file)}`);
			for (const name of stray)
				console.error(`unexpected file in generated/: ${name}`);
			console.error(
				"generated effects are out of date — run `pnpm run generate:effects`",
			);
			process.exit(1);
		}
		console.log(`generated effects up to date (${files.size} files)`);
	} else {
		fs.mkdirSync(OUT_DIR, { recursive: true });
		for (const name of stray) fs.rmSync(path.join(OUT_DIR, name));
		for (const [file, content] of files) {
			fs.writeFileSync(file, content);
			console.log(`wrote ${path.relative(repoRoot, file)}`);
		}
	}

	// The skill catalog is derived from catalog.json, so it is refreshed (or
	// checked) in the same run. One command keeps everything in step.
	const catalog = spawnSync(
		process.execPath,
		[
			path.join(repoRoot, "scripts", "sync-effects-catalog.mjs"),
			...(check ? ["--check"] : []),
		],
		{ cwd: repoRoot, stdio: "inherit" },
	);
	if (catalog.status !== 0) process.exit(catalog.status ?? 1);
} catch (err) {
	if (
		err instanceof GeneratorError ||
		(err as Error).name === "NodeManifestError"
	) {
		console.error(`generate-effects failed:\n${(err as Error).message}`);
		process.exit(1);
	}
	throw err;
}