foldkit-entity 0.10.0 → 0.12.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/README.md +316 -8
- package/dist/conformance/index.d.mts +203 -4
- package/dist/conformance/index.d.mts.map +1 -1
- package/dist/conformance/index.mjs +351 -5
- package/dist/conformance/index.mjs.map +1 -1
- package/dist/{index-_x1ScI4v.d.mts → index-B9fbDo_-.d.mts} +951 -75
- package/dist/index-B9fbDo_-.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-Iz7806gm.mjs → src-CSxcKUv6.mjs} +1233 -174
- package/dist/src-CSxcKUv6.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/index-_x1ScI4v.d.mts.map +0 -1
- package/dist/src-Iz7806gm.mjs.map +0 -1
|
@@ -1,22 +1,7 @@
|
|
|
1
|
-
import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
1
|
+
import { Array as Array$1, Data, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
|
|
6
|
-
/** What a schema's AST holds, read through Effect's own guards. */
|
|
7
|
-
const SchemaShape = {
|
|
8
|
-
/** True for the `null` and `undefined` members that make a schema optional. */
|
|
9
|
-
isNullish,
|
|
10
|
-
/**
|
|
11
|
-
* The members of a schema with `null` and `undefined` set aside, so optional
|
|
12
|
-
* text is still text; a schema that is not a union is its one member.
|
|
13
|
-
*/
|
|
14
|
-
present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
|
|
15
|
-
/** True when every value the schema admits is a string. */
|
|
16
|
-
isText
|
|
17
|
-
};
|
|
18
|
-
//#endregion
|
|
19
|
-
//#region src/collation.ts
|
|
3
|
+
import { absurd } from "effect/Function";
|
|
4
|
+
// src/collation.ts
|
|
20
5
|
/**
|
|
21
6
|
* How text compares when a query orders by it, declared rather than left to
|
|
22
7
|
* the backend. Left unsaid, SQLite compares bytes, Postgres follows the
|
|
@@ -48,10 +33,106 @@ const Collation = {
|
|
|
48
33
|
/** Member metadata: how a text field orders, wherever a query orders by it. */
|
|
49
34
|
of: (collation) => key$1.of(collation),
|
|
50
35
|
/** The collation a member's metadata declares, if any. */
|
|
51
|
-
declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0])
|
|
36
|
+
declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0]),
|
|
37
|
+
/**
|
|
38
|
+
* Text as `asciiFold` compares it: ASCII letters lowercased, every other
|
|
39
|
+
* character as it is, which is what SQLite's `lower` does without ICU and so
|
|
40
|
+
* what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
|
|
41
|
+
* there. An operator implementing `asciiFold` folds with this.
|
|
42
|
+
*/
|
|
43
|
+
foldAscii: (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase())
|
|
44
|
+
};
|
|
45
|
+
// src/law.ts
|
|
46
|
+
/**
|
|
47
|
+
* Laws an operator declares (expr-operations-DESIGN §10): equations every
|
|
48
|
+
* implementation of it keeps over a domain. A law describes; nothing rewrites a
|
|
49
|
+
* body by one. `Conformance.laws` tests an implementation against them, and
|
|
50
|
+
* what it finds is evidence recorded in that implementation's table.
|
|
51
|
+
*/
|
|
52
|
+
const Laws = Data.taggedEnum();
|
|
53
|
+
const unnarrowed = { domain: Option.none() };
|
|
54
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
55
|
+
const nameOf$1 = (operator) => operator.descriptor.version === 1 ? operator.descriptor.id : `${operator.descriptor.id}@${operator.descriptor.version}`;
|
|
56
|
+
const Law = {
|
|
57
|
+
associative: Laws.Associative(unnarrowed),
|
|
58
|
+
commutative: Laws.Commutative(unnarrowed),
|
|
59
|
+
idempotent: Laws.Idempotent(unnarrowed),
|
|
60
|
+
preservesCollation: Laws.PreservesCollation(unnarrowed),
|
|
61
|
+
/** `value` leaves the other argument as it is, from `side` (both by default). */
|
|
62
|
+
identity: (value, side = "both") => Laws.Identity({
|
|
63
|
+
...unnarrowed,
|
|
64
|
+
value,
|
|
65
|
+
side
|
|
66
|
+
}),
|
|
67
|
+
/** `value` is the answer whatever the other argument, from `side` (both by default). */
|
|
68
|
+
absorbing: (value, side = "both") => Laws.Absorbing({
|
|
69
|
+
...unnarrowed,
|
|
70
|
+
value,
|
|
71
|
+
side
|
|
72
|
+
}),
|
|
73
|
+
/** `other` undoes the operator: `op(a, other(a))` is `identity`. */
|
|
74
|
+
inverse: (other, identity) => Laws.Inverse({
|
|
75
|
+
...unnarrowed,
|
|
76
|
+
other,
|
|
77
|
+
identity
|
|
78
|
+
}),
|
|
79
|
+
/** The operator distributes over `over`, from the left. */
|
|
80
|
+
distributes: (over) => Laws.Distributes({
|
|
81
|
+
...unnarrowed,
|
|
82
|
+
over
|
|
83
|
+
}),
|
|
84
|
+
/** Moving the argument at `position` up moves the result up (or down, decreasing). */
|
|
85
|
+
monotonic: (direction, position) => Laws.Monotonic({
|
|
86
|
+
...unnarrowed,
|
|
87
|
+
direction,
|
|
88
|
+
position
|
|
89
|
+
}),
|
|
90
|
+
/**
|
|
91
|
+
* The law over the values `domain` accepts only: a law that holds of the
|
|
92
|
+
* integers and not of every number, say, narrowed so it is tested where it
|
|
93
|
+
* is claimed.
|
|
94
|
+
*/
|
|
95
|
+
within: (law, domain) => Object.freeze({
|
|
96
|
+
...law,
|
|
97
|
+
domain: Option.some(domain)
|
|
98
|
+
}),
|
|
99
|
+
$match: Laws.$match,
|
|
100
|
+
/** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
|
|
101
|
+
describe: (law) => {
|
|
102
|
+
const witnesses = Laws.$match(law, {
|
|
103
|
+
Associative: () => ({}),
|
|
104
|
+
Commutative: () => ({}),
|
|
105
|
+
Idempotent: () => ({}),
|
|
106
|
+
PreservesCollation: () => ({}),
|
|
107
|
+
Identity: ({ value, side }) => ({
|
|
108
|
+
value,
|
|
109
|
+
side
|
|
110
|
+
}),
|
|
111
|
+
Absorbing: ({ value, side }) => ({
|
|
112
|
+
value,
|
|
113
|
+
side
|
|
114
|
+
}),
|
|
115
|
+
Inverse: ({ other, identity }) => ({
|
|
116
|
+
other: nameOf$1(other),
|
|
117
|
+
identity
|
|
118
|
+
}),
|
|
119
|
+
Distributes: ({ over }) => ({ over: nameOf$1(over) }),
|
|
120
|
+
Monotonic: ({ direction, position }) => ({
|
|
121
|
+
direction,
|
|
122
|
+
position
|
|
123
|
+
})
|
|
124
|
+
});
|
|
125
|
+
return {
|
|
126
|
+
kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
|
|
127
|
+
witnesses,
|
|
128
|
+
domain: Option.match(law.domain, {
|
|
129
|
+
onNone: () => null,
|
|
130
|
+
onSome: (domain) => Schema.toJsonSchemaDocument(domain).schema
|
|
131
|
+
})
|
|
132
|
+
};
|
|
133
|
+
}
|
|
52
134
|
};
|
|
53
|
-
|
|
54
|
-
//#region src/expr.ts
|
|
135
|
+
// src/expr.ts
|
|
55
136
|
/**
|
|
56
137
|
* `Expr` — a query's scalar computations as typed values.
|
|
57
138
|
*
|
|
@@ -65,6 +146,8 @@ const Collation = {
|
|
|
65
146
|
* operation here is one a real query in this repository needs; the set grows
|
|
66
147
|
* from queries, not from what a database could express.
|
|
67
148
|
*/
|
|
149
|
+
/** A table implementing nothing: every primitive operator is unsupported by it. */
|
|
150
|
+
const noOperators = Object.freeze({ has: () => false });
|
|
68
151
|
const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
|
|
69
152
|
/**
|
|
70
153
|
* An Entity's field and a `FieldExpr` are the same three members under the same
|
|
@@ -98,7 +181,8 @@ const predicateTags = /* @__PURE__ */ new Set([
|
|
|
98
181
|
"And",
|
|
99
182
|
"Or",
|
|
100
183
|
"Not",
|
|
101
|
-
"Compare"
|
|
184
|
+
"Compare",
|
|
185
|
+
"Test"
|
|
102
186
|
]);
|
|
103
187
|
/** Whether a value is a predicate, and so usable where a boolean is wanted. */
|
|
104
188
|
const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
@@ -109,7 +193,7 @@ const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
|
109
193
|
const toOperand = (value) => {
|
|
110
194
|
const tag = tagOf(value);
|
|
111
195
|
if (tag === "Field") return fieldExpr(value);
|
|
112
|
-
if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
|
|
196
|
+
if (tag === "Literal" || tag === "Input" || tag === "Next" || tag === "Call" || predicateTags.has(tag)) return value;
|
|
113
197
|
return literal(value);
|
|
114
198
|
};
|
|
115
199
|
/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
|
|
@@ -144,8 +228,10 @@ const literalKind = (value) => {
|
|
|
144
228
|
/** How a side orders, read from its encoded form. */
|
|
145
229
|
const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
|
|
146
230
|
Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
|
|
231
|
+
Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
|
|
147
232
|
Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
|
|
148
|
-
Literal: ({ value }) => literalKind(value)
|
|
233
|
+
Literal: ({ value }) => literalKind(value),
|
|
234
|
+
Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast)
|
|
149
235
|
}));
|
|
150
236
|
/**
|
|
151
237
|
* How a comparison's text compares: the collation given, else the field's
|
|
@@ -159,14 +245,23 @@ const collationFor = (step, left, right, given) => {
|
|
|
159
245
|
const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
|
|
160
246
|
if (kinds.has("none") || kinds.size > 1) throw new Error(`[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`);
|
|
161
247
|
if (!kinds.has("text")) return Option.none();
|
|
162
|
-
const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [
|
|
248
|
+
const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [{
|
|
249
|
+
name: `${field.owner.name}.${field.key}`,
|
|
250
|
+
collation: field.collation
|
|
251
|
+
}]), Match.tag("Next", ({ field }) => [{
|
|
252
|
+
name: `${field.owner.name}.${field.key}`,
|
|
253
|
+
collation: field.collation
|
|
254
|
+
}]), Match.tag("Call", (call) => [{
|
|
255
|
+
name: showExpr(call),
|
|
256
|
+
collation: call.collation
|
|
257
|
+
}]), Match.orElse(() => [])));
|
|
163
258
|
const [first] = fields;
|
|
164
|
-
if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field,
|
|
165
|
-
const named = fields.map((field) =>
|
|
259
|
+
if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, nor a call carrying a collation, to say how it orders`);
|
|
260
|
+
const named = fields.map((field) => field.name).join(" and ");
|
|
166
261
|
const collations = Option.match(given, {
|
|
167
262
|
onSome: (collation) => [collation],
|
|
168
263
|
onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
|
|
169
|
-
throw new Error(`[foldkit-entity] Expr.${step}: ${field.
|
|
264
|
+
throw new Error(`[foldkit-entity] Expr.${step}: ${field.name} is text with no declared collation, so backends would order it differently; declare Collation.binary or Collation.asciiFold on it, or pass one`);
|
|
170
265
|
}))
|
|
171
266
|
});
|
|
172
267
|
const [collation] = collations;
|
|
@@ -211,7 +306,304 @@ const connective = (step, kind) => (...given) => {
|
|
|
211
306
|
operands
|
|
212
307
|
});
|
|
213
308
|
};
|
|
309
|
+
const collationTags = /* @__PURE__ */ new Set([
|
|
310
|
+
"Binary",
|
|
311
|
+
"AsciiFold",
|
|
312
|
+
"Locale"
|
|
313
|
+
]);
|
|
314
|
+
/** A call's last value, when it is one past the arguments: its options, checked. */
|
|
315
|
+
const callOptionsOf = (id, value) => {
|
|
316
|
+
const collation = typeof value === "object" && value !== null && Object.hasOwn(value, "collation") ? value.collation : void 0;
|
|
317
|
+
if (!collationTags.has(tagOf(collation))) throw new Error(`[foldkit-entity] ${id}: a value past its arguments is \`{ collation }\`, a Collation`);
|
|
318
|
+
return collation;
|
|
319
|
+
};
|
|
320
|
+
/** A collation a call was given: one its operator compares by, and portable where required. */
|
|
321
|
+
const givenCollation = (id, descriptor, collation) => {
|
|
322
|
+
if (Option.isSome(descriptor.definedAs) || descriptor.collation === "none") throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`);
|
|
323
|
+
if (descriptor.collation === "required" && collation._tag === "Locale") throw new Error(`[foldkit-entity] ${id}: compares by the backend's "${collation.locale}" collation, which only that backend has`);
|
|
324
|
+
return Option.some(collation);
|
|
325
|
+
};
|
|
326
|
+
/** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */
|
|
327
|
+
const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
|
|
328
|
+
/**
|
|
329
|
+
* Why `law` cannot be declared of an operator of this shape, if it cannot: an
|
|
330
|
+
* equation over two arguments of a unary operator, a witness that does not
|
|
331
|
+
* decode as the argument it stands in, or a collation law of an operator
|
|
332
|
+
* whose text keeps none.
|
|
333
|
+
*/
|
|
334
|
+
const lawProblem = (law, input, output, collation) => {
|
|
335
|
+
const name = Law.describe(law).kind;
|
|
336
|
+
const binary = () => input.length === 2 ? Option.none() : Option.some(`${name} is a law of an operator of two arguments, and this one takes ${input.length}`);
|
|
337
|
+
const decodes = (value, schema, what) => Schema.is(Schema.toEncoded(schema))(value) ? Option.none() : Option.some(`${name}'s ${what} ${JSON.stringify(value)} does not decode as its schema`);
|
|
338
|
+
const sides = (value, side) => Option.orElse(binary(), () => Option.orElse(side === "right" ? Option.none() : decodes(value, input[0], "left witness"), () => side === "left" ? Option.none() : decodes(value, input[1], "right witness")));
|
|
339
|
+
return Law.$match(law, {
|
|
340
|
+
Associative: binary,
|
|
341
|
+
Commutative: binary,
|
|
342
|
+
Idempotent: binary,
|
|
343
|
+
Identity: ({ value, side }) => sides(value, side),
|
|
344
|
+
Absorbing: ({ value, side }) => sides(value, side),
|
|
345
|
+
Inverse: ({ other, identity }) => Option.orElse(binary(), () => other.descriptor.input.length === 1 ? decodes(identity, output, "identity") : Option.some(`${name}'s other operator takes one argument`)),
|
|
346
|
+
Distributes: ({ over }) => Option.orElse(binary(), () => over.descriptor.input.length === 2 ? Option.none() : Option.some(`${name} is over an operator of two arguments`)),
|
|
347
|
+
Monotonic: ({ position }) => Number.isSafeInteger(position) && position >= 0 && position < input.length ? Option.none() : Option.some(`${name}'s position ${position} is not an argument's`),
|
|
348
|
+
PreservesCollation: () => collation === "operands" ? Option.none() : Option.some(`${name} is a law of an operator declared \`collation: 'operands'\``)
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
/** Whether a schema's stored form is a boolean, which makes its operator a predicate. */
|
|
352
|
+
const storedAsBoolean = (schema) => SchemaAST.isBoolean(Schema.toEncoded(schema).ast);
|
|
353
|
+
/** Every field, field after a write, and input an expression reads, as keys to compare. */
|
|
354
|
+
const readKeys = (...nodes) => {
|
|
355
|
+
const read = dependenciesOf(...nodes);
|
|
356
|
+
const named = (prefix, fields) => fields.map((field) => `${prefix}${field.entity}.${field.key}`);
|
|
357
|
+
return /* @__PURE__ */ new Set([
|
|
358
|
+
...named("", read.fields),
|
|
359
|
+
...named("next ", read.next),
|
|
360
|
+
...read.inputs.map((key) => `$${key}`)
|
|
361
|
+
]);
|
|
362
|
+
};
|
|
363
|
+
/** One argument, checked against the schema it is passed for, as a node. */
|
|
364
|
+
const argumentFor = (id, position, schema, value) => {
|
|
365
|
+
const arg = toOperand(value);
|
|
366
|
+
const fail = (what) => {
|
|
367
|
+
throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`);
|
|
368
|
+
};
|
|
369
|
+
if (isPredicate(arg)) {
|
|
370
|
+
if (!storedAsBoolean(schema)) fail("is a predicate, but the operator does not take a boolean");
|
|
371
|
+
return arg;
|
|
372
|
+
}
|
|
373
|
+
if (arg._tag === "Literal") {
|
|
374
|
+
if (!Schema.is(Schema.toEncoded(schema))(arg.value)) fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`);
|
|
375
|
+
return arg;
|
|
376
|
+
}
|
|
377
|
+
const wanted = orderKindOf(Schema.toEncoded(schema).ast);
|
|
378
|
+
const given = sideKind(arg);
|
|
379
|
+
if (wanted !== "none" && (given === "number" || given === "text") && given !== wanted) fail(`is stored as ${given}, but the operator takes ${wanted}`);
|
|
380
|
+
return arg;
|
|
381
|
+
};
|
|
382
|
+
/** A scalar's collation: a field's declared one, or a call's. */
|
|
383
|
+
const collationOf = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
|
|
384
|
+
Field: (field) => field.collation,
|
|
385
|
+
Next: ({ field }) => field.collation,
|
|
386
|
+
Call: (call) => call.collation,
|
|
387
|
+
Literal: () => Option.none(),
|
|
388
|
+
Input: () => Option.none()
|
|
389
|
+
}));
|
|
390
|
+
/**
|
|
391
|
+
* The collation a primitive call compares text under: the one its collated
|
|
392
|
+
* text arguments share. A literal or an input carries none and does not vote.
|
|
393
|
+
* `required` refuses a call with none, or with a backend's locale.
|
|
394
|
+
*/
|
|
395
|
+
const callCollation = (id, rule, args) => {
|
|
396
|
+
if (rule === "none") return Option.none();
|
|
397
|
+
const fail = (what) => {
|
|
398
|
+
throw new Error(`[foldkit-entity] ${id}: ${what}`);
|
|
399
|
+
};
|
|
400
|
+
const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
|
|
401
|
+
name: showExpr(arg),
|
|
402
|
+
collation: collationOf(arg)
|
|
403
|
+
}]);
|
|
404
|
+
const collations = voters.flatMap(({ name, collation }) => Option.match(collation, {
|
|
405
|
+
onSome: (each) => [each],
|
|
406
|
+
onNone: () => rule === "required" ? fail(`${name} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`) : []
|
|
407
|
+
}));
|
|
408
|
+
const [shared] = collations;
|
|
409
|
+
if (shared === void 0) return rule === "required" ? fail("compares text with no field or call holding a collation") : Option.none();
|
|
410
|
+
if (collations.some((each) => each._tag !== shared._tag)) fail(`${voters.map((voter) => voter.name).join(" and ")} declare different collations`);
|
|
411
|
+
if (rule === "required" && shared._tag === "Locale") fail(`compares by the backend's "${shared.locale}" collation, which only that backend has`);
|
|
412
|
+
return Option.some(shared);
|
|
413
|
+
};
|
|
414
|
+
/** Builds an operator: checks what it is given once, then each call. */
|
|
415
|
+
const makeOperator = (id, options) => {
|
|
416
|
+
const fail = (what) => {
|
|
417
|
+
throw new Error(`[foldkit-entity] Expr.operator("${id}"): ${what}`);
|
|
418
|
+
};
|
|
419
|
+
if (!operatorId.test(id)) fail("an id is namespaced lower camel case, as `cms.published`");
|
|
420
|
+
if (id.startsWith("foldkit.")) fail("ids under `foldkit.` are reserved");
|
|
421
|
+
const version = options.version ?? 1;
|
|
422
|
+
if (!Number.isSafeInteger(version) || version < 1) fail("a version is a positive integer");
|
|
423
|
+
if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) fail("`input` is one schema per argument");
|
|
424
|
+
if (!Schema.isSchema(options.output)) fail("`output` is a schema");
|
|
425
|
+
const definedAs = Option.fromUndefinedOr(options.definedAs);
|
|
426
|
+
if (Option.isSome(definedAs) && typeof definedAs.value !== "function") fail("`definedAs` builds what a call means");
|
|
427
|
+
if (Option.isSome(definedAs) && (options.nulls !== void 0 || options.collation !== void 0)) fail("a defined operator means its body, so `nulls` and `collation` are its body's");
|
|
428
|
+
const nulls = options.nulls ?? "strict";
|
|
429
|
+
const collation = options.collation ?? "none";
|
|
430
|
+
if (nulls !== "strict" && nulls !== "handled") fail("`nulls` is 'strict' or 'handled'");
|
|
431
|
+
if (collation !== "none" && collation !== "operands" && collation !== "required") fail("`collation` is 'none', 'operands' or 'required'");
|
|
432
|
+
const input = Object.freeze([...options.input]);
|
|
433
|
+
const predicate = storedAsBoolean(options.output);
|
|
434
|
+
if (collation === "operands" && orderKindOf(Schema.toEncoded(options.output).ast) !== "text") fail("`collation: 'operands'` describes a text result, and this one is not text");
|
|
435
|
+
const laws = Object.freeze([...options.laws ?? []]);
|
|
436
|
+
for (const law of laws) Option.match(lawProblem(law, input, options.output, collation), {
|
|
437
|
+
onNone: () => void 0,
|
|
438
|
+
onSome: fail
|
|
439
|
+
});
|
|
440
|
+
const descriptor = Object.freeze({
|
|
441
|
+
_tag: "Operator",
|
|
442
|
+
id,
|
|
443
|
+
version,
|
|
444
|
+
description: Option.fromUndefinedOr(options.description),
|
|
445
|
+
input,
|
|
446
|
+
output: options.output,
|
|
447
|
+
definedAs,
|
|
448
|
+
nulls,
|
|
449
|
+
collation,
|
|
450
|
+
laws
|
|
451
|
+
});
|
|
452
|
+
/** A defined call's expansion, checked: of its output's kind, reading only its arguments. */
|
|
453
|
+
const expand = (body, args) => {
|
|
454
|
+
const expansion = toOperand(body(...args));
|
|
455
|
+
if (predicate !== isPredicate(expansion)) throw new Error(`[foldkit-entity] ${id}: its output is ${predicate ? "a boolean, so `definedAs` returns a predicate" : "not a boolean, so `definedAs` returns a scalar"}`);
|
|
456
|
+
const allowed = readKeys(...args);
|
|
457
|
+
const hidden = [...readKeys(expansion)].filter((key) => !allowed.has(key));
|
|
458
|
+
if (hidden.length > 0) throw new Error(`[foldkit-entity] ${id}: \`definedAs\` reads ${hidden.join(", ")}, which no argument holds; pass it as one`);
|
|
459
|
+
return expansion;
|
|
460
|
+
};
|
|
461
|
+
const call = (...written) => {
|
|
462
|
+
const explicit = written.length === input.length + 1 ? Option.some(callOptionsOf(id, written[written.length - 1])) : Option.none();
|
|
463
|
+
const given = Option.isSome(explicit) ? written.slice(0, -1) : written;
|
|
464
|
+
if (given.length !== input.length) throw new Error(`[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? "" : "s"}, given ${given.length}`);
|
|
465
|
+
const args = Object.freeze(given.map((value, position) => argumentFor(id, position, input[position], value)));
|
|
466
|
+
const expansion = Option.map(descriptor.definedAs, (body) => expand(body, args));
|
|
467
|
+
const carried = Option.match(explicit, {
|
|
468
|
+
onSome: (each) => givenCollation(id, descriptor, each),
|
|
469
|
+
onNone: () => Option.match(expansion, {
|
|
470
|
+
onSome: (body) => isPredicate(body) ? Option.none() : collationOf(body),
|
|
471
|
+
onNone: () => callCollation(id, collation, args)
|
|
472
|
+
})
|
|
473
|
+
});
|
|
474
|
+
return predicate ? node({
|
|
475
|
+
_tag: "Test",
|
|
476
|
+
operator: descriptor,
|
|
477
|
+
args,
|
|
478
|
+
expansion,
|
|
479
|
+
collation: carried
|
|
480
|
+
}) : node({
|
|
481
|
+
_tag: "Call",
|
|
482
|
+
operator: descriptor,
|
|
483
|
+
args,
|
|
484
|
+
expansion,
|
|
485
|
+
collation: carried
|
|
486
|
+
});
|
|
487
|
+
};
|
|
488
|
+
return Object.freeze(Object.assign(call, { descriptor }));
|
|
489
|
+
};
|
|
490
|
+
/** Each defined call replaced by its expansion, deeply; built once per node. */
|
|
491
|
+
const expandedCache = /* @__PURE__ */ new WeakMap();
|
|
492
|
+
const expandedScalar = (scalar) => {
|
|
493
|
+
const known = expandedCache.get(scalar);
|
|
494
|
+
if (known !== void 0) return known;
|
|
495
|
+
const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
|
|
496
|
+
onSome: expandedScalar,
|
|
497
|
+
onNone: () => node({
|
|
498
|
+
...scalar,
|
|
499
|
+
args: scalar.args.map(expandedSide)
|
|
500
|
+
})
|
|
501
|
+
}) : scalar;
|
|
502
|
+
expandedCache.set(scalar, result);
|
|
503
|
+
return result;
|
|
504
|
+
};
|
|
505
|
+
const expandedSide = (side) => isPredicate(side) ? expandedPredicate(side) : expandedScalar(side);
|
|
506
|
+
const expandedPredicate = (predicate) => {
|
|
507
|
+
const known = expandedCache.get(predicate);
|
|
508
|
+
if (known !== void 0) return known;
|
|
509
|
+
const result = Match.value(predicate).pipe(Match.tagsExhaustive({
|
|
510
|
+
Eq: (eq) => node({
|
|
511
|
+
...eq,
|
|
512
|
+
left: expandedSide(eq.left),
|
|
513
|
+
right: expandedSide(eq.right)
|
|
514
|
+
}),
|
|
515
|
+
Null: (nul) => node({
|
|
516
|
+
...nul,
|
|
517
|
+
operand: expandedScalar(nul.operand)
|
|
518
|
+
}),
|
|
519
|
+
Contains: (contains) => node({
|
|
520
|
+
...contains,
|
|
521
|
+
value: expandedScalar(contains.value),
|
|
522
|
+
search: expandedSide(contains.search)
|
|
523
|
+
}),
|
|
524
|
+
In: (inPredicate) => node({
|
|
525
|
+
...inPredicate,
|
|
526
|
+
value: expandedScalar(inPredicate.value),
|
|
527
|
+
among: expandedScalar(inPredicate.among)
|
|
528
|
+
}),
|
|
529
|
+
And: (and) => node({
|
|
530
|
+
...and,
|
|
531
|
+
operands: Array$1.map(and.operands, expandedPredicate)
|
|
532
|
+
}),
|
|
533
|
+
Or: (or) => node({
|
|
534
|
+
...or,
|
|
535
|
+
operands: Array$1.map(or.operands, expandedPredicate)
|
|
536
|
+
}),
|
|
537
|
+
Not: (not) => node({
|
|
538
|
+
...not,
|
|
539
|
+
operand: expandedPredicate(not.operand)
|
|
540
|
+
}),
|
|
541
|
+
Compare: (compare) => node({
|
|
542
|
+
...compare,
|
|
543
|
+
left: expandedScalar(compare.left),
|
|
544
|
+
right: expandedScalar(compare.right)
|
|
545
|
+
}),
|
|
546
|
+
Test: (test) => Option.match(test.expansion, {
|
|
547
|
+
onSome: expandedPredicate,
|
|
548
|
+
onNone: () => node({
|
|
549
|
+
...test,
|
|
550
|
+
args: test.args.map(expandedSide)
|
|
551
|
+
})
|
|
552
|
+
})
|
|
553
|
+
}));
|
|
554
|
+
expandedCache.set(predicate, result);
|
|
555
|
+
return result;
|
|
556
|
+
};
|
|
214
557
|
const Expr = {
|
|
558
|
+
/**
|
|
559
|
+
* An operator, defined by what a call of it means: `definedAs` builds that
|
|
560
|
+
* expression from the call's arguments, once per call, and every interpreter
|
|
561
|
+
* runs it, so the operator needs no implementation anywhere. What it adds is
|
|
562
|
+
* a name: a query, a guard and an invariant that mean the same thing say so,
|
|
563
|
+
* and print it.
|
|
564
|
+
*
|
|
565
|
+
* ```ts
|
|
566
|
+
* const published = Expr.operator('cms.published', {
|
|
567
|
+
* input: [Schema.Unknown],
|
|
568
|
+
* output: Schema.Boolean,
|
|
569
|
+
* definedAs: publishedAt => Expr.isNotNull(publishedAt),
|
|
570
|
+
* })
|
|
571
|
+
* Query.where(published(Post.fields.publishedAt))
|
|
572
|
+
* ```
|
|
573
|
+
*
|
|
574
|
+
* Arguments are checked by their stored form: a field, scalar or plain value
|
|
575
|
+
* of the input's stored type, or a predicate where it takes a boolean. A
|
|
576
|
+
* boolean output makes a call a predicate. `definedAs` may read only what its
|
|
577
|
+
* arguments hold: a field or input it closes over instead is refused when
|
|
578
|
+
* called, since nothing asking what the call reads would see it. The id is
|
|
579
|
+
* namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
|
|
580
|
+
* changes when what it means does.
|
|
581
|
+
*
|
|
582
|
+
* **Without `definedAs` it is primitive**: each interpreter implements it
|
|
583
|
+
* (`Operators.implement` in memory), and one without an implementation
|
|
584
|
+
* refuses the body by the operator's id. `nulls` (default `strict`: a null
|
|
585
|
+
* argument gives null, the implementation never sees one) and `collation`
|
|
586
|
+
* (`operands`: a text result carries its text arguments' shared collation;
|
|
587
|
+
* `required`: it compares text itself and needs one) are a primitive
|
|
588
|
+
* operator's; a defined one means its body for both.
|
|
589
|
+
*/
|
|
590
|
+
operator: (id, options) => makeOperator(id, options),
|
|
591
|
+
/**
|
|
592
|
+
* The predicate or scalar (an order term's, say) with every call of a
|
|
593
|
+
* defined operator replaced by what it means, deeply. An interpreter that
|
|
594
|
+
* compiles a body expands it first, and compiles exactly what was written
|
|
595
|
+
* out. A call with no definition stays, for the interpreter to run or refuse
|
|
596
|
+
* by name.
|
|
597
|
+
*/
|
|
598
|
+
expanded: (node) => isPredicate(node) ? expandedPredicate(node) : expandedScalar(node),
|
|
599
|
+
/**
|
|
600
|
+
* What these expressions need that an interpreter lacks, as `Query.unsupported`
|
|
601
|
+
* says it for a query: each kernel operation `supported` does not list, then
|
|
602
|
+
* each primitive operator `operators` does not implement, by name (`id`, or
|
|
603
|
+
* `id@version` past the first). For anything holding expressions that is not a
|
|
604
|
+
* query: a guard's rule, an invariant, a write's `when`.
|
|
605
|
+
*/
|
|
606
|
+
unsupported: (nodes, interpreter) => unsupportedIn(nodes, interpreter.operations, interpreter.operators),
|
|
215
607
|
/** A constant. Comparisons coerce a plain value, so this is rarely written. */
|
|
216
608
|
literal,
|
|
217
609
|
/**
|
|
@@ -223,6 +615,14 @@ const Expr = {
|
|
|
223
615
|
key,
|
|
224
616
|
schema
|
|
225
617
|
}),
|
|
618
|
+
/**
|
|
619
|
+
* A field as the row a write would leave holds it: what `Entity.invariant`'s
|
|
620
|
+
* builder hands out as `after`.
|
|
621
|
+
*/
|
|
622
|
+
next: (field) => node({
|
|
623
|
+
_tag: "Next",
|
|
624
|
+
field: fieldExpr(field)
|
|
625
|
+
}),
|
|
226
626
|
/** One field of one Entity, as a scalar. */
|
|
227
627
|
field: (field) => fieldExpr(field),
|
|
228
628
|
/**
|
|
@@ -363,16 +763,99 @@ const Expr = {
|
|
|
363
763
|
*/
|
|
364
764
|
whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
|
|
365
765
|
/** An expression as readable text; see `showExpr` for what it is and is not. */
|
|
366
|
-
show: (node) => showExpr(node)
|
|
766
|
+
show: (node) => showExpr(node),
|
|
767
|
+
/**
|
|
768
|
+
* The predicate with each field after a write (`Next`) that `values` names,
|
|
769
|
+
* by key, read as that value: how an invariant is judged where the
|
|
770
|
+
* write's new values are known. A field it does not name stays `Next`, for
|
|
771
|
+
* the interpreter to read as the row after holds it.
|
|
772
|
+
*/
|
|
773
|
+
substituteNext: (predicate, values) => substituted(predicate, (operand) => Match.value(operand).pipe(Match.tag("Next", ({ field }) => Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand), Match.orElse(() => operand)))
|
|
774
|
+
};
|
|
775
|
+
const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite);
|
|
776
|
+
/**
|
|
777
|
+
* A scalar rewritten: a call's arguments and expansion each, so a field read
|
|
778
|
+
* under it is rewritten as one read directly is; anything else by `rewrite`.
|
|
779
|
+
*/
|
|
780
|
+
const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
|
|
781
|
+
...scalar,
|
|
782
|
+
args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
|
|
783
|
+
expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
|
|
784
|
+
}) : rewrite(scalar);
|
|
785
|
+
const substituted = (predicate, rewrite) => {
|
|
786
|
+
switch (predicate._tag) {
|
|
787
|
+
case "Eq": return node({
|
|
788
|
+
...predicate,
|
|
789
|
+
left: substitutedSide(predicate.left, rewrite),
|
|
790
|
+
right: substitutedSide(predicate.right, rewrite)
|
|
791
|
+
});
|
|
792
|
+
case "Null": return node({
|
|
793
|
+
...predicate,
|
|
794
|
+
operand: substitutedScalar(predicate.operand, rewrite)
|
|
795
|
+
});
|
|
796
|
+
case "Contains": return node({
|
|
797
|
+
...predicate,
|
|
798
|
+
value: substitutedScalar(predicate.value, rewrite),
|
|
799
|
+
search: substitutedSide(predicate.search, rewrite)
|
|
800
|
+
});
|
|
801
|
+
case "In": return node({
|
|
802
|
+
...predicate,
|
|
803
|
+
value: substitutedScalar(predicate.value, rewrite),
|
|
804
|
+
among: substitutedScalar(predicate.among, rewrite)
|
|
805
|
+
});
|
|
806
|
+
case "And":
|
|
807
|
+
case "Or": return node({
|
|
808
|
+
...predicate,
|
|
809
|
+
operands: Array$1.map(predicate.operands, (operand) => substituted(operand, rewrite))
|
|
810
|
+
});
|
|
811
|
+
case "Not": return node({
|
|
812
|
+
...predicate,
|
|
813
|
+
operand: substituted(predicate.operand, rewrite)
|
|
814
|
+
});
|
|
815
|
+
case "Compare": return node({
|
|
816
|
+
...predicate,
|
|
817
|
+
left: substitutedScalar(predicate.left, rewrite),
|
|
818
|
+
right: substitutedScalar(predicate.right, rewrite)
|
|
819
|
+
});
|
|
820
|
+
case "Test": return node({
|
|
821
|
+
...predicate,
|
|
822
|
+
args: Object.freeze(predicate.args.map((arg) => substitutedSide(arg, rewrite))),
|
|
823
|
+
expansion: Option.map(predicate.expansion, (expansion) => substituted(expansion, rewrite))
|
|
824
|
+
});
|
|
825
|
+
}
|
|
367
826
|
};
|
|
368
827
|
/** A term, its nulls placed by `options` or by the direction's default. */
|
|
369
|
-
const term = (direction, expr, options = {}) =>
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
828
|
+
const term = (direction, expr, options = {}) => {
|
|
829
|
+
const collation = Option.orElse(Option.fromUndefinedOr(options.collation), () => Match.value(expr).pipe(Match.tag("Field", (field) => field.collation), Match.tag("Call", (call) => call.collation), Match.orElse(() => Option.none())));
|
|
830
|
+
if (expr._tag === "Call") orderableCall(expr, collation);
|
|
831
|
+
return node({
|
|
832
|
+
_tag: "Term",
|
|
833
|
+
direction,
|
|
834
|
+
expr,
|
|
835
|
+
nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
|
|
836
|
+
collation
|
|
837
|
+
});
|
|
838
|
+
};
|
|
839
|
+
/**
|
|
840
|
+
* Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):
|
|
841
|
+
* its result must be a number, or text under a collation every interpreter
|
|
842
|
+
* shares. A field's text may be left to the backend; a call's has no backend
|
|
843
|
+
* column to fall back on.
|
|
844
|
+
*/
|
|
845
|
+
const orderableCall = (call, collation) => {
|
|
846
|
+
const fail = (why) => {
|
|
847
|
+
throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`);
|
|
848
|
+
};
|
|
849
|
+
const kind = sideKind(call);
|
|
850
|
+
if (kind === "number") return;
|
|
851
|
+
if (kind !== "text") fail("is neither a number nor text, so it orders nowhere alike");
|
|
852
|
+
Option.match(collation, {
|
|
853
|
+
onNone: () => fail("is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold"),
|
|
854
|
+
onSome: (each) => {
|
|
855
|
+
if (each._tag === "Locale") fail(`is ordered by the backend's "${each.locale}" collation, which a call cannot carry`);
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
};
|
|
376
859
|
const Order = {
|
|
377
860
|
/** Smallest first; rows without a value last, unless `nulls` says first. */
|
|
378
861
|
asc: (expr, options) => term("asc", toExpr(expr, "asc"), options),
|
|
@@ -380,8 +863,8 @@ const Order = {
|
|
|
380
863
|
desc: (expr, options) => term("desc", toExpr(expr, "desc"), options),
|
|
381
864
|
/**
|
|
382
865
|
* The order the input names, among `choices`: every name the sort can hold
|
|
383
|
-
* maps to a field, so a name left out is a type error
|
|
384
|
-
* silently orders by nothing. A `null` sort chooses none, and the terms after
|
|
866
|
+
* maps to a field or a call that orders, so a name left out is a type error
|
|
867
|
+
* here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
|
|
385
868
|
* it decide.
|
|
386
869
|
*
|
|
387
870
|
* ```ts
|
|
@@ -392,7 +875,8 @@ const Order = {
|
|
|
392
875
|
const fields = Object.create(null);
|
|
393
876
|
for (const [name, choice] of Object.entries(choices)) {
|
|
394
877
|
const expr = toExpr(choice, "chosen");
|
|
395
|
-
if (expr._tag !== "Field") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is
|
|
878
|
+
if (expr._tag !== "Field" && expr._tag !== "Call") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is neither a field nor a call`);
|
|
879
|
+
if (expr._tag === "Call") orderableCall(expr, expr.collation);
|
|
396
880
|
fields[name] = expr;
|
|
397
881
|
}
|
|
398
882
|
return node({
|
|
@@ -413,15 +897,18 @@ const notPlaceable = (reason) => Object.freeze({
|
|
|
413
897
|
* every order term.
|
|
414
898
|
*/
|
|
415
899
|
const ordersIntrinsically = (ast) => SchemaAST.isNumber(ast) || SchemaAST.isBoolean(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal !== "string" || SchemaAST.isUnion(ast) && ast.types.every((member) => SchemaAST.isNull(member) || ordersIntrinsically(member));
|
|
416
|
-
/** Why a term cannot be placed by a client
|
|
417
|
-
const unplaceable = (orderTerm) => Match.value(orderTerm.expr).pipe(Match.tag("
|
|
900
|
+
/** Why a term cannot be placed by a client running `operators`, if it cannot. */
|
|
901
|
+
const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
|
|
902
|
+
const missing = missingFrom(dependenciesOf(call).operators, operators);
|
|
903
|
+
return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
|
|
904
|
+
}), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
|
|
418
905
|
onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
|
|
419
906
|
onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
|
|
420
907
|
Binary: () => Option.none(),
|
|
421
908
|
AsciiFold: () => Option.none(),
|
|
422
909
|
Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
|
|
423
910
|
}))
|
|
424
|
-
})), Match.orElse(() => Option.some("it orders by something that is
|
|
911
|
+
})), Match.orElse(() => Option.some("it orders by something that is neither a field nor a call")));
|
|
425
912
|
/** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
|
|
426
913
|
const idTerms = /* @__PURE__ */ new WeakMap();
|
|
427
914
|
const idTermOf = (entity) => {
|
|
@@ -468,6 +955,22 @@ const walk = (expr, found) => {
|
|
|
468
955
|
case "Input":
|
|
469
956
|
found.inputs.add(expr.key);
|
|
470
957
|
return;
|
|
958
|
+
case "Next": {
|
|
959
|
+
found.operations.add("next");
|
|
960
|
+
const { field } = expr;
|
|
961
|
+
const byKey = found.next.get(field.owner.token) ?? /* @__PURE__ */ new Map();
|
|
962
|
+
found.next.set(field.owner.token, byKey);
|
|
963
|
+
if (!byKey.has(field.key)) {
|
|
964
|
+
const read = {
|
|
965
|
+
entity: field.owner.name,
|
|
966
|
+
key: field.key,
|
|
967
|
+
owner: field.owner
|
|
968
|
+
};
|
|
969
|
+
byKey.set(field.key, read);
|
|
970
|
+
found.nextOrder.push(read);
|
|
971
|
+
}
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
471
974
|
case "Eq":
|
|
472
975
|
found.operations.add("eq");
|
|
473
976
|
walk(expr.left, found);
|
|
@@ -511,6 +1014,15 @@ const walk = (expr, found) => {
|
|
|
511
1014
|
walk(expr.sort, found);
|
|
512
1015
|
for (const choice of Object.values(expr.choices)) walk(choice, found);
|
|
513
1016
|
return;
|
|
1017
|
+
case "Call":
|
|
1018
|
+
case "Test":
|
|
1019
|
+
found.operators.add(expr.operator);
|
|
1020
|
+
Option.match(expansionOf(expr), {
|
|
1021
|
+
onSome: (expansion) => walk(expansion, found),
|
|
1022
|
+
onNone: () => expr.args.forEach((arg) => walk(arg, found))
|
|
1023
|
+
});
|
|
1024
|
+
return;
|
|
1025
|
+
default: return absurd(expr);
|
|
514
1026
|
}
|
|
515
1027
|
};
|
|
516
1028
|
/**
|
|
@@ -524,13 +1036,18 @@ const dependenciesOf = (...nodes) => {
|
|
|
524
1036
|
fields: /* @__PURE__ */ new Map(),
|
|
525
1037
|
order: [],
|
|
526
1038
|
inputs: /* @__PURE__ */ new Set(),
|
|
527
|
-
|
|
1039
|
+
next: /* @__PURE__ */ new Map(),
|
|
1040
|
+
nextOrder: [],
|
|
1041
|
+
operations: /* @__PURE__ */ new Set(),
|
|
1042
|
+
operators: /* @__PURE__ */ new Set()
|
|
528
1043
|
};
|
|
529
1044
|
for (const term of nodes) walk(term, found);
|
|
530
1045
|
return {
|
|
531
1046
|
fields: found.order,
|
|
1047
|
+
next: found.nextOrder,
|
|
532
1048
|
inputs: [...found.inputs],
|
|
533
|
-
operations: [...found.operations]
|
|
1049
|
+
operations: [...found.operations],
|
|
1050
|
+
operators: [...found.operators]
|
|
534
1051
|
};
|
|
535
1052
|
};
|
|
536
1053
|
/** Every field an expression reads, as the nodes themselves, each node visited once. */
|
|
@@ -541,6 +1058,9 @@ const fieldsIn = function* (expr, seen) {
|
|
|
541
1058
|
case "Field":
|
|
542
1059
|
yield expr;
|
|
543
1060
|
return;
|
|
1061
|
+
case "Next":
|
|
1062
|
+
yield expr.field;
|
|
1063
|
+
return;
|
|
544
1064
|
case "Literal":
|
|
545
1065
|
case "Input": return;
|
|
546
1066
|
case "Eq":
|
|
@@ -575,6 +1095,11 @@ const fieldsIn = function* (expr, seen) {
|
|
|
575
1095
|
case "Chosen":
|
|
576
1096
|
for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
|
|
577
1097
|
return;
|
|
1098
|
+
case "Call":
|
|
1099
|
+
case "Test":
|
|
1100
|
+
for (const arg of expr.args) yield* fieldsIn(arg, seen);
|
|
1101
|
+
return;
|
|
1102
|
+
default: return absurd(expr);
|
|
578
1103
|
}
|
|
579
1104
|
};
|
|
580
1105
|
/**
|
|
@@ -599,7 +1124,8 @@ const childrenOf = (expr) => {
|
|
|
599
1124
|
switch (expr._tag) {
|
|
600
1125
|
case "Literal":
|
|
601
1126
|
case "Field":
|
|
602
|
-
case "Input":
|
|
1127
|
+
case "Input":
|
|
1128
|
+
case "Next": return [];
|
|
603
1129
|
case "Eq": return [expr.left, expr.right];
|
|
604
1130
|
case "Null": return [expr.operand];
|
|
605
1131
|
case "Contains": return [expr.value, expr.search];
|
|
@@ -608,6 +1134,11 @@ const childrenOf = (expr) => {
|
|
|
608
1134
|
case "Or": return expr.operands;
|
|
609
1135
|
case "Not": return [expr.operand];
|
|
610
1136
|
case "Compare": return [expr.left, expr.right];
|
|
1137
|
+
case "Call":
|
|
1138
|
+
case "Test": return Option.match(expansionOf(expr), {
|
|
1139
|
+
onSome: (expansion) => [expansion],
|
|
1140
|
+
onNone: () => expr.args
|
|
1141
|
+
});
|
|
611
1142
|
}
|
|
612
1143
|
};
|
|
613
1144
|
/** A node's size as a tree, each distinct node sized once. */
|
|
@@ -678,13 +1209,15 @@ const Query = {
|
|
|
678
1209
|
/**
|
|
679
1210
|
* Whether a client can order this query's rows exactly as the server does,
|
|
680
1211
|
* for one input: every term over a number or a boolean (a row may lack it), or over text with a
|
|
681
|
-
* portable collation (`binary`, `asciiFold`)
|
|
682
|
-
*
|
|
1212
|
+
* portable collation (`binary`, `asciiFold`), or a call whose primitive
|
|
1213
|
+
* operators the client's table (`operators`; none when not given) runs. A
|
|
1214
|
+
* body that names no order leaves it to the server, and is never placeable.
|
|
683
1215
|
*/
|
|
684
|
-
placement: (self, input) => {
|
|
1216
|
+
placement: (self, input, options = {}) => {
|
|
685
1217
|
if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
|
|
1218
|
+
const operators = options.operators ?? noOperators;
|
|
686
1219
|
for (const orderTerm of Query.orderFor(self, input)) {
|
|
687
|
-
const reason = unplaceable(orderTerm);
|
|
1220
|
+
const reason = unplaceable(orderTerm, operators);
|
|
688
1221
|
if (Option.isSome(reason)) return notPlaceable(reason.value);
|
|
689
1222
|
}
|
|
690
1223
|
return placeable;
|
|
@@ -701,8 +1234,10 @@ const Query = {
|
|
|
701
1234
|
}),
|
|
702
1235
|
/**
|
|
703
1236
|
* The operations this query needs that `supported` does not list, in the
|
|
704
|
-
* order the query uses them
|
|
705
|
-
* `
|
|
1237
|
+
* order the query uses them, then each primitive operator `operators` does
|
|
1238
|
+
* not implement, by name. Without `operators`, every primitive operator is
|
|
1239
|
+
* named: a list of operations implements none. Empty means an interpreter
|
|
1240
|
+
* declaring both can answer it.
|
|
706
1241
|
*
|
|
707
1242
|
* An interpreter declares what it runs and refuses the rest, rather than
|
|
708
1243
|
* ignoring an operation it does not implement — which would answer a
|
|
@@ -716,10 +1251,7 @@ const Query = {
|
|
|
716
1251
|
* if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
|
|
717
1252
|
* ```
|
|
718
1253
|
*/
|
|
719
|
-
unsupported: (self, supported) =>
|
|
720
|
-
const runs = new Set(supported);
|
|
721
|
-
return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
|
|
722
|
-
},
|
|
1254
|
+
unsupported: (self, supported, operators = noOperators) => unsupportedIn([...self.where, ...self.orderBy], supported, operators),
|
|
723
1255
|
/**
|
|
724
1256
|
* The whole query as readable text, one clause per line:
|
|
725
1257
|
*
|
|
@@ -763,6 +1295,7 @@ const showExpr = (node) => {
|
|
|
763
1295
|
case "Literal": return JSON.stringify(node.value) ?? String(node.value);
|
|
764
1296
|
case "Field": return `${node.owner.name}.${node.key}`;
|
|
765
1297
|
case "Input": return `$${node.key}`;
|
|
1298
|
+
case "Next": return `next ${node.field.owner.name}.${node.field.key}`;
|
|
766
1299
|
case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
|
|
767
1300
|
case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
|
|
768
1301
|
case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
|
|
@@ -771,8 +1304,29 @@ const showExpr = (node) => {
|
|
|
771
1304
|
case "Or": return node.operands.map(showConnected).join(" or ");
|
|
772
1305
|
case "Not": return `not (${showExpr(node.operand)})`;
|
|
773
1306
|
case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
|
|
1307
|
+
case "Call":
|
|
1308
|
+
case "Test": return `${operatorName$1(node.operator)}(${node.args.map(showOperand).join(", ")})`;
|
|
774
1309
|
}
|
|
775
1310
|
};
|
|
1311
|
+
/** A call's expansion, scalar or predicate alike. */
|
|
1312
|
+
const expansionOf = (call) => call.expansion;
|
|
1313
|
+
/**
|
|
1314
|
+
* What `nodes` need that an interpreter lacks: each kernel operation it does
|
|
1315
|
+
* not list, then each primitive operator its table does not implement, by
|
|
1316
|
+
* name. A defined operator needs nothing: what it means is walked instead.
|
|
1317
|
+
*/
|
|
1318
|
+
const unsupportedIn = (nodes, supported, operators) => {
|
|
1319
|
+
const read = dependenciesOf(...nodes);
|
|
1320
|
+
const runs = new Set(supported);
|
|
1321
|
+
return [...read.operations.filter((operation) => !runs.has(operation)), ...missingFrom(read.operators, operators)];
|
|
1322
|
+
};
|
|
1323
|
+
/**
|
|
1324
|
+
* The primitive operators among `read` that `operators` does not implement, by
|
|
1325
|
+
* name. A defined one needs nothing: what it means was walked into `read`.
|
|
1326
|
+
*/
|
|
1327
|
+
const missingFrom = (read, operators) => read.filter((operator) => Option.isNone(operator.definedAs) && !operators.has(operator)).map(operatorName$1);
|
|
1328
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1329
|
+
const operatorName$1 = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
776
1330
|
const symbols = {
|
|
777
1331
|
lt: "<",
|
|
778
1332
|
lte: "<=",
|
|
@@ -785,47 +1339,146 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
|
|
|
785
1339
|
Or: () => `(${showExpr(node)})`
|
|
786
1340
|
}), Match.orElse(() => showExpr(node)));
|
|
787
1341
|
const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
|
|
788
|
-
|
|
789
|
-
//#region src/readFilter.ts
|
|
1342
|
+
// src/text.ts
|
|
790
1343
|
/**
|
|
791
|
-
* The
|
|
792
|
-
*
|
|
793
|
-
* a list judges membership by the list's body; a change to one of these
|
|
794
|
-
* members can move a row into or out of what the server lists, which only
|
|
795
|
-
* the server can say. Declared by whoever owns the rule (`foldkit-guard`
|
|
796
|
-
* attaches it), read by whoever places (`foldkit-remote`).
|
|
1344
|
+
* The kernel's text operators: primitive, so each interpreter implements them,
|
|
1345
|
+
* and each states what it means here, where data-query §6.0.1 holds the rest.
|
|
797
1346
|
*/
|
|
798
|
-
const
|
|
799
|
-
merge: (lists) => [[...new Set(lists.flat())]],
|
|
800
|
-
summarize: (members) => members.join(", ")
|
|
801
|
-
});
|
|
802
|
-
const ReadFilter = {
|
|
803
|
-
/** Entity metadata: the rows the server lists depend on these members. */
|
|
804
|
-
of: (members) => key.of(members),
|
|
805
|
-
/** The members an Entity's metadata names, every attachment's together. */
|
|
806
|
-
members: (metadata) => key.get(metadata)[0] ?? []
|
|
807
|
-
};
|
|
808
|
-
//#endregion
|
|
809
|
-
//#region src/words.ts
|
|
810
|
-
const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
|
|
811
|
-
const Words = {
|
|
1347
|
+
const Text = {
|
|
812
1348
|
/**
|
|
813
|
-
*
|
|
814
|
-
*
|
|
815
|
-
*
|
|
816
|
-
*
|
|
817
|
-
*
|
|
1349
|
+
* Whether the first text begins with the second, under the first's collation.
|
|
1350
|
+
*
|
|
1351
|
+
* | Case | Answer |
|
|
1352
|
+
* | --- | --- |
|
|
1353
|
+
* | either is null | unknown |
|
|
1354
|
+
* | the prefix is `''` | true |
|
|
1355
|
+
* | otherwise | whether it begins so, compared under the collation |
|
|
1356
|
+
*
|
|
1357
|
+
* The collation is the text's: a field's declared one, or a call's. `binary`
|
|
1358
|
+
* compares exactly; `asciiFold` folds ASCII letters on both sides. Text with
|
|
1359
|
+
* none, or with a backend's locale, is refused where the call is written.
|
|
1360
|
+
* Prefixes are by character, so non-ASCII and astral text begin as they read.
|
|
1361
|
+
*
|
|
1362
|
+
* ```ts
|
|
1363
|
+
* Query.where(Text.startsWith(Product.fields.upc, input.search))
|
|
1364
|
+
* ```
|
|
818
1365
|
*/
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1366
|
+
startsWith: Expr.operator("text.startsWith", {
|
|
1367
|
+
input: [Schema.NullOr(Schema.String), Schema.NullOr(Schema.String)],
|
|
1368
|
+
output: Schema.Boolean,
|
|
1369
|
+
collation: "required",
|
|
1370
|
+
description: "Whether the first text begins with the second, under the first's collation."
|
|
1371
|
+
}) };
|
|
1372
|
+
// src/operators.ts
|
|
1373
|
+
/**
|
|
1374
|
+
* How the in-memory interpreter runs primitive operators: a table of
|
|
1375
|
+
* implementations, passed to `evaluate` and every judge as a value. A table is
|
|
1376
|
+
* immutable and implements each operator once; nothing registers anything
|
|
1377
|
+
* globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
|
|
1378
|
+
*/
|
|
1379
|
+
const Evidence = Data.taggedEnum();
|
|
1380
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1381
|
+
const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
1382
|
+
const fail$3 = (what) => {
|
|
1383
|
+
throw new Error(`[foldkit-entity] Operators: ${what}`);
|
|
1384
|
+
};
|
|
1385
|
+
const table = (implementations, checked, evidence) => {
|
|
1386
|
+
const byOperator = /* @__PURE__ */ new Map();
|
|
1387
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1388
|
+
for (const { operator, run } of implementations) {
|
|
1389
|
+
if (byOperator.has(operator)) fail$3(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
|
|
1390
|
+
const named = byName.get(nameOf(operator));
|
|
1391
|
+
if (named !== void 0 && named !== operator) fail$3(`two operators are named ${nameOf(operator)}; give one another id or version`);
|
|
1392
|
+
byName.set(nameOf(operator), operator);
|
|
1393
|
+
byOperator.set(operator, run);
|
|
1394
|
+
}
|
|
1395
|
+
return Object.freeze({
|
|
1396
|
+
_tag: "MemoryOperators",
|
|
1397
|
+
has: (operator) => byOperator.has(operator),
|
|
1398
|
+
get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
|
|
1399
|
+
checked,
|
|
1400
|
+
implementations: Object.freeze([...implementations]),
|
|
1401
|
+
evidence: Object.freeze([...evidence])
|
|
1402
|
+
});
|
|
1403
|
+
};
|
|
1404
|
+
/** Whether two laws, as JSON, are the same law. */
|
|
1405
|
+
const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
1406
|
+
/** An implementation, its operator's null rule checked against the function chosen for it. */
|
|
1407
|
+
const implementation = (operator, nulls, run) => {
|
|
1408
|
+
if (operator.nulls !== nulls) fail$3(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
|
|
1409
|
+
return Object.freeze({
|
|
1410
|
+
operator,
|
|
1411
|
+
run: (args, context) => run(...args, context)
|
|
1412
|
+
});
|
|
1413
|
+
};
|
|
1414
|
+
const Operators = {
|
|
1415
|
+
/**
|
|
1416
|
+
* An implementation of a strict operator: a pure function of its arguments'
|
|
1417
|
+
* stored values, never given a null (the kernel answers null, or unknown, for
|
|
1418
|
+
* one first), and told the call's collation last.
|
|
1419
|
+
*
|
|
1420
|
+
* ```ts
|
|
1421
|
+
* Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
|
|
1422
|
+
* ```
|
|
1423
|
+
*/
|
|
1424
|
+
implement: (operator, run) => implementation(operator.descriptor, "strict", run),
|
|
1425
|
+
/**
|
|
1426
|
+
* An implementation of an operator declared `nulls: 'handled'`: given nulls
|
|
1427
|
+
* as they are, it answers for them; a predicate answers `null` for unknown.
|
|
1428
|
+
*/
|
|
1429
|
+
implementHandlingNulls: (operator, run) => implementation(operator.descriptor, "handled", run),
|
|
1430
|
+
/** A table of implementations. One operator implemented twice, or two under one name, is refused. */
|
|
1431
|
+
memory: (...implementations) => table(implementations, false, []),
|
|
1432
|
+
/** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
|
|
1433
|
+
merge: (left, right) => {
|
|
1434
|
+
const both = right.implementations.filter(({ operator }) => left.has(operator));
|
|
1435
|
+
if (both.length > 0) fail$3(`both tables implement ${both.map(({ operator }) => nameOf(operator)).join(", ")}; replace with Operators.override`);
|
|
1436
|
+
return table([...left.implementations, ...right.implementations], left.checked || right.checked, [...left.evidence, ...right.evidence]);
|
|
1437
|
+
},
|
|
1438
|
+
/**
|
|
1439
|
+
* The table with these implementations in place of its own for the same
|
|
1440
|
+
* operators. Evidence of a replaced implementation goes with it: it was
|
|
1441
|
+
* that implementation's.
|
|
1442
|
+
*/
|
|
1443
|
+
override: (base, ...implementations) => {
|
|
1444
|
+
const replaced = new Set(implementations.map(({ operator }) => operator));
|
|
1445
|
+
const names = new Set([...replaced].map(nameOf));
|
|
1446
|
+
return table([...base.implementations.filter(({ operator }) => !replaced.has(operator)), ...implementations], base.checked, base.evidence.filter(({ operator }) => !names.has(operator)));
|
|
1447
|
+
},
|
|
1448
|
+
/**
|
|
1449
|
+
* The table with what is known of its implementations' laws recorded: each
|
|
1450
|
+
* record of an operator it implements and a law that operator declares.
|
|
1451
|
+
* `Conformance.laws` gives `Tested` records; `Evidence.Proven` says a proof
|
|
1452
|
+
* elsewhere covers one.
|
|
1453
|
+
*/
|
|
1454
|
+
withEvidence: (base, evidence) => {
|
|
1455
|
+
const declared = new Map(base.implementations.map(({ operator }) => [nameOf(operator), operator.laws.map(Law.describe)]));
|
|
1456
|
+
for (const record of evidence) if (!(declared.get(record.operator) ?? fail$3(`evidence names ${record.operator}, which this table does not implement`)).some((law) => sameLaw(law, record.law))) fail$3(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`);
|
|
1457
|
+
return table(base.implementations, base.checked, [...base.evidence, ...evidence]);
|
|
1458
|
+
},
|
|
1459
|
+
/**
|
|
1460
|
+
* Each operator the table implements, by name, with the laws it declares and
|
|
1461
|
+
* the evidence the table records of them: what a server can publish of how
|
|
1462
|
+
* it runs a body. JSON as it is.
|
|
1463
|
+
*/
|
|
1464
|
+
describeTable: (base) => base.implementations.map(({ operator }) => ({
|
|
1465
|
+
operator: nameOf(operator),
|
|
1466
|
+
laws: operator.laws.map(Law.describe),
|
|
1467
|
+
evidence: base.evidence.filter((record) => record.operator === nameOf(operator))
|
|
1468
|
+
})),
|
|
1469
|
+
/**
|
|
1470
|
+
* The table, checking every answer against its operator's output schema, so
|
|
1471
|
+
* an implementation that answers the wrong kind fails where it answered. For
|
|
1472
|
+
* tests: it costs a decode per call.
|
|
1473
|
+
*/
|
|
1474
|
+
checked: (base) => table(base.implementations, true, base.evidence),
|
|
1475
|
+
/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
|
|
1476
|
+
kernel: table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
|
|
1477
|
+
const [text, prefix, { collation }] = given;
|
|
1478
|
+
return Option.exists(collation, (each) => each._tag === "AsciiFold") ? Collation.foldAscii(text).startsWith(Collation.foldAscii(prefix)) : text.startsWith(prefix);
|
|
1479
|
+
})], false, [])
|
|
1480
|
+
};
|
|
1481
|
+
// src/evaluate.ts
|
|
829
1482
|
/**
|
|
830
1483
|
* The reference interpreter: a query body run over rows already in memory.
|
|
831
1484
|
*
|
|
@@ -856,20 +1509,80 @@ var QueryEvaluateError = class extends Error {
|
|
|
856
1509
|
this.name = "QueryEvaluateError";
|
|
857
1510
|
}
|
|
858
1511
|
};
|
|
859
|
-
|
|
1512
|
+
/**
|
|
1513
|
+
* A call of a primitive operator the table does not implement. Its own class,
|
|
1514
|
+
* because a form judging an invariant reads it as a judgement it cannot make
|
|
1515
|
+
* (`Undecided`), not as a failure.
|
|
1516
|
+
*/
|
|
1517
|
+
var OperatorMissingError = class extends QueryEvaluateError {
|
|
1518
|
+
operator;
|
|
1519
|
+
/** The operator by its id, and its version past the first. */
|
|
1520
|
+
named;
|
|
1521
|
+
constructor(operator) {
|
|
1522
|
+
super(`this interpreter does not run the operator "${operatorName(operator)}"`);
|
|
1523
|
+
this.name = "OperatorMissingError";
|
|
1524
|
+
this.operator = operator;
|
|
1525
|
+
this.named = operatorName(operator);
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
1529
|
+
const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
1530
|
+
const valueOf = (node, scope) => {
|
|
860
1531
|
switch (node._tag) {
|
|
861
|
-
case "Field": return row[node.key];
|
|
1532
|
+
case "Field": return scope.row[node.key];
|
|
1533
|
+
case "Next": return scope.next[node.field.key];
|
|
862
1534
|
case "Literal": return node.value;
|
|
863
|
-
case "Input": return input[node.key];
|
|
1535
|
+
case "Input": return scope.input[node.key];
|
|
1536
|
+
case "Call": return called(node, scope);
|
|
1537
|
+
default: return absurd(node);
|
|
864
1538
|
}
|
|
865
1539
|
};
|
|
866
|
-
const isNull = (value) => value === null || value === void 0;
|
|
867
1540
|
/**
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
1541
|
+
* What a call comes to, as a value (a predicate's truth as SQL's, unknown as
|
|
1542
|
+
* null). The table's implementation when it has one; else, for a defined
|
|
1543
|
+
* operator, what it means; else it is refused by name.
|
|
1544
|
+
*/
|
|
1545
|
+
const called = (call, scope) => {
|
|
1546
|
+
const expansion = call.expansion;
|
|
1547
|
+
return Option.match(scope.operators.get(call.operator), {
|
|
1548
|
+
onSome: (run) => ran(call, run, scope),
|
|
1549
|
+
onNone: () => Option.match(expansion, {
|
|
1550
|
+
onSome: (body) => sideOf(body, scope),
|
|
1551
|
+
onNone: () => {
|
|
1552
|
+
throw new OperatorMissingError(call.operator);
|
|
1553
|
+
}
|
|
1554
|
+
})
|
|
1555
|
+
});
|
|
1556
|
+
};
|
|
1557
|
+
/**
|
|
1558
|
+
* A primitive operator run: strict about null and NUL before it is asked, a
|
|
1559
|
+
* throw it makes named as its own, and, in a checked table, its answer held to
|
|
1560
|
+
* its output schema.
|
|
871
1561
|
*/
|
|
872
|
-
const
|
|
1562
|
+
const ran = (call, run, scope) => {
|
|
1563
|
+
const { operator } = call;
|
|
1564
|
+
const values = call.args.map((arg) => sideOf(arg, scope));
|
|
1565
|
+
if (values.some(holdsNul)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" was given text holding a NUL character, which SQL text cannot hold portably`);
|
|
1566
|
+
if (operator.nulls === "strict" && values.some(isNull)) return null;
|
|
1567
|
+
let answer;
|
|
1568
|
+
try {
|
|
1569
|
+
answer = run(values, { collation: call.collation });
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
if (error instanceof QueryEvaluateError) throw error;
|
|
1572
|
+
throw new QueryEvaluateError(`the operator "${operatorName(operator)}" failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1573
|
+
}
|
|
1574
|
+
const unknownTruth = call._tag === "Test" && answer === null;
|
|
1575
|
+
if (scope.operators.checked && !unknownTruth && !Schema.is(Schema.toEncoded(operator.output))(answer)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" answered ${JSON.stringify(answer)}, which its output schema does not admit`);
|
|
1576
|
+
return answer;
|
|
1577
|
+
};
|
|
1578
|
+
/** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */
|
|
1579
|
+
const truthOf = (call, answer) => {
|
|
1580
|
+
if (answer === null || answer === void 0) return "unknown";
|
|
1581
|
+
if (typeof answer !== "boolean") throw new QueryEvaluateError(`the operator "${operatorName(call.operator)}" answered ${JSON.stringify(answer)}, which is not a truth`);
|
|
1582
|
+
return answer;
|
|
1583
|
+
};
|
|
1584
|
+
const isNull = (value) => value === null || value === void 0;
|
|
1585
|
+
const { foldAscii } = Collation;
|
|
873
1586
|
const NUL = String.fromCharCode(0);
|
|
874
1587
|
/**
|
|
875
1588
|
* Whether `value` is text holding a NUL, which Postgres text cannot hold and
|
|
@@ -877,57 +1590,71 @@ const NUL = String.fromCharCode(0);
|
|
|
877
1590
|
*/
|
|
878
1591
|
const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
|
|
879
1592
|
/** A predicate used as a value is its own truth; anything else is its value. */
|
|
880
|
-
const sideOf = (node,
|
|
1593
|
+
const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
|
|
1594
|
+
/**
|
|
1595
|
+
* What an operand comes to over no row: a call of literals and inputs, run by
|
|
1596
|
+
* `operators` (the kernel's when not given), a predicate as its truth with
|
|
1597
|
+
* unknown as null. How a conformance check asks an implementation one
|
|
1598
|
+
* question; refuses what `evaluate` refuses (an operator the table lacks,
|
|
1599
|
+
* text holding NUL).
|
|
1600
|
+
*/
|
|
1601
|
+
const valueOfOperand = (node, options = {}) => sideOf(node, {
|
|
1602
|
+
row: {},
|
|
1603
|
+
input: options.input ?? {},
|
|
1604
|
+
next: {},
|
|
1605
|
+
operators: options.operators ?? Operators.kernel
|
|
1606
|
+
});
|
|
881
1607
|
/**
|
|
882
1608
|
* A predicate compared as a value. SQL's unknown is null there too, so an
|
|
883
1609
|
* unknown compared to anything stays unknown rather than becoming false.
|
|
884
1610
|
*/
|
|
885
1611
|
const truthValue = (truth) => truth === "unknown" ? null : truth;
|
|
886
|
-
const holds = (node,
|
|
1612
|
+
const holds = (node, scope) => {
|
|
887
1613
|
switch (node._tag) {
|
|
1614
|
+
case "Test": return truthOf(node, called(node, scope));
|
|
888
1615
|
case "Eq": {
|
|
889
|
-
const left = sideOf(node.left,
|
|
890
|
-
const right = sideOf(node.right,
|
|
1616
|
+
const left = sideOf(node.left, scope);
|
|
1617
|
+
const right = sideOf(node.right, scope);
|
|
891
1618
|
if (isNull(left) || isNull(right)) return "unknown";
|
|
892
1619
|
if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("an equality was given text holding a NUL character, which SQL text cannot hold portably");
|
|
893
1620
|
return left === right;
|
|
894
1621
|
}
|
|
895
|
-
case "Null": return isNull(valueOf(node.operand,
|
|
1622
|
+
case "Null": return isNull(valueOf(node.operand, scope)) !== node.present;
|
|
896
1623
|
case "Contains": {
|
|
897
|
-
const value = valueOf(node.value,
|
|
898
|
-
const search = sideOf(node.search,
|
|
1624
|
+
const value = valueOf(node.value, scope);
|
|
1625
|
+
const search = sideOf(node.search, scope);
|
|
899
1626
|
if (isNull(value) || isNull(search)) return "unknown";
|
|
900
1627
|
if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
|
|
901
1628
|
if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
|
|
902
1629
|
return foldAscii(value).includes(foldAscii(search));
|
|
903
1630
|
}
|
|
904
1631
|
case "In": {
|
|
905
|
-
const among = valueOf(node.among,
|
|
1632
|
+
const among = valueOf(node.among, scope);
|
|
906
1633
|
if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
|
|
907
1634
|
if (among.length === 0) return false;
|
|
908
|
-
const value = valueOf(node.value,
|
|
1635
|
+
const value = valueOf(node.value, scope);
|
|
909
1636
|
if (holdsNul(value) || among.some(holdsNul)) throw new QueryEvaluateError("a membership test was given text holding a NUL character, which SQL text cannot hold portably");
|
|
910
1637
|
if (isNull(value)) return "unknown";
|
|
911
1638
|
if (among.some((each) => each === value)) return true;
|
|
912
1639
|
return among.some(isNull) ? "unknown" : false;
|
|
913
1640
|
}
|
|
914
1641
|
case "And": {
|
|
915
|
-
const truths = node.operands.map((operand) => holds(operand,
|
|
1642
|
+
const truths = node.operands.map((operand) => holds(operand, scope));
|
|
916
1643
|
if (truths.includes(false)) return false;
|
|
917
1644
|
return truths.includes("unknown") ? "unknown" : true;
|
|
918
1645
|
}
|
|
919
1646
|
case "Or": {
|
|
920
|
-
const truths = node.operands.map((operand) => holds(operand,
|
|
1647
|
+
const truths = node.operands.map((operand) => holds(operand, scope));
|
|
921
1648
|
if (truths.includes(true)) return true;
|
|
922
1649
|
return truths.includes("unknown") ? "unknown" : false;
|
|
923
1650
|
}
|
|
924
1651
|
case "Not": {
|
|
925
|
-
const truth = holds(node.operand,
|
|
1652
|
+
const truth = holds(node.operand, scope);
|
|
926
1653
|
return truth === "unknown" ? "unknown" : !truth;
|
|
927
1654
|
}
|
|
928
1655
|
case "Compare": {
|
|
929
|
-
const left = valueOf(node.left,
|
|
930
|
-
const right = valueOf(node.right,
|
|
1656
|
+
const left = valueOf(node.left, scope);
|
|
1657
|
+
const right = valueOf(node.right, scope);
|
|
931
1658
|
if (isNull(left) || isNull(right)) return "unknown";
|
|
932
1659
|
if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
|
|
933
1660
|
const kind = typeof left;
|
|
@@ -945,16 +1672,34 @@ const readsAField = /* @__PURE__ */ new WeakMap();
|
|
|
945
1672
|
* before it builds anything: `isNull($status)` is known before any row is.
|
|
946
1673
|
* Refuses what `evaluate` refuses (text holding a NUL).
|
|
947
1674
|
*/
|
|
948
|
-
const decided = (node, input) => {
|
|
1675
|
+
const decided = (node, input, operators = Operators.kernel) => {
|
|
949
1676
|
let reads = readsAField.get(node);
|
|
950
1677
|
if (reads === void 0) {
|
|
951
|
-
|
|
1678
|
+
const read = dependenciesOf(node);
|
|
1679
|
+
reads = read.fields.length + read.next.length > 0;
|
|
952
1680
|
readsAField.set(node, reads);
|
|
953
1681
|
}
|
|
954
|
-
return reads ? Option.none() : Option.some(holds(node, {
|
|
1682
|
+
return reads ? Option.none() : Option.some(holds(node, {
|
|
1683
|
+
row: {},
|
|
1684
|
+
input,
|
|
1685
|
+
next: {},
|
|
1686
|
+
operators
|
|
1687
|
+
}));
|
|
955
1688
|
};
|
|
1689
|
+
/** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
|
|
1690
|
+
const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => holds(node, {
|
|
1691
|
+
row,
|
|
1692
|
+
input,
|
|
1693
|
+
next,
|
|
1694
|
+
operators
|
|
1695
|
+
});
|
|
956
1696
|
/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
|
|
957
|
-
const matches = (body, row, input) => body.where.every((node) => holds(node,
|
|
1697
|
+
const matches = (body, row, input, operators) => body.where.every((node) => holds(node, {
|
|
1698
|
+
row,
|
|
1699
|
+
input,
|
|
1700
|
+
next: {},
|
|
1701
|
+
operators
|
|
1702
|
+
}) === true);
|
|
958
1703
|
/** The kinds of value this interpreter orders by; every key of one term must share one. */
|
|
959
1704
|
const comparable = /* @__PURE__ */ new Set([
|
|
960
1705
|
"string",
|
|
@@ -985,58 +1730,72 @@ const compare = (left, right, collation) => {
|
|
|
985
1730
|
if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
|
|
986
1731
|
return left - right;
|
|
987
1732
|
};
|
|
1733
|
+
/** Each term's key for one row: a field's value, or what a call comes to over the row. */
|
|
1734
|
+
const keysOf = (row, terms, scope) => terms.map((term) => valueOf(term.expr, {
|
|
1735
|
+
row,
|
|
1736
|
+
input: scope.input,
|
|
1737
|
+
next: {},
|
|
1738
|
+
operators: scope.operators
|
|
1739
|
+
}));
|
|
988
1740
|
/**
|
|
989
1741
|
* Refuses an ordering this interpreter will not answer for, before sorting, so
|
|
990
1742
|
* the refusal names the first offending row in row order rather than whichever
|
|
991
1743
|
* pair the engine's sort happened to compare first. Every term is checked over
|
|
992
|
-
* every row: a key whose kind differs from the first present one's. A
|
|
993
|
-
* is not refused; the term says where it goes.
|
|
1744
|
+
* every row's keys: a key whose kind differs from the first present one's. A
|
|
1745
|
+
* null key is not refused; the term says where it goes.
|
|
994
1746
|
*/
|
|
995
|
-
const checkOrder = (
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
first ??= kind;
|
|
1006
|
-
if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
|
|
1007
|
-
}
|
|
1747
|
+
const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
|
|
1748
|
+
if (term.expr._tag !== "Field" && term.expr._tag !== "Call") throw new QueryEvaluateError(`query "${query}" orders by something that is neither a field nor a call`);
|
|
1749
|
+
if (Option.exists(term.collation, (declared) => declared._tag === "Locale")) throw new QueryEvaluateError(`query "${query}" orders ${Expr.show(term.expr)} by a backend's locale collation, which only that backend has`);
|
|
1750
|
+
let first;
|
|
1751
|
+
for (const row of keys) {
|
|
1752
|
+
const value = row[index];
|
|
1753
|
+
if (isNull(value)) continue;
|
|
1754
|
+
const kind = typeof value;
|
|
1755
|
+
first ??= kind;
|
|
1756
|
+
if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
|
|
1008
1757
|
}
|
|
1009
|
-
};
|
|
1010
|
-
/** Two rows by checked terms: negative when `left` sorts first. */
|
|
1758
|
+
});
|
|
1759
|
+
/** Two rows' keys by checked terms: negative when `left` sorts first. */
|
|
1011
1760
|
const byTerms = (terms, left, right) => {
|
|
1012
|
-
for (const term of terms) {
|
|
1013
|
-
const
|
|
1014
|
-
const
|
|
1015
|
-
const absentRight = isNull(right[key]);
|
|
1761
|
+
for (const [index, term] of terms.entries()) {
|
|
1762
|
+
const absentLeft = isNull(left[index]);
|
|
1763
|
+
const absentRight = isNull(right[index]);
|
|
1016
1764
|
if (absentLeft || absentRight) {
|
|
1017
1765
|
if (absentLeft && absentRight) continue;
|
|
1018
1766
|
return absentLeft === (term.nulls === "first") ? -1 : 1;
|
|
1019
1767
|
}
|
|
1020
|
-
const sign = compare(left[
|
|
1768
|
+
const sign = compare(left[index], right[index], term.collation);
|
|
1021
1769
|
if (sign !== 0) return term.direction === "asc" ? sign : -sign;
|
|
1022
1770
|
}
|
|
1023
1771
|
return 0;
|
|
1024
1772
|
};
|
|
1025
|
-
const ordered = (rows, terms, query) => {
|
|
1773
|
+
const ordered = (rows, terms, query, scope) => {
|
|
1026
1774
|
if (terms.length === 0 || rows.length < 2) return [...rows];
|
|
1027
|
-
|
|
1028
|
-
|
|
1775
|
+
const keyed = rows.map((row) => ({
|
|
1776
|
+
row,
|
|
1777
|
+
keys: keysOf(row, terms, scope)
|
|
1778
|
+
}));
|
|
1779
|
+
checkOrder(keyed.map(({ keys }) => keys), terms, query);
|
|
1780
|
+
return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row);
|
|
1029
1781
|
};
|
|
1030
1782
|
/**
|
|
1031
1783
|
* Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
|
|
1032
|
-
* as `evaluate` sorts: negative when it comes first.
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1784
|
+
* as `evaluate` sorts: negative when it comes first. A call among them runs
|
|
1785
|
+
* over each row with `input` and `operators` (the kernel's when not given).
|
|
1786
|
+
* Refuses what `evaluate` refuses, for these two rows: a term over neither a
|
|
1787
|
+
* field nor a call, a locale collation, keys of different kinds, or an
|
|
1788
|
+
* operator the table lacks. For a client placing one row among others it
|
|
1035
1789
|
* holds.
|
|
1036
1790
|
*/
|
|
1037
|
-
const compareRows = (terms, left, right, query) => {
|
|
1038
|
-
|
|
1039
|
-
|
|
1791
|
+
const compareRows = (terms, left, right, query, options = {}) => {
|
|
1792
|
+
const scope = {
|
|
1793
|
+
input: options.input ?? {},
|
|
1794
|
+
operators: options.operators ?? Operators.kernel
|
|
1795
|
+
};
|
|
1796
|
+
const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
|
|
1797
|
+
checkOrder(keys, terms, query);
|
|
1798
|
+
return byTerms(terms, keys[0], keys[1]);
|
|
1040
1799
|
};
|
|
1041
1800
|
/**
|
|
1042
1801
|
* The operations this interpreter runs. It is the reference, so this is the
|
|
@@ -1060,8 +1819,8 @@ const supported = [
|
|
|
1060
1819
|
* than skipping it and answering a different question. Called by `evaluate`;
|
|
1061
1820
|
* call it directly to check a body once instead of on every run.
|
|
1062
1821
|
*/
|
|
1063
|
-
const assertSupported = (body) => {
|
|
1064
|
-
const missing = Query.unsupported(body, supported);
|
|
1822
|
+
const assertSupported = (body, operators = Operators.kernel) => {
|
|
1823
|
+
const missing = Query.unsupported(body, supported, operators);
|
|
1065
1824
|
if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
|
|
1066
1825
|
};
|
|
1067
1826
|
/**
|
|
@@ -1072,12 +1831,213 @@ const assertSupported = (body) => {
|
|
|
1072
1831
|
* placeholders were built with — the same record the query would be called
|
|
1073
1832
|
* with anywhere else.
|
|
1074
1833
|
*/
|
|
1075
|
-
const evaluate = (body, input, rows) => {
|
|
1076
|
-
|
|
1077
|
-
|
|
1834
|
+
const evaluate = (body, input, rows, options = {}) => {
|
|
1835
|
+
const operators = options.operators ?? Operators.kernel;
|
|
1836
|
+
assertSupported(body, operators);
|
|
1837
|
+
return ordered(rows.filter((row) => matches(body, row, input, operators)), Query.orderFor(body, input), body.entity.name, {
|
|
1838
|
+
input,
|
|
1839
|
+
operators
|
|
1840
|
+
});
|
|
1841
|
+
};
|
|
1842
|
+
// src/invariant.ts
|
|
1843
|
+
/**
|
|
1844
|
+
* Invariants: what every stored row of an Entity must hold, and what every
|
|
1845
|
+
* change of one must, declared once on the Entity through its metadata and read
|
|
1846
|
+
* from there by each interpreter: the reference judge here, a Schema check, a
|
|
1847
|
+
* form, a server's writer.
|
|
1848
|
+
*
|
|
1849
|
+
* One is built over the row before a write (`before`, each field as `Expr.field`) and
|
|
1850
|
+
* the row after it (`after`, each field as `Expr.next`). What it reads decides
|
|
1851
|
+
* when it is judged:
|
|
1852
|
+
*
|
|
1853
|
+
* ```text
|
|
1854
|
+
* reads `after` only -> a state invariant: every create and update, a CHECK constraint
|
|
1855
|
+
* reads `before` too -> a transition invariant: every update, which has a row before
|
|
1856
|
+
* ```
|
|
1857
|
+
*
|
|
1858
|
+
* It reads no input and no principal. Who may write is a guard's; whether a
|
|
1859
|
+
* write applies now is its `when`'s.
|
|
1860
|
+
*/
|
|
1861
|
+
const Invariants = Metadata.key("foldkit-entity/invariants", {
|
|
1862
|
+
merge: (values) => [...new Set(values)],
|
|
1863
|
+
summarize: (invariant) => invariant.id
|
|
1864
|
+
});
|
|
1865
|
+
/** Whether an invariant reads the row before, and so is judged only where there is one. */
|
|
1866
|
+
const readsBefore = (held) => held.before.length > 0;
|
|
1867
|
+
const fail$2 = (entity, message) => {
|
|
1868
|
+
throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
|
|
1869
|
+
};
|
|
1870
|
+
const invariant = (id, build, options) => Object.assign((entity) => {
|
|
1871
|
+
if (id.length === 0) fail$2(entity, "an invariant needs an id");
|
|
1872
|
+
if (invariantsOf(entity).some((held) => held.id === id)) fail$2(entity, `"${id}" is declared twice`);
|
|
1873
|
+
const fields = entity.fields;
|
|
1874
|
+
const after = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]));
|
|
1875
|
+
const predicate = build({
|
|
1876
|
+
before: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)])),
|
|
1877
|
+
after
|
|
1878
|
+
});
|
|
1879
|
+
const body = Query.from(entity).pipe(Query.where(predicate));
|
|
1880
|
+
const dependencies = Query.dependencies(body);
|
|
1881
|
+
if (dependencies.inputs.length > 0) fail$2(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
|
|
1882
|
+
const beforeReads = dependencies.predicate.map((field) => field.key);
|
|
1883
|
+
const afterReads = dependencies.next.map((field) => field.key);
|
|
1884
|
+
if (afterReads.length === 0) fail$2(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
|
|
1885
|
+
const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
|
|
1886
|
+
for (const key of path) if (!Object.hasOwn(fields, key)) fail$2(entity, `"${id}"'s path names "${key}", not a field`);
|
|
1887
|
+
return entity.pipe(Entity.annotate(Invariants.of(Object.freeze({
|
|
1888
|
+
id,
|
|
1889
|
+
predicate,
|
|
1890
|
+
message: options.message,
|
|
1891
|
+
path: Object.freeze([...path]),
|
|
1892
|
+
before: Object.freeze(beforeReads),
|
|
1893
|
+
after: Object.freeze(afterReads)
|
|
1894
|
+
}))));
|
|
1895
|
+
}, { id });
|
|
1896
|
+
const invariantsOf = (entity) => Invariants.get(entity.metadata);
|
|
1897
|
+
/** `judge` with the invariants given, as a binding that keeps them holds them. */
|
|
1898
|
+
const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
|
|
1899
|
+
const missing = /* @__PURE__ */ new Set();
|
|
1900
|
+
const unrun = /* @__PURE__ */ new Set();
|
|
1901
|
+
const failures = [];
|
|
1902
|
+
const { after, before } = change;
|
|
1903
|
+
for (const held of invariants) {
|
|
1904
|
+
if (readsBefore(held) && before === void 0) continue;
|
|
1905
|
+
const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
|
|
1906
|
+
if (absent.length > 0) absent.forEach((key) => missing.add(key));
|
|
1907
|
+
else try {
|
|
1908
|
+
if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
|
|
1909
|
+
} catch (error) {
|
|
1910
|
+
if (!(error instanceof OperatorMissingError)) throw error;
|
|
1911
|
+
unrun.add(error.named);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
if (failures.length > 0) return {
|
|
1915
|
+
_tag: "Invalid",
|
|
1916
|
+
failures
|
|
1917
|
+
};
|
|
1918
|
+
if (missing.size > 0 || unrun.size > 0) return {
|
|
1919
|
+
_tag: "Undecided",
|
|
1920
|
+
fields: [...missing],
|
|
1921
|
+
operators: [...unrun]
|
|
1922
|
+
};
|
|
1923
|
+
return { _tag: "Valid" };
|
|
1924
|
+
};
|
|
1925
|
+
/**
|
|
1926
|
+
* A row, or a change, under every invariant (each row as the store holds it,
|
|
1927
|
+
* encoded): valid only when each is true. SQL's unknown, from a null, fails
|
|
1928
|
+
* one, as a `WHERE` drops the row; a field a row does not have leaves it
|
|
1929
|
+
* undecided, never valid. Without `before` (a create), transition invariants
|
|
1930
|
+
* are not judged.
|
|
1931
|
+
*/
|
|
1932
|
+
const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
|
|
1933
|
+
/**
|
|
1934
|
+
* The row an input's value describes, judged under its Entity's state
|
|
1935
|
+
* invariants: each key mapped to a field, encoded as the store holds it. An
|
|
1936
|
+
* invariant over a field the input does not set (an `Option` holding nothing, a
|
|
1937
|
+
* key left out) is undecided, so a partial input is never called valid on its
|
|
1938
|
+
* account. It has no row before, so it judges no transition.
|
|
1939
|
+
*/
|
|
1940
|
+
const judgeInput = (input, value, operators = Operators.kernel) => {
|
|
1941
|
+
const invariants = invariantsOf(input.entity);
|
|
1942
|
+
if (invariants.length === 0) return { _tag: "Valid" };
|
|
1943
|
+
const members = input.members;
|
|
1944
|
+
const row = {};
|
|
1945
|
+
for (const [key, member] of Object.entries(members)) {
|
|
1946
|
+
if (member._tag !== "Field" || !Object.hasOwn(value, key)) continue;
|
|
1947
|
+
const encode = Schema.encodeUnknownOption(member.schema);
|
|
1948
|
+
const given = value[key];
|
|
1949
|
+
const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
|
|
1950
|
+
const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
|
|
1951
|
+
Option.map(Option.flatMap(held, () => stored), (encoded) => {
|
|
1952
|
+
row[member.key] = encoded;
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
return judgeAgainst(invariants, { after: row }, operators);
|
|
1078
1956
|
};
|
|
1079
|
-
|
|
1080
|
-
|
|
1957
|
+
/**
|
|
1958
|
+
* The Entity's state invariants as an Effect Schema check over its row type:
|
|
1959
|
+
* each failure at its path, with its message. The value is encoded first,
|
|
1960
|
+
* field by field, so it is judged as the store would hold it.
|
|
1961
|
+
*/
|
|
1962
|
+
const check = (entity, options = {}) => Schema.makeFilter((value) => {
|
|
1963
|
+
const fields = entity.fields;
|
|
1964
|
+
const decoded = value;
|
|
1965
|
+
const row = {};
|
|
1966
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
1967
|
+
if (!Object.hasOwn(decoded, key)) continue;
|
|
1968
|
+
row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
|
|
1969
|
+
}
|
|
1970
|
+
const judged = judge(entity, { after: row }, options.operators);
|
|
1971
|
+
if (judged._tag !== "Invalid") return void 0;
|
|
1972
|
+
return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
|
|
1973
|
+
path: [key],
|
|
1974
|
+
issue: failure.message
|
|
1975
|
+
})));
|
|
1976
|
+
});
|
|
1977
|
+
// src/shape.ts
|
|
1978
|
+
const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
|
|
1979
|
+
const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
|
|
1980
|
+
/** Whether any of these checks is `Schema.isInt`, alone or inside a group (`isInt32`). */
|
|
1981
|
+
const checksInteger = (checks) => checks.some((check) => Match.value(check).pipe(Match.tagsExhaustive({
|
|
1982
|
+
Filter: (filter) => filter.annotations?.representation?.id === "effect/schema/isInt",
|
|
1983
|
+
FilterGroup: (group) => checksInteger(group.checks)
|
|
1984
|
+
})));
|
|
1985
|
+
/** What a schema's AST holds, read through Effect's own guards. */
|
|
1986
|
+
const SchemaShape = {
|
|
1987
|
+
/** True for the `null` and `undefined` members that make a schema optional. */
|
|
1988
|
+
isNullish,
|
|
1989
|
+
/**
|
|
1990
|
+
* The members of a schema with `null` and `undefined` set aside, so optional
|
|
1991
|
+
* text is still text; a schema that is not a union is its one member.
|
|
1992
|
+
*/
|
|
1993
|
+
present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
|
|
1994
|
+
/** True when every value the schema admits is a string. */
|
|
1995
|
+
isText,
|
|
1996
|
+
/**
|
|
1997
|
+
* True when the AST is checked to hold integers (`Schema.isInt`, alone or in
|
|
1998
|
+
* a group such as `isInt32`). Read it from a schema's encoded side to ask
|
|
1999
|
+
* what the store holds.
|
|
2000
|
+
*/
|
|
2001
|
+
holdsIntegers: (ast) => checksInteger(ast.checks ?? [])
|
|
2002
|
+
};
|
|
2003
|
+
// src/readFilter.ts
|
|
2004
|
+
/**
|
|
2005
|
+
* The members a server filters an Entity's rows by under a rule the client
|
|
2006
|
+
* does not run, such as an authorization rule. A client that places rows in
|
|
2007
|
+
* a list judges membership by the list's body; a change to one of these
|
|
2008
|
+
* members can move a row into or out of what the server lists, which only
|
|
2009
|
+
* the server can say. Declared by whoever owns the rule (`foldkit-guard`
|
|
2010
|
+
* attaches it), read by whoever places (`foldkit-remote`).
|
|
2011
|
+
*/
|
|
2012
|
+
const key = Metadata.key("foldkit-entity/read-filter", {
|
|
2013
|
+
merge: (lists) => [[...new Set(lists.flat())]],
|
|
2014
|
+
summarize: (members) => members.join(", ")
|
|
2015
|
+
});
|
|
2016
|
+
const ReadFilter = {
|
|
2017
|
+
/** Entity metadata: the rows the server lists depend on these members. */
|
|
2018
|
+
of: (members) => key.of(members),
|
|
2019
|
+
/** The members an Entity's metadata names, every attachment's together. */
|
|
2020
|
+
members: (metadata) => key.get(metadata)[0] ?? []
|
|
2021
|
+
};
|
|
2022
|
+
// src/words.ts
|
|
2023
|
+
const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
|
|
2024
|
+
const Words = {
|
|
2025
|
+
/**
|
|
2026
|
+
* A schema's words, as a label and its help text. Under Effect 4 a checked
|
|
2027
|
+
* schema resolves to its last check's annotations, which say what the check
|
|
2028
|
+
* expects and carry no `title`, so a title given before the check is read from
|
|
2029
|
+
* the schema's own annotations. Read words through this, never through
|
|
2030
|
+
* `Schema.resolveAnnotations` directly.
|
|
2031
|
+
*/
|
|
2032
|
+
of: (schema) => {
|
|
2033
|
+
const resolved = Schema.resolveAnnotations(schema) ?? {};
|
|
2034
|
+
const own = schema.ast.annotations ?? {};
|
|
2035
|
+
return {
|
|
2036
|
+
title: Option.orElse(text(resolved.title), () => text(own["title"])),
|
|
2037
|
+
description: Option.orElse(text(resolved.description), () => text(own["description"]))
|
|
2038
|
+
};
|
|
2039
|
+
} };
|
|
2040
|
+
// src/write.ts
|
|
1081
2041
|
/**
|
|
1082
2042
|
* A write as a value: what an operation changes, declared over the input it
|
|
1083
2043
|
* takes, so the changes can be known before it runs and its interpreters can
|
|
@@ -1093,6 +2053,13 @@ const evaluate = (body, input, rows) => {
|
|
|
1093
2053
|
* It is authority someone declared, never something derived from an Entity: an
|
|
1094
2054
|
* Entity having a field does not mean anyone may set it.
|
|
1095
2055
|
*/
|
|
2056
|
+
const update = (input, options) => settingSomething(declared("Update", input, options));
|
|
2057
|
+
const remove = (input, options) => {
|
|
2058
|
+
const write = declared("Delete", input, options);
|
|
2059
|
+
const named = [...write.sets, ...write.links][0];
|
|
2060
|
+
if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
|
|
2061
|
+
return write;
|
|
2062
|
+
};
|
|
1096
2063
|
const fail$1 = (input, message) => {
|
|
1097
2064
|
throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
|
|
1098
2065
|
};
|
|
@@ -1151,6 +2118,15 @@ const declared = (kind, input, options) => {
|
|
|
1151
2118
|
case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
|
|
1152
2119
|
}
|
|
1153
2120
|
}
|
|
2121
|
+
const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
|
|
2122
|
+
const placeholders = Object.create(null);
|
|
2123
|
+
for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
|
|
2124
|
+
return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
|
|
2125
|
+
});
|
|
2126
|
+
const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
|
|
2127
|
+
expect,
|
|
2128
|
+
sets
|
|
2129
|
+
})]);
|
|
1154
2130
|
return Object.freeze({
|
|
1155
2131
|
_tag: kind,
|
|
1156
2132
|
input,
|
|
@@ -1159,12 +2135,44 @@ const declared = (kind, input, options) => {
|
|
|
1159
2135
|
field: id
|
|
1160
2136
|
}),
|
|
1161
2137
|
expect,
|
|
2138
|
+
when,
|
|
1162
2139
|
sets: Object.freeze(sets),
|
|
2140
|
+
increments: Object.freeze(increments),
|
|
1163
2141
|
links: Object.freeze(links)
|
|
1164
2142
|
});
|
|
1165
2143
|
};
|
|
2144
|
+
/** Whether a value's stored form is a plain number. */
|
|
2145
|
+
const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
|
|
2146
|
+
/** Whether a value's stored form is checked to be an integer. */
|
|
2147
|
+
const storedAsInteger = (schema) => SchemaShape.holdsIntegers(Schema.toEncoded(schema).ast);
|
|
2148
|
+
/**
|
|
2149
|
+
* One increment, checked: a field of the Entity stored as a number, written
|
|
2150
|
+
* by nothing else, moved by an unmapped input key whose value is a number, and
|
|
2151
|
+
* an integer when the field is one.
|
|
2152
|
+
*/
|
|
2153
|
+
const incrementOf = (input, fieldKey, key, declared) => {
|
|
2154
|
+
const fields = input.entity.fields;
|
|
2155
|
+
const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
|
|
2156
|
+
if (field === void 0) return fail$1(input, `increments "${fieldKey}", which is not a field`);
|
|
2157
|
+
if (fieldKey === "id") return fail$1(input, "increments the id");
|
|
2158
|
+
if (declared.expect?.field.key === fieldKey) return fail$1(input, `increments "${fieldKey}", the revision it expects`);
|
|
2159
|
+
if (declared.sets.some((set) => set.field.key === fieldKey)) return fail$1(input, `increments "${fieldKey}", which a key also sets`);
|
|
2160
|
+
if (!storedAsNumber(field.schema)) return fail$1(input, `increments "${fieldKey}", which is not stored as a number`);
|
|
2161
|
+
const member = membersOf(input)[key];
|
|
2162
|
+
if (member === void 0) return fail$1(input, `"${key}" is not a key of the input`);
|
|
2163
|
+
if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
|
|
2164
|
+
const amount = input.schema.fields[key];
|
|
2165
|
+
if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
|
|
2166
|
+
const integer = storedAsInteger(amount);
|
|
2167
|
+
if (storedAsInteger(field.schema) && !integer) return fail$1(input, `"${key}" may not be an integer, but "${fieldKey}" is one; give the amount Schema.Int`);
|
|
2168
|
+
return Object.freeze({
|
|
2169
|
+
key,
|
|
2170
|
+
field,
|
|
2171
|
+
integer
|
|
2172
|
+
});
|
|
2173
|
+
};
|
|
1166
2174
|
/** An update or an insert that would write nothing is refused where it is declared. */
|
|
1167
|
-
const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 ? fail$1(write.input, "it sets no field") : write;
|
|
2175
|
+
const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 ? fail$1(write.input, "it sets no field") : write;
|
|
1168
2176
|
const Write = {
|
|
1169
2177
|
/**
|
|
1170
2178
|
* Sets, on the row whose id is the input's `id` key, every field the input
|
|
@@ -1179,10 +2187,12 @@ const Write = {
|
|
|
1179
2187
|
* id it holds. Refused where it is written: an `id` that is not the Entity's
|
|
1180
2188
|
* `id` field, a `many` relation or a nested key (not written by an update
|
|
1181
2189
|
* yet), or nothing to set.
|
|
2190
|
+
*
|
|
2191
|
+
* `when` is what the row must hold for the update to land, checked where it
|
|
2192
|
+
* commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
|
|
2193
|
+
* does not hold of is refused as unmet.
|
|
1182
2194
|
*/
|
|
1183
|
-
update
|
|
1184
|
-
return settingSomething(declared("Update", input, options));
|
|
1185
|
-
},
|
|
2195
|
+
update,
|
|
1186
2196
|
/**
|
|
1187
2197
|
* Inserts the row whose id is the input's `id` key, an id the client chose,
|
|
1188
2198
|
* with every field and `one` relation the input maps a key to. An insert
|
|
@@ -1196,14 +2206,9 @@ const Write = {
|
|
|
1196
2206
|
* Deletes the row whose id is the input's `id` key, only while it is still at
|
|
1197
2207
|
* the revision `expect` names, when it names one. It sets nothing, so a key
|
|
1198
2208
|
* mapped to a member is refused where it is written. A row already gone (a
|
|
1199
|
-
* retry) is gone.
|
|
2209
|
+
* retry) is gone. `when`, as an update's, is what the row must hold.
|
|
1200
2210
|
*/
|
|
1201
|
-
delete:
|
|
1202
|
-
const write = declared("Delete", input, options);
|
|
1203
|
-
const named = [...write.sets, ...write.links][0];
|
|
1204
|
-
if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
|
|
1205
|
-
return write;
|
|
1206
|
-
},
|
|
2211
|
+
delete: remove,
|
|
1207
2212
|
/**
|
|
1208
2213
|
* The revision this input says the row was read at, encoded, with its field:
|
|
1209
2214
|
* what an interpreter writes only a row still at. None for a write that
|
|
@@ -1214,7 +2219,24 @@ const Write = {
|
|
|
1214
2219
|
revision: encoded(field, value[key])
|
|
1215
2220
|
})),
|
|
1216
2221
|
/** The members any invocation may write: what a query reading none of them cannot be changed by. */
|
|
1217
|
-
writes: (write) => [
|
|
2222
|
+
writes: (write) => [
|
|
2223
|
+
...write.sets.map((set) => set.field),
|
|
2224
|
+
...write.increments.map((increment) => increment.field),
|
|
2225
|
+
...write.links.map((link) => link.relation)
|
|
2226
|
+
],
|
|
2227
|
+
/**
|
|
2228
|
+
* The fields a write reads from the row it writes: those its `when` reads,
|
|
2229
|
+
* each it increments, and the revision it expects. What an interpreter
|
|
2230
|
+
* must read, and what a startup check judges it could disclose.
|
|
2231
|
+
*/
|
|
2232
|
+
reads: (write) => {
|
|
2233
|
+
const fields = /* @__PURE__ */ new Map();
|
|
2234
|
+
const add = (field) => fields.set(field.key, field);
|
|
2235
|
+
Option.map(write.when, (body) => Query.dependencies(body).predicate.forEach((field) => add(field)));
|
|
2236
|
+
write.increments.forEach((increment) => add(increment.field));
|
|
2237
|
+
if (write.expect !== void 0) add(write.expect.field);
|
|
2238
|
+
return [...fields.values()];
|
|
2239
|
+
},
|
|
1218
2240
|
/**
|
|
1219
2241
|
* The row this input writes and its new values, encoded as the store holds
|
|
1220
2242
|
* them: the patch a client shows before the server answers. `keys`, when
|
|
@@ -1241,16 +2263,24 @@ const Write = {
|
|
|
1241
2263
|
id: String(encoded(target.fields.id, id))
|
|
1242
2264
|
}));
|
|
1243
2265
|
}
|
|
2266
|
+
const increments = {};
|
|
2267
|
+
for (const { key, field } of write.increments) {
|
|
2268
|
+
if (!asked(key)) continue;
|
|
2269
|
+
const schema = write.input.schema.fields[key];
|
|
2270
|
+
Option.map(given(input[key]), (held) => {
|
|
2271
|
+
increments[field.key] = Schema.encodeUnknownSync(schema)(held);
|
|
2272
|
+
});
|
|
2273
|
+
}
|
|
1244
2274
|
return {
|
|
1245
2275
|
entity: write.input.entity.name,
|
|
1246
2276
|
id: String(encoded(write.id.field, input[write.id.key])),
|
|
1247
2277
|
values,
|
|
1248
|
-
links
|
|
2278
|
+
links,
|
|
2279
|
+
increments
|
|
1249
2280
|
};
|
|
1250
2281
|
}
|
|
1251
2282
|
};
|
|
1252
|
-
|
|
1253
|
-
//#region src/index.ts
|
|
2283
|
+
// src/index.ts
|
|
1254
2284
|
/**
|
|
1255
2285
|
* `foldkit-entity` — domain structure as typed values.
|
|
1256
2286
|
*
|
|
@@ -1454,6 +2484,36 @@ const Entity = {
|
|
|
1454
2484
|
...entity,
|
|
1455
2485
|
metadata: Metadata.combine([entity.metadata, metadata])
|
|
1456
2486
|
}),
|
|
2487
|
+
/**
|
|
2488
|
+
* Declares what every stored row, or every change of one, must hold:
|
|
2489
|
+
* `Entity.invariant('reservedWithinQuantity', ({ after }) =>
|
|
2490
|
+
* Expr.lte(after.reserved, after.quantity), { message })` over the row a
|
|
2491
|
+
* write leaves, or with `before` too over the change an update makes.
|
|
2492
|
+
* Refused where it is declared: an id declared twice, a predicate over another
|
|
2493
|
+
* Entity, one reading an input or nothing of `after` (that is a `when`), a path
|
|
2494
|
+
* naming no field.
|
|
2495
|
+
*/
|
|
2496
|
+
invariant,
|
|
2497
|
+
/** The Entity's invariants, in the order they were declared. */
|
|
2498
|
+
invariants: invariantsOf,
|
|
2499
|
+
/**
|
|
2500
|
+
* A row (`{ after }`, a create's) or a change (`{ before, after }`, an
|
|
2501
|
+
* update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
|
|
2502
|
+
* that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
|
|
2503
|
+
* one reads that a row lacks.
|
|
2504
|
+
*/
|
|
2505
|
+
judge,
|
|
2506
|
+
/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
|
|
2507
|
+
readsBefore,
|
|
2508
|
+
/** `Entity.judge` against invariants already read, such as those a database binding keeps. */
|
|
2509
|
+
judgeAgainst,
|
|
2510
|
+
/**
|
|
2511
|
+
* The row an `Entity.input`'s value describes, judged: what a form can say
|
|
2512
|
+
* before the server does. Undecided for an invariant over a field it leaves unset.
|
|
2513
|
+
*/
|
|
2514
|
+
judgeInput,
|
|
2515
|
+
/** The state invariants as a Schema check over the row type, each failure at its path. */
|
|
2516
|
+
check,
|
|
1457
2517
|
/** Attaches an interpreter's metadata to members, by key. */
|
|
1458
2518
|
annotateMembers: (metadata) => (entity) => {
|
|
1459
2519
|
const given = metadata;
|
|
@@ -1588,7 +2648,6 @@ const Relation = {
|
|
|
1588
2648
|
})
|
|
1589
2649
|
};
|
|
1590
2650
|
const Derived = { make: (schema) => ({ schema }) };
|
|
1591
|
-
|
|
1592
|
-
export { SchemaShape as C, Collation as S, Order as _, SelectionPageTypeId as a, isPredicate as b, QueryEvaluateError as c, decided as d, evaluate as f, Expr as g, ReadFilter as h, Relation as i, assertSupported as l, Words as m, Entity as n, SelectionTypeId as o, supported as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, Query as v, maxQueryNodes as x, dependenciesOf as y };
|
|
2651
|
+
export { Law as A, Expr as C, isPredicate as D, dependenciesOf as E, maxQueryNodes as O, Text as S, Query as T, supported as _, SelectionPageTypeId as a, Evidence as b, Words as c, OperatorMissingError as d, QueryEvaluateError as f, evaluate as g, decided as h, Relation as i, Collation as j, noOperators as k, ReadFilter as l, compareRows as m, Entity as n, SelectionTypeId as o, assertSupported as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, truthOver as v, Order as w, Operators as x, valueOfOperand as y };
|
|
1593
2652
|
|
|
1594
|
-
//# sourceMappingURL=src-
|
|
2653
|
+
//# sourceMappingURL=src-CSxcKUv6.mjs.map
|