@toolproof-core/schema 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/generated/types/Resource_Genesis.d.ts +3 -0
  2. package/dist/generated/types/Resource_Genesis.js +1 -0
  3. package/dist/generated/types/Resource_Job.d.ts +3 -0
  4. package/dist/generated/types/Resource_Job.js +1 -0
  5. package/dist/generated/types/Resource_RawStrategy.d.ts +3 -0
  6. package/dist/generated/types/Resource_RawStrategy.js +1 -0
  7. package/dist/generated/types/Resource_ResourceType.d.ts +3 -0
  8. package/dist/generated/types/Resource_ResourceType.js +1 -0
  9. package/dist/generated/types/Resource_RunnableStrategy.d.ts +3 -0
  10. package/dist/generated/types/Resource_RunnableStrategy.js +1 -0
  11. package/dist/generated/types/types.d.ts +1784 -0
  12. package/dist/generated/types/types.js +1 -0
  13. package/dist/scripts/_lib/config.d.ts +53 -0
  14. package/dist/scripts/_lib/config.js +138 -0
  15. package/dist/scripts/extractSchemas.d.ts +1 -0
  16. package/dist/scripts/extractSchemas.js +210 -0
  17. package/dist/scripts/extractSubSchemaWithDefs.d.ts +1 -0
  18. package/dist/scripts/extractSubSchemaWithDefs.js +187 -0
  19. package/dist/scripts/generateDependencies.d.ts +1 -0
  20. package/dist/scripts/generateDependencies.js +106 -0
  21. package/dist/scripts/generateResourceShells.d.ts +1 -0
  22. package/dist/scripts/generateResourceShells.js +91 -0
  23. package/dist/scripts/generateResourceTypeType.d.ts +1 -0
  24. package/dist/scripts/generateResourceTypeType.js +93 -0
  25. package/dist/scripts/generateSchemaShims.d.ts +1 -0
  26. package/dist/scripts/generateSchemaShims.js +105 -0
  27. package/dist/scripts/generateTypes.d.ts +1 -0
  28. package/dist/scripts/generateTypes.js +550 -0
  29. package/dist/scripts/rewriteAnchors.d.ts +1 -0
  30. package/dist/scripts/rewriteAnchors.js +96 -0
  31. package/package.json +45 -0
  32. package/src/Genesis.json +2043 -0
  33. package/src/Roadmap.json +102 -0
  34. package/src/generated/dependencies.json +299 -0
  35. package/src/generated/resourceTypes/Genesis.json +2043 -0
  36. package/src/generated/resourceTypes/Genesis.ts +2 -0
  37. package/src/generated/resources/Genesis.json +2962 -0
  38. package/src/generated/resources/Genesis.ts +2 -0
  39. package/src/generated/schemas/Genesis.json +1489 -0
  40. package/src/generated/schemas/Genesis.ts +2 -0
  41. package/src/generated/schemas/Goal.json +86 -0
  42. package/src/generated/schemas/Goal.ts +2 -0
  43. package/src/generated/schemas/Job.json +236 -0
  44. package/src/generated/schemas/Job.ts +2 -0
  45. package/src/generated/schemas/RawStrategy.json +667 -0
  46. package/src/generated/schemas/RawStrategy.ts +2 -0
  47. package/src/generated/schemas/ResourceType.json +140 -0
  48. package/src/generated/schemas/ResourceType.ts +2 -0
  49. package/src/generated/schemas/RunnableStrategy.json +737 -0
  50. package/src/generated/schemas/RunnableStrategy.ts +2 -0
  51. package/src/generated/schemas/StrategyRun.json +1025 -0
  52. package/src/generated/schemas/StrategyRun.ts +2 -0
  53. package/src/generated/types/Resource_Genesis.d.ts +3 -0
  54. package/src/generated/types/Resource_Genesis.js +1 -0
  55. package/src/generated/types/Resource_Job.d.ts +3 -0
  56. package/src/generated/types/Resource_Job.js +1 -0
  57. package/src/generated/types/Resource_RawStrategy.d.ts +3 -0
  58. package/src/generated/types/Resource_RawStrategy.js +1 -0
  59. package/src/generated/types/Resource_ResourceType.d.ts +3 -0
  60. package/src/generated/types/Resource_ResourceType.js +1 -0
  61. package/src/generated/types/Resource_RunnableStrategy.d.ts +3 -0
  62. package/src/generated/types/Resource_RunnableStrategy.js +1 -0
  63. package/src/generated/types/types.d.ts +1784 -0
  64. package/src/generated/types/types.js +1 -0
  65. package/src/index.ts +1 -0
  66. package/src/scripts/_lib/config.ts +181 -0
  67. package/src/scripts/extractSchemas.ts +229 -0
  68. package/src/scripts/extractSubSchemaWithDefs.ts +196 -0
  69. package/src/scripts/generateDependencies.ts +120 -0
  70. package/src/scripts/generateResourceShells.ts +105 -0
  71. package/src/scripts/generateResourceTypeType.ts +110 -0
  72. package/src/scripts/generateSchemaShims.ts +115 -0
  73. package/src/scripts/generateTypes.ts +615 -0
  74. package/src/scripts/rewriteAnchors.ts +123 -0
@@ -0,0 +1 @@
1
+ export {}
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Configuration for schema generation scripts
3
+ * All paths are configurable via environment variables
4
+ * Provides sensible defaults for standard project structure
5
+ */
6
+
7
+ import path from 'path';
8
+
9
+ /**
10
+ * Get environment variable with optional default
11
+ */
12
+ function getEnv(name: string, defaultValue: string): string {
13
+ const value = process.env[name];
14
+ return value || defaultValue;
15
+ }
16
+
17
+ /**
18
+ * Schema configuration with required environment variables
19
+ */
20
+ export class SchemaConfig {
21
+ // Base paths
22
+ private readonly root: string;
23
+ private readonly sourceDir: string;
24
+ private readonly sourceFile: string;
25
+ private readonly normalizedDir: string;
26
+ private readonly outputDir: string;
27
+ private readonly typesSrcDir: string;
28
+ private readonly typesDistDir: string;
29
+ private readonly generatedResourcesDir: string;
30
+ private readonly dependencyMapPath: string;
31
+
32
+ // Schema metadata
33
+ private readonly baseUrl: string;
34
+ private readonly version: string;
35
+
36
+ constructor() {
37
+ // Environment variables with sensible defaults
38
+ this.root = getEnv('TP_SCHEMA_ROOT', process.cwd());
39
+ this.sourceDir = getEnv('TP_SCHEMA_SOURCE_DIR', 'src/');
40
+ this.sourceFile = getEnv('TP_SCHEMA_SOURCE_FILE', 'Genesis.json');
41
+ // Intermediate, generated artifact produced by rewriteAnchors.
42
+ // This should NOT live next to the source-of-truth schemas.
43
+ this.normalizedDir = getEnv('TP_SCHEMA_NORMALIZED_DIR', 'src/generated/resourceTypes');
44
+ this.outputDir = getEnv('TP_SCHEMA_OUTPUT_DIR', 'src/generated/schemas');
45
+ this.typesSrcDir = getEnv('TP_SCHEMA_TYPES_SRC_DIR', 'src/generated/types');
46
+ this.typesDistDir = getEnv('TP_SCHEMA_TYPES_DIST_DIR', 'dist/generated/types');
47
+ this.generatedResourcesDir = getEnv('TP_SCHEMA_RESOURCES_DIR', 'src/generated/resources');
48
+ this.dependencyMapPath = getEnv('TP_SCHEMA_DEPENDENCY_MAP_PATH', 'src/generated/dependencies.json');
49
+ this.baseUrl = getEnv('TP_SCHEMA_BASE_URL', 'https://schemas.toolproof.com');
50
+ this.version = getEnv('TP_SCHEMA_VERSION', 'v0');
51
+ }
52
+
53
+ // Path getters
54
+ getRoot(): string {
55
+ return this.root;
56
+ }
57
+
58
+ getSourceDir(): string {
59
+ return path.isAbsolute(this.sourceDir)
60
+ ? this.sourceDir
61
+ : path.join(this.root, this.sourceDir);
62
+ }
63
+
64
+ getSourceFile(): string {
65
+ return this.sourceFile;
66
+ }
67
+
68
+ getSourcePath(): string {
69
+ return path.join(this.getSourceDir(), this.sourceFile);
70
+ }
71
+
72
+ getNormalizedDir(): string {
73
+ return path.isAbsolute(this.normalizedDir)
74
+ ? this.normalizedDir
75
+ : path.join(this.root, this.normalizedDir);
76
+ }
77
+
78
+ getNormalizedSourceFile(): string {
79
+ // We keep the same basename (Genesis.json) in the generated folder.
80
+ // The source-of-truth Genesis.json lives under `TP_SCHEMA_SOURCE_DIR`.
81
+ // The generated/normalized Genesis.json lives under `TP_SCHEMA_NORMALIZED_DIR`.
82
+ return this.sourceFile;
83
+ }
84
+
85
+ getNormalizedSourcePath(): string {
86
+ return path.join(this.getNormalizedDir(), this.getNormalizedSourceFile());
87
+ }
88
+
89
+ getOutputDir(): string {
90
+ return path.isAbsolute(this.outputDir)
91
+ ? this.outputDir
92
+ : path.join(this.root, this.outputDir);
93
+ }
94
+
95
+ getOutputPath(filename: string): string {
96
+ return path.join(this.getOutputDir(), filename);
97
+ }
98
+
99
+ getTypesSrcDir(): string {
100
+ return path.isAbsolute(this.typesSrcDir)
101
+ ? this.typesSrcDir
102
+ : path.join(this.root, this.typesSrcDir);
103
+ }
104
+
105
+ getTypesDistDir(): string {
106
+ return path.isAbsolute(this.typesDistDir)
107
+ ? this.typesDistDir
108
+ : path.join(this.root, this.typesDistDir);
109
+ }
110
+
111
+ getTypesSrcPath(filename: string): string {
112
+ return path.join(this.getTypesSrcDir(), filename);
113
+ }
114
+
115
+ getTypesDistPath(filename: string): string {
116
+ return path.join(this.getTypesDistDir(), filename);
117
+ }
118
+
119
+ getGeneratedResourcesDir(): string {
120
+ return path.isAbsolute(this.generatedResourcesDir)
121
+ ? this.generatedResourcesDir
122
+ : path.join(this.root, this.generatedResourcesDir);
123
+ }
124
+
125
+ getDependencyMapPath(): string {
126
+ return path.isAbsolute(this.dependencyMapPath)
127
+ ? this.dependencyMapPath
128
+ : path.join(this.root, this.dependencyMapPath);
129
+ }
130
+
131
+ // Schema URL methods
132
+ getBaseUrl(): string {
133
+ return this.baseUrl;
134
+ }
135
+
136
+ getVersion(): string {
137
+ return this.version;
138
+ }
139
+
140
+ getSchemaId(schemaName: string): string {
141
+ return `${this.baseUrl}/${this.version}/${schemaName}.json`;
142
+ }
143
+
144
+ /**
145
+ * Check if a URL matches the configured schema base URL pattern
146
+ */
147
+ isSchemaUrl(url: string): boolean {
148
+ const baseUrlPattern = this.baseUrl.replace('https://', 'https?://');
149
+ return new RegExp(`^${baseUrlPattern}/`, 'i').test(url);
150
+ }
151
+
152
+ /**
153
+ * Extract schema name from URL (removes base URL and version prefix)
154
+ */
155
+ extractSchemaName(url: string): string {
156
+ // Remove base URL
157
+ let name = url.replace(new RegExp(`^${this.baseUrl}/`, 'i'), '');
158
+
159
+ // Remove version prefix (v0/, v1/, etc.)
160
+ name = name.replace(/^v\d+\//, '');
161
+
162
+ // Remove .json extension
163
+ name = name.replace(/\.json$/, '');
164
+
165
+ return name;
166
+ }
167
+ }
168
+
169
+ // Singleton instance
170
+ let configInstance: SchemaConfig | null = null;
171
+
172
+ /**
173
+ * Get the schema configuration singleton
174
+ * Throws error if required environment variables are not set
175
+ */
176
+ export function getConfig(): SchemaConfig {
177
+ if (!configInstance) {
178
+ configInstance = new SchemaConfig();
179
+ }
180
+ return configInstance;
181
+ }
@@ -0,0 +1,229 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { getConfig } from "./_lib/config.js";
5
+
6
+ type JSONValue = null | boolean | number | string | JSONValue[] | { [k: string]: JSONValue };
7
+
8
+ interface ExtractOptions {
9
+ inPath: string;
10
+ outPath: string;
11
+ topLevelId?: string;
12
+ }
13
+
14
+ function parseArgs(): ExtractOptions {
15
+ const config = getConfig();
16
+ const argv = process.argv.slice(2);
17
+ let inPath = "";
18
+ let outPath = "";
19
+ let topLevelId: string | undefined;
20
+ for (let i = 0; i < argv.length; i++) {
21
+ const a = argv[i];
22
+ if (a === "--in" && i + 1 < argv.length) inPath = argv[++i];
23
+ else if (a === "--out" && i + 1 < argv.length) outPath = argv[++i];
24
+ else if (a === "--id" && i + 1 < argv.length) {
25
+ let v = argv[++i];
26
+ // Strip accidental surrounding quotes from PowerShell/cmd
27
+ if ((v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))) {
28
+ v = v.slice(1, -1);
29
+ }
30
+ topLevelId = v;
31
+ }
32
+ }
33
+
34
+ // Use config defaults if not provided via CLI
35
+ if (!inPath) {
36
+ // Use generated/normalized version with anchor refs rewritten to pointers
37
+ inPath = config.getNormalizedSourcePath();
38
+ }
39
+ if (!outPath) {
40
+ outPath = config.getOutputPath(config.getSourceFile());
41
+ }
42
+ if (!topLevelId) {
43
+ topLevelId = config.getSchemaId('Genesis');
44
+ }
45
+
46
+ // Resolve to absolute paths from project root
47
+ const cwd = config.getRoot();
48
+ const wasInRelative = !path.isAbsolute(inPath);
49
+ const wasOutRelative = !path.isAbsolute(outPath);
50
+ if (wasInRelative) inPath = path.join(cwd, inPath);
51
+ if (wasOutRelative) outPath = path.join(cwd, outPath);
52
+ // Fallback: resolve relative to script directory if not found
53
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
54
+ if (!fs.existsSync(inPath) && wasInRelative) inPath = path.resolve(scriptDir, inPath);
55
+ const outDir = path.dirname(outPath);
56
+ if (!fs.existsSync(outDir) && wasOutRelative) {
57
+ // Try making directory relative to script dir
58
+ const altOut = path.resolve(scriptDir, outPath);
59
+ const altOutDir = path.dirname(altOut);
60
+ if (!fs.existsSync(path.dirname(outPath))) {
61
+ // Prefer creating outDir at cwd location if possible; otherwise fallback below when writing
62
+ } else {
63
+ outPath = altOut;
64
+ }
65
+ }
66
+ return { inPath, outPath, topLevelId };
67
+ }
68
+
69
+ // Heuristic: determine if a node is a Type envelope
70
+ function isTypeEnvelope(node: any): boolean {
71
+ return (
72
+ node && typeof node === "object" && !Array.isArray(node) &&
73
+ // Treat any object that has an 'nucleusSchema' AND 'identity' as a Type envelope
74
+ // This prevents false positives where 'nucleusSchema' is just a regular schema property
75
+ node.nucleusSchema && typeof node.nucleusSchema === "object" &&
76
+ node.identity && typeof node.identity === "string"
77
+ );
78
+ }
79
+
80
+ // Merge $defs into target, without overwriting existing keys unless identical
81
+ function mergeDefs(target: Record<string, JSONValue>, source?: any, label?: string) {
82
+ if (!source || typeof source !== "object") return;
83
+ const src = (source as any)["$defs"];
84
+ if (!src || typeof src !== "object") return;
85
+ for (const [k, v] of Object.entries(src)) {
86
+ if (!(k in target)) {
87
+ target[k] = v as JSONValue;
88
+ } else {
89
+ // Best-effort: if duplicate key, require structural equality; otherwise, namespace
90
+ const existing = JSON.stringify(target[k]);
91
+ const incoming = JSON.stringify(v);
92
+ if (existing !== incoming) {
93
+ const altKey = `${k}__from_${(label || "defs").replace(/[^A-Za-z0-9_]+/g, "_")}`;
94
+ if (!(altKey in target)) target[altKey] = v as JSONValue;
95
+ }
96
+ }
97
+ }
98
+ }
99
+
100
+ // Deeply traverse an object replacing any Type envelope with its nucleusSchema,
101
+ // and hoist its inner $defs to topDefs. Prevent infinite recursion with a visited set.
102
+ function unwrapTypes(node: JSONValue, topDefs: Record<string, JSONValue>, labelPath: string[] = [], visited = new Set<any>()): JSONValue {
103
+ if (node && typeof node === "object") {
104
+ if (visited.has(node)) return node; // avoid cycles
105
+ visited.add(node);
106
+ }
107
+
108
+ if (isTypeEnvelope(node)) {
109
+ const env = node as any;
110
+ const inner = env.nucleusSchema;
111
+ // Hoist inner $defs before stripping
112
+ mergeDefs(topDefs, inner, labelPath.join("_"));
113
+ // Return the inner schema itself, after also unwrapping any nested envelopes it may contain
114
+ const unwrappedInner = unwrapTypes(inner as JSONValue, topDefs, labelPath.concat([String(env.identity || "env")]), visited);
115
+ return unwrappedInner;
116
+ }
117
+
118
+ if (Array.isArray(node)) {
119
+ return node.map((v, i) => unwrapTypes(v, topDefs, labelPath.concat([String(i)]), visited)) as JSONValue;
120
+ }
121
+
122
+ if (node && typeof node === "object") {
123
+ const out: Record<string, JSONValue> = {};
124
+ for (const [k, v] of Object.entries(node)) {
125
+ if (k === "$defs" && v && typeof v === "object" && !Array.isArray(v)) {
126
+ // Process nested $defs: unwrap each entry value if it's a Type envelope
127
+ const defsOut: Record<string, JSONValue> = {};
128
+ for (const [dk, dv] of Object.entries(v as any)) {
129
+ const unwrapped = unwrapTypes(dv as JSONValue, topDefs, labelPath.concat(["$defs", dk]), visited);
130
+ defsOut[dk] = unwrapped;
131
+ }
132
+ out[k] = defsOut;
133
+ } else {
134
+ out[k] = unwrapTypes(v as JSONValue, topDefs, labelPath.concat([k]), visited);
135
+ }
136
+ }
137
+ return out;
138
+ }
139
+
140
+ return node;
141
+ }
142
+
143
+ /**
144
+ * Pure function that takes a schema document and options, and returns the flattened schema.
145
+ * Performs no I/O operations.
146
+ */
147
+ function extractSchemaLogic(doc: any, topLevelId?: string): any {
148
+ if (!doc || typeof doc !== "object" || !doc.nucleusSchema) {
149
+ throw new Error("Input must be a Type JSON with an nucleusSchema at the top level");
150
+ }
151
+
152
+ const topSchema = (doc as any).nucleusSchema;
153
+ const outDefs: Record<string, JSONValue> = {};
154
+
155
+ // Seed with top-level $defs (if any) before unwrapping
156
+ mergeDefs(outDefs, topSchema, "top");
157
+
158
+ // Unwrap the entire top schema tree so that any nested Type envelopes become raw schemas
159
+ const flattened = unwrapTypes(topSchema as JSONValue, outDefs, ["nucleusSchema"]);
160
+
161
+ // Assemble output: force $schema, optionally set $id, hoist collected $defs
162
+ let base: any;
163
+ if (flattened && typeof flattened === "object" && !Array.isArray(flattened)) {
164
+ base = { ...(flattened as any) };
165
+ } else {
166
+ // If flattened is not an object (should be rare for a top-level schema), wrap it
167
+ base = { const: flattened };
168
+ }
169
+ // Assemble, but avoid duplicating $id: if the flattened base already has $id, prefer it.
170
+ const output: Record<string, JSONValue> = {
171
+ $schema: "https://json-schema.org/draft/2020-12/schema",
172
+ ...base,
173
+ };
174
+ if (topLevelId && !(output as any).$id) {
175
+ (output as any).$id = topLevelId;
176
+ }
177
+
178
+ // Enforce presence of $id: schema must declare an absolute identity.
179
+ if (!(output as any).$id) {
180
+ throw new Error(
181
+ "Flattened schema must define $id. Provide it via CLI --id or include $id in the source nucleusSchema."
182
+ );
183
+ }
184
+
185
+ // Merge collected defs into output.$defs, taking care not to clobber any existing
186
+ if (!("$defs" in output)) output.$defs = {} as any;
187
+ const finalDefs: Record<string, JSONValue> = (output.$defs as any) || {};
188
+ for (const [k, v] of Object.entries(outDefs)) {
189
+ if (!(k in finalDefs)) finalDefs[k] = v;
190
+ }
191
+ output.$defs = finalDefs as any;
192
+
193
+ // Ensure a stable order for readability
194
+ return orderKeys(output, ["$id", "$schema", "$vocabulary", "$defs", "title", "description", "type", "allOf", "anyOf", "oneOf", "not", "if", "then", "else", "properties", "required", "additionalProperties", "unevaluatedProperties"]);
195
+ }
196
+
197
+ function main() {
198
+ const { inPath, outPath, topLevelId } = parseArgs();
199
+
200
+ if (!fs.existsSync(inPath)) {
201
+ console.error(`Input file not found at ${inPath}`);
202
+ process.exit(1);
203
+ }
204
+
205
+ const raw = fs.readFileSync(inPath, "utf8");
206
+ const doc = JSON.parse(raw);
207
+
208
+ // Core logic is now in a pure function
209
+ const ordered = extractSchemaLogic(doc, topLevelId);
210
+
211
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
212
+ fs.writeFileSync(outPath, JSON.stringify(ordered, null, 4), "utf8");
213
+ console.log(`Wrote flattened schema to ${outPath}`);
214
+ }
215
+
216
+ function orderKeys(obj: any, preferred: string[]): any {
217
+ if (Array.isArray(obj)) return obj.map((v) => orderKeys(v, preferred));
218
+ if (!obj || typeof obj !== "object") return obj;
219
+ const keys = Object.keys(obj);
220
+ const sorted = [
221
+ ...preferred.filter((k) => keys.includes(k)),
222
+ ...keys.filter((k) => !preferred.includes(k)).sort()
223
+ ];
224
+ const out: any = {};
225
+ for (const k of sorted) out[k] = orderKeys(obj[k], preferred);
226
+ return out;
227
+ }
228
+
229
+ main();
@@ -0,0 +1,196 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { getConfig } from './_lib/config.js';
4
+
5
+ /**
6
+ * Generic extractor: given a subschema name that exists under Genesis.json $defs,
7
+ * produce a standalone JSON Schema file that contains that subschema plus an inner $defs
8
+ * object holding all direct & transitive local $defs dependencies (by #/$defs/... $ref).
9
+ *
10
+ * Genesis.json itself is left unchanged.
11
+ *
12
+ * Usage:
13
+ * node ./dist/scripts/extractSubschemaWithDefs.js --name <DefName>
14
+ *
15
+ * Writes: src/genesis/generated/schemas/<DefName>.json
16
+ */
17
+ /**
18
+ * Pure function to extract a subschema and its dependencies from a genesis object.
19
+ * Performs no I/O operations.
20
+ *
21
+ * @param genesis The root Genesis schema object
22
+ * @param name The name of the definition to extract
23
+ * @returns The standalone subschema
24
+ */
25
+ function extractSubSchemaLogic(genesis: any, name: string): any {
26
+ const rootDefs: Record<string, any> | undefined = genesis.$defs;
27
+ if (!rootDefs || typeof rootDefs !== 'object') {
28
+ throw new Error('No $defs object found in Genesis.json');
29
+ }
30
+
31
+ const target = rootDefs[name];
32
+ if (!target) {
33
+ throw new Error(`Subschema named '${name}' not found under $defs in Genesis.json`);
34
+ }
35
+
36
+ // Collect transitive local $defs names referenced by target
37
+ const needed = collectLocalDefClosure(target, rootDefs);
38
+
39
+ // Build output schema: clone target and attach collected subset as $defs
40
+ const targetClone = deepClone(target);
41
+ const defsOut: Record<string, any> = {};
42
+ for (const defName of needed) {
43
+ // Avoid including the target itself inside its own $defs (mirrors previous pattern)
44
+ if (defName === name) continue;
45
+ const defSchema = rootDefs[defName];
46
+ if (defSchema === undefined) {
47
+ console.warn(`Warning: referenced def '${defName}' missing in root $defs (skipped).`);
48
+ continue;
49
+ }
50
+ defsOut[defName] = deepClone(defSchema);
51
+ }
52
+
53
+ // Merge any pre-existing inner $defs of targetClone (if present) giving precedence to collected ones
54
+ const existingInner = isObject(targetClone.$defs) ? targetClone.$defs : {};
55
+ targetClone.$defs = { ...existingInner, ...defsOut };
56
+
57
+ return targetClone;
58
+ }
59
+
60
+ async function main() {
61
+ const config = getConfig();
62
+ const { name } = parseArgs(process.argv.slice(2));
63
+ if (!name) {
64
+ console.error('Missing --name <DefName> argument');
65
+ process.exit(1);
66
+ }
67
+
68
+ const schemasDir = config.getOutputDir();
69
+ const genesisPath = path.join(schemasDir, config.getSourceFile());
70
+ const outPath = config.getOutputPath(`${name}.json`);
71
+
72
+ if (!fs.existsSync(genesisPath)) {
73
+ console.error(`Genesis.json not found at ${genesisPath}`);
74
+ process.exit(1);
75
+ }
76
+
77
+ const raw = fs.readFileSync(genesisPath, 'utf-8');
78
+ const genesis = JSON.parse(raw);
79
+
80
+ try {
81
+ // Call the pure logic function
82
+ const result = extractSubSchemaLogic(genesis, name);
83
+
84
+ // I/O: Write the result
85
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
86
+ fs.writeFileSync(outPath, JSON.stringify(result, null, 2) + '\n');
87
+ console.log(`Extracted subschema '${name}' -> ${outPath}`);
88
+ } catch (error: any) {
89
+ console.error(error.message);
90
+ process.exit(1);
91
+ }
92
+ }
93
+
94
+ // ---- Helpers ----
95
+ function parseArgs(args: string[]): { name?: string } {
96
+ let name: string | undefined;
97
+ for (let i = 0; i < args.length; i++) {
98
+ const a = args[i];
99
+ if (a === '--name') {
100
+ name = args[i + 1];
101
+ i++;
102
+ } else if (a.startsWith('--name=')) {
103
+ name = a.split('=')[1];
104
+ }
105
+ }
106
+ return { name };
107
+ }
108
+
109
+ function isObject(v: any): v is Record<string, any> {
110
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
111
+ }
112
+
113
+ function deepClone<T>(v: T): T {
114
+ if (Array.isArray(v)) return v.map((x) => deepClone(x)) as any;
115
+ if (isObject(v)) {
116
+ const out: Record<string, any> = {};
117
+ for (const k of Object.keys(v)) out[k] = deepClone((v as any)[k]);
118
+ return out as any;
119
+ }
120
+ return v;
121
+ }
122
+
123
+ function extractPointerDefName(ref: string): string | null {
124
+ // Accept refs like '#/$defs/Name' only (single-level under $defs)
125
+ if (!ref || !ref.startsWith('#/')) return null;
126
+ const parts = ref.slice(2).split('/'); // remove '#/'
127
+ if (parts.length !== 2) return null;
128
+ if (parts[0] !== '$defs') return null;
129
+ // Decode JSON Pointer tokens for the def name
130
+ const name = parts[1].replace(/~1/g, '/').replace(/~0/g, '~');
131
+ return name;
132
+ }
133
+
134
+ function resolveRefToDefName(ref: string, rootDefs: Record<string, any>): string | null {
135
+ if (!ref) return null;
136
+ // Case 1: JSON Pointer into $defs: '#/$defs/Name'
137
+ const byPointer = extractPointerDefName(ref);
138
+ if (byPointer) return byPointer;
139
+
140
+ // Case 2: Anchor ref: '#Name' -> find a def whose nucleusSchema.$anchor equals 'Name'
141
+ if (ref.startsWith('#') && !ref.startsWith('#/')) {
142
+ const anchor = ref.slice(1);
143
+ if (!anchor) return null;
144
+ for (const [defName, defSchema] of Object.entries(rootDefs)) {
145
+ if (!defSchema || typeof defSchema !== 'object') continue;
146
+ // Flattened Genesis has defs as the extraction schema itself (with $anchor at the top level).
147
+ // Unflattened may have { nucleusSchema: { $anchor } } envelopes. Support both.
148
+ const topLevelAnchor = (defSchema as any).$anchor;
149
+ const nested = (defSchema as any).nucleusSchema;
150
+ const nestedAnchor = nested && typeof nested === 'object' ? nested.$anchor : undefined;
151
+ const defAnchor = typeof topLevelAnchor === 'string' ? topLevelAnchor : (typeof nestedAnchor === 'string' ? nestedAnchor : undefined);
152
+ if (defAnchor === anchor) {
153
+ return defName;
154
+ }
155
+ }
156
+ }
157
+
158
+ return null;
159
+ }
160
+
161
+ function collectLocalDefClosure(node: any, rootDefs: Record<string, any>): Set<string> {
162
+ const needed = new Set<string>();
163
+ const queue: string[] = [];
164
+
165
+ function visit(n: any) {
166
+ if (Array.isArray(n)) {
167
+ for (const item of n) visit(item);
168
+ return;
169
+ }
170
+ if (!isObject(n)) return;
171
+ if (typeof n.$ref === 'string') {
172
+ const name = resolveRefToDefName(n.$ref, rootDefs);
173
+ if (name && !needed.has(name)) {
174
+ needed.add(name);
175
+ queue.push(name);
176
+ }
177
+ }
178
+ for (const val of Object.values(n)) visit(val);
179
+ }
180
+
181
+ visit(node);
182
+
183
+ while (queue.length > 0) {
184
+ const name = queue.shift()!;
185
+ const def = rootDefs[name];
186
+ if (!def) continue; // Missing def handled earlier
187
+ visit(def);
188
+ }
189
+
190
+ return needed;
191
+ }
192
+
193
+ main().catch((e) => {
194
+ console.error(e);
195
+ process.exit(1);
196
+ });