@modernrelay/orbit-omnigraph 0.2.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.
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ import { parsePgSchema, schemaFingerprint, ORBIT_TYPE_KEY } from './chunk-32TESFMK.js';
3
+ import { readFileSync, writeFileSync } from 'fs';
4
+ import process from 'process';
5
+ import { Omnigraph } from '@modernrelay/omnigraph';
6
+
7
+ // src/codegen.ts
8
+ var SCALAR_TS = {
9
+ String: "string",
10
+ Blob: "string",
11
+ Bool: "boolean",
12
+ I32: "number",
13
+ I64: "number",
14
+ U32: "number",
15
+ U64: "number",
16
+ F32: "number",
17
+ F64: "number",
18
+ Date: "string",
19
+ DateTime: "string"
20
+ };
21
+ function tsStringLiteral(value) {
22
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\r/g, "\\r").replace(/\n/g, "\\n")}'`;
23
+ }
24
+ function tsType(type) {
25
+ if (typeof type === "string") return SCALAR_TS[type];
26
+ switch (type.kind) {
27
+ case "vector":
28
+ return "number[]";
29
+ case "enum":
30
+ return type.values.length === 0 ? "string" : type.values.map(tsStringLiteral).join(" | ");
31
+ case "list":
32
+ return `${SCALAR_TS[type.element]}[]`;
33
+ case "unknown":
34
+ return "unknown";
35
+ }
36
+ }
37
+ function wireNote(type) {
38
+ if (typeof type === "string") {
39
+ switch (type) {
40
+ case "Date":
41
+ return "`Date` \u2014 normalized to 'YYYY-MM-DD' (UTC) on load (B.6).";
42
+ case "DateTime":
43
+ return "`DateTime` \u2014 normalized to ISO 8601 UTC on load (B.6).";
44
+ case "Blob":
45
+ return "`Blob` \u2014 `data:` URI for inline blobs, stored URI refs verbatim (B.6/B.10).";
46
+ case "I64":
47
+ case "U64":
48
+ return `\`${type}\` \u2014 JSON numbers round silently past \xB12^53 (B.6).`;
49
+ default:
50
+ return null;
51
+ }
52
+ }
53
+ switch (type.kind) {
54
+ case "vector":
55
+ return `\`Vector(${type.dim})\`.`;
56
+ case "unknown":
57
+ return `Unrecognized \`.pg\` type \`${type.raw}\` \u2014 value passes through verbatim.`;
58
+ default:
59
+ return null;
60
+ }
61
+ }
62
+ var IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
63
+ function propertyKey(name) {
64
+ return IDENT_RE.test(name) ? name : tsStringLiteral(name);
65
+ }
66
+ function emitProperty(lines, prop) {
67
+ const note = wireNote(prop.type);
68
+ if (note !== null) lines.push(` /** ${note} */`);
69
+ const base = tsType(prop.type);
70
+ lines.push(` ${propertyKey(prop.name)}: ${prop.optional ? `${base} | null` : base};`);
71
+ }
72
+ function emitPropsInterface(lines, interfaceName, kindLabel, typeName, properties) {
73
+ lines.push(`/** Normalized attrs for ${kindLabel} type \`${typeName}\` (B.6). */`);
74
+ lines.push(`export interface ${interfaceName} {`);
75
+ if (!properties.some((p) => p.name === "id")) {
76
+ lines.push(
77
+ ` /** Physical Omnigraph id \u2014 injected into every export line's \`data\` (B.2); unique per ${kindLabel} type only (B.3). */`
78
+ );
79
+ lines.push(" id: string;");
80
+ }
81
+ for (const prop of properties) {
82
+ emitProperty(lines, prop);
83
+ }
84
+ lines.push("}");
85
+ lines.push("");
86
+ }
87
+ function emitAttrsUnion(lines, unionName, doc, members) {
88
+ lines.push(`/** ${doc} */`);
89
+ if (members.length === 0) {
90
+ lines.push(`export type ${unionName} = never;`);
91
+ } else {
92
+ lines.push(`export type ${unionName} =`);
93
+ members.forEach(({ typeName, interfaceName }, i) => {
94
+ const tail = i === members.length - 1 ? ";" : "";
95
+ lines.push(
96
+ ` | ({ ${tsStringLiteral(ORBIT_TYPE_KEY)}: ${tsStringLiteral(typeName)} } & ${interfaceName})${tail}`
97
+ );
98
+ });
99
+ }
100
+ lines.push("");
101
+ }
102
+ function headerBanner(fingerprintLine, extra) {
103
+ const lines = [
104
+ "// AUTO-GENERATED \u2014 DO NOT EDIT.",
105
+ "//",
106
+ "// .pg \u2192 TypeScript typed attrs (orbit spec Appendix B.6), generated by",
107
+ "// @modernrelay/orbit-omnigraph (`orbit-omnigraph-codegen`).",
108
+ `// ${fingerprintLine}`
109
+ ];
110
+ if (extra !== void 0 && extra.length > 0) {
111
+ for (const raw of extra.split("\n")) {
112
+ lines.push(raw.startsWith("//") ? raw : `// ${raw}`.trimEnd());
113
+ }
114
+ }
115
+ lines.push(
116
+ "//",
117
+ "// Shapes describe attrs AFTER the adapter's B.6 normalization (both read",
118
+ "// paths converge on the query-path string encodings):",
119
+ "// Date \u2192 'YYYY-MM-DD' \xB7 DateTime \u2192 ISO 8601 \xB7 enum(...) \u2192 literal union",
120
+ "// I64/U64/F32/F64 \u2192 number \xB7 Vector(n) \u2192 number[] \xB7 T? \u2192 T | null",
121
+ "// Blob \u2192 string ('data:' URI for inline blobs, stored URI for external)",
122
+ ""
123
+ );
124
+ return lines;
125
+ }
126
+ function generateTypes(schema, opts) {
127
+ const fingerprintLine = opts?.fingerprint !== void 0 ? `Schema fingerprint: ${opts.fingerprint} (B.2).` : `Schema fingerprint: ${schemaFingerprint(JSON.stringify(schema))} (parsed model \u2014 regenerate from .pg source for the B.2 source fingerprint).`;
128
+ const lines = headerBanner(fingerprintLine, opts?.header);
129
+ const nodeMembers = schema.nodes.map((n) => ({
130
+ typeName: n.name,
131
+ interfaceName: `${n.name}Props`
132
+ }));
133
+ const edgeMembers = schema.edges.map((e) => ({
134
+ typeName: e.name,
135
+ interfaceName: `${e.name}EdgeProps`
136
+ }));
137
+ schema.nodes.forEach((n, i) => {
138
+ const member = nodeMembers[i];
139
+ if (member) emitPropsInterface(lines, member.interfaceName, "node", n.name, n.properties);
140
+ });
141
+ schema.edges.forEach((e, i) => {
142
+ const member = edgeMembers[i];
143
+ if (member) emitPropsInterface(lines, member.interfaceName, "edge", e.name, e.properties);
144
+ });
145
+ emitAttrsUnion(
146
+ lines,
147
+ "NodeAttrs",
148
+ "Discriminated union over every node type's normalized attrs \u2014 `'orbit:type'` is injected by the adapter (B.3).",
149
+ nodeMembers
150
+ );
151
+ emitAttrsUnion(
152
+ lines,
153
+ "EdgeAttrs",
154
+ "Discriminated union over every edge type's normalized attrs \u2014 `'orbit:type'` is the edge name (B.3).",
155
+ edgeMembers
156
+ );
157
+ lines.push("/** Type-name \u2192 props lookup for both kinds (closed sets from the schema \u2014 B.3). */");
158
+ lines.push("export interface TypeMap {");
159
+ lines.push(" nodes: {");
160
+ for (const m of nodeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);
161
+ lines.push(" };");
162
+ lines.push(" edges: {");
163
+ for (const m of edgeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);
164
+ lines.push(" };");
165
+ lines.push("}");
166
+ lines.push("");
167
+ lines.push("export type NodeTypeName = keyof TypeMap['nodes'];");
168
+ lines.push("export type EdgeTypeName = keyof TypeMap['edges'];");
169
+ lines.push("");
170
+ return lines.join("\n");
171
+ }
172
+ function generateTypesFromPgSource(source, opts) {
173
+ const schema = parsePgSchema(source);
174
+ const options = { fingerprint: schemaFingerprint(source) };
175
+ if (opts?.header !== void 0) options.header = opts.header;
176
+ return generateTypes(schema, options);
177
+ }
178
+
179
+ // src/codegen-cli.ts
180
+ var USAGE = `Usage:
181
+ orbit-omnigraph-codegen <schema.pg> [-o <out.ts>]
182
+ orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o <out.ts>]
183
+
184
+ Generates TypeScript typed attrs (spec B.6) from a .pg schema \u2014 read from a
185
+ file, or fetched from a running omnigraph-server (unauthenticated client).
186
+ Writes to stdout unless -o is given.
187
+ `;
188
+ function parseArgs(argv) {
189
+ const args = {};
190
+ for (let i = 0; i < argv.length; i++) {
191
+ const arg = argv[i];
192
+ if (arg === void 0) continue;
193
+ switch (arg) {
194
+ case "-h":
195
+ case "--help":
196
+ return "help";
197
+ case "-o":
198
+ case "--out": {
199
+ const v = argv[++i];
200
+ if (v === void 0) return `missing value for ${arg}`;
201
+ args.out = v;
202
+ break;
203
+ }
204
+ case "--from-server": {
205
+ const v = argv[++i];
206
+ if (v === void 0) return "missing value for --from-server";
207
+ args.fromServer = v;
208
+ break;
209
+ }
210
+ case "--graph": {
211
+ const v = argv[++i];
212
+ if (v === void 0) return "missing value for --graph";
213
+ args.graph = v;
214
+ break;
215
+ }
216
+ default:
217
+ if (arg.startsWith("-")) return `unknown option '${arg}'`;
218
+ if (args.schemaPath !== void 0) return `unexpected argument '${arg}'`;
219
+ args.schemaPath = arg;
220
+ }
221
+ }
222
+ if (args.fromServer !== void 0 && args.schemaPath !== void 0) {
223
+ return "pass a schema file OR --from-server, not both";
224
+ }
225
+ if (args.fromServer !== void 0 && args.graph === void 0) {
226
+ return "--from-server requires --graph <id> (schema reads are graph-scoped)";
227
+ }
228
+ if (args.fromServer === void 0 && args.schemaPath === void 0) {
229
+ return "no schema given";
230
+ }
231
+ return args;
232
+ }
233
+ async function main(argv) {
234
+ const parsed = parseArgs(argv);
235
+ if (parsed === "help") {
236
+ process.stdout.write(USAGE);
237
+ return 0;
238
+ }
239
+ if (typeof parsed === "string") {
240
+ process.stderr.write(`orbit-omnigraph-codegen: ${parsed}
241
+
242
+ ${USAGE}`);
243
+ return 2;
244
+ }
245
+ let source;
246
+ let provenance;
247
+ if (parsed.fromServer !== void 0 && parsed.graph !== void 0) {
248
+ const og = new Omnigraph({ baseUrl: parsed.fromServer, graphId: parsed.graph });
249
+ const schema = await og.schema.get();
250
+ source = schema.schemaSource;
251
+ provenance = `Source: ${parsed.fromServer} (graph '${parsed.graph}', GET /schema)`;
252
+ } else if (parsed.schemaPath !== void 0) {
253
+ source = readFileSync(parsed.schemaPath, "utf8");
254
+ provenance = `Source: ${parsed.schemaPath}`;
255
+ } else {
256
+ return 2;
257
+ }
258
+ const output = generateTypesFromPgSource(source, { header: provenance });
259
+ if (parsed.out !== void 0) {
260
+ writeFileSync(parsed.out, output);
261
+ process.stderr.write(`orbit-omnigraph-codegen: wrote ${parsed.out}
262
+ `);
263
+ } else {
264
+ process.stdout.write(output);
265
+ }
266
+ return 0;
267
+ }
268
+ main(process.argv.slice(2)).then(
269
+ (code) => {
270
+ process.exitCode = code;
271
+ },
272
+ (err) => {
273
+ const message = err instanceof Error ? err.message : String(err);
274
+ process.stderr.write(`orbit-omnigraph-codegen: ${message}
275
+ `);
276
+ process.exitCode = 1;
277
+ }
278
+ );
279
+ //# sourceMappingURL=codegen-cli.js.map
280
+ //# sourceMappingURL=codegen-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/codegen.ts","../src/codegen-cli.ts"],"names":[],"mappings":";;;;;;;AAoEA,IAAM,SAAA,GAA0C;AAAA,EAC9C,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,QAAA;AAAA,EACN,IAAA,EAAM,SAAA;AAAA,EACN,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,IAAA,EAAM,QAAA;AAAA,EACN,QAAA,EAAU;AACZ,CAAA;AAGA,SAAS,gBAAgB,KAAA,EAAuB;AAC9C,EAAA,OAAO,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAA,EAAO,MAAM,EAAE,OAAA,CAAQ,IAAA,EAAM,KAAK,CAAA,CAAE,QAAQ,KAAA,EAAO,KAAK,EAAE,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA,CAAA,CAAA;AAC1G;AAEA,SAAS,OAAO,IAAA,EAAsB;AACpC,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,UAAU,IAAI,CAAA;AACnD,EAAA,QAAQ,KAAK,IAAA;AAAM,IACjB,KAAK,QAAA;AACH,MAAA,OAAO,UAAA;AAAA,IACT,KAAK,MAAA;AACH,MAAA,OAAO,IAAA,CAAK,MAAA,CAAO,MAAA,KAAW,CAAA,GAAI,QAA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,CAAM,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,EAC1B,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AAAA,EACrB,CAAA;AAAA,EACA,CAAC,GAAA,KAAiB;AAChB,IAAA,MAAM,UAAU,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,yBAAA,EAA4B,OAAO;AAAA,CAAI,CAAA;AAC5D,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA","file":"codegen-cli.js","sourcesContent":["/**\n * `.pg` → TypeScript codegen (spec Appendix B.6).\n *\n * The `.pg` scalar set is closed, so typed attrs for the §5 `N`/`E` generics\n * generate mechanically: one interface per node/edge type, a `NodeAttrs` /\n * `EdgeAttrs` discriminated union on the adapter-injected `'orbit:type'`\n * field (B.3 — namespaced so a schema's own `type` property emits as an\n * ordinary member), and a `TypeMap` lookup interface.\n *\n * Generated shapes describe attrs **after** the adapter's B.6 normalization\n * (the v1 loader rewrites export-path wire values to the query-path string\n * forms before populating attrs — see `normalize.ts`), so one encoding holds\n * regardless of read path:\n *\n * `Date` → `string` (`'YYYY-MM-DD'`)\n * `DateTime` → `string` (ISO 8601, `'YYYY-MM-DDTHH:MM:SS.mmmZ'`)\n * `enum(...)` → string-literal union\n * `I64`/`U64` → `number` (beware silent rounding past ±2^53 — B.6)\n * `F32`/`F64` → `number`\n * `Vector(n)` → `number[]`\n * `Blob` → `string` (`data:` URI for inline blobs, stored URI refs verbatim)\n * `T?` → `T | null`\n *\n * Output is a self-contained module (no imports), safe under the strictest\n * tsconfig (`strict`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`,\n * `isolatedModules`). The file carries a DO-NOT-EDIT header with the B.2\n * schema fingerprint. Generation is deterministic — no timestamps — so the\n * output is committable and diff-stable.\n *\n * Browser-safe: no `node:` imports (the CLI wrapper in `codegen-cli.ts` owns\n * file I/O).\n */\n\nimport { ORBIT_TYPE_KEY } from './normalize';\nimport {\n parsePgSchema,\n schemaFingerprint,\n type PgProperty,\n type PgScalarName,\n type PgSchema,\n type PgType,\n} from './pgSchema';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface GenerateTypesOptions {\n /**\n * Extra provenance lines for the DO-NOT-EDIT banner (e.g. the schema file\n * path or server URL). May be multi-line; lines are comment-prefixed as\n * needed.\n */\n header?: string;\n /**\n * The B.2 schema fingerprint of the `.pg` **source** (from\n * {@link schemaFingerprint}). When omitted, a fingerprint of the canonical\n * parsed model is used instead and labelled as such — prefer\n * {@link generateTypesFromPgSource}, which always stamps the source\n * fingerprint.\n */\n fingerprint?: string;\n}\n\n// ---------------------------------------------------------------------------\n// B.6 wire → TS mapping (post-normalization)\n// ---------------------------------------------------------------------------\n\nconst SCALAR_TS: Record<PgScalarName, string> = {\n String: 'string',\n Blob: 'string',\n Bool: 'boolean',\n I32: 'number',\n I64: 'number',\n U32: 'number',\n U64: 'number',\n F32: 'number',\n F64: 'number',\n Date: 'string',\n DateTime: 'string',\n};\n\n/** Single-quoted TS string literal with escapes. */\nfunction tsStringLiteral(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\r/g, '\\\\r').replace(/\\n/g, '\\\\n')}'`;\n}\n\nfunction tsType(type: PgType): string {\n if (typeof type === 'string') return SCALAR_TS[type];\n switch (type.kind) {\n case 'vector':\n return 'number[]';\n case 'enum':\n return type.values.length === 0 ? 'string' : type.values.map(tsStringLiteral).join(' | ');\n case 'list':\n return `${SCALAR_TS[type.element]}[]`;\n case 'unknown':\n return 'unknown';\n }\n}\n\n/** One-line doc note for types whose TS shape hides a wire subtlety (B.6). */\nfunction wireNote(type: PgType): string | null {\n if (typeof type === 'string') {\n switch (type) {\n case 'Date':\n return \"`Date` — normalized to 'YYYY-MM-DD' (UTC) on load (B.6).\";\n case 'DateTime':\n return '`DateTime` — normalized to ISO 8601 UTC on load (B.6).';\n case 'Blob':\n return \"`Blob` — `data:` URI for inline blobs, stored URI refs verbatim (B.6/B.10).\";\n case 'I64':\n case 'U64':\n return `\\`${type}\\` — JSON numbers round silently past ±2^53 (B.6).`;\n default:\n return null;\n }\n }\n switch (type.kind) {\n case 'vector':\n return `\\`Vector(${type.dim})\\`.`;\n case 'unknown':\n return `Unrecognized \\`.pg\\` type \\`${type.raw}\\` — value passes through verbatim.`;\n default:\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Emission helpers\n// ---------------------------------------------------------------------------\n\nconst IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nfunction propertyKey(name: string): string {\n return IDENT_RE.test(name) ? name : tsStringLiteral(name);\n}\n\nfunction emitProperty(lines: string[], prop: PgProperty): void {\n const note = wireNote(prop.type);\n if (note !== null) lines.push(` /** ${note} */`);\n const base = tsType(prop.type);\n lines.push(` ${propertyKey(prop.name)}: ${prop.optional ? `${base} | null` : base};`);\n}\n\nfunction emitPropsInterface(\n lines: string[],\n interfaceName: string,\n kindLabel: 'node' | 'edge',\n typeName: string,\n properties: readonly PgProperty[],\n): void {\n lines.push(`/** Normalized attrs for ${kindLabel} type \\`${typeName}\\` (B.6). */`);\n lines.push(`export interface ${interfaceName} {`);\n if (!properties.some((p) => p.name === 'id')) {\n lines.push(\n ` /** Physical Omnigraph id — injected into every export line's \\`data\\` (B.2); unique per ${kindLabel} type only (B.3). */`,\n );\n lines.push(' id: string;');\n }\n for (const prop of properties) {\n // Every schema property emits normally — including one named `type`: the\n // adapter's discriminator lives at the namespaced ORBIT_TYPE_KEY, so\n // there is nothing to shadow (B.3/B.6).\n emitProperty(lines, prop);\n }\n lines.push('}');\n lines.push('');\n}\n\nfunction emitAttrsUnion(\n lines: string[],\n unionName: string,\n doc: string,\n members: ReadonlyArray<{ typeName: string; interfaceName: string }>,\n): void {\n lines.push(`/** ${doc} */`);\n if (members.length === 0) {\n lines.push(`export type ${unionName} = never;`);\n } else {\n lines.push(`export type ${unionName} =`);\n members.forEach(({ typeName, interfaceName }, i) => {\n const tail = i === members.length - 1 ? ';' : '';\n lines.push(\n ` | ({ ${tsStringLiteral(ORBIT_TYPE_KEY)}: ${tsStringLiteral(typeName)} } & ${interfaceName})${tail}`,\n );\n });\n }\n lines.push('');\n}\n\nfunction headerBanner(fingerprintLine: string, extra: string | undefined): string[] {\n const lines = [\n '// AUTO-GENERATED — DO NOT EDIT.',\n '//',\n '// .pg → TypeScript typed attrs (orbit spec Appendix B.6), generated by',\n '// @modernrelay/orbit-omnigraph (`orbit-omnigraph-codegen`).',\n `// ${fingerprintLine}`,\n ];\n if (extra !== undefined && extra.length > 0) {\n for (const raw of extra.split('\\n')) {\n lines.push(raw.startsWith('//') ? raw : `// ${raw}`.trimEnd());\n }\n }\n lines.push(\n '//',\n \"// Shapes describe attrs AFTER the adapter's B.6 normalization (both read\",\n '// paths converge on the query-path string encodings):',\n \"// Date → 'YYYY-MM-DD' · DateTime → ISO 8601 · enum(...) → literal union\",\n '// I64/U64/F32/F64 → number · Vector(n) → number[] · T? → T | null',\n \"// Blob → string ('data:' URI for inline blobs, stored URI for external)\",\n '',\n );\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a self-contained TypeScript module of typed attrs from a parsed\n * `.pg` schema (B.6): one `<Name>Props` interface per node type, one\n * `<Name>EdgeProps` per edge type (suffixed so a node and an edge sharing a\n * name cannot collide), `NodeAttrs`/`EdgeAttrs` discriminated unions on the\n * adapter-injected `'orbit:type'` field, and a `TypeMap` lookup interface with\n * `NodeTypeName`/`EdgeTypeName` key unions.\n *\n * Deterministic: identical input (schema + options) yields identical output.\n */\nexport function generateTypes(schema: PgSchema, opts?: GenerateTypesOptions): string {\n const fingerprintLine =\n opts?.fingerprint !== undefined\n ? `Schema fingerprint: ${opts.fingerprint} (B.2).`\n : `Schema fingerprint: ${schemaFingerprint(JSON.stringify(schema))} (parsed model — regenerate from .pg source for the B.2 source fingerprint).`;\n const lines = headerBanner(fingerprintLine, opts?.header);\n\n const nodeMembers = schema.nodes.map((n) => ({\n typeName: n.name,\n interfaceName: `${n.name}Props`,\n }));\n const edgeMembers = schema.edges.map((e) => ({\n typeName: e.name,\n interfaceName: `${e.name}EdgeProps`,\n }));\n\n schema.nodes.forEach((n, i) => {\n const member = nodeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'node', n.name, n.properties);\n });\n schema.edges.forEach((e, i) => {\n const member = edgeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'edge', e.name, e.properties);\n });\n\n emitAttrsUnion(\n lines,\n 'NodeAttrs',\n \"Discriminated union over every node type's normalized attrs — `'orbit:type'` is injected by the adapter (B.3).\",\n nodeMembers,\n );\n emitAttrsUnion(\n lines,\n 'EdgeAttrs',\n \"Discriminated union over every edge type's normalized attrs — `'orbit:type'` is the edge name (B.3).\",\n edgeMembers,\n );\n\n lines.push('/** Type-name → props lookup for both kinds (closed sets from the schema — B.3). */');\n lines.push('export interface TypeMap {');\n lines.push(' nodes: {');\n for (const m of nodeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push(' edges: {');\n for (const m of edgeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push(\"export type NodeTypeName = keyof TypeMap['nodes'];\");\n lines.push(\"export type EdgeTypeName = keyof TypeMap['edges'];\");\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Parse `.pg` source and generate typed attrs (see {@link generateTypes}),\n * stamping the header with the B.2 source fingerprint\n * ({@link schemaFingerprint} over the verbatim source).\n */\nexport function generateTypesFromPgSource(\n source: string,\n opts?: Omit<GenerateTypesOptions, 'fingerprint'>,\n): string {\n const schema = parsePgSchema(source);\n const options: GenerateTypesOptions = { fingerprint: schemaFingerprint(source) };\n if (opts?.header !== undefined) options.header = opts.header;\n return generateTypes(schema, options);\n}\n","#!/usr/bin/env node\n/**\n * `orbit-omnigraph-codegen` — minimal `.pg` → TypeScript codegen CLI (spec B.6).\n *\n * orbit-omnigraph-codegen <schema.pg> [-o out.ts]\n * orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o out.ts]\n *\n * The first form reads a `.pg` file; the second fetches the active schema\n * from a running omnigraph-server via a plain **unauthenticated** SDK client\n * (`og.schema.get()` returns the raw `.pg` source — B.6). Authenticated\n * client construction stays exclusively in the `/server` entry (B.1); point\n * this tool at an `--unauthenticated` server or a same-origin proxy.\n *\n * Without `-o`, the generated module goes to stdout.\n */\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport process from 'node:process';\nimport { Omnigraph } from '@modernrelay/omnigraph';\nimport { generateTypesFromPgSource } from './codegen';\n\nconst USAGE = `Usage:\n orbit-omnigraph-codegen <schema.pg> [-o <out.ts>]\n orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o <out.ts>]\n\nGenerates TypeScript typed attrs (spec B.6) from a .pg schema — read from a\nfile, or fetched from a running omnigraph-server (unauthenticated client).\nWrites to stdout unless -o is given.\n`;\n\ninterface CliArgs {\n schemaPath?: string;\n out?: string;\n fromServer?: string;\n graph?: string;\n}\n\nfunction parseArgs(argv: readonly string[]): CliArgs | string {\n const args: CliArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === undefined) continue;\n switch (arg) {\n case '-h':\n case '--help':\n return 'help';\n case '-o':\n case '--out': {\n const v = argv[++i];\n if (v === undefined) return `missing value for ${arg}`;\n args.out = v;\n break;\n }\n case '--from-server': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --from-server';\n args.fromServer = v;\n break;\n }\n case '--graph': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --graph';\n args.graph = v;\n break;\n }\n default:\n if (arg.startsWith('-')) return `unknown option '${arg}'`;\n if (args.schemaPath !== undefined) return `unexpected argument '${arg}'`;\n args.schemaPath = arg;\n }\n }\n if (args.fromServer !== undefined && args.schemaPath !== undefined) {\n return 'pass a schema file OR --from-server, not both';\n }\n if (args.fromServer !== undefined && args.graph === undefined) {\n return '--from-server requires --graph <id> (schema reads are graph-scoped)';\n }\n if (args.fromServer === undefined && args.schemaPath === undefined) {\n return 'no schema given';\n }\n return args;\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const parsed = parseArgs(argv);\n if (parsed === 'help') {\n process.stdout.write(USAGE);\n return 0;\n }\n if (typeof parsed === 'string') {\n process.stderr.write(`orbit-omnigraph-codegen: ${parsed}\\n\\n${USAGE}`);\n return 2;\n }\n\n let source: string;\n let provenance: string;\n if (parsed.fromServer !== undefined && parsed.graph !== undefined) {\n const og = new Omnigraph({ baseUrl: parsed.fromServer, graphId: parsed.graph });\n const schema = await og.schema.get();\n source = schema.schemaSource;\n provenance = `Source: ${parsed.fromServer} (graph '${parsed.graph}', GET /schema)`;\n } else if (parsed.schemaPath !== undefined) {\n source = readFileSync(parsed.schemaPath, 'utf8');\n provenance = `Source: ${parsed.schemaPath}`;\n } else {\n // Unreachable: parseArgs guarantees one of the two.\n return 2;\n }\n\n const output = generateTypesFromPgSource(source, { header: provenance });\n if (parsed.out !== undefined) {\n writeFileSync(parsed.out, output);\n process.stderr.write(`orbit-omnigraph-codegen: wrote ${parsed.out}\\n`);\n } else {\n process.stdout.write(output);\n }\n return 0;\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`orbit-omnigraph-codegen: ${message}\\n`);\n process.exitCode = 1;\n },\n);\n"]}