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