@niscorp/vex 0.4.4 → 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 +90 -0
  2. package/DESIGN.md +72 -45
  3. package/DOCS.md +219 -21
  4. package/README.md +18 -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-CoJxInw-.d.ts → handler-DdfaWN_J.d.ts} +7 -1
  28. package/dist/{handler-CsFbanZA.d.cts → handler-kvZkxwaN.d.cts} +7 -1
  29. package/dist/index.cjs +667 -259
  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 +290 -248
  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-B2HEmyNq.d.cts → types-BxkRxTTx.d.cts} +38 -2
  38. package/dist/{types-DC68ZUuq.d.ts → types-DgUZNKii.d.ts} +38 -2
  39. package/package.json +8 -8
  40. package/dist/chunk-W5MYFJKT.js.map +0 -1
@@ -16,6 +16,12 @@ var QueryRequestSchema = z.object({
16
16
  shape: z.unknown().optional(),
17
17
  context: ContextSchema.default({})
18
18
  });
19
+ var dropNullIntentAndFingerprint = (body) => {
20
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return body;
21
+ const isNullAt = (key) => Reflect.get(body, key) === null;
22
+ if (!isNullAt("intent") && !isNullAt("fingerprint")) return body;
23
+ return Object.fromEntries(Object.entries(body).filter(([key, value]) => value !== null || key !== "intent" && key !== "fingerprint"));
24
+ };
19
25
 
20
26
  // src/engine/optional.ts
21
27
  var gateKeys = (key) => Array.isArray(key) ? key : [key];
@@ -109,6 +115,179 @@ var refuseOptional = (where) => {
109
115
  );
110
116
  };
111
117
 
118
+ // src/scope/discover.ts
119
+ var extractEntityFromPath = (path) => {
120
+ const parts = path.split(".");
121
+ return parts.length === 2 ? parts[0] : void 0;
122
+ };
123
+ var collectFromFieldOrValue = (fov, out) => {
124
+ if (isFieldPathShape(fov)) {
125
+ const entity = extractEntityFromPath(fov);
126
+ if (entity !== void 0) out.add(entity);
127
+ }
128
+ };
129
+ var collectFromFilter = (filter, out) => {
130
+ if ("exists" in filter) {
131
+ for (const entity of filter.exists.from) out.add(entity);
132
+ if (filter.exists.filter !== void 0) collectFromFilter(filter.exists.filter, out);
133
+ return;
134
+ }
135
+ if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
136
+ 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;
137
+ collectFromFieldOrValue(pair[0], out);
138
+ collectFromFieldOrValue(pair[1], out);
139
+ return;
140
+ }
141
+ if ("in" in filter || "notIn" in filter) {
142
+ const tuple = "in" in filter ? filter.in : filter.notIn;
143
+ const entity = extractEntityFromPath(tuple[0]);
144
+ if (entity !== void 0) out.add(entity);
145
+ const target = tuple[1];
146
+ if (Array.isArray(target)) {
147
+ for (const v of target) {
148
+ collectFromFieldOrValue(v, out);
149
+ }
150
+ }
151
+ return;
152
+ }
153
+ if ("like" in filter || "ilike" in filter) {
154
+ const tuple = "like" in filter ? filter.like : filter.ilike;
155
+ const entity = extractEntityFromPath(tuple[0]);
156
+ if (entity !== void 0) out.add(entity);
157
+ collectFromFieldOrValue(tuple[1], out);
158
+ return;
159
+ }
160
+ if ("isNull" in filter) {
161
+ const entity = extractEntityFromPath(filter.isNull);
162
+ if (entity !== void 0) out.add(entity);
163
+ return;
164
+ }
165
+ if ("isNotNull" in filter) {
166
+ const entity = extractEntityFromPath(filter.isNotNull);
167
+ if (entity !== void 0) out.add(entity);
168
+ return;
169
+ }
170
+ if ("and" in filter) {
171
+ for (const sub of filter.and) {
172
+ collectFromFilter(sub, out);
173
+ }
174
+ return;
175
+ }
176
+ if ("or" in filter) {
177
+ for (const sub of filter.or) {
178
+ collectFromFilter(sub, out);
179
+ }
180
+ return;
181
+ }
182
+ if ("not" in filter) {
183
+ collectFromFilter(filter.not, out);
184
+ return;
185
+ }
186
+ if ("semantic" in filter) {
187
+ const entity = extractEntityFromPath(filter.semantic.field);
188
+ if (entity !== void 0) out.add(entity);
189
+ return;
190
+ }
191
+ if ("fuzzy" in filter) {
192
+ const entity = extractEntityFromPath(filter.fuzzy.field);
193
+ if (entity !== void 0) out.add(entity);
194
+ return;
195
+ }
196
+ if ("optional" in filter) refuseOptional("scope discovery");
197
+ };
198
+ var collectFromCompute = (expr, out) => {
199
+ if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
200
+ const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
201
+ collectFromFieldOrValue(pair[0], out);
202
+ collectFromFieldOrValue(pair[1], out);
203
+ return;
204
+ }
205
+ if ("concat" in expr) {
206
+ for (const v of expr.concat) {
207
+ collectFromFieldOrValue(v, out);
208
+ }
209
+ return;
210
+ }
211
+ if ("coalesce" in expr) {
212
+ for (const v of expr.coalesce) {
213
+ collectFromFieldOrValue(v, out);
214
+ }
215
+ return;
216
+ }
217
+ if ("case" in expr) {
218
+ for (const when of expr.case.when) {
219
+ collectFromFilter(when.condition, out);
220
+ collectFromFieldOrValue(when.then, out);
221
+ }
222
+ collectFromFieldOrValue(expr.case.else, out);
223
+ return;
224
+ }
225
+ };
226
+ var collectFromAggregate = (expr, out) => {
227
+ 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;
228
+ if (typeof arg !== "string") {
229
+ collectFromCompute(arg, out);
230
+ return;
231
+ }
232
+ const entity = extractEntityFromPath(arg);
233
+ if (entity !== void 0) out.add(entity);
234
+ };
235
+ var collectFromQuery = (dsl, out) => {
236
+ const aliases = /* @__PURE__ */ new Set();
237
+ const local = /* @__PURE__ */ new Set();
238
+ for (const source of dsl.from) {
239
+ if (typeof source === "string") {
240
+ out.add(source);
241
+ } else {
242
+ aliases.add(source.as);
243
+ collectFromQuery(source.query, out);
244
+ }
245
+ }
246
+ for (const ref of dsl.fields ?? []) {
247
+ const entity = extractEntityFromPath(typeof ref === "string" ? ref : ref.field);
248
+ if (entity !== void 0) local.add(entity);
249
+ }
250
+ if (dsl.filter !== void 0) {
251
+ collectFromFilter(dsl.filter, local);
252
+ }
253
+ if (dsl.compute !== void 0) {
254
+ for (const key of Object.keys(dsl.compute)) {
255
+ const expr = dsl.compute[key];
256
+ if (expr !== void 0) {
257
+ collectFromCompute(expr, local);
258
+ }
259
+ }
260
+ }
261
+ if (dsl.aggregate !== void 0) {
262
+ for (const key of Object.keys(dsl.aggregate)) {
263
+ const expr = dsl.aggregate[key];
264
+ if (expr !== void 0) {
265
+ collectFromAggregate(expr, local);
266
+ }
267
+ }
268
+ }
269
+ if (dsl.groupBy !== void 0) {
270
+ for (const path of dsl.groupBy) {
271
+ const entity = extractEntityFromPath(path);
272
+ if (entity !== void 0) local.add(entity);
273
+ }
274
+ }
275
+ if (dsl.sort !== void 0) {
276
+ for (const entry of dsl.sort) {
277
+ const entity = extractEntityFromPath(entry.field);
278
+ if (entity !== void 0) local.add(entity);
279
+ }
280
+ }
281
+ for (const entity of local) {
282
+ if (!aliases.has(entity)) out.add(entity);
283
+ }
284
+ };
285
+ var discoverEntities = (dsl) => {
286
+ const entities = /* @__PURE__ */ new Set();
287
+ collectFromQuery(dsl, entities);
288
+ return entities;
289
+ };
290
+
112
291
  // src/scope/scope.types.ts
113
292
  var isSetMatch = (m) => "in" in m;
114
293
 
@@ -121,28 +300,24 @@ var VexScopeError = class extends VexError {
121
300
  this.entity = entity;
122
301
  }
123
302
  };
124
- var matchesFor = (entity, rule, def) => {
125
- if (rule === void 0) {
126
- if (def === "deny") throw new VexScopeError(entity, `Entity "${entity}" is not allowed by scope policy (default: deny)`);
127
- return [];
128
- }
303
+ var readRulesOf = (policy, table) => {
304
+ const rule = policy.entities[table];
305
+ if (rule === void 0) return policy.default === "deny" ? "unlisted" : [];
129
306
  if ("public" in rule) return [];
130
- if ("deny" in rule) throw new VexScopeError(entity, `Entity "${entity}" is denied by scope policy`);
131
- if (rule.read === void 0) {
132
- if (def === "deny") throw new VexScopeError(entity, `Reads of "${entity}" are not allowed by scope policy (default: deny)`);
133
- return [];
134
- }
307
+ if ("deny" in rule) return "denied";
308
+ if (rule.read === void 0) return policy.default === "deny" ? "ungranted" : [];
135
309
  return rule.read;
136
310
  };
137
- var canReadTable = (policy, table) => {
138
- const rule = policy.entities[table];
139
- if (rule === void 0) return policy.default === "allow";
140
- if ("public" in rule) return true;
141
- if ("deny" in rule) return false;
142
- return rule.read !== void 0 || policy.default === "allow";
311
+ var matchesFor = (policy, entity) => {
312
+ const rules = readRulesOf(policy, entity);
313
+ if (rules === "unlisted") throw new VexScopeError(entity, `Entity "${entity}" is not allowed by scope policy (default: deny)`);
314
+ if (rules === "denied") throw new VexScopeError(entity, `Entity "${entity}" is denied by scope policy`);
315
+ if (rules === "ungranted") throw new VexScopeError(entity, `Reads of "${entity}" are not allowed by scope policy (default: deny)`);
316
+ return rules;
143
317
  };
318
+ var canReadTable = (policy, table) => Array.isArray(readRulesOf(policy, table));
144
319
  var checkScope = (entities, policy) => {
145
- for (const entity of entities) matchesFor(entity, policy.entities[entity], policy.default);
320
+ for (const entity of entities) matchesFor(policy, entity);
146
321
  };
147
322
  var andMerge = (existing, additions) => {
148
323
  if (additions.length === 0) return existing;
@@ -155,7 +330,7 @@ var andMerge = (existing, additions) => {
155
330
  var predicateFor = (entityName, alias, match, fields) => {
156
331
  const field = fields.find((f) => f.name === match.match);
157
332
  if (field === void 0) throw new VexScopeError(entityName, `Scope rule for "${entityName}" names column "${match.match}", which the table does not have`);
158
- const path = `${entityName}.${match.match}`;
333
+ const path = `${alias}.${match.match}`;
159
334
  const original = isSetMatch(match) ? { in: [path, { $scope: match.in }] } : { eq: [path, { $scope: match.to }] };
160
335
  return { original, resolvedPaths: /* @__PURE__ */ new Map([[path, { alias, column: match.match, schema: field }]]) };
161
336
  };
@@ -165,10 +340,10 @@ var placeInto = (level, policy) => {
165
340
  const entity = source.entity;
166
341
  if (entity === void 0) continue;
167
342
  const join = level.joins.find((j) => j.toAlias === source.alias);
168
- for (const match of matchesFor(entity.name, policy.entities[entity.name], policy.default)) {
343
+ for (const match of matchesFor(policy, entity.name)) {
169
344
  const predicate = predicateFor(entity.name, source.alias, match, entity.fields);
170
345
  if (predicate === void 0) continue;
171
- level.aliasMap.set(`${entity.name}.${match.match}`, `${source.alias}.${match.match}`);
346
+ level.aliasMap.set(`${source.alias}.${match.match}`, `${source.alias}.${match.match}`);
172
347
  if (join !== void 0 && join.kind === "left") join.on = [...join.on ?? [], predicate];
173
348
  else whereAdditions.push(predicate);
174
349
  }
@@ -218,16 +393,17 @@ var resolveParams = async (slots, context, scope, embed) => {
218
393
  results.push(context[slot.key]);
219
394
  continue;
220
395
  }
221
- if (slot.kind === "scope") {
396
+ if (slot.kind === "scope" && slot.embed !== true) {
222
397
  results.push(scope[slot.key]);
223
398
  continue;
224
399
  }
400
+ const from = slot.kind === "scope" ? "scope" : "context";
225
401
  if (embed === void 0) {
226
402
  throw new Error(`Semantic parameter "${slot.key}" requires an embed function`);
227
403
  }
228
- const text = context[slot.key];
404
+ const text = (from === "scope" ? scope : context)[slot.key];
229
405
  if (typeof text !== "string") {
230
- throw new Error(`Semantic parameter "${slot.key}" requires a string value in context`);
406
+ throw new Error(`Semantic parameter "${slot.key}" requires a string value in ${from}`);
231
407
  }
232
408
  const vector = await embed(text, slot.dimensions);
233
409
  results.push(`[${vector.join(",")}]`);
@@ -504,6 +680,7 @@ var fireAndForget = (p, onError) => {
504
680
  };
505
681
  var TOUCH_EVERY_MS = 6e4;
506
682
  var isTouchDue = (entry, now) => entry.lastUsedAt === void 0 || now - entry.lastUsedAt >= TOUCH_EVERY_MS;
683
+ var touchEntry = (cache, key, entry, now) => cache.touch !== void 0 ? cache.touch(key, now) : cache.set(key, { ...entry, lastUsedAt: now });
507
684
  var isEntryFresh = (entry, currentFingerprint) => {
508
685
  const expired = entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
509
686
  const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
@@ -538,15 +715,125 @@ var quoteLiteral = (s) => {
538
715
  return s.includes("\\") ? `E'${doubled.replace(/\\/g, "\\\\")}'` : `'${doubled}'`;
539
716
  };
540
717
  var quoteIdent = (name) => `"${name.replace(/"/g, '""')}"`;
718
+ var RESERVED = /* @__PURE__ */ new Set([
719
+ "all",
720
+ "analyse",
721
+ "analyze",
722
+ "and",
723
+ "any",
724
+ "array",
725
+ "as",
726
+ "asc",
727
+ "asymmetric",
728
+ "authorization",
729
+ "binary",
730
+ "both",
731
+ "case",
732
+ "cast",
733
+ "check",
734
+ "collate",
735
+ "collation",
736
+ "column",
737
+ "concurrently",
738
+ "constraint",
739
+ "create",
740
+ "cross",
741
+ "current_catalog",
742
+ "current_date",
743
+ "current_role",
744
+ "current_schema",
745
+ "current_time",
746
+ "current_timestamp",
747
+ "current_user",
748
+ "default",
749
+ "deferrable",
750
+ "desc",
751
+ "distinct",
752
+ "do",
753
+ "else",
754
+ "end",
755
+ "except",
756
+ "false",
757
+ "fetch",
758
+ "for",
759
+ "foreign",
760
+ "freeze",
761
+ "from",
762
+ "full",
763
+ "grant",
764
+ "group",
765
+ "having",
766
+ "ilike",
767
+ "in",
768
+ "initially",
769
+ "inner",
770
+ "intersect",
771
+ "into",
772
+ "is",
773
+ "isnull",
774
+ "join",
775
+ "lateral",
776
+ "leading",
777
+ "left",
778
+ "like",
779
+ "limit",
780
+ "localtime",
781
+ "localtimestamp",
782
+ "natural",
783
+ "not",
784
+ "notnull",
785
+ "null",
786
+ "offset",
787
+ "on",
788
+ "only",
789
+ "or",
790
+ "order",
791
+ "outer",
792
+ "overlaps",
793
+ "placing",
794
+ "primary",
795
+ "references",
796
+ "returning",
797
+ "right",
798
+ "select",
799
+ "session_user",
800
+ "similar",
801
+ "some",
802
+ "symmetric",
803
+ "system_user",
804
+ "table",
805
+ "tablesample",
806
+ "then",
807
+ "to",
808
+ "trailing",
809
+ "true",
810
+ "union",
811
+ "unique",
812
+ "user",
813
+ "using",
814
+ "variadic",
815
+ "verbose",
816
+ "when",
817
+ "where",
818
+ "window",
819
+ "with"
820
+ ]);
821
+ var LOWER_IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
822
+ var sqlName = (name) => LOWER_IDENTIFIER.test(name) && !RESERVED.has(name) ? name : quoteIdent(name);
823
+ var columnSql = (qualifier, column) => `${sqlName(qualifier)}.${sqlName(column)}`;
824
+ var tableSql = (table, namespace) => namespace === void 0 ? sqlName(table) : `${quoteIdent(namespace)}.${sqlName(table)}`;
541
825
  var numberLiteral = (n) => {
542
826
  if (!Number.isFinite(n)) throw new VexError("invalid_dsl", `${String(n)} is not a number SQL can hold.`);
543
827
  return String(n);
544
828
  };
545
829
  var columnOf = (path, ctx) => {
546
830
  const mapped = ctx.aliasMap.get(path);
547
- if (mapped !== void 0) return mapped;
831
+ if (mapped !== void 0) {
832
+ const dot = mapped.indexOf(".");
833
+ return columnSql(mapped.slice(0, dot), mapped.slice(dot + 1));
834
+ }
548
835
  const res = ctx.resolvedPaths.get(path);
549
- if (res !== void 0) return `${res.alias}.${res.column}`;
836
+ if (res !== void 0) return columnSql(res.alias, res.column);
550
837
  throw new VexError("invalid_dsl", `"${path}" is not a column this query reads.`);
551
838
  };
552
839
  var isFieldPath = isFieldPathShape;
@@ -596,7 +883,7 @@ var compileJoinPairs = (join) => join.fromColumns.map((column, i) => {
596
883
  `The join from "${join.fromAlias}" to "${join.toAlias}" pairs "${column}" with no column.`
597
884
  );
598
885
  }
599
- return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;
886
+ return `${columnSql(join.fromAlias, column)} = ${columnSql(join.toAlias, to)}`;
600
887
  });
601
888
  var compileComparisonFilter = (op, pair, ctx) => {
602
889
  const left = compileFieldOrValue(pair[0], ctx);
@@ -615,7 +902,7 @@ var compileFilter = (filter, ctx) => {
615
902
  };
616
903
  const parts = ["SELECT 1"];
617
904
  const first = resolved.sources[0];
618
- if (first?.table !== void 0) parts.push(`FROM ${first.table} AS ${first.alias}`);
905
+ if (first?.table !== void 0) parts.push(`FROM ${tableSql(first.table, ctx.namespace)} AS ${sqlName(first.alias)}`);
619
906
  for (const join of resolved.joins) {
620
907
  const source = resolved.sources.find((s) => s.alias === join.toAlias);
621
908
  if (source?.table === void 0) continue;
@@ -624,7 +911,7 @@ var compileFilter = (filter, ctx) => {
624
911
  ...compileJoinPairs(join),
625
912
  ...(join.on ?? []).map((extra) => compileFilter(extra.original, inner))
626
913
  ];
627
- parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(" AND ")}`);
914
+ parts.push(`${keyword} ${tableSql(source.table, ctx.namespace)} AS ${sqlName(join.toAlias)} ON ${conditions.join(" AND ")}`);
628
915
  }
629
916
  if (resolved.filter !== void 0) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);
630
917
  return `EXISTS (${parts.join(" ")})`;
@@ -707,17 +994,13 @@ var compileFilter = (filter, ctx) => {
707
994
  const fieldPath = filter.semantic.field;
708
995
  const col = columnOf(fieldPath, ctx);
709
996
  const queryRef = filter.semantic.query;
710
- const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
711
997
  if ("$context" in queryRef) assertNotReserved(queryRef.$context);
712
998
  const res = ctx.resolvedPaths.get(fieldPath);
713
999
  const dimensions = res?.schema.vectorDimensions;
714
1000
  ctx.paramCounter.value += 1;
715
- ctx.paramSlots.push({
716
- key,
717
- kind: "semantic",
718
- type: "string",
719
- dimensions
720
- });
1001
+ ctx.paramSlots.push(
1002
+ "$context" in queryRef ? { key: queryRef.$context, kind: "semantic", type: "string", dimensions } : { key: queryRef.$scope, kind: "scope", type: "string", dimensions, embed: true }
1003
+ );
721
1004
  const paramRef = `$${ctx.paramCounter.value}`;
722
1005
  const minScore = numberLiteral(filter.semantic.minScore ?? 0);
723
1006
  return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;
@@ -1143,18 +1426,11 @@ var assertReturnedColumns = (refs, schema) => {
1143
1426
  }
1144
1427
  };
1145
1428
  var readMatchesFor = (table, policy) => {
1146
- const rule = policy.entities[table];
1147
- if (rule === void 0) {
1148
- if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
1149
- return [];
1150
- }
1151
- if ("public" in rule) return [];
1152
- if ("deny" in rule) throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
1153
- if (rule.read === void 0) {
1154
- if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
1155
- return [];
1156
- }
1157
- return rule.read;
1429
+ const rules = readRulesOf(policy, table);
1430
+ if (rules === "unlisted") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
1431
+ if (rules === "denied") throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
1432
+ if (rules === "ungranted") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
1433
+ return rules;
1158
1434
  };
1159
1435
  var boundaryOf = (table, r) => isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };
1160
1436
  var scopeLookups = (cols, policy) => {
@@ -1172,21 +1448,22 @@ var scopeLookups = (cols, policy) => {
1172
1448
  }
1173
1449
  return out;
1174
1450
  };
1175
- var writeGate = (table, op, policy) => {
1451
+ var writeGateOf = (table, op, policy) => {
1176
1452
  const rule = policy.entities[table];
1177
- if (rule === void 0) {
1178
- if (policy.default === "deny") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
1179
- return void 0;
1180
- }
1453
+ if (rule === void 0) return policy.default === "deny" ? "unlisted" : void 0;
1181
1454
  if ("public" in rule) return void 0;
1182
- if ("deny" in rule) throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
1455
+ if ("deny" in rule) return "denied";
1183
1456
  const specific = op === "insert" ? rule.insert : op === "update" ? rule.update : rule.delete;
1184
- if (rule.write === void 0 && specific === void 0) {
1185
- if (policy.default === "deny") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
1186
- return void 0;
1187
- }
1457
+ if (rule.write === void 0 && specific === void 0) return policy.default === "deny" ? "ungranted" : void 0;
1188
1458
  return { rule, rules: [...rule.write ?? [], ...specific ?? []] };
1189
1459
  };
1460
+ var writeGate = (table, op, policy) => {
1461
+ const gate = writeGateOf(table, op, policy);
1462
+ if (gate === "unlisted") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
1463
+ if (gate === "denied") throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
1464
+ if (gate === "ungranted") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
1465
+ return gate;
1466
+ };
1190
1467
  var scopeInsertParts = (table, rawValues, rawConflict, policy) => {
1191
1468
  let values = scopeLookups(rawValues, policy);
1192
1469
  let conflict = rawConflict === void 0 || rawConflict.set === void 0 ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };
@@ -1250,12 +1527,13 @@ var itemRow = (element, itemKeys) => {
1250
1527
  const fields = element !== null && typeof element === "object" && !Array.isArray(element) ? element : {};
1251
1528
  return Object.fromEntries(Object.entries(itemKeys).map(([column, key]) => [column, fields[key]]));
1252
1529
  };
1253
- var newCtx = () => ({
1530
+ var newCtx = (namespace) => ({
1254
1531
  resolvedPaths: /* @__PURE__ */ new Map(),
1255
1532
  aliasMap: /* @__PURE__ */ new Map(),
1256
1533
  paramSlots: [],
1257
1534
  paramCounter: { value: 0 },
1258
- returned: /* @__PURE__ */ new Map()
1535
+ returned: /* @__PURE__ */ new Map(),
1536
+ ...namespace !== void 0 ? { namespace } : {}
1259
1537
  });
1260
1538
  var indexFilterFields = (filter, aliasMap) => {
1261
1539
  for (const path of filterColumns(filter)) aliasMap.set(path, path);
@@ -1264,7 +1542,7 @@ var compileValue = (v, ctx) => {
1264
1542
  if (isLookup(v)) {
1265
1543
  indexFilterFields(v.$lookup.where, ctx.aliasMap);
1266
1544
  const where = compileFilter(v.$lookup.where, ctx);
1267
- return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
1545
+ return `(SELECT ${sqlName(v.$lookup.field)} FROM ${tableSql(v.$lookup.from, ctx.namespace)} WHERE ${where})`;
1268
1546
  }
1269
1547
  if (isReturned(v)) {
1270
1548
  ctx.paramCounter.value += 1;
@@ -1284,37 +1562,84 @@ var compileColumnValue = (table, column, v, ctx, schema) => {
1284
1562
  }
1285
1563
  return sql;
1286
1564
  };
1287
- var compileConflict = (m, ctx, schema) => {
1565
+ var scopeSlot = (r, ctx) => {
1566
+ ctx.paramCounter.value += 1;
1567
+ ctx.paramSlots.push(isSetMatch(r) ? { key: r.in, kind: "scope", type: "string[]" } : { key: r.to, kind: "scope", type: "string" });
1568
+ return isSetMatch(r) ? `= ANY($${ctx.paramCounter.value})` : `= $${ctx.paramCounter.value}`;
1569
+ };
1570
+ var keptChecks = (table, written, pinned, ctx, schema) => pinned.flatMap((rule) => {
1571
+ const value = written.get(rule.match);
1572
+ const type = findEntity(table, schema)?.fields.find((f) => f.name === rule.match)?.type;
1573
+ if (value === void 0 || type === void 0) return [];
1574
+ return [{ rule, sql: `(${value})::${type} ${scopeSlot(rule, ctx)}` }];
1575
+ });
1576
+ var compileConflict = (m, ctx, schema, pinned) => {
1288
1577
  const c = m.onConflict;
1289
1578
  if (c === void 0) return "";
1290
- if (c.set === void 0) return ` ON CONFLICT (${c.target.join(", ")}) DO NOTHING`;
1291
- const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);
1292
- let where = "";
1579
+ const target = c.target.map(sqlName).join(", ");
1580
+ if (c.set === void 0) return ` ON CONFLICT (${target}) DO NOTHING`;
1581
+ const written = new Map(Object.entries(c.set).map(([col, v]) => [col, compileColumnValue(m.table, col, v, ctx, schema)]));
1582
+ const sets = [...written].map(([col, sql]) => `${sqlName(col)} = ${sql}`);
1583
+ const conditions = [];
1293
1584
  if (c.where !== void 0) {
1294
1585
  indexFilterFields(c.where, ctx.aliasMap);
1295
- where = ` WHERE ${compileFilter(c.where, ctx)}`;
1586
+ conditions.push(compileFilter(c.where, ctx));
1296
1587
  }
1297
- return ` ON CONFLICT (${c.target.join(", ")}) DO UPDATE SET ${sets.join(", ")}${where}`;
1588
+ conditions.push(...keptChecks(m.table, written, pinned, ctx, schema).map((k) => k.sql));
1589
+ const where = conditions.length === 0 ? "" : ` WHERE ${conditions.join(" AND ")}`;
1590
+ return ` ON CONFLICT (${target}) DO UPDATE SET ${sets.join(", ")}${where}`;
1298
1591
  };
1299
- var compileMutation = (m, schema) => {
1300
- const ctx = newCtx();
1592
+ var compileMovedCheck = (m, schema, pinned) => {
1593
+ const ctx = newCtx(schema.namespace);
1594
+ const written = new Map(
1595
+ Object.entries(m.set).filter(([c]) => pinned.some((r) => r.match === c)).map(([c, v]) => [c, compileColumnValue(m.table, c, v, ctx, schema)])
1596
+ );
1597
+ const checks = keptChecks(m.table, written, pinned, ctx, schema);
1598
+ if (checks.length === 0) return void 0;
1599
+ indexFilterFields(m.where, ctx.aliasMap);
1600
+ const where = compileFilter(m.where, ctx);
1601
+ const each = checks.map((k, i) => `(${k.sql}) IS TRUE AS "${i}"`).join(", ");
1602
+ const all = checks.map((k) => k.sql).join(" AND ");
1603
+ return {
1604
+ sql: `SELECT ${each} FROM ${tableSql(m.table, schema.namespace)} WHERE ${where} AND (${all}) IS NOT TRUE LIMIT 1`,
1605
+ slots: ctx.paramSlots,
1606
+ returned: ctx.returned,
1607
+ rules: checks.map((k) => k.rule)
1608
+ };
1609
+ };
1610
+ var movedRefusal = (table, rule) => new VexScopeError(
1611
+ table,
1612
+ `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.`
1613
+ );
1614
+ var READABLE = "vex:readable";
1615
+ var returning = (readable, ctx) => {
1616
+ if (readable === "all") return " RETURNING *";
1617
+ if (readable === "none") return ` RETURNING *, FALSE AS "${READABLE}"`;
1618
+ return ` RETURNING *, (${readable.map((r) => `${sqlName(r.match)} ${scopeSlot(r, ctx)}`).join(" AND ")}) AS "${READABLE}"`;
1619
+ };
1620
+ var compileMutation = (m, schema, pinned, readable) => {
1621
+ const ctx = newCtx(schema.namespace);
1622
+ const finish = (head) => {
1623
+ const ownSlots = ctx.paramSlots.length;
1624
+ return { sql: `${head}${returning(readable, ctx)}`, slots: ctx.paramSlots, returned: ctx.returned, ownSlots, marked: readable !== "all" };
1625
+ };
1301
1626
  if (m.op === "insert") {
1302
1627
  const entries = Object.entries(m.values);
1303
- const cols = entries.map(([c]) => c);
1628
+ const cols = entries.map(([c]) => sqlName(c));
1304
1629
  const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
1305
- return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1630
+ return finish(`INSERT INTO ${tableSql(m.table, schema.namespace)} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema, pinned)}`);
1306
1631
  }
1307
1632
  if (m.op === "insertEach") {
1308
1633
  const types = new Map(findEntity(m.table, schema)?.fields.map((f) => [f.name, f.type]));
1309
1634
  const entries = Object.entries(m.values);
1310
- const cols = entries.map(([c]) => c);
1635
+ const cols = entries.map(([c]) => sqlName(c));
1311
1636
  const itemKeys = {};
1312
1637
  const itemColumns = [];
1313
1638
  const exprs = entries.map(([col, v]) => {
1314
1639
  if (isItemRef(v)) {
1315
1640
  itemKeys[col] = v.$item;
1316
- itemColumns.push(`${col} ${String(types.get(col))}`);
1317
- return `item.${col}`;
1641
+ itemColumns.push(`${sqlName(col)} ${String(types.get(col))}`);
1642
+ return `item.${sqlName(col)}`;
1318
1643
  }
1319
1644
  return isReturned(v) ? compileColumnValue(m.table, col, v, ctx, schema) : compileValue(v, ctx);
1320
1645
  });
@@ -1322,32 +1647,31 @@ var compileMutation = (m, schema) => {
1322
1647
  ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
1323
1648
  const items = `$${ctx.paramCounter.value}::jsonb`;
1324
1649
  const source = itemColumns.length === 0 ? `jsonb_array_elements(${items}) AS item` : `jsonb_to_recordset(${items}) AS item(${itemColumns.join(", ")})`;
1325
- return {
1326
- sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
1327
- slots: ctx.paramSlots,
1328
- returned: ctx.returned,
1329
- itemKeys
1330
- };
1650
+ return { ...finish(`INSERT INTO ${tableSql(m.table, schema.namespace)} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema, pinned)}`), itemKeys };
1331
1651
  }
1332
1652
  if (m.op === "update") {
1333
- const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
1653
+ const written = new Map(Object.entries(m.set).map(([c, v]) => [c, compileColumnValue(m.table, c, v, ctx, schema)]));
1654
+ const sets = [...written].map(([c, sql]) => `${sqlName(c)} = ${sql}`);
1334
1655
  indexFilterFields(m.where, ctx.aliasMap);
1335
- const where2 = compileFilter(m.where, ctx);
1336
- return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1656
+ const where2 = [compileFilter(m.where, ctx), ...keptChecks(m.table, written, pinned, ctx, schema).map((k) => k.sql)].join(" AND ");
1657
+ return finish(`UPDATE ${tableSql(m.table, schema.namespace)} SET ${sets.join(", ")} WHERE ${where2}`);
1337
1658
  }
1338
1659
  indexFilterFields(m.where, ctx.aliasMap);
1339
1660
  const where = compileFilter(m.where, ctx);
1340
- return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
1661
+ return finish(`DELETE FROM ${tableSql(m.table, schema.namespace)} WHERE ${where}`);
1341
1662
  };
1663
+ 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;
1342
1664
  var SUGAR = {
1343
- upsert: (m, context) => {
1344
- const keyed = context[m.key] !== void 0 && context[m.key] !== "";
1665
+ // Where the database does not make the key, inserting on a null one would break its NOT NULL.
1666
+ upsert: (m, context, schema) => {
1667
+ const value = context[m.key];
1668
+ const keyed = value !== void 0 && value !== "" && (value !== null || !keyMadeByDatabase(m, schema));
1345
1669
  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 } };
1346
1670
  }
1347
1671
  };
1348
- var desugarMutation = (m, context) => {
1672
+ var desugarMutation = (m, context, schema) => {
1349
1673
  const rewrite = SUGAR[m.op];
1350
- return rewrite === void 0 ? m : rewrite(m, context);
1674
+ return rewrite === void 0 ? m : rewrite(m, context, schema);
1351
1675
  };
1352
1676
  var mutationMisfits = (def, schema) => {
1353
1677
  const reasons = [];
@@ -1355,7 +1679,7 @@ var mutationMisfits = (def, schema) => {
1355
1679
  for (const [at, entry] of list.entries()) {
1356
1680
  const asked = [
1357
1681
  // keyed, an upsert is an update; unkeyed, an insert
1358
- ...(entry.op === "upsert" ? [{ [entry.key]: 0 }, {}] : [{}]).map((context) => () => assertWritableColumns(desugarMutation(entry, context), schema)),
1682
+ ...(entry.op === "upsert" ? [{ [entry.key]: 0 }, {}] : [{}]).map((context) => () => assertWritableColumns(desugarMutation(entry, context, schema), schema)),
1359
1683
  () => assertReturnedColumns(returnedIn(list, at).refs, schema)
1360
1684
  ];
1361
1685
  for (const ask of asked) {
@@ -1368,10 +1692,22 @@ var mutationMisfits = (def, schema) => {
1368
1692
  }
1369
1693
  return reasons;
1370
1694
  };
1695
+ var pinnedRules = (m, policy) => {
1696
+ const updates = m.op === "update" || m.op !== "delete" && m.onConflict?.set !== void 0;
1697
+ const gate = updates ? writeGateOf(m.table, "update", policy) : void 0;
1698
+ if (gate === void 0 || typeof gate === "string") return [];
1699
+ const stamped = new Set(gate.rules.flatMap((r) => "set" in r ? [r.set] : []));
1700
+ return gate.rules.flatMap((r) => "match" in r && !stamped.has(r.match) ? [r] : []);
1701
+ };
1702
+ var readableRules = (m, policy) => {
1703
+ if ((m.op === "insert" || m.op === "insertEach") && m.onConflict?.set === void 0) return "all";
1704
+ const rules = readRulesOf(policy, m.table);
1705
+ return typeof rules === "string" ? "none" : rules.length === 0 ? "all" : rules;
1706
+ };
1371
1707
  var executeWrites = async (client, def, mctx) => {
1372
1708
  const parsed = MutationDefinitionSchema.parse(def);
1373
1709
  const entries = Array.isArray(parsed) ? parsed : [parsed];
1374
- const cores = entries.map((entry) => desugarMutation(entry, mctx.context));
1710
+ const cores = entries.map((entry) => desugarMutation(entry, mctx.context, mctx.schema));
1375
1711
  const compiled = cores.map((core, at) => {
1376
1712
  const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
1377
1713
  if (missing.length > 0) {
@@ -1384,45 +1720,70 @@ var executeWrites = async (client, def, mctx) => {
1384
1720
  const m = scopeMutation(core, mctx.policy);
1385
1721
  assertWritableColumns(m, mctx.schema);
1386
1722
  assertReturnedColumns(returned.refs, mctx.schema);
1387
- const statement = compileMutation(m, mctx.schema);
1388
- requireScope({ paramSlots: statement.slots }, mctx.scope);
1389
- const reads = [...statement.returned].map(([slot, ref]) => {
1723
+ const pinned = mctx.checkMovedRows === false ? [] : pinnedRules(m, mctx.policy);
1724
+ const statement = compileMutation(m, mctx.schema, pinned, mctx.answerReadableRows === true ? readableRules(m, mctx.policy) : "all");
1725
+ requireScope({ paramSlots: statement.slots.slice(0, statement.ownSlots) }, mctx.scope);
1726
+ const readsOf = (of) => [...of.returned].map(([slot, ref]) => {
1390
1727
  const source = returned.refs.get(ref);
1391
1728
  if (source === void 0) throw new VexError("invalid_dsl", `"${ref}" names no earlier statement of the batch.`);
1392
1729
  return { slot, ref, source };
1393
1730
  });
1394
- return { ...statement, reads, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
1731
+ const moved = m.op === "update" ? compileMovedCheck(m, mctx.schema, pinned) : void 0;
1732
+ return {
1733
+ ...statement,
1734
+ reads: readsOf(statement),
1735
+ ...moved === void 0 ? {} : { moved: { ...moved, reads: readsOf(moved) } },
1736
+ table: m.table,
1737
+ op: m.op === "insertEach" ? "insert" : m.op
1738
+ };
1395
1739
  });
1740
+ const bindParams = async (c, results) => {
1741
+ const params = await resolveParams(c.slots, mctx.context, mctx.scope);
1742
+ for (const read of c.reads) {
1743
+ const rows = results[read.source.statement]?.rows ?? [];
1744
+ const row = rows[0];
1745
+ if (rows.length !== 1 || row === void 0) {
1746
+ throw new VexError(
1747
+ "execution_error",
1748
+ `"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
1749
+ { returned: read.ref, rows: rows.length }
1750
+ );
1751
+ }
1752
+ if (!(read.source.column in row)) {
1753
+ 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 });
1754
+ }
1755
+ params[read.slot] = row[read.source.column];
1756
+ }
1757
+ return params.map((value, i) => {
1758
+ if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
1759
+ if (c.slots[i]?.type !== "json") return value;
1760
+ if (!Array.isArray(value)) {
1761
+ throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
1762
+ }
1763
+ const { itemKeys } = c;
1764
+ return JSON.stringify(itemKeys === void 0 ? value : value.map((element) => itemRow(element, itemKeys)));
1765
+ });
1766
+ };
1396
1767
  const runAll = async (q) => {
1397
1768
  const results = [];
1398
1769
  for (const c of compiled) {
1399
- const params = await resolveParams(c.slots, mctx.context, mctx.scope);
1400
- for (const read of c.reads) {
1401
- const rows = results[read.source.statement]?.rows ?? [];
1402
- const row = rows[0];
1403
- if (rows.length !== 1 || row === void 0) {
1404
- throw new VexError(
1405
- "execution_error",
1406
- `"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
1407
- { returned: read.ref, rows: rows.length }
1408
- );
1409
- }
1410
- if (!(read.source.column in row)) {
1411
- 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 });
1412
- }
1413
- params[read.slot] = row[read.source.column];
1770
+ if (c.moved !== void 0) {
1771
+ const [row] = (await q.query(c.moved.sql, await bindParams(c.moved, results))).rows;
1772
+ const broken = row === void 0 ? void 0 : c.moved.rules.find((_, i) => row[String(i)] !== true);
1773
+ if (broken !== void 0) throw movedRefusal(c.table, broken);
1414
1774
  }
1415
- const bound = params.map((value, i) => {
1416
- if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
1417
- if (c.slots[i]?.type !== "json") return value;
1418
- if (!Array.isArray(value)) {
1419
- throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
1420
- }
1421
- const { itemKeys } = c;
1422
- return JSON.stringify(itemKeys === void 0 ? value : value.map((element) => itemRow(element, itemKeys)));
1423
- });
1424
- const res = await q.query(c.sql, bound);
1425
- results.push({ table: c.table, op: c.op, rows: res.rows });
1775
+ const res = await q.query(c.sql, await bindParams(c, results));
1776
+ if (!c.marked) {
1777
+ results.push({ table: c.table, op: c.op, rows: res.rows });
1778
+ continue;
1779
+ }
1780
+ const rows = [];
1781
+ const readable = [];
1782
+ for (const { [READABLE]: seen, ...row } of res.rows) {
1783
+ rows.push(row);
1784
+ if (seen === true) readable.push(row);
1785
+ }
1786
+ results.push({ table: c.table, op: c.op, rows, readable });
1426
1787
  }
1427
1788
  return results;
1428
1789
  };
@@ -1456,40 +1817,39 @@ var filterSchema = (schema, entities) => {
1456
1817
  if (entities === void 0 || entities.length === 0) return schema.entities;
1457
1818
  return schema.entities.filter((e) => entities.includes(e.name));
1458
1819
  };
1459
- var canWriteTable = (policy, table, op) => {
1460
- const rule = policy.entities[table];
1461
- if (rule === void 0) return policy.default === "allow";
1462
- if ("public" in rule) return true;
1463
- if ("deny" in rule) return false;
1464
- if (rule.write !== void 0 || policy.default === "allow") return true;
1465
- if (op === "insert" || op === "insertEach") return rule.insert !== void 0;
1466
- if (op === "update") return rule.update !== void 0;
1467
- if (op === "delete") return rule.delete !== void 0;
1468
- if (op === "upsert") return rule.insert !== void 0 || rule.update !== void 0;
1469
- return false;
1820
+ var WRITES_OF = {
1821
+ insert: ["insert"],
1822
+ insertEach: ["insert"],
1823
+ update: ["update"],
1824
+ delete: ["delete"],
1825
+ upsert: ["insert", "update"]
1470
1826
  };
1471
- var collectTables = (dsl) => {
1472
- const out = [];
1473
- const walk = (q) => {
1474
- for (const src of q.from) {
1475
- if (typeof src === "string") out.push(src);
1476
- else walk(src.query);
1477
- }
1478
- };
1479
- walk(dsl);
1480
- return out;
1827
+ var canWriteTable = (policy, table, op) => WRITES_OF[op].some((write) => typeof writeGateOf(table, write, policy) !== "string");
1828
+ var tablesRead = (dsl) => {
1829
+ try {
1830
+ return [...discoverEntities(pruneOptional(dsl, "all"))];
1831
+ } catch (err) {
1832
+ if (isVexError(err)) return void 0;
1833
+ throw err;
1834
+ }
1481
1835
  };
1482
- var entryVisible = (policy, entry) => {
1483
- if (entry.kind === "ok") return collectTables(entry.dsl).every((t) => canReadTable(policy, t));
1484
- if (entry.kind === "mutation") return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));
1836
+ var entryVisible = (policies, entry) => {
1837
+ if (entry.kind === "ok") {
1838
+ const { read } = policies;
1839
+ return read === void 0 || (tablesRead(entry.dsl)?.every((t) => canReadTable(read, t)) ?? false);
1840
+ }
1841
+ if (entry.kind === "mutation") {
1842
+ const { write } = policies;
1843
+ return write === void 0 || mutationEffect(entry.mutation).every((e) => canWriteTable(write, e.table, e.op));
1844
+ }
1485
1845
  return false;
1486
1846
  };
1487
- var listFingerprints = async (engine, policy) => {
1847
+ var listFingerprints = async (engine, policies) => {
1488
1848
  if (engine.cache.entries === void 0) return [];
1489
1849
  const schema = engine.getSchema();
1490
1850
  const current = schema !== void 0 ? computeSchemaFingerprint(schema) : void 0;
1491
1851
  const rows = await engine.cache.entries();
1492
- 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 }) => ({
1852
+ return rows.filter(({ key, entry }) => (entry.kind === "ok" || entry.kind === "mutation") && !key.startsWith("neg:")).filter(({ entry }) => entryVisible(policies, entry)).map(({ key, entry }) => ({
1493
1853
  fingerprint: key,
1494
1854
  kind: entry.kind === "mutation" ? "mutation" : "query",
1495
1855
  protected: entry.protected === true,
@@ -1507,11 +1867,12 @@ var listFingerprints = async (engine, policy) => {
1507
1867
  }));
1508
1868
  };
1509
1869
  var handleDiscovery = async (config) => {
1510
- const { engine, entities: entityFilter, scopePolicy } = config;
1870
+ const { engine, entities: entityFilter } = config;
1871
+ const scopePolicy = config.scopePolicy ?? engine.scopePolicy;
1511
1872
  const filtered = filterSchema(engine.getSchema(), entityFilter).filter(
1512
1873
  (e) => scopePolicy === void 0 || canReadTable(scopePolicy, e.name)
1513
1874
  );
1514
- const fingerprints = await listFingerprints(engine, scopePolicy);
1875
+ const fingerprints = await listFingerprints(engine, { read: scopePolicy, write: config.mutations?.policy ?? scopePolicy });
1515
1876
  const protectedCount = fingerprints.filter((f) => f.protected).length;
1516
1877
  return {
1517
1878
  protection: protectedCount === 0 ? "none" : protectedCount === fingerprints.length ? "all" : "some",
@@ -1589,10 +1950,29 @@ var handleQuery = async (config, body, scope, live) => {
1589
1950
  return result;
1590
1951
  };
1591
1952
  var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1953
+ var policyAtReach = async (config, fingerprint, reach) => {
1954
+ if (config.policyForReach === void 0) {
1955
+ return {
1956
+ status: 500,
1957
+ body: {
1958
+ error: "execution_error",
1959
+ message: `Entry "${fingerprint}" requires reach "${reach}" and this handler has no policyForReach.`
1960
+ }
1961
+ };
1962
+ }
1963
+ const narrowed = await config.policyForReach(reach);
1964
+ if (narrowed === void 0) {
1965
+ return {
1966
+ status: 403,
1967
+ body: { error: "scope_denied", message: `Reach "${reach}" is not available to this principal.` }
1968
+ };
1969
+ }
1970
+ return narrowed;
1971
+ };
1592
1972
  var runQuery = async (config, body, scope, probe, live) => {
1593
1973
  const { engine } = config;
1594
1974
  if (exceedsDepth(body)) return { status: 400, body: { error: "invalid_request", message: depthRefusal() } };
1595
- const parsed = QueryRequestSchema.safeParse(body);
1975
+ const parsed = QueryRequestSchema.safeParse(dropNullIntentAndFingerprint(body));
1596
1976
  if (!parsed.success) {
1597
1977
  return {
1598
1978
  status: 400,
@@ -1636,31 +2016,19 @@ var runQuery = async (config, body, scope, probe, live) => {
1636
2016
  }
1637
2017
  let writePolicy = config.mutations.policy;
1638
2018
  if (entry.reach !== void 0) {
1639
- if (config.policyForReach === void 0) {
1640
- return {
1641
- status: 500,
1642
- body: {
1643
- error: "execution_error",
1644
- message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entry.reach}" and this handler has no policyForReach.`
1645
- }
1646
- };
1647
- }
1648
- const narrowed = await config.policyForReach(entry.reach);
1649
- if (narrowed === void 0) {
1650
- return {
1651
- status: 403,
1652
- body: { error: "scope_denied", message: `Reach "${entry.reach}" is not available to this principal.` }
1653
- };
1654
- }
1655
- writePolicy = narrowed;
2019
+ const reached = await policyAtReach(config, parsed.data.fingerprint, entry.reach);
2020
+ if ("status" in reached) return reached;
2021
+ writePolicy = reached;
1656
2022
  }
1657
2023
  const writes = await executeWrites(config.mutations.client, entry.mutation, {
1658
2024
  context: parsed.data.context,
1659
2025
  scope,
1660
2026
  policy: writePolicy,
1661
- schema
2027
+ schema,
2028
+ ...config.mutations.checkMovedRows !== void 0 ? { checkMovedRows: config.mutations.checkMovedRows } : {},
2029
+ ...config.mutations.answerReadableRows === true ? { answerReadableRows: true } : {}
1662
2030
  });
1663
- const rows = writes.flatMap((w) => w.rows);
2031
+ const rows = writes.flatMap((w) => w.readable ?? w.rows);
1664
2032
  engine.invalidate(tablesChangedBy(writes, schema));
1665
2033
  if (config.mutations.onWrite !== void 0) {
1666
2034
  try {
@@ -1670,35 +2038,23 @@ var runQuery = async (config, body, scope, probe, live) => {
1670
2038
  }
1671
2039
  }
1672
2040
  const now = Date.now();
1673
- if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));
2041
+ if (isTouchDue(entry, now)) fireAndForget(touchEntry(engine.cache, parsed.data.fingerprint, entry, now));
1674
2042
  if (probe !== void 0) probe.rows = rows.length;
1675
2043
  return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };
1676
2044
  }
1677
2045
  }
1678
2046
  let readPolicy = config.scopePolicy;
1679
2047
  if (entryReach !== void 0) {
1680
- if (config.policyForReach === void 0) {
1681
- return {
1682
- status: 500,
1683
- body: {
1684
- error: "execution_error",
1685
- message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entryReach}" and this handler has no policyForReach.`
1686
- }
1687
- };
1688
- }
1689
- readPolicy = await config.policyForReach(entryReach);
1690
- if (readPolicy === void 0) {
1691
- return {
1692
- status: 403,
1693
- body: { error: "scope_denied", message: `Reach "${entryReach}" is not available to this principal.` }
1694
- };
1695
- }
2048
+ const reached = await policyAtReach(config, parsed.data.fingerprint ?? "", entryReach);
2049
+ if ("status" in reached) return reached;
2050
+ readPolicy = reached;
1696
2051
  }
1697
2052
  const response = await engine.execute(parsed.data, {
1698
2053
  scope,
1699
2054
  entities: config.entities,
1700
2055
  ...config.locked === true ? { locked: true } : {},
1701
2056
  ...readPolicy !== void 0 ? { scopePolicy: readPolicy } : {},
2057
+ ...entryReach !== void 0 ? { policyForReach: () => readPolicy } : {},
1702
2058
  ...live !== void 0 ? { signal: live.signal, onChange: live.onChange } : {}
1703
2059
  });
1704
2060
  if (probe !== void 0) {
@@ -1723,20 +2079,35 @@ var runQuery = async (config, body, scope, probe, live) => {
1723
2079
  }
1724
2080
  };
1725
2081
  }
1726
- console.error("[vex] unhandled error:", err);
1727
2082
  const errObj = err;
1728
2083
  const message = err instanceof Error ? err.message : typeof errObj?.message === "string" ? errObj.message : "Unknown error";
1729
2084
  const code = typeof errObj?.code === "string" ? errObj.code : "execution_error";
2085
+ const sql = typeof errObj?.query === "string" ? ` in: ${errObj.query}` : "";
2086
+ console.error(`[vex] unhandled error ${code}${sql}`, err instanceof Error && err.stack !== void 0 ? err.stack : message);
1730
2087
  return {
1731
2088
  status: 500,
1732
2089
  body: { error: code, message }
1733
2090
  };
1734
2091
  }
1735
2092
  };
1736
- var handleFingerprintPatch = async (config, fingerprint, patch) => {
2093
+ var managementRefusal = (config) => {
1737
2094
  if (config.locked === true) {
1738
2095
  return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1739
2096
  }
2097
+ if (config.manageFingerprints === false) {
2098
+ return { status: 403, body: { error: "locked", message: "Fingerprint management is off on this endpoint." } };
2099
+ }
2100
+ return void 0;
2101
+ };
2102
+ var warnOfOpenManagement = (config) => {
2103
+ if (config.locked === true || config.manageFingerprints === false) return;
2104
+ console.warn(
2105
+ "[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."
2106
+ );
2107
+ };
2108
+ var handleFingerprintPatch = async (config, fingerprint, patch) => {
2109
+ const refused = managementRefusal(config);
2110
+ if (refused !== void 0) return refused;
1740
2111
  const entry = await config.engine.cache.get(fingerprint);
1741
2112
  if (entry === void 0 || entry.kind !== "ok" && entry.kind !== "mutation") {
1742
2113
  return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
@@ -1748,9 +2119,8 @@ var handleFingerprintPatch = async (config, fingerprint, patch) => {
1748
2119
  return { status: 200, body: { fingerprint, protected: patch.protected } };
1749
2120
  };
1750
2121
  var handleFingerprintDelete = async (config, fingerprint) => {
1751
- if (config.locked === true) {
1752
- return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1753
- }
2122
+ const refused = managementRefusal(config);
2123
+ if (refused !== void 0) return refused;
1754
2124
  const entry = await config.engine.cache.get(fingerprint);
1755
2125
  if (entry === void 0) {
1756
2126
  return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
@@ -1762,6 +2132,6 @@ var handleFingerprintDelete = async (config, fingerprint) => {
1762
2132
  return { status: 200, body: { fingerprint, deleted: true } };
1763
2133
  };
1764
2134
 
1765
- export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, canReadTable, canonicalHash, canonicalText, checkScope, collectMutationContext, collectQueryContext, compileAggregate, compileCompute, compileFieldOrValue, compileFilter, compileJoinPairs, computePolicyKey, computeRequestHash, computeSchemaFingerprint, executeMutation, executeQuery, executeWrites, findMissingContext, fireAndForget, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, hashText, isEntryFresh, isSetMatch, isTouchDue, lintMutation, mintFingerprint, mutationEffect, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, presenceSignature, pruneOptional, quoteIdent, refuseOptional, requireScope, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy };
1766
- //# sourceMappingURL=chunk-W5MYFJKT.js.map
1767
- //# sourceMappingURL=chunk-W5MYFJKT.js.map
2135
+ export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, canReadTable, canonicalHash, canonicalText, checkScope, collectMutationContext, collectQueryContext, columnSql, compileAggregate, compileCompute, compileFieldOrValue, compileFilter, compileJoinPairs, computePolicyKey, computeRequestHash, computeSchemaFingerprint, discoverEntities, dropNullIntentAndFingerprint, executeMutation, executeQuery, executeWrites, findMissingContext, fireAndForget, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, hashText, isEntryFresh, isSetMatch, isTouchDue, lintMutation, mintFingerprint, mutationEffect, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, presenceSignature, pruneOptional, quoteIdent, refuseOptional, requireScope, requiredContextKeys, resolveParams, scopeResolved, sqlName, sweepCache, tableSql, tablesChangedBy, touchEntry, warnOfOpenManagement };
2136
+ //# sourceMappingURL=chunk-F7OXXJIH.js.map
2137
+ //# sourceMappingURL=chunk-F7OXXJIH.js.map