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