@crasi/bisque-ir 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/index.js +456 -0
- package/dist/index.js.map +7 -0
- package/dist/types/execute.d.ts +44 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/match.d.ts +22 -0
- package/dist/types/schema.d.ts +151 -0
- package/dist/types/server.d.ts +46 -0
- package/dist/types/validate.d.ts +48 -0
- package/package.json +46 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Crasi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @crasi/bisque-ir
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Query IR, validator and in-memory executor.
|
|
4
|
+
|
|
5
|
+
Part of [Bisque](https://github.com/gogeorge/bisque): contract-bounded, end-user generative customization for embedded web apps. A host declares a contract; its users ask for views and tools in plain language; a propose-only conductor returns a declarative spec that runs on the user's data in the browser. The model never sees a record.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @crasi/bisque-ir
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { validateIR, memoryExecutor } from "@crasi/bisque-ir";
|
|
13
|
+
|
|
14
|
+
const check = validateIR(query, manifest); // declared reads, joins only along refs, a mandatory limit
|
|
15
|
+
const executor = memoryExecutor(() => workingSet); // runs on the user's data, in the host's browser
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`serveQuery` and `serveDistinct` do the same over HTTP for hosts whose data lives on their own server.
|
|
19
|
+
|
|
20
|
+
Every Bisque package shares one version; see the [changelog](https://github.com/gogeorge/bisque/blob/main/CHANGELOG.md). Documentation lives in the
|
|
21
|
+
[repository](https://github.com/gogeorge/bisque#readme).
|
|
22
|
+
|
|
23
|
+
MIT © Crasi
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
// src/schema.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var Literal = z.union([z.string().max(200), z.number(), z.boolean(), z.null()]);
|
|
4
|
+
var ParamRef = z.object({ param: z.string() }).strict();
|
|
5
|
+
var TodayRef = z.object({ today: z.number().int().min(-3660).max(3660) }).strict();
|
|
6
|
+
var Scalar = z.union([Literal, ParamRef, TodayRef]);
|
|
7
|
+
var Value = z.union([Scalar, z.array(Scalar).max(200)]);
|
|
8
|
+
var COMPARE_OPS = ["=", "!=", "<", "<=", ">", ">="];
|
|
9
|
+
var SET_OPS = ["in", "notIn"];
|
|
10
|
+
var MATCH_OP = "match";
|
|
11
|
+
var NULL_OPS = ["isNull", "notNull"];
|
|
12
|
+
var Cond = z.union([z.tuple([z.string(), z.enum([...COMPARE_OPS, ...SET_OPS, MATCH_OP]), Value]), z.tuple([z.string(), z.enum(NULL_OPS)])]);
|
|
13
|
+
var Join = z.object({ on: z.string(), to: z.string() }).strict();
|
|
14
|
+
var AGGREGATES = ["sum", "avg", "min", "max", "count", "countDistinct"];
|
|
15
|
+
var measure = (k) => z.object({ [k]: z.string(), as: z.string() }).strict();
|
|
16
|
+
var Measure = z.union([measure("sum"), measure("avg"), measure("min"), measure("max"), measure("count"), measure("countDistinct")]);
|
|
17
|
+
var OrderKey = z.tuple([z.string(), z.enum(["asc", "desc"])]);
|
|
18
|
+
var IRSchema = z.object({
|
|
19
|
+
scan: z.string(),
|
|
20
|
+
join: z.array(Join).max(6).optional(),
|
|
21
|
+
where: z.array(Cond).max(20).optional(),
|
|
22
|
+
groupBy: z.array(z.string()).max(4).optional(),
|
|
23
|
+
measures: z.array(Measure).max(8).optional(),
|
|
24
|
+
select: z.array(z.string()).max(24).optional(),
|
|
25
|
+
orderBy: z.array(OrderKey).max(4).optional(),
|
|
26
|
+
limit: z.number().int()
|
|
27
|
+
}).strict();
|
|
28
|
+
function measureOf(m) {
|
|
29
|
+
const agg = AGGREGATES.find((a) => a in m);
|
|
30
|
+
return { agg, field: m[agg], as: m.as };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/validate.ts
|
|
34
|
+
import { MAX_ROWS, problem } from "@crasi/bisque-core";
|
|
35
|
+
import { canRead } from "@crasi/bisque-contract";
|
|
36
|
+
function zodProblems(err, prefix2 = "") {
|
|
37
|
+
return err.issues.map((i) => problem([prefix2, ...i.path.map(String)].filter(Boolean).join("."), "schema", i.message));
|
|
38
|
+
}
|
|
39
|
+
function resolveField(m, scope, name) {
|
|
40
|
+
const dot = name.indexOf(".");
|
|
41
|
+
const [resource, field] = dot < 0 ? [scope.scan, name] : [name.slice(0, dot), name.slice(dot + 1)];
|
|
42
|
+
if (!scope.resources.has(resource)) {
|
|
43
|
+
return m.resources[resource] ? `"${resource}" is not joined; add a join along a declared reference to use ${name}` : `unknown resource "${resource}"`;
|
|
44
|
+
}
|
|
45
|
+
const desc = m.resources[resource]?.fields[field];
|
|
46
|
+
if (!desc) {
|
|
47
|
+
const known = Object.keys(m.resources[resource]?.fields ?? {}).join(", ");
|
|
48
|
+
return dot < 0 && scope.resources.size > 1 ? `"${field}" is not a field of ${resource}; qualify fields of joined resources, e.g. products.name (fields of ${resource}: ${known})` : `"${field}" is not a field of ${resource} (fields: ${known})`;
|
|
49
|
+
}
|
|
50
|
+
return { resource, field, desc };
|
|
51
|
+
}
|
|
52
|
+
var ORDERABLE = ["number", "date", "datetime", "string", "enum"];
|
|
53
|
+
function validateIR(input, m, opts = {}) {
|
|
54
|
+
const out = { ok: false, problems: [], touched: [], columns: {}, params: [] };
|
|
55
|
+
const parsed = IRSchema.safeParse(input);
|
|
56
|
+
if (!parsed.success) {
|
|
57
|
+
out.problems = zodProblems(parsed.error);
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
const ir = parsed.data;
|
|
61
|
+
out.ir = ir;
|
|
62
|
+
const P = out.problems;
|
|
63
|
+
const scanRes = m.resources[ir.scan];
|
|
64
|
+
if (!scanRes) {
|
|
65
|
+
P.push(problem("scan", "unknown_resource", `unknown resource "${ir.scan}" (resources: ${Object.keys(m.resources).join(", ")})`));
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
const scope = { scan: ir.scan, resources: /* @__PURE__ */ new Set([ir.scan]) };
|
|
69
|
+
(ir.join ?? []).forEach((j, i) => {
|
|
70
|
+
const on = resolveField(m, scope, j.on);
|
|
71
|
+
if (typeof on === "string") return P.push(problem(`join.${i}.on`, "unknown_field", on));
|
|
72
|
+
if (!m.resources[j.to]) return P.push(problem(`join.${i}.to`, "unknown_resource", `unknown resource "${j.to}"`));
|
|
73
|
+
if (on.desc.ref !== j.to)
|
|
74
|
+
return P.push(
|
|
75
|
+
problem(`join.${i}`, "undeclared_join", on.desc.ref ? `${j.on} references ${on.desc.ref}, not ${j.to}` : `${j.on} is not a declared reference, so it cannot be joined`)
|
|
76
|
+
);
|
|
77
|
+
if (scope.resources.has(j.to)) return P.push(problem(`join.${i}.to`, "undeclared_join", `${j.to} is already in the query; each resource can be joined once`));
|
|
78
|
+
scope.resources.add(j.to);
|
|
79
|
+
});
|
|
80
|
+
out.touched = [...scope.resources];
|
|
81
|
+
const params = /* @__PURE__ */ new Set();
|
|
82
|
+
const checkValue = (path, v, desc) => {
|
|
83
|
+
const scalars = Array.isArray(v) ? v : [v];
|
|
84
|
+
for (const s of scalars) {
|
|
85
|
+
if (s && typeof s === "object" && "param" in s) {
|
|
86
|
+
params.add(s.param);
|
|
87
|
+
if (opts.params && !(s.param in opts.params)) P.push(problem(path, "unknown_param", `param "${s.param}" is not declared in the spec's params`));
|
|
88
|
+
} else if (s && typeof s === "object" && "today" in s) {
|
|
89
|
+
if (desc.type !== "date" && desc.type !== "datetime") P.push(problem(path, "type", "{today: n} compares only with date fields"));
|
|
90
|
+
} else if (s !== null && desc.type === "number" && typeof s !== "number") P.push(problem(path, "type", "this field is a number"));
|
|
91
|
+
else if (s !== null && desc.type === "enum" && !desc.enum.includes(String(s))) P.push(problem(path, "type", `must be one of ${desc.enum.join(", ")}`));
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
(ir.where ?? []).forEach((c, i) => {
|
|
95
|
+
const path = `where.${i}`;
|
|
96
|
+
const f = resolveField(m, scope, c[0]);
|
|
97
|
+
if (typeof f === "string") return P.push(problem(`${path}.0`, "unknown_field", f));
|
|
98
|
+
const op = c[1];
|
|
99
|
+
if (op === "isNull" || op === "notNull") return;
|
|
100
|
+
const v = c[2];
|
|
101
|
+
if ((op === "in" || op === "notIn") && !Array.isArray(v)) P.push(problem(`${path}.2`, "type", `${op} takes a list`));
|
|
102
|
+
if (["<", "<=", ">", ">="].includes(op) && !ORDERABLE.includes(f.desc.type))
|
|
103
|
+
P.push(problem(`${path}.1`, "type", `${c[0]} is ${f.desc.type} and cannot be compared with ${op}`));
|
|
104
|
+
if (op === "match") {
|
|
105
|
+
if (f.desc.type !== "string") P.push(problem(`${path}.1`, "type", "match works on text fields such as names"));
|
|
106
|
+
const lits = Array.isArray(v) ? v : [v];
|
|
107
|
+
if (!lits.length || lits.some((x) => typeof x !== "string")) P.push(problem(`${path}.2`, "type", "match takes one name or a list of names"));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
checkValue(`${path}.2`, v, f.desc);
|
|
111
|
+
});
|
|
112
|
+
const columns = {};
|
|
113
|
+
const addColumn = (name, path) => {
|
|
114
|
+
const f = resolveField(m, scope, name);
|
|
115
|
+
if (typeof f === "string") return void P.push(problem(path, "unknown_field", f));
|
|
116
|
+
columns[name] = { ...f.desc, source: { resource: f.resource, field: f.field } };
|
|
117
|
+
};
|
|
118
|
+
const grouping = !!(ir.groupBy?.length || ir.measures?.length);
|
|
119
|
+
if (ir.select?.length && grouping) P.push(problem("select", "schema", "use select without groupBy/measures, or groupBy/measures without select"));
|
|
120
|
+
if (!ir.select?.length && !grouping) P.push(problem("", "schema", "a query must select fields, or group and measure"));
|
|
121
|
+
(ir.groupBy ?? []).forEach((g, i) => addColumn(g, `groupBy.${i}`));
|
|
122
|
+
(ir.select ?? []).forEach((s, i) => addColumn(s, `select.${i}`));
|
|
123
|
+
(ir.measures ?? []).forEach((raw, i) => {
|
|
124
|
+
const { agg, field, as } = measureOf(raw);
|
|
125
|
+
const path = `measures.${i}`;
|
|
126
|
+
if (!/^[a-z_][a-z0-9_]*$/i.test(as)) P.push(problem(`${path}.as`, "schema", "measure names are simple identifiers like value"));
|
|
127
|
+
if (columns[as]) P.push(problem(`${path}.as`, "schema", `"${as}" is already a column`));
|
|
128
|
+
if (agg === "count" && field === "*") {
|
|
129
|
+
columns[as] = { type: "number", nullable: false, measure: { agg, of: "*" } };
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const f = resolveField(m, scope, field);
|
|
133
|
+
if (typeof f === "string") return P.push(problem(`${path}.${agg}`, "unknown_field", f));
|
|
134
|
+
if ((agg === "sum" || agg === "avg") && f.desc.type !== "number") P.push(problem(`${path}.${agg}`, "type", `${agg} needs a number field; ${field} is ${f.desc.type}`));
|
|
135
|
+
if ((agg === "min" || agg === "max") && !ORDERABLE.includes(f.desc.type)) P.push(problem(`${path}.${agg}`, "type", `${agg} needs a number or date field`));
|
|
136
|
+
const type = agg === "count" || agg === "countDistinct" || agg === "sum" || agg === "avg" ? "number" : f.desc.type;
|
|
137
|
+
columns[as] = {
|
|
138
|
+
type,
|
|
139
|
+
nullable: agg === "min" || agg === "max" || agg === "avg",
|
|
140
|
+
label: agg === "min" || agg === "max" ? f.desc.label : void 0,
|
|
141
|
+
unit: agg === "sum" || agg === "avg" || agg === "min" || agg === "max" ? f.desc.unit : void 0,
|
|
142
|
+
measure: { agg, of: field }
|
|
143
|
+
};
|
|
144
|
+
});
|
|
145
|
+
out.columns = columns;
|
|
146
|
+
(ir.orderBy ?? []).forEach(([col], i) => {
|
|
147
|
+
if (!columns[col]) P.push(problem(`orderBy.${i}.0`, "unknown_field", `order by an output column (${Object.keys(columns).join(", ") || "none"})`));
|
|
148
|
+
});
|
|
149
|
+
const cap = Math.min(scanRes.cap ?? MAX_ROWS, MAX_ROWS, opts.maxLimit ?? MAX_ROWS);
|
|
150
|
+
if (ir.limit < 1 || ir.limit > cap) P.push(problem("limit", "limit", `limit must be between 1 and ${cap}`));
|
|
151
|
+
for (const r of out.touched) {
|
|
152
|
+
if (opts.reads && !opts.reads.includes(r)) P.push(problem("", "undeclared_read", `reads ${r}, which the manifest does not declare`));
|
|
153
|
+
if (opts.role && !canRead(m, opts.role, r)) P.push(problem("", "role_denied", `role ${opts.role} cannot read ${r}`));
|
|
154
|
+
}
|
|
155
|
+
out.params = [...params];
|
|
156
|
+
out.ok = P.length === 0;
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
function touched(ir) {
|
|
160
|
+
return [ir.scan, ...(ir.join ?? []).map((j) => j.to)];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/execute.ts
|
|
164
|
+
import { BisqueError, MAX_ROWS as MAX_ROWS2, canonicalJson } from "@crasi/bisque-core";
|
|
165
|
+
|
|
166
|
+
// src/match.ts
|
|
167
|
+
function normalize(s) {
|
|
168
|
+
return s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
169
|
+
}
|
|
170
|
+
function resolveMatches(ir, src, m) {
|
|
171
|
+
if (!ir.where?.some((c) => c[1] === "match")) return { ir, resolution: [] };
|
|
172
|
+
const resolution = [];
|
|
173
|
+
const where = ir.where.map((c) => {
|
|
174
|
+
if (c[1] !== "match") return c;
|
|
175
|
+
const name = c[0].includes(".") ? c[0] : `${ir.scan}.${c[0]}`;
|
|
176
|
+
const dot = name.indexOf(".");
|
|
177
|
+
const [resource, field] = [name.slice(0, dot), name.slice(dot + 1)];
|
|
178
|
+
if (!m.resources[resource]) return c;
|
|
179
|
+
const known = [
|
|
180
|
+
...new Set(
|
|
181
|
+
src(resource).map((r) => r[field]).filter((v) => v != null).map(String)
|
|
182
|
+
)
|
|
183
|
+
];
|
|
184
|
+
const lits = (Array.isArray(c[2]) ? c[2] : [c[2]]).map(String);
|
|
185
|
+
const chosen = [];
|
|
186
|
+
for (const lit of lits) {
|
|
187
|
+
const n = normalize(lit);
|
|
188
|
+
const exact = known.filter((k) => normalize(k) === n);
|
|
189
|
+
if (exact.length) {
|
|
190
|
+
chosen.push(...exact);
|
|
191
|
+
resolution.push({ field: c[0], literal: lit, status: "exact", values: exact });
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const partial = known.filter((k) => normalize(k).includes(n));
|
|
195
|
+
if (partial.length === 1) {
|
|
196
|
+
chosen.push(partial[0]);
|
|
197
|
+
resolution.push({ field: c[0], literal: lit, status: "unique", values: partial });
|
|
198
|
+
} else {
|
|
199
|
+
resolution.push({ field: c[0], literal: lit, status: partial.length ? "ambiguous" : "unmatched", values: partial.slice(0, 8) });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return [c[0], "in", chosen];
|
|
203
|
+
});
|
|
204
|
+
return { ir: { ...ir, where }, resolution };
|
|
205
|
+
}
|
|
206
|
+
function pickMatch(ir, field, literal, value) {
|
|
207
|
+
return {
|
|
208
|
+
...ir,
|
|
209
|
+
where: ir.where?.map((c) => {
|
|
210
|
+
if (c[0] !== field || c[1] !== "match") return c;
|
|
211
|
+
const lits = Array.isArray(c[2]) ? c[2] : [c[2]];
|
|
212
|
+
return [c[0], "match", lits.map((l) => l === literal ? value : l)];
|
|
213
|
+
})
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/execute.ts
|
|
218
|
+
var qualify = (scan, f) => f.includes(".") ? f : `${scan}.${f}`;
|
|
219
|
+
function prefix(resource, row) {
|
|
220
|
+
const out = {};
|
|
221
|
+
for (const k in row) out[`${resource}.${k}`] = row[k];
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
function addDaysIso(date, days) {
|
|
225
|
+
const d = /* @__PURE__ */ new Date(`${date.slice(0, 10)}T00:00:00Z`);
|
|
226
|
+
d.setUTCDate(d.getUTCDate() + days);
|
|
227
|
+
return d.toISOString().slice(0, 10);
|
|
228
|
+
}
|
|
229
|
+
function resolveScalar(v, opts) {
|
|
230
|
+
if (v && typeof v === "object" && "param" in v) {
|
|
231
|
+
if (!opts.params || !(v.param in opts.params)) throw new BisqueError(`param "${v.param}" has no value`);
|
|
232
|
+
return opts.params[v.param];
|
|
233
|
+
}
|
|
234
|
+
if (v && typeof v === "object" && "today" in v) return addDaysIso(opts.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), v.today);
|
|
235
|
+
return v;
|
|
236
|
+
}
|
|
237
|
+
function resolveValue(v, opts) {
|
|
238
|
+
return Array.isArray(v) ? v.map((x) => resolveScalar(x, opts)) : resolveScalar(v, opts);
|
|
239
|
+
}
|
|
240
|
+
function cmp(a, op, b) {
|
|
241
|
+
switch (op) {
|
|
242
|
+
case "=":
|
|
243
|
+
return a === b || a != null && b != null && String(a) === String(b);
|
|
244
|
+
case "!=":
|
|
245
|
+
return !(a === b || a != null && b != null && String(a) === String(b));
|
|
246
|
+
case "<":
|
|
247
|
+
return a != null && b != null && a < b;
|
|
248
|
+
case "<=":
|
|
249
|
+
return a != null && b != null && a <= b;
|
|
250
|
+
case ">":
|
|
251
|
+
return a != null && b != null && a > b;
|
|
252
|
+
case ">=":
|
|
253
|
+
return a != null && b != null && a >= b;
|
|
254
|
+
case "in":
|
|
255
|
+
return b.some((x) => x === a || String(x) === String(a));
|
|
256
|
+
case "notIn":
|
|
257
|
+
return !b.some((x) => x === a || String(x) === String(a));
|
|
258
|
+
case "isNull":
|
|
259
|
+
return a == null;
|
|
260
|
+
case "notNull":
|
|
261
|
+
return a != null;
|
|
262
|
+
}
|
|
263
|
+
throw new BisqueError(`unknown operator ${op}`);
|
|
264
|
+
}
|
|
265
|
+
var clean = (n) => Math.round(n * 1e6) / 1e6;
|
|
266
|
+
function aggregate(agg, field, rows) {
|
|
267
|
+
if (agg === "count") return field === "*" ? rows.length : rows.filter((r) => r[field] != null).length;
|
|
268
|
+
const vals = rows.map((r) => r[field]).filter((v) => v != null);
|
|
269
|
+
if (agg === "countDistinct") return new Set(vals.map(String)).size;
|
|
270
|
+
if (!vals.length) return agg === "sum" ? 0 : null;
|
|
271
|
+
if (agg === "sum") return clean(vals.reduce((a, b) => a + b, 0));
|
|
272
|
+
if (agg === "avg") return clean(vals.reduce((a, b) => a + b, 0) / vals.length);
|
|
273
|
+
if (agg === "min") return vals.reduce((a, b) => b < a ? b : a);
|
|
274
|
+
if (agg === "max") return vals.reduce((a, b) => b > a ? b : a);
|
|
275
|
+
throw new BisqueError(`unknown aggregate ${agg}`);
|
|
276
|
+
}
|
|
277
|
+
function compareValues(a, b) {
|
|
278
|
+
if (a == null && b == null) return 0;
|
|
279
|
+
if (a == null) return 1;
|
|
280
|
+
if (b == null) return -1;
|
|
281
|
+
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
282
|
+
return String(a).localeCompare(String(b));
|
|
283
|
+
}
|
|
284
|
+
function runIR(input, src, opts) {
|
|
285
|
+
const m = opts.manifest;
|
|
286
|
+
const { ir, resolution } = resolveMatches(input, src, m);
|
|
287
|
+
const scanRes = m.resources[ir.scan];
|
|
288
|
+
if (!scanRes) throw new BisqueError(`unknown resource ${ir.scan}`);
|
|
289
|
+
let rows = src(ir.scan).map((r) => prefix(ir.scan, r));
|
|
290
|
+
const inScope = /* @__PURE__ */ new Set([ir.scan]);
|
|
291
|
+
for (const j of ir.join ?? []) {
|
|
292
|
+
const on = qualify(ir.scan, j.on);
|
|
293
|
+
const [res, field] = [on.slice(0, on.indexOf(".")), on.slice(on.indexOf(".") + 1)];
|
|
294
|
+
if (!inScope.has(res) || m.resources[res]?.fields[field]?.ref !== j.to) throw new BisqueError("undeclared join", []);
|
|
295
|
+
const key = m.resources[j.to].key ?? "id";
|
|
296
|
+
const idx = new Map(src(j.to).map((t) => [String(t[key]), prefix(j.to, t)]));
|
|
297
|
+
rows = rows.map((r) => ({ ...r, ...idx.get(String(r[on])) ?? {} }));
|
|
298
|
+
inScope.add(j.to);
|
|
299
|
+
}
|
|
300
|
+
for (const c of ir.where ?? []) {
|
|
301
|
+
const f = qualify(ir.scan, c[0]);
|
|
302
|
+
const v = c.length === 3 ? resolveValue(c[2], opts) : void 0;
|
|
303
|
+
rows = rows.filter((r) => cmp(r[f], c[1], v));
|
|
304
|
+
}
|
|
305
|
+
let out;
|
|
306
|
+
if (ir.groupBy?.length || ir.measures?.length) {
|
|
307
|
+
const groupBy = ir.groupBy ?? [];
|
|
308
|
+
const groups = /* @__PURE__ */ new Map();
|
|
309
|
+
for (const r of rows) {
|
|
310
|
+
const k = JSON.stringify(groupBy.map((g2) => r[qualify(ir.scan, g2)] ?? null));
|
|
311
|
+
const g = groups.get(k);
|
|
312
|
+
if (g) g.push(r);
|
|
313
|
+
else groups.set(k, [r]);
|
|
314
|
+
}
|
|
315
|
+
if (!groupBy.length && !groups.size) groups.set("[]", []);
|
|
316
|
+
out = [...groups.values()].map((g) => {
|
|
317
|
+
const row = {};
|
|
318
|
+
for (const f of groupBy) row[f] = g[0]?.[qualify(ir.scan, f)] ?? null;
|
|
319
|
+
for (const raw of ir.measures ?? []) {
|
|
320
|
+
const { agg, field, as } = measureOf(raw);
|
|
321
|
+
row[as] = aggregate(agg, field === "*" ? "*" : qualify(ir.scan, field), g);
|
|
322
|
+
}
|
|
323
|
+
return row;
|
|
324
|
+
});
|
|
325
|
+
} else {
|
|
326
|
+
const select = ir.select ?? [];
|
|
327
|
+
out = rows.map((r) => Object.fromEntries(select.map((f) => [f, r[qualify(ir.scan, f)] ?? null])));
|
|
328
|
+
}
|
|
329
|
+
if (ir.orderBy?.length) {
|
|
330
|
+
const keys = ir.orderBy;
|
|
331
|
+
out.sort((a, b) => {
|
|
332
|
+
for (const [col, dir] of keys) {
|
|
333
|
+
const d = compareValues(a[col], b[col]);
|
|
334
|
+
if (d) return dir === "desc" ? -d : d;
|
|
335
|
+
}
|
|
336
|
+
return 0;
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
const total = out.length;
|
|
340
|
+
const n = Math.min(ir.limit, scanRes.cap ?? MAX_ROWS2, MAX_ROWS2);
|
|
341
|
+
return { rows: out.slice(0, n), total, truncated: total > n, resolution };
|
|
342
|
+
}
|
|
343
|
+
function memoryExecutor(getStore, derived = {}, opts = {}) {
|
|
344
|
+
const derivedCache = /* @__PURE__ */ new WeakMap();
|
|
345
|
+
const resultCache = /* @__PURE__ */ new WeakMap();
|
|
346
|
+
const source = (store) => (resource) => {
|
|
347
|
+
if (derived[resource]) {
|
|
348
|
+
let m = derivedCache.get(store);
|
|
349
|
+
if (!m) derivedCache.set(store, m = /* @__PURE__ */ new Map());
|
|
350
|
+
let rows2 = m.get(resource);
|
|
351
|
+
if (!rows2) m.set(resource, rows2 = derived[resource](store));
|
|
352
|
+
return rows2;
|
|
353
|
+
}
|
|
354
|
+
const rows = store[resource];
|
|
355
|
+
if (!Array.isArray(rows)) throw new BisqueError(`the store has no rows for resource "${resource}"; bind it or declare it derived`);
|
|
356
|
+
return rows;
|
|
357
|
+
};
|
|
358
|
+
return {
|
|
359
|
+
async run(ir, ro) {
|
|
360
|
+
const store = getStore();
|
|
361
|
+
const today = ro.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
362
|
+
const key = canonicalJson({ ir, params: ro.params ?? {}, today });
|
|
363
|
+
let cache = resultCache.get(store);
|
|
364
|
+
if (!cache) resultCache.set(store, cache = /* @__PURE__ */ new Map());
|
|
365
|
+
const hit = cache.get(key);
|
|
366
|
+
if (hit) return hit;
|
|
367
|
+
const res = runIR(ir, source(store), { ...ro, today });
|
|
368
|
+
cache.set(key, res);
|
|
369
|
+
return res;
|
|
370
|
+
},
|
|
371
|
+
async distinct(resource, field) {
|
|
372
|
+
const rows = source(getStore())(resource);
|
|
373
|
+
return [
|
|
374
|
+
...new Set(
|
|
375
|
+
rows.map((r) => r[field]).filter((v) => v != null).map(String)
|
|
376
|
+
)
|
|
377
|
+
].sort((a, b) => a.localeCompare(b));
|
|
378
|
+
},
|
|
379
|
+
version: () => getStore(),
|
|
380
|
+
subscribe: opts.subscribe
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/server.ts
|
|
385
|
+
import { z as z2 } from "zod";
|
|
386
|
+
import { BisqueError as BisqueError2, problem as problem2 } from "@crasi/bisque-core";
|
|
387
|
+
import { canRead as canRead2, sharedFieldKeys } from "@crasi/bisque-contract";
|
|
388
|
+
var ServerQueryRequestSchema = z2.object({
|
|
389
|
+
ir: z2.unknown(),
|
|
390
|
+
params: z2.record(z2.string().max(40), Value).optional(),
|
|
391
|
+
today: z2.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()
|
|
392
|
+
}).strict();
|
|
393
|
+
async function serveQuery(input, opts) {
|
|
394
|
+
const req = ServerQueryRequestSchema.safeParse(input);
|
|
395
|
+
if (!req.success)
|
|
396
|
+
throw new BisqueError2(
|
|
397
|
+
"bad query request",
|
|
398
|
+
req.error.issues.map((i) => problem2(i.path.join("."), "schema", i.message))
|
|
399
|
+
);
|
|
400
|
+
const v = validateIR(req.data.ir, opts.manifest, { role: opts.role });
|
|
401
|
+
if (!v.ok || !v.ir) throw new BisqueError2("query rejected", v.problems);
|
|
402
|
+
const loaded = /* @__PURE__ */ new Map();
|
|
403
|
+
await Promise.all(v.touched.map(async (r) => loaded.set(r, await opts.load(r))));
|
|
404
|
+
return runIR(
|
|
405
|
+
v.ir,
|
|
406
|
+
(r) => {
|
|
407
|
+
const rows = loaded.get(r);
|
|
408
|
+
if (!rows) throw new BisqueError2(`resource ${r} was not loaded for this query`);
|
|
409
|
+
return rows;
|
|
410
|
+
},
|
|
411
|
+
{ manifest: opts.manifest, params: req.data.params, today: req.data.today }
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
async function serveDistinct(resource, field, opts) {
|
|
415
|
+
const key = `${String(resource)}.${String(field)}`;
|
|
416
|
+
if (typeof resource !== "string" || typeof field !== "string" || !sharedFieldKeys(opts.manifest).includes(key)) throw new BisqueError2(`${key} is not a shared field`);
|
|
417
|
+
if (!canRead2(opts.manifest, opts.role, resource)) throw new BisqueError2(`role ${opts.role} cannot read ${resource}`);
|
|
418
|
+
const rows = await opts.load(resource);
|
|
419
|
+
return [
|
|
420
|
+
...new Set(
|
|
421
|
+
rows.map((r) => r[field]).filter((x) => x != null).map(String)
|
|
422
|
+
)
|
|
423
|
+
].sort((a, b) => a.localeCompare(b));
|
|
424
|
+
}
|
|
425
|
+
export {
|
|
426
|
+
AGGREGATES,
|
|
427
|
+
COMPARE_OPS,
|
|
428
|
+
Cond,
|
|
429
|
+
IRSchema,
|
|
430
|
+
Join,
|
|
431
|
+
Literal,
|
|
432
|
+
MATCH_OP,
|
|
433
|
+
Measure,
|
|
434
|
+
NULL_OPS,
|
|
435
|
+
OrderKey,
|
|
436
|
+
ParamRef,
|
|
437
|
+
SET_OPS,
|
|
438
|
+
Scalar,
|
|
439
|
+
ServerQueryRequestSchema,
|
|
440
|
+
TodayRef,
|
|
441
|
+
Value,
|
|
442
|
+
addDaysIso,
|
|
443
|
+
measureOf,
|
|
444
|
+
memoryExecutor,
|
|
445
|
+
normalize,
|
|
446
|
+
pickMatch,
|
|
447
|
+
resolveField,
|
|
448
|
+
resolveMatches,
|
|
449
|
+
runIR,
|
|
450
|
+
serveDistinct,
|
|
451
|
+
serveQuery,
|
|
452
|
+
touched,
|
|
453
|
+
validateIR,
|
|
454
|
+
zodProblems
|
|
455
|
+
};
|
|
456
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/schema.ts", "../src/validate.ts", "../src/execute.ts", "../src/match.ts", "../src/server.ts"],
|
|
4
|
+
"sourcesContent": ["import { z } from \"zod\";\n\n/**\n * The query algebra Q (\u00A74.4) as JSON:\n * scan(r) | \u03C3_\u03C6(q) | \u03C0_f(q) | q \u22C8_{f\u2192r'} scan(r') | \u03B3_{g; agg}(q) | \u03C4_f(q) | \u03BB_n(q)\n * Deliberately weaker than SQL: joins follow declared refs only, \u03C6 is a\n * conjunction, and the limit is mandatory.\n */\nexport const Literal = z.union([z.string().max(200), z.number(), z.boolean(), z.null()]);\nexport const ParamRef = z.object({ param: z.string() }).strict();\n/** A date relative to today, in days: `{ today: 30 }` is 30 days from now. */\nexport const TodayRef = z.object({ today: z.number().int().min(-3660).max(3660) }).strict();\nexport const Scalar = z.union([Literal, ParamRef, TodayRef]);\nexport const Value = z.union([Scalar, z.array(Scalar).max(200)]);\n\nexport const COMPARE_OPS = [\"=\", \"!=\", \"<\", \"<=\", \">\", \">=\"] as const;\nexport const SET_OPS = [\"in\", \"notIn\"] as const;\n/** Symbolic name filter, resolved locally against host values (issue I2). */\nexport const MATCH_OP = \"match\" as const;\nexport const NULL_OPS = [\"isNull\", \"notNull\"] as const;\n\nexport const Cond = z.union([z.tuple([z.string(), z.enum([...COMPARE_OPS, ...SET_OPS, MATCH_OP]), Value]), z.tuple([z.string(), z.enum(NULL_OPS)])]);\n\nexport const Join = z.object({ on: z.string(), to: z.string() }).strict();\n\nexport const AGGREGATES = [\"sum\", \"avg\", \"min\", \"max\", \"count\", \"countDistinct\"] as const;\nexport type Aggregate = (typeof AGGREGATES)[number];\n\nconst measure = <K extends Aggregate>(k: K) => z.object({ [k]: z.string(), as: z.string() } as { [P in K]: z.ZodString } & { as: z.ZodString }).strict();\nexport const Measure = z.union([measure(\"sum\"), measure(\"avg\"), measure(\"min\"), measure(\"max\"), measure(\"count\"), measure(\"countDistinct\")]);\n\nexport const OrderKey = z.tuple([z.string(), z.enum([\"asc\", \"desc\"])]);\n\nexport const IRSchema = z\n .object({\n scan: z.string(),\n join: z.array(Join).max(6).optional(),\n where: z.array(Cond).max(20).optional(),\n groupBy: z.array(z.string()).max(4).optional(),\n measures: z.array(Measure).max(8).optional(),\n select: z.array(z.string()).max(24).optional(),\n orderBy: z.array(OrderKey).max(4).optional(),\n limit: z.number().int(),\n })\n .strict();\n\nexport type IR = z.infer<typeof IRSchema>;\nexport type IRCond = z.infer<typeof Cond>;\nexport type IRValue = z.infer<typeof Value>;\nexport type IRScalar = z.infer<typeof Scalar>;\nexport type IRMeasure = z.infer<typeof Measure>;\n\nexport function measureOf(m: IRMeasure): { agg: Aggregate; field: string; as: string } {\n const agg = AGGREGATES.find((a) => a in m)!;\n return { agg, field: (m as Record<string, string>)[agg], as: m.as };\n}\n\nexport type Row = Record<string, unknown>;\n", "import type { z } from \"zod\";\nimport { MAX_ROWS, problem, type Problem, type Role } from \"@crasi/bisque-core\";\nimport { canRead, type ContractManifest, type FieldDescriptor, type FieldType } from \"@crasi/bisque-contract\";\nimport { IRSchema, measureOf, type IR, type IRValue } from \"./schema\";\n\nexport type Column = FieldDescriptor & {\n /** The resource and field the column comes from; absent for measures. */\n source?: { resource: string; field: string };\n measure?: { agg: string; of: string };\n};\n\nexport type IRValidation = {\n ok: boolean;\n problems: Problem[];\n ir?: IR;\n /** Every resource the query touches: scan + join targets (Proposition 1). */\n touched: string[];\n /** Output columns by name, as written in the IR. */\n columns: Record<string, Column>;\n /** Params the query refers to. */\n params: string[];\n};\n\nexport type IRValidateOptions = {\n /** The artifact manifest's declared reads. Every touched resource must be in it. */\n reads?: string[];\n role?: Role;\n /** Declared params and their types. When given, every `{param}` must be in it. */\n params?: Record<string, FieldType | \"any\">;\n maxLimit?: number;\n};\n\nexport function zodProblems(err: z.ZodError, prefix = \"\"): Problem[] {\n return err.issues.map((i) => problem([prefix, ...i.path.map(String)].filter(Boolean).join(\".\"), \"schema\", i.message));\n}\n\ntype Scope = { scan: string; resources: Set<string> };\n\nexport function resolveField(m: ContractManifest, scope: Scope, name: string): { resource: string; field: string; desc: FieldDescriptor } | string {\n const dot = name.indexOf(\".\");\n const [resource, field] = dot < 0 ? [scope.scan, name] : [name.slice(0, dot), name.slice(dot + 1)];\n if (!scope.resources.has(resource)) {\n return m.resources[resource] ? `\"${resource}\" is not joined; add a join along a declared reference to use ${name}` : `unknown resource \"${resource}\"`;\n }\n const desc = m.resources[resource]?.fields[field];\n if (!desc) {\n const known = Object.keys(m.resources[resource]?.fields ?? {}).join(\", \");\n return dot < 0 && scope.resources.size > 1\n ? `\"${field}\" is not a field of ${resource}; qualify fields of joined resources, e.g. products.name (fields of ${resource}: ${known})`\n : `\"${field}\" is not a field of ${resource} (fields: ${known})`;\n }\n return { resource, field, desc };\n}\n\nconst ORDERABLE: FieldType[] = [\"number\", \"date\", \"datetime\", \"string\", \"enum\"];\n\nexport function validateIR(input: unknown, m: ContractManifest, opts: IRValidateOptions = {}): IRValidation {\n const out: IRValidation = { ok: false, problems: [], touched: [], columns: {}, params: [] };\n const parsed = IRSchema.safeParse(input);\n if (!parsed.success) {\n out.problems = zodProblems(parsed.error);\n return out;\n }\n const ir = parsed.data;\n out.ir = ir;\n const P = out.problems;\n const scanRes = m.resources[ir.scan];\n if (!scanRes) {\n P.push(problem(\"scan\", \"unknown_resource\", `unknown resource \"${ir.scan}\" (resources: ${Object.keys(m.resources).join(\", \")})`));\n return out;\n }\n const scope: Scope = { scan: ir.scan, resources: new Set([ir.scan]) };\n (ir.join ?? []).forEach((j, i) => {\n const on = resolveField(m, scope, j.on);\n if (typeof on === \"string\") return P.push(problem(`join.${i}.on`, \"unknown_field\", on));\n if (!m.resources[j.to]) return P.push(problem(`join.${i}.to`, \"unknown_resource\", `unknown resource \"${j.to}\"`));\n if (on.desc.ref !== j.to)\n return P.push(\n problem(`join.${i}`, \"undeclared_join\", on.desc.ref ? `${j.on} references ${on.desc.ref}, not ${j.to}` : `${j.on} is not a declared reference, so it cannot be joined`),\n );\n if (scope.resources.has(j.to)) return P.push(problem(`join.${i}.to`, \"undeclared_join\", `${j.to} is already in the query; each resource can be joined once`));\n scope.resources.add(j.to);\n });\n out.touched = [...scope.resources];\n\n const params = new Set<string>();\n const checkValue = (path: string, v: IRValue, desc: FieldDescriptor) => {\n const scalars = Array.isArray(v) ? v : [v];\n for (const s of scalars) {\n if (s && typeof s === \"object\" && \"param\" in s) {\n params.add(s.param);\n if (opts.params && !(s.param in opts.params)) P.push(problem(path, \"unknown_param\", `param \"${s.param}\" is not declared in the spec's params`));\n } else if (s && typeof s === \"object\" && \"today\" in s) {\n if (desc.type !== \"date\" && desc.type !== \"datetime\") P.push(problem(path, \"type\", \"{today: n} compares only with date fields\"));\n } else if (s !== null && desc.type === \"number\" && typeof s !== \"number\") P.push(problem(path, \"type\", \"this field is a number\"));\n else if (s !== null && desc.type === \"enum\" && !desc.enum!.includes(String(s))) P.push(problem(path, \"type\", `must be one of ${desc.enum!.join(\", \")}`));\n }\n };\n\n (ir.where ?? []).forEach((c, i) => {\n const path = `where.${i}`;\n const f = resolveField(m, scope, c[0]);\n if (typeof f === \"string\") return P.push(problem(`${path}.0`, \"unknown_field\", f));\n const op = c[1];\n if (op === \"isNull\" || op === \"notNull\") return;\n const v = c[2] as IRValue;\n if ((op === \"in\" || op === \"notIn\") && !Array.isArray(v)) P.push(problem(`${path}.2`, \"type\", `${op} takes a list`));\n if ([\"<\", \"<=\", \">\", \">=\"].includes(op) && !ORDERABLE.includes(f.desc.type))\n P.push(problem(`${path}.1`, \"type\", `${c[0]} is ${f.desc.type} and cannot be compared with ${op}`));\n if (op === \"match\") {\n if (f.desc.type !== \"string\") P.push(problem(`${path}.1`, \"type\", \"match works on text fields such as names\"));\n const lits = Array.isArray(v) ? v : [v];\n if (!lits.length || lits.some((x) => typeof x !== \"string\")) P.push(problem(`${path}.2`, \"type\", \"match takes one name or a list of names\"));\n return;\n }\n checkValue(`${path}.2`, v, f.desc);\n });\n\n const columns: Record<string, Column> = {};\n const addColumn = (name: string, path: string) => {\n const f = resolveField(m, scope, name);\n if (typeof f === \"string\") return void P.push(problem(path, \"unknown_field\", f));\n columns[name] = { ...f.desc, source: { resource: f.resource, field: f.field } };\n };\n const grouping = !!(ir.groupBy?.length || ir.measures?.length);\n if (ir.select?.length && grouping) P.push(problem(\"select\", \"schema\", \"use select without groupBy/measures, or groupBy/measures without select\"));\n if (!ir.select?.length && !grouping) P.push(problem(\"\", \"schema\", \"a query must select fields, or group and measure\"));\n (ir.groupBy ?? []).forEach((g, i) => addColumn(g, `groupBy.${i}`));\n (ir.select ?? []).forEach((s, i) => addColumn(s, `select.${i}`));\n (ir.measures ?? []).forEach((raw, i) => {\n const { agg, field, as } = measureOf(raw);\n const path = `measures.${i}`;\n if (!/^[a-z_][a-z0-9_]*$/i.test(as)) P.push(problem(`${path}.as`, \"schema\", \"measure names are simple identifiers like value\"));\n if (columns[as]) P.push(problem(`${path}.as`, \"schema\", `\"${as}\" is already a column`));\n if (agg === \"count\" && field === \"*\") {\n columns[as] = { type: \"number\", nullable: false, measure: { agg, of: \"*\" } };\n return;\n }\n const f = resolveField(m, scope, field);\n if (typeof f === \"string\") return P.push(problem(`${path}.${agg}`, \"unknown_field\", f));\n if ((agg === \"sum\" || agg === \"avg\") && f.desc.type !== \"number\") P.push(problem(`${path}.${agg}`, \"type\", `${agg} needs a number field; ${field} is ${f.desc.type}`));\n if ((agg === \"min\" || agg === \"max\") && !ORDERABLE.includes(f.desc.type)) P.push(problem(`${path}.${agg}`, \"type\", `${agg} needs a number or date field`));\n const type: FieldType = agg === \"count\" || agg === \"countDistinct\" || agg === \"sum\" || agg === \"avg\" ? \"number\" : f.desc.type;\n columns[as] = {\n type,\n nullable: agg === \"min\" || agg === \"max\" || agg === \"avg\",\n label: agg === \"min\" || agg === \"max\" ? f.desc.label : undefined,\n unit: agg === \"sum\" || agg === \"avg\" || agg === \"min\" || agg === \"max\" ? f.desc.unit : undefined,\n measure: { agg, of: field },\n };\n });\n out.columns = columns;\n\n (ir.orderBy ?? []).forEach(([col], i) => {\n if (!columns[col]) P.push(problem(`orderBy.${i}.0`, \"unknown_field\", `order by an output column (${Object.keys(columns).join(\", \") || \"none\"})`));\n });\n\n const cap = Math.min(scanRes.cap ?? MAX_ROWS, MAX_ROWS, opts.maxLimit ?? MAX_ROWS);\n if (ir.limit < 1 || ir.limit > cap) P.push(problem(\"limit\", \"limit\", `limit must be between 1 and ${cap}`));\n\n for (const r of out.touched) {\n if (opts.reads && !opts.reads.includes(r)) P.push(problem(\"\", \"undeclared_read\", `reads ${r}, which the manifest does not declare`));\n if (opts.role && !canRead(m, opts.role, r)) P.push(problem(\"\", \"role_denied\", `role ${opts.role} cannot read ${r}`));\n }\n out.params = [...params];\n out.ok = P.length === 0;\n return out;\n}\n\n/** Resources an IR touches, without full validation. Used by the bridge's manifest gate. */\nexport function touched(ir: Pick<IR, \"scan\" | \"join\">): string[] {\n return [ir.scan, ...(ir.join ?? []).map((j) => j.to)];\n}\n", "import { BisqueError, MAX_ROWS, canonicalJson } from \"@crasi/bisque-core\";\nimport type { ContractManifest } from \"@crasi/bisque-contract\";\nimport { measureOf, type IR, type IRScalar, type IRValue, type Row } from \"./schema\";\nimport { resolveMatches, type MatchResolution } from \"./match\";\n\nexport type Source = (resource: string) => Row[];\n\nexport type RunOptions = {\n manifest: ContractManifest;\n params?: Record<string, unknown>;\n /** ISO date used for `{today: n}`. Defaults to the current date. */\n today?: string;\n};\n\nexport type QueryResult = {\n rows: Row[];\n /** Row count before the limit was applied. */\n total: number;\n truncated: boolean;\n /** How each `match` filter's names were resolved locally (issue I2). */\n resolution: MatchResolution[];\n};\n\nconst qualify = (scan: string, f: string) => (f.includes(\".\") ? f : `${scan}.${f}`);\n\nfunction prefix(resource: string, row: Row): Row {\n const out: Row = {};\n for (const k in row) out[`${resource}.${k}`] = row[k];\n return out;\n}\n\nexport function addDaysIso(date: string, days: number): string {\n const d = new Date(`${date.slice(0, 10)}T00:00:00Z`);\n d.setUTCDate(d.getUTCDate() + days);\n return d.toISOString().slice(0, 10);\n}\n\nfunction resolveScalar(v: IRScalar, opts: RunOptions): unknown {\n if (v && typeof v === \"object\" && \"param\" in v) {\n if (!opts.params || !(v.param in opts.params)) throw new BisqueError(`param \"${v.param}\" has no value`);\n return opts.params[v.param];\n }\n if (v && typeof v === \"object\" && \"today\" in v) return addDaysIso(opts.today ?? new Date().toISOString().slice(0, 10), v.today);\n return v;\n}\n\nfunction resolveValue(v: IRValue, opts: RunOptions): unknown {\n return Array.isArray(v) ? v.map((x) => resolveScalar(x, opts)) : resolveScalar(v, opts);\n}\n\nfunction cmp(a: unknown, op: string, b: unknown): boolean {\n switch (op) {\n case \"=\":\n return a === b || (a != null && b != null && String(a) === String(b));\n case \"!=\":\n return !(a === b || (a != null && b != null && String(a) === String(b)));\n case \"<\":\n return a != null && b != null && (a as number) < (b as number);\n case \"<=\":\n return a != null && b != null && (a as number) <= (b as number);\n case \">\":\n return a != null && b != null && (a as number) > (b as number);\n case \">=\":\n return a != null && b != null && (a as number) >= (b as number);\n case \"in\":\n return (b as unknown[]).some((x) => x === a || String(x) === String(a));\n case \"notIn\":\n return !(b as unknown[]).some((x) => x === a || String(x) === String(a));\n case \"isNull\":\n return a == null;\n case \"notNull\":\n return a != null;\n }\n throw new BisqueError(`unknown operator ${op}`);\n}\n\nconst clean = (n: number) => Math.round(n * 1e6) / 1e6;\n\nfunction aggregate(agg: string, field: string, rows: Row[]): unknown {\n if (agg === \"count\") return field === \"*\" ? rows.length : rows.filter((r) => r[field] != null).length;\n const vals = rows.map((r) => r[field]).filter((v) => v != null);\n if (agg === \"countDistinct\") return new Set(vals.map(String)).size;\n if (!vals.length) return agg === \"sum\" ? 0 : null;\n if (agg === \"sum\") return clean((vals as number[]).reduce((a, b) => a + b, 0));\n if (agg === \"avg\") return clean((vals as number[]).reduce((a, b) => a + b, 0) / vals.length);\n // biome-ignore lint/complexity/useMathMinMax: also compares dates and strings, which Math.min would turn into NaN.\n if (agg === \"min\") return vals.reduce((a, b) => ((b as number) < (a as number) ? b : a));\n // biome-ignore lint/complexity/useMathMinMax: as for min.\n if (agg === \"max\") return vals.reduce((a, b) => ((b as number) > (a as number) ? b : a));\n throw new BisqueError(`unknown aggregate ${agg}`);\n}\n\nfunction compareValues(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return 1;\n if (b == null) return -1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n return String(a).localeCompare(String(b));\n}\n\n/**\n * Runs a validated IR over in-memory rows (Listing 4). Callers validate\n * first; this function re-checks only what would make it unsafe (undeclared\n * joins), so a bug elsewhere cannot widen what it reads.\n */\nexport function runIR(input: IR, src: Source, opts: RunOptions): QueryResult {\n const m = opts.manifest;\n const { ir, resolution } = resolveMatches(input, src, m);\n const scanRes = m.resources[ir.scan];\n if (!scanRes) throw new BisqueError(`unknown resource ${ir.scan}`);\n let rows = src(ir.scan).map((r) => prefix(ir.scan, r));\n const inScope = new Set([ir.scan]);\n for (const j of ir.join ?? []) {\n const on = qualify(ir.scan, j.on);\n const [res, field] = [on.slice(0, on.indexOf(\".\")), on.slice(on.indexOf(\".\") + 1)];\n if (!inScope.has(res) || m.resources[res]?.fields[field]?.ref !== j.to) throw new BisqueError(\"undeclared join\", []);\n const key = m.resources[j.to].key ?? \"id\";\n const idx = new Map(src(j.to).map((t) => [String(t[key]), prefix(j.to, t)]));\n // Many-to-one: each row gains at most one partner, so cardinality never grows.\n rows = rows.map((r) => ({ ...r, ...(idx.get(String(r[on])) ?? {}) }));\n inScope.add(j.to);\n }\n for (const c of ir.where ?? []) {\n const f = qualify(ir.scan, c[0]);\n const v = c.length === 3 ? resolveValue(c[2] as IRValue, opts) : undefined;\n rows = rows.filter((r) => cmp(r[f], c[1], v));\n }\n let out: Row[];\n if (ir.groupBy?.length || ir.measures?.length) {\n const groupBy = ir.groupBy ?? [];\n const groups = new Map<string, Row[]>();\n for (const r of rows) {\n const k = JSON.stringify(groupBy.map((g) => r[qualify(ir.scan, g)] ?? null));\n const g = groups.get(k);\n if (g) g.push(r);\n else groups.set(k, [r]);\n }\n if (!groupBy.length && !groups.size) groups.set(\"[]\", []);\n out = [...groups.values()].map((g) => {\n const row: Row = {};\n for (const f of groupBy) row[f] = g[0]?.[qualify(ir.scan, f)] ?? null;\n for (const raw of ir.measures ?? []) {\n const { agg, field, as } = measureOf(raw);\n row[as] = aggregate(agg, field === \"*\" ? \"*\" : qualify(ir.scan, field), g);\n }\n return row;\n });\n } else {\n const select = ir.select ?? [];\n out = rows.map((r) => Object.fromEntries(select.map((f) => [f, r[qualify(ir.scan, f)] ?? null])));\n }\n if (ir.orderBy?.length) {\n const keys = ir.orderBy;\n out.sort((a, b) => {\n for (const [col, dir] of keys) {\n const d = compareValues(a[col], b[col]);\n if (d) return dir === \"desc\" ? -d : d;\n }\n return 0;\n });\n }\n const total = out.length;\n const n = Math.min(ir.limit, scanRes.cap ?? MAX_ROWS, MAX_ROWS);\n return { rows: out.slice(0, n), total, truncated: total > n, resolution };\n}\n\n/** Anything that can run IR: the in-memory executor in v1; a server executor after it. */\nexport interface Executor {\n run(ir: IR, opts: RunOptions): Promise<QueryResult>;\n /** Distinct values of a field, for host-shared lookup values. Only called for `share` fields. */\n distinct(resource: string, field: string): Promise<string[]>;\n /** Changes whenever the underlying data changes (issue I9). */\n version(): unknown;\n subscribe?(listener: () => void): () => void;\n}\n\nexport type DerivedBindings<S> = Record<string, (store: S) => Row[]>;\n\n/**\n * Executor over a client-held store, for hosts that already keep the\n * tenant's working set in the browser (4caster). Results are memoized on\n * (query, params, store identity), so a Realtime update that replaces the\n * store invalidates everything at once.\n */\nexport function memoryExecutor<S extends object>(getStore: () => S, derived: DerivedBindings<S> = {}, opts: { subscribe?: (listener: () => void) => () => void } = {}): Executor {\n const derivedCache = new WeakMap<S, Map<string, Row[]>>();\n const resultCache = new WeakMap<S, Map<string, QueryResult>>();\n const source =\n (store: S): Source =>\n (resource) => {\n if (derived[resource]) {\n let m = derivedCache.get(store);\n if (!m) derivedCache.set(store, (m = new Map()));\n let rows = m.get(resource);\n if (!rows) m.set(resource, (rows = derived[resource](store)));\n return rows;\n }\n const rows = (store as Record<string, unknown>)[resource];\n if (!Array.isArray(rows)) throw new BisqueError(`the store has no rows for resource \"${resource}\"; bind it or declare it derived`);\n return rows as Row[];\n };\n return {\n async run(ir, ro) {\n const store = getStore();\n // Pin the date now, so `{today: n}` results do not outlive the day they were computed on.\n const today = ro.today ?? new Date().toISOString().slice(0, 10);\n // The full canonical text, not a hash of it: a collision would return another query's rows.\n const key = canonicalJson({ ir, params: ro.params ?? {}, today });\n let cache = resultCache.get(store);\n if (!cache) resultCache.set(store, (cache = new Map()));\n const hit = cache.get(key);\n if (hit) return hit;\n const res = runIR(ir, source(store), { ...ro, today });\n cache.set(key, res);\n return res;\n },\n async distinct(resource, field) {\n const rows = source(getStore())(resource);\n return [\n ...new Set(\n rows\n .map((r) => r[field])\n .filter((v) => v != null)\n .map(String),\n ),\n ].sort((a, b) => a.localeCompare(b));\n },\n version: () => getStore(),\n subscribe: opts.subscribe,\n };\n}\n", "import type { ContractManifest } from \"@crasi/bisque-contract\";\nimport type { IR, IRCond, Row } from \"./schema\";\n\n/**\n * Symbolic `match` filters (issue I2). The model writes the user's words \u2014\n * `[\"key_accounts.name\", \"match\", [\"Metro\", \"TABAC\"]]` \u2014 and the host\n * resolves them against its own values, locally. Nothing about the\n * resolution goes back to the model except the bucketed diagnostics.\n */\nexport type MatchResolution = {\n field: string;\n literal: string;\n status: \"exact\" | \"unique\" | \"ambiguous\" | \"unmatched\";\n /** Values the literal resolved to (one), or could mean (several). Shown to the user as chips. */\n values: string[];\n};\n\nexport function normalize(s: string): string {\n return s.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\nexport function resolveMatches(ir: IR, src: (r: string) => Row[], m: ContractManifest): { ir: IR; resolution: MatchResolution[] } {\n if (!ir.where?.some((c) => c[1] === \"match\")) return { ir, resolution: [] };\n const resolution: MatchResolution[] = [];\n const where = ir.where.map((c): IRCond => {\n if (c[1] !== \"match\") return c;\n const name = c[0].includes(\".\") ? c[0] : `${ir.scan}.${c[0]}`;\n const dot = name.indexOf(\".\");\n const [resource, field] = [name.slice(0, dot), name.slice(dot + 1)];\n if (!m.resources[resource]) return c;\n const known = [\n ...new Set(\n src(resource)\n .map((r) => r[field])\n .filter((v) => v != null)\n .map(String),\n ),\n ];\n const lits = (Array.isArray(c[2]) ? c[2] : [c[2]]).map(String);\n const chosen: string[] = [];\n for (const lit of lits) {\n const n = normalize(lit);\n const exact = known.filter((k) => normalize(k) === n);\n if (exact.length) {\n chosen.push(...exact);\n resolution.push({ field: c[0], literal: lit, status: \"exact\", values: exact });\n continue;\n }\n const partial = known.filter((k) => normalize(k).includes(n));\n if (partial.length === 1) {\n chosen.push(partial[0]);\n resolution.push({ field: c[0], literal: lit, status: \"unique\", values: partial });\n } else {\n // Ambiguous names match nothing until the user picks a chip.\n resolution.push({ field: c[0], literal: lit, status: partial.length ? \"ambiguous\" : \"unmatched\", values: partial.slice(0, 8) });\n }\n }\n return [c[0], \"in\", chosen];\n });\n return { ir: { ...ir, where }, resolution };\n}\n\n/** Replace one ambiguous literal with the value the user picked. */\nexport function pickMatch(ir: IR, field: string, literal: string, value: string): IR {\n return {\n ...ir,\n where: ir.where?.map((c) => {\n if (c[0] !== field || c[1] !== \"match\") return c;\n const lits = Array.isArray(c[2]) ? c[2] : [c[2]];\n return [c[0], \"match\", lits.map((l) => (l === literal ? value : l))];\n }),\n };\n}\n", "import { z } from \"zod\";\nimport { BisqueError, problem, type Role } from \"@crasi/bisque-core\";\nimport { canRead, sharedFieldKeys, type ContractManifest } from \"@crasi/bisque-contract\";\nimport { Value } from \"./schema\";\nimport { runIR, type QueryResult } from \"./execute\";\nimport { validateIR } from \"./validate\";\nimport type { Row } from \"./schema\";\n\n/**\n * Running specs on the host's server, for hosts whose data does not live in\n * the browser (no client-held store, or no row-level security to lean on).\n * The browser sends the query, not a resource name and not a tenant; the\n * server re-validates it against the contract and the role it reads from\n * its own session, loads only what the query touches, and runs it.\n *\n * The rows still go only to the host's own page, never to the conductor:\n * custody (P1) is the same as for the in-memory executor.\n */\nexport type ServerQueryRequest = { ir: unknown; params?: Record<string, unknown>; today?: string };\n\nexport const ServerQueryRequestSchema = z\n .object({\n ir: z.unknown(),\n params: z.record(z.string().max(40), Value).optional(),\n today: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .optional(),\n })\n .strict();\n\nexport type ServerQueryOptions = {\n manifest: ContractManifest;\n /** From the host's session, never from the request. */\n role: Role;\n /**\n * Rows of one resource for the signed-in tenant, already scoped and capped\n * by the host. Called once per touched resource per query.\n */\n load: (resource: string) => Promise<Row[]>;\n};\n\nexport async function serveQuery(input: unknown, opts: ServerQueryOptions): Promise<QueryResult> {\n const req = ServerQueryRequestSchema.safeParse(input);\n if (!req.success)\n throw new BisqueError(\n \"bad query request\",\n req.error.issues.map((i) => problem(i.path.join(\".\"), \"schema\", i.message)),\n );\n const v = validateIR(req.data.ir, opts.manifest, { role: opts.role });\n if (!v.ok || !v.ir) throw new BisqueError(\"query rejected\", v.problems);\n const loaded = new Map<string, Row[]>();\n await Promise.all(v.touched.map(async (r) => loaded.set(r, await opts.load(r))));\n return runIR(\n v.ir,\n (r) => {\n const rows = loaded.get(r);\n // validateIR bounds what is touched; anything else is a bug, not a read.\n if (!rows) throw new BisqueError(`resource ${r} was not loaded for this query`);\n return rows;\n },\n { manifest: opts.manifest, params: req.data.params, today: req.data.today },\n );\n}\n\n/** Distinct values of a field the contract marks `values: \"share\"`; refuses any other field. */\nexport async function serveDistinct(resource: unknown, field: unknown, opts: ServerQueryOptions): Promise<string[]> {\n const key = `${String(resource)}.${String(field)}`;\n if (typeof resource !== \"string\" || typeof field !== \"string\" || !sharedFieldKeys(opts.manifest).includes(key)) throw new BisqueError(`${key} is not a shared field`);\n if (!canRead(opts.manifest, opts.role, resource)) throw new BisqueError(`role ${opts.role} cannot read ${resource}`);\n const rows = await opts.load(resource);\n return [\n ...new Set(\n rows\n .map((r) => r[field])\n .filter((x) => x != null)\n .map(String),\n ),\n ].sort((a, b) => a.localeCompare(b));\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,SAAS;AAQX,IAAM,UAAU,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,GAAG,GAAG,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,KAAK,CAAC,CAAC;AAChF,IAAM,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO;AAExD,IAAM,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,IAAI,IAAI,EAAE,CAAC,EAAE,OAAO;AACnF,IAAM,SAAS,EAAE,MAAM,CAAC,SAAS,UAAU,QAAQ,CAAC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AC,CAAC;AACrC;",
|
|
6
|
+
"names": ["prefix", "MAX_ROWS", "g", "MAX_ROWS", "rows", "z", "BisqueError", "problem", "canRead", "z", "BisqueError", "problem", "canRead"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { ContractManifest } from "@crasi/bisque-contract";
|
|
2
|
+
import { type IR, type Row } from "./schema.js";
|
|
3
|
+
import { type MatchResolution } from "./match.js";
|
|
4
|
+
export type Source = (resource: string) => Row[];
|
|
5
|
+
export type RunOptions = {
|
|
6
|
+
manifest: ContractManifest;
|
|
7
|
+
params?: Record<string, unknown>;
|
|
8
|
+
/** ISO date used for `{today: n}`. Defaults to the current date. */
|
|
9
|
+
today?: string;
|
|
10
|
+
};
|
|
11
|
+
export type QueryResult = {
|
|
12
|
+
rows: Row[];
|
|
13
|
+
/** Row count before the limit was applied. */
|
|
14
|
+
total: number;
|
|
15
|
+
truncated: boolean;
|
|
16
|
+
/** How each `match` filter's names were resolved locally (issue I2). */
|
|
17
|
+
resolution: MatchResolution[];
|
|
18
|
+
};
|
|
19
|
+
export declare function addDaysIso(date: string, days: number): string;
|
|
20
|
+
/**
|
|
21
|
+
* Runs a validated IR over in-memory rows (Listing 4). Callers validate
|
|
22
|
+
* first; this function re-checks only what would make it unsafe (undeclared
|
|
23
|
+
* joins), so a bug elsewhere cannot widen what it reads.
|
|
24
|
+
*/
|
|
25
|
+
export declare function runIR(input: IR, src: Source, opts: RunOptions): QueryResult;
|
|
26
|
+
/** Anything that can run IR: the in-memory executor in v1; a server executor after it. */
|
|
27
|
+
export interface Executor {
|
|
28
|
+
run(ir: IR, opts: RunOptions): Promise<QueryResult>;
|
|
29
|
+
/** Distinct values of a field, for host-shared lookup values. Only called for `share` fields. */
|
|
30
|
+
distinct(resource: string, field: string): Promise<string[]>;
|
|
31
|
+
/** Changes whenever the underlying data changes (issue I9). */
|
|
32
|
+
version(): unknown;
|
|
33
|
+
subscribe?(listener: () => void): () => void;
|
|
34
|
+
}
|
|
35
|
+
export type DerivedBindings<S> = Record<string, (store: S) => Row[]>;
|
|
36
|
+
/**
|
|
37
|
+
* Executor over a client-held store, for hosts that already keep the
|
|
38
|
+
* tenant's working set in the browser (4caster). Results are memoized on
|
|
39
|
+
* (query, params, store identity), so a Realtime update that replaces the
|
|
40
|
+
* store invalidates everything at once.
|
|
41
|
+
*/
|
|
42
|
+
export declare function memoryExecutor<S extends object>(getStore: () => S, derived?: DerivedBindings<S>, opts?: {
|
|
43
|
+
subscribe?: (listener: () => void) => () => void;
|
|
44
|
+
}): Executor;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ContractManifest } from "@crasi/bisque-contract";
|
|
2
|
+
import type { IR, Row } from "./schema.js";
|
|
3
|
+
/**
|
|
4
|
+
* Symbolic `match` filters (issue I2). The model writes the user's words —
|
|
5
|
+
* `["key_accounts.name", "match", ["Metro", "TABAC"]]` — and the host
|
|
6
|
+
* resolves them against its own values, locally. Nothing about the
|
|
7
|
+
* resolution goes back to the model except the bucketed diagnostics.
|
|
8
|
+
*/
|
|
9
|
+
export type MatchResolution = {
|
|
10
|
+
field: string;
|
|
11
|
+
literal: string;
|
|
12
|
+
status: "exact" | "unique" | "ambiguous" | "unmatched";
|
|
13
|
+
/** Values the literal resolved to (one), or could mean (several). Shown to the user as chips. */
|
|
14
|
+
values: string[];
|
|
15
|
+
};
|
|
16
|
+
export declare function normalize(s: string): string;
|
|
17
|
+
export declare function resolveMatches(ir: IR, src: (r: string) => Row[], m: ContractManifest): {
|
|
18
|
+
ir: IR;
|
|
19
|
+
resolution: MatchResolution[];
|
|
20
|
+
};
|
|
21
|
+
/** Replace one ambiguous literal with the value the user picked. */
|
|
22
|
+
export declare function pickMatch(ir: IR, field: string, literal: string, value: string): IR;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* The query algebra Q (§4.4) as JSON:
|
|
4
|
+
* scan(r) | σ_φ(q) | π_f(q) | q ⋈_{f→r'} scan(r') | γ_{g; agg}(q) | τ_f(q) | λ_n(q)
|
|
5
|
+
* Deliberately weaker than SQL: joins follow declared refs only, φ is a
|
|
6
|
+
* conjunction, and the limit is mandatory.
|
|
7
|
+
*/
|
|
8
|
+
export declare const Literal: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>;
|
|
9
|
+
export declare const ParamRef: z.ZodObject<{
|
|
10
|
+
param: z.ZodString;
|
|
11
|
+
}, z.core.$strict>;
|
|
12
|
+
/** A date relative to today, in days: `{ today: 30 }` is 30 days from now. */
|
|
13
|
+
export declare const TodayRef: z.ZodObject<{
|
|
14
|
+
today: z.ZodNumber;
|
|
15
|
+
}, z.core.$strict>;
|
|
16
|
+
export declare const Scalar: z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
17
|
+
param: z.ZodString;
|
|
18
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
19
|
+
today: z.ZodNumber;
|
|
20
|
+
}, z.core.$strict>]>;
|
|
21
|
+
export declare const Value: z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
22
|
+
param: z.ZodString;
|
|
23
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
24
|
+
today: z.ZodNumber;
|
|
25
|
+
}, z.core.$strict>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
26
|
+
param: z.ZodString;
|
|
27
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
28
|
+
today: z.ZodNumber;
|
|
29
|
+
}, z.core.$strict>]>>]>;
|
|
30
|
+
export declare const COMPARE_OPS: readonly ["=", "!=", "<", "<=", ">", ">="];
|
|
31
|
+
export declare const SET_OPS: readonly ["in", "notIn"];
|
|
32
|
+
/** Symbolic name filter, resolved locally against host values (issue I2). */
|
|
33
|
+
export declare const MATCH_OP: "match";
|
|
34
|
+
export declare const NULL_OPS: readonly ["isNull", "notNull"];
|
|
35
|
+
export declare const Cond: z.ZodUnion<readonly [z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
36
|
+
"!=": "!=";
|
|
37
|
+
"<": "<";
|
|
38
|
+
"<=": "<=";
|
|
39
|
+
"=": "=";
|
|
40
|
+
">": ">";
|
|
41
|
+
">=": ">=";
|
|
42
|
+
in: "in";
|
|
43
|
+
match: "match";
|
|
44
|
+
notIn: "notIn";
|
|
45
|
+
}>, z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
46
|
+
param: z.ZodString;
|
|
47
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
48
|
+
today: z.ZodNumber;
|
|
49
|
+
}, z.core.$strict>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
50
|
+
param: z.ZodString;
|
|
51
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
52
|
+
today: z.ZodNumber;
|
|
53
|
+
}, z.core.$strict>]>>]>], null>, z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
54
|
+
isNull: "isNull";
|
|
55
|
+
notNull: "notNull";
|
|
56
|
+
}>], null>]>;
|
|
57
|
+
export declare const Join: z.ZodObject<{
|
|
58
|
+
on: z.ZodString;
|
|
59
|
+
to: z.ZodString;
|
|
60
|
+
}, z.core.$strict>;
|
|
61
|
+
export declare const AGGREGATES: readonly ["sum", "avg", "min", "max", "count", "countDistinct"];
|
|
62
|
+
export type Aggregate = (typeof AGGREGATES)[number];
|
|
63
|
+
export declare const Measure: z.ZodUnion<readonly [z.ZodObject<{
|
|
64
|
+
as: z.ZodString;
|
|
65
|
+
sum: z.ZodString;
|
|
66
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
67
|
+
as: z.ZodString;
|
|
68
|
+
avg: z.ZodString;
|
|
69
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
70
|
+
as: z.ZodString;
|
|
71
|
+
min: z.ZodString;
|
|
72
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
73
|
+
as: z.ZodString;
|
|
74
|
+
max: z.ZodString;
|
|
75
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
76
|
+
as: z.ZodString;
|
|
77
|
+
count: z.ZodString;
|
|
78
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
79
|
+
as: z.ZodString;
|
|
80
|
+
countDistinct: z.ZodString;
|
|
81
|
+
}, z.core.$strict>]>;
|
|
82
|
+
export declare const OrderKey: z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
83
|
+
asc: "asc";
|
|
84
|
+
desc: "desc";
|
|
85
|
+
}>], null>;
|
|
86
|
+
export declare const IRSchema: z.ZodObject<{
|
|
87
|
+
scan: z.ZodString;
|
|
88
|
+
join: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
89
|
+
on: z.ZodString;
|
|
90
|
+
to: z.ZodString;
|
|
91
|
+
}, z.core.$strict>>>;
|
|
92
|
+
where: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
93
|
+
"!=": "!=";
|
|
94
|
+
"<": "<";
|
|
95
|
+
"<=": "<=";
|
|
96
|
+
"=": "=";
|
|
97
|
+
">": ">";
|
|
98
|
+
">=": ">=";
|
|
99
|
+
in: "in";
|
|
100
|
+
match: "match";
|
|
101
|
+
notIn: "notIn";
|
|
102
|
+
}>, z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
103
|
+
param: z.ZodString;
|
|
104
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
105
|
+
today: z.ZodNumber;
|
|
106
|
+
}, z.core.$strict>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
107
|
+
param: z.ZodString;
|
|
108
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
109
|
+
today: z.ZodNumber;
|
|
110
|
+
}, z.core.$strict>]>>]>], null>, z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
111
|
+
isNull: "isNull";
|
|
112
|
+
notNull: "notNull";
|
|
113
|
+
}>], null>]>>>;
|
|
114
|
+
groupBy: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
115
|
+
measures: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
|
|
116
|
+
as: z.ZodString;
|
|
117
|
+
sum: z.ZodString;
|
|
118
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
119
|
+
as: z.ZodString;
|
|
120
|
+
avg: z.ZodString;
|
|
121
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
122
|
+
as: z.ZodString;
|
|
123
|
+
min: z.ZodString;
|
|
124
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
125
|
+
as: z.ZodString;
|
|
126
|
+
max: z.ZodString;
|
|
127
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
128
|
+
as: z.ZodString;
|
|
129
|
+
count: z.ZodString;
|
|
130
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
131
|
+
as: z.ZodString;
|
|
132
|
+
countDistinct: z.ZodString;
|
|
133
|
+
}, z.core.$strict>]>>>;
|
|
134
|
+
select: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
135
|
+
orderBy: z.ZodOptional<z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
136
|
+
asc: "asc";
|
|
137
|
+
desc: "desc";
|
|
138
|
+
}>], null>>>;
|
|
139
|
+
limit: z.ZodNumber;
|
|
140
|
+
}, z.core.$strict>;
|
|
141
|
+
export type IR = z.infer<typeof IRSchema>;
|
|
142
|
+
export type IRCond = z.infer<typeof Cond>;
|
|
143
|
+
export type IRValue = z.infer<typeof Value>;
|
|
144
|
+
export type IRScalar = z.infer<typeof Scalar>;
|
|
145
|
+
export type IRMeasure = z.infer<typeof Measure>;
|
|
146
|
+
export declare function measureOf(m: IRMeasure): {
|
|
147
|
+
agg: Aggregate;
|
|
148
|
+
field: string;
|
|
149
|
+
as: string;
|
|
150
|
+
};
|
|
151
|
+
export type Row = Record<string, unknown>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type Role } from "@crasi/bisque-core";
|
|
3
|
+
import { type ContractManifest } from "@crasi/bisque-contract";
|
|
4
|
+
import { type QueryResult } from "./execute.js";
|
|
5
|
+
import type { Row } from "./schema.js";
|
|
6
|
+
/**
|
|
7
|
+
* Running specs on the host's server, for hosts whose data does not live in
|
|
8
|
+
* the browser (no client-held store, or no row-level security to lean on).
|
|
9
|
+
* The browser sends the query, not a resource name and not a tenant; the
|
|
10
|
+
* server re-validates it against the contract and the role it reads from
|
|
11
|
+
* its own session, loads only what the query touches, and runs it.
|
|
12
|
+
*
|
|
13
|
+
* The rows still go only to the host's own page, never to the conductor:
|
|
14
|
+
* custody (P1) is the same as for the in-memory executor.
|
|
15
|
+
*/
|
|
16
|
+
export type ServerQueryRequest = {
|
|
17
|
+
ir: unknown;
|
|
18
|
+
params?: Record<string, unknown>;
|
|
19
|
+
today?: string;
|
|
20
|
+
};
|
|
21
|
+
export declare const ServerQueryRequestSchema: z.ZodObject<{
|
|
22
|
+
ir: z.ZodUnknown;
|
|
23
|
+
params: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
24
|
+
param: z.ZodString;
|
|
25
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
26
|
+
today: z.ZodNumber;
|
|
27
|
+
}, z.core.$strict>]>, z.ZodArray<z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>, z.ZodObject<{
|
|
28
|
+
param: z.ZodString;
|
|
29
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
30
|
+
today: z.ZodNumber;
|
|
31
|
+
}, z.core.$strict>]>>]>>>;
|
|
32
|
+
today: z.ZodOptional<z.ZodString>;
|
|
33
|
+
}, z.core.$strict>;
|
|
34
|
+
export type ServerQueryOptions = {
|
|
35
|
+
manifest: ContractManifest;
|
|
36
|
+
/** From the host's session, never from the request. */
|
|
37
|
+
role: Role;
|
|
38
|
+
/**
|
|
39
|
+
* Rows of one resource for the signed-in tenant, already scoped and capped
|
|
40
|
+
* by the host. Called once per touched resource per query.
|
|
41
|
+
*/
|
|
42
|
+
load: (resource: string) => Promise<Row[]>;
|
|
43
|
+
};
|
|
44
|
+
export declare function serveQuery(input: unknown, opts: ServerQueryOptions): Promise<QueryResult>;
|
|
45
|
+
/** Distinct values of a field the contract marks `values: "share"`; refuses any other field. */
|
|
46
|
+
export declare function serveDistinct(resource: unknown, field: unknown, opts: ServerQueryOptions): Promise<string[]>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
import { type Problem, type Role } from "@crasi/bisque-core";
|
|
3
|
+
import { type ContractManifest, type FieldDescriptor, type FieldType } from "@crasi/bisque-contract";
|
|
4
|
+
import { type IR } from "./schema.js";
|
|
5
|
+
export type Column = FieldDescriptor & {
|
|
6
|
+
/** The resource and field the column comes from; absent for measures. */
|
|
7
|
+
source?: {
|
|
8
|
+
resource: string;
|
|
9
|
+
field: string;
|
|
10
|
+
};
|
|
11
|
+
measure?: {
|
|
12
|
+
agg: string;
|
|
13
|
+
of: string;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
export type IRValidation = {
|
|
17
|
+
ok: boolean;
|
|
18
|
+
problems: Problem[];
|
|
19
|
+
ir?: IR;
|
|
20
|
+
/** Every resource the query touches: scan + join targets (Proposition 1). */
|
|
21
|
+
touched: string[];
|
|
22
|
+
/** Output columns by name, as written in the IR. */
|
|
23
|
+
columns: Record<string, Column>;
|
|
24
|
+
/** Params the query refers to. */
|
|
25
|
+
params: string[];
|
|
26
|
+
};
|
|
27
|
+
export type IRValidateOptions = {
|
|
28
|
+
/** The artifact manifest's declared reads. Every touched resource must be in it. */
|
|
29
|
+
reads?: string[];
|
|
30
|
+
role?: Role;
|
|
31
|
+
/** Declared params and their types. When given, every `{param}` must be in it. */
|
|
32
|
+
params?: Record<string, FieldType | "any">;
|
|
33
|
+
maxLimit?: number;
|
|
34
|
+
};
|
|
35
|
+
export declare function zodProblems(err: z.ZodError, prefix?: string): Problem[];
|
|
36
|
+
type Scope = {
|
|
37
|
+
scan: string;
|
|
38
|
+
resources: Set<string>;
|
|
39
|
+
};
|
|
40
|
+
export declare function resolveField(m: ContractManifest, scope: Scope, name: string): {
|
|
41
|
+
resource: string;
|
|
42
|
+
field: string;
|
|
43
|
+
desc: FieldDescriptor;
|
|
44
|
+
} | string;
|
|
45
|
+
export declare function validateIR(input: unknown, m: ContractManifest, opts?: IRValidateOptions): IRValidation;
|
|
46
|
+
/** Resources an IR touches, without full validation. Used by the bridge's manifest gate. */
|
|
47
|
+
export declare function touched(ir: Pick<IR, "scan" | "join">): string[];
|
|
48
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crasi/bisque-ir",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Query IR, validator and in-memory executor",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Crasi",
|
|
7
|
+
"homepage": "https://github.com/gogeorge/bisque#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/gogeorge/bisque.git",
|
|
11
|
+
"directory": "packages/ir"
|
|
12
|
+
},
|
|
13
|
+
"bugs": "https://github.com/gogeorge/bisque/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"bisque",
|
|
16
|
+
"generative-ui",
|
|
17
|
+
"ai",
|
|
18
|
+
"llm",
|
|
19
|
+
"query",
|
|
20
|
+
"ir",
|
|
21
|
+
"executor"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/types/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"zod": "^4.6.7",
|
|
43
|
+
"@crasi/bisque-core": "0.3.0",
|
|
44
|
+
"@crasi/bisque-contract": "0.3.0"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"typecheck": "tsc -p ."
|
|
48
|
+
}
|
|
6
49
|
}
|