@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
package/dist/canonical.js CHANGED
@@ -1,14 +1,505 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  // src/canonical/v2.ts
4
+ var objectRef = z.string().max(255).regex(/^[a-z][a-z0-9_]{0,40}\/[A-Za-z_][A-Za-z0-9_]*$/, "Expected an explicit namespace/object reference (no wildcards)");
5
+ var functionRef = z.string().max(255).regex(/^[a-z][a-z0-9-]*$/, "Expected a function slug");
6
+ var refs = (schema) => z.array(schema).max(256).refine(
7
+ (values) => new Set(values).size === values.length,
8
+ "Duplicate dependency reference"
9
+ ).default([]);
10
+ var ontologyContractSchema = z.strictObject({
11
+ version: z.literal(1),
12
+ read: refs(objectRef),
13
+ write: refs(objectRef),
14
+ produce: refs(objectRef),
15
+ invoke: refs(functionRef)
16
+ }).refine((contract) => JSON.stringify(contract).length <= 4096, "Ontology contract exceeds the 4 KiB signed-context budget");
17
+ function readOntologyContract(manifest) {
18
+ if (!manifest || typeof manifest !== "object" || !("ontology" in manifest) || manifest.ontology === void 0) return void 0;
19
+ return ontologyContractSchema.parse(manifest.ontology);
20
+ }
21
+ var quoteIdentifier = (name) => `"${name.replaceAll('"', '""')}"`;
22
+ var quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
23
+
24
+ // src/checks/compile.ts
25
+ function tokenize(source) {
26
+ const tokens = [];
27
+ for (let position = 0; position < source.length; ) {
28
+ const char = source[position];
29
+ if (/\s/.test(char)) {
30
+ position++;
31
+ continue;
32
+ }
33
+ if (char === "(" || char === ")" || char === ",") {
34
+ tokens.push({ kind: char === "(" ? "lparen" : char === ")" ? "rparen" : "comma", value: char, position });
35
+ position++;
36
+ continue;
37
+ }
38
+ if (char === "'") {
39
+ const start = position++;
40
+ let value = "";
41
+ let closed = false;
42
+ while (position < source.length) {
43
+ if (source[position] !== "'") {
44
+ value += source[position++];
45
+ continue;
46
+ }
47
+ if (source[position + 1] === "'") {
48
+ value += "'";
49
+ position += 2;
50
+ continue;
51
+ }
52
+ position++;
53
+ closed = true;
54
+ break;
55
+ }
56
+ if (!closed) throw new Error(`unterminated string at position ${start}`);
57
+ if (/[\x00-\x1f\x7f]/.test(value)) throw new Error(`control character in string at position ${start}`);
58
+ tokens.push({ kind: "string", value, position: start });
59
+ continue;
60
+ }
61
+ const operator = /^(<=|>=|<>|!=|!~|=|<|>|~)/.exec(source.slice(position));
62
+ if (operator) {
63
+ tokens.push({ kind: "operator", value: operator[0] === "<>" ? "!=" : operator[0], position });
64
+ position += operator[0].length;
65
+ continue;
66
+ }
67
+ const number = /^-?\d+(?:\.\d+)?/.exec(source.slice(position));
68
+ if (number) {
69
+ tokens.push({ kind: "number", value: number[0], position });
70
+ position += number[0].length;
71
+ continue;
72
+ }
73
+ const identifier3 = /^[a-zA-Z_][a-zA-Z_0-9]*/.exec(source.slice(position));
74
+ if (identifier3) {
75
+ tokens.push({ kind: "identifier", value: identifier3[0], position });
76
+ position += identifier3[0].length;
77
+ continue;
78
+ }
79
+ throw new Error(`unexpected character '${char}' at position ${position}`);
80
+ }
81
+ tokens.push({ kind: "end", value: "", position: source.length });
82
+ if (tokens.length > 256) throw new Error("check expression exceeds 256 tokens");
83
+ return tokens;
84
+ }
85
+ var Parser = class {
86
+ constructor(tokens, columns) {
87
+ this.tokens = tokens;
88
+ this.columns = /* @__PURE__ */ new Map();
89
+ for (const column of columns) {
90
+ for (const alias of [column.name, column.columnName]) {
91
+ const previous = this.columns.get(alias);
92
+ if (previous && previous.columnName !== column.columnName) {
93
+ throw new Error(`ambiguous check column '${alias}'`);
94
+ }
95
+ this.columns.set(alias, column);
96
+ }
97
+ }
98
+ }
99
+ index = 0;
100
+ depth = 0;
101
+ columns;
102
+ parse() {
103
+ const expression = this.parseOr();
104
+ this.expect("end", "end of expression");
105
+ return expression;
106
+ }
107
+ parseOr() {
108
+ let left = this.parseAnd();
109
+ while (this.matchKeyword("or")) left = `(${left} OR ${this.parseAnd()})`;
110
+ return left;
111
+ }
112
+ parseAnd() {
113
+ let left = this.parseNot();
114
+ while (this.matchKeyword("and")) left = `(${left} AND ${this.parseNot()})`;
115
+ return left;
116
+ }
117
+ parseNot() {
118
+ if (this.matchKeyword("not")) return `(NOT ${this.parseNot()})`;
119
+ return this.parsePrimary();
120
+ }
121
+ parsePrimary() {
122
+ if (this.peek().kind === "lparen") {
123
+ if (++this.depth > 32) throw new Error("check expression nesting exceeds 32 levels");
124
+ this.advance();
125
+ const expression = this.parseOr();
126
+ this.expect("rparen", "')'");
127
+ this.depth--;
128
+ return `(${expression})`;
129
+ }
130
+ return this.parseComparison();
131
+ }
132
+ parseComparison() {
133
+ const left = this.parseValue();
134
+ if (this.matchKeyword("is")) {
135
+ const negate = this.matchKeyword("not");
136
+ this.expectKeyword("null");
137
+ return `${left.sql} IS ${negate ? "NOT " : ""}NULL`;
138
+ }
139
+ if (this.matchKeyword("between")) {
140
+ const lower = this.parseValue();
141
+ this.expectKeyword("and");
142
+ const upper = this.parseValue();
143
+ return `${left.sql} BETWEEN ${lower.sql} AND ${upper.sql}`;
144
+ }
145
+ if (this.matchKeyword("in")) {
146
+ this.expect("lparen", "'(' after IN");
147
+ const values = [this.parseValue()];
148
+ while (this.peek().kind === "comma") {
149
+ this.advance();
150
+ values.push(this.parseValue());
151
+ }
152
+ this.expect("rparen", "')' after IN values");
153
+ if (values.some((value) => !value.literal)) throw new Error("IN values must be literals");
154
+ return `${left.sql} IN (${values.map((value) => value.sql).join(", ")})`;
155
+ }
156
+ const operator = this.expect("operator", "a comparison operator");
157
+ const right = this.parseValue();
158
+ if (operator.value === "~" || operator.value === "!~") {
159
+ if (left.column && left.column.type !== "text") throw new Error("regex checks require a text column");
160
+ if (!right.literal) throw new Error("regex pattern must be a literal");
161
+ }
162
+ return `${left.sql} ${operator.value} ${right.sql}`;
163
+ }
164
+ parseValue() {
165
+ const token = this.advance();
166
+ if (token.kind === "string") return { sql: quoteLiteral(token.value), literal: true };
167
+ if (token.kind === "number") {
168
+ const number = Number(token.value);
169
+ if (!Number.isFinite(number) || Number.isInteger(number) && !Number.isSafeInteger(number)) {
170
+ throw new Error(`unsafe numeric literal at position ${token.position}`);
171
+ }
172
+ return { sql: token.value, literal: true };
173
+ }
174
+ if (token.kind !== "identifier") throw new Error(`expected a column or literal at position ${token.position}`);
175
+ const keyword = token.value.toLowerCase();
176
+ if (keyword === "true" || keyword === "false" || keyword === "null") return { sql: keyword.toUpperCase(), literal: true };
177
+ if (keyword === "btrim") {
178
+ this.expect("lparen", "'(' after btrim");
179
+ const column2 = this.parseColumn();
180
+ this.expect("rparen", "')' after btrim column");
181
+ if (column2.type !== "text") throw new Error("btrim requires a text column");
182
+ return { sql: `btrim(${quoteIdentifier(column2.columnName)})`, column: column2 };
183
+ }
184
+ const column = this.columns.get(token.value);
185
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
186
+ return { sql: quoteIdentifier(column.columnName), column };
187
+ }
188
+ parseColumn() {
189
+ const token = this.expect("identifier", "a column name");
190
+ const column = this.columns.get(token.value);
191
+ if (!column) throw new Error(`unknown check column '${token.value}'`);
192
+ return column;
193
+ }
194
+ peek() {
195
+ return this.tokens[this.index];
196
+ }
197
+ advance() {
198
+ const token = this.peek();
199
+ if (token.kind !== "end") this.index++;
200
+ return token;
201
+ }
202
+ matchKeyword(keyword) {
203
+ if (this.peek().kind !== "identifier" || this.peek().value.toLowerCase() !== keyword) return false;
204
+ this.advance();
205
+ return true;
206
+ }
207
+ expectKeyword(keyword) {
208
+ if (!this.matchKeyword(keyword)) throw new Error(`expected '${keyword}' at position ${this.peek().position}`);
209
+ }
210
+ expect(kind, description) {
211
+ const token = this.peek();
212
+ if (token.kind !== kind) throw new Error(`expected ${description} at position ${token.position}`);
213
+ return this.advance();
214
+ }
215
+ };
216
+ function compileCheckExpression(source, columns) {
217
+ return new Parser(tokenize(source), columns).parse();
218
+ }
4
219
 
5
220
  // src/constants.ts
6
221
  var COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/;
222
+ var MAX_IDENTIFIER_LENGTH = 63;
223
+ var QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\.[a-z][a-z0-9_]{0,62}$/;
224
+ var CELL_PARTS = ["at", "by", "rev", "source", "conflicts"];
225
+ var CELL_PART_SUFFIX = {
226
+ at: "__at",
227
+ by: "__by",
228
+ rev: "__rev",
229
+ source: "__src",
230
+ conflicts: "__lost"
231
+ };
232
+ var MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6;
233
+ function cellColumnName(column, part) {
234
+ return `${column}${CELL_PART_SUFFIX[part]}`;
235
+ }
236
+ var MATERIALIZE_ACTOR = "orm:materialize";
237
+ JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] });
238
+ var policyVariantSchema = z.object({
239
+ /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
240
+ when: z.string().min(1).max(1e3),
241
+ /** Exactly one of: allow-all bypass, or a row predicate. */
242
+ allow: z.literal(true).optional(),
243
+ policy: z.string().min(1).max(2e3).optional()
244
+ }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
245
+ message: "A variant declares exactly one of allow: true or policy"
246
+ });
247
+ var policyExpressionSchema = z.union([
248
+ z.string().min(1).max(2e3),
249
+ z.object({
250
+ default: z.string().min(1).max(2e3),
251
+ variants: z.array(policyVariantSchema).max(10).default([])
252
+ })
253
+ ]);
254
+ function parseDurationMs(input) {
255
+ if (typeof input === "number") return Number.isInteger(input) && input > 0 ? input : void 0;
256
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(input);
257
+ if (!match) return void 0;
258
+ const factor = match[2] === "ms" ? 1 : match[2] === "s" ? 1e3 : 6e4;
259
+ const value = Math.round(Number(match[1]) * factor);
260
+ return value > 0 ? value : void 0;
261
+ }
262
+ var identifier = z.string().min(1).max(63).regex(/^[a-z][a-z0-9_]*$/);
263
+ var durationMs = z.number().int().positive().max(24 * 60 * 60 * 1e3);
264
+ var RESOLVED_VIEW_SYSTEM_COLUMNS = {
265
+ writebackStatus: { name: "writebackStatus", columnName: "_writeback_status", type: "text" },
266
+ writebackError: { name: "writebackError", columnName: "_writeback_error", type: "text" }
267
+ };
268
+ var RESOLVED_SOURCE_SYSTEM_COLUMNS = {
269
+ tombstoned: { name: "sysTombstoned", columnName: "_tombstoned" },
270
+ fetchedAt: { name: "sysFetchedAt", columnName: "_fetched_at" },
271
+ writebackStatus: { name: "sysWritebackStatus", columnName: "_writeback_status" },
272
+ writebackError: { name: "sysWritebackError", columnName: "_writeback_error" },
273
+ writebackAt: { name: "sysWritebackAt", columnName: "_writeback_at" }
274
+ };
275
+ var RESOLVED_VIEW_CELL_PARTS = ["source", "at", "by", "conflicts"];
276
+ var RESOLVED_SOURCE_CELL_PARTS = { manual: ["at", "by", "rev"], prefetch: ["at", "by"] };
277
+ var RESERVED_RESOLVED_COLUMN_NAMES = /* @__PURE__ */ new Set([
278
+ ...Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName]),
279
+ ...Object.values(RESOLVED_SOURCE_SYSTEM_COLUMNS).flatMap((c) => [c.name, c.columnName])
280
+ ]);
281
+ var COMPARATORS = ["latest", "highest", "lowest", "priority", "nonNullFirst", "custom"];
282
+ var canonicalFunctionRefSchema = z.object({
283
+ /** `managed` = a Managed Function id/slug; `native` = an in-process Atlas function (reserved). */
284
+ kind: z.enum(["managed", "native"]),
285
+ id: z.string().min(1).max(200)
286
+ }).strict();
287
+ var canonicalFetchShapeSchema = z.union([
288
+ z.object({ shape: z.literal("single") }).strict(),
289
+ z.object({ shape: z.literal("batch"), maxKeys: z.number().int().min(2).max(500) }).strict()
290
+ ]);
291
+ var canonicalResolvedSourceSchema = z.object({
292
+ name: identifier,
293
+ kind: z.enum(["manual", "etl", "prefetch"]),
294
+ /** Backing relation in this namespace: an internal table (manual/prefetch) or a synced table (etl). */
295
+ table: identifier,
296
+ /** Resolved columns (logical names) this source supplies — the primary key is implicit. */
297
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
298
+ /** etl: logical timestamptz/date column on the synced table used as every cell's updated_at. */
299
+ updatedAt: z.string().min(1).max(63).optional(),
300
+ /** prefetch: resolved column holding the source system's key (may be the primary key). */
301
+ key: z.string().min(1).max(63).optional(),
302
+ fetch: canonicalFetchShapeSchema.optional(),
303
+ function: canonicalFunctionRefSchema.optional(),
304
+ prefetchDefaults: z.object({
305
+ maxStalenessMs: durationMs,
306
+ timeoutMs: durationMs,
307
+ onError: z.enum(["fallback", "fail"])
308
+ }).strict().optional(),
309
+ writeback: z.object({
310
+ columns: z.array(z.string().min(1).max(63)).min(1).max(500),
311
+ defaultMode: z.enum(["sync", "async"]),
312
+ timeoutMs: durationMs,
313
+ /** Remove confirmed cells from the manual source so a stale edit cannot shadow the source. */
314
+ clearManualOnConfirm: z.boolean()
315
+ }).strict().optional()
316
+ }).strict();
317
+ var canonicalResolveRuleSchema = z.object({
318
+ column: z.string().min(1).max(63),
319
+ comparator: z.enum(COMPARATORS),
320
+ /** Source names, in tie-break order. */
321
+ candidates: z.array(identifier).min(1).max(16),
322
+ /** custom only: SQL ORDER BY key over value / updated_at / source / actor / ord. */
323
+ orderBy: z.string().min(1).max(2e3).optional()
324
+ }).strict();
325
+ var canonicalResolvedSchema = z.object({
326
+ sources: z.array(canonicalResolvedSourceSchema).min(1).max(16),
327
+ /** One rule per resolved (non-pk) column; documents the generated view for tooling. */
328
+ resolve: z.array(canonicalResolveRuleSchema).max(500),
329
+ /** Sources whose tombstone hides the resolved row (v1: the manual source only). */
330
+ deletedBy: z.array(identifier).max(1).default([]),
331
+ /**
332
+ * Materialized: the view reads an indexed internal table (`table`) that the
333
+ * data plane keeps in step with `compute`, the internal view holding the
334
+ * resolution query. Omitted when the view computes on read.
335
+ */
336
+ materialized: z.object({ table: identifier, compute: identifier }).strict().optional(),
337
+ /** Write policies evaluated against the RESOLVED row (reads use the view's read policy). */
338
+ policies: z.object({
339
+ write: policyExpressionSchema.optional(),
340
+ insert: policyExpressionSchema.optional(),
341
+ update: policyExpressionSchema.optional()
342
+ }).strict().default({})
343
+ }).strict();
344
+ function validateResolvedView({ view, tables, views = [] }) {
345
+ const resolved = view.resolved;
346
+ if (!resolved) return [];
347
+ const errors = [];
348
+ const fail = (message) => errors.push(`resolved table '${view.view}': ${message}`);
349
+ const pkColumn = view.primaryKey?.length === 1 ? view.columns.find((c) => c.columnName === view.primaryKey?.[0]) : void 0;
350
+ if (!pkColumn) {
351
+ fail("requires exactly one primary-key column");
352
+ return errors;
353
+ }
354
+ const systemNames = new Set(Object.values(RESOLVED_VIEW_SYSTEM_COLUMNS).map((c) => c.name));
355
+ const scope = {
356
+ view,
357
+ resolved,
358
+ pkColumn,
359
+ dataColumns: new Map(view.columns.filter((c) => !systemNames.has(c.name) && c.cell === void 0).map((c) => [c.name, c])),
360
+ sourceByName: /* @__PURE__ */ new Map(),
361
+ fail
362
+ };
363
+ if (resolved.sources.filter((source) => source.kind === "manual").length !== 1) fail("requires exactly one manual source");
364
+ const tableByName = new Map(tables.map((table) => [table.table, table]));
365
+ for (const source of resolved.sources) {
366
+ if (scope.sourceByName.has(source.name)) fail(`duplicate source '${source.name}'`);
367
+ scope.sourceByName.set(source.name, source);
368
+ const table = tableByName.get(source.table);
369
+ if (!table) fail(`source '${source.name}' references unknown table '${source.table}'`);
370
+ else validateSource({ scope, source, table });
371
+ }
372
+ validateRules(scope);
373
+ validateViewCells(scope);
374
+ if (resolved.materialized) validateMaterialized({ scope, tableByName, views });
375
+ for (const name of resolved.deletedBy) {
376
+ if (scope.sourceByName.get(name)?.kind !== "manual") fail(`deletedBy '${name}' must be the manual source`);
377
+ }
378
+ return errors;
379
+ }
380
+ function validateSource({ scope, source, table }) {
381
+ const { fail } = scope;
382
+ if (source.kind === "etl" && table.source === void 0) fail(`etl source '${source.name}' must reference a synced table`);
383
+ if (source.kind !== "etl" && (table.internal !== true || table.cellMetadata !== true)) {
384
+ fail(`${source.kind} source '${source.name}' must reference an internal table with cell metadata`);
385
+ }
386
+ const hasRev = table.columns.some((column) => column.cell?.part === "rev");
387
+ if (source.kind === "manual" && !hasRev) fail(`manual source '${source.name}' must carry '__rev' cell columns`);
388
+ if (source.kind === "prefetch" && hasRev) fail(`prefetch source '${source.name}' must not carry '__rev' cell columns`);
389
+ const byName = new Map(table.columns.map((c) => [c.name, c]));
390
+ validateSourceColumns({ scope, source, byName });
391
+ if (source.kind === "etl") {
392
+ const updatedAt = source.updatedAt === void 0 ? void 0 : byName.get(source.updatedAt);
393
+ if (source.updatedAt !== void 0 && updatedAt?.type !== "timestamptz" && updatedAt?.type !== "date") {
394
+ fail(`etl source '${source.name}' updatedAt must name a timestamptz/date column on '${source.table}'`);
395
+ }
396
+ }
397
+ validatePrefetchFields({ scope, source });
398
+ }
399
+ function validatePrefetchFields({ scope, source }) {
400
+ const { fail, pkColumn } = scope;
401
+ if (source.kind !== "prefetch") {
402
+ if (source.key || source.fetch || source.function || source.prefetchDefaults || source.writeback) {
403
+ fail(`only prefetch sources may declare key/fetch/function/prefetchDefaults/writeback ('${source.name}')`);
404
+ }
405
+ return;
406
+ }
407
+ if (!source.key || !source.fetch || !source.function || !source.prefetchDefaults) {
408
+ fail(`prefetch source '${source.name}' requires key, fetch, function and prefetchDefaults`);
409
+ } else if (source.key !== pkColumn.name && !source.columns.includes(source.key)) {
410
+ fail(`prefetch source '${source.name}' key '${source.key}' must be the primary key or one of its columns`);
411
+ }
412
+ for (const column of source.writeback?.columns ?? []) {
413
+ if (!source.columns.includes(column)) fail(`prefetch source '${source.name}' writes back '${column}', which it does not supply`);
414
+ }
415
+ }
416
+ function validateSourceColumns({ scope, source, byName }) {
417
+ const { fail, pkColumn, dataColumns } = scope;
418
+ for (const column of [pkColumn.name, ...source.columns]) {
419
+ const own = column === pkColumn.name ? pkColumn : dataColumns.get(column);
420
+ const theirs = byName.get(column);
421
+ if (!own) fail(`source '${source.name}' supplies unknown column '${column}'`);
422
+ else if (!theirs) fail(`source '${source.name}' table '${source.table}' has no column '${column}'`);
423
+ else if (JSON.stringify(theirs.type) !== JSON.stringify(own.type)) fail(`column '${column}' has a different type on source '${source.name}'`);
424
+ }
425
+ }
426
+ function validateRules({ resolved, pkColumn, dataColumns, sourceByName, fail }) {
427
+ const ruled = /* @__PURE__ */ new Set();
428
+ for (const rule of resolved.resolve) {
429
+ if (!dataColumns.has(rule.column) || rule.column === pkColumn.name) {
430
+ fail(`resolve rule targets unknown column '${rule.column}'`);
431
+ continue;
432
+ }
433
+ if (ruled.has(rule.column)) fail(`column '${rule.column}' has more than one resolve rule`);
434
+ ruled.add(rule.column);
435
+ if (rule.comparator === "custom" !== (rule.orderBy !== void 0)) {
436
+ fail(`column '${rule.column}': orderBy is required for custom comparators and only allowed there`);
437
+ }
438
+ if (new Set(rule.candidates).size !== rule.candidates.length) fail(`column '${rule.column}' repeats a candidate`);
439
+ for (const candidate of rule.candidates) {
440
+ const source = sourceByName.get(candidate);
441
+ if (!source) fail(`column '${rule.column}' names unknown candidate source '${candidate}'`);
442
+ else if (!source.columns.includes(rule.column)) fail(`column '${rule.column}' candidate '${candidate}' does not supply it`);
443
+ }
444
+ }
445
+ for (const column of dataColumns.keys()) {
446
+ if (column !== pkColumn.name && !ruled.has(column)) fail(`column '${column}' has no resolve rule`);
447
+ }
448
+ }
449
+ var VIEW_CELL_TYPES = {
450
+ source: "text",
451
+ at: "timestamptz",
452
+ by: "text",
453
+ conflicts: "jsonb"
454
+ };
455
+ function validateViewCells({ view, dataColumns, pkColumn, fail }) {
456
+ const expected = /* @__PURE__ */ new Map();
457
+ for (const column of dataColumns.values()) {
458
+ if (column.name === pkColumn.name) continue;
459
+ for (const part of RESOLVED_VIEW_CELL_PARTS) {
460
+ expected.set(cellColumnName(column.name, part), { part, columnName: cellColumnName(column.columnName, part) });
461
+ }
462
+ }
463
+ for (const column of view.columns) {
464
+ if (!column.cell) continue;
465
+ const want = expected.get(column.name);
466
+ if (!want || want.part !== column.cell.part || want.columnName !== column.columnName || cellColumnName(column.cell.of, column.cell.part) !== column.name) {
467
+ fail(`unexpected cell column '${column.name}'`);
468
+ continue;
469
+ }
470
+ if (column.type !== VIEW_CELL_TYPES[column.cell.part]) fail(`cell column '${column.name}' must be ${VIEW_CELL_TYPES[column.cell.part]}`);
471
+ expected.delete(column.name);
472
+ }
473
+ for (const name of expected.keys()) fail(`missing cell column '${name}'`);
474
+ }
475
+ var columnSignature = (columns) => JSON.stringify(columns.map((column) => [column.name, column.columnName, column.type]));
476
+ function validateMaterialized({ scope, tableByName, views }) {
477
+ const { view, resolved, fail } = scope;
478
+ const { table: tableName, compute: computeName } = resolved.materialized;
479
+ const table = tableByName.get(tableName);
480
+ if (!table || table.internal !== true || table.materializes !== view.view) {
481
+ fail(`materialized table '${tableName}' must be an internal table that materializes '${view.view}'`);
482
+ } else {
483
+ if (columnSignature(table.columns) !== columnSignature(view.columns)) fail(`materialized table '${tableName}' must have exactly the view's columns`);
484
+ if (JSON.stringify(table.primaryKey ?? []) !== JSON.stringify(view.primaryKey ?? [])) fail(`materialized table '${tableName}' must share the view's primary key`);
485
+ }
486
+ const compute = views.find((candidate) => candidate.view === computeName);
487
+ if (!compute || compute.internal !== true) fail(`compute view '${computeName}' must be an internal view`);
488
+ else if (columnSignature(compute.columns) !== columnSignature(view.columns)) fail(`compute view '${computeName}' must have exactly the view's columns`);
489
+ for (const source of resolved.sources) {
490
+ if (source.kind !== "etl") continue;
491
+ const read = tableByName.get(source.table)?.policies?.read;
492
+ const unconditional = typeof read === "string" ? read.trim() === "true" : read !== void 0 && read.default.trim() === "true" && read.variants.length === 0;
493
+ if (!unconditional) {
494
+ fail(`etl source '${source.name}' must have read policy 'true' to be materialized (the copy is shared by every caller)`);
495
+ }
496
+ }
497
+ }
7
498
 
8
499
  // src/canonical/v2.ts
9
500
  var CANONICAL_FORMAT = 2;
10
501
  var IDENTIFIER_RE = /^[a-z][a-z0-9_]*$/;
11
- var identifier = z.string().min(1).max(63).regex(IDENTIFIER_RE);
502
+ var identifier2 = z.string().min(1).max(63).regex(IDENTIFIER_RE);
12
503
  var columnIdentifier = z.string().min(1).max(63).regex(COLUMN_IDENTIFIER_PATTERN);
13
504
  var COLUMN_TYPES = [
14
505
  "uuid",
@@ -24,14 +515,14 @@ var COLUMN_TYPES = [
24
515
  ];
25
516
  var columnTypeSchema = z.enum(COLUMN_TYPES);
26
517
  var canonicalEnumSchema = z.object({
27
- name: identifier,
518
+ name: identifier2,
28
519
  values: z.array(z.string().min(1).max(63)).min(1).max(100)
29
520
  });
30
521
  var canonicalColumnSchema = z.object({
31
522
  /** Property name in TS (camelCase); columnName is the Postgres name. */
32
523
  name: z.string().min(1).max(63),
33
524
  columnName: columnIdentifier,
34
- type: z.union([columnTypeSchema, z.object({ enum: identifier })]),
525
+ type: z.union([columnTypeSchema, z.object({ enum: identifier2 })]),
35
526
  nullable: z.boolean().default(true),
36
527
  unique: z.boolean().default(false),
37
528
  /** Literal default, or one of the allowlisted SQL functions. */
@@ -47,7 +538,14 @@ var canonicalColumnSchema = z.object({
47
538
  /** Migration hints — same semantics as v1. */
48
539
  renamedFrom: columnIdentifier.optional(),
49
540
  cast: z.string().max(200).optional(),
50
- deprecated: z.boolean().default(false)
541
+ deprecated: z.boolean().default(false),
542
+ /**
543
+ * Marks a system cell-metadata column (see CELL_PARTS in constants): part
544
+ * `part` of the cell of logical column `of`. Synthesized by authoring,
545
+ * never client-writable, absent from GraphQL scalar fields. Omitted on
546
+ * ordinary columns so their hashes are unchanged.
547
+ */
548
+ cell: z.object({ of: z.string().min(1).max(63), part: z.enum(CELL_PARTS) }).strict().optional()
51
549
  }).superRefine((column, ctx) => {
52
550
  if (column.onUpdateFn === void 0) return;
53
551
  if (typeof column.type !== "string" || column.type !== "timestamptz" && column.type !== "date") {
@@ -62,36 +560,28 @@ var canonicalLinkSchema = z.object({
62
560
  name: z.string().min(1).max(63),
63
561
  kind: z.enum(["toOne", "toMany", "toPlatformUser"]),
64
562
  /** Target table name (namespace-local). Absent for toPlatformUser. */
65
- target: identifier.optional(),
563
+ target: identifier2.optional(),
564
+ /** Owning namespace of an imported target; omitted for local links. */
565
+ namespace: identifier2.max(41).optional(),
66
566
  /** FK column on the owning side (toOne/toPlatformUser: on this table; toMany: on the target). */
67
567
  on: columnIdentifier,
68
568
  /** Referenced column on the target (default: target's PK / platform user `sub`). */
69
569
  references: columnIdentifier.optional(),
70
570
  /** enforce: true emits a real FK constraint (same-namespace toOne only). */
71
571
  enforce: z.boolean().default(false),
572
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
573
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
72
574
  description: z.string().max(500).optional()
73
575
  });
74
576
  var canonicalIndexSchema = z.object({
75
577
  columns: z.array(columnIdentifier).min(1),
76
578
  unique: z.boolean().default(false),
77
- name: identifier.optional()
78
- });
79
- var policyVariantSchema = z.object({
80
- /** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
81
- when: z.string().min(1).max(1e3),
82
- /** Exactly one of: allow-all bypass, or a row predicate. */
83
- allow: z.literal(true).optional(),
84
- policy: z.string().min(1).max(2e3).optional()
85
- }).refine((v) => v.allow === true !== (typeof v.policy === "string"), {
86
- message: "A variant declares exactly one of allow: true or policy"
579
+ name: identifier2.optional()
87
580
  });
88
- var policyExpressionSchema = z.union([
89
- z.string().min(1).max(2e3),
90
- z.object({
91
- default: z.string().min(1).max(2e3),
92
- variants: z.array(policyVariantSchema).max(10).default([])
93
- })
94
- ]);
581
+ var canonicalCheckSchema = z.object({
582
+ name: identifier2,
583
+ expression: z.string().min(1).max(2e3)
584
+ }).strict();
95
585
  var canonicalPoliciesSchema = z.object({
96
586
  read: policyExpressionSchema.optional(),
97
587
  write: policyExpressionSchema.optional(),
@@ -279,7 +769,7 @@ var VIEW_QUERY_FUNCTION_ALLOWLIST = [
279
769
  "width_bucket"
280
770
  ];
281
771
  var canonicalActionSchema = z.object({
282
- name: identifier,
772
+ name: identifier2,
283
773
  requires: z.string().max(1e3).optional(),
284
774
  params: z.record(z.string(), z.object({
285
775
  type: columnTypeSchema,
@@ -291,9 +781,9 @@ var canonicalActionSchema = z.object({
291
781
  });
292
782
  var canonicalCowMutationSchema = z.object({
293
783
  kind: z.enum(["override", "revert"]),
294
- name: identifier,
784
+ name: identifier2,
295
785
  /** Synced table (same namespace) the overlay copies from / falls back to. */
296
- synced: identifier,
786
+ synced: identifier2,
297
787
  /** Single-column primary key PROPERTY (TS camelCase, like column `name`) shared by overlay and synced. */
298
788
  pk: z.string().min(1).max(63),
299
789
  /** Override: contract properties copied INSERT…SELECT from synced (pk included). Empty for revert. */
@@ -321,23 +811,28 @@ var canonicalCowMutationSchema = z.object({
321
811
  }
322
812
  });
323
813
  var canonicalForeignKeySchema = z.object({
324
- name: identifier,
814
+ name: identifier2,
325
815
  columns: z.array(columnIdentifier).min(1).max(8),
326
- target: identifier,
816
+ target: identifier2,
327
817
  references: z.array(columnIdentifier).min(1).max(8),
328
- deferrable: z.enum(["initially-immediate", "initially-deferred"]).optional()
818
+ deferrable: z.enum(["initially-immediate", "initially-deferred"]).optional(),
819
+ onDelete: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional(),
820
+ onUpdate: z.enum(["cascade", "restrict", "no action", "set null", "set default"]).optional()
329
821
  }).strict();
330
822
  var canonicalTableSchema = z.object({
331
- table: identifier,
823
+ table: identifier2,
824
+ displayName: z.string().trim().min(1).max(120).optional(),
332
825
  description: z.string().max(2e3).optional(),
333
826
  /** Table-level rename hint (new in v2). */
334
- renamedFrom: identifier.optional(),
335
- /** Synced/reflected read-only tables (`source: gold.*`) — v1 semantics. */
336
- source: z.string().regex(/^gold\.[a-z][a-z0-9_]*$/).optional(),
827
+ renamedFrom: identifier2.optional(),
828
+ /** Synced/reflected read-only tables (`source: schema.table`) — v1 semantics. */
829
+ source: z.string().regex(QUALIFIED_TABLE_PATTERN).optional(),
337
830
  columns: z.array(canonicalColumnSchema).default([]),
338
831
  primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
339
832
  links: z.array(canonicalLinkSchema).default([]),
340
833
  indexes: z.array(canonicalIndexSchema).default([]),
834
+ /** Omitted by old definitions, preserving their existing content hashes. */
835
+ checks: z.array(canonicalCheckSchema).max(100).optional(),
341
836
  policies: canonicalPoliciesSchema.default({}),
342
837
  /**
343
838
  * v1-conversion carry-over only. v2 has no action surface — the runtime
@@ -348,22 +843,55 @@ var canonicalTableSchema = z.object({
348
843
  /** Optional (not defaulted) so pre-CoW canonical documents keep byte-identical hashes. */
349
844
  cowMutations: z.array(canonicalCowMutationSchema).optional(),
350
845
  /** Omitted by old definitions, preserving their existing content hashes. */
351
- foreignKeys: z.array(canonicalForeignKeySchema).max(100).optional()
846
+ foreignKeys: z.array(canonicalForeignKeySchema).max(100).optional(),
847
+ /**
848
+ * Per-cell edit metadata (`cellMetadata: true` in authoring): every tracked
849
+ * column `c` carries typed `c__at` / `c__by` system columns (plus `c__rev`
850
+ * on a resolved table's internal sources), listed explicitly in `columns`
851
+ * with a `cell` marker so DDL and migrations treat them as ordinary columns.
852
+ * Omitted when off so existing definitions hash unchanged.
853
+ */
854
+ cellMetadata: z.literal(true).optional(),
855
+ /**
856
+ * System-owned backing table of a resolved table (its manual or prefetch
857
+ * source). Internal tables get DDL and IR metadata but no GraphQL surface;
858
+ * only the data plane writes them. Omitted when false.
859
+ */
860
+ internal: z.literal(true).optional(),
861
+ /**
862
+ * The materialized copy of resolved table `materializes` (internal): the
863
+ * same columns as that view, including its cell parts, maintained by the
864
+ * data plane. Omitted otherwise.
865
+ */
866
+ materializes: identifier2.optional()
352
867
  });
868
+ var MAX_VIEW_QUERY = 1e5;
869
+ var MAX_RESOLVED_VIEW_QUERY = 5e6;
353
870
  var canonicalViewSchema = z.object({
354
- view: identifier,
871
+ view: identifier2,
355
872
  description: z.string().max(2e3).optional(),
356
873
  columns: z.array(canonicalColumnSchema).min(1),
357
874
  /** Logical identity for GraphQL only; PostgreSQL views have no PK constraint. */
358
875
  primaryKey: z.array(columnIdentifier).min(1).max(8).optional(),
359
876
  links: z.array(canonicalLinkSchema).default([]),
360
877
  policies: z.object({ read: policyExpressionSchema }).strict(),
361
- query: z.string().min(1).max(1e5).refine(isSingleViewQuerySql, {
878
+ query: z.string().min(1).max(MAX_RESOLVED_VIEW_QUERY).refine(isSingleViewQuerySql, {
362
879
  message: "view query must be one SELECT/WITH statement without comments or dollar-quoted bodies"
363
880
  }),
364
881
  /** Namespace-local logical relation names, sorted for deterministic hashing. */
365
- dependencies: z.array(identifier).max(500)
882
+ dependencies: z.array(identifier2).max(500),
883
+ /**
884
+ * Present when this view is a resolved table (defineResolvedTable): the
885
+ * multi-source metadata behind its generated query. Omitted otherwise so
886
+ * existing views hash unchanged.
887
+ */
888
+ resolved: canonicalResolvedSchema.optional(),
889
+ /** System-owned view (a materialized resolved table's compute view): no GraphQL surface. */
890
+ internal: z.literal(true).optional()
366
891
  }).superRefine((view, ctx) => {
892
+ if (view.resolved === void 0 && view.query.length > MAX_VIEW_QUERY) {
893
+ ctx.addIssue({ code: "custom", path: ["query"], message: `view query must be at most ${MAX_VIEW_QUERY} characters` });
894
+ }
367
895
  for (const [index, column] of view.columns.entries()) {
368
896
  if (column.default !== void 0 || column.defaultFn !== void 0) {
369
897
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare a default` });
@@ -378,20 +906,91 @@ var canonicalViewSchema = z.object({
378
906
  ctx.addIssue({ code: "custom", path: ["columns", index], message: `view column '${column.name}' cannot declare migration hints` });
379
907
  }
380
908
  }
909
+ if (view.resolved === void 0 && view.internal !== true) {
910
+ for (const [index, column] of view.columns.entries()) {
911
+ if (column.cell) ctx.addIssue({ code: "custom", path: ["columns", index], message: `only resolved tables carry cell columns ('${column.name}')` });
912
+ }
913
+ }
381
914
  for (const [index, link] of view.links.entries()) {
382
915
  if (link.enforce) {
383
916
  ctx.addIssue({ code: "custom", path: ["links", index, "enforce"], message: `view link '${link.name}' cannot enforce a foreign key` });
384
917
  }
918
+ if (link.onDelete !== void 0 || link.onUpdate !== void 0) {
919
+ ctx.addIssue({ code: "custom", path: ["links", index], message: `view link '${link.name}' cannot declare referential actions` });
920
+ }
385
921
  }
386
922
  });
387
- var canonicalDefinitionSchema = z.object({
923
+ var CELL_PART_TYPES = {
924
+ at: "timestamptz",
925
+ by: "text",
926
+ rev: "uuid",
927
+ source: "text",
928
+ conflicts: "jsonb"
929
+ };
930
+ function trackedCellColumns(table) {
931
+ const pk = new Set(table.primaryKey ?? []);
932
+ return table.columns.filter((column) => column.cell === void 0 && !pk.has(column.columnName) && column.onUpdateFn === void 0);
933
+ }
934
+ var SUFFIXES = Object.values(CELL_PART_SUFFIX);
935
+ function validateCellMetadata(table, index, ctx) {
936
+ const fail = (message, path = ["tables", index]) => ctx.addIssue({ code: "custom", path, message });
937
+ const cells = table.columns.flatMap((column, position) => column.cell ? [{ column, position, cell: column.cell }] : []);
938
+ if (table.materializes !== void 0) return;
939
+ if (table.cellMetadata !== true) {
940
+ for (const { position } of cells) fail(`cell-metadata columns require cellMetadata on table '${table.table}'`, ["tables", index, "columns", position]);
941
+ return;
942
+ }
943
+ if (table.source !== void 0) {
944
+ fail(`synced table '${table.table}' cannot track cell metadata`);
945
+ return;
946
+ }
947
+ const tracked = trackedCellColumns(table);
948
+ const byName = new Map(tracked.map((column) => [column.name, column]));
949
+ const withRev = cells.some(({ cell }) => cell.part === "rev");
950
+ if (withRev && table.internal !== true) fail(`only a resolved table's internal sources carry '__rev' cell columns ('${table.table}')`);
951
+ const seen = /* @__PURE__ */ new Set();
952
+ for (const { column, position, cell } of cells) {
953
+ const path = ["tables", index, "columns", position];
954
+ const owner = byName.get(cell.of);
955
+ if (!owner) {
956
+ fail(`cell column '${column.name}' belongs to '${cell.of}', which is not a tracked column`, path);
957
+ continue;
958
+ }
959
+ 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);
960
+ if (column.name !== cellColumnName(owner.name, cell.part) || column.columnName !== cellColumnName(owner.columnName, cell.part)) {
961
+ fail(`cell column for '${owner.name}' ${cell.part} must be named '${cellColumnName(owner.name, cell.part)}' / '${cellColumnName(owner.columnName, cell.part)}'`, path);
962
+ }
963
+ if (column.type !== CELL_PART_TYPES[cell.part] || !column.nullable || column.unique || column.default !== void 0 || column.defaultFn !== void 0) {
964
+ fail(`cell column '${column.name}' must be a nullable, default-less ${CELL_PART_TYPES[cell.part]}`, path);
965
+ }
966
+ const key = `${cell.of}:${cell.part}`;
967
+ if (seen.has(key)) fail(`duplicate cell column '${column.name}'`, path);
968
+ seen.add(key);
969
+ }
970
+ for (const column of tracked) {
971
+ if (column.columnName.length > MAX_TRACKED_COLUMN_NAME) {
972
+ fail(`column '${column.columnName}' is too long to track cell metadata (max ${MAX_TRACKED_COLUMN_NAME} characters)`);
973
+ }
974
+ if (SUFFIXES.some((suffix) => column.columnName.endsWith(suffix))) {
975
+ fail(`column '${column.columnName}' ends in a reserved cell-metadata suffix (${SUFFIXES.join(", ")})`);
976
+ }
977
+ for (const part of withRev ? ["at", "by", "rev"] : ["at", "by"]) {
978
+ if (!seen.has(`${column.name}:${part}`)) fail(`tracked column '${column.name}' is missing its '${cellColumnName(column.columnName, part)}' cell column`);
979
+ }
980
+ }
981
+ }
982
+ var exportGateSchema = z.union([z.literal(true), z.object({ capability: z.string().min(1) }).strict(), z.object({ role: z.string().min(1) }).strict()]);
983
+ var relationExportSchema = z.object({ read: exportGateSchema, write: exportGateSchema.optional() }).strict();
984
+ var localDefinitionSchema = z.object({
388
985
  definition_format: z.literal(CANONICAL_FORMAT),
389
- namespace: identifier.max(41),
986
+ namespace: identifier2.max(41),
390
987
  description: z.string().max(2e3).optional(),
391
988
  enums: z.array(canonicalEnumSchema).default([]),
392
989
  tables: z.array(canonicalTableSchema).min(0).max(500),
393
990
  /** Optional to preserve byte-identical hashes for pre-view canonical v2 documents. */
394
991
  views: z.array(canonicalViewSchema).max(500).optional(),
992
+ /** Target-owned cross-namespace access contract, using existing namespace grants. */
993
+ exports: z.record(identifier2, relationExportSchema).optional(),
395
994
  /** Verbatim custom-roles grammar (@sequenceholdings/custom-roles-manifest). */
396
995
  capabilities: z.object({
397
996
  roles: z.unknown().optional(),
@@ -404,6 +1003,7 @@ var canonicalDefinitionSchema = z.object({
404
1003
  ctx.addIssue({ code: "custom", path: ["tables", index, "table"], message: `duplicate relation '${table.table}'` });
405
1004
  }
406
1005
  seen.add(table.table);
1006
+ validateCellMetadata(table, index, ctx);
407
1007
  if (table.source !== void 0) {
408
1008
  for (const [columnIndex, column] of table.columns.entries()) {
409
1009
  if (column.onUpdateFn !== void 0) {
@@ -417,12 +1017,41 @@ var canonicalDefinitionSchema = z.object({
417
1017
  }
418
1018
  }
419
1019
  const fkTables = new Map(definition.tables.map((table) => [table.table, table]));
1020
+ const relations = /* @__PURE__ */ new Set([...fkTables.keys(), ...(definition.views ?? []).map((view) => view.view)]);
1021
+ for (const name of Object.keys(definition.exports ?? {})) {
1022
+ if (!relations.has(name)) ctx.addIssue({ code: "custom", path: ["exports", name], message: `export '${name}' is not a local object` });
1023
+ }
420
1024
  for (const [tableIndex, table] of definition.tables.entries()) {
1025
+ for (const [linkIndex, link] of table.links.entries()) {
1026
+ if (link.enforce && link.namespace !== void 0 && link.namespace !== definition.namespace) {
1027
+ ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", linkIndex], message: "physical foreign keys require a local target; use an ORM link without enforce" });
1028
+ }
1029
+ }
421
1030
  const names = /* @__PURE__ */ new Set([
422
1031
  ...table.primaryKey?.length ? [`${table.table}_pkey`] : [],
423
1032
  ...table.columns.filter((column) => column.unique && !(table.primaryKey?.length === 1 && table.primaryKey[0] === column.columnName)).map((column) => `${table.table}_${column.columnName}_unique`),
424
1033
  ...table.links.filter((link) => link.enforce).map((link) => `fk_${table.table}_${link.name}`)
425
1034
  ]);
1035
+ for (const [index, link] of table.links.entries()) {
1036
+ if ((link.onDelete !== void 0 || link.onUpdate !== void 0) && (!link.enforce || link.kind !== "toOne")) {
1037
+ ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "links", index], message: "referential actions require an enforced toOne link" });
1038
+ }
1039
+ if (link.onDelete === "set null" || link.onUpdate === "set null") {
1040
+ const source = table.columns.find((column) => column.columnName === link.on);
1041
+ 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" });
1042
+ }
1043
+ }
1044
+ for (const [index, check] of (table.checks ?? []).entries()) {
1045
+ const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "checks", index], message });
1046
+ if (table.source) fail("synced tables cannot declare checks");
1047
+ if (names.has(check.name)) fail(`duplicate constraint '${check.name}'`);
1048
+ names.add(check.name);
1049
+ try {
1050
+ compileCheckExpression(check.expression, table.columns);
1051
+ } catch (error) {
1052
+ fail(error instanceof Error ? error.message : String(error));
1053
+ }
1054
+ }
426
1055
  for (const [index, fk] of (table.foreignKeys ?? []).entries()) {
427
1056
  const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "foreignKeys", index], message });
428
1057
  if (names.has(fk.name)) fail(`duplicate foreign key '${fk.name}'`);
@@ -440,10 +1069,18 @@ var canonicalDefinitionSchema = z.object({
440
1069
  if (!sourceColumn || !targetColumn) fail("foreign key references an unknown column");
441
1070
  else if (JSON.stringify(sourceColumn.type) !== JSON.stringify(targetColumn.type)) fail("foreign key column types must match");
442
1071
  }
1072
+ if (fk.onDelete === "set null" || fk.onUpdate === "set null") {
1073
+ 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");
1074
+ }
443
1075
  const uniqueKeys = [target.primaryKey ?? [], ...target.indexes.filter((index2) => index2.unique).map((index2) => index2.columns), ...target.columns.filter((column) => column.unique).map((column) => [column.columnName])];
444
1076
  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");
445
1077
  }
446
1078
  }
1079
+ for (const [viewIndex, view] of (definition.views ?? []).entries()) {
1080
+ for (const message of validateResolvedView({ view, tables: definition.tables, views: definition.views ?? [] })) {
1081
+ ctx.addIssue({ code: "custom", path: ["views", viewIndex, "resolved"], message });
1082
+ }
1083
+ }
447
1084
  const tableByName = new Map(definition.tables.map((table) => [table.table, table]));
448
1085
  for (const [tableIndex, table] of definition.tables.entries()) {
449
1086
  const cowMutations = table.cowMutations ?? [];
@@ -559,6 +1196,10 @@ var canonicalDefinitionSchema = z.object({
559
1196
  };
560
1197
  for (const view of views) visit(view.view, []);
561
1198
  });
1199
+ var canonicalDefinitionSchema = localDefinitionSchema.safeExtend({
1200
+ /** Flattened, pinned snapshots. Imported relations never participate in this namespace's DDL. */
1201
+ imports: z.array(localDefinitionSchema).max(32).optional()
1202
+ });
562
1203
  function canonicalRelations(definition) {
563
1204
  const views = (definition.views ?? []).map((view) => ({
564
1205
  table: view.view,
@@ -567,8 +1208,12 @@ function canonicalRelations(definition) {
567
1208
  ...view.primaryKey !== void 0 ? { primaryKey: view.primaryKey } : {},
568
1209
  links: view.links,
569
1210
  indexes: [],
570
- policies: { read: view.policies.read },
571
- actions: []
1211
+ // A resolved table's write policies (evaluated against the resolved row)
1212
+ // ride alongside the view's read policy.
1213
+ policies: { read: view.policies.read, ...view.resolved?.policies ?? {} },
1214
+ actions: [],
1215
+ ...view.resolved !== void 0 ? { resolved: view.resolved } : {},
1216
+ ...view.internal ? { internal: true } : {}
572
1217
  }));
573
1218
  return [...definition.tables, ...views].sort((a, b) => a.table.localeCompare(b.table));
574
1219
  }
@@ -578,13 +1223,14 @@ function normalizeCanonical(definition) {
578
1223
  ...definition,
579
1224
  enums: sortByName(definition.enums),
580
1225
  tables: [...definition.tables].sort((a, b) => a.table.localeCompare(b.table)).map((t) => {
581
- const { cowMutations, foreignKeys, ...rest } = t;
1226
+ const { cowMutations, foreignKeys, checks, ...rest } = t;
582
1227
  return {
583
1228
  ...rest,
584
1229
  links: sortByName(t.links),
585
1230
  indexes: [...t.indexes].sort((a, b) => (a.name ?? a.columns.join("_")).localeCompare(b.name ?? b.columns.join("_"))),
586
1231
  actions: sortByName(t.actions),
587
1232
  ...foreignKeys?.length ? { foreignKeys: sortByName(foreignKeys) } : {},
1233
+ ...checks?.length ? { checks: sortByName(checks) } : {},
588
1234
  // Omitted entirely when absent/empty so pre-CoW documents hash unchanged.
589
1235
  ...cowMutations !== void 0 && cowMutations.length > 0 ? { cowMutations: sortByName(cowMutations) } : {}
590
1236
  };
@@ -597,9 +1243,14 @@ function normalizeCanonical(definition) {
597
1243
  dependencies: [...view.dependencies].sort()
598
1244
  }));
599
1245
  }
1246
+ if (definition.imports?.length) {
1247
+ normalized.imports = definition.imports.map(normalizeCanonical).sort((a, b) => a.namespace.localeCompare(b.namespace));
1248
+ } else {
1249
+ delete normalized.imports;
1250
+ }
600
1251
  return normalized;
601
1252
  }
602
1253
 
603
- export { CANONICAL_FORMAT, COLUMN_TYPES, IDENTIFIER_RE, VIEW_QUERY_FUNCTION_ALLOWLIST, canonicalActionSchema, canonicalColumnSchema, canonicalCowMutationSchema, canonicalDefinitionSchema, canonicalEnumSchema, canonicalForeignKeySchema, canonicalIndexSchema, canonicalLinkSchema, canonicalPoliciesSchema, canonicalRelations, canonicalTableSchema, canonicalViewSchema, isSingleViewQuerySql, normalizeCanonical, policyExpressionSchema, policyVariantSchema };
1254
+ export { CANONICAL_FORMAT, CELL_PART_TYPES, COLUMN_TYPES, COMPARATORS, IDENTIFIER_RE, RESERVED_RESOLVED_COLUMN_NAMES, RESOLVED_SOURCE_CELL_PARTS, RESOLVED_SOURCE_SYSTEM_COLUMNS, RESOLVED_VIEW_CELL_PARTS, RESOLVED_VIEW_SYSTEM_COLUMNS, VIEW_QUERY_FUNCTION_ALLOWLIST, canonicalActionSchema, canonicalCheckSchema, canonicalColumnSchema, canonicalCowMutationSchema, canonicalDefinitionSchema, canonicalEnumSchema, canonicalFetchShapeSchema, canonicalForeignKeySchema, canonicalFunctionRefSchema, canonicalIndexSchema, canonicalLinkSchema, canonicalPoliciesSchema, canonicalRelations, canonicalResolveRuleSchema, canonicalResolvedSchema, canonicalResolvedSourceSchema, canonicalTableSchema, canonicalViewSchema, exportGateSchema, isSingleViewQuerySql, localDefinitionSchema, normalizeCanonical, ontologyContractSchema, parseDurationMs, policyExpressionSchema, policyVariantSchema, readOntologyContract, relationExportSchema, trackedCellColumns, validateResolvedView };
604
1255
  //# sourceMappingURL=canonical.js.map
605
1256
  //# sourceMappingURL=canonical.js.map