@niscorp/vex 0.1.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/DESIGN.md +881 -0
- package/DOCS.md +1295 -0
- package/LICENSE +202 -0
- package/README.md +97 -0
- package/dist/adapters/express/index.cjs +1406 -0
- package/dist/adapters/express/index.cjs.map +1 -0
- package/dist/adapters/express/index.d.cts +25 -0
- package/dist/adapters/express/index.d.ts +25 -0
- package/dist/adapters/express/index.js +60 -0
- package/dist/adapters/express/index.js.map +1 -0
- package/dist/adapters/hono/index.cjs +1426 -0
- package/dist/adapters/hono/index.cjs.map +1 -0
- package/dist/adapters/hono/index.d.cts +25 -0
- package/dist/adapters/hono/index.d.ts +25 -0
- package/dist/adapters/hono/index.js +78 -0
- package/dist/adapters/hono/index.js.map +1 -0
- package/dist/adapters/pglite/index.cjs +17 -0
- package/dist/adapters/pglite/index.cjs.map +1 -0
- package/dist/adapters/pglite/index.d.cts +21 -0
- package/dist/adapters/pglite/index.d.ts +21 -0
- package/dist/adapters/pglite/index.js +14 -0
- package/dist/adapters/pglite/index.js.map +1 -0
- package/dist/agent/index.cjs +478 -0
- package/dist/agent/index.cjs.map +1 -0
- package/dist/agent/index.d.cts +29 -0
- package/dist/agent/index.d.ts +29 -0
- package/dist/agent/index.js +313 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/chunk-FPKW4TRX.js +1528 -0
- package/dist/chunk-FPKW4TRX.js.map +1 -0
- package/dist/chunk-HF25Q53I.js +165 -0
- package/dist/chunk-HF25Q53I.js.map +1 -0
- package/dist/handler-Cql8SJ3F.d.cts +133 -0
- package/dist/handler-mICf9ins.d.ts +133 -0
- package/dist/index.cjs +4078 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +199 -0
- package/dist/index.d.ts +199 -0
- package/dist/index.js +2340 -0
- package/dist/index.js.map +1 -0
- package/dist/introspect-D3OaXHBc.d.cts +16 -0
- package/dist/introspect-D3OaXHBc.d.ts +16 -0
- package/dist/types-BRvMB6IM.d.cts +1491 -0
- package/dist/types-BRvMB6IM.d.ts +1491 -0
- package/package.json +125 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4078 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
var crypto = require('crypto');
|
|
5
|
+
var strata = require('@niscorp/strata');
|
|
6
|
+
var prism = require('@niscorp/prism');
|
|
7
|
+
var postgres = require('@niscorp/strata/postgres');
|
|
8
|
+
|
|
9
|
+
// src/engine/runtime.ts
|
|
10
|
+
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set(["sortBy", "sortDir"]);
|
|
11
|
+
var ContextSchema = zod.z.object({
|
|
12
|
+
sortBy: zod.z.string().optional(),
|
|
13
|
+
sortDir: zod.z.enum(["asc", "desc"]).optional()
|
|
14
|
+
}).catchall(zod.z.unknown()).describe(
|
|
15
|
+
'Caller runtime values. Keys referenced from the DSL via { $context: "key" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` ("asc"|"desc") are reserved keys that drive ORDER BY directly and are never bound as parameters.'
|
|
16
|
+
);
|
|
17
|
+
var QueryRequestSchema = zod.z.object({
|
|
18
|
+
// The ONE cache identity. Server-minted (`fp_…`) when absent — returned in
|
|
19
|
+
// meta.cache.fingerprint, an immutable pin. Caller-chosen strings are
|
|
20
|
+
// mutable named slots: the name is yours, its content follows your request.
|
|
21
|
+
// Alone → replay-or-error. With intent/shape → hit when the stored request
|
|
22
|
+
// matches, regenerate-and-replace when it differs (409 when protected).
|
|
23
|
+
fingerprint: zod.z.string().min(1).optional(),
|
|
24
|
+
intent: zod.z.string().optional(),
|
|
25
|
+
shape: zod.z.unknown().optional(),
|
|
26
|
+
context: ContextSchema.default({})
|
|
27
|
+
});
|
|
28
|
+
var ContextRefSchema = zod.z.object({
|
|
29
|
+
$context: zod.z.string().describe("Key to look up in the request context object")
|
|
30
|
+
}).strict().describe("Reference to a caller-provided context value");
|
|
31
|
+
var ScopeRefSchema = zod.z.object({
|
|
32
|
+
$scope: zod.z.string().describe("Key to look up in the server-side scope values")
|
|
33
|
+
}).strict().describe("Reference to a server-injected scope value (access control)");
|
|
34
|
+
var FieldOrValueSchema = zod.z.union([
|
|
35
|
+
zod.z.string().describe("A field path (entity.field format) or a literal string"),
|
|
36
|
+
zod.z.number().describe("A literal number"),
|
|
37
|
+
zod.z.boolean().describe("A literal boolean"),
|
|
38
|
+
zod.z.null().describe("A literal null"),
|
|
39
|
+
ContextRefSchema,
|
|
40
|
+
ScopeRefSchema
|
|
41
|
+
]).describe("A field path, literal value, or dynamic reference");
|
|
42
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
43
|
+
var FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/;
|
|
44
|
+
var isIdentifier = (value) => IDENTIFIER.test(value);
|
|
45
|
+
var isFieldPathShape = (value) => typeof value === "string" && FIELD_PATH.test(value);
|
|
46
|
+
var IdentifierSchema = zod.z.string().regex(IDENTIFIER, "A name is letters, digits and underscores, not starting with a digit");
|
|
47
|
+
var FieldPathSchema = zod.z.string().regex(FIELD_PATH, "A field path is entity.field \u2014 each part letters, digits and underscores, not starting with a digit");
|
|
48
|
+
|
|
49
|
+
// src/schemas/filter.schema.ts
|
|
50
|
+
var comparisonPair = zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]).describe("[left, right] \u2014 both can be field paths, literals, or references");
|
|
51
|
+
var fieldString = FieldPathSchema.describe("Field path in entity.field format");
|
|
52
|
+
var collectionTarget = zod.z.union([
|
|
53
|
+
zod.z.array(FieldOrValueSchema).min(1).describe("Array of literal values or references"),
|
|
54
|
+
ContextRefSchema,
|
|
55
|
+
ScopeRefSchema
|
|
56
|
+
]).describe("A set of values or a reference that resolves to an array");
|
|
57
|
+
var ExistsSchema = zod.z.lazy(
|
|
58
|
+
() => zod.z.object({
|
|
59
|
+
from: zod.z.array(zod.z.string()).min(1).describe("Entities the subquery reads. Joined by foreign key like any other from."),
|
|
60
|
+
filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: ["<inner>.<fk>", "<outer>.id"] }.')
|
|
61
|
+
}).strict()
|
|
62
|
+
);
|
|
63
|
+
var FilterSchema = zod.z.lazy(
|
|
64
|
+
() => zod.z.union([
|
|
65
|
+
zod.z.object({ exists: ExistsSchema }).strict().describe("EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS."),
|
|
66
|
+
zod.z.object({ eq: comparisonPair }).strict().describe("Equals: tests equality between two values"),
|
|
67
|
+
zod.z.object({ neq: comparisonPair }).strict().describe("Not equals"),
|
|
68
|
+
zod.z.object({ gt: comparisonPair }).strict().describe("Greater than"),
|
|
69
|
+
zod.z.object({ gte: comparisonPair }).strict().describe("Greater than or equal"),
|
|
70
|
+
zod.z.object({ lt: comparisonPair }).strict().describe("Less than"),
|
|
71
|
+
zod.z.object({ lte: comparisonPair }).strict().describe("Less than or equal"),
|
|
72
|
+
zod.z.object({ in: zod.z.tuple([fieldString, collectionTarget]) }).strict().describe("Field value is in a set"),
|
|
73
|
+
zod.z.object({ notIn: zod.z.tuple([fieldString, collectionTarget]) }).strict().describe("Field value is not in a set"),
|
|
74
|
+
zod.z.object({ like: zod.z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe("Case-sensitive LIKE pattern match (use % as wildcard)"),
|
|
75
|
+
zod.z.object({ ilike: zod.z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe("Case-insensitive ILIKE pattern match (use % as wildcard)"),
|
|
76
|
+
zod.z.object({ isNull: fieldString }).strict().describe("Field value is NULL"),
|
|
77
|
+
zod.z.object({ isNotNull: fieldString }).strict().describe("Field value is NOT NULL"),
|
|
78
|
+
zod.z.object({ and: zod.z.array(FilterSchema).min(2) }).strict().describe("Logical AND: all conditions must be true"),
|
|
79
|
+
zod.z.object({ or: zod.z.array(FilterSchema).min(2) }).strict().describe("Logical OR: at least one condition must be true"),
|
|
80
|
+
zod.z.object({ not: FilterSchema }).strict().describe("Logical NOT: negates the condition"),
|
|
81
|
+
zod.z.object({
|
|
82
|
+
semantic: zod.z.object({
|
|
83
|
+
field: FieldPathSchema.describe("Vector column field path (entity.field)"),
|
|
84
|
+
query: zod.z.union([ContextRefSchema, ScopeRefSchema]).describe("Text to embed and compare"),
|
|
85
|
+
minScore: zod.z.number().min(0).max(1).optional().describe("Minimum cosine similarity (0\u20131)")
|
|
86
|
+
}).strict()
|
|
87
|
+
}).strict().describe("Semantic vector similarity search"),
|
|
88
|
+
zod.z.object({
|
|
89
|
+
fuzzy: zod.z.object({
|
|
90
|
+
field: FieldPathSchema.describe("String field path"),
|
|
91
|
+
query: zod.z.union([ContextRefSchema, ScopeRefSchema]).describe("Text to fuzzy-match"),
|
|
92
|
+
maxDistance: zod.z.number().int().nonnegative().optional().describe("Maximum Levenshtein edit distance")
|
|
93
|
+
}).strict()
|
|
94
|
+
}).strict().describe("Fuzzy string match"),
|
|
95
|
+
zod.z.object({
|
|
96
|
+
optional: zod.z.object({
|
|
97
|
+
key: zod.z.union([zod.z.string().min(1), zod.z.array(zod.z.string().min(1)).min(1)]).describe("The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both \u2014 gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply."),
|
|
98
|
+
// BARE, never `.describe()`d. That call CLONES the schema, and zod
|
|
99
|
+
// detects a recursive reference by instance identity — a clone is a
|
|
100
|
+
// different instance, so `to-json-schema` stops seeing the cycle and
|
|
101
|
+
// expands the filter union into itself until the stack goes. Every
|
|
102
|
+
// other recursive slot here (`not`, `and`, `or`) uses it bare for the
|
|
103
|
+
// same reason; the description belongs on the wrapper below.
|
|
104
|
+
then: FilterSchema
|
|
105
|
+
}).strict()
|
|
106
|
+
}).strict().describe(
|
|
107
|
+
'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles \u2014 it does not match everything, it is not there. Absent means missing, undefined or null; "" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).'
|
|
108
|
+
)
|
|
109
|
+
])
|
|
110
|
+
);
|
|
111
|
+
var CaseWhenSchema = zod.z.object({
|
|
112
|
+
condition: FilterSchema,
|
|
113
|
+
then: FieldOrValueSchema.describe("Value when condition is true")
|
|
114
|
+
}).strict();
|
|
115
|
+
var ComputeExpressionSchema = zod.z.union([
|
|
116
|
+
zod.z.object({ add: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Addition: a + b"),
|
|
117
|
+
zod.z.object({ subtract: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Subtraction: a - b"),
|
|
118
|
+
zod.z.object({ multiply: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Multiplication: a * b"),
|
|
119
|
+
zod.z.object({ divide: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Division: a / b"),
|
|
120
|
+
zod.z.object({ concat: zod.z.array(FieldOrValueSchema).min(2) }).strict().describe("String concatenation"),
|
|
121
|
+
zod.z.object({ coalesce: zod.z.array(FieldOrValueSchema).min(2) }).strict().describe("Returns first non-null value"),
|
|
122
|
+
zod.z.object({
|
|
123
|
+
case: zod.z.object({
|
|
124
|
+
when: zod.z.array(CaseWhenSchema).min(1).describe("Condition/result pairs evaluated in order"),
|
|
125
|
+
else: FieldOrValueSchema.describe("Default value when no condition matches")
|
|
126
|
+
}).strict()
|
|
127
|
+
}).strict().describe("CASE WHEN conditional expression")
|
|
128
|
+
]).describe("Computed expression: arithmetic, string, or conditional");
|
|
129
|
+
var fieldPath = FieldPathSchema.describe("Field path in entity.field format");
|
|
130
|
+
var fieldOrExpr = zod.z.union([fieldPath, ComputeExpressionSchema]).describe("A field path or a compute expression");
|
|
131
|
+
var AggregateExpressionSchema = zod.z.union([
|
|
132
|
+
zod.z.object({ count: zod.z.union([FieldPathSchema, zod.z.literal("*")]).describe('Field path or "*" for COUNT(*)') }).strict().describe("COUNT"),
|
|
133
|
+
zod.z.object({ countDistinct: FieldPathSchema.describe("Field path whose distinct non-null values are counted") }).strict().describe("COUNT(DISTINCT field)"),
|
|
134
|
+
zod.z.object({ sum: fieldOrExpr }).strict().describe("SUM"),
|
|
135
|
+
zod.z.object({ avg: fieldOrExpr }).strict().describe("AVG"),
|
|
136
|
+
zod.z.object({ min: fieldOrExpr }).strict().describe("MIN"),
|
|
137
|
+
zod.z.object({ max: fieldOrExpr }).strict().describe("MAX")
|
|
138
|
+
]).describe("Aggregate function applied to a field or expression");
|
|
139
|
+
|
|
140
|
+
// src/schemas/query.schema.ts
|
|
141
|
+
var SortEntrySchema = zod.z.object({
|
|
142
|
+
field: zod.z.union([FieldPathSchema, IdentifierSchema]).describe("Field path (entity.field), computed field name, or aggregate alias"),
|
|
143
|
+
dir: zod.z.enum(["asc", "desc"]).default("asc").describe("Sort direction")
|
|
144
|
+
}).strict().describe("Sort specification");
|
|
145
|
+
var SubquerySourceSchema = zod.z.object({
|
|
146
|
+
as: IdentifierSchema.describe("Alias for subquery results \u2014 use as prefix in field paths"),
|
|
147
|
+
query: zod.z.lazy(() => QuerySchema).describe("A nested query")
|
|
148
|
+
}).strict().describe("Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.");
|
|
149
|
+
var SourceSchema = zod.z.union([
|
|
150
|
+
zod.z.string().describe("Entity name from the database schema"),
|
|
151
|
+
SubquerySourceSchema
|
|
152
|
+
]).describe("Data source: entity name or subquery");
|
|
153
|
+
var FieldRefSchema = zod.z.union([
|
|
154
|
+
FieldPathSchema.describe("A column in entity.field format"),
|
|
155
|
+
zod.z.object({
|
|
156
|
+
field: FieldPathSchema.describe("A column in entity.field format"),
|
|
157
|
+
as: IdentifierSchema.describe("Output key for this column")
|
|
158
|
+
}).strict().describe("An aliased column: output under `as` instead of the column name")
|
|
159
|
+
]).describe("A selected field \u2014 a bare `entity.field`, or `{ field, as }` to alias the output key");
|
|
160
|
+
var QuerySchema = zod.z.lazy(
|
|
161
|
+
() => zod.z.object({
|
|
162
|
+
from: zod.z.array(SourceSchema).min(1).describe("Data sources \u2014 entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys \u2014 a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away."),
|
|
163
|
+
fields: zod.z.array(FieldRefSchema).optional().describe("Raw columns to select \u2014 each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here \u2014 those are added automatically."),
|
|
164
|
+
filter: FilterSchema.optional().describe("Filter conditions"),
|
|
165
|
+
compute: zod.z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe("Computed fields \u2014 key is output alias, value is the expression"),
|
|
166
|
+
aggregate: zod.z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe("Aggregate functions \u2014 key is output alias, value is the function"),
|
|
167
|
+
groupBy: zod.z.array(FieldPathSchema).optional().describe("Fields to group by for aggregation"),
|
|
168
|
+
sort: zod.z.array(SortEntrySchema).optional().describe("Sort order"),
|
|
169
|
+
limit: zod.z.number().int().positive().optional().describe("Maximum rows to return"),
|
|
170
|
+
distinct: zod.z.boolean().optional().describe("Eliminate duplicate rows")
|
|
171
|
+
}).strict().refine(
|
|
172
|
+
(q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,
|
|
173
|
+
{ message: "A query must select at least one of `fields` or `aggregate`." }
|
|
174
|
+
)
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
// src/errors.ts
|
|
178
|
+
var VexError = class extends Error {
|
|
179
|
+
code;
|
|
180
|
+
details;
|
|
181
|
+
constructor(code, message, details) {
|
|
182
|
+
super(message);
|
|
183
|
+
this.name = "VexError";
|
|
184
|
+
this.code = code;
|
|
185
|
+
this.details = details;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// src/engine/optional.ts
|
|
190
|
+
var gateKeys = (key) => Array.isArray(key) ? key : [key];
|
|
191
|
+
var optionalKeysOf = (dsl) => {
|
|
192
|
+
const keys = [];
|
|
193
|
+
const walk = (filter) => {
|
|
194
|
+
if ("optional" in filter) {
|
|
195
|
+
for (const key of gateKeys(filter.optional.key)) {
|
|
196
|
+
if (!keys.includes(key)) keys.push(key);
|
|
197
|
+
}
|
|
198
|
+
walk(filter.optional.then);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if ("and" in filter) {
|
|
202
|
+
for (const sub of filter.and) walk(sub);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if ("or" in filter) {
|
|
206
|
+
for (const sub of filter.or) walk(sub);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if ("not" in filter) {
|
|
210
|
+
walk(filter.not);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
if (dsl.filter !== void 0) walk(dsl.filter);
|
|
215
|
+
for (const source of dsl.from) {
|
|
216
|
+
if (typeof source !== "string") keys.push(...optionalKeysOf(source.query).filter((k) => !keys.includes(k)));
|
|
217
|
+
}
|
|
218
|
+
return keys;
|
|
219
|
+
};
|
|
220
|
+
var presenceOf = (context) => {
|
|
221
|
+
const present = /* @__PURE__ */ new Set();
|
|
222
|
+
for (const [key, value] of Object.entries(context)) {
|
|
223
|
+
if (value !== void 0 && value !== null) present.add(key);
|
|
224
|
+
}
|
|
225
|
+
return present;
|
|
226
|
+
};
|
|
227
|
+
var presenceSignature = (dsl, present) => {
|
|
228
|
+
const keys = optionalKeysOf(dsl);
|
|
229
|
+
if (keys.length === 0) return "";
|
|
230
|
+
if (present === "all") return keys.join(",");
|
|
231
|
+
return keys.filter((k) => present.has(k)).join(",");
|
|
232
|
+
};
|
|
233
|
+
var prune = (filter, present, insideExists) => {
|
|
234
|
+
if ("optional" in filter) {
|
|
235
|
+
const keys = gateKeys(filter.optional.key);
|
|
236
|
+
if (insideExists) {
|
|
237
|
+
throw new VexError("invalid_dsl", `An optional condition ("${keys.join(", ")}") cannot live inside an exists \u2014 its correlation must hold on every run.`);
|
|
238
|
+
}
|
|
239
|
+
if (present !== "all" && !keys.every((key) => present.has(key))) return void 0;
|
|
240
|
+
return prune(filter.optional.then, present, insideExists);
|
|
241
|
+
}
|
|
242
|
+
if ("exists" in filter) {
|
|
243
|
+
const inner = filter.exists.filter === void 0 ? void 0 : prune(filter.exists.filter, present, true);
|
|
244
|
+
return inner === void 0 ? { exists: { from: filter.exists.from } } : { exists: { from: filter.exists.from, filter: inner } };
|
|
245
|
+
}
|
|
246
|
+
if ("and" in filter || "or" in filter) {
|
|
247
|
+
const isAnd = "and" in filter;
|
|
248
|
+
const kept = (isAnd ? filter.and : filter.or).map((sub) => prune(sub, present, insideExists)).filter((sub) => sub !== void 0);
|
|
249
|
+
if (kept.length === 0) return void 0;
|
|
250
|
+
if (kept.length === 1) return kept[0];
|
|
251
|
+
return isAnd ? { and: kept } : { or: kept };
|
|
252
|
+
}
|
|
253
|
+
if ("not" in filter) {
|
|
254
|
+
const inner = prune(filter.not, present, insideExists);
|
|
255
|
+
if (inner === void 0) {
|
|
256
|
+
throw new VexError("invalid_dsl", "An optional condition cannot be the whole body of a `not` \u2014 wrap the `not` in the optional instead.");
|
|
257
|
+
}
|
|
258
|
+
return { not: inner };
|
|
259
|
+
}
|
|
260
|
+
return filter;
|
|
261
|
+
};
|
|
262
|
+
var pruneOptional = (dsl, present) => {
|
|
263
|
+
const from = dsl.from.map(
|
|
264
|
+
(source) => typeof source === "string" ? source : { as: source.as, query: pruneOptional(source.query, present) }
|
|
265
|
+
);
|
|
266
|
+
if (dsl.filter === void 0) return { ...dsl, from };
|
|
267
|
+
const filter = prune(dsl.filter, present, false);
|
|
268
|
+
if (filter === void 0) {
|
|
269
|
+
const { filter: _dropped, ...rest } = dsl;
|
|
270
|
+
return { ...rest, from };
|
|
271
|
+
}
|
|
272
|
+
return { ...dsl, from, filter };
|
|
273
|
+
};
|
|
274
|
+
var refuseOptional = (where) => {
|
|
275
|
+
throw new VexError(
|
|
276
|
+
"invalid_dsl",
|
|
277
|
+
`An optional condition reached ${where}. It should have been resolved by pruneOptional before the pipeline ran \u2014 reaching this point means a query was compiled without knowing which context keys the caller supplied.`
|
|
278
|
+
);
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// src/scope/discover.ts
|
|
282
|
+
var extractEntityFromPath = (path) => {
|
|
283
|
+
const parts = path.split(".");
|
|
284
|
+
return parts.length === 2 ? parts[0] : void 0;
|
|
285
|
+
};
|
|
286
|
+
var collectFromFieldOrValue = (fov, out) => {
|
|
287
|
+
if (isFieldPathShape(fov)) {
|
|
288
|
+
const entity = extractEntityFromPath(fov);
|
|
289
|
+
if (entity !== void 0) out.add(entity);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
var collectFromFilter = (filter, out) => {
|
|
293
|
+
if ("exists" in filter) {
|
|
294
|
+
for (const entity of filter.exists.from) out.add(entity);
|
|
295
|
+
if (filter.exists.filter !== void 0) collectFromFilter(filter.exists.filter, out);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
|
|
299
|
+
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;
|
|
300
|
+
collectFromFieldOrValue(pair[0], out);
|
|
301
|
+
collectFromFieldOrValue(pair[1], out);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if ("in" in filter || "notIn" in filter) {
|
|
305
|
+
const tuple = "in" in filter ? filter.in : filter.notIn;
|
|
306
|
+
const entity = extractEntityFromPath(tuple[0]);
|
|
307
|
+
if (entity !== void 0) out.add(entity);
|
|
308
|
+
const target = tuple[1];
|
|
309
|
+
if (Array.isArray(target)) {
|
|
310
|
+
for (const v of target) {
|
|
311
|
+
collectFromFieldOrValue(v, out);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if ("like" in filter || "ilike" in filter) {
|
|
317
|
+
const tuple = "like" in filter ? filter.like : filter.ilike;
|
|
318
|
+
const entity = extractEntityFromPath(tuple[0]);
|
|
319
|
+
if (entity !== void 0) out.add(entity);
|
|
320
|
+
collectFromFieldOrValue(tuple[1], out);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if ("isNull" in filter) {
|
|
324
|
+
const entity = extractEntityFromPath(filter.isNull);
|
|
325
|
+
if (entity !== void 0) out.add(entity);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if ("isNotNull" in filter) {
|
|
329
|
+
const entity = extractEntityFromPath(filter.isNotNull);
|
|
330
|
+
if (entity !== void 0) out.add(entity);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if ("and" in filter) {
|
|
334
|
+
for (const sub of filter.and) {
|
|
335
|
+
collectFromFilter(sub, out);
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if ("or" in filter) {
|
|
340
|
+
for (const sub of filter.or) {
|
|
341
|
+
collectFromFilter(sub, out);
|
|
342
|
+
}
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if ("not" in filter) {
|
|
346
|
+
collectFromFilter(filter.not, out);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if ("semantic" in filter) {
|
|
350
|
+
const entity = extractEntityFromPath(filter.semantic.field);
|
|
351
|
+
if (entity !== void 0) out.add(entity);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if ("fuzzy" in filter) {
|
|
355
|
+
const entity = extractEntityFromPath(filter.fuzzy.field);
|
|
356
|
+
if (entity !== void 0) out.add(entity);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if ("optional" in filter) refuseOptional("scope discovery");
|
|
360
|
+
};
|
|
361
|
+
var collectFromCompute = (expr, out) => {
|
|
362
|
+
if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
|
|
363
|
+
const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
|
|
364
|
+
collectFromFieldOrValue(pair[0], out);
|
|
365
|
+
collectFromFieldOrValue(pair[1], out);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if ("concat" in expr) {
|
|
369
|
+
for (const v of expr.concat) {
|
|
370
|
+
collectFromFieldOrValue(v, out);
|
|
371
|
+
}
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if ("coalesce" in expr) {
|
|
375
|
+
for (const v of expr.coalesce) {
|
|
376
|
+
collectFromFieldOrValue(v, out);
|
|
377
|
+
}
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if ("case" in expr) {
|
|
381
|
+
for (const when of expr.case.when) {
|
|
382
|
+
collectFromFilter(when.condition, out);
|
|
383
|
+
collectFromFieldOrValue(when.then, out);
|
|
384
|
+
}
|
|
385
|
+
collectFromFieldOrValue(expr.case.else, out);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
var collectFromAggregate = (expr, out) => {
|
|
390
|
+
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;
|
|
391
|
+
if (typeof arg !== "string") {
|
|
392
|
+
collectFromCompute(arg, out);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const entity = extractEntityFromPath(arg);
|
|
396
|
+
if (entity !== void 0) out.add(entity);
|
|
397
|
+
};
|
|
398
|
+
var collectFromQuery = (dsl, out) => {
|
|
399
|
+
const aliases = /* @__PURE__ */ new Set();
|
|
400
|
+
const local = /* @__PURE__ */ new Set();
|
|
401
|
+
for (const source of dsl.from) {
|
|
402
|
+
if (typeof source === "string") {
|
|
403
|
+
out.add(source);
|
|
404
|
+
} else {
|
|
405
|
+
aliases.add(source.as);
|
|
406
|
+
collectFromQuery(source.query, out);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (const ref of dsl.fields ?? []) {
|
|
410
|
+
const entity = extractEntityFromPath(typeof ref === "string" ? ref : ref.field);
|
|
411
|
+
if (entity !== void 0) local.add(entity);
|
|
412
|
+
}
|
|
413
|
+
if (dsl.filter !== void 0) {
|
|
414
|
+
collectFromFilter(dsl.filter, local);
|
|
415
|
+
}
|
|
416
|
+
if (dsl.compute !== void 0) {
|
|
417
|
+
for (const key of Object.keys(dsl.compute)) {
|
|
418
|
+
const expr = dsl.compute[key];
|
|
419
|
+
if (expr !== void 0) {
|
|
420
|
+
collectFromCompute(expr, local);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (dsl.aggregate !== void 0) {
|
|
425
|
+
for (const key of Object.keys(dsl.aggregate)) {
|
|
426
|
+
const expr = dsl.aggregate[key];
|
|
427
|
+
if (expr !== void 0) {
|
|
428
|
+
collectFromAggregate(expr, local);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (dsl.groupBy !== void 0) {
|
|
433
|
+
for (const path of dsl.groupBy) {
|
|
434
|
+
const entity = extractEntityFromPath(path);
|
|
435
|
+
if (entity !== void 0) local.add(entity);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (dsl.sort !== void 0) {
|
|
439
|
+
for (const entry of dsl.sort) {
|
|
440
|
+
const entity = extractEntityFromPath(entry.field);
|
|
441
|
+
if (entity !== void 0) local.add(entity);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
for (const entity of local) {
|
|
445
|
+
if (!aliases.has(entity)) out.add(entity);
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
var discoverEntities = (dsl) => {
|
|
449
|
+
const entities = /* @__PURE__ */ new Set();
|
|
450
|
+
collectFromQuery(dsl, entities);
|
|
451
|
+
return entities;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// src/scope/scope.types.ts
|
|
455
|
+
var isSetMatch = (m) => "in" in m;
|
|
456
|
+
|
|
457
|
+
// src/scope/apply.ts
|
|
458
|
+
var VexScopeError = class extends VexError {
|
|
459
|
+
entity;
|
|
460
|
+
constructor(entity, message) {
|
|
461
|
+
super("scope_denied", message);
|
|
462
|
+
this.name = "VexScopeError";
|
|
463
|
+
this.entity = entity;
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
var matchesFor = (entity, rule, def) => {
|
|
467
|
+
if (rule === void 0) {
|
|
468
|
+
if (def === "deny") throw new VexScopeError(entity, `Entity "${entity}" is not allowed by scope policy (default: deny)`);
|
|
469
|
+
return [];
|
|
470
|
+
}
|
|
471
|
+
if ("public" in rule) return [];
|
|
472
|
+
if ("deny" in rule) throw new VexScopeError(entity, `Entity "${entity}" is denied by scope policy`);
|
|
473
|
+
if (rule.read === void 0) {
|
|
474
|
+
if (def === "deny") throw new VexScopeError(entity, `Reads of "${entity}" are not allowed by scope policy (default: deny)`);
|
|
475
|
+
return [];
|
|
476
|
+
}
|
|
477
|
+
return rule.read;
|
|
478
|
+
};
|
|
479
|
+
var canReadTable = (policy, table) => {
|
|
480
|
+
const rule = policy.entities[table];
|
|
481
|
+
if (rule === void 0) return policy.default === "allow";
|
|
482
|
+
if ("public" in rule) return true;
|
|
483
|
+
if ("deny" in rule) return false;
|
|
484
|
+
return rule.read !== void 0 || policy.default === "allow";
|
|
485
|
+
};
|
|
486
|
+
var checkScope = (entities, policy) => {
|
|
487
|
+
for (const entity of entities) matchesFor(entity, policy.entities[entity], policy.default);
|
|
488
|
+
};
|
|
489
|
+
var andMerge = (existing, additions) => {
|
|
490
|
+
if (additions.length === 0) return existing;
|
|
491
|
+
const all = existing === void 0 ? additions : [existing, ...additions];
|
|
492
|
+
if (all.length === 1) return all[0];
|
|
493
|
+
const paths = /* @__PURE__ */ new Map();
|
|
494
|
+
for (const part of all) for (const [key, value] of part.resolvedPaths) paths.set(key, value);
|
|
495
|
+
return { original: { and: all.map((f) => f.original) }, resolvedPaths: paths };
|
|
496
|
+
};
|
|
497
|
+
var predicateFor = (entityName, alias, match, fields) => {
|
|
498
|
+
const field = fields.find((f) => f.name === match.match);
|
|
499
|
+
if (field === void 0) throw new VexScopeError(entityName, `Scope rule for "${entityName}" names column "${match.match}", which the table does not have`);
|
|
500
|
+
const path = `${entityName}.${match.match}`;
|
|
501
|
+
const original = isSetMatch(match) ? { in: [path, { $scope: match.in }] } : { eq: [path, { $scope: match.to }] };
|
|
502
|
+
return { original, resolvedPaths: /* @__PURE__ */ new Map([[path, { alias, column: match.match, schema: field }]]) };
|
|
503
|
+
};
|
|
504
|
+
var placeInto = (level, policy) => {
|
|
505
|
+
const whereAdditions = [];
|
|
506
|
+
for (const source of level.sources) {
|
|
507
|
+
const entity = source.entity;
|
|
508
|
+
if (entity === void 0) continue;
|
|
509
|
+
const join = level.joins.find((j) => j.toAlias === source.alias);
|
|
510
|
+
for (const match of matchesFor(entity.name, policy.entities[entity.name], policy.default)) {
|
|
511
|
+
const predicate = predicateFor(entity.name, source.alias, match, entity.fields);
|
|
512
|
+
if (predicate === void 0) continue;
|
|
513
|
+
level.aliasMap.set(`${entity.name}.${match.match}`, `${source.alias}.${match.match}`);
|
|
514
|
+
if (join !== void 0 && join.kind === "left") join.on = [...join.on ?? [], predicate];
|
|
515
|
+
else whereAdditions.push(predicate);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const merged = andMerge(level.filter, whereAdditions);
|
|
519
|
+
if (merged !== void 0) level.filter = merged;
|
|
520
|
+
};
|
|
521
|
+
var scopeResolved = (resolved, policy) => {
|
|
522
|
+
for (const source of resolved.sources) {
|
|
523
|
+
if (source.subquery !== void 0) scopeResolved(source.subquery, policy);
|
|
524
|
+
}
|
|
525
|
+
for (const node of resolved.existsMap?.values() ?? []) {
|
|
526
|
+
placeInto(node, policy);
|
|
527
|
+
}
|
|
528
|
+
placeInto(resolved, policy);
|
|
529
|
+
return resolved;
|
|
530
|
+
};
|
|
531
|
+
var applyScope = (dsl, entities, policy) => {
|
|
532
|
+
checkScope(entities, policy);
|
|
533
|
+
return dsl;
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
// src/scope/grants.ts
|
|
537
|
+
var SCOPE_VERBS = ["read", "write.insert", "write.update", "write.delete"];
|
|
538
|
+
var scopeGrants = (tables) => tables.flatMap((t) => SCOPE_VERBS.map((v) => `${t}.${v}`));
|
|
539
|
+
var RULE_KEYS = ["read", "write", "insert", "update", "delete"];
|
|
540
|
+
var isRuleSet = (value) => RULE_KEYS.some((k) => k in value);
|
|
541
|
+
var behaviorFor = (behaviors, table, profile) => {
|
|
542
|
+
const entry = behaviors[table];
|
|
543
|
+
if (entry === void 0) return {};
|
|
544
|
+
if (isRuleSet(entry)) return entry;
|
|
545
|
+
return (profile === void 0 ? void 0 : entry[profile]) ?? entry["default"];
|
|
546
|
+
};
|
|
547
|
+
var onlyMatches = (rules) => rules.filter((r) => "match" in r);
|
|
548
|
+
var VERBS = new Set(SCOPE_VERBS);
|
|
549
|
+
var bindingsOf = (entry) => (isRuleSet(entry) ? [entry] : Object.values(entry)).flatMap(
|
|
550
|
+
(rules) => RULE_KEYS.flatMap(
|
|
551
|
+
(phase) => (rules[phase] ?? []).map(
|
|
552
|
+
(rule) => "set" in rule ? { field: rule.set, key: rule.to } : isSetMatch(rule) ? { field: rule.match, key: rule.in } : { field: rule.match, key: rule.to }
|
|
553
|
+
)
|
|
554
|
+
)
|
|
555
|
+
);
|
|
556
|
+
var scopeBindings = (behaviors, tables, scope) => {
|
|
557
|
+
const seen = /* @__PURE__ */ new Map();
|
|
558
|
+
for (const table of tables) {
|
|
559
|
+
const entry = behaviors[table];
|
|
560
|
+
if (entry === void 0) continue;
|
|
561
|
+
for (const { field, key } of bindingsOf(entry)) {
|
|
562
|
+
if (scope[key] === void 0 || scope[key] === null) continue;
|
|
563
|
+
seen.set(`${table}.${field}:${key}`, { entity: table, field, key });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return [...seen.values()].sort((a, b) => `${a.entity}.${a.field}:${a.key}`.localeCompare(`${b.entity}.${b.field}:${b.key}`));
|
|
567
|
+
};
|
|
568
|
+
var behaviorColumns = (behaviors) => Object.entries(behaviors).flatMap(([table, entry]) => bindingsOf(entry).map(({ field }) => ({ entity: table, field })));
|
|
569
|
+
var scopeProfiles = (behaviors) => {
|
|
570
|
+
const names = /* @__PURE__ */ new Set();
|
|
571
|
+
for (const entry of Object.values(behaviors)) {
|
|
572
|
+
if (isRuleSet(entry)) continue;
|
|
573
|
+
for (const name of Object.keys(entry)) if (name !== "default") names.add(name);
|
|
574
|
+
}
|
|
575
|
+
return names;
|
|
576
|
+
};
|
|
577
|
+
var createScopePolicy = (grants, behaviors = {}, scoping) => {
|
|
578
|
+
if (scoping !== void 0 && !scopeProfiles(behaviors).has(scoping)) return { default: "deny", entities: {} };
|
|
579
|
+
const entities = {};
|
|
580
|
+
for (const grant of grants) {
|
|
581
|
+
const dot = grant.indexOf(".");
|
|
582
|
+
if (dot < 0) continue;
|
|
583
|
+
const table = grant.slice(0, dot);
|
|
584
|
+
const verb = grant.slice(dot + 1);
|
|
585
|
+
if (!VERBS.has(verb)) continue;
|
|
586
|
+
const b = behaviorFor(behaviors, table, scoping);
|
|
587
|
+
if (b === void 0) continue;
|
|
588
|
+
const rule = entities[table] ??= {};
|
|
589
|
+
if (verb === "read") rule.read = b?.read ?? [];
|
|
590
|
+
else if (verb === "write.insert") rule.insert = [...b?.write ?? [], ...b?.insert ?? []];
|
|
591
|
+
else if (verb === "write.update") rule.update = [...b?.write ?? [], ...b?.update ?? []];
|
|
592
|
+
else if (verb === "write.delete") rule.delete = [...onlyMatches(b?.write ?? []), ...b?.delete ?? []];
|
|
593
|
+
}
|
|
594
|
+
return { default: "deny", entities };
|
|
595
|
+
};
|
|
596
|
+
var matchCount = (rules) => (rules ?? []).filter((r) => "match" in r).length;
|
|
597
|
+
var mergeScopePolicies = (policies) => {
|
|
598
|
+
const entities = {};
|
|
599
|
+
for (const policy of policies) {
|
|
600
|
+
for (const [table, rule] of Object.entries(policy.entities)) {
|
|
601
|
+
if (rule === void 0 || "public" in rule || "deny" in rule) continue;
|
|
602
|
+
const into = entities[table] ??= {};
|
|
603
|
+
for (const phase of ["read", "insert", "update", "delete"]) {
|
|
604
|
+
const incoming = rule[phase];
|
|
605
|
+
if (incoming === void 0) continue;
|
|
606
|
+
const held = into[phase];
|
|
607
|
+
if (held === void 0 || matchCount(incoming) < matchCount(held)) {
|
|
608
|
+
into[phase] = incoming;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return { default: "deny", entities };
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
// src/engine/resolver.ts
|
|
617
|
+
var levenshtein = (a, b) => {
|
|
618
|
+
const la = a.length;
|
|
619
|
+
const lb = b.length;
|
|
620
|
+
if (la === 0) return lb;
|
|
621
|
+
if (lb === 0) return la;
|
|
622
|
+
let prev = Array.from({ length: lb + 1 }, (_, i) => i);
|
|
623
|
+
let curr = new Array(lb + 1);
|
|
624
|
+
for (let i = 1; i <= la; i++) {
|
|
625
|
+
curr[0] = i;
|
|
626
|
+
for (let j = 1; j <= lb; j++) {
|
|
627
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
628
|
+
const prevJ = prev[j] ?? 0;
|
|
629
|
+
const currJ1 = curr[j - 1] ?? 0;
|
|
630
|
+
const prevJ1 = prev[j - 1] ?? 0;
|
|
631
|
+
curr[j] = Math.min(prevJ + 1, currJ1 + 1, prevJ1 + cost);
|
|
632
|
+
}
|
|
633
|
+
[prev, curr] = [curr, prev];
|
|
634
|
+
}
|
|
635
|
+
return prev[lb] ?? 0;
|
|
636
|
+
};
|
|
637
|
+
var findClosest = (target, candidates) => {
|
|
638
|
+
let best;
|
|
639
|
+
let bestDist = Infinity;
|
|
640
|
+
for (const c of candidates) {
|
|
641
|
+
const dist = levenshtein(target.toLowerCase(), c.toLowerCase());
|
|
642
|
+
if (dist < bestDist) {
|
|
643
|
+
bestDist = dist;
|
|
644
|
+
best = c;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (bestDist <= Math.max(3, Math.ceil(target.length / 2))) {
|
|
648
|
+
return best;
|
|
649
|
+
}
|
|
650
|
+
return void 0;
|
|
651
|
+
};
|
|
652
|
+
var generateAlias = (name, counter) => {
|
|
653
|
+
const prefix = name.charAt(0).toLowerCase();
|
|
654
|
+
const current = counter.get(prefix) ?? 0;
|
|
655
|
+
const next = current + 1;
|
|
656
|
+
counter.set(prefix, next);
|
|
657
|
+
return `${prefix}${next}`;
|
|
658
|
+
};
|
|
659
|
+
var findEntity = (name, schema) => {
|
|
660
|
+
const found = schema.entities.find((e) => e.name === name);
|
|
661
|
+
if (found !== void 0) return found;
|
|
662
|
+
const allNames = schema.entities.map((e) => e.name);
|
|
663
|
+
const suggestion = findClosest(name, allNames);
|
|
664
|
+
const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
|
|
665
|
+
throw new VexError(
|
|
666
|
+
"invalid_dsl",
|
|
667
|
+
`Entity "${name}" not found in schema.${hint}`,
|
|
668
|
+
{ suggestion, options: allNames }
|
|
669
|
+
);
|
|
670
|
+
};
|
|
671
|
+
var findField = (fieldName, entity) => {
|
|
672
|
+
const found = entity.fields.find((f) => f.name === fieldName);
|
|
673
|
+
if (found !== void 0) return found;
|
|
674
|
+
const allFields = entity.fields.map((f) => f.name);
|
|
675
|
+
const suggestion = findClosest(fieldName, allFields);
|
|
676
|
+
const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
|
|
677
|
+
throw new VexError(
|
|
678
|
+
"invalid_dsl",
|
|
679
|
+
`Field "${fieldName}" not found on entity "${entity.name}".${hint} Available fields: ${allFields.join(", ")}`,
|
|
680
|
+
{ suggestion, options: allFields }
|
|
681
|
+
);
|
|
682
|
+
};
|
|
683
|
+
var parsePath = (path) => {
|
|
684
|
+
if (!isFieldPathShape(path)) {
|
|
685
|
+
throw new VexError(
|
|
686
|
+
"invalid_dsl",
|
|
687
|
+
`Invalid field path "${path}". Expected format: entity.field`
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
const dotIndex = path.indexOf(".");
|
|
691
|
+
return {
|
|
692
|
+
entity: path.substring(0, dotIndex),
|
|
693
|
+
field: path.substring(dotIndex + 1)
|
|
694
|
+
};
|
|
695
|
+
};
|
|
696
|
+
var assertName = (name, what) => {
|
|
697
|
+
if (!isIdentifier(name)) {
|
|
698
|
+
throw new VexError("invalid_dsl", `Invalid ${what} "${name}": letters, digits and underscores, not starting with a digit.`);
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
var findJoinBetween = (fromEntity, toEntity, fromAlias, toAlias) => {
|
|
702
|
+
for (const rel of fromEntity.relations) {
|
|
703
|
+
if (rel.entity === toEntity.name) {
|
|
704
|
+
const fkNullable = rel.localFields.some(
|
|
705
|
+
(column) => fromEntity.fields.find((f) => f.name === column)?.nullable === true
|
|
706
|
+
);
|
|
707
|
+
return {
|
|
708
|
+
fromAlias,
|
|
709
|
+
fromColumns: rel.localFields,
|
|
710
|
+
toAlias,
|
|
711
|
+
toColumns: rel.foreignFields,
|
|
712
|
+
toTable: toEntity.table,
|
|
713
|
+
kind: fkNullable ? "left" : "inner"
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
for (const rel of toEntity.relations) {
|
|
718
|
+
if (rel.entity === fromEntity.name) {
|
|
719
|
+
return {
|
|
720
|
+
fromAlias,
|
|
721
|
+
fromColumns: rel.foreignFields,
|
|
722
|
+
toAlias,
|
|
723
|
+
toColumns: rel.localFields,
|
|
724
|
+
toTable: toEntity.table,
|
|
725
|
+
kind: "inner"
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
return void 0;
|
|
730
|
+
};
|
|
731
|
+
var resolveFieldPath = (path, entityLookup, schema) => {
|
|
732
|
+
const parsed = parsePath(path);
|
|
733
|
+
const lookup = entityLookup.get(parsed.entity);
|
|
734
|
+
if (lookup === void 0) {
|
|
735
|
+
const entityExists = schema.entities.some((e) => e.name === parsed.entity);
|
|
736
|
+
if (entityExists) {
|
|
737
|
+
throw new VexError(
|
|
738
|
+
"invalid_dsl",
|
|
739
|
+
`Entity "${parsed.entity}" is referenced in field path "${path}" but not listed in "from"`
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
const allNames = schema.entities.map((e) => e.name);
|
|
743
|
+
const suggestion = findClosest(parsed.entity, allNames);
|
|
744
|
+
const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
|
|
745
|
+
throw new VexError(
|
|
746
|
+
"invalid_dsl",
|
|
747
|
+
`Entity "${parsed.entity}" not found in schema.${hint}`,
|
|
748
|
+
{ suggestion, options: allNames }
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
const fieldSchema = findField(parsed.field, lookup.entity);
|
|
752
|
+
return {
|
|
753
|
+
resolved: {
|
|
754
|
+
path,
|
|
755
|
+
alias: lookup.alias,
|
|
756
|
+
column: fieldSchema.name,
|
|
757
|
+
outputName: parsed.field,
|
|
758
|
+
schema: fieldSchema
|
|
759
|
+
},
|
|
760
|
+
entityName: parsed.entity
|
|
761
|
+
};
|
|
762
|
+
};
|
|
763
|
+
var isFieldPath = isFieldPathShape;
|
|
764
|
+
var collectFilterPaths = (filter, entityLookup, schema, resolvedPaths, existsOut, aliasCounter) => {
|
|
765
|
+
if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
|
|
766
|
+
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;
|
|
767
|
+
resolveFilterFieldOrValue(pair[0], entityLookup, schema, resolvedPaths);
|
|
768
|
+
resolveFilterFieldOrValue(pair[1], entityLookup, schema, resolvedPaths);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if ("in" in filter || "notIn" in filter) {
|
|
772
|
+
const tuple = "in" in filter ? filter.in : filter.notIn;
|
|
773
|
+
resolveFilterFieldPath(tuple[0], entityLookup, schema, resolvedPaths);
|
|
774
|
+
const target = tuple[1];
|
|
775
|
+
if (Array.isArray(target)) {
|
|
776
|
+
for (const v of target) {
|
|
777
|
+
resolveFilterFieldOrValue(v, entityLookup, schema, resolvedPaths);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
if ("like" in filter || "ilike" in filter) {
|
|
783
|
+
const tuple = "like" in filter ? filter.like : filter.ilike;
|
|
784
|
+
resolveFilterFieldPath(tuple[0], entityLookup, schema, resolvedPaths);
|
|
785
|
+
resolveFilterFieldOrValue(tuple[1], entityLookup, schema, resolvedPaths);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
if ("isNull" in filter) {
|
|
789
|
+
resolveFilterFieldPath(filter.isNull, entityLookup, schema, resolvedPaths);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if ("isNotNull" in filter) {
|
|
793
|
+
resolveFilterFieldPath(filter.isNotNull, entityLookup, schema, resolvedPaths);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if ("exists" in filter) {
|
|
797
|
+
if (existsOut === void 0 || aliasCounter === void 0) return;
|
|
798
|
+
const inner = new Map(entityLookup);
|
|
799
|
+
const innerSources = [];
|
|
800
|
+
const innerEntities = [];
|
|
801
|
+
const innerJoins = [];
|
|
802
|
+
const innerAliasMap = /* @__PURE__ */ new Map();
|
|
803
|
+
for (const name of filter.exists.from) {
|
|
804
|
+
const entity = findEntity(name, schema);
|
|
805
|
+
const alias = generateAlias(name, aliasCounter);
|
|
806
|
+
inner.set(name, { entity, alias });
|
|
807
|
+
innerSources.push({ alias, entity, table: entity.table });
|
|
808
|
+
innerEntities.push({ entity, alias });
|
|
809
|
+
}
|
|
810
|
+
for (let i = 1; i < innerEntities.length; i += 1) {
|
|
811
|
+
const curr = innerEntities[i];
|
|
812
|
+
if (curr === void 0) continue;
|
|
813
|
+
let found = false;
|
|
814
|
+
for (let j = 0; j < i; j += 1) {
|
|
815
|
+
const earlier = innerEntities[j];
|
|
816
|
+
if (earlier === void 0) continue;
|
|
817
|
+
const join = findJoinBetween(earlier.entity, curr.entity, earlier.alias, curr.alias);
|
|
818
|
+
if (join !== void 0) {
|
|
819
|
+
innerJoins.push(join);
|
|
820
|
+
found = true;
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
if (!found) throw new VexError("invalid_dsl", `No foreign key relationship found between the entities of an "exists" and "${curr.entity.name}".`);
|
|
825
|
+
}
|
|
826
|
+
let innerFilter;
|
|
827
|
+
if (filter.exists.filter !== void 0) {
|
|
828
|
+
const innerPaths = /* @__PURE__ */ new Map();
|
|
829
|
+
collectFilterPaths(filter.exists.filter, inner, schema, innerPaths, existsOut, aliasCounter);
|
|
830
|
+
innerFilter = { original: filter.exists.filter, resolvedPaths: innerPaths };
|
|
831
|
+
for (const [path, res] of innerPaths) {
|
|
832
|
+
const owner = path.slice(0, path.indexOf("."));
|
|
833
|
+
if (filter.exists.from.includes(owner)) innerAliasMap.set(path, `${res.alias}.${res.column}`);
|
|
834
|
+
else resolvedPaths.set(path, res);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
existsOut.set(filter.exists, { sources: innerSources, joins: innerJoins, filter: innerFilter, aliasMap: innerAliasMap });
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
if ("and" in filter) {
|
|
841
|
+
for (const sub of filter.and) {
|
|
842
|
+
collectFilterPaths(sub, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
|
|
843
|
+
}
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
if ("or" in filter) {
|
|
847
|
+
for (const sub of filter.or) {
|
|
848
|
+
collectFilterPaths(sub, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
|
|
849
|
+
}
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
if ("not" in filter) {
|
|
853
|
+
collectFilterPaths(filter.not, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
if ("semantic" in filter) {
|
|
857
|
+
resolveFilterFieldPath(filter.semantic.field, entityLookup, schema, resolvedPaths);
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
if ("fuzzy" in filter) {
|
|
861
|
+
resolveFilterFieldPath(filter.fuzzy.field, entityLookup, schema, resolvedPaths);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if ("optional" in filter) refuseOptional("field resolution");
|
|
865
|
+
};
|
|
866
|
+
var resolveFilterFieldPath = (path, entityLookup, schema, resolvedPaths) => {
|
|
867
|
+
if (resolvedPaths.has(path)) return;
|
|
868
|
+
const { resolved } = resolveFieldPath(path, entityLookup, schema);
|
|
869
|
+
resolvedPaths.set(path, { alias: resolved.alias, column: resolved.column, schema: resolved.schema });
|
|
870
|
+
};
|
|
871
|
+
var resolveFilterFieldOrValue = (fov, entityLookup, schema, resolvedPaths) => {
|
|
872
|
+
if (typeof fov === "string" && isFieldPath(fov)) {
|
|
873
|
+
resolveFilterFieldPath(fov, entityLookup, schema, resolvedPaths);
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
var extractSemantic = (filter, entityLookup, schema) => {
|
|
877
|
+
if ("semantic" in filter) {
|
|
878
|
+
const { resolved } = resolveFieldPath(filter.semantic.field, entityLookup, schema);
|
|
879
|
+
const queryRef = filter.semantic.query;
|
|
880
|
+
const contextPath = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
|
|
881
|
+
return {
|
|
882
|
+
field: resolved,
|
|
883
|
+
contextPath,
|
|
884
|
+
minScore: filter.semantic.minScore
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
if ("and" in filter) {
|
|
888
|
+
for (const sub of filter.and) {
|
|
889
|
+
const result = extractSemantic(sub, entityLookup, schema);
|
|
890
|
+
if (result !== void 0) return result;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
if ("or" in filter) {
|
|
894
|
+
for (const sub of filter.or) {
|
|
895
|
+
const result = extractSemantic(sub, entityLookup, schema);
|
|
896
|
+
if (result !== void 0) return result;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
if ("not" in filter) {
|
|
900
|
+
return extractSemantic(filter.not, entityLookup, schema);
|
|
901
|
+
}
|
|
902
|
+
return void 0;
|
|
903
|
+
};
|
|
904
|
+
var resolve = (dsl, schema) => {
|
|
905
|
+
const aliasCounter = /* @__PURE__ */ new Map();
|
|
906
|
+
const entityLookup = /* @__PURE__ */ new Map();
|
|
907
|
+
const aliasMap = /* @__PURE__ */ new Map();
|
|
908
|
+
const sources = [];
|
|
909
|
+
const joins = [];
|
|
910
|
+
const entitySources = [];
|
|
911
|
+
for (const source of dsl.from) {
|
|
912
|
+
if (typeof source === "string") {
|
|
913
|
+
const entity = findEntity(source, schema);
|
|
914
|
+
const alias = generateAlias(source, aliasCounter);
|
|
915
|
+
entityLookup.set(source, { entity, alias });
|
|
916
|
+
sources.push({ alias, entity, table: entity.table });
|
|
917
|
+
entitySources.push({ entity, alias });
|
|
918
|
+
} else {
|
|
919
|
+
assertName(source.as, "subquery alias");
|
|
920
|
+
const subResolved = resolve(source.query, schema);
|
|
921
|
+
const alias = source.as;
|
|
922
|
+
const synthField = (name, normalizedType) => ({
|
|
923
|
+
name,
|
|
924
|
+
type: normalizedType,
|
|
925
|
+
normalizedType,
|
|
926
|
+
nullable: true,
|
|
927
|
+
primaryKey: false
|
|
928
|
+
});
|
|
929
|
+
const syntheticFields = [
|
|
930
|
+
...subResolved.fields.map((f) => ({ ...f.schema, name: f.outputName })),
|
|
931
|
+
...subResolved.computes.map((c) => synthField(c.name, "unknown")),
|
|
932
|
+
...subResolved.aggregates.map((a) => synthField(a.name, "number"))
|
|
933
|
+
];
|
|
934
|
+
const syntheticEntity = {
|
|
935
|
+
name: alias,
|
|
936
|
+
table: alias,
|
|
937
|
+
fields: syntheticFields,
|
|
938
|
+
relations: [],
|
|
939
|
+
indexes: []
|
|
940
|
+
};
|
|
941
|
+
entityLookup.set(alias, { entity: syntheticEntity, alias });
|
|
942
|
+
sources.push({ alias, subquery: subResolved });
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
for (let i = 1; i < entitySources.length; i++) {
|
|
946
|
+
const prev = entitySources[i - 1];
|
|
947
|
+
const curr = entitySources[i];
|
|
948
|
+
if (prev === void 0 || curr === void 0) continue;
|
|
949
|
+
let joinFound = false;
|
|
950
|
+
for (let j = 0; j < i; j++) {
|
|
951
|
+
const earlier = entitySources[j];
|
|
952
|
+
if (earlier === void 0) continue;
|
|
953
|
+
const join = findJoinBetween(earlier.entity, curr.entity, earlier.alias, curr.alias);
|
|
954
|
+
if (join !== void 0) {
|
|
955
|
+
joins.push(join);
|
|
956
|
+
joinFound = true;
|
|
957
|
+
break;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
if (!joinFound) {
|
|
961
|
+
throw new VexError(
|
|
962
|
+
"invalid_dsl",
|
|
963
|
+
`No foreign key relationship found between any previous entity and "${curr.entity.name}". Cannot determine join condition.`
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const fields = [];
|
|
968
|
+
for (const ref of dsl.fields ?? []) {
|
|
969
|
+
const path = typeof ref === "string" ? ref : ref.field;
|
|
970
|
+
if (typeof ref !== "string") assertName(ref.as, "field alias");
|
|
971
|
+
const { resolved } = resolveFieldPath(path, entityLookup, schema);
|
|
972
|
+
fields.push(typeof ref === "string" ? resolved : { ...resolved, outputName: ref.as });
|
|
973
|
+
aliasMap.set(path, `${resolved.alias}.${resolved.column}`);
|
|
974
|
+
}
|
|
975
|
+
let resolvedFilter;
|
|
976
|
+
let semantic;
|
|
977
|
+
const existsMap = /* @__PURE__ */ new Map();
|
|
978
|
+
if (dsl.filter !== void 0) {
|
|
979
|
+
const resolvedPaths = /* @__PURE__ */ new Map();
|
|
980
|
+
collectFilterPaths(dsl.filter, entityLookup, schema, resolvedPaths, existsMap, aliasCounter);
|
|
981
|
+
resolvedFilter = { original: dsl.filter, resolvedPaths };
|
|
982
|
+
for (const [path, res] of resolvedPaths) {
|
|
983
|
+
aliasMap.set(path, `${res.alias}.${res.column}`);
|
|
984
|
+
}
|
|
985
|
+
semantic = extractSemantic(dsl.filter, entityLookup, schema);
|
|
986
|
+
}
|
|
987
|
+
const computes = [];
|
|
988
|
+
if (dsl.compute !== void 0) {
|
|
989
|
+
for (const [name, expr] of Object.entries(dsl.compute)) {
|
|
990
|
+
if (expr !== void 0) {
|
|
991
|
+
assertName(name, "compute name");
|
|
992
|
+
resolveComputePaths(expr, entityLookup, schema, aliasMap, existsMap, aliasCounter);
|
|
993
|
+
computes.push({ name, expression: expr });
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const aggregates = [];
|
|
998
|
+
if (dsl.aggregate !== void 0) {
|
|
999
|
+
for (const [name, expr] of Object.entries(dsl.aggregate)) {
|
|
1000
|
+
if (expr !== void 0) {
|
|
1001
|
+
assertName(name, "aggregate name");
|
|
1002
|
+
resolveAggregatePaths(expr, entityLookup, schema, aliasMap);
|
|
1003
|
+
aggregates.push({ name, expression: expr });
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
const groupBy = [];
|
|
1008
|
+
if (dsl.groupBy !== void 0) {
|
|
1009
|
+
for (const path of dsl.groupBy) {
|
|
1010
|
+
const { resolved } = resolveFieldPath(path, entityLookup, schema);
|
|
1011
|
+
groupBy.push(resolved);
|
|
1012
|
+
aliasMap.set(path, `${resolved.alias}.${resolved.column}`);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const sort = [];
|
|
1016
|
+
if (dsl.sort !== void 0) {
|
|
1017
|
+
const computeNames = new Set(computes.map((c) => c.name));
|
|
1018
|
+
const aggregateNames = new Set(aggregates.map((a) => a.name));
|
|
1019
|
+
for (const entry of dsl.sort) {
|
|
1020
|
+
const dir = entry.dir ?? "asc";
|
|
1021
|
+
if (computeNames.has(entry.field) || aggregateNames.has(entry.field)) {
|
|
1022
|
+
sort.push({ field: entry.field, dir });
|
|
1023
|
+
} else {
|
|
1024
|
+
const { resolved } = resolveFieldPath(entry.field, entityLookup, schema);
|
|
1025
|
+
aliasMap.set(entry.field, `${resolved.alias}.${resolved.column}`);
|
|
1026
|
+
sort.push({ field: resolved, dir });
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return {
|
|
1031
|
+
sources,
|
|
1032
|
+
joins,
|
|
1033
|
+
fields,
|
|
1034
|
+
filter: resolvedFilter,
|
|
1035
|
+
semantic,
|
|
1036
|
+
computes,
|
|
1037
|
+
aggregates,
|
|
1038
|
+
groupBy,
|
|
1039
|
+
sort,
|
|
1040
|
+
limit: dsl.limit,
|
|
1041
|
+
distinct: dsl.distinct ?? false,
|
|
1042
|
+
aliasMap,
|
|
1043
|
+
...existsMap.size > 0 ? { existsMap } : {}
|
|
1044
|
+
};
|
|
1045
|
+
};
|
|
1046
|
+
var resolveComputePaths = (expr, entityLookup, schema, aliasMap, existsOut, aliasCounter) => {
|
|
1047
|
+
const resolveFieldOrValue = (fov) => {
|
|
1048
|
+
if (typeof fov === "string" && isFieldPath(fov)) {
|
|
1049
|
+
if (!aliasMap.has(fov)) {
|
|
1050
|
+
const { resolved } = resolveFieldPath(fov, entityLookup, schema);
|
|
1051
|
+
aliasMap.set(fov, `${resolved.alias}.${resolved.column}`);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
|
|
1056
|
+
const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
|
|
1057
|
+
resolveFieldOrValue(pair[0]);
|
|
1058
|
+
resolveFieldOrValue(pair[1]);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if ("concat" in expr) {
|
|
1062
|
+
for (const v of expr.concat) resolveFieldOrValue(v);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
if ("coalesce" in expr) {
|
|
1066
|
+
for (const v of expr.coalesce) resolveFieldOrValue(v);
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
if ("case" in expr) {
|
|
1070
|
+
for (const when of expr.case.when) {
|
|
1071
|
+
const resolvedPaths = /* @__PURE__ */ new Map();
|
|
1072
|
+
collectFilterPaths(when.condition, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
|
|
1073
|
+
for (const [path, res] of resolvedPaths) {
|
|
1074
|
+
aliasMap.set(path, `${res.alias}.${res.column}`);
|
|
1075
|
+
}
|
|
1076
|
+
resolveFieldOrValue(when.then);
|
|
1077
|
+
}
|
|
1078
|
+
resolveFieldOrValue(expr.case.else);
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
var resolveAggregatePaths = (expr, entityLookup, schema, aliasMap) => {
|
|
1082
|
+
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;
|
|
1083
|
+
if (arg === "*") return;
|
|
1084
|
+
if (typeof arg !== "string") {
|
|
1085
|
+
resolveComputePaths(arg, entityLookup, schema, aliasMap);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (!aliasMap.has(arg)) {
|
|
1089
|
+
const { resolved } = resolveFieldPath(arg, entityLookup, schema);
|
|
1090
|
+
aliasMap.set(arg, `${resolved.alias}.${resolved.column}`);
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
|
|
1094
|
+
// src/engine/analyzer.ts
|
|
1095
|
+
var measureNestingDepth = (source) => {
|
|
1096
|
+
if (source.subquery === void 0) return 0;
|
|
1097
|
+
let maxChild = 0;
|
|
1098
|
+
for (const childSource of source.subquery.sources) {
|
|
1099
|
+
const childDepth = measureNestingDepth(childSource);
|
|
1100
|
+
if (childDepth > maxChild) maxChild = childDepth;
|
|
1101
|
+
}
|
|
1102
|
+
return 1 + maxChild;
|
|
1103
|
+
};
|
|
1104
|
+
var getMaxNestingDepth = (resolved) => {
|
|
1105
|
+
let max = 0;
|
|
1106
|
+
for (const source of resolved.sources) {
|
|
1107
|
+
const depth = measureNestingDepth(source);
|
|
1108
|
+
if (depth > max) max = depth;
|
|
1109
|
+
}
|
|
1110
|
+
return max;
|
|
1111
|
+
};
|
|
1112
|
+
var hasCartesianProduct = (resolved) => {
|
|
1113
|
+
const entitySources = resolved.sources.filter((s) => s.entity !== void 0);
|
|
1114
|
+
if (entitySources.length <= 1) return false;
|
|
1115
|
+
const seenAliases = /* @__PURE__ */ new Set();
|
|
1116
|
+
const firstSource = entitySources[0];
|
|
1117
|
+
if (firstSource !== void 0) {
|
|
1118
|
+
seenAliases.add(firstSource.alias);
|
|
1119
|
+
}
|
|
1120
|
+
for (let i = 1; i < entitySources.length; i++) {
|
|
1121
|
+
const source = entitySources[i];
|
|
1122
|
+
if (source === void 0) continue;
|
|
1123
|
+
const hasJoin = resolved.joins.some(
|
|
1124
|
+
(j) => j.toAlias === source.alias && seenAliases.has(j.fromAlias) || j.fromAlias === source.alias && seenAliases.has(j.toAlias)
|
|
1125
|
+
);
|
|
1126
|
+
if (!hasJoin) return true;
|
|
1127
|
+
seenAliases.add(source.alias);
|
|
1128
|
+
}
|
|
1129
|
+
return false;
|
|
1130
|
+
};
|
|
1131
|
+
var findUnindexedFilterColumns = (resolved) => {
|
|
1132
|
+
if (resolved.filter === void 0) return [];
|
|
1133
|
+
const unindexed = [];
|
|
1134
|
+
for (const [path, res] of resolved.filter.resolvedPaths) {
|
|
1135
|
+
const source = resolved.sources.find((s) => s.alias === res.alias);
|
|
1136
|
+
if (source === void 0 || source.entity === void 0) continue;
|
|
1137
|
+
const isIndexed = source.entity.indexes.some(
|
|
1138
|
+
(idx) => idx.fields.includes(res.column)
|
|
1139
|
+
);
|
|
1140
|
+
const isPrimaryKey = source.entity.fields.some(
|
|
1141
|
+
(f) => f.name === res.column && f.primaryKey
|
|
1142
|
+
);
|
|
1143
|
+
if (!isIndexed && !isPrimaryKey) {
|
|
1144
|
+
unindexed.push(path);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return unindexed;
|
|
1148
|
+
};
|
|
1149
|
+
var hasAggregatesWithoutGroupBy = (resolved) => resolved.aggregates.length > 0 && resolved.groupBy.length === 0;
|
|
1150
|
+
var analyze = (resolved, config) => {
|
|
1151
|
+
const warnings = [];
|
|
1152
|
+
const errors = [];
|
|
1153
|
+
const depth = getMaxNestingDepth(resolved);
|
|
1154
|
+
if (depth > config.maxNestingDepth) {
|
|
1155
|
+
errors.push(
|
|
1156
|
+
`Subquery nesting depth ${depth} exceeds maximum allowed depth of ${config.maxNestingDepth}`
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
if (config.rejectCartesianProducts && hasCartesianProduct(resolved)) {
|
|
1160
|
+
errors.push(
|
|
1161
|
+
"Cartesian product detected: multiple sources with no join between them. Add a join or reduce sources."
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
const unindexed = findUnindexedFilterColumns(resolved);
|
|
1165
|
+
if (unindexed.length > 0) {
|
|
1166
|
+
const message = `Unindexed filter columns: ${unindexed.join(", ")}. Consider adding indexes for better performance.`;
|
|
1167
|
+
if (config.rejectUnindexedFilters) {
|
|
1168
|
+
errors.push(message);
|
|
1169
|
+
} else if (config.warnUnindexedFilters) {
|
|
1170
|
+
warnings.push(message);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
if (hasAggregatesWithoutGroupBy(resolved)) {
|
|
1174
|
+
warnings.push(
|
|
1175
|
+
"Aggregate functions used without groupBy. The result will be a single aggregated row."
|
|
1176
|
+
);
|
|
1177
|
+
}
|
|
1178
|
+
if (resolved.semantic !== void 0) {
|
|
1179
|
+
const semanticField = resolved.semantic.field;
|
|
1180
|
+
const vectorSource = resolved.sources.find(
|
|
1181
|
+
(s) => s.alias === semanticField.alias
|
|
1182
|
+
);
|
|
1183
|
+
if (vectorSource !== void 0 && vectorSource.entity !== void 0) {
|
|
1184
|
+
const hasVectorIndex = vectorSource.entity.indexes.some(
|
|
1185
|
+
(idx) => idx.fields.includes(semanticField.column) && (idx.type === "hnsw" || idx.type === "ivfflat")
|
|
1186
|
+
);
|
|
1187
|
+
if (!hasVectorIndex) {
|
|
1188
|
+
warnings.push(
|
|
1189
|
+
`Vector field "${semanticField.path}" has no HNSW or IVFFlat index. Semantic search may be slow.`
|
|
1190
|
+
);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
return { warnings, errors };
|
|
1195
|
+
};
|
|
1196
|
+
|
|
1197
|
+
// src/utils/context.ts
|
|
1198
|
+
var defaultForType = (type) => {
|
|
1199
|
+
if (type === "string") return "";
|
|
1200
|
+
if (type === "number") return 0;
|
|
1201
|
+
if (type === "boolean") return false;
|
|
1202
|
+
if (type === "string[]") return [""];
|
|
1203
|
+
if (type === "number[]") return [0];
|
|
1204
|
+
if (type === "json") return [];
|
|
1205
|
+
return "";
|
|
1206
|
+
};
|
|
1207
|
+
var buildValidationContext = (contract) => {
|
|
1208
|
+
const ctx = {};
|
|
1209
|
+
for (const key of Object.keys(contract)) {
|
|
1210
|
+
const slot = contract[key];
|
|
1211
|
+
if (slot === void 0) continue;
|
|
1212
|
+
if (slot.kind === "semantic") continue;
|
|
1213
|
+
ctx[key] = defaultForType(slot.type);
|
|
1214
|
+
}
|
|
1215
|
+
return ctx;
|
|
1216
|
+
};
|
|
1217
|
+
var resolveParams = async (slots, context, scope, embed) => {
|
|
1218
|
+
const results = [];
|
|
1219
|
+
for (const slot of slots) {
|
|
1220
|
+
if (slot.kind === "context") {
|
|
1221
|
+
results.push(context[slot.key]);
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
if (slot.kind === "scope") {
|
|
1225
|
+
results.push(scope[slot.key]);
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
if (embed === void 0) {
|
|
1229
|
+
throw new Error(`Semantic parameter "${slot.key}" requires an embed function`);
|
|
1230
|
+
}
|
|
1231
|
+
const text = context[slot.key];
|
|
1232
|
+
if (typeof text !== "string") {
|
|
1233
|
+
throw new Error(`Semantic parameter "${slot.key}" requires a string value in context`);
|
|
1234
|
+
}
|
|
1235
|
+
const vector = await embed(text, slot.dimensions);
|
|
1236
|
+
results.push(`[${vector.join(",")}]`);
|
|
1237
|
+
}
|
|
1238
|
+
return results;
|
|
1239
|
+
};
|
|
1240
|
+
|
|
1241
|
+
// src/engine/executor.ts
|
|
1242
|
+
var executeQuery = async (compiled, context, scope, adapter, embed) => {
|
|
1243
|
+
const boundParams = await resolveParams(
|
|
1244
|
+
compiled.paramSlots,
|
|
1245
|
+
context,
|
|
1246
|
+
scope,
|
|
1247
|
+
embed
|
|
1248
|
+
);
|
|
1249
|
+
return adapter.execute(compiled, boundParams);
|
|
1250
|
+
};
|
|
1251
|
+
var buildContextContract = (compiled, optionalKeys = []) => {
|
|
1252
|
+
const contract = {};
|
|
1253
|
+
for (const slot of compiled.paramSlots) {
|
|
1254
|
+
contract[slot.key] = {
|
|
1255
|
+
type: slot.type,
|
|
1256
|
+
kind: slot.kind,
|
|
1257
|
+
...optionalKeys.includes(slot.key) ? { optional: true } : {}
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
for (const key of optionalKeys) {
|
|
1261
|
+
if (contract[key] !== void 0) continue;
|
|
1262
|
+
contract[key] = { kind: "context", optional: true, absent: true };
|
|
1263
|
+
}
|
|
1264
|
+
return contract;
|
|
1265
|
+
};
|
|
1266
|
+
var findMissingContext = (compiled, context) => {
|
|
1267
|
+
const missing = [];
|
|
1268
|
+
for (const slot of compiled.paramSlots) {
|
|
1269
|
+
if ((slot.kind === "context" || slot.kind === "semantic") && context[slot.key] === void 0) {
|
|
1270
|
+
missing.push(slot.key);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
return missing;
|
|
1274
|
+
};
|
|
1275
|
+
var requireScope = (compiled, scope) => {
|
|
1276
|
+
const missing = [...new Set(compiled.paramSlots.filter((slot) => slot.kind === "scope" && scope[slot.key] === void 0).map((slot) => slot.key))];
|
|
1277
|
+
if (missing.length > 0) {
|
|
1278
|
+
throw new VexError("missing_scope", `This statement is scoped by ${missing.join(", ")}, which the host did not supply.`, { keys: missing });
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
|
|
1282
|
+
// src/cache/memory.ts
|
|
1283
|
+
var createMemoryCache = () => {
|
|
1284
|
+
const store = /* @__PURE__ */ new Map();
|
|
1285
|
+
const get = async (key) => {
|
|
1286
|
+
return store.get(key);
|
|
1287
|
+
};
|
|
1288
|
+
const set = async (key, entry) => {
|
|
1289
|
+
store.set(key, entry);
|
|
1290
|
+
};
|
|
1291
|
+
const del = async (key) => {
|
|
1292
|
+
store.delete(key);
|
|
1293
|
+
};
|
|
1294
|
+
const clear = async () => {
|
|
1295
|
+
store.clear();
|
|
1296
|
+
};
|
|
1297
|
+
const keys = async () => {
|
|
1298
|
+
return [...store.keys()];
|
|
1299
|
+
};
|
|
1300
|
+
const entries = async () => {
|
|
1301
|
+
return [...store.entries()].map(([key, entry]) => ({ key, entry }));
|
|
1302
|
+
};
|
|
1303
|
+
return { get, set, delete: del, clear, keys, entries };
|
|
1304
|
+
};
|
|
1305
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1306
|
+
var normalizeShape = (shape) => {
|
|
1307
|
+
if (shape === null) return "null";
|
|
1308
|
+
if (shape === void 0) return "unknown";
|
|
1309
|
+
if (Array.isArray(shape)) {
|
|
1310
|
+
const first = shape[0];
|
|
1311
|
+
return first !== void 0 ? [normalizeShape(first)] : [];
|
|
1312
|
+
}
|
|
1313
|
+
if (isRecord(shape)) {
|
|
1314
|
+
const sortedKeys = Object.keys(shape).sort();
|
|
1315
|
+
const normalized = {};
|
|
1316
|
+
for (const key of sortedKeys) {
|
|
1317
|
+
normalized[key] = normalizeShape(shape[key]);
|
|
1318
|
+
}
|
|
1319
|
+
return normalized;
|
|
1320
|
+
}
|
|
1321
|
+
if (typeof shape === "string") return "string";
|
|
1322
|
+
if (typeof shape === "number") return "number";
|
|
1323
|
+
if (typeof shape === "boolean") return "boolean";
|
|
1324
|
+
return "unknown";
|
|
1325
|
+
};
|
|
1326
|
+
var mintFingerprint = () => `fp_${crypto.createHash("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0, 16)}`;
|
|
1327
|
+
var computeRequestHash = (request) => {
|
|
1328
|
+
const identity = {
|
|
1329
|
+
intent: request.intent ?? null,
|
|
1330
|
+
shape: normalizeShape(request.shape),
|
|
1331
|
+
contextKeys: Object.keys(request.context ?? {}).sort()
|
|
1332
|
+
};
|
|
1333
|
+
return crypto.createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
1334
|
+
};
|
|
1335
|
+
var canonical = (value) => {
|
|
1336
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
1337
|
+
if (isRecord(value)) {
|
|
1338
|
+
const out = {};
|
|
1339
|
+
for (const key of Object.keys(value).sort()) out[key] = canonical(value[key]);
|
|
1340
|
+
return out;
|
|
1341
|
+
}
|
|
1342
|
+
return value;
|
|
1343
|
+
};
|
|
1344
|
+
var computePolicyKey = (policy) => policy === void 0 ? "none" : crypto.createHash("sha256").update(JSON.stringify(canonical(policy))).digest("hex").slice(0, 16);
|
|
1345
|
+
var computeSchemaFingerprint = (schema) => {
|
|
1346
|
+
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
1347
|
+
const stable = {
|
|
1348
|
+
entities: [...schema.entities].sort(byName).map((e) => ({
|
|
1349
|
+
name: e.name,
|
|
1350
|
+
table: e.table,
|
|
1351
|
+
fields: [...e.fields].sort(byName).map((f) => ({
|
|
1352
|
+
name: f.name,
|
|
1353
|
+
type: f.type,
|
|
1354
|
+
normalizedType: f.normalizedType,
|
|
1355
|
+
nullable: f.nullable,
|
|
1356
|
+
primaryKey: f.primaryKey,
|
|
1357
|
+
...f.vectorDimensions !== void 0 ? { vectorDimensions: f.vectorDimensions } : {}
|
|
1358
|
+
})),
|
|
1359
|
+
// Column order within a relation is the key's own order, so it is
|
|
1360
|
+
// preserved; relations are sorted by target and columns. This shape
|
|
1361
|
+
// changed when keys became composite, so every entry cached before
|
|
1362
|
+
// revalidates once on the next boot — the drift eviction, by design.
|
|
1363
|
+
relations: [...e.relations].sort((a, b) => `${a.entity}.${a.localFields.join(",")}`.localeCompare(`${b.entity}.${b.localFields.join(",")}`)).map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),
|
|
1364
|
+
// Index field order is significant (composite indexes) and stable
|
|
1365
|
+
// from introspection, so it is preserved; indexes are sorted by name.
|
|
1366
|
+
indexes: [...e.indexes].sort(byName).map((i) => ({
|
|
1367
|
+
name: i.name,
|
|
1368
|
+
fields: i.fields,
|
|
1369
|
+
unique: i.unique,
|
|
1370
|
+
type: i.type
|
|
1371
|
+
}))
|
|
1372
|
+
}))
|
|
1373
|
+
};
|
|
1374
|
+
return crypto.createHash("sha256").update(JSON.stringify(stable)).digest("hex");
|
|
1375
|
+
};
|
|
1376
|
+
|
|
1377
|
+
// src/cache/util.ts
|
|
1378
|
+
var fireAndForget = (p, onError) => {
|
|
1379
|
+
void p.catch((err) => {
|
|
1380
|
+
if (onError) onError(err);
|
|
1381
|
+
else console.error("[vex:cache]", err);
|
|
1382
|
+
});
|
|
1383
|
+
};
|
|
1384
|
+
var TOUCH_EVERY_MS = 6e4;
|
|
1385
|
+
var isTouchDue = (entry, now) => entry.lastUsedAt === void 0 || now - entry.lastUsedAt >= TOUCH_EVERY_MS;
|
|
1386
|
+
var isEntryFresh = (entry, currentFingerprint) => {
|
|
1387
|
+
const expired = entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
|
|
1388
|
+
const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
|
|
1389
|
+
return !expired && !stale;
|
|
1390
|
+
};
|
|
1391
|
+
var sweepCache = async (cache, options) => {
|
|
1392
|
+
const cutoff = Date.now() - options.maxIdleMs;
|
|
1393
|
+
const rows = cache.entries !== void 0 ? await cache.entries() : await Promise.all((await cache.keys()).map(async (key) => ({ key, entry: await cache.get(key) })));
|
|
1394
|
+
let evicted = 0;
|
|
1395
|
+
for (const { key, entry } of rows) {
|
|
1396
|
+
if (entry === void 0) continue;
|
|
1397
|
+
if (entry.protected === true) continue;
|
|
1398
|
+
const lastAlive = entry.lastUsedAt ?? entry.createdAt;
|
|
1399
|
+
if (lastAlive < cutoff) {
|
|
1400
|
+
await cache.delete(key);
|
|
1401
|
+
evicted += 1;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
return evicted;
|
|
1405
|
+
};
|
|
1406
|
+
var canonical2 = (value) => {
|
|
1407
|
+
if (Array.isArray(value)) return value.map(canonical2);
|
|
1408
|
+
if (value !== null && typeof value === "object" && !(value instanceof Date)) {
|
|
1409
|
+
const sorted = {};
|
|
1410
|
+
for (const [key, inner] of Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) sorted[key] = canonical2(inner);
|
|
1411
|
+
return sorted;
|
|
1412
|
+
}
|
|
1413
|
+
return value;
|
|
1414
|
+
};
|
|
1415
|
+
var canonicalText = (value) => JSON.stringify(canonical2(value)) ?? "undefined";
|
|
1416
|
+
var hashText = (text) => crypto.createHash("sha256").update(text).digest("hex");
|
|
1417
|
+
var canonicalHash = (value) => hashText(canonicalText(value));
|
|
1418
|
+
|
|
1419
|
+
// src/engine/live.ts
|
|
1420
|
+
var DEFAULT_TTL_MS = 6e4;
|
|
1421
|
+
var DEFAULT_MAX_ENTRIES = 5e3;
|
|
1422
|
+
var DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
|
|
1423
|
+
var DEFAULT_DEBOUNCE_MS = 10;
|
|
1424
|
+
var THRASH_WINDOW_MS = 6e4;
|
|
1425
|
+
var THRASH_FLOOR = 100;
|
|
1426
|
+
var unref = (timer) => {
|
|
1427
|
+
if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") timer.unref();
|
|
1428
|
+
};
|
|
1429
|
+
var createLiveRows = (config = {}, emit = () => {
|
|
1430
|
+
}, now = Date.now) => {
|
|
1431
|
+
const ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;
|
|
1432
|
+
const maxEntries = config.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
1433
|
+
const maxBytes = config.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
1434
|
+
const maxEntryBytes = config.maxEntryBytes ?? Math.floor(maxBytes / 10);
|
|
1435
|
+
const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
1436
|
+
const versions = /* @__PURE__ */ new Map();
|
|
1437
|
+
const versionOf = (table) => versions.get(table) ?? 0;
|
|
1438
|
+
const snapshot = (tables) => tables.map(versionOf);
|
|
1439
|
+
const unchanged = (tables, seen) => tables.every((table, i) => versionOf(table) === seen[i]);
|
|
1440
|
+
const stored = /* @__PURE__ */ new Map();
|
|
1441
|
+
let bytes = 0;
|
|
1442
|
+
const flights = /* @__PURE__ */ new Map();
|
|
1443
|
+
const follows = /* @__PURE__ */ new Map();
|
|
1444
|
+
const followsByTable = /* @__PURE__ */ new Map();
|
|
1445
|
+
const counts = { hits: 0, misses: 0, evictions: 0, oversized: 0, refreshes: 0 };
|
|
1446
|
+
const thrash = { start: now(), hits: 0, evictions: 0, warned: 0 };
|
|
1447
|
+
const drop = (key) => {
|
|
1448
|
+
const entry = stored.get(key);
|
|
1449
|
+
if (entry === void 0) return;
|
|
1450
|
+
stored.delete(key);
|
|
1451
|
+
bytes -= entry.bytes;
|
|
1452
|
+
};
|
|
1453
|
+
const noteEviction = () => {
|
|
1454
|
+
const at = now();
|
|
1455
|
+
if (at - thrash.start > THRASH_WINDOW_MS) {
|
|
1456
|
+
thrash.start = at;
|
|
1457
|
+
thrash.hits = 0;
|
|
1458
|
+
thrash.evictions = 0;
|
|
1459
|
+
}
|
|
1460
|
+
thrash.evictions += 1;
|
|
1461
|
+
if (thrash.evictions >= THRASH_FLOOR && thrash.evictions > thrash.hits && at - thrash.warned > THRASH_WINDOW_MS) {
|
|
1462
|
+
thrash.warned = at;
|
|
1463
|
+
console.warn(
|
|
1464
|
+
`[vex:rows] evicting faster than answering (${thrash.evictions} evictions, ${thrash.hits} hits this minute) \u2014 raise the engine's rows.maxBytes / rows.maxEntries.`
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
const store = (key, rows, tables, seen) => {
|
|
1469
|
+
drop(key);
|
|
1470
|
+
const size = (JSON.stringify(rows) ?? "").length;
|
|
1471
|
+
if (size > maxEntryBytes) {
|
|
1472
|
+
counts.oversized += 1;
|
|
1473
|
+
emit({ type: "rows.evict", reason: "oversized", bytes: size });
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
stored.set(key, { rows, bytes: size, tables, seen, at: now() });
|
|
1477
|
+
bytes += size;
|
|
1478
|
+
while (stored.size > maxEntries || bytes > maxBytes) {
|
|
1479
|
+
const oldest = stored.keys().next();
|
|
1480
|
+
if (oldest.done === true) break;
|
|
1481
|
+
const evicted = stored.get(oldest.value);
|
|
1482
|
+
drop(oldest.value);
|
|
1483
|
+
counts.evictions += 1;
|
|
1484
|
+
emit({ type: "rows.evict", reason: "capacity", bytes: evicted?.bytes ?? 0 });
|
|
1485
|
+
noteEviction();
|
|
1486
|
+
}
|
|
1487
|
+
};
|
|
1488
|
+
const read = (key, source) => {
|
|
1489
|
+
const hit = stored.get(key);
|
|
1490
|
+
if (hit !== void 0) {
|
|
1491
|
+
if (now() - hit.at < ttlMs && unchanged(hit.tables, hit.seen)) {
|
|
1492
|
+
stored.delete(key);
|
|
1493
|
+
stored.set(key, hit);
|
|
1494
|
+
counts.hits += 1;
|
|
1495
|
+
thrash.hits += 1;
|
|
1496
|
+
return Promise.resolve(hit.rows);
|
|
1497
|
+
}
|
|
1498
|
+
drop(key);
|
|
1499
|
+
}
|
|
1500
|
+
counts.misses += 1;
|
|
1501
|
+
const flight = flights.get(key);
|
|
1502
|
+
if (flight !== void 0 && unchanged(flight.tables, flight.seen)) return flight.promise;
|
|
1503
|
+
const seen = snapshot(source.tables);
|
|
1504
|
+
const promise = source.fetch().then((rows) => {
|
|
1505
|
+
store(key, rows, source.tables, seen);
|
|
1506
|
+
return rows;
|
|
1507
|
+
});
|
|
1508
|
+
const entry = { promise, tables: source.tables, seen };
|
|
1509
|
+
flights.set(key, entry);
|
|
1510
|
+
const settle = () => {
|
|
1511
|
+
if (flights.get(key) === entry) flights.delete(key);
|
|
1512
|
+
};
|
|
1513
|
+
promise.then(settle, settle);
|
|
1514
|
+
return promise;
|
|
1515
|
+
};
|
|
1516
|
+
const dirty = /* @__PURE__ */ new Set();
|
|
1517
|
+
let flushTimer;
|
|
1518
|
+
const schedule = (key) => {
|
|
1519
|
+
dirty.add(key);
|
|
1520
|
+
if (flushTimer !== void 0) return;
|
|
1521
|
+
flushTimer = setTimeout(() => {
|
|
1522
|
+
flushTimer = void 0;
|
|
1523
|
+
const keys = [...dirty];
|
|
1524
|
+
dirty.clear();
|
|
1525
|
+
for (const next of keys) void refresh(next, false);
|
|
1526
|
+
}, debounceMs);
|
|
1527
|
+
unref(flushTimer);
|
|
1528
|
+
};
|
|
1529
|
+
const arm = (key, follow2) => {
|
|
1530
|
+
if (follow2.timer !== void 0) clearTimeout(follow2.timer);
|
|
1531
|
+
if (!Number.isFinite(ttlMs)) return;
|
|
1532
|
+
follow2.timer = setTimeout(() => void refresh(key, true), ttlMs);
|
|
1533
|
+
unref(follow2.timer);
|
|
1534
|
+
};
|
|
1535
|
+
const refresh = async (key, bypass) => {
|
|
1536
|
+
const follow2 = follows.get(key);
|
|
1537
|
+
if (follow2 === void 0) return;
|
|
1538
|
+
follow2.issued += 1;
|
|
1539
|
+
const ticket = follow2.issued;
|
|
1540
|
+
if (bypass) drop(key);
|
|
1541
|
+
let rows;
|
|
1542
|
+
try {
|
|
1543
|
+
rows = await read(key, follow2.source);
|
|
1544
|
+
} catch (err) {
|
|
1545
|
+
emit({ type: "rows.error", message: err instanceof Error ? err.message : String(err) });
|
|
1546
|
+
if (follows.get(key) === follow2) arm(key, follow2);
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
if (follows.get(key) !== follow2 || ticket < follow2.landed) return;
|
|
1550
|
+
follow2.landed = ticket;
|
|
1551
|
+
counts.refreshes += 1;
|
|
1552
|
+
arm(key, follow2);
|
|
1553
|
+
const rowsHash = hashText(JSON.stringify(rows) ?? "");
|
|
1554
|
+
if (rowsHash === follow2.rowsHash) return;
|
|
1555
|
+
follow2.rowsHash = rowsHash;
|
|
1556
|
+
for (const follower of [...follow2.followers]) {
|
|
1557
|
+
try {
|
|
1558
|
+
follower.deliver(rows);
|
|
1559
|
+
} catch (err) {
|
|
1560
|
+
emit({ type: "rows.error", message: err instanceof Error ? err.message : String(err) });
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
const unfollow = (key, follower) => {
|
|
1565
|
+
const follow2 = follows.get(key);
|
|
1566
|
+
if (follow2 === void 0) return;
|
|
1567
|
+
follow2.followers.delete(follower);
|
|
1568
|
+
if (follow2.followers.size > 0) return;
|
|
1569
|
+
follows.delete(key);
|
|
1570
|
+
dirty.delete(key);
|
|
1571
|
+
if (follow2.timer !== void 0) clearTimeout(follow2.timer);
|
|
1572
|
+
for (const table of follow2.source.tables) {
|
|
1573
|
+
const keys = followsByTable.get(table);
|
|
1574
|
+
keys?.delete(key);
|
|
1575
|
+
if (keys !== void 0 && keys.size === 0) followsByTable.delete(table);
|
|
1576
|
+
}
|
|
1577
|
+
};
|
|
1578
|
+
const follow = (key, source, rows, follower, signal) => {
|
|
1579
|
+
if (signal.aborted) return;
|
|
1580
|
+
let existing = follows.get(key);
|
|
1581
|
+
if (existing === void 0) {
|
|
1582
|
+
existing = { source, followers: /* @__PURE__ */ new Set(), rowsHash: hashText(JSON.stringify(rows) ?? ""), issued: 0, landed: 0 };
|
|
1583
|
+
follows.set(key, existing);
|
|
1584
|
+
for (const table of source.tables) {
|
|
1585
|
+
let keys = followsByTable.get(table);
|
|
1586
|
+
if (keys === void 0) {
|
|
1587
|
+
keys = /* @__PURE__ */ new Set();
|
|
1588
|
+
followsByTable.set(table, keys);
|
|
1589
|
+
}
|
|
1590
|
+
keys.add(key);
|
|
1591
|
+
}
|
|
1592
|
+
arm(key, existing);
|
|
1593
|
+
}
|
|
1594
|
+
existing.followers.add(follower);
|
|
1595
|
+
signal.addEventListener("abort", () => unfollow(key, follower), { once: true });
|
|
1596
|
+
};
|
|
1597
|
+
const invalidate = (tables) => {
|
|
1598
|
+
for (const table of tables) versions.set(table, versionOf(table) + 1);
|
|
1599
|
+
for (const table of tables) {
|
|
1600
|
+
for (const key of followsByTable.get(table) ?? []) schedule(key);
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
const stats = () => {
|
|
1604
|
+
let followers = 0;
|
|
1605
|
+
for (const entry of follows.values()) followers += entry.followers.size;
|
|
1606
|
+
return { entries: stored.size, bytes, follows: follows.size, followers, ...counts };
|
|
1607
|
+
};
|
|
1608
|
+
const stop = () => {
|
|
1609
|
+
if (flushTimer !== void 0) clearTimeout(flushTimer);
|
|
1610
|
+
flushTimer = void 0;
|
|
1611
|
+
for (const entry of follows.values()) if (entry.timer !== void 0) clearTimeout(entry.timer);
|
|
1612
|
+
};
|
|
1613
|
+
return { read, follow, invalidate, stats, stop };
|
|
1614
|
+
};
|
|
1615
|
+
var applySortContext = (dsl, context) => {
|
|
1616
|
+
const sortBy = context["sortBy"];
|
|
1617
|
+
if (typeof sortBy !== "string" || sortBy === "") return dsl;
|
|
1618
|
+
const dir = context["sortDir"] === "desc" ? "desc" : "asc";
|
|
1619
|
+
const tiebreakers = (dsl.sort ?? []).filter((entry) => entry.field !== sortBy);
|
|
1620
|
+
return { ...dsl, sort: [{ field: sortBy, dir }, ...tiebreakers] };
|
|
1621
|
+
};
|
|
1622
|
+
var DEFAULT_MAX_NESTING_DEPTH = 2;
|
|
1623
|
+
var DEFAULT_LIMIT = 100;
|
|
1624
|
+
var DEFAULT_MAX_LIMIT = 1e3;
|
|
1625
|
+
var DEFAULT_STATEMENT_TIMEOUT_MS = 1e4;
|
|
1626
|
+
var DEFAULT_UNSATISFIABLE_TTL_MS = 3e5;
|
|
1627
|
+
var DEFAULT_MAX_PRESENCE_VARIANTS = 32;
|
|
1628
|
+
var createQueryEngine = (engineConfig) => {
|
|
1629
|
+
const { adapter, scope: scopePolicy, generateDsl, mapToShape, embed, behaviors } = engineConfig;
|
|
1630
|
+
const emit = engineConfig.onEvent ?? (() => {
|
|
1631
|
+
});
|
|
1632
|
+
const maxNestingDepth = engineConfig.config?.maxNestingDepth ?? DEFAULT_MAX_NESTING_DEPTH;
|
|
1633
|
+
const defaultLimit = engineConfig.config?.defaultLimit ?? DEFAULT_LIMIT;
|
|
1634
|
+
const maxLimit = engineConfig.config?.maxLimit ?? DEFAULT_MAX_LIMIT;
|
|
1635
|
+
const rejectCartesianProducts = engineConfig.config?.rejectCartesianProducts ?? true;
|
|
1636
|
+
const warnUnindexedFilters = engineConfig.config?.warnUnindexedFilters ?? true;
|
|
1637
|
+
const rejectUnindexedFilters = engineConfig.config?.rejectUnindexedFilters ?? false;
|
|
1638
|
+
const unsatisfiableTtlMs = engineConfig.config?.unsatisfiableTtlMs ?? DEFAULT_UNSATISFIABLE_TTL_MS;
|
|
1639
|
+
const analysisConfig = {
|
|
1640
|
+
maxNestingDepth,
|
|
1641
|
+
rejectCartesianProducts,
|
|
1642
|
+
warnUnindexedFilters,
|
|
1643
|
+
rejectUnindexedFilters
|
|
1644
|
+
};
|
|
1645
|
+
const live = createLiveRows(engineConfig.rows, emit);
|
|
1646
|
+
let cachedSchema;
|
|
1647
|
+
let cachedFingerprint;
|
|
1648
|
+
const cache = engineConfig.cache ?? createMemoryCache();
|
|
1649
|
+
const variantsSeen = /* @__PURE__ */ new Map();
|
|
1650
|
+
const maxPresenceVariants = engineConfig.config?.maxPresenceVariants ?? DEFAULT_MAX_PRESENCE_VARIANTS;
|
|
1651
|
+
const noteVariant = (fingerprint, signature, warnings) => {
|
|
1652
|
+
if (fingerprint === void 0 || signature === "") return;
|
|
1653
|
+
let seen = variantsSeen.get(fingerprint);
|
|
1654
|
+
if (seen === void 0) {
|
|
1655
|
+
seen = /* @__PURE__ */ new Set();
|
|
1656
|
+
variantsSeen.set(fingerprint, seen);
|
|
1657
|
+
}
|
|
1658
|
+
if (seen.has(signature)) return;
|
|
1659
|
+
seen.add(signature);
|
|
1660
|
+
if (seen.size > maxPresenceVariants) {
|
|
1661
|
+
warnings.push(
|
|
1662
|
+
`"${fingerprint}" has now compiled ${seen.size} distinct optional-key combinations (limit ${maxPresenceVariants}). An entry answering this many shapes is closer to a query builder than to a question \u2014 consider splitting it.`
|
|
1663
|
+
);
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
1667
|
+
const introspect = async () => {
|
|
1668
|
+
const options = engineConfig.config?.entities !== void 0 ? { entities: engineConfig.config.entities } : void 0;
|
|
1669
|
+
const schema = await adapter.introspect(options);
|
|
1670
|
+
const readLimit = engineConfig.config?.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;
|
|
1671
|
+
if (adapter.limitReads !== void 0 && await adapter.limitReads(readLimit) === "unenforced" && readLimit > 0) {
|
|
1672
|
+
console.warn(`[vex] reads are not bounded: this database cannot enforce statement_timeout (${readLimit}ms asked). Fine for development; production wants Postgres.`);
|
|
1673
|
+
}
|
|
1674
|
+
if (behaviors !== void 0) {
|
|
1675
|
+
const missing = behaviorColumns(behaviors).filter(({ entity, field }) => !schema.entities.some((e) => e.name === entity && e.fields.some((f) => f.name === field)));
|
|
1676
|
+
if (missing.length > 0) {
|
|
1677
|
+
throw new VexError("execution_error", `The behaviors name columns the database does not have: ${missing.map((m) => `${m.entity}.${m.field}`).join(", ")}.`);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
cachedSchema = schema;
|
|
1681
|
+
cachedFingerprint = computeSchemaFingerprint(schema);
|
|
1682
|
+
return schema;
|
|
1683
|
+
};
|
|
1684
|
+
const ensureSchema = () => {
|
|
1685
|
+
if (cachedSchema === void 0) {
|
|
1686
|
+
throw new VexError(
|
|
1687
|
+
"execution_error",
|
|
1688
|
+
"Database schema not loaded. Call introspect() first."
|
|
1689
|
+
);
|
|
1690
|
+
}
|
|
1691
|
+
return cachedSchema;
|
|
1692
|
+
};
|
|
1693
|
+
const runPipeline = (dsl, policyOverride) => {
|
|
1694
|
+
const schema = ensureSchema();
|
|
1695
|
+
let processedDsl = dsl;
|
|
1696
|
+
if (processedDsl.limit === void 0) {
|
|
1697
|
+
processedDsl = { ...processedDsl, limit: defaultLimit };
|
|
1698
|
+
} else if (processedDsl.limit > maxLimit) {
|
|
1699
|
+
processedDsl = { ...processedDsl, limit: maxLimit };
|
|
1700
|
+
}
|
|
1701
|
+
const entities = discoverEntities(processedDsl);
|
|
1702
|
+
const activePolicy = policyOverride ?? scopePolicy;
|
|
1703
|
+
if (activePolicy !== void 0) checkScope(entities, activePolicy);
|
|
1704
|
+
const resolved = resolve(processedDsl, schema);
|
|
1705
|
+
if (activePolicy !== void 0) scopeResolved(resolved, activePolicy);
|
|
1706
|
+
const analysis = analyze(resolved, analysisConfig);
|
|
1707
|
+
if (analysis.errors.length > 0) {
|
|
1708
|
+
throw new VexError(
|
|
1709
|
+
"invalid_dsl",
|
|
1710
|
+
`Analysis failed: ${analysis.errors.join("; ")}`,
|
|
1711
|
+
{ errors: analysis.errors, warnings: analysis.warnings }
|
|
1712
|
+
);
|
|
1713
|
+
}
|
|
1714
|
+
const compiled = adapter.compile(resolved);
|
|
1715
|
+
return { compiled, warnings: analysis.warnings };
|
|
1716
|
+
};
|
|
1717
|
+
const compile2 = (dsl) => runPipeline(pruneOptional(dsl, "all")).compiled;
|
|
1718
|
+
const test = async (dsl, scopeValues) => {
|
|
1719
|
+
try {
|
|
1720
|
+
const testDsl = { ...pruneOptional(dsl, "all"), limit: 5 };
|
|
1721
|
+
const { compiled, warnings } = runPipeline(testDsl);
|
|
1722
|
+
const syntheticContext = buildValidationContext(compiled.contextContract);
|
|
1723
|
+
const scope = scopeValues ?? {};
|
|
1724
|
+
requireScope(compiled, scope);
|
|
1725
|
+
const rows = await executeQuery(compiled, syntheticContext, scope, adapter, embed);
|
|
1726
|
+
return { rows, warnings, errors: [] };
|
|
1727
|
+
} catch (err) {
|
|
1728
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1729
|
+
return { rows: [], warnings: [], errors: [message] };
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
const freshOrEvict = (entry, key) => {
|
|
1733
|
+
if (isEntryFresh(entry, cachedFingerprint)) return true;
|
|
1734
|
+
void cache.delete(key);
|
|
1735
|
+
return false;
|
|
1736
|
+
};
|
|
1737
|
+
const touch = (key, entry) => {
|
|
1738
|
+
const now = Date.now();
|
|
1739
|
+
if (isTouchDue(entry, now)) fireAndForget(cache.set(key, { ...entry, lastUsedAt: now }));
|
|
1740
|
+
};
|
|
1741
|
+
const resolveFingerprint = async (validRequest, hasRequest, requestHash) => {
|
|
1742
|
+
const fp = validRequest.fingerprint;
|
|
1743
|
+
if (fp === void 0) {
|
|
1744
|
+
return { fingerprint: mintFingerprint(), hit: false, replaced: false };
|
|
1745
|
+
}
|
|
1746
|
+
const entry = await cache.get(fp);
|
|
1747
|
+
if (entry?.kind === "mutation") {
|
|
1748
|
+
throw new VexError(
|
|
1749
|
+
"invalid_request",
|
|
1750
|
+
`Fingerprint "${fp}" names a mutation \u2014 the query engine cannot execute writes. Replay it through the vex endpoint.`
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
if (entry?.kind === "ok" && freshOrEvict(entry, fp)) {
|
|
1754
|
+
if (!hasRequest || entry.requestHash === requestHash) {
|
|
1755
|
+
touch(fp, entry);
|
|
1756
|
+
return {
|
|
1757
|
+
fingerprint: fp,
|
|
1758
|
+
dsl: entry.dsl,
|
|
1759
|
+
...entry.prismIr !== void 0 ? { cachedIr: entry.prismIr } : {},
|
|
1760
|
+
...entry.intent !== void 0 ? { intent: entry.intent } : {},
|
|
1761
|
+
...entry.shape !== void 0 ? { shape: entry.shape } : {},
|
|
1762
|
+
...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
|
|
1763
|
+
hit: true,
|
|
1764
|
+
replaced: false
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
if (entry.protected === true) {
|
|
1768
|
+
throw new VexError(
|
|
1769
|
+
"fingerprint_protected",
|
|
1770
|
+
`Fingerprint "${fp}" is protected and this request no longer matches its stored one. Replay it with the fingerprint alone, or use a new name.`
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1773
|
+
return { fingerprint: fp, hit: false, replaced: true };
|
|
1774
|
+
}
|
|
1775
|
+
if (!hasRequest) {
|
|
1776
|
+
throw new VexError("cache_miss", `Unknown fingerprint "${fp}" \u2014 pass intent + shape to (re)generate it.`);
|
|
1777
|
+
}
|
|
1778
|
+
return { fingerprint: fp, hit: false, replaced: false };
|
|
1779
|
+
};
|
|
1780
|
+
const callerOf = (policy, scope, tables) => ({
|
|
1781
|
+
bindings: scopeBindings(behaviors ?? {}, tables, scope),
|
|
1782
|
+
read: async (dsl) => {
|
|
1783
|
+
const { compiled, warnings } = runPipeline(pruneOptional(dsl, "all"), policy);
|
|
1784
|
+
requireScope(compiled, scope);
|
|
1785
|
+
if (compiled.paramSlots.some((slot) => slot.kind === "semantic")) {
|
|
1786
|
+
return { rows: [], sql: compiled.sql, warnings: [...warnings, "Semantic params present \u2014 execution skipped, SQL structure validated only"] };
|
|
1787
|
+
}
|
|
1788
|
+
const params = compiled.paramSlots.map((slot) => slot.kind === "scope" ? scope[slot.key] : null);
|
|
1789
|
+
return { rows: await adapter.execute(compiled, params), sql: compiled.sql, warnings };
|
|
1790
|
+
}
|
|
1791
|
+
});
|
|
1792
|
+
const generateMissingDsl = async (validRequest, flightKey, negKey, entities, policy, scope) => {
|
|
1793
|
+
if (generateDsl === void 0) {
|
|
1794
|
+
throw new VexError("agent_failed", "No query generation function available and no cached query found");
|
|
1795
|
+
}
|
|
1796
|
+
const fullSchema = ensureSchema();
|
|
1797
|
+
const agentSchema = {
|
|
1798
|
+
...fullSchema,
|
|
1799
|
+
entities: fullSchema.entities.filter(
|
|
1800
|
+
(e) => (entities === void 0 || entities.includes(e.name)) && (policy === void 0 || canReadTable(policy, e.name))
|
|
1801
|
+
)
|
|
1802
|
+
};
|
|
1803
|
+
const generate = async () => {
|
|
1804
|
+
try {
|
|
1805
|
+
return await generateDsl(validRequest, agentSchema, callerOf(policy, scope, agentSchema.entities.map((e) => e.name)));
|
|
1806
|
+
} catch (err) {
|
|
1807
|
+
if (err instanceof VexError && err.code === "unsatisfiable") {
|
|
1808
|
+
const now = Date.now();
|
|
1809
|
+
await cache.set(negKey, {
|
|
1810
|
+
kind: "unsatisfiable",
|
|
1811
|
+
reason: err.message,
|
|
1812
|
+
createdAt: now,
|
|
1813
|
+
expiresAt: now + unsatisfiableTtlMs,
|
|
1814
|
+
...validRequest.intent !== void 0 ? { intent: validRequest.intent } : {},
|
|
1815
|
+
shape: validRequest.shape,
|
|
1816
|
+
...cachedFingerprint !== void 0 ? { schemaFingerprint: cachedFingerprint } : {}
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
throw err;
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
const existing = inFlight.get(flightKey);
|
|
1823
|
+
if (existing !== void 0) return existing;
|
|
1824
|
+
const generation = generate();
|
|
1825
|
+
inFlight.set(flightKey, generation);
|
|
1826
|
+
try {
|
|
1827
|
+
return await generation;
|
|
1828
|
+
} finally {
|
|
1829
|
+
inFlight.delete(flightKey);
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
const mapRows = (rows, shape, ir, context, scope) => {
|
|
1833
|
+
const single = !Array.isArray(shape);
|
|
1834
|
+
const source = {
|
|
1835
|
+
result: single ? rows[0] ?? null : rows,
|
|
1836
|
+
context,
|
|
1837
|
+
scope
|
|
1838
|
+
};
|
|
1839
|
+
return prism.execute(ir, source);
|
|
1840
|
+
};
|
|
1841
|
+
const executeAndMap = async (compiled, validRequest, cachedIr, context, scope) => {
|
|
1842
|
+
const execStart = Date.now();
|
|
1843
|
+
const rows = await executeQuery(compiled, context, scope, adapter, embed);
|
|
1844
|
+
const executionMs = Date.now() - execStart;
|
|
1845
|
+
emit({ type: "query.rows", count: rows.length, executionMs });
|
|
1846
|
+
let result = rows;
|
|
1847
|
+
let mappingMs;
|
|
1848
|
+
let mappedIr = cachedIr;
|
|
1849
|
+
if (validRequest.shape !== void 0) {
|
|
1850
|
+
if (cachedIr !== void 0) {
|
|
1851
|
+
const mapStart = Date.now();
|
|
1852
|
+
result = mapRows(rows, validRequest.shape, cachedIr, context, scope);
|
|
1853
|
+
mappingMs = Date.now() - mapStart;
|
|
1854
|
+
} else if (mapToShape !== void 0) {
|
|
1855
|
+
const mapStart = Date.now();
|
|
1856
|
+
const mapped = await mapToShape(rows, validRequest.shape);
|
|
1857
|
+
mappingMs = Date.now() - mapStart;
|
|
1858
|
+
result = mapped.transformed;
|
|
1859
|
+
mappedIr = mapped.ir;
|
|
1860
|
+
}
|
|
1861
|
+
if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
|
|
1862
|
+
}
|
|
1863
|
+
return { result, executionMs, mappingMs, mappedIr };
|
|
1864
|
+
};
|
|
1865
|
+
const execute = async (request, options) => {
|
|
1866
|
+
if (strata.exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${strata.depthRefusal()}`);
|
|
1867
|
+
const parsed = QueryRequestSchema.safeParse(request);
|
|
1868
|
+
if (!parsed.success) {
|
|
1869
|
+
throw new VexError("invalid_request", `Invalid request: ${parsed.error.message}`);
|
|
1870
|
+
}
|
|
1871
|
+
const validRequest = parsed.data;
|
|
1872
|
+
const scope = options?.scope ?? {};
|
|
1873
|
+
const activePolicy = options?.scopePolicy ?? scopePolicy;
|
|
1874
|
+
const t0 = Date.now();
|
|
1875
|
+
const hasRequest = validRequest.shape !== void 0 && validRequest.shape !== null;
|
|
1876
|
+
if (validRequest.fingerprint === void 0 && !hasRequest) {
|
|
1877
|
+
throw new VexError("invalid_request", "Pass a fingerprint (replay) or intent + shape (generate) \u2014 or both (named slot).");
|
|
1878
|
+
}
|
|
1879
|
+
const requestHash = hasRequest ? computeRequestHash(validRequest) : void 0;
|
|
1880
|
+
const flightKey = requestHash !== void 0 ? `${requestHash}:${computePolicyKey(activePolicy)}` : void 0;
|
|
1881
|
+
const negKey = flightKey !== void 0 ? `neg:${flightKey}` : void 0;
|
|
1882
|
+
emit({
|
|
1883
|
+
type: "query.start",
|
|
1884
|
+
intent: validRequest.intent,
|
|
1885
|
+
shape: validRequest.shape,
|
|
1886
|
+
fingerprint: validRequest.fingerprint,
|
|
1887
|
+
entities: options?.entities
|
|
1888
|
+
});
|
|
1889
|
+
const cached = await resolveFingerprint(validRequest, hasRequest, requestHash);
|
|
1890
|
+
emit({ type: "query.cache", hit: cached.hit, fingerprint: cached.fingerprint, replaced: cached.replaced });
|
|
1891
|
+
let dsl = cached.dsl;
|
|
1892
|
+
let agentMs;
|
|
1893
|
+
if (dsl === void 0) {
|
|
1894
|
+
if (options?.locked === true) {
|
|
1895
|
+
throw new VexError("locked", "This endpoint is replay-only \u2014 unknown or changed fingerprints cannot generate here.");
|
|
1896
|
+
}
|
|
1897
|
+
if (flightKey === void 0 || negKey === void 0) {
|
|
1898
|
+
throw new VexError("invalid_request", "Generation needs intent + shape.");
|
|
1899
|
+
}
|
|
1900
|
+
const negative = await cache.get(negKey);
|
|
1901
|
+
if (negative?.kind === "unsatisfiable" && freshOrEvict(negative, negKey)) {
|
|
1902
|
+
emit({ type: "query.error", code: "unsatisfiable", message: negative.reason });
|
|
1903
|
+
throw new VexError("unsatisfiable", negative.reason);
|
|
1904
|
+
}
|
|
1905
|
+
const agentStart = Date.now();
|
|
1906
|
+
dsl = await generateMissingDsl(validRequest, flightKey, negKey, options?.entities, activePolicy, scope);
|
|
1907
|
+
agentMs = Date.now() - agentStart;
|
|
1908
|
+
emit({ type: "query.dsl", dsl, agentMs });
|
|
1909
|
+
}
|
|
1910
|
+
const presence = presenceOf(validRequest.context);
|
|
1911
|
+
const shaped = pruneOptional(applySortContext(dsl, validRequest.context), presence);
|
|
1912
|
+
const { compiled, warnings } = runPipeline(shaped, activePolicy);
|
|
1913
|
+
noteVariant(cached.fingerprint, presenceSignature(dsl, presence), warnings);
|
|
1914
|
+
emit({ type: "query.sql", sql: compiled.sql, warnings });
|
|
1915
|
+
requireScope(compiled, scope);
|
|
1916
|
+
const context = validRequest.context;
|
|
1917
|
+
const missingKeys = findMissingContext(compiled, context);
|
|
1918
|
+
if (missingKeys.length > 0) {
|
|
1919
|
+
return {
|
|
1920
|
+
result: [],
|
|
1921
|
+
meta: {
|
|
1922
|
+
cache: {
|
|
1923
|
+
hit: cached.hit,
|
|
1924
|
+
fingerprint: cached.fingerprint,
|
|
1925
|
+
intent: cached.intent ?? validRequest.intent,
|
|
1926
|
+
...cached.replaced ? { replaced: true } : {}
|
|
1927
|
+
},
|
|
1928
|
+
context: buildContextContract(compiled, optionalKeysOf(dsl)),
|
|
1929
|
+
warnings: warnings.length > 0 ? warnings : void 0,
|
|
1930
|
+
missingContext: missingKeys
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
const effectiveRequest = hasRequest ? validRequest : { ...validRequest, shape: cached.shape };
|
|
1935
|
+
const reactiveIr = cached.cachedIr;
|
|
1936
|
+
if (cached.hit && cached.refresh === "reactive" && (effectiveRequest.shape === void 0 || reactiveIr !== void 0)) {
|
|
1937
|
+
const shape = effectiveRequest.shape;
|
|
1938
|
+
const shapeRows = (rows2) => shape === void 0 || reactiveIr === void 0 ? rows2 : mapRows(rows2, shape, reactiveIr, context, scope);
|
|
1939
|
+
const params = await resolveParams(compiled.paramSlots, context, scope, embed);
|
|
1940
|
+
const key = canonicalHash([compiled.sql, params]);
|
|
1941
|
+
const source = { tables: [...discoverEntities(shaped)], fetch: () => adapter.execute(compiled, params) };
|
|
1942
|
+
const execStart = Date.now();
|
|
1943
|
+
const rows = await live.read(key, source);
|
|
1944
|
+
const executionMs2 = Date.now() - execStart;
|
|
1945
|
+
emit({ type: "query.rows", count: rows.length, executionMs: executionMs2 });
|
|
1946
|
+
const result2 = shapeRows(rows);
|
|
1947
|
+
const meta = {
|
|
1948
|
+
cache: {
|
|
1949
|
+
hit: cached.hit,
|
|
1950
|
+
fingerprint: cached.fingerprint,
|
|
1951
|
+
intent: cached.intent ?? validRequest.intent
|
|
1952
|
+
},
|
|
1953
|
+
context: buildContextContract(compiled, optionalKeysOf(dsl)),
|
|
1954
|
+
warnings: warnings.length > 0 ? warnings : void 0
|
|
1955
|
+
};
|
|
1956
|
+
const { signal, onChange } = options ?? {};
|
|
1957
|
+
if (signal !== void 0 && onChange !== void 0) {
|
|
1958
|
+
let lastHash = canonicalHash(result2);
|
|
1959
|
+
live.follow(key, source, rows, {
|
|
1960
|
+
deliver: (next) => {
|
|
1961
|
+
const nextResult = shapeRows(next);
|
|
1962
|
+
const nextHash = canonicalHash(nextResult);
|
|
1963
|
+
if (nextHash === lastHash) return;
|
|
1964
|
+
lastHash = nextHash;
|
|
1965
|
+
onChange({ result: nextResult, meta });
|
|
1966
|
+
}
|
|
1967
|
+
}, signal);
|
|
1968
|
+
}
|
|
1969
|
+
emit({ type: "query.done", totalMs: Date.now() - t0 });
|
|
1970
|
+
return { result: result2, meta: { ...meta, timing: { executionMs: executionMs2 } } };
|
|
1971
|
+
}
|
|
1972
|
+
const { result, executionMs, mappingMs, mappedIr } = await executeAndMap(
|
|
1973
|
+
compiled,
|
|
1974
|
+
effectiveRequest,
|
|
1975
|
+
cached.cachedIr,
|
|
1976
|
+
context,
|
|
1977
|
+
scope
|
|
1978
|
+
);
|
|
1979
|
+
if (!cached.hit) {
|
|
1980
|
+
const now = Date.now();
|
|
1981
|
+
const entry = {
|
|
1982
|
+
kind: "ok",
|
|
1983
|
+
dsl,
|
|
1984
|
+
...mappedIr !== void 0 ? { prismIr: mappedIr } : {},
|
|
1985
|
+
createdAt: now,
|
|
1986
|
+
lastUsedAt: now,
|
|
1987
|
+
...requestHash !== void 0 ? { requestHash } : {},
|
|
1988
|
+
...validRequest.intent !== void 0 ? { intent: validRequest.intent } : {},
|
|
1989
|
+
shape: validRequest.shape,
|
|
1990
|
+
...cachedFingerprint !== void 0 ? { schemaFingerprint: cachedFingerprint } : {}
|
|
1991
|
+
};
|
|
1992
|
+
await cache.set(cached.fingerprint, entry);
|
|
1993
|
+
}
|
|
1994
|
+
emit({ type: "query.done", totalMs: Date.now() - t0 });
|
|
1995
|
+
return {
|
|
1996
|
+
result,
|
|
1997
|
+
meta: {
|
|
1998
|
+
cache: {
|
|
1999
|
+
hit: cached.hit,
|
|
2000
|
+
fingerprint: cached.fingerprint,
|
|
2001
|
+
intent: cached.intent ?? validRequest.intent,
|
|
2002
|
+
...cached.replaced ? { replaced: true } : {}
|
|
2003
|
+
},
|
|
2004
|
+
context: buildContextContract(compiled, optionalKeysOf(dsl)),
|
|
2005
|
+
timing: {
|
|
2006
|
+
...agentMs !== void 0 ? { agentMs } : {},
|
|
2007
|
+
executionMs,
|
|
2008
|
+
...mappingMs !== void 0 ? { mappingMs } : {}
|
|
2009
|
+
},
|
|
2010
|
+
warnings: warnings.length > 0 ? warnings : void 0
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
};
|
|
2014
|
+
const getDslSchema = () => zod.z.toJSONSchema(QuerySchema, { target: "draft-7", reused: "ref" });
|
|
2015
|
+
const getSchema = () => cachedSchema;
|
|
2016
|
+
return {
|
|
2017
|
+
introspect,
|
|
2018
|
+
execute,
|
|
2019
|
+
compile: compile2,
|
|
2020
|
+
test,
|
|
2021
|
+
getDslSchema,
|
|
2022
|
+
getSchema,
|
|
2023
|
+
cache,
|
|
2024
|
+
invalidate: live.invalidate,
|
|
2025
|
+
rows: { stats: live.stats, stop: live.stop }
|
|
2026
|
+
};
|
|
2027
|
+
};
|
|
2028
|
+
|
|
2029
|
+
// src/adapters/postgres/introspect.ts
|
|
2030
|
+
var normalizeType = (pgType) => {
|
|
2031
|
+
const lower = pgType.toLowerCase();
|
|
2032
|
+
if (lower.startsWith("varchar") || lower.startsWith("character varying") || lower === "text" || lower.startsWith("char") || lower === "name" || lower === "citext") {
|
|
2033
|
+
return "string";
|
|
2034
|
+
}
|
|
2035
|
+
if (lower === "integer" || lower === "int" || lower === "bigint" || lower === "smallint" || lower === "serial" || lower === "bigserial" || lower === "smallserial" || lower === "numeric" || lower.startsWith("numeric") || lower === "decimal" || lower.startsWith("decimal") || lower === "real" || lower === "double precision" || lower === "float" || lower.startsWith("float")) {
|
|
2036
|
+
return "number";
|
|
2037
|
+
}
|
|
2038
|
+
if (lower === "boolean" || lower === "bool") return "boolean";
|
|
2039
|
+
if (lower === "date") return "date";
|
|
2040
|
+
if (lower.startsWith("timestamp")) return "timestamp";
|
|
2041
|
+
if (lower === "uuid") return "uuid";
|
|
2042
|
+
if (lower === "json" || lower === "jsonb") return "json";
|
|
2043
|
+
if (lower === "array" || lower.endsWith("[]") || lower.startsWith("_")) return "array";
|
|
2044
|
+
if (lower === "vector" || lower.startsWith("vector")) return "vector";
|
|
2045
|
+
return "unknown";
|
|
2046
|
+
};
|
|
2047
|
+
var extractVectorDimensions = (pgType) => {
|
|
2048
|
+
const match = /vector\((\d+)\)/i.exec(pgType);
|
|
2049
|
+
if (match !== null && match[1] !== void 0) {
|
|
2050
|
+
return parseInt(match[1], 10);
|
|
2051
|
+
}
|
|
2052
|
+
return void 0;
|
|
2053
|
+
};
|
|
2054
|
+
var TABLES_QUERY = `
|
|
2055
|
+
SELECT t.table_name, obj_description(cl.oid, 'pg_class') AS description
|
|
2056
|
+
FROM information_schema.tables t
|
|
2057
|
+
JOIN pg_namespace ns ON ns.nspname = t.table_schema
|
|
2058
|
+
JOIN pg_class cl ON cl.relname = t.table_name AND cl.relnamespace = ns.oid
|
|
2059
|
+
WHERE t.table_schema = $1
|
|
2060
|
+
AND t.table_type = 'BASE TABLE'
|
|
2061
|
+
ORDER BY t.table_name
|
|
2062
|
+
`;
|
|
2063
|
+
var COLUMNS_QUERY = `
|
|
2064
|
+
SELECT
|
|
2065
|
+
c.table_name,
|
|
2066
|
+
c.column_name,
|
|
2067
|
+
c.data_type,
|
|
2068
|
+
c.udt_name,
|
|
2069
|
+
c.is_nullable,
|
|
2070
|
+
c.column_default,
|
|
2071
|
+
CASE
|
|
2072
|
+
WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name
|
|
2073
|
+
WHEN c.data_type = 'ARRAY' THEN c.udt_name
|
|
2074
|
+
ELSE c.data_type
|
|
2075
|
+
END AS effective_type,
|
|
2076
|
+
COALESCE(
|
|
2077
|
+
(SELECT format_type(a.atttypid, a.atttypmod)
|
|
2078
|
+
FROM pg_attribute a
|
|
2079
|
+
JOIN pg_class cl ON a.attrelid = cl.oid
|
|
2080
|
+
JOIN pg_namespace ns ON cl.relnamespace = ns.oid
|
|
2081
|
+
WHERE cl.relname = c.table_name
|
|
2082
|
+
AND ns.nspname = $1
|
|
2083
|
+
AND a.attname = c.column_name
|
|
2084
|
+
AND a.attnum > 0),
|
|
2085
|
+
c.data_type
|
|
2086
|
+
) AS full_type,
|
|
2087
|
+
(SELECT col_description(a.attrelid, a.attnum)
|
|
2088
|
+
FROM pg_attribute a
|
|
2089
|
+
JOIN pg_class cl ON a.attrelid = cl.oid
|
|
2090
|
+
JOIN pg_namespace ns ON cl.relnamespace = ns.oid
|
|
2091
|
+
WHERE cl.relname = c.table_name
|
|
2092
|
+
AND ns.nspname = $1
|
|
2093
|
+
AND a.attname = c.column_name
|
|
2094
|
+
AND a.attnum > 0) AS description
|
|
2095
|
+
FROM information_schema.columns c
|
|
2096
|
+
WHERE c.table_schema = $1
|
|
2097
|
+
ORDER BY c.table_name, c.ordinal_position
|
|
2098
|
+
`;
|
|
2099
|
+
var CONSTRAINTS_QUERY = `
|
|
2100
|
+
SELECT
|
|
2101
|
+
c.contype::text AS kind,
|
|
2102
|
+
rel.relname AS from_table,
|
|
2103
|
+
frel.relname AS to_table,
|
|
2104
|
+
array_agg(a.attname ORDER BY k.n)::text[] AS from_columns,
|
|
2105
|
+
array_agg(fa.attname ORDER BY k.n)::text[] AS to_columns
|
|
2106
|
+
FROM pg_constraint c
|
|
2107
|
+
JOIN pg_class rel ON rel.oid = c.conrelid
|
|
2108
|
+
JOIN pg_namespace ns ON ns.oid = rel.relnamespace
|
|
2109
|
+
LEFT JOIN pg_class frel ON frel.oid = c.confrelid AND frel.relnamespace = rel.relnamespace
|
|
2110
|
+
CROSS JOIN LATERAL unnest(c.conkey, c.confkey) WITH ORDINALITY AS k(attnum, fattnum, n)
|
|
2111
|
+
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
|
|
2112
|
+
LEFT JOIN pg_attribute fa ON fa.attrelid = c.confrelid AND fa.attnum = k.fattnum
|
|
2113
|
+
WHERE ns.nspname = $1
|
|
2114
|
+
AND c.contype IN ('p', 'u', 'f')
|
|
2115
|
+
GROUP BY c.oid, c.contype, rel.relname, frel.relname
|
|
2116
|
+
ORDER BY c.oid
|
|
2117
|
+
`;
|
|
2118
|
+
var INDEXES_QUERY = `
|
|
2119
|
+
SELECT
|
|
2120
|
+
i.tablename AS table_name,
|
|
2121
|
+
i.indexname AS index_name,
|
|
2122
|
+
ix.indisunique AS is_unique,
|
|
2123
|
+
am.amname AS index_type,
|
|
2124
|
+
array_agg(a.attname ORDER BY k.n)::text[] AS columns
|
|
2125
|
+
FROM pg_indexes i
|
|
2126
|
+
JOIN pg_class c ON c.relname = i.indexname
|
|
2127
|
+
JOIN pg_index ix ON ix.indexrelid = c.oid
|
|
2128
|
+
JOIN pg_am am ON am.oid = c.relam
|
|
2129
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n)
|
|
2130
|
+
JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum
|
|
2131
|
+
WHERE i.schemaname = $1
|
|
2132
|
+
GROUP BY i.tablename, i.indexname, ix.indisunique, am.amname
|
|
2133
|
+
ORDER BY i.tablename, i.indexname
|
|
2134
|
+
`;
|
|
2135
|
+
var ROW_COUNTS_QUERY = `
|
|
2136
|
+
SELECT
|
|
2137
|
+
relname AS table_name,
|
|
2138
|
+
n_live_tup AS row_count
|
|
2139
|
+
FROM pg_stat_user_tables
|
|
2140
|
+
WHERE schemaname = $1
|
|
2141
|
+
`;
|
|
2142
|
+
var introspectPostgres = async (pool, options) => {
|
|
2143
|
+
const schemaName = options?.schema ?? "public";
|
|
2144
|
+
const [tablesResult, columnsResult, keysResult, indexesResult, rowCountsResult] = await Promise.all([
|
|
2145
|
+
pool.query(TABLES_QUERY, [schemaName]),
|
|
2146
|
+
pool.query(COLUMNS_QUERY, [schemaName]),
|
|
2147
|
+
pool.query(CONSTRAINTS_QUERY, [schemaName]),
|
|
2148
|
+
pool.query(INDEXES_QUERY, [schemaName]),
|
|
2149
|
+
pool.query(ROW_COUNTS_QUERY, [schemaName])
|
|
2150
|
+
]);
|
|
2151
|
+
const keys = keysResult.rows.map((row) => ({
|
|
2152
|
+
kind: row["kind"],
|
|
2153
|
+
fromTable: row["from_table"],
|
|
2154
|
+
toTable: row["to_table"] ?? null,
|
|
2155
|
+
fromColumns: row["from_columns"],
|
|
2156
|
+
toColumns: row["to_columns"]
|
|
2157
|
+
}));
|
|
2158
|
+
const pkMap = /* @__PURE__ */ new Map();
|
|
2159
|
+
const uniqueSets = /* @__PURE__ */ new Map();
|
|
2160
|
+
for (const key of keys) {
|
|
2161
|
+
if (key.kind === "f") continue;
|
|
2162
|
+
if (key.kind === "p") {
|
|
2163
|
+
let cols = pkMap.get(key.fromTable);
|
|
2164
|
+
if (cols === void 0) {
|
|
2165
|
+
cols = /* @__PURE__ */ new Set();
|
|
2166
|
+
pkMap.set(key.fromTable, cols);
|
|
2167
|
+
}
|
|
2168
|
+
for (const col of key.fromColumns) cols.add(col);
|
|
2169
|
+
}
|
|
2170
|
+
let sets = uniqueSets.get(key.fromTable);
|
|
2171
|
+
if (sets === void 0) {
|
|
2172
|
+
sets = [];
|
|
2173
|
+
uniqueSets.set(key.fromTable, sets);
|
|
2174
|
+
}
|
|
2175
|
+
sets.push(key.fromColumns);
|
|
2176
|
+
}
|
|
2177
|
+
const rowCountMap = /* @__PURE__ */ new Map();
|
|
2178
|
+
for (const row of rowCountsResult.rows) {
|
|
2179
|
+
const table = row["table_name"];
|
|
2180
|
+
const count = Number(row["row_count"] ?? 0);
|
|
2181
|
+
rowCountMap.set(table, count);
|
|
2182
|
+
}
|
|
2183
|
+
const columnsByTable = /* @__PURE__ */ new Map();
|
|
2184
|
+
for (const row of columnsResult.rows) {
|
|
2185
|
+
const table = row["table_name"];
|
|
2186
|
+
const colName = row["column_name"];
|
|
2187
|
+
const dataType = row["effective_type"];
|
|
2188
|
+
const fullType = row["full_type"];
|
|
2189
|
+
const isNullable = row["is_nullable"];
|
|
2190
|
+
const colDefault = row["column_default"];
|
|
2191
|
+
const colDescription = row["description"];
|
|
2192
|
+
const tablePks = pkMap.get(table);
|
|
2193
|
+
const isPk = tablePks !== void 0 && tablePks.has(colName);
|
|
2194
|
+
const nt = normalizeType(fullType ?? dataType);
|
|
2195
|
+
const vecDims = nt === "vector" ? extractVectorDimensions(fullType ?? dataType) : void 0;
|
|
2196
|
+
const field = {
|
|
2197
|
+
name: colName,
|
|
2198
|
+
type: fullType ?? dataType,
|
|
2199
|
+
normalizedType: nt,
|
|
2200
|
+
nullable: isNullable === "YES",
|
|
2201
|
+
primaryKey: isPk,
|
|
2202
|
+
...colDefault !== null ? { defaultValue: colDefault } : {},
|
|
2203
|
+
...colDescription !== null && colDescription !== "" ? { description: colDescription } : {},
|
|
2204
|
+
...vecDims !== void 0 ? { vectorDimensions: vecDims } : {}
|
|
2205
|
+
};
|
|
2206
|
+
let fields = columnsByTable.get(table);
|
|
2207
|
+
if (fields === void 0) {
|
|
2208
|
+
fields = [];
|
|
2209
|
+
columnsByTable.set(table, fields);
|
|
2210
|
+
}
|
|
2211
|
+
fields.push(field);
|
|
2212
|
+
}
|
|
2213
|
+
const relationsByTable = /* @__PURE__ */ new Map();
|
|
2214
|
+
const addRelation = (table, relation) => {
|
|
2215
|
+
let rels = relationsByTable.get(table);
|
|
2216
|
+
if (rels === void 0) {
|
|
2217
|
+
rels = [];
|
|
2218
|
+
relationsByTable.set(table, rels);
|
|
2219
|
+
}
|
|
2220
|
+
rels.push(relation);
|
|
2221
|
+
};
|
|
2222
|
+
for (const key of keys) {
|
|
2223
|
+
if (key.kind !== "f" || key.toTable === null) continue;
|
|
2224
|
+
const foreignFields = key.toColumns.filter((col) => col !== null);
|
|
2225
|
+
if (foreignFields.length !== key.fromColumns.length) continue;
|
|
2226
|
+
const isFkUnique = (uniqueSets.get(key.fromTable) ?? []).some(
|
|
2227
|
+
(set) => set.every((col) => key.fromColumns.includes(col))
|
|
2228
|
+
);
|
|
2229
|
+
addRelation(key.fromTable, {
|
|
2230
|
+
type: "belongsTo",
|
|
2231
|
+
entity: key.toTable,
|
|
2232
|
+
localFields: key.fromColumns,
|
|
2233
|
+
foreignFields
|
|
2234
|
+
});
|
|
2235
|
+
addRelation(key.toTable, {
|
|
2236
|
+
type: isFkUnique ? "hasOne" : "hasMany",
|
|
2237
|
+
entity: key.fromTable,
|
|
2238
|
+
localFields: foreignFields,
|
|
2239
|
+
foreignFields: key.fromColumns
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
const indexesByTable = /* @__PURE__ */ new Map();
|
|
2243
|
+
for (const row of indexesResult.rows) {
|
|
2244
|
+
const table = row["table_name"];
|
|
2245
|
+
const indexName = row["index_name"];
|
|
2246
|
+
const isUnique = row["is_unique"];
|
|
2247
|
+
const indexType = row["index_type"];
|
|
2248
|
+
const columns = row["columns"];
|
|
2249
|
+
const mappedType = mapIndexType(indexType);
|
|
2250
|
+
const idx = {
|
|
2251
|
+
name: indexName,
|
|
2252
|
+
fields: columns,
|
|
2253
|
+
unique: isUnique,
|
|
2254
|
+
type: mappedType
|
|
2255
|
+
};
|
|
2256
|
+
let idxList = indexesByTable.get(table);
|
|
2257
|
+
if (idxList === void 0) {
|
|
2258
|
+
idxList = [];
|
|
2259
|
+
indexesByTable.set(table, idxList);
|
|
2260
|
+
}
|
|
2261
|
+
idxList.push(idx);
|
|
2262
|
+
}
|
|
2263
|
+
const filteredTables = tablesResult.rows.filter((row) => {
|
|
2264
|
+
const name = row["table_name"];
|
|
2265
|
+
if (options?.entities !== void 0 && !options.entities.includes(name)) return false;
|
|
2266
|
+
if (options?.exclude !== void 0 && options.exclude.includes(name)) return false;
|
|
2267
|
+
return true;
|
|
2268
|
+
});
|
|
2269
|
+
const entities = filteredTables.map((row) => {
|
|
2270
|
+
const tableName = row["table_name"];
|
|
2271
|
+
const tableDescription = row["description"];
|
|
2272
|
+
return {
|
|
2273
|
+
name: tableName,
|
|
2274
|
+
table: tableName,
|
|
2275
|
+
...tableDescription !== null && tableDescription !== "" ? { description: tableDescription } : {},
|
|
2276
|
+
fields: columnsByTable.get(tableName) ?? [],
|
|
2277
|
+
relations: relationsByTable.get(tableName) ?? [],
|
|
2278
|
+
indexes: indexesByTable.get(tableName) ?? [],
|
|
2279
|
+
rowCount: rowCountMap.get(tableName)
|
|
2280
|
+
};
|
|
2281
|
+
});
|
|
2282
|
+
return { entities };
|
|
2283
|
+
};
|
|
2284
|
+
var mapIndexType = (pgType) => {
|
|
2285
|
+
const lower = pgType.toLowerCase();
|
|
2286
|
+
if (lower === "btree") return "btree";
|
|
2287
|
+
if (lower === "hash") return "hash";
|
|
2288
|
+
if (lower === "gin") return "gin";
|
|
2289
|
+
if (lower === "gist") return "gist";
|
|
2290
|
+
if (lower === "ivfflat") return "ivfflat";
|
|
2291
|
+
if (lower === "hnsw") return "hnsw";
|
|
2292
|
+
return "other";
|
|
2293
|
+
};
|
|
2294
|
+
|
|
2295
|
+
// src/adapters/postgres/operators.ts
|
|
2296
|
+
var assertNotReserved = (key) => {
|
|
2297
|
+
if (RESERVED_CONTEXT_KEYS.has(key))
|
|
2298
|
+
throw new VexError(
|
|
2299
|
+
"invalid_dsl",
|
|
2300
|
+
`"${key}" is a reserved sort key (applied to ORDER BY); it cannot be bound as a parameter.`
|
|
2301
|
+
);
|
|
2302
|
+
};
|
|
2303
|
+
var quoteLiteral = (s) => {
|
|
2304
|
+
const doubled = s.replace(/'/g, "''");
|
|
2305
|
+
return s.includes("\\") ? `E'${doubled.replace(/\\/g, "\\\\")}'` : `'${doubled}'`;
|
|
2306
|
+
};
|
|
2307
|
+
var quoteIdent = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
2308
|
+
var numberLiteral = (n) => {
|
|
2309
|
+
if (!Number.isFinite(n)) throw new VexError("invalid_dsl", `${String(n)} is not a number SQL can hold.`);
|
|
2310
|
+
return String(n);
|
|
2311
|
+
};
|
|
2312
|
+
var columnOf = (path, ctx) => {
|
|
2313
|
+
const mapped = ctx.aliasMap.get(path);
|
|
2314
|
+
if (mapped !== void 0) return mapped;
|
|
2315
|
+
const res = ctx.resolvedPaths.get(path);
|
|
2316
|
+
if (res !== void 0) return `${res.alias}.${res.column}`;
|
|
2317
|
+
throw new VexError("invalid_dsl", `"${path}" is not a column this query reads.`);
|
|
2318
|
+
};
|
|
2319
|
+
var isFieldPath2 = isFieldPathShape;
|
|
2320
|
+
var inferParamType = (path, resolvedPaths) => {
|
|
2321
|
+
const res = resolvedPaths.get(path);
|
|
2322
|
+
if (res === void 0) return "string";
|
|
2323
|
+
const nt = res.schema.normalizedType;
|
|
2324
|
+
if (nt === "number") return "number";
|
|
2325
|
+
if (nt === "boolean") return "boolean";
|
|
2326
|
+
return "string";
|
|
2327
|
+
};
|
|
2328
|
+
var compileFieldOrValue = (fov, ctx) => {
|
|
2329
|
+
if (fov === null) return "NULL";
|
|
2330
|
+
if (typeof fov === "boolean") return fov ? "TRUE" : "FALSE";
|
|
2331
|
+
if (typeof fov === "number") return numberLiteral(fov);
|
|
2332
|
+
if (typeof fov === "string") {
|
|
2333
|
+
return isFieldPath2(fov) ? columnOf(fov, ctx) : quoteLiteral(fov);
|
|
2334
|
+
}
|
|
2335
|
+
if (typeof fov === "object" && fov !== null && "$context" in fov) {
|
|
2336
|
+
const key = fov.$context;
|
|
2337
|
+
assertNotReserved(key);
|
|
2338
|
+
ctx.paramCounter.value += 1;
|
|
2339
|
+
ctx.paramSlots.push({
|
|
2340
|
+
key,
|
|
2341
|
+
kind: "context",
|
|
2342
|
+
type: inferParamType(key, ctx.resolvedPaths)
|
|
2343
|
+
});
|
|
2344
|
+
return `$${ctx.paramCounter.value}`;
|
|
2345
|
+
}
|
|
2346
|
+
if (typeof fov === "object" && fov !== null && "$scope" in fov) {
|
|
2347
|
+
const key = fov.$scope;
|
|
2348
|
+
ctx.paramCounter.value += 1;
|
|
2349
|
+
ctx.paramSlots.push({
|
|
2350
|
+
key,
|
|
2351
|
+
kind: "scope",
|
|
2352
|
+
type: inferParamType(key, ctx.resolvedPaths)
|
|
2353
|
+
});
|
|
2354
|
+
return `$${ctx.paramCounter.value}`;
|
|
2355
|
+
}
|
|
2356
|
+
return "NULL";
|
|
2357
|
+
};
|
|
2358
|
+
var compileJoinPairs = (join) => join.fromColumns.map((column, i) => {
|
|
2359
|
+
const to = join.toColumns[i];
|
|
2360
|
+
if (to === void 0) {
|
|
2361
|
+
throw new VexError(
|
|
2362
|
+
"invalid_dsl",
|
|
2363
|
+
`The join from "${join.fromAlias}" to "${join.toAlias}" pairs "${column}" with no column.`
|
|
2364
|
+
);
|
|
2365
|
+
}
|
|
2366
|
+
return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;
|
|
2367
|
+
});
|
|
2368
|
+
var compileComparisonFilter = (op, pair, ctx) => {
|
|
2369
|
+
const left = compileFieldOrValue(pair[0], ctx);
|
|
2370
|
+
const right = compileFieldOrValue(pair[1], ctx);
|
|
2371
|
+
return `${left} ${op} ${right}`;
|
|
2372
|
+
};
|
|
2373
|
+
var compileFilter = (filter, ctx) => {
|
|
2374
|
+
if ("exists" in filter) {
|
|
2375
|
+
const resolved = ctx.existsMap?.get(filter.exists);
|
|
2376
|
+
if (resolved === void 0) throw new VexError("invalid_dsl", `An "exists" filter was not resolved. It must appear in a query's own filter.`);
|
|
2377
|
+
const inner = {
|
|
2378
|
+
...ctx,
|
|
2379
|
+
resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,
|
|
2380
|
+
// The inner map LAYERS OVER the outer one, so an inner path resolves to
|
|
2381
|
+
// the inner alias and an outer path — the correlation — still resolves.
|
|
2382
|
+
aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap])
|
|
2383
|
+
};
|
|
2384
|
+
const parts = ["SELECT 1"];
|
|
2385
|
+
const first = resolved.sources[0];
|
|
2386
|
+
if (first?.table !== void 0) parts.push(`FROM ${first.table} AS ${first.alias}`);
|
|
2387
|
+
for (const join of resolved.joins) {
|
|
2388
|
+
const source = resolved.sources.find((s) => s.alias === join.toAlias);
|
|
2389
|
+
if (source?.table === void 0) continue;
|
|
2390
|
+
const keyword = join.kind === "left" ? "LEFT JOIN" : "JOIN";
|
|
2391
|
+
const conditions = [
|
|
2392
|
+
...compileJoinPairs(join),
|
|
2393
|
+
...(join.on ?? []).map((extra) => compileFilter(extra.original, inner))
|
|
2394
|
+
];
|
|
2395
|
+
parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(" AND ")}`);
|
|
2396
|
+
}
|
|
2397
|
+
if (resolved.filter !== void 0) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);
|
|
2398
|
+
return `EXISTS (${parts.join(" ")})`;
|
|
2399
|
+
}
|
|
2400
|
+
if ("eq" in filter) return compileComparisonFilter("=", filter.eq, ctx);
|
|
2401
|
+
if ("neq" in filter) return compileComparisonFilter("<>", filter.neq, ctx);
|
|
2402
|
+
if ("gt" in filter) return compileComparisonFilter(">", filter.gt, ctx);
|
|
2403
|
+
if ("gte" in filter) return compileComparisonFilter(">=", filter.gte, ctx);
|
|
2404
|
+
if ("lt" in filter) return compileComparisonFilter("<", filter.lt, ctx);
|
|
2405
|
+
if ("lte" in filter) return compileComparisonFilter("<=", filter.lte, ctx);
|
|
2406
|
+
if ("in" in filter) {
|
|
2407
|
+
const col = columnOf(filter.in[0], ctx);
|
|
2408
|
+
const target = filter.in[1];
|
|
2409
|
+
if (Array.isArray(target)) {
|
|
2410
|
+
const values = target.map((v) => compileFieldOrValue(v, ctx));
|
|
2411
|
+
return `${col} IN (${values.join(", ")})`;
|
|
2412
|
+
}
|
|
2413
|
+
if ("$context" in target) {
|
|
2414
|
+
assertNotReserved(target.$context);
|
|
2415
|
+
ctx.paramCounter.value += 1;
|
|
2416
|
+
ctx.paramSlots.push({ key: target.$context, kind: "context", type: "string[]" });
|
|
2417
|
+
return `${col} = ANY($${ctx.paramCounter.value})`;
|
|
2418
|
+
}
|
|
2419
|
+
if ("$scope" in target) {
|
|
2420
|
+
ctx.paramCounter.value += 1;
|
|
2421
|
+
ctx.paramSlots.push({ key: target.$scope, kind: "scope", type: "string[]" });
|
|
2422
|
+
return `${col} = ANY($${ctx.paramCounter.value})`;
|
|
2423
|
+
}
|
|
2424
|
+
return `${col} IN ()`;
|
|
2425
|
+
}
|
|
2426
|
+
if ("notIn" in filter) {
|
|
2427
|
+
const col = columnOf(filter.notIn[0], ctx);
|
|
2428
|
+
const target = filter.notIn[1];
|
|
2429
|
+
if (Array.isArray(target)) {
|
|
2430
|
+
const values = target.map((v) => compileFieldOrValue(v, ctx));
|
|
2431
|
+
return `${col} NOT IN (${values.join(", ")})`;
|
|
2432
|
+
}
|
|
2433
|
+
if ("$context" in target) {
|
|
2434
|
+
assertNotReserved(target.$context);
|
|
2435
|
+
ctx.paramCounter.value += 1;
|
|
2436
|
+
ctx.paramSlots.push({ key: target.$context, kind: "context", type: "string[]" });
|
|
2437
|
+
return `${col} <> ALL($${ctx.paramCounter.value})`;
|
|
2438
|
+
}
|
|
2439
|
+
if ("$scope" in target) {
|
|
2440
|
+
ctx.paramCounter.value += 1;
|
|
2441
|
+
ctx.paramSlots.push({ key: target.$scope, kind: "scope", type: "string[]" });
|
|
2442
|
+
return `${col} <> ALL($${ctx.paramCounter.value})`;
|
|
2443
|
+
}
|
|
2444
|
+
return `${col} NOT IN ()`;
|
|
2445
|
+
}
|
|
2446
|
+
if ("like" in filter) {
|
|
2447
|
+
const col = columnOf(filter.like[0], ctx);
|
|
2448
|
+
const pattern = compileFieldOrValue(filter.like[1], ctx);
|
|
2449
|
+
return `${col} LIKE ${pattern}`;
|
|
2450
|
+
}
|
|
2451
|
+
if ("ilike" in filter) {
|
|
2452
|
+
const col = columnOf(filter.ilike[0], ctx);
|
|
2453
|
+
const pattern = compileFieldOrValue(filter.ilike[1], ctx);
|
|
2454
|
+
return `${col} ILIKE ${pattern}`;
|
|
2455
|
+
}
|
|
2456
|
+
if ("isNull" in filter) {
|
|
2457
|
+
return `${columnOf(filter.isNull, ctx)} IS NULL`;
|
|
2458
|
+
}
|
|
2459
|
+
if ("isNotNull" in filter) {
|
|
2460
|
+
return `${columnOf(filter.isNotNull, ctx)} IS NOT NULL`;
|
|
2461
|
+
}
|
|
2462
|
+
if ("and" in filter) {
|
|
2463
|
+
const parts = filter.and.map((sub) => compileFilter(sub, ctx));
|
|
2464
|
+
return `(${parts.join(" AND ")})`;
|
|
2465
|
+
}
|
|
2466
|
+
if ("or" in filter) {
|
|
2467
|
+
const parts = filter.or.map((sub) => compileFilter(sub, ctx));
|
|
2468
|
+
return `(${parts.join(" OR ")})`;
|
|
2469
|
+
}
|
|
2470
|
+
if ("not" in filter) {
|
|
2471
|
+
const inner = compileFilter(filter.not, ctx);
|
|
2472
|
+
return `NOT (${inner})`;
|
|
2473
|
+
}
|
|
2474
|
+
if ("semantic" in filter) {
|
|
2475
|
+
const fieldPath2 = filter.semantic.field;
|
|
2476
|
+
const col = columnOf(fieldPath2, ctx);
|
|
2477
|
+
const queryRef = filter.semantic.query;
|
|
2478
|
+
const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
|
|
2479
|
+
if ("$context" in queryRef) assertNotReserved(queryRef.$context);
|
|
2480
|
+
const res = ctx.resolvedPaths.get(fieldPath2);
|
|
2481
|
+
const dimensions = res?.schema.vectorDimensions;
|
|
2482
|
+
ctx.paramCounter.value += 1;
|
|
2483
|
+
ctx.paramSlots.push({
|
|
2484
|
+
key,
|
|
2485
|
+
kind: "semantic",
|
|
2486
|
+
type: "string",
|
|
2487
|
+
dimensions
|
|
2488
|
+
});
|
|
2489
|
+
const paramRef = `$${ctx.paramCounter.value}`;
|
|
2490
|
+
const minScore = numberLiteral(filter.semantic.minScore ?? 0);
|
|
2491
|
+
return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;
|
|
2492
|
+
}
|
|
2493
|
+
if ("fuzzy" in filter) {
|
|
2494
|
+
const col = columnOf(filter.fuzzy.field, ctx);
|
|
2495
|
+
const queryRef = filter.fuzzy.query;
|
|
2496
|
+
const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
|
|
2497
|
+
const kind = "$context" in queryRef ? "context" : "scope";
|
|
2498
|
+
if ("$context" in queryRef) assertNotReserved(queryRef.$context);
|
|
2499
|
+
ctx.paramCounter.value += 1;
|
|
2500
|
+
ctx.paramSlots.push({ key, kind, type: "string" });
|
|
2501
|
+
const paramRef = `$${ctx.paramCounter.value}`;
|
|
2502
|
+
const maxDistance = filter.fuzzy.maxDistance;
|
|
2503
|
+
if (maxDistance !== void 0) {
|
|
2504
|
+
return `levenshtein(${col}, ${paramRef}) <= ${numberLiteral(maxDistance)}`;
|
|
2505
|
+
}
|
|
2506
|
+
return `${col} % ${paramRef}`;
|
|
2507
|
+
}
|
|
2508
|
+
if ("optional" in filter) refuseOptional("SQL compilation");
|
|
2509
|
+
return "TRUE";
|
|
2510
|
+
};
|
|
2511
|
+
var compileCompute = (expr, ctx) => {
|
|
2512
|
+
if ("add" in expr) {
|
|
2513
|
+
const a = compileFieldOrValue(expr.add[0], ctx);
|
|
2514
|
+
const b = compileFieldOrValue(expr.add[1], ctx);
|
|
2515
|
+
return `(${a} + ${b})`;
|
|
2516
|
+
}
|
|
2517
|
+
if ("subtract" in expr) {
|
|
2518
|
+
const a = compileFieldOrValue(expr.subtract[0], ctx);
|
|
2519
|
+
const b = compileFieldOrValue(expr.subtract[1], ctx);
|
|
2520
|
+
return `(${a} - ${b})`;
|
|
2521
|
+
}
|
|
2522
|
+
if ("multiply" in expr) {
|
|
2523
|
+
const a = compileFieldOrValue(expr.multiply[0], ctx);
|
|
2524
|
+
const b = compileFieldOrValue(expr.multiply[1], ctx);
|
|
2525
|
+
return `(${a} * ${b})`;
|
|
2526
|
+
}
|
|
2527
|
+
if ("divide" in expr) {
|
|
2528
|
+
const a = compileFieldOrValue(expr.divide[0], ctx);
|
|
2529
|
+
const b = compileFieldOrValue(expr.divide[1], ctx);
|
|
2530
|
+
return `(${a} / ${b})`;
|
|
2531
|
+
}
|
|
2532
|
+
if ("concat" in expr) {
|
|
2533
|
+
const parts = expr.concat.map((v) => compileFieldOrValue(v, ctx));
|
|
2534
|
+
return `(${parts.join(" || ")})`;
|
|
2535
|
+
}
|
|
2536
|
+
if ("coalesce" in expr) {
|
|
2537
|
+
const parts = expr.coalesce.map((v) => compileFieldOrValue(v, ctx));
|
|
2538
|
+
return `COALESCE(${parts.join(", ")})`;
|
|
2539
|
+
}
|
|
2540
|
+
if ("case" in expr) {
|
|
2541
|
+
const whenClauses = expr.case.when.map((w) => {
|
|
2542
|
+
const cond = compileFilter(w.condition, ctx);
|
|
2543
|
+
const val = compileFieldOrValue(w.then, ctx);
|
|
2544
|
+
return `WHEN ${cond} THEN ${val}`;
|
|
2545
|
+
});
|
|
2546
|
+
const elseVal = compileFieldOrValue(expr.case.else, ctx);
|
|
2547
|
+
return `CASE ${whenClauses.join(" ")} ELSE ${elseVal} END`;
|
|
2548
|
+
}
|
|
2549
|
+
return "NULL";
|
|
2550
|
+
};
|
|
2551
|
+
var aggArg = (arg, ctx) => typeof arg === "string" ? columnOf(arg, ctx) : compileCompute(arg, ctx);
|
|
2552
|
+
var compileAggregate = (expr, ctx) => {
|
|
2553
|
+
if ("count" in expr) {
|
|
2554
|
+
if (expr.count === "*") return "COUNT(*)";
|
|
2555
|
+
return `COUNT(${columnOf(expr.count, ctx)})`;
|
|
2556
|
+
}
|
|
2557
|
+
if ("countDistinct" in expr) return `COUNT(DISTINCT ${columnOf(expr.countDistinct, ctx)})`;
|
|
2558
|
+
if ("sum" in expr) return `SUM(${aggArg(expr.sum, ctx)})`;
|
|
2559
|
+
if ("avg" in expr) return `AVG(${aggArg(expr.avg, ctx)})`;
|
|
2560
|
+
if ("min" in expr) return `MIN(${aggArg(expr.min, ctx)})`;
|
|
2561
|
+
if ("max" in expr) return `MAX(${aggArg(expr.max, ctx)})`;
|
|
2562
|
+
return "NULL";
|
|
2563
|
+
};
|
|
2564
|
+
|
|
2565
|
+
// src/adapters/postgres/compile.ts
|
|
2566
|
+
var compileQuery = (resolved) => {
|
|
2567
|
+
const paramSlots = [];
|
|
2568
|
+
const paramCounter = { value: 0 };
|
|
2569
|
+
const ctx = {
|
|
2570
|
+
resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
|
|
2571
|
+
aliasMap: resolved.aliasMap,
|
|
2572
|
+
paramSlots,
|
|
2573
|
+
paramCounter,
|
|
2574
|
+
...resolved.existsMap !== void 0 ? { existsMap: resolved.existsMap } : {}
|
|
2575
|
+
};
|
|
2576
|
+
const sqlParts = [];
|
|
2577
|
+
const selectParts = [];
|
|
2578
|
+
if (resolved.distinct) {
|
|
2579
|
+
selectParts.push("DISTINCT");
|
|
2580
|
+
}
|
|
2581
|
+
const fieldColumns = resolved.fields.map(
|
|
2582
|
+
(f) => `${f.alias}.${f.column} AS ${quoteIdent(f.outputName)}`
|
|
2583
|
+
);
|
|
2584
|
+
const computeColumns = resolved.computes.map((c) => {
|
|
2585
|
+
const expr = compileCompute(c.expression, ctx);
|
|
2586
|
+
return `${expr} AS ${quoteIdent(c.name)}`;
|
|
2587
|
+
});
|
|
2588
|
+
const aggregateColumns = resolved.aggregates.map((a) => {
|
|
2589
|
+
const expr = compileAggregate(a.expression, ctx);
|
|
2590
|
+
return `${expr} AS ${quoteIdent(a.name)}`;
|
|
2591
|
+
});
|
|
2592
|
+
const semanticColumns = [];
|
|
2593
|
+
if (resolved.semantic !== void 0) {
|
|
2594
|
+
const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
|
|
2595
|
+
const semanticParamIndex = findSemanticParamIndex(paramSlots);
|
|
2596
|
+
if (semanticParamIndex !== void 0) {
|
|
2597
|
+
semanticColumns.push(`1 - (${col} <=> $${semanticParamIndex}) AS "$score"`);
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns, ...semanticColumns];
|
|
2601
|
+
if (selectParts.length > 0) {
|
|
2602
|
+
sqlParts.push(`SELECT ${selectParts.join(" ")} ${allColumns.join(", ")}`);
|
|
2603
|
+
} else {
|
|
2604
|
+
sqlParts.push(`SELECT ${allColumns.join(", ")}`);
|
|
2605
|
+
}
|
|
2606
|
+
const firstSource = resolved.sources[0];
|
|
2607
|
+
if (firstSource !== void 0) {
|
|
2608
|
+
if (firstSource.subquery !== void 0) {
|
|
2609
|
+
const subSql = compileQuery(firstSource.subquery);
|
|
2610
|
+
mergeSubqueryParams(subSql, paramSlots, paramCounter);
|
|
2611
|
+
sqlParts.push(`FROM (${subSql.sql}) AS ${firstSource.alias}`);
|
|
2612
|
+
} else if (firstSource.table !== void 0) {
|
|
2613
|
+
sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
for (const join of resolved.joins) {
|
|
2617
|
+
const joinSource = resolved.sources.find((s) => s.alias === join.toAlias);
|
|
2618
|
+
if (joinSource !== void 0) {
|
|
2619
|
+
const keyword = join.kind === "left" ? "LEFT JOIN" : "JOIN";
|
|
2620
|
+
const conditions = [
|
|
2621
|
+
...compileJoinPairs(join),
|
|
2622
|
+
...(join.on ?? []).map((extra) => compileFilter(extra.original, ctx))
|
|
2623
|
+
];
|
|
2624
|
+
const on = conditions.join(" AND ");
|
|
2625
|
+
if (joinSource.subquery !== void 0) {
|
|
2626
|
+
const subSql = compileQuery(joinSource.subquery);
|
|
2627
|
+
mergeSubqueryParams(subSql, paramSlots, paramCounter);
|
|
2628
|
+
sqlParts.push(`${keyword} (${subSql.sql}) AS ${join.toAlias} ON ${on}`);
|
|
2629
|
+
} else {
|
|
2630
|
+
sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
}
|
|
2634
|
+
const joinedAliases = new Set(resolved.joins.map((j) => j.toAlias));
|
|
2635
|
+
for (const source of resolved.sources) {
|
|
2636
|
+
if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
|
|
2637
|
+
if (source.subquery !== void 0) {
|
|
2638
|
+
const subSql = compileQuery(source.subquery);
|
|
2639
|
+
mergeSubqueryParams(subSql, paramSlots, paramCounter);
|
|
2640
|
+
sqlParts.push(`CROSS JOIN (${subSql.sql}) AS ${source.alias}`);
|
|
2641
|
+
} else if (source.table !== void 0) {
|
|
2642
|
+
sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
if (resolved.filter !== void 0) {
|
|
2646
|
+
const whereClause = compileFilter(resolved.filter.original, ctx);
|
|
2647
|
+
sqlParts.push(`WHERE ${whereClause}`);
|
|
2648
|
+
}
|
|
2649
|
+
if (resolved.groupBy.length > 0) {
|
|
2650
|
+
const groupByParts = resolved.groupBy.map((f) => `${f.alias}.${f.column}`);
|
|
2651
|
+
sqlParts.push(`GROUP BY ${groupByParts.join(", ")}`);
|
|
2652
|
+
}
|
|
2653
|
+
if (resolved.sort.length > 0) {
|
|
2654
|
+
const orderByParts = resolved.sort.map((s) => {
|
|
2655
|
+
if (typeof s.field === "string") {
|
|
2656
|
+
return `${quoteIdent(s.field)} ${s.dir === "desc" ? "DESC" : "ASC"}`;
|
|
2657
|
+
}
|
|
2658
|
+
return `${s.field.alias}.${s.field.column} ${s.dir === "desc" ? "DESC" : "ASC"}`;
|
|
2659
|
+
});
|
|
2660
|
+
sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
|
|
2661
|
+
} else if (resolved.semantic !== void 0) {
|
|
2662
|
+
const semanticIdx = findSemanticParamIndex(paramSlots);
|
|
2663
|
+
if (semanticIdx !== void 0) {
|
|
2664
|
+
const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
|
|
2665
|
+
sqlParts.push(`ORDER BY ${col} <=> $${semanticIdx} ASC`);
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
if (resolved.limit !== void 0) {
|
|
2669
|
+
if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
|
|
2670
|
+
throw new VexError("invalid_dsl", `LIMIT must be a positive integer, not ${String(resolved.limit)}.`);
|
|
2671
|
+
}
|
|
2672
|
+
sqlParts.push(`LIMIT ${resolved.limit}`);
|
|
2673
|
+
}
|
|
2674
|
+
const contextContract = {};
|
|
2675
|
+
for (const slot of paramSlots) {
|
|
2676
|
+
contextContract[slot.key] = { type: slot.type, kind: slot.kind };
|
|
2677
|
+
}
|
|
2678
|
+
return {
|
|
2679
|
+
sql: sqlParts.join(" "),
|
|
2680
|
+
paramSlots,
|
|
2681
|
+
contextContract
|
|
2682
|
+
};
|
|
2683
|
+
};
|
|
2684
|
+
var findSemanticParamIndex = (slots) => {
|
|
2685
|
+
for (let i = 0; i < slots.length; i++) {
|
|
2686
|
+
const slot = slots[i];
|
|
2687
|
+
if (slot !== void 0 && slot.kind === "semantic") {
|
|
2688
|
+
return i + 1;
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
return void 0;
|
|
2692
|
+
};
|
|
2693
|
+
var mergeSubqueryParams = (subCompiled, parentSlots, parentCounter) => {
|
|
2694
|
+
for (const slot of subCompiled.paramSlots) {
|
|
2695
|
+
parentCounter.value += 1;
|
|
2696
|
+
parentSlots.push(slot);
|
|
2697
|
+
}
|
|
2698
|
+
};
|
|
2699
|
+
|
|
2700
|
+
// src/adapters/postgres/statement-timeout.ts
|
|
2701
|
+
var UNIT_MS = { "": 1, ms: 1, s: 1e3, min: 6e4, h: 36e5, d: 864e5 };
|
|
2702
|
+
var parseTimeout = (shown) => {
|
|
2703
|
+
const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|min|h|d)?\s*$/.exec(shown);
|
|
2704
|
+
if (match === null) return void 0;
|
|
2705
|
+
const unit = UNIT_MS[match[2] ?? ""];
|
|
2706
|
+
return unit === void 0 ? void 0 : Number(match[1]) * unit;
|
|
2707
|
+
};
|
|
2708
|
+
var enforcementFor = async (pool, ceilingMs) => {
|
|
2709
|
+
if (pool.statementTimeouts === false) return "unenforced";
|
|
2710
|
+
const shown = await pool.query("SHOW statement_timeout");
|
|
2711
|
+
const current = parseTimeout(String(shown.rows[0]?.["statement_timeout"] ?? ""));
|
|
2712
|
+
if (current !== void 0 && current > 0 && current <= ceilingMs) return "connection";
|
|
2713
|
+
return pool.transaction === void 0 ? "unenforced" : "statement";
|
|
2714
|
+
};
|
|
2715
|
+
|
|
2716
|
+
// src/adapters/postgres/postgres.adapter.ts
|
|
2717
|
+
var NUMERIC_OIDS = /* @__PURE__ */ new Set([
|
|
2718
|
+
20,
|
|
2719
|
+
// int8
|
|
2720
|
+
700,
|
|
2721
|
+
// float4
|
|
2722
|
+
701,
|
|
2723
|
+
// float8
|
|
2724
|
+
1700
|
|
2725
|
+
// numeric
|
|
2726
|
+
]);
|
|
2727
|
+
var coerceNumericColumns = (rows, fields) => {
|
|
2728
|
+
const numericKeys = fields.filter((f) => NUMERIC_OIDS.has(f.dataTypeID)).map((f) => f.name);
|
|
2729
|
+
if (numericKeys.length === 0 || rows.length === 0) return rows;
|
|
2730
|
+
return rows.map((row) => {
|
|
2731
|
+
const out = { ...row };
|
|
2732
|
+
for (const key of numericKeys) {
|
|
2733
|
+
const v = out[key];
|
|
2734
|
+
if (typeof v === "string") {
|
|
2735
|
+
const n = Number(v);
|
|
2736
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
return out;
|
|
2740
|
+
});
|
|
2741
|
+
};
|
|
2742
|
+
var createPostgresAdapter = (config) => {
|
|
2743
|
+
const { pool, schema = "public", exclude } = config;
|
|
2744
|
+
const capabilities = {
|
|
2745
|
+
vectorSearch: true,
|
|
2746
|
+
fuzzyMatch: false,
|
|
2747
|
+
// Requires pg_trgm extension, not guaranteed
|
|
2748
|
+
jsonFields: true,
|
|
2749
|
+
fullTextSearch: true,
|
|
2750
|
+
returningClause: true,
|
|
2751
|
+
cte: true,
|
|
2752
|
+
windowFunctions: true,
|
|
2753
|
+
statementTimeout: true
|
|
2754
|
+
};
|
|
2755
|
+
const introspect = async (options) => introspectPostgres(pool, {
|
|
2756
|
+
...options,
|
|
2757
|
+
schema: options?.schema ?? schema,
|
|
2758
|
+
exclude: options?.exclude ?? exclude
|
|
2759
|
+
});
|
|
2760
|
+
const compile2 = (resolved) => compileQuery(resolved);
|
|
2761
|
+
let perStatementMs;
|
|
2762
|
+
const limitReads = async (ms) => {
|
|
2763
|
+
perStatementMs = void 0;
|
|
2764
|
+
if (ms <= 0) return "unenforced";
|
|
2765
|
+
const enforcement = await enforcementFor(pool, ms);
|
|
2766
|
+
if (enforcement === "statement") perStatementMs = Math.round(ms);
|
|
2767
|
+
return enforcement;
|
|
2768
|
+
};
|
|
2769
|
+
const execute = async (query, params) => {
|
|
2770
|
+
const { transaction } = pool;
|
|
2771
|
+
const limit = perStatementMs;
|
|
2772
|
+
const result = limit === void 0 || transaction === void 0 ? await pool.query(query.sql, params) : await transaction(async (tx) => {
|
|
2773
|
+
await tx.query(`SET LOCAL statement_timeout = ${limit}`);
|
|
2774
|
+
return tx.query(query.sql, params);
|
|
2775
|
+
});
|
|
2776
|
+
return coerceNumericColumns(result.rows, result.fields);
|
|
2777
|
+
};
|
|
2778
|
+
return {
|
|
2779
|
+
id: "postgres",
|
|
2780
|
+
introspect,
|
|
2781
|
+
compile: compile2,
|
|
2782
|
+
execute,
|
|
2783
|
+
capabilities,
|
|
2784
|
+
limitReads
|
|
2785
|
+
};
|
|
2786
|
+
};
|
|
2787
|
+
|
|
2788
|
+
// src/guide.ts
|
|
2789
|
+
var vexGuide = () => [
|
|
2790
|
+
"VEX \u2014 how to read data. A Vex endpoint answers POST with a JSON body and returns { result, meta }.",
|
|
2791
|
+
"",
|
|
2792
|
+
"The request body takes one of three postures:",
|
|
2793
|
+
' 1. GENERATE: { intent, shape, context? } \u2014 intent is plain English (all detail: filters, thresholds, sorting, grouping); shape is a JSON EXAMPLE of the output (an ARRAY with one example element returns a LIST; a plain OBJECT returns ONE record; values are type markers: "" 0 false). The result is cached and meta.cache.fingerprint carries its identity.',
|
|
2794
|
+
" 2. REPLAY: { fingerprint, context? } \u2014 re-runs the exact cached query. Never regenerates. Unknown fingerprint \u2192 error cache_miss.",
|
|
2795
|
+
" 3. NAMED SLOT: { fingerprint, intent, shape, context? } \u2014 hit when the stored request matches; regenerate-and-replace when it differs (protected slots refuse with fingerprint_protected).",
|
|
2796
|
+
"",
|
|
2797
|
+
"context \u2014 runtime values, bound as SQL parameters:",
|
|
2798
|
+
" - Keys are part of the query's contract; VALUES vary freely per call. Replaying one fingerprint with different context values re-runs the same query with new parameters \u2014 this is how a search term, an id, a threshold, or a date flows in per call.",
|
|
2799
|
+
' - The query binds ONLY keys you pass at generation. To parameterize a query: name the value in the intent AND pass the key with a real value in context \u2014 e.g. intent "companies whose name contains the search text" with context { "q": "acme" }. Replays then pass new values for the same keys.',
|
|
2800
|
+
' - Reserved keys: sortBy (an "entity.field", schema-validated) and sortDir ("asc"|"desc") drive ORDER BY directly on any replay.',
|
|
2801
|
+
' - A value the query filters with ILIKE is a pattern: "%text%" matches contains.',
|
|
2802
|
+
' - OPTIONAL keys: meta.context marks some keys `optional: true`. Those switch a condition ON \u2014 send the key and it applies, omit it and the condition is not in the query at all (it does not match everything by accident, and omitting it is never an error). A key marked `absent: true` is one you did not send on this run. This is how one fingerprint answers "everyone", "everyone matching a search", and "one by id".',
|
|
2803
|
+
"",
|
|
2804
|
+
"result \u2014 exactly the requested shape (array, object, or scalar). meta.cache = { hit, fingerprint, replaced? }; meta.missingContext lists REQUIRED context keys you did not send \u2014 the query ran without them, so the result is WRONG. Supply the keys and re-run before trusting it. Optional keys never appear there; leaving one out is a choice, not a mistake.",
|
|
2805
|
+
"",
|
|
2806
|
+
"GET on the same URL returns the endpoint's self-description: its entities, the query body contract, and every existing named fingerprint with its intent \u2014 check it before generating a query that may already exist."
|
|
2807
|
+
].join("\n");
|
|
2808
|
+
|
|
2809
|
+
// src/cache/cache.types.ts
|
|
2810
|
+
var REFRESH_MODES = ["snapshot", "reactive"];
|
|
2811
|
+
var isRefresh = (value) => REFRESH_MODES.some((mode) => mode === value);
|
|
2812
|
+
var LookupSchema = zod.z.object({
|
|
2813
|
+
$lookup: zod.z.object({
|
|
2814
|
+
from: zod.z.string().describe("Table the value is read from"),
|
|
2815
|
+
field: zod.z.string().describe("Column the subquery returns"),
|
|
2816
|
+
where: FilterSchema.describe("Bounds the lookup \u2014 should match at most one row")
|
|
2817
|
+
}).strict()
|
|
2818
|
+
}).strict().describe("Scalar subquery: reads one value from another table at write time; read scope rules apply");
|
|
2819
|
+
var ValueSchema = zod.z.union([
|
|
2820
|
+
zod.z.string(),
|
|
2821
|
+
zod.z.number(),
|
|
2822
|
+
zod.z.boolean(),
|
|
2823
|
+
zod.z.null(),
|
|
2824
|
+
zod.z.object({ $context: zod.z.string() }).strict(),
|
|
2825
|
+
LookupSchema
|
|
2826
|
+
]);
|
|
2827
|
+
var Columns = zod.z.record(zod.z.string(), ValueSchema).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
|
|
2828
|
+
var OnConflictSchema = zod.z.object({
|
|
2829
|
+
target: zod.z.array(zod.z.string()).min(1).describe("Conflict columns \u2014 must match a unique index or the primary key"),
|
|
2830
|
+
set: Columns.optional().describe("DO UPDATE SET when the row already exists; omitted \u2192 DO NOTHING (no row returned on conflict)")
|
|
2831
|
+
}).strict();
|
|
2832
|
+
var InsertSchema = zod.z.object({ op: zod.z.literal("insert"), table: zod.z.string(), values: Columns, onConflict: OnConflictSchema.optional() }).strict();
|
|
2833
|
+
var UpdateSchema = zod.z.object({ op: zod.z.literal("update"), table: zod.z.string(), set: Columns, where: FilterSchema }).strict();
|
|
2834
|
+
var DeleteSchema = zod.z.object({ op: zod.z.literal("delete"), table: zod.z.string(), where: FilterSchema }).strict();
|
|
2835
|
+
var ItemRefSchema = zod.z.object({ $item: zod.z.string() }).strict().describe("insertEach only: a key read from the current element of `items`");
|
|
2836
|
+
var EachColumns = zod.z.record(zod.z.string(), zod.z.union([ValueSchema, ItemRefSchema])).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
|
|
2837
|
+
var InsertEachSchema = zod.z.object({
|
|
2838
|
+
op: zod.z.literal("insertEach"),
|
|
2839
|
+
table: zod.z.string(),
|
|
2840
|
+
items: zod.z.object({ $context: zod.z.string() }).strict().describe("Context key holding an array of objects \u2014 one inserted row per element"),
|
|
2841
|
+
values: EachColumns,
|
|
2842
|
+
onConflict: OnConflictSchema.optional()
|
|
2843
|
+
}).strict();
|
|
2844
|
+
var UpsertSchema = zod.z.object({
|
|
2845
|
+
op: zod.z.literal("upsert"),
|
|
2846
|
+
table: zod.z.string(),
|
|
2847
|
+
columns: Columns,
|
|
2848
|
+
// set on BOTH branches (update SET, and part of the insert)
|
|
2849
|
+
insert: Columns.optional(),
|
|
2850
|
+
// extra columns set ONLY on insert — immutable-on-create (e.g. a FK)
|
|
2851
|
+
key: zod.z.string()
|
|
2852
|
+
}).strict().describe('Sugar: insert-or-update by `key` (e.g. "id"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');
|
|
2853
|
+
var MutationSchema = zod.z.discriminatedUnion("op", [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);
|
|
2854
|
+
var MutationDefinitionSchema = zod.z.union([MutationSchema, MutationSchema.array().min(1)]);
|
|
2855
|
+
var isCompiledIr = (value) => {
|
|
2856
|
+
if (value === null || typeof value !== "object") return false;
|
|
2857
|
+
const ir = value;
|
|
2858
|
+
if (ir["irVersion"] !== 1) return false;
|
|
2859
|
+
if (!("core" in ir)) return false;
|
|
2860
|
+
const tables = ir["tables"];
|
|
2861
|
+
if (tables === null || typeof tables !== "object") return false;
|
|
2862
|
+
const t = tables;
|
|
2863
|
+
return Array.isArray(t["paths"]) && Array.isArray(t["strings"]);
|
|
2864
|
+
};
|
|
2865
|
+
var validateEntry = (entry) => {
|
|
2866
|
+
if (typeof entry.createdAt !== "number") return "createdAt must be a number";
|
|
2867
|
+
if (entry.expiresAt !== void 0 && typeof entry.expiresAt !== "number") {
|
|
2868
|
+
return "expiresAt must be a number when present";
|
|
2869
|
+
}
|
|
2870
|
+
if (entry.kind === "unsatisfiable") {
|
|
2871
|
+
return typeof entry.reason === "string" && entry.reason.length > 0 ? null : "unsatisfiable entry requires a non-empty reason";
|
|
2872
|
+
}
|
|
2873
|
+
if (entry.kind === "ok") {
|
|
2874
|
+
if (strata.exceedsDepth(entry.dsl)) return `invalid dsl: ${strata.depthRefusal()}`;
|
|
2875
|
+
const parsed = QuerySchema.safeParse(entry.dsl);
|
|
2876
|
+
if (!parsed.success) return `invalid dsl: ${parsed.error.message}`;
|
|
2877
|
+
if (entry.prismIr !== void 0 && !isCompiledIr(entry.prismIr)) {
|
|
2878
|
+
return "invalid prismIr: not a CompiledIr structure";
|
|
2879
|
+
}
|
|
2880
|
+
if (entry.refresh !== void 0 && !isRefresh(entry.refresh)) {
|
|
2881
|
+
return `invalid refresh: ${String(entry.refresh)}`;
|
|
2882
|
+
}
|
|
2883
|
+
return null;
|
|
2884
|
+
}
|
|
2885
|
+
if (entry.kind === "mutation") {
|
|
2886
|
+
if (strata.exceedsDepth(entry.mutation)) return `invalid mutation: ${strata.depthRefusal()}`;
|
|
2887
|
+
const parsed = MutationDefinitionSchema.safeParse(entry.mutation);
|
|
2888
|
+
return parsed.success ? null : `invalid mutation: ${parsed.error.message}`;
|
|
2889
|
+
}
|
|
2890
|
+
return `unknown cache entry kind: ${String(entry.kind)}`;
|
|
2891
|
+
};
|
|
2892
|
+
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
2893
|
+
var quoteIdent2 = (name, label) => {
|
|
2894
|
+
if (!IDENT.test(name)) {
|
|
2895
|
+
throw new Error(`Invalid ${label} identifier for postgres cache: "${name}"`);
|
|
2896
|
+
}
|
|
2897
|
+
return `"${name}"`;
|
|
2898
|
+
};
|
|
2899
|
+
var SELECT_COLS = "key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh";
|
|
2900
|
+
var rowToEntry = (row) => {
|
|
2901
|
+
const createdAt = row["created_at"].getTime();
|
|
2902
|
+
const expiresAtRaw = row["expires_at"];
|
|
2903
|
+
const lastUsedRaw = row["last_used_at"];
|
|
2904
|
+
const fingerprint = row["schema_fingerprint"];
|
|
2905
|
+
const meta = {
|
|
2906
|
+
createdAt,
|
|
2907
|
+
...expiresAtRaw ? { expiresAt: expiresAtRaw.getTime() } : {},
|
|
2908
|
+
...lastUsedRaw ? { lastUsedAt: lastUsedRaw.getTime() } : {},
|
|
2909
|
+
...row["protected"] === true ? { protected: true } : {},
|
|
2910
|
+
...row["request_hash"] != null ? { requestHash: String(row["request_hash"]) } : {},
|
|
2911
|
+
...fingerprint ? { schemaFingerprint: fingerprint } : {},
|
|
2912
|
+
...row["intent"] != null ? { intent: String(row["intent"]) } : {},
|
|
2913
|
+
...row["shape"] != null ? { shape: row["shape"] } : {}
|
|
2914
|
+
};
|
|
2915
|
+
if (row["kind"] === "unsatisfiable") {
|
|
2916
|
+
return { kind: "unsatisfiable", reason: String(row["reason"] ?? ""), ...meta };
|
|
2917
|
+
}
|
|
2918
|
+
if (row["kind"] === "mutation") {
|
|
2919
|
+
return {
|
|
2920
|
+
kind: "mutation",
|
|
2921
|
+
mutation: row["dsl"],
|
|
2922
|
+
...row["reach"] != null ? { reach: row["reach"] } : {},
|
|
2923
|
+
...meta
|
|
2924
|
+
};
|
|
2925
|
+
}
|
|
2926
|
+
return {
|
|
2927
|
+
kind: "ok",
|
|
2928
|
+
dsl: row["dsl"],
|
|
2929
|
+
...row["prism_ir"] != null ? { prismIr: row["prism_ir"] } : {},
|
|
2930
|
+
// A DECLARED REACH IS PART OF THE ENTRY, so it has to survive the round
|
|
2931
|
+
// trip. Dropping it here would not fail loudly — the read would simply be
|
|
2932
|
+
// served at the caller's own, wider reach, which is the exact thing the
|
|
2933
|
+
// field exists to prevent.
|
|
2934
|
+
...row["reach"] != null ? { reach: row["reach"] } : {},
|
|
2935
|
+
// So must the refresh mode: dropped, a reactive read would quietly answer
|
|
2936
|
+
// once and never again.
|
|
2937
|
+
...isRefresh(row["refresh"]) ? { refresh: row["refresh"] } : {},
|
|
2938
|
+
...meta
|
|
2939
|
+
};
|
|
2940
|
+
};
|
|
2941
|
+
var createPostgresCache = (config) => {
|
|
2942
|
+
const { pool, onError } = config;
|
|
2943
|
+
const schema = quoteIdent2(config.schema ?? "public", "schema");
|
|
2944
|
+
const table = quoteIdent2(config.table ?? "vex_cache", "table");
|
|
2945
|
+
const qualified = `${schema}.${table}`;
|
|
2946
|
+
const isDefault = (config.schema ?? "public") === "public" && (config.table ?? "vex_cache") === "vex_cache";
|
|
2947
|
+
const slug = `${config.schema ?? "public"}-${config.table ?? "vex_cache"}`.toLowerCase().replace(/[^a-z0-9-]/g, "-");
|
|
2948
|
+
const sequence = {
|
|
2949
|
+
id: isDefault ? "nisc.vex.cache" : `nisc.vex.cache.${slug}`,
|
|
2950
|
+
migrations: [
|
|
2951
|
+
{
|
|
2952
|
+
description: "The vex cache table, converged from any earlier shape",
|
|
2953
|
+
steps: [
|
|
2954
|
+
{ kind: "sql", sql: `CREATE SCHEMA IF NOT EXISTS ${schema}` },
|
|
2955
|
+
{
|
|
2956
|
+
kind: "sql",
|
|
2957
|
+
sql: `CREATE TABLE IF NOT EXISTS ${qualified} (
|
|
2958
|
+
key text PRIMARY KEY,
|
|
2959
|
+
kind text NOT NULL DEFAULT 'ok',
|
|
2960
|
+
intent text,
|
|
2961
|
+
shape jsonb,
|
|
2962
|
+
dsl jsonb,
|
|
2963
|
+
prism_ir jsonb,
|
|
2964
|
+
reach text,
|
|
2965
|
+
reason text,
|
|
2966
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
2967
|
+
expires_at timestamptz,
|
|
2968
|
+
schema_fingerprint text,
|
|
2969
|
+
protected boolean NOT NULL DEFAULT false,
|
|
2970
|
+
last_used_at timestamptz,
|
|
2971
|
+
request_hash text,
|
|
2972
|
+
refresh text
|
|
2973
|
+
)`
|
|
2974
|
+
},
|
|
2975
|
+
{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS protected boolean NOT NULL DEFAULT false` },
|
|
2976
|
+
{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS last_used_at timestamptz` },
|
|
2977
|
+
{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS request_hash text` },
|
|
2978
|
+
{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS reach text` },
|
|
2979
|
+
{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS refresh text` }
|
|
2980
|
+
]
|
|
2981
|
+
}
|
|
2982
|
+
]
|
|
2983
|
+
};
|
|
2984
|
+
const init = async () => {
|
|
2985
|
+
await postgres.migrate(pool, [sequence]);
|
|
2986
|
+
};
|
|
2987
|
+
const evict = (key, reason) => {
|
|
2988
|
+
fireAndForget(pool.query(`DELETE FROM ${qualified} WHERE key = $1`, [key]), onError);
|
|
2989
|
+
const err = new Error(`[vex:cache:postgres] evicted invalid row for key "${key}": ${reason}`);
|
|
2990
|
+
if (onError) onError(err);
|
|
2991
|
+
else console.error(err);
|
|
2992
|
+
};
|
|
2993
|
+
const get = async (key) => {
|
|
2994
|
+
const res = await pool.query(
|
|
2995
|
+
`SELECT ${SELECT_COLS} FROM ${qualified}
|
|
2996
|
+
WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,
|
|
2997
|
+
[key]
|
|
2998
|
+
);
|
|
2999
|
+
const row = res.rows[0];
|
|
3000
|
+
if (row === void 0) return void 0;
|
|
3001
|
+
const entry = rowToEntry(row);
|
|
3002
|
+
const error = validateEntry(entry);
|
|
3003
|
+
if (error !== null) {
|
|
3004
|
+
evict(key, error);
|
|
3005
|
+
return void 0;
|
|
3006
|
+
}
|
|
3007
|
+
return entry;
|
|
3008
|
+
};
|
|
3009
|
+
const set = async (key, entry) => {
|
|
3010
|
+
const error = validateEntry(entry);
|
|
3011
|
+
if (error !== null) {
|
|
3012
|
+
const wrapped = new Error(
|
|
3013
|
+
`[vex:cache:postgres] refusing to write invalid entry for key "${key}": ${error}`
|
|
3014
|
+
);
|
|
3015
|
+
if (onError) {
|
|
3016
|
+
onError(wrapped);
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
throw wrapped;
|
|
3020
|
+
}
|
|
3021
|
+
const isOk = entry.kind === "ok";
|
|
3022
|
+
const dsl = isOk ? JSON.stringify(entry.dsl) : entry.kind === "mutation" ? JSON.stringify(entry.mutation) : null;
|
|
3023
|
+
const prismIr = isOk && entry.prismIr !== void 0 ? JSON.stringify(entry.prismIr) : null;
|
|
3024
|
+
const reason = entry.kind === "unsatisfiable" ? entry.reason : null;
|
|
3025
|
+
const intent = entry.intent ?? null;
|
|
3026
|
+
const shape = entry.shape !== void 0 ? JSON.stringify(entry.shape) : null;
|
|
3027
|
+
const createdAt = new Date(entry.createdAt);
|
|
3028
|
+
const expiresAt = entry.expiresAt !== void 0 ? new Date(entry.expiresAt) : null;
|
|
3029
|
+
const fingerprint = entry.schemaFingerprint ?? null;
|
|
3030
|
+
const isProtected = entry.protected === true;
|
|
3031
|
+
const lastUsedAt = entry.lastUsedAt !== void 0 ? new Date(entry.lastUsedAt) : null;
|
|
3032
|
+
const requestHash = entry.requestHash ?? null;
|
|
3033
|
+
const reach = entry.kind === "unsatisfiable" ? null : entry.reach ?? null;
|
|
3034
|
+
const refresh = entry.kind === "ok" ? entry.refresh ?? null : null;
|
|
3035
|
+
await pool.query(
|
|
3036
|
+
`INSERT INTO ${qualified} (key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh)
|
|
3037
|
+
VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
|
3038
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
3039
|
+
kind = EXCLUDED.kind,
|
|
3040
|
+
intent = EXCLUDED.intent,
|
|
3041
|
+
shape = EXCLUDED.shape,
|
|
3042
|
+
dsl = EXCLUDED.dsl,
|
|
3043
|
+
prism_ir = EXCLUDED.prism_ir,
|
|
3044
|
+
reach = EXCLUDED.reach,
|
|
3045
|
+
reason = EXCLUDED.reason,
|
|
3046
|
+
created_at = EXCLUDED.created_at,
|
|
3047
|
+
expires_at = EXCLUDED.expires_at,
|
|
3048
|
+
schema_fingerprint = EXCLUDED.schema_fingerprint,
|
|
3049
|
+
protected = EXCLUDED.protected,
|
|
3050
|
+
last_used_at = EXCLUDED.last_used_at,
|
|
3051
|
+
request_hash = EXCLUDED.request_hash,
|
|
3052
|
+
refresh = EXCLUDED.refresh`,
|
|
3053
|
+
[key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh]
|
|
3054
|
+
);
|
|
3055
|
+
};
|
|
3056
|
+
const del = async (key) => {
|
|
3057
|
+
await pool.query(`DELETE FROM ${qualified} WHERE key = $1`, [key]);
|
|
3058
|
+
};
|
|
3059
|
+
const clear = async () => {
|
|
3060
|
+
await pool.query(`DELETE FROM ${qualified}`);
|
|
3061
|
+
};
|
|
3062
|
+
const keys = async () => {
|
|
3063
|
+
const res = await pool.query(
|
|
3064
|
+
`SELECT key FROM ${qualified} WHERE expires_at IS NULL OR expires_at > now()`
|
|
3065
|
+
);
|
|
3066
|
+
return res.rows.map((r) => String(r["key"]));
|
|
3067
|
+
};
|
|
3068
|
+
const entries = async () => {
|
|
3069
|
+
const res = await pool.query(
|
|
3070
|
+
`SELECT ${SELECT_COLS} FROM ${qualified}
|
|
3071
|
+
WHERE expires_at IS NULL OR expires_at > now()`
|
|
3072
|
+
);
|
|
3073
|
+
const out = [];
|
|
3074
|
+
for (const row of res.rows) {
|
|
3075
|
+
const key = String(row["key"]);
|
|
3076
|
+
const entry = rowToEntry(row);
|
|
3077
|
+
const error = validateEntry(entry);
|
|
3078
|
+
if (error !== null) {
|
|
3079
|
+
evict(key, error);
|
|
3080
|
+
continue;
|
|
3081
|
+
}
|
|
3082
|
+
out.push({ key, entry });
|
|
3083
|
+
}
|
|
3084
|
+
return out;
|
|
3085
|
+
};
|
|
3086
|
+
return { init, sequence, get, set, delete: del, clear, keys, entries };
|
|
3087
|
+
};
|
|
3088
|
+
|
|
3089
|
+
// src/cache/tiered.ts
|
|
3090
|
+
var createTieredCache = (config) => {
|
|
3091
|
+
const { l1, l2, onError } = config;
|
|
3092
|
+
const warmup = config.warmup ?? "full";
|
|
3093
|
+
const promote = async (key, entry) => {
|
|
3094
|
+
const error = validateEntry(entry);
|
|
3095
|
+
if (error !== null) {
|
|
3096
|
+
const wrapped = new Error(`[vex:cache:tiered] evicting invalid L2 entry for key "${key}": ${error}`);
|
|
3097
|
+
if (onError) onError(wrapped);
|
|
3098
|
+
else console.error(wrapped);
|
|
3099
|
+
fireAndForget(l2.delete(key), onError);
|
|
3100
|
+
return false;
|
|
3101
|
+
}
|
|
3102
|
+
await l1.set(key, entry);
|
|
3103
|
+
return true;
|
|
3104
|
+
};
|
|
3105
|
+
const init = async () => {
|
|
3106
|
+
await l2.init?.();
|
|
3107
|
+
await l1.init?.();
|
|
3108
|
+
if (warmup === "lazy") return;
|
|
3109
|
+
if (typeof warmup === "object" && warmup.mode === "partial") {
|
|
3110
|
+
for (const key of warmup.fingerprints) {
|
|
3111
|
+
const entry = await l2.get(key);
|
|
3112
|
+
if (entry !== void 0) await promote(key, entry);
|
|
3113
|
+
}
|
|
3114
|
+
return;
|
|
3115
|
+
}
|
|
3116
|
+
if (l2.entries) {
|
|
3117
|
+
const all = await l2.entries();
|
|
3118
|
+
for (const { key, entry } of all) await promote(key, entry);
|
|
3119
|
+
return;
|
|
3120
|
+
}
|
|
3121
|
+
const keys2 = await l2.keys();
|
|
3122
|
+
for (const key of keys2) {
|
|
3123
|
+
const entry = await l2.get(key);
|
|
3124
|
+
if (entry !== void 0) await promote(key, entry);
|
|
3125
|
+
}
|
|
3126
|
+
};
|
|
3127
|
+
const get = async (key) => {
|
|
3128
|
+
const hit = await l1.get(key);
|
|
3129
|
+
if (hit !== void 0) return hit;
|
|
3130
|
+
const fromL2 = await l2.get(key);
|
|
3131
|
+
if (fromL2 === void 0) return void 0;
|
|
3132
|
+
const ok = await promote(key, fromL2);
|
|
3133
|
+
return ok ? fromL2 : void 0;
|
|
3134
|
+
};
|
|
3135
|
+
const set = async (key, entry) => {
|
|
3136
|
+
await l1.set(key, entry);
|
|
3137
|
+
fireAndForget(l2.set(key, entry), onError);
|
|
3138
|
+
};
|
|
3139
|
+
const del = async (key) => {
|
|
3140
|
+
await l1.delete(key);
|
|
3141
|
+
fireAndForget(l2.delete(key), onError);
|
|
3142
|
+
};
|
|
3143
|
+
const clear = async () => {
|
|
3144
|
+
await l1.clear();
|
|
3145
|
+
fireAndForget(l2.clear(), onError);
|
|
3146
|
+
};
|
|
3147
|
+
const keys = async () => l1.keys();
|
|
3148
|
+
return { init, get, set, delete: del, clear, keys, ...l2.sequence !== void 0 ? { sequence: l2.sequence } : {} };
|
|
3149
|
+
};
|
|
3150
|
+
|
|
3151
|
+
// src/mutations/signature.ts
|
|
3152
|
+
var isContextRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && typeof v["$context"] === "string";
|
|
3153
|
+
var columnInfo = (path, schema) => {
|
|
3154
|
+
const [table, field] = path.split(".");
|
|
3155
|
+
const entity = schema?.entities.find((e) => e.table === table || e.name === table);
|
|
3156
|
+
const f = entity?.fields.find((x) => x.name === field);
|
|
3157
|
+
return { type: f?.normalizedType ?? "unknown", column: path };
|
|
3158
|
+
};
|
|
3159
|
+
var addField = (sig, key, field) => {
|
|
3160
|
+
const existing = sig[key];
|
|
3161
|
+
if (existing === void 0) {
|
|
3162
|
+
sig[key] = field;
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
3165
|
+
if (existing.type === "unknown" && field.type !== "unknown") {
|
|
3166
|
+
sig[key] = { ...field, ...existing.note !== void 0 ? { note: existing.note } : {} };
|
|
3167
|
+
}
|
|
3168
|
+
};
|
|
3169
|
+
var deepScan = (value, sig) => {
|
|
3170
|
+
if (isContextRef(value)) {
|
|
3171
|
+
addField(sig, value.$context, { type: "unknown" });
|
|
3172
|
+
return;
|
|
3173
|
+
}
|
|
3174
|
+
if (Array.isArray(value)) {
|
|
3175
|
+
for (const v of value) deepScan(v, sig);
|
|
3176
|
+
return;
|
|
3177
|
+
}
|
|
3178
|
+
if (value !== null && typeof value === "object") {
|
|
3179
|
+
for (const v of Object.values(value)) deepScan(v, sig);
|
|
3180
|
+
}
|
|
3181
|
+
};
|
|
3182
|
+
var COMPARISONS = ["eq", "neq", "gt", "gte", "lt", "lte"];
|
|
3183
|
+
var walkFilter = (filter, schema, sig) => {
|
|
3184
|
+
const f = filter;
|
|
3185
|
+
for (const op of COMPARISONS) {
|
|
3186
|
+
const pair = f[op];
|
|
3187
|
+
if (Array.isArray(pair) && pair.length === 2) {
|
|
3188
|
+
const [a, b] = pair;
|
|
3189
|
+
if (typeof a === "string" && isContextRef(b)) addField(sig, b.$context, columnInfo(a, schema));
|
|
3190
|
+
else if (typeof b === "string" && isContextRef(a)) addField(sig, a.$context, columnInfo(b, schema));
|
|
3191
|
+
else deepScan(pair, sig);
|
|
3192
|
+
return;
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
if ("in" in f || "notIn" in f) {
|
|
3196
|
+
const [path, target] = f["in"] ?? f["notIn"];
|
|
3197
|
+
if (isContextRef(target)) addField(sig, target.$context, { ...columnInfo(path, schema), type: `${columnInfo(path, schema).type}[]` });
|
|
3198
|
+
else deepScan(target, sig);
|
|
3199
|
+
return;
|
|
3200
|
+
}
|
|
3201
|
+
if ("like" in f || "ilike" in f) {
|
|
3202
|
+
const [path, v] = f["like"] ?? f["ilike"];
|
|
3203
|
+
if (isContextRef(v)) addField(sig, v.$context, { type: "string", column: path, note: "pattern" });
|
|
3204
|
+
return;
|
|
3205
|
+
}
|
|
3206
|
+
if ("and" in f || "or" in f) {
|
|
3207
|
+
for (const sub of f["and"] ?? f["or"]) walkFilter(sub, schema, sig);
|
|
3208
|
+
return;
|
|
3209
|
+
}
|
|
3210
|
+
if ("not" in f) {
|
|
3211
|
+
walkFilter(f["not"], schema, sig);
|
|
3212
|
+
return;
|
|
3213
|
+
}
|
|
3214
|
+
deepScan(f, sig);
|
|
3215
|
+
};
|
|
3216
|
+
var isLookupRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
3217
|
+
var columnsOf = (m) => m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : m.op === "upsert" ? { ...m.columns, ...m.insert ?? {} } : {};
|
|
3218
|
+
var collectMutationContext = (def, schema) => {
|
|
3219
|
+
const sig = {};
|
|
3220
|
+
const list = Array.isArray(def) ? def : [def];
|
|
3221
|
+
for (const m of list) {
|
|
3222
|
+
for (const [col, v] of Object.entries(columnsOf(m))) {
|
|
3223
|
+
if (isLookupRef(v)) {
|
|
3224
|
+
walkFilter(v.$lookup.where, schema, sig);
|
|
3225
|
+
continue;
|
|
3226
|
+
}
|
|
3227
|
+
if (!isContextRef(v)) continue;
|
|
3228
|
+
const insertOnly = m.op === "upsert" && m.insert !== void 0 && col in m.insert;
|
|
3229
|
+
addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...insertOnly ? { note: "insert only" } : {} });
|
|
3230
|
+
}
|
|
3231
|
+
if (m.op === "update" || m.op === "delete") walkFilter(m.where, schema, sig);
|
|
3232
|
+
if (m.op === "insertEach") {
|
|
3233
|
+
const itemKeys = Object.values(m.values).filter((v) => v !== null && typeof v === "object" && "$item" in v).map((v) => v.$item);
|
|
3234
|
+
sig[m.items.$context] = { type: "json", note: `array of objects \u2014 one inserted row per element${itemKeys.length > 0 ? ` (keys: ${itemKeys.join(", ")})` : ""}` };
|
|
3235
|
+
}
|
|
3236
|
+
if (m.op === "upsert") {
|
|
3237
|
+
sig[m.key] = { ...columnInfo(`${m.table}.${m.key}`, schema), note: "upsert key \u2014 present updates that row, absent/empty inserts" };
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
return sig;
|
|
3241
|
+
};
|
|
3242
|
+
var collectQueryContext = (dsl, schema) => {
|
|
3243
|
+
const sig = {};
|
|
3244
|
+
const walkQuery = (q) => {
|
|
3245
|
+
for (const source of q.from) {
|
|
3246
|
+
if (typeof source !== "string") walkQuery(source.query);
|
|
3247
|
+
}
|
|
3248
|
+
if (q.filter !== void 0) walkFilter(q.filter, schema, sig);
|
|
3249
|
+
if (q.compute !== void 0) deepScan(q.compute, sig);
|
|
3250
|
+
if (q.aggregate !== void 0) deepScan(q.aggregate, sig);
|
|
3251
|
+
};
|
|
3252
|
+
walkQuery(dsl);
|
|
3253
|
+
return sig;
|
|
3254
|
+
};
|
|
3255
|
+
var mutationEffect = (def) => {
|
|
3256
|
+
const list = Array.isArray(def) ? def : [def];
|
|
3257
|
+
return list.flatMap((m) => {
|
|
3258
|
+
const base = { op: m.op, table: m.table, columns: Object.keys(columnsOf(m)).sort() };
|
|
3259
|
+
const conflictSet = (m.op === "insert" || m.op === "insertEach") && m.onConflict?.set !== void 0 ? m.onConflict.set : void 0;
|
|
3260
|
+
if (conflictSet === void 0) return [base];
|
|
3261
|
+
return [base, { op: "update", table: m.table, columns: Object.keys(conflictSet).sort() }];
|
|
3262
|
+
});
|
|
3263
|
+
};
|
|
3264
|
+
var requiredContextKeys = (m) => {
|
|
3265
|
+
const keys = /* @__PURE__ */ new Set();
|
|
3266
|
+
const cols = m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : {};
|
|
3267
|
+
for (const v of Object.values(cols)) {
|
|
3268
|
+
if (isContextRef(v)) keys.add(v.$context);
|
|
3269
|
+
else if (isLookupRef(v)) {
|
|
3270
|
+
const sub = {};
|
|
3271
|
+
deepScan(v.$lookup.where, sub);
|
|
3272
|
+
for (const k of Object.keys(sub)) keys.add(k);
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3275
|
+
if (m.op === "insertEach") keys.add(m.items.$context);
|
|
3276
|
+
if (m.op === "update" || m.op === "delete") {
|
|
3277
|
+
const sub = {};
|
|
3278
|
+
deepScan(m.where, sub);
|
|
3279
|
+
for (const k of Object.keys(sub)) keys.add(k);
|
|
3280
|
+
}
|
|
3281
|
+
return [...keys].sort();
|
|
3282
|
+
};
|
|
3283
|
+
var findOptional = (value) => {
|
|
3284
|
+
if (Array.isArray(value)) return value.some(findOptional);
|
|
3285
|
+
if (value === null || typeof value !== "object") return false;
|
|
3286
|
+
if ("optional" in value) return true;
|
|
3287
|
+
return Object.values(value).some(findOptional);
|
|
3288
|
+
};
|
|
3289
|
+
var lintMutation = (def) => {
|
|
3290
|
+
const issues = [];
|
|
3291
|
+
const list = Array.isArray(def) ? def : [def];
|
|
3292
|
+
for (const m of list) {
|
|
3293
|
+
if (findOptional(m)) {
|
|
3294
|
+
issues.push(`${m.op} on "${m.table}" contains an optional condition \u2014 a write's bounds cannot depend on what the caller chose to send`);
|
|
3295
|
+
}
|
|
3296
|
+
if (m.op !== "update" && m.op !== "delete") continue;
|
|
3297
|
+
const sub = {};
|
|
3298
|
+
deepScan(m.where, sub);
|
|
3299
|
+
if (Object.keys(sub).length === 0) {
|
|
3300
|
+
issues.push(`${m.op} on "${m.table}" has no $context-keyed WHERE \u2014 the write is not caller-bounded`);
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
return issues;
|
|
3304
|
+
};
|
|
3305
|
+
|
|
3306
|
+
// src/cache/seed.ts
|
|
3307
|
+
var same = (a, b) => a === void 0 || b === void 0 ? a === b : canonicalText(a) === canonicalText(b);
|
|
3308
|
+
var seedCache = async (cache, entries) => {
|
|
3309
|
+
for (const entry of entries) {
|
|
3310
|
+
const existing = await cache.get(entry.fingerprint);
|
|
3311
|
+
if ("mutation" in entry) {
|
|
3312
|
+
const issues = lintMutation(entry.mutation);
|
|
3313
|
+
if (issues.length > 0) {
|
|
3314
|
+
throw new Error(`Mutation seed "${entry.fingerprint}" fails the authoring lint:
|
|
3315
|
+
${issues.join("\n ")}`);
|
|
3316
|
+
}
|
|
3317
|
+
const current2 = existing?.kind === "mutation" && existing.protected === true && same(existing.mutation, entry.mutation) && same(existing.reach, entry.reach) && same(existing.intent, entry.intent);
|
|
3318
|
+
if (current2) continue;
|
|
3319
|
+
await cache.set(entry.fingerprint, {
|
|
3320
|
+
kind: "mutation",
|
|
3321
|
+
mutation: entry.mutation,
|
|
3322
|
+
...entry.reach !== void 0 ? { reach: entry.reach } : {},
|
|
3323
|
+
...entry.intent !== void 0 ? { intent: entry.intent } : {},
|
|
3324
|
+
protected: true,
|
|
3325
|
+
createdAt: Date.now()
|
|
3326
|
+
});
|
|
3327
|
+
continue;
|
|
3328
|
+
}
|
|
3329
|
+
const prismIr = await prism.compile(entry.mapping ?? { $ref: "$.result" });
|
|
3330
|
+
const current = existing?.kind === "ok" && existing.protected === true && existing.prismIr?.meta.fingerprint === prismIr.meta.fingerprint && same(existing.dsl, entry.dsl) && same(existing.shape, entry.shape) && same(existing.reach, entry.reach) && same(existing.intent, entry.intent) && (existing.refresh ?? "snapshot") === (entry.refresh ?? "snapshot");
|
|
3331
|
+
if (current) continue;
|
|
3332
|
+
await cache.set(entry.fingerprint, {
|
|
3333
|
+
kind: "ok",
|
|
3334
|
+
...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
|
|
3335
|
+
dsl: entry.dsl,
|
|
3336
|
+
prismIr,
|
|
3337
|
+
...entry.reach !== void 0 ? { reach: entry.reach } : {},
|
|
3338
|
+
...entry.intent !== void 0 ? { intent: entry.intent } : {},
|
|
3339
|
+
...entry.shape !== void 0 ? { shape: entry.shape } : {},
|
|
3340
|
+
protected: true,
|
|
3341
|
+
createdAt: Date.now()
|
|
3342
|
+
});
|
|
3343
|
+
}
|
|
3344
|
+
};
|
|
3345
|
+
|
|
3346
|
+
// src/mutations/engine.ts
|
|
3347
|
+
var isLookup = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
3348
|
+
var isItemRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$item" in v;
|
|
3349
|
+
var collectLookups = (m) => {
|
|
3350
|
+
const out = [];
|
|
3351
|
+
const scan = (cols) => {
|
|
3352
|
+
for (const v of Object.values(cols ?? {})) if (isLookup(v)) out.push(v.$lookup);
|
|
3353
|
+
};
|
|
3354
|
+
if (m.op === "insert" || m.op === "insertEach") {
|
|
3355
|
+
scan(m.values);
|
|
3356
|
+
scan(m.onConflict?.set);
|
|
3357
|
+
}
|
|
3358
|
+
if (m.op === "update") scan(m.set);
|
|
3359
|
+
return out;
|
|
3360
|
+
};
|
|
3361
|
+
var findEntity2 = (table, schema) => schema.entities.find((e) => e.table === table || e.name === table);
|
|
3362
|
+
var assertConflictTarget = (table, target, entity) => {
|
|
3363
|
+
const uniqueSets = [
|
|
3364
|
+
entity.fields.filter((f) => f.primaryKey).map((f) => f.name),
|
|
3365
|
+
...entity.indexes.filter((i) => i.unique).map((i) => [...i.fields])
|
|
3366
|
+
].filter((s) => s.length > 0);
|
|
3367
|
+
if (uniqueSets.length === 0) return;
|
|
3368
|
+
const want = new Set(target);
|
|
3369
|
+
const ok = uniqueSets.some((s) => s.length === want.size && s.every((c) => want.has(c)));
|
|
3370
|
+
if (!ok) {
|
|
3371
|
+
throw new VexError(
|
|
3372
|
+
"invalid_dsl",
|
|
3373
|
+
`onConflict target (${target.join(", ")}) does not match a unique constraint on "${table}". Unique column sets: ${uniqueSets.map((s) => `(${s.join(", ")})`).join(" ")}.`
|
|
3374
|
+
);
|
|
3375
|
+
}
|
|
3376
|
+
};
|
|
3377
|
+
var filterColumns = (filter) => {
|
|
3378
|
+
const out = [];
|
|
3379
|
+
const value = (v) => {
|
|
3380
|
+
if (isFieldPathShape(v)) out.push(v);
|
|
3381
|
+
};
|
|
3382
|
+
const walk = (f) => {
|
|
3383
|
+
if ("and" in f) return f.and.forEach(walk);
|
|
3384
|
+
if ("or" in f) return f.or.forEach(walk);
|
|
3385
|
+
if ("not" in f) return walk(f.not);
|
|
3386
|
+
if ("eq" in f) return f.eq.forEach(value);
|
|
3387
|
+
if ("neq" in f) return f.neq.forEach(value);
|
|
3388
|
+
if ("gt" in f) return f.gt.forEach(value);
|
|
3389
|
+
if ("gte" in f) return f.gte.forEach(value);
|
|
3390
|
+
if ("lt" in f) return f.lt.forEach(value);
|
|
3391
|
+
if ("lte" in f) return f.lte.forEach(value);
|
|
3392
|
+
if ("in" in f || "notIn" in f) {
|
|
3393
|
+
const [field, target] = "in" in f ? f.in : f.notIn;
|
|
3394
|
+
out.push(field);
|
|
3395
|
+
if (Array.isArray(target)) target.forEach(value);
|
|
3396
|
+
return;
|
|
3397
|
+
}
|
|
3398
|
+
if ("like" in f || "ilike" in f) {
|
|
3399
|
+
const [field, pattern] = "like" in f ? f.like : f.ilike;
|
|
3400
|
+
out.push(field);
|
|
3401
|
+
return value(pattern);
|
|
3402
|
+
}
|
|
3403
|
+
if ("isNull" in f) return void out.push(f.isNull);
|
|
3404
|
+
if ("isNotNull" in f) return void out.push(f.isNotNull);
|
|
3405
|
+
if ("semantic" in f) return void out.push(f.semantic.field);
|
|
3406
|
+
if ("fuzzy" in f) return void out.push(f.fuzzy.field);
|
|
3407
|
+
};
|
|
3408
|
+
walk(filter);
|
|
3409
|
+
return out;
|
|
3410
|
+
};
|
|
3411
|
+
var assertFilterColumns = (filter, table, schema, where) => {
|
|
3412
|
+
const entity = findEntity2(table, schema);
|
|
3413
|
+
if (entity === void 0) throw new VexError("invalid_dsl", `Unknown table "${table}" in ${where}.`);
|
|
3414
|
+
for (const path of filterColumns(filter)) {
|
|
3415
|
+
const dot = path.indexOf(".");
|
|
3416
|
+
const owner = path.slice(0, dot);
|
|
3417
|
+
const column = path.slice(dot + 1);
|
|
3418
|
+
if (!isFieldPathShape(path) || owner !== table || !entity.fields.some((f) => f.name === column)) {
|
|
3419
|
+
throw new VexError("invalid_dsl", `"${path}" in ${where} is not a column of "${table}".`);
|
|
3420
|
+
}
|
|
3421
|
+
}
|
|
3422
|
+
};
|
|
3423
|
+
var assertWritableColumns = (m, schema) => {
|
|
3424
|
+
const entity = findEntity2(m.table, schema);
|
|
3425
|
+
if (entity === void 0) throw new VexError("invalid_dsl", `Unknown table "${m.table}".`);
|
|
3426
|
+
if (m.op === "update" || m.op === "delete") assertFilterColumns(m.where, m.table, schema, "the WHERE");
|
|
3427
|
+
const known = new Set(entity.fields.map((f) => f.name));
|
|
3428
|
+
const cols = m.op === "insert" || m.op === "insertEach" ? Object.keys(m.values) : m.op === "update" ? Object.keys(m.set) : [];
|
|
3429
|
+
for (const c of cols) {
|
|
3430
|
+
if (!known.has(c)) throw new VexError("invalid_dsl", `Unknown column "${m.table}.${c}".`);
|
|
3431
|
+
}
|
|
3432
|
+
for (const l of collectLookups(m)) {
|
|
3433
|
+
const le = findEntity2(l.from, schema);
|
|
3434
|
+
if (le === void 0) throw new VexError("invalid_dsl", `Unknown table "${l.from}" in $lookup.`);
|
|
3435
|
+
if (!le.fields.some((f) => f.name === l.field)) throw new VexError("invalid_dsl", `Unknown column "${l.from}.${l.field}" in $lookup.`);
|
|
3436
|
+
assertFilterColumns(l.where, l.from, schema, "a $lookup");
|
|
3437
|
+
}
|
|
3438
|
+
if ((m.op === "insert" || m.op === "insertEach") && m.onConflict !== void 0) {
|
|
3439
|
+
for (const c of [...m.onConflict.target, ...Object.keys(m.onConflict.set ?? {})]) {
|
|
3440
|
+
if (!known.has(c)) throw new VexError("invalid_dsl", `Unknown column "${m.table}.${c}" in onConflict.`);
|
|
3441
|
+
}
|
|
3442
|
+
assertConflictTarget(m.table, m.onConflict.target, entity);
|
|
3443
|
+
if (m.onConflict.where !== void 0) assertFilterColumns(m.onConflict.where, m.table, schema, "onConflict");
|
|
3444
|
+
}
|
|
3445
|
+
};
|
|
3446
|
+
var readMatchesFor = (table, policy) => {
|
|
3447
|
+
const rule = policy.entities[table];
|
|
3448
|
+
if (rule === void 0) {
|
|
3449
|
+
if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
|
|
3450
|
+
return [];
|
|
3451
|
+
}
|
|
3452
|
+
if ("public" in rule) return [];
|
|
3453
|
+
if ("deny" in rule) throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
|
|
3454
|
+
if (rule.read === void 0) {
|
|
3455
|
+
if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
|
|
3456
|
+
return [];
|
|
3457
|
+
}
|
|
3458
|
+
return rule.read;
|
|
3459
|
+
};
|
|
3460
|
+
var boundaryOf = (table, r) => isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };
|
|
3461
|
+
var scopeLookups = (cols, policy) => {
|
|
3462
|
+
const out = {};
|
|
3463
|
+
for (const [k, v] of Object.entries(cols)) {
|
|
3464
|
+
if (!isLookup(v)) {
|
|
3465
|
+
out[k] = v;
|
|
3466
|
+
continue;
|
|
3467
|
+
}
|
|
3468
|
+
let where = v.$lookup.where;
|
|
3469
|
+
for (const r of readMatchesFor(v.$lookup.from, policy)) {
|
|
3470
|
+
where = { and: [where, boundaryOf(v.$lookup.from, r)] };
|
|
3471
|
+
}
|
|
3472
|
+
out[k] = { $lookup: { ...v.$lookup, where } };
|
|
3473
|
+
}
|
|
3474
|
+
return out;
|
|
3475
|
+
};
|
|
3476
|
+
var writeGate = (table, op, policy) => {
|
|
3477
|
+
const rule = policy.entities[table];
|
|
3478
|
+
if (rule === void 0) {
|
|
3479
|
+
if (policy.default === "deny") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
|
|
3480
|
+
return void 0;
|
|
3481
|
+
}
|
|
3482
|
+
if ("public" in rule) return void 0;
|
|
3483
|
+
if ("deny" in rule) throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
|
|
3484
|
+
const specific = op === "insert" ? rule.insert : op === "update" ? rule.update : rule.delete;
|
|
3485
|
+
if (rule.write === void 0 && specific === void 0) {
|
|
3486
|
+
if (policy.default === "deny") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
|
|
3487
|
+
return void 0;
|
|
3488
|
+
}
|
|
3489
|
+
return { rule, rules: [...rule.write ?? [], ...specific ?? []] };
|
|
3490
|
+
};
|
|
3491
|
+
var scopeInsertParts = (table, rawValues, rawConflict, policy) => {
|
|
3492
|
+
let values = scopeLookups(rawValues, policy);
|
|
3493
|
+
let conflict = rawConflict === void 0 || rawConflict.set === void 0 ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };
|
|
3494
|
+
const gate = writeGate(table, "insert", policy);
|
|
3495
|
+
if (gate === void 0) return { values, conflict };
|
|
3496
|
+
for (const r of gate.rules) {
|
|
3497
|
+
if ("match" in r && isSetMatch(r)) {
|
|
3498
|
+
throw new VexScopeError(
|
|
3499
|
+
table,
|
|
3500
|
+
`Scope rule for "${table}" is set-valued ("${r.match}" in "${r.in}") and cannot pin an INSERT \u2014 a write's subject must be a single value. Use a scalar match, or carry the subject in a $lookup whose own read rules bound it.`
|
|
3501
|
+
);
|
|
3502
|
+
}
|
|
3503
|
+
values = { ...values, ["set" in r ? r.set : r.match]: { $scope: r.to } };
|
|
3504
|
+
}
|
|
3505
|
+
if (conflict?.set !== void 0) {
|
|
3506
|
+
if (gate.rule.write === void 0 && gate.rule.update === void 0) {
|
|
3507
|
+
throw new VexScopeError(table, `onConflict on "${table}" declares DO UPDATE, but this principal has no update grant.`);
|
|
3508
|
+
}
|
|
3509
|
+
for (const r of [...gate.rule.write ?? [], ...gate.rule.update ?? []]) {
|
|
3510
|
+
if ("set" in r) {
|
|
3511
|
+
conflict = { ...conflict, set: { ...conflict.set ?? {}, [r.set]: { $scope: r.to } } };
|
|
3512
|
+
} else if (!conflict.target.includes(r.match)) {
|
|
3513
|
+
const boundary = boundaryOf(table, r);
|
|
3514
|
+
conflict = { ...conflict, where: conflict.where === void 0 ? boundary : { and: [conflict.where, boundary] } };
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
return { values, conflict };
|
|
3519
|
+
};
|
|
3520
|
+
var scopeMutation = (m, policy) => {
|
|
3521
|
+
if (m.op === "insert") {
|
|
3522
|
+
const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);
|
|
3523
|
+
return { op: "insert", table: m.table, values, ...conflict === void 0 ? {} : { onConflict: conflict } };
|
|
3524
|
+
}
|
|
3525
|
+
if (m.op === "insertEach") {
|
|
3526
|
+
const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);
|
|
3527
|
+
return { op: "insertEach", table: m.table, items: m.items, values, ...conflict === void 0 ? {} : { onConflict: conflict } };
|
|
3528
|
+
}
|
|
3529
|
+
if (m.op === "update") {
|
|
3530
|
+
let set = scopeLookups(m.set, policy);
|
|
3531
|
+
let where2 = m.where;
|
|
3532
|
+
const gate2 = writeGate(m.table, "update", policy);
|
|
3533
|
+
if (gate2 !== void 0) {
|
|
3534
|
+
for (const r of gate2.rules) {
|
|
3535
|
+
if ("set" in r) set = { ...set, [r.set]: { $scope: r.to } };
|
|
3536
|
+
else where2 = { and: [where2, boundaryOf(m.table, r)] };
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
return { op: "update", table: m.table, set, where: where2 };
|
|
3540
|
+
}
|
|
3541
|
+
let where = m.where;
|
|
3542
|
+
const gate = writeGate(m.table, "delete", policy);
|
|
3543
|
+
if (gate !== void 0) {
|
|
3544
|
+
for (const r of gate.rules) {
|
|
3545
|
+
if ("match" in r) where = { and: [where, boundaryOf(m.table, r)] };
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
return { op: "delete", table: m.table, where };
|
|
3549
|
+
};
|
|
3550
|
+
var newCtx = () => ({
|
|
3551
|
+
resolvedPaths: /* @__PURE__ */ new Map(),
|
|
3552
|
+
aliasMap: /* @__PURE__ */ new Map(),
|
|
3553
|
+
paramSlots: [],
|
|
3554
|
+
paramCounter: { value: 0 }
|
|
3555
|
+
});
|
|
3556
|
+
var indexFilterFields = (filter, aliasMap) => {
|
|
3557
|
+
for (const path of filterColumns(filter)) aliasMap.set(path, path);
|
|
3558
|
+
};
|
|
3559
|
+
var compileValue = (v, ctx) => {
|
|
3560
|
+
if (isLookup(v)) {
|
|
3561
|
+
indexFilterFields(v.$lookup.where, ctx.aliasMap);
|
|
3562
|
+
const where = compileFilter(v.$lookup.where, ctx);
|
|
3563
|
+
return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
|
|
3564
|
+
}
|
|
3565
|
+
return compileFieldOrValue(v, ctx);
|
|
3566
|
+
};
|
|
3567
|
+
var compileColumnValue = (table, column, v, ctx, schema) => {
|
|
3568
|
+
const before = ctx.paramSlots.length;
|
|
3569
|
+
const sql = compileValue(v, ctx);
|
|
3570
|
+
const json = findEntity2(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === "json";
|
|
3571
|
+
if (json && typeof v === "object" && v !== null && "$context" in v) {
|
|
3572
|
+
const slot = ctx.paramSlots[before];
|
|
3573
|
+
if (slot !== void 0) ctx.paramSlots[before] = { ...slot, encode: "json" };
|
|
3574
|
+
}
|
|
3575
|
+
return sql;
|
|
3576
|
+
};
|
|
3577
|
+
var compileConflict = (m, ctx, schema) => {
|
|
3578
|
+
const c = m.onConflict;
|
|
3579
|
+
if (c === void 0) return "";
|
|
3580
|
+
if (c.set === void 0) return ` ON CONFLICT (${c.target.join(", ")}) DO NOTHING`;
|
|
3581
|
+
const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);
|
|
3582
|
+
let where = "";
|
|
3583
|
+
if (c.where !== void 0) {
|
|
3584
|
+
indexFilterFields(c.where, ctx.aliasMap);
|
|
3585
|
+
where = ` WHERE ${compileFilter(c.where, ctx)}`;
|
|
3586
|
+
}
|
|
3587
|
+
return ` ON CONFLICT (${c.target.join(", ")}) DO UPDATE SET ${sets.join(", ")}${where}`;
|
|
3588
|
+
};
|
|
3589
|
+
var ITEM_CAST = {
|
|
3590
|
+
number: "numeric",
|
|
3591
|
+
boolean: "boolean",
|
|
3592
|
+
date: "date",
|
|
3593
|
+
timestamp: "timestamptz",
|
|
3594
|
+
uuid: "uuid"
|
|
3595
|
+
};
|
|
3596
|
+
var compileMutation = (m, schema) => {
|
|
3597
|
+
const ctx = newCtx();
|
|
3598
|
+
if (m.op === "insert") {
|
|
3599
|
+
const entries = Object.entries(m.values);
|
|
3600
|
+
const cols = entries.map(([c]) => c);
|
|
3601
|
+
const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
|
|
3602
|
+
return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };
|
|
3603
|
+
}
|
|
3604
|
+
if (m.op === "insertEach") {
|
|
3605
|
+
const entity = findEntity2(m.table, schema);
|
|
3606
|
+
const entries = Object.entries(m.values);
|
|
3607
|
+
const cols = entries.map(([c]) => c);
|
|
3608
|
+
const exprs = entries.map(([col, v]) => {
|
|
3609
|
+
if (isItemRef(v)) {
|
|
3610
|
+
const nt = entity?.fields.find((f) => f.name === col)?.normalizedType ?? "string";
|
|
3611
|
+
if (nt === "json") return `(item.value->${quoteLiteral(v.$item)})`;
|
|
3612
|
+
const cast = ITEM_CAST[nt];
|
|
3613
|
+
const raw = `(item.value->>${quoteLiteral(v.$item)})`;
|
|
3614
|
+
return cast === void 0 ? raw : `${raw}::${cast}`;
|
|
3615
|
+
}
|
|
3616
|
+
return compileValue(v, ctx);
|
|
3617
|
+
});
|
|
3618
|
+
ctx.paramCounter.value += 1;
|
|
3619
|
+
ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
|
|
3620
|
+
const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;
|
|
3621
|
+
return {
|
|
3622
|
+
sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
|
|
3623
|
+
slots: ctx.paramSlots
|
|
3624
|
+
};
|
|
3625
|
+
}
|
|
3626
|
+
if (m.op === "update") {
|
|
3627
|
+
const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
|
|
3628
|
+
indexFilterFields(m.where, ctx.aliasMap);
|
|
3629
|
+
const where2 = compileFilter(m.where, ctx);
|
|
3630
|
+
return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots };
|
|
3631
|
+
}
|
|
3632
|
+
indexFilterFields(m.where, ctx.aliasMap);
|
|
3633
|
+
const where = compileFilter(m.where, ctx);
|
|
3634
|
+
return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };
|
|
3635
|
+
};
|
|
3636
|
+
var SUGAR = {
|
|
3637
|
+
upsert: (m, context) => {
|
|
3638
|
+
const keyed = context[m.key] !== void 0 && context[m.key] !== "";
|
|
3639
|
+
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 } };
|
|
3640
|
+
}
|
|
3641
|
+
};
|
|
3642
|
+
var desugarMutation = (m, context) => {
|
|
3643
|
+
const rewrite = SUGAR[m.op];
|
|
3644
|
+
return rewrite === void 0 ? m : rewrite(m, context);
|
|
3645
|
+
};
|
|
3646
|
+
var executeWrites = async (client, def, mctx) => {
|
|
3647
|
+
const parsed = MutationDefinitionSchema.parse(def);
|
|
3648
|
+
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
3649
|
+
const compiled = entries.map((entry) => {
|
|
3650
|
+
const core = desugarMutation(entry, mctx.context);
|
|
3651
|
+
const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
|
|
3652
|
+
if (missing.length > 0) {
|
|
3653
|
+
throw new VexError("missing_context", `Mutation is missing context: ${missing.join(", ")}.`, {
|
|
3654
|
+
expected: collectMutationContext(parsed, mctx.schema)
|
|
3655
|
+
});
|
|
3656
|
+
}
|
|
3657
|
+
const m = scopeMutation(core, mctx.policy);
|
|
3658
|
+
assertWritableColumns(m, mctx.schema);
|
|
3659
|
+
const statement = compileMutation(m, mctx.schema);
|
|
3660
|
+
requireScope({ paramSlots: statement.slots }, mctx.scope);
|
|
3661
|
+
return { ...statement, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
|
|
3662
|
+
});
|
|
3663
|
+
const runAll = async (q) => {
|
|
3664
|
+
const results = [];
|
|
3665
|
+
for (const c of compiled) {
|
|
3666
|
+
const params = await resolveParams(c.slots, mctx.context, mctx.scope);
|
|
3667
|
+
const bound = params.map((value, i) => {
|
|
3668
|
+
if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
|
|
3669
|
+
if (c.slots[i]?.type !== "json") return value;
|
|
3670
|
+
if (!Array.isArray(value)) {
|
|
3671
|
+
throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
|
|
3672
|
+
}
|
|
3673
|
+
return JSON.stringify(value);
|
|
3674
|
+
});
|
|
3675
|
+
const res = await q.query(c.sql, bound);
|
|
3676
|
+
results.push({ table: c.table, op: c.op, rows: res.rows });
|
|
3677
|
+
}
|
|
3678
|
+
return results;
|
|
3679
|
+
};
|
|
3680
|
+
if (compiled.length === 1) return runAll(client);
|
|
3681
|
+
if (client.transaction === void 0) {
|
|
3682
|
+
throw new VexError("execution_error", "Batch mutations require a transactional client.");
|
|
3683
|
+
}
|
|
3684
|
+
return client.transaction((tx) => runAll(tx));
|
|
3685
|
+
};
|
|
3686
|
+
var executeMutation = async (client, def, mctx) => (await executeWrites(client, def, mctx)).flatMap((w) => w.rows);
|
|
3687
|
+
var tablesChangedBy = (writes, schema) => {
|
|
3688
|
+
const changed = /* @__PURE__ */ new Set();
|
|
3689
|
+
const referencing = (table) => (schema?.entities.find((entity) => entity.name === table)?.relations ?? []).filter((relation) => relation.type !== "belongsTo").map((relation) => relation.entity);
|
|
3690
|
+
for (const write of writes) {
|
|
3691
|
+
if (write.rows.length === 0) continue;
|
|
3692
|
+
changed.add(write.table);
|
|
3693
|
+
if (write.op !== "delete") continue;
|
|
3694
|
+
const pending = [write.table];
|
|
3695
|
+
for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
|
|
3696
|
+
for (const table of referencing(next)) {
|
|
3697
|
+
if (changed.has(table)) continue;
|
|
3698
|
+
changed.add(table);
|
|
3699
|
+
pending.push(table);
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
}
|
|
3703
|
+
return [...changed];
|
|
3704
|
+
};
|
|
3705
|
+
var filterSchema = (schema, entities) => {
|
|
3706
|
+
if (schema === void 0) return [];
|
|
3707
|
+
if (entities === void 0 || entities.length === 0) return schema.entities;
|
|
3708
|
+
return schema.entities.filter((e) => entities.includes(e.name));
|
|
3709
|
+
};
|
|
3710
|
+
var canWriteTable = (policy, table, op) => {
|
|
3711
|
+
const rule = policy.entities[table];
|
|
3712
|
+
if (rule === void 0) return policy.default === "allow";
|
|
3713
|
+
if ("public" in rule) return true;
|
|
3714
|
+
if ("deny" in rule) return false;
|
|
3715
|
+
if (rule.write !== void 0 || policy.default === "allow") return true;
|
|
3716
|
+
if (op === "insert" || op === "insertEach") return rule.insert !== void 0;
|
|
3717
|
+
if (op === "update") return rule.update !== void 0;
|
|
3718
|
+
if (op === "delete") return rule.delete !== void 0;
|
|
3719
|
+
if (op === "upsert") return rule.insert !== void 0 || rule.update !== void 0;
|
|
3720
|
+
return false;
|
|
3721
|
+
};
|
|
3722
|
+
var collectTables = (dsl) => {
|
|
3723
|
+
const out = [];
|
|
3724
|
+
const walk = (q) => {
|
|
3725
|
+
for (const src of q.from) {
|
|
3726
|
+
if (typeof src === "string") out.push(src);
|
|
3727
|
+
else walk(src.query);
|
|
3728
|
+
}
|
|
3729
|
+
};
|
|
3730
|
+
walk(dsl);
|
|
3731
|
+
return out;
|
|
3732
|
+
};
|
|
3733
|
+
var entryVisible = (policy, entry) => {
|
|
3734
|
+
if (entry.kind === "ok") return collectTables(entry.dsl).every((t) => canReadTable(policy, t));
|
|
3735
|
+
if (entry.kind === "mutation") return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));
|
|
3736
|
+
return false;
|
|
3737
|
+
};
|
|
3738
|
+
var listFingerprints = async (engine, policy) => {
|
|
3739
|
+
if (engine.cache.entries === void 0) return [];
|
|
3740
|
+
const schema = engine.getSchema();
|
|
3741
|
+
const current = schema !== void 0 ? computeSchemaFingerprint(schema) : void 0;
|
|
3742
|
+
const rows = await engine.cache.entries();
|
|
3743
|
+
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 }) => ({
|
|
3744
|
+
fingerprint: key,
|
|
3745
|
+
kind: entry.kind === "mutation" ? "mutation" : "query",
|
|
3746
|
+
protected: entry.protected === true,
|
|
3747
|
+
schemaFresh: isEntryFresh(entry, current),
|
|
3748
|
+
...entry.intent !== void 0 ? { intent: entry.intent } : {},
|
|
3749
|
+
createdAt: entry.createdAt,
|
|
3750
|
+
...entry.lastUsedAt !== void 0 ? { lastUsedAt: entry.lastUsedAt } : {},
|
|
3751
|
+
// The derived contract — what to pass, straight from the stored def.
|
|
3752
|
+
...entry.kind === "ok" ? {
|
|
3753
|
+
context: collectQueryContext(entry.dsl, schema),
|
|
3754
|
+
...entry.shape !== void 0 ? { shape: entry.shape } : {}
|
|
3755
|
+
} : entry.kind === "mutation" ? {
|
|
3756
|
+
context: collectMutationContext(entry.mutation, schema),
|
|
3757
|
+
effect: mutationEffect(entry.mutation)
|
|
3758
|
+
} : {}
|
|
3759
|
+
}));
|
|
3760
|
+
};
|
|
3761
|
+
var handleDiscovery = async (config) => {
|
|
3762
|
+
const { engine, entities: entityFilter, scopePolicy } = config;
|
|
3763
|
+
const filtered = filterSchema(engine.getSchema(), entityFilter).filter(
|
|
3764
|
+
(e) => scopePolicy === void 0 || canReadTable(scopePolicy, e.name)
|
|
3765
|
+
);
|
|
3766
|
+
const fingerprints = await listFingerprints(engine, scopePolicy);
|
|
3767
|
+
const protectedCount = fingerprints.filter((f) => f.protected).length;
|
|
3768
|
+
return {
|
|
3769
|
+
protection: protectedCount === 0 ? "none" : protectedCount === fingerprints.length ? "all" : "some",
|
|
3770
|
+
locked: config.locked === true,
|
|
3771
|
+
fingerprints,
|
|
3772
|
+
vex: "1.0",
|
|
3773
|
+
description: "Query this resource using natural language or structured DSL",
|
|
3774
|
+
entities: filtered.map((e) => ({
|
|
3775
|
+
name: e.name,
|
|
3776
|
+
fields: e.fields.map((f) => ({
|
|
3777
|
+
name: f.name,
|
|
3778
|
+
type: f.normalizedType,
|
|
3779
|
+
nullable: f.nullable,
|
|
3780
|
+
primaryKey: f.primaryKey
|
|
3781
|
+
})),
|
|
3782
|
+
relations: e.relations.map((r) => ({
|
|
3783
|
+
entity: r.entity,
|
|
3784
|
+
type: r.type,
|
|
3785
|
+
via: r.localFields
|
|
3786
|
+
})),
|
|
3787
|
+
rowCount: e.rowCount
|
|
3788
|
+
})),
|
|
3789
|
+
query: {
|
|
3790
|
+
method: "POST",
|
|
3791
|
+
accepts: "application/json",
|
|
3792
|
+
body: {
|
|
3793
|
+
fingerprint: {
|
|
3794
|
+
type: "string",
|
|
3795
|
+
required: false,
|
|
3796
|
+
description: "Cache identity. Alone \u2192 replay a known query (no generation). With intent+shape \u2192 a named slot: matching request hits, differing request regenerates and replaces (409 when protected). Omitted \u2192 generate fresh; the minted fingerprint returns in meta.cache.fingerprint."
|
|
3797
|
+
},
|
|
3798
|
+
intent: {
|
|
3799
|
+
type: "string",
|
|
3800
|
+
required: false,
|
|
3801
|
+
description: "Natural language description of what data you need"
|
|
3802
|
+
},
|
|
3803
|
+
shape: {
|
|
3804
|
+
type: "any",
|
|
3805
|
+
required: false,
|
|
3806
|
+
description: "Example of the response structure \u2014 use empty strings, zeros, booleans as type indicators. Required unless replaying by fingerprint."
|
|
3807
|
+
},
|
|
3808
|
+
context: {
|
|
3809
|
+
type: "Record<string, unknown>",
|
|
3810
|
+
required: false,
|
|
3811
|
+
description: 'Runtime parameters referenced in filters as { $context: "key" }'
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
},
|
|
3815
|
+
dsl: zod.z.toJSONSchema(QuerySchema, { target: "draft-7", reused: "ref" })
|
|
3816
|
+
};
|
|
3817
|
+
};
|
|
3818
|
+
var rowsOf = (result) => Array.isArray(result) ? result.length : result === null || result === void 0 ? 0 : 1;
|
|
3819
|
+
var handleQuery = async (config, body, scope, live) => {
|
|
3820
|
+
if (config.onExecute === void 0) return runQuery(config, body, scope, void 0, live);
|
|
3821
|
+
const startUnixNano = Date.now() * 1e6;
|
|
3822
|
+
const t0 = elapsedClock();
|
|
3823
|
+
const probe = { kind: "query" };
|
|
3824
|
+
const result = await runQuery(config, body, scope, probe, live);
|
|
3825
|
+
const record = {
|
|
3826
|
+
kind: probe.kind,
|
|
3827
|
+
// 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a
|
|
3828
|
+
// fault); everything else is an error.
|
|
3829
|
+
status: result.status === 200 ? "ok" : result.status === 403 ? "refused" : "error",
|
|
3830
|
+
startUnixNano,
|
|
3831
|
+
endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,
|
|
3832
|
+
scope,
|
|
3833
|
+
...probe.fingerprint !== void 0 ? { fingerprint: probe.fingerprint } : {},
|
|
3834
|
+
...probe.reach !== void 0 ? { reach: probe.reach } : {},
|
|
3835
|
+
...probe.cacheHit !== void 0 ? { cacheHit: probe.cacheHit } : {},
|
|
3836
|
+
...probe.rows !== void 0 ? { rows: probe.rows } : {}
|
|
3837
|
+
};
|
|
3838
|
+
try {
|
|
3839
|
+
config.onExecute(record);
|
|
3840
|
+
} catch (err) {
|
|
3841
|
+
console.error("[vex:onExecute]", err);
|
|
3842
|
+
}
|
|
3843
|
+
return result;
|
|
3844
|
+
};
|
|
3845
|
+
var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
3846
|
+
var runQuery = async (config, body, scope, probe, live) => {
|
|
3847
|
+
const { engine } = config;
|
|
3848
|
+
if (strata.exceedsDepth(body)) return { status: 400, body: { error: "invalid_request", message: strata.depthRefusal() } };
|
|
3849
|
+
const parsed = QueryRequestSchema.safeParse(body);
|
|
3850
|
+
if (!parsed.success) {
|
|
3851
|
+
return {
|
|
3852
|
+
status: 400,
|
|
3853
|
+
body: {
|
|
3854
|
+
error: "invalid_request",
|
|
3855
|
+
message: parsed.error.message
|
|
3856
|
+
}
|
|
3857
|
+
};
|
|
3858
|
+
}
|
|
3859
|
+
const hasShape = parsed.data.shape !== void 0 && parsed.data.shape !== null;
|
|
3860
|
+
if (!hasShape && parsed.data.fingerprint === void 0) {
|
|
3861
|
+
return {
|
|
3862
|
+
status: 400,
|
|
3863
|
+
body: {
|
|
3864
|
+
error: "invalid_request",
|
|
3865
|
+
message: "Pass a fingerprint (replay) or intent + shape (generate) \u2014 or both (named slot)."
|
|
3866
|
+
}
|
|
3867
|
+
};
|
|
3868
|
+
}
|
|
3869
|
+
if (probe !== void 0 && parsed.data.fingerprint !== void 0) probe.fingerprint = parsed.data.fingerprint;
|
|
3870
|
+
try {
|
|
3871
|
+
let entryReach;
|
|
3872
|
+
if (parsed.data.fingerprint !== void 0) {
|
|
3873
|
+
const entry = await engine.cache.get(parsed.data.fingerprint);
|
|
3874
|
+
if (entry !== void 0 && entry.kind === "ok") entryReach = entry.reach;
|
|
3875
|
+
if (probe !== void 0 && entryReach !== void 0) probe.reach = entryReach;
|
|
3876
|
+
if (entry !== void 0 && entry.kind === "mutation") {
|
|
3877
|
+
if (probe !== void 0) {
|
|
3878
|
+
probe.kind = "mutation";
|
|
3879
|
+
if (entry.reach !== void 0) probe.reach = entry.reach;
|
|
3880
|
+
}
|
|
3881
|
+
if (config.mutations === void 0) {
|
|
3882
|
+
return {
|
|
3883
|
+
status: 500,
|
|
3884
|
+
body: { error: "execution_error", message: "This endpoint serves no mutations \u2014 handler has no mutation client configured." }
|
|
3885
|
+
};
|
|
3886
|
+
}
|
|
3887
|
+
const schema = engine.getSchema();
|
|
3888
|
+
if (schema === void 0) {
|
|
3889
|
+
return { status: 500, body: { error: "execution_error", message: "Vex schema not introspected." } };
|
|
3890
|
+
}
|
|
3891
|
+
let writePolicy = config.mutations.policy;
|
|
3892
|
+
if (entry.reach !== void 0) {
|
|
3893
|
+
if (config.policyForReach === void 0) {
|
|
3894
|
+
return {
|
|
3895
|
+
status: 500,
|
|
3896
|
+
body: {
|
|
3897
|
+
error: "execution_error",
|
|
3898
|
+
message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entry.reach}" and this handler has no policyForReach.`
|
|
3899
|
+
}
|
|
3900
|
+
};
|
|
3901
|
+
}
|
|
3902
|
+
const narrowed = await config.policyForReach(entry.reach);
|
|
3903
|
+
if (narrowed === void 0) {
|
|
3904
|
+
return {
|
|
3905
|
+
status: 403,
|
|
3906
|
+
body: { error: "scope_denied", message: `Reach "${entry.reach}" is not available to this principal.` }
|
|
3907
|
+
};
|
|
3908
|
+
}
|
|
3909
|
+
writePolicy = narrowed;
|
|
3910
|
+
}
|
|
3911
|
+
const writes = await executeWrites(config.mutations.client, entry.mutation, {
|
|
3912
|
+
context: parsed.data.context,
|
|
3913
|
+
scope,
|
|
3914
|
+
policy: writePolicy,
|
|
3915
|
+
schema
|
|
3916
|
+
});
|
|
3917
|
+
const rows = writes.flatMap((w) => w.rows);
|
|
3918
|
+
engine.invalidate(tablesChangedBy(writes, schema));
|
|
3919
|
+
if (config.mutations.onWrite !== void 0) {
|
|
3920
|
+
try {
|
|
3921
|
+
config.mutations.onWrite({ fingerprint: parsed.data.fingerprint, writes, scope });
|
|
3922
|
+
} catch (err) {
|
|
3923
|
+
console.error("[vex:onWrite]", err);
|
|
3924
|
+
}
|
|
3925
|
+
}
|
|
3926
|
+
const now = Date.now();
|
|
3927
|
+
if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));
|
|
3928
|
+
if (probe !== void 0) probe.rows = rows.length;
|
|
3929
|
+
return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };
|
|
3930
|
+
}
|
|
3931
|
+
}
|
|
3932
|
+
let readPolicy = config.scopePolicy;
|
|
3933
|
+
if (entryReach !== void 0) {
|
|
3934
|
+
if (config.policyForReach === void 0) {
|
|
3935
|
+
return {
|
|
3936
|
+
status: 500,
|
|
3937
|
+
body: {
|
|
3938
|
+
error: "execution_error",
|
|
3939
|
+
message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entryReach}" and this handler has no policyForReach.`
|
|
3940
|
+
}
|
|
3941
|
+
};
|
|
3942
|
+
}
|
|
3943
|
+
readPolicy = await config.policyForReach(entryReach);
|
|
3944
|
+
if (readPolicy === void 0) {
|
|
3945
|
+
return {
|
|
3946
|
+
status: 403,
|
|
3947
|
+
body: { error: "scope_denied", message: `Reach "${entryReach}" is not available to this principal.` }
|
|
3948
|
+
};
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
const response = await engine.execute(parsed.data, {
|
|
3952
|
+
scope,
|
|
3953
|
+
entities: config.entities,
|
|
3954
|
+
...config.locked === true ? { locked: true } : {},
|
|
3955
|
+
...readPolicy !== void 0 ? { scopePolicy: readPolicy } : {},
|
|
3956
|
+
...live !== void 0 ? { signal: live.signal, onChange: live.onChange } : {}
|
|
3957
|
+
});
|
|
3958
|
+
if (probe !== void 0) {
|
|
3959
|
+
probe.cacheHit = response.meta.cache.hit;
|
|
3960
|
+
if (response.meta.cache.fingerprint !== void 0) probe.fingerprint = response.meta.cache.fingerprint;
|
|
3961
|
+
probe.rows = rowsOf(response.result);
|
|
3962
|
+
}
|
|
3963
|
+
return { status: 200, body: response };
|
|
3964
|
+
} catch (err) {
|
|
3965
|
+
if (err instanceof VexError && err.code === "missing_scope") {
|
|
3966
|
+
console.error("[vex] refused a statement the host did not scope:", err.message);
|
|
3967
|
+
return { status: 500, body: { error: "missing_scope", message: "The server did not supply the scope this request needs." } };
|
|
3968
|
+
}
|
|
3969
|
+
if (err instanceof VexError) {
|
|
3970
|
+
const status = err.code === "fingerprint_protected" ? 409 : err.code === "cache_miss" ? 404 : 400;
|
|
3971
|
+
return {
|
|
3972
|
+
status,
|
|
3973
|
+
body: {
|
|
3974
|
+
error: err.code,
|
|
3975
|
+
message: err.message,
|
|
3976
|
+
details: err.details
|
|
3977
|
+
}
|
|
3978
|
+
};
|
|
3979
|
+
}
|
|
3980
|
+
console.error("[vex] unhandled error:", err);
|
|
3981
|
+
const errObj = err;
|
|
3982
|
+
const message = err instanceof Error ? err.message : typeof errObj?.message === "string" ? errObj.message : "Unknown error";
|
|
3983
|
+
const code = typeof errObj?.code === "string" ? errObj.code : "execution_error";
|
|
3984
|
+
return {
|
|
3985
|
+
status: 500,
|
|
3986
|
+
body: { error: code, message }
|
|
3987
|
+
};
|
|
3988
|
+
}
|
|
3989
|
+
};
|
|
3990
|
+
var handleFingerprintPatch = async (config, fingerprint, patch) => {
|
|
3991
|
+
if (config.locked === true) {
|
|
3992
|
+
return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
|
|
3993
|
+
}
|
|
3994
|
+
const entry = await config.engine.cache.get(fingerprint);
|
|
3995
|
+
if (entry === void 0 || entry.kind !== "ok" && entry.kind !== "mutation") {
|
|
3996
|
+
return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
|
|
3997
|
+
}
|
|
3998
|
+
if (typeof patch.protected !== "boolean") {
|
|
3999
|
+
return { status: 400, body: { error: "invalid_request", message: "Body must be { protected: boolean }" } };
|
|
4000
|
+
}
|
|
4001
|
+
await config.engine.cache.set(fingerprint, { ...entry, protected: patch.protected });
|
|
4002
|
+
return { status: 200, body: { fingerprint, protected: patch.protected } };
|
|
4003
|
+
};
|
|
4004
|
+
var handleFingerprintDelete = async (config, fingerprint) => {
|
|
4005
|
+
if (config.locked === true) {
|
|
4006
|
+
return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
|
|
4007
|
+
}
|
|
4008
|
+
const entry = await config.engine.cache.get(fingerprint);
|
|
4009
|
+
if (entry === void 0) {
|
|
4010
|
+
return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
|
|
4011
|
+
}
|
|
4012
|
+
if (entry.kind === "ok" && entry.protected === true) {
|
|
4013
|
+
return { status: 409, body: { error: "fingerprint_protected", message: `"${fingerprint}" is protected \u2014 unprotect it first.` } };
|
|
4014
|
+
}
|
|
4015
|
+
await config.engine.cache.delete(fingerprint);
|
|
4016
|
+
return { status: 200, body: { fingerprint, deleted: true } };
|
|
4017
|
+
};
|
|
4018
|
+
|
|
4019
|
+
exports.AggregateExpressionSchema = AggregateExpressionSchema;
|
|
4020
|
+
exports.ComputeExpressionSchema = ComputeExpressionSchema;
|
|
4021
|
+
exports.FilterSchema = FilterSchema;
|
|
4022
|
+
exports.MutationDefinitionSchema = MutationDefinitionSchema;
|
|
4023
|
+
exports.MutationSchema = MutationSchema;
|
|
4024
|
+
exports.QueryRequestSchema = QueryRequestSchema;
|
|
4025
|
+
exports.QuerySchema = QuerySchema;
|
|
4026
|
+
exports.REFRESH_MODES = REFRESH_MODES;
|
|
4027
|
+
exports.SCOPE_VERBS = SCOPE_VERBS;
|
|
4028
|
+
exports.VexError = VexError;
|
|
4029
|
+
exports.VexScopeError = VexScopeError;
|
|
4030
|
+
exports.analyze = analyze;
|
|
4031
|
+
exports.applyScope = applyScope;
|
|
4032
|
+
exports.buildContextContract = buildContextContract;
|
|
4033
|
+
exports.buildValidationContext = buildValidationContext;
|
|
4034
|
+
exports.checkScope = checkScope;
|
|
4035
|
+
exports.collectMutationContext = collectMutationContext;
|
|
4036
|
+
exports.collectQueryContext = collectQueryContext;
|
|
4037
|
+
exports.compileFieldOrValue = compileFieldOrValue;
|
|
4038
|
+
exports.compileFilter = compileFilter;
|
|
4039
|
+
exports.computeRequestHash = computeRequestHash;
|
|
4040
|
+
exports.computeSchemaFingerprint = computeSchemaFingerprint;
|
|
4041
|
+
exports.createMemoryCache = createMemoryCache;
|
|
4042
|
+
exports.createPostgresAdapter = createPostgresAdapter;
|
|
4043
|
+
exports.createPostgresCache = createPostgresCache;
|
|
4044
|
+
exports.createQueryEngine = createQueryEngine;
|
|
4045
|
+
exports.createScopePolicy = createScopePolicy;
|
|
4046
|
+
exports.createTieredCache = createTieredCache;
|
|
4047
|
+
exports.discoverEntities = discoverEntities;
|
|
4048
|
+
exports.executeMutation = executeMutation;
|
|
4049
|
+
exports.executeQuery = executeQuery;
|
|
4050
|
+
exports.executeWrites = executeWrites;
|
|
4051
|
+
exports.findMissingContext = findMissingContext;
|
|
4052
|
+
exports.handleDiscovery = handleDiscovery;
|
|
4053
|
+
exports.handleFingerprintDelete = handleFingerprintDelete;
|
|
4054
|
+
exports.handleFingerprintPatch = handleFingerprintPatch;
|
|
4055
|
+
exports.handleQuery = handleQuery;
|
|
4056
|
+
exports.isRefresh = isRefresh;
|
|
4057
|
+
exports.lintMutation = lintMutation;
|
|
4058
|
+
exports.mergeScopePolicies = mergeScopePolicies;
|
|
4059
|
+
exports.mintFingerprint = mintFingerprint;
|
|
4060
|
+
exports.mutationEffect = mutationEffect;
|
|
4061
|
+
exports.normalizeShape = normalizeShape;
|
|
4062
|
+
exports.optionalKeysOf = optionalKeysOf;
|
|
4063
|
+
exports.presenceOf = presenceOf;
|
|
4064
|
+
exports.pruneOptional = pruneOptional;
|
|
4065
|
+
exports.requiredContextKeys = requiredContextKeys;
|
|
4066
|
+
exports.resolve = resolve;
|
|
4067
|
+
exports.resolveParams = resolveParams;
|
|
4068
|
+
exports.scopeBindings = scopeBindings;
|
|
4069
|
+
exports.scopeGrants = scopeGrants;
|
|
4070
|
+
exports.scopeProfiles = scopeProfiles;
|
|
4071
|
+
exports.scopeResolved = scopeResolved;
|
|
4072
|
+
exports.seedCache = seedCache;
|
|
4073
|
+
exports.sweepCache = sweepCache;
|
|
4074
|
+
exports.tablesChangedBy = tablesChangedBy;
|
|
4075
|
+
exports.validateEntry = validateEntry;
|
|
4076
|
+
exports.vexGuide = vexGuide;
|
|
4077
|
+
//# sourceMappingURL=index.cjs.map
|
|
4078
|
+
//# sourceMappingURL=index.cjs.map
|