@sequenceholdings/orm 2.0.0 → 2.1.1

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 (69) hide show
  1. package/README.md +94 -2
  2. package/dist/authoring.cjs +1474 -54
  3. package/dist/authoring.cjs.map +1 -1
  4. package/dist/authoring.d.cts +242 -4
  5. package/dist/authoring.d.ts +242 -4
  6. package/dist/authoring.js +1465 -56
  7. package/dist/authoring.js.map +1 -1
  8. package/dist/canonical.cjs +740 -42
  9. package/dist/canonical.cjs.map +1 -1
  10. package/dist/canonical.d.cts +742 -53
  11. package/dist/canonical.d.ts +742 -53
  12. package/dist/canonical.js +724 -43
  13. package/dist/canonical.js.map +1 -1
  14. package/dist/cli.cjs +2478 -328
  15. package/dist/cli.cjs.map +1 -1
  16. package/dist/cli.js +2480 -330
  17. package/dist/cli.js.map +1 -1
  18. package/dist/client.cjs +90 -25
  19. package/dist/client.cjs.map +1 -1
  20. package/dist/client.d.cts +39 -22
  21. package/dist/client.d.ts +39 -22
  22. package/dist/client.js +87 -26
  23. package/dist/client.js.map +1 -1
  24. package/dist/compiler.cjs +1755 -329
  25. package/dist/compiler.cjs.map +1 -1
  26. package/dist/compiler.d.cts +56 -3
  27. package/dist/compiler.d.ts +56 -3
  28. package/dist/compiler.js +1756 -330
  29. package/dist/compiler.js.map +1 -1
  30. package/dist/constants-YoFGjIBM.d.cts +99 -0
  31. package/dist/constants-YoFGjIBM.d.ts +99 -0
  32. package/dist/dynamic-input.d.cts +1 -0
  33. package/dist/dynamic-input.d.ts +1 -0
  34. package/dist/index.cjs +1973 -164
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +474 -100
  37. package/dist/index.d.ts +474 -100
  38. package/dist/index.js +1940 -167
  39. package/dist/index.js.map +1 -1
  40. package/dist/ir.cjs +869 -46
  41. package/dist/ir.cjs.map +1 -1
  42. package/dist/ir.d.cts +699 -25
  43. package/dist/ir.d.ts +699 -25
  44. package/dist/ir.js +861 -47
  45. package/dist/ir.js.map +1 -1
  46. package/dist/{naming-CTvWSRTf.d.ts → naming-CPfx7EfF.d.ts} +28 -1
  47. package/dist/{naming-DRyinU4u.d.cts → naming-CU9ThP_E.d.cts} +28 -1
  48. package/dist/policy-1iZbGnZZ.d.cts +24 -0
  49. package/dist/policy-1iZbGnZZ.d.ts +24 -0
  50. package/dist/predicate-v2.cjs +852 -49
  51. package/dist/predicate-v2.cjs.map +1 -1
  52. package/dist/predicate-v2.d.cts +2 -1
  53. package/dist/predicate-v2.d.ts +2 -1
  54. package/dist/predicate-v2.js +852 -49
  55. package/dist/predicate-v2.js.map +1 -1
  56. package/dist/sdl.cjs +1309 -58
  57. package/dist/sdl.cjs.map +1 -1
  58. package/dist/sdl.d.cts +7 -3
  59. package/dist/sdl.d.ts +7 -3
  60. package/dist/sdl.js +1305 -59
  61. package/dist/sdl.js.map +1 -1
  62. package/package.json +11 -6
  63. package/templates/orm-namespace/CLAUDE.md +6 -4
  64. package/templates/orm-namespace/codegen.preset.d.cts +7 -0
  65. package/templates/orm-namespace/codegen.ts +2 -1
  66. package/templates/orm-namespace/graphql/example/queries.ts +4 -3
  67. package/templates/orm-namespace/package.json +2 -1
  68. package/templates/orm-namespace/schema/tables.ts +3 -2
  69. package/templates/orm-namespace/sequence.config.ts +7 -11
package/dist/ir.js CHANGED
@@ -1,9 +1,480 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  // src/ir/index.ts
4
+ var quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
5
+ var quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
6
+
7
+ // src/checks/compile.ts
8
+ function tokenize(source) {
9
+ const tokens = [];
10
+ for (let position = 0; position < source.length; ) {
11
+ const char = source[position];
12
+ if (/\s/.test(char)) {
13
+ position++;
14
+ continue;
15
+ }
16
+ if (char === "(" || char === ")" || char === ",") {
17
+ tokens.push({ kind: char === "(" ? "lparen" : char === ")" ? "rparen" : "comma", value: char, position });
18
+ position++;
19
+ continue;
20
+ }
21
+ if (char === "'") {
22
+ const start = position++;
23
+ let value = "";
24
+ let closed = false;
25
+ while (position < source.length) {
26
+ if (source[position] !== "'") {
27
+ value += source[position++];
28
+ continue;
29
+ }
30
+ if (source[position + 1] === "'") {
31
+ value += "'";
32
+ position += 2;
33
+ continue;
34
+ }
35
+ position++;
36
+ closed = true;
37
+ break;
38
+ }
39
+ if (!closed) throw new Error(`unterminated string at position ${start}`);
40
+ if (/[\x00-\x1f\x7f]/.test(value)) throw new Error(`control character in string at position ${start}`);
41
+ tokens.push({ kind: "string", value, position: start });
42
+ continue;
43
+ }
44
+ const operator = /^(<=|>=|<>|!=|!~|=|<|>|~)/.exec(source.slice(position));
45
+ if (operator) {
46
+ tokens.push({ kind: "operator", value: operator[0] === "<>" ? "!=" : operator[0], position });
47
+ position += operator[0].length;
48
+ continue;
49
+ }
50
+ const number = /^-?\d+(?:\.\d+)?/.exec(source.slice(position));
51
+ if (number) {
52
+ tokens.push({ kind: "number", value: number[0], position });
53
+ position += number[0].length;
54
+ continue;
55
+ }
56
+ const identifier3 = /^[a-zA-Z_][a-zA-Z_0-9]*/.exec(source.slice(position));
57
+ if (identifier3) {
58
+ tokens.push({ kind: "identifier", value: identifier3[0], position });
59
+ position += identifier3[0].length;
60
+ continue;
61
+ }
62
+ throw new Error(`unexpected character '${char}' at position ${position}`);
63
+ }
64
+ tokens.push({ kind: "end", value: "", position: source.length });
65
+ if (tokens.length > 256) throw new Error("check expression exceeds 256 tokens");
66
+ return tokens;
67
+ }
68
+ var Parser = class {
69
+ constructor(tokens, columns) {
70
+ this.tokens = tokens;
71
+ this.columns = /* @__PURE__ */ new Map();
72
+ for (const column of columns) {
73
+ for (const alias of [column.name, column.columnName]) {
74
+ const previous = this.columns.get(alias);
75
+ if (previous && previous.columnName !== column.columnName) {
76
+ throw new Error(`ambiguous check column '${alias}'`);
77
+ }
78
+ this.columns.set(alias, column);
79
+ }
80
+ }
81
+ }
82
+ index = 0;
83
+ depth = 0;
84
+ columns;
85
+ parse() {
86
+ const expression = this.parseOr();
87
+ this.expect("end", "end of expression");
88
+ return expression;
89
+ }
90
+ parseOr() {
91
+ let left = this.parseAnd();
92
+ while (this.matchKeyword("or")) left = `(${left} OR ${this.parseAnd()})`;
93
+ return left;
94
+ }
95
+ parseAnd() {
96
+ let left = this.parseNot();
97
+ while (this.matchKeyword("and")) left = `(${left} AND ${this.parseNot()})`;
98
+ return left;
99
+ }
100
+ parseNot() {
101
+ if (this.matchKeyword("not")) return `(NOT ${this.parseNot()})`;
102
+ return this.parsePrimary();
103
+ }
104
+ parsePrimary() {
105
+ if (this.peek().kind === "lparen") {
106
+ if (++this.depth > 32) throw new Error("check expression nesting exceeds 32 levels");
107
+ this.advance();
108
+ const expression = this.parseOr();
109
+ this.expect("rparen", "')'");
110
+ this.depth--;
111
+ return `(${expression})`;
112
+ }
113
+ return this.parseComparison();
114
+ }
115
+ parseComparison() {
116
+ const left = this.parseValue();
117
+ if (this.matchKeyword("is")) {
118
+ const negate = this.matchKeyword("not");
119
+ this.expectKeyword("null");
120
+ return `${left.sql} IS ${negate ? "NOT " : ""}NULL`;
121
+ }
122
+ if (this.matchKeyword("between")) {
123
+ const lower = this.parseValue();
124
+ this.expectKeyword("and");
125
+ const upper = this.parseValue();
126
+ return `${left.sql} BETWEEN ${lower.sql} AND ${upper.sql}`;
127
+ }
128
+ if (this.matchKeyword("in")) {
129
+ this.expect("lparen", "'(' after IN");
130
+ const values = [this.parseValue()];
131
+ while (this.peek().kind === "comma") {
132
+ this.advance();
133
+ values.push(this.parseValue());
134
+ }
135
+ this.expect("rparen", "')' after IN values");
136
+ if (values.some((value) => !value.literal)) throw new Error("IN values must be literals");
137
+ return `${left.sql} IN (${values.map((value) => value.sql).join(", ")})`;
138
+ }
139
+ const operator = this.expect("operator", "a comparison operator");
140
+ const right = this.parseValue();
141
+ if (operator.value === "~" || operator.value === "!~") {
142
+ if (left.column && left.column.type !== "text") throw new Error("regex checks require a text column");
143
+ if (!right.literal) throw new Error("regex pattern must be a literal");
144
+ }
145
+ return `${left.sql} ${operator.value} ${right.sql}`;
146
+ }
147
+ parseValue() {
148
+ const token = this.advance();
149
+ if (token.kind === "string") return { sql: quoteLiteral(token.value), literal: true };
150
+ if (token.kind === "number") {
151
+ const number = Number(token.value);
152
+ if (!Number.isFinite(number) || Number.isInteger(number) && !Number.isSafeInteger(number)) {
153
+ throw new Error(`unsafe numeric literal at position ${token.position}`);
154
+ }
155
+ return { sql: token.value, literal: true };
156
+ }
157
+ if (token.kind !== "identifier") throw new Error(`expected a column or literal at position ${token.position}`);
158
+ const keyword = token.value.toLowerCase();
159
+ if (keyword === "true" || keyword === "false" || keyword === "null") return { sql: keyword.toUpperCase(), literal: true };
160
+ if (keyword === "btrim") {
161
+ this.expect("lparen", "'(' after btrim");
162
+ const column2 = this.parseColumn();
163
+ this.expect("rparen", "')' after btrim column");
164
+ if (column2.type !== "text") throw new Error("btrim requires a text column");
165
+ return { sql: `btrim(${quoteIdentifier(column2.columnName)})`, column: column2 };
166
+ }
167
+ const column = this.columns.get(token.value);
168
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
169
+ return { sql: quoteIdentifier(column.columnName), column };
170
+ }
171
+ parseColumn() {
172
+ const token = this.expect("identifier", "a column name");
173
+ const column = this.columns.get(token.value);
174
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
175
+ return column;
176
+ }
177
+ peek() {
178
+ return this.tokens[this.index];
179
+ }
180
+ advance() {
181
+ const token = this.peek();
182
+ if (token.kind !== "end") this.index++;
183
+ return token;
184
+ }
185
+ matchKeyword(keyword) {
186
+ if (this.peek().kind !== "identifier" || this.peek().value.toLowerCase() !== keyword) return false;
187
+ this.advance();
188
+ return true;
189
+ }
190
+ expectKeyword(keyword) {
191
+ if (!this.matchKeyword(keyword)) throw new Error(`expected '${keyword}' at position ${this.peek().position}`);
192
+ }
193
+ expect(kind, description) {
194
+ const token = this.peek();
195
+ if (token.kind !== kind) throw new Error(`expected ${description} at position ${token.position}`);
196
+ return this.advance();
197
+ }
198
+ };
199
+ function compileCheckExpression(source, columns) {
200
+ return new Parser(tokenize(source), columns).parse();
201
+ }
202
+
203
+ // src/constants.ts
204
+ var COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/;
205
+ var MAX_IDENTIFIER_LENGTH = 63;
206
+ var CELL_PARTS = ["at", "by", "rev", "source", "conflicts"];
207
+ var CELL_PART_SUFFIX = {
208
+ at: "__at",
209
+ by: "__by",
210
+ rev: "__rev",
211
+ source: "__src",
212
+ conflicts: "__lost"
213
+ };
214
+ var MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6;
215
+ var CELLS_FIELD = "cells";
216
+ function cellColumnName(column, part) {
217
+ return `${column}${CELL_PART_SUFFIX[part]}`;
218
+ }
219
+ var MATERIALIZE_ACTOR = "orm:materialize";
220
+ JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] });
221
+ var policyVariantSchema = z.object({
222
+ /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
223
+ when: z.string().min(1).max(1e3),
224
+ /** Exactly one of: allow-all bypass, or a row predicate. */
225
+ allow: z.literal(true).optional(),
226
+ policy: z.string().min(1).max(2e3).optional()
227
+ }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
228
+ message: "A variant declares exactly one of allow: true or policy"
229
+ });
230
+ var policyExpressionSchema = z.union([
231
+ z.string().min(1).max(2e3),
232
+ z.object({
233
+ default: z.string().min(1).max(2e3),
234
+ variants: z.array(policyVariantSchema).max(10).default([])
235
+ })
236
+ ]);
237
+ var identifier = z.string().min(1).max(63).regex(/^[a-z][a-z0-9_]*$/);
238
+ var durationMs = z.number().int().positive().max(24 * 60 * 60 * 1e3);
239
+ var RESOLVED_VIEW_SYSTEM_COLUMNS = {
240
+ writebackStatus: { name: "writebackStatus", columnName: "_writeback_status", type: "text" },
241
+ writebackError: { name: "writebackError", columnName: "_writeback_error", type: "text" }
242
+ };
243
+ var RESOLVED_SOURCE_SYSTEM_COLUMNS = {
244
+ tombstoned: { name: "sysTombstoned", columnName: "_tombstoned" },
245
+ fetchedAt: { name: "sysFetchedAt", columnName: "_fetched_at" },
246
+ writebackStatus: { name: "sysWritebackStatus", columnName: "_writeback_status" },
247
+ writebackError: { name: "sysWritebackError", columnName: "_writeback_error" },
248
+ writebackAt: { name: "sysWritebackAt", columnName: "_writeback_at" }
249
+ };
250
+ var RESOLVED_VIEW_CELL_PARTS = ["source", "at", "by", "conflicts"];
251
+ /* @__PURE__ */ new Set([
252
+ ...Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName]),
253
+ ...Object.values(RESOLVED_SOURCE_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName])
254
+ ]);
255
+ var COMPARATORS = ["latest", "highest", "lowest", "priority", "nonNullFirst", "custom"];
256
+ var canonicalFunctionRefSchema = z.object({
257
+ /** `managed` = a Managed Function id/slug; `native` = an in-process Atlas function (reserved). */
258
+ kind: z.enum(["managed", "native"]),
259
+ id: z.string().min(1).max(200)
260
+ }).strict();
261
+ var canonicalFetchShapeSchema = z.union([
262
+ z.object({ shape: z.literal("single") }).strict(),
263
+ z.object({ shape: z.literal("batch"), maxKeys: z.number().int().min(2).max(500) }).strict()
264
+ ]);
265
+ var canonicalResolvedSourceSchema = z.object({
266
+ name: identifier,
267
+ kind: z.enum(["manual", "etl", "prefetch"]),
268
+ /** Backing relation in this namespace: an internal table (manual/prefetch) or a synced table (etl). */
269
+ table: identifier,
270
+ /** Resolved columns (logical names) this source supplies — the primary key is implicit. */
271
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
272
+ /** etl: logical timestamptz/date column on the synced table used as every cell's updated_at. */
273
+ updatedAt: z.string().min(1).max(63).optional(),
274
+ /** prefetch: resolved column holding the source system's key (may be the primary key). */
275
+ key: z.string().min(1).max(63).optional(),
276
+ fetch: canonicalFetchShapeSchema.optional(),
277
+ function: canonicalFunctionRefSchema.optional(),
278
+ prefetchDefaults: z.object({
279
+ maxStalenessMs: durationMs,
280
+ timeoutMs: durationMs,
281
+ onError: z.enum(["fallback", "fail"])
282
+ }).strict().optional(),
283
+ writeback: z.object({
284
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
285
+ defaultMode: z.enum(["sync", "async"]),
286
+ timeoutMs: durationMs,
287
+ /** Remove confirmed cells from the manual source so a stale edit cannot shadow the source. */
288
+ clearManualOnConfirm: z.boolean()
289
+ }).strict().optional()
290
+ }).strict();
291
+ var canonicalResolveRuleSchema = z.object({
292
+ column: z.string().min(1).max(63),
293
+ comparator: z.enum(COMPARATORS),
294
+ /** Source names, in tie-break order. */
295
+ candidates: z.array(identifier).min(1).max(16),
296
+ /** custom only: SQL ORDER BY key over value / updated_at / source / actor / ord. */
297
+ orderBy: z.string().min(1).max(2e3).optional()
298
+ }).strict();
299
+ var canonicalResolvedSchema = z.object({
300
+ sources: z.array(canonicalResolvedSourceSchema).min(1).max(16),
301
+ /** One rule per resolved (non-pk) column; documents the generated view for tooling. */
302
+ resolve: z.array(canonicalResolveRuleSchema).max(500),
303
+ /** Sources whose tombstone hides the resolved row (v1: the manual source only). */
304
+ deletedBy: z.array(identifier).max(1).default([]),
305
+ /**
306
+ * Materialized: the view reads an indexed internal table (`table`) that the
307
+ * data plane keeps in step with `compute`, the internal view holding the
308
+ * resolution query. Omitted when the view computes on read.
309
+ */
310
+ materialized: z.object({ table: identifier, compute: identifier }).strict().optional(),
311
+ /** Write policies evaluated against the RESOLVED row (reads use the view's read policy). */
312
+ policies: z.object({
313
+ write: policyExpressionSchema.optional(),
314
+ insert: policyExpressionSchema.optional(),
315
+ update: policyExpressionSchema.optional()
316
+ }).strict().default({})
317
+ }).strict();
318
+ function validateResolvedView({ view, tables, views = [] }) {
319
+ const resolved = view.resolved;
320
+ if (!resolved) return [];
321
+ const errors = [];
322
+ const fail = (message) => errors.push(`resolved table '${view.view}': ${message}`);
323
+ const pkColumn = view.primaryKey?.length === 1 ? view.columns.find((c) => c.columnName === view.primaryKey?.[0]) : void 0;
324
+ if (!pkColumn) {
325
+ fail("requires exactly one primary-key column");
326
+ return errors;
327
+ }
328
+ const systemNames = new Set(Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).map((c) => c.name));
329
+ const scope = {
330
+ view,
331
+ resolved,
332
+ pkColumn,
333
+ dataColumns: new Map(view.columns.filter((c) => !systemNames.has(c.name) && c.cell === void 0).map((c) => [c.name, c])),
334
+ sourceByName: /* @__PURE__ */ new Map(),
335
+ fail
336
+ };
337
+ if (resolved.sources.filter((source) => source.kind === "manual").length !== 1) fail("requires exactly one manual source");
338
+ const tableByName = new Map(tables.map((table) => [table.table, table]));
339
+ for (const source of resolved.sources) {
340
+ if (scope.sourceByName.has(source.name)) fail(`duplicate source '${source.name}'`);
341
+ scope.sourceByName.set(source.name, source);
342
+ const table = tableByName.get(source.table);
343
+ if (!table) fail(`source '${source.name}' references unknown table '${source.table}'`);
344
+ else validateSource({ scope, source, table });
345
+ }
346
+ validateRules(scope);
347
+ validateViewCells(scope);
348
+ if (resolved.materialized) validateMaterialized({ scope, tableByName, views });
349
+ for (const name of resolved.deletedBy) {
350
+ if (scope.sourceByName.get(name)?.kind !== "manual") fail(`deletedBy '${name}' must be the manual source`);
351
+ }
352
+ return errors;
353
+ }
354
+ function validateSource({ scope, source, table }) {
355
+ const { fail } = scope;
356
+ if (source.kind === "etl" && table.source === void 0) fail(`etl source '${source.name}' must reference a synced table`);
357
+ if (source.kind !== "etl" && (table.internal !== true || table.cellMetadata !== true)) {
358
+ fail(`${source.kind} source '${source.name}' must reference an internal table with cell metadata`);
359
+ }
360
+ const hasRev = table.columns.some((column) => column.cell?.part === "rev");
361
+ if (source.kind === "manual" && !hasRev) fail(`manual source '${source.name}' must carry '__rev' cell columns`);
362
+ if (source.kind === "prefetch" && hasRev) fail(`prefetch source '${source.name}' must not carry '__rev' cell columns`);
363
+ const byName = new Map(table.columns.map((c) => [c.name, c]));
364
+ validateSourceColumns({ scope, source, byName });
365
+ if (source.kind === "etl") {
366
+ const updatedAt = source.updatedAt === void 0 ? void 0 : byName.get(source.updatedAt);
367
+ if (source.updatedAt !== void 0 && updatedAt?.type !== "timestamptz" && updatedAt?.type !== "date") {
368
+ fail(`etl source '${source.name}' updatedAt must name a timestamptz/date column on '${source.table}'`);
369
+ }
370
+ }
371
+ validatePrefetchFields({ scope, source });
372
+ }
373
+ function validatePrefetchFields({ scope, source }) {
374
+ const { fail, pkColumn } = scope;
375
+ if (source.kind !== "prefetch") {
376
+ if (source.key || source.fetch || source.function || source.prefetchDefaults || source.writeback) {
377
+ fail(`only prefetch sources may declare key/fetch/function/prefetchDefaults/writeback ('${source.name}')`);
378
+ }
379
+ return;
380
+ }
381
+ if (!source.key || !source.fetch || !source.function || !source.prefetchDefaults) {
382
+ fail(`prefetch source '${source.name}' requires key, fetch, function and prefetchDefaults`);
383
+ } else if (source.key !== pkColumn.name && !source.columns.includes(source.key)) {
384
+ fail(`prefetch source '${source.name}' key '${source.key}' must be the primary key or one of its columns`);
385
+ }
386
+ for (const column of source.writeback?.columns ?? []) {
387
+ if (!source.columns.includes(column)) fail(`prefetch source '${source.name}' writes back '${column}', which it does not supply`);
388
+ }
389
+ }
390
+ function validateSourceColumns({ scope, source, byName }) {
391
+ const { fail, pkColumn, dataColumns } = scope;
392
+ for (const column of [pkColumn.name, ...source.columns]) {
393
+ const own = column === pkColumn.name ? pkColumn : dataColumns.get(column);
394
+ const theirs = byName.get(column);
395
+ if (!own) fail(`source '${source.name}' supplies unknown column '${column}'`);
396
+ else if (!theirs) fail(`source '${source.name}' table '${source.table}' has no column '${column}'`);
397
+ else if (JSON.stringify(theirs.type) !== JSON.stringify(own.type)) fail(`column '${column}' has a different type on source '${source.name}'`);
398
+ }
399
+ }
400
+ function validateRules({ resolved, pkColumn, dataColumns, sourceByName, fail }) {
401
+ const ruled = /* @__PURE__ */ new Set();
402
+ for (const rule of resolved.resolve) {
403
+ if (!dataColumns.has(rule.column) || rule.column === pkColumn.name) {
404
+ fail(`resolve rule targets unknown column '${rule.column}'`);
405
+ continue;
406
+ }
407
+ if (ruled.has(rule.column)) fail(`column '${rule.column}' has more than one resolve rule`);
408
+ ruled.add(rule.column);
409
+ if (rule.comparator === "custom" !== (rule.orderBy !== void 0)) {
410
+ fail(`column '${rule.column}': orderBy is required for custom comparators and only allowed there`);
411
+ }
412
+ if (new Set(rule.candidates).size !== rule.candidates.length) fail(`column '${rule.column}' repeats a candidate`);
413
+ for (const candidate of rule.candidates) {
414
+ const source = sourceByName.get(candidate);
415
+ if (!source) fail(`column '${rule.column}' names unknown candidate source '${candidate}'`);
416
+ else if (!source.columns.includes(rule.column)) fail(`column '${rule.column}' candidate '${candidate}' does not supply it`);
417
+ }
418
+ }
419
+ for (const column of dataColumns.keys()) {
420
+ if (column !== pkColumn.name && !ruled.has(column)) fail(`column '${column}' has no resolve rule`);
421
+ }
422
+ }
423
+ var VIEW_CELL_TYPES = {
424
+ source: "text",
425
+ at: "timestamptz",
426
+ by: "text",
427
+ conflicts: "jsonb"
428
+ };
429
+ function validateViewCells({ view, dataColumns, pkColumn, fail }) {
430
+ const expected = /* @__PURE__ */ new Map();
431
+ for (const column of dataColumns.values()) {
432
+ if (column.name === pkColumn.name) continue;
433
+ for (const part of RESOLVED_VIEW_CELL_PARTS) {
434
+ expected.set(cellColumnName(column.name, part), { part, columnName: cellColumnName(column.columnName, part) });
435
+ }
436
+ }
437
+ for (const column of view.columns) {
438
+ if (!column.cell) continue;
439
+ const want = expected.get(column.name);
440
+ if (!want || want.part !== column.cell.part || want.columnName !== column.columnName || cellColumnName(column.cell.of, column.cell.part) !== column.name) {
441
+ fail(`unexpected cell column '${column.name}'`);
442
+ continue;
443
+ }
444
+ if (column.type !== VIEW_CELL_TYPES[column.cell.part]) fail(`cell column '${column.name}' must be ${VIEW_CELL_TYPES[column.cell.part]}`);
445
+ expected.delete(column.name);
446
+ }
447
+ for (const name of expected.keys()) fail(`missing cell column '${name}'`);
448
+ }
449
+ var columnSignature = (columns) => JSON.stringify(columns.map((column) => [column.name, column.columnName, column.type]));
450
+ function validateMaterialized({ scope, tableByName, views }) {
451
+ const { view, resolved, fail } = scope;
452
+ const { table: tableName, compute: computeName } = resolved.materialized;
453
+ const table = tableByName.get(tableName);
454
+ if (!table || table.internal !== true || table.materializes !== view.view) {
455
+ fail(`materialized table '${tableName}' must be an internal table that materializes '${view.view}'`);
456
+ } else {
457
+ if (columnSignature(table.columns) !== columnSignature(view.columns)) fail(`materialized table '${tableName}' must have exactly the view's columns`);
458
+ if (JSON.stringify(table.primaryKey ?? []) !== JSON.stringify(view.primaryKey ?? [])) fail(`materialized table '${tableName}' must share the view's primary key`);
459
+ }
460
+ const compute = views.find((candidate) => candidate.view === computeName);
461
+ if (!compute || compute.internal !== true) fail(`compute view '${computeName}' must be an internal view`);
462
+ else if (columnSignature(compute.columns) !== columnSignature(view.columns)) fail(`compute view '${computeName}' must have exactly the view's columns`);
463
+ for (const source of resolved.sources) {
464
+ if (source.kind !== "etl") continue;
465
+ const read = tableByName.get(source.table)?.policies?.read;
466
+ const unconditional = typeof read === "string" ? read.trim() === "true" : read !== void 0 && read.default.trim() === "true" && read.variants.length === 0;
467
+ if (!unconditional) {
468
+ fail(`etl source '${source.name}' must have read policy 'true' to be materialized (the copy is shared by every caller)`);
469
+ }
470
+ }
471
+ }
472
+
473
+ // src/canonical/v2.ts
4
474
  var CANONICAL_FORMAT = 2;
5
475
  var IDENTIFIER_RE = /^[a-z][a-z0-9_]*$/;
6
- var identifier = z.string().min(1).max(63).regex(IDENTIFIER_RE);
476
+ var identifier2 = z.string().min(1).max(63).regex(IDENTIFIER_RE);
477
+ var columnIdentifier = z.string().min(1).max(63).regex(COLUMN_IDENTIFIER_PATTERN);
7
478
  var COLUMN_TYPES = [
8
479
  "uuid",
9
480
  "text",
@@ -18,59 +489,71 @@ var COLUMN_TYPES = [
18
489
  ];
19
490
  var columnTypeSchema = z.enum(COLUMN_TYPES);
20
491
  var canonicalEnumSchema = z.object({
21
- name: identifier,
492
+ name: identifier2,
22
493
  values: z.array(z.string().min(1).max(63)).min(1).max(100)
23
494
  });
24
495
  var canonicalColumnSchema = z.object({
25
496
  /** Property name in TS (camelCase); columnName is the Postgres name. */
26
497
  name: z.string().min(1).max(63),
27
- columnName: identifier,
28
- type: z.union([columnTypeSchema, z.object({ enum: identifier })]),
498
+ columnName: columnIdentifier,
499
+ type: z.union([columnTypeSchema, z.object({ enum: identifier2 })]),
29
500
  nullable: z.boolean().default(true),
30
501
  unique: z.boolean().default(false),
31
502
  /** Literal default, or one of the allowlisted SQL functions. */
32
503
  default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
33
504
  defaultFn: z.enum(["gen_random_uuid()", "now()"]).optional(),
505
+ /**
506
+ * Stamp this column from the database clock on UPDATE (`now()`). The
507
+ * column stays insertable (defaults fill gaps) but is omitted from
508
+ * SetInput / settable so callers cannot backdate it.
509
+ */
510
+ onUpdateFn: z.enum(["now()"]).optional(),
34
511
  description: z.string().max(500).optional(),
35
512
  /** Migration hints — same semantics as v1. */
36
- renamedFrom: identifier.optional(),
513
+ renamedFrom: columnIdentifier.optional(),
37
514
  cast: z.string().max(200).optional(),
38
- deprecated: z.boolean().default(false)
515
+ deprecated: z.boolean().default(false),
516
+ /**
517
+ * Marks a system cell-metadata column (see CELL_PARTS in constants): part
518
+ * `part` of the cell of logical column `of`. Synthesized by authoring,
519
+ * never client-writable, absent from GraphQL scalar fields. Omitted on
520
+ * ordinary columns so their hashes are unchanged.
521
+ */
522
+ cell: z.object({ of: z.string().min(1).max(63), part: z.enum(CELL_PARTS) }).strict().optional()
523
+ }).superRefine((column, ctx) => {
524
+ if (column.onUpdateFn === void 0) return;
525
+ if (typeof column.type !== "string" || column.type !== "timestamptz" && column.type !== "date") {
526
+ ctx.addIssue({
527
+ code: "custom",
528
+ path: ["onUpdateFn"],
529
+ message: `onUpdateFn '${column.onUpdateFn}' is only valid on timestamptz/date columns`
530
+ });
531
+ }
39
532
  });
40
533
  var canonicalLinkSchema = z.object({
41
534
  name: z.string().min(1).max(63),
42
535
  kind: z.enum(["toOne", "toMany", "toPlatformUser"]),
43
536
  /** Target table name (namespace-local). Absent for toPlatformUser. */
44
- target: identifier.optional(),
537
+ target: identifier2.optional(),
45
538
  /** FK column on the owning side (toOne/toPlatformUser: on this table; toMany: on the target). */
46
- on: identifier,
539
+ on: columnIdentifier,
47
540
  /** Referenced column on the target (default: target's PK / platform user `sub`). */
48
- references: identifier.optional(),
541
+ references: columnIdentifier.optional(),
49
542
  /** enforce: true emits a real FK constraint (same-namespace toOne only). */
50
543
  enforce: z.boolean().default(false),
544
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
545
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
51
546
  description: z.string().max(500).optional()
52
547
  });
53
548
  var canonicalIndexSchema = z.object({
54
- columns: z.array(identifier).min(1),
549
+ columns: z.array(columnIdentifier).min(1),
55
550
  unique: z.boolean().default(false),
56
- name: identifier.optional()
57
- });
58
- var policyVariantSchema = z.object({
59
- /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
60
- when: z.string().min(1).max(1e3),
61
- /** Exactly one of: allow-all bypass, or a row predicate. */
62
- allow: z.literal(true).optional(),
63
- policy: z.string().min(1).max(2e3).optional()
64
- }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
65
- message: "A variant declares exactly one of allow: true or policy"
551
+ name: identifier2.optional()
66
552
  });
67
- var policyExpressionSchema = z.union([
68
- z.string().min(1).max(2e3),
69
- z.object({
70
- default: z.string().min(1).max(2e3),
71
- variants: z.array(policyVariantSchema).max(10).default([])
72
- })
73
- ]);
553
+ var canonicalCheckSchema = z.object({
554
+ name: identifier2,
555
+ expression: z.string().min(1).max(2e3)
556
+ }).strict();
74
557
  var canonicalPoliciesSchema = z.object({
75
558
  read: policyExpressionSchema.optional(),
76
559
  write: policyExpressionSchema.optional(),
@@ -101,7 +584,7 @@ function isSingleViewQuerySql(value) {
101
584
  return state === "normal" && !/\$[a-z_0-9]*\$/i.test(query);
102
585
  }
103
586
  var canonicalActionSchema = z.object({
104
- name: identifier,
587
+ name: identifier2,
105
588
  requires: z.string().max(1e3).optional(),
106
589
  params: z.record(z.string(), z.object({
107
590
  type: columnTypeSchema,
@@ -113,9 +596,9 @@ var canonicalActionSchema = z.object({
113
596
  });
114
597
  var canonicalCowMutationSchema = z.object({
115
598
  kind: z.enum(["override", "revert"]),
116
- name: identifier,
599
+ name: identifier2,
117
600
  /** Synced table (same namespace) the overlay copies from / falls back to. */
118
- synced: identifier,
601
+ synced: identifier2,
119
602
  /** Single-column primary key PROPERTY (TS camelCase, like column `name`) shared by overlay and synced. */
120
603
  pk: z.string().min(1).max(63),
121
604
  /** Override: contract properties copied INSERT…SELECT from synced (pk included). Empty for revert. */
@@ -142,17 +625,28 @@ var canonicalCowMutationSchema = z.object({
142
625
  }
143
626
  }
144
627
  });
628
+ var canonicalForeignKeySchema = z.object({
629
+ name: identifier2,
630
+ columns: z.array(columnIdentifier).min(1).max(8),
631
+ target: identifier2,
632
+ references: z.array(columnIdentifier).min(1).max(8),
633
+ deferrable: z.enum(["initially-immediate", "initially-deferred"]).optional(),
634
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
635
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional()
636
+ }).strict();
145
637
  var canonicalTableSchema = z.object({
146
- table: identifier,
638
+ table: identifier2,
147
639
  description: z.string().max(2e3).optional(),
148
640
  /** Table-level rename hint (new in v2). */
149
- renamedFrom: identifier.optional(),
641
+ renamedFrom: identifier2.optional(),
150
642
  /** Synced/reflected read-only tables (`source: gold.*`) — v1 semantics. */
151
643
  source: z.string().regex(/^gold\.[a-z][a-z0-9_]*$/).optional(),
152
644
  columns: z.array(canonicalColumnSchema).default([]),
153
- primaryKey: z.array(identifier).min(1).max(8).optional(),
645
+ primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
154
646
  links: z.array(canonicalLinkSchema).default([]),
155
647
  indexes: z.array(canonicalIndexSchema).default([]),
648
+ /** Omitted by old definitions, preserving their existing content hashes. */
649
+ checks: z.array(canonicalCheckSchema).max(100).optional(),
156
650
  policies: canonicalPoliciesSchema.default({}),
157
651
  /**
158
652
  * v1-conversion carry-over only. v2 has no action surface — the runtime
@@ -161,26 +655,64 @@ var canonicalTableSchema = z.object({
161
655
  */
162
656
  actions: z.array(canonicalActionSchema).default([]),
163
657
  /** Optional (not defaulted) so pre-CoW canonical documents keep byte-identical hashes. */
164
- cowMutations: z.array(canonicalCowMutationSchema).optional()
658
+ cowMutations: z.array(canonicalCowMutationSchema).optional(),
659
+ /** Omitted by old definitions, preserving their existing content hashes. */
660
+ foreignKeys: z.array(canonicalForeignKeySchema).max(100).optional(),
661
+ /**
662
+ * Per-cell edit metadata (`cellMetadata: true` in authoring): every tracked
663
+ * column `c` carries typed `c__at` / `c__by` system columns (plus `c__rev`
664
+ * on a resolved table's internal sources), listed explicitly in `columns`
665
+ * with a `cell` marker so DDL and migrations treat them as ordinary columns.
666
+ * Omitted when off so existing definitions hash unchanged.
667
+ */
668
+ cellMetadata: z.literal(true).optional(),
669
+ /**
670
+ * System-owned backing table of a resolved table (its manual or prefetch
671
+ * source). Internal tables get DDL and IR metadata but no GraphQL surface;
672
+ * only the data plane writes them. Omitted when false.
673
+ */
674
+ internal: z.literal(true).optional(),
675
+ /**
676
+ * The materialized copy of resolved table `materializes` (internal): the
677
+ * same columns as that view, including its cell parts, maintained by the
678
+ * data plane. Omitted otherwise.
679
+ */
680
+ materializes: identifier2.optional()
165
681
  });
682
+ var MAX_VIEW_QUERY = 1e5;
683
+ var MAX_RESOLVED_VIEW_QUERY = 5e6;
166
684
  var canonicalViewSchema = z.object({
167
- view: identifier,
685
+ view: identifier2,
168
686
  description: z.string().max(2e3).optional(),
169
687
  columns: z.array(canonicalColumnSchema).min(1),
170
688
  /** Logical identity for GraphQL only; PostgreSQL views have no PK constraint. */
171
- primaryKey: z.array(identifier).min(1).max(8).optional(),
689
+ primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
172
690
  links: z.array(canonicalLinkSchema).default([]),
173
691
  policies: z.object({ read: policyExpressionSchema }).strict(),
174
- query: z.string().min(1).max(1e5).refine(isSingleViewQuerySql, {
692
+ query: z.string().min(1).max(MAX_RESOLVED_VIEW_QUERY).refine(isSingleViewQuerySql, {
175
693
  message: "view query must be one SELECT/WITH statement without comments or dollar-quoted bodies"
176
694
  }),
177
695
  /** Namespace-local logical relation names, sorted for deterministic hashing. */
178
- dependencies: z.array(identifier).max(500)
696
+ dependencies: z.array(identifier2).max(500),
697
+ /**
698
+ * Present when this view is a resolved table (defineResolvedTable): the
699
+ * multi-source metadata behind its generated query. Omitted otherwise so
700
+ * existing views hash unchanged.
701
+ */
702
+ resolved: canonicalResolvedSchema.optional(),
703
+ /** System-owned view (a materialized resolved table's compute view): no GraphQL surface. */
704
+ internal: z.literal(true).optional()
179
705
  }).superRefine((view, ctx) => {
706
+ if (view.resolved === void 0 && view.query.length > MAX_VIEW_QUERY) {
707
+ ctx.addIssue({ code: "custom", path: ["query"], message: `view query must be at most ${MAX_VIEW_QUERY} characters` });
708
+ }
180
709
  for (const [index, column] of view.columns.entries()) {
181
710
  if (column.default !== void 0 || column.defaultFn !== void 0) {
182
711
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare a default` });
183
712
  }
713
+ if (column.onUpdateFn !== void 0) {
714
+ ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare onUpdateFn` });
715
+ }
184
716
  if (column.unique) {
185
717
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare unique` });
186
718
  }
@@ -188,15 +720,82 @@ var canonicalViewSchema = z.object({
188
720
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare migration hints` });
189
721
  }
190
722
  }
723
+ if (view.resolved === void 0 && view.internal !== true) {
724
+ for (const [index, column] of view.columns.entries()) {
725
+ if (column.cell) ctx.addIssue({ code: "custom", path: ["columns", index], message: `only resolved tables carry cell columns ('${column.name}')` });
726
+ }
727
+ }
191
728
  for (const [index, link] of view.links.entries()) {
192
729
  if (link.enforce) {
193
730
  ctx.addIssue({ code: "custom", path: ["links", index, "enforce"], message: `view link '${link.name}' cannot enforce a foreign key` });
194
731
  }
732
+ if (link.onDelete !== void 0 || link.onUpdate !== void 0) {
733
+ ctx.addIssue({ code: "custom", path: ["links", index], message: `view link '${link.name}' cannot declare referential actions` });
734
+ }
195
735
  }
196
736
  });
737
+ var CELL_PART_TYPES = {
738
+ at: "timestamptz",
739
+ by: "text",
740
+ rev: "uuid",
741
+ source: "text",
742
+ conflicts: "jsonb"
743
+ };
744
+ function trackedCellColumns(table) {
745
+ const pk = new Set(table.primaryKey ?? []);
746
+ return table.columns.filter((column) => column.cell === void 0 && !pk.has(column.columnName) && column.onUpdateFn === void 0);
747
+ }
748
+ var SUFFIXES = Object.values(CELL_PART_SUFFIX);
749
+ function validateCellMetadata(table, index, ctx) {
750
+ const fail = (message, path = ["tables", index]) => ctx.addIssue({ code: "custom", path, message });
751
+ const cells = table.columns.flatMap((column, position) => column.cell ? [{ column, position, cell: column.cell }] : []);
752
+ if (table.materializes !== void 0) return;
753
+ if (table.cellMetadata !== true) {
754
+ for (const { position } of cells) fail(`cell-metadata columns require cellMetadata on table '${table.table}'`, ["tables", index, "columns", position]);
755
+ return;
756
+ }
757
+ if (table.source !== void 0) {
758
+ fail(`synced table '${table.table}' cannot track cell metadata`);
759
+ return;
760
+ }
761
+ const tracked = trackedCellColumns(table);
762
+ const byName = new Map(tracked.map((column) => [column.name, column]));
763
+ const withRev = cells.some(({ cell }) => cell.part === "rev");
764
+ if (withRev && table.internal !== true) fail(`only a resolved table's internal sources carry '__rev' cell columns ('${table.table}')`);
765
+ const seen = /* @__PURE__ */ new Set();
766
+ for (const { column, position, cell } of cells) {
767
+ const path = ["tables", index, "columns", position];
768
+ const owner = byName.get(cell.of);
769
+ if (!owner) {
770
+ fail(`cell column '${column.name}' belongs to '${cell.of}', which is not a tracked column`, path);
771
+ continue;
772
+ }
773
+ if (cell.part !== "at" && cell.part !== "by" && cell.part !== "rev") fail(`a table cell column must be part at/by/rev, not '${cell.part}'`, path);
774
+ if (column.name !== cellColumnName(owner.name, cell.part) || column.columnName !== cellColumnName(owner.columnName, cell.part)) {
775
+ fail(`cell column for '${owner.name}' ${cell.part} must be named '${cellColumnName(owner.name, cell.part)}' / '${cellColumnName(owner.columnName, cell.part)}'`, path);
776
+ }
777
+ if (column.type !== CELL_PART_TYPES[cell.part] || !column.nullable || column.unique || column.default !== void 0 || column.defaultFn !== void 0) {
778
+ fail(`cell column '${column.name}' must be a nullable, default-less ${CELL_PART_TYPES[cell.part]}`, path);
779
+ }
780
+ const key = `${cell.of}:${cell.part}`;
781
+ if (seen.has(key)) fail(`duplicate cell column '${column.name}'`, path);
782
+ seen.add(key);
783
+ }
784
+ for (const column of tracked) {
785
+ if (column.columnName.length > MAX_TRACKED_COLUMN_NAME) {
786
+ fail(`column '${column.columnName}' is too long to track cell metadata (max ${MAX_TRACKED_COLUMN_NAME} characters)`);
787
+ }
788
+ if (SUFFIXES.some((suffix) => column.columnName.endsWith(suffix))) {
789
+ fail(`column '${column.columnName}' ends in a reserved cell-metadata suffix (${SUFFIXES.join(", ")})`);
790
+ }
791
+ for (const part of withRev ? ["at", "by", "rev"] : ["at", "by"]) {
792
+ if (!seen.has(`${column.name}:${part}`)) fail(`tracked column '${column.name}' is missing its '${cellColumnName(column.columnName, part)}' cell column`);
793
+ }
794
+ }
795
+ }
197
796
  z.object({
198
797
  definition_format: z.literal(CANONICAL_FORMAT),
199
- namespace: identifier.max(41),
798
+ namespace: identifier2.max(41),
200
799
  description: z.string().max(2e3).optional(),
201
800
  enums: z.array(canonicalEnumSchema).default([]),
202
801
  tables: z.array(canonicalTableSchema).min(0).max(500),
@@ -214,6 +813,74 @@ z.object({
214
813
  ctx.addIssue({ code: "custom", path: ["tables", index, "table"], message: `duplicate relation '${table.table}'` });
215
814
  }
216
815
  seen.add(table.table);
816
+ validateCellMetadata(table, index, ctx);
817
+ if (table.source !== void 0) {
818
+ for (const [columnIndex, column] of table.columns.entries()) {
819
+ if (column.onUpdateFn !== void 0) {
820
+ ctx.addIssue({
821
+ code: "custom",
822
+ path: ["tables", index, "columns", columnIndex],
823
+ message: `synced table '${table.table}' column '${column.name}' cannot declare onUpdateFn`
824
+ });
825
+ }
826
+ }
827
+ }
828
+ }
829
+ const fkTables = new Map(definition.tables.map((table) => [table.table, table]));
830
+ for (const [tableIndex, table] of definition.tables.entries()) {
831
+ const names = /* @__PURE__ */ new Set([
832
+ ...table.primaryKey?.length ? [`${table.table}_pkey`] : [],
833
+ ...table.columns.filter((column) => column.unique && !(table.primaryKey?.length === 1 && table.primaryKey[0] === column.columnName)).map((column) => `${table.table}_${column.columnName}_unique`),
834
+ ...table.links.filter((link) => link.enforce).map((link) => `fk_${table.table}_${link.name}`)
835
+ ]);
836
+ for (const [index, link] of table.links.entries()) {
837
+ if ((link.onDelete !== void 0 || link.onUpdate !== void 0) && (!link.enforce || link.kind !== "toOne")) {
838
+ ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", index], message: "referential actions require an enforced toOne link" });
839
+ }
840
+ if (link.onDelete === "set null" || link.onUpdate === "set null") {
841
+ const source = table.columns.find((column) => column.columnName === link.on);
842
+ if (source?.nullable === false || table.primaryKey?.includes(link.on)) ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", index], message: "SET NULL requires a nullable source column" });
843
+ }
844
+ }
845
+ for (const [index, check] of (table.checks ?? []).entries()) {
846
+ const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "checks", index], message });
847
+ if (table.source) fail("synced tables cannot declare checks");
848
+ if (names.has(check.name)) fail(`duplicate constraint '${check.name}'`);
849
+ names.add(check.name);
850
+ try {
851
+ compileCheckExpression(check.expression, table.columns);
852
+ } catch (error) {
853
+ fail(error instanceof Error ? error.message : String(error));
854
+ }
855
+ }
856
+ for (const [index, fk] of (table.foreignKeys ?? []).entries()) {
857
+ const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "foreignKeys", index], message });
858
+ if (names.has(fk.name)) fail(`duplicate foreign key '${fk.name}'`);
859
+ names.add(fk.name);
860
+ const target = fkTables.get(fk.target);
861
+ if (table.source || !target || target.source) {
862
+ fail("foreign keys must connect owned tables in the same namespace");
863
+ continue;
864
+ }
865
+ if (fk.columns.length !== fk.references.length) fail("foreign key columns and references must have the same number of columns");
866
+ if (new Set(fk.columns).size !== fk.columns.length || new Set(fk.references).size !== fk.references.length) fail("foreign key columns must not repeat");
867
+ for (const [position, name] of fk.columns.entries()) {
868
+ const sourceColumn = table.columns.find((column) => column.columnName === name);
869
+ const targetColumn = target.columns.find((column) => column.columnName === fk.references[position]);
870
+ if (!sourceColumn || !targetColumn) fail("foreign key references an unknown column");
871
+ else if (JSON.stringify(sourceColumn.type) !== JSON.stringify(targetColumn.type)) fail("foreign key column types must match");
872
+ }
873
+ if (fk.onDelete === "set null" || fk.onUpdate === "set null") {
874
+ if (fk.columns.some((name) => table.columns.find((column) => column.columnName === name)?.nullable === false || table.primaryKey?.includes(name))) fail("SET NULL requires nullable source columns");
875
+ }
876
+ const uniqueKeys = [target.primaryKey ?? [], ...target.indexes.filter((index2) => index2.unique).map((index2) => index2.columns), ...target.columns.filter((column) => column.unique).map((column) => [column.columnName])];
877
+ if (!uniqueKeys.some((key) => key.length === fk.references.length && key.every((column) => fk.references.includes(column)))) fail("foreign key target columns must form a unique key");
878
+ }
879
+ }
880
+ for (const [viewIndex, view] of (definition.views ?? []).entries()) {
881
+ for (const message of validateResolvedView({ view, tables: definition.tables, views: definition.views ?? [] })) {
882
+ ctx.addIssue({ code: "custom", path: ["views", viewIndex, "resolved"], message });
883
+ }
217
884
  }
218
885
  const tableByName = new Map(definition.tables.map((table) => [table.table, table]));
219
886
  for (const [tableIndex, table] of definition.tables.entries()) {
@@ -332,7 +999,18 @@ z.object({
332
999
  });
333
1000
 
334
1001
  // src/ir/index.ts
335
- var IR_VERSION = 1;
1002
+ var IR_VERSION = 2;
1003
+ var LEGACY_IR_VERSION = 1;
1004
+ var irVersionSchema = z.union([z.literal(LEGACY_IR_VERSION), z.literal(IR_VERSION)]);
1005
+ var operationVersionSchema = z.object({ irVersion: irVersionSchema });
1006
+ function requiredArtifactIrVersion(operations) {
1007
+ let required = LEGACY_IR_VERSION;
1008
+ for (const operation of operations) {
1009
+ const { irVersion } = operationVersionSchema.parse(operation);
1010
+ if (irVersion > required) required = irVersion;
1011
+ }
1012
+ return required;
1013
+ }
336
1014
  var CLAIMS_CONTRACT = {
337
1015
  sub: "string",
338
1016
  org: "string?",
@@ -404,6 +1082,21 @@ var selectionIrSchema = z.lazy(
404
1082
  () => z.object({
405
1083
  typename: z.string(),
406
1084
  columns: z.array(z.object({ alias: z.string(), column: z.string() })),
1085
+ cells: z.object({
1086
+ alias: z.string(),
1087
+ typename: z.string(),
1088
+ fields: z.array(z.object({
1089
+ alias: z.string(),
1090
+ column: z.string(),
1091
+ typename: z.string(),
1092
+ parts: z.array(z.object({
1093
+ alias: z.string(),
1094
+ part: z.enum(["source", "at", "by", "conflicts"]),
1095
+ fields: z.array(z.object({ alias: z.string(), field: z.enum(["source", "at", "value"]) })).optional(),
1096
+ typename: z.string().optional()
1097
+ }))
1098
+ }))
1099
+ }).optional(),
407
1100
  relations: z.array(z.object({
408
1101
  alias: z.string(),
409
1102
  link: z.string(),
@@ -425,6 +1118,11 @@ var selectionIrSchema = z.lazy(
425
1118
  })
426
1119
  );
427
1120
  var includeIfSchema = z.object({ variable: z.string(), negated: z.boolean() });
1121
+ var prefetchPlanIrSchema = z.object({
1122
+ source: z.string(),
1123
+ maxStalenessMs: z.number().int().positive().optional(),
1124
+ key: z.union([z.object({ one: valueIrSchema }), z.object({ many: valueIrSchema })])
1125
+ });
428
1126
  var selectRootSchema = z.object({
429
1127
  kind: z.literal("select"),
430
1128
  alias: z.string(),
@@ -436,7 +1134,8 @@ var selectRootSchema = z.object({
436
1134
  distinctOn: z.union([z.array(z.string()), z.object({ slot: z.string() })]).optional(),
437
1135
  limit: limitIrSchema,
438
1136
  offset: z.object({ variable: z.string().optional(), value: z.number().int().optional() }).optional(),
439
- includeIf: includeIfSchema.optional()
1137
+ includeIf: includeIfSchema.optional(),
1138
+ prefetch: z.array(prefetchPlanIrSchema).optional()
440
1139
  });
441
1140
  var byPkRootSchema = z.object({
442
1141
  kind: z.literal("byPk"),
@@ -446,7 +1145,8 @@ var byPkRootSchema = z.object({
446
1145
  pk: z.array(z.object({ column: z.string(), value: valueIrSchema })).min(1),
447
1146
  /** Policy predicate — ANDed with the PK match. */
448
1147
  where: predIrSchema,
449
- includeIf: includeIfSchema.optional()
1148
+ includeIf: includeIfSchema.optional(),
1149
+ prefetch: z.array(prefetchPlanIrSchema).optional()
450
1150
  });
451
1151
  var aggregateRootSchema = z.object({
452
1152
  kind: z.literal("aggregate"),
@@ -459,6 +1159,33 @@ var aggregateRootSchema = z.object({
459
1159
  nodes: selectionIrSchema.optional(),
460
1160
  includeIf: includeIfSchema.optional()
461
1161
  });
1162
+ var DATE_BUCKETS = ["year", "quarter", "month", "week", "day", "hour"];
1163
+ var groupByKeyIrSchema = z.object({
1164
+ column: z.string(),
1165
+ bucket: z.enum(DATE_BUCKETS).optional()
1166
+ });
1167
+ var aggregateGroupsRootSchema = z.object({
1168
+ kind: z.literal("aggregateGroups"),
1169
+ alias: z.string(),
1170
+ table: z.string(),
1171
+ /** Composed at compile time: AND(policy, documentWhere?, dynamicFilter?). */
1172
+ where: predIrSchema,
1173
+ groupBy: z.array(groupByKeyIrSchema).min(1),
1174
+ /**
1175
+ * The `key { … }` projection: which group columns appear in each entry's key
1176
+ * object, in selection order. A subset of `groupBy` (the compiler rejects a
1177
+ * key field that is not a group key — it would be indeterminate within the
1178
+ * group). Empty when the document selects only `aggregate`.
1179
+ */
1180
+ key: z.array(z.object({ alias: z.string(), column: z.string() })).default([]),
1181
+ count: z.object({ columns: z.array(z.string()).optional(), distinct: z.boolean().optional() }).optional(),
1182
+ sum: z.array(z.string()).optional(),
1183
+ avg: z.array(z.string()).optional(),
1184
+ /** Bounds the GROUP count, not the scanned rows — see MAX_GROUPS. */
1185
+ limit: limitIrSchema,
1186
+ offset: z.object({ variable: z.string().optional(), value: z.number().int().optional() }).optional(),
1187
+ includeIf: includeIfSchema.optional()
1188
+ });
462
1189
  var writeValuesSchema = z.union([
463
1190
  z.object({ slot: z.string() }),
464
1191
  z.object({ entries: z.array(z.object({ column: z.string(), value: valueIrSchema })) })
@@ -477,7 +1204,20 @@ var mutationRootSchema = z.object({
477
1204
  * coalesce view falls back to synced. Both are gated on a matching synced
478
1205
  * row and carry the write policy in `where` like update/delete.
479
1206
  */
480
- op: z.enum(["insert", "insertOne", "update", "updateByPk", "delete", "deleteByPk", "cowOverride", "cowRevert"]),
1207
+ op: z.enum(["insert", "insertOne", "update", "updateByPk", "delete", "deleteByPk", "cowOverride", "cowRevert", "resolvedWrite"]),
1208
+ /**
1209
+ * resolvedWrite: a write to a resolved table (`table` is its view). The
1210
+ * executor gates on the resolved row (write policy in `where`), writes only
1211
+ * the touched cells into the manual source, then re-checks `insertCheck`
1212
+ * against the resolved row. `revert` clears `revertColumns` from the manual
1213
+ * source; `delete` tombstones the row there.
1214
+ */
1215
+ resolvedAction: z.enum(["insert", "update", "delete", "revert"]).optional(),
1216
+ revertColumns: z.array(z.string()).optional(),
1217
+ /** `@writeback(source:, mode:)` directives on this root. */
1218
+ writeback: z.array(z.object({ source: z.string(), mode: z.enum(["sync", "async"]) })).optional(),
1219
+ /** `@localOnly(source:)` — writeback columns deliberately kept local for these sources. */
1220
+ localOnly: z.array(z.string()).optional(),
481
1221
  alias: z.string(),
482
1222
  table: z.string(),
483
1223
  /** CoW ops: logical name of the synced twin (read through its policy-filtered view). */
@@ -504,12 +1244,15 @@ var mutationRootSchema = z.object({
504
1244
  insertCheck: predIrSchema.optional(),
505
1245
  returning: selectionIrSchema.nullable(),
506
1246
  affectedRows: z.boolean().default(false),
1247
+ /** v2: abort the transaction when the actual write count differs, regardless of selection. */
1248
+ assertAffectedRows: z.number().int().min(0).max(2147483647).optional(),
507
1249
  includeIf: includeIfSchema.optional()
508
1250
  });
509
1251
  var rootIrSchema = z.discriminatedUnion("kind", [
510
1252
  selectRootSchema,
511
1253
  byPkRootSchema,
512
1254
  aggregateRootSchema,
1255
+ aggregateGroupsRootSchema,
513
1256
  mutationRootSchema
514
1257
  ]);
515
1258
  var INPUT_REF_KINDS = [
@@ -539,7 +1282,7 @@ var variableIrSchema = z.object({
539
1282
  defaultValue: variableDefaultIrSchema.optional()
540
1283
  });
541
1284
  var compiledOperationSchema = z.object({
542
- irVersion: z.literal(IR_VERSION),
1285
+ irVersion: irVersionSchema,
543
1286
  name: z.string(),
544
1287
  opHash: z.string().regex(/^sha256:[0-9a-f]{64}$/),
545
1288
  kind: z.enum(["query", "mutation"]),
@@ -551,6 +1294,50 @@ var compiledOperationSchema = z.object({
551
1294
  /** Every table the op touches — data-token scoping + audit. */
552
1295
  tableSet: z.array(z.string()).min(1),
553
1296
  roots: z.array(rootIrSchema).min(1)
1297
+ }).superRefine((operation, ctx) => {
1298
+ for (const [index, root] of operation.roots.entries()) {
1299
+ if (root.kind !== "mutation" || root.assertAffectedRows === void 0) continue;
1300
+ if (operation.irVersion < 2 || operation.kind !== "mutation" || root.includeIf !== void 0) {
1301
+ ctx.addIssue({ code: "custom", path: ["roots", index], message: "affected-row assertions require unconditional mutation roots and IR v2" });
1302
+ }
1303
+ }
1304
+ });
1305
+ var resolvedSourceIrSchema = z.object({
1306
+ name: z.string(),
1307
+ kind: z.enum(["manual", "etl", "prefetch"]),
1308
+ /** Logical table key of the backing relation. */
1309
+ table: z.string(),
1310
+ columns: z.array(z.string()),
1311
+ key: z.string().optional(),
1312
+ fetch: z.union([
1313
+ z.object({ shape: z.literal("single") }),
1314
+ z.object({ shape: z.literal("batch"), maxKeys: z.number().int().positive() })
1315
+ ]).optional(),
1316
+ function: z.object({ kind: z.enum(["managed", "native"]), id: z.string() }).optional(),
1317
+ prefetchDefaults: z.object({
1318
+ maxStalenessMs: z.number().int().positive(),
1319
+ timeoutMs: z.number().int().positive(),
1320
+ onError: z.enum(["fallback", "fail"])
1321
+ }).optional(),
1322
+ writeback: z.object({
1323
+ columns: z.array(z.string()),
1324
+ defaultMode: z.enum(["sync", "async"]),
1325
+ timeoutMs: z.number().int().positive(),
1326
+ clearManualOnConfirm: z.boolean()
1327
+ }).optional()
1328
+ });
1329
+ var resolvedMetaIrSchema = z.object({
1330
+ /** Logical pk column of the resolved view (single-column). */
1331
+ pk: z.string(),
1332
+ /** Source name of the manual source. */
1333
+ manual: z.string(),
1334
+ sources: z.array(resolvedSourceIrSchema),
1335
+ deletedBy: z.array(z.string()),
1336
+ /**
1337
+ * Materialized: the view reads `table`, which the data plane refreshes from
1338
+ * the `compute` view (claims-gated) whenever it writes a source row.
1339
+ */
1340
+ materialized: z.object({ table: z.string(), compute: z.string() }).optional()
554
1341
  });
555
1342
  var tableMetaIrSchema = z.object({
556
1343
  table: z.string(),
@@ -587,18 +1374,45 @@ var tableMetaIrSchema = z.object({
587
1374
  insertable: z.array(z.string()),
588
1375
  settable: z.array(z.string()),
589
1376
  appendable: z.array(z.string()),
1377
+ /**
1378
+ * Logical columns stamped with Postgres `now()` on UPDATE (canonical
1379
+ * `onUpdateFn`). Omitted when empty so pre-onUpdate artifacts still parse.
1380
+ */
1381
+ touchOnUpdate: z.array(z.string()).optional(),
1382
+ /**
1383
+ * Per-cell metadata: logical column → the logical names of its cell-part
1384
+ * columns (which are listed in `columns`, but never filterable, orderable or
1385
+ * writable). Tables stamp `at`/`by` (and a manual source `rev`) on every
1386
+ * write; resolved views expose `source`/`at`/`by`/`conflicts`. Omitted when
1387
+ * the relation tracks no cells.
1388
+ */
1389
+ cells: z.record(z.string(), z.object({
1390
+ at: z.string().optional(),
1391
+ by: z.string().optional(),
1392
+ rev: z.string().optional(),
1393
+ source: z.string().optional(),
1394
+ conflicts: z.string().optional()
1395
+ }).strict()).optional(),
1396
+ /** Resolved-table view metadata (sources, prefetch/writeback config) for the data plane. */
1397
+ resolved: resolvedMetaIrSchema.optional(),
590
1398
  constraints: z.array(z.object({ name: z.string(), columns: z.array(z.string()) })),
591
1399
  /** Depth/node caps for dynamic filter trees on this table. */
592
1400
  dynamicFilterMaxDepth: z.number().int().positive().default(6),
593
1401
  dynamicFilterMaxNodes: z.number().int().positive().default(64)
594
1402
  });
595
1403
  var compiledArtifactSchema = z.object({
596
- irVersion: z.literal(IR_VERSION),
1404
+ irVersion: irVersionSchema,
597
1405
  namespace: z.string(),
598
1406
  schemaHash: z.string(),
599
1407
  opsHash: z.string(),
600
1408
  tables: z.record(z.string(), tableMetaIrSchema),
601
1409
  operations: z.record(z.string(), compiledOperationSchema)
1410
+ }).superRefine((artifact, ctx) => {
1411
+ for (const [name, operation] of Object.entries(artifact.operations)) {
1412
+ if (operation.irVersion > artifact.irVersion) {
1413
+ ctx.addIssue({ code: "custom", path: ["operations", name, "irVersion"], message: "operation requires a newer IR version than its artifact" });
1414
+ }
1415
+ }
602
1416
  });
603
1417
  var IrVersionError = class extends Error {
604
1418
  constructor(found) {
@@ -609,7 +1423,7 @@ var IrVersionError = class extends Error {
609
1423
  function normalizeIr(raw) {
610
1424
  if (!raw || typeof raw !== "object") throw new IrVersionError(void 0);
611
1425
  const version = raw.irVersion;
612
- if (version !== IR_VERSION) throw new IrVersionError(version);
1426
+ if (version !== LEGACY_IR_VERSION && version !== IR_VERSION) throw new IrVersionError(version);
613
1427
  return compiledArtifactSchema.parse(raw);
614
1428
  }
615
1429
  function indexByHash(artifact) {
@@ -618,6 +1432,6 @@ function indexByHash(artifact) {
618
1432
  return map;
619
1433
  }
620
1434
 
621
- export { CLAIMS_CONTRACT, CMP_OPS, INPUT_REF_KINDS, IR_VERSION, IrVersionError, compiledArtifactSchema, compiledOperationSchema, indexByHash, limitIrSchema, normalizeIr, orderIrSchema, predIrSchema, rootIrSchema, selectionIrSchema, tableMetaIrSchema, valueIrSchema, variableDefaultIrSchema, variableIrSchema };
1435
+ export { CELLS_FIELD, CELL_PARTS, CLAIMS_CONTRACT, CMP_OPS, DATE_BUCKETS, INPUT_REF_KINDS, IR_VERSION, IrVersionError, LEGACY_IR_VERSION, cellColumnName, compiledArtifactSchema, compiledOperationSchema, indexByHash, limitIrSchema, normalizeIr, orderIrSchema, predIrSchema, prefetchPlanIrSchema, requiredArtifactIrVersion, resolvedMetaIrSchema, resolvedSourceIrSchema, rootIrSchema, selectionIrSchema, tableMetaIrSchema, valueIrSchema, variableDefaultIrSchema, variableIrSchema };
622
1436
  //# sourceMappingURL=ir.js.map
623
1437
  //# sourceMappingURL=ir.js.map