@syncular/typegen 0.58.0 → 0.59.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 (60) hide show
  1. package/README.md +43 -25
  2. package/dist/cli.js +8 -3
  3. package/dist/emit-dart.d.ts +4 -3
  4. package/dist/emit-dart.js +39 -88
  5. package/dist/emit-kotlin.d.ts +3 -3
  6. package/dist/emit-kotlin.js +39 -86
  7. package/dist/emit-queries-dart.d.ts +1 -1
  8. package/dist/emit-queries-dart.js +17 -26
  9. package/dist/emit-queries-kotlin.d.ts +1 -1
  10. package/dist/emit-queries-kotlin.js +15 -24
  11. package/dist/emit-queries-rust.d.ts +1 -1
  12. package/dist/emit-queries-rust.js +1 -6
  13. package/dist/emit-queries-swift.d.ts +1 -1
  14. package/dist/emit-queries-swift.js +22 -26
  15. package/dist/emit-queries.d.ts +1 -1
  16. package/dist/emit-queries.js +1 -6
  17. package/dist/emit-swift.d.ts +3 -3
  18. package/dist/emit-swift.js +41 -89
  19. package/dist/emit.d.ts +1 -1
  20. package/dist/emit.js +33 -98
  21. package/dist/errors.d.ts +6 -2
  22. package/dist/errors.js +10 -2
  23. package/dist/generate.d.ts +4 -3
  24. package/dist/generate.js +32 -49
  25. package/dist/init.js +1 -1
  26. package/dist/ir.d.ts +11 -0
  27. package/dist/ir.js +66 -47
  28. package/dist/lower.d.ts +0 -7
  29. package/dist/lower.js +0 -62
  30. package/dist/migration-lock.d.ts +32 -23
  31. package/dist/migration-lock.js +115 -92
  32. package/dist/naming.d.ts +25 -0
  33. package/dist/naming.js +92 -0
  34. package/dist/query.d.ts +54 -14
  35. package/dist/query.js +484 -462
  36. package/dist/sql.js +18 -3
  37. package/dist/syql-lowering.js +10 -1
  38. package/dist/syql-validator.js +13 -220
  39. package/package.json +3 -3
  40. package/src/cli.ts +9 -3
  41. package/src/emit-dart.ts +41 -102
  42. package/src/emit-kotlin.ts +38 -102
  43. package/src/emit-queries-dart.ts +23 -32
  44. package/src/emit-queries-kotlin.ts +20 -30
  45. package/src/emit-queries-rust.ts +7 -12
  46. package/src/emit-queries-swift.ts +26 -32
  47. package/src/emit-queries.ts +5 -11
  48. package/src/emit-swift.ts +42 -104
  49. package/src/emit.ts +33 -116
  50. package/src/errors.ts +13 -2
  51. package/src/generate.ts +74 -76
  52. package/src/init.ts +4 -1
  53. package/src/ir.ts +87 -50
  54. package/src/lower.ts +0 -53
  55. package/src/migration-lock.ts +192 -137
  56. package/src/naming.ts +154 -0
  57. package/src/query.ts +615 -504
  58. package/src/sql.ts +30 -3
  59. package/src/syql-lowering.ts +15 -1
  60. package/src/syql-validator.ts +21 -279
@@ -1,4 +1,21 @@
1
- import { snakeToCamel } from './naming.js';
1
+ /**
2
+ * Swift emitter: neutral IR → one standalone `.swift` file exporting
3
+ *
4
+ * - `enum <EnumName> { static let schema: JSONValue }` — the ServerSchema
5
+ * object: the exact `serializeSchema` JSON the TS module embeds, parsed
6
+ * from a string literal (fed straight into `SyncularClient(schema:)`),
7
+ * - one `struct` per table with typed properties (per the six §2.4 column
8
+ * types, plus blob_ref/crdt in their honest Swift shapes) and a
9
+ * `init?(row:)` from a `[String: JSONValue]` (the shape `query`/`readRows`
10
+ * return),
11
+ * - a `subscriptions` namespace of typed requested-scope builders.
12
+ *
13
+ * The file imports only `Syncular` (for `JSONValue`). The header carries the
14
+ * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
15
+ * emitter.
16
+ */
17
+ import { appColumnType, serializeSchema, } from './ir.js';
18
+ import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
2
19
  /**
3
20
  * §2.4 column type → honest Swift type. `json`/`blob_ref` are the raw
4
21
  * canonical JSON string (the client's blob API parses blob_ref); `bytes`/
@@ -14,81 +31,9 @@ const SWIFT_TYPE = {
14
31
  blob_ref: 'String',
15
32
  crdt: '[UInt8]',
16
33
  };
17
- function appColumnType(column) {
18
- return column.encrypted === true && column.declaredType !== undefined
19
- ? column.declaredType
20
- : column.type;
21
- }
22
- /** §5.11: app-side Swift type — declaredType for an encrypted column. */
23
- function appSwiftType(column) {
24
- return SWIFT_TYPE[appColumnType(column)];
25
- }
26
- function pascalCase(name) {
27
- return name
28
- .split(/[_-]+/)
29
- .filter((part) => part.length > 0)
30
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
- .join('');
32
- }
33
- /** Language-facing field name — the pinned §12 naming map. */
34
- function camelCase(name) {
35
- return snakeToCamel(name);
36
- }
37
- function quote(value) {
38
- return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
39
- }
40
- /** Emit a `JSONValue` literal for the schema object (built from the IR). */
41
- function emitSchemaValue(ir, indent) {
42
- const lines = [];
43
- const i = indent;
44
- lines.push(`${i}.object([`);
45
- lines.push(`${i} "version": .number(${ir.schemaVersion}),`);
46
- lines.push(`${i} "tables": .array([`);
47
- for (const table of ir.tables) {
48
- lines.push(`${i} .object([`);
49
- lines.push(`${i} "name": .string(${quote(table.name)}),`);
50
- lines.push(`${i} "primaryKey": .string(${quote(table.primaryKey)}),`);
51
- lines.push(`${i} "columns": .array([`);
52
- for (const column of table.columns) {
53
- const parts = [
54
- `"name": .string(${quote(column.name)})`,
55
- `"type": .string(${quote(column.type)})`,
56
- `"nullable": .bool(${column.nullable})`,
57
- ];
58
- if (column.crdtType !== undefined) {
59
- parts.push(`"crdtType": .string(${quote(column.crdtType)})`);
60
- }
61
- if (column.encrypted === true) {
62
- parts.push('"encrypted": .bool(true)');
63
- parts.push(`"declaredType": .string(${quote(column.declaredType ?? column.type)})`);
64
- }
65
- lines.push(`${i} .object([${parts.join(', ')}]),`);
66
- }
67
- lines.push(`${i} ]),`);
68
- lines.push(`${i} "scopes": .array([`);
69
- for (const scope of table.scopes) {
70
- lines.push(`${i} .object(["pattern": .string(${quote(scope.pattern)}), "column": .string(${quote(scope.column)})]),`);
71
- }
72
- lines.push(`${i} ]),`);
73
- if (table.ftsIndexes.length > 0) {
74
- lines.push(`${i} "ftsIndexes": .array([`);
75
- for (const index of table.ftsIndexes) {
76
- const columns = index.columns
77
- .map((column) => `.string(${quote(column)})`)
78
- .join(', ');
79
- lines.push(`${i} .object(["name": .string(${quote(index.name)}), "columns": .array([${columns}]), "tokenize": .string(${quote(index.tokenize)})]),`);
80
- }
81
- lines.push(`${i} ]),`);
82
- }
83
- lines.push(`${i} ]),`);
84
- }
85
- lines.push(`${i} ]),`);
86
- lines.push(`${i}])`);
87
- return lines;
88
- }
89
34
  /** The accessor that lifts a §2.4 value out of a `[String: JSONValue]` row. */
90
35
  function rowAccessor(column) {
91
- const key = `row[${quote(column.name)}]`;
36
+ const key = `row[${stringLiteral(column.name, 'swift')}]`;
92
37
  switch (appColumnType(column)) {
93
38
  case 'string':
94
39
  case 'json':
@@ -115,22 +60,22 @@ function emitStruct(table) {
115
60
  lines.push(`/// One ${table.name} row (§2.4 column order).`);
116
61
  lines.push(`public struct ${type}: Sendable, Equatable {`);
117
62
  for (const column of table.columns) {
118
- const swift = appSwiftType(column);
63
+ const swift = SWIFT_TYPE[appColumnType(column)];
119
64
  const opt = column.nullable ? '?' : '';
120
- lines.push(` public let ${camelCase(column.name)}: ${swift}${opt}`);
65
+ lines.push(` public let ${snakeToCamel(column.name)}: ${swift}${opt}`);
121
66
  }
122
67
  lines.push('');
123
68
  // Memberwise init (public, so app code can build rows too).
124
69
  const params = table.columns
125
70
  .map((c) => {
126
- const swift = appSwiftType(c);
71
+ const swift = SWIFT_TYPE[appColumnType(c)];
127
72
  const opt = c.nullable ? '? = nil' : '';
128
- return `${camelCase(c.name)}: ${swift}${opt}`;
73
+ return `${snakeToCamel(c.name)}: ${swift}${opt}`;
129
74
  })
130
75
  .join(', ');
131
76
  lines.push(` public init(${params}) {`);
132
77
  for (const column of table.columns) {
133
- const name = camelCase(column.name);
78
+ const name = snakeToCamel(column.name);
134
79
  lines.push(` self.${name} = ${name}`);
135
80
  }
136
81
  lines.push(' }');
@@ -139,7 +84,7 @@ function emitStruct(table) {
139
84
  lines.push(` /// Returns nil when a non-nullable column is missing or mistyped.`);
140
85
  lines.push(' public init?(row: [String: JSONValue]) {');
141
86
  for (const column of table.columns) {
142
- const name = camelCase(column.name);
87
+ const name = snakeToCamel(column.name);
143
88
  const accessor = rowAccessor(column);
144
89
  if (column.nullable) {
145
90
  lines.push(` self.${name} = ${accessor}`);
@@ -163,18 +108,20 @@ function emitSubscription(sub) {
163
108
  }
164
109
  }
165
110
  const lines = [];
166
- lines.push(` /// Requested-scope template for the ${quote(sub.name)} subscription.`);
111
+ lines.push(` /// Requested-scope template for the ${stringLiteral(sub.name, 'swift')} subscription.`);
167
112
  lines.push(` public enum ${pascalCase(sub.name)} {`);
168
- lines.push(` public static let name = ${quote(sub.name)}`);
169
- lines.push(` public static let table = ${quote(sub.table)}`);
170
- const args = params.map((p) => `${camelCase(p)}: String`).join(', ');
113
+ lines.push(` public static let name = ${stringLiteral(sub.name, 'swift')}`);
114
+ lines.push(` public static let table = ${stringLiteral(sub.table, 'swift')}`);
115
+ const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
171
116
  lines.push(` public static func scopes(${args}) -> [String: [String]] {`);
172
117
  lines.push(' [');
173
118
  for (const scope of sub.scopes) {
174
119
  const values = scope.values
175
- .map((value) => value.kind === 'literal' ? quote(value.value) : camelCase(value.name))
120
+ .map((value) => value.kind === 'literal'
121
+ ? stringLiteral(value.value, 'swift')
122
+ : snakeToCamel(value.name))
176
123
  .join(', ');
177
- lines.push(` ${quote(scope.variable)}: [${values}],`);
124
+ lines.push(` ${stringLiteral(scope.variable, 'swift')}: [${values}],`);
178
125
  }
179
126
  lines.push(' ]');
180
127
  lines.push(' }');
@@ -196,10 +143,15 @@ export function emitSwiftModule(ir, hash, enumName) {
196
143
  schemaLines.push(`/// The generated syncular schema (SPEC §2.4, §3.1) + typed rows.`);
197
144
  schemaLines.push(`public enum ${enumName} {`);
198
145
  schemaLines.push(` /// ServerSchema-compatible schema — pass to \`SyncularClient(schema:)\`.`);
199
- schemaLines.push(' public static let schema: JSONValue =');
200
- for (const line of emitSchemaValue(ir, ' ')) {
201
- schemaLines.push(line);
146
+ // A multi-line literal strips the closing delimiter's indentation from
147
+ // every line, so the parsed string is the serializeSchema bytes. JSON
148
+ // escapes every quote inside a string, so it never holds the closing
149
+ // delimiter; doubling backslashes also disarms `\(` interpolation.
150
+ schemaLines.push(' public static let schema: JSONValue = try! JSONValue(decoding: """');
151
+ for (const line of serializeSchema(ir).split('\n')) {
152
+ schemaLines.push(` ${line.replaceAll('\\', '\\\\')}`);
202
153
  }
154
+ schemaLines.push(' """)');
203
155
  schemaLines.push('');
204
156
  // Subscriptions namespace nested in the schema enum.
205
157
  schemaLines.push(' /// Typed requested-scope builders per subscription.');
package/dist/emit.d.ts CHANGED
@@ -12,6 +12,6 @@
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
14
14
  */
15
- import type { IrDocument } from './ir.js';
15
+ import { type IrDocument } from './ir.js';
16
16
  import { type NamingMode } from './naming.js';
17
17
  export declare function emitModule(ir: IrDocument, hash: string, naming?: NamingMode): string;
package/dist/emit.js CHANGED
@@ -1,4 +1,19 @@
1
- import { snakeToCamel } from './naming.js';
1
+ /**
2
+ * TS emitter: neutral IR → one standalone generated module exporting
3
+ *
4
+ * - `schema` — a ServerSchema-compatible object (structurally typed; the
5
+ * generated file imports nothing),
6
+ * - a `<Table>Row` interface per table,
7
+ * - `<Table>Insert` / `<Table>Update` mutation-input shapes honoring
8
+ * nullability,
9
+ * - a `<name>Subscription` helper constant per manifest subscription with
10
+ * a typed requested-scopes builder.
11
+ *
12
+ * The header carries the IR hash so `--check` verifies freshness
13
+ * byte-exactly.
14
+ */
15
+ import { appColumnType, serializeSchema, } from './ir.js';
16
+ import { pascalCase, snakeToCamel, stringLiteral, } from './naming.js';
2
17
  const TS_TYPE = {
3
18
  string: 'string',
4
19
  integer: 'number',
@@ -13,92 +28,9 @@ const TS_TYPE = {
13
28
  // is an app-level helper in @syncular/crdt-yjs, not generated code.
14
29
  crdt: 'Uint8Array',
15
30
  };
16
- /**
17
- * §5.11: the app-side TS type of a column. An encrypted column's wire type is
18
- * `bytes`, but the app sees its declared type (the local mirror is plaintext).
19
- */
20
- function appTsType(column) {
21
- const type = column.encrypted === true && column.declaredType !== undefined
22
- ? column.declaredType
23
- : column.type;
24
- return TS_TYPE[type];
25
- }
26
- function pascalCase(name) {
27
- return name
28
- .split(/[_-]+/)
29
- .filter((part) => part.length > 0)
30
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
- .join('');
32
- }
33
- function quote(value) {
34
- return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
35
- }
36
31
  const IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
37
32
  function propertyKey(name) {
38
- return IDENTIFIER_RE.test(name) ? name : quote(name);
39
- }
40
- function emitSchema(ir) {
41
- const lines = [];
42
- lines.push('/** ServerSchema-compatible schema object (SPEC §2.4, §3.1). */');
43
- lines.push('export const schema = {');
44
- lines.push(` version: ${ir.schemaVersion},`);
45
- lines.push(' tables: [');
46
- for (const table of ir.tables) {
47
- lines.push(' {');
48
- lines.push(` name: ${quote(table.name)},`);
49
- lines.push(' columns: [');
50
- for (const column of table.columns) {
51
- // §5.10.1: emit crdtType on crdt columns so a generated server schema
52
- // can select the merger; omitted (and thus unchanged) for others.
53
- const crdtType = column.crdtType !== undefined
54
- ? `, crdtType: ${quote(column.crdtType)}`
55
- : '';
56
- // §5.11: emit encrypted/declaredType on encrypted columns so the client
57
- // codec encrypts/decrypts them; omitted for others.
58
- const encrypted = column.encrypted === true
59
- ? `, encrypted: true, declaredType: ${quote(column.declaredType ?? column.type)}`
60
- : '';
61
- lines.push(` { name: ${quote(column.name)}, type: ${quote(column.type)}, nullable: ${column.nullable}${crdtType}${encrypted} },`);
62
- }
63
- lines.push(' ],');
64
- lines.push(` primaryKey: ${quote(table.primaryKey)},`);
65
- lines.push(' scopes: [');
66
- for (const scope of table.scopes) {
67
- lines.push(` { pattern: ${quote(scope.pattern)}, column: ${quote(scope.column)} },`);
68
- }
69
- lines.push(' ],');
70
- // §6.11 declared references — emitted only when the table declares any,
71
- // so reference-free tables keep their exact pre-reference generated bytes.
72
- if (table.references.length > 0) {
73
- lines.push(' references: [');
74
- for (const reference of table.references) {
75
- lines.push(` { column: ${quote(reference.column)}, parentTable: ${quote(reference.parentTable)}, onDelete: ${quote(reference.onDelete)} },`);
76
- }
77
- lines.push(' ],');
78
- }
79
- // Local secondary indexes — emitted only when the table declares any, so
80
- // index-free tables keep their exact pre-index generated bytes.
81
- if (table.indexes.length > 0) {
82
- lines.push(' indexes: [');
83
- for (const index of table.indexes) {
84
- const cols = index.columns.map((c) => quote(c)).join(', ');
85
- lines.push(` { name: ${quote(index.name)}, columns: [${cols}], unique: ${index.unique} },`);
86
- }
87
- lines.push(' ],');
88
- }
89
- if (table.ftsIndexes.length > 0) {
90
- lines.push(' ftsIndexes: [');
91
- for (const index of table.ftsIndexes) {
92
- const cols = index.columns.map((column) => quote(column)).join(', ');
93
- lines.push(` { name: ${quote(index.name)}, columns: [${cols}], tokenize: ${quote(index.tokenize)} },`);
94
- }
95
- lines.push(' ],');
96
- }
97
- lines.push(' },');
98
- }
99
- lines.push(' ],');
100
- lines.push('} as const;');
101
- return lines.join('\n');
33
+ return IDENTIFIER_RE.test(name) ? name : stringLiteral(name, 'ts');
102
34
  }
103
35
  function emitRowInterfaces(table, naming) {
104
36
  const type = pascalCase(table.name);
@@ -110,7 +42,7 @@ function emitRowInterfaces(table, naming) {
110
42
  lines.push(`/** One ${table.name} row (§2.4 column order). */`);
111
43
  lines.push(`export interface ${type}Row {`);
112
44
  for (const column of table.columns) {
113
- const ts = appTsType(column);
45
+ const ts = TS_TYPE[appColumnType(column)];
114
46
  lines.push(` ${key(column.name)}: ${ts}${column.nullable ? ' | null' : ''};`);
115
47
  }
116
48
  lines.push('}');
@@ -118,7 +50,7 @@ function emitRowInterfaces(table, naming) {
118
50
  lines.push(`/** Insert shape: nullable columns may be omitted. */`);
119
51
  lines.push(`export interface ${type}Insert {`);
120
52
  for (const column of table.columns) {
121
- const ts = appTsType(column);
53
+ const ts = TS_TYPE[appColumnType(column)];
122
54
  lines.push(column.nullable
123
55
  ? ` ${key(column.name)}?: ${ts} | null;`
124
56
  : ` ${key(column.name)}: ${ts};`);
@@ -128,7 +60,7 @@ function emitRowInterfaces(table, naming) {
128
60
  lines.push(`/** Update shape: primary key required, all other columns optional. */`);
129
61
  lines.push(`export interface ${type}Update {`);
130
62
  for (const column of table.columns) {
131
- const ts = appTsType(column);
63
+ const ts = TS_TYPE[appColumnType(column)];
132
64
  if (column.name === table.primaryKey) {
133
65
  lines.push(` ${key(column.name)}: ${ts};`);
134
66
  }
@@ -147,11 +79,11 @@ function emitTableDescriptor(table, naming) {
147
79
  const field = naming === 'camel' ? snakeToCamel(table.primaryKey) : table.primaryKey;
148
80
  const constant = `${naming === 'camel' ? snakeToCamel(table.name) : table.name}Table`;
149
81
  return [
150
- `/** Typed mutation/resource descriptor for ${quote(table.name)}. */`,
151
- `export const ${constant}: SyncTable<${type}Row, ${type}Insert, ${type}Update, ${appTsType(primary)}> = {`,
152
- ` name: ${quote(table.name)},`,
153
- ` primaryKey: ${quote(field)},`,
154
- ` physicalPrimaryKey: ${quote(table.primaryKey)},`,
82
+ `/** Typed mutation/resource descriptor for ${stringLiteral(table.name, 'ts')}. */`,
83
+ `export const ${constant}: SyncTable<${type}Row, ${type}Insert, ${type}Update, ${TS_TYPE[appColumnType(primary)]}> = {`,
84
+ ` name: ${stringLiteral(table.name, 'ts')},`,
85
+ ` primaryKey: ${stringLiteral(field, 'ts')},`,
86
+ ` physicalPrimaryKey: ${stringLiteral(table.primaryKey, 'ts')},`,
155
87
  '};',
156
88
  ].join('\n');
157
89
  }
@@ -174,16 +106,16 @@ function emitSubscription(sub) {
174
106
  lines.push('}');
175
107
  lines.push('');
176
108
  }
177
- lines.push(`/** Requested-scope template for the ${quote(sub.name)} subscription. */`);
109
+ lines.push(`/** Requested-scope template for the ${stringLiteral(sub.name, 'ts')} subscription. */`);
178
110
  lines.push(`export const ${sub.name}Subscription = {`);
179
- lines.push(` name: ${quote(sub.name)},`);
180
- lines.push(` table: ${quote(sub.table)},`);
111
+ lines.push(` name: ${stringLiteral(sub.name, 'ts')},`);
112
+ lines.push(` table: ${stringLiteral(sub.table, 'ts')},`);
181
113
  const args = params.length > 0 ? `params: ${paramsType}` : '';
182
114
  lines.push(` scopes: (${args}): Record<string, string[]> => ({`);
183
115
  for (const scope of sub.scopes) {
184
116
  const values = scope.values
185
117
  .map((value) => value.kind === 'literal'
186
- ? quote(value.value)
118
+ ? stringLiteral(value.value, 'ts')
187
119
  : `params.${propertyKey(value.name)}`)
188
120
  .join(', ');
189
121
  lines.push(` ${propertyKey(scope.variable)}: [${values}],`);
@@ -214,7 +146,10 @@ export function emitModule(ir, hash, naming = 'camel') {
214
146
  ' readonly __id?: Id;',
215
147
  '}',
216
148
  ].join('\n'));
217
- parts.push(emitSchema(ir));
149
+ parts.push([
150
+ '/** ServerSchema-compatible schema object (SPEC §2.4, §3.1). */',
151
+ `export const schema = ${serializeSchema(ir)} as const;`,
152
+ ].join('\n'));
218
153
  for (const table of ir.tables) {
219
154
  parts.push(emitRowInterfaces(table, naming));
220
155
  parts.push(emitTableDescriptor(table, naming));
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,10 @@
1
- /** Fail-loud codegen error: every message names the offending construct. */
1
+ /** Fail-loud codegen error: every message names the offending construct. A
2
+ * coded error carries a static message, its stable `code`, and the dynamic
3
+ * values (table, column, …) in `details`. */
2
4
  export declare class TypegenError extends Error {
3
5
  /** Input the error came from (a migration file, the manifest, …). */
4
6
  readonly source: string;
5
- constructor(source: string, message: string);
7
+ readonly code?: string;
8
+ readonly details?: Readonly<Record<string, unknown>>;
9
+ constructor(source: string, message: string, code?: string, details?: Readonly<Record<string, unknown>>);
6
10
  }
package/dist/errors.js CHANGED
@@ -1,10 +1,18 @@
1
- /** Fail-loud codegen error: every message names the offending construct. */
1
+ /** Fail-loud codegen error: every message names the offending construct. A
2
+ * coded error carries a static message, its stable `code`, and the dynamic
3
+ * values (table, column, …) in `details`. */
2
4
  export class TypegenError extends Error {
3
5
  /** Input the error came from (a migration file, the manifest, …). */
4
6
  source;
5
- constructor(source, message) {
7
+ code;
8
+ details;
9
+ constructor(source, message, code, details) {
6
10
  super(`${source}: ${message}`);
7
11
  this.name = 'TypegenError';
8
12
  this.source = source;
13
+ if (code !== undefined)
14
+ this.code = code;
15
+ if (details !== undefined)
16
+ this.details = details;
9
17
  }
10
18
  }
@@ -73,9 +73,10 @@ export interface GenerateResult {
73
73
  */
74
74
  export declare function baselineMigrationHistory(manifestDir: string): GeneratedOutput;
75
75
  /**
76
- * Validate and explicitly compact a version-1 migration lock to version 2.
77
- * The caller owns the in-place write so the CLI can make the format transition
78
- * visible and reviewable.
76
+ * Validate a format-1 or format-2 migration lock and convert it to the
77
+ * current format, recording each locked migration's schema version from the
78
+ * manifest. The caller owns the in-place write so the CLI can make the format
79
+ * transition visible and reviewable.
79
80
  */
80
81
  export declare function upgradeMigrationHistory(manifestDir: string): GeneratedOutput;
81
82
  /** Fast CI check for migration history without emitting/query analysis. */
package/dist/generate.js CHANGED
@@ -17,8 +17,8 @@ import { emitSwiftModule } from './emit-swift.js';
17
17
  import { TypegenError } from './errors.js';
18
18
  import { canonicalizeExtensions, IR_VERSION, irHash, serializeIr, } from './ir.js';
19
19
  import { MANIFEST_FILENAME, parseManifest, } from './manifest.js';
20
- import { buildMigrationLock, LEGACY_MIGRATION_LOCK_FORMAT_VERSION, lockedMigrationNames, MIGRATION_LOCK_FILENAME, readMigrationLock, serializeMigrationLock, updateMigrationLock, } from './migration-lock.js';
21
- import { buildNamingMap } from './naming.js';
20
+ import { buildMigrationLock, buildSchemaVersions, lockedMigrationNames, MIGRATION_LOCK_FILENAME, MIGRATION_LOCK_FORMAT_VERSION, readMigrationLock, serializeMigrationLock, updateMigrationLock, upgradeMigrationLock, } from './migration-lock.js';
21
+ import { validateSchemaIdentifiers } from './naming.js';
22
22
  import { analyzeQueryFile, synthesizeDdl, } from './query.js';
23
23
  import { serializeQueryIr } from './query-ir.js';
24
24
  import { applyMigrationSql, validateFinalSchemaIdentifiers, } from './sql.js';
@@ -38,9 +38,13 @@ function resolveScope(table, spec) {
38
38
  }
39
39
  const variable = match[2];
40
40
  const column = typeof spec === 'string' ? variable : spec.column;
41
- if (!table.columns.some((c) => c.name === column)) {
41
+ const scopeColumn = table.columns.find((c) => c.name === column);
42
+ if (scopeColumn === undefined) {
42
43
  throw new TypegenError(MANIFEST_FILENAME, `table ${table.name}: scope pattern ${JSON.stringify(pattern)} names unknown column ${JSON.stringify(column)}`);
43
44
  }
45
+ if (scopeColumn.type !== 'string' && scopeColumn.type !== 'integer') {
46
+ throw new TypegenError(MANIFEST_FILENAME, 'a scope column must have type string or integer (§3.1)', 'typegen.scope_column_type', { table: table.name, column, type: scopeColumn.type });
47
+ }
44
48
  return { pattern, variable, column };
45
49
  }
46
50
  function buildTable(manifestTable, parsed) {
@@ -96,6 +100,12 @@ function applyEncryption(parsed, scopes, encryptedColumns) {
96
100
  if (column.type === 'crdt') {
97
101
  throw new TypegenError(MANIFEST_FILENAME, `table ${parsed.name}: crdt column ${JSON.stringify(name)} cannot be encrypted — the server merges crdt bytes plaintext (§5.10.3, §5.11)`);
98
102
  }
103
+ // The server indexes ciphertext under a random nonce: a UNIQUE index
104
+ // never fires there while clients enforce it on plaintext.
105
+ const index = parsed.indexes.find((i) => i.columns.includes(name));
106
+ if (index !== undefined) {
107
+ throw new TypegenError(MANIFEST_FILENAME, 'an encrypted column cannot be an index column (§5.11)', 'typegen.encrypted_index_column', { table: parsed.name, index: index.name, column: name });
108
+ }
99
109
  }
100
110
  return parsed.columns.map((column) => {
101
111
  if (!encrypted.has(column.name))
@@ -141,6 +151,11 @@ function validateReferences(tables, parsedTables) {
141
151
  if (child.type !== parentKey.type) {
142
152
  throw new TypegenError(MANIFEST_FILENAME, `table ${table.name}: reference column ${JSON.stringify(reference.column)} has type ${JSON.stringify(child.type)} but ${parent.name}.${parent.primaryKey} has type ${JSON.stringify(parentKey.type)} — the types must match (§6.11)`);
143
153
  }
154
+ // The server reaches children through this index (§6.11); a migration
155
+ // that drops it leaves a schema the server refuses to compile.
156
+ if (!table.indexes.some((index) => index.columns.length === 1 && index.columns[0] === reference.column)) {
157
+ throw new TypegenError(MANIFEST_FILENAME, 'a declared reference needs a single-column index over its column (§6.11)', 'typegen.reference_index_missing', { table: table.name, column: reference.column });
158
+ }
144
159
  if (patternsOf(table) !== patternsOf(parent)) {
145
160
  throw new TypegenError(MANIFEST_FILENAME, `table ${table.name}: reference column ${JSON.stringify(reference.column)} targets ${parent.name}, whose scope patterns (${parent.scopes.map((scope) => scope.pattern).join(', ')}) differ from ${table.name}'s (${table.scopes.map((scope) => scope.pattern).join(', ')}) — a cascade MUST NOT cross an authorization boundary (§6.11)`);
146
161
  }
@@ -176,23 +191,6 @@ function buildSubscription(sub, tables) {
176
191
  .sort((a, b) => (a.variable < b.variable ? -1 : 1));
177
192
  return { name: sub.name, table: sub.table, scopes };
178
193
  }
179
- function buildSchemaVersions(manifest, migrations) {
180
- const names = migrations.map((m) => m.name);
181
- let cursor = 0;
182
- const out = manifest.schemaVersions.map((entry) => {
183
- const index = names.indexOf(entry.through, cursor);
184
- if (index === -1) {
185
- throw new TypegenError(MANIFEST_FILENAME, `schemaVersions: version ${entry.version} names migration ${JSON.stringify(entry.through)}, which does not exist after ${JSON.stringify(names[cursor - 1] ?? '(start)')} (migrations: ${names.join(', ')})`);
186
- }
187
- const covered = names.slice(cursor, index + 1);
188
- cursor = index + 1;
189
- return { version: entry.version, migrations: covered };
190
- });
191
- if (cursor !== names.length) {
192
- throw new TypegenError(MANIFEST_FILENAME, `schemaVersions: migrations ${names.slice(cursor).join(', ')} are not covered by any schema version — the last entry's "through" must be the last migration`);
193
- }
194
- return out;
195
- }
196
194
  /** Pure IR construction — the testable heart of the generator. Migrations
197
195
  * named in `lockedNames` replay as immutable deployed history: rules that
198
196
  * only appended migrations must satisfy are skipped for them. */
@@ -206,7 +204,7 @@ export function buildIr(manifest, migrations, lockedNames) {
206
204
  applyMigrationSql(parsedTables, migration.sql, `${migration.name}/up.sql`, droppedTables, { lockedHistory: lockedNames?.has(migration.name) === true });
207
205
  }
208
206
  validateFinalSchemaIdentifiers(parsedTables);
209
- const schemaVersions = buildSchemaVersions(manifest, migrations);
207
+ const schemaVersions = buildSchemaVersions(manifest.schemaVersions, migrations);
210
208
  const tables = manifest.tables.map((manifestTable) => {
211
209
  const parsed = parsedTables.get(manifestTable.name);
212
210
  if (parsed === undefined) {
@@ -307,8 +305,7 @@ export function makeQueryDb(ir) {
307
305
  try {
308
306
  const columnNames = stmt.columnNames;
309
307
  // Execute once against the empty DB to populate decltype; result is [].
310
- const paramsCount = stmt
311
- .paramsCount;
308
+ const paramsCount = stmt.paramsCount;
312
309
  // An unbound FTS5 MATCH parameter is treated as the empty query and
313
310
  // fails parsing. A numeric probe is valid for MATCH and LIMIT alike,
314
311
  // while the empty database still guarantees no result rows.
@@ -397,44 +394,32 @@ export function baselineMigrationHistory(manifestDir) {
397
394
  buildIr(manifest, migrations);
398
395
  return {
399
396
  path: resolve(manifestDir, MIGRATION_LOCK_FILENAME),
400
- content: serializeMigrationLock(buildMigrationLock(migrations)),
397
+ content: serializeMigrationLock(buildMigrationLock(migrations, manifest.schemaVersions)),
401
398
  };
402
399
  }
403
400
  /**
404
- * Validate and explicitly compact a version-1 migration lock to version 2.
405
- * The caller owns the in-place write so the CLI can make the format transition
406
- * visible and reviewable.
401
+ * Validate a format-1 or format-2 migration lock and convert it to the
402
+ * current format, recording each locked migration's schema version from the
403
+ * manifest. The caller owns the in-place write so the CLI can make the format
404
+ * transition visible and reviewable.
407
405
  */
408
406
  export function upgradeMigrationHistory(manifestDir) {
409
407
  const { manifest, migrations } = loadProjectInputs(manifestDir);
410
408
  const locked = readMigrationLock(manifestDir);
411
- if (locked.formatVersion !== LEGACY_MIGRATION_LOCK_FORMAT_VERSION) {
412
- throw new TypegenError(MIGRATION_LOCK_FILENAME, 'already uses the current compact migration-lock format');
413
- }
414
- // Validate the immutable prefix before replacing its representation.
415
- updateMigrationLock(locked, migrations);
416
- // upgrade-lock converts the committed representation of history that is
417
- // already locked. Extending the lock over appended migrations is its own
418
- // reviewable act, so unlocked migrations stop the conversion here.
419
- if (migrations.length > locked.migrations.length) {
420
- const appended = migrations
421
- .slice(locked.migrations.length)
422
- .map((migration) => migration.name)
423
- .join(', ');
424
- throw new TypegenError(MIGRATION_LOCK_FILENAME, `migrations ${appended} are appended beyond the locked history — run generate to extend the lock over them, commit the extended lock, then rerun \`migrations upgrade-lock\``);
409
+ if (locked.formatVersion === MIGRATION_LOCK_FORMAT_VERSION) {
410
+ throw new TypegenError(MIGRATION_LOCK_FILENAME, 'already uses the current migration-lock format');
425
411
  }
426
- const lockedNames = lockedMigrationNames(locked);
427
- buildIr(manifest, migrations, lockedNames);
412
+ buildIr(manifest, migrations, lockedMigrationNames(locked));
428
413
  return {
429
414
  path: resolve(manifestDir, MIGRATION_LOCK_FILENAME),
430
- content: serializeMigrationLock(buildMigrationLock(migrations, undefined, lockedNames)),
415
+ content: serializeMigrationLock(upgradeMigrationLock(locked, migrations, manifest.schemaVersions)),
431
416
  };
432
417
  }
433
418
  /** Fast CI check for migration history without emitting/query analysis. */
434
419
  export function checkMigrationHistory(manifestDir) {
435
420
  const { manifest, migrations } = loadProjectInputs(manifestDir);
436
421
  const locked = readMigrationLock(manifestDir);
437
- const current = updateMigrationLock(locked, migrations);
422
+ const current = updateMigrationLock(locked, migrations, manifest.schemaVersions);
438
423
  buildIr(manifest, migrations, lockedMigrationNames(locked));
439
424
  const output = {
440
425
  path: resolve(manifestDir, MIGRATION_LOCK_FILENAME),
@@ -451,7 +436,7 @@ export function checkMigrationHistory(manifestDir) {
451
436
  export function generate(manifestDir) {
452
437
  const { manifest, migrations } = loadProjectInputs(manifestDir);
453
438
  const locked = readMigrationLock(manifestDir);
454
- const migrationLock = updateMigrationLock(locked, migrations);
439
+ const migrationLock = updateMigrationLock(locked, migrations, manifest.schemaVersions);
455
440
  const ir = buildIr(manifest, migrations, lockedMigrationNames(locked));
456
441
  // §5/§12 naming: the emitter targets this run generates (keyword hazards
457
442
  // are only real on targets that exist), and the per-table collision check
@@ -470,9 +455,7 @@ export function generate(manifestDir) {
470
455
  targets,
471
456
  backend: manifest.queryBackend,
472
457
  };
473
- for (const table of ir.tables) {
474
- buildNamingMap(table.columns.map((c) => c.name), manifest.naming, MANIFEST_FILENAME, `table ${table.name}`, targets);
475
- }
458
+ validateSchemaIdentifiers(ir.tables, manifest.naming, targets, MANIFEST_FILENAME);
476
459
  const irJson = serializeIr(ir);
477
460
  const hash = irHash(irJson);
478
461
  const module = emitModule(ir, hash, manifest.naming);
package/dist/init.js CHANGED
@@ -85,7 +85,7 @@ export function initProject(dir) {
85
85
  mkdirSync(queriesDir, { recursive: true });
86
86
  writeFileSync(manifestPath, STARTER_MANIFEST, 'utf8');
87
87
  writeFileSync(migrationPath, STARTER_MIGRATION, 'utf8');
88
- writeFileSync(migrationLockPath, serializeMigrationLock(buildMigrationLock([{ name: '0001_initial', sql: STARTER_MIGRATION }])), 'utf8');
88
+ writeFileSync(migrationLockPath, serializeMigrationLock(buildMigrationLock([{ name: '0001_initial', sql: STARTER_MIGRATION }], [{ version: 1, through: '0001_initial' }])), 'utf8');
89
89
  writeFileSync(queryPath, STARTER_QUERY, 'utf8');
90
90
  return {
91
91
  written: [manifestPath, migrationPath, migrationLockPath, queryPath],
package/dist/ir.d.ts CHANGED
@@ -17,6 +17,10 @@ export interface IrColumn {
17
17
  /** §5.11: the app-side type of an encrypted column. Present iff `encrypted`. */
18
18
  readonly declaredType?: IrColumnType;
19
19
  }
20
+ /** §5.11: the app-side type of a column. An encrypted column rides the wire
21
+ * as `bytes`; generated rows expose its declared type (the local mirror is
22
+ * plaintext). */
23
+ export declare function appColumnType(column: IrColumn): IrColumnType;
20
24
  /** One §3.1 scope pattern, fully resolved (no re-parsing downstream). */
21
25
  export interface IrScope {
22
26
  readonly pattern: string;
@@ -108,5 +112,12 @@ export interface IrDocument {
108
112
  export declare function canonicalizeExtensions(value: unknown): unknown;
109
113
  /** Serialize with a fixed key order — byte-deterministic for equal IRs. */
110
114
  export declare function serializeIr(ir: IrDocument): string;
115
+ /**
116
+ * The ServerSchema-compatible schema object (§2.4, §3.1) as 2-space JSON.
117
+ * Every emitter embeds these exact bytes: TS as an object literal, Swift,
118
+ * Kotlin, and Dart as a string literal they parse, so every platform hands
119
+ * its client the same tables, scopes, references, and indexes.
120
+ */
121
+ export declare function serializeSchema(ir: IrDocument): string;
111
122
  /** Hash of the exact IR file bytes; stamped into generated modules. */
112
123
  export declare function irHash(irJson: string): string;