@syncular/typegen 0.57.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
package/README.md CHANGED
@@ -30,8 +30,9 @@ are mutually exclusive.
30
30
  exists. `migrations check` is the fast, CI-friendly history check without
31
31
  query analysis or output generation. New migrations are appended to the lock
32
32
  by ordinary `generate`; locked migrations may never be edited, removed,
33
- renamed, or reordered. Existing format-1 locks remain valid and keep their
34
- format until `migrations upgrade-lock` explicitly validates and compacts them.
33
+ renamed, or reordered. A lock in format 1 or 2 predates per-migration schema
34
+ versions: `generate` and `migrations check` refuse it with
35
+ `typegen.migration_lock_outdated` until `migrations upgrade-lock` converts it.
35
36
 
36
37
  `init` scaffolds a starter `syncular.json`, first migration, and migration
37
38
  lock into an existing project (the "add syncular to my app" path). It refuses
@@ -81,7 +82,7 @@ schema guide and suggests `syncular init`.
81
82
  | `manifestVersion` | yes | Must be `1`. Format growth happens by bumping this, not by tolerating unknown keys. |
82
83
  | `migrations` | no (default `./migrations`) | Directory of `NNNN_name/up.sql` migrations, relative to the manifest. |
83
84
  | `queries` | no (default `./queries`) | Directory of `.sql` / `.syql` named-query files (see §6). Only read when some output requests a queries file. |
84
- | `naming` | no (default `"camel"`) | `"camel"` maps snake_case SQL names to camelCase in generated row types/params (projections lower with `AS` aliases so runtime keys match); `"preserve"` keeps SQL-truth names. Collisions/keyword hazards are generate-time errors. |
85
+ | `naming` | no (default `"camel"`) | `"camel"` maps snake_case SQL names to camelCase in generated row types/params (projections lower with `AS` aliases so runtime keys match); `"preserve"` keeps SQL-truth names. Swift, Kotlin, and Dart row fields are camelCase in both modes. In both modes, generation fails on two table or column names that differ only in letter case (`typegen.duplicate_identifier`), two tables or columns mapping to one generated name on an emitted target (`typegen.identifier_collision`), and a generated field that is a reserved word on an emitted target or starts with `_` on Dart (`typegen.reserved_identifier`). |
85
86
  | `queryBackend` | no (default `"auto"`) | Advanced revision-1 SYQL lowering override: `"neutralize"` emits guarded statements, `"variants"` enumerates activation states, and `"auto"` deterministically enumerates at ≤ 2 activation controls. This never changes source meaning or the public API. |
86
87
  | `output.ir` | no (default `./syncular.ir.json`) | IR output path, relative to the manifest. |
87
88
  | `output.module` | no (default `./syncular.generated.ts`) | Generated TS module path, relative to the manifest. |
@@ -110,14 +111,19 @@ migration list in order: version *n* covers every migration after the
110
111
  previous entry's `through` up to and including its own. **Gap rule**: the
111
112
  final entry's `through` must be the final migration — a migration not
112
113
  covered by any version is a hard error (so is a `through` naming a
113
- missing or out-of-order migration).
114
+ missing or out-of-order migration). **Locked versions**: the migration lock
115
+ records the version of every locked migration. A locked migration keeps its
116
+ version (`typegen.migration_version_changed` otherwise), and a migration added
117
+ after the lock belongs to a version above the highest locked one
118
+ (`typegen.schema_version_locked` otherwise). A deployed version therefore never
119
+ gains a column that its deployed clients would not reset for (§7.4).
114
120
 
115
121
  ### Immutable migration history
116
122
 
117
123
  `syncular.migrations.lock.json` is the version-controlled deployment baseline.
118
- Format 2 records every migration name and SHA-256 checksum (line endings
119
- normalized), plus one canonical head-schema column snapshot used only for
120
- diagnostics. It contains no SQL, filesystem path, row data, or runtime database
124
+ Format 3 records every migration name, its SHA-256 checksum (line endings
125
+ normalized), and the schema version it belongs to, plus one canonical
126
+ head-schema column snapshot used only for diagnostics. It contains no SQL, filesystem path, row data, or runtime database
121
127
  state, and grows with migration metadata plus the current schema rather than
122
128
  repeating the full cumulative schema after every migration.
123
129
 
@@ -130,17 +136,20 @@ git add syncular.migrations.lock.json
130
136
  syncular migrations check --manifest-dir .
131
137
  ```
132
138
 
133
- Projects with a committed format-1 lock upgrade deliberately, after first
134
- checking that immutable history is unchanged:
139
+ Projects with a committed format-1 or format-2 lock run one upgrade before
140
+ generating. `upgrade-lock` validates the locked history, records each locked
141
+ migration's schema version from the manifest's `schemaVersions`, and leaves
142
+ migrations appended after the old lock for `generate` to lock. Run it on a
143
+ manifest whose `schemaVersions` still describe the deployed versions:
135
144
 
136
145
  ```sh
137
- syncular migrations check --manifest-dir .
138
146
  syncular migrations upgrade-lock --manifest-dir .
139
147
  git add syncular.migrations.lock.json
148
+ syncular migrations check --manifest-dir .
140
149
  ```
141
150
 
142
- The upgrade command refuses an already-current lock and ordinary `generate`
143
- never changes the lock format implicitly.
151
+ The upgrade command refuses an already-current lock, and `generate` never
152
+ changes the lock format.
144
153
 
145
154
  After that, a deployed migration is immutable. Restore an accidentally edited
146
155
  migration and express the repair in a new `NNNN_name/up.sql`; do not delete and
@@ -346,14 +355,20 @@ statement (`CREATE TRIGGER/VIEW`, DML, `ALTER … RENAME`, …); unknown
346
355
  or parameterized types (`VARCHAR(36)`); quoted identifiers
347
356
  (`"t"`, `` `t` ``, `[t]`); table constraints (`FOREIGN KEY`, `UNIQUE`,
348
357
  `CHECK`, `CONSTRAINT`); column constraints beyond the list above
349
- (`CHECK`, `COLLATE`, …); `DEFAULT (expression)`; composite
358
+ (`CHECK`, `COLLATE`, …); `DEFAULT (expression)` and a `DEFAULT` followed by
359
+ a word other than `NULL`, `TRUE`, `FALSE`, or `CURRENT_TIME/DATE/TIMESTAMP`
360
+ (`DEFAULT NOT NULL` fails with `typegen.invalid_default`); composite
350
361
  or missing primary keys; `PRIMARY KEY` on `ADD COLUMN`; duplicate
351
362
  tables/columns; ASC/DESC, expression, or partial (`WHERE`) index columns; a
352
363
  duplicate or unknown-column index; unsupported virtual-table modules or FTS5
353
364
  options; an FTS projection without an owner or with invalid columns;
354
- trailing clauses (`STRICT`).
365
+ trailing clauses (`STRICT`); a declared reference whose column no longer has
366
+ a single-column index after replay, for example after `DROP INDEX` of its
367
+ generated `idx_<table>_<column>_ref` (`typegen.reference_index_missing`; the
368
+ server reaches children through that index, §6.11).
355
369
 
356
- **`DEFAULT` literals on `CREATE TABLE` are accepted and ignored**: typegen
370
+ **`DEFAULT` literals on `CREATE TABLE` are accepted and ignored**, including
371
+ signed numbers (`DEFAULT -1`): typegen
357
372
  extracts the schema *shape*; executing migrations (where defaults matter) is
358
373
  the host's job. Recording them is not needed by any emitter today. On
359
374
  `ALTER TABLE … ADD COLUMN`, a literal default does not make a non-null append
@@ -446,8 +461,10 @@ generated files depend only on the wrapper package's `JSONValue`/`JsonValue`.
446
461
 
447
462
  Each generated file exports, per language:
448
463
 
449
- - a **schema constant** built from the IR (byte-stable ordering) — pass it
450
- straight to the wrapper's `create(schema:)`;
464
+ - a **schema constant** parsed from a string literal that holds the exact
465
+ schema JSON the TS module's `schema` holds, with its references and indexes
466
+ (`test/golden-native.test.ts` asserts the bytes are identical in all four
467
+ languages); pass it straight to the wrapper's `create(schema:)`;
451
468
  - **one typed row type per table** with a `fromRow` factory that lifts a
452
469
  `query`/`readRows` row into the typed shape (returning null/nil when a
453
470
  non-nullable column is missing or mistyped);
@@ -456,10 +473,10 @@ Each generated file exports, per language:
456
473
 
457
474
  | | Swift | Kotlin | Dart |
458
475
  |---|---|---|---|
459
- | Schema | `enum <EnumName> { static let schema: JSONValue }` | `object <ObjectName> { val schema: JsonValue }` | `const Map<String, Object?> syncularSchema` |
476
+ | Schema | `enum <EnumName> { static let schema: JSONValue }` | `object <ObjectName> { val schema: JsonValue }` | `final Map<String, Object?> syncularSchema` |
460
477
  | Row | `struct <Table>` + `init?(row: [String: JSONValue])` | `data class <Table>` + `fromRow(row: JsonValue)` | `class <Table>` + `static <Table>? fromRow(Map<String, Object?>)` |
461
478
  | Subscription | `enum subscriptions.<Name>` w/ `scopes(...)` | `object Subscriptions.<Name>` w/ `scopes(...)` | `class Syncular<Name>Subscription` w/ static `scopes(...)` |
462
- | Imports | `Foundation`, `Syncular` | `dev.syncular.JsonValue` | (none) |
479
+ | Imports | `Foundation`, `Syncular` | `dev.syncular.JsonValue` | `dart:convert` |
463
480
 
464
481
  **Type mapping** (the six §2.4 types + blob_ref/crdt):
465
482
 
@@ -631,7 +648,7 @@ boundary):
631
648
  | Result column | Type source | Nullability | Fidelity |
632
649
  |---|---|---|---|
633
650
  | **plain column ref** (`title`, `t.title`, `title AS x`) | resolved to the IR column (decltype confirms) — exact IR type, incl. `json`/`blob_ref`/`crdt` | the IR column's nullability, lifted to nullable whenever `LEFT`, `RIGHT`, or `FULL OUTER JOIN` can null-extend its table alias | **exact** |
634
- | **computed expression** (`count(*)`, `done + 1`, `:p AS l`) | decltype is null → documented fallback: aggregate/arithmetic → number, else string | always nullable (an expression's nullability is not knowable from decltype) | **fallback** |
651
+ | **computed expression** (`count(*)`, `CAST(done + 1 AS INTEGER)`) | decltype is null → the target type of a whole-expression `CAST`, or `integer` for a whole-expression `count(...)`; any other expression fails with `typegen.computed_column_type` | always nullable (an expression's nullability is not knowable from decltype) | **fallback** |
635
652
 
636
653
  Every local synced table also has the protocol-owned `_sync_version` column.
637
654
  Named queries may project it with an explicit public alias when an application
@@ -668,9 +685,10 @@ new right relation unit, `RIGHT` lifts every prior relation in that chain, and
668
685
  join while its nested join order remains intact. `INNER`, `CROSS`, and ordinary
669
686
  `JOIN` do not remove nullability already introduced earlier in the chain.
670
687
  Unqualified coalesced `USING`/`NATURAL` columns are not assigned a guessed
671
- physical origin and stay on the honest nullable fallback path. Want an exact
672
- type for a computed column? Alias it to a plain ref, or accept the honest
673
- fallback.
688
+ physical origin and stay nullable. A computed column takes its type from the
689
+ query text ([SYQL §14.4](../../docs/SYQL.md)): wrap the expression in
690
+ `CAST(... AS <type>)`. A cast that is an operand, as in `CAST(a AS INTEGER) + 1`,
691
+ does not type the column.
674
692
 
675
693
  **Parameters** use the `:name` convention. A param's type is **inferred** where
676
694
  it compares against a plain column ref — `WHERE list_id = :listId` (equality,
@@ -747,7 +765,7 @@ represented by the same proof model.
747
765
  | TS | `listTodosRow` interface + `ListTodosParams` + `listTodosTables` + `async listTodos(client, params): Promise<ListTodosRow[]>` + a `listTodosQuery` descriptor for React |
748
766
  | Swift | `struct ListTodosRow` + `init?(row:)` and `<Enum>Queries.listTodos(client:listId:) throws -> [ListTodosRow]` + `listTodosTables` |
749
767
  | Kotlin | `data class ListTodosRow` + `fromRow` and `<Object>Queries.listTodos(client, listId): List<ListTodosRow>` + `listTodosTables` |
750
- | Dart | `class ListTodosRow` + `fromRow` and `syncularListTodosQuery(client, listId): List<ListTodosRow>` + `syncularListTodosQueryTables` |
768
+ | Dart | `class ListTodosRow` + `fromRow` and `syncularListTodosQuery(client, listId: listId): List<ListTodosRow>` + `syncularListTodosQueryTables` |
751
769
  | Rust | `list_todos::{Row, Params, DESCRIPTOR, select, run, snapshot}` with strict decoding, `i64` fidelity, reactive dependencies, `WindowCoverage`, and proven `row_key` |
752
770
 
753
771
  Each projection row is its **own** generated type per query (the drift-kill:
@@ -794,5 +812,5 @@ revisioned store:
794
812
  ```ts
795
813
  import { listTodosQuery } from './syncular.queries';
796
814
  const todos = useQuery(listTodosQuery, { listId });
797
- // todos.rows: ListTodosRow[]; todos.phase: loading | partial | ready | error
815
+ // todos.rows: ListTodosRow[]; todos.phase: loading | partial | ready | blocked | error
798
816
  ```
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { existsSync, readFileSync, watch, writeFileSync } from 'node:fs';
19
19
  import { resolve } from 'node:path';
20
+ import { TypegenError } from './errors.js';
20
21
  import { formatSyql } from './fmt.js';
21
22
  import { baselineMigrationHistory, checkMigrationHistory, checkOutputs, generate, loadQueries, upgradeMigrationHistory, writeOutputs, } from './generate.js';
22
23
  import { InitError, initProject } from './init.js';
@@ -49,7 +50,7 @@ fmt options:
49
50
  migrations options:
50
51
  baseline create the first immutable history lock; refuses overwrite
51
52
  check validate the committed history without generating outputs
52
- upgrade-lock explicitly compact a validated format-1 lock to format 2
53
+ upgrade-lock convert a validated format-1 or format-2 lock to format 3
53
54
  --manifest-dir <dir> directory holding syncular.json (default: .)
54
55
 
55
56
  init options:
@@ -182,7 +183,11 @@ function parseManifestDir(argv) {
182
183
  }
183
184
  /** Add a docs pointer to the fail-loud missing-input errors. */
184
185
  function friendlyGenerateError(error) {
185
- const message = error instanceof Error ? error.message : String(error);
186
+ const message = error instanceof TypegenError && error.code !== undefined
187
+ ? `${error.message}\n${error.code} ${JSON.stringify(error.details ?? {})}`
188
+ : error instanceof Error
189
+ ? error.message
190
+ : String(error);
186
191
  if (message.includes('manifest not found') ||
187
192
  message.includes('migrations directory does not exist') ||
188
193
  message.includes('no migrations found')) {
@@ -344,7 +349,7 @@ function runMigrations(argv) {
344
349
  fail(friendlyGenerateError(error));
345
350
  }
346
351
  writeFileSync(output.path, output.content, 'utf8');
347
- console.log(`upgraded ${output.path} to compact format 2`);
352
+ console.log(`upgraded ${output.path} to format 3`);
348
353
  console.log('review and commit the migration-lock format upgrade');
349
354
  return;
350
355
  }
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Dart emitter: neutral IR → one standalone `.dart` file exporting
3
3
  *
4
- * - `const syncularSchema` — the ServerSchema-compatible `Map<String,
5
- * Object?>` built from the IR (fed straight into `SyncularClient.create(
4
+ * - `final syncularSchema` — the ServerSchema-compatible `Map<String,
5
+ * Object?>`: the exact `serializeSchema` JSON the TS module embeds,
6
+ * decoded from a string literal (fed straight into `SyncularClient.create(
6
7
  * schema: …)`),
7
8
  * - one class per table with typed fields (per the six §2.4 column types +
8
9
  * blob_ref/crdt) and a `fromRow(Map<String, Object?>)` factory,
@@ -13,5 +14,5 @@
13
14
  * `query`/`readRows` return. The header carries the IR hash so `--check`
14
15
  * verifies freshness byte-exactly.
15
16
  */
16
- import type { IrDocument } from './ir.js';
17
+ import { type IrDocument } from './ir.js';
17
18
  export declare function emitDartModule(ir: IrDocument, hash: string): string;
package/dist/emit-dart.js CHANGED
@@ -1,4 +1,21 @@
1
- import { snakeToCamel } from './naming.js';
1
+ /**
2
+ * Dart emitter: neutral IR → one standalone `.dart` file exporting
3
+ *
4
+ * - `final syncularSchema` — the ServerSchema-compatible `Map<String,
5
+ * Object?>`: the exact `serializeSchema` JSON the TS module embeds,
6
+ * decoded from a string literal (fed straight into `SyncularClient.create(
7
+ * schema: …)`),
8
+ * - one class per table with typed fields (per the six §2.4 column types +
9
+ * blob_ref/crdt) and a `fromRow(Map<String, Object?>)` factory,
10
+ * - a `syncular<Name>Subscription` helper per subscription with a typed
11
+ * `scopes(...)` builder.
12
+ *
13
+ * The row shape is `Map<String, Object?>` — the exact type the Dart wrapper's
14
+ * `query`/`readRows` return. The header carries the IR hash so `--check`
15
+ * verifies freshness byte-exactly.
16
+ */
17
+ import { appColumnType, serializeSchema, } from './ir.js';
18
+ import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
2
19
  /** §2.4 column type → honest Dart type. `json`/`blob_ref` are the raw
3
20
  * canonical JSON string; `bytes`/`crdt` are opaque `List<int>`. */
4
21
  const DART_TYPE = {
@@ -11,78 +28,9 @@ const DART_TYPE = {
11
28
  blob_ref: 'String',
12
29
  crdt: 'List<int>',
13
30
  };
14
- function appColumnType(column) {
15
- return column.encrypted === true && column.declaredType !== undefined
16
- ? column.declaredType
17
- : column.type;
18
- }
19
- /** §5.11: app-side Dart type — declaredType for an encrypted column. */
20
- function appDartType(column) {
21
- return DART_TYPE[appColumnType(column)];
22
- }
23
- function pascalCase(name) {
24
- return name
25
- .split(/[_-]+/)
26
- .filter((part) => part.length > 0)
27
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
28
- .join('');
29
- }
30
- /** Language-facing field name — the pinned §12 naming map. */
31
- function camelCase(name) {
32
- return snakeToCamel(name);
33
- }
34
- function quote(value) {
35
- return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\$/g, '\\$')}'`;
36
- }
37
- function emitSchemaValue(ir, indent) {
38
- const lines = [];
39
- const i = indent;
40
- lines.push(`${i}<String, Object?>{`);
41
- lines.push(`${i} 'version': ${ir.schemaVersion},`);
42
- lines.push(`${i} 'tables': [`);
43
- for (const table of ir.tables) {
44
- lines.push(`${i} {`);
45
- lines.push(`${i} 'name': ${quote(table.name)},`);
46
- lines.push(`${i} 'primaryKey': ${quote(table.primaryKey)},`);
47
- lines.push(`${i} 'columns': [`);
48
- for (const column of table.columns) {
49
- const parts = [
50
- `'name': ${quote(column.name)}`,
51
- `'type': ${quote(column.type)}`,
52
- `'nullable': ${column.nullable}`,
53
- ];
54
- if (column.crdtType !== undefined) {
55
- parts.push(`'crdtType': ${quote(column.crdtType)}`);
56
- }
57
- if (column.encrypted === true) {
58
- parts.push("'encrypted': true");
59
- parts.push(`'declaredType': ${quote(column.declaredType ?? column.type)}`);
60
- }
61
- lines.push(`${i} {${parts.join(', ')}},`);
62
- }
63
- lines.push(`${i} ],`);
64
- lines.push(`${i} 'scopes': [`);
65
- for (const scope of table.scopes) {
66
- lines.push(`${i} {'pattern': ${quote(scope.pattern)}, 'column': ${quote(scope.column)}},`);
67
- }
68
- lines.push(`${i} ],`);
69
- if (table.ftsIndexes.length > 0) {
70
- lines.push(`${i} 'ftsIndexes': [`);
71
- for (const index of table.ftsIndexes) {
72
- const columns = index.columns.map((column) => quote(column)).join(', ');
73
- lines.push(`${i} {'name': ${quote(index.name)}, 'columns': [${columns}], 'tokenize': ${quote(index.tokenize)}},`);
74
- }
75
- lines.push(`${i} ],`);
76
- }
77
- lines.push(`${i} },`);
78
- }
79
- lines.push(`${i} ],`);
80
- lines.push(`${i}}`);
81
- return lines;
82
- }
83
31
  /** The accessor lifting a §2.4 value out of a `Map<String, Object?>` row. */
84
32
  function rowAccessor(column) {
85
- const key = `row[${quote(column.name)}]`;
33
+ const key = `row[${stringLiteral(column.name, 'dart')}]`;
86
34
  switch (appColumnType(column)) {
87
35
  case 'string':
88
36
  case 'json':
@@ -105,13 +53,13 @@ function emitClass(table) {
105
53
  lines.push(`/// One ${table.name} row (§2.4 column order).`);
106
54
  lines.push(`class ${type} {`);
107
55
  for (const column of table.columns) {
108
- const dart = appDartType(column);
56
+ const dart = DART_TYPE[appColumnType(column)];
109
57
  const opt = column.nullable ? '?' : '';
110
- lines.push(` final ${dart}${opt} ${camelCase(column.name)};`);
58
+ lines.push(` final ${dart}${opt} ${snakeToCamel(column.name)};`);
111
59
  }
112
60
  lines.push('');
113
61
  const ctorParams = table.columns
114
- .map((c) => `${c.nullable ? '' : 'required '}this.${camelCase(c.name)}`)
62
+ .map((c) => `${c.nullable ? '' : 'required '}this.${snakeToCamel(c.name)}`)
115
63
  .join(', ');
116
64
  lines.push(` const ${type}({${ctorParams}});`);
117
65
  lines.push('');
@@ -120,14 +68,14 @@ function emitClass(table) {
120
68
  lines.push(` static ${type}? fromRow(Map<String, Object?> row) {`);
121
69
  for (const column of table.columns) {
122
70
  if (!column.nullable) {
123
- const name = camelCase(column.name);
71
+ const name = snakeToCamel(column.name);
124
72
  lines.push(` final ${name} = ${rowAccessor(column)};`);
125
73
  lines.push(` if (${name} == null) return null;`);
126
74
  }
127
75
  }
128
76
  const args = table.columns
129
77
  .map((c) => {
130
- const name = camelCase(c.name);
78
+ const name = snakeToCamel(c.name);
131
79
  return c.nullable ? `${name}: ${rowAccessor(c)}` : `${name}: ${name}`;
132
80
  })
133
81
  .join(', ');
@@ -146,18 +94,22 @@ function emitSubscription(sub) {
146
94
  }
147
95
  }
148
96
  const lines = [];
149
- lines.push(`/// Requested-scope template for the ${quote(sub.name)} subscription.`);
97
+ lines.push(`/// Requested-scope template for the ${stringLiteral(sub.name, 'dart')} subscription.`);
150
98
  lines.push(`class Syncular${pascalCase(sub.name)}Subscription {`);
151
- lines.push(` static const String name = ${quote(sub.name)};`);
152
- lines.push(` static const String table = ${quote(sub.table)};`);
153
- const args = params.map((p) => `required String ${camelCase(p)}`).join(', ');
99
+ lines.push(` static const String name = ${stringLiteral(sub.name, 'dart')};`);
100
+ lines.push(` static const String table = ${stringLiteral(sub.table, 'dart')};`);
101
+ const args = params
102
+ .map((p) => `required String ${snakeToCamel(p)}`)
103
+ .join(', ');
154
104
  const argsClause = args.length > 0 ? `{${args}}` : '';
155
105
  lines.push(` static Map<String, List<String>> scopes(${argsClause}) => {`);
156
106
  for (const scope of sub.scopes) {
157
107
  const values = scope.values
158
- .map((value) => value.kind === 'literal' ? quote(value.value) : camelCase(value.name))
108
+ .map((value) => value.kind === 'literal'
109
+ ? stringLiteral(value.value, 'dart')
110
+ : snakeToCamel(value.name))
159
111
  .join(', ');
160
- lines.push(` ${quote(scope.variable)}: [${values}],`);
112
+ lines.push(` ${stringLiteral(scope.variable, 'dart')}: [${values}],`);
161
113
  }
162
114
  lines.push(' };');
163
115
  lines.push('}');
@@ -170,17 +122,16 @@ export function emitDartModule(ir, hash) {
170
122
  `// irVersion: ${ir.irVersion}`,
171
123
  `// irHash: ${hash}`,
172
124
  '// ignore_for_file: type=lint',
125
+ '',
126
+ "import 'dart:convert';",
173
127
  ].join('\n'));
174
128
  // The schema constant.
175
129
  const schemaLines = [];
176
130
  schemaLines.push('/// ServerSchema-compatible schema (SPEC §2.4, §3.1) —');
177
131
  schemaLines.push('/// pass to `SyncularClient.create(schema: …)`.');
178
- const schemaValue = emitSchemaValue(ir, '');
179
- schemaValue[0] = `const Map<String, Object?> syncularSchema = ${schemaValue[0]}`;
180
- schemaValue[schemaValue.length - 1] =
181
- `${schemaValue[schemaValue.length - 1]};`;
182
- for (const line of schemaValue)
183
- schemaLines.push(line);
132
+ // A multi-line literal drops the line break after its opening quotes, so
133
+ // the decoded string is the serializeSchema bytes.
134
+ schemaLines.push(`final Map<String, Object?> syncularSchema = jsonDecode('''\n${stringLiteral(serializeSchema(ir), 'dart').slice(1, -1)}''') as Map<String, Object?>;`);
184
135
  parts.push(schemaLines.join('\n'));
185
136
  // Shared row-decode helpers — emitted only when a column type references
186
137
  // them. An unused private helper is an ANALYZER diagnostic (unused_element),
@@ -2,8 +2,8 @@
2
2
  * Kotlin emitter: neutral IR → one standalone `.kt` file exporting
3
3
  *
4
4
  * - `object <ObjectName> { val schema: JsonValue }` — the ServerSchema
5
- * object built from the IR (fed straight into `SyncularClient.create(
6
- * schema = …)`),
5
+ * object: the exact `serializeSchema` JSON the TS module embeds, parsed
6
+ * from a raw string (fed straight into `SyncularClient.create(schema = …)`),
7
7
  * - one `data class` per table with typed properties (per the six §2.4 column
8
8
  * types + blob_ref/crdt) and a `fromRow(row: JsonValue)` companion factory,
9
9
  * - a `Subscriptions` object of typed requested-scope builders.
@@ -12,5 +12,5 @@
12
12
  * `query`/`readRows` return (each row a `JsonValue.Obj`). The header carries
13
13
  * the IR hash so `--check` verifies freshness byte-exactly.
14
14
  */
15
- import type { IrDocument } from './ir.js';
15
+ import { type IrDocument } from './ir.js';
16
16
  export declare function emitKotlinModule(ir: IrDocument, hash: string, packageName: string, objectName: string): string;
@@ -1,4 +1,19 @@
1
- import { snakeToCamel } from './naming.js';
1
+ /**
2
+ * Kotlin emitter: neutral IR → one standalone `.kt` file exporting
3
+ *
4
+ * - `object <ObjectName> { val schema: JsonValue }` — the ServerSchema
5
+ * object: the exact `serializeSchema` JSON the TS module embeds, parsed
6
+ * from a raw string (fed straight into `SyncularClient.create(schema = …)`),
7
+ * - one `data class` per table with typed properties (per the six §2.4 column
8
+ * types + blob_ref/crdt) and a `fromRow(row: JsonValue)` companion factory,
9
+ * - a `Subscriptions` object of typed requested-scope builders.
10
+ *
11
+ * The row shape is `JsonValue` — the exact type the Kotlin wrapper's
12
+ * `query`/`readRows` return (each row a `JsonValue.Obj`). The header carries
13
+ * the IR hash so `--check` verifies freshness byte-exactly.
14
+ */
15
+ import { appColumnType, serializeSchema, } from './ir.js';
16
+ import { pascalCase, snakeToCamel, stringLiteral } from './naming.js';
2
17
  /** §2.4 column type → honest Kotlin type. `json`/`blob_ref` are the raw
3
18
  * canonical JSON string; `bytes`/`crdt` are opaque `ByteArray`. */
4
19
  const KOTLIN_TYPE = {
@@ -11,80 +26,9 @@ const KOTLIN_TYPE = {
11
26
  blob_ref: 'String',
12
27
  crdt: 'ByteArray',
13
28
  };
14
- function appColumnType(column) {
15
- return column.encrypted === true && column.declaredType !== undefined
16
- ? column.declaredType
17
- : column.type;
18
- }
19
- /** §5.11: app-side Kotlin type — declaredType for an encrypted column. */
20
- function appKotlinType(column) {
21
- return KOTLIN_TYPE[appColumnType(column)];
22
- }
23
- function pascalCase(name) {
24
- return name
25
- .split(/[_-]+/)
26
- .filter((part) => part.length > 0)
27
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
28
- .join('');
29
- }
30
- /** Language-facing field name — the pinned §12 naming map. */
31
- function camelCase(name) {
32
- return snakeToCamel(name);
33
- }
34
- function quote(value) {
35
- return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$')}"`;
36
- }
37
- function emitSchemaValue(ir, indent) {
38
- const lines = [];
39
- const i = indent;
40
- lines.push(`${i}JsonValue.obj(`);
41
- lines.push(`${i} "version" to JsonValue.of(${ir.schemaVersion}),`);
42
- lines.push(`${i} "tables" to JsonValue.arr(listOf(`);
43
- for (const table of ir.tables) {
44
- lines.push(`${i} JsonValue.obj(`);
45
- lines.push(`${i} "name" to JsonValue.of(${quote(table.name)}),`);
46
- lines.push(`${i} "primaryKey" to JsonValue.of(${quote(table.primaryKey)}),`);
47
- lines.push(`${i} "columns" to JsonValue.arr(listOf(`);
48
- for (const column of table.columns) {
49
- const parts = [
50
- `"name" to JsonValue.of(${quote(column.name)})`,
51
- `"type" to JsonValue.of(${quote(column.type)})`,
52
- `"nullable" to JsonValue.of(${column.nullable})`,
53
- ];
54
- if (column.crdtType !== undefined) {
55
- parts.push(`"crdtType" to JsonValue.of(${quote(column.crdtType)})`);
56
- }
57
- if (column.encrypted === true) {
58
- parts.push('"encrypted" to JsonValue.of(true)');
59
- parts.push(`"declaredType" to JsonValue.of(${quote(column.declaredType ?? column.type)})`);
60
- }
61
- lines.push(`${i} JsonValue.obj(${parts.join(', ')}),`);
62
- }
63
- lines.push(`${i} )),`);
64
- lines.push(`${i} "scopes" to JsonValue.arr(listOf(`);
65
- for (const scope of table.scopes) {
66
- lines.push(`${i} JsonValue.obj("pattern" to JsonValue.of(${quote(scope.pattern)}), "column" to JsonValue.of(${quote(scope.column)})),`);
67
- }
68
- lines.push(`${i} )),`);
69
- if (table.ftsIndexes.length > 0) {
70
- lines.push(`${i} "ftsIndexes" to JsonValue.arr(listOf(`);
71
- for (const index of table.ftsIndexes) {
72
- const columns = index.columns
73
- .map((column) => `JsonValue.of(${quote(column)})`)
74
- .join(', ');
75
- lines.push(`${i} JsonValue.obj("name" to JsonValue.of(${quote(index.name)}), "columns" to JsonValue.arr(listOf(${columns})), "tokenize" to JsonValue.of(${quote(index.tokenize)})),`);
76
- }
77
- lines.push(`${i} )),`);
78
- }
79
- lines.push(`${i} ),`);
80
- }
81
- lines.push(`${i} )),`);
82
- lines.push(`${i})`);
83
- return lines;
84
- }
85
29
  /** The accessor lifting a §2.4 value out of a row `JsonValue`. */
86
30
  function rowAccessor(column) {
87
- const key = `row[${quote(column.name)}]`;
31
+ const key = `row[${stringLiteral(column.name, 'kotlin')}]`;
88
32
  switch (appColumnType(column)) {
89
33
  case 'string':
90
34
  case 'json':
@@ -107,16 +51,16 @@ function emitDataClass(table) {
107
51
  lines.push(`/** One ${table.name} row (§2.4 column order). */`);
108
52
  lines.push(`data class ${type}(`);
109
53
  for (const column of table.columns) {
110
- const kotlin = appKotlinType(column);
54
+ const kotlin = KOTLIN_TYPE[appColumnType(column)];
111
55
  const opt = column.nullable ? '?' : '';
112
- lines.push(` val ${camelCase(column.name)}: ${kotlin}${opt},`);
56
+ lines.push(` val ${snakeToCamel(column.name)}: ${kotlin}${opt},`);
113
57
  }
114
58
  lines.push(') {');
115
59
  lines.push(' companion object {');
116
60
  lines.push(` /** Build from a \`query\`/\`readRows\` row. Null on a missing/mistyped non-nullable column. */`);
117
61
  lines.push(` fun fromRow(row: JsonValue): ${type}? {`);
118
62
  for (const column of table.columns) {
119
- const name = camelCase(column.name);
63
+ const name = snakeToCamel(column.name);
120
64
  const accessor = rowAccessor(column);
121
65
  if (column.nullable) {
122
66
  lines.push(` val ${name} = ${accessor}`);
@@ -125,7 +69,7 @@ function emitDataClass(table) {
125
69
  lines.push(` val ${name} = ${accessor} ?: return null`);
126
70
  }
127
71
  }
128
- const args = table.columns.map((c) => camelCase(c.name)).join(', ');
72
+ const args = table.columns.map((c) => snakeToCamel(c.name)).join(', ');
129
73
  lines.push(` return ${type}(${args})`);
130
74
  lines.push(' }');
131
75
  lines.push(' }');
@@ -142,17 +86,19 @@ function emitSubscription(sub) {
142
86
  }
143
87
  }
144
88
  const lines = [];
145
- lines.push(` /** Requested-scope template for the ${quote(sub.name)} subscription. */`);
89
+ lines.push(` /** Requested-scope template for the ${stringLiteral(sub.name, 'kotlin')} subscription. */`);
146
90
  lines.push(` object ${pascalCase(sub.name)} {`);
147
- lines.push(` const val name = ${quote(sub.name)}`);
148
- lines.push(` const val table = ${quote(sub.table)}`);
149
- const args = params.map((p) => `${camelCase(p)}: String`).join(', ');
91
+ lines.push(` const val name = ${stringLiteral(sub.name, 'kotlin')}`);
92
+ lines.push(` const val table = ${stringLiteral(sub.table, 'kotlin')}`);
93
+ const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
150
94
  lines.push(` fun scopes(${args}): Map<String, List<String>> = mapOf(`);
151
95
  for (const scope of sub.scopes) {
152
96
  const values = scope.values
153
- .map((value) => value.kind === 'literal' ? quote(value.value) : camelCase(value.name))
97
+ .map((value) => value.kind === 'literal'
98
+ ? stringLiteral(value.value, 'kotlin')
99
+ : snakeToCamel(value.name))
154
100
  .join(', ');
155
- lines.push(` ${quote(scope.variable)} to listOf(${values}),`);
101
+ lines.push(` ${stringLiteral(scope.variable, 'kotlin')} to listOf(${values}),`);
156
102
  }
157
103
  lines.push(' )');
158
104
  lines.push(' }');
@@ -173,9 +119,16 @@ export function emitKotlinModule(ir, hash, packageName, objectName) {
173
119
  schemaLines.push('/** The generated syncular schema (SPEC §2.4, §3.1). */');
174
120
  schemaLines.push(`object ${objectName} {`);
175
121
  schemaLines.push(` /** ServerSchema-compatible schema — pass to \`SyncularClient.create(schema = …)\`. */`);
176
- schemaLines.push(' val schema: JsonValue =');
177
- for (const line of emitSchemaValue(ir, ' '))
178
- schemaLines.push(line);
122
+ // A raw string has no escapes; only `$` needs its template form.
123
+ // trimIndent() strips the common indentation and the blank first and last
124
+ // lines, so the parsed string is the serializeSchema bytes.
125
+ schemaLines.push(' val schema: JsonValue = JsonValue.parse(');
126
+ schemaLines.push(' """');
127
+ for (const line of serializeSchema(ir).split('\n')) {
128
+ schemaLines.push(` ${line.replaceAll('$', () => "${'$'}")}`);
129
+ }
130
+ schemaLines.push(' """.trimIndent(),');
131
+ schemaLines.push(' )');
179
132
  schemaLines.push('');
180
133
  schemaLines.push(' /** Typed requested-scope builders per subscription. */');
181
134
  schemaLines.push(' object Subscriptions {');
@@ -1,2 +1,2 @@
1
- import type { AnalyzedQuery } from './query.js';
1
+ import { type AnalyzedQuery } from './query.js';
2
2
  export declare function emitQueriesDartModule(queries: readonly AnalyzedQuery[], hash: string, irVersion: number): string;