@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/authoring.js
CHANGED
|
@@ -155,9 +155,13 @@ var NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/;
|
|
|
155
155
|
var IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
156
156
|
var COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/;
|
|
157
157
|
var MAX_IDENTIFIER_LENGTH = 63;
|
|
158
|
+
var CAPABILITY_KEY_PATTERN = /^(?:org\/|app\/[a-z][a-z0-9-]{0,63}\/)?[a-z0-9-]{1,64}$/;
|
|
159
|
+
var CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
158
160
|
var QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\.[a-z][a-z0-9_]{0,62}$/;
|
|
159
161
|
var SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN;
|
|
160
162
|
var HASH_DOMAIN = "sequence-orm-definitions\0";
|
|
163
|
+
var RESERVED_TABLE_NAMES = /* @__PURE__ */ new Set(["actions", "query"]);
|
|
164
|
+
var RESERVED_COLUMN_NAMES = /* @__PURE__ */ new Set(["select", "order", "limit", "offset"]);
|
|
161
165
|
var CELL_PARTS = ["at", "by", "rev", "source", "conflicts"];
|
|
162
166
|
var CELL_PART_SUFFIX = {
|
|
163
167
|
at: "__at",
|
|
@@ -182,6 +186,13 @@ var OrmDefinitionError = class extends Error {
|
|
|
182
186
|
}
|
|
183
187
|
name = "OrmDefinitionError";
|
|
184
188
|
};
|
|
189
|
+
var PredicateParseError = class extends Error {
|
|
190
|
+
constructor(message, position) {
|
|
191
|
+
super(`${message} (at position ${position})`);
|
|
192
|
+
this.position = position;
|
|
193
|
+
}
|
|
194
|
+
name = "PredicateParseError";
|
|
195
|
+
};
|
|
185
196
|
|
|
186
197
|
// src/authoring/registry.ts
|
|
187
198
|
var CONTEXT_STACK_KEY = Symbol.for("sequence.orm.authoring.context-stack.v2");
|
|
@@ -400,12 +411,28 @@ function defineSyncedTable(name2, columnsOrConfig, maybeConfig) {
|
|
|
400
411
|
);
|
|
401
412
|
}
|
|
402
413
|
}
|
|
414
|
+
for (const index of config.indexes ?? []) {
|
|
415
|
+
const label = index.name ?? index.columns.join(", ");
|
|
416
|
+
if (entries.length === 0) {
|
|
417
|
+
throw new OrmDefinitionError(
|
|
418
|
+
`synced table "${name2}": index (${label}) requires declared columns \u2014 only a typed synced table can declare indexes`,
|
|
419
|
+
file
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
if (index.unique === true) {
|
|
423
|
+
throw new OrmDefinitionError(
|
|
424
|
+
`synced table "${name2}": index (${label}) cannot be unique \u2014 the primary key already identifies a row, and a unique index can fail the sync`,
|
|
425
|
+
file
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
403
429
|
const tableConfig = {};
|
|
404
430
|
if (config.description !== void 0) tableConfig.description = config.description;
|
|
405
431
|
if (config.primaryKey !== void 0) tableConfig.primaryKey = config.primaryKey;
|
|
406
432
|
if (config.links !== void 0) tableConfig.links = config.links;
|
|
407
433
|
if (config.policies !== void 0) tableConfig.policies = { read: config.policies.read };
|
|
408
434
|
if (config.internal === true) tableConfig.internal = true;
|
|
435
|
+
if (config.indexes !== void 0 && config.indexes.length > 0) tableConfig.indexes = config.indexes;
|
|
409
436
|
const table = {
|
|
410
437
|
kind: TABLE_BRAND,
|
|
411
438
|
tableName: name2,
|
|
@@ -1107,6 +1134,732 @@ var Parser = class {
|
|
|
1107
1134
|
function compileCheckExpression(source, columns) {
|
|
1108
1135
|
return new Parser(tokenize(source), columns).parse();
|
|
1109
1136
|
}
|
|
1137
|
+
|
|
1138
|
+
// src/predicate/ast.ts
|
|
1139
|
+
var COMPARE_OPS = ["=", "!=", "<", "<=", ">", ">="];
|
|
1140
|
+
function walkPredicate(predicate, visit) {
|
|
1141
|
+
visit(predicate);
|
|
1142
|
+
if (predicate.kind === "and" || predicate.kind === "or") {
|
|
1143
|
+
for (const operand of predicate.operands) walkPredicate(operand, visit);
|
|
1144
|
+
}
|
|
1145
|
+
if (predicate.kind === "not") walkPredicate(predicate.operand, visit);
|
|
1146
|
+
}
|
|
1147
|
+
function predicateOperands(predicate) {
|
|
1148
|
+
const operands = [];
|
|
1149
|
+
walkPredicate(predicate, (node) => {
|
|
1150
|
+
if (node.kind === "compare") operands.push(node.left, node.right);
|
|
1151
|
+
});
|
|
1152
|
+
return operands;
|
|
1153
|
+
}
|
|
1154
|
+
function referencedColumns(predicate) {
|
|
1155
|
+
const names = predicateOperands(predicate).flatMap(
|
|
1156
|
+
(operand) => operand.kind === "column" ? [operand.name] : []
|
|
1157
|
+
);
|
|
1158
|
+
return [...new Set(names)];
|
|
1159
|
+
}
|
|
1160
|
+
var identifierSchema = z.string().max(MAX_IDENTIFIER_LENGTH).regex(IDENTIFIER_PATTERN, "must be a lowercase identifier (a-z, 0-9, _)");
|
|
1161
|
+
var namespaceSchema = z.string().regex(NAMESPACE_PATTERN, "must be lowercase, start with a letter, and be at most 41 characters");
|
|
1162
|
+
var tableReferenceSchema = z.string().refine(
|
|
1163
|
+
(value) => IDENTIFIER_PATTERN.test(value) || QUALIFIED_TABLE_PATTERN.test(value),
|
|
1164
|
+
"must be a table name or a schema-qualified table reference"
|
|
1165
|
+
);
|
|
1166
|
+
|
|
1167
|
+
// src/schema/columns.ts
|
|
1168
|
+
var COLUMN_TYPES = [
|
|
1169
|
+
"uuid",
|
|
1170
|
+
"text",
|
|
1171
|
+
"integer",
|
|
1172
|
+
"bigint",
|
|
1173
|
+
"numeric",
|
|
1174
|
+
"double",
|
|
1175
|
+
"boolean",
|
|
1176
|
+
"timestamptz",
|
|
1177
|
+
"date",
|
|
1178
|
+
"jsonb"
|
|
1179
|
+
];
|
|
1180
|
+
var columnTypeSchema = z.enum(COLUMN_TYPES);
|
|
1181
|
+
var FUNCTION_DEFAULTS = {
|
|
1182
|
+
"gen_random_uuid()": ["uuid"],
|
|
1183
|
+
"now()": ["timestamptz", "date"]
|
|
1184
|
+
};
|
|
1185
|
+
var CAST_PATTERN = /^([a-z][a-z0-9_]*)::([a-z]+)$/;
|
|
1186
|
+
function defaultIssue(value, type) {
|
|
1187
|
+
if (typeof value === "boolean") return type === "boolean" ? null : `boolean default is invalid for type '${type}'`;
|
|
1188
|
+
if (typeof value === "number") {
|
|
1189
|
+
if (!["integer", "bigint", "numeric", "double"].includes(type)) {
|
|
1190
|
+
return `numeric default is invalid for type '${type}'`;
|
|
1191
|
+
}
|
|
1192
|
+
if (["integer", "bigint"].includes(type)) {
|
|
1193
|
+
if (!Number.isInteger(value)) return `default for type '${type}' must be an integer`;
|
|
1194
|
+
if (!Number.isSafeInteger(value)) {
|
|
1195
|
+
return `default for type '${type}' exceeds the safe integer range \u2014 YAML numbers lose precision past 2^53`;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
if (type === "numeric" && Math.abs(value) > Number.MAX_SAFE_INTEGER) {
|
|
1199
|
+
return "numeric default exceeds the safe float range \u2014 write it as a string (e.g. '9007199254740993') to keep exact precision";
|
|
1200
|
+
}
|
|
1201
|
+
return null;
|
|
1202
|
+
}
|
|
1203
|
+
const allowedTypes = FUNCTION_DEFAULTS[value];
|
|
1204
|
+
if (allowedTypes) return allowedTypes.includes(type) ? null : `default '${value}' is invalid for type '${type}'`;
|
|
1205
|
+
return null;
|
|
1206
|
+
}
|
|
1207
|
+
var columnSchema = z.strictObject({
|
|
1208
|
+
type: columnTypeSchema,
|
|
1209
|
+
primary_key: z.boolean().optional(),
|
|
1210
|
+
nullable: z.boolean().optional(),
|
|
1211
|
+
unique: z.boolean().optional(),
|
|
1212
|
+
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
|
|
1213
|
+
description: z.string().optional(),
|
|
1214
|
+
renamed_from: identifierSchema.optional(),
|
|
1215
|
+
cast: z.string().optional(),
|
|
1216
|
+
deprecated: z.boolean().optional()
|
|
1217
|
+
}).superRefine((column, ctx) => {
|
|
1218
|
+
if (column.default !== void 0) {
|
|
1219
|
+
const issue = defaultIssue(column.default, column.type);
|
|
1220
|
+
if (issue) ctx.addIssue({ code: "custom", message: issue, path: ["default"] });
|
|
1221
|
+
}
|
|
1222
|
+
if (column.primary_key && column.nullable) {
|
|
1223
|
+
ctx.addIssue({ code: "custom", message: "a primary key column cannot be nullable", path: ["nullable"] });
|
|
1224
|
+
}
|
|
1225
|
+
if (column.primary_key && column.deprecated) {
|
|
1226
|
+
ctx.addIssue({ code: "custom", message: "a primary key column cannot be deprecated", path: ["deprecated"] });
|
|
1227
|
+
}
|
|
1228
|
+
if (column.cast && !CAST_PATTERN.test(column.cast)) {
|
|
1229
|
+
ctx.addIssue({ code: "custom", message: "cast must have the shape '<column>::<type>'", path: ["cast"] });
|
|
1230
|
+
}
|
|
1231
|
+
});
|
|
1232
|
+
function castParts(cast) {
|
|
1233
|
+
const match = CAST_PATTERN.exec(cast);
|
|
1234
|
+
if (!match) return null;
|
|
1235
|
+
return { column: match[1], type: match[2] };
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// src/predicate/parse.ts
|
|
1239
|
+
var KEYWORDS = /* @__PURE__ */ new Set(["and", "or", "not", "true", "false", "null", "claim", "capability"]);
|
|
1240
|
+
var OPERATOR_PATTERN = /^(!=|<=|>=|<>|=|<|>)/;
|
|
1241
|
+
var IDENTIFIER_START = /[a-z_]/;
|
|
1242
|
+
var IDENTIFIER_CHAR = /[a-z0-9_.-]/;
|
|
1243
|
+
var NUMBER_PATTERN = /^-?\d+(\.\d+)?/;
|
|
1244
|
+
function tokenize2(source) {
|
|
1245
|
+
const tokens = [];
|
|
1246
|
+
let position = 0;
|
|
1247
|
+
while (position < source.length) {
|
|
1248
|
+
const char = source[position];
|
|
1249
|
+
if (/\s/.test(char)) {
|
|
1250
|
+
position += 1;
|
|
1251
|
+
continue;
|
|
1252
|
+
}
|
|
1253
|
+
if (char === "(") {
|
|
1254
|
+
tokens.push({ kind: "lparen", value: char, position });
|
|
1255
|
+
position += 1;
|
|
1256
|
+
continue;
|
|
1257
|
+
}
|
|
1258
|
+
if (char === ")") {
|
|
1259
|
+
tokens.push({ kind: "rparen", value: char, position });
|
|
1260
|
+
position += 1;
|
|
1261
|
+
continue;
|
|
1262
|
+
}
|
|
1263
|
+
if (char === ",") {
|
|
1264
|
+
tokens.push({ kind: "comma", value: char, position });
|
|
1265
|
+
position += 1;
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
if (char === "'") {
|
|
1269
|
+
const { value, end } = readString(source, position);
|
|
1270
|
+
tokens.push({ kind: "string", value, position });
|
|
1271
|
+
position = end;
|
|
1272
|
+
continue;
|
|
1273
|
+
}
|
|
1274
|
+
const operator = OPERATOR_PATTERN.exec(source.slice(position));
|
|
1275
|
+
if (operator) {
|
|
1276
|
+
const value = operator[0] === "<>" ? "!=" : operator[0];
|
|
1277
|
+
tokens.push({ kind: "operator", value, position });
|
|
1278
|
+
position += operator[0].length;
|
|
1279
|
+
continue;
|
|
1280
|
+
}
|
|
1281
|
+
const number = NUMBER_PATTERN.exec(source.slice(position));
|
|
1282
|
+
if (number && !IDENTIFIER_START.test(char)) {
|
|
1283
|
+
tokens.push({ kind: "number", value: number[0], position });
|
|
1284
|
+
position += number[0].length;
|
|
1285
|
+
continue;
|
|
1286
|
+
}
|
|
1287
|
+
if (IDENTIFIER_START.test(char)) {
|
|
1288
|
+
let end = position;
|
|
1289
|
+
while (end < source.length && IDENTIFIER_CHAR.test(source[end])) end += 1;
|
|
1290
|
+
tokens.push({ kind: "identifier", value: source.slice(position, end), position });
|
|
1291
|
+
position = end;
|
|
1292
|
+
continue;
|
|
1293
|
+
}
|
|
1294
|
+
throw new PredicateParseError(`unexpected character '${char}'`, position);
|
|
1295
|
+
}
|
|
1296
|
+
tokens.push({ kind: "end", value: "", position: source.length });
|
|
1297
|
+
return tokens;
|
|
1298
|
+
}
|
|
1299
|
+
function readString(source, start) {
|
|
1300
|
+
let value = "";
|
|
1301
|
+
let position = start + 1;
|
|
1302
|
+
while (position < source.length) {
|
|
1303
|
+
const char = source[position];
|
|
1304
|
+
if (char !== "'") {
|
|
1305
|
+
value += char;
|
|
1306
|
+
position += 1;
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
if (source[position + 1] === "'") {
|
|
1310
|
+
value += "'";
|
|
1311
|
+
position += 2;
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
return { value, end: position + 1 };
|
|
1315
|
+
}
|
|
1316
|
+
throw new PredicateParseError("unterminated string literal", start);
|
|
1317
|
+
}
|
|
1318
|
+
var Parser2 = class {
|
|
1319
|
+
constructor(tokens) {
|
|
1320
|
+
this.tokens = tokens;
|
|
1321
|
+
}
|
|
1322
|
+
index = 0;
|
|
1323
|
+
parse() {
|
|
1324
|
+
const predicate = this.parseOr();
|
|
1325
|
+
this.expect("end", "end of expression");
|
|
1326
|
+
return predicate;
|
|
1327
|
+
}
|
|
1328
|
+
parseOr() {
|
|
1329
|
+
const operands = [this.parseAnd()];
|
|
1330
|
+
while (this.matchKeyword("or")) operands.push(this.parseAnd());
|
|
1331
|
+
return operands.length === 1 ? operands[0] : { kind: "or", operands };
|
|
1332
|
+
}
|
|
1333
|
+
parseAnd() {
|
|
1334
|
+
const operands = [this.parseNot()];
|
|
1335
|
+
while (this.matchKeyword("and")) operands.push(this.parseNot());
|
|
1336
|
+
return operands.length === 1 ? operands[0] : { kind: "and", operands };
|
|
1337
|
+
}
|
|
1338
|
+
parseNot() {
|
|
1339
|
+
if (this.matchKeyword("not")) return { kind: "not", operand: this.parseNot() };
|
|
1340
|
+
return this.parsePrimary();
|
|
1341
|
+
}
|
|
1342
|
+
parsePrimary() {
|
|
1343
|
+
if (this.peek().kind === "lparen") {
|
|
1344
|
+
this.advance();
|
|
1345
|
+
const inner = this.parseOr();
|
|
1346
|
+
this.expect("rparen", "')'");
|
|
1347
|
+
return inner;
|
|
1348
|
+
}
|
|
1349
|
+
if (this.peekKeyword("capability")) {
|
|
1350
|
+
const capability = this.parseCapability();
|
|
1351
|
+
const next = this.peek();
|
|
1352
|
+
if (next.kind === "operator") {
|
|
1353
|
+
throw new PredicateParseError("capability() is boolean-valued and cannot appear in a comparison", next.position);
|
|
1354
|
+
}
|
|
1355
|
+
return capability;
|
|
1356
|
+
}
|
|
1357
|
+
return this.parseComparison();
|
|
1358
|
+
}
|
|
1359
|
+
parseCapability() {
|
|
1360
|
+
this.advance();
|
|
1361
|
+
const key = this.parseCallArgument("capability");
|
|
1362
|
+
if (!CAPABILITY_KEY_PATTERN.test(key)) {
|
|
1363
|
+
throw new PredicateParseError(`invalid capability key '${key}'`, this.peek().position);
|
|
1364
|
+
}
|
|
1365
|
+
return { kind: "capability", key };
|
|
1366
|
+
}
|
|
1367
|
+
parseComparison() {
|
|
1368
|
+
const left = this.parseOperand();
|
|
1369
|
+
const operator = this.expect("operator", "a comparison operator");
|
|
1370
|
+
if (!COMPARE_OPS.includes(operator.value)) {
|
|
1371
|
+
throw new PredicateParseError(`unsupported operator '${operator.value}'`, operator.position);
|
|
1372
|
+
}
|
|
1373
|
+
const right = this.parseOperand();
|
|
1374
|
+
return { kind: "compare", op: operator.value, left, right };
|
|
1375
|
+
}
|
|
1376
|
+
parseOperand() {
|
|
1377
|
+
const token = this.peek();
|
|
1378
|
+
if (token.kind === "string") {
|
|
1379
|
+
this.advance();
|
|
1380
|
+
return { kind: "literal", value: token.value };
|
|
1381
|
+
}
|
|
1382
|
+
if (token.kind === "number") {
|
|
1383
|
+
this.advance();
|
|
1384
|
+
const value = Number(token.value);
|
|
1385
|
+
if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) {
|
|
1386
|
+
throw new PredicateParseError(
|
|
1387
|
+
`numeric literal '${token.value}' exceeds safe integer precision \u2014 quote it as a string`,
|
|
1388
|
+
token.position
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
return { kind: "literal", value };
|
|
1392
|
+
}
|
|
1393
|
+
if (token.kind !== "identifier") {
|
|
1394
|
+
throw new PredicateParseError(`expected an operand, got '${token.value || "end"}'`, token.position);
|
|
1395
|
+
}
|
|
1396
|
+
this.advance();
|
|
1397
|
+
if (token.value === "true" || token.value === "false") {
|
|
1398
|
+
return { kind: "literal", value: token.value === "true" };
|
|
1399
|
+
}
|
|
1400
|
+
if (token.value === "null") return { kind: "literal", value: null };
|
|
1401
|
+
if (token.value === "claim") {
|
|
1402
|
+
const key = this.parseCallArgument("claim");
|
|
1403
|
+
if (!CLAIM_KEY_PATTERN.test(key)) {
|
|
1404
|
+
throw new PredicateParseError(`invalid claim key '${key}'`, token.position);
|
|
1405
|
+
}
|
|
1406
|
+
return { kind: "claim", key };
|
|
1407
|
+
}
|
|
1408
|
+
if (token.value === "capability") {
|
|
1409
|
+
throw new PredicateParseError("capability() is boolean-valued and cannot appear in a comparison", token.position);
|
|
1410
|
+
}
|
|
1411
|
+
if (KEYWORDS.has(token.value) || !IDENTIFIER_PATTERN.test(token.value)) {
|
|
1412
|
+
throw new PredicateParseError(`invalid column reference '${token.value}'`, token.position);
|
|
1413
|
+
}
|
|
1414
|
+
return { kind: "column", name: token.value };
|
|
1415
|
+
}
|
|
1416
|
+
parseCallArgument(fn) {
|
|
1417
|
+
this.expect("lparen", `'(' after ${fn}`);
|
|
1418
|
+
const argument = this.expect("string", `a quoted key in ${fn}(...)`);
|
|
1419
|
+
this.expect("rparen", `')' after ${fn} key`);
|
|
1420
|
+
return argument.value;
|
|
1421
|
+
}
|
|
1422
|
+
peek() {
|
|
1423
|
+
return this.tokens[this.index];
|
|
1424
|
+
}
|
|
1425
|
+
peekKeyword(keyword) {
|
|
1426
|
+
const token = this.peek();
|
|
1427
|
+
return token.kind === "identifier" && token.value === keyword;
|
|
1428
|
+
}
|
|
1429
|
+
matchKeyword(keyword) {
|
|
1430
|
+
if (!this.peekKeyword(keyword)) return false;
|
|
1431
|
+
this.advance();
|
|
1432
|
+
return true;
|
|
1433
|
+
}
|
|
1434
|
+
advance() {
|
|
1435
|
+
const token = this.peek();
|
|
1436
|
+
if (token.kind !== "end") this.index += 1;
|
|
1437
|
+
return token;
|
|
1438
|
+
}
|
|
1439
|
+
expect(kind, description) {
|
|
1440
|
+
const token = this.peek();
|
|
1441
|
+
if (token.kind !== kind) {
|
|
1442
|
+
throw new PredicateParseError(`expected ${description}, got '${token.value || "end"}'`, token.position);
|
|
1443
|
+
}
|
|
1444
|
+
return this.advance();
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
function parsePredicate(source) {
|
|
1448
|
+
const trimmed = source.trim();
|
|
1449
|
+
if (trimmed.length === 0) throw new PredicateParseError("empty predicate", 0);
|
|
1450
|
+
return { source: trimmed, ast: new Parser2(tokenize2(trimmed)).parse() };
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
// src/schema/predicates.ts
|
|
1454
|
+
var parsedPredicateSchema = z.string().transform((source, ctx) => {
|
|
1455
|
+
try {
|
|
1456
|
+
return parsePredicate(source);
|
|
1457
|
+
} catch (error) {
|
|
1458
|
+
ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : String(error) });
|
|
1459
|
+
return z.NEVER;
|
|
1460
|
+
}
|
|
1461
|
+
});
|
|
1462
|
+
|
|
1463
|
+
// src/schema/actions.ts
|
|
1464
|
+
var EXECUTES_VERB_PATTERN = /^\s*(insert|update|delete)\b/i;
|
|
1465
|
+
var DOLLAR_QUOTE_PATTERN = /\$[a-zA-Z0-9_]*\$/;
|
|
1466
|
+
var RETURNING_PATTERN = /\breturning\b/i;
|
|
1467
|
+
var ESCAPE_STRING_PATTERN = /(?<![a-zA-Z0-9_])[Ee]'/;
|
|
1468
|
+
var MASKED_CLAIM_CALL_PATTERN = /\b(?:claim|capability)\(\s*''\s*\)/g;
|
|
1469
|
+
var BARE_CLAIM_CALL_PATTERN = /\b(?:claim|capability)\s*\(/;
|
|
1470
|
+
var EXISTS_ENTRY_PATTERN = /^exists\(\s*'([^']+)'\s*,\s*([a-z][a-z0-9_]*)\s*\)$/;
|
|
1471
|
+
var NAMED_PARAM_PATTERN = /(?<!:):([a-z][a-z0-9_]*)/g;
|
|
1472
|
+
var QUOTED_STRING_PATTERN = /'(?:[^']|'')*'/g;
|
|
1473
|
+
var SQL_COMMENT_PATTERN = /--|\/\*/;
|
|
1474
|
+
var actionParamSchema = z.strictObject({
|
|
1475
|
+
type: columnTypeSchema,
|
|
1476
|
+
optional: z.boolean().optional(),
|
|
1477
|
+
description: z.string().optional()
|
|
1478
|
+
});
|
|
1479
|
+
var validatesEntrySchema = z.string().transform((source, ctx) => {
|
|
1480
|
+
const match = EXISTS_ENTRY_PATTERN.exec(source.trim());
|
|
1481
|
+
if (!match) {
|
|
1482
|
+
ctx.addIssue({ code: "custom", message: "validates entries must have the shape exists('<table>', <param>)" });
|
|
1483
|
+
return z.NEVER;
|
|
1484
|
+
}
|
|
1485
|
+
const table = tableReferenceSchema.safeParse(match[1]);
|
|
1486
|
+
if (!table.success) {
|
|
1487
|
+
ctx.addIssue({ code: "custom", message: `invalid table reference '${match[1]}'` });
|
|
1488
|
+
return z.NEVER;
|
|
1489
|
+
}
|
|
1490
|
+
return { source: source.trim(), table: table.data, param: match[2] };
|
|
1491
|
+
});
|
|
1492
|
+
var AUDIT_ACTIONS = ["create", "update", "delete"];
|
|
1493
|
+
var auditSchema = z.strictObject({
|
|
1494
|
+
action: z.enum(AUDIT_ACTIONS),
|
|
1495
|
+
resource: identifierSchema.optional()
|
|
1496
|
+
});
|
|
1497
|
+
var actionSchema = z.strictObject({
|
|
1498
|
+
description: z.string().optional(),
|
|
1499
|
+
requires: parsedPredicateSchema.optional(),
|
|
1500
|
+
params: z.record(identifierSchema, actionParamSchema).optional(),
|
|
1501
|
+
validates: z.array(validatesEntrySchema).optional(),
|
|
1502
|
+
// One statement, or an ordered list run atomically in the action function.
|
|
1503
|
+
executes: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
|
|
1504
|
+
// Declares the columns the action's RETURNING yields. Present → the
|
|
1505
|
+
// function returns those rows (typed in the client); absent → the action
|
|
1506
|
+
// reports rows_affected only. The column names/types must match the
|
|
1507
|
+
// RETURNING list, which Postgres enforces at CREATE FUNCTION.
|
|
1508
|
+
returns: z.record(identifierSchema, columnTypeSchema).optional(),
|
|
1509
|
+
audit: auditSchema.optional()
|
|
1510
|
+
}).superRefine((action, ctx) => {
|
|
1511
|
+
const params = Object.keys(action.params ?? {});
|
|
1512
|
+
if (action.requires && referencedColumns(action.requires.ast).length > 0) {
|
|
1513
|
+
ctx.addIssue({
|
|
1514
|
+
code: "custom",
|
|
1515
|
+
message: "requires may reference claims and capabilities only, not columns",
|
|
1516
|
+
path: ["requires"]
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
for (const issue of executesIssues(action.executes, new Set(params), action.returns !== void 0)) {
|
|
1520
|
+
ctx.addIssue({ code: "custom", message: issue, path: ["executes"] });
|
|
1521
|
+
}
|
|
1522
|
+
if (action.returns && Object.keys(action.returns).length === 0) {
|
|
1523
|
+
ctx.addIssue({ code: "custom", message: "returns must declare at least one column", path: ["returns"] });
|
|
1524
|
+
}
|
|
1525
|
+
for (const [index, entry] of (action.validates ?? []).entries()) {
|
|
1526
|
+
if (!params.includes(entry.param)) {
|
|
1527
|
+
ctx.addIssue({
|
|
1528
|
+
code: "custom",
|
|
1529
|
+
message: `validates references undeclared param '${entry.param}'`,
|
|
1530
|
+
path: ["validates", index]
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
});
|
|
1535
|
+
function extractNamedParams(sql4) {
|
|
1536
|
+
const withoutStrings = sql4.replace(QUOTED_STRING_PATTERN, "''");
|
|
1537
|
+
const names = [...withoutStrings.matchAll(NAMED_PARAM_PATTERN)].map((match) => match[1]);
|
|
1538
|
+
return [...new Set(names)];
|
|
1539
|
+
}
|
|
1540
|
+
function actionStatementSources(executes) {
|
|
1541
|
+
return (Array.isArray(executes) ? executes : [executes]).map((statement) => statement.trim());
|
|
1542
|
+
}
|
|
1543
|
+
function executesIssues(executes, declaredParams, hasReturns) {
|
|
1544
|
+
const issues = [];
|
|
1545
|
+
const statements = actionStatementSources(executes);
|
|
1546
|
+
statements.forEach((statement, index) => {
|
|
1547
|
+
const withoutStrings = statement.replace(QUOTED_STRING_PATTERN, "''");
|
|
1548
|
+
const at = statements.length > 1 ? ` (statement ${index + 1})` : "";
|
|
1549
|
+
if (!EXECUTES_VERB_PATTERN.test(statement)) issues.push(`executes must be INSERT, UPDATE, or DELETE${at}`);
|
|
1550
|
+
if (withoutStrings.replace(/;\s*$/, "").includes(";")) issues.push(`each executes entry must be a single statement${at}`);
|
|
1551
|
+
if (SQL_COMMENT_PATTERN.test(withoutStrings)) issues.push(`executes must not contain SQL comments${at}`);
|
|
1552
|
+
if (DOLLAR_QUOTE_PATTERN.test(withoutStrings)) issues.push(`executes must not use dollar-quoted strings${at}`);
|
|
1553
|
+
if (ESCAPE_STRING_PATTERN.test(withoutStrings)) issues.push(`executes must not use escape strings (E'\u2026')${at}`);
|
|
1554
|
+
if (withoutStrings.includes('"')) issues.push(`executes must not use double-quoted identifiers${at}`);
|
|
1555
|
+
if (BARE_CLAIM_CALL_PATTERN.test(withoutStrings.replace(MASKED_CLAIM_CALL_PATTERN, ""))) {
|
|
1556
|
+
issues.push(`executes has a malformed claim()/capability() call \u2014 use e.g. claim('sub')${at}`);
|
|
1557
|
+
}
|
|
1558
|
+
if (RETURNING_PATTERN.test(withoutStrings) && !(hasReturns && index === statements.length - 1)) {
|
|
1559
|
+
issues.push(
|
|
1560
|
+
hasReturns ? `only the last executes statement may use RETURNING${at}` : `executes must not use RETURNING unless the action declares returns${at}`
|
|
1561
|
+
);
|
|
1562
|
+
}
|
|
1563
|
+
});
|
|
1564
|
+
const last = statements.at(-1);
|
|
1565
|
+
if (hasReturns && last && !RETURNING_PATTERN.test(last.replace(QUOTED_STRING_PATTERN, "''"))) {
|
|
1566
|
+
issues.push("the last executes statement must use RETURNING to populate the declared returns columns");
|
|
1567
|
+
}
|
|
1568
|
+
const undeclared = extractNamedParams(statements.join("\n")).filter((name2) => !declaredParams.has(name2));
|
|
1569
|
+
if (undeclared.length > 0) issues.push(`executes references undeclared params: ${undeclared.join(", ")}`);
|
|
1570
|
+
return issues;
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
// src/schema/table.ts
|
|
1574
|
+
var linkSchema = z.strictObject({
|
|
1575
|
+
to: tableReferenceSchema,
|
|
1576
|
+
on: identifierSchema,
|
|
1577
|
+
enforce: z.boolean().optional(),
|
|
1578
|
+
description: z.string().optional()
|
|
1579
|
+
});
|
|
1580
|
+
var indexSchema = z.union([
|
|
1581
|
+
z.array(identifierSchema).min(1),
|
|
1582
|
+
z.strictObject({
|
|
1583
|
+
columns: z.array(identifierSchema).min(1),
|
|
1584
|
+
unique: z.boolean().optional(),
|
|
1585
|
+
name: identifierSchema.optional()
|
|
1586
|
+
})
|
|
1587
|
+
]).transform((index) => Array.isArray(index) ? { columns: index } : index);
|
|
1588
|
+
var policiesSchema = z.strictObject({
|
|
1589
|
+
read: parsedPredicateSchema.optional(),
|
|
1590
|
+
write: parsedPredicateSchema.optional(),
|
|
1591
|
+
insert: parsedPredicateSchema.optional(),
|
|
1592
|
+
update: parsedPredicateSchema.optional()
|
|
1593
|
+
});
|
|
1594
|
+
z.strictObject({
|
|
1595
|
+
namespace: namespaceSchema,
|
|
1596
|
+
table: identifierSchema,
|
|
1597
|
+
description: z.string().optional(),
|
|
1598
|
+
columns: z.record(identifierSchema, columnSchema).optional(),
|
|
1599
|
+
source: z.string().regex(SYNCED_SOURCE_PATTERN, "source must be a qualified lowercase schema.table identifier").optional(),
|
|
1600
|
+
links: z.record(identifierSchema, linkSchema).optional(),
|
|
1601
|
+
indexes: z.array(indexSchema).optional(),
|
|
1602
|
+
policies: policiesSchema.optional(),
|
|
1603
|
+
actions: z.record(identifierSchema, actionSchema).optional()
|
|
1604
|
+
}).superRefine((table, ctx) => {
|
|
1605
|
+
if (RESERVED_TABLE_NAMES.has(table.table)) {
|
|
1606
|
+
ctx.addIssue({ code: "custom", message: `'${table.table}' is a reserved table name`, path: ["table"] });
|
|
1607
|
+
}
|
|
1608
|
+
for (const name2 of Object.keys(table.columns ?? {})) {
|
|
1609
|
+
if (RESERVED_COLUMN_NAMES.has(name2)) {
|
|
1610
|
+
ctx.addIssue({
|
|
1611
|
+
code: "custom",
|
|
1612
|
+
message: `column '${name2}' collides with the Data API's reserved query parameters (select, order, limit, offset) \u2014 it could never be filtered`,
|
|
1613
|
+
path: ["columns", name2]
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
if (table.source) validateSyncedTable(table, ctx);
|
|
1618
|
+
else validateColumnTable(table, ctx);
|
|
1619
|
+
validateLinks(table, ctx);
|
|
1620
|
+
validatePolicyColumns(table, ctx);
|
|
1621
|
+
validateDerivedNameLengths(table, ctx);
|
|
1622
|
+
});
|
|
1623
|
+
var indexName = (table, definition) => definition.name ?? `ix_${table}_${definition.columns.join("_")}`;
|
|
1624
|
+
var policyName = (table, suffix) => `${table}_${suffix}`;
|
|
1625
|
+
var foreignKeyName = (table, link) => `fk_${table}_${link}`;
|
|
1626
|
+
function validateSyncedTable(table, ctx) {
|
|
1627
|
+
const forbidden = [
|
|
1628
|
+
["actions", "synced tables are read-only; actions are not allowed"],
|
|
1629
|
+
["indexes", "v1 synced tables cannot declare indexes; declare them with defineSyncedTable({ indexes }) in a v2 definition"]
|
|
1630
|
+
];
|
|
1631
|
+
for (const [field, message] of forbidden) {
|
|
1632
|
+
if (table[field] !== void 0) ctx.addIssue({ code: "custom", message, path: [field] });
|
|
1633
|
+
}
|
|
1634
|
+
if (table.policies?.write) {
|
|
1635
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "write"] });
|
|
1636
|
+
}
|
|
1637
|
+
if (table.policies?.insert) {
|
|
1638
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "insert"] });
|
|
1639
|
+
}
|
|
1640
|
+
if (table.policies?.update) {
|
|
1641
|
+
ctx.addIssue({ code: "custom", message: "synced tables are read-only", path: ["policies", "update"] });
|
|
1642
|
+
}
|
|
1643
|
+
const columns = table.columns ?? {};
|
|
1644
|
+
const names = Object.keys(columns);
|
|
1645
|
+
if (names.length === 0) return;
|
|
1646
|
+
const primaryKeys = names.filter((name2) => columns[name2]?.primary_key);
|
|
1647
|
+
if (primaryKeys.length !== 1) {
|
|
1648
|
+
ctx.addIssue({ code: "custom", message: "exactly one column must be primary_key", path: ["columns"] });
|
|
1649
|
+
}
|
|
1650
|
+
validateRenames(columns, names, ctx);
|
|
1651
|
+
for (const name2 of names) {
|
|
1652
|
+
const column = columns[name2];
|
|
1653
|
+
if (!column) continue;
|
|
1654
|
+
const cast = column.cast ? castParts(column.cast) : null;
|
|
1655
|
+
if (column.cast && cast?.column !== name2) {
|
|
1656
|
+
ctx.addIssue({
|
|
1657
|
+
code: "custom",
|
|
1658
|
+
message: "cast must reference the column it is declared on",
|
|
1659
|
+
path: ["columns", name2, "cast"]
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
if (cast && cast.type !== column.type) {
|
|
1663
|
+
ctx.addIssue({
|
|
1664
|
+
code: "custom",
|
|
1665
|
+
message: `cast target '${cast.type}' must match the declared type '${column.type}'`,
|
|
1666
|
+
path: ["columns", name2, "cast"]
|
|
1667
|
+
});
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
function validateRenames(columns, names, ctx) {
|
|
1672
|
+
const renameSources = /* @__PURE__ */ new Map();
|
|
1673
|
+
for (const name2 of names) {
|
|
1674
|
+
const renamedFrom = columns[name2]?.renamed_from;
|
|
1675
|
+
if (!renamedFrom) continue;
|
|
1676
|
+
if (renamedFrom === name2 || names.includes(renamedFrom)) {
|
|
1677
|
+
ctx.addIssue({
|
|
1678
|
+
code: "custom",
|
|
1679
|
+
message: "renamed_from must name a column that no longer exists",
|
|
1680
|
+
path: ["columns", name2, "renamed_from"]
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
const claimed = renameSources.get(renamedFrom);
|
|
1684
|
+
if (claimed) {
|
|
1685
|
+
ctx.addIssue({
|
|
1686
|
+
code: "custom",
|
|
1687
|
+
message: `renamed_from '${renamedFrom}' is already claimed by '${claimed}'`,
|
|
1688
|
+
path: ["columns", name2, "renamed_from"]
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
renameSources.set(renamedFrom, name2);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
function validateColumnTable(table, ctx) {
|
|
1695
|
+
const columns = table.columns ?? {};
|
|
1696
|
+
const names = Object.keys(columns);
|
|
1697
|
+
if (names.length === 0) {
|
|
1698
|
+
ctx.addIssue({ code: "custom", message: "a table must declare columns or a source", path: ["columns"] });
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
const primaryKeys = names.filter((name2) => columns[name2]?.primary_key);
|
|
1702
|
+
if (primaryKeys.length !== 1) {
|
|
1703
|
+
ctx.addIssue({ code: "custom", message: "exactly one column must be primary_key", path: ["columns"] });
|
|
1704
|
+
}
|
|
1705
|
+
validateRenames(columns, names, ctx);
|
|
1706
|
+
for (const name2 of names) {
|
|
1707
|
+
const column = columns[name2];
|
|
1708
|
+
if (!column) continue;
|
|
1709
|
+
const cast = column.cast ? castParts(column.cast) : null;
|
|
1710
|
+
if (column.cast && cast?.column !== name2) {
|
|
1711
|
+
ctx.addIssue({
|
|
1712
|
+
code: "custom",
|
|
1713
|
+
message: "cast must reference the column it is declared on",
|
|
1714
|
+
path: ["columns", name2, "cast"]
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
if (cast && cast.type !== column.type) {
|
|
1718
|
+
ctx.addIssue({
|
|
1719
|
+
code: "custom",
|
|
1720
|
+
message: `cast target '${cast.type}' must match the declared type '${column.type}'`,
|
|
1721
|
+
path: ["columns", name2, "cast"]
|
|
1722
|
+
});
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
for (const [position, index] of (table.indexes ?? []).entries()) {
|
|
1726
|
+
if (new Set(index.columns).size !== index.columns.length) {
|
|
1727
|
+
ctx.addIssue({
|
|
1728
|
+
code: "custom",
|
|
1729
|
+
message: "index names a column more than once",
|
|
1730
|
+
path: ["indexes", position]
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
for (const column of index.columns) {
|
|
1734
|
+
if (!names.includes(column)) {
|
|
1735
|
+
ctx.addIssue({
|
|
1736
|
+
code: "custom",
|
|
1737
|
+
message: `index references unknown column '${column}'`,
|
|
1738
|
+
path: ["indexes", position]
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
function validateLinks(table, ctx) {
|
|
1745
|
+
const columnNames = Object.keys(table.columns ?? {});
|
|
1746
|
+
for (const [name2, link] of Object.entries(table.links ?? {})) {
|
|
1747
|
+
if (columnNames.length > 0 && !columnNames.includes(link.on)) {
|
|
1748
|
+
ctx.addIssue({ code: "custom", message: `link references unknown column '${link.on}'`, path: ["links", name2, "on"] });
|
|
1749
|
+
}
|
|
1750
|
+
if (link.enforce && link.to.includes(".")) {
|
|
1751
|
+
ctx.addIssue({
|
|
1752
|
+
code: "custom",
|
|
1753
|
+
message: "enforce is only valid for links inside the namespace; cross-boundary links stay soft",
|
|
1754
|
+
path: ["links", name2, "enforce"]
|
|
1755
|
+
});
|
|
1756
|
+
}
|
|
1757
|
+
if (link.enforce && table.source) {
|
|
1758
|
+
ctx.addIssue({
|
|
1759
|
+
code: "custom",
|
|
1760
|
+
message: "a synced table cannot enforce foreign keys \u2014 its DDL is owned by the sync",
|
|
1761
|
+
path: ["links", name2, "enforce"]
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
function validateDerivedNameLengths(table, ctx) {
|
|
1767
|
+
const worstPolicy = policyName(table.table, "insert");
|
|
1768
|
+
if (!table.source && worstPolicy.length > MAX_IDENTIFIER_LENGTH) {
|
|
1769
|
+
ctx.addIssue({
|
|
1770
|
+
code: "custom",
|
|
1771
|
+
message: `table name is too long \u2014 the derived policy name '${worstPolicy}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit`,
|
|
1772
|
+
path: ["table"]
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
for (const [position, index] of (table.indexes ?? []).entries()) {
|
|
1776
|
+
const name2 = indexName(table.table, index);
|
|
1777
|
+
if (name2.length > MAX_IDENTIFIER_LENGTH) {
|
|
1778
|
+
ctx.addIssue({
|
|
1779
|
+
code: "custom",
|
|
1780
|
+
message: `derived index name '${name2}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 set a shorter explicit name`,
|
|
1781
|
+
path: ["indexes", position]
|
|
1782
|
+
});
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
for (const [name2, link] of Object.entries(table.links ?? {})) {
|
|
1786
|
+
const constraint = foreignKeyName(table.table, name2);
|
|
1787
|
+
if (link.enforce && constraint.length > MAX_IDENTIFIER_LENGTH) {
|
|
1788
|
+
ctx.addIssue({
|
|
1789
|
+
code: "custom",
|
|
1790
|
+
message: `derived foreign-key name '${constraint}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 shorten the link or table name`,
|
|
1791
|
+
path: ["links", name2]
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
for (const name2 of Object.keys(table.actions ?? {})) {
|
|
1796
|
+
const fnName = `action_${name2}`;
|
|
1797
|
+
if (fnName.length > MAX_IDENTIFIER_LENGTH) {
|
|
1798
|
+
ctx.addIssue({
|
|
1799
|
+
code: "custom",
|
|
1800
|
+
message: `derived action function name '${fnName}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 shorten the action name`,
|
|
1801
|
+
path: ["actions", name2]
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
var TYPE_GROUPS = {
|
|
1807
|
+
integer: "numeric",
|
|
1808
|
+
bigint: "numeric",
|
|
1809
|
+
numeric: "numeric",
|
|
1810
|
+
double: "numeric",
|
|
1811
|
+
text: "text",
|
|
1812
|
+
uuid: "uuid",
|
|
1813
|
+
date: "temporal",
|
|
1814
|
+
timestamptz: "temporal",
|
|
1815
|
+
boolean: "boolean",
|
|
1816
|
+
jsonb: "jsonb"
|
|
1817
|
+
};
|
|
1818
|
+
function validatePolicyColumns(table, ctx) {
|
|
1819
|
+
const columns = table.columns ?? {};
|
|
1820
|
+
const columnNames = Object.keys(columns);
|
|
1821
|
+
if (columnNames.length === 0) return;
|
|
1822
|
+
for (const kind of ["read", "write", "insert", "update"]) {
|
|
1823
|
+
const predicate = table.policies?.[kind];
|
|
1824
|
+
if (!predicate) continue;
|
|
1825
|
+
for (const column of referencedColumns(predicate.ast)) {
|
|
1826
|
+
if (!columnNames.includes(column)) {
|
|
1827
|
+
ctx.addIssue({
|
|
1828
|
+
code: "custom",
|
|
1829
|
+
message: `policy references unknown column '${column}'`,
|
|
1830
|
+
path: ["policies", kind]
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
walkPredicate(predicate.ast, (node) => {
|
|
1835
|
+
if (node.kind !== "compare") return;
|
|
1836
|
+
const issue = comparisonTypeIssue(node.left, node.right, columns);
|
|
1837
|
+
if (issue) ctx.addIssue({ code: "custom", message: issue, path: ["policies", kind] });
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
function comparisonTypeIssue(left, right, columns) {
|
|
1842
|
+
const groupOf = (operand) => operand.kind === "column" ? columns[operand.name] ? TYPE_GROUPS[columns[operand.name].type] : null : null;
|
|
1843
|
+
if (left.kind === "column" && right.kind === "column") {
|
|
1844
|
+
const leftGroup = groupOf(left);
|
|
1845
|
+
const rightGroup = groupOf(right);
|
|
1846
|
+
if (leftGroup && rightGroup && leftGroup !== rightGroup) {
|
|
1847
|
+
return `policy compares '${left.name}' (${columns[left.name].type}) with '${right.name}' (${columns[right.name].type}) \u2014 incomparable types`;
|
|
1848
|
+
}
|
|
1849
|
+
return null;
|
|
1850
|
+
}
|
|
1851
|
+
const column = left.kind === "column" ? left : right.kind === "column" ? right : null;
|
|
1852
|
+
const literal2 = left.kind === "literal" ? left : right.kind === "literal" ? right : null;
|
|
1853
|
+
if (!column || !literal2 || literal2.value === null) return null;
|
|
1854
|
+
const columnGroup = groupOf(column);
|
|
1855
|
+
if (!columnGroup) return null;
|
|
1856
|
+
if (typeof literal2.value === "string") return null;
|
|
1857
|
+
const literalGroup = typeof literal2.value === "number" ? "numeric" : "boolean";
|
|
1858
|
+
if (literalGroup !== columnGroup) {
|
|
1859
|
+
return `policy compares '${column.name}' (${columns[column.name].type}) with a ${typeof literal2.value} literal \u2014 incomparable types`;
|
|
1860
|
+
}
|
|
1861
|
+
return null;
|
|
1862
|
+
}
|
|
1110
1863
|
var policyVariantSchema = z.object({
|
|
1111
1864
|
/** Claims-only guard (capability()/role()/claim() comparisons — no columns). */
|
|
1112
1865
|
when: z.string().min(1).max(1e3),
|
|
@@ -1423,7 +2176,7 @@ var CANONICAL_FORMAT = 2;
|
|
|
1423
2176
|
var IDENTIFIER_RE = /^[a-z][a-z0-9_]*$/;
|
|
1424
2177
|
var identifier2 = z.string().min(1).max(63).regex(IDENTIFIER_RE);
|
|
1425
2178
|
var columnIdentifier = z.string().min(1).max(63).regex(COLUMN_IDENTIFIER_PATTERN);
|
|
1426
|
-
var
|
|
2179
|
+
var COLUMN_TYPES2 = [
|
|
1427
2180
|
"uuid",
|
|
1428
2181
|
"text",
|
|
1429
2182
|
"integer",
|
|
@@ -1435,7 +2188,7 @@ var COLUMN_TYPES = [
|
|
|
1435
2188
|
"date",
|
|
1436
2189
|
"jsonb"
|
|
1437
2190
|
];
|
|
1438
|
-
var
|
|
2191
|
+
var columnTypeSchema2 = z.enum(COLUMN_TYPES2);
|
|
1439
2192
|
var canonicalEnumSchema = z.object({
|
|
1440
2193
|
name: identifier2,
|
|
1441
2194
|
values: z.array(z.string().min(1).max(63)).min(1).max(100)
|
|
@@ -1444,7 +2197,7 @@ var canonicalColumnSchema = z.object({
|
|
|
1444
2197
|
/** Property name in TS (camelCase); columnName is the Postgres name. */
|
|
1445
2198
|
name: z.string().min(1).max(63),
|
|
1446
2199
|
columnName: columnIdentifier,
|
|
1447
|
-
type: z.union([
|
|
2200
|
+
type: z.union([columnTypeSchema2, z.object({ enum: identifier2 })]),
|
|
1448
2201
|
nullable: z.boolean().default(true),
|
|
1449
2202
|
unique: z.boolean().default(false),
|
|
1450
2203
|
/** Literal default, or one of the allowlisted SQL functions. */
|
|
@@ -1694,7 +2447,7 @@ var canonicalActionSchema = z.object({
|
|
|
1694
2447
|
name: identifier2,
|
|
1695
2448
|
requires: z.string().max(1e3).optional(),
|
|
1696
2449
|
params: z.record(z.string(), z.object({
|
|
1697
|
-
type:
|
|
2450
|
+
type: columnTypeSchema2,
|
|
1698
2451
|
nullable: z.boolean().default(false)
|
|
1699
2452
|
})).default({}),
|
|
1700
2453
|
executes: z.string().min(1).max(1e4),
|
|
@@ -1795,7 +2548,8 @@ var canonicalTableSchema = z.object({
|
|
|
1795
2548
|
if ([table.policies.write, table.policies.insert, table.policies.update].some((policy) => policy !== void 0)) {
|
|
1796
2549
|
fail("is read-only and cannot declare write policies", ["policies"]);
|
|
1797
2550
|
}
|
|
1798
|
-
const
|
|
2551
|
+
const ownedIndexes = table.source === void 0 ? table.indexes : table.indexes.filter((index) => index.unique);
|
|
2552
|
+
const ownedCollections = [ownedIndexes, table.actions, table.checks, table.foreignKeys, table.cowMutations];
|
|
1799
2553
|
const ownedMetadata = [table.cellMetadata, table.internal, table.materializes, table.renamedFrom];
|
|
1800
2554
|
if (ownedCollections.some((items) => items !== void 0 && items.length > 0) || ownedMetadata.some((value) => value !== void 0)) {
|
|
1801
2555
|
fail("cannot declare owned storage, constraints or identity operations");
|
|
@@ -1897,6 +2651,23 @@ function trackedCellColumns(table) {
|
|
|
1897
2651
|
return table.columns.filter((column) => column.cell === void 0 && !pk.has(column.columnName) && column.onUpdateFn === void 0);
|
|
1898
2652
|
}
|
|
1899
2653
|
var SUFFIXES = Object.values(CELL_PART_SUFFIX);
|
|
2654
|
+
function validateSyncedIndexes(table, tableIndex, ctx) {
|
|
2655
|
+
if (table.source === void 0) return;
|
|
2656
|
+
const columns = new Set(table.columns.map((column) => column.columnName));
|
|
2657
|
+
for (const [position, index] of table.indexes.entries()) {
|
|
2658
|
+
const fail = (message) => ctx.addIssue({ code: "custom", path: ["tables", tableIndex, "indexes", position], message: `synced table '${table.table}' ${message}` });
|
|
2659
|
+
if (columns.size === 0) fail("must declare columns to declare indexes");
|
|
2660
|
+
if (index.unique) fail("cannot declare a unique index");
|
|
2661
|
+
if (new Set(index.columns).size !== index.columns.length) fail("index names a column more than once");
|
|
2662
|
+
for (const column of index.columns) {
|
|
2663
|
+
if (columns.size > 0 && !columns.has(column)) fail(`index references unknown column '${column}'`);
|
|
2664
|
+
}
|
|
2665
|
+
const name2 = indexName(table.table, index);
|
|
2666
|
+
if (name2.length > MAX_IDENTIFIER_LENGTH) {
|
|
2667
|
+
fail(`derived index name '${name2}' exceeds Postgres's ${MAX_IDENTIFIER_LENGTH}-byte identifier limit \u2014 set a shorter explicit name`);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
1900
2671
|
function validateCellMetadata(table, index, ctx) {
|
|
1901
2672
|
const fail = (message, path = ["tables", index]) => ctx.addIssue({ code: "custom", path, message });
|
|
1902
2673
|
const cells = table.columns.flatMap((column, position) => column.cell ? [{ column, position, cell: column.cell }] : []);
|
|
@@ -1963,12 +2734,24 @@ var localDefinitionSchema = z.object({
|
|
|
1963
2734
|
}).default({ uses: [] })
|
|
1964
2735
|
}).superRefine((definition, ctx) => {
|
|
1965
2736
|
const seen = /* @__PURE__ */ new Set();
|
|
2737
|
+
const syncedIndexOwners = /* @__PURE__ */ new Map();
|
|
1966
2738
|
for (const [index, table] of definition.tables.entries()) {
|
|
1967
2739
|
if (seen.has(table.table)) {
|
|
1968
2740
|
ctx.addIssue({ code: "custom", path: ["tables", index, "table"], message: `duplicate relation '${table.table}'` });
|
|
1969
2741
|
}
|
|
1970
2742
|
seen.add(table.table);
|
|
1971
2743
|
validateCellMetadata(table, index, ctx);
|
|
2744
|
+
validateSyncedIndexes(table, index, ctx);
|
|
2745
|
+
if (table.source !== void 0) {
|
|
2746
|
+
for (const [position, entry] of table.indexes.entries()) {
|
|
2747
|
+
const name2 = indexName(table.table, entry);
|
|
2748
|
+
const owner = syncedIndexOwners.get(name2);
|
|
2749
|
+
if (owner !== void 0) {
|
|
2750
|
+
ctx.addIssue({ code: "custom", path: ["tables", index, "indexes", position], message: `synced index '${name2}' is also declared on '${owner}'` });
|
|
2751
|
+
}
|
|
2752
|
+
syncedIndexOwners.set(name2, table.table);
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
1972
2755
|
if (table.source !== void 0) {
|
|
1973
2756
|
for (const [columnIndex, column] of table.columns.entries()) {
|
|
1974
2757
|
if (column.onUpdateFn !== void 0) {
|
|
@@ -2946,9 +3729,15 @@ function buildCanonicalTable({ table, relationsByName, enumsByName }) {
|
|
|
2946
3729
|
if (table.config.checks?.length) {
|
|
2947
3730
|
throw new OrmDefinitionError(`synced table "${table.tableName}" is system-owned; checks are not allowed`, table.file);
|
|
2948
3731
|
}
|
|
2949
|
-
if (table.config.indexes
|
|
3732
|
+
if (table.config.indexes?.some((index) => index.unique === true)) {
|
|
3733
|
+
throw new OrmDefinitionError(
|
|
3734
|
+
`synced table "${table.tableName}": indexes cannot be unique \u2014 the primary key already identifies a row, and a unique index can fail the sync`,
|
|
3735
|
+
table.file
|
|
3736
|
+
);
|
|
3737
|
+
}
|
|
3738
|
+
if (table.config.indexes?.length && Object.keys(table.columns).length === 0) {
|
|
2950
3739
|
throw new OrmDefinitionError(
|
|
2951
|
-
`synced table "${table.tableName}"
|
|
3740
|
+
`synced table "${table.tableName}": only a typed synced table (declared columns) can declare indexes`,
|
|
2952
3741
|
table.file
|
|
2953
3742
|
);
|
|
2954
3743
|
}
|