@sequenceholdings/orm 2.1.0 → 2.2.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 (77) hide show
  1. package/README.md +40 -1
  2. package/dist/authoring.cjs +1619 -121
  3. package/dist/authoring.cjs.map +1 -1
  4. package/dist/authoring.d.cts +252 -8
  5. package/dist/authoring.d.ts +252 -8
  6. package/dist/authoring.js +1607 -123
  7. package/dist/authoring.js.map +1 -1
  8. package/dist/canonical.cjs +713 -41
  9. package/dist/canonical.cjs.map +1 -1
  10. package/dist/canonical.d.cts +1520 -51
  11. package/dist/canonical.d.ts +1520 -51
  12. package/dist/canonical.js +693 -42
  13. package/dist/canonical.js.map +1 -1
  14. package/dist/cli.cjs +7103 -3901
  15. package/dist/cli.cjs.map +1 -1
  16. package/dist/cli.js +7104 -3902
  17. package/dist/cli.js.map +1 -1
  18. package/dist/client.cjs +122 -40
  19. package/dist/client.cjs.map +1 -1
  20. package/dist/client.d.cts +85 -25
  21. package/dist/client.d.ts +85 -25
  22. package/dist/client.js +119 -41
  23. package/dist/client.js.map +1 -1
  24. package/dist/compiler.cjs +2464 -450
  25. package/dist/compiler.cjs.map +1 -1
  26. package/dist/compiler.d.cts +79 -4
  27. package/dist/compiler.d.ts +79 -4
  28. package/dist/compiler.js +2457 -451
  29. package/dist/compiler.js.map +1 -1
  30. package/dist/constants-C6EG6Wq7.d.cts +99 -0
  31. package/dist/constants-C6EG6Wq7.d.ts +99 -0
  32. package/dist/definition-DjfC7Lll.d.cts +91 -0
  33. package/dist/definition-DjfC7Lll.d.ts +91 -0
  34. package/dist/dynamic-input.cjs +2 -1
  35. package/dist/dynamic-input.cjs.map +1 -1
  36. package/dist/dynamic-input.d.cts +9 -1
  37. package/dist/dynamic-input.d.ts +9 -1
  38. package/dist/dynamic-input.js +2 -1
  39. package/dist/dynamic-input.js.map +1 -1
  40. package/dist/index.cjs +2656 -418
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +693 -116
  43. package/dist/index.d.ts +693 -116
  44. package/dist/index.js +2622 -420
  45. package/dist/index.js.map +1 -1
  46. package/dist/ir.cjs +811 -48
  47. package/dist/ir.cjs.map +1 -1
  48. package/dist/ir.d.cts +670 -27
  49. package/dist/ir.d.ts +670 -27
  50. package/dist/ir.js +802 -49
  51. package/dist/ir.js.map +1 -1
  52. package/dist/{naming-DCn94LJ4.d.ts → naming-CPfx7EfF.d.ts} +14 -1
  53. package/dist/{naming-DPglwzkB.d.cts → naming-CU9ThP_E.d.cts} +14 -1
  54. package/dist/policy-1iZbGnZZ.d.cts +24 -0
  55. package/dist/policy-1iZbGnZZ.d.ts +24 -0
  56. package/dist/predicate-v2.cjs +804 -51
  57. package/dist/predicate-v2.cjs.map +1 -1
  58. package/dist/predicate-v2.d.cts +2 -1
  59. package/dist/predicate-v2.d.ts +2 -1
  60. package/dist/predicate-v2.js +804 -51
  61. package/dist/predicate-v2.js.map +1 -1
  62. package/dist/sdl.cjs +1014 -75
  63. package/dist/sdl.cjs.map +1 -1
  64. package/dist/sdl.d.cts +14 -3
  65. package/dist/sdl.d.ts +14 -3
  66. package/dist/sdl.js +1012 -76
  67. package/dist/sdl.js.map +1 -1
  68. package/package.json +13 -7
  69. package/src/codegen-gql/server-fns.cjs +2 -2
  70. package/templates/orm-namespace/AGENTS.md +10 -0
  71. package/templates/orm-namespace/CLAUDE.md +1 -82
  72. package/templates/orm-namespace/codegen.preset.d.cts +7 -0
  73. package/templates/orm-namespace/codegen.ts +2 -1
  74. package/templates/orm-namespace/graphql/example/queries.ts +4 -3
  75. package/templates/orm-namespace/package.json +2 -1
  76. package/templates/orm-namespace/schema/tables.ts +3 -2
  77. package/templates/orm-namespace/sequence.config.ts +7 -11
@@ -30,10 +30,477 @@ var PolicyCompileError = class extends Error {
30
30
 
31
31
  // src/constants.ts
32
32
  var COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/;
33
- var CAPABILITY_KEY_PATTERN = /^(?:org\/)?[a-z0-9-]{1,64}$/;
33
+ var MAX_IDENTIFIER_LENGTH = 63;
34
+ var CAPABILITY_KEY_PATTERN = /^(?:org\/|app\/[a-z][a-z0-9-]{0,63}\/)?[a-z0-9-]{1,64}$/;
35
+ var QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\.[a-z][a-z0-9_]{0,62}$/;
36
+ var CELL_PARTS = ["at", "by", "rev", "source", "conflicts"];
37
+ var CELL_PART_SUFFIX = {
38
+ at: "__at",
39
+ by: "__by",
40
+ rev: "__rev",
41
+ source: "__src",
42
+ conflicts: "__lost"
43
+ };
44
+ var MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6;
45
+ function cellColumnName(column, part) {
46
+ return `${column}${CELL_PART_SUFFIX[part]}`;
47
+ }
48
+ var MATERIALIZE_ACTOR = "orm:materialize";
49
+ JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] });
50
+ var quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
51
+ var quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
52
+
53
+ // src/checks/compile.ts
54
+ function tokenize(source) {
55
+ const tokens = [];
56
+ for (let position = 0; position < source.length; ) {
57
+ const char = source[position];
58
+ if (/\s/.test(char)) {
59
+ position++;
60
+ continue;
61
+ }
62
+ if (char === "(" || char === ")" || char === ",") {
63
+ tokens.push({ kind: char === "(" ? "lparen" : char === ")" ? "rparen" : "comma", value: char, position });
64
+ position++;
65
+ continue;
66
+ }
67
+ if (char === "'") {
68
+ const start = position++;
69
+ let value = "";
70
+ let closed = false;
71
+ while (position < source.length) {
72
+ if (source[position] !== "'") {
73
+ value += source[position++];
74
+ continue;
75
+ }
76
+ if (source[position + 1] === "'") {
77
+ value += "'";
78
+ position += 2;
79
+ continue;
80
+ }
81
+ position++;
82
+ closed = true;
83
+ break;
84
+ }
85
+ if (!closed) throw new Error(`unterminated string at position ${start}`);
86
+ if (/[\x00-\x1f\x7f]/.test(value)) throw new Error(`control character in string at position ${start}`);
87
+ tokens.push({ kind: "string", value, position: start });
88
+ continue;
89
+ }
90
+ const operator = /^(<=|>=|<>|!=|!~|=|<|>|~)/.exec(source.slice(position));
91
+ if (operator) {
92
+ tokens.push({ kind: "operator", value: operator[0] === "<>" ? "!=" : operator[0], position });
93
+ position += operator[0].length;
94
+ continue;
95
+ }
96
+ const number = /^-?\d+(?:\.\d+)?/.exec(source.slice(position));
97
+ if (number) {
98
+ tokens.push({ kind: "number", value: number[0], position });
99
+ position += number[0].length;
100
+ continue;
101
+ }
102
+ const identifier3 = /^[a-zA-Z_][a-zA-Z_0-9]*/.exec(source.slice(position));
103
+ if (identifier3) {
104
+ tokens.push({ kind: "identifier", value: identifier3[0], position });
105
+ position += identifier3[0].length;
106
+ continue;
107
+ }
108
+ throw new Error(`unexpected character '${char}' at position ${position}`);
109
+ }
110
+ tokens.push({ kind: "end", value: "", position: source.length });
111
+ if (tokens.length > 256) throw new Error("check expression exceeds 256 tokens");
112
+ return tokens;
113
+ }
114
+ var Parser = class {
115
+ constructor(tokens, columns) {
116
+ this.tokens = tokens;
117
+ this.columns = /* @__PURE__ */ new Map();
118
+ for (const column of columns) {
119
+ for (const alias of [column.name, column.columnName]) {
120
+ const previous = this.columns.get(alias);
121
+ if (previous && previous.columnName !== column.columnName) {
122
+ throw new Error(`ambiguous check column '${alias}'`);
123
+ }
124
+ this.columns.set(alias, column);
125
+ }
126
+ }
127
+ }
128
+ index = 0;
129
+ depth = 0;
130
+ columns;
131
+ parse() {
132
+ const expression = this.parseOr();
133
+ this.expect("end", "end of expression");
134
+ return expression;
135
+ }
136
+ parseOr() {
137
+ let left = this.parseAnd();
138
+ while (this.matchKeyword("or")) left = `(${left} OR ${this.parseAnd()})`;
139
+ return left;
140
+ }
141
+ parseAnd() {
142
+ let left = this.parseNot();
143
+ while (this.matchKeyword("and")) left = `(${left} AND ${this.parseNot()})`;
144
+ return left;
145
+ }
146
+ parseNot() {
147
+ if (this.matchKeyword("not")) return `(NOT ${this.parseNot()})`;
148
+ return this.parsePrimary();
149
+ }
150
+ parsePrimary() {
151
+ if (this.peek().kind === "lparen") {
152
+ if (++this.depth > 32) throw new Error("check expression nesting exceeds 32 levels");
153
+ this.advance();
154
+ const expression = this.parseOr();
155
+ this.expect("rparen", "')'");
156
+ this.depth--;
157
+ return `(${expression})`;
158
+ }
159
+ return this.parseComparison();
160
+ }
161
+ parseComparison() {
162
+ const left = this.parseValue();
163
+ if (this.matchKeyword("is")) {
164
+ const negate = this.matchKeyword("not");
165
+ this.expectKeyword("null");
166
+ return `${left.sql} IS ${negate ? "NOT " : ""}NULL`;
167
+ }
168
+ if (this.matchKeyword("between")) {
169
+ const lower = this.parseValue();
170
+ this.expectKeyword("and");
171
+ const upper = this.parseValue();
172
+ return `${left.sql} BETWEEN ${lower.sql} AND ${upper.sql}`;
173
+ }
174
+ if (this.matchKeyword("in")) {
175
+ this.expect("lparen", "'(' after IN");
176
+ const values = [this.parseValue()];
177
+ while (this.peek().kind === "comma") {
178
+ this.advance();
179
+ values.push(this.parseValue());
180
+ }
181
+ this.expect("rparen", "')' after IN values");
182
+ if (values.some((value) => !value.literal)) throw new Error("IN values must be literals");
183
+ return `${left.sql} IN (${values.map((value) => value.sql).join(", ")})`;
184
+ }
185
+ const operator = this.expect("operator", "a comparison operator");
186
+ const right = this.parseValue();
187
+ if (operator.value === "~" || operator.value === "!~") {
188
+ if (left.column && left.column.type !== "text") throw new Error("regex checks require a text column");
189
+ if (!right.literal) throw new Error("regex pattern must be a literal");
190
+ }
191
+ return `${left.sql} ${operator.value} ${right.sql}`;
192
+ }
193
+ parseValue() {
194
+ const token = this.advance();
195
+ if (token.kind === "string") return { sql: quoteLiteral(token.value), literal: true };
196
+ if (token.kind === "number") {
197
+ const number = Number(token.value);
198
+ if (!Number.isFinite(number) || Number.isInteger(number) && !Number.isSafeInteger(number)) {
199
+ throw new Error(`unsafe numeric literal at position ${token.position}`);
200
+ }
201
+ return { sql: token.value, literal: true };
202
+ }
203
+ if (token.kind !== "identifier") throw new Error(`expected a column or literal at position ${token.position}`);
204
+ const keyword = token.value.toLowerCase();
205
+ if (keyword === "true" || keyword === "false" || keyword === "null") return { sql: keyword.toUpperCase(), literal: true };
206
+ if (keyword === "btrim") {
207
+ this.expect("lparen", "'(' after btrim");
208
+ const column2 = this.parseColumn();
209
+ this.expect("rparen", "')' after btrim column");
210
+ if (column2.type !== "text") throw new Error("btrim requires a text column");
211
+ return { sql: `btrim(${quoteIdentifier(column2.columnName)})`, column: column2 };
212
+ }
213
+ const column = this.columns.get(token.value);
214
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
215
+ return { sql: quoteIdentifier(column.columnName), column };
216
+ }
217
+ parseColumn() {
218
+ const token = this.expect("identifier", "a column name");
219
+ const column = this.columns.get(token.value);
220
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
221
+ return column;
222
+ }
223
+ peek() {
224
+ return this.tokens[this.index];
225
+ }
226
+ advance() {
227
+ const token = this.peek();
228
+ if (token.kind !== "end") this.index++;
229
+ return token;
230
+ }
231
+ matchKeyword(keyword) {
232
+ if (this.peek().kind !== "identifier" || this.peek().value.toLowerCase() !== keyword) return false;
233
+ this.advance();
234
+ return true;
235
+ }
236
+ expectKeyword(keyword) {
237
+ if (!this.matchKeyword(keyword)) throw new Error(`expected '${keyword}' at position ${this.peek().position}`);
238
+ }
239
+ expect(kind, description) {
240
+ const token = this.peek();
241
+ if (token.kind !== kind) throw new Error(`expected ${description} at position ${token.position}`);
242
+ return this.advance();
243
+ }
244
+ };
245
+ function compileCheckExpression(source, columns) {
246
+ return new Parser(tokenize(source), columns).parse();
247
+ }
248
+ var policyVariantSchema = z.object({
249
+ /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
250
+ when: z.string().min(1).max(1e3),
251
+ /** Exactly one of: allow-all bypass, or a row predicate. */
252
+ allow: z.literal(true).optional(),
253
+ policy: z.string().min(1).max(2e3).optional()
254
+ }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
255
+ message: "A variant declares exactly one of allow: true or policy"
256
+ });
257
+ var policyExpressionSchema = z.union([
258
+ z.string().min(1).max(2e3),
259
+ z.object({
260
+ default: z.string().min(1).max(2e3),
261
+ variants: z.array(policyVariantSchema).max(10).default([])
262
+ })
263
+ ]);
264
+ var identifier = z.string().min(1).max(63).regex(/^[a-z][a-z0-9_]*$/);
265
+ var durationMs = z.number().int().positive().max(24 * 60 * 60 * 1e3);
266
+ var RESOLVED_VIEW_SYSTEM_COLUMNS = {
267
+ writebackStatus: { name: "writebackStatus", columnName: "_writeback_status", type: "text" },
268
+ writebackError: { name: "writebackError", columnName: "_writeback_error", type: "text" }
269
+ };
270
+ var RESOLVED_SOURCE_SYSTEM_COLUMNS = {
271
+ tombstoned: { name: "sysTombstoned", columnName: "_tombstoned" },
272
+ fetchedAt: { name: "sysFetchedAt", columnName: "_fetched_at" },
273
+ writebackStatus: { name: "sysWritebackStatus", columnName: "_writeback_status" },
274
+ writebackError: { name: "sysWritebackError", columnName: "_writeback_error" },
275
+ writebackAt: { name: "sysWritebackAt", columnName: "_writeback_at" }
276
+ };
277
+ var RESOLVED_VIEW_CELL_PARTS = ["source", "at", "by", "conflicts"];
278
+ /* @__PURE__ */ new Set([
279
+ ...Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName]),
280
+ ...Object.values(RESOLVED_SOURCE_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName])
281
+ ]);
282
+ var COMPARATORS = ["latest", "highest", "lowest", "priority", "nonNullFirst", "custom"];
283
+ var canonicalFunctionRefSchema = z.object({
284
+ /** `managed` = a Managed Function id/slug; `native` = an in-process Atlas function (reserved). */
285
+ kind: z.enum(["managed", "native"]),
286
+ id: z.string().min(1).max(200)
287
+ }).strict();
288
+ var canonicalFetchShapeSchema = z.union([
289
+ z.object({ shape: z.literal("single") }).strict(),
290
+ z.object({ shape: z.literal("batch"), maxKeys: z.number().int().min(2).max(500) }).strict()
291
+ ]);
292
+ var canonicalResolvedSourceSchema = z.object({
293
+ name: identifier,
294
+ kind: z.enum(["manual", "etl", "prefetch"]),
295
+ /** Backing relation in this namespace: an internal table (manual/prefetch) or a synced table (etl). */
296
+ table: identifier,
297
+ /** Resolved columns (logical names) this source supplies — the primary key is implicit. */
298
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
299
+ /** etl: logical timestamptz/date column on the synced table used as every cell's updated_at. */
300
+ updatedAt: z.string().min(1).max(63).optional(),
301
+ /** prefetch: resolved column holding the source system's key (may be the primary key). */
302
+ key: z.string().min(1).max(63).optional(),
303
+ fetch: canonicalFetchShapeSchema.optional(),
304
+ function: canonicalFunctionRefSchema.optional(),
305
+ prefetchDefaults: z.object({
306
+ maxStalenessMs: durationMs,
307
+ timeoutMs: durationMs,
308
+ onError: z.enum(["fallback", "fail"])
309
+ }).strict().optional(),
310
+ writeback: z.object({
311
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
312
+ defaultMode: z.enum(["sync", "async"]),
313
+ timeoutMs: durationMs,
314
+ /** Remove confirmed cells from the manual source so a stale edit cannot shadow the source. */
315
+ clearManualOnConfirm: z.boolean()
316
+ }).strict().optional()
317
+ }).strict();
318
+ var canonicalResolveRuleSchema = z.object({
319
+ column: z.string().min(1).max(63),
320
+ comparator: z.enum(COMPARATORS),
321
+ /** Source names, in tie-break order. */
322
+ candidates: z.array(identifier).min(1).max(16),
323
+ /** custom only: SQL ORDER BY key over value / updated_at / source / actor / ord. */
324
+ orderBy: z.string().min(1).max(2e3).optional()
325
+ }).strict();
326
+ var canonicalResolvedSchema = z.object({
327
+ sources: z.array(canonicalResolvedSourceSchema).min(1).max(16),
328
+ /** One rule per resolved (non-pk) column; documents the generated view for tooling. */
329
+ resolve: z.array(canonicalResolveRuleSchema).max(500),
330
+ /** Sources whose tombstone hides the resolved row (v1: the manual source only). */
331
+ deletedBy: z.array(identifier).max(1).default([]),
332
+ /**
333
+ * Materialized: the view reads an indexed internal table (`table`) that the
334
+ * data plane keeps in step with `compute`, the internal view holding the
335
+ * resolution query. Omitted when the view computes on read.
336
+ */
337
+ materialized: z.object({ table: identifier, compute: identifier }).strict().optional(),
338
+ /** Write policies evaluated against the RESOLVED row (reads use the view's read policy). */
339
+ policies: z.object({
340
+ write: policyExpressionSchema.optional(),
341
+ insert: policyExpressionSchema.optional(),
342
+ update: policyExpressionSchema.optional()
343
+ }).strict().default({})
344
+ }).strict();
345
+ function validateResolvedView({ view, tables, views = [] }) {
346
+ const resolved = view.resolved;
347
+ if (!resolved) return [];
348
+ const errors = [];
349
+ const fail = (message) => errors.push(`resolved table '${view.view}': ${message}`);
350
+ const pkColumn = view.primaryKey?.length === 1 ? view.columns.find((c) => c.columnName === view.primaryKey?.[0]) : void 0;
351
+ if (!pkColumn) {
352
+ fail("requires exactly one primary-key column");
353
+ return errors;
354
+ }
355
+ const systemNames = new Set(Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).map((c) => c.name));
356
+ const scope = {
357
+ view,
358
+ resolved,
359
+ pkColumn,
360
+ dataColumns: new Map(view.columns.filter((c) => !systemNames.has(c.name) && c.cell === void 0).map((c) => [c.name, c])),
361
+ sourceByName: /* @__PURE__ */ new Map(),
362
+ fail
363
+ };
364
+ if (resolved.sources.filter((source) => source.kind === "manual").length !== 1) fail("requires exactly one manual source");
365
+ const tableByName = new Map(tables.map((table) => [table.table, table]));
366
+ for (const source of resolved.sources) {
367
+ if (scope.sourceByName.has(source.name)) fail(`duplicate source '${source.name}'`);
368
+ scope.sourceByName.set(source.name, source);
369
+ const table = tableByName.get(source.table);
370
+ if (!table) fail(`source '${source.name}' references unknown table '${source.table}'`);
371
+ else validateSource({ scope, source, table });
372
+ }
373
+ validateRules(scope);
374
+ validateViewCells(scope);
375
+ if (resolved.materialized) validateMaterialized({ scope, tableByName, views });
376
+ for (const name of resolved.deletedBy) {
377
+ if (scope.sourceByName.get(name)?.kind !== "manual") fail(`deletedBy '${name}' must be the manual source`);
378
+ }
379
+ return errors;
380
+ }
381
+ function validateSource({ scope, source, table }) {
382
+ const { fail } = scope;
383
+ if (source.kind === "etl" && table.source === void 0) fail(`etl source '${source.name}' must reference a synced table`);
384
+ if (source.kind !== "etl" && (table.internal !== true || table.cellMetadata !== true)) {
385
+ fail(`${source.kind} source '${source.name}' must reference an internal table with cell metadata`);
386
+ }
387
+ const hasRev = table.columns.some((column) => column.cell?.part === "rev");
388
+ if (source.kind === "manual" && !hasRev) fail(`manual source '${source.name}' must carry '__rev' cell columns`);
389
+ if (source.kind === "prefetch" && hasRev) fail(`prefetch source '${source.name}' must not carry '__rev' cell columns`);
390
+ const byName = new Map(table.columns.map((c) => [c.name, c]));
391
+ validateSourceColumns({ scope, source, byName });
392
+ if (source.kind === "etl") {
393
+ const updatedAt = source.updatedAt === void 0 ? void 0 : byName.get(source.updatedAt);
394
+ if (source.updatedAt !== void 0 && updatedAt?.type !== "timestamptz" && updatedAt?.type !== "date") {
395
+ fail(`etl source '${source.name}' updatedAt must name a timestamptz/date column on '${source.table}'`);
396
+ }
397
+ }
398
+ validatePrefetchFields({ scope, source });
399
+ }
400
+ function validatePrefetchFields({ scope, source }) {
401
+ const { fail, pkColumn } = scope;
402
+ if (source.kind !== "prefetch") {
403
+ if (source.key || source.fetch || source.function || source.prefetchDefaults || source.writeback) {
404
+ fail(`only prefetch sources may declare key/fetch/function/prefetchDefaults/writeback ('${source.name}')`);
405
+ }
406
+ return;
407
+ }
408
+ if (!source.key || !source.fetch || !source.function || !source.prefetchDefaults) {
409
+ fail(`prefetch source '${source.name}' requires key, fetch, function and prefetchDefaults`);
410
+ } else if (source.key !== pkColumn.name && !source.columns.includes(source.key)) {
411
+ fail(`prefetch source '${source.name}' key '${source.key}' must be the primary key or one of its columns`);
412
+ }
413
+ for (const column of source.writeback?.columns ?? []) {
414
+ if (!source.columns.includes(column)) fail(`prefetch source '${source.name}' writes back '${column}', which it does not supply`);
415
+ }
416
+ }
417
+ function validateSourceColumns({ scope, source, byName }) {
418
+ const { fail, pkColumn, dataColumns } = scope;
419
+ for (const column of [pkColumn.name, ...source.columns]) {
420
+ const own = column === pkColumn.name ? pkColumn : dataColumns.get(column);
421
+ const theirs = byName.get(column);
422
+ if (!own) fail(`source '${source.name}' supplies unknown column '${column}'`);
423
+ else if (!theirs) fail(`source '${source.name}' table '${source.table}' has no column '${column}'`);
424
+ else if (JSON.stringify(theirs.type) !== JSON.stringify(own.type)) fail(`column '${column}' has a different type on source '${source.name}'`);
425
+ }
426
+ }
427
+ function validateRules({ resolved, pkColumn, dataColumns, sourceByName, fail }) {
428
+ const ruled = /* @__PURE__ */ new Set();
429
+ for (const rule of resolved.resolve) {
430
+ if (!dataColumns.has(rule.column) || rule.column === pkColumn.name) {
431
+ fail(`resolve rule targets unknown column '${rule.column}'`);
432
+ continue;
433
+ }
434
+ if (ruled.has(rule.column)) fail(`column '${rule.column}' has more than one resolve rule`);
435
+ ruled.add(rule.column);
436
+ if (rule.comparator === "custom" !== (rule.orderBy !== void 0)) {
437
+ fail(`column '${rule.column}': orderBy is required for custom comparators and only allowed there`);
438
+ }
439
+ if (new Set(rule.candidates).size !== rule.candidates.length) fail(`column '${rule.column}' repeats a candidate`);
440
+ for (const candidate of rule.candidates) {
441
+ const source = sourceByName.get(candidate);
442
+ if (!source) fail(`column '${rule.column}' names unknown candidate source '${candidate}'`);
443
+ else if (!source.columns.includes(rule.column)) fail(`column '${rule.column}' candidate '${candidate}' does not supply it`);
444
+ }
445
+ }
446
+ for (const column of dataColumns.keys()) {
447
+ if (column !== pkColumn.name && !ruled.has(column)) fail(`column '${column}' has no resolve rule`);
448
+ }
449
+ }
450
+ var VIEW_CELL_TYPES = {
451
+ source: "text",
452
+ at: "timestamptz",
453
+ by: "text",
454
+ conflicts: "jsonb"
455
+ };
456
+ function validateViewCells({ view, dataColumns, pkColumn, fail }) {
457
+ const expected = /* @__PURE__ */ new Map();
458
+ for (const column of dataColumns.values()) {
459
+ if (column.name === pkColumn.name) continue;
460
+ for (const part of RESOLVED_VIEW_CELL_PARTS) {
461
+ expected.set(cellColumnName(column.name, part), { part, columnName: cellColumnName(column.columnName, part) });
462
+ }
463
+ }
464
+ for (const column of view.columns) {
465
+ if (!column.cell) continue;
466
+ const want = expected.get(column.name);
467
+ if (!want || want.part !== column.cell.part || want.columnName !== column.columnName || cellColumnName(column.cell.of, column.cell.part) !== column.name) {
468
+ fail(`unexpected cell column '${column.name}'`);
469
+ continue;
470
+ }
471
+ if (column.type !== VIEW_CELL_TYPES[column.cell.part]) fail(`cell column '${column.name}' must be ${VIEW_CELL_TYPES[column.cell.part]}`);
472
+ expected.delete(column.name);
473
+ }
474
+ for (const name of expected.keys()) fail(`missing cell column '${name}'`);
475
+ }
476
+ var columnSignature = (columns) => JSON.stringify(columns.map((column) => [column.name, column.columnName, column.type]));
477
+ function validateMaterialized({ scope, tableByName, views }) {
478
+ const { view, resolved, fail } = scope;
479
+ const { table: tableName, compute: computeName } = resolved.materialized;
480
+ const table = tableByName.get(tableName);
481
+ if (!table || table.internal !== true || table.materializes !== view.view) {
482
+ fail(`materialized table '${tableName}' must be an internal table that materializes '${view.view}'`);
483
+ } else {
484
+ if (columnSignature(table.columns) !== columnSignature(view.columns)) fail(`materialized table '${tableName}' must have exactly the view's columns`);
485
+ if (JSON.stringify(table.primaryKey ?? []) !== JSON.stringify(view.primaryKey ?? [])) fail(`materialized table '${tableName}' must share the view's primary key`);
486
+ }
487
+ const compute = views.find((candidate) => candidate.view === computeName);
488
+ if (!compute || compute.internal !== true) fail(`compute view '${computeName}' must be an internal view`);
489
+ else if (columnSignature(compute.columns) !== columnSignature(view.columns)) fail(`compute view '${computeName}' must have exactly the view's columns`);
490
+ for (const source of resolved.sources) {
491
+ if (source.kind !== "etl") continue;
492
+ const read = tableByName.get(source.table)?.policies?.read;
493
+ const unconditional = typeof read === "string" ? read.trim() === "true" : read !== void 0 && read.default.trim() === "true" && read.variants.length === 0;
494
+ if (!unconditional) {
495
+ fail(`etl source '${source.name}' must have read policy 'true' to be materialized (the copy is shared by every caller)`);
496
+ }
497
+ }
498
+ }
499
+
500
+ // src/canonical/v2.ts
34
501
  var CANONICAL_FORMAT = 2;
35
502
  var IDENTIFIER_RE = /^[a-z][a-z0-9_]*$/;
36
- var identifier = z.string().min(1).max(63).regex(IDENTIFIER_RE);
503
+ var identifier2 = z.string().min(1).max(63).regex(IDENTIFIER_RE);
37
504
  var columnIdentifier = z.string().min(1).max(63).regex(COLUMN_IDENTIFIER_PATTERN);
38
505
  var COLUMN_TYPES = [
39
506
  "uuid",
@@ -49,14 +516,14 @@ var COLUMN_TYPES = [
49
516
  ];
50
517
  var columnTypeSchema = z.enum(COLUMN_TYPES);
51
518
  var canonicalEnumSchema = z.object({
52
- name: identifier,
519
+ name: identifier2,
53
520
  values: z.array(z.string().min(1).max(63)).min(1).max(100)
54
521
  });
55
522
  var canonicalColumnSchema = z.object({
56
523
  /** Property name in TS (camelCase); columnName is the Postgres name. */
57
524
  name: z.string().min(1).max(63),
58
525
  columnName: columnIdentifier,
59
- type: z.union([columnTypeSchema, z.object({ enum: identifier })]),
526
+ type: z.union([columnTypeSchema, z.object({ enum: identifier2 })]),
60
527
  nullable: z.boolean().default(true),
61
528
  unique: z.boolean().default(false),
62
529
  /** Literal default, or one of the allowlisted SQL functions. */
@@ -72,7 +539,14 @@ var canonicalColumnSchema = z.object({
72
539
  /** Migration hints — same semantics as v1. */
73
540
  renamedFrom: columnIdentifier.optional(),
74
541
  cast: z.string().max(200).optional(),
75
- deprecated: z.boolean().default(false)
542
+ deprecated: z.boolean().default(false),
543
+ /**
544
+ * Marks a system cell-metadata column (see CELL_PARTS in constants): part
545
+ * `part` of the cell of logical column `of`. Synthesized by authoring,
546
+ * never client-writable, absent from GraphQL scalar fields. Omitted on
547
+ * ordinary columns so their hashes are unchanged.
548
+ */
549
+ cell: z.object({ of: z.string().min(1).max(63), part: z.enum(CELL_PARTS) }).strict().optional()
76
550
  }).superRefine((column, ctx) => {
77
551
  if (column.onUpdateFn === void 0) return;
78
552
  if (typeof column.type !== "string" || column.type !== "timestamptz" && column.type !== "date") {
@@ -87,36 +561,28 @@ var canonicalLinkSchema = z.object({
87
561
  name: z.string().min(1).max(63),
88
562
  kind: z.enum(["toOne", "toMany", "toPlatformUser"]),
89
563
  /** Target table name (namespace-local). Absent for toPlatformUser. */
90
- target: identifier.optional(),
564
+ target: identifier2.optional(),
565
+ /** Owning namespace of an imported target; omitted for local links. */
566
+ namespace: identifier2.max(41).optional(),
91
567
  /** FK column on the owning side (toOne/toPlatformUser: on this table; toMany: on the target). */
92
568
  on: columnIdentifier,
93
569
  /** Referenced column on the target (default: target's PK / platform user `sub`). */
94
570
  references: columnIdentifier.optional(),
95
571
  /** enforce: true emits a real FK constraint (same-namespace toOne only). */
96
572
  enforce: z.boolean().default(false),
573
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
574
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
97
575
  description: z.string().max(500).optional()
98
576
  });
99
577
  var canonicalIndexSchema = z.object({
100
578
  columns: z.array(columnIdentifier).min(1),
101
579
  unique: z.boolean().default(false),
102
- name: identifier.optional()
580
+ name: identifier2.optional()
103
581
  });
104
- var policyVariantSchema = z.object({
105
- /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
106
- when: z.string().min(1).max(1e3),
107
- /** Exactly one of: allow-all bypass, or a row predicate. */
108
- allow: z.literal(true).optional(),
109
- policy: z.string().min(1).max(2e3).optional()
110
- }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
111
- message: "A variant declares exactly one of allow: true or policy"
112
- });
113
- var policyExpressionSchema = z.union([
114
- z.string().min(1).max(2e3),
115
- z.object({
116
- default: z.string().min(1).max(2e3),
117
- variants: z.array(policyVariantSchema).max(10).default([])
118
- })
119
- ]);
582
+ var canonicalCheckSchema = z.object({
583
+ name: identifier2,
584
+ expression: z.string().min(1).max(2e3)
585
+ }).strict();
120
586
  var canonicalPoliciesSchema = z.object({
121
587
  read: policyExpressionSchema.optional(),
122
588
  write: policyExpressionSchema.optional(),
@@ -147,7 +613,7 @@ function isSingleViewQuerySql(value) {
147
613
  return state === "normal" && !/\$[a-z_0-9]*\$/i.test(query);
148
614
  }
149
615
  var canonicalActionSchema = z.object({
150
- name: identifier,
616
+ name: identifier2,
151
617
  requires: z.string().max(1e3).optional(),
152
618
  params: z.record(z.string(), z.object({
153
619
  type: columnTypeSchema,
@@ -159,9 +625,9 @@ var canonicalActionSchema = z.object({
159
625
  });
160
626
  var canonicalCowMutationSchema = z.object({
161
627
  kind: z.enum(["override", "revert"]),
162
- name: identifier,
628
+ name: identifier2,
163
629
  /** Synced table (same namespace) the overlay copies from / falls back to. */
164
- synced: identifier,
630
+ synced: identifier2,
165
631
  /** Single-column primary key PROPERTY (TS camelCase, like column `name`) shared by overlay and synced. */
166
632
  pk: z.string().min(1).max(63),
167
633
  /** Override: contract properties copied INSERT…SELECT from synced (pk included). Empty for revert. */
@@ -189,23 +655,28 @@ var canonicalCowMutationSchema = z.object({
189
655
  }
190
656
  });
191
657
  var canonicalForeignKeySchema = z.object({
192
- name: identifier,
658
+ name: identifier2,
193
659
  columns: z.array(columnIdentifier).min(1).max(8),
194
- target: identifier,
660
+ target: identifier2,
195
661
  references: z.array(columnIdentifier).min(1).max(8),
196
- deferrable: z.enum(["initially-immediate", "initially-deferred"]).optional()
662
+ deferrable: z.enum(["initially-immediate", "initially-deferred"]).optional(),
663
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
664
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional()
197
665
  }).strict();
198
666
  var canonicalTableSchema = z.object({
199
- table: identifier,
667
+ table: identifier2,
668
+ displayName: z.string().trim().min(1).max(120).optional(),
200
669
  description: z.string().max(2e3).optional(),
201
670
  /** Table-level rename hint (new in v2). */
202
- renamedFrom: identifier.optional(),
203
- /** Synced/reflected read-only tables (`source: gold.*`) — v1 semantics. */
204
- source: z.string().regex(/^gold\.[a-z][a-z0-9_]*$/).optional(),
671
+ renamedFrom: identifier2.optional(),
672
+ /** Synced/reflected read-only tables (`source: schema.table`) — v1 semantics. */
673
+ source: z.string().regex(QUALIFIED_TABLE_PATTERN).optional(),
205
674
  columns: z.array(canonicalColumnSchema).default([]),
206
675
  primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
207
676
  links: z.array(canonicalLinkSchema).default([]),
208
677
  indexes: z.array(canonicalIndexSchema).default([]),
678
+ /** Omitted by old definitions, preserving their existing content hashes. */
679
+ checks: z.array(canonicalCheckSchema).max(100).optional(),
209
680
  policies: canonicalPoliciesSchema.default({}),
210
681
  /**
211
682
  * v1-conversion carry-over only. v2 has no action surface — the runtime
@@ -216,22 +687,55 @@ var canonicalTableSchema = z.object({
216
687
  /** Optional (not defaulted) so pre-CoW canonical documents keep byte-identical hashes. */
217
688
  cowMutations: z.array(canonicalCowMutationSchema).optional(),
218
689
  /** Omitted by old definitions, preserving their existing content hashes. */
219
- foreignKeys: z.array(canonicalForeignKeySchema).max(100).optional()
690
+ foreignKeys: z.array(canonicalForeignKeySchema).max(100).optional(),
691
+ /**
692
+ * Per-cell edit metadata (`cellMetadata: true` in authoring): every tracked
693
+ * column `c` carries typed `c__at` / `c__by` system columns (plus `c__rev`
694
+ * on a resolved table's internal sources), listed explicitly in `columns`
695
+ * with a `cell` marker so DDL and migrations treat them as ordinary columns.
696
+ * Omitted when off so existing definitions hash unchanged.
697
+ */
698
+ cellMetadata: z.literal(true).optional(),
699
+ /**
700
+ * System-owned backing table of a resolved table (its manual or prefetch
701
+ * source). Internal tables get DDL and IR metadata but no GraphQL surface;
702
+ * only the data plane writes them. Omitted when false.
703
+ */
704
+ internal: z.literal(true).optional(),
705
+ /**
706
+ * The materialized copy of resolved table `materializes` (internal): the
707
+ * same columns as that view, including its cell parts, maintained by the
708
+ * data plane. Omitted otherwise.
709
+ */
710
+ materializes: identifier2.optional()
220
711
  });
712
+ var MAX_VIEW_QUERY = 1e5;
713
+ var MAX_RESOLVED_VIEW_QUERY = 5e6;
221
714
  var canonicalViewSchema = z.object({
222
- view: identifier,
715
+ view: identifier2,
223
716
  description: z.string().max(2e3).optional(),
224
717
  columns: z.array(canonicalColumnSchema).min(1),
225
718
  /** Logical identity for GraphQL only; PostgreSQL views have no PK constraint. */
226
719
  primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
227
720
  links: z.array(canonicalLinkSchema).default([]),
228
721
  policies: z.object({ read: policyExpressionSchema }).strict(),
229
- query: z.string().min(1).max(1e5).refine(isSingleViewQuerySql, {
722
+ query: z.string().min(1).max(MAX_RESOLVED_VIEW_QUERY).refine(isSingleViewQuerySql, {
230
723
  message: "view query must be one SELECT/WITH statement without comments or dollar-quoted bodies"
231
724
  }),
232
725
  /** Namespace-local logical relation names, sorted for deterministic hashing. */
233
- dependencies: z.array(identifier).max(500)
726
+ dependencies: z.array(identifier2).max(500),
727
+ /**
728
+ * Present when this view is a resolved table (defineResolvedTable): the
729
+ * multi-source metadata behind its generated query. Omitted otherwise so
730
+ * existing views hash unchanged.
731
+ */
732
+ resolved: canonicalResolvedSchema.optional(),
733
+ /** System-owned view (a materialized resolved table's compute view): no GraphQL surface. */
734
+ internal: z.literal(true).optional()
234
735
  }).superRefine((view, ctx) => {
736
+ if (view.resolved === void 0 && view.query.length > MAX_VIEW_QUERY) {
737
+ ctx.addIssue({ code: "custom", path: ["query"], message: `view query must be at most ${MAX_VIEW_QUERY} characters` });
738
+ }
235
739
  for (const [index, column] of view.columns.entries()) {
236
740
  if (column.default !== void 0 || column.defaultFn !== void 0) {
237
741
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare a default` });
@@ -246,20 +750,91 @@ var canonicalViewSchema = z.object({
246
750
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare migration hints` });
247
751
  }
248
752
  }
753
+ if (view.resolved === void 0 && view.internal !== true) {
754
+ for (const [index, column] of view.columns.entries()) {
755
+ if (column.cell) ctx.addIssue({ code: "custom", path: ["columns", index], message: `only resolved tables carry cell columns ('${column.name}')` });
756
+ }
757
+ }
249
758
  for (const [index, link] of view.links.entries()) {
250
759
  if (link.enforce) {
251
760
  ctx.addIssue({ code: "custom", path: ["links", index, "enforce"], message: `view link '${link.name}' cannot enforce a foreign key` });
252
761
  }
762
+ if (link.onDelete !== void 0 || link.onUpdate !== void 0) {
763
+ ctx.addIssue({ code: "custom", path: ["links", index], message: `view link '${link.name}' cannot declare referential actions` });
764
+ }
253
765
  }
254
766
  });
255
- z.object({
767
+ var CELL_PART_TYPES = {
768
+ at: "timestamptz",
769
+ by: "text",
770
+ rev: "uuid",
771
+ source: "text",
772
+ conflicts: "jsonb"
773
+ };
774
+ function trackedCellColumns(table) {
775
+ const pk = new Set(table.primaryKey ?? []);
776
+ return table.columns.filter((column) => column.cell === void 0 && !pk.has(column.columnName) && column.onUpdateFn === void 0);
777
+ }
778
+ var SUFFIXES = Object.values(CELL_PART_SUFFIX);
779
+ function validateCellMetadata(table, index, ctx) {
780
+ const fail = (message, path = ["tables", index]) => ctx.addIssue({ code: "custom", path, message });
781
+ const cells = table.columns.flatMap((column, position) => column.cell ? [{ column, position, cell: column.cell }] : []);
782
+ if (table.materializes !== void 0) return;
783
+ if (table.cellMetadata !== true) {
784
+ for (const { position } of cells) fail(`cell-metadata columns require cellMetadata on table '${table.table}'`, ["tables", index, "columns", position]);
785
+ return;
786
+ }
787
+ if (table.source !== void 0) {
788
+ fail(`synced table '${table.table}' cannot track cell metadata`);
789
+ return;
790
+ }
791
+ const tracked = trackedCellColumns(table);
792
+ const byName = new Map(tracked.map((column) => [column.name, column]));
793
+ const withRev = cells.some(({ cell }) => cell.part === "rev");
794
+ if (withRev && table.internal !== true) fail(`only a resolved table's internal sources carry '__rev' cell columns ('${table.table}')`);
795
+ const seen = /* @__PURE__ */ new Set();
796
+ for (const { column, position, cell } of cells) {
797
+ const path = ["tables", index, "columns", position];
798
+ const owner = byName.get(cell.of);
799
+ if (!owner) {
800
+ fail(`cell column '${column.name}' belongs to '${cell.of}', which is not a tracked column`, path);
801
+ continue;
802
+ }
803
+ 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);
804
+ if (column.name !== cellColumnName(owner.name, cell.part) || column.columnName !== cellColumnName(owner.columnName, cell.part)) {
805
+ fail(`cell column for '${owner.name}' ${cell.part} must be named '${cellColumnName(owner.name, cell.part)}' / '${cellColumnName(owner.columnName, cell.part)}'`, path);
806
+ }
807
+ if (column.type !== CELL_PART_TYPES[cell.part] || !column.nullable || column.unique || column.default !== void 0 || column.defaultFn !== void 0) {
808
+ fail(`cell column '${column.name}' must be a nullable, default-less ${CELL_PART_TYPES[cell.part]}`, path);
809
+ }
810
+ const key = `${cell.of}:${cell.part}`;
811
+ if (seen.has(key)) fail(`duplicate cell column '${column.name}'`, path);
812
+ seen.add(key);
813
+ }
814
+ for (const column of tracked) {
815
+ if (column.columnName.length > MAX_TRACKED_COLUMN_NAME) {
816
+ fail(`column '${column.columnName}' is too long to track cell metadata (max ${MAX_TRACKED_COLUMN_NAME} characters)`);
817
+ }
818
+ if (SUFFIXES.some((suffix) => column.columnName.endsWith(suffix))) {
819
+ fail(`column '${column.columnName}' ends in a reserved cell-metadata suffix (${SUFFIXES.join(", ")})`);
820
+ }
821
+ for (const part of withRev ? ["at", "by", "rev"] : ["at", "by"]) {
822
+ if (!seen.has(`${column.name}:${part}`)) fail(`tracked column '${column.name}' is missing its '${cellColumnName(column.columnName, part)}' cell column`);
823
+ }
824
+ }
825
+ }
826
+ var exportGateSchema = z.union([z.literal(true), z.object({ capability: z.string().min(1) }).strict(), z.object({ role: z.string().min(1) }).strict()]);
827
+ var relationExportSchema = z.object({ read: exportGateSchema, write: exportGateSchema.optional() }).strict();
828
+ var localDefinitionSchema = z.object({
256
829
  definition_format: z.literal(CANONICAL_FORMAT),
257
- namespace: identifier.max(41),
830
+ namespace: identifier2.max(41),
258
831
  description: z.string().max(2e3).optional(),
259
832
  enums: z.array(canonicalEnumSchema).default([]),
260
833
  tables: z.array(canonicalTableSchema).min(0).max(500),
261
834
  /** Optional to preserve byte-identical hashes for pre-view canonical v2 documents. */
262
835
  views: z.array(canonicalViewSchema).max(500).optional(),
836
+ /** Target-owned cross-namespace access contract, using existing namespace grants. */
837
+ exports: z.record(identifier2, relationExportSchema).optional(),
263
838
  /** Verbatim custom-roles grammar (@sequenceholdings/custom-roles-manifest). */
264
839
  capabilities: z.object({
265
840
  roles: z.unknown().optional(),
@@ -272,6 +847,7 @@ z.object({
272
847
  ctx.addIssue({ code: "custom", path: ["tables", index, "table"], message: `duplicate relation '${table.table}'` });
273
848
  }
274
849
  seen.add(table.table);
850
+ validateCellMetadata(table, index, ctx);
275
851
  if (table.source !== void 0) {
276
852
  for (const [columnIndex, column] of table.columns.entries()) {
277
853
  if (column.onUpdateFn !== void 0) {
@@ -285,12 +861,41 @@ z.object({
285
861
  }
286
862
  }
287
863
  const fkTables = new Map(definition.tables.map((table) => [table.table, table]));
864
+ const relations = /* @__PURE__ */ new Set([...fkTables.keys(), ...(definition.views ?? []).map((view) => view.view)]);
865
+ for (const name of Object.keys(definition.exports ?? {})) {
866
+ if (!relations.has(name)) ctx.addIssue({ code: "custom", path: ["exports", name], message: `export '${name}' is not a local object` });
867
+ }
288
868
  for (const [tableIndex, table] of definition.tables.entries()) {
869
+ for (const [linkIndex, link] of table.links.entries()) {
870
+ if (link.enforce && link.namespace !== void 0 && link.namespace !== definition.namespace) {
871
+ ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", linkIndex], message: "physical foreign keys require a local target; use an ORM link without enforce" });
872
+ }
873
+ }
289
874
  const names = /* @__PURE__ */ new Set([
290
875
  ...table.primaryKey?.length ? [`${table.table}_pkey`] : [],
291
876
  ...table.columns.filter((column) => column.unique && !(table.primaryKey?.length === 1 && table.primaryKey[0] === column.columnName)).map((column) => `${table.table}_${column.columnName}_unique`),
292
877
  ...table.links.filter((link) => link.enforce).map((link) => `fk_${table.table}_${link.name}`)
293
878
  ]);
879
+ for (const [index, link] of table.links.entries()) {
880
+ if ((link.onDelete !== void 0 || link.onUpdate !== void 0) && (!link.enforce || link.kind !== "toOne")) {
881
+ ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", index], message: "referential actions require an enforced toOne link" });
882
+ }
883
+ if (link.onDelete === "set null" || link.onUpdate === "set null") {
884
+ const source = table.columns.find((column) => column.columnName === link.on);
885
+ 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" });
886
+ }
887
+ }
888
+ for (const [index, check] of (table.checks ?? []).entries()) {
889
+ const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "checks", index], message });
890
+ if (table.source) fail("synced tables cannot declare checks");
891
+ if (names.has(check.name)) fail(`duplicate constraint '${check.name}'`);
892
+ names.add(check.name);
893
+ try {
894
+ compileCheckExpression(check.expression, table.columns);
895
+ } catch (error) {
896
+ fail(error instanceof Error ? error.message : String(error));
897
+ }
898
+ }
294
899
  for (const [index, fk] of (table.foreignKeys ?? []).entries()) {
295
900
  const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "foreignKeys", index], message });
296
901
  if (names.has(fk.name)) fail(`duplicate foreign key '${fk.name}'`);
@@ -308,10 +913,18 @@ z.object({
308
913
  if (!sourceColumn || !targetColumn) fail("foreign key references an unknown column");
309
914
  else if (JSON.stringify(sourceColumn.type) !== JSON.stringify(targetColumn.type)) fail("foreign key column types must match");
310
915
  }
916
+ if (fk.onDelete === "set null" || fk.onUpdate === "set null") {
917
+ 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");
918
+ }
311
919
  const uniqueKeys = [target.primaryKey ?? [], ...target.indexes.filter((index2) => index2.unique).map((index2) => index2.columns), ...target.columns.filter((column) => column.unique).map((column) => [column.columnName])];
312
920
  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");
313
921
  }
314
922
  }
923
+ for (const [viewIndex, view] of (definition.views ?? []).entries()) {
924
+ for (const message of validateResolvedView({ view, tables: definition.tables, views: definition.views ?? [] })) {
925
+ ctx.addIssue({ code: "custom", path: ["views", viewIndex, "resolved"], message });
926
+ }
927
+ }
315
928
  const tableByName = new Map(definition.tables.map((table) => [table.table, table]));
316
929
  for (const [tableIndex, table] of definition.tables.entries()) {
317
930
  const cowMutations = table.cowMutations ?? [];
@@ -427,11 +1040,18 @@ z.object({
427
1040
  };
428
1041
  for (const view of views) visit(view.view, []);
429
1042
  });
1043
+ localDefinitionSchema.safeExtend({
1044
+ /** Flattened, pinned snapshots. Imported relations never participate in this namespace's DDL. */
1045
+ imports: z.array(localDefinitionSchema).max(32).optional()
1046
+ });
430
1047
 
431
1048
  // src/ir/index.ts
432
- var IR_VERSION = 2;
433
1049
  var LEGACY_IR_VERSION = 1;
434
- var irVersionSchema = z.union([z.literal(LEGACY_IR_VERSION), z.literal(IR_VERSION)]);
1050
+ var GUARDED_IR_VERSION = 2;
1051
+ var COMPOSED_IR_VERSION = 3;
1052
+ var SQL_IR_VERSION = 4;
1053
+ var RUNTIME_SQL_IR_VERSION = 5;
1054
+ var irVersionSchema = z.union([z.literal(LEGACY_IR_VERSION), z.literal(GUARDED_IR_VERSION), z.literal(COMPOSED_IR_VERSION), z.literal(SQL_IR_VERSION), z.literal(RUNTIME_SQL_IR_VERSION)]);
435
1055
  z.object({ irVersion: irVersionSchema });
436
1056
  var CLAIMS_CONTRACT = {
437
1057
  sub: "string",
@@ -475,8 +1095,8 @@ var predIrSchema = z.lazy(
475
1095
  value: z.number(),
476
1096
  where: predIrSchema.optional()
477
1097
  }),
478
- z.object({ kind: z.literal("capability"), key: z.string() }),
479
- z.object({ kind: z.literal("role"), key: z.string() }),
1098
+ z.object({ kind: z.literal("capability"), key: z.string(), namespace: z.string().optional() }),
1099
+ z.object({ kind: z.literal("role"), key: z.string(), namespace: z.string().optional() }),
480
1100
  z.object({ kind: z.literal("dynamicFilter"), slot: z.string() }),
481
1101
  z.object({ kind: z.literal("const"), value: z.boolean() })
482
1102
  ])
@@ -504,6 +1124,21 @@ var selectionIrSchema = z.lazy(
504
1124
  () => z.object({
505
1125
  typename: z.string(),
506
1126
  columns: z.array(z.object({ alias: z.string(), column: z.string() })),
1127
+ cells: z.object({
1128
+ alias: z.string(),
1129
+ typename: z.string(),
1130
+ fields: z.array(z.object({
1131
+ alias: z.string(),
1132
+ column: z.string(),
1133
+ typename: z.string(),
1134
+ parts: z.array(z.object({
1135
+ alias: z.string(),
1136
+ part: z.enum(["source", "at", "by", "conflicts"]),
1137
+ fields: z.array(z.object({ alias: z.string(), field: z.enum(["source", "at", "value"]) })).optional(),
1138
+ typename: z.string().optional()
1139
+ }))
1140
+ }))
1141
+ }).optional(),
507
1142
  relations: z.array(z.object({
508
1143
  alias: z.string(),
509
1144
  link: z.string(),
@@ -525,6 +1160,11 @@ var selectionIrSchema = z.lazy(
525
1160
  })
526
1161
  );
527
1162
  var includeIfSchema = z.object({ variable: z.string(), negated: z.boolean() });
1163
+ var prefetchPlanIrSchema = z.object({
1164
+ source: z.string(),
1165
+ maxStalenessMs: z.number().int().positive().optional(),
1166
+ key: z.union([z.object({ one: valueIrSchema }), z.object({ many: valueIrSchema })])
1167
+ });
528
1168
  var selectRootSchema = z.object({
529
1169
  kind: z.literal("select"),
530
1170
  alias: z.string(),
@@ -536,7 +1176,8 @@ var selectRootSchema = z.object({
536
1176
  distinctOn: z.union([z.array(z.string()), z.object({ slot: z.string() })]).optional(),
537
1177
  limit: limitIrSchema,
538
1178
  offset: z.object({ variable: z.string().optional(), value: z.number().int().optional() }).optional(),
539
- includeIf: includeIfSchema.optional()
1179
+ includeIf: includeIfSchema.optional(),
1180
+ prefetch: z.array(prefetchPlanIrSchema).optional()
540
1181
  });
541
1182
  var byPkRootSchema = z.object({
542
1183
  kind: z.literal("byPk"),
@@ -546,7 +1187,8 @@ var byPkRootSchema = z.object({
546
1187
  pk: z.array(z.object({ column: z.string(), value: valueIrSchema })).min(1),
547
1188
  /** Policy predicate — ANDed with the PK match. */
548
1189
  where: predIrSchema,
549
- includeIf: includeIfSchema.optional()
1190
+ includeIf: includeIfSchema.optional(),
1191
+ prefetch: z.array(prefetchPlanIrSchema).optional()
550
1192
  });
551
1193
  var aggregateRootSchema = z.object({
552
1194
  kind: z.literal("aggregate"),
@@ -604,7 +1246,20 @@ var mutationRootSchema = z.object({
604
1246
  * coalesce view falls back to synced. Both are gated on a matching synced
605
1247
  * row and carry the write policy in `where` like update/delete.
606
1248
  */
607
- op: z.enum(["insert", "insertOne", "update", "updateByPk", "delete", "deleteByPk", "cowOverride", "cowRevert"]),
1249
+ op: z.enum(["insert", "insertOne", "update", "updateByPk", "delete", "deleteByPk", "cowOverride", "cowRevert", "resolvedWrite"]),
1250
+ /**
1251
+ * resolvedWrite: a write to a resolved table (`table` is its view). The
1252
+ * executor gates on the resolved row (write policy in `where`), writes only
1253
+ * the touched cells into the manual source, then re-checks `insertCheck`
1254
+ * against the resolved row. `revert` clears `revertColumns` from the manual
1255
+ * source; `delete` tombstones the row there.
1256
+ */
1257
+ resolvedAction: z.enum(["insert", "update", "delete", "revert"]).optional(),
1258
+ revertColumns: z.array(z.string()).optional(),
1259
+ /** `@writeback(source:, mode:)` directives on this root. */
1260
+ writeback: z.array(z.object({ source: z.string(), mode: z.enum(["sync", "async"]) })).optional(),
1261
+ /** `@localOnly(source:)` — writeback columns deliberately kept local for these sources. */
1262
+ localOnly: z.array(z.string()).optional(),
608
1263
  alias: z.string(),
609
1264
  table: z.string(),
610
1265
  /** CoW ops: logical name of the synced twin (read through its policy-filtered view). */
@@ -668,7 +1323,31 @@ var variableIrSchema = z.object({
668
1323
  /** Absent = no default declared; see {@link variableDefaultIrSchema}. */
669
1324
  defaultValue: variableDefaultIrSchema.optional()
670
1325
  });
1326
+ var sqlColumnSchema = z.object({ name: z.string(), type: z.enum(["text", "boolean", "integer", "bigint", "numeric", "double", "uuid", "date", "timestamptz"]), nullable: z.boolean() });
671
1327
  var compiledOperationSchema = z.object({
1328
+ language: z.literal("sql").optional(),
1329
+ /** Server-compiled object catalog and permission ceiling, never caller SQL. */
1330
+ sqlQuery: z.object({
1331
+ catalog: z.object({
1332
+ identity: z.string(),
1333
+ objects: z.array(z.object({
1334
+ ref: z.string(),
1335
+ table: z.string(),
1336
+ columns: z.array(sqlColumnSchema.extend({ type: z.string() })).min(1),
1337
+ scan: z.string().min(1),
1338
+ read: z.array(z.string()).min(1)
1339
+ }).strict()).min(1).max(256)
1340
+ }).strict(),
1341
+ read: z.array(z.string()).min(1).max(256),
1342
+ maxRows: z.number().int().min(1).max(1e4)
1343
+ }).strict().optional(),
1344
+ sql: z.object({
1345
+ text: z.string().min(1).max(1048576),
1346
+ columns: z.array(sqlColumnSchema).min(1).max(256),
1347
+ parameters: z.array(z.string()).max(128),
1348
+ read: z.array(z.string()).min(1).max(256),
1349
+ maxRows: z.number().int().min(1).max(1e4)
1350
+ }).strict().optional(),
672
1351
  irVersion: irVersionSchema,
673
1352
  name: z.string(),
674
1353
  opHash: z.string().regex(/^sha256:[0-9a-f]{64}$/),
@@ -680,8 +1359,16 @@ var compiledOperationSchema = z.object({
680
1359
  variables: z.array(variableIrSchema),
681
1360
  /** Every table the op touches — data-token scoping + audit. */
682
1361
  tableSet: z.array(z.string()).min(1),
683
- roots: z.array(rootIrSchema).min(1)
1362
+ roots: z.array(rootIrSchema)
684
1363
  }).superRefine((operation, ctx) => {
1364
+ if (operation.language === "sql") {
1365
+ const validPlan = operation.sqlQuery ? !operation.sql && operation.irVersion === RUNTIME_SQL_IR_VERSION : !!operation.sql && operation.irVersion === SQL_IR_VERSION;
1366
+ if (!validPlan || operation.kind !== "query" || operation.roots.length !== 0 || !operation.requires?.capability) {
1367
+ ctx.addIssue({ code: "custom", message: "SQL operations require a query-only v4 plan or v5 runtime contract, capability, and no GraphQL roots" });
1368
+ }
1369
+ } else if (operation.sql || operation.sqlQuery || operation.roots.length === 0) {
1370
+ ctx.addIssue({ code: "custom", message: "GraphQL operations require roots and cannot carry SQL" });
1371
+ }
685
1372
  for (const [index, root] of operation.roots.entries()) {
686
1373
  if (root.kind !== "mutation" || root.assertAffectedRows === void 0) continue;
687
1374
  if (operation.irVersion < 2 || operation.kind !== "mutation" || root.includeIf !== void 0) {
@@ -689,13 +1376,55 @@ var compiledOperationSchema = z.object({
689
1376
  }
690
1377
  }
691
1378
  });
1379
+ var resolvedSourceIrSchema = z.object({
1380
+ name: z.string(),
1381
+ kind: z.enum(["manual", "etl", "prefetch"]),
1382
+ /** Logical table key of the backing relation. */
1383
+ table: z.string(),
1384
+ columns: z.array(z.string()),
1385
+ key: z.string().optional(),
1386
+ fetch: z.union([
1387
+ z.object({ shape: z.literal("single") }),
1388
+ z.object({ shape: z.literal("batch"), maxKeys: z.number().int().positive() })
1389
+ ]).optional(),
1390
+ function: z.object({ kind: z.enum(["managed", "native"]), id: z.string() }).optional(),
1391
+ prefetchDefaults: z.object({
1392
+ maxStalenessMs: z.number().int().positive(),
1393
+ timeoutMs: z.number().int().positive(),
1394
+ onError: z.enum(["fallback", "fail"])
1395
+ }).optional(),
1396
+ writeback: z.object({
1397
+ columns: z.array(z.string()),
1398
+ defaultMode: z.enum(["sync", "async"]),
1399
+ timeoutMs: z.number().int().positive(),
1400
+ clearManualOnConfirm: z.boolean()
1401
+ }).optional()
1402
+ });
1403
+ var resolvedMetaIrSchema = z.object({
1404
+ /** Logical pk column of the resolved view (single-column). */
1405
+ pk: z.string(),
1406
+ /** Source name of the manual source. */
1407
+ manual: z.string(),
1408
+ sources: z.array(resolvedSourceIrSchema),
1409
+ deletedBy: z.array(z.string()),
1410
+ /**
1411
+ * Materialized: the view reads `table`, which the data plane refreshes from
1412
+ * the `compute` view (claims-gated) whenever it writes a source row.
1413
+ */
1414
+ materialized: z.object({ table: z.string(), compute: z.string() }).optional()
1415
+ });
692
1416
  var tableMetaIrSchema = z.object({
693
1417
  table: z.string(),
1418
+ namespace: z.string().optional(),
1419
+ dependencies: z.array(z.string()).optional(),
1420
+ foreignReferences: z.array(z.object({ column: z.string(), target: z.string(), targetColumn: z.string() })).optional(),
1421
+ exportRead: z.union([z.literal(true), z.object({ capability: z.string() }), z.object({ role: z.string() })]).optional(),
1422
+ exportWrite: z.union([z.literal(true), z.object({ capability: z.string() }), z.object({ role: z.string() })]).optional(),
694
1423
  schema: z.string(),
695
1424
  typename: z.string(),
696
1425
  /**
697
1426
  * True when statements over this relation evaluate a claims-gated synced
698
- * view: synced twins (`source: gold.*`) materialize as views whose baked
1427
+ * view: synced twins (`source: schema.table`) materialize as views whose baked
699
1428
  * policy reads `current_setting('request.jwt.claims')`, and namespace views
700
1429
  * inherit the gate transitively through their declared dependencies. The
701
1430
  * executor must stamp that GUC (transaction-scoped) before any statement
@@ -729,6 +1458,22 @@ var tableMetaIrSchema = z.object({
729
1458
  * `onUpdateFn`). Omitted when empty so pre-onUpdate artifacts still parse.
730
1459
  */
731
1460
  touchOnUpdate: z.array(z.string()).optional(),
1461
+ /**
1462
+ * Per-cell metadata: logical column → the logical names of its cell-part
1463
+ * columns (which are listed in `columns`, but never filterable, orderable or
1464
+ * writable). Tables stamp `at`/`by` (and a manual source `rev`) on every
1465
+ * write; resolved views expose `source`/`at`/`by`/`conflicts`. Omitted when
1466
+ * the relation tracks no cells.
1467
+ */
1468
+ cells: z.record(z.string(), z.object({
1469
+ at: z.string().optional(),
1470
+ by: z.string().optional(),
1471
+ rev: z.string().optional(),
1472
+ source: z.string().optional(),
1473
+ conflicts: z.string().optional()
1474
+ }).strict()).optional(),
1475
+ /** Resolved-table view metadata (sources, prefetch/writeback config) for the data plane. */
1476
+ resolved: resolvedMetaIrSchema.optional(),
732
1477
  constraints: z.array(z.object({ name: z.string(), columns: z.array(z.string()) })),
733
1478
  /** Depth/node caps for dynamic filter trees on this table. */
734
1479
  dynamicFilterMaxDepth: z.number().int().positive().default(6),
@@ -738,10 +1483,18 @@ z.object({
738
1483
  irVersion: irVersionSchema,
739
1484
  namespace: z.string(),
740
1485
  schemaHash: z.string(),
1486
+ ownSchemaHash: z.string().optional(),
1487
+ dependencies: z.record(z.string(), z.string()).optional(),
1488
+ readPolicies: z.record(z.string(), predIrSchema).optional(),
741
1489
  opsHash: z.string(),
1490
+ /** Apply-observed synced objects without a serving backing; not part of the authored schema hash. */
1491
+ unbackedTables: z.array(z.string()).optional(),
742
1492
  tables: z.record(z.string(), tableMetaIrSchema),
743
1493
  operations: z.record(z.string(), compiledOperationSchema)
744
1494
  }).superRefine((artifact, ctx) => {
1495
+ if (Object.keys(artifact.dependencies ?? {}).length > 0 && artifact.irVersion < COMPOSED_IR_VERSION) {
1496
+ ctx.addIssue({ code: "custom", path: ["irVersion"], message: "cross-namespace dependencies require IR v3" });
1497
+ }
745
1498
  for (const [name, operation] of Object.entries(artifact.operations)) {
746
1499
  if (operation.irVersion > artifact.irVersion) {
747
1500
  ctx.addIssue({ code: "custom", path: ["operations", name, "irVersion"], message: "operation requires a newer IR version than its artifact" });
@@ -757,7 +1510,7 @@ var IDENTIFIER_CHAR = /[a-zA-Z0-9_]/;
757
1510
  var NUMBER_PATTERN = /^-?\d+(\.\d+)?/;
758
1511
  var SCALAR_CLAIM_KEYS = Object.entries(CLAIMS_CONTRACT).filter(([, type]) => !type.endsWith("[]")).map(([key]) => key);
759
1512
  var ARRAY_CLAIM_KEYS = Object.entries(CLAIMS_CONTRACT).filter(([, type]) => type.endsWith("[]")).map(([key]) => key);
760
- function tokenize(source) {
1513
+ function tokenize2(source) {
761
1514
  const tokens = [];
762
1515
  let position = 0;
763
1516
  while (position < source.length) {
@@ -836,7 +1589,7 @@ function readString(source, start) {
836
1589
  }
837
1590
  throw new PolicyParseError("unterminated string literal", start);
838
1591
  }
839
- var Parser = class {
1592
+ var Parser2 = class {
840
1593
  constructor(tokens) {
841
1594
  this.tokens = tokens;
842
1595
  }
@@ -1010,7 +1763,7 @@ var Parser = class {
1010
1763
  function parsePolicy(source) {
1011
1764
  const trimmed = source.trim();
1012
1765
  if (trimmed.length === 0) throw new PolicyParseError("empty policy expression", 0);
1013
- return { source: trimmed, ast: new Parser(tokenize(trimmed)).parse() };
1766
+ return { source: trimmed, ast: new Parser2(tokenize2(trimmed)).parse() };
1014
1767
  }
1015
1768
 
1016
1769
  // src/predicate-v2/compile.ts