foldkit-entity 0.6.0 → 0.8.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.
@@ -0,0 +1,1332 @@
1
+ import { Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
+ import { Metadata } from "foldkit-metadata";
3
+ //#region src/shape.ts
4
+ const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
5
+ const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
6
+ /** What a schema's AST holds, read through Effect's own guards. */
7
+ const SchemaShape = {
8
+ /** True for the `null` and `undefined` members that make a schema optional. */
9
+ isNullish,
10
+ /**
11
+ * The members of a schema with `null` and `undefined` set aside, so optional
12
+ * text is still text; a schema that is not a union is its one member.
13
+ */
14
+ present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
15
+ /** True when every value the schema admits is a string. */
16
+ isText
17
+ };
18
+ //#endregion
19
+ //#region src/collation.ts
20
+ /**
21
+ * How text compares when a query orders by it, declared rather than left to
22
+ * the backend. Left unsaid, SQLite compares bytes, Postgres follows the
23
+ * database's locale and a JavaScript sort follows UTF-16 code units, so the
24
+ * same body could order the same rows three ways. A declared collation is one
25
+ * every interpreter that can honour it compiles to the same order, and one
26
+ * that cannot refuses.
27
+ *
28
+ * It is a trait of a field (`Entity.annotateMembers({ title: Collation.of(
29
+ * Collation.binary) })`), so most queries declare nothing; an order term may
30
+ * override it (`Order.asc(field, { collation })`).
31
+ */
32
+ const key$1 = Metadata.key("foldkit-entity/collation", {
33
+ merge: (collations) => collations.slice(-1),
34
+ summarize: (collation) => collation._tag
35
+ });
36
+ /** A collation name a backend can be told, and nothing that could be read as SQL. */
37
+ const localeName = /^[A-Za-z0-9_.@-]{1,64}$/;
38
+ const Collation = {
39
+ binary: Object.freeze({ _tag: "Binary" }),
40
+ asciiFold: Object.freeze({ _tag: "AsciiFold" }),
41
+ locale: (locale) => {
42
+ if (!localeName.test(locale)) throw new Error(`[foldkit-entity] Collation.locale: "${locale}" is not a collation name`);
43
+ return Object.freeze({
44
+ _tag: "Locale",
45
+ locale
46
+ });
47
+ },
48
+ /** Member metadata: how a text field orders, wherever a query orders by it. */
49
+ of: (collation) => key$1.of(collation),
50
+ /** The collation a member's metadata declares, if any. */
51
+ declared: (metadata) => Option.fromUndefinedOr(key$1.get(metadata)[0])
52
+ };
53
+ //#endregion
54
+ //#region src/expr.ts
55
+ /**
56
+ * `Expr` — a query's scalar computations as typed values.
57
+ *
58
+ * An Entity says what a domain has; an `Expr` says something about one row of
59
+ * it. A field reference, an input placeholder, a literal, and comparisons of
60
+ * those are all immutable data: building one performs no work, reads nothing,
61
+ * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
62
+ * to SQL, an in-memory evaluator to a predicate over rows.
63
+ *
64
+ * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
65
+ * operation here is one a real query in this repository needs; the set grows
66
+ * from queries, not from what a database could express.
67
+ */
68
+ const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
69
+ /**
70
+ * An Entity's field and a `FieldExpr` are the same three members under the same
71
+ * tag — the Entity's carries `metadata` besides — so this reads either and is
72
+ * idempotent on its own output. Nothing needs to tell them apart, which is
73
+ * better than telling them apart by which extra member happens to be present.
74
+ */
75
+ /**
76
+ * Every node is frozen as it is made, so a query built from it stays the value
77
+ * it was when `Query.where` checked it: nothing can swap a field or a literal
78
+ * in afterwards. It also means no node can come to contain itself. A literal's
79
+ * own payload is the caller's; the kernel compares scalars.
80
+ */
81
+ const node = (value) => Object.freeze(value);
82
+ const literal = (value) => node({
83
+ _tag: "Literal",
84
+ value
85
+ });
86
+ const fieldExpr = (field) => node({
87
+ _tag: "Field",
88
+ owner: field.owner,
89
+ key: field.key,
90
+ schema: field.schema,
91
+ collation: Option.orElse(Collation.declared(field.metadata), () => field.key === "id" ? Option.some(Collation.binary) : Option.none())
92
+ });
93
+ const predicateTags = /* @__PURE__ */ new Set([
94
+ "Eq",
95
+ "Null",
96
+ "Contains",
97
+ "In"
98
+ ]);
99
+ /** Whether a value is a predicate, and so usable where a boolean is wanted. */
100
+ const isPredicate = (value) => predicateTags.has(tagOf(value));
101
+ /**
102
+ * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
103
+ * itself, and anything else is the constant it is.
104
+ */
105
+ const toOperand = (value) => {
106
+ const tag = tagOf(value);
107
+ if (tag === "Field") return fieldExpr(value);
108
+ if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
109
+ return literal(value);
110
+ };
111
+ /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
112
+ const toExpr = (value, step) => {
113
+ const operand = toOperand(value);
114
+ 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`);
115
+ return operand;
116
+ };
117
+ const Expr = {
118
+ /** A constant. Comparisons coerce a plain value, so this is rarely written. */
119
+ literal,
120
+ /**
121
+ * A value the query is given when it runs. A definition builds these from its
122
+ * `Input` schema; written by hand only when constructing a body directly.
123
+ */
124
+ input: (key, schema) => node({
125
+ _tag: "Input",
126
+ key,
127
+ schema
128
+ }),
129
+ /** One field of one Entity, as a scalar. */
130
+ field: (field) => fieldExpr(field),
131
+ /**
132
+ * Two scalars are the same value. A field or a plain value on either side is
133
+ * coerced, so the common form reads as it means:
134
+ *
135
+ * ```ts
136
+ * Expr.eq(Post.fields.slug, input.slug)
137
+ * Expr.eq(Post.fields.status, 'active')
138
+ * ```
139
+ */
140
+ eq: (left, right) => node({
141
+ _tag: "Eq",
142
+ left: toOperand(left),
143
+ right: toOperand(right)
144
+ }),
145
+ /**
146
+ * Whether a field holds no value. Its opposite is `isNotNull`; both are the
147
+ * one node, because a query asks which of the two it means and nothing here
148
+ * can negate a predicate.
149
+ */
150
+ isNull: (operand) => node({
151
+ _tag: "Null",
152
+ operand: toExpr(operand, "isNull"),
153
+ present: false
154
+ }),
155
+ /** Whether a field holds a value. */
156
+ isNotNull: (operand) => node({
157
+ _tag: "Null",
158
+ operand: toExpr(operand, "isNotNull"),
159
+ present: true
160
+ }),
161
+ /**
162
+ * Whether a text value contains `search`, anywhere in it. Containing the
163
+ * empty string is everything, so a search box with nothing typed in it is the
164
+ * same query as one with something — no branch, and no second query.
165
+ *
166
+ * **Case-insensitive**, which is what a search means, and which has to be
167
+ * said rather than left to the interpreter: SQLite's `like` ignores case and
168
+ * Postgres's does not, so a body that left it open would mean two things.
169
+ * Folding is ASCII-only, because that is what `lower` does in SQLite without
170
+ * ICU.
171
+ *
172
+ * **Over a column that can be null this is not the same as no filter.** A
173
+ * null contains nothing, not even the empty string, so its rows drop out. A
174
+ * nullable column that should match everything on an empty search says so:
175
+ * `Expr.or` does not exist yet, so for now such a column needs its own
176
+ * predicate or a native escape hatch.
177
+ */
178
+ contains: (value, search) => node({
179
+ _tag: "Contains",
180
+ value: toExpr(value, "contains"),
181
+ search: toOperand(search)
182
+ }),
183
+ /**
184
+ * Whether a value is one of `among`: a list written out, or an input whose
185
+ * value is one. Each element is compared as `eq` compares.
186
+ *
187
+ * ```ts
188
+ * Expr.in(Todo.fields.projectId, input.projectIds)
189
+ * Expr.in(Todo.fields.status, ['open', 'blocked'])
190
+ * ```
191
+ *
192
+ * As SQL's `in`: a null value is unknown, as is no match against a list
193
+ * holding a null, and an empty list matches no row. A list written out is
194
+ * copied, so changing the array afterwards does not change the query.
195
+ */
196
+ in: (value, among) => node({
197
+ _tag: "In",
198
+ value: toExpr(value, "in"),
199
+ among: Array.isArray(among) ? literal(Object.freeze([...among])) : toExpr(among, "in")
200
+ }),
201
+ /** An expression as readable text; see `showExpr` for what it is and is not. */
202
+ show: (node) => showExpr(node)
203
+ };
204
+ /** A term, its nulls placed by `options` or by the direction's default. */
205
+ const term = (direction, expr, options = {}) => node({
206
+ _tag: "Term",
207
+ direction,
208
+ expr,
209
+ nulls: options.nulls ?? (direction === "asc" ? "last" : "first"),
210
+ collation: Option.orElse(Option.fromUndefinedOr(options.collation), () => Match.value(expr).pipe(Match.tag("Field", (field) => field.collation), Match.orElse(() => Option.none())))
211
+ });
212
+ const Order = {
213
+ /** Smallest first; rows without a value last, unless `nulls` says first. */
214
+ asc: (expr, options) => term("asc", toExpr(expr, "asc"), options),
215
+ /** Largest first; rows without a value first, unless `nulls` says last. */
216
+ desc: (expr, options) => term("desc", toExpr(expr, "desc"), options),
217
+ /**
218
+ * The order the input names, among `choices`: every name the sort can hold
219
+ * maps to a field, so a name left out is a type error here, not a query that
220
+ * silently orders by nothing. A `null` sort chooses none, and the terms after
221
+ * it decide.
222
+ *
223
+ * ```ts
224
+ * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))
225
+ * ```
226
+ */
227
+ chosen: (sort, choices) => {
228
+ const fields = Object.create(null);
229
+ for (const [name, choice] of Object.entries(choices)) {
230
+ const expr = toExpr(choice, "chosen");
231
+ if (expr._tag !== "Field") throw new Error(`[foldkit-entity] Order.chosen: "${name}" is not a field`);
232
+ fields[name] = expr;
233
+ }
234
+ return node({
235
+ _tag: "Chosen",
236
+ sort,
237
+ choices: Object.freeze(fields)
238
+ });
239
+ }
240
+ };
241
+ const placeable = Object.freeze({ _tag: "Placeable" });
242
+ const notPlaceable = (reason) => Object.freeze({
243
+ _tag: "NotPlaceable",
244
+ reason
245
+ });
246
+ /**
247
+ * Whether values encoded by `ast` order the same everywhere: numbers and
248
+ * booleans, never text. A null among them does too: where it goes is said on
249
+ * every order term.
250
+ */
251
+ 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));
252
+ /** Why a term cannot be placed by a client, if it cannot. */
253
+ const unplaceable = (orderTerm) => Match.value(orderTerm.expr).pipe(Match.tag("Field", (field) => Option.match(orderTerm.collation, {
254
+ onNone: () => ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.none() : Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`),
255
+ onSome: (collation) => Match.value(collation).pipe(Match.tagsExhaustive({
256
+ Binary: () => Option.none(),
257
+ AsciiFold: () => Option.none(),
258
+ Locale: ({ locale }) => Option.some(`it orders ${field.owner.name}.${field.key} by the backend's "${locale}" collation`)
259
+ }))
260
+ })), Match.orElse(() => Option.some("it orders by something that is not a field")));
261
+ /** Each Entity's id tie-break, made once, so a resolved order reuses one term. */
262
+ const idTerms = /* @__PURE__ */ new WeakMap();
263
+ const idTermOf = (entity) => {
264
+ const known = idTerms.get(entity);
265
+ if (known !== void 0) return known;
266
+ const id = entity.fields.id;
267
+ if (id === void 0) throw new Error(`[foldkit-entity] ${entity.name} has no id field to break an order's ties by`);
268
+ const tieBreak = term("asc", fieldExpr(id));
269
+ idTerms.set(entity, tieBreak);
270
+ return tieBreak;
271
+ };
272
+ /** The fixed term a chosen order is for one input, or none for a `null` sort. */
273
+ const chosenTerms = (chosen, input) => {
274
+ const sort = input[chosen.sort.key];
275
+ if (sort === null || sort === void 0) return [];
276
+ const picked = typeof sort === "object" && "by" in sort && typeof sort.by === "string" ? sort.by : void 0;
277
+ const direction = typeof sort === "object" && "direction" in sort ? sort.direction : void 0;
278
+ 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(", ")})`);
279
+ return [term(direction, chosen.choices[picked])];
280
+ };
281
+ /**
282
+ * Visits each node once. A node can be shared by several paths (`eq(n, n)`),
283
+ * and a walk that followed every path would take time exponential in the depth.
284
+ */
285
+ const walk = (expr, found) => {
286
+ if (found.seen.has(expr)) return;
287
+ found.seen.add(expr);
288
+ switch (expr._tag) {
289
+ case "Literal": return;
290
+ case "Field": {
291
+ const byKey = found.fields.get(expr.owner.token) ?? /* @__PURE__ */ new Map();
292
+ found.fields.set(expr.owner.token, byKey);
293
+ if (!byKey.has(expr.key)) {
294
+ const field = {
295
+ entity: expr.owner.name,
296
+ key: expr.key,
297
+ owner: expr.owner
298
+ };
299
+ byKey.set(expr.key, field);
300
+ found.order.push(field);
301
+ }
302
+ return;
303
+ }
304
+ case "Input":
305
+ found.inputs.add(expr.key);
306
+ return;
307
+ case "Eq":
308
+ found.operations.add("eq");
309
+ walk(expr.left, found);
310
+ walk(expr.right, found);
311
+ return;
312
+ case "Null":
313
+ found.operations.add(expr.present ? "isNotNull" : "isNull");
314
+ walk(expr.operand, found);
315
+ return;
316
+ case "Contains":
317
+ found.operations.add("contains");
318
+ walk(expr.value, found);
319
+ walk(expr.search, found);
320
+ return;
321
+ case "In":
322
+ found.operations.add("in");
323
+ walk(expr.value, found);
324
+ walk(expr.among, found);
325
+ return;
326
+ case "Term":
327
+ walk(expr.expr, found);
328
+ return;
329
+ case "Chosen":
330
+ walk(expr.sort, found);
331
+ for (const choice of Object.values(expr.choices)) walk(choice, found);
332
+ return;
333
+ }
334
+ };
335
+ /**
336
+ * What an expression reads and uses, for the planner and for an interpreter
337
+ * deciding whether it can run this query at all. Distinct entries only, in the
338
+ * order first seen, so the answer is stable enough to assert on.
339
+ */
340
+ const dependenciesOf = (...nodes) => {
341
+ const found = {
342
+ seen: /* @__PURE__ */ new Set(),
343
+ fields: /* @__PURE__ */ new Map(),
344
+ order: [],
345
+ inputs: /* @__PURE__ */ new Set(),
346
+ operations: /* @__PURE__ */ new Set()
347
+ };
348
+ for (const term of nodes) walk(term, found);
349
+ return {
350
+ fields: found.order,
351
+ inputs: [...found.inputs],
352
+ operations: [...found.operations]
353
+ };
354
+ };
355
+ /** Every field an expression reads, as the nodes themselves, each node visited once. */
356
+ const fieldsIn = function* (expr, seen) {
357
+ if (seen.has(expr)) return;
358
+ seen.add(expr);
359
+ switch (expr._tag) {
360
+ case "Field":
361
+ yield expr;
362
+ return;
363
+ case "Literal":
364
+ case "Input": return;
365
+ case "Eq":
366
+ yield* fieldsIn(expr.left, seen);
367
+ yield* fieldsIn(expr.right, seen);
368
+ return;
369
+ case "Null":
370
+ yield* fieldsIn(expr.operand, seen);
371
+ return;
372
+ case "Contains":
373
+ yield* fieldsIn(expr.value, seen);
374
+ yield* fieldsIn(expr.search, seen);
375
+ return;
376
+ case "In":
377
+ yield* fieldsIn(expr.value, seen);
378
+ yield* fieldsIn(expr.among, seen);
379
+ return;
380
+ case "Term":
381
+ yield* fieldsIn(expr.expr, seen);
382
+ return;
383
+ case "Chosen":
384
+ for (const choice of Object.values(expr.choices)) yield* fieldsIn(choice, seen);
385
+ return;
386
+ }
387
+ };
388
+ /**
389
+ * A query reads one Entity, so a predicate or ordering term naming a different
390
+ * one cannot be answered — an interpreter would be asked for a column of a
391
+ * table it was never told to read. Compared by identity, not by name, because
392
+ * two Entities defined with the same name are two Entities.
393
+ */
394
+ const checkOwnership = (step, what, entity, nodes) => {
395
+ const seen = /* @__PURE__ */ new Set();
396
+ 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}`);
397
+ };
398
+ /**
399
+ * The most nodes a query's predicates may hold once every shared node is
400
+ * counted on each path that reaches it. Interpreters read a predicate as a
401
+ * tree: `evaluate` once per row, and the SQL compiler into text that repeats a
402
+ * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is
403
+ * thirty-one objects and a billion nodes of work. Real queries are tens.
404
+ */
405
+ const maxQueryNodes = 1e3;
406
+ const childrenOf = (expr) => {
407
+ switch (expr._tag) {
408
+ case "Literal":
409
+ case "Field":
410
+ case "Input": return [];
411
+ case "Eq": return [expr.left, expr.right];
412
+ case "Null": return [expr.operand];
413
+ case "Contains": return [expr.value, expr.search];
414
+ case "In": return [expr.value, expr.among];
415
+ }
416
+ };
417
+ /** A node's size as a tree, each distinct node sized once. */
418
+ const expandedSize = (expr, sizes) => {
419
+ const known = sizes.get(expr);
420
+ if (known !== void 0) return known;
421
+ const size = Math.min(1001, childrenOf(expr).reduce((sum, child) => sum + expandedSize(child, sizes), 1));
422
+ sizes.set(expr, size);
423
+ return size;
424
+ };
425
+ const QueryProto = {
426
+ _tag: "Query",
427
+ pipe() {
428
+ return Pipeable.pipeArguments(this, arguments);
429
+ }
430
+ };
431
+ const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
432
+ entity,
433
+ where: Object.freeze(where),
434
+ orderBy: Object.freeze(orderBy)
435
+ }));
436
+ const Query = {
437
+ /** Every row of an Entity: the query each transformation narrows. */
438
+ from: (entity) => query(entity, [], []),
439
+ /**
440
+ * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
441
+ * second never replaces the first — so a fragment can be written once and
442
+ * piped into any query over the same Entity:
443
+ *
444
+ * ```ts
445
+ * const published = Query.where(Expr.eq(Post.fields.published, true))
446
+ * Query.from(Post).pipe(published, Query.where(byTitle))
447
+ * ```
448
+ */
449
+ where: (...predicates) => (self) => {
450
+ if (predicates.length === 0) return self;
451
+ checkOwnership("where", "a predicate", self.entity, predicates);
452
+ const where = [...self.where, ...predicates];
453
+ const sizes = /* @__PURE__ */ new Map();
454
+ if (where.reduce((sum, predicate) => sum + expandedSize(predicate, sizes), 0) > 1e3) throw new Error(`[foldkit-entity] Query.where: the predicates expand to more than ${maxQueryNodes} nodes, counting a shared node on every path that reaches it`);
455
+ return query(self.entity, where, self.orderBy);
456
+ },
457
+ /**
458
+ * Reads the rows in this order. Two `orderBy`s append, so an earlier term
459
+ * stays the more significant one and a later call adds a tie-breaker rather
460
+ * than silently winning.
461
+ */
462
+ orderBy: (...terms) => (self) => {
463
+ if (terms.length === 0) return self;
464
+ checkOwnership("orderBy", "a term", self.entity, terms);
465
+ return query(self.entity, self.where, [...self.orderBy, ...terms]);
466
+ },
467
+ /**
468
+ * The fixed terms this query orders by for one input: each chosen order
469
+ * resolved to the field its input names, or to nothing for a `null` sort,
470
+ * and the Entity's id last, ascending, unless the terms already read it. So
471
+ * the order is total, and every interpreter breaks ties the same way: one
472
+ * that broke them its own way would place rows a step apart from another.
473
+ */
474
+ orderFor: (self, input) => {
475
+ const terms = self.orderBy.flatMap((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
476
+ Term: (term) => [term],
477
+ Chosen: (chosen) => chosenTerms(chosen, input)
478
+ })));
479
+ const id = idTermOf(self.entity);
480
+ return terms.some((term) => term.expr._tag === "Field" && term.expr.key === "id") ? terms : [...terms, id];
481
+ },
482
+ /**
483
+ * Whether a client can order this query's rows exactly as the server does,
484
+ * for one input: every term over a number or a boolean (a row may lack it), or over text with a
485
+ * portable collation (`binary`, `asciiFold`). A body that names no order
486
+ * leaves it to the server, and is never placeable.
487
+ */
488
+ placement: (self, input) => {
489
+ if (self.orderBy.length === 0) return notPlaceable("its order is the server's: the body names none");
490
+ for (const orderTerm of Query.orderFor(self, input)) {
491
+ const reason = unplaceable(orderTerm);
492
+ if (Option.isSome(reason)) return notPlaceable(reason.value);
493
+ }
494
+ return placeable;
495
+ },
496
+ /**
497
+ * What the whole query reads: the fields and inputs of every predicate and
498
+ * every ordering term, and the operations it uses, with the fields also
499
+ * split by role.
500
+ */
501
+ dependencies: (self) => ({
502
+ ...dependenciesOf(...self.where, ...self.orderBy),
503
+ predicate: dependenciesOf(...self.where).fields,
504
+ order: dependenciesOf(...self.orderBy).fields
505
+ }),
506
+ /**
507
+ * The operations this query needs that `supported` does not list, in the
508
+ * order the query uses them. Empty means an interpreter declaring
509
+ * `supported` can answer it.
510
+ *
511
+ * An interpreter declares what it runs and refuses the rest, rather than
512
+ * ignoring an operation it does not implement — which would answer a
513
+ * different question and say nothing. The refusal is the interpreter's to
514
+ * raise: this only says what is missing, because what to do about it differs
515
+ * between one that compiles at registration and one that runs a body
516
+ * directly.
517
+ *
518
+ * ```ts
519
+ * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
520
+ * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
521
+ * ```
522
+ */
523
+ unsupported: (self, supported) => {
524
+ const runs = new Set(supported);
525
+ return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
526
+ },
527
+ /**
528
+ * The whole query as readable text, one clause per line:
529
+ *
530
+ * ```text
531
+ * FROM Post
532
+ * WHERE Post.slug = $slug
533
+ * AND Post.published = true
534
+ * ORDER BY Post.updatedAt DESC
535
+ * ```
536
+ *
537
+ * For an explanation or a diagnostic, never for an interpreter — see
538
+ * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
539
+ * than printing an empty one, so what is shown is what was written.
540
+ */
541
+ show: (self) => [
542
+ `FROM ${self.entity.name}`,
543
+ ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
544
+ ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((entry) => Match.value(entry).pipe(Match.tagsExhaustive({
545
+ Term: (term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`,
546
+ Chosen: (chosen) => `$${chosen.sort.key} among (${Object.entries(chosen.choices).map(([name, field]) => `${name}: ${Expr.show(field)}`).join(", ")})`
547
+ }))).join(", ")}`]
548
+ ].join("\n")
549
+ };
550
+ /**
551
+ * An expression as readable text, in the IR's own terms.
552
+ *
553
+ * This is for a human — an explanation, a diagnostic, a test that wants to
554
+ * assert on a whole predicate at once — and deliberately **not** for an
555
+ * interpreter. It is close enough to SQL to read at a glance and unlike it
556
+ * everywhere that matters: an input is `$slug` rather than a bound parameter,
557
+ * `contains` is named rather than rendered as somebody's `like`, and no
558
+ * dialect's escaping or collation is implied. What actually ran is whatever
559
+ * that backend compiled, which is not this.
560
+ *
561
+ * A predicate standing where a value is wanted is parenthesised, because
562
+ * `x is not null = $archived` reads as three operands and is two. A predicate
563
+ * that *is* the whole expression is not: nothing encloses it.
564
+ */
565
+ const showExpr = (node) => {
566
+ switch (node._tag) {
567
+ case "Literal": return JSON.stringify(node.value) ?? String(node.value);
568
+ case "Field": return `${node.owner.name}.${node.key}`;
569
+ case "Input": return `$${node.key}`;
570
+ case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
571
+ case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
572
+ case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
573
+ case "In": return `${showOperand(node.value)} in ${showOperand(node.among)}`;
574
+ }
575
+ };
576
+ const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
577
+ //#endregion
578
+ //#region src/readFilter.ts
579
+ /**
580
+ * The members a server filters an Entity's rows by under a rule the client
581
+ * does not run, such as an authorization rule. A client that places rows in
582
+ * a list judges membership by the list's body; a change to one of these
583
+ * members can move a row into or out of what the server lists, which only
584
+ * the server can say. Declared by whoever owns the rule (`foldkit-guard`
585
+ * attaches it), read by whoever places (`foldkit-remote`).
586
+ */
587
+ const key = Metadata.key("foldkit-entity/read-filter", {
588
+ merge: (lists) => [[...new Set(lists.flat())]],
589
+ summarize: (members) => members.join(", ")
590
+ });
591
+ const ReadFilter = {
592
+ /** Entity metadata: the rows the server lists depend on these members. */
593
+ of: (members) => key.of(members),
594
+ /** The members an Entity's metadata names, every attachment's together. */
595
+ members: (metadata) => key.get(metadata)[0] ?? []
596
+ };
597
+ //#endregion
598
+ //#region src/words.ts
599
+ const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
600
+ const Words = {
601
+ /**
602
+ * A schema's words, as a label and its help text. Under Effect 4 a checked
603
+ * schema resolves to its last check's annotations, which say what the check
604
+ * expects and carry no `title`, so a title given before the check is read from
605
+ * the schema's own annotations. Read words through this, never through
606
+ * `Schema.resolveAnnotations` directly.
607
+ */
608
+ of: (schema) => {
609
+ const resolved = Schema.resolveAnnotations(schema) ?? {};
610
+ const own = schema.ast.annotations ?? {};
611
+ return {
612
+ title: Option.orElse(text(resolved.title), () => text(own["title"])),
613
+ description: Option.orElse(text(resolved.description), () => text(own["description"]))
614
+ };
615
+ } };
616
+ //#endregion
617
+ //#region src/evaluate.ts
618
+ /**
619
+ * The reference interpreter: a query body run over rows already in memory.
620
+ *
621
+ * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
622
+ * directly, which is what makes "source-neutral" a fact rather than a claim —
623
+ * the two are checked against each other over a real database, and a body that
624
+ * means one thing here and another there is a bug in one of them.
625
+ *
626
+ * It is also the interpreter to reach for when there is no database: a test
627
+ * that wants rows, a server assembling a page from values it already holds, or
628
+ * a client judging rows it already has.
629
+ *
630
+ * It lives in `foldkit-entity` because it is the **reference semantics** of the
631
+ * IR this package owns — what §6.0.1 means operationally rather than in prose —
632
+ * and a specification's reference implementation belongs with the
633
+ * specification. The rule that keeps it here: **it may depend on the IR and
634
+ * nothing else.** The moment it wants a Remote concept it has moved to the
635
+ * wrong place and should leave.
636
+ *
637
+ * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
638
+ * because SQL is what the other interpreter runs. The important case is null:
639
+ * `null = null` is unknown in SQL and a row is not matched by it, where
640
+ * JavaScript would happily call the two equal.
641
+ */
642
+ var QueryEvaluateError = class extends Error {
643
+ constructor(message) {
644
+ super(`[foldkit-entity] ${message}`);
645
+ this.name = "QueryEvaluateError";
646
+ }
647
+ };
648
+ const valueOf = (node, row, input) => {
649
+ switch (node._tag) {
650
+ case "Field": return row[node.key];
651
+ case "Literal": return node.value;
652
+ case "Input": return input[node.key];
653
+ }
654
+ };
655
+ const isNull = (value) => value === null || value === void 0;
656
+ /**
657
+ * Lowercases ASCII letters and leaves every other character as it is, which is
658
+ * what SQLite's `lower` does without ICU and so what the compiled SQL folds to.
659
+ * `toLowerCase` would fold `É` to `é` here and not there.
660
+ */
661
+ const foldAscii = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
662
+ const NUL = String.fromCharCode(0);
663
+ /** A predicate used as a value is its own truth; anything else is its value. */
664
+ const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
665
+ /**
666
+ * A predicate compared as a value. SQL's unknown is null there too, so an
667
+ * unknown compared to anything stays unknown rather than becoming false.
668
+ */
669
+ const truthValue = (truth) => truth === "unknown" ? null : truth;
670
+ const holds = (node, row, input) => {
671
+ switch (node._tag) {
672
+ case "Eq": {
673
+ const left = sideOf(node.left, row, input);
674
+ const right = sideOf(node.right, row, input);
675
+ if (isNull(left) || isNull(right)) return "unknown";
676
+ return left === right;
677
+ }
678
+ case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
679
+ case "Contains": {
680
+ const value = valueOf(node.value, row, input);
681
+ const search = sideOf(node.search, row, input);
682
+ if (isNull(value) || isNull(search)) return "unknown";
683
+ if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
684
+ if (value.includes(NUL) || search.includes(NUL)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
685
+ return foldAscii(value).includes(foldAscii(search));
686
+ }
687
+ case "In": {
688
+ const among = valueOf(node.among, row, input);
689
+ if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
690
+ if (among.length === 0) return false;
691
+ const value = valueOf(node.value, row, input);
692
+ if (isNull(value)) return "unknown";
693
+ if (among.some((each) => each === value)) return true;
694
+ return among.some(isNull) ? "unknown" : false;
695
+ }
696
+ }
697
+ };
698
+ /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
699
+ const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
700
+ /** The kinds of value this interpreter orders by; every key of one term must share one. */
701
+ const comparable = /* @__PURE__ */ new Set([
702
+ "string",
703
+ "number",
704
+ "boolean"
705
+ ]);
706
+ /**
707
+ * Text by code point, as SQLite's `BINARY` and Postgres's `"C"` compare it.
708
+ * JavaScript's `<` compares UTF-16 code units, which puts a character past
709
+ * U+FFFF (two units, the first from U+D800) before U+E000 to U+FFFF, where
710
+ * every byte-ordered backend puts it after.
711
+ */
712
+ const byCodePoint = (left, right) => {
713
+ let i = 0;
714
+ let j = 0;
715
+ while (i < left.length && j < right.length) {
716
+ const a = left.codePointAt(i);
717
+ const b = right.codePointAt(j);
718
+ if (a !== b) return a < b ? -1 : 1;
719
+ i += a > 65535 ? 2 : 1;
720
+ j += b > 65535 ? 2 : 1;
721
+ }
722
+ return i < left.length ? 1 : j < right.length ? -1 : 0;
723
+ };
724
+ /** Two keys of one term, text by its collation (code point when none is declared). */
725
+ const compare = (left, right, collation) => {
726
+ if (typeof left === "string" && typeof right === "string") return Option.exists(collation, (declared) => declared._tag === "AsciiFold") ? byCodePoint(foldAscii(left), foldAscii(right)) : byCodePoint(left, right);
727
+ if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
728
+ return left - right;
729
+ };
730
+ /**
731
+ * Refuses an ordering this interpreter will not answer for, before sorting, so
732
+ * the refusal names the first offending row in row order rather than whichever
733
+ * pair the engine's sort happened to compare first. Every term is checked over
734
+ * every row: a key whose kind differs from the first present one's. A null key
735
+ * is not refused; the term says where it goes.
736
+ */
737
+ const checkOrder = (rows, terms, query) => {
738
+ for (const term of terms) {
739
+ if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
740
+ if (Option.exists(term.collation, (declared) => declared._tag === "Locale")) throw new QueryEvaluateError(`query "${query}" orders "${term.expr.key}" by a backend's locale collation, which only that backend has`);
741
+ const key = term.expr.key;
742
+ let first;
743
+ for (const row of rows) {
744
+ const value = row[key];
745
+ if (isNull(value)) continue;
746
+ const kind = typeof value;
747
+ first ??= kind;
748
+ if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
749
+ }
750
+ }
751
+ };
752
+ /** Two rows by checked terms: negative when `left` sorts first. */
753
+ const byTerms = (terms, left, right) => {
754
+ for (const term of terms) {
755
+ const key = term.expr.key;
756
+ const absentLeft = isNull(left[key]);
757
+ const absentRight = isNull(right[key]);
758
+ if (absentLeft || absentRight) {
759
+ if (absentLeft && absentRight) continue;
760
+ return absentLeft === (term.nulls === "first") ? -1 : 1;
761
+ }
762
+ const sign = compare(left[key], right[key], term.collation);
763
+ if (sign !== 0) return term.direction === "asc" ? sign : -sign;
764
+ }
765
+ return 0;
766
+ };
767
+ const ordered = (rows, terms, query) => {
768
+ if (terms.length === 0 || rows.length < 2) return [...rows];
769
+ checkOrder(rows, terms, query);
770
+ return [...rows].sort((left, right) => byTerms(terms, left, right));
771
+ };
772
+ /**
773
+ * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
774
+ * as `evaluate` sorts: negative when it comes first. Refuses what `evaluate`
775
+ * refuses, for these two rows: a term not over a field, a locale collation,
776
+ * or keys of different kinds. For a client placing one row among others it
777
+ * holds.
778
+ */
779
+ const compareRows = (terms, left, right, query) => {
780
+ checkOrder([left, right], terms, query);
781
+ return byTerms(terms, left, right);
782
+ };
783
+ /**
784
+ * The operations this interpreter runs. It is the reference, so this is the
785
+ * whole kernel — but it is declared rather than assumed, because an
786
+ * interpreter that gains an operator and forgets to say so is exactly what
787
+ * `Query.unsupported` exists to catch.
788
+ */
789
+ const supported = [
790
+ "eq",
791
+ "isNull",
792
+ "isNotNull",
793
+ "contains",
794
+ "in"
795
+ ];
796
+ /**
797
+ * Refuses a body needing an operation this interpreter does not run, rather
798
+ * than skipping it and answering a different question. Called by `evaluate`;
799
+ * call it directly to check a body once instead of on every run.
800
+ */
801
+ const assertSupported = (body) => {
802
+ const missing = Query.unsupported(body, supported);
803
+ if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
804
+ };
805
+ /**
806
+ * The rows the body matches, in the order it asks for. Pure: it reads the rows
807
+ * it is given and nothing else.
808
+ *
809
+ * `input` holds the values this run was given, by the keys the body's
810
+ * placeholders were built with — the same record the query would be called
811
+ * with anywhere else.
812
+ */
813
+ const evaluate = (body, input, rows) => {
814
+ assertSupported(body);
815
+ return ordered(rows.filter((row) => matches(body, row, input)), Query.orderFor(body, input), body.entity.name);
816
+ };
817
+ //#endregion
818
+ //#region src/write.ts
819
+ /**
820
+ * A write as a value: what an operation changes, declared over the input it
821
+ * takes, so the changes can be known before it runs and its interpreters can
822
+ * agree on what it means.
823
+ *
824
+ * A `Write` is built on `Entity.input`, which already says which input key is
825
+ * which member of the Entity. `Write.update`, `Write.insert` and `Write.delete`
826
+ * add what to do with them: the key that names the row, and optionally the key
827
+ * holding the revision it was read at. Every other key mapped to a field is
828
+ * set; a key mapped to `Entity.unmapped` is about the operation and is not
829
+ * written.
830
+ *
831
+ * It is authority someone declared, never something derived from an Entity: an
832
+ * Entity having a field does not mean anyone may set it.
833
+ */
834
+ const fail$1 = (input, message) => {
835
+ throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
836
+ };
837
+ const membersOf = (input) => input.members;
838
+ /** A field's value as the store holds it. A field's schema needs no service, so none is asked. */
839
+ const encoded = (field, value) => Schema.encodeUnknownSync(field.schema)(value);
840
+ /**
841
+ * A key's value as given, when it was: an absent key, and an `Option` that
842
+ * holds nothing, give none, and a `Some` what it holds. What `Entity.input`
843
+ * lets a key map itself to, a write can bind.
844
+ */
845
+ const given = (value) => {
846
+ if (value === void 0) return Option.none();
847
+ return Option.isOption(value) ? value : Option.some(value);
848
+ };
849
+ const fieldAt = (input, key, role) => {
850
+ const member = membersOf(input)[key];
851
+ if (member === void 0) return fail$1(input, `${role} "${key}" is not a key of the input`);
852
+ if (member._tag !== "Field") return fail$1(input, `${role} "${key}" is not mapped to a field`);
853
+ return member;
854
+ };
855
+ /**
856
+ * What every kind shares: the key naming the row, the expected revision, and
857
+ * what the other keys set or point. A kind adds its own checks.
858
+ */
859
+ const declared = (kind, input, options) => {
860
+ const id = fieldAt(input, options.id, "id");
861
+ if (id.key !== "id") fail$1(input, `id "${options.id}" is mapped to "${id.key}", not to "id"`);
862
+ const idSchema = input.schema.fields[options.id];
863
+ const takes = Schema.is(Schema.toType(idSchema));
864
+ 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`);
865
+ if (options.expect === options.id) fail$1(input, "expect cannot be the id");
866
+ const expect = options.expect === void 0 ? void 0 : Object.freeze({
867
+ key: options.expect,
868
+ field: fieldAt(input, options.expect, "expect")
869
+ });
870
+ const sets = [];
871
+ const links = [];
872
+ for (const [key, member] of Object.entries(membersOf(input))) {
873
+ if (member === void 0 || key === options.id || key === options.expect) continue;
874
+ switch (member._tag) {
875
+ case "Field":
876
+ sets.push(Object.freeze({
877
+ key,
878
+ field: member
879
+ }));
880
+ break;
881
+ case "Unmapped": break;
882
+ case "RelationInput":
883
+ if (member.relation.cardinality !== "one") fail$1(input, `"${key}" is a many relation; a write points one relation at a time`);
884
+ links.push(Object.freeze({
885
+ key,
886
+ relation: member.relation
887
+ }));
888
+ break;
889
+ case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
890
+ }
891
+ }
892
+ return Object.freeze({
893
+ _tag: kind,
894
+ input,
895
+ id: Object.freeze({
896
+ key: options.id,
897
+ field: id
898
+ }),
899
+ expect,
900
+ sets: Object.freeze(sets),
901
+ links: Object.freeze(links)
902
+ });
903
+ };
904
+ /** An update or an insert that would write nothing is refused where it is declared. */
905
+ const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 ? fail$1(write.input, "it sets no field") : write;
906
+ const Write = {
907
+ /**
908
+ * Sets, on the row whose id is the input's `id` key, every field the input
909
+ * maps a key to. `expect` names the key holding the revision the row was
910
+ * read at: an interpreter writes only a row still at that revision.
911
+ *
912
+ * ```ts
913
+ * const EditPost = Write.update(EditPostInput, { id: 'id' })
914
+ * ```
915
+ *
916
+ * A key mapped to a `one` relation (`Relation.input`) points the row at the
917
+ * id it holds. Refused where it is written: an `id` that is not the Entity's
918
+ * `id` field, a `many` relation or a nested key (not written by an update
919
+ * yet), or nothing to set.
920
+ */
921
+ update: (input, options) => {
922
+ return settingSomething(declared("Update", input, options));
923
+ },
924
+ /**
925
+ * Inserts the row whose id is the input's `id` key, an id the client chose,
926
+ * with every field and `one` relation the input maps a key to. An insert
927
+ * expects no revision: there is no row to have read. A row already there
928
+ * under that id (a retry) is left as it is.
929
+ */
930
+ insert: (input, options) => {
931
+ return settingSomething(declared("Insert", input, options));
932
+ },
933
+ /**
934
+ * Deletes the row whose id is the input's `id` key, only while it is still at
935
+ * the revision `expect` names, when it names one. It sets nothing, so a key
936
+ * mapped to a member is refused where it is written. A row already gone (a
937
+ * retry) is gone.
938
+ */
939
+ delete: (input, options) => {
940
+ const write = declared("Delete", input, options);
941
+ const named = [...write.sets, ...write.links][0];
942
+ if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
943
+ return write;
944
+ },
945
+ /**
946
+ * The revision this input says the row was read at, encoded, with its field:
947
+ * what an interpreter writes only a row still at. None for a write that
948
+ * expects none.
949
+ */
950
+ expected: (write, value) => Option.map(Option.fromUndefinedOr(write.expect), ({ key, field }) => ({
951
+ field: field.key,
952
+ revision: encoded(field, value[key])
953
+ })),
954
+ /** The members any invocation may write: what a query reading none of them cannot be changed by. */
955
+ writes: (write) => [...write.sets.map((set) => set.field), ...write.links.map((link) => link.relation)],
956
+ /**
957
+ * The row this input writes and its new values, encoded as the store holds
958
+ * them: the patch a client shows before the server answers. `keys`, when
959
+ * given, narrows it to those input keys (what an author changed); the rest of
960
+ * the input is still the whole, validated value.
961
+ */
962
+ bind: (write, value, keys) => {
963
+ const input = value;
964
+ const wanted = keys === void 0 ? void 0 : new Set(keys);
965
+ const asked = (key) => wanted === void 0 || wanted.has(key);
966
+ const values = {};
967
+ for (const { key, field } of write.sets) {
968
+ if (!asked(key)) continue;
969
+ Option.map(given(input[key]), (held) => {
970
+ values[field.key] = encoded(field, held);
971
+ });
972
+ }
973
+ const links = {};
974
+ for (const { key, relation } of write.links) {
975
+ if (!asked(key)) continue;
976
+ const target = relation.target();
977
+ links[relation.key] = Option.map(Option.flatMap(given(input[key]), Option.fromNullishOr), (id) => ({
978
+ entity: target.name,
979
+ id: String(encoded(target.fields.id, id))
980
+ }));
981
+ }
982
+ return {
983
+ entity: write.input.entity.name,
984
+ id: String(encoded(write.id.field, input[write.id.key])),
985
+ values,
986
+ links
987
+ };
988
+ }
989
+ };
990
+ //#endregion
991
+ //#region src/index.ts
992
+ /**
993
+ * `foldkit-entity` — domain structure as typed values.
994
+ *
995
+ * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
996
+ * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
997
+ * values an interpreter supplies). It describes; it fetches, stores, and
998
+ * renders nothing. Remote, Drizzle, and form packages interpret it and attach
999
+ * what they need as `foldkit-metadata`.
1000
+ */
1001
+ const EntityTypeId = Symbol.for("foldkit-entity/Entity");
1002
+ const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
1003
+ const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
1004
+ /** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
1005
+ const idSchemaOf = (entity) => {
1006
+ const id = entity.fields.id;
1007
+ if (id === void 0 || id._tag !== "Field") return Schema.String;
1008
+ const type = Schema.toType(id.schema);
1009
+ return SchemaShape.isText(type.ast) ? type : Schema.String;
1010
+ };
1011
+ const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
1012
+ const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
1013
+ const unmapped = Object.freeze({ _tag: "Unmapped" });
1014
+ const EntityProto = {
1015
+ [EntityTypeId]: EntityTypeId,
1016
+ pipe() {
1017
+ return Pipeable.pipeArguments(this, arguments);
1018
+ }
1019
+ };
1020
+ const make = (parts) => Object.freeze(Object.assign(Object.create(EntityProto), parts, {
1021
+ name: parts.identity.name,
1022
+ fields: Object.freeze(parts.fields),
1023
+ relations: Object.freeze(parts.relations),
1024
+ derived: Object.freeze(parts.derived),
1025
+ members: Object.freeze({
1026
+ ...parts.fields,
1027
+ ...parts.relations,
1028
+ ...parts.derived
1029
+ })
1030
+ }));
1031
+ const isSameEntity = (left, right) => left.identity.token === right.identity.token;
1032
+ const fail = (entity, message) => {
1033
+ throw new Error(`Entity "${entity.name}": ${message}`);
1034
+ };
1035
+ const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
1036
+ const kindName = {
1037
+ Field: "field",
1038
+ Relation: "relation",
1039
+ Derived: "derived member"
1040
+ };
1041
+ const kindOf = (entity, key) => {
1042
+ const member = entity.members[key];
1043
+ return member && kindName[member._tag];
1044
+ };
1045
+ const assertFree = (entity, keys, adding) => {
1046
+ for (const key of keys) {
1047
+ const kind = kindOf(entity, key);
1048
+ if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
1049
+ }
1050
+ };
1051
+ const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
1052
+ const Entity = {
1053
+ /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
1054
+ define: (name, schema) => {
1055
+ const identity = Object.freeze({
1056
+ name,
1057
+ token: Symbol(name)
1058
+ });
1059
+ return make({
1060
+ identity,
1061
+ schema,
1062
+ fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
1063
+ _tag: "Field",
1064
+ owner: identity,
1065
+ key,
1066
+ schema: fieldSchema,
1067
+ metadata: Metadata.empty
1068
+ })),
1069
+ relations: {},
1070
+ derived: {},
1071
+ metadata: Metadata.empty
1072
+ });
1073
+ },
1074
+ /**
1075
+ * Declares the relations between a set of Entities in one step, and returns
1076
+ * them related. One step, because Entities that point at each other cannot
1077
+ * each be declared in terms of the other.
1078
+ */
1079
+ relate: (entities, relations) => {
1080
+ const keyByToken = /* @__PURE__ */ new Map();
1081
+ for (const [key, entity] of Object.entries(entities)) {
1082
+ if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
1083
+ const earlier = keyByToken.get(entity.identity.token);
1084
+ if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
1085
+ keyByToken.set(entity.identity.token, key);
1086
+ }
1087
+ const given = relations;
1088
+ 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`);
1089
+ const related = {};
1090
+ for (const [ownerKey, entity] of Object.entries(entities)) {
1091
+ const specs = given[ownerKey] ?? {};
1092
+ assertFree(entity, Object.keys(specs), "relation");
1093
+ const added = mapValues(specs, (spec, key) => {
1094
+ const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
1095
+ if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
1096
+ return Object.freeze({
1097
+ _tag: "Relation",
1098
+ owner: entity.identity,
1099
+ key,
1100
+ target: () => related[targetKey],
1101
+ cardinality: spec.cardinality,
1102
+ optional: spec.optional,
1103
+ metadata: Metadata.empty
1104
+ });
1105
+ });
1106
+ related[ownerKey] = make({
1107
+ ...entity,
1108
+ relations: {
1109
+ ...entity.relations,
1110
+ ...added
1111
+ }
1112
+ });
1113
+ }
1114
+ return Object.freeze(related);
1115
+ },
1116
+ /**
1117
+ * Selects members of an Entity and assembles the schema of the result. A
1118
+ * relation selected with `true` yields an `EntityRef`; with a Selection of its
1119
+ * target, that Selection's value. `many` yields an array, an optional `one`
1120
+ * is nullable.
1121
+ */
1122
+ select: (entity, spec) => {
1123
+ const members = entity.members;
1124
+ const fields = mapValues(spec, (selected, key) => {
1125
+ const member = members[key];
1126
+ if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
1127
+ if (member._tag !== "Relation") {
1128
+ if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
1129
+ return member.schema;
1130
+ }
1131
+ const target = member.target();
1132
+ if (isSelectionPage(selected)) {
1133
+ if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
1134
+ if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
1135
+ return Schema.Struct({
1136
+ items: Schema.Array(selected.selection.schema),
1137
+ hasNext: Schema.Boolean,
1138
+ hasPrevious: Schema.Boolean
1139
+ });
1140
+ }
1141
+ let item;
1142
+ if (selected === true) item = Schema.Struct({
1143
+ entity: Schema.Literal(target.name),
1144
+ id: idSchemaOf(target)
1145
+ });
1146
+ else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
1147
+ else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
1148
+ return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
1149
+ });
1150
+ return Object.freeze({
1151
+ [SelectionTypeId]: SelectionTypeId,
1152
+ entity,
1153
+ members: spec,
1154
+ schema: Schema.Struct(fields)
1155
+ });
1156
+ },
1157
+ /**
1158
+ * A `many` relation read a page at a time, in place of its Selection:
1159
+ * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
1160
+ * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
1161
+ */
1162
+ page: (selection, window) => {
1163
+ const sides = [window.first, window.last].filter((size) => size !== void 0);
1164
+ 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`);
1165
+ 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`);
1166
+ return Object.freeze({
1167
+ [SelectionPageTypeId]: SelectionPageTypeId,
1168
+ selection,
1169
+ window
1170
+ });
1171
+ },
1172
+ /** Adds readable members that are not part of `entity.schema`. */
1173
+ derived: (specs) => (entity) => {
1174
+ assertFree(entity, Object.keys(specs), "derived member");
1175
+ const added = mapValues(specs, (spec, key) => Object.freeze({
1176
+ _tag: "Derived",
1177
+ owner: entity.identity,
1178
+ key,
1179
+ schema: spec.schema,
1180
+ metadata: Metadata.empty
1181
+ }));
1182
+ return make({
1183
+ ...entity,
1184
+ derived: {
1185
+ ...entity.derived,
1186
+ ...added
1187
+ }
1188
+ });
1189
+ },
1190
+ /** Attaches an interpreter's metadata to the Entity itself. */
1191
+ annotate: (metadata) => (entity) => make({
1192
+ ...entity,
1193
+ metadata: Metadata.combine([entity.metadata, metadata])
1194
+ }),
1195
+ /** Attaches an interpreter's metadata to members, by key. */
1196
+ annotateMembers: (metadata) => (entity) => {
1197
+ const given = metadata;
1198
+ 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`);
1199
+ const annotate = (members) => mapValues(members, (member, key) => {
1200
+ const extra = given[key];
1201
+ return extra === void 0 ? member : Object.freeze({
1202
+ ...member,
1203
+ metadata: Metadata.combine([member.metadata, extra])
1204
+ });
1205
+ });
1206
+ return make({
1207
+ ...entity,
1208
+ fields: annotate(entity.fields),
1209
+ relations: annotate(entity.relations),
1210
+ derived: annotate(entity.derived)
1211
+ });
1212
+ },
1213
+ /**
1214
+ * Reads an operation's input schema against an Entity. A key that names a
1215
+ * field maps to it; any other key is mapped explicitly, to a Field, to
1216
+ * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
1217
+ * from a naming convention such as `authorId`.
1218
+ */
1219
+ input: (entity, schema, ...mapping) => {
1220
+ const written = mapping[0] ?? {};
1221
+ 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`);
1222
+ const named = (key, name) => {
1223
+ const member = entity.members[name];
1224
+ switch (member?._tag) {
1225
+ case "Field": return member;
1226
+ case "Relation": return Object.freeze({
1227
+ _tag: "RelationInput",
1228
+ relation: member
1229
+ });
1230
+ case "Derived":
1231
+ case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
1232
+ }
1233
+ };
1234
+ const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
1235
+ const fields = entity.fields;
1236
+ const members = mapValues(schema.fields, (_, key) => {
1237
+ const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
1238
+ 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`);
1239
+ if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
1240
+ 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}"`);
1241
+ return member;
1242
+ });
1243
+ return Object.freeze({
1244
+ entity,
1245
+ schema,
1246
+ members: Object.freeze(members)
1247
+ });
1248
+ },
1249
+ /** For an input key that is about the operation rather than the Entity. */
1250
+ unmapped,
1251
+ /**
1252
+ * The schemas of some of an Entity's fields, by key, to spread into an input's
1253
+ * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
1254
+ * The input then keeps the field's own rules, and its keys map themselves.
1255
+ */
1256
+ fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
1257
+ /**
1258
+ * The Selection of every member an input writes, with each relation as refs:
1259
+ * what an edit screen loads before it shows the input's current values.
1260
+ */
1261
+ selectFor: (input) => {
1262
+ const members = input.members;
1263
+ 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)]] : []));
1264
+ return Entity.select(input.entity, spec);
1265
+ },
1266
+ /**
1267
+ * The input values that reproduce `value`, a value read through `selectFor`
1268
+ * (or any Selection with those members): a field as it is, a relation as the
1269
+ * id or ids of its refs. A key whose member `value` lacks is left out, as is
1270
+ * an unmapped key, which the Entity knows nothing about.
1271
+ */
1272
+ valuesFor: (input, value) => {
1273
+ const members = input.members;
1274
+ const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
1275
+ const entries = Object.entries(members).flatMap(([key, member]) => {
1276
+ if (member._tag === "Unmapped") return [];
1277
+ const written = member._tag === "Field" ? member.key : member.relation.key;
1278
+ if (!(written in value)) return [];
1279
+ const read = value[written];
1280
+ switch (member._tag) {
1281
+ case "Field": return [[key, read]];
1282
+ case "NestedInput": {
1283
+ const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
1284
+ return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
1285
+ }
1286
+ case "RelationInput": {
1287
+ const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
1288
+ return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
1289
+ }
1290
+ }
1291
+ });
1292
+ return Object.fromEntries(entries);
1293
+ },
1294
+ is: isEntity,
1295
+ /** True when both descriptors are versions of one Entity. */
1296
+ same: isSameEntity
1297
+ };
1298
+ function one(target, options) {
1299
+ return {
1300
+ target,
1301
+ cardinality: "one",
1302
+ optional: options?.optional ?? false
1303
+ };
1304
+ }
1305
+ /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
1306
+ const Relation = {
1307
+ one,
1308
+ /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
1309
+ input: (relation) => Object.freeze({
1310
+ _tag: "RelationInput",
1311
+ relation
1312
+ }),
1313
+ /**
1314
+ * For `Entity.input`: the input key holds the relation's target itself, written
1315
+ * through `input`, an `Entity.input` of the target. A `many` holds a list.
1316
+ */
1317
+ nested: (relation, input) => Object.freeze({
1318
+ _tag: "NestedInput",
1319
+ relation,
1320
+ input
1321
+ }),
1322
+ many: (target) => ({
1323
+ target,
1324
+ cardinality: "many",
1325
+ optional: false
1326
+ })
1327
+ };
1328
+ const Derived = { make: (schema) => ({ schema }) };
1329
+ //#endregion
1330
+ export { SchemaShape as S, Query as _, SelectionPageTypeId as a, maxQueryNodes as b, QueryEvaluateError as c, evaluate as d, supported as f, Order as g, Expr as h, Relation as i, assertSupported as l, ReadFilter as m, Entity as n, SelectionTypeId as o, Words as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, dependenciesOf as v, Collation as x, isPredicate as y };
1331
+
1332
+ //# sourceMappingURL=src-BtxgsdKb.mjs.map