@niscorp/vex 0.4.5 → 0.5.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 (40) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/DESIGN.md +72 -45
  3. package/DOCS.md +130 -21
  4. package/README.md +17 -0
  5. package/dist/adapters/express/index.cjs +606 -173
  6. package/dist/adapters/express/index.cjs.map +1 -1
  7. package/dist/adapters/express/index.d.cts +6 -2
  8. package/dist/adapters/express/index.d.ts +6 -2
  9. package/dist/adapters/express/index.js +16 -3
  10. package/dist/adapters/express/index.js.map +1 -1
  11. package/dist/adapters/hono/index.cjs +597 -173
  12. package/dist/adapters/hono/index.cjs.map +1 -1
  13. package/dist/adapters/hono/index.d.cts +5 -2
  14. package/dist/adapters/hono/index.d.ts +5 -2
  15. package/dist/adapters/hono/index.js +7 -3
  16. package/dist/adapters/hono/index.js.map +1 -1
  17. package/dist/agent/index.cjs +12 -12
  18. package/dist/agent/index.cjs.map +1 -1
  19. package/dist/agent/index.d.cts +1 -1
  20. package/dist/agent/index.d.ts +1 -1
  21. package/dist/agent/index.js +12 -12
  22. package/dist/agent/index.js.map +1 -1
  23. package/dist/{chunk-W5MYFJKT.js → chunk-F7OXXJIH.js} +562 -192
  24. package/dist/chunk-F7OXXJIH.js.map +1 -0
  25. package/dist/{chunk-F7RDSWYF.js → chunk-VHNCSQPO.js} +2 -2
  26. package/dist/{chunk-F7RDSWYF.js.map → chunk-VHNCSQPO.js.map} +1 -1
  27. package/dist/{handler-O6XslV-S.d.ts → handler-DdfaWN_J.d.ts} +7 -1
  28. package/dist/{handler-CB0BqKsY.d.cts → handler-kvZkxwaN.d.cts} +7 -1
  29. package/dist/index.cjs +493 -232
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +5 -3
  32. package/dist/index.d.ts +5 -3
  33. package/dist/index.js +118 -221
  34. package/dist/index.js.map +1 -1
  35. package/dist/migrations/index.cjs.map +1 -1
  36. package/dist/migrations/index.js +1 -1
  37. package/dist/{types-BmHuPfPS.d.cts → types-BxkRxTTx.d.cts} +5 -0
  38. package/dist/{types-D5CCaqcd.d.ts → types-DgUZNKii.d.ts} +5 -0
  39. package/package.json +8 -8
  40. package/dist/chunk-W5MYFJKT.js.map +0 -1
@@ -17,6 +17,12 @@ var QueryRequestSchema = zod.z.object({
17
17
  shape: zod.z.unknown().optional(),
18
18
  context: ContextSchema.default({})
19
19
  });
20
+ var dropNullIntentAndFingerprint = (body) => {
21
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return body;
22
+ const isNullAt = (key) => Reflect.get(body, key) === null;
23
+ if (!isNullAt("intent") && !isNullAt("fingerprint")) return body;
24
+ return Object.fromEntries(Object.entries(body).filter(([key, value]) => value !== null || key !== "intent" && key !== "fingerprint"));
25
+ };
20
26
  var ContextRefSchema = zod.z.object({
21
27
  $context: zod.z.string().describe("Key to look up in the request context object")
22
28
  }).strict().describe("Reference to a caller-provided context value");
@@ -170,6 +176,7 @@ var fireAndForget = (p, onError) => {
170
176
  };
171
177
  var TOUCH_EVERY_MS = 6e4;
172
178
  var isTouchDue = (entry, now) => entry.lastUsedAt === void 0 || now - entry.lastUsedAt >= TOUCH_EVERY_MS;
179
+ var touchEntry = (cache, key, entry, now) => cache.touch !== void 0 ? cache.touch(key, now) : cache.set(key, { ...entry, lastUsedAt: now });
173
180
  var isEntryFresh = (entry, currentFingerprint) => {
174
181
  const expired = entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
175
182
  const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
@@ -357,6 +364,47 @@ Object.defineProperty(VexError.prototype, VEX_ERROR, { value: true });
357
364
  var isVexError = (err) => err instanceof VexError || err instanceof Error && Reflect.get(err, VEX_ERROR) === true;
358
365
 
359
366
  // src/engine/optional.ts
367
+ var gateKeys = (key) => Array.isArray(key) ? key : [key];
368
+ var prune = (filter, present, insideExists) => {
369
+ if ("optional" in filter) {
370
+ const keys = gateKeys(filter.optional.key);
371
+ if (insideExists) {
372
+ throw new VexError("invalid_dsl", `An optional condition ("${keys.join(", ")}") cannot live inside an exists \u2014 its correlation must hold on every run.`);
373
+ }
374
+ return prune(filter.optional.then, present, insideExists);
375
+ }
376
+ if ("exists" in filter) {
377
+ const inner = filter.exists.filter === void 0 ? void 0 : prune(filter.exists.filter, present, true);
378
+ return inner === void 0 ? { exists: { from: filter.exists.from } } : { exists: { from: filter.exists.from, filter: inner } };
379
+ }
380
+ if ("and" in filter || "or" in filter) {
381
+ const isAnd = "and" in filter;
382
+ const kept = (isAnd ? filter.and : filter.or).map((sub) => prune(sub, present, insideExists)).filter((sub) => sub !== void 0);
383
+ if (kept.length === 0) return void 0;
384
+ if (kept.length === 1) return kept[0];
385
+ return isAnd ? { and: kept } : { or: kept };
386
+ }
387
+ if ("not" in filter) {
388
+ const inner = prune(filter.not, present, insideExists);
389
+ if (inner === void 0) {
390
+ throw new VexError("invalid_dsl", "An optional condition cannot be the whole body of a `not` \u2014 wrap the `not` in the optional instead.");
391
+ }
392
+ return { not: inner };
393
+ }
394
+ return filter;
395
+ };
396
+ var pruneOptional = (dsl, present) => {
397
+ const from = dsl.from.map(
398
+ (source) => typeof source === "string" ? source : { as: source.as, query: pruneOptional(source.query, present) }
399
+ );
400
+ if (dsl.filter === void 0) return { ...dsl, from };
401
+ const filter = prune(dsl.filter, present, false);
402
+ if (filter === void 0) {
403
+ const { filter: _dropped, ...rest } = dsl;
404
+ return { ...rest, from };
405
+ }
406
+ return { ...dsl, from, filter };
407
+ };
360
408
  var refuseOptional = (where) => {
361
409
  throw new VexError(
362
410
  "invalid_dsl",
@@ -376,15 +424,126 @@ var quoteLiteral = (s) => {
376
424
  const doubled = s.replace(/'/g, "''");
377
425
  return s.includes("\\") ? `E'${doubled.replace(/\\/g, "\\\\")}'` : `'${doubled}'`;
378
426
  };
427
+ var quoteIdent = (name) => `"${name.replace(/"/g, '""')}"`;
428
+ var RESERVED = /* @__PURE__ */ new Set([
429
+ "all",
430
+ "analyse",
431
+ "analyze",
432
+ "and",
433
+ "any",
434
+ "array",
435
+ "as",
436
+ "asc",
437
+ "asymmetric",
438
+ "authorization",
439
+ "binary",
440
+ "both",
441
+ "case",
442
+ "cast",
443
+ "check",
444
+ "collate",
445
+ "collation",
446
+ "column",
447
+ "concurrently",
448
+ "constraint",
449
+ "create",
450
+ "cross",
451
+ "current_catalog",
452
+ "current_date",
453
+ "current_role",
454
+ "current_schema",
455
+ "current_time",
456
+ "current_timestamp",
457
+ "current_user",
458
+ "default",
459
+ "deferrable",
460
+ "desc",
461
+ "distinct",
462
+ "do",
463
+ "else",
464
+ "end",
465
+ "except",
466
+ "false",
467
+ "fetch",
468
+ "for",
469
+ "foreign",
470
+ "freeze",
471
+ "from",
472
+ "full",
473
+ "grant",
474
+ "group",
475
+ "having",
476
+ "ilike",
477
+ "in",
478
+ "initially",
479
+ "inner",
480
+ "intersect",
481
+ "into",
482
+ "is",
483
+ "isnull",
484
+ "join",
485
+ "lateral",
486
+ "leading",
487
+ "left",
488
+ "like",
489
+ "limit",
490
+ "localtime",
491
+ "localtimestamp",
492
+ "natural",
493
+ "not",
494
+ "notnull",
495
+ "null",
496
+ "offset",
497
+ "on",
498
+ "only",
499
+ "or",
500
+ "order",
501
+ "outer",
502
+ "overlaps",
503
+ "placing",
504
+ "primary",
505
+ "references",
506
+ "returning",
507
+ "right",
508
+ "select",
509
+ "session_user",
510
+ "similar",
511
+ "some",
512
+ "symmetric",
513
+ "system_user",
514
+ "table",
515
+ "tablesample",
516
+ "then",
517
+ "to",
518
+ "trailing",
519
+ "true",
520
+ "union",
521
+ "unique",
522
+ "user",
523
+ "using",
524
+ "variadic",
525
+ "verbose",
526
+ "when",
527
+ "where",
528
+ "window",
529
+ "with"
530
+ ]);
531
+ var LOWER_IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
532
+ var sqlName = (name) => LOWER_IDENTIFIER.test(name) && !RESERVED.has(name) ? name : quoteIdent(name);
533
+ var columnSql = (qualifier, column) => `${sqlName(qualifier)}.${sqlName(column)}`;
534
+ var tableSql = (table, namespace) => namespace === void 0 ? sqlName(table) : `${quoteIdent(namespace)}.${sqlName(table)}`;
379
535
  var numberLiteral = (n) => {
380
536
  if (!Number.isFinite(n)) throw new VexError("invalid_dsl", `${String(n)} is not a number SQL can hold.`);
381
537
  return String(n);
382
538
  };
383
539
  var columnOf = (path, ctx) => {
384
540
  const mapped = ctx.aliasMap.get(path);
385
- if (mapped !== void 0) return mapped;
541
+ if (mapped !== void 0) {
542
+ const dot = mapped.indexOf(".");
543
+ return columnSql(mapped.slice(0, dot), mapped.slice(dot + 1));
544
+ }
386
545
  const res = ctx.resolvedPaths.get(path);
387
- if (res !== void 0) return `${res.alias}.${res.column}`;
546
+ if (res !== void 0) return columnSql(res.alias, res.column);
388
547
  throw new VexError("invalid_dsl", `"${path}" is not a column this query reads.`);
389
548
  };
390
549
  var isFieldPath = isFieldPathShape;
@@ -434,7 +593,7 @@ var compileJoinPairs = (join) => join.fromColumns.map((column, i) => {
434
593
  `The join from "${join.fromAlias}" to "${join.toAlias}" pairs "${column}" with no column.`
435
594
  );
436
595
  }
437
- return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;
596
+ return `${columnSql(join.fromAlias, column)} = ${columnSql(join.toAlias, to)}`;
438
597
  });
439
598
  var compileComparisonFilter = (op, pair, ctx) => {
440
599
  const left = compileFieldOrValue(pair[0], ctx);
@@ -453,7 +612,7 @@ var compileFilter = (filter, ctx) => {
453
612
  };
454
613
  const parts = ["SELECT 1"];
455
614
  const first = resolved.sources[0];
456
- if (first?.table !== void 0) parts.push(`FROM ${first.table} AS ${first.alias}`);
615
+ if (first?.table !== void 0) parts.push(`FROM ${tableSql(first.table, ctx.namespace)} AS ${sqlName(first.alias)}`);
457
616
  for (const join of resolved.joins) {
458
617
  const source = resolved.sources.find((s) => s.alias === join.toAlias);
459
618
  if (source?.table === void 0) continue;
@@ -462,7 +621,7 @@ var compileFilter = (filter, ctx) => {
462
621
  ...compileJoinPairs(join),
463
622
  ...(join.on ?? []).map((extra) => compileFilter(extra.original, inner))
464
623
  ];
465
- parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(" AND ")}`);
624
+ parts.push(`${keyword} ${tableSql(source.table, ctx.namespace)} AS ${sqlName(join.toAlias)} ON ${conditions.join(" AND ")}`);
466
625
  }
467
626
  if (resolved.filter !== void 0) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);
468
627
  return `EXISTS (${parts.join(" ")})`;
@@ -545,17 +704,13 @@ var compileFilter = (filter, ctx) => {
545
704
  const fieldPath2 = filter.semantic.field;
546
705
  const col = columnOf(fieldPath2, ctx);
547
706
  const queryRef = filter.semantic.query;
548
- const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
549
707
  if ("$context" in queryRef) assertNotReserved(queryRef.$context);
550
708
  const res = ctx.resolvedPaths.get(fieldPath2);
551
709
  const dimensions = res?.schema.vectorDimensions;
552
710
  ctx.paramCounter.value += 1;
553
- ctx.paramSlots.push({
554
- key,
555
- kind: "semantic",
556
- type: "string",
557
- dimensions
558
- });
711
+ ctx.paramSlots.push(
712
+ "$context" in queryRef ? { key: queryRef.$context, kind: "semantic", type: "string", dimensions } : { key: queryRef.$scope, kind: "scope", type: "string", dimensions, embed: true }
713
+ );
559
714
  const paramRef = `$${ctx.paramCounter.value}`;
560
715
  const minScore = numberLiteral(filter.semantic.minScore ?? 0);
561
716
  return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;
@@ -591,13 +746,15 @@ var VexScopeError = class extends VexError {
591
746
  this.entity = entity;
592
747
  }
593
748
  };
594
- var canReadTable = (policy, table) => {
749
+ var readRulesOf = (policy, table) => {
595
750
  const rule = policy.entities[table];
596
- if (rule === void 0) return policy.default === "allow";
597
- if ("public" in rule) return true;
598
- if ("deny" in rule) return false;
599
- return rule.read !== void 0 || policy.default === "allow";
751
+ if (rule === void 0) return policy.default === "deny" ? "unlisted" : [];
752
+ if ("public" in rule) return [];
753
+ if ("deny" in rule) return "denied";
754
+ if (rule.read === void 0) return policy.default === "deny" ? "ungranted" : [];
755
+ return rule.read;
600
756
  };
757
+ var canReadTable = (policy, table) => Array.isArray(readRulesOf(policy, table));
601
758
 
602
759
  // src/utils/context.ts
603
760
  var resolveParams = async (slots, context, scope, embed) => {
@@ -607,10 +764,11 @@ var resolveParams = async (slots, context, scope, embed) => {
607
764
  results.push(context[slot.key]);
608
765
  continue;
609
766
  }
610
- if (slot.kind === "scope") {
767
+ if (slot.kind === "scope" && slot.embed !== true) {
611
768
  results.push(scope[slot.key]);
612
769
  continue;
613
770
  }
771
+ slot.kind === "scope" ? "scope" : "context";
614
772
  {
615
773
  throw new Error(`Semantic parameter "${slot.key}" requires an embed function`);
616
774
  }
@@ -952,18 +1110,11 @@ var assertReturnedColumns = (refs, schema) => {
952
1110
  }
953
1111
  };
954
1112
  var readMatchesFor = (table, policy) => {
955
- const rule = policy.entities[table];
956
- if (rule === void 0) {
957
- if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
958
- return [];
959
- }
960
- if ("public" in rule) return [];
961
- if ("deny" in rule) throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
962
- if (rule.read === void 0) {
963
- if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
964
- return [];
965
- }
966
- return rule.read;
1113
+ const rules = readRulesOf(policy, table);
1114
+ if (rules === "unlisted") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
1115
+ if (rules === "denied") throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
1116
+ if (rules === "ungranted") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
1117
+ return rules;
967
1118
  };
968
1119
  var boundaryOf = (table, r) => isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };
969
1120
  var scopeLookups = (cols, policy) => {
@@ -981,21 +1132,22 @@ var scopeLookups = (cols, policy) => {
981
1132
  }
982
1133
  return out;
983
1134
  };
984
- var writeGate = (table, op, policy) => {
1135
+ var writeGateOf = (table, op, policy) => {
985
1136
  const rule = policy.entities[table];
986
- if (rule === void 0) {
987
- if (policy.default === "deny") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
988
- return void 0;
989
- }
1137
+ if (rule === void 0) return policy.default === "deny" ? "unlisted" : void 0;
990
1138
  if ("public" in rule) return void 0;
991
- if ("deny" in rule) throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
1139
+ if ("deny" in rule) return "denied";
992
1140
  const specific = op === "insert" ? rule.insert : op === "update" ? rule.update : rule.delete;
993
- if (rule.write === void 0 && specific === void 0) {
994
- if (policy.default === "deny") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
995
- return void 0;
996
- }
1141
+ if (rule.write === void 0 && specific === void 0) return policy.default === "deny" ? "ungranted" : void 0;
997
1142
  return { rule, rules: [...rule.write ?? [], ...specific ?? []] };
998
1143
  };
1144
+ var writeGate = (table, op, policy) => {
1145
+ const gate = writeGateOf(table, op, policy);
1146
+ if (gate === "unlisted") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
1147
+ if (gate === "denied") throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
1148
+ if (gate === "ungranted") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
1149
+ return gate;
1150
+ };
999
1151
  var scopeInsertParts = (table, rawValues, rawConflict, policy) => {
1000
1152
  let values = scopeLookups(rawValues, policy);
1001
1153
  let conflict = rawConflict === void 0 || rawConflict.set === void 0 ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };
@@ -1059,12 +1211,13 @@ var itemRow = (element, itemKeys) => {
1059
1211
  const fields = element !== null && typeof element === "object" && !Array.isArray(element) ? element : {};
1060
1212
  return Object.fromEntries(Object.entries(itemKeys).map(([column, key]) => [column, fields[key]]));
1061
1213
  };
1062
- var newCtx = () => ({
1214
+ var newCtx = (namespace) => ({
1063
1215
  resolvedPaths: /* @__PURE__ */ new Map(),
1064
1216
  aliasMap: /* @__PURE__ */ new Map(),
1065
1217
  paramSlots: [],
1066
1218
  paramCounter: { value: 0 },
1067
- returned: /* @__PURE__ */ new Map()
1219
+ returned: /* @__PURE__ */ new Map(),
1220
+ ...namespace !== void 0 ? { namespace } : {}
1068
1221
  });
1069
1222
  var indexFilterFields = (filter, aliasMap) => {
1070
1223
  for (const path of filterColumns(filter)) aliasMap.set(path, path);
@@ -1073,7 +1226,7 @@ var compileValue = (v, ctx) => {
1073
1226
  if (isLookup(v)) {
1074
1227
  indexFilterFields(v.$lookup.where, ctx.aliasMap);
1075
1228
  const where = compileFilter(v.$lookup.where, ctx);
1076
- return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
1229
+ return `(SELECT ${sqlName(v.$lookup.field)} FROM ${tableSql(v.$lookup.from, ctx.namespace)} WHERE ${where})`;
1077
1230
  }
1078
1231
  if (isReturned(v)) {
1079
1232
  ctx.paramCounter.value += 1;
@@ -1093,37 +1246,84 @@ var compileColumnValue = (table, column, v, ctx, schema) => {
1093
1246
  }
1094
1247
  return sql;
1095
1248
  };
1096
- var compileConflict = (m, ctx, schema) => {
1249
+ var scopeSlot = (r, ctx) => {
1250
+ ctx.paramCounter.value += 1;
1251
+ ctx.paramSlots.push(isSetMatch(r) ? { key: r.in, kind: "scope", type: "string[]" } : { key: r.to, kind: "scope", type: "string" });
1252
+ return isSetMatch(r) ? `= ANY($${ctx.paramCounter.value})` : `= $${ctx.paramCounter.value}`;
1253
+ };
1254
+ var keptChecks = (table, written, pinned, ctx, schema) => pinned.flatMap((rule) => {
1255
+ const value = written.get(rule.match);
1256
+ const type = findEntity(table, schema)?.fields.find((f) => f.name === rule.match)?.type;
1257
+ if (value === void 0 || type === void 0) return [];
1258
+ return [{ rule, sql: `(${value})::${type} ${scopeSlot(rule, ctx)}` }];
1259
+ });
1260
+ var compileConflict = (m, ctx, schema, pinned) => {
1097
1261
  const c = m.onConflict;
1098
1262
  if (c === void 0) return "";
1099
- if (c.set === void 0) return ` ON CONFLICT (${c.target.join(", ")}) DO NOTHING`;
1100
- const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);
1101
- let where = "";
1263
+ const target = c.target.map(sqlName).join(", ");
1264
+ if (c.set === void 0) return ` ON CONFLICT (${target}) DO NOTHING`;
1265
+ const written = new Map(Object.entries(c.set).map(([col, v]) => [col, compileColumnValue(m.table, col, v, ctx, schema)]));
1266
+ const sets = [...written].map(([col, sql]) => `${sqlName(col)} = ${sql}`);
1267
+ const conditions = [];
1102
1268
  if (c.where !== void 0) {
1103
1269
  indexFilterFields(c.where, ctx.aliasMap);
1104
- where = ` WHERE ${compileFilter(c.where, ctx)}`;
1270
+ conditions.push(compileFilter(c.where, ctx));
1105
1271
  }
1106
- return ` ON CONFLICT (${c.target.join(", ")}) DO UPDATE SET ${sets.join(", ")}${where}`;
1272
+ conditions.push(...keptChecks(m.table, written, pinned, ctx, schema).map((k) => k.sql));
1273
+ const where = conditions.length === 0 ? "" : ` WHERE ${conditions.join(" AND ")}`;
1274
+ return ` ON CONFLICT (${target}) DO UPDATE SET ${sets.join(", ")}${where}`;
1107
1275
  };
1108
- var compileMutation = (m, schema) => {
1109
- const ctx = newCtx();
1276
+ var compileMovedCheck = (m, schema, pinned) => {
1277
+ const ctx = newCtx(schema.namespace);
1278
+ const written = new Map(
1279
+ Object.entries(m.set).filter(([c]) => pinned.some((r) => r.match === c)).map(([c, v]) => [c, compileColumnValue(m.table, c, v, ctx, schema)])
1280
+ );
1281
+ const checks = keptChecks(m.table, written, pinned, ctx, schema);
1282
+ if (checks.length === 0) return void 0;
1283
+ indexFilterFields(m.where, ctx.aliasMap);
1284
+ const where = compileFilter(m.where, ctx);
1285
+ const each = checks.map((k, i) => `(${k.sql}) IS TRUE AS "${i}"`).join(", ");
1286
+ const all = checks.map((k) => k.sql).join(" AND ");
1287
+ return {
1288
+ sql: `SELECT ${each} FROM ${tableSql(m.table, schema.namespace)} WHERE ${where} AND (${all}) IS NOT TRUE LIMIT 1`,
1289
+ slots: ctx.paramSlots,
1290
+ returned: ctx.returned,
1291
+ rules: checks.map((k) => k.rule)
1292
+ };
1293
+ };
1294
+ var movedRefusal = (table, rule) => new VexScopeError(
1295
+ table,
1296
+ `This update would move a row of "${table}" out of the caller's update rule { match: "${rule.match}", ${isSetMatch(rule) ? `in: "${rule.in}"` : `to: "${rule.to}"`} }: the new "${table}.${rule.match}" ${isSetMatch(rule) ? `is not one of the scope's "${rule.in}"` : `is not the scope's "${rule.to}"`}. Nothing was written.`
1297
+ );
1298
+ var READABLE = "vex:readable";
1299
+ var returning = (readable, ctx) => {
1300
+ if (readable === "all") return " RETURNING *";
1301
+ if (readable === "none") return ` RETURNING *, FALSE AS "${READABLE}"`;
1302
+ return ` RETURNING *, (${readable.map((r) => `${sqlName(r.match)} ${scopeSlot(r, ctx)}`).join(" AND ")}) AS "${READABLE}"`;
1303
+ };
1304
+ var compileMutation = (m, schema, pinned, readable) => {
1305
+ const ctx = newCtx(schema.namespace);
1306
+ const finish = (head) => {
1307
+ const ownSlots = ctx.paramSlots.length;
1308
+ return { sql: `${head}${returning(readable, ctx)}`, slots: ctx.paramSlots, returned: ctx.returned, ownSlots, marked: readable !== "all" };
1309
+ };
1110
1310
  if (m.op === "insert") {
1111
1311
  const entries = Object.entries(m.values);
1112
- const cols = entries.map(([c]) => c);
1312
+ const cols = entries.map(([c]) => sqlName(c));
1113
1313
  const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
1114
- return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1314
+ return finish(`INSERT INTO ${tableSql(m.table, schema.namespace)} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema, pinned)}`);
1115
1315
  }
1116
1316
  if (m.op === "insertEach") {
1117
1317
  const types = new Map(findEntity(m.table, schema)?.fields.map((f) => [f.name, f.type]));
1118
1318
  const entries = Object.entries(m.values);
1119
- const cols = entries.map(([c]) => c);
1319
+ const cols = entries.map(([c]) => sqlName(c));
1120
1320
  const itemKeys = {};
1121
1321
  const itemColumns = [];
1122
1322
  const exprs = entries.map(([col, v]) => {
1123
1323
  if (isItemRef(v)) {
1124
1324
  itemKeys[col] = v.$item;
1125
- itemColumns.push(`${col} ${String(types.get(col))}`);
1126
- return `item.${col}`;
1325
+ itemColumns.push(`${sqlName(col)} ${String(types.get(col))}`);
1326
+ return `item.${sqlName(col)}`;
1127
1327
  }
1128
1328
  return isReturned(v) ? compileColumnValue(m.table, col, v, ctx, schema) : compileValue(v, ctx);
1129
1329
  });
@@ -1131,37 +1331,48 @@ var compileMutation = (m, schema) => {
1131
1331
  ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
1132
1332
  const items = `$${ctx.paramCounter.value}::jsonb`;
1133
1333
  const source = itemColumns.length === 0 ? `jsonb_array_elements(${items}) AS item` : `jsonb_to_recordset(${items}) AS item(${itemColumns.join(", ")})`;
1134
- return {
1135
- sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
1136
- slots: ctx.paramSlots,
1137
- returned: ctx.returned,
1138
- itemKeys
1139
- };
1334
+ return { ...finish(`INSERT INTO ${tableSql(m.table, schema.namespace)} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema, pinned)}`), itemKeys };
1140
1335
  }
1141
1336
  if (m.op === "update") {
1142
- const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
1337
+ const written = new Map(Object.entries(m.set).map(([c, v]) => [c, compileColumnValue(m.table, c, v, ctx, schema)]));
1338
+ const sets = [...written].map(([c, sql]) => `${sqlName(c)} = ${sql}`);
1143
1339
  indexFilterFields(m.where, ctx.aliasMap);
1144
- const where2 = compileFilter(m.where, ctx);
1145
- return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1340
+ const where2 = [compileFilter(m.where, ctx), ...keptChecks(m.table, written, pinned, ctx, schema).map((k) => k.sql)].join(" AND ");
1341
+ return finish(`UPDATE ${tableSql(m.table, schema.namespace)} SET ${sets.join(", ")} WHERE ${where2}`);
1146
1342
  }
1147
1343
  indexFilterFields(m.where, ctx.aliasMap);
1148
1344
  const where = compileFilter(m.where, ctx);
1149
- return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1345
+ return finish(`DELETE FROM ${tableSql(m.table, schema.namespace)} WHERE ${where}`);
1150
1346
  };
1347
+ var keyMadeByDatabase = (m, schema) => !(m.key in m.columns) && !(m.key in (m.insert ?? {})) && findEntity(m.table, schema)?.fields.find((f) => f.name === m.key)?.defaultValue !== void 0;
1151
1348
  var SUGAR = {
1152
- upsert: (m, context) => {
1153
- const keyed = context[m.key] !== void 0 && context[m.key] !== "";
1349
+ // Where the database does not make the key, inserting on a null one would break its NOT NULL.
1350
+ upsert: (m, context, schema) => {
1351
+ const value = context[m.key];
1352
+ const keyed = value !== void 0 && value !== "" && (value !== null || !keyMadeByDatabase(m, schema));
1154
1353
  return keyed ? { op: "update", table: m.table, set: m.columns, where: { eq: [`${m.table}.${m.key}`, { $context: m.key }] } } : { op: "insert", table: m.table, values: { ...m.columns, ...m.insert } };
1155
1354
  }
1156
1355
  };
1157
- var desugarMutation = (m, context) => {
1356
+ var desugarMutation = (m, context, schema) => {
1158
1357
  const rewrite = SUGAR[m.op];
1159
- return rewrite === void 0 ? m : rewrite(m, context);
1358
+ return rewrite === void 0 ? m : rewrite(m, context, schema);
1359
+ };
1360
+ var pinnedRules = (m, policy) => {
1361
+ const updates = m.op === "update" || m.op !== "delete" && m.onConflict?.set !== void 0;
1362
+ const gate = updates ? writeGateOf(m.table, "update", policy) : void 0;
1363
+ if (gate === void 0 || typeof gate === "string") return [];
1364
+ const stamped = new Set(gate.rules.flatMap((r) => "set" in r ? [r.set] : []));
1365
+ return gate.rules.flatMap((r) => "match" in r && !stamped.has(r.match) ? [r] : []);
1366
+ };
1367
+ var readableRules = (m, policy) => {
1368
+ if ((m.op === "insert" || m.op === "insertEach") && m.onConflict?.set === void 0) return "all";
1369
+ const rules = readRulesOf(policy, m.table);
1370
+ return typeof rules === "string" ? "none" : rules.length === 0 ? "all" : rules;
1160
1371
  };
1161
1372
  var executeWrites = async (client, def, mctx) => {
1162
1373
  const parsed = MutationDefinitionSchema.parse(def);
1163
1374
  const entries = Array.isArray(parsed) ? parsed : [parsed];
1164
- const cores = entries.map((entry) => desugarMutation(entry, mctx.context));
1375
+ const cores = entries.map((entry) => desugarMutation(entry, mctx.context, mctx.schema));
1165
1376
  const compiled = cores.map((core, at) => {
1166
1377
  const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
1167
1378
  if (missing.length > 0) {
@@ -1174,45 +1385,70 @@ var executeWrites = async (client, def, mctx) => {
1174
1385
  const m = scopeMutation(core, mctx.policy);
1175
1386
  assertWritableColumns(m, mctx.schema);
1176
1387
  assertReturnedColumns(returned.refs, mctx.schema);
1177
- const statement = compileMutation(m, mctx.schema);
1178
- requireScope({ paramSlots: statement.slots }, mctx.scope);
1179
- const reads = [...statement.returned].map(([slot, ref]) => {
1388
+ const pinned = mctx.checkMovedRows === false ? [] : pinnedRules(m, mctx.policy);
1389
+ const statement = compileMutation(m, mctx.schema, pinned, mctx.answerReadableRows === true ? readableRules(m, mctx.policy) : "all");
1390
+ requireScope({ paramSlots: statement.slots.slice(0, statement.ownSlots) }, mctx.scope);
1391
+ const readsOf = (of) => [...of.returned].map(([slot, ref]) => {
1180
1392
  const source = returned.refs.get(ref);
1181
1393
  if (source === void 0) throw new VexError("invalid_dsl", `"${ref}" names no earlier statement of the batch.`);
1182
1394
  return { slot, ref, source };
1183
1395
  });
1184
- return { ...statement, reads, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
1396
+ const moved = m.op === "update" ? compileMovedCheck(m, mctx.schema, pinned) : void 0;
1397
+ return {
1398
+ ...statement,
1399
+ reads: readsOf(statement),
1400
+ ...moved === void 0 ? {} : { moved: { ...moved, reads: readsOf(moved) } },
1401
+ table: m.table,
1402
+ op: m.op === "insertEach" ? "insert" : m.op
1403
+ };
1185
1404
  });
1405
+ const bindParams = async (c, results) => {
1406
+ const params = await resolveParams(c.slots, mctx.context, mctx.scope);
1407
+ for (const read of c.reads) {
1408
+ const rows = results[read.source.statement]?.rows ?? [];
1409
+ const row = rows[0];
1410
+ if (rows.length !== 1 || row === void 0) {
1411
+ throw new VexError(
1412
+ "execution_error",
1413
+ `"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
1414
+ { returned: read.ref, rows: rows.length }
1415
+ );
1416
+ }
1417
+ if (!(read.source.column in row)) {
1418
+ throw new VexError("execution_error", `"${read.ref}": the row statement ${read.source.statement + 1} returned has no "${read.source.column}" key. Nothing was written.`, { returned: read.ref });
1419
+ }
1420
+ params[read.slot] = row[read.source.column];
1421
+ }
1422
+ return params.map((value, i) => {
1423
+ if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
1424
+ if (c.slots[i]?.type !== "json") return value;
1425
+ if (!Array.isArray(value)) {
1426
+ throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
1427
+ }
1428
+ const { itemKeys } = c;
1429
+ return JSON.stringify(itemKeys === void 0 ? value : value.map((element) => itemRow(element, itemKeys)));
1430
+ });
1431
+ };
1186
1432
  const runAll = async (q) => {
1187
1433
  const results = [];
1188
1434
  for (const c of compiled) {
1189
- const params = await resolveParams(c.slots, mctx.context, mctx.scope);
1190
- for (const read of c.reads) {
1191
- const rows = results[read.source.statement]?.rows ?? [];
1192
- const row = rows[0];
1193
- if (rows.length !== 1 || row === void 0) {
1194
- throw new VexError(
1195
- "execution_error",
1196
- `"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
1197
- { returned: read.ref, rows: rows.length }
1198
- );
1199
- }
1200
- if (!(read.source.column in row)) {
1201
- throw new VexError("execution_error", `"${read.ref}": the row statement ${read.source.statement + 1} returned has no "${read.source.column}" key. Nothing was written.`, { returned: read.ref });
1202
- }
1203
- params[read.slot] = row[read.source.column];
1435
+ if (c.moved !== void 0) {
1436
+ const [row] = (await q.query(c.moved.sql, await bindParams(c.moved, results))).rows;
1437
+ const broken = row === void 0 ? void 0 : c.moved.rules.find((_, i) => row[String(i)] !== true);
1438
+ if (broken !== void 0) throw movedRefusal(c.table, broken);
1204
1439
  }
1205
- const bound = params.map((value, i) => {
1206
- if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
1207
- if (c.slots[i]?.type !== "json") return value;
1208
- if (!Array.isArray(value)) {
1209
- throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
1210
- }
1211
- const { itemKeys } = c;
1212
- return JSON.stringify(itemKeys === void 0 ? value : value.map((element) => itemRow(element, itemKeys)));
1213
- });
1214
- const res = await q.query(c.sql, bound);
1215
- results.push({ table: c.table, op: c.op, rows: res.rows });
1440
+ const res = await q.query(c.sql, await bindParams(c, results));
1441
+ if (!c.marked) {
1442
+ results.push({ table: c.table, op: c.op, rows: res.rows });
1443
+ continue;
1444
+ }
1445
+ const rows = [];
1446
+ const readable = [];
1447
+ for (const { [READABLE]: seen, ...row } of res.rows) {
1448
+ rows.push(row);
1449
+ if (seen === true) readable.push(row);
1450
+ }
1451
+ results.push({ table: c.table, op: c.op, rows, readable });
1216
1452
  }
1217
1453
  return results;
1218
1454
  };
@@ -1222,6 +1458,181 @@ var executeWrites = async (client, def, mctx) => {
1222
1458
  }
1223
1459
  return client.transaction((tx) => runAll(tx));
1224
1460
  };
1461
+
1462
+ // src/scope/discover.ts
1463
+ var extractEntityFromPath = (path) => {
1464
+ const parts = path.split(".");
1465
+ return parts.length === 2 ? parts[0] : void 0;
1466
+ };
1467
+ var collectFromFieldOrValue = (fov, out) => {
1468
+ if (isFieldPathShape(fov)) {
1469
+ const entity = extractEntityFromPath(fov);
1470
+ if (entity !== void 0) out.add(entity);
1471
+ }
1472
+ };
1473
+ var collectFromFilter = (filter, out) => {
1474
+ if ("exists" in filter) {
1475
+ for (const entity of filter.exists.from) out.add(entity);
1476
+ if (filter.exists.filter !== void 0) collectFromFilter(filter.exists.filter, out);
1477
+ return;
1478
+ }
1479
+ if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
1480
+ const pair = "eq" in filter ? filter.eq : "neq" in filter ? filter.neq : "gt" in filter ? filter.gt : "gte" in filter ? filter.gte : "lt" in filter ? filter.lt : filter.lte;
1481
+ collectFromFieldOrValue(pair[0], out);
1482
+ collectFromFieldOrValue(pair[1], out);
1483
+ return;
1484
+ }
1485
+ if ("in" in filter || "notIn" in filter) {
1486
+ const tuple = "in" in filter ? filter.in : filter.notIn;
1487
+ const entity = extractEntityFromPath(tuple[0]);
1488
+ if (entity !== void 0) out.add(entity);
1489
+ const target = tuple[1];
1490
+ if (Array.isArray(target)) {
1491
+ for (const v of target) {
1492
+ collectFromFieldOrValue(v, out);
1493
+ }
1494
+ }
1495
+ return;
1496
+ }
1497
+ if ("like" in filter || "ilike" in filter) {
1498
+ const tuple = "like" in filter ? filter.like : filter.ilike;
1499
+ const entity = extractEntityFromPath(tuple[0]);
1500
+ if (entity !== void 0) out.add(entity);
1501
+ collectFromFieldOrValue(tuple[1], out);
1502
+ return;
1503
+ }
1504
+ if ("isNull" in filter) {
1505
+ const entity = extractEntityFromPath(filter.isNull);
1506
+ if (entity !== void 0) out.add(entity);
1507
+ return;
1508
+ }
1509
+ if ("isNotNull" in filter) {
1510
+ const entity = extractEntityFromPath(filter.isNotNull);
1511
+ if (entity !== void 0) out.add(entity);
1512
+ return;
1513
+ }
1514
+ if ("and" in filter) {
1515
+ for (const sub of filter.and) {
1516
+ collectFromFilter(sub, out);
1517
+ }
1518
+ return;
1519
+ }
1520
+ if ("or" in filter) {
1521
+ for (const sub of filter.or) {
1522
+ collectFromFilter(sub, out);
1523
+ }
1524
+ return;
1525
+ }
1526
+ if ("not" in filter) {
1527
+ collectFromFilter(filter.not, out);
1528
+ return;
1529
+ }
1530
+ if ("semantic" in filter) {
1531
+ const entity = extractEntityFromPath(filter.semantic.field);
1532
+ if (entity !== void 0) out.add(entity);
1533
+ return;
1534
+ }
1535
+ if ("fuzzy" in filter) {
1536
+ const entity = extractEntityFromPath(filter.fuzzy.field);
1537
+ if (entity !== void 0) out.add(entity);
1538
+ return;
1539
+ }
1540
+ if ("optional" in filter) refuseOptional("scope discovery");
1541
+ };
1542
+ var collectFromCompute = (expr, out) => {
1543
+ if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
1544
+ const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
1545
+ collectFromFieldOrValue(pair[0], out);
1546
+ collectFromFieldOrValue(pair[1], out);
1547
+ return;
1548
+ }
1549
+ if ("concat" in expr) {
1550
+ for (const v of expr.concat) {
1551
+ collectFromFieldOrValue(v, out);
1552
+ }
1553
+ return;
1554
+ }
1555
+ if ("coalesce" in expr) {
1556
+ for (const v of expr.coalesce) {
1557
+ collectFromFieldOrValue(v, out);
1558
+ }
1559
+ return;
1560
+ }
1561
+ if ("case" in expr) {
1562
+ for (const when of expr.case.when) {
1563
+ collectFromFilter(when.condition, out);
1564
+ collectFromFieldOrValue(when.then, out);
1565
+ }
1566
+ collectFromFieldOrValue(expr.case.else, out);
1567
+ return;
1568
+ }
1569
+ };
1570
+ var collectFromAggregate = (expr, out) => {
1571
+ const arg = "count" in expr ? expr.count : "countDistinct" in expr ? expr.countDistinct : "sum" in expr ? expr.sum : "avg" in expr ? expr.avg : "min" in expr ? expr.min : expr.max;
1572
+ if (typeof arg !== "string") {
1573
+ collectFromCompute(arg, out);
1574
+ return;
1575
+ }
1576
+ const entity = extractEntityFromPath(arg);
1577
+ if (entity !== void 0) out.add(entity);
1578
+ };
1579
+ var collectFromQuery = (dsl, out) => {
1580
+ const aliases = /* @__PURE__ */ new Set();
1581
+ const local = /* @__PURE__ */ new Set();
1582
+ for (const source of dsl.from) {
1583
+ if (typeof source === "string") {
1584
+ out.add(source);
1585
+ } else {
1586
+ aliases.add(source.as);
1587
+ collectFromQuery(source.query, out);
1588
+ }
1589
+ }
1590
+ for (const ref of dsl.fields ?? []) {
1591
+ const entity = extractEntityFromPath(typeof ref === "string" ? ref : ref.field);
1592
+ if (entity !== void 0) local.add(entity);
1593
+ }
1594
+ if (dsl.filter !== void 0) {
1595
+ collectFromFilter(dsl.filter, local);
1596
+ }
1597
+ if (dsl.compute !== void 0) {
1598
+ for (const key of Object.keys(dsl.compute)) {
1599
+ const expr = dsl.compute[key];
1600
+ if (expr !== void 0) {
1601
+ collectFromCompute(expr, local);
1602
+ }
1603
+ }
1604
+ }
1605
+ if (dsl.aggregate !== void 0) {
1606
+ for (const key of Object.keys(dsl.aggregate)) {
1607
+ const expr = dsl.aggregate[key];
1608
+ if (expr !== void 0) {
1609
+ collectFromAggregate(expr, local);
1610
+ }
1611
+ }
1612
+ }
1613
+ if (dsl.groupBy !== void 0) {
1614
+ for (const path of dsl.groupBy) {
1615
+ const entity = extractEntityFromPath(path);
1616
+ if (entity !== void 0) local.add(entity);
1617
+ }
1618
+ }
1619
+ if (dsl.sort !== void 0) {
1620
+ for (const entry of dsl.sort) {
1621
+ const entity = extractEntityFromPath(entry.field);
1622
+ if (entity !== void 0) local.add(entity);
1623
+ }
1624
+ }
1625
+ for (const entity of local) {
1626
+ if (!aliases.has(entity)) out.add(entity);
1627
+ }
1628
+ };
1629
+ var discoverEntities = (dsl) => {
1630
+ const entities = /* @__PURE__ */ new Set();
1631
+ collectFromQuery(dsl, entities);
1632
+ return entities;
1633
+ };
1634
+
1635
+ // src/handler.ts
1225
1636
  var tablesChangedBy = (writes, schema) => {
1226
1637
  const changed = /* @__PURE__ */ new Set();
1227
1638
  const referencing = (table) => (schema?.entities.find((entity) => entity.name === table)?.relations ?? []).filter((relation) => relation.type !== "belongsTo").map((relation) => relation.entity);
@@ -1245,40 +1656,39 @@ var filterSchema = (schema, entities) => {
1245
1656
  if (entities === void 0 || entities.length === 0) return schema.entities;
1246
1657
  return schema.entities.filter((e) => entities.includes(e.name));
1247
1658
  };
1248
- var canWriteTable = (policy, table, op) => {
1249
- const rule = policy.entities[table];
1250
- if (rule === void 0) return policy.default === "allow";
1251
- if ("public" in rule) return true;
1252
- if ("deny" in rule) return false;
1253
- if (rule.write !== void 0 || policy.default === "allow") return true;
1254
- if (op === "insert" || op === "insertEach") return rule.insert !== void 0;
1255
- if (op === "update") return rule.update !== void 0;
1256
- if (op === "delete") return rule.delete !== void 0;
1257
- if (op === "upsert") return rule.insert !== void 0 || rule.update !== void 0;
1258
- return false;
1659
+ var WRITES_OF = {
1660
+ insert: ["insert"],
1661
+ insertEach: ["insert"],
1662
+ update: ["update"],
1663
+ delete: ["delete"],
1664
+ upsert: ["insert", "update"]
1259
1665
  };
1260
- var collectTables = (dsl) => {
1261
- const out = [];
1262
- const walk = (q) => {
1263
- for (const src of q.from) {
1264
- if (typeof src === "string") out.push(src);
1265
- else walk(src.query);
1266
- }
1267
- };
1268
- walk(dsl);
1269
- return out;
1666
+ var canWriteTable = (policy, table, op) => WRITES_OF[op].some((write) => typeof writeGateOf(table, write, policy) !== "string");
1667
+ var tablesRead = (dsl) => {
1668
+ try {
1669
+ return [...discoverEntities(pruneOptional(dsl, "all"))];
1670
+ } catch (err) {
1671
+ if (isVexError(err)) return void 0;
1672
+ throw err;
1673
+ }
1270
1674
  };
1271
- var entryVisible = (policy, entry) => {
1272
- if (entry.kind === "ok") return collectTables(entry.dsl).every((t) => canReadTable(policy, t));
1273
- if (entry.kind === "mutation") return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));
1675
+ var entryVisible = (policies, entry) => {
1676
+ if (entry.kind === "ok") {
1677
+ const { read } = policies;
1678
+ return read === void 0 || (tablesRead(entry.dsl)?.every((t) => canReadTable(read, t)) ?? false);
1679
+ }
1680
+ if (entry.kind === "mutation") {
1681
+ const { write } = policies;
1682
+ return write === void 0 || mutationEffect(entry.mutation).every((e) => canWriteTable(write, e.table, e.op));
1683
+ }
1274
1684
  return false;
1275
1685
  };
1276
- var listFingerprints = async (engine, policy) => {
1686
+ var listFingerprints = async (engine, policies) => {
1277
1687
  if (engine.cache.entries === void 0) return [];
1278
1688
  const schema = engine.getSchema();
1279
1689
  const current = schema !== void 0 ? computeSchemaFingerprint(schema) : void 0;
1280
1690
  const rows = await engine.cache.entries();
1281
- return rows.filter(({ key, entry }) => (entry.kind === "ok" || entry.kind === "mutation") && !key.startsWith("neg:")).filter(({ entry }) => policy === void 0 || entryVisible(policy, entry)).map(({ key, entry }) => ({
1691
+ return rows.filter(({ key, entry }) => (entry.kind === "ok" || entry.kind === "mutation") && !key.startsWith("neg:")).filter(({ entry }) => entryVisible(policies, entry)).map(({ key, entry }) => ({
1282
1692
  fingerprint: key,
1283
1693
  kind: entry.kind === "mutation" ? "mutation" : "query",
1284
1694
  protected: entry.protected === true,
@@ -1296,11 +1706,12 @@ var listFingerprints = async (engine, policy) => {
1296
1706
  }));
1297
1707
  };
1298
1708
  var handleDiscovery = async (config) => {
1299
- const { engine, entities: entityFilter, scopePolicy } = config;
1709
+ const { engine, entities: entityFilter } = config;
1710
+ const scopePolicy = config.scopePolicy ?? engine.scopePolicy;
1300
1711
  const filtered = filterSchema(engine.getSchema(), entityFilter).filter(
1301
1712
  (e) => scopePolicy === void 0 || canReadTable(scopePolicy, e.name)
1302
1713
  );
1303
- const fingerprints = await listFingerprints(engine, scopePolicy);
1714
+ const fingerprints = await listFingerprints(engine, { read: scopePolicy, write: config.mutations?.policy ?? scopePolicy });
1304
1715
  const protectedCount = fingerprints.filter((f) => f.protected).length;
1305
1716
  return {
1306
1717
  protection: protectedCount === 0 ? "none" : protectedCount === fingerprints.length ? "all" : "some",
@@ -1378,10 +1789,29 @@ var handleQuery = async (config, body, scope, live) => {
1378
1789
  return result;
1379
1790
  };
1380
1791
  var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1792
+ var policyAtReach = async (config, fingerprint, reach) => {
1793
+ if (config.policyForReach === void 0) {
1794
+ return {
1795
+ status: 500,
1796
+ body: {
1797
+ error: "execution_error",
1798
+ message: `Entry "${fingerprint}" requires reach "${reach}" and this handler has no policyForReach.`
1799
+ }
1800
+ };
1801
+ }
1802
+ const narrowed = await config.policyForReach(reach);
1803
+ if (narrowed === void 0) {
1804
+ return {
1805
+ status: 403,
1806
+ body: { error: "scope_denied", message: `Reach "${reach}" is not available to this principal.` }
1807
+ };
1808
+ }
1809
+ return narrowed;
1810
+ };
1381
1811
  var runQuery = async (config, body, scope, probe, live) => {
1382
1812
  const { engine } = config;
1383
1813
  if (strata.exceedsDepth(body)) return { status: 400, body: { error: "invalid_request", message: strata.depthRefusal() } };
1384
- const parsed = QueryRequestSchema.safeParse(body);
1814
+ const parsed = QueryRequestSchema.safeParse(dropNullIntentAndFingerprint(body));
1385
1815
  if (!parsed.success) {
1386
1816
  return {
1387
1817
  status: 400,
@@ -1425,31 +1855,19 @@ var runQuery = async (config, body, scope, probe, live) => {
1425
1855
  }
1426
1856
  let writePolicy = config.mutations.policy;
1427
1857
  if (entry.reach !== void 0) {
1428
- if (config.policyForReach === void 0) {
1429
- return {
1430
- status: 500,
1431
- body: {
1432
- error: "execution_error",
1433
- message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entry.reach}" and this handler has no policyForReach.`
1434
- }
1435
- };
1436
- }
1437
- const narrowed = await config.policyForReach(entry.reach);
1438
- if (narrowed === void 0) {
1439
- return {
1440
- status: 403,
1441
- body: { error: "scope_denied", message: `Reach "${entry.reach}" is not available to this principal.` }
1442
- };
1443
- }
1444
- writePolicy = narrowed;
1858
+ const reached = await policyAtReach(config, parsed.data.fingerprint, entry.reach);
1859
+ if ("status" in reached) return reached;
1860
+ writePolicy = reached;
1445
1861
  }
1446
1862
  const writes = await executeWrites(config.mutations.client, entry.mutation, {
1447
1863
  context: parsed.data.context,
1448
1864
  scope,
1449
1865
  policy: writePolicy,
1450
- schema
1866
+ schema,
1867
+ ...config.mutations.checkMovedRows !== void 0 ? { checkMovedRows: config.mutations.checkMovedRows } : {},
1868
+ ...config.mutations.answerReadableRows === true ? { answerReadableRows: true } : {}
1451
1869
  });
1452
- const rows = writes.flatMap((w) => w.rows);
1870
+ const rows = writes.flatMap((w) => w.readable ?? w.rows);
1453
1871
  engine.invalidate(tablesChangedBy(writes, schema));
1454
1872
  if (config.mutations.onWrite !== void 0) {
1455
1873
  try {
@@ -1459,35 +1877,23 @@ var runQuery = async (config, body, scope, probe, live) => {
1459
1877
  }
1460
1878
  }
1461
1879
  const now = Date.now();
1462
- if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));
1880
+ if (isTouchDue(entry, now)) fireAndForget(touchEntry(engine.cache, parsed.data.fingerprint, entry, now));
1463
1881
  if (probe !== void 0) probe.rows = rows.length;
1464
1882
  return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };
1465
1883
  }
1466
1884
  }
1467
1885
  let readPolicy = config.scopePolicy;
1468
1886
  if (entryReach !== void 0) {
1469
- if (config.policyForReach === void 0) {
1470
- return {
1471
- status: 500,
1472
- body: {
1473
- error: "execution_error",
1474
- message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entryReach}" and this handler has no policyForReach.`
1475
- }
1476
- };
1477
- }
1478
- readPolicy = await config.policyForReach(entryReach);
1479
- if (readPolicy === void 0) {
1480
- return {
1481
- status: 403,
1482
- body: { error: "scope_denied", message: `Reach "${entryReach}" is not available to this principal.` }
1483
- };
1484
- }
1887
+ const reached = await policyAtReach(config, parsed.data.fingerprint ?? "", entryReach);
1888
+ if ("status" in reached) return reached;
1889
+ readPolicy = reached;
1485
1890
  }
1486
1891
  const response = await engine.execute(parsed.data, {
1487
1892
  scope,
1488
1893
  entities: config.entities,
1489
1894
  ...config.locked === true ? { locked: true } : {},
1490
1895
  ...readPolicy !== void 0 ? { scopePolicy: readPolicy } : {},
1896
+ ...entryReach !== void 0 ? { policyForReach: () => readPolicy } : {},
1491
1897
  ...live !== void 0 ? { signal: live.signal, onChange: live.onChange } : {}
1492
1898
  });
1493
1899
  if (probe !== void 0) {
@@ -1512,20 +1918,35 @@ var runQuery = async (config, body, scope, probe, live) => {
1512
1918
  }
1513
1919
  };
1514
1920
  }
1515
- console.error("[vex] unhandled error:", err);
1516
1921
  const errObj = err;
1517
1922
  const message = err instanceof Error ? err.message : typeof errObj?.message === "string" ? errObj.message : "Unknown error";
1518
1923
  const code = typeof errObj?.code === "string" ? errObj.code : "execution_error";
1924
+ const sql = typeof errObj?.query === "string" ? ` in: ${errObj.query}` : "";
1925
+ console.error(`[vex] unhandled error ${code}${sql}`, err instanceof Error && err.stack !== void 0 ? err.stack : message);
1519
1926
  return {
1520
1927
  status: 500,
1521
1928
  body: { error: code, message }
1522
1929
  };
1523
1930
  }
1524
1931
  };
1525
- var handleFingerprintPatch = async (config, fingerprint, patch) => {
1932
+ var managementRefusal = (config) => {
1526
1933
  if (config.locked === true) {
1527
1934
  return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1528
1935
  }
1936
+ if (config.manageFingerprints === false) {
1937
+ return { status: 403, body: { error: "locked", message: "Fingerprint management is off on this endpoint." } };
1938
+ }
1939
+ return void 0;
1940
+ };
1941
+ var warnOfOpenManagement = (config) => {
1942
+ if (config.locked === true || config.manageFingerprints === false) return;
1943
+ console.warn(
1944
+ "[vex] This endpoint is unlocked and manages fingerprints: whoever reaches it can unprotect, delete or regenerate any entry, a seeded one included. Set manageFingerprints: false unless everybody who reaches it may do that."
1945
+ );
1946
+ };
1947
+ var handleFingerprintPatch = async (config, fingerprint, patch) => {
1948
+ const refused = managementRefusal(config);
1949
+ if (refused !== void 0) return refused;
1529
1950
  const entry = await config.engine.cache.get(fingerprint);
1530
1951
  if (entry === void 0 || entry.kind !== "ok" && entry.kind !== "mutation") {
1531
1952
  return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
@@ -1537,9 +1958,8 @@ var handleFingerprintPatch = async (config, fingerprint, patch) => {
1537
1958
  return { status: 200, body: { fingerprint, protected: patch.protected } };
1538
1959
  };
1539
1960
  var handleFingerprintDelete = async (config, fingerprint) => {
1540
- if (config.locked === true) {
1541
- return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1542
- }
1961
+ const refused = managementRefusal(config);
1962
+ if (refused !== void 0) return refused;
1543
1963
  const entry = await config.engine.cache.get(fingerprint);
1544
1964
  if (entry === void 0) {
1545
1965
  return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
@@ -1558,20 +1978,33 @@ var fingerprintFromBody = (body) => {
1558
1978
  return typeof fp === "string" && fp.length > 0 ? fp : void 0;
1559
1979
  };
1560
1980
  var vex = (config) => {
1981
+ warnOfOpenManagement(config);
1561
1982
  const handlerConfig = {
1562
1983
  engine: config.engine,
1563
1984
  entities: config.entities,
1564
1985
  ...config.locked === true ? { locked: true } : {},
1986
+ ...config.manageFingerprints === false ? { manageFingerprints: false } : {},
1565
1987
  ...config.mutations !== void 0 ? { mutations: config.mutations } : {}
1566
1988
  };
1989
+ const requestConfig = async (req) => {
1990
+ const policy = config.getPolicy ? await config.getPolicy(req) : void 0;
1991
+ const { getPolicyForReach } = config;
1992
+ return {
1993
+ ...handlerConfig,
1994
+ ...policy !== void 0 ? { scopePolicy: policy } : {},
1995
+ ...getPolicyForReach !== void 0 ? { policyForReach: (reach) => getPolicyForReach(req, reach) } : {},
1996
+ ...config.onExecute !== void 0 ? { onExecute: config.onExecute } : {},
1997
+ ...config.mutations !== void 0 ? { mutations: { ...config.mutations, policy: policy ?? config.mutations.policy } } : {}
1998
+ };
1999
+ };
1567
2000
  return async (req, res) => {
1568
2001
  if (req.method === "GET") {
1569
- res.json(await handleDiscovery(handlerConfig));
2002
+ res.json(await handleDiscovery(await requestConfig(req)));
1570
2003
  return;
1571
2004
  }
1572
2005
  if (req.method === "POST") {
1573
2006
  const scope = config.getScope ? await config.getScope(req) : {};
1574
- const result = await handleQuery(handlerConfig, req.body, scope);
2007
+ const result = await handleQuery(await requestConfig(req), req.body, scope);
1575
2008
  res.status(result.status).json(result.body);
1576
2009
  return;
1577
2010
  }