foldkit-entity 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +962 -512
  2. package/dist/collation.d.ts +33 -0
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/collation.js +46 -0
  5. package/dist/collation.js.map +1 -0
  6. package/dist/conformance/index.d.ts +66 -0
  7. package/dist/conformance/index.d.ts.map +1 -0
  8. package/dist/conformance/{index.mjs → index.js} +22 -360
  9. package/dist/conformance/index.js.map +1 -0
  10. package/dist/conformance/operator.d.ts +115 -0
  11. package/dist/conformance/operator.d.ts.map +1 -0
  12. package/dist/conformance/operator.js +354 -0
  13. package/dist/conformance/operator.js.map +1 -0
  14. package/dist/conformance/relational.d.ts +240 -0
  15. package/dist/conformance/relational.d.ts.map +1 -0
  16. package/dist/conformance/relational.js +425 -0
  17. package/dist/conformance/relational.js.map +1 -0
  18. package/dist/conformance/tuples.d.ts +8 -0
  19. package/dist/conformance/tuples.d.ts.map +1 -0
  20. package/dist/conformance/tuples.js +43 -0
  21. package/dist/conformance/tuples.js.map +1 -0
  22. package/dist/conformance/variants.d.ts +47 -0
  23. package/dist/conformance/variants.d.ts.map +1 -0
  24. package/dist/conformance/variants.js +126 -0
  25. package/dist/conformance/variants.js.map +1 -0
  26. package/dist/context.d.ts +60 -0
  27. package/dist/context.d.ts.map +1 -0
  28. package/dist/context.js +36 -0
  29. package/dist/context.js.map +1 -0
  30. package/dist/descriptor.d.ts +33 -0
  31. package/dist/descriptor.d.ts.map +1 -0
  32. package/dist/descriptor.js +137 -0
  33. package/dist/descriptor.js.map +1 -0
  34. package/dist/entity.d.ts +231 -0
  35. package/dist/entity.d.ts.map +1 -0
  36. package/dist/entity.js +435 -0
  37. package/dist/entity.js.map +1 -0
  38. package/dist/evaluate.d.ts +204 -0
  39. package/dist/evaluate.d.ts.map +1 -0
  40. package/dist/evaluate.js +765 -0
  41. package/dist/evaluate.js.map +1 -0
  42. package/dist/expr.d.ts +915 -0
  43. package/dist/expr.d.ts.map +1 -0
  44. package/dist/expr.js +1630 -0
  45. package/dist/expr.js.map +1 -0
  46. package/dist/held.d.ts +112 -0
  47. package/dist/held.d.ts.map +1 -0
  48. package/dist/held.js +155 -0
  49. package/dist/held.js.map +1 -0
  50. package/dist/ids.d.ts +8 -0
  51. package/dist/ids.d.ts.map +1 -0
  52. package/dist/ids.js +8 -0
  53. package/dist/ids.js.map +1 -0
  54. package/dist/index.d.ts +380 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +110 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/invariant.d.ts +123 -0
  59. package/dist/invariant.d.ts.map +1 -0
  60. package/dist/invariant.js +236 -0
  61. package/dist/invariant.js.map +1 -0
  62. package/dist/jsonSchema.d.ts +3 -0
  63. package/dist/jsonSchema.d.ts.map +1 -0
  64. package/dist/jsonSchema.js +17 -0
  65. package/dist/jsonSchema.js.map +1 -0
  66. package/dist/law.d.ts +264 -0
  67. package/dist/law.d.ts.map +1 -0
  68. package/dist/law.js +111 -0
  69. package/dist/law.js.map +1 -0
  70. package/dist/operators.d.ts +170 -0
  71. package/dist/operators.d.ts.map +1 -0
  72. package/dist/operators.js +207 -0
  73. package/dist/operators.js.map +1 -0
  74. package/dist/readFilter.d.ts +8 -0
  75. package/dist/readFilter.d.ts.map +1 -0
  76. package/dist/readFilter.js +23 -0
  77. package/dist/readFilter.js.map +1 -0
  78. package/dist/record.d.ts +11 -0
  79. package/dist/record.d.ts.map +1 -0
  80. package/dist/record.js +21 -0
  81. package/dist/record.js.map +1 -0
  82. package/dist/sets.d.ts +18 -0
  83. package/dist/sets.d.ts.map +1 -0
  84. package/dist/sets.js +57 -0
  85. package/dist/sets.js.map +1 -0
  86. package/dist/shape.d.ts +23 -0
  87. package/dist/shape.d.ts.map +1 -0
  88. package/dist/shape.js +30 -0
  89. package/dist/shape.js.map +1 -0
  90. package/dist/tested.d.ts +8 -0
  91. package/dist/tested.d.ts.map +1 -0
  92. package/dist/tested.js +25 -0
  93. package/dist/tested.js.map +1 -0
  94. package/dist/text.d.ts +27 -0
  95. package/dist/text.d.ts.map +1 -0
  96. package/dist/text.js +39 -0
  97. package/dist/text.js.map +1 -0
  98. package/dist/variants.d.ts +72 -0
  99. package/dist/variants.d.ts.map +1 -0
  100. package/dist/variants.js +76 -0
  101. package/dist/variants.js.map +1 -0
  102. package/dist/words.d.ts +17 -0
  103. package/dist/words.d.ts.map +1 -0
  104. package/dist/words.js +22 -0
  105. package/dist/words.js.map +1 -0
  106. package/dist/write.d.ts +312 -0
  107. package/dist/write.d.ts.map +1 -0
  108. package/dist/write.js +520 -0
  109. package/dist/write.js.map +1 -0
  110. package/package.json +8 -8
  111. package/dist/conformance/index.d.mts +0 -274
  112. package/dist/conformance/index.d.mts.map +0 -1
  113. package/dist/conformance/index.mjs.map +0 -1
  114. package/dist/index-hu8IYlNc.d.mts +0 -2228
  115. package/dist/index-hu8IYlNc.d.mts.map +0 -1
  116. package/dist/index.d.mts +0 -2
  117. package/dist/index.mjs +0 -1
  118. package/dist/src-DBAilaDV.mjs +0 -3061
  119. package/dist/src-DBAilaDV.mjs.map +0 -1
@@ -1,3061 +0,0 @@
1
- import { Array as Array$1, Data, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
- import { Metadata } from "foldkit-metadata";
3
- import { absurd } from "effect/Function";
4
- // src/collation.ts
5
- /**
6
- * How text compares when a query orders by it, declared rather than left to
7
- * the backend. Left unsaid, SQLite compares bytes, Postgres follows the
8
- * database's locale and a JavaScript sort follows UTF-16 code units, so the
9
- * same body could order the same rows three ways. A declared collation is one
10
- * every interpreter that can honour it compiles to the same order, and one
11
- * that cannot refuses.
12
- *
13
- * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(
14
- * Collation.binary) })`), so most queries declare nothing; an order term may
15
- * override it (`Order.asc(field, { collation })`).
16
- */
17
- const key$1 = Metadata.key("foldkit-entity/collation", {
18
- merge: (collations) => collations.slice(-1),
19
- summarize: (collation) => collation._tag
20
- });
21
- /** A collation name a backend can be told, and nothing that could be read as SQL. */
22
- const localeName = /^[A-Za-z0-9_.@-]{1,64}$/;
23
- const Collation = {
24
- binary: Object.freeze({ _tag: "Binary" }),
25
- asciiFold: Object.freeze({ _tag: "AsciiFold" }),
26
- locale: (locale) => {
27
- if (!localeName.test(locale)) throw new Error(`[foldkit-entity] Collation.locale: "${locale}" is not a collation name`);
28
- return Object.freeze({
29
- _tag: "Locale",
30
- locale
31
- });
32
- },
33
- /** Member metadata: how a text field orders, wherever a query orders by it. */
34
- of: (collation) => key$1.of(collation),
35
- /** The collation a member's metadata declares, if any. */
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/shape.ts
46
- const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
47
- 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);
48
- /** Whether any of these checks is `Schema.isInt`, alone or inside a group (`isInt32`). */
49
- const checksInteger = (checks) => checks.some((check) => Match.value(check).pipe(Match.tagsExhaustive({
50
- Filter: (filter) => filter.annotations?.representation?.id === "effect/schema/isInt",
51
- FilterGroup: (group) => checksInteger(group.checks)
52
- })));
53
- /** What a schema's AST holds, read through Effect's own guards. */
54
- const SchemaShape = {
55
- /** True for the `null` and `undefined` members that make a schema optional. */
56
- isNullish,
57
- /**
58
- * The members of a schema with `null` and `undefined` set aside, so optional
59
- * text is still text; a schema that is not a union is its one member.
60
- */
61
- present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
62
- /** True when every value the schema admits is a string. */
63
- isText,
64
- /**
65
- * True when the AST is checked to hold integers (`Schema.isInt`, alone or in
66
- * a group such as `isInt32`). Read it from a schema's encoded side to ask
67
- * what the store holds.
68
- */
69
- holdsIntegers: (ast) => checksInteger(ast.checks ?? [])
70
- };
71
- // src/jsonSchema.ts
72
- /**
73
- * A schema's JSON Schema, of what it encodes to as JSON carries it, its
74
- * definitions kept under `$defs` so a `$ref` in it resolves. Not exported from
75
- * the package.
76
- */
77
- const jsonSchemaOf = (schema) => {
78
- const document = Schema.toJsonSchemaDocument(schema);
79
- return Object.keys(document.definitions).length === 0 ? document.schema : {
80
- ...document.schema,
81
- $defs: document.definitions
82
- };
83
- };
84
- // src/law.ts
85
- /**
86
- * Laws an operator declares (expr-operations-DESIGN §10): equations every
87
- * implementation of it keeps over a domain. A law describes; nothing rewrites a
88
- * body by one. `Conformance.laws` tests an implementation against them, and
89
- * what it finds is evidence recorded in that implementation's table.
90
- */
91
- const Laws = Data.taggedEnum();
92
- const unnarrowed = { domain: Option.none() };
93
- /**
94
- * A law as JSON says it: what `Operators.describe` lists and evidence names.
95
- * Its witnesses are values as stored and operators by name; its domain is a
96
- * JSON Schema, or `null` for the operator's whole input.
97
- */
98
- const LawDescription = Schema.Struct({
99
- kind: Schema.String,
100
- witnesses: Schema.Record(Schema.String, Schema.Unknown),
101
- domain: Schema.Unknown
102
- });
103
- /** An operator by its id, and its version when that is not the first. */
104
- const nameOf$1 = (operator) => operator.descriptor.version === 1 ? operator.descriptor.id : `${operator.descriptor.id}@${operator.descriptor.version}`;
105
- const Law = {
106
- associative: Laws.Associative(unnarrowed),
107
- commutative: Laws.Commutative(unnarrowed),
108
- idempotent: Laws.Idempotent(unnarrowed),
109
- preservesCollation: Laws.PreservesCollation(unnarrowed),
110
- /** `value` leaves the other argument as it is, from `side` (both by default). */
111
- identity: (value, side = "both") => Laws.Identity({
112
- ...unnarrowed,
113
- value,
114
- side
115
- }),
116
- /** `value` is the answer whatever the other argument, from `side` (both by default). */
117
- absorbing: (value, side = "both") => Laws.Absorbing({
118
- ...unnarrowed,
119
- value,
120
- side
121
- }),
122
- /** `other` undoes the operator: `op(a, other(a))` is `identity`. */
123
- inverse: (other, identity) => Laws.Inverse({
124
- ...unnarrowed,
125
- other,
126
- identity
127
- }),
128
- /** The operator distributes over `over`, from the left. */
129
- distributes: (over) => Laws.Distributes({
130
- ...unnarrowed,
131
- over
132
- }),
133
- /** Moving the argument at `position` up moves the result up (or down, decreasing). */
134
- monotonic: (direction, position) => Laws.Monotonic({
135
- ...unnarrowed,
136
- direction,
137
- position
138
- }),
139
- /**
140
- * The law over the values `domain` accepts only: a law that holds of the
141
- * integers and not of every number, say, narrowed so it is tested where it
142
- * is claimed.
143
- */
144
- within: (law, domain) => Object.freeze({
145
- ...law,
146
- domain: Option.some(domain)
147
- }),
148
- $match: Laws.$match,
149
- /**
150
- * The operators a law, as JSON, calls besides its own (`inverse`'s and
151
- * `distributes`' witnesses), by name: evidence of it is of their
152
- * implementations too, and goes when one of them is replaced.
153
- */
154
- witnessesNamed: (law) => [law.witnesses["other"], law.witnesses["over"]].filter((name) => typeof name === "string"),
155
- /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
156
- describe: (law) => {
157
- const witnesses = Laws.$match(law, {
158
- Associative: () => ({}),
159
- Commutative: () => ({}),
160
- Idempotent: () => ({}),
161
- PreservesCollation: () => ({}),
162
- Identity: ({ value, side }) => ({
163
- value,
164
- side
165
- }),
166
- Absorbing: ({ value, side }) => ({
167
- value,
168
- side
169
- }),
170
- Inverse: ({ other, identity }) => ({
171
- other: nameOf$1(other),
172
- identity
173
- }),
174
- Distributes: ({ over }) => ({ over: nameOf$1(over) }),
175
- Monotonic: ({ direction, position }) => ({
176
- direction,
177
- position
178
- })
179
- });
180
- return {
181
- kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
182
- witnesses,
183
- domain: Option.match(law.domain, {
184
- onNone: () => null,
185
- onSome: jsonSchemaOf
186
- })
187
- };
188
- }
189
- };
190
- // src/expr.ts
191
- /**
192
- * `Expr` — a query's scalar computations as typed values.
193
- *
194
- * An Entity says what a domain has; an `Expr` says something about one row of
195
- * it. A field reference, an input placeholder, a literal, and comparisons of
196
- * those are all immutable data: building one performs no work, reads nothing,
197
- * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
198
- * to SQL, an in-memory evaluator to a predicate over rows.
199
- *
200
- * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
201
- * operation here is one a real query in this repository needs; the set grows
202
- * from queries, not from what a database could express.
203
- */
204
- /** A table implementing nothing: every primitive operator is unsupported by it. */
205
- const noOperators = Object.freeze({
206
- has: () => false,
207
- versions: () => []
208
- });
209
- /**
210
- * An operator `operators` does not implement, by name, with the versions of it
211
- * the table does implement: `acme.slug@2 (this table has acme.slug)`.
212
- */
213
- const missingName = (operator, operators) => {
214
- const held = operators.versions(operator.id);
215
- if (held.includes(operator.version)) return `${operatorName$1(operator)} (this table has another declaration of it; declare an operator once and import it)`;
216
- return held.length === 0 ? operatorName$1(operator) : `${operatorName$1(operator)} (this table has ${held.map((version) => operatorName$1({
217
- ...operator,
218
- version
219
- })).join(", ")})`;
220
- };
221
- const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
222
- /**
223
- * An Entity's field and a `FieldExpr` are the same three members under the same
224
- * tag — the Entity's carries `metadata` besides — so this reads either and is
225
- * idempotent on its own output. Nothing needs to tell them apart, which is
226
- * better than telling them apart by which extra member happens to be present.
227
- */
228
- /**
229
- * Every node is frozen as it is made, so a query built from it stays the value
230
- * it was when `Query.where` checked it: nothing can swap a field or a literal
231
- * in afterwards. It also means no node can come to contain itself. A literal's
232
- * own payload is the caller's; the kernel compares scalars.
233
- */
234
- const node = (value) => Object.freeze(value);
235
- const literal = (value) => node({
236
- _tag: "Literal",
237
- value
238
- });
239
- const fieldExpr = (field) => node({
240
- _tag: "Field",
241
- owner: field.owner,
242
- key: field.key,
243
- schema: field.schema,
244
- collation: Option.orElse(Collation.declared(field.metadata), () => field.key === "id" ? Option.some(Collation.binary) : Option.none())
245
- });
246
- const predicateTags = /* @__PURE__ */ new Set([
247
- "Eq",
248
- "Null",
249
- "Contains",
250
- "In",
251
- "And",
252
- "Or",
253
- "Not",
254
- "Compare",
255
- "Test"
256
- ]);
257
- /** Whether a value is a predicate, and so usable where a boolean is wanted. */
258
- const isPredicate = (value) => predicateTags.has(tagOf(value));
259
- /**
260
- * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
261
- * itself, and anything else is the constant it is.
262
- */
263
- const toOperand = (value) => {
264
- const tag = tagOf(value);
265
- if (tag === "Field" && !Object.hasOwn(value, "metadata")) return value;
266
- if (tag === "Field") return fieldExpr(value);
267
- if (tag === "Literal" || tag === "Input" || tag === "Next" || tag === "Call" || predicateTags.has(tag)) return value;
268
- return literal(value);
269
- };
270
- /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
271
- const toExpr = (value, step) => {
272
- const operand = toOperand(value);
273
- if (isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`);
274
- return operand;
275
- };
276
- /** How values encoded by `ast` order: as numbers, as text, or not at all. */
277
- const orderKindOf = (ast) => {
278
- if (SchemaAST.isNumber(ast)) return "number";
279
- if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast)) return "text";
280
- if (SchemaAST.isLiteral(ast)) {
281
- if (typeof ast.literal === "number") return "number";
282
- if (typeof ast.literal === "string") return "text";
283
- return "none";
284
- }
285
- if (SchemaAST.isUnion(ast)) {
286
- const kinds = new Set(ast.types.filter((member) => !SchemaAST.isNull(member)).map(orderKindOf));
287
- const [only] = kinds;
288
- return kinds.size === 1 && only !== void 0 ? only : "none";
289
- }
290
- return "none";
291
- };
292
- /** How a literal orders; a null orders as anything, since comparing it is unknown. */
293
- const literalKind = (value) => {
294
- if (value === null) return "null";
295
- if (typeof value === "number") return "number";
296
- if (typeof value === "string") return "text";
297
- return "none";
298
- };
299
- /** How a side orders, read from its encoded form. */
300
- const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
301
- Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
302
- Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
303
- Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
304
- Literal: ({ value }) => literalKind(value),
305
- Call: ({ operator }) => orderKindOf(Schema.toEncoded(operator.output).ast)
306
- }));
307
- /**
308
- * How a comparison's text compares: the collation given, else the field's
309
- * declared one. Text orders differently by backend (SQLite's `BINARY`, the
310
- * Postgres database's locale, JavaScript's UTF-16 units), so it is compared
311
- * only under `binary` or `asciiFold`, which every interpreter here agrees on,
312
- * and only against a field, whose collation it is. Values that order
313
- * intrinsically, numbers, need none.
314
- */
315
- const collationFor = (step, left, right, given) => {
316
- const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
317
- 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`);
318
- if (!kinds.has("text")) return Option.none();
319
- const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [{
320
- name: `${field.owner.name}.${field.key}`,
321
- collation: field.collation
322
- }]), Match.tag("Next", ({ field }) => [{
323
- name: `${field.owner.name}.${field.key}`,
324
- collation: field.collation
325
- }]), Match.tag("Call", (call) => [{
326
- name: showExpr(call),
327
- collation: call.collation
328
- }]), Match.orElse(() => [])));
329
- const [first] = fields;
330
- 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`);
331
- const named = fields.map((field) => field.name).join(" and ");
332
- const collations = Option.match(given, {
333
- onSome: (collation) => [collation],
334
- onNone: () => fields.map((field) => Option.getOrElse(field.collation, () => {
335
- 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`);
336
- }))
337
- });
338
- const [collation] = collations;
339
- if (collation === void 0 || collations.some((each) => each._tag !== collation._tag)) throw new Error(`[foldkit-entity] Expr.${step}: ${named} declare different collations; pass one to compare them by`);
340
- return Match.value(collation).pipe(Match.tagsExhaustive({
341
- Binary: () => Option.some(collation),
342
- AsciiFold: () => Option.some(collation),
343
- Locale: ({ locale }) => {
344
- throw new Error(`[foldkit-entity] Expr.${step}: ${named} compares by the backend's "${locale}" collation, which only that backend has`);
345
- }
346
- }));
347
- };
348
- /** `Expr.lt` and its three siblings: the operator fixed, the sides typed alike. */
349
- const comparison = (operator) => (left, right, options = {}) => {
350
- const leftSide = toExpr(left, operator);
351
- const rightSide = toExpr(right, operator);
352
- return node({
353
- _tag: "Compare",
354
- operator,
355
- left: leftSide,
356
- right: rightSide,
357
- collation: collationFor(operator, leftSide, rightSide, Option.fromUndefinedOr(options.collation))
358
- });
359
- };
360
- /** A connective's operands, each checked to be a predicate, with one of the same kind flattened in. */
361
- const connected = (step, kind, given) => {
362
- const operands = given.flatMap((operand) => {
363
- if (!isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: every operand is a predicate; compare a value with Expr.eq first`);
364
- return Match.value(operand).pipe(Match.tags({
365
- And: (and) => kind === "And" ? and.operands : [and],
366
- Or: (or) => kind === "Or" ? or.operands : [or]
367
- }), Match.orElse(() => [operand]));
368
- });
369
- if (operands.length > 1e3) throw new Error(`[foldkit-entity] Expr.${step}: more than ${maxQueryNodes} operands, the most a query's predicates may hold`);
370
- if (!Array$1.isReadonlyArrayNonEmpty(operands)) throw new Error(`[foldkit-entity] Expr.${step}: no operands, which would match ${step === "and" ? "every row" : "no row"}; check a list is non-empty before spreading it`);
371
- return operands;
372
- };
373
- const connective = (step, kind) => (...given) => {
374
- const operands = connected(step, kind, given);
375
- return operands.length === 1 ? operands[0] : node({
376
- _tag: kind,
377
- operands
378
- });
379
- };
380
- const collationTags = /* @__PURE__ */ new Set([
381
- "Binary",
382
- "AsciiFold",
383
- "Locale"
384
- ]);
385
- /** A call's last value, when it is one past the arguments: its options, checked. */
386
- const callOptionsOf = (id, value) => {
387
- const collation = typeof value === "object" && value !== null && Object.hasOwn(value, "collation") ? value.collation : void 0;
388
- if (!collationTags.has(tagOf(collation))) throw new Error(`[foldkit-entity] ${id}: a value past its arguments is \`{ collation }\`, a Collation`);
389
- return collation;
390
- };
391
- /** A collation a call was given: one its operator compares by, and portable where required. */
392
- const givenCollation = (id, descriptor, collation) => {
393
- if (Option.isSome(descriptor.definedAs) || descriptor.collation === "none") throw new Error(`[foldkit-entity] ${id}: takes no collation; it compares no text of its own`);
394
- if (collation._tag === "Locale") throw new Error(`[foldkit-entity] ${id}: compares by the backend's "${collation.locale}" collation, which only that backend has`);
395
- return Option.some(collation);
396
- };
397
- /** Namespaced, lower camel case: `cms.published`, `text.startsWith`. */
398
- const operatorId = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
399
- /**
400
- * Why `law` cannot be declared of an operator of this shape, if it cannot: an
401
- * equation over two arguments of a unary operator, a witness that does not
402
- * decode as the argument it stands in, or a collation law of an operator
403
- * whose text keeps none.
404
- */
405
- const lawProblem = (law, input, output, collation) => {
406
- const name = Law.describe(law).kind;
407
- 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}`);
408
- 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`);
409
- 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")));
410
- return Law.$match(law, {
411
- Associative: binary,
412
- Commutative: binary,
413
- Idempotent: binary,
414
- Identity: ({ value, side }) => sides(value, side),
415
- Absorbing: ({ value, side }) => sides(value, side),
416
- Inverse: ({ other, identity }) => Option.orElse(binary(), () => other.descriptor.input.length === 1 ? decodes(identity, output, "identity") : Option.some(`${name}'s other operator takes one argument`)),
417
- Distributes: ({ over }) => Option.orElse(binary(), () => over.descriptor.input.length === 2 ? Option.none() : Option.some(`${name} is over an operator of two arguments`)),
418
- Monotonic: ({ position }) => Number.isSafeInteger(position) && position >= 0 && position < input.length ? Option.none() : Option.some(`${name}'s position ${position} is not an argument's`),
419
- PreservesCollation: () => collation === "operands" ? Option.none() : Option.some(`${name} is a law of an operator declared \`collation: 'operands'\``)
420
- });
421
- };
422
- /** Whether a schema's stored form is a boolean, which makes its operator a predicate. */
423
- const storedAsBoolean = (schema) => SchemaAST.isBoolean(Schema.toEncoded(schema).ast);
424
- /** What a schema stores, null aside: one kind an argument is checked by, or `other`. */
425
- const storedKindOf = (schema) => {
426
- const present = SchemaShape.present(Schema.toEncoded(schema).ast);
427
- if (present.length === 0) return "other";
428
- if (present.every(SchemaAST.isNumber)) return "number";
429
- if (present.every(SchemaShape.isText)) return "text";
430
- if (present.every(SchemaAST.isBoolean)) return "boolean";
431
- return "other";
432
- };
433
- /** The schema a scalar's values are stored by. */
434
- const scalarSchema = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
435
- Field: (field) => field.schema,
436
- Next: ({ field }) => field.schema,
437
- Input: (input) => input.schema,
438
- Literal: () => Schema.Unknown,
439
- Call: ({ operator }) => operator.output
440
- }));
441
- /** Every field, field after a write, and input an expression reads, as keys to compare. */
442
- const readKeys = (...nodes) => {
443
- const read = dependenciesOf(...nodes);
444
- const named = (prefix, fields) => fields.map((field) => `${prefix}${field.entity}.${field.key}`);
445
- return /* @__PURE__ */ new Set([
446
- ...named("", read.fields),
447
- ...named("next ", read.next),
448
- ...read.inputs.map((key) => `$${key}`)
449
- ]);
450
- };
451
- /** One argument, checked against the schema it is passed for, as a node. */
452
- const argumentFor = (id, position, schema, value) => {
453
- const arg = toOperand(value);
454
- const fail = (what) => {
455
- throw new Error(`[foldkit-entity] ${id}: argument ${position + 1} ${what}`);
456
- };
457
- if (isPredicate(arg)) {
458
- if (!storedAsBoolean(schema)) fail("is a predicate, but the operator does not take a boolean");
459
- return arg;
460
- }
461
- if (arg._tag === "Literal") {
462
- if (!Schema.is(Schema.toEncoded(schema))(arg.value)) fail(`is ${JSON.stringify(arg.value)}, which the operator's input schema does not admit`);
463
- return arg;
464
- }
465
- const wanted = storedKindOf(schema);
466
- const given = storedKindOf(scalarSchema(arg));
467
- if (wanted !== "other" && given !== "other" && given !== wanted) fail(`is stored as ${given}, but the operator takes ${wanted}`);
468
- return arg;
469
- };
470
- /** A scalar's collation: a field's declared one, or a call's. */
471
- const collationOf = (scalar) => Match.value(scalar).pipe(Match.tagsExhaustive({
472
- Field: (field) => field.collation,
473
- Next: ({ field }) => field.collation,
474
- Call: (call) => call.collation,
475
- Literal: () => Option.none(),
476
- Input: () => Option.none()
477
- }));
478
- /**
479
- * The collation a primitive call compares text under: the one its collated
480
- * text arguments share. A literal or an input carries none and does not vote.
481
- * `required` refuses a call with none, or with a backend's locale.
482
- */
483
- const callCollation = (id, rule, args) => {
484
- if (rule === "none") return Option.none();
485
- const fail = (what) => {
486
- throw new Error(`[foldkit-entity] ${id}: ${what}`);
487
- };
488
- const voters = args.flatMap((arg) => isPredicate(arg) || arg._tag === "Literal" || arg._tag === "Input" || sideKind(arg) !== "text" ? [] : [{
489
- arg,
490
- collation: collationOf(arg)
491
- }]);
492
- const collations = voters.flatMap(({ arg, collation }) => Option.match(collation, {
493
- onSome: (each) => [each],
494
- onNone: () => rule === "required" ? fail(`${showExpr(arg)} is text with no declared collation, so backends would compare it differently; declare Collation.binary or Collation.asciiFold on it`) : []
495
- }));
496
- const [shared] = collations;
497
- if (shared === void 0) return rule === "required" ? fail("compares text with no field or call holding a collation") : Option.none();
498
- if (collations.some((each) => each._tag !== shared._tag)) fail(`${voters.map((voter) => showExpr(voter.arg)).join(" and ")} declare different collations`);
499
- if (shared._tag === "Locale") fail(`compares by the backend's "${shared.locale}" collation, which a call cannot carry`);
500
- return Option.some(shared);
501
- };
502
- /** Builds an operator: checks what it is given once, then each call. */
503
- const makeOperator = (id, options) => {
504
- const fail = (what) => {
505
- throw new Error(`[foldkit-entity] Expr.operator("${id}"): ${what}`);
506
- };
507
- if (!operatorId.test(id)) fail("an id is namespaced lower camel case, as `cms.published`");
508
- if (id.startsWith("foldkit.")) fail("ids under `foldkit.` are reserved");
509
- const version = options.version ?? 1;
510
- if (!Number.isSafeInteger(version) || version < 1) fail("a version is a positive integer");
511
- if (!Array.isArray(options.input) || !options.input.every(Schema.isSchema)) fail("`input` is one schema per argument");
512
- if (!Schema.isSchema(options.output)) fail("`output` is a schema");
513
- const definedAs = Option.fromUndefinedOr(options.definedAs);
514
- if (Option.isSome(definedAs) && typeof definedAs.value !== "function") fail("`definedAs` builds what a call means");
515
- 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");
516
- const nulls = options.nulls ?? "strict";
517
- const collation = options.collation ?? "none";
518
- if (nulls !== "strict" && nulls !== "handled") fail("`nulls` is 'strict' or 'handled'");
519
- if (collation !== "none" && collation !== "operands" && collation !== "required") fail("`collation` is 'none', 'operands' or 'required'");
520
- const input = Object.freeze([...options.input]);
521
- const predicate = storedAsBoolean(options.output);
522
- if (collation === "operands" && orderKindOf(Schema.toEncoded(options.output).ast) !== "text") fail("`collation: 'operands'` describes a text result, and this one is not text");
523
- const laws = Object.freeze([...options.laws ?? []]);
524
- for (const law of laws) Option.match(lawProblem(law, input, options.output, collation), {
525
- onNone: () => void 0,
526
- onSome: fail
527
- });
528
- const descriptor = Object.freeze({
529
- _tag: "Operator",
530
- id,
531
- version,
532
- description: Option.fromUndefinedOr(options.description),
533
- input,
534
- output: options.output,
535
- definedAs,
536
- nulls,
537
- collation,
538
- laws
539
- });
540
- /** A defined call's expansion, checked: of its output's kind, reading only its arguments. */
541
- const expand = (body, args) => {
542
- const expansion = toOperand(body(...args));
543
- 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"}`);
544
- const allowed = readKeys(...args);
545
- const hidden = [...readKeys(expansion)].filter((key) => !allowed.has(key));
546
- if (hidden.length > 0) throw new Error(`[foldkit-entity] ${id}: \`definedAs\` reads ${hidden.join(", ")}, which no argument holds; pass it as one`);
547
- return expansion;
548
- };
549
- const call = (...written) => {
550
- const explicit = written.length === input.length + 1 ? Option.some(callOptionsOf(id, written[written.length - 1])) : Option.none();
551
- const given = Option.isSome(explicit) ? written.slice(0, -1) : written;
552
- if (given.length !== input.length) throw new Error(`[foldkit-entity] ${id}: takes ${input.length} argument${input.length === 1 ? "" : "s"}, given ${given.length}`);
553
- const args = Object.freeze(given.map((value, position) => argumentFor(id, position, input[position], value)));
554
- const expansion = Option.map(descriptor.definedAs, (body) => expand(body, args));
555
- const carried = Option.match(explicit, {
556
- onSome: (each) => givenCollation(id, descriptor, each),
557
- onNone: () => Option.match(expansion, {
558
- onSome: (body) => isPredicate(body) ? Option.none() : collationOf(body),
559
- onNone: () => callCollation(id, collation, args)
560
- })
561
- });
562
- return predicate ? node({
563
- _tag: "Test",
564
- operator: descriptor,
565
- args,
566
- expansion,
567
- collation: carried
568
- }) : node({
569
- _tag: "Call",
570
- operator: descriptor,
571
- args,
572
- expansion,
573
- collation: carried
574
- });
575
- };
576
- return Object.freeze(Object.assign(call, { descriptor }));
577
- };
578
- /** Each defined call replaced by its expansion, deeply; built once per node. */
579
- const expandedCache = /* @__PURE__ */ new WeakMap();
580
- const expandedScalar = (scalar) => {
581
- const known = expandedCache.get(scalar);
582
- if (known !== void 0) return known;
583
- const result = scalar._tag === "Call" ? Option.match(scalar.expansion, {
584
- onSome: expandedScalar,
585
- onNone: () => node({
586
- ...scalar,
587
- args: scalar.args.map(expandedSide)
588
- })
589
- }) : scalar;
590
- expandedCache.set(scalar, result);
591
- return result;
592
- };
593
- const expandedSide = (side) => isPredicate(side) ? expandedPredicate(side) : expandedScalar(side);
594
- const expandedPredicate = (predicate) => {
595
- const known = expandedCache.get(predicate);
596
- if (known !== void 0) return known;
597
- const result = Match.value(predicate).pipe(Match.tagsExhaustive({
598
- Eq: (eq) => node({
599
- ...eq,
600
- left: expandedSide(eq.left),
601
- right: expandedSide(eq.right)
602
- }),
603
- Null: (nul) => node({
604
- ...nul,
605
- operand: expandedScalar(nul.operand)
606
- }),
607
- Contains: (contains) => node({
608
- ...contains,
609
- value: expandedScalar(contains.value),
610
- search: expandedSide(contains.search)
611
- }),
612
- In: (inPredicate) => node({
613
- ...inPredicate,
614
- value: expandedScalar(inPredicate.value),
615
- among: expandedScalar(inPredicate.among)
616
- }),
617
- And: (and) => node({
618
- ...and,
619
- operands: Array$1.map(and.operands, expandedPredicate)
620
- }),
621
- Or: (or) => node({
622
- ...or,
623
- operands: Array$1.map(or.operands, expandedPredicate)
624
- }),
625
- Not: (not) => node({
626
- ...not,
627
- operand: expandedPredicate(not.operand)
628
- }),
629
- Compare: (compare) => node({
630
- ...compare,
631
- left: expandedScalar(compare.left),
632
- right: expandedScalar(compare.right)
633
- }),
634
- Test: (test) => Option.match(test.expansion, {
635
- onSome: expandedPredicate,
636
- onNone: () => node({
637
- ...test,
638
- args: test.args.map(expandedSide)
639
- })
640
- })
641
- }));
642
- expandedCache.set(predicate, result);
643
- return result;
644
- };
645
- const Expr = {
646
- /**
647
- * An operator, defined by what a call of it means: `definedAs` builds that
648
- * expression from the call's arguments, once per call, and every interpreter
649
- * runs it, so the operator needs no implementation anywhere. What it adds is
650
- * a name: a query, a guard and an invariant that mean the same thing say so,
651
- * and print it.
652
- *
653
- * ```ts
654
- * const published = Expr.operator('cms.published', {
655
- * input: [Schema.Unknown],
656
- * output: Schema.Boolean,
657
- * definedAs: publishedAt => Expr.isNotNull(publishedAt),
658
- * })
659
- * Query.where(published(Post.fields.publishedAt))
660
- * ```
661
- *
662
- * Arguments are checked by their stored form: a field, scalar or plain value
663
- * of the input's stored type, or a predicate where it takes a boolean. A
664
- * boolean output makes a call a predicate. `definedAs` may read only what its
665
- * arguments hold: a field or input it closes over instead is refused when
666
- * called, since nothing asking what the call reads would see it. The id is
667
- * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
668
- * changes when what it means does.
669
- *
670
- * **Without `definedAs` it is primitive**: each interpreter implements it
671
- * (`Operators.implement` in memory), and one without an implementation
672
- * refuses the body by the operator's id. `nulls` (default `strict`: a null
673
- * argument gives null, the implementation never sees one) and `collation`
674
- * (`operands`: a text result carries its text arguments' shared collation;
675
- * `required`: it compares text itself and needs one) are a primitive
676
- * operator's; a defined one means its body for both.
677
- */
678
- operator: (id, options) => makeOperator(id, options),
679
- /**
680
- * The predicate or scalar (an order term's, say) with every call of a
681
- * defined operator replaced by what it means, deeply. An interpreter that
682
- * compiles a body expands it first, and compiles exactly what was written
683
- * out. A call with no definition stays, for the interpreter to run or refuse
684
- * by name.
685
- */
686
- /**
687
- * Whether a constant written in these expressions is text holding a NUL, or
688
- * a list holding one: SQL refuses such a parameter wherever it compiles, so
689
- * an interpreter refuses the run, not one row.
690
- */
691
- givesNul: (...nodes) => {
692
- const seen = /* @__PURE__ */ new Set();
693
- const nul = (value) => typeof value === "string" && value.includes(String.fromCharCode(0));
694
- const walk = (node) => {
695
- if (seen.has(node)) return false;
696
- seen.add(node);
697
- if (node._tag === "Literal") return Array.isArray(node.value) ? node.value.some(nul) : nul(node.value);
698
- return childrenOf(node).some(walk);
699
- };
700
- return nodes.some(walk);
701
- },
702
- expanded: (node) => isPredicate(node) ? expandedPredicate(node) : expandedScalar(node),
703
- /**
704
- * What these expressions need that an interpreter lacks, as `Query.unsupported`
705
- * says it for a query: each kernel operation `supported` does not list, then
706
- * each primitive operator `operators` does not implement, by name (`id`, or
707
- * `id@version` past the first). For anything holding expressions that is not a
708
- * query: a guard's rule, an invariant, a write's `when`.
709
- */
710
- unsupported: (nodes, interpreter) => unsupportedIn(nodes, interpreter.operations, interpreter.operators),
711
- /** A constant. Comparisons coerce a plain value, so this is rarely written. */
712
- literal,
713
- /**
714
- * A value the query is given when it runs. A definition builds these from its
715
- * `Input` schema; written by hand only when constructing a body directly.
716
- */
717
- input: (key, schema) => node({
718
- _tag: "Input",
719
- key,
720
- schema
721
- }),
722
- /**
723
- * A field as the row a write would leave holds it: what `Entity.invariant`'s
724
- * builder hands out as `after`.
725
- */
726
- next: (field) => node({
727
- _tag: "Next",
728
- field: fieldExpr(field)
729
- }),
730
- /** One field of one Entity, as a scalar. */
731
- field: (field) => fieldExpr(field),
732
- /**
733
- * Two scalars are the same value: a field (or an expression) on the left,
734
- * and the value on the right, typed from it. Fields and plain values are
735
- * coerced, so the common form reads as it means:
736
- *
737
- * ```ts
738
- * Expr.eq(Post.fields.slug, input.slug)
739
- * Expr.eq(Post.fields.status, 'active')
740
- * ```
741
- */
742
- eq: (left, right) => node({
743
- _tag: "Eq",
744
- left: toOperand(left),
745
- right: toOperand(right)
746
- }),
747
- /**
748
- * Whether a field holds no value. Its opposite is `isNotNull`; both are the
749
- * one node, since a query asks which of the two it means, and `is not null`
750
- * has no unknown for a `not` to keep.
751
- */
752
- isNull: (operand) => node({
753
- _tag: "Null",
754
- operand: toExpr(operand, "isNull"),
755
- present: false
756
- }),
757
- /** Whether a field holds a value. */
758
- isNotNull: (operand) => node({
759
- _tag: "Null",
760
- operand: toExpr(operand, "isNotNull"),
761
- present: true
762
- }),
763
- /**
764
- * Whether a text value contains `search`, anywhere in it. Containing the
765
- * empty string is everything, so a search box with nothing typed in it is the
766
- * same query as one with something — no branch, and no second query.
767
- *
768
- * **Case-insensitive**, which is what a search means, and which has to be
769
- * said rather than left to the interpreter: SQLite's `like` ignores case and
770
- * Postgres's does not, so a body that left it open would mean two things.
771
- * Folding is ASCII-only, because that is what `lower` does in SQLite without
772
- * ICU.
773
- *
774
- * **Over a column that can be null this is not the same as no filter.** A
775
- * null contains nothing, not even the empty string, so its rows drop out. A
776
- * nullable column that should match everything on an empty search says so:
777
- * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
778
- */
779
- contains: (value, search) => {
780
- const operand = toOperand(search);
781
- if (operand._tag !== "Literal" && operand._tag !== "Input") throw new Error(`[foldkit-entity] Expr.contains: the search is ${showExpr(operand)}; search for a value or an input`);
782
- return node({
783
- _tag: "Contains",
784
- value: toExpr(value, "contains"),
785
- search: operand
786
- });
787
- },
788
- /**
789
- * Whether a value is one of `among`: a list written out, or an input whose
790
- * value is one. Each element is compared as `eq` compares.
791
- *
792
- * ```ts
793
- * Expr.in(Todo.fields.projectId, input.projectIds)
794
- * Expr.in(Todo.fields.status, ['open', 'blocked'])
795
- * ```
796
- *
797
- * As SQL's `in`: a null value is unknown, as is no match against a list
798
- * holding a null, and an empty list matches no row. A list written out is
799
- * copied, so changing the array afterwards does not change the query.
800
- */
801
- in: (value, among) => node({
802
- _tag: "In",
803
- value: toExpr(value, "in"),
804
- among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
805
- }),
806
- /**
807
- * `left` orders before `right`. Numbers compare as numbers; text compares
808
- * under a collation, the one given or the field's declared one, which must be
809
- * `binary` or `asciiFold` (so every backend agrees), and text needs a field on
810
- * one side. A date compares by its encoded form: as text when it is stored as
811
- * an ISO string, so its field declares `Collation.binary`. A null on either
812
- * side is unknown, so the row is matched by neither this nor its `not`.
813
- *
814
- * ```ts
815
- * Expr.lt(fields.cents, 1000)
816
- * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
817
- * ```
818
- */
819
- lt: comparison("lt"),
820
- /** `left` orders before `right`, or with it; see `Expr.lt`. */
821
- lte: comparison("lte"),
822
- /** `left` orders after `right`; see `Expr.lt`. */
823
- gt: comparison("gt"),
824
- /** `left` orders after `right`, or with it; see `Expr.lt`. */
825
- gte: comparison("gte"),
826
- /**
827
- * Every operand holds, as one predicate to place inside another: `where`'s
828
- * list is already a conjunction, so this is for `or(and(a, b), c)`.
829
- * Unknown as SQL's `and` is: false wins over unknown, which wins over true.
830
- * Needs an operand; a list built at run time is checked non-empty first
831
- * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.
832
- */
833
- and: connective("and", "And"),
834
- /**
835
- * At least one operand holds:
836
- *
837
- * ```ts
838
- * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))
839
- * ```
840
- *
841
- * Unknown as SQL's `or` is: true wins over unknown, which wins over false.
842
- * Needs an operand, since an empty `or` would match no row.
843
- */
844
- or: connective("or", "Or"),
845
- /**
846
- * The operand does not hold. **A null is matched by neither side**:
847
- * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since
848
- * `null = 'draft'` is unknown and so is its `not`, as in SQL. "Everything
849
- * but drafts" over a nullable column is
850
- * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.
851
- */
852
- not: (operand) => {
853
- if (!isPredicate(operand)) throw new Error("[foldkit-entity] Expr.not: the operand is a predicate; compare a value with Expr.eq first");
854
- return node({
855
- _tag: "Not",
856
- operand
857
- });
858
- },
859
- /**
860
- * A filter that applies only when its input is given: `or(isNull($x), …)`,
861
- * with the predicate built from the input as never null.
862
- *
863
- * ```ts
864
- * // Every product, or those of the chosen status.
865
- * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))
866
- * ```
867
- *
868
- * An interpreter that runs per request, as the Drizzle compiler does, decides
869
- * `isNull($x)` before writing SQL, so this compiles to `true`, which filters
870
- * nothing, or to the predicate alone.
871
- */
872
- whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
873
- /** An expression as readable text; see `showExpr` for what it is and is not. */
874
- show: (node) => showExpr(node),
875
- /**
876
- * The predicate with each field after a write (`Next`) that `values` names,
877
- * by key, read as that value: how an invariant is judged where the
878
- * write's new values are known. A field it does not name stays `Next`, for
879
- * the interpreter to read as the row after holds it.
880
- */
881
- 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)))
882
- };
883
- const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : substitutedScalar(side, rewrite);
884
- /**
885
- * A scalar rewritten: a call's arguments and expansion each, so a field read
886
- * under it is rewritten as one read directly is; anything else by `rewrite`.
887
- */
888
- const substitutedScalar = (scalar, rewrite) => scalar._tag === "Call" ? node({
889
- ...scalar,
890
- args: Object.freeze(scalar.args.map((arg) => substitutedSide(arg, rewrite))),
891
- expansion: Option.map(scalar.expansion, (expansion) => substitutedScalar(expansion, rewrite))
892
- }) : rewrite(scalar);
893
- const substituted = (predicate, rewrite) => {
894
- switch (predicate._tag) {
895
- case "Eq": return node({
896
- ...predicate,
897
- left: substitutedSide(predicate.left, rewrite),
898
- right: substitutedSide(predicate.right, rewrite)
899
- });
900
- case "Null": return node({
901
- ...predicate,
902
- operand: substitutedScalar(predicate.operand, rewrite)
903
- });
904
- case "Contains": return node({
905
- ...predicate,
906
- value: substitutedScalar(predicate.value, rewrite),
907
- search: substitutedSide(predicate.search, rewrite)
908
- });
909
- case "In": return node({
910
- ...predicate,
911
- value: substitutedScalar(predicate.value, rewrite),
912
- among: substitutedScalar(predicate.among, rewrite)
913
- });
914
- case "And":
915
- case "Or": return node({
916
- ...predicate,
917
- operands: Array$1.map(predicate.operands, (operand) => substituted(operand, rewrite))
918
- });
919
- case "Not": return node({
920
- ...predicate,
921
- operand: substituted(predicate.operand, rewrite)
922
- });
923
- case "Compare": return node({
924
- ...predicate,
925
- left: substitutedScalar(predicate.left, rewrite),
926
- right: substitutedScalar(predicate.right, rewrite)
927
- });
928
- case "Test": return node({
929
- ...predicate,
930
- args: Object.freeze(predicate.args.map((arg) => substitutedSide(arg, rewrite))),
931
- expansion: Option.map(predicate.expansion, (expansion) => substituted(expansion, rewrite))
932
- });
933
- }
934
- };
935
- /** A term, its nulls placed by `options` or by the direction's default. */
936
- const term = (direction, expr, options = {}) => {
937
- const number = sideKind(expr) === "number";
938
- if (number && options.collation !== void 0) throw new Error(`[foldkit-entity] Order: ${showExpr(expr)} is a number, which needs no collation; a collation orders text`);
939
- const collation = number ? Option.none() : 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())));
940
- if (expr._tag === "Call") orderableCall(expr, collation);
941
- return node({
942
- _tag: "Term",
943
- direction,
944
- expr,
945
- nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
946
- collation
947
- });
948
- };
949
- /**
950
- * Refuses a call no interpreter could order alike (expr-operations-DESIGN §8):
951
- * its result must be a number, or text under a collation every interpreter
952
- * shares. A field's text may be left to the backend; a call's has no backend
953
- * column to fall back on.
954
- */
955
- const orderableCall = (call, collation) => {
956
- const fail = (why) => {
957
- throw new Error(`[foldkit-entity] Order: ${showExpr(call)} ${why}`);
958
- };
959
- const kind = sideKind(call);
960
- if (kind === "number") return;
961
- if (kind !== "text") fail("is neither a number nor text, so it orders nowhere alike");
962
- Option.match(collation, {
963
- onNone: () => fail("is text with no collation, so backends would order it differently; give the term or its text Collation.binary or Collation.asciiFold"),
964
- onSome: (each) => {
965
- if (each._tag === "Locale") fail(`is ordered by the backend's "${each.locale}" collation, which a call cannot carry`);
966
- }
967
- });
968
- };
969
- const Order = {
970
- /** Smallest first; rows without a value last, unless `nulls` says first. */
971
- asc: (expr, options) => term("asc", toExpr(expr, "asc"), options),
972
- /** Largest first; rows without a value first, unless `nulls` says last. */
973
- desc: (expr, options) => term("desc", toExpr(expr, "desc"), options),
974
- /**
975
- * The order the input names, among `choices`: every name the sort can hold
976
- * maps to a field or a call that orders, so a name left out is a type error
977
- * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
978
- * it decide.
979
- *
980
- * ```ts
981
- * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))
982
- * ```
983
- */
984
- chosen: (sort, choices) => {
985
- const fields = Object.create(null);
986
- for (const [name, choice] of Object.entries(choices)) {
987
- const expr = toExpr(choice, "chosen");
988
- if (expr._tag !== "Field" && expr._tag !== "Call") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is neither a field nor a call`);
989
- if (expr._tag === "Call") orderableCall(expr, expr.collation);
990
- fields[name] = expr;
991
- }
992
- return node({
993
- _tag: "Chosen",
994
- sort,
995
- choices: Object.freeze(fields)
996
- });
997
- }
998
- };
999
- const placeable = Object.freeze({ _tag: "Placeable" });
1000
- const notPlaceable = (reason) => Object.freeze({
1001
- _tag: "NotPlaceable",
1002
- reason
1003
- });
1004
- /**
1005
- * Whether values encoded by `ast` order the same everywhere: numbers and
1006
- * booleans, never text. A null among them does too: where it goes is said on
1007
- * every order term.
1008
- */
1009
- 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));
1010
- /** Why a term cannot be placed by a client running `operators`, if it cannot. */
1011
- const unplaceable = (orderTerm, operators) => Match.value(orderTerm.expr).pipe(Match.tag("Call", (call) => {
1012
- const missing = missingFrom(dependenciesOf(call).operators, operators);
1013
- return missing.length === 0 ? Option.none() : Option.some(`it orders by ${showExpr(call)}, and this client does not run ${missing.join(", ")}`);
1014
- }), Match.tag("Field", (field) => Option.match(orderTerm.collation, {
1015
- onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
1016
- onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
1017
- Binary: () => Option.none(),
1018
- AsciiFold: () => Option.none(),
1019
- Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
1020
- }))
1021
- })), Match.orElse(() => Option.some("it orders by something that is neither a field nor a call")));
1022
- /** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
1023
- const idTerms = /* @__PURE__ */ new WeakMap();
1024
- const idTermOf = (entity) => {
1025
- const known = idTerms.get(entity);
1026
- if (known !== void 0) return known;
1027
- const id = entity.fields.id;
1028
- if (id === void 0) throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`);
1029
- const tieBreak = term("asc", fieldExpr(id));
1030
- idTerms.set(entity, tieBreak);
1031
- return tieBreak;
1032
- };
1033
- /** The fixed term a chosen order is for one input, or none for a `null` sort. */
1034
- const chosenTerms = (chosen, input) => {
1035
- const sort = input[chosen.sort.key];
1036
- if (sort === null || sort === void 0) return [];
1037
- const picked = typeof sort === "object" && "by" in sort && typeof sort.by === "string" ? sort.by : void 0;
1038
- const direction = typeof sort === "object" && "direction" in sort ? sort.direction : void 0;
1039
- if (picked === void 0 || !Object.hasOwn(chosen.choices, picked) || direction !== "asc" && direction !== "desc") throw new Error(`[foldkit-entity] Order.chosen: $${chosen.sort.key} names no order it offers (${Object.keys(chosen.choices).join(", ")})`);
1040
- return [term(direction, chosen.choices[picked])];
1041
- };
1042
- /**
1043
- * Visits each node once. A node can be shared by several paths (`eq(n, n)`),
1044
- * and a walk that followed every path would take time exponential in the depth.
1045
- */
1046
- const walk = (expr, found) => {
1047
- if (found.seen.has(expr)) return;
1048
- found.seen.add(expr);
1049
- switch (expr._tag) {
1050
- case "Literal": return;
1051
- case "Field": {
1052
- const byKey = found.fields.get(expr.owner.token) ?? /* @__PURE__ */ new Map();
1053
- found.fields.set(expr.owner.token, byKey);
1054
- if (!byKey.has(expr.key)) {
1055
- const field = {
1056
- entity: expr.owner.name,
1057
- key: expr.key,
1058
- owner: expr.owner
1059
- };
1060
- byKey.set(expr.key, field);
1061
- found.order.push(field);
1062
- }
1063
- return;
1064
- }
1065
- case "Input":
1066
- found.inputs.add(expr.key);
1067
- return;
1068
- case "Next": {
1069
- found.operations.add("next");
1070
- const { field } = expr;
1071
- const byKey = found.next.get(field.owner.token) ?? /* @__PURE__ */ new Map();
1072
- found.next.set(field.owner.token, byKey);
1073
- if (!byKey.has(field.key)) {
1074
- const read = {
1075
- entity: field.owner.name,
1076
- key: field.key,
1077
- owner: field.owner
1078
- };
1079
- byKey.set(field.key, read);
1080
- found.nextOrder.push(read);
1081
- }
1082
- return;
1083
- }
1084
- case "Eq":
1085
- found.operations.add("eq");
1086
- walk(expr.left, found);
1087
- walk(expr.right, found);
1088
- return;
1089
- case "Null":
1090
- found.operations.add(expr.present ? "isNotNull" : "isNull");
1091
- walk(expr.operand, found);
1092
- return;
1093
- case "Contains":
1094
- found.operations.add("contains");
1095
- walk(expr.value, found);
1096
- walk(expr.search, found);
1097
- return;
1098
- case "In":
1099
- found.operations.add("in");
1100
- walk(expr.value, found);
1101
- walk(expr.among, found);
1102
- return;
1103
- case "And":
1104
- found.operations.add("and");
1105
- for (const operand of expr.operands) walk(operand, found);
1106
- return;
1107
- case "Or":
1108
- found.operations.add("or");
1109
- for (const operand of expr.operands) walk(operand, found);
1110
- return;
1111
- case "Not":
1112
- found.operations.add("not");
1113
- walk(expr.operand, found);
1114
- return;
1115
- case "Compare":
1116
- found.operations.add("compare");
1117
- walk(expr.left, found);
1118
- walk(expr.right, found);
1119
- return;
1120
- case "Term":
1121
- walk(expr.expr, found);
1122
- return;
1123
- case "Chosen":
1124
- walk(expr.sort, found);
1125
- for (const choice of Object.values(expr.choices)) walk(choice, found);
1126
- return;
1127
- case "Call":
1128
- case "Test":
1129
- found.operators.add(expr.operator);
1130
- Option.match(expansionOf(expr), {
1131
- onSome: (expansion) => walk(expansion, found),
1132
- onNone: () => expr.args.forEach((arg) => walk(arg, found))
1133
- });
1134
- return;
1135
- default: return absurd(expr);
1136
- }
1137
- };
1138
- /**
1139
- * What an expression reads and uses, for the planner and for an interpreter
1140
- * deciding whether it can run this query at all. Distinct entries only, in the
1141
- * order first seen, so the answer is stable enough to assert on.
1142
- */
1143
- const dependenciesOf = (...nodes) => {
1144
- const found = {
1145
- seen: /* @__PURE__ */ new Set(),
1146
- fields: /* @__PURE__ */ new Map(),
1147
- order: [],
1148
- inputs: /* @__PURE__ */ new Set(),
1149
- next: /* @__PURE__ */ new Map(),
1150
- nextOrder: [],
1151
- operations: /* @__PURE__ */ new Set(),
1152
- operators: /* @__PURE__ */ new Set()
1153
- };
1154
- for (const term of nodes) walk(term, found);
1155
- return {
1156
- fields: found.order,
1157
- next: found.nextOrder,
1158
- inputs: [...found.inputs],
1159
- operations: [...found.operations],
1160
- operators: [...found.operators]
1161
- };
1162
- };
1163
- /** Every field an expression reads, as the nodes themselves, each node visited once. */
1164
- const fieldsIn = function* (expr, seen) {
1165
- if (seen.has(expr)) return;
1166
- seen.add(expr);
1167
- switch (expr._tag) {
1168
- case "Field":
1169
- yield expr;
1170
- return;
1171
- case "Next":
1172
- yield expr.field;
1173
- return;
1174
- case "Literal":
1175
- case "Input": return;
1176
- case "Eq":
1177
- yield* fieldsIn(expr.left, seen);
1178
- yield* fieldsIn(expr.right, seen);
1179
- return;
1180
- case "Null":
1181
- yield* fieldsIn(expr.operand, seen);
1182
- return;
1183
- case "Contains":
1184
- yield* fieldsIn(expr.value, seen);
1185
- yield* fieldsIn(expr.search, seen);
1186
- return;
1187
- case "In":
1188
- yield* fieldsIn(expr.value, seen);
1189
- yield* fieldsIn(expr.among, seen);
1190
- return;
1191
- case "And":
1192
- case "Or":
1193
- for (const operand of expr.operands) yield* fieldsIn(operand, seen);
1194
- return;
1195
- case "Not":
1196
- yield* fieldsIn(expr.operand, seen);
1197
- return;
1198
- case "Compare":
1199
- yield* fieldsIn(expr.left, seen);
1200
- yield* fieldsIn(expr.right, seen);
1201
- return;
1202
- case "Term":
1203
- yield* fieldsIn(expr.expr, seen);
1204
- return;
1205
- case "Chosen":
1206
- for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
1207
- return;
1208
- case "Call":
1209
- case "Test":
1210
- for (const arg of expr.args) yield* fieldsIn(arg, seen);
1211
- return;
1212
- default: return absurd(expr);
1213
- }
1214
- };
1215
- /**
1216
- * A query reads one Entity, so a predicate or ordering term naming a different
1217
- * one cannot be answered — an interpreter would be asked for a column of a
1218
- * table it was never told to read. Compared by identity, not by name, because
1219
- * two Entities defined with the same name are two Entities.
1220
- */
1221
- const checkOwnership = (step, what, entity, nodes) => {
1222
- const seen = /* @__PURE__ */ new Set();
1223
- for (const term of nodes) for (const field of fieldsIn(term, seen)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
1224
- };
1225
- /**
1226
- * The most nodes a query's predicates may hold once every shared node is
1227
- * counted on each path that reaches it. Interpreters read a predicate as a
1228
- * tree: `evaluate` once per row, and the SQL compiler into text that repeats a
1229
- * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is
1230
- * thirty-one objects and a billion nodes of work. Real queries are tens.
1231
- */
1232
- const maxQueryNodes = 1e3;
1233
- const childrenOf = (expr) => {
1234
- switch (expr._tag) {
1235
- case "Literal":
1236
- case "Field":
1237
- case "Input":
1238
- case "Next": return [];
1239
- case "Eq": return [expr.left, expr.right];
1240
- case "Null": return [expr.operand];
1241
- case "Contains": return [expr.value, expr.search];
1242
- case "In": return [expr.value, expr.among];
1243
- case "And":
1244
- case "Or": return expr.operands;
1245
- case "Not": return [expr.operand];
1246
- case "Compare": return [expr.left, expr.right];
1247
- case "Call":
1248
- case "Test": return Option.match(expansionOf(expr), {
1249
- onSome: (expansion) => [expansion],
1250
- onNone: () => expr.args
1251
- });
1252
- }
1253
- };
1254
- /** A node's size as a tree, each distinct node sized once. */
1255
- const expandedSize = (expr, sizes) => {
1256
- const known = sizes.get(expr);
1257
- if (known !== void 0) return known;
1258
- const size = Math.min(1001, childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1));
1259
- sizes.set(expr, size);
1260
- return size;
1261
- };
1262
- const QueryProto = {
1263
- _tag: "Query",
1264
- pipe() {
1265
- return Pipeable.pipeArguments(this, arguments);
1266
- }
1267
- };
1268
- const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
1269
- entity,
1270
- where: Object.freeze(where),
1271
- orderBy: Object.freeze(orderBy)
1272
- }));
1273
- /**
1274
- * Refuses a query whose predicates and order terms (every chosen alternative
1275
- * among them) expand past `maxQueryNodes`, counting a shared node on every
1276
- * path that reaches it: what an interpreter walks, and SQL writes out.
1277
- */
1278
- const checkSize = (step, where, orderBy) => {
1279
- const sizes = /* @__PURE__ */ new Map();
1280
- const terms = orderBy.flatMap((ordering) => Match.valueTags(ordering, {
1281
- Term: ({ expr }) => [expr],
1282
- Chosen: ({ choices }) => Object.values(choices)
1283
- }));
1284
- if ([...where, ...terms].reduce((sum, each) => sum + expandedSize(each, sizes), 0) > 1e3) throw new Error(`[foldkit-entity] Query.${step}: the query expands to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`);
1285
- };
1286
- const Query = {
1287
- /** Every row of an Entity: the query each transformation narrows. */
1288
- from: (entity) => query(entity, [], []),
1289
- /**
1290
- * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
1291
- * second never replaces the first — so a fragment can be written once and
1292
- * piped into any query over the same Entity:
1293
- *
1294
- * ```ts
1295
- * const published = Query.where(Expr.eq(Post.fields.published, true))
1296
- * Query.from(Post).pipe(published, Query.where(byTitle))
1297
- * ```
1298
- */
1299
- where: (...predicates) => (self) => {
1300
- if (predicates.length === 0) return self;
1301
- checkOwnership("where", "a predicate", self.entity, predicates);
1302
- const where = [...self.where, ...predicates];
1303
- checkSize("where", where, self.orderBy);
1304
- return query(self.entity, where, self.orderBy);
1305
- },
1306
- /**
1307
- * Reads the rows in this order. Two `orderBy`s append, so an earlier term
1308
- * stays the more significant one and a later call adds a tie-breaker rather
1309
- * than silently winning.
1310
- */
1311
- orderBy: (...terms) => (self) => {
1312
- if (terms.length === 0) return self;
1313
- checkOwnership("orderBy", "a term", self.entity, terms);
1314
- const orderBy = [...self.orderBy, ...terms];
1315
- checkSize("orderBy", self.where, orderBy);
1316
- return query(self.entity, self.where, orderBy);
1317
- },
1318
- /**
1319
- * The fixed terms this query orders by for one input: each chosen order
1320
- * resolved to the field its input names, or to nothing for a `null` sort,
1321
- * and the Entity's id last, ascending, unless the terms already read it. So
1322
- * the order is total, and every interpreter breaks ties the same way: one
1323
- * that broke them its own way would place rows a step apart from another.
1324
- */
1325
- orderFor: (self, input) => {
1326
- const terms = self.orderBy.flatMap((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
1327
- Term: (term) => [term],
1328
- Chosen: (chosen) => chosenTerms(chosen, input)
1329
- })));
1330
- const id = idTermOf(self.entity);
1331
- return terms.some((term) => term.expr._tag === "Field" && term.expr.key === "id") ? terms : [...terms, id];
1332
- },
1333
- /**
1334
- * Whether a client can order this query's rows exactly as the server does,
1335
- * for one input: every term over a number or a boolean (a row may lack it), or over text with a
1336
- * portable collation (`binary`, `asciiFold`), or a call whose primitive
1337
- * operators the client's table (`operators`; none when not given) runs. A
1338
- * body that names no order leaves it to the server, and is never placeable.
1339
- */
1340
- placement: (self, input, options = {}) => {
1341
- if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
1342
- const operators = options.operators ?? noOperators;
1343
- for (const orderTerm of Query.orderFor(self, input)) {
1344
- const reason = unplaceable(orderTerm, operators);
1345
- if (Option.isSome(reason)) return notPlaceable(reason.value);
1346
- }
1347
- return placeable;
1348
- },
1349
- /**
1350
- * Each operator the body calls, by name (`id`, or `id@version` past the
1351
- * first), in the order it first calls them: a defined one, and each
1352
- * primitive one its expansion calls.
1353
- */
1354
- operators: (self) => Query.dependencies(self).operators.map(operatorName$1),
1355
- /**
1356
- * What the whole query reads: the fields and inputs of every predicate and
1357
- * every ordering term, and the operations it uses, with the fields also
1358
- * split by role.
1359
- */
1360
- dependencies: (self) => ({
1361
- ...dependenciesOf(...self.where, ...self.orderBy),
1362
- predicate: dependenciesOf(...self.where).fields,
1363
- order: dependenciesOf(...self.orderBy).fields
1364
- }),
1365
- /**
1366
- * The operations this query needs that `supported` does not list, in the
1367
- * order the query uses them, then each primitive operator `operators` does
1368
- * not implement, by name. Without `operators`, every primitive operator is
1369
- * named: a list of operations implements none. Empty means an interpreter
1370
- * declaring both can answer it.
1371
- *
1372
- * An interpreter declares what it runs and refuses the rest, rather than
1373
- * ignoring an operation it does not implement — which would answer a
1374
- * different question and say nothing. The refusal is the interpreter's to
1375
- * raise: this only says what is missing, because what to do about it differs
1376
- * between one that compiles at registration and one that runs a body
1377
- * directly.
1378
- *
1379
- * ```ts
1380
- * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
1381
- * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
1382
- * ```
1383
- */
1384
- unsupported: (self, supported, operators = noOperators) => unsupportedIn([...self.where, ...self.orderBy], supported, operators),
1385
- /**
1386
- * The whole query as readable text, one clause per line:
1387
- *
1388
- * ```text
1389
- * FROM Post
1390
- * WHERE Post.slug = $slug
1391
- * AND Post.published = true
1392
- * ORDER BY Post.updatedAt DESC
1393
- * ```
1394
- *
1395
- * For an explanation or a diagnostic, never for an interpreter — see
1396
- * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
1397
- * than printing an empty one, so what is shown is what was written.
1398
- */
1399
- show: (self) => [
1400
- `FROM ${self.entity.name}`,
1401
- ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Match.value(predicate).pipe(Match.tag("Or", (or) => self.where.length > 1 ? `(${Expr.show(or)})` : Expr.show(or)), Match.orElse((each) => Expr.show(each)))}`),
1402
- ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
1403
- Term: (term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,
1404
- Chosen: (chosen) => `$${chosen.sort.key} among (${Object.entries(chosen.choices).map(([name, field]) => `${name}: ${Expr.show(field)}`).join(", ")})`
1405
- }))).join(", ")}`]
1406
- ].join("\n")
1407
- };
1408
- /**
1409
- * An expression as readable text, in the IR's own terms.
1410
- *
1411
- * This is for a human — an explanation, a diagnostic, a test that wants to
1412
- * assert on a whole predicate at once — and deliberately **not** for an
1413
- * interpreter. It is close enough to SQL to read at a glance and unlike it
1414
- * everywhere that matters: an input is `$slug` rather than a bound parameter,
1415
- * `contains` is named rather than rendered as somebody's `like`, and no
1416
- * dialect's escaping or collation is implied. What actually ran is whatever
1417
- * that backend compiled, which is not this.
1418
- *
1419
- * A predicate standing where a value is wanted is parenthesised, because
1420
- * `x is not null = $archived` reads as three operands and is two. A predicate
1421
- * that *is* the whole expression is not: nothing encloses it.
1422
- */
1423
- const showExpr = (node) => {
1424
- switch (node._tag) {
1425
- case "Literal": return JSON.stringify(node.value) ?? String(node.value);
1426
- case "Field": return `${node.owner.name}.${node.key}`;
1427
- case "Input": return `$${node.key}`;
1428
- case "Next": return `next ${node.field.owner.name}.${node.field.key}`;
1429
- case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
1430
- case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
1431
- case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
1432
- case "In": return `${showOperand(node.value)} in ${showOperand(node.among)}`;
1433
- case "And": return node.operands.map(showConnected).join(" and ");
1434
- case "Or": return node.operands.map(showConnected).join(" or ");
1435
- case "Not": return `not (${showExpr(node.operand)})`;
1436
- case "Compare": return `${showOperand(node.left)} ${symbols[node.operator]} ${showOperand(node.right)}`;
1437
- case "Call":
1438
- case "Test": return `${operatorName$1(node.operator)}(${node.args.map(showOperand).join(", ")})`;
1439
- }
1440
- };
1441
- /** A call's expansion, scalar or predicate alike. */
1442
- const expansionOf = (call) => call.expansion;
1443
- /**
1444
- * What `nodes` need that an interpreter lacks: each kernel operation it does
1445
- * not list, then each primitive operator its table does not implement, by
1446
- * name. A defined operator needs nothing: what it means is walked instead.
1447
- */
1448
- const unsupportedIn = (nodes, supported, operators) => {
1449
- const read = dependenciesOf(...nodes);
1450
- const runs = new Set(supported);
1451
- return [...read.operations.filter((operation) => !runs.has(operation)), ...missingFrom(read.operators, operators)];
1452
- };
1453
- /**
1454
- * The primitive operators among `read` that `operators` does not implement, by
1455
- * name. A defined one needs nothing: what it means was walked into `read`.
1456
- */
1457
- const missingFrom = (read, operators) => read.filter((operator) => Option.isNone(operator.definedAs) && !operators.has(operator)).map((operator) => missingName(operator, operators));
1458
- /** An operator by its id, and its version when that is not the first. */
1459
- const operatorName$1 = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
1460
- const symbols = {
1461
- lt: "<",
1462
- lte: "<=",
1463
- gt: ">",
1464
- gte: ">="
1465
- };
1466
- /** An operand of `and` or `or`: another connective is parenthesised, so its grouping shows. */
1467
- const showConnected = (node) => Match.value(node).pipe(Match.tags({
1468
- And: () => `(${showExpr(node)})`,
1469
- Or: () => `(${showExpr(node)})`
1470
- }), Match.orElse(() => showExpr(node)));
1471
- const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
1472
- // src/tested.ts
1473
- /**
1474
- * What made each `Tested` record: `Conformance.laws` over one memory
1475
- * implementation, or `Conformance.lawsBy` through a runner. A table records
1476
- * only evidence of its own kind, so a record built by hand, copied, or tested
1477
- * on another implementation is refused. Kept beside the records rather than in
1478
- * them: a record is JSON a server publishes, and an implementation is a
1479
- * function. Not exported from the package.
1480
- */
1481
- const testedOn = /* @__PURE__ */ new WeakMap();
1482
- const ranByRunner = /* @__PURE__ */ new WeakSet();
1483
- const stampTested = (record, implementation) => {
1484
- testedOn.set(record, implementation);
1485
- };
1486
- const stampRun = (record) => {
1487
- ranByRunner.add(record);
1488
- };
1489
- const implementationTested = (record) => Option.fromUndefinedOr(testedOn.get(record));
1490
- const testedByRunner = (record) => ranByRunner.has(record);
1491
- // src/text.ts
1492
- /**
1493
- * The kernel's text operators: primitive, so each interpreter implements them,
1494
- * and each states what it means here, where data-query §6.0.1 holds the rest.
1495
- */
1496
- const Text = {
1497
- /**
1498
- * Whether the first text begins with the second, under the first's collation.
1499
- *
1500
- * | Case | Answer |
1501
- * | --- | --- |
1502
- * | either is null | unknown |
1503
- * | the prefix is `''` | true |
1504
- * | otherwise | whether it begins so, compared under the collation |
1505
- *
1506
- * The collation is the one its text operands share (a field's declared one,
1507
- * or a call's), or one given to the call. `binary` compares exactly;
1508
- * `asciiFold` folds ASCII letters on both sides. Operands declaring
1509
- * different collations, text with none, or a backend's locale are refused
1510
- * where the call is written.
1511
- * Prefixes are by character, so non-ASCII and astral text begin as they read.
1512
- *
1513
- * ```ts
1514
- * Query.where(Text.startsWith(Product.fields.upc, input.search))
1515
- * ```
1516
- */
1517
- startsWith: Expr.operator("text.startsWith", {
1518
- input: [Schema.NullOr(Schema.String), Schema.NullOr(Schema.String)],
1519
- output: Schema.Boolean,
1520
- collation: "required",
1521
- description: "Whether the first text begins with the second, under the first's collation."
1522
- }) };
1523
- // src/operators.ts
1524
- /**
1525
- * How the in-memory interpreter runs primitive operators: a table of
1526
- * implementations, passed to `evaluate` and every judge as a value. A table is
1527
- * immutable and implements each operator once; nothing registers anything
1528
- * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
1529
- */
1530
- const Evidence = Data.taggedEnum();
1531
- /** A JSON Schema document's root: an object (`$defs` holds what it refers to). */
1532
- const JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
1533
- /**
1534
- * An operator as JSON, by its signature and never its body (a defined
1535
- * operator says `defined`, not what it means): what a server can publish of
1536
- * what a body may call, and a client compare with what it runs. Its schemas
1537
- * are each argument's and the result's stored side, as JSON Schemas.
1538
- */
1539
- const OperatorDescription = Schema.Struct({
1540
- /** By id, and `@version` past the first: what tables, evidence and refusals name. */
1541
- name: Schema.String,
1542
- id: Schema.String,
1543
- version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
1544
- description: Schema.NullOr(Schema.String),
1545
- input: Schema.Array(JsonSchema),
1546
- output: JsonSchema,
1547
- nulls: Schema.Literals(["strict", "handled"]),
1548
- collation: Schema.Literals([
1549
- "none",
1550
- "operands",
1551
- "required"
1552
- ]),
1553
- laws: Schema.Array(LawDescription),
1554
- defined: Schema.Boolean
1555
- });
1556
- const described = (operator) => ({
1557
- name: nameOf(operator),
1558
- id: operator.id,
1559
- version: operator.version,
1560
- description: Option.getOrNull(operator.description),
1561
- input: operator.input.map(jsonSchemaOf),
1562
- output: jsonSchemaOf(operator.output),
1563
- nulls: operator.nulls,
1564
- collation: operator.collation,
1565
- laws: operator.laws.map(Law.describe),
1566
- defined: Option.isSome(operator.definedAs)
1567
- });
1568
- /** An operator by its id, and its version when that is not the first. */
1569
- const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
1570
- const fail$3 = (what) => {
1571
- throw new Error(`[foldkit-entity] Operators: ${what}`);
1572
- };
1573
- const table = (implementations, checked, evidence) => {
1574
- const byOperator = /* @__PURE__ */ new Map();
1575
- const byName = /* @__PURE__ */ new Map();
1576
- for (const { operator, run } of implementations) {
1577
- if (byOperator.has(operator)) fail$3(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
1578
- const named = byName.get(nameOf(operator));
1579
- if (named !== void 0 && named !== operator) fail$3(`two operators are named ${nameOf(operator)}; give one another id or version`);
1580
- byName.set(nameOf(operator), operator);
1581
- byOperator.set(operator, run);
1582
- }
1583
- return Object.freeze({
1584
- _tag: "MemoryOperators",
1585
- has: (operator) => byOperator.has(operator),
1586
- versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
1587
- get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
1588
- named: (name) => Option.fromUndefinedOr(byName.get(name)),
1589
- checked,
1590
- implementations: Object.freeze([...implementations]),
1591
- evidence: Object.freeze([...evidence])
1592
- });
1593
- };
1594
- /** Whether two laws, as JSON, are the same law. */
1595
- const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
1596
- /** An implementation, its operator's null rule checked against the function chosen for it. */
1597
- const implementation = (operator, nulls, run) => {
1598
- if (Option.isSome(operator.definedAs)) fail$3(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
1599
- 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`);
1600
- return Object.freeze({
1601
- operator,
1602
- run: (args, context) => run(...args, context)
1603
- });
1604
- };
1605
- const Operators = {
1606
- /**
1607
- * An implementation of a strict operator: a pure function of its arguments'
1608
- * stored values, never given a null (the kernel answers null, or unknown, for
1609
- * one first), and told the call's collation last.
1610
- *
1611
- * ```ts
1612
- * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
1613
- * ```
1614
- */
1615
- implement: (operator, run) => implementation(operator.descriptor, "strict", run),
1616
- /**
1617
- * An implementation of an operator declared `nulls: 'handled'`: given nulls
1618
- * as they are, it answers for them; a predicate answers `null` for unknown.
1619
- */
1620
- implementHandlingNulls: (operator, run) => implementation(operator.descriptor, "handled", run),
1621
- /** A table of implementations. One operator implemented twice, or two under one name, is refused. */
1622
- memory: (...implementations) => table(implementations, false, []),
1623
- /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
1624
- merge: (left, right) => {
1625
- const both = right.implementations.filter(({ operator }) => left.has(operator));
1626
- if (both.length > 0) fail$3(`both tables implement ${both.map(({ operator }) => nameOf(operator)).join(", ")}; replace with Operators.override`);
1627
- return table([...left.implementations, ...right.implementations], left.checked || right.checked, [...left.evidence, ...right.evidence]);
1628
- },
1629
- /**
1630
- * The table with these implementations in place of its own for the same
1631
- * operators. Evidence of a replaced implementation goes with it: it was
1632
- * that implementation's.
1633
- */
1634
- override: (base, ...implementations) => {
1635
- const replaced = new Set(implementations.map(({ operator }) => operator));
1636
- const names = new Set([...replaced].map(nameOf));
1637
- return table([...base.implementations.filter(({ operator }) => !replaced.has(operator)), ...implementations], base.checked, base.evidence.filter(({ operator, law }) => !names.has(operator) && !Law.witnessesNamed(law).some((name) => names.has(name))));
1638
- },
1639
- /**
1640
- * The table with what is known of its implementations' laws recorded: each
1641
- * record of an operator it implements and a law that operator declares.
1642
- * `Conformance.laws` gives `Tested` records, each of the implementation it
1643
- * ran, and a table takes only those of its own; `Evidence.Proven` says a
1644
- * proof elsewhere covers one.
1645
- */
1646
- withEvidence: (base, evidence) => {
1647
- const own = new Map(base.implementations.map((each) => [nameOf(each.operator), each]));
1648
- for (const record of evidence) {
1649
- const implemented = own.get(record.operator) ?? fail$3(`evidence names ${record.operator}, which this table does not implement`);
1650
- if (!implemented.operator.laws.map(Law.describe).some((law) => sameLaw(law, record.law))) fail$3(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`);
1651
- if (record._tag === "Tested" && !Option.exists(implementationTested(record), (tested) => tested === implemented)) fail$3(`evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`);
1652
- }
1653
- return table(base.implementations, base.checked, [...base.evidence, ...evidence]);
1654
- },
1655
- /**
1656
- * The memory implementation `Conformance.laws` tested a record on; none for
1657
- * a record of a runner (`Conformance.lawsBy`) or a proof.
1658
- */
1659
- testedOn: (record) => implementationTested(record),
1660
- /**
1661
- * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL
1662
- * table takes. Which runner it was, the database's or another, is the
1663
- * caller's word; a record built by hand, copied, or tested in memory is not.
1664
- */
1665
- testedByRunner,
1666
- /**
1667
- * Each operator the table implements, by name, with the laws it declares and
1668
- * the evidence the table records of them: what a server can publish of how
1669
- * it runs a body. JSON as it is.
1670
- */
1671
- describeTable: (base) => base.implementations.map(({ operator }) => ({
1672
- ...described(operator),
1673
- evidence: base.evidence.filter((record) => record.operator === nameOf(operator))
1674
- })),
1675
- /**
1676
- * An operator as JSON (`OperatorDescription`): its name, version and
1677
- * description, each argument's and its result's stored side as a JSON
1678
- * Schema (as JSON carries it: a number also admits the strings `"Infinity"`,
1679
- * `"-Infinity"` and `"NaN"`), its null and collation rules, its laws, and
1680
- * whether it is defined. Its signature, never its body.
1681
- */
1682
- describe: (operator) => described(operator.descriptor),
1683
- /**
1684
- * The table, checking every answer against its operator's output schema, so
1685
- * an implementation that answers the wrong kind fails where it answered. For
1686
- * tests: it costs a decode per call.
1687
- */
1688
- checked: (base) => table(base.implementations, true, base.evidence),
1689
- /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
1690
- kernel: table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
1691
- const [text, prefix, { collation }] = given;
1692
- return Option.exists(collation, (each) => each._tag === "AsciiFold") ? Collation.foldAscii(text).startsWith(Collation.foldAscii(prefix)) : text.startsWith(prefix);
1693
- })], false, [])
1694
- };
1695
- // src/evaluate.ts
1696
- /**
1697
- * The reference interpreter: a query body run over rows already in memory.
1698
- *
1699
- * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
1700
- * directly, which is what makes "source-neutral" a fact rather than a claim —
1701
- * the two are checked against each other over a real database, and a body that
1702
- * means one thing here and another there is a bug in one of them.
1703
- *
1704
- * It is also the interpreter to reach for when there is no database: a test
1705
- * that wants rows, a server assembling a page from values it already holds, or
1706
- * a client judging rows it already has.
1707
- *
1708
- * It lives in `foldkit-entity` because it is the **reference semantics** of the
1709
- * IR this package owns — what §6.0.1 means operationally rather than in prose —
1710
- * and a specification's reference implementation belongs with the
1711
- * specification. The rule that keeps it here: **it may depend on the IR and
1712
- * nothing else.** The moment it wants a Remote concept it has moved to the
1713
- * wrong place and should leave.
1714
- *
1715
- * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
1716
- * because SQL is what the other interpreter runs. The important case is null:
1717
- * `null = null` is unknown in SQL and a row is not matched by it, where
1718
- * JavaScript would happily call the two equal.
1719
- */
1720
- var QueryEvaluateError = class extends Error {
1721
- constructor(message) {
1722
- super(`[foldkit-entity] ${message}`);
1723
- this.name = "QueryEvaluateError";
1724
- }
1725
- };
1726
- /**
1727
- * A call of a primitive operator the table does not implement. Its own class,
1728
- * because a form judging an invariant reads it as a judgement it cannot make
1729
- * (`Undecided`), not as a failure.
1730
- */
1731
- var OperatorMissingError = class extends QueryEvaluateError {
1732
- operator;
1733
- /** The operator by its id, and its version past the first. */
1734
- named;
1735
- /** `operators`, the table that lacks it, names the versions of it that it does hold. */
1736
- constructor(operator, operators = noOperators) {
1737
- super(`this interpreter does not run the operator "${missingName(operator, operators)}"`);
1738
- this.name = "OperatorMissingError";
1739
- this.operator = operator;
1740
- this.named = operatorName(operator);
1741
- }
1742
- };
1743
- /** An operator by its id, and its version when that is not the first. */
1744
- const operatorName = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
1745
- const valueOf = (node, scope) => {
1746
- switch (node._tag) {
1747
- case "Field": return scope.row[node.key];
1748
- case "Next": return scope.next[node.field.key];
1749
- case "Literal": return node.value;
1750
- case "Input": return scope.input[node.key];
1751
- case "Call": return called(node, scope);
1752
- default: return absurd(node);
1753
- }
1754
- };
1755
- /**
1756
- * What a call comes to, as a value (a predicate's truth as SQL's, unknown as
1757
- * null). A defined operator's is what it means, as SQL compiles it; a
1758
- * primitive one's is the table's implementation, or it is refused by name.
1759
- */
1760
- const called = (call, scope) => {
1761
- const expansion = call.expansion;
1762
- return Option.match(expansion, {
1763
- onSome: (body) => sideOf(body, scope),
1764
- onNone: () => Option.match(scope.operators.get(call.operator), {
1765
- onSome: (run) => ran(call, run, scope),
1766
- onNone: () => {
1767
- throw new OperatorMissingError(call.operator, scope.operators);
1768
- }
1769
- })
1770
- });
1771
- };
1772
- /** A call of a primitive operator run, its arguments worked out over the scope. */
1773
- const ran = (call, run, scope) => runWith(call.operator, run, call.args.map((arg) => sideOf(arg, scope)), call.collation, call._tag === "Test", scope.operators.checked);
1774
- /**
1775
- * A primitive operator run over values: strict about null and NUL before it
1776
- * is asked, a throw it makes named as its own, and, in a checked table, its
1777
- * answer held to its output schema (a predicate's null is its unknown).
1778
- */
1779
- const runWith = (operator, run, values, collation, predicate, checked) => {
1780
- if (values.some(holdsNul)) throw new QueryEvaluateError(`the operator "${operatorName(operator)}" was given text holding a NUL character, which SQL text cannot hold portably`);
1781
- if (operator.nulls === "strict" && values.some(isNull)) return null;
1782
- let answer;
1783
- try {
1784
- answer = run(values.map((value) => value === void 0 ? null : value), { collation });
1785
- } catch (error) {
1786
- if (error instanceof QueryEvaluateError) throw error;
1787
- throw new QueryEvaluateError(`the operator "${operatorName(operator)}" failed: ${error instanceof Error ? error.message : String(error)}`);
1788
- }
1789
- if (checked && !(predicate && answer === null) && !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`);
1790
- return answer;
1791
- };
1792
- /**
1793
- * A primitive operator over stored values, as a call of it is run: what a
1794
- * computed assignment comes to (`Write.apply`). Refused, as a call is, when
1795
- * `operators` does not implement it.
1796
- */
1797
- const applyOperator = (operator, values, options) => Option.match(options.operators.get(operator), {
1798
- onNone: () => {
1799
- throw new OperatorMissingError(operator, options.operators);
1800
- },
1801
- onSome: (run) => runWith(operator, run, values, options.collation, SchemaAST.isBoolean(Schema.toEncoded(operator.output).ast), options.operators.checked)
1802
- });
1803
- /** A predicate operator's answer as a truth: null is unknown, anything but a boolean refused. */
1804
- const truthOf = (call, answer) => {
1805
- if (answer === null || answer === void 0) return "unknown";
1806
- if (typeof answer !== "boolean") throw new QueryEvaluateError(`the operator "${operatorName(call.operator)}" answered ${JSON.stringify(answer)}, which is not a truth`);
1807
- return answer;
1808
- };
1809
- const isNull = (value) => value === null || value === void 0;
1810
- const { foldAscii } = Collation;
1811
- const NUL = String.fromCharCode(0);
1812
- /**
1813
- * Whether `value` is text holding a NUL, which Postgres text cannot hold and
1814
- * SQLite compares only up to: no two interpreters agree on it.
1815
- */
1816
- const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
1817
- /** A predicate used as a value is its own truth; anything else is its value. */
1818
- const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
1819
- /**
1820
- * What an operand comes to over no row: a call of literals and inputs, run by
1821
- * `operators` (the kernel's when not given), a predicate as its truth with
1822
- * unknown as null. How a conformance check asks an implementation one
1823
- * question; refuses what `evaluate` refuses (an operator the table lacks,
1824
- * text holding NUL).
1825
- */
1826
- const valueOfOperand = (node, options = {}) => sideOf(node, {
1827
- row: {},
1828
- input: options.input ?? {},
1829
- next: {},
1830
- operators: options.operators ?? Operators.kernel
1831
- });
1832
- /**
1833
- * Refuses a value the query was given (a literal or an input) holding a NUL,
1834
- * before any null beside it can answer: SQL refuses such a parameter where it
1835
- * compiles, whatever the row holds. A NUL stored in a row is refused after,
1836
- * as SQL meets it only beside a value that is not null.
1837
- */
1838
- const refuseGivenNul = (message, sides) => {
1839
- if (sides.some(([side, value]) => !isPredicate(side) && (side._tag === "Literal" || side._tag === "Input") && holdsNul(value))) throw new QueryEvaluateError(message);
1840
- };
1841
- /**
1842
- * A predicate compared as a value. SQL's unknown is null there too, so an
1843
- * unknown compared to anything stays unknown rather than becoming false.
1844
- */
1845
- const truthValue = (truth) => truth === "unknown" ? null : truth;
1846
- const holds = (node, scope) => {
1847
- switch (node._tag) {
1848
- case "Test": return truthOf(node, called(node, scope));
1849
- case "Eq": {
1850
- const left = sideOf(node.left, scope);
1851
- const right = sideOf(node.right, scope);
1852
- const nul = "an equality was given text holding a NUL character, which SQL text cannot hold portably";
1853
- refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
1854
- if (isNull(left) || isNull(right)) return "unknown";
1855
- if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
1856
- return left === right;
1857
- }
1858
- case "Null": return isNull(valueOf(node.operand, scope)) !== node.present;
1859
- case "Contains": {
1860
- const value = valueOf(node.value, scope);
1861
- const search = sideOf(node.search, scope);
1862
- refuseGivenNul("a containment test was given text holding a NUL character, which SQL text cannot hold portably", [[node.search, search], [node.value, value]]);
1863
- if (isNull(value) || isNull(search)) return "unknown";
1864
- if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
1865
- if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
1866
- return foldAscii(value).includes(foldAscii(search));
1867
- }
1868
- case "In": {
1869
- const among = valueOf(node.among, scope);
1870
- if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
1871
- if (among.length === 0) return false;
1872
- const value = valueOf(node.value, scope);
1873
- 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");
1874
- if (isNull(value)) return "unknown";
1875
- if (among.some((each) => each === value)) return true;
1876
- return among.some(isNull) ? "unknown" : false;
1877
- }
1878
- case "And": {
1879
- const truths = node.operands.map((operand) => holds(operand, scope));
1880
- if (truths.includes(false)) return false;
1881
- return truths.includes("unknown") ? "unknown" : true;
1882
- }
1883
- case "Or": {
1884
- const truths = node.operands.map((operand) => holds(operand, scope));
1885
- if (truths.includes(true)) return true;
1886
- return truths.includes("unknown") ? "unknown" : false;
1887
- }
1888
- case "Not": {
1889
- const truth = holds(node.operand, scope);
1890
- return truth === "unknown" ? "unknown" : !truth;
1891
- }
1892
- case "Compare": {
1893
- const left = valueOf(node.left, scope);
1894
- const right = valueOf(node.right, scope);
1895
- const nul = "a comparison was given text holding a NUL character, which SQL text cannot hold portably";
1896
- refuseGivenNul(nul, [[node.left, left], [node.right, right]]);
1897
- if (isNull(left) || isNull(right)) return "unknown";
1898
- if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError(nul);
1899
- const kind = typeof left;
1900
- if (kind !== typeof right || kind !== "number" && kind !== "string") throw new QueryEvaluateError("a comparison was given values that do not order together");
1901
- const order = compare(left, right, node.collation);
1902
- return Match.value(node.operator).pipe(Match.when("lt", () => order < 0), Match.when("lte", () => order <= 0), Match.when("gt", () => order > 0), Match.when("gte", () => order >= 0), Match.exhaustive);
1903
- }
1904
- }
1905
- };
1906
- /** Whether a predicate reads a field, asked once per node: nodes are frozen. */
1907
- const readsAField = /* @__PURE__ */ new WeakMap();
1908
- /**
1909
- * A predicate's truth from the input alone, when it reads no field; none when
1910
- * it reads one. An interpreter that runs per request decides such a predicate
1911
- * before it builds anything: `isNull($status)` is known before any row is.
1912
- * Refuses what `evaluate` refuses (text holding a NUL).
1913
- */
1914
- const decided = (node, input, operators = Operators.kernel) => {
1915
- let reads = readsAField.get(node);
1916
- if (reads === void 0) {
1917
- const read = dependenciesOf(node);
1918
- reads = read.fields.length + read.next.length > 0;
1919
- readsAField.set(node, reads);
1920
- }
1921
- return reads ? Option.none() : Option.some(holds(node, {
1922
- row: {},
1923
- input,
1924
- next: {},
1925
- operators
1926
- }));
1927
- };
1928
- /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
1929
- const truthOver = (node, row, input = {}, next = {}, operators = Operators.kernel) => holds(node, {
1930
- row,
1931
- input,
1932
- next,
1933
- operators
1934
- });
1935
- /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
1936
- const matches = (body, row, input, operators) => body.where.every((node) => holds(node, {
1937
- row,
1938
- input,
1939
- next: {},
1940
- operators
1941
- }) === true);
1942
- /** The kinds of value this interpreter orders by; every key of one term must share one. */
1943
- const comparable = /* @__PURE__ */ new Set([
1944
- "string",
1945
- "number",
1946
- "boolean"
1947
- ]);
1948
- /**
1949
- * Text by code point, as SQLite's `BINARY` and Postgres's `"C"` compare it.
1950
- * JavaScript's `<` compares UTF-16 code units, which puts a character past
1951
- * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where
1952
- * every byte-ordered backend puts it after.
1953
- */
1954
- const byCodePoint = (left, right) => {
1955
- let i = 0;
1956
- let j = 0;
1957
- while (i < left.length && j < right.length) {
1958
- const a = left.codePointAt(i);
1959
- const b = right.codePointAt(j);
1960
- if (a !== b) return a < b ? -1 : 1;
1961
- i += a > 65535 ? 2 : 1;
1962
- j += b > 65535 ? 2 : 1;
1963
- }
1964
- return i < left.length ? 1 : j < right.length ? -1 : 0;
1965
- };
1966
- /** Two keys of one term, text by its collation (code point when none is declared). */
1967
- const compare = (left, right, collation) => {
1968
- if (typeof left === "string" && typeof right === "string") return Option.exists(collation, (declared) => declared._tag === "AsciiFold") ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right);
1969
- if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
1970
- return left - right;
1971
- };
1972
- /** Each term's key for one row: a field's value, or what a call comes to over the row. */
1973
- const keysOf = (row, terms, scope) => terms.map((term) => valueOf(term.expr, {
1974
- row,
1975
- input: scope.input,
1976
- next: {},
1977
- operators: scope.operators
1978
- }));
1979
- /**
1980
- * Refuses an ordering this interpreter will not answer for, before sorting, so
1981
- * the refusal names the first offending row in row order rather than whichever
1982
- * pair the engine's sort happened to compare first. Every term is checked over
1983
- * every row's keys: a key whose kind differs from the first present one's. A
1984
- * null key is not refused; the term says where it goes.
1985
- */
1986
- const checkOrder = (keys, terms, query) => terms.forEach((term, index) => {
1987
- 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`);
1988
- 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`);
1989
- let first;
1990
- for (const row of keys) {
1991
- const value = row[index];
1992
- if (isNull(value)) continue;
1993
- const kind = typeof value;
1994
- first ??= kind;
1995
- if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
1996
- }
1997
- });
1998
- /** Two rows' keys by checked terms: negative when `left` sorts first. */
1999
- const byTerms = (terms, left, right) => {
2000
- for (const [index, term] of terms.entries()) {
2001
- const absentLeft = isNull(left[index]);
2002
- const absentRight = isNull(right[index]);
2003
- if (absentLeft || absentRight) {
2004
- if (absentLeft && absentRight) continue;
2005
- return absentLeft === (term.nulls === "first") ? -1 : 1;
2006
- }
2007
- const sign = compare(left[index], right[index], term.collation);
2008
- if (sign !== 0) return term.direction === "asc" ? sign : -sign;
2009
- }
2010
- return 0;
2011
- };
2012
- const ordered = (rows, terms, query, scope) => {
2013
- if (terms.length === 0) return [...rows];
2014
- const keyed = rows.map((row) => ({
2015
- row,
2016
- keys: keysOf(row, terms, scope)
2017
- }));
2018
- checkOrder(keyed.map(({ keys }) => keys), terms, query);
2019
- return keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row);
2020
- };
2021
- /**
2022
- * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
2023
- * as `evaluate` sorts: negative when it comes first. A call among them runs
2024
- * over each row with `input` and `operators` (the kernel's when not given).
2025
- * Refuses what `evaluate` refuses, for these two rows: a term over neither a
2026
- * field nor a call, a locale collation, keys of different kinds, or an
2027
- * operator the table lacks. For a client placing one row among others it
2028
- * holds.
2029
- */
2030
- const compareRows = (terms, left, right, query, options = {}) => {
2031
- const scope = {
2032
- input: options.input ?? {},
2033
- operators: options.operators ?? Operators.kernel
2034
- };
2035
- const keys = [keysOf(left, terms, scope), keysOf(right, terms, scope)];
2036
- checkOrder(keys, terms, query);
2037
- return byTerms(terms, keys[0], keys[1]);
2038
- };
2039
- /**
2040
- * The operations this interpreter runs. It is the reference, so this is the
2041
- * whole kernel — but it is declared rather than assumed, because an
2042
- * interpreter that gains an operator and forgets to say so is exactly what
2043
- * `Query.unsupported` exists to catch.
2044
- */
2045
- const supported = [
2046
- "eq",
2047
- "isNull",
2048
- "isNotNull",
2049
- "contains",
2050
- "in",
2051
- "and",
2052
- "or",
2053
- "not",
2054
- "compare"
2055
- ];
2056
- /**
2057
- * Refuses a body needing an operation this interpreter does not run, rather
2058
- * than skipping it and answering a different question. Called by `evaluate`;
2059
- * call it directly to check a body once instead of on every run.
2060
- */
2061
- const assertSupported = (body, operators = Operators.kernel) => {
2062
- const missing = Query.unsupported(body, supported, operators);
2063
- if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
2064
- };
2065
- /**
2066
- * The rows the body matches, in the order it asks for. Pure: it reads the rows
2067
- * it is given and nothing else.
2068
- *
2069
- * `input` holds the values this run was given, by the keys the body's
2070
- * placeholders were built with — the same record the query would be called
2071
- * with anywhere else.
2072
- */
2073
- const evaluate = (body, input, rows, options = {}) => {
2074
- const operators = options.operators ?? Operators.kernel;
2075
- assertSupported(body, operators);
2076
- return ordered(rows.filter((row) => matches(body, row, input, operators)), Query.orderFor(body, input), body.entity.name, {
2077
- input,
2078
- operators
2079
- });
2080
- };
2081
- /**
2082
- * As `evaluate`, with each row judged alone: a row whose own values are
2083
- * refused (text holding a NUL, a value an operator fails on) is set aside in
2084
- * `refused` and the others are still answered. A client judging the rows it
2085
- * holds wants this, since one bad stored row says nothing about the rest.
2086
- *
2087
- * What no single row causes still refuses the run: an operation or operator
2088
- * the table lacks, an order by a locale collation, an input the body reads
2089
- * holding a NUL (every row would refuse, and no row is the cause), and order
2090
- * keys of different kinds across rows.
2091
- */
2092
- const evaluateEach = (body, input, rows, options = {}) => {
2093
- const operators = options.operators ?? Operators.kernel;
2094
- assertSupported(body, operators);
2095
- const terms = Query.orderFor(body, input);
2096
- const scope = {
2097
- input,
2098
- operators
2099
- };
2100
- const keyed = [];
2101
- const refused = [];
2102
- for (const row of rows) try {
2103
- if (matches(body, row, input, operators)) keyed.push({
2104
- row,
2105
- keys: keysOf(row, terms, scope)
2106
- });
2107
- } catch (error) {
2108
- if (!(error instanceof QueryEvaluateError) || givenNul(body, terms, input)) throw error;
2109
- refused.push(row);
2110
- }
2111
- checkOrder(keyed.map(({ keys }) => keys), terms, body.entity.name);
2112
- return {
2113
- matched: keyed.sort((left, right) => byTerms(terms, left.keys, right.keys)).map(({ row }) => row),
2114
- refused
2115
- };
2116
- };
2117
- /** Whether a constant or an input the body reads is text holding a NUL, or a list holding one. */
2118
- const givenNul = (body, terms, input) => Expr.givesNul(...body.where, ...terms.map((term) => term.expr)) || Query.dependencies(body).inputs.some((key) => {
2119
- const value = input[key];
2120
- return Array.isArray(value) ? value.some(holdsNul) : holdsNul(value);
2121
- });
2122
- // src/invariant.ts
2123
- /**
2124
- * Invariants: what every stored row of an Entity must hold, and what every
2125
- * change of one must, declared once on the Entity through its metadata and read
2126
- * from there by each interpreter: the reference judge here, a Schema check, a
2127
- * form, a server's writer.
2128
- *
2129
- * One is built over the row before a write (`before`, each field as `Expr.field`) and
2130
- * the row after it (`after`, each field as `Expr.next`). What it reads decides
2131
- * when it is judged:
2132
- *
2133
- * ```text
2134
- * reads `after` only -> a state invariant: every create and update, a CHECK constraint
2135
- * reads `before` too -> a transition invariant: every update, which has a row before
2136
- * ```
2137
- *
2138
- * It reads no input and no principal. Who may write is a guard's; whether a
2139
- * write applies now is its `when`'s.
2140
- */
2141
- const Invariants = Metadata.key("foldkit-entity/invariants", {
2142
- merge: (values) => [...new Set(values)],
2143
- summarize: (invariant) => invariant.id
2144
- });
2145
- /** Whether an invariant reads the row before, and so is judged only where there is one. */
2146
- const readsBefore = (held) => held.before.length > 0;
2147
- const fail$2 = (entity, message) => {
2148
- throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
2149
- };
2150
- const invariant = (id, build, options) => Object.assign((entity) => {
2151
- if (id.length === 0) fail$2(entity, "an invariant needs an id");
2152
- if (invariantsOf(entity).some((held) => held.id === id)) fail$2(entity, `"${id}" is declared twice`);
2153
- const fields = entity.fields;
2154
- const after = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]));
2155
- const predicate = build({
2156
- before: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)])),
2157
- after
2158
- });
2159
- const body = Query.from(entity).pipe(Query.where(predicate));
2160
- const dependencies = Query.dependencies(body);
2161
- if (dependencies.inputs.length > 0) fail$2(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
2162
- const beforeReads = dependencies.predicate.map((field) => field.key);
2163
- const afterReads = dependencies.next.map((field) => field.key);
2164
- if (afterReads.length === 0) fail$2(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
2165
- const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
2166
- for (const key of path) if (!Object.hasOwn(fields, key)) fail$2(entity, `"${id}"'s path names "${key}", not a field`);
2167
- return entity.pipe(Entity.annotate(Invariants.of(Object.freeze({
2168
- id,
2169
- predicate,
2170
- message: options.message,
2171
- path: Object.freeze([...path]),
2172
- before: Object.freeze(beforeReads),
2173
- after: Object.freeze(afterReads)
2174
- }))));
2175
- }, { id });
2176
- const invariantsOf = (entity) => Invariants.get(entity.metadata);
2177
- /** `judge` with the invariants given, as a binding that keeps them holds them. */
2178
- const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
2179
- const missing = /* @__PURE__ */ new Set();
2180
- const unrun = /* @__PURE__ */ new Set();
2181
- const failures = [];
2182
- const { after, before } = change;
2183
- for (const held of invariants) {
2184
- if (readsBefore(held) && before === void 0) continue;
2185
- const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
2186
- if (absent.length > 0) absent.forEach((key) => missing.add(key));
2187
- else try {
2188
- if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
2189
- } catch (error) {
2190
- if (!(error instanceof OperatorMissingError)) throw error;
2191
- unrun.add(error.named);
2192
- }
2193
- }
2194
- if (failures.length > 0) return {
2195
- _tag: "Invalid",
2196
- failures
2197
- };
2198
- if (missing.size > 0 || unrun.size > 0) return {
2199
- _tag: "Undecided",
2200
- fields: [...missing],
2201
- operators: [...unrun]
2202
- };
2203
- return { _tag: "Valid" };
2204
- };
2205
- /**
2206
- * A row, or a change, under every invariant (each row as the store holds it,
2207
- * encoded): valid only when each is true. SQL's unknown, from a null, fails
2208
- * one, as a `WHERE` drops the row; a field a row does not have leaves it
2209
- * undecided, never valid. Without `before` (a create), transition invariants
2210
- * are not judged.
2211
- */
2212
- const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
2213
- /**
2214
- * The row an input's value describes, judged under its Entity's state
2215
- * invariants: each key mapped to a field, encoded as the store holds it. An
2216
- * invariant over a field the input does not set (an `Option` holding nothing, a
2217
- * key left out) is undecided, so a partial input is never called valid on its
2218
- * account. It has no row before, so it judges no transition.
2219
- */
2220
- const judgeInput = (input, value, operators = Operators.kernel) => {
2221
- const invariants = invariantsOf(input.entity);
2222
- if (invariants.length === 0) return { _tag: "Valid" };
2223
- const members = input.members;
2224
- const row = {};
2225
- for (const [key, member] of Object.entries(members)) {
2226
- if (member._tag !== "Field" || !Object.hasOwn(value, key)) continue;
2227
- const encode = Schema.encodeUnknownOption(member.schema);
2228
- const given = value[key];
2229
- const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
2230
- const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
2231
- Option.map(Option.flatMap(held, () => stored), (encoded) => {
2232
- row[member.key] = encoded;
2233
- });
2234
- }
2235
- return judgeAgainst(invariants, { after: row }, operators);
2236
- };
2237
- /**
2238
- * The Entity's state invariants as an Effect Schema check over its row type:
2239
- * each failure at its path, with its message. The value is encoded first,
2240
- * field by field, so it is judged as the store would hold it.
2241
- */
2242
- const check = (entity, options = {}) => Schema.makeFilter((value) => {
2243
- const fields = entity.fields;
2244
- const decoded = value;
2245
- const row = {};
2246
- for (const [key, field] of Object.entries(fields)) {
2247
- if (!Object.hasOwn(decoded, key)) continue;
2248
- row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
2249
- }
2250
- const judged = judge(entity, { after: row }, options.operators);
2251
- if (judged._tag !== "Invalid") return void 0;
2252
- return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
2253
- path: [key],
2254
- issue: failure.message
2255
- })));
2256
- });
2257
- // src/readFilter.ts
2258
- /**
2259
- * The members a server filters an Entity's rows by under a rule the client
2260
- * does not run, such as an authorization rule. A client that places rows in
2261
- * a list judges membership by the list's body; a change to one of these
2262
- * members can move a row into or out of what the server lists, which only
2263
- * the server can say. Declared by whoever owns the rule (`foldkit-guard`
2264
- * attaches it), read by whoever places (`foldkit-remote`).
2265
- */
2266
- const key = Metadata.key("foldkit-entity/read-filter", {
2267
- merge: (lists) => [[...new Set(lists.flat())]],
2268
- summarize: (members) => members.join(", ")
2269
- });
2270
- const ReadFilter = {
2271
- /** Entity metadata: the rows the server lists depend on these members. */
2272
- of: (members) => key.of(members),
2273
- /** The members an Entity's metadata names, every attachment's together. */
2274
- members: (metadata) => key.get(metadata)[0] ?? []
2275
- };
2276
- // src/words.ts
2277
- const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
2278
- const Words = {
2279
- /**
2280
- * A schema's words, as a label and its help text. Under Effect 4 a checked
2281
- * schema resolves to its last check's annotations, which say what the check
2282
- * expects and carry no `title`, so a title given before the check is read from
2283
- * the schema's own annotations. Read words through this, never through
2284
- * `Schema.resolveAnnotations` directly.
2285
- */
2286
- of: (schema) => {
2287
- const resolved = Schema.resolveAnnotations(schema) ?? {};
2288
- const own = schema.ast.annotations ?? {};
2289
- return {
2290
- title: Option.orElse(text(resolved.title), () => text(own["title"])),
2291
- description: Option.orElse(text(resolved.description), () => text(own["description"]))
2292
- };
2293
- } };
2294
- // src/write.ts
2295
- /**
2296
- * A write as a value: what an operation changes, declared over the input it
2297
- * takes, so the changes can be known before it runs and its interpreters can
2298
- * agree on what it means.
2299
- *
2300
- * A `Write` is built on `Entity.input`, which already says which input key is
2301
- * which member of the Entity. `Write.update`, `Write.insert` and `Write.delete`
2302
- * add what to do with them: the key that names the row, and optionally the key
2303
- * holding the revision it was read at. Every other key mapped to a field is
2304
- * set; a key mapped to `Entity.unmapped` is about the operation and is not
2305
- * written.
2306
- *
2307
- * It is authority someone declared, never something derived from an Entity: an
2308
- * Entity having a field does not mean anyone may set it.
2309
- */
2310
- const Computation = Data.taggedEnum();
2311
- const update = (input, options) => settingSomething(declared("Update", input, options));
2312
- const remove = (input, options) => {
2313
- const write = declared("Delete", input, options);
2314
- const named = [...write.sets, ...write.links][0];
2315
- if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
2316
- return write;
2317
- };
2318
- const fail$1 = (input, message) => {
2319
- throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
2320
- };
2321
- const membersOf = (input) => input.members;
2322
- /** A field's value as the store holds it. A field's schema needs no service, so none is asked. */
2323
- const encoded = (field, value) => Schema.encodeUnknownSync(field.schema)(value);
2324
- /**
2325
- * A key's value as given, when it was: an absent key, and an `Option` that
2326
- * holds nothing, give none, and a `Some` what it holds. What `Entity.input`
2327
- * lets a key map itself to, a write can bind.
2328
- */
2329
- const given = (value) => {
2330
- if (value === void 0) return Option.none();
2331
- return Option.isOption(value) ? value : Option.some(value);
2332
- };
2333
- const fieldAt = (input, key, role) => {
2334
- const member = membersOf(input)[key];
2335
- if (member === void 0) return fail$1(input, `${role} "${key}" is not a key of the input`);
2336
- if (member._tag !== "Field") return fail$1(input, `${role} "${key}" is not mapped to a field`);
2337
- return member;
2338
- };
2339
- /**
2340
- * What every kind shares: the key naming the row, the expected revision, and
2341
- * what the other keys set or point. A kind adds its own checks.
2342
- */
2343
- const declared = (kind, input, options) => {
2344
- const id = fieldAt(input, options.id, "id");
2345
- if (id.key !== "id") fail$1(input, `id "${options.id}" is mapped to "${id.key}", not to "id"`);
2346
- const idSchema = input.schema.fields[options.id];
2347
- const takes = Schema.is(Schema.toType(idSchema));
2348
- if (SchemaAST.isOptional(idSchema.ast) || takes(void 0) || takes(Option.none())) fail$1(input, `id "${options.id}" may be absent, and a declared write names its row`);
2349
- if (options.expect === options.id) fail$1(input, "expect cannot be the id");
2350
- const expect = options.expect === void 0 ? void 0 : Object.freeze({
2351
- key: options.expect,
2352
- field: fieldAt(input, options.expect, "expect")
2353
- });
2354
- const sets = [];
2355
- const links = [];
2356
- for (const [key, member] of Object.entries(membersOf(input))) {
2357
- if (member === void 0 || key === options.id || key === options.expect) continue;
2358
- switch (member._tag) {
2359
- case "Field":
2360
- sets.push(Object.freeze({
2361
- key,
2362
- field: member
2363
- }));
2364
- break;
2365
- case "Unmapped": break;
2366
- case "RelationInput":
2367
- if (member.relation.cardinality !== "one") fail$1(input, `"${key}" is a many relation; a write points one relation at a time`);
2368
- links.push(Object.freeze({
2369
- key,
2370
- relation: member.relation
2371
- }));
2372
- break;
2373
- case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
2374
- }
2375
- }
2376
- const placeholders = Object.create(null);
2377
- for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
2378
- const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
2379
- return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
2380
- });
2381
- const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
2382
- expect,
2383
- sets
2384
- })]);
2385
- const fields = input.entity.fields;
2386
- const row = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)]));
2387
- const assignments = Object.entries(options.compute ?? {}).flatMap(([fieldKey, compute]) => compute === void 0 ? [] : [assignmentOf(input, fieldKey, () => compute({
2388
- row,
2389
- input: placeholders
2390
- }), {
2391
- expect,
2392
- sets,
2393
- increments
2394
- })]);
2395
- return Object.freeze({
2396
- _tag: kind,
2397
- input,
2398
- id: Object.freeze({
2399
- key: options.id,
2400
- field: id
2401
- }),
2402
- expect,
2403
- when,
2404
- sets: Object.freeze(sets),
2405
- increments: Object.freeze(increments),
2406
- assignments: Object.freeze(assignments),
2407
- links: Object.freeze(links)
2408
- });
2409
- };
2410
- /** The kind of one stored form, as far as an assignment must agree with its field. */
2411
- const storedKind = (ast) => {
2412
- if (SchemaAST.isNull(ast)) return "null";
2413
- const literal = SchemaAST.isLiteral(ast) ? typeof ast.literal : void 0;
2414
- if (SchemaAST.isNumber(ast) || literal === "number") return "number";
2415
- if (SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || literal === "string") return "text";
2416
- if (SchemaAST.isBoolean(ast) || literal === "boolean") return "boolean";
2417
- return "other";
2418
- };
2419
- /** Every kind a stored form may hold: a union's members' kinds. */
2420
- const storedKinds = (ast) => new Set(SchemaAST.isUnion(ast) ? ast.types.flatMap((member) => [...storedKinds(member)]) : [storedKind(ast)]);
2421
- /** The stored kinds a scalar may come to, by what it is. */
2422
- const kindsOf = (expr) => {
2423
- switch (expr._tag) {
2424
- case "Field": return storedKinds(Schema.toEncoded(expr.schema).ast);
2425
- case "Next": return storedKinds(Schema.toEncoded(expr.field.schema).ast);
2426
- case "Input": return storedKinds(Schema.toEncoded(expr.schema).ast);
2427
- case "Literal": return /* @__PURE__ */ new Set([expr.value === null ? "null" : typeof expr.value === "string" ? "text" : typeof expr.value]);
2428
- case "Call": return storedKinds(Schema.toEncoded(expr.operator.output).ast);
2429
- }
2430
- };
2431
- /**
2432
- * Whether `expr` may come to null: a nullable field or input, a null literal,
2433
- * an operator answering one, or a strict operator given an argument that may
2434
- * be null, which it answers with null.
2435
- */
2436
- const mayBeNull = (expr) => kindsOf(expr).has("null") || expr._tag === "Call" && expr.operator.nulls === "strict" && expr.args.some((arg) => !isPredicate(arg) && mayBeNull(arg));
2437
- /** Whether a predicate is anywhere in `expr`, which data carries only as a value. */
2438
- const holdsPredicate = (expr) => isPredicate(expr) || expr._tag === "Call" && expr.args.some(holdsPredicate);
2439
- /**
2440
- * One computed field, checked: a field of the Entity written by nothing else,
2441
- * computed from this Entity's row before the write and the input alone
2442
- * (never `Next`, so assignments do not depend on each other), to a value of
2443
- * the field's stored kind, with no predicate in it.
2444
- */
2445
- const assignmentOf = (input, fieldKey, compute, declared) => {
2446
- const fields = input.entity.fields;
2447
- const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
2448
- if (field === void 0) return fail$1(input, `computes "${fieldKey}", which is not a field`);
2449
- if (fieldKey === "id") return fail$1(input, "computes the id");
2450
- if (declared.expect?.field.key === fieldKey) return fail$1(input, `computes "${fieldKey}", the revision it expects`);
2451
- if (declared.sets.some((set) => set.field.key === fieldKey) || declared.increments.some((increment) => increment.field.key === fieldKey)) return fail$1(input, `computes "${fieldKey}", which the write also sets`);
2452
- const operand = compute();
2453
- const expr = isPredicate(operand) ? operand : Expr.expanded(operand);
2454
- if (isPredicate(expr) || holdsPredicate(expr)) return fail$1(input, `computes "${fieldKey}" with a predicate, which an assignment carries only as a value`);
2455
- const reads = dependenciesOf(expr);
2456
- if (reads.next.length > 0) return fail$1(input, `computes "${fieldKey}" from the row after the write, which an assignment never reads`);
2457
- const stranger = reads.fields.find((read) => read.owner.name !== input.entity.name);
2458
- if (stranger !== void 0) return fail$1(input, `computes "${fieldKey}" from ${stranger.owner.name}.${stranger.key}, another Entity's field`);
2459
- const stored = storedKinds(Schema.toEncoded(field.schema).ast);
2460
- const comes = [...kindsOf(expr)].filter((kind) => kind !== "null" && !stored.has(kind));
2461
- if (comes.length > 0) return fail$1(input, `computes "${fieldKey}" as ${comes.join(" or ")}, which it does not store`);
2462
- if (!stored.has("null") && mayBeNull(expr)) return fail$1(input, `computes "${fieldKey}" as possibly null, which it does not store`);
2463
- return Object.freeze({
2464
- field,
2465
- expr
2466
- });
2467
- };
2468
- /** An assignment's expression, bound to one input, as data. */
2469
- const computationOf = (write, expr, input) => {
2470
- switch (expr._tag) {
2471
- case "Field":
2472
- case "Next": return Computation.Field({ key: expr._tag === "Field" ? expr.key : expr.field.key });
2473
- case "Literal": return Computation.Value({ value: expr.value });
2474
- case "Input": return Computation.Value({ value: Schema.encodeUnknownSync(write.input.schema.fields[expr.key])(input[expr.key]) });
2475
- case "Call": return Computation.Call({
2476
- operator: expr.operator.version === 1 ? expr.operator.id : `${expr.operator.id}@${expr.operator.version}`,
2477
- args: expr.args.map((arg) => computationOf(write, arg, input)),
2478
- collation: Option.getOrNull(expr.collation)
2479
- });
2480
- }
2481
- };
2482
- /**
2483
- * What a computation comes to over `row`, the row before the write: none when
2484
- * the row lacks a field it reads, or `operators` lacks an operator it calls.
2485
- */
2486
- const computed = (computation, row, operators) => Computation.$match(computation, {
2487
- Field: ({ key }) => Object.hasOwn(row, key) ? Option.some(row[key]) : Option.none(),
2488
- Value: ({ value }) => Option.some(value),
2489
- Call: ({ operator, args, collation }) => Option.flatMap(operators.named(operator), (descriptor) => Option.map(Option.all(args.map((arg) => computed(arg, row, operators))), (values) => applyOperator(descriptor, values, {
2490
- collation: Option.fromNullOr(collation),
2491
- operators
2492
- })))
2493
- });
2494
- /** Whether a value's stored form is a plain number. */
2495
- const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
2496
- /** Whether a value's stored form is checked to be an integer. */
2497
- const storedAsInteger = (schema) => SchemaShape.holdsIntegers(Schema.toEncoded(schema).ast);
2498
- /**
2499
- * One increment, checked: a field of the Entity stored as a number, written
2500
- * by nothing else, moved by an unmapped input key whose value is a number, and
2501
- * an integer when the field is one.
2502
- */
2503
- const incrementOf = (input, fieldKey, key, declared) => {
2504
- const fields = input.entity.fields;
2505
- const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
2506
- if (field === void 0) return fail$1(input, `increments "${fieldKey}", which is not a field`);
2507
- if (fieldKey === "id") return fail$1(input, "increments the id");
2508
- if (declared.expect?.field.key === fieldKey) return fail$1(input, `increments "${fieldKey}", the revision it expects`);
2509
- if (declared.sets.some((set) => set.field.key === fieldKey)) return fail$1(input, `increments "${fieldKey}", which a key also sets`);
2510
- if (!storedAsNumber(field.schema)) return fail$1(input, `increments "${fieldKey}", which is not stored as a number`);
2511
- const member = membersOf(input)[key];
2512
- if (member === void 0) return fail$1(input, `"${key}" is not a key of the input`);
2513
- if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
2514
- const amount = input.schema.fields[key];
2515
- if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
2516
- const integer = storedAsInteger(amount);
2517
- if (storedAsInteger(field.schema) && !integer) return fail$1(input, `"${key}" may not be an integer, but "${fieldKey}" is one; give the amount Schema.Int`);
2518
- return Object.freeze({
2519
- key,
2520
- field,
2521
- integer
2522
- });
2523
- };
2524
- /** An update or an insert that would write nothing is refused where it is declared. */
2525
- const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 && write.assignments.length === 0 ? fail$1(write.input, "it sets no field") : write;
2526
- const Write = {
2527
- /**
2528
- * Sets, on the row whose id is the input's `id` key, every field the input
2529
- * maps a key to. `expect` names the key holding the revision the row was
2530
- * read at: an interpreter writes only a row still at that revision.
2531
- *
2532
- * ```ts
2533
- * const EditPost = Write.update(EditPostInput, { id: 'id' })
2534
- * ```
2535
- *
2536
- * A key mapped to a `one` relation (`Relation.input`) points the row at the
2537
- * id it holds. Refused where it is written: an `id` that is not the Entity's
2538
- * `id` field, a `many` relation or a nested key (not written by an update
2539
- * yet), or nothing to set.
2540
- *
2541
- * `when` is what the row must hold for the update to land, checked where it
2542
- * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
2543
- * does not hold of is refused as unmet.
2544
- *
2545
- * `compute` sets a field to what an expression comes to over the row before
2546
- * the write and the input, run where it commits
2547
- * (`{ label: ({ row }) => concat(row.title, ' draft') }`). It is refused for
2548
- * a field another key writes, an expression over the row after the write or
2549
- * another Entity, or one of a kind the field does not store.
2550
- */
2551
- update,
2552
- /**
2553
- * Inserts the row whose id is the input's `id` key, an id the client chose,
2554
- * with every field and `one` relation the input maps a key to. An insert
2555
- * expects no revision: there is no row to have read. A row already there
2556
- * under that id (a retry) is left as it is.
2557
- */
2558
- insert: (input, options) => {
2559
- return settingSomething(declared("Insert", input, options));
2560
- },
2561
- /**
2562
- * Deletes the row whose id is the input's `id` key, only while it is still at
2563
- * the revision `expect` names, when it names one. It sets nothing, so a key
2564
- * mapped to a member is refused where it is written. A row already gone (a
2565
- * retry) is gone. `when`, as an update's, is what the row must hold.
2566
- */
2567
- delete: remove,
2568
- /**
2569
- * The revision this input says the row was read at, encoded, with its field:
2570
- * what an interpreter writes only a row still at. None for a write that
2571
- * expects none.
2572
- */
2573
- expected: (write, value) => Option.map(Option.fromUndefinedOr(write.expect), ({ key, field }) => ({
2574
- field: field.key,
2575
- revision: encoded(field, value[key])
2576
- })),
2577
- /** The members any invocation may write: what a query reading none of them cannot be changed by. */
2578
- writes: (write) => [
2579
- ...write.sets.map((set) => set.field),
2580
- ...write.increments.map((increment) => increment.field),
2581
- ...write.assignments.map((assignment) => assignment.field),
2582
- ...write.links.map((link) => link.relation)
2583
- ],
2584
- /**
2585
- * The fields a write reads from the row it writes: those its `when` reads,
2586
- * each it increments, each its assignments read, and the revision it
2587
- * expects. What an interpreter must read, and what a startup check judges
2588
- * it could disclose.
2589
- */
2590
- reads: (write) => {
2591
- const fields = /* @__PURE__ */ new Map();
2592
- const add = (field) => fields.set(field.key, field);
2593
- Option.map(write.when, (body) => Query.dependencies(body).predicate.forEach((field) => add(field)));
2594
- write.increments.forEach((increment) => add(increment.field));
2595
- write.assignments.forEach((assignment) => dependenciesOf(assignment.expr).fields.forEach((field) => add(field)));
2596
- if (write.expect !== void 0) add(write.expect.field);
2597
- return [...fields.values()];
2598
- },
2599
- /**
2600
- * The row this input writes and its new values, encoded as the store holds
2601
- * them: the patch a client shows before the server answers. `keys`, when
2602
- * given, narrows it to those input keys (what an author changed); the rest of
2603
- * the input is still the whole, validated value.
2604
- */
2605
- bind: (write, value, keys) => {
2606
- const input = value;
2607
- const wanted = keys === void 0 ? void 0 : new Set(keys);
2608
- const asked = (key) => wanted === void 0 || wanted.has(key);
2609
- const values = {};
2610
- for (const { key, field } of write.sets) {
2611
- if (!asked(key)) continue;
2612
- Option.map(given(input[key]), (held) => {
2613
- values[field.key] = encoded(field, held);
2614
- });
2615
- }
2616
- const links = {};
2617
- for (const { key, relation } of write.links) {
2618
- if (!asked(key)) continue;
2619
- const target = relation.target();
2620
- links[relation.key] = Option.map(Option.flatMap(given(input[key]), Option.fromNullishOr), (id) => ({
2621
- entity: target.name,
2622
- id: String(encoded(target.fields.id, id))
2623
- }));
2624
- }
2625
- const increments = {};
2626
- for (const { key, field } of write.increments) {
2627
- if (!asked(key)) continue;
2628
- const schema = write.input.schema.fields[key];
2629
- Option.map(given(input[key]), (held) => {
2630
- increments[field.key] = Schema.encodeUnknownSync(schema)(held);
2631
- });
2632
- }
2633
- const assignments = {};
2634
- for (const { field, expr } of write.assignments) assignments[field.key] = computationOf(write, expr, input);
2635
- return {
2636
- entity: write.input.entity.name,
2637
- id: String(encoded(write.id.field, input[write.id.key])),
2638
- values,
2639
- links,
2640
- increments,
2641
- assignments
2642
- };
2643
- },
2644
- /**
2645
- * The fields of the row before it that a bound write's amounts and
2646
- * assignments read: what to read to work out the row it leaves.
2647
- */
2648
- boundReads: (bound) => {
2649
- const keys = new Set(Object.keys(bound.increments));
2650
- const walk = (computation) => Computation.$match(computation, {
2651
- Field: ({ key }) => void keys.add(key),
2652
- Value: () => void 0,
2653
- Call: ({ args }) => args.forEach(walk)
2654
- });
2655
- Object.values(bound.assignments).forEach(walk);
2656
- return [...keys];
2657
- },
2658
- /**
2659
- * The row a bound write leaves over `row`, the row before it: its values
2660
- * set, each amount added (a null stays null, as in SQL), and each
2661
- * assignment computed by `operators` over the row before. `unknown` names
2662
- * each field it could not work out: one `row` lacks, or holds as no number
2663
- * for an amount, or an assignment calling an operator the table lacks. That
2664
- * field keeps what `row` holds. The one computation of this row: a guard
2665
- * judges it, a writer explains a miss with it, a client predicts it.
2666
- */
2667
- apply: (row, bound, options) => {
2668
- const after = {
2669
- ...row,
2670
- ...bound.values
2671
- };
2672
- const unknown = [];
2673
- for (const [field, amount] of Object.entries(bound.increments)) {
2674
- const held = Object.hasOwn(row, field) ? row[field] : void 0;
2675
- if (held === null) after[field] = null;
2676
- else if (typeof held === "number") after[field] = held + amount;
2677
- else unknown.push(field);
2678
- }
2679
- for (const [field, computation] of Object.entries(bound.assignments)) Option.match(computed(computation, row, options.operators), {
2680
- onNone: () => unknown.push(field),
2681
- onSome: (value) => {
2682
- after[field] = value;
2683
- }
2684
- });
2685
- return {
2686
- row: after,
2687
- unknown
2688
- };
2689
- }
2690
- };
2691
- // src/index.ts
2692
- /**
2693
- * `foldkit-entity` — domain structure as typed values.
2694
- *
2695
- * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
2696
- * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
2697
- * values an interpreter supplies). It describes; it fetches, stores, and
2698
- * renders nothing. Remote, Drizzle, and form packages interpret it and attach
2699
- * what they need as `foldkit-metadata`.
2700
- */
2701
- const EntityTypeId = Symbol.for("foldkit-entity/Entity");
2702
- const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
2703
- const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
2704
- /** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
2705
- const idSchemaOf = (entity) => {
2706
- const id = entity.fields.id;
2707
- if (id === void 0 || id._tag !== "Field") return Schema.String;
2708
- const type = Schema.toType(id.schema);
2709
- return SchemaShape.isText(type.ast) ? type : Schema.String;
2710
- };
2711
- const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
2712
- const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
2713
- const unmapped = Object.freeze({ _tag: "Unmapped" });
2714
- const EntityProto = {
2715
- [EntityTypeId]: EntityTypeId,
2716
- pipe() {
2717
- return Pipeable.pipeArguments(this, arguments);
2718
- }
2719
- };
2720
- const make = (parts) => Object.freeze(Object.assign(Object.create(EntityProto), parts, {
2721
- name: parts.identity.name,
2722
- fields: Object.freeze(parts.fields),
2723
- relations: Object.freeze(parts.relations),
2724
- derived: Object.freeze(parts.derived),
2725
- members: Object.freeze({
2726
- ...parts.fields,
2727
- ...parts.relations,
2728
- ...parts.derived
2729
- })
2730
- }));
2731
- const isSameEntity = (left, right) => left.identity.token === right.identity.token;
2732
- const fail = (entity, message) => {
2733
- throw new Error(`Entity "${entity.name}": ${message}`);
2734
- };
2735
- const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
2736
- const kindName = {
2737
- Field: "field",
2738
- Relation: "relation",
2739
- Derived: "derived member"
2740
- };
2741
- const kindOf = (entity, key) => {
2742
- const member = entity.members[key];
2743
- return member && kindName[member._tag];
2744
- };
2745
- const assertFree = (entity, keys, adding) => {
2746
- for (const key of keys) {
2747
- const kind = kindOf(entity, key);
2748
- if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
2749
- }
2750
- };
2751
- const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
2752
- const Entity = {
2753
- /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
2754
- define: (name, schema) => {
2755
- const identity = Object.freeze({
2756
- name,
2757
- token: Symbol(name)
2758
- });
2759
- return make({
2760
- identity,
2761
- schema,
2762
- fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
2763
- _tag: "Field",
2764
- owner: identity,
2765
- key,
2766
- schema: fieldSchema,
2767
- metadata: Metadata.empty
2768
- })),
2769
- relations: {},
2770
- derived: {},
2771
- metadata: Metadata.empty
2772
- });
2773
- },
2774
- /**
2775
- * Declares the relations between a set of Entities in one step, and returns
2776
- * them related. One step, because Entities that point at each other cannot
2777
- * each be declared in terms of the other.
2778
- */
2779
- relate: (entities, relations) => {
2780
- const keyByToken = /* @__PURE__ */ new Map();
2781
- for (const [key, entity] of Object.entries(entities)) {
2782
- if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
2783
- const earlier = keyByToken.get(entity.identity.token);
2784
- if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
2785
- keyByToken.set(entity.identity.token, key);
2786
- }
2787
- const given = relations;
2788
- for (const owner of Object.keys(given)) if (!(owner in entities)) throw new Error(`Entity.relate: relations given for "${owner}", which is not being related`);
2789
- const related = {};
2790
- for (const [ownerKey, entity] of Object.entries(entities)) {
2791
- const specs = given[ownerKey] ?? {};
2792
- assertFree(entity, Object.keys(specs), "relation");
2793
- const added = mapValues(specs, (spec, key) => {
2794
- const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
2795
- if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
2796
- return Object.freeze({
2797
- _tag: "Relation",
2798
- owner: entity.identity,
2799
- key,
2800
- target: () => related[targetKey],
2801
- cardinality: spec.cardinality,
2802
- optional: spec.optional,
2803
- metadata: Metadata.empty
2804
- });
2805
- });
2806
- related[ownerKey] = make({
2807
- ...entity,
2808
- relations: {
2809
- ...entity.relations,
2810
- ...added
2811
- }
2812
- });
2813
- }
2814
- return Object.freeze(related);
2815
- },
2816
- /**
2817
- * Selects members of an Entity and assembles the schema of the result. A
2818
- * relation selected with `true` yields an `EntityRef`; with a Selection of its
2819
- * target, that Selection's value. `many` yields an array, an optional `one`
2820
- * is nullable.
2821
- */
2822
- select: (entity, spec) => {
2823
- const members = entity.members;
2824
- const fields = mapValues(spec, (selected, key) => {
2825
- const member = members[key];
2826
- if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
2827
- if (member._tag !== "Relation") {
2828
- if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
2829
- return member.schema;
2830
- }
2831
- const target = member.target();
2832
- if (isSelectionPage(selected)) {
2833
- if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
2834
- if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
2835
- return Schema.Struct({
2836
- items: Schema.Array(selected.selection.schema),
2837
- hasNext: Schema.Boolean,
2838
- hasPrevious: Schema.Boolean
2839
- });
2840
- }
2841
- let item;
2842
- if (selected === true) item = Schema.Struct({
2843
- entity: Schema.Literal(target.name),
2844
- id: idSchemaOf(target)
2845
- });
2846
- else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
2847
- else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
2848
- return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
2849
- });
2850
- return Object.freeze({
2851
- [SelectionTypeId]: SelectionTypeId,
2852
- entity,
2853
- members: spec,
2854
- schema: Schema.Struct(fields)
2855
- });
2856
- },
2857
- /**
2858
- * A `many` relation read a page at a time, in place of its Selection:
2859
- * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
2860
- * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
2861
- */
2862
- page: (selection, window) => {
2863
- const sides = [window.first, window.last].filter((size) => size !== void 0);
2864
- if (sides.length !== 1 || !sides.every((size) => Number.isInteger(size) && size >= 0)) throw new Error(`Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`);
2865
- if (window.first !== void 0 && window.before !== void 0 || window.last !== void 0 && window.after !== void 0) throw new Error(`Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`);
2866
- return Object.freeze({
2867
- [SelectionPageTypeId]: SelectionPageTypeId,
2868
- selection,
2869
- window
2870
- });
2871
- },
2872
- /** Adds readable members that are not part of `entity.schema`. */
2873
- derived: (specs) => (entity) => {
2874
- assertFree(entity, Object.keys(specs), "derived member");
2875
- const added = mapValues(specs, (spec, key) => Object.freeze({
2876
- _tag: "Derived",
2877
- owner: entity.identity,
2878
- key,
2879
- schema: spec.schema,
2880
- metadata: Metadata.empty
2881
- }));
2882
- return make({
2883
- ...entity,
2884
- derived: {
2885
- ...entity.derived,
2886
- ...added
2887
- }
2888
- });
2889
- },
2890
- /** Attaches an interpreter's metadata to the Entity itself. */
2891
- annotate: (metadata) => (entity) => make({
2892
- ...entity,
2893
- metadata: Metadata.combine([entity.metadata, metadata])
2894
- }),
2895
- /**
2896
- * Declares what every stored row, or every change of one, must hold:
2897
- * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
2898
- * Expr.lte(after.reserved, after.quantity), { message })` over the row a
2899
- * write leaves, or with `before` too over the change an update makes.
2900
- * Refused where it is declared: an id declared twice, a predicate over another
2901
- * Entity, one reading an input or nothing of `after` (that is a `when`), a path
2902
- * naming no field.
2903
- */
2904
- invariant,
2905
- /** The Entity's invariants, in the order they were declared. */
2906
- invariants: invariantsOf,
2907
- /**
2908
- * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
2909
- * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
2910
- * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
2911
- * one reads that a row lacks.
2912
- */
2913
- judge,
2914
- /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
2915
- readsBefore,
2916
- /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
2917
- judgeAgainst,
2918
- /**
2919
- * The row an `Entity.input`'s value describes, judged: what a form can say
2920
- * before the server does. Undecided for an invariant over a field it leaves unset.
2921
- */
2922
- judgeInput,
2923
- /** The state invariants as a Schema check over the row type, each failure at its path. */
2924
- check,
2925
- /** Attaches an interpreter's metadata to members, by key. */
2926
- annotateMembers: (metadata) => (entity) => {
2927
- const given = metadata;
2928
- for (const key of Object.keys(given)) if (kindOf(entity, key) === void 0) throw new Error(`Entity "${entity.name}": cannot annotate "${key}", it is not a member`);
2929
- const annotate = (members) => mapValues(members, (member, key) => {
2930
- const extra = given[key];
2931
- return extra === void 0 ? member : Object.freeze({
2932
- ...member,
2933
- metadata: Metadata.combine([member.metadata, extra])
2934
- });
2935
- });
2936
- return make({
2937
- ...entity,
2938
- fields: annotate(entity.fields),
2939
- relations: annotate(entity.relations),
2940
- derived: annotate(entity.derived)
2941
- });
2942
- },
2943
- /**
2944
- * Reads an operation's input schema against an Entity. A key that names a
2945
- * field maps to it; any other key is mapped explicitly, to a Field, to
2946
- * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
2947
- * from a naming convention such as `authorId`.
2948
- */
2949
- input: (entity, schema, ...mapping) => {
2950
- const written = mapping[0] ?? {};
2951
- for (const key of Object.keys(written)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
2952
- const named = (key, name) => {
2953
- const member = entity.members[name];
2954
- switch (member?._tag) {
2955
- case "Field": return member;
2956
- case "Relation": return Object.freeze({
2957
- _tag: "RelationInput",
2958
- relation: member
2959
- });
2960
- case "Derived":
2961
- case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
2962
- }
2963
- };
2964
- const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
2965
- const fields = entity.fields;
2966
- const members = mapValues(schema.fields, (_, key) => {
2967
- const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
2968
- const owned = member._tag === "Field" ? member : member._tag === "RelationInput" || member._tag === "NestedInput" ? member.relation : member._tag === "Unmapped" ? void 0 : fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`);
2969
- if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
2970
- if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
2971
- return member;
2972
- });
2973
- return Object.freeze({
2974
- entity,
2975
- schema,
2976
- members: Object.freeze(members)
2977
- });
2978
- },
2979
- /** For an input key that is about the operation rather than the Entity. */
2980
- unmapped,
2981
- /**
2982
- * The schemas of some of an Entity's fields, by key, to spread into an input's
2983
- * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
2984
- * The input then keeps the field's own rules, and its keys map themselves.
2985
- */
2986
- fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
2987
- /**
2988
- * The Selection of every member an input writes, with each relation as refs:
2989
- * what an edit screen loads before it shows the input's current values.
2990
- */
2991
- selectFor: (input) => {
2992
- const members = input.members;
2993
- const spec = Object.fromEntries(Object.values(members).flatMap((member) => member._tag === "Field" ? [[member.key, true]] : member._tag === "RelationInput" ? [[member.relation.key, true]] : member._tag === "NestedInput" ? [[member.relation.key, Entity.selectFor(member.input)]] : []));
2994
- return Entity.select(input.entity, spec);
2995
- },
2996
- /**
2997
- * The input values that reproduce `value`, a value read through `selectFor`
2998
- * (or any Selection with those members): a field as it is, a relation as the
2999
- * id or ids of its refs. A key whose member `value` lacks is left out, as is
3000
- * an unmapped key, which the Entity knows nothing about.
3001
- */
3002
- valuesFor: (input, value) => {
3003
- const members = input.members;
3004
- const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
3005
- const entries = Object.entries(members).flatMap(([key, member]) => {
3006
- if (member._tag === "Unmapped") return [];
3007
- const written = member._tag === "Field" ? member.key : member.relation.key;
3008
- if (!(written in value)) return [];
3009
- const read = value[written];
3010
- switch (member._tag) {
3011
- case "Field": return [[key, read]];
3012
- case "NestedInput": {
3013
- const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
3014
- return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
3015
- }
3016
- case "RelationInput": {
3017
- const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
3018
- return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
3019
- }
3020
- }
3021
- });
3022
- return Object.fromEntries(entries);
3023
- },
3024
- is: isEntity,
3025
- /** True when both descriptors are versions of one Entity. */
3026
- same: isSameEntity
3027
- };
3028
- function one(target, options) {
3029
- return {
3030
- target,
3031
- cardinality: "one",
3032
- optional: options?.optional ?? false
3033
- };
3034
- }
3035
- /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
3036
- const Relation = {
3037
- one,
3038
- /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
3039
- input: (relation) => Object.freeze({
3040
- _tag: "RelationInput",
3041
- relation
3042
- }),
3043
- /**
3044
- * For `Entity.input`: the input key holds the relation's target itself, written
3045
- * through `input`, an `Entity.input` of the target. A `many` holds a list.
3046
- */
3047
- nested: (relation, input) => Object.freeze({
3048
- _tag: "NestedInput",
3049
- relation,
3050
- input
3051
- }),
3052
- many: (target) => ({
3053
- target,
3054
- cardinality: "many",
3055
- optional: false
3056
- })
3057
- };
3058
- const Derived = { make: (schema) => ({ schema }) };
3059
- export { Query as A, OperatorDescription as C, stampTested as D, stampRun as E, noOperators as F, Law as I, LawDescription as L, isPredicate as M, maxQueryNodes as N, Expr as O, missingName as P, SchemaShape as R, Evidence as S, Text as T, evaluate as _, SelectionPageTypeId as a, truthOver as b, Write as c, OperatorMissingError as d, QueryEvaluateError as f, decided as g, compareRows as h, Relation as i, dependenciesOf as j, Order as k, Words as l, assertSupported as m, Entity as n, SelectionTypeId as o, applyOperator as p, EntityTypeId as r, Computation as s, Derived as t, ReadFilter as u, evaluateEach as v, Operators as w, valueOfOperand as x, supported as y, Collation as z };
3060
-
3061
- //# sourceMappingURL=src-DBAilaDV.mjs.map