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.
package/dist/index.mjs CHANGED
@@ -1,818 +1,2 @@
1
- import { 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/expr.ts
20
- /**
21
- * `Expr` — a query's scalar computations as typed values.
22
- *
23
- * An Entity says what a domain has; an `Expr` says something about one row of
24
- * it. A field reference, an input placeholder, a literal, and comparisons of
25
- * those are all immutable data: building one performs no work, reads nothing,
26
- * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
27
- * to SQL, an in-memory evaluator to a predicate over rows.
28
- *
29
- * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
30
- * operation here is one a real query in this repository needs; the set grows
31
- * from queries, not from what a database could express.
32
- */
33
- const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
34
- /**
35
- * An Entity's field and a `FieldExpr` are the same three members under the same
36
- * tag — the Entity's carries `metadata` besides — so this reads either and is
37
- * idempotent on its own output. Nothing needs to tell them apart, which is
38
- * better than telling them apart by which extra member happens to be present.
39
- */
40
- const literal = (value) => ({
41
- _tag: "Literal",
42
- value
43
- });
44
- const fieldExpr = (field) => ({
45
- _tag: "Field",
46
- owner: field.owner,
47
- key: field.key,
48
- schema: field.schema
49
- });
50
- const predicateTags = /* @__PURE__ */ new Set([
51
- "Eq",
52
- "Null",
53
- "Contains"
54
- ]);
55
- /** Whether a value is a predicate, and so usable where a boolean is wanted. */
56
- const isPredicate = (value) => predicateTags.has(tagOf(value));
57
- /**
58
- * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
59
- * itself, and anything else is the constant it is.
60
- */
61
- const toOperand = (value) => {
62
- const tag = tagOf(value);
63
- if (tag === "Field") return fieldExpr(value);
64
- if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
65
- return literal(value);
66
- };
67
- /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
68
- const toExpr = (value, step) => {
69
- const operand = toOperand(value);
70
- 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`);
71
- return operand;
72
- };
73
- const Expr = {
74
- /** A constant. Comparisons coerce a plain value, so this is rarely written. */
75
- literal,
76
- /**
77
- * A value the query is given when it runs. A definition builds these from its
78
- * `Input` schema; written by hand only when constructing a body directly.
79
- */
80
- input: (key, schema) => ({
81
- _tag: "Input",
82
- key,
83
- schema
84
- }),
85
- /** One field of one Entity, as a scalar. */
86
- field: (field) => fieldExpr(field),
87
- /**
88
- * Two scalars are the same value. A field or a plain value on either side is
89
- * coerced, so the common form reads as it means:
90
- *
91
- * ```ts
92
- * Expr.eq(Post.fields.slug, input.slug)
93
- * Expr.eq(Post.fields.status, 'active')
94
- * ```
95
- */
96
- eq: (left, right) => ({
97
- _tag: "Eq",
98
- left: toOperand(left),
99
- right: toOperand(right)
100
- }),
101
- /**
102
- * Whether a field holds no value. Its opposite is `isNotNull`; both are the
103
- * one node, because a query asks which of the two it means and nothing here
104
- * can negate a predicate.
105
- */
106
- isNull: (operand) => ({
107
- _tag: "Null",
108
- operand: toExpr(operand, "isNull"),
109
- present: false
110
- }),
111
- /** Whether a field holds a value. */
112
- isNotNull: (operand) => ({
113
- _tag: "Null",
114
- operand: toExpr(operand, "isNotNull"),
115
- present: true
116
- }),
117
- /**
118
- * Whether a text value contains `search`, anywhere in it. Containing the
119
- * empty string is everything, so a search box with nothing typed in it is the
120
- * same query as one with something — no branch, and no second query.
121
- *
122
- * **Case-insensitive**, which is what a search means, and which has to be
123
- * said rather than left to the interpreter: SQLite's `like` ignores case and
124
- * Postgres's does not, so a body that left it open would mean two things.
125
- * Folding is ASCII-only, because that is what `lower` does in SQLite without
126
- * ICU.
127
- *
128
- * **Over a column that can be null this is not the same as no filter.** A
129
- * null contains nothing, not even the empty string, so its rows drop out. A
130
- * nullable column that should match everything on an empty search says so:
131
- * `Expr.or` does not exist yet, so for now such a column needs its own
132
- * predicate or a native escape hatch.
133
- */
134
- contains: (value, search) => ({
135
- _tag: "Contains",
136
- value: toExpr(value, "contains"),
137
- search: toOperand(search)
138
- }),
139
- /** An expression as readable text; see `showExpr` for what it is and is not. */
140
- show: (node) => showExpr(node)
141
- };
142
- const Order = {
143
- asc: (expr) => ({
144
- direction: "asc",
145
- expr: toExpr(expr, "asc")
146
- }),
147
- desc: (expr) => ({
148
- direction: "desc",
149
- expr: toExpr(expr, "desc")
150
- })
151
- };
152
- const walk = (node, fields, inputs, operations) => {
153
- switch (node._tag) {
154
- case "Literal": return;
155
- case "Field":
156
- fields.set(`${node.owner.name}.${node.key}`, {
157
- entity: node.owner.name,
158
- key: node.key
159
- });
160
- return;
161
- case "Input":
162
- inputs.add(node.key);
163
- return;
164
- case "Eq":
165
- operations.add("eq");
166
- walk(node.left, fields, inputs, operations);
167
- walk(node.right, fields, inputs, operations);
168
- return;
169
- case "Null":
170
- operations.add(node.present ? "isNotNull" : "isNull");
171
- walk(node.operand, fields, inputs, operations);
172
- return;
173
- case "Contains":
174
- operations.add("contains");
175
- walk(node.value, fields, inputs, operations);
176
- walk(node.search, fields, inputs, operations);
177
- return;
178
- }
179
- };
180
- /**
181
- * What an expression reads and uses, for the planner and for an interpreter
182
- * deciding whether it can run this query at all. Distinct entries only, in the
183
- * order first seen, so the answer is stable enough to assert on.
184
- */
185
- const dependenciesOf = (...nodes) => {
186
- const fields = /* @__PURE__ */ new Map();
187
- const inputs = /* @__PURE__ */ new Set();
188
- const operations = /* @__PURE__ */ new Set();
189
- for (const node of nodes) walk("direction" in node ? node.expr : node, fields, inputs, operations);
190
- return {
191
- fields: [...fields.values()],
192
- inputs: [...inputs],
193
- operations: [...operations]
194
- };
195
- };
196
- /** Every field an expression reads, as the nodes themselves. */
197
- const fieldsIn = function* (node) {
198
- switch (node._tag) {
199
- case "Field":
200
- yield node;
201
- return;
202
- case "Literal":
203
- case "Input": return;
204
- case "Eq":
205
- yield* fieldsIn(node.left);
206
- yield* fieldsIn(node.right);
207
- return;
208
- case "Null":
209
- yield* fieldsIn(node.operand);
210
- return;
211
- case "Contains":
212
- yield* fieldsIn(node.value);
213
- yield* fieldsIn(node.search);
214
- return;
215
- }
216
- };
217
- /**
218
- * A query reads one Entity, so a predicate or ordering term naming a different
219
- * one cannot be answered — an interpreter would be asked for a column of a
220
- * table it was never told to read. Compared by identity, not by name, because
221
- * two Entities defined with the same name are two Entities.
222
- */
223
- const checkOwnership = (step, what, entity, nodes) => {
224
- for (const node of nodes) for (const field of fieldsIn("direction" in node ? node.expr : node)) 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}`);
225
- };
226
- const QueryProto = {
227
- _tag: "Query",
228
- pipe() {
229
- return Pipeable.pipeArguments(this, arguments);
230
- }
231
- };
232
- const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
233
- entity,
234
- where: Object.freeze(where),
235
- orderBy: Object.freeze(orderBy)
236
- }));
237
- const Query = {
238
- /** Every row of an Entity: the query each transformation narrows. */
239
- from: (entity) => query(entity, [], []),
240
- /**
241
- * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
242
- * second never replaces the first — so a fragment can be written once and
243
- * piped into any query over the same Entity:
244
- *
245
- * ```ts
246
- * const published = Query.where(Expr.eq(Post.fields.published, true))
247
- * Query.from(Post).pipe(published, Query.where(byTitle))
248
- * ```
249
- */
250
- where: (...predicates) => (self) => {
251
- if (predicates.length === 0) return self;
252
- checkOwnership("where", "a predicate", self.entity, predicates);
253
- return query(self.entity, [...self.where, ...predicates], self.orderBy);
254
- },
255
- /**
256
- * Reads the rows in this order. Two `orderBy`s append, so an earlier term
257
- * stays the more significant one and a later call adds a tie-breaker rather
258
- * than silently winning.
259
- */
260
- orderBy: (...terms) => (self) => {
261
- if (terms.length === 0) return self;
262
- checkOwnership("orderBy", "a term", self.entity, terms);
263
- return query(self.entity, self.where, [...self.orderBy, ...terms]);
264
- },
265
- /**
266
- * What the whole query reads: the fields and inputs of every predicate and
267
- * every ordering term, and the operations it uses.
268
- */
269
- dependencies: (self) => dependenciesOf(...self.where, ...self.orderBy),
270
- /**
271
- * The operations this query needs that `supported` does not list, in the
272
- * order the query uses them. Empty means an interpreter declaring
273
- * `supported` can answer it.
274
- *
275
- * An interpreter declares what it runs and refuses the rest, rather than
276
- * ignoring an operation it does not implement — which would answer a
277
- * different question and say nothing. The refusal is the interpreter's to
278
- * raise: this only says what is missing, because what to do about it differs
279
- * between one that compiles at registration and one that runs a body
280
- * directly.
281
- *
282
- * ```ts
283
- * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
284
- * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
285
- * ```
286
- */
287
- unsupported: (self, supported) => {
288
- const runs = new Set(supported);
289
- return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
290
- },
291
- /**
292
- * The whole query as readable text, one clause per line:
293
- *
294
- * ```text
295
- * FROM Post
296
- * WHERE Post.slug = $slug
297
- * AND Post.published = true
298
- * ORDER BY Post.updatedAt DESC
299
- * ```
300
- *
301
- * For an explanation or a diagnostic, never for an interpreter — see
302
- * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
303
- * than printing an empty one, so what is shown is what was written.
304
- */
305
- show: (self) => [
306
- `FROM ${self.entity.name}`,
307
- ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
308
- ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`).join(", ")}`]
309
- ].join("\n")
310
- };
311
- /**
312
- * An expression as readable text, in the IR's own terms.
313
- *
314
- * This is for a human — an explanation, a diagnostic, a test that wants to
315
- * assert on a whole predicate at once — and deliberately **not** for an
316
- * interpreter. It is close enough to SQL to read at a glance and unlike it
317
- * everywhere that matters: an input is `$slug` rather than a bound parameter,
318
- * `contains` is named rather than rendered as somebody's `like`, and no
319
- * dialect's escaping or collation is implied. What actually ran is whatever
320
- * that backend compiled, which is not this.
321
- *
322
- * A predicate standing where a value is wanted is parenthesised, because
323
- * `x is not null = $archived` reads as three operands and is two. A predicate
324
- * that *is* the whole expression is not: nothing encloses it.
325
- */
326
- const showExpr = (node) => {
327
- switch (node._tag) {
328
- case "Literal": return JSON.stringify(node.value) ?? String(node.value);
329
- case "Field": return `${node.owner.name}.${node.key}`;
330
- case "Input": return `$${node.key}`;
331
- case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
332
- case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
333
- case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
334
- }
335
- };
336
- const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
337
- //#endregion
338
- //#region src/words.ts
339
- const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
340
- const Words = {
341
- /**
342
- * A schema's words, as a label and its help text. Under Effect 4 a checked
343
- * schema resolves to its last check's annotations, which say what the check
344
- * expects and carry no `title`, so a title given before the check is read from
345
- * the schema's own annotations. Read words through this, never through
346
- * `Schema.resolveAnnotations` directly.
347
- */
348
- of: (schema) => {
349
- const resolved = Schema.resolveAnnotations(schema) ?? {};
350
- const own = schema.ast.annotations ?? {};
351
- return {
352
- title: Option.orElse(text(resolved.title), () => text(own["title"])),
353
- description: Option.orElse(text(resolved.description), () => text(own["description"]))
354
- };
355
- } };
356
- //#endregion
357
- //#region src/evaluate.ts
358
- /**
359
- * The reference interpreter: a query body run over rows already in memory.
360
- *
361
- * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
362
- * directly, which is what makes "source-neutral" a fact rather than a claim —
363
- * the two are checked against each other over a real database, and a body that
364
- * means one thing here and another there is a bug in one of them.
365
- *
366
- * It is also the interpreter to reach for when there is no database: a test
367
- * that wants rows, a server assembling a page from values it already holds, or
368
- * a client judging rows it already has.
369
- *
370
- * It lives in `foldkit-entity` because it is the **reference semantics** of the
371
- * IR this package owns — what §6.0.1 means operationally rather than in prose —
372
- * and a specification's reference implementation belongs with the
373
- * specification. The rule that keeps it here: **it may depend on the IR and
374
- * nothing else.** The moment it wants a Remote concept it has moved to the
375
- * wrong place and should leave.
376
- *
377
- * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
378
- * because SQL is what the other interpreter runs. The important case is null:
379
- * `null = null` is unknown in SQL and a row is not matched by it, where
380
- * JavaScript would happily call the two equal.
381
- */
382
- var QueryEvaluateError = class extends Error {
383
- constructor(message) {
384
- super(`[foldkit-entity] ${message}`);
385
- this.name = "QueryEvaluateError";
386
- }
387
- };
388
- const valueOf = (node, row, input) => {
389
- switch (node._tag) {
390
- case "Field": return row[node.key];
391
- case "Literal": return node.value;
392
- case "Input": return input[node.key];
393
- }
394
- };
395
- const isNull = (value) => value === null || value === void 0;
396
- /** A predicate used as a value is its own truth; anything else is its value. */
397
- const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
398
- /**
399
- * A predicate compared as a value. SQL's unknown is null there too, so an
400
- * unknown compared to anything stays unknown rather than becoming false.
401
- */
402
- const truthValue = (truth) => truth === "unknown" ? null : truth;
403
- const holds = (node, row, input) => {
404
- switch (node._tag) {
405
- case "Eq": {
406
- const left = sideOf(node.left, row, input);
407
- const right = sideOf(node.right, row, input);
408
- if (isNull(left) || isNull(right)) return "unknown";
409
- return left === right;
410
- }
411
- case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
412
- case "Contains": {
413
- const value = valueOf(node.value, row, input);
414
- const search = sideOf(node.search, row, input);
415
- if (isNull(value) || isNull(search)) return "unknown";
416
- if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
417
- return value.toLowerCase().includes(search.toLowerCase());
418
- }
419
- }
420
- };
421
- /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
422
- const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
423
- const compare = (left, right, query) => {
424
- if (typeof left === "string" && typeof right === "string") return left < right ? -1 : left > right ? 1 : 0;
425
- if (typeof left === "number" && typeof right === "number") return left - right;
426
- if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
427
- throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`);
428
- };
429
- const ordered = (rows, terms, query) => {
430
- if (terms.length === 0) return [...rows];
431
- return [...rows].sort((left, right) => {
432
- for (const term of terms) {
433
- if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
434
- const a = left[term.expr.key];
435
- const b = right[term.expr.key];
436
- if (isNull(a) || isNull(b)) throw new QueryEvaluateError(`query "${query}" orders by "${term.expr.key}", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`);
437
- const sign = compare(a, b, query);
438
- if (sign !== 0) return term.direction === "asc" ? sign : -sign;
439
- }
440
- return 0;
441
- });
442
- };
443
- /**
444
- * The operations this interpreter runs. It is the reference, so this is the
445
- * whole kernel — but it is declared rather than assumed, because an
446
- * interpreter that gains an operator and forgets to say so is exactly what
447
- * `Query.unsupported` exists to catch.
448
- */
449
- const supported = [
450
- "eq",
451
- "isNull",
452
- "isNotNull",
453
- "contains"
454
- ];
455
- /**
456
- * Refuses a body needing an operation this interpreter does not run, rather
457
- * than skipping it and answering a different question. Called by `evaluate`;
458
- * call it directly to check a body once instead of on every run.
459
- */
460
- const assertSupported = (body) => {
461
- const missing = Query.unsupported(body, supported);
462
- if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
463
- };
464
- /**
465
- * The rows the body matches, in the order it asks for. Pure: it reads the rows
466
- * it is given and nothing else.
467
- *
468
- * `input` holds the values this run was given, by the keys the body's
469
- * placeholders were built with — the same record the query would be called
470
- * with anywhere else.
471
- */
472
- const evaluate = (body, input, rows) => {
473
- assertSupported(body);
474
- return ordered(rows.filter((row) => matches(body, row, input)), body.orderBy, body.entity.name);
475
- };
476
- //#endregion
477
- //#region src/index.ts
478
- /**
479
- * `foldkit-entity` — domain structure as typed values.
480
- *
481
- * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
482
- * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
483
- * values an interpreter supplies). It describes; it fetches, stores, and
484
- * renders nothing. Remote, Drizzle, and form packages interpret it and attach
485
- * what they need as `foldkit-metadata`.
486
- */
487
- const EntityTypeId = Symbol.for("foldkit-entity/Entity");
488
- const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
489
- const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
490
- /** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
491
- const idSchemaOf = (entity) => {
492
- const id = entity.fields.id;
493
- if (id === void 0 || id._tag !== "Field") return Schema.String;
494
- const type = Schema.toType(id.schema);
495
- return SchemaShape.isText(type.ast) ? type : Schema.String;
496
- };
497
- const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
498
- const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
499
- const unmapped = Object.freeze({ _tag: "Unmapped" });
500
- const EntityProto = {
501
- [EntityTypeId]: EntityTypeId,
502
- pipe() {
503
- return Pipeable.pipeArguments(this, arguments);
504
- }
505
- };
506
- const make = (parts) => Object.freeze(Object.assign(Object.create(EntityProto), parts, {
507
- name: parts.identity.name,
508
- fields: Object.freeze(parts.fields),
509
- relations: Object.freeze(parts.relations),
510
- derived: Object.freeze(parts.derived),
511
- members: Object.freeze({
512
- ...parts.fields,
513
- ...parts.relations,
514
- ...parts.derived
515
- })
516
- }));
517
- const isSameEntity = (left, right) => left.identity.token === right.identity.token;
518
- const fail = (entity, message) => {
519
- throw new Error(`Entity "${entity.name}": ${message}`);
520
- };
521
- const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
522
- const kindName = {
523
- Field: "field",
524
- Relation: "relation",
525
- Derived: "derived member"
526
- };
527
- const kindOf = (entity, key) => {
528
- const member = entity.members[key];
529
- return member && kindName[member._tag];
530
- };
531
- const assertFree = (entity, keys, adding) => {
532
- for (const key of keys) {
533
- const kind = kindOf(entity, key);
534
- if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
535
- }
536
- };
537
- const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
538
- const Entity = {
539
- /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
540
- define: (name, schema) => {
541
- const identity = Object.freeze({
542
- name,
543
- token: Symbol(name)
544
- });
545
- return make({
546
- identity,
547
- schema,
548
- fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
549
- _tag: "Field",
550
- owner: identity,
551
- key,
552
- schema: fieldSchema,
553
- metadata: Metadata.empty
554
- })),
555
- relations: {},
556
- derived: {},
557
- metadata: Metadata.empty
558
- });
559
- },
560
- /**
561
- * Declares the relations between a set of Entities in one step, and returns
562
- * them related. One step, because Entities that point at each other cannot
563
- * each be declared in terms of the other.
564
- */
565
- relate: (entities, relations) => {
566
- const keyByToken = /* @__PURE__ */ new Map();
567
- for (const [key, entity] of Object.entries(entities)) {
568
- if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
569
- const earlier = keyByToken.get(entity.identity.token);
570
- if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
571
- keyByToken.set(entity.identity.token, key);
572
- }
573
- const given = relations;
574
- 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`);
575
- const related = {};
576
- for (const [ownerKey, entity] of Object.entries(entities)) {
577
- const specs = given[ownerKey] ?? {};
578
- assertFree(entity, Object.keys(specs), "relation");
579
- const added = mapValues(specs, (spec, key) => {
580
- const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
581
- if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
582
- return Object.freeze({
583
- _tag: "Relation",
584
- owner: entity.identity,
585
- key,
586
- target: () => related[targetKey],
587
- cardinality: spec.cardinality,
588
- optional: spec.optional,
589
- metadata: Metadata.empty
590
- });
591
- });
592
- related[ownerKey] = make({
593
- ...entity,
594
- relations: {
595
- ...entity.relations,
596
- ...added
597
- }
598
- });
599
- }
600
- return Object.freeze(related);
601
- },
602
- /**
603
- * Selects members of an Entity and assembles the schema of the result. A
604
- * relation selected with `true` yields an `EntityRef`; with a Selection of its
605
- * target, that Selection's value. `many` yields an array, an optional `one`
606
- * is nullable.
607
- */
608
- select: (entity, spec) => {
609
- const members = entity.members;
610
- const fields = mapValues(spec, (selected, key) => {
611
- const member = members[key];
612
- if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
613
- if (member._tag !== "Relation") {
614
- if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
615
- return member.schema;
616
- }
617
- const target = member.target();
618
- if (isSelectionPage(selected)) {
619
- if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
620
- if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
621
- return Schema.Struct({
622
- items: Schema.Array(selected.selection.schema),
623
- hasNext: Schema.Boolean,
624
- hasPrevious: Schema.Boolean
625
- });
626
- }
627
- let item;
628
- if (selected === true) item = Schema.Struct({
629
- entity: Schema.Literal(target.name),
630
- id: idSchemaOf(target)
631
- });
632
- else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
633
- else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
634
- return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
635
- });
636
- return Object.freeze({
637
- [SelectionTypeId]: SelectionTypeId,
638
- entity,
639
- members: spec,
640
- schema: Schema.Struct(fields)
641
- });
642
- },
643
- /**
644
- * A `many` relation read a page at a time, in place of its Selection:
645
- * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
646
- * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
647
- */
648
- page: (selection, window) => {
649
- const sides = [window.first, window.last].filter((size) => size !== void 0);
650
- 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`);
651
- 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`);
652
- return Object.freeze({
653
- [SelectionPageTypeId]: SelectionPageTypeId,
654
- selection,
655
- window
656
- });
657
- },
658
- /** Adds readable members that are not part of `entity.schema`. */
659
- derived: (specs) => (entity) => {
660
- assertFree(entity, Object.keys(specs), "derived member");
661
- const added = mapValues(specs, (spec, key) => Object.freeze({
662
- _tag: "Derived",
663
- owner: entity.identity,
664
- key,
665
- schema: spec.schema,
666
- metadata: Metadata.empty
667
- }));
668
- return make({
669
- ...entity,
670
- derived: {
671
- ...entity.derived,
672
- ...added
673
- }
674
- });
675
- },
676
- /** Attaches an interpreter's metadata to the Entity itself. */
677
- annotate: (metadata) => (entity) => make({
678
- ...entity,
679
- metadata: Metadata.combine([entity.metadata, metadata])
680
- }),
681
- /** Attaches an interpreter's metadata to members, by key. */
682
- annotateMembers: (metadata) => (entity) => {
683
- const given = metadata;
684
- 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`);
685
- const annotate = (members) => mapValues(members, (member, key) => {
686
- const extra = given[key];
687
- return extra === void 0 ? member : Object.freeze({
688
- ...member,
689
- metadata: Metadata.combine([member.metadata, extra])
690
- });
691
- });
692
- return make({
693
- ...entity,
694
- fields: annotate(entity.fields),
695
- relations: annotate(entity.relations),
696
- derived: annotate(entity.derived)
697
- });
698
- },
699
- /**
700
- * Reads an operation's input schema against an Entity. A key that names a
701
- * field maps to it; any other key is mapped explicitly, to a Field, to
702
- * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
703
- * from a naming convention such as `authorId`.
704
- */
705
- input: (entity, schema, ...mapping) => {
706
- const written = mapping[0] ?? {};
707
- 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`);
708
- const named = (key, name) => {
709
- const member = entity.members[name];
710
- switch (member?._tag) {
711
- case "Field": return member;
712
- case "Relation": return Object.freeze({
713
- _tag: "RelationInput",
714
- relation: member
715
- });
716
- case "Derived":
717
- case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
718
- }
719
- };
720
- const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
721
- const fields = entity.fields;
722
- const members = mapValues(schema.fields, (_, key) => {
723
- const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
724
- 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`);
725
- if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
726
- 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}"`);
727
- return member;
728
- });
729
- return Object.freeze({
730
- entity,
731
- schema,
732
- members: Object.freeze(members)
733
- });
734
- },
735
- /** For an input key that is about the operation rather than the Entity. */
736
- unmapped,
737
- /**
738
- * The schemas of some of an Entity's fields, by key, to spread into an input's
739
- * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
740
- * The input then keeps the field's own rules, and its keys map themselves.
741
- */
742
- fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
743
- /**
744
- * The Selection of every member an input writes, with each relation as refs:
745
- * what an edit screen loads before it shows the input's current values.
746
- */
747
- selectFor: (input) => {
748
- const members = input.members;
749
- 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)]] : []));
750
- return Entity.select(input.entity, spec);
751
- },
752
- /**
753
- * The input values that reproduce `value`, a value read through `selectFor`
754
- * (or any Selection with those members): a field as it is, a relation as the
755
- * id or ids of its refs. A key whose member `value` lacks is left out, as is
756
- * an unmapped key, which the Entity knows nothing about.
757
- */
758
- valuesFor: (input, value) => {
759
- const members = input.members;
760
- const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
761
- const entries = Object.entries(members).flatMap(([key, member]) => {
762
- if (member._tag === "Unmapped") return [];
763
- const written = member._tag === "Field" ? member.key : member.relation.key;
764
- if (!(written in value)) return [];
765
- const read = value[written];
766
- switch (member._tag) {
767
- case "Field": return [[key, read]];
768
- case "NestedInput": {
769
- const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
770
- return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
771
- }
772
- case "RelationInput": {
773
- const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
774
- return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
775
- }
776
- }
777
- });
778
- return Object.fromEntries(entries);
779
- },
780
- is: isEntity,
781
- /** True when both descriptors are versions of one Entity. */
782
- same: isSameEntity
783
- };
784
- function one(target, options) {
785
- return {
786
- target,
787
- cardinality: "one",
788
- optional: options?.optional ?? false
789
- };
790
- }
791
- /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
792
- const Relation = {
793
- one,
794
- /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
795
- input: (relation) => Object.freeze({
796
- _tag: "RelationInput",
797
- relation
798
- }),
799
- /**
800
- * For `Entity.input`: the input key holds the relation's target itself, written
801
- * through `input`, an `Entity.input` of the target. A `many` holds a list.
802
- */
803
- nested: (relation, input) => Object.freeze({
804
- _tag: "NestedInput",
805
- relation,
806
- input
807
- }),
808
- many: (target) => ({
809
- target,
810
- cardinality: "many",
811
- optional: false
812
- })
813
- };
814
- const Derived = { make: (schema) => ({ schema }) };
815
- //#endregion
816
- export { Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, Relation, SchemaShape, SelectionPageTypeId, SelectionTypeId, Words, assertSupported, dependenciesOf, evaluate, isPredicate, supported };
817
-
818
- //# sourceMappingURL=index.mjs.map
1
+ import { S as SchemaShape, _ as Query, a as SelectionPageTypeId, b as maxQueryNodes, c as QueryEvaluateError, d as evaluate, f as supported, g as Order, h as Expr, i as Relation, l as assertSupported, m as ReadFilter, n as Entity, o as SelectionTypeId, p as Words, r as EntityTypeId, s as Write, t as Derived, u as compareRows, v as dependenciesOf, x as Collation, y as isPredicate } from "./src-BtxgsdKb.mjs";
2
+ export { Collation, Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, ReadFilter, Relation, SchemaShape, SelectionPageTypeId, SelectionTypeId, Words, Write, assertSupported, compareRows, dependenciesOf, evaluate, isPredicate, maxQueryNodes, supported };