@syncular/typegen 0.59.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 (47) hide show
  1. package/README.md +53 -18
  2. package/dist/emit-dart.js +7 -18
  3. package/dist/emit-kotlin.d.ts +1 -1
  4. package/dist/emit-kotlin.js +9 -20
  5. package/dist/emit-queries-rust.js +18 -14
  6. package/dist/emit-queries.js +19 -23
  7. package/dist/emit-swift.d.ts +1 -1
  8. package/dist/emit-swift.js +9 -20
  9. package/dist/emit.d.ts +2 -2
  10. package/dist/emit.js +9 -20
  11. package/dist/fmt.js +11 -2
  12. package/dist/generate.js +31 -26
  13. package/dist/init.js +4 -5
  14. package/dist/ir.d.ts +3 -2
  15. package/dist/ir.js +1 -2
  16. package/dist/lsp.js +6 -1
  17. package/dist/manifest.d.ts +1 -2
  18. package/dist/manifest.js +13 -12
  19. package/dist/query.d.ts +40 -0
  20. package/dist/query.js +159 -0
  21. package/dist/syql-ast.d.ts +2 -0
  22. package/dist/syql-ast.js +7 -1
  23. package/dist/syql-browser.js +7 -6
  24. package/dist/syql-diagnostics.d.ts +1 -0
  25. package/dist/syql-diagnostics.js +1 -0
  26. package/dist/syql-lowering.js +1 -0
  27. package/dist/syql-parser.d.ts +4 -1
  28. package/dist/syql-parser.js +42 -5
  29. package/package.json +3 -3
  30. package/src/emit-dart.ts +11 -22
  31. package/src/emit-kotlin.ts +13 -26
  32. package/src/emit-queries-rust.ts +22 -19
  33. package/src/emit-queries.ts +23 -38
  34. package/src/emit-swift.ts +15 -24
  35. package/src/emit.ts +15 -22
  36. package/src/fmt.ts +10 -2
  37. package/src/generate.ts +44 -36
  38. package/src/init.ts +4 -5
  39. package/src/ir.ts +4 -4
  40. package/src/lsp.ts +11 -4
  41. package/src/manifest.ts +22 -18
  42. package/src/query.ts +251 -0
  43. package/src/syql-ast.ts +9 -0
  44. package/src/syql-browser.ts +8 -7
  45. package/src/syql-diagnostics.ts +2 -0
  46. package/src/syql-lowering.ts +1 -0
  47. package/src/syql-parser.ts +73 -8
package/README.md CHANGED
@@ -67,11 +67,7 @@ schema guide and suggests `syncular init`.
67
67
  }
68
68
  ],
69
69
  "subscriptions": [
70
- {
71
- "name": "projectTasks",
72
- "table": "tasks",
73
- "scopes": { "project_id": ["{projectId}"] }
74
- }
70
+ { "name": "projectTasks", "scopes": { "project_id": "{projectId}" } }
75
71
  ],
76
72
  "extensions": {}
77
73
  }
@@ -97,8 +93,8 @@ schema guide and suggests `syncular init`.
97
93
  | `tables[].name` | yes | Must be created by a migration. |
98
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. |
99
95
  | `tables[].extensions` | no (default `{}`) | Opaque passthrough into the IR table's `extensions` slot. |
100
- | `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. |
101
- | `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. |
102
98
  | `extensions` | no (default `{}`) | Opaque passthrough into the IR document's `extensions` slot. |
103
99
 
104
100
  Unknown keys are hard errors at every level, except inside `extensions`
@@ -212,11 +208,10 @@ the six §2.4 names.
212
208
  "subscriptions": [
213
209
  {
214
210
  "name": "projectTasks",
215
- "table": "tasks",
216
211
  "scopes": [
217
212
  {
218
213
  "variable": "project_id",
219
- "values": [{ "kind": "parameter", "name": "projectId" }]
214
+ "value": { "kind": "parameter", "name": "projectId" }
220
215
  }
221
216
  ]
222
217
  }
@@ -238,7 +233,7 @@ the six §2.4 names.
238
233
  **only** when the table declares at least one index, so index-free tables
239
234
  (every pre-index manifest) keep byte-identical IR + generated output. It is a
240
235
  client-side/query-check concern; see §3's index note.
241
- - `subscriptions[].scopes` is sorted by `variable`; each value is
236
+ - `subscriptions[].scopes` is sorted by `variable`; each `value` is
242
237
  `{ "kind": "literal", "value" }` or `{ "kind": "parameter", "name" }`.
243
238
  - **Determinism**: equal inputs produce byte-identical output — fixed key
244
239
  order (as shown above), 2-space indent, LF, trailing newline, extension
@@ -433,10 +428,10 @@ The emitted `*.generated.ts` module:
433
428
  - `TUpdate` — primary key required; every other column optional.
434
429
  - Insert/Update are **client-side input conveniences only** — the wire
435
430
  stays full-row upserts (§6.1); nothing partial is ever encoded.
436
- - Exports per subscription `s`: `sSubscription` with `name`, `table`, and
437
- a `scopes(params)` builder returning `Record<string, string[]>`
438
- (requested scopes), plus an `SParams` interface when the template has
439
- `{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.
440
435
 
441
436
  **Lint/freshness split**: `*.generated.ts` is excluded from oxlint and oxfmt
442
437
  (see `.oxlintrc.json` / `.oxfmtrc.json`) — hand-format rules on machine
@@ -468,8 +463,10 @@ Each generated file exports, per language:
468
463
  - **one typed row type per table** with a `fromRow` factory that lifts a
469
464
  `query`/`readRows` row into the typed shape (returning null/nil when a
470
465
  non-nullable column is missing or mistyped);
471
- - **one requested-scope builder per subscription**, `{param}` placeholders
472
- 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.
473
470
 
474
471
  | | Swift | Kotlin | Dart |
475
472
  |---|---|---|---|
@@ -706,6 +703,41 @@ Missing **both** inference and a comment is a generate-time error naming the
706
703
  param and the fix. A `-- param` comment for a param the query does not use is
707
704
  also an error. The inference is deliberately simple and honest.
708
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
+
709
741
  **Emitted SQL.** Wrappers take **positional** params (`query(sql, params[])`),
710
742
  so the emitted SQL rewrites `:name` → `?` (repeats included) and each runner
711
743
  reorders the named params object into the positional array. Comments are
@@ -740,8 +772,11 @@ scope on every table instance. Select the unit with `by` for a multi-scope
740
772
  table. The descriptor includes all proven dimensions; unbound dimensions are
741
773
  omitted. A required scope bind can propagate across a qualified
742
774
  scope-column equality in an unconditional outer `WHERE` clause or a simple
743
- mandatory `ON` clause. The generated descriptor contains aggregate coverage for
744
- 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
745
780
  every instance of the table carries the same proof (the same scopes, operators,
746
781
  and parameters); the descriptor then holds one coverage entry and one
747
782
  dependency for that table. An unproven instance or differing proofs fail with
package/dist/emit-dart.js CHANGED
@@ -85,31 +85,20 @@ function emitClass(table) {
85
85
  return lines;
86
86
  }
87
87
  function emitSubscription(sub) {
88
- const params = [];
89
- for (const scope of sub.scopes) {
90
- for (const value of scope.values) {
91
- if (value.kind === 'parameter' && !params.includes(value.name)) {
92
- params.push(value.name);
93
- }
94
- }
95
- }
88
+ const params = [
89
+ ...new Set(sub.scopes.flatMap(({ value }) => value.kind === 'parameter' ? [value.name] : [])),
90
+ ];
96
91
  const lines = [];
97
- lines.push(`/// Requested-scope template for the ${stringLiteral(sub.name, 'dart')} subscription.`);
92
+ lines.push(`/// Unit template for the ${stringLiteral(sub.name, 'dart')} subscription (SPEC §4.1).`);
98
93
  lines.push(`class Syncular${pascalCase(sub.name)}Subscription {`);
99
94
  lines.push(` static const String name = ${stringLiteral(sub.name, 'dart')};`);
100
- lines.push(` static const String table = ${stringLiteral(sub.table, 'dart')};`);
101
95
  const args = params
102
96
  .map((p) => `required String ${snakeToCamel(p)}`)
103
97
  .join(', ');
104
98
  const argsClause = args.length > 0 ? `{${args}}` : '';
105
- lines.push(` static Map<String, List<String>> scopes(${argsClause}) => {`);
106
- for (const scope of sub.scopes) {
107
- const values = scope.values
108
- .map((value) => value.kind === 'literal'
109
- ? stringLiteral(value.value, 'dart')
110
- : snakeToCamel(value.name))
111
- .join(', ');
112
- lines.push(` ${stringLiteral(scope.variable, 'dart')}: [${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)},`);
113
102
  }
114
103
  lines.push(' };');
115
104
  lines.push('}');
@@ -6,7 +6,7 @@
6
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
@@ -6,7 +6,7 @@
6
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
@@ -77,28 +77,17 @@ function emitDataClass(table) {
77
77
  return lines;
78
78
  }
79
79
  function emitSubscription(sub) {
80
- const params = [];
81
- for (const scope of sub.scopes) {
82
- for (const value of scope.values) {
83
- if (value.kind === 'parameter' && !params.includes(value.name)) {
84
- params.push(value.name);
85
- }
86
- }
87
- }
80
+ const params = [
81
+ ...new Set(sub.scopes.flatMap(({ value }) => value.kind === 'parameter' ? [value.name] : [])),
82
+ ];
88
83
  const lines = [];
89
- lines.push(` /** Requested-scope template for the ${stringLiteral(sub.name, 'kotlin')} subscription. */`);
84
+ lines.push(` /** Unit template for the ${stringLiteral(sub.name, 'kotlin')} subscription (SPEC §4.1). */`);
90
85
  lines.push(` object ${pascalCase(sub.name)} {`);
91
86
  lines.push(` const val name = ${stringLiteral(sub.name, 'kotlin')}`);
92
- lines.push(` const val table = ${stringLiteral(sub.table, 'kotlin')}`);
93
87
  const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
94
- lines.push(` fun scopes(${args}): Map<String, List<String>> = mapOf(`);
95
- for (const scope of sub.scopes) {
96
- const values = scope.values
97
- .map((value) => value.kind === 'literal'
98
- ? stringLiteral(value.value, 'kotlin')
99
- : snakeToCamel(value.name))
100
- .join(', ');
101
- lines.push(` ${stringLiteral(scope.variable, 'kotlin')} to listOf(${values}),`);
88
+ lines.push(` fun scopes(${args}): Map<String, String> = mapOf(`);
89
+ for (const { variable, value } of sub.scopes) {
90
+ lines.push(` ${stringLiteral(variable, 'kotlin')} to ${value.kind === 'literal' ? stringLiteral(value.value, 'kotlin') : snakeToCamel(value.name)},`);
102
91
  }
103
92
  lines.push(' )');
104
93
  lines.push(' }');
@@ -130,7 +119,7 @@ export function emitKotlinModule(ir, hash, packageName, objectName) {
130
119
  schemaLines.push(' """.trimIndent(),');
131
120
  schemaLines.push(' )');
132
121
  schemaLines.push('');
133
- schemaLines.push(' /** Typed requested-scope builders per subscription. */');
122
+ schemaLines.push(' /** Typed unit-template builders per subscription (SPEC §4.1). */');
134
123
  schemaLines.push(' object Subscriptions {');
135
124
  if (ir.subscriptions.length === 0) {
136
125
  schemaLines.push(' // (no subscriptions declared)');
@@ -1,5 +1,5 @@
1
1
  import { buildRustNamingMap, rustPascalCase, rustSnakeCase } from './naming.js';
2
- import { syqlInput, } from './query.js';
2
+ import { syqlInput, windowBases, } from './query.js';
3
3
  const RUST_TYPE = {
4
4
  string: 'String',
5
5
  integer: 'i64',
@@ -378,23 +378,26 @@ function emitDependencies(query) {
378
378
  return lines;
379
379
  }
380
380
  function emitCoverage(query) {
381
- const usesParams = query.reactive.coverage.some((coverage) => coverage.units.length > 0 ||
382
- coverage.fixedScopes.some((scope) => scope.params.length > 0));
381
+ const coverage = windowBases(query.reactive.coverage);
383
382
  const lines = [
384
- ` pub fn coverage(${usesParams ? 'params' : '_params'}: &Params) -> Vec<WindowCoverage> {`,
383
+ ` pub fn coverage(${coverage.length > 0 ? 'params' : '_params'}: &Params) -> Vec<WindowCoverage> {`,
385
384
  ' vec![',
386
385
  ];
387
- for (const coverage of query.reactive.coverage) {
388
- const fixed = coverage.fixedScopes.map((scope) => {
389
- const values = scope.params
390
- .map((param) => reactiveParam(query, param))
391
- .join(', ');
392
- return `(${quote(scope.variable)}.to_owned(), vec![${values}])`;
393
- });
394
- const units = coverage.units
386
+ for (const entry of coverage) {
387
+ const fixed = entry.fixedScopes.map((scope) => `(${quote(scope.variable)}.to_owned(), ${reactiveParam(query, scope.param)})`);
388
+ const units = entry.units
395
389
  .map((param) => reactiveParam(query, param))
396
390
  .join(', ');
397
- lines.push(' WindowCoverage {', ' base: WindowBase {', ` table: ${quote(coverage.table)}.to_owned(),`, ` variable: ${quote(coverage.variable)}.to_owned(),`, ` fixed_scopes: vec![${fixed.join(', ')}],`, ' params: None,', ' },', ` units: vec![${units}],`, ' },');
391
+ const fixedLine = ` fixed_scopes: UnitScopes::from([${fixed.join(', ')}]),`;
392
+ lines.push(' WindowCoverage {', ' base: WindowBase {', ` variable: ${quote(entry.variable)}.to_owned(),`, ...(fixed.length === 0
393
+ ? [' fixed_scopes: UnitScopes::new(),']
394
+ : fixedLine.length <= 100
395
+ ? [fixedLine]
396
+ : [
397
+ ' fixed_scopes: UnitScopes::from([',
398
+ ...fixed.map((pair) => ` ${pair},`),
399
+ ' ]),',
400
+ ]), ' },', ` units: vec![${units}],`, ' },');
398
401
  }
399
402
  lines.push(' ]', ' }');
400
403
  return lines;
@@ -493,7 +496,8 @@ function emitSupport(clientCrate) {
493
496
  'use std::error::Error;',
494
497
  'use std::fmt;',
495
498
  `use ${clientCrate}::{`,
496
- ' CoverageSnapshot, QueryOwner, QueryRow, QueryValue, SyncClient, WindowBase, WindowCoverage,',
499
+ ' CoverageSnapshot, QueryOwner, QueryRow, QueryValue, SyncClient, UnitScopes, WindowBase,',
500
+ ' WindowCoverage,',
497
501
  '};',
498
502
  '',
499
503
  '#[derive(Debug, Clone, PartialEq, Eq, Default)]',
@@ -1,4 +1,4 @@
1
- import { syqlInput, } from './query.js';
1
+ import { syqlInput, windowBases, } from './query.js';
2
2
  const TS_TYPE = {
3
3
  string: 'string',
4
4
  integer: 'number',
@@ -62,6 +62,20 @@ function reactiveParam(query, name) {
62
62
  throw new Error(`unknown reactive param ${name}`);
63
63
  return `String(params.${propertyKey(param.langName)})`;
64
64
  }
65
+ /** The `coverage` member's opening line and one line per window base. */
66
+ function emitCoverage(query) {
67
+ const coverage = windowBases(query.reactive.coverage);
68
+ return [
69
+ ` coverage: (${coverage.length > 0 ? 'params' : ''}) => [`,
70
+ ...coverage.map((entry) => {
71
+ const fixed = entry.fixedScopes
72
+ .map((scope) => `${propertyKey(scope.variable)}: ${reactiveParam(query, scope.param)}`)
73
+ .join(', ');
74
+ const fixedPart = fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : '';
75
+ return ` { base: { variable: ${quote(entry.variable)}${fixedPart} }, units: [${entry.units.map((param) => reactiveParam(query, param)).join(', ')}] },`;
76
+ }),
77
+ ];
78
+ }
65
79
  function syqlTsValueType(type, nullable) {
66
80
  return `${SYQL_PARAM_TS_TYPE[type]}${nullable ? ' | null' : ''}`;
67
81
  }
@@ -276,15 +290,7 @@ function emitSyqlQuery(query, hash) {
276
290
  lines.push(` { table: ${quote(dependency.table)}${keys.length > 0 ? `, scopeKeys: [${keys.join(', ')}]` : ''} },`);
277
291
  }
278
292
  lines.push(' ],');
279
- const coverageUsesParams = query.reactive.coverage.some((coverage) => coverage.units.length > 0 ||
280
- coverage.fixedScopes.some((scope) => scope.params.length > 0));
281
- lines.push(` coverage: (${coverageUsesParams ? 'params' : ''}) => [`);
282
- for (const coverage of query.reactive.coverage) {
283
- const fixed = coverage.fixedScopes
284
- .map((scope) => `${propertyKey(scope.variable)}: [${scope.params.map((param) => reactiveParam(query, param)).join(', ')}]`)
285
- .join(', ');
286
- lines.push(` { base: { table: ${quote(coverage.table)}, variable: ${quote(coverage.variable)}${fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : ''} }, units: [${coverage.units.map((param) => reactiveParam(query, param)).join(', ')}] },`);
287
- }
293
+ lines.push(...emitCoverage(query));
288
294
  lines.push(' ],', hasParams
289
295
  ? ` bind: (params: ${Params}) => ${query.name}Select(params).bind,`
290
296
  : ` bind: () => ${query.name}Select().bind,`);
@@ -365,16 +371,7 @@ function emitQuery(query, hash) {
365
371
  lines.push(` { table: ${quote(dependency.table)}${keys.length > 0 ? `, scopeKeys: [${keys.join(', ')}]` : ''} },`);
366
372
  }
367
373
  lines.push(' ],');
368
- const coverageUsesParams = query.reactive.coverage.some((coverage) => coverage.units.length > 0 ||
369
- coverage.fixedScopes.some((scope) => scope.params.length > 0));
370
- lines.push(` coverage: (${coverageUsesParams ? 'params' : ''}) => [`);
371
- for (const coverage of query.reactive.coverage) {
372
- const fixed = coverage.fixedScopes
373
- .map((scope) => `${propertyKey(scope.variable)}: [${scope.params.map((param) => reactiveParam(query, param)).join(', ')}]`)
374
- .join(', ');
375
- const fixedPart = fixed.length > 0 ? `, fixedScopes: { ${fixed} }` : '';
376
- lines.push(` { base: { table: ${quote(coverage.table)}, variable: ${quote(coverage.variable)}${fixedPart} }, units: [${coverage.units.map((param) => reactiveParam(query, param)).join(', ')}] },`);
377
- }
374
+ lines.push(...emitCoverage(query));
378
375
  lines.push(' ],');
379
376
  if (hasParams) {
380
377
  lines.push(` bind: (params: ${Params}) => ${positional},`);
@@ -498,12 +495,11 @@ export function emitQueriesModule(queries, hash, irVersion) {
498
495
  ' readonly nullable: boolean;',
499
496
  '}',
500
497
  '',
498
+ '/** A window base (SPEC §4.8) and the unit values a query reads. */',
501
499
  'export interface WindowCoverage {',
502
500
  ' readonly base: {',
503
- ' readonly table: string;',
504
501
  ' readonly variable: string;',
505
- ' readonly fixedScopes?: Readonly<Record<string, readonly string[]>>;',
506
- ' readonly params?: string;',
502
+ ' readonly fixedScopes?: Readonly<Record<string, string>>;',
507
503
  ' };',
508
504
  ' readonly units: readonly string[];',
509
505
  '}',
@@ -8,7 +8,7 @@
8
8
  * types, plus blob_ref/crdt in their honest Swift shapes) and a
9
9
  * `init?(row:)` from a `[String: JSONValue]` (the shape `query`/`readRows`
10
10
  * return),
11
- * - a `subscriptions` namespace of typed requested-scope builders.
11
+ * - a `subscriptions` namespace of typed unit-template builders (SPEC §4.1).
12
12
  *
13
13
  * The file imports only `Syncular` (for `JSONValue`). The header carries the
14
14
  * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
@@ -8,7 +8,7 @@
8
8
  * types, plus blob_ref/crdt in their honest Swift shapes) and a
9
9
  * `init?(row:)` from a `[String: JSONValue]` (the shape `query`/`readRows`
10
10
  * return),
11
- * - a `subscriptions` namespace of typed requested-scope builders.
11
+ * - a `subscriptions` namespace of typed unit-template builders (SPEC §4.1).
12
12
  *
13
13
  * The file imports only `Syncular` (for `JSONValue`). The header carries the
14
14
  * IR hash so `--check` verifies freshness byte-exactly, exactly like the TS
@@ -99,29 +99,18 @@ function emitStruct(table) {
99
99
  return lines;
100
100
  }
101
101
  function emitSubscription(sub) {
102
- const params = [];
103
- for (const scope of sub.scopes) {
104
- for (const value of scope.values) {
105
- if (value.kind === 'parameter' && !params.includes(value.name)) {
106
- params.push(value.name);
107
- }
108
- }
109
- }
102
+ const params = [
103
+ ...new Set(sub.scopes.flatMap(({ value }) => value.kind === 'parameter' ? [value.name] : [])),
104
+ ];
110
105
  const lines = [];
111
- lines.push(` /// Requested-scope template for the ${stringLiteral(sub.name, 'swift')} subscription.`);
106
+ lines.push(` /// Unit template for the ${stringLiteral(sub.name, 'swift')} subscription (SPEC §4.1).`);
112
107
  lines.push(` public enum ${pascalCase(sub.name)} {`);
113
108
  lines.push(` public static let name = ${stringLiteral(sub.name, 'swift')}`);
114
- lines.push(` public static let table = ${stringLiteral(sub.table, 'swift')}`);
115
109
  const args = params.map((p) => `${snakeToCamel(p)}: String`).join(', ');
116
- lines.push(` public static func scopes(${args}) -> [String: [String]] {`);
110
+ lines.push(` public static func scopes(${args}) -> [String: String] {`);
117
111
  lines.push(' [');
118
- for (const scope of sub.scopes) {
119
- const values = scope.values
120
- .map((value) => value.kind === 'literal'
121
- ? stringLiteral(value.value, 'swift')
122
- : snakeToCamel(value.name))
123
- .join(', ');
124
- lines.push(` ${stringLiteral(scope.variable, 'swift')}: [${values}],`);
112
+ for (const { variable, value } of sub.scopes) {
113
+ lines.push(` ${stringLiteral(variable, 'swift')}: ${value.kind === 'literal' ? stringLiteral(value.value, 'swift') : snakeToCamel(value.name)},`);
125
114
  }
126
115
  lines.push(' ]');
127
116
  lines.push(' }');
@@ -154,7 +143,7 @@ export function emitSwiftModule(ir, hash, enumName) {
154
143
  schemaLines.push(' """)');
155
144
  schemaLines.push('');
156
145
  // Subscriptions namespace nested in the schema enum.
157
- schemaLines.push(' /// Typed requested-scope builders per subscription.');
146
+ schemaLines.push(' /// Typed unit-template builders per subscription (SPEC §4.1).');
158
147
  schemaLines.push(' public enum subscriptions {');
159
148
  if (ir.subscriptions.length === 0) {
160
149
  schemaLines.push(' // (no subscriptions declared)');
package/dist/emit.d.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  * - a `<Table>Row` interface per table,
7
7
  * - `<Table>Insert` / `<Table>Update` mutation-input shapes honoring
8
8
  * nullability,
9
- * - a `<name>Subscription` helper constant per manifest subscription with
10
- * a typed requested-scopes builder.
9
+ * - a `<name>Subscription` helper constant per manifest unit template with
10
+ * a typed builder of its unit scope map (SPEC §4.1).
11
11
  *
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
package/dist/emit.js CHANGED
@@ -6,8 +6,8 @@
6
6
  * - a `<Table>Row` interface per table,
7
7
  * - `<Table>Insert` / `<Table>Update` mutation-input shapes honoring
8
8
  * nullability,
9
- * - a `<name>Subscription` helper constant per manifest subscription with
10
- * a typed requested-scopes builder.
9
+ * - a `<name>Subscription` helper constant per manifest unit template with
10
+ * a typed builder of its unit scope map (SPEC §4.1).
11
11
  *
12
12
  * The header carries the IR hash so `--check` verifies freshness
13
13
  * byte-exactly.
@@ -88,14 +88,9 @@ function emitTableDescriptor(table, naming) {
88
88
  ].join('\n');
89
89
  }
90
90
  function emitSubscription(sub) {
91
- const params = [];
92
- for (const scope of sub.scopes) {
93
- for (const value of scope.values) {
94
- if (value.kind === 'parameter' && !params.includes(value.name)) {
95
- params.push(value.name);
96
- }
97
- }
98
- }
91
+ const params = [
92
+ ...new Set(sub.scopes.flatMap(({ value }) => value.kind === 'parameter' ? [value.name] : [])),
93
+ ];
99
94
  const lines = [];
100
95
  const paramsType = `${pascalCase(sub.name)}Params`;
101
96
  if (params.length > 0) {
@@ -106,19 +101,13 @@ function emitSubscription(sub) {
106
101
  lines.push('}');
107
102
  lines.push('');
108
103
  }
109
- lines.push(`/** Requested-scope template for the ${stringLiteral(sub.name, 'ts')} subscription. */`);
104
+ lines.push(`/** Unit template for the ${stringLiteral(sub.name, 'ts')} subscription (SPEC §4.1). */`);
110
105
  lines.push(`export const ${sub.name}Subscription = {`);
111
106
  lines.push(` name: ${stringLiteral(sub.name, 'ts')},`);
112
- lines.push(` table: ${stringLiteral(sub.table, 'ts')},`);
113
107
  const args = params.length > 0 ? `params: ${paramsType}` : '';
114
- lines.push(` scopes: (${args}): Record<string, string[]> => ({`);
115
- for (const scope of sub.scopes) {
116
- const values = scope.values
117
- .map((value) => value.kind === 'literal'
118
- ? stringLiteral(value.value, 'ts')
119
- : `params.${propertyKey(value.name)}`)
120
- .join(', ');
121
- lines.push(` ${propertyKey(scope.variable)}: [${values}],`);
108
+ lines.push(` scopes: (${args}): Record<string, string> => ({`);
109
+ for (const { variable, value } of sub.scopes) {
110
+ lines.push(` ${propertyKey(variable)}: ${value.kind === 'literal' ? stringLiteral(value.value, 'ts') : `params.${propertyKey(value.name)}`},`);
122
111
  }
123
112
  lines.push(' }),');
124
113
  lines.push('} as const;');
package/dist/fmt.js CHANGED
@@ -217,6 +217,7 @@ function formatTokens(parsed) {
217
217
  let importList = false;
218
218
  let justClosedImportList = false;
219
219
  let seenTopLevel = false;
220
+ let acknowledging = false;
220
221
  let pendingBetween = 0;
221
222
  let inlineParameterRecord = false;
222
223
  let justClosedInlineParameterRecord = false;
@@ -231,11 +232,19 @@ function formatTokens(parsed) {
231
232
  (lower === 'import' ||
232
233
  lower === 'predicate' ||
233
234
  lower === 'query' ||
234
- lower === 'sync') &&
235
+ lower === 'sync' ||
236
+ (lower === 'allow' &&
237
+ (previous === undefined ||
238
+ previous.kind === 'string' ||
239
+ previous.text === '}'))) &&
235
240
  !(lower === 'query' && previous?.text === 'sync');
236
241
  if (topLevelDeclaration) {
237
- if (seenTopLevel)
242
+ // Acknowledgements sit on their own lines directly above their query.
243
+ if (acknowledging)
244
+ writer.newline();
245
+ else if (seenTopLevel)
238
246
  writer.blankline();
247
+ acknowledging = lower === 'allow';
239
248
  seenTopLevel = true;
240
249
  previous = undefined;
241
250
  awaitsDeclarationParameters = lower === 'predicate' || lower === 'query';
package/dist/generate.js CHANGED
@@ -19,7 +19,7 @@ import { canonicalizeExtensions, IR_VERSION, irHash, serializeIr, } from './ir.j
19
19
  import { MANIFEST_FILENAME, parseManifest, } from './manifest.js';
20
20
  import { buildMigrationLock, buildSchemaVersions, lockedMigrationNames, MIGRATION_LOCK_FILENAME, MIGRATION_LOCK_FORMAT_VERSION, readMigrationLock, serializeMigrationLock, updateMigrationLock, upgradeMigrationLock, } from './migration-lock.js';
21
21
  import { validateSchemaIdentifiers } from './naming.js';
22
- import { analyzeQueryFile, synthesizeDdl, } from './query.js';
22
+ import { analyzeQueryFile, checkQueryPlan, synthesizeDdl, } from './query.js';
23
23
  import { serializeQueryIr } from './query-ir.js';
24
24
  import { applyMigrationSql, validateFinalSchemaIdentifiers, } from './sql.js';
25
25
  import { lowerSyqlQuery } from './syql-lowering.js';
@@ -163,33 +163,22 @@ function validateReferences(tables, parsedTables) {
163
163
  }
164
164
  }
165
165
  function buildSubscription(sub, tables) {
166
- const table = tables.find((t) => t.name === sub.table);
167
- if (table === undefined) {
168
- throw new TypegenError(MANIFEST_FILENAME, `subscription ${sub.name}: unknown table ${JSON.stringify(sub.table)}`);
166
+ const variables = Object.keys(sub.scopes).sort();
167
+ if (!tables.some((table) => variables.every((variable) => table.scopes.some((scope) => scope.variable === variable)))) {
168
+ throw new TypegenError(MANIFEST_FILENAME, 'a unit template covers no table: no table declares all of its scope variables (SPEC §4.1)', 'typegen.subscription_uncovered', { subscription: sub.name, variables });
169
169
  }
170
- const declared = new Set(table.scopes.map((s) => s.variable));
171
- const scopes = Object.entries(sub.scopes)
172
- .map(([variable, values]) => {
173
- if (!declared.has(variable)) {
174
- throw new TypegenError(MANIFEST_FILENAME, `subscription ${sub.name}: ${JSON.stringify(variable)} is not a scope variable of table ${sub.table} (declared: ${[...declared].join(', ')})`);
170
+ const scopes = variables.map((variable) => {
171
+ const value = sub.scopes[variable];
172
+ const param = PARAM_RE.exec(value);
173
+ if (param?.[1] !== undefined) {
174
+ return { variable, value: { kind: 'parameter', name: param[1] } };
175
175
  }
176
- const irValues = values.map((value) => {
177
- const param = PARAM_RE.exec(value);
178
- if (param?.[1] !== undefined) {
179
- return { kind: 'parameter', name: param[1] };
180
- }
181
- if (value.includes('{') || value.includes('}')) {
182
- throw new TypegenError(MANIFEST_FILENAME, `subscription ${sub.name}: scope value ${JSON.stringify(value)} mixes literals and placeholders — a value is either a literal or exactly '{param}'`);
183
- }
184
- if (value === '*') {
185
- throw new TypegenError(MANIFEST_FILENAME, `subscription ${sub.name}: '*' is rejected in requested scopes (§3.2)`);
186
- }
187
- return { kind: 'literal', value };
188
- });
189
- return { variable, values: irValues };
190
- })
191
- .sort((a, b) => (a.variable < b.variable ? -1 : 1));
192
- return { name: sub.name, table: sub.table, scopes };
176
+ if (value.includes('{') || value.includes('}') || value === '*') {
177
+ throw new TypegenError(MANIFEST_FILENAME, "a unit template value is a literal other than '*' (§3.2) or exactly '{param}'", 'typegen.subscription_invalid_value', { subscription: sub.name, variable, value });
178
+ }
179
+ return { variable, value: { kind: 'literal', value } };
180
+ });
181
+ return { name: sub.name, scopes };
193
182
  }
194
183
  /** Pure IR construction — the testable heart of the generator. Migrations
195
184
  * named in `lockedNames` replay as immutable deployed history: rules that
@@ -320,6 +309,20 @@ export function makeQueryDb(ir) {
320
309
  stmt.finalize();
321
310
  }
322
311
  },
312
+ plan(sql, index) {
313
+ if (index !== undefined)
314
+ sqlite.run(`SAVEPOINT plan_probe; ${index}`);
315
+ try {
316
+ return sqlite
317
+ .query(`EXPLAIN QUERY PLAN ${sql}`)
318
+ .all();
319
+ }
320
+ finally {
321
+ if (index !== undefined) {
322
+ sqlite.run('ROLLBACK TO plan_probe; RELEASE plan_probe');
323
+ }
324
+ }
325
+ },
323
326
  };
324
327
  return { db, close: () => sqlite.close() };
325
328
  }
@@ -362,6 +365,8 @@ export function analyzeQueries(ir, queries, naming, queriesRoot = resolve('/__sy
362
365
  }
363
366
  seen.set(q.name, q.file);
364
367
  }
368
+ for (const query of analyzed)
369
+ checkQueryPlan(query, ir, db);
365
370
  return analyzed;
366
371
  }
367
372
  finally {
package/dist/init.js CHANGED
@@ -22,11 +22,7 @@ const STARTER_MANIFEST = `{
22
22
  "schemaVersions": [{ "version": 1, "through": "0001_initial" }],
23
23
  "tables": [{ "name": "notes", "scopes": ["list:{list_id}"] }],
24
24
  "subscriptions": [
25
- {
26
- "name": "notesInList",
27
- "table": "notes",
28
- "scopes": { "list_id": ["{listId}"] }
29
- }
25
+ { "name": "notesInList", "scopes": { "list_id": "{listId}" } }
30
26
  ]
31
27
  }
32
28
  `;
@@ -38,6 +34,9 @@ CREATE TABLE notes (
38
34
  body TEXT NOT NULL,
39
35
  updated_at_ms INTEGER NOT NULL
40
36
  );
37
+
38
+ -- The starter query reads one list; this index lets SQLite search it.
39
+ CREATE INDEX idx_notes_list ON notes (list_id);
41
40
  `;
42
41
  // A starter NAMED query (the typed .sql read tier). typegen type-checks it
43
42
  // against the schema via SQLite and emits a typed \`notesInList(client, listId)\`