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