@syncular/typegen 0.58.0 → 0.60.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 (78) hide show
  1. package/README.md +96 -43
  2. package/dist/cli.js +8 -3
  3. package/dist/emit-dart.d.ts +4 -3
  4. package/dist/emit-dart.js +40 -100
  5. package/dist/emit-kotlin.d.ts +4 -4
  6. package/dist/emit-kotlin.js +41 -99
  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 +18 -19
  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 +18 -27
  17. package/dist/emit-swift.d.ts +4 -4
  18. package/dist/emit-swift.js +43 -102
  19. package/dist/emit.d.ts +3 -3
  20. package/dist/emit.js +37 -113
  21. package/dist/errors.d.ts +6 -2
  22. package/dist/errors.js +10 -2
  23. package/dist/fmt.js +11 -2
  24. package/dist/generate.d.ts +4 -3
  25. package/dist/generate.js +61 -73
  26. package/dist/init.js +5 -6
  27. package/dist/ir.d.ts +14 -2
  28. package/dist/ir.js +67 -49
  29. package/dist/lower.d.ts +0 -7
  30. package/dist/lower.js +0 -62
  31. package/dist/lsp.js +6 -1
  32. package/dist/manifest.d.ts +1 -2
  33. package/dist/manifest.js +13 -12
  34. package/dist/migration-lock.d.ts +32 -23
  35. package/dist/migration-lock.js +115 -92
  36. package/dist/naming.d.ts +25 -0
  37. package/dist/naming.js +92 -0
  38. package/dist/query.d.ts +94 -14
  39. package/dist/query.js +642 -461
  40. package/dist/sql.js +18 -3
  41. package/dist/syql-ast.d.ts +2 -0
  42. package/dist/syql-ast.js +7 -1
  43. package/dist/syql-browser.js +7 -6
  44. package/dist/syql-diagnostics.d.ts +1 -0
  45. package/dist/syql-diagnostics.js +1 -0
  46. package/dist/syql-lowering.js +11 -1
  47. package/dist/syql-parser.d.ts +4 -1
  48. package/dist/syql-parser.js +42 -5
  49. package/dist/syql-validator.js +13 -220
  50. package/package.json +3 -3
  51. package/src/cli.ts +9 -3
  52. package/src/emit-dart.ts +44 -116
  53. package/src/emit-kotlin.ts +41 -118
  54. package/src/emit-queries-dart.ts +23 -32
  55. package/src/emit-queries-kotlin.ts +20 -30
  56. package/src/emit-queries-rust.ts +29 -31
  57. package/src/emit-queries-swift.ts +26 -32
  58. package/src/emit-queries.ts +26 -47
  59. package/src/emit-swift.ts +49 -120
  60. package/src/emit.ts +45 -135
  61. package/src/errors.ts +13 -2
  62. package/src/fmt.ts +10 -2
  63. package/src/generate.ts +113 -107
  64. package/src/init.ts +8 -6
  65. package/src/ir.ts +91 -54
  66. package/src/lower.ts +0 -53
  67. package/src/lsp.ts +11 -4
  68. package/src/manifest.ts +22 -18
  69. package/src/migration-lock.ts +192 -137
  70. package/src/naming.ts +154 -0
  71. package/src/query.ts +864 -502
  72. package/src/sql.ts +30 -3
  73. package/src/syql-ast.ts +9 -0
  74. package/src/syql-browser.ts +8 -7
  75. package/src/syql-diagnostics.ts +2 -0
  76. package/src/syql-lowering.ts +16 -1
  77. package/src/syql-parser.ts +73 -8
  78. 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
@@ -66,11 +67,7 @@ schema guide and suggests `syncular init`.
66
67
  }
67
68
  ],
68
69
  "subscriptions": [
69
- {
70
- "name": "projectTasks",
71
- "table": "tasks",
72
- "scopes": { "project_id": ["{projectId}"] }
73
- }
70
+ { "name": "projectTasks", "scopes": { "project_id": "{projectId}" } }
74
71
  ],
75
72
  "extensions": {}
76
73
  }
@@ -81,7 +78,7 @@ schema guide and suggests `syncular init`.
81
78
  | `manifestVersion` | yes | Must be `1`. Format growth happens by bumping this, not by tolerating unknown keys. |
82
79
  | `migrations` | no (default `./migrations`) | Directory of `NNNN_name/up.sql` migrations, relative to the manifest. |
83
80
  | `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. |
81
+ | `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
82
  | `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
83
  | `output.ir` | no (default `./syncular.ir.json`) | IR output path, relative to the manifest. |
87
84
  | `output.module` | no (default `./syncular.generated.ts`) | Generated TS module path, relative to the manifest. |
@@ -96,8 +93,8 @@ schema guide and suggests `syncular init`.
96
93
  | `tables[].name` | yes | Must be created by a migration. |
97
94
  | `tables[].scopes` | yes, ≥ 1 | §3.1 scope patterns: `'prefix:{variable}'` (column = variable) or `{ "pattern", "column" }`. The column must exist on the table; one variable must not map to two different columns. |
98
95
  | `tables[].extensions` | no (default `{}`) | Opaque passthrough into the IR table's `extensions` slot. |
99
- | `subscriptions` | no (default `[]`) | Requested-scope templates. `name` must be a valid JS identifier and unique; `table` must be a listed table; every scope key must be a scope variable of that table. |
100
- | `subscriptions[].scopes` | yes, non-empty | Map of variable → non-empty list of values. Each value is **either** a literal **or** exactly `"{param}"`. Partial templates (`"p-{x}"`) and `"*"` (§3.2 rejects requested wildcards) are hard errors. |
96
+ | `subscriptions` | no (default `[]`) | Unit templates (SPEC §4.1). `name` must be a valid JS identifier and unique. A template names no table: its unit covers every table that declares all of its scope variables. A template whose variables no single table declares fails with `typegen.subscription_uncovered`. |
97
+ | `subscriptions[].scopes` | yes, non-empty | Map of variable → one value. The value is **either** a literal **or** exactly `"{param}"`. Partial templates (`"p-{x}"`) and `"*"` (§3.2 rejects requested wildcards) fail with `typegen.subscription_invalid_value`. Several values of one variable are several templates. An entry with a `table` key or a value list (the wire version 3 shape) fails with `typegen.subscription_legacy_shape`, whose message names this shape. |
101
98
  | `extensions` | no (default `{}`) | Opaque passthrough into the IR document's `extensions` slot. |
102
99
 
103
100
  Unknown keys are hard errors at every level, except inside `extensions`
@@ -110,14 +107,19 @@ migration list in order: version *n* covers every migration after the
110
107
  previous entry's `through` up to and including its own. **Gap rule**: the
111
108
  final entry's `through` must be the final migration — a migration not
112
109
  covered by any version is a hard error (so is a `through` naming a
113
- missing or out-of-order migration).
110
+ missing or out-of-order migration). **Locked versions**: the migration lock
111
+ records the version of every locked migration. A locked migration keeps its
112
+ version (`typegen.migration_version_changed` otherwise), and a migration added
113
+ after the lock belongs to a version above the highest locked one
114
+ (`typegen.schema_version_locked` otherwise). A deployed version therefore never
115
+ gains a column that its deployed clients would not reset for (§7.4).
114
116
 
115
117
  ### Immutable migration history
116
118
 
117
119
  `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
120
+ Format 3 records every migration name, its SHA-256 checksum (line endings
121
+ normalized), and the schema version it belongs to, plus one canonical
122
+ head-schema column snapshot used only for diagnostics. It contains no SQL, filesystem path, row data, or runtime database
121
123
  state, and grows with migration metadata plus the current schema rather than
122
124
  repeating the full cumulative schema after every migration.
123
125
 
@@ -130,17 +132,20 @@ git add syncular.migrations.lock.json
130
132
  syncular migrations check --manifest-dir .
131
133
  ```
132
134
 
133
- Projects with a committed format-1 lock upgrade deliberately, after first
134
- checking that immutable history is unchanged:
135
+ Projects with a committed format-1 or format-2 lock run one upgrade before
136
+ generating. `upgrade-lock` validates the locked history, records each locked
137
+ migration's schema version from the manifest's `schemaVersions`, and leaves
138
+ migrations appended after the old lock for `generate` to lock. Run it on a
139
+ manifest whose `schemaVersions` still describe the deployed versions:
135
140
 
136
141
  ```sh
137
- syncular migrations check --manifest-dir .
138
142
  syncular migrations upgrade-lock --manifest-dir .
139
143
  git add syncular.migrations.lock.json
144
+ syncular migrations check --manifest-dir .
140
145
  ```
141
146
 
142
- The upgrade command refuses an already-current lock and ordinary `generate`
143
- never changes the lock format implicitly.
147
+ The upgrade command refuses an already-current lock, and `generate` never
148
+ changes the lock format.
144
149
 
145
150
  After that, a deployed migration is immutable. Restore an accidentally edited
146
151
  migration and express the repair in a new `NNNN_name/up.sql`; do not delete and
@@ -203,11 +208,10 @@ the six §2.4 names.
203
208
  "subscriptions": [
204
209
  {
205
210
  "name": "projectTasks",
206
- "table": "tasks",
207
211
  "scopes": [
208
212
  {
209
213
  "variable": "project_id",
210
- "values": [{ "kind": "parameter", "name": "projectId" }]
214
+ "value": { "kind": "parameter", "name": "projectId" }
211
215
  }
212
216
  ]
213
217
  }
@@ -229,7 +233,7 @@ the six §2.4 names.
229
233
  **only** when the table declares at least one index, so index-free tables
230
234
  (every pre-index manifest) keep byte-identical IR + generated output. It is a
231
235
  client-side/query-check concern; see §3's index note.
232
- - `subscriptions[].scopes` is sorted by `variable`; each value is
236
+ - `subscriptions[].scopes` is sorted by `variable`; each `value` is
233
237
  `{ "kind": "literal", "value" }` or `{ "kind": "parameter", "name" }`.
234
238
  - **Determinism**: equal inputs produce byte-identical output — fixed key
235
239
  order (as shown above), 2-space indent, LF, trailing newline, extension
@@ -346,14 +350,20 @@ statement (`CREATE TRIGGER/VIEW`, DML, `ALTER … RENAME`, …); unknown
346
350
  or parameterized types (`VARCHAR(36)`); quoted identifiers
347
351
  (`"t"`, `` `t` ``, `[t]`); table constraints (`FOREIGN KEY`, `UNIQUE`,
348
352
  `CHECK`, `CONSTRAINT`); column constraints beyond the list above
349
- (`CHECK`, `COLLATE`, …); `DEFAULT (expression)`; composite
353
+ (`CHECK`, `COLLATE`, …); `DEFAULT (expression)` and a `DEFAULT` followed by
354
+ a word other than `NULL`, `TRUE`, `FALSE`, or `CURRENT_TIME/DATE/TIMESTAMP`
355
+ (`DEFAULT NOT NULL` fails with `typegen.invalid_default`); composite
350
356
  or missing primary keys; `PRIMARY KEY` on `ADD COLUMN`; duplicate
351
357
  tables/columns; ASC/DESC, expression, or partial (`WHERE`) index columns; a
352
358
  duplicate or unknown-column index; unsupported virtual-table modules or FTS5
353
359
  options; an FTS projection without an owner or with invalid columns;
354
- trailing clauses (`STRICT`).
360
+ trailing clauses (`STRICT`); a declared reference whose column no longer has
361
+ a single-column index after replay, for example after `DROP INDEX` of its
362
+ generated `idx_<table>_<column>_ref` (`typegen.reference_index_missing`; the
363
+ server reaches children through that index, §6.11).
355
364
 
356
- **`DEFAULT` literals on `CREATE TABLE` are accepted and ignored**: typegen
365
+ **`DEFAULT` literals on `CREATE TABLE` are accepted and ignored**, including
366
+ signed numbers (`DEFAULT -1`): typegen
357
367
  extracts the schema *shape*; executing migrations (where defaults matter) is
358
368
  the host's job. Recording them is not needed by any emitter today. On
359
369
  `ALTER TABLE … ADD COLUMN`, a literal default does not make a non-null append
@@ -418,10 +428,10 @@ The emitted `*.generated.ts` module:
418
428
  - `TUpdate` — primary key required; every other column optional.
419
429
  - Insert/Update are **client-side input conveniences only** — the wire
420
430
  stays full-row upserts (§6.1); nothing partial is ever encoded.
421
- - Exports per subscription `s`: `sSubscription` with `name`, `table`, and
422
- a `scopes(params)` builder returning `Record<string, string[]>`
423
- (requested scopes), plus an `SParams` interface when the template has
424
- `{param}` placeholders.
431
+ - Exports per subscription `s`: `sSubscription` with `name` and a
432
+ `scopes(params)` builder returning the unit's scope map
433
+ `Record<string, string>`, which `client.subscribe(...)` takes, plus an
434
+ `SParams` interface when the template has `{param}` placeholders.
425
435
 
426
436
  **Lint/freshness split**: `*.generated.ts` is excluded from oxlint and oxfmt
427
437
  (see `.oxlintrc.json` / `.oxfmtrc.json`) — hand-format rules on machine
@@ -446,20 +456,24 @@ generated files depend only on the wrapper package's `JSONValue`/`JsonValue`.
446
456
 
447
457
  Each generated file exports, per language:
448
458
 
449
- - a **schema constant** built from the IR (byte-stable ordering) — pass it
450
- straight to the wrapper's `create(schema:)`;
459
+ - a **schema constant** parsed from a string literal that holds the exact
460
+ schema JSON the TS module's `schema` holds, with its references and indexes
461
+ (`test/golden-native.test.ts` asserts the bytes are identical in all four
462
+ languages); pass it straight to the wrapper's `create(schema:)`;
451
463
  - **one typed row type per table** with a `fromRow` factory that lifts a
452
464
  `query`/`readRows` row into the typed shape (returning null/nil when a
453
465
  non-nullable column is missing or mistyped);
454
- - **one requested-scope builder per subscription**, `{param}` placeholders
455
- becoming typed function arguments.
466
+ - **one unit-template builder per subscription**, `{param}` placeholders
467
+ becoming typed function arguments. It returns the unit's scope map
468
+ (`[String: String]`, `Map<String, String>`), which the binding's
469
+ `subscribe` takes.
456
470
 
457
471
  | | Swift | Kotlin | Dart |
458
472
  |---|---|---|---|
459
- | Schema | `enum <EnumName> { static let schema: JSONValue }` | `object <ObjectName> { val schema: JsonValue }` | `const Map<String, Object?> syncularSchema` |
473
+ | Schema | `enum <EnumName> { static let schema: JSONValue }` | `object <ObjectName> { val schema: JsonValue }` | `final Map<String, Object?> syncularSchema` |
460
474
  | Row | `struct <Table>` + `init?(row: [String: JSONValue])` | `data class <Table>` + `fromRow(row: JsonValue)` | `class <Table>` + `static <Table>? fromRow(Map<String, Object?>)` |
461
475
  | 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) |
476
+ | Imports | `Foundation`, `Syncular` | `dev.syncular.JsonValue` | `dart:convert` |
463
477
 
464
478
  **Type mapping** (the six §2.4 types + blob_ref/crdt):
465
479
 
@@ -631,7 +645,7 @@ boundary):
631
645
  | Result column | Type source | Nullability | Fidelity |
632
646
  |---|---|---|---|
633
647
  | **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** |
648
+ | **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
649
 
636
650
  Every local synced table also has the protocol-owned `_sync_version` column.
637
651
  Named queries may project it with an explicit public alias when an application
@@ -668,9 +682,10 @@ new right relation unit, `RIGHT` lifts every prior relation in that chain, and
668
682
  join while its nested join order remains intact. `INNER`, `CROSS`, and ordinary
669
683
  `JOIN` do not remove nullability already introduced earlier in the chain.
670
684
  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.
685
+ physical origin and stay nullable. A computed column takes its type from the
686
+ query text ([SYQL §14.4](../../docs/SYQL.md)): wrap the expression in
687
+ `CAST(... AS <type>)`. A cast that is an operand, as in `CAST(a AS INTEGER) + 1`,
688
+ does not type the column.
674
689
 
675
690
  **Parameters** use the `:name` convention. A param's type is **inferred** where
676
691
  it compares against a plain column ref — `WHERE list_id = :listId` (equality,
@@ -688,6 +703,41 @@ Missing **both** inference and a comment is a generate-time error naming the
688
703
  param and the fix. A `-- param` comment for a param the query does not use is
689
704
  also an error. The inference is deliberately simple and honest.
690
705
 
706
+ **Query plan check.** Generation runs `EXPLAIN QUERY PLAN` on every emitted
707
+ statement (each physical statement of a `.syql` query) against the in-memory
708
+ schema database, which holds the declared indexes and no statistics, and fails
709
+ on four findings ([SYQL §14.5](../../docs/SYQL.md#145-query-plan-check)):
710
+
711
+ | Code | Finding |
712
+ |---|---|
713
+ | `typegen.query_scan` | A scan that an index on one column of the scanned table removes; `columns` lists those columns |
714
+ | `typegen.query_automatic_index` | A transient index SQLite builds on every run for a join |
715
+ | `typegen.query_unbounded` | A top-level scan in a statement with no `WHERE` and no `LIMIT` outside parentheses |
716
+ | `typegen.query_many_tables` | More than four tables, each a reactive dependency |
717
+
718
+ The details carry `query`, `file`, the statement index, its positional `sql`,
719
+ the `table` and the `plan` lines (`tables` for `many_tables`). Declare the
720
+ index, change the query, or acknowledge the finding on the statement with a
721
+ reason. A `.sql` acknowledgement is a leading comment beside `-- name:` and
722
+ `-- param`; a `.syql` acknowledgement is an `allow` line above the query:
723
+
724
+ ```sql
725
+ -- allow scan tasks: a project holds at most 200 tasks
726
+ SELECT id, title FROM tasks WHERE priority = :priority
727
+ ```
728
+
729
+ ```syql
730
+ allow scan tasks 'a project holds at most 200 tasks'
731
+ query tasksByPriority(priority) {
732
+ select id, title from tasks where priority = :priority;
733
+ }
734
+ ```
735
+
736
+ An acknowledgement without a reason fails with
737
+ `typegen.query_acknowledgement_invalid` (`SYQL2013_INVALID_ACKNOWLEDGEMENT` in
738
+ `.syql`), and one that matches no finding of its query fails with
739
+ `typegen.query_acknowledgement_unused`.
740
+
691
741
  **Emitted SQL.** Wrappers take **positional** params (`query(sql, params[])`),
692
742
  so the emitted SQL rewrites `:name` → `?` (repeats included) and each runner
693
743
  reorders the named params object into the positional array. Comments are
@@ -722,8 +772,11 @@ scope on every table instance. Select the unit with `by` for a multi-scope
722
772
  table. The descriptor includes all proven dimensions; unbound dimensions are
723
773
  omitted. A required scope bind can propagate across a qualified
724
774
  scope-column equality in an unconditional outer `WHERE` clause or a simple
725
- mandatory `ON` clause. The generated descriptor contains aggregate coverage for
726
- every table, and readiness requires all of it. A self-join claims coverage when
775
+ mandatory `ON` clause. The analysis holds aggregate coverage for every table,
776
+ and readiness requires all of it. The generated descriptor's `coverage(params)`
777
+ returns window bases (SPEC §4.8), `{ base: { variable, fixedScopes? }, units }`:
778
+ a base names no table, so tables proven by the same base share one entry, and
779
+ a fixed scope holds one value. A self-join claims coverage when
727
780
  every instance of the table carries the same proof (the same scopes, operators,
728
781
  and parameters); the descriptor then holds one coverage entry and one
729
782
  dependency for that table. An unproven instance or differing proofs fail with
@@ -747,7 +800,7 @@ represented by the same proof model.
747
800
  | TS | `listTodosRow` interface + `ListTodosParams` + `listTodosTables` + `async listTodos(client, params): Promise<ListTodosRow[]>` + a `listTodosQuery` descriptor for React |
748
801
  | Swift | `struct ListTodosRow` + `init?(row:)` and `<Enum>Queries.listTodos(client:listId:) throws -> [ListTodosRow]` + `listTodosTables` |
749
802
  | 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` |
803
+ | Dart | `class ListTodosRow` + `fromRow` and `syncularListTodosQuery(client, listId: listId): List<ListTodosRow>` + `syncularListTodosQueryTables` |
751
804
  | Rust | `list_todos::{Row, Params, DESCRIPTOR, select, run, snapshot}` with strict decoding, `i64` fidelity, reactive dependencies, `WindowCoverage`, and proven `row_key` |
752
805
 
753
806
  Each projection row is its **own** generated type per query (the drift-kill:
@@ -794,5 +847,5 @@ revisioned store:
794
847
  ```ts
795
848
  import { listTodosQuery } from './syncular.queries';
796
849
  const todos = useQuery(listTodosQuery, { listId });
797
- // todos.rows: ListTodosRow[]; todos.phase: loading | partial | ready | error
850
+ // todos.rows: ListTodosRow[]; todos.phase: loading | partial | ready | blocked | error
798
851
  ```
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(', ');
@@ -137,27 +85,20 @@ function emitClass(table) {
137
85
  return lines;
138
86
  }
139
87
  function emitSubscription(sub) {
140
- const params = [];
141
- for (const scope of sub.scopes) {
142
- for (const value of scope.values) {
143
- if (value.kind === 'parameter' && !params.includes(value.name)) {
144
- params.push(value.name);
145
- }
146
- }
147
- }
88
+ const params = [
89
+ ...new Set(sub.scopes.flatMap(({ value }) => value.kind === 'parameter' ? [value.name] : [])),
90
+ ];
148
91
  const lines = [];
149
- lines.push(`/// Requested-scope template for the ${quote(sub.name)} subscription.`);
92
+ lines.push(`/// Unit template for the ${stringLiteral(sub.name, 'dart')} subscription (SPEC §4.1).`);
150
93
  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(', ');
94
+ lines.push(` static const String name = ${stringLiteral(sub.name, 'dart')};`);
95
+ const args = params
96
+ .map((p) => `required String ${snakeToCamel(p)}`)
97
+ .join(', ');
154
98
  const argsClause = args.length > 0 ? `{${args}}` : '';
155
- lines.push(` static Map<String, List<String>> scopes(${argsClause}) => {`);
156
- for (const scope of sub.scopes) {
157
- const values = scope.values
158
- .map((value) => value.kind === 'literal' ? quote(value.value) : camelCase(value.name))
159
- .join(', ');
160
- lines.push(` ${quote(scope.variable)}: [${values}],`);
99
+ lines.push(` static Map<String, String> scopes(${argsClause}) => {`);
100
+ for (const { variable, value } of sub.scopes) {
101
+ lines.push(` ${stringLiteral(variable, 'dart')}: ${value.kind === 'literal' ? stringLiteral(value.value, 'dart') : snakeToCamel(value.name)},`);
161
102
  }
162
103
  lines.push(' };');
163
104
  lines.push('}');
@@ -170,17 +111,16 @@ export function emitDartModule(ir, hash) {
170
111
  `// irVersion: ${ir.irVersion}`,
171
112
  `// irHash: ${hash}`,
172
113
  '// ignore_for_file: type=lint',
114
+ '',
115
+ "import 'dart:convert';",
173
116
  ].join('\n'));
174
117
  // The schema constant.
175
118
  const schemaLines = [];
176
119
  schemaLines.push('/// ServerSchema-compatible schema (SPEC §2.4, §3.1) —');
177
120
  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);
121
+ // A multi-line literal drops the line break after its opening quotes, so
122
+ // the decoded string is the serializeSchema bytes.
123
+ schemaLines.push(`final Map<String, Object?> syncularSchema = jsonDecode('''\n${stringLiteral(serializeSchema(ir), 'dart').slice(1, -1)}''') as Map<String, Object?>;`);
184
124
  parts.push(schemaLines.join('\n'));
185
125
  // Shared row-decode helpers — emitted only when a column type references
186
126
  // them. An unused private helper is an ANALYZER diagnostic (unused_element),
@@ -2,15 +2,15 @@
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
- * - a `Subscriptions` object of typed requested-scope builders.
9
+ * - a `Subscriptions` object of typed unit-template builders (SPEC §4.1).
10
10
  *
11
11
  * The row shape is `JsonValue` — the exact type the Kotlin wrapper's
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;