@sequenceholdings/orm 2.10.0 → 2.11.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.
- package/README.md +71 -0
- package/dist/authoring.cjs +796 -7
- package/dist/authoring.cjs.map +1 -1
- package/dist/authoring.d.cts +11 -2
- package/dist/authoring.d.ts +11 -2
- package/dist/authoring.js +796 -7
- package/dist/authoring.js.map +1 -1
- package/dist/canonical.cjs +777 -6
- package/dist/canonical.cjs.map +1 -1
- package/dist/canonical.d.cts +43 -43
- package/dist/canonical.d.ts +43 -43
- package/dist/canonical.js +777 -6
- package/dist/canonical.js.map +1 -1
- package/dist/cli.cjs +7561 -7502
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +7561 -7502
- package/dist/cli.js.map +1 -1
- package/dist/compiler.cjs +801 -33
- package/dist/compiler.cjs.map +1 -1
- package/dist/compiler.d.cts +1 -1
- package/dist/compiler.d.ts +1 -1
- package/dist/compiler.js +801 -33
- package/dist/compiler.js.map +1 -1
- package/dist/index.cjs +3716 -3445
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +95 -30
- package/dist/index.d.ts +95 -30
- package/dist/index.js +3711 -3444
- package/dist/index.js.map +1 -1
- package/dist/ir.cjs +778 -7
- package/dist/ir.cjs.map +1 -1
- package/dist/ir.d.cts +58 -58
- package/dist/ir.d.ts +58 -58
- package/dist/ir.js +778 -7
- package/dist/ir.js.map +1 -1
- package/dist/predicate-v2.cjs +793 -23
- package/dist/predicate-v2.cjs.map +1 -1
- package/dist/predicate-v2.js +793 -23
- package/dist/predicate-v2.js.map +1 -1
- package/dist/sdl.cjs +786 -17
- package/dist/sdl.cjs.map +1 -1
- package/dist/sdl.js +786 -17
- package/dist/sdl.js.map +1 -1
- package/package.json +1 -1
- package/dist/{definition-B99BsOAO.d.cts → definition-CevES7lM.d.cts} +2 -2
- package/dist/{definition-B99BsOAO.d.ts → definition-CevES7lM.d.ts} +2 -2
package/dist/sdl.js
CHANGED
|
@@ -203,10 +203,16 @@ function compileCheckExpression(source, columns) {
|
|
|
203
203
|
|
|
204
204
|
// src/constants.ts
|
|
205
205
|
var NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/;
|
|
206
|
+
var IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
206
207
|
var COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/;
|
|
207
208
|
var MAX_IDENTIFIER_LENGTH = 63;
|
|
209
|
+
var CAPABILITY_KEY_PATTERN = /^(?:org\/|app\/[a-z][a-z0-9-]{0,63}\/)?[a-z0-9-]{1,64}$/;
|
|
208
210
|
var MAX_PERSISTED_READ_ROWS = 50001;
|
|
211
|
+
var CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
209
212
|
var QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\.[a-z][a-z0-9_]{0,62}$/;
|
|
213
|
+
var SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN;
|
|
214
|
+
var RESERVED_TABLE_NAMES = /* @__PURE__ */ new Set(["actions", "query"]);
|
|
215
|
+
var RESERVED_COLUMN_NAMES = /* @__PURE__ */ new Set(["select", "order", "limit", "offset"]);
|
|
210
216
|
var CELL_PARTS = ["at", "by", "rev", "source", "conflicts"];
|
|
211
217
|
var CELL_PART_SUFFIX = {
|
|
212
218
|
at: "__at",
|
|
@@ -222,6 +228,748 @@ function cellColumnName(column, part) {
|
|
|
222
228
|
}
|
|
223
229
|
var MATERIALIZE_ACTOR = "orm:materialize";
|
|
224
230
|
JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] });
|
|
231
|
+
|
|
232
|
+
// src/predicate/ast.ts
|
|
233
|
+
var COMPARE_OPS = ["=", "!=", "<", "<=", ">", ">="];
|
|
234
|
+
function walkPredicate(predicate, visit) {
|
|
235
|
+
visit(predicate);
|
|
236
|
+
if (predicate.kind === "and" || predicate.kind === "or") {
|
|
237
|
+
for (const operand of predicate.operands) walkPredicate(operand, visit);
|
|
238
|
+
}
|
|
239
|
+
if (predicate.kind === "not") walkPredicate(predicate.operand, visit);
|
|
240
|
+
}
|
|
241
|
+
function predicateOperands(predicate) {
|
|
242
|
+
const operands = [];
|
|
243
|
+
walkPredicate(predicate, (node) => {
|
|
244
|
+
if (node.kind === "compare") operands.push(node.left, node.right);
|
|
245
|
+
});
|
|
246
|
+
return operands;
|
|
247
|
+
}
|
|
248
|
+
function referencedColumns(predicate) {
|
|
249
|
+
const names = predicateOperands(predicate).flatMap(
|
|
250
|
+
(operand) => operand.kind === "column" ? [operand.name] : []
|
|
251
|
+
);
|
|
252
|
+
return [...new Set(names)];
|
|
253
|
+
}
|
|
254
|
+
var identifierSchema = z.string().max(MAX_IDENTIFIER_LENGTH).regex(IDENTIFIER_PATTERN, "must be a lowercase identifier (a-z, 0-9, _)");
|
|
255
|
+
var namespaceSchema = z.string().regex(NAMESPACE_PATTERN, "must be lowercase, start with a letter, and be at most 41 characters");
|
|
256
|
+
var tableReferenceSchema = z.string().refine(
|
|
257
|
+
(value) => IDENTIFIER_PATTERN.test(value) || QUALIFIED_TABLE_PATTERN.test(value),
|
|
258
|
+
"must be a table name or a schema-qualified table reference"
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
// src/schema/columns.ts
|
|
262
|
+
var COLUMN_TYPES = [
|
|
263
|
+
"uuid",
|
|
264
|
+
"text",
|
|
265
|
+
"integer",
|
|
266
|
+
"bigint",
|
|
267
|
+
"numeric",
|
|
268
|
+
"double",
|
|
269
|
+
"boolean",
|
|
270
|
+
"timestamptz",
|
|
271
|
+
"date",
|
|
272
|
+
"jsonb"
|
|
273
|
+
];
|
|
274
|
+
var columnTypeSchema = z.enum(COLUMN_TYPES);
|
|
275
|
+
var FUNCTION_DEFAULTS = {
|
|
276
|
+
"gen_random_uuid()": ["uuid"],
|
|
277
|
+
"now()": ["timestamptz", "date"]
|
|
278
|
+
};
|
|
279
|
+
var CAST_PATTERN = /^([a-z][a-z0-9_]*)::([a-z]+)$/;
|
|
280
|
+
function defaultIssue(value, type) {
|
|
281
|
+
if (typeof value === "boolean") return type === "boolean" ? null : `boolean default is invalid for type '${type}'`;
|
|
282
|
+
if (typeof value === "number") {
|
|
283
|
+
if (!["integer", "bigint", "numeric", "double"].includes(type)) {
|
|
284
|
+
return `numeric default is invalid for type '${type}'`;
|
|
285
|
+
}
|
|
286
|
+
if (["integer", "bigint"].includes(type)) {
|
|
287
|
+
if (!Number.isInteger(value)) return `default for type '${type}' must be an integer`;
|
|
288
|
+
if (!Number.isSafeInteger(value)) {
|
|
289
|
+
return `default for type '${type}' exceeds the safe integer range \u2014 YAML numbers lose precision past 2^53`;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (type === "numeric" && Math.abs(value) > Number.MAX_SAFE_INTEGER) {
|
|
293
|
+
return "numeric default exceeds the safe float range \u2014 write it as a string (e.g. '9007199254740993') to keep exact precision";
|
|
294
|
+
}
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
const allowedTypes = FUNCTION_DEFAULTS[value];
|
|
298
|
+
if (allowedTypes) return allowedTypes.includes(type) ? null : `default '${value}' is invalid for type '${type}'`;
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
var columnSchema = z.strictObject({
|
|
302
|
+
type: columnTypeSchema,
|
|
303
|
+
primary_key: z.boolean().optional(),
|
|
304
|
+
nullable: z.boolean().optional(),
|
|
305
|
+
unique: z.boolean().optional(),
|
|
306
|
+
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
|
|
307
|
+
description: z.string().optional(),
|
|
308
|
+
renamed_from: identifierSchema.optional(),
|
|
309
|
+
cast: z.string().optional(),
|
|
310
|
+
deprecated: z.boolean().optional()
|
|
311
|
+
}).superRefine((column, ctx) => {
|
|
312
|
+
if (column.default !== void 0) {
|
|
313
|
+
const issue = defaultIssue(column.default, column.type);
|
|
314
|
+
if (issue) ctx.addIssue({ code: "custom", message: issue, path: ["default"] });
|
|
315
|
+
}
|
|
316
|
+
if (column.primary_key && column.nullable) {
|
|
317
|
+
ctx.addIssue({ code: "custom", message: "a primary key column cannot be nullable", path: ["nullable"] });
|
|
318
|
+
}
|
|
319
|
+
if (column.primary_key && column.deprecated) {
|
|
320
|
+
ctx.addIssue({ code: "custom", message: "a primary key column cannot be deprecated", path: ["deprecated"] });
|
|
321
|
+
}
|
|
322
|
+
if (column.cast && !CAST_PATTERN.test(column.cast)) {
|
|
323
|
+
ctx.addIssue({ code: "custom", message: "cast must have the shape '<column>::<type>'", path: ["cast"] });
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
function castParts(cast) {
|
|
327
|
+
const match = CAST_PATTERN.exec(cast);
|
|
328
|
+
if (!match) return null;
|
|
329
|
+
return { column: match[1], type: match[2] };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/errors.ts
|
|
333
|
+
var OrmDefinitionError = class extends Error {
|
|
334
|
+
constructor(message, file) {
|
|
335
|
+
super(file ? `${file}: ${message}` : message);
|
|
336
|
+
this.file = file;
|
|
337
|
+
}
|
|
338
|
+
name = "OrmDefinitionError";
|
|
339
|
+
};
|
|
340
|
+
var PredicateParseError = class extends Error {
|
|
341
|
+
constructor(message, position) {
|
|
342
|
+
super(`${message} (at position ${position})`);
|
|
343
|
+
this.position = position;
|
|
344
|
+
}
|
|
345
|
+
name = "PredicateParseError";
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
// src/predicate/parse.ts
|
|
349
|
+
var KEYWORDS = /* @__PURE__ */ new Set(["and", "or", "not", "true", "false", "null", "claim", "capability"]);
|
|
350
|
+
var OPERATOR_PATTERN = /^(!=|<=|>=|<>|=|<|>)/;
|
|
351
|
+
var IDENTIFIER_START = /[a-z_]/;
|
|
352
|
+
var IDENTIFIER_CHAR = /[a-z0-9_.-]/;
|
|
353
|
+
var NUMBER_PATTERN = /^-?\d+(\.\d+)?/;
|
|
354
|
+
function tokenize2(source) {
|
|
355
|
+
const tokens = [];
|
|
356
|
+
let position = 0;
|
|
357
|
+
while (position < source.length) {
|
|
358
|
+
const char = source[position];
|
|
359
|
+
if (/\s/.test(char)) {
|
|
360
|
+
position += 1;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (char === "(") {
|
|
364
|
+
tokens.push({ kind: "lparen", value: char, position });
|
|
365
|
+
position += 1;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
if (char === ")") {
|
|
369
|
+
tokens.push({ kind: "rparen", value: char, position });
|
|
370
|
+
position += 1;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (char === ",") {
|
|
374
|
+
tokens.push({ kind: "comma", value: char, position });
|
|
375
|
+
position += 1;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (char === "'") {
|
|
379
|
+
const { value, end } = readString(source, position);
|
|
380
|
+
tokens.push({ kind: "string", value, position });
|
|
381
|
+
position = end;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const operator = OPERATOR_PATTERN.exec(source.slice(position));
|
|
385
|
+
if (operator) {
|
|
386
|
+
const value = operator[0] === "<>" ? "!=" : operator[0];
|
|
387
|
+
tokens.push({ kind: "operator", value, position });
|
|
388
|
+
position += operator[0].length;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const number = NUMBER_PATTERN.exec(source.slice(position));
|
|
392
|
+
if (number && !IDENTIFIER_START.test(char)) {
|
|
393
|
+
tokens.push({ kind: "number", value: number[0], position });
|
|
394
|
+
position += number[0].length;
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
if (IDENTIFIER_START.test(char)) {
|
|
398
|
+
let end = position;
|
|
399
|
+
while (end < source.length && IDENTIFIER_CHAR.test(source[end])) end += 1;
|
|
400
|
+
tokens.push({ kind: "identifier", value: source.slice(position, end), position });
|
|
401
|
+
position = end;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
throw new PredicateParseError(`unexpected character '${char}'`, position);
|
|
405
|
+
}
|
|
406
|
+
tokens.push({ kind: "end", value: "", position: source.length });
|
|
407
|
+
return tokens;
|
|
408
|
+
}
|
|
409
|
+
function readString(source, start) {
|
|
410
|
+
let value = "";
|
|
411
|
+
let position = start + 1;
|
|
412
|
+
while (position < source.length) {
|
|
413
|
+
const char = source[position];
|
|
414
|
+
if (char !== "'") {
|
|
415
|
+
value += char;
|
|
416
|
+
position += 1;
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (source[position + 1] === "'") {
|
|
420
|
+
value += "'";
|
|
421
|
+
position += 2;
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
return { value, end: position + 1 };
|
|
425
|
+
}
|
|
426
|
+
throw new PredicateParseError("unterminated string literal", start);
|
|
427
|
+
}
|
|
428
|
+
var Parser2 = class {
|
|
429
|
+
constructor(tokens) {
|
|
430
|
+
this.tokens = tokens;
|
|
431
|
+
}
|
|
432
|
+
index = 0;
|
|
433
|
+
parse() {
|
|
434
|
+
const predicate = this.parseOr();
|
|
435
|
+
this.expect("end", "end of expression");
|
|
436
|
+
return predicate;
|
|
437
|
+
}
|
|
438
|
+
parseOr() {
|
|
439
|
+
const operands = [this.parseAnd()];
|
|
440
|
+
while (this.matchKeyword("or")) operands.push(this.parseAnd());
|
|
441
|
+
return operands.length === 1 ? operands[0] : { kind: "or", operands };
|
|
442
|
+
}
|
|
443
|
+
parseAnd() {
|
|
444
|
+
const operands = [this.parseNot()];
|
|
445
|
+
while (this.matchKeyword("and")) operands.push(this.parseNot());
|
|
446
|
+
return operands.length === 1 ? operands[0] : { kind: "and", operands };
|
|
447
|
+
}
|
|
448
|
+
parseNot() {
|
|
449
|
+
if (this.matchKeyword("not")) return { kind: "not", operand: this.parseNot() };
|
|
450
|
+
return this.parsePrimary();
|
|
451
|
+
}
|
|
452
|
+
parsePrimary() {
|
|
453
|
+
if (this.peek().kind === "lparen") {
|
|
454
|
+
this.advance();
|
|
455
|
+
const inner = this.parseOr();
|
|
456
|
+
this.expect("rparen", "')'");
|
|
457
|
+
return inner;
|
|
458
|
+
}
|
|
459
|
+
if (this.peekKeyword("capability")) {
|
|
460
|
+
const capability = this.parseCapability();
|
|
461
|
+
const next = this.peek();
|
|
462
|
+
if (next.kind === "operator") {
|
|
463
|
+
throw new PredicateParseError("capability() is boolean-valued and cannot appear in a comparison", next.position);
|
|
464
|
+
}
|
|
465
|
+
return capability;
|
|
466
|
+
}
|
|
467
|
+
return this.parseComparison();
|
|
468
|
+
}
|
|
469
|
+
parseCapability() {
|
|
470
|
+
this.advance();
|
|
471
|
+
const key = this.parseCallArgument("capability");
|
|
472
|
+
if (!CAPABILITY_KEY_PATTERN.test(key)) {
|
|
473
|
+
throw new PredicateParseError(`invalid capability key '${key}'`, this.peek().position);
|
|
474
|
+
}
|
|
475
|
+
return { kind: "capability", key };
|
|
476
|
+
}
|
|
477
|
+
parseComparison() {
|
|
478
|
+
const left = this.parseOperand();
|
|
479
|
+
const operator = this.expect("operator", "a comparison operator");
|
|
480
|
+
if (!COMPARE_OPS.includes(operator.value)) {
|
|
481
|
+
throw new PredicateParseError(`unsupported operator '${operator.value}'`, operator.position);
|
|
482
|
+
}
|
|
483
|
+
const right = this.parseOperand();
|
|
484
|
+
return { kind: "compare", op: operator.value, left, right };
|
|
485
|
+
}
|
|
486
|
+
parseOperand() {
|
|
487
|
+
const token = this.peek();
|
|
488
|
+
if (token.kind === "string") {
|
|
489
|
+
this.advance();
|
|
490
|
+
return { kind: "literal", value: token.value };
|
|
491
|
+
}
|
|
492
|
+
if (token.kind === "number") {
|
|
493
|
+
this.advance();
|
|
494
|
+
const value = Number(token.value);
|
|
495
|
+
if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) {
|
|
496
|
+
throw new PredicateParseError(
|
|
497
|
+
`numeric literal '${token.value}' exceeds safe integer precision \u2014 quote it as a string`,
|
|
498
|
+
token.position
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
return { kind: "literal", value };
|
|
502
|
+
}
|
|
503
|
+
if (token.kind !== "identifier") {
|
|
504
|
+
throw new PredicateParseError(`expected an operand, got '${token.value || "end"}'`, token.position);
|
|
505
|
+
}
|
|
506
|
+
this.advance();
|
|
507
|
+
if (token.value === "true" || token.value === "false") {
|
|
508
|
+
return { kind: "literal", value: token.value === "true" };
|
|
509
|
+
}
|
|
510
|
+
if (token.value === "null") return { kind: "literal", value: null };
|
|
511
|
+
if (token.value === "claim") {
|
|
512
|
+
const key = this.parseCallArgument("claim");
|
|
513
|
+
if (!CLAIM_KEY_PATTERN.test(key)) {
|
|
514
|
+
throw new PredicateParseError(`invalid claim key '${key}'`, token.position);
|
|
515
|
+
}
|
|
516
|
+
return { kind: "claim", key };
|
|
517
|
+
}
|
|
518
|
+
if (token.value === "capability") {
|
|
519
|
+
throw new PredicateParseError("capability() is boolean-valued and cannot appear in a comparison", token.position);
|
|
520
|
+
}
|
|
521
|
+
if (KEYWORDS.has(token.value) || !IDENTIFIER_PATTERN.test(token.value)) {
|
|
522
|
+
throw new PredicateParseError(`invalid column reference '${token.value}'`, token.position);
|
|
523
|
+
}
|
|
524
|
+
return { kind: "column", name: token.value };
|
|
525
|
+
}
|
|
526
|
+
parseCallArgument(fn) {
|
|
527
|
+
this.expect("lparen", `'(' after ${fn}`);
|
|
528
|
+
const argument = this.expect("string", `a quoted key in ${fn}(...)`);
|
|
529
|
+
this.expect("rparen", `')' after ${fn} key`);
|
|
530
|
+
return argument.value;
|
|
531
|
+
}
|
|
532
|
+
peek() {
|
|
533
|
+
return this.tokens[this.index];
|
|
534
|
+
}
|
|
535
|
+
peekKeyword(keyword) {
|
|
536
|
+
const token = this.peek();
|
|
537
|
+
return token.kind === "identifier" && token.value === keyword;
|
|
538
|
+
}
|
|
539
|
+
matchKeyword(keyword) {
|
|
540
|
+
if (!this.peekKeyword(keyword)) return false;
|
|
541
|
+
this.advance();
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
advance() {
|
|
545
|
+
const token = this.peek();
|
|
546
|
+
if (token.kind !== "end") this.index += 1;
|
|
547
|
+
return token;
|
|
548
|
+
}
|
|
549
|
+
expect(kind, description) {
|
|
550
|
+
const token = this.peek();
|
|
551
|
+
if (token.kind !== kind) {
|
|
552
|
+
throw new PredicateParseError(`expected ${description}, got '${token.value || "end"}'`, token.position);
|
|
553
|
+
}
|
|
554
|
+
return this.advance();
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
function parsePredicate(source) {
|
|
558
|
+
const trimmed = source.trim();
|
|
559
|
+
if (trimmed.length === 0) throw new PredicateParseError("empty predicate", 0);
|
|
560
|
+
return { source: trimmed, ast: new Parser2(tokenize2(trimmed)).parse() };
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// src/schema/predicates.ts
|
|
564
|
+
var parsedPredicateSchema = z.string().transform((source, ctx) => {
|
|
565
|
+
try {
|
|
566
|
+
return parsePredicate(source);
|
|
567
|
+
} catch (error) {
|
|
568
|
+
ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : String(error) });
|
|
569
|
+
return z.NEVER;
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
// src/schema/actions.ts
|
|
574
|
+
var EXECUTES_VERB_PATTERN = /^\s*(insert|update|delete)\b/i;
|
|
575
|
+
var DOLLAR_QUOTE_PATTERN = /\$[a-zA-Z0-9_]*\$/;
|
|
576
|
+
var RETURNING_PATTERN = /\breturning\b/i;
|
|
577
|
+
var ESCAPE_STRING_PATTERN = /(?<![a-zA-Z0-9_])[Ee]'/;
|
|
578
|
+
var MASKED_CLAIM_CALL_PATTERN = /\b(?:claim|capability)\(\s*''\s*\)/g;
|
|
579
|
+
var BARE_CLAIM_CALL_PATTERN = /\b(?:claim|capability)\s*\(/;
|
|
580
|
+
var EXISTS_ENTRY_PATTERN = /^exists\(\s*'([^']+)'\s*,\s*([a-z][a-z0-9_]*)\s*\)$/;
|
|
581
|
+
var NAMED_PARAM_PATTERN = /(?<!:):([a-z][a-z0-9_]*)/g;
|
|
582
|
+
var QUOTED_STRING_PATTERN = /'(?:[^']|'')*'/g;
|
|
583
|
+
var SQL_COMMENT_PATTERN = /--|\/\*/;
|
|
584
|
+
var actionParamSchema = z.strictObject({
|
|
585
|
+
type: columnTypeSchema,
|
|
586
|
+
optional: z.boolean().optional(),
|
|
587
|
+
description: z.string().optional()
|
|
588
|
+
});
|
|
589
|
+
var validatesEntrySchema = z.string().transform((source, ctx) => {
|
|
590
|
+
const match = EXISTS_ENTRY_PATTERN.exec(source.trim());
|
|
591
|
+
if (!match) {
|
|
592
|
+
ctx.addIssue({ code: "custom", message: "validates entries must have the shape exists('<table>', <param>)" });
|
|
593
|
+
return z.NEVER;
|
|
594
|
+
}
|
|
595
|
+
const table = tableReferenceSchema.safeParse(match[1]);
|
|
596
|
+
if (!table.success) {
|
|
597
|
+
ctx.addIssue({ code: "custom", message: `invalid table reference '${match[1]}'` });
|
|
598
|
+
return z.NEVER;
|
|
599
|
+
}
|
|
600
|
+
return { source: source.trim(), table: table.data, param: match[2] };
|
|
601
|
+
});
|
|
602
|
+
var AUDIT_ACTIONS = ["create", "update", "delete"];
|
|
603
|
+
var auditSchema = z.strictObject({
|
|
604
|
+
action: z.enum(AUDIT_ACTIONS),
|
|
605
|
+
resource: identifierSchema.optional()
|
|
606
|
+
});
|
|
607
|
+
var actionSchema = z.strictObject({
|
|
608
|
+
description: z.string().optional(),
|
|
609
|
+
requires: parsedPredicateSchema.optional(),
|
|
610
|
+
params: z.record(identifierSchema, actionParamSchema).optional(),
|
|
611
|
+
validates: z.array(validatesEntrySchema).optional(),
|
|
612
|
+
// One statement, or an ordered list run atomically in the action function.
|
|
613
|
+
executes: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
|
|
614
|
+
// Declares the columns the action's RETURNING yields. Present → the
|
|
615
|
+
// function returns those rows (typed in the client); absent → the action
|
|
616
|
+
// reports rows_affected only. The column names/types must match the
|
|
617
|
+
// RETURNING list, which Postgres enforces at CREATE FUNCTION.
|
|
618
|
+
returns: z.record(identifierSchema, columnTypeSchema).optional(),
|
|
619
|
+
audit: auditSchema.optional()
|
|
620
|
+
}).superRefine((action, ctx) => {
|
|
621
|
+
const params = Object.keys(action.params ?? {});
|
|
622
|
+
if (action.requires && referencedColumns(action.requires.ast).length > 0) {
|
|
623
|
+
ctx.addIssue({
|
|
624
|
+
code: "custom",
|
|
625
|
+
message: "requires may reference claims and capabilities only, not columns",
|
|
626
|
+
path: ["requires"]
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
for (const issue of executesIssues(action.executes, new Set(params), action.returns !== void 0)) {
|
|
630
|
+
ctx.addIssue({ code: "custom", message: issue, path: ["executes"] });
|
|
631
|
+
}
|
|
632
|
+
if (action.returns && Object.keys(action.returns).length === 0) {
|
|
633
|
+
ctx.addIssue({ code: "custom", message: "returns must declare at least one column", path: ["returns"] });
|
|
634
|
+
}
|
|
635
|
+
for (const [index, entry] of (action.validates ?? []).entries()) {
|
|
636
|
+
if (!params.includes(entry.param)) {
|
|
637
|
+
ctx.addIssue({
|
|
638
|
+
code: "custom",
|
|
639
|
+
message: `validates references undeclared param '${entry.param}'`,
|
|
640
|
+
path: ["validates", index]
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
function extractNamedParams(sql) {
|
|
646
|
+
const withoutStrings = sql.replace(QUOTED_STRING_PATTERN, "''");
|
|
647
|
+
const names = [...withoutStrings.matchAll(NAMED_PARAM_PATTERN)].map((match) => match[1]);
|
|
648
|
+
return [...new Set(names)];
|
|
649
|
+
}
|
|
650
|
+
function actionStatementSources(executes) {
|
|
651
|
+
return (Array.isArray(executes) ? executes : [executes]).map((statement) => statement.trim());
|
|
652
|
+
}
|
|
653
|
+
function executesIssues(executes, declaredParams, hasReturns) {
|
|
654
|
+
const issues = [];
|
|
655
|
+
const statements = actionStatementSources(executes);
|
|
656
|
+
statements.forEach((statement, index) => {
|
|
657
|
+
const withoutStrings = statement.replace(QUOTED_STRING_PATTERN, "''");
|
|
658
|
+
const at = statements.length > 1 ? ` (statement ${index + 1})` : "";
|
|
659
|
+
if (!EXECUTES_VERB_PATTERN.test(statement)) issues.push(`executes must be INSERT, UPDATE, or DELETE${at}`);
|
|
660
|
+
if (withoutStrings.replace(/;\s*$/, "").includes(";")) issues.push(`each executes entry must be a single statement${at}`);
|
|
661
|
+
if (SQL_COMMENT_PATTERN.test(withoutStrings)) issues.push(`executes must not contain SQL comments${at}`);
|
|
662
|
+
if (DOLLAR_QUOTE_PATTERN.test(withoutStrings)) issues.push(`executes must not use dollar-quoted strings${at}`);
|
|
663
|
+
if (ESCAPE_STRING_PATTERN.test(withoutStrings)) issues.push(`executes must not use escape strings (E'\u2026')${at}`);
|
|
664
|
+
if (withoutStrings.includes('"')) issues.push(`executes must not use double-quoted identifiers${at}`);
|
|
665
|
+
if (BARE_CLAIM_CALL_PATTERN.test(withoutStrings.replace(MASKED_CLAIM_CALL_PATTERN, ""))) {
|
|
666
|
+
issues.push(`executes has a malformed claim()/capability() call \u2014 use e.g. claim('sub')${at}`);
|
|
667
|
+
}
|
|
668
|
+
if (RETURNING_PATTERN.test(withoutStrings) && !(hasReturns && index === statements.length - 1)) {
|
|
669
|
+
issues.push(
|
|
670
|
+
hasReturns ? `only the last executes statement may use RETURNING${at}` : `executes must not use RETURNING unless the action declares returns${at}`
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
const last = statements.at(-1);
|
|
675
|
+
if (hasReturns && last && !RETURNING_PATTERN.test(last.replace(QUOTED_STRING_PATTERN, "''"))) {
|
|
676
|
+
issues.push("the last executes statement must use RETURNING to populate the declared returns columns");
|
|
677
|
+
}
|
|
678
|
+
const undeclared = extractNamedParams(statements.join("\n")).filter((name) => !declaredParams.has(name));
|
|
679
|
+
if (undeclared.length > 0) issues.push(`executes references undeclared params: ${undeclared.join(", ")}`);
|
|
680
|
+
return issues;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// src/schema/table.ts
|
|
684
|
+
var linkSchema = z.strictObject({
|
|
685
|
+
to: tableReferenceSchema,
|
|
686
|
+
on: identifierSchema,
|
|
687
|
+
enforce: z.boolean().optional(),
|
|
688
|
+
description: z.string().optional()
|
|
689
|
+
});
|
|
690
|
+
var indexSchema = z.union([
|
|
691
|
+
z.array(identifierSchema).min(1),
|
|
692
|
+
z.strictObject({
|
|
693
|
+
columns: z.array(identifierSchema).min(1),
|
|
694
|
+
unique: z.boolean().optional(),
|
|
695
|
+
name: identifierSchema.optional()
|
|
696
|
+
})
|
|
697
|
+
]).transform((index) => Array.isArray(index) ? { columns: index } : index);
|
|
698
|
+
var policiesSchema = z.strictObject({
|
|
699
|
+
read: parsedPredicateSchema.optional(),
|
|
700
|
+
write: parsedPredicateSchema.optional(),
|
|
701
|
+
insert: parsedPredicateSchema.optional(),
|
|
702
|
+
update: parsedPredicateSchema.optional()
|
|
703
|
+
});
|
|
704
|
+
z.strictObject({
|
|
705
|
+
namespace: namespaceSchema,
|
|
706
|
+
table: identifierSchema,
|
|
707
|
+
description: z.string().optional(),
|
|
708
|
+
columns: z.record(identifierSchema, columnSchema).optional(),
|
|
709
|
+
source: z.string().regex(SYNCED_SOURCE_PATTERN, "source must be a qualified lowercase schema.table identifier").optional(),
|
|
710
|
+
links: z.record(identifierSchema, linkSchema).optional(),
|
|
711
|
+
indexes: z.array(indexSchema).optional(),
|
|
712
|
+
policies: policiesSchema.optional(),
|
|
713
|
+
actions: z.record(identifierSchema, actionSchema).optional()
|
|
714
|
+
}).superRefine((table, ctx) => {
|
|
715
|
+
if (RESERVED_TABLE_NAMES.has(table.table)) {
|
|
716
|
+
ctx.addIssue({ code: "custom", message: `'${table.table}' is a reserved table name`, path: ["table"] });
|
|
717
|
+
}
|
|
718
|
+
for (const name of Object.keys(table.columns ?? {})) {
|
|
719
|
+
if (RESERVED_COLUMN_NAMES.has(name)) {
|
|
720
|
+
ctx.addIssue({
|
|
721
|
+
code: "custom",
|
|
722
|
+
message: `column '${name}' collides with the Data API's reserved query parameters (select, order, limit, offset) \u2014 it could never be filtered`,
|
|
723
|
+
path: ["columns", name]
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (table.source) validateSyncedTable(table, ctx);
|
|
728
|
+
else validateColumnTable(table, ctx);
|
|
729
|
+
validateLinks(table, ctx);
|
|
730
|
+
validatePolicyColumns(table, ctx);
|
|
731
|
+
validateDerivedNameLengths(table, ctx);
|
|
732
|
+
});
|
|
733
|
+
var indexName = (table, definition) => definition.name ?? `ix_${table}_${definition.columns.join("_")}`;
|
|
734
|
+
var policyName = (table, suffix) => `${table}_${suffix}`;
|
|
735
|
+
var foreignKeyName = (table, link) => `fk_${table}_${link}`;
|
|
736
|
+
function validateSyncedTable(table, ctx) {
|
|
737
|
+
const forbidden = [
|
|
738
|
+
["actions", "synced tables are read-only; actions are not allowed"],
|
|
739
|
+
["indexes", "v1 synced tables cannot declare indexes; declare them with defineSyncedTable({ indexes }) in a v2 definition"]
|
|
740
|
+
];
|
|
741
|
+
for (const [field, message] of forbidden) {
|
|
742
|
+
if (table[field] !== void 0) ctx.addIssue({ code: "custom", message, path: [field] });
|
|
743
|
+
}
|
|
744
|
+
if (table.policies?.write) {
|
|
745
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "write"] });
|
|
746
|
+
}
|
|
747
|
+
if (table.policies?.insert) {
|
|
748
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "insert"] });
|
|
749
|
+
}
|
|
750
|
+
if (table.policies?.update) {
|
|
751
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "update"] });
|
|
752
|
+
}
|
|
753
|
+
const columns = table.columns ?? {};
|
|
754
|
+
const names = Object.keys(columns);
|
|
755
|
+
if (names.length === 0) return;
|
|
756
|
+
const primaryKeys = names.filter((name) => columns[name]?.primary_key);
|
|
757
|
+
if (primaryKeys.length !== 1) {
|
|
758
|
+
ctx.addIssue({ code: "custom", message: "exactly one column must be primary_key", path: ["columns"] });
|
|
759
|
+
}
|
|
760
|
+
validateRenames(columns, names, ctx);
|
|
761
|
+
for (const name of names) {
|
|
762
|
+
const column = columns[name];
|
|
763
|
+
if (!column) continue;
|
|
764
|
+
const cast = column.cast ? castParts(column.cast) : null;
|
|
765
|
+
if (column.cast && cast?.column !== name) {
|
|
766
|
+
ctx.addIssue({
|
|
767
|
+
code: "custom",
|
|
768
|
+
message: "cast must reference the column it is declared on",
|
|
769
|
+
path: ["columns", name, "cast"]
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
if (cast && cast.type !== column.type) {
|
|
773
|
+
ctx.addIssue({
|
|
774
|
+
code: "custom",
|
|
775
|
+
message: `cast target '${cast.type}' must match the declared type '${column.type}'`,
|
|
776
|
+
path: ["columns", name, "cast"]
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function validateRenames(columns, names, ctx) {
|
|
782
|
+
const renameSources = /* @__PURE__ */ new Map();
|
|
783
|
+
for (const name of names) {
|
|
784
|
+
const renamedFrom = columns[name]?.renamed_from;
|
|
785
|
+
if (!renamedFrom) continue;
|
|
786
|
+
if (renamedFrom === name || names.includes(renamedFrom)) {
|
|
787
|
+
ctx.addIssue({
|
|
788
|
+
code: "custom",
|
|
789
|
+
message: "renamed_from must name a column that no longer exists",
|
|
790
|
+
path: ["columns", name, "renamed_from"]
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
const claimed = renameSources.get(renamedFrom);
|
|
794
|
+
if (claimed) {
|
|
795
|
+
ctx.addIssue({
|
|
796
|
+
code: "custom",
|
|
797
|
+
message: `renamed_from '${renamedFrom}' is already claimed by '${claimed}'`,
|
|
798
|
+
path: ["columns", name, "renamed_from"]
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
renameSources.set(renamedFrom, name);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
function validateColumnTable(table, ctx) {
|
|
805
|
+
const columns = table.columns ?? {};
|
|
806
|
+
const names = Object.keys(columns);
|
|
807
|
+
if (names.length === 0) {
|
|
808
|
+
ctx.addIssue({ code: "custom", message: "a table must declare columns or a source", path: ["columns"] });
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
const primaryKeys = names.filter((name) => columns[name]?.primary_key);
|
|
812
|
+
if (primaryKeys.length !== 1) {
|
|
813
|
+
ctx.addIssue({ code: "custom", message: "exactly one column must be primary_key", path: ["columns"] });
|
|
814
|
+
}
|
|
815
|
+
validateRenames(columns, names, ctx);
|
|
816
|
+
for (const name of names) {
|
|
817
|
+
const column = columns[name];
|
|
818
|
+
if (!column) continue;
|
|
819
|
+
const cast = column.cast ? castParts(column.cast) : null;
|
|
820
|
+
if (column.cast && cast?.column !== name) {
|
|
821
|
+
ctx.addIssue({
|
|
822
|
+
code: "custom",
|
|
823
|
+
message: "cast must reference the column it is declared on",
|
|
824
|
+
path: ["columns", name, "cast"]
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
if (cast && cast.type !== column.type) {
|
|
828
|
+
ctx.addIssue({
|
|
829
|
+
code: "custom",
|
|
830
|
+
message: `cast target '${cast.type}' must match the declared type '${column.type}'`,
|
|
831
|
+
path: ["columns", name, "cast"]
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
for (const [position, index] of (table.indexes ?? []).entries()) {
|
|
836
|
+
if (new Set(index.columns).size !== index.columns.length) {
|
|
837
|
+
ctx.addIssue({
|
|
838
|
+
code: "custom",
|
|
839
|
+
message: "index names a column more than once",
|
|
840
|
+
path: ["indexes", position]
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
for (const column of index.columns) {
|
|
844
|
+
if (!names.includes(column)) {
|
|
845
|
+
ctx.addIssue({
|
|
846
|
+
code: "custom",
|
|
847
|
+
message: `index references unknown column '${column}'`,
|
|
848
|
+
path: ["indexes", position]
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
function validateLinks(table, ctx) {
|
|
855
|
+
const columnNames = Object.keys(table.columns ?? {});
|
|
856
|
+
for (const [name, link] of Object.entries(table.links ?? {})) {
|
|
857
|
+
if (columnNames.length > 0 && !columnNames.includes(link.on)) {
|
|
858
|
+
ctx.addIssue({ code: "custom", message: `link references unknown column '${link.on}'`, path: ["links", name, "on"] });
|
|
859
|
+
}
|
|
860
|
+
if (link.enforce && link.to.includes(".")) {
|
|
861
|
+
ctx.addIssue({
|
|
862
|
+
code: "custom",
|
|
863
|
+
message: "enforce is only valid for links inside the namespace; cross-boundary links stay soft",
|
|
864
|
+
path: ["links", name, "enforce"]
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
if (link.enforce && table.source) {
|
|
868
|
+
ctx.addIssue({
|
|
869
|
+
code: "custom",
|
|
870
|
+
message: "a synced table cannot enforce foreign keys \u2014 its DDL is owned by the sync",
|
|
871
|
+
path: ["links", name, "enforce"]
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
function validateDerivedNameLengths(table, ctx) {
|
|
877
|
+
const worstPolicy = policyName(table.table, "insert");
|
|
878
|
+
if (!table.source && worstPolicy.length > MAX_IDENTIFIER_LENGTH) {
|
|
879
|
+
ctx.addIssue({
|
|
880
|
+
code: "custom",
|
|
881
|
+
message: `table name is too long \u2014 the derived policy name '${worstPolicy}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit`,
|
|
882
|
+
path: ["table"]
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
for (const [position, index] of (table.indexes ?? []).entries()) {
|
|
886
|
+
const name = indexName(table.table, index);
|
|
887
|
+
if (name.length > MAX_IDENTIFIER_LENGTH) {
|
|
888
|
+
ctx.addIssue({
|
|
889
|
+
code: "custom",
|
|
890
|
+
message: `derived index name '${name}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 set a shorter explicit name`,
|
|
891
|
+
path: ["indexes", position]
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
for (const [name, link] of Object.entries(table.links ?? {})) {
|
|
896
|
+
const constraint = foreignKeyName(table.table, name);
|
|
897
|
+
if (link.enforce && constraint.length > MAX_IDENTIFIER_LENGTH) {
|
|
898
|
+
ctx.addIssue({
|
|
899
|
+
code: "custom",
|
|
900
|
+
message: `derived foreign-key name '${constraint}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 shorten the link or table name`,
|
|
901
|
+
path: ["links", name]
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
for (const name of Object.keys(table.actions ?? {})) {
|
|
906
|
+
const fnName = `action_${name}`;
|
|
907
|
+
if (fnName.length > MAX_IDENTIFIER_LENGTH) {
|
|
908
|
+
ctx.addIssue({
|
|
909
|
+
code: "custom",
|
|
910
|
+
message: `derived action function name '${fnName}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 shorten the action name`,
|
|
911
|
+
path: ["actions", name]
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
var TYPE_GROUPS = {
|
|
917
|
+
integer: "numeric",
|
|
918
|
+
bigint: "numeric",
|
|
919
|
+
numeric: "numeric",
|
|
920
|
+
double: "numeric",
|
|
921
|
+
text: "text",
|
|
922
|
+
uuid: "uuid",
|
|
923
|
+
date: "temporal",
|
|
924
|
+
timestamptz: "temporal",
|
|
925
|
+
boolean: "boolean",
|
|
926
|
+
jsonb: "jsonb"
|
|
927
|
+
};
|
|
928
|
+
function validatePolicyColumns(table, ctx) {
|
|
929
|
+
const columns = table.columns ?? {};
|
|
930
|
+
const columnNames = Object.keys(columns);
|
|
931
|
+
if (columnNames.length === 0) return;
|
|
932
|
+
for (const kind of ["read", "write", "insert", "update"]) {
|
|
933
|
+
const predicate = table.policies?.[kind];
|
|
934
|
+
if (!predicate) continue;
|
|
935
|
+
for (const column of referencedColumns(predicate.ast)) {
|
|
936
|
+
if (!columnNames.includes(column)) {
|
|
937
|
+
ctx.addIssue({
|
|
938
|
+
code: "custom",
|
|
939
|
+
message: `policy references unknown column '${column}'`,
|
|
940
|
+
path: ["policies", kind]
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
walkPredicate(predicate.ast, (node) => {
|
|
945
|
+
if (node.kind !== "compare") return;
|
|
946
|
+
const issue = comparisonTypeIssue(node.left, node.right, columns);
|
|
947
|
+
if (issue) ctx.addIssue({ code: "custom", message: issue, path: ["policies", kind] });
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
function comparisonTypeIssue(left, right, columns) {
|
|
952
|
+
const groupOf = (operand) => operand.kind === "column" ? columns[operand.name] ? TYPE_GROUPS[columns[operand.name].type] : null : null;
|
|
953
|
+
if (left.kind === "column" && right.kind === "column") {
|
|
954
|
+
const leftGroup = groupOf(left);
|
|
955
|
+
const rightGroup = groupOf(right);
|
|
956
|
+
if (leftGroup && rightGroup && leftGroup !== rightGroup) {
|
|
957
|
+
return `policy compares '${left.name}' (${columns[left.name].type}) with '${right.name}' (${columns[right.name].type}) \u2014 incomparable types`;
|
|
958
|
+
}
|
|
959
|
+
return null;
|
|
960
|
+
}
|
|
961
|
+
const column = left.kind === "column" ? left : right.kind === "column" ? right : null;
|
|
962
|
+
const literal = left.kind === "literal" ? left : right.kind === "literal" ? right : null;
|
|
963
|
+
if (!column || !literal || literal.value === null) return null;
|
|
964
|
+
const columnGroup = groupOf(column);
|
|
965
|
+
if (!columnGroup) return null;
|
|
966
|
+
if (typeof literal.value === "string") return null;
|
|
967
|
+
const literalGroup = typeof literal.value === "number" ? "numeric" : "boolean";
|
|
968
|
+
if (literalGroup !== columnGroup) {
|
|
969
|
+
return `policy compares '${column.name}' (${columns[column.name].type}) with a ${typeof literal.value} literal \u2014 incomparable types`;
|
|
970
|
+
}
|
|
971
|
+
return null;
|
|
972
|
+
}
|
|
225
973
|
var policyVariantSchema = z.object({
|
|
226
974
|
/** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
|
|
227
975
|
when: z.string().min(1).max(1e3),
|
|
@@ -530,7 +1278,7 @@ var CANONICAL_FORMAT = 2;
|
|
|
530
1278
|
var IDENTIFIER_RE = /^[a-z][a-z0-9_]*$/;
|
|
531
1279
|
var identifier2 = z.string().min(1).max(63).regex(IDENTIFIER_RE);
|
|
532
1280
|
var columnIdentifier = z.string().min(1).max(63).regex(COLUMN_IDENTIFIER_PATTERN);
|
|
533
|
-
var
|
|
1281
|
+
var COLUMN_TYPES2 = [
|
|
534
1282
|
"uuid",
|
|
535
1283
|
"text",
|
|
536
1284
|
"integer",
|
|
@@ -542,7 +1290,7 @@ var COLUMN_TYPES = [
|
|
|
542
1290
|
"date",
|
|
543
1291
|
"jsonb"
|
|
544
1292
|
];
|
|
545
|
-
var
|
|
1293
|
+
var columnTypeSchema2 = z.enum(COLUMN_TYPES2);
|
|
546
1294
|
var canonicalEnumSchema = z.object({
|
|
547
1295
|
name: identifier2,
|
|
548
1296
|
values: z.array(z.string().min(1).max(63)).min(1).max(100)
|
|
@@ -551,7 +1299,7 @@ var canonicalColumnSchema = z.object({
|
|
|
551
1299
|
/** Property name in TS (camelCase); columnName is the Postgres name. */
|
|
552
1300
|
name: z.string().min(1).max(63),
|
|
553
1301
|
columnName: columnIdentifier,
|
|
554
|
-
type: z.union([
|
|
1302
|
+
type: z.union([columnTypeSchema2, z.object({ enum: identifier2 })]),
|
|
555
1303
|
nullable: z.boolean().default(true),
|
|
556
1304
|
unique: z.boolean().default(false),
|
|
557
1305
|
/** Literal default, or one of the allowlisted SQL functions. */
|
|
@@ -644,7 +1392,7 @@ var canonicalActionSchema = z.object({
|
|
|
644
1392
|
name: identifier2,
|
|
645
1393
|
requires: z.string().max(1e3).optional(),
|
|
646
1394
|
params: z.record(z.string(), z.object({
|
|
647
|
-
type:
|
|
1395
|
+
type: columnTypeSchema2,
|
|
648
1396
|
nullable: z.boolean().default(false)
|
|
649
1397
|
})).default({}),
|
|
650
1398
|
executes: z.string().min(1).max(1e4),
|
|
@@ -745,7 +1493,8 @@ var canonicalTableSchema = z.object({
|
|
|
745
1493
|
if ([table.policies.write, table.policies.insert, table.policies.update].some((policy) => policy !== void 0)) {
|
|
746
1494
|
fail("is read-only and cannot declare write policies", ["policies"]);
|
|
747
1495
|
}
|
|
748
|
-
const
|
|
1496
|
+
const ownedIndexes = table.source === void 0 ? table.indexes : table.indexes.filter((index) => index.unique);
|
|
1497
|
+
const ownedCollections = [ownedIndexes, table.actions, table.checks, table.foreignKeys, table.cowMutations];
|
|
749
1498
|
const ownedMetadata = [table.cellMetadata, table.internal, table.materializes, table.renamedFrom];
|
|
750
1499
|
if (ownedCollections.some((items) => items !== void 0 && items.length > 0) || ownedMetadata.some((value) => value !== void 0)) {
|
|
751
1500
|
fail("cannot declare owned storage, constraints or identity operations");
|
|
@@ -847,6 +1596,23 @@ function trackedCellColumns(table) {
|
|
|
847
1596
|
return table.columns.filter((column) => column.cell === void 0 && !pk.has(column.columnName) && column.onUpdateFn === void 0);
|
|
848
1597
|
}
|
|
849
1598
|
var SUFFIXES = Object.values(CELL_PART_SUFFIX);
|
|
1599
|
+
function validateSyncedIndexes(table, tableIndex, ctx) {
|
|
1600
|
+
if (table.source === void 0) return;
|
|
1601
|
+
const columns = new Set(table.columns.map((column) => column.columnName));
|
|
1602
|
+
for (const [position, index] of table.indexes.entries()) {
|
|
1603
|
+
const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "indexes", position], message: `synced table '${table.table}' ${message}` });
|
|
1604
|
+
if (columns.size === 0) fail("must declare columns to declare indexes");
|
|
1605
|
+
if (index.unique) fail("cannot declare a unique index");
|
|
1606
|
+
if (new Set(index.columns).size !== index.columns.length) fail("index names a column more than once");
|
|
1607
|
+
for (const column of index.columns) {
|
|
1608
|
+
if (columns.size > 0 && !columns.has(column)) fail(`index references unknown column '${column}'`);
|
|
1609
|
+
}
|
|
1610
|
+
const name = indexName(table.table, index);
|
|
1611
|
+
if (name.length > MAX_IDENTIFIER_LENGTH) {
|
|
1612
|
+
fail(`derived index name '${name}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 set a shorter explicit name`);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
850
1616
|
function validateCellMetadata(table, index, ctx) {
|
|
851
1617
|
const fail = (message, path = ["tables", index]) => ctx.addIssue({ code: "custom", path, message });
|
|
852
1618
|
const cells = table.columns.flatMap((column, position) => column.cell ? [{ column, position, cell: column.cell }] : []);
|
|
@@ -913,12 +1679,24 @@ var localDefinitionSchema = z.object({
|
|
|
913
1679
|
}).default({ uses: [] })
|
|
914
1680
|
}).superRefine((definition, ctx) => {
|
|
915
1681
|
const seen = /* @__PURE__ */ new Set();
|
|
1682
|
+
const syncedIndexOwners = /* @__PURE__ */ new Map();
|
|
916
1683
|
for (const [index, table] of definition.tables.entries()) {
|
|
917
1684
|
if (seen.has(table.table)) {
|
|
918
1685
|
ctx.addIssue({ code: "custom", path: ["tables", index, "table"], message: `duplicate relation '${table.table}'` });
|
|
919
1686
|
}
|
|
920
1687
|
seen.add(table.table);
|
|
921
1688
|
validateCellMetadata(table, index, ctx);
|
|
1689
|
+
validateSyncedIndexes(table, index, ctx);
|
|
1690
|
+
if (table.source !== void 0) {
|
|
1691
|
+
for (const [position, entry] of table.indexes.entries()) {
|
|
1692
|
+
const name = indexName(table.table, entry);
|
|
1693
|
+
const owner = syncedIndexOwners.get(name);
|
|
1694
|
+
if (owner !== void 0) {
|
|
1695
|
+
ctx.addIssue({ code: "custom", path: ["tables", index, "indexes", position], message: `synced index '${name}' is also declared on '${owner}'` });
|
|
1696
|
+
}
|
|
1697
|
+
syncedIndexOwners.set(name, table.table);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
922
1700
|
if (table.source !== void 0) {
|
|
923
1701
|
for (const [columnIndex, column] of table.columns.entries()) {
|
|
924
1702
|
if (column.onUpdateFn !== void 0) {
|
|
@@ -1222,7 +2000,7 @@ function graphqlScalarFor(type) {
|
|
|
1222
2000
|
}
|
|
1223
2001
|
var COLUMN_TYPE_BY_SCALAR = new Map([
|
|
1224
2002
|
["ID", "text"],
|
|
1225
|
-
...
|
|
2003
|
+
...COLUMN_TYPES2.map((type) => [graphqlScalarFor(type), type])
|
|
1226
2004
|
]);
|
|
1227
2005
|
function columnTypeForScalar(scalarName) {
|
|
1228
2006
|
return COLUMN_TYPE_BY_SCALAR.get(scalarName);
|
|
@@ -1568,7 +2346,7 @@ var variableDefaultIrSchema = z.object({
|
|
|
1568
2346
|
var variableIrSchema = z.object({
|
|
1569
2347
|
name: z.string(),
|
|
1570
2348
|
type: z.union([
|
|
1571
|
-
z.object({ kind: z.literal("scalar"), scalar: z.enum(
|
|
2349
|
+
z.object({ kind: z.literal("scalar"), scalar: z.enum(COLUMN_TYPES2) }),
|
|
1572
2350
|
/** `values` is the declared membership whitelist — the executor validates against it. */
|
|
1573
2351
|
z.object({ kind: z.literal("enum"), name: z.string(), values: z.array(z.string()).min(1) }),
|
|
1574
2352
|
/** §4f dynamic slot: validated against `tables[table]` whitelists at runtime. */
|
|
@@ -1701,7 +2479,7 @@ var tableMetaIrSchema = z.object({
|
|
|
1701
2479
|
columns: z.array(z.object({
|
|
1702
2480
|
name: z.string(),
|
|
1703
2481
|
columnName: z.string(),
|
|
1704
|
-
type: z.union([z.enum(
|
|
2482
|
+
type: z.union([z.enum(COLUMN_TYPES2), z.object({ enum: z.string(), values: z.array(z.string()) })]),
|
|
1705
2483
|
nullable: z.boolean()
|
|
1706
2484
|
})),
|
|
1707
2485
|
/** Empty for keyless read-only views; keyed tables and views list logical columns. */
|
|
@@ -1770,15 +2548,6 @@ z.object({
|
|
|
1770
2548
|
}
|
|
1771
2549
|
}
|
|
1772
2550
|
});
|
|
1773
|
-
|
|
1774
|
-
// src/errors.ts
|
|
1775
|
-
var OrmDefinitionError = class extends Error {
|
|
1776
|
-
constructor(message, file) {
|
|
1777
|
-
super(file ? `${file}: ${message}` : message);
|
|
1778
|
-
this.file = file;
|
|
1779
|
-
}
|
|
1780
|
-
name = "OrmDefinitionError";
|
|
1781
|
-
};
|
|
1782
2551
|
function stableJson(value) {
|
|
1783
2552
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1784
2553
|
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|