foldkit-entity 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +139 -5
  2. package/dist/collation.d.ts +33 -2
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/conformance/index.d.ts +4 -4
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +5 -7
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/conformance/operator.d.ts +1 -2
  9. package/dist/conformance/operator.d.ts.map +1 -1
  10. package/dist/conformance/operator.js +2 -6
  11. package/dist/conformance/operator.js.map +1 -1
  12. package/dist/conformance/relational.d.ts +17 -17
  13. package/dist/conformance/relational.d.ts.map +1 -1
  14. package/dist/conformance/relational.js +1 -3
  15. package/dist/conformance/relational.js.map +1 -1
  16. package/dist/conformance/variants.d.ts +47 -0
  17. package/dist/conformance/variants.d.ts.map +1 -0
  18. package/dist/conformance/variants.js +126 -0
  19. package/dist/conformance/variants.js.map +1 -0
  20. package/dist/context.d.ts +60 -2
  21. package/dist/context.d.ts.map +1 -0
  22. package/dist/descriptor.d.ts +33 -0
  23. package/dist/descriptor.d.ts.map +1 -0
  24. package/dist/descriptor.js +137 -0
  25. package/dist/descriptor.js.map +1 -0
  26. package/dist/entity.d.ts +231 -0
  27. package/dist/entity.d.ts.map +1 -0
  28. package/dist/entity.js +435 -0
  29. package/dist/entity.js.map +1 -0
  30. package/dist/evaluate.d.ts +204 -2
  31. package/dist/evaluate.d.ts.map +1 -0
  32. package/dist/evaluate.js +51 -7
  33. package/dist/evaluate.js.map +1 -1
  34. package/dist/expr.d.ts +915 -2
  35. package/dist/expr.d.ts.map +1 -0
  36. package/dist/expr.js +50 -10
  37. package/dist/expr.js.map +1 -1
  38. package/dist/held.d.ts +112 -2
  39. package/dist/held.d.ts.map +1 -0
  40. package/dist/held.js +13 -2
  41. package/dist/held.js.map +1 -1
  42. package/dist/ids.d.ts +8 -0
  43. package/dist/ids.d.ts.map +1 -0
  44. package/dist/ids.js +8 -0
  45. package/dist/ids.js.map +1 -0
  46. package/dist/index.d.ts +380 -6
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +108 -12
  49. package/dist/index.js.map +1 -0
  50. package/dist/invariant.d.ts +123 -2
  51. package/dist/invariant.d.ts.map +1 -0
  52. package/dist/invariant.js +236 -1
  53. package/dist/invariant.js.map +1 -0
  54. package/dist/law.d.ts +264 -2
  55. package/dist/law.d.ts.map +1 -0
  56. package/dist/law.js +1 -1
  57. package/dist/operators.d.ts +170 -2
  58. package/dist/operators.d.ts.map +1 -0
  59. package/dist/operators.js +3 -3
  60. package/dist/readFilter.d.ts +8 -2
  61. package/dist/readFilter.d.ts.map +1 -0
  62. package/dist/sets.d.ts +18 -2
  63. package/dist/sets.d.ts.map +1 -0
  64. package/dist/sets.js +1 -1
  65. package/dist/shape.d.ts +23 -2
  66. package/dist/shape.d.ts.map +1 -0
  67. package/dist/tested.d.ts +8 -2
  68. package/dist/tested.d.ts.map +1 -0
  69. package/dist/text.d.ts +27 -2
  70. package/dist/text.d.ts.map +1 -0
  71. package/dist/text.js +1 -1
  72. package/dist/variants.d.ts +72 -0
  73. package/dist/variants.d.ts.map +1 -0
  74. package/dist/variants.js +76 -0
  75. package/dist/variants.js.map +1 -0
  76. package/dist/words.d.ts +17 -2
  77. package/dist/words.d.ts.map +1 -0
  78. package/dist/write.d.ts +312 -2
  79. package/dist/write.d.ts.map +1 -0
  80. package/dist/write.js +3 -3
  81. package/package.json +3 -3
  82. package/dist/collation-BB4YTIbY.d.ts +0 -34
  83. package/dist/collation-BB4YTIbY.d.ts.map +0 -1
  84. package/dist/index-48JeXG0A.d.ts +0 -2585
  85. package/dist/index-48JeXG0A.d.ts.map +0 -1
  86. package/dist/readFilter-CWMnFRVw.d.ts +0 -9
  87. package/dist/readFilter-CWMnFRVw.d.ts.map +0 -1
  88. package/dist/shape-LAowRf9f.d.ts +0 -23
  89. package/dist/shape-LAowRf9f.d.ts.map +0 -1
  90. package/dist/src-DKhUqLoC.js +0 -731
  91. package/dist/src-DKhUqLoC.js.map +0 -1
  92. package/dist/words-a4e9o-TK.d.ts +0 -18
  93. package/dist/words-a4e9o-TK.d.ts.map +0 -1
@@ -1,2585 +0,0 @@
1
- import { t as Collation } from "./collation-BB4YTIbY.js";
2
- import "./readFilter-CWMnFRVw.js";
3
- import "./words-a4e9o-TK.js";
4
- import "./shape-LAowRf9f.js";
5
- import { Array, Data, Effect, Option, Pipeable, Schema, SchemaAST } from "effect";
6
- import { Metadata } from "foldkit-metadata";
7
- /** An operator a law names as a witness: the inverse, or the operator distributed over. */
8
- type AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>;
9
- /** Which argument a witness stands in. */
10
- type Side = 'left' | 'right' | 'both';
11
- /**
12
- * A law, over its domain: by default every non-null value of the operator's
13
- * input schemas; narrowed by `Law.within`.
14
- */
15
- type Law = Data.TaggedEnum<{
16
- /** `op(op(a, b), c) = op(a, op(b, c))` */
17
- Associative: {
18
- readonly domain: Option.Option<Schema.Top>;
19
- };
20
- /** `op(a, b) = op(b, a)` */
21
- Commutative: {
22
- readonly domain: Option.Option<Schema.Top>;
23
- };
24
- /** `op(a, a) = a` */
25
- Idempotent: {
26
- readonly domain: Option.Option<Schema.Top>;
27
- };
28
- /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */
29
- Identity: {
30
- readonly domain: Option.Option<Schema.Top>;
31
- readonly value: unknown;
32
- readonly side: Side;
33
- };
34
- /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */
35
- Absorbing: {
36
- readonly domain: Option.Option<Schema.Top>;
37
- readonly value: unknown;
38
- readonly side: Side;
39
- };
40
- /** `op(a, other(a)) = identity` */
41
- Inverse: {
42
- readonly domain: Option.Option<Schema.Top>;
43
- readonly other: AnyOperator;
44
- readonly identity: unknown;
45
- };
46
- /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */
47
- Distributes: {
48
- readonly domain: Option.Option<Schema.Top>;
49
- readonly over: AnyOperator;
50
- };
51
- /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */
52
- Monotonic: {
53
- readonly domain: Option.Option<Schema.Top>;
54
- readonly direction: 'increasing' | 'decreasing';
55
- readonly position: number;
56
- };
57
- /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */
58
- PreservesCollation: {
59
- readonly domain: Option.Option<Schema.Top>;
60
- };
61
- }>;
62
- /**
63
- * A law as JSON says it: what `Operators.describe` lists and evidence names.
64
- * Its witnesses are values as stored and operators by name; its domain is a
65
- * JSON Schema, or `null` for the operator's whole input.
66
- */
67
- declare const LawDescription: Schema.Struct<{
68
- readonly kind: Schema.String;
69
- readonly witnesses: Schema.$Record<Schema.String, Schema.Unknown>;
70
- readonly domain: Schema.Unknown;
71
- }>;
72
- type LawDescription = typeof LawDescription.Type;
73
- declare const Law: {
74
- associative: {
75
- readonly _tag: "Associative";
76
- readonly domain: Option.Option<Schema.Top>;
77
- };
78
- commutative: {
79
- readonly _tag: "Commutative";
80
- readonly domain: Option.Option<Schema.Top>;
81
- };
82
- idempotent: {
83
- readonly _tag: "Idempotent";
84
- readonly domain: Option.Option<Schema.Top>;
85
- };
86
- preservesCollation: {
87
- readonly _tag: "PreservesCollation";
88
- readonly domain: Option.Option<Schema.Top>;
89
- };
90
- /** `value` leaves the other argument as it is, from `side` (both by default). */
91
- identity: (value: unknown, side?: Side) => Law;
92
- /** `value` is the answer whatever the other argument, from `side` (both by default). */
93
- absorbing: (value: unknown, side?: Side) => Law;
94
- /** `other` undoes the operator: `op(a, other(a))` is `identity`. */
95
- inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(other: Operator<In, Out>, identity: unknown) => Law;
96
- /** The operator distributes over `over`, from the left. */
97
- distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(over: Operator<In, Out>) => Law;
98
- /** Moving the argument at `position` up moves the result up (or down, decreasing). */
99
- monotonic: (direction: 'increasing' | 'decreasing', position: number) => Law;
100
- /**
101
- * The law over the values `domain` accepts only: a law that holds of the
102
- * integers and not of every number, say, narrowed so it is tested where it
103
- * is claimed.
104
- */
105
- within: (law: Law, domain: Schema.Top) => Law;
106
- $match: {
107
- <Cases extends { readonly [Tag in "Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]: (args: Extract<{
108
- readonly _tag: "Absorbing";
109
- readonly domain: Option.Option<Schema.Top>;
110
- readonly value: unknown;
111
- readonly side: Side;
112
- } | {
113
- readonly _tag: "Associative";
114
- readonly domain: Option.Option<Schema.Top>;
115
- } | {
116
- readonly _tag: "Commutative";
117
- readonly domain: Option.Option<Schema.Top>;
118
- } | {
119
- readonly _tag: "Distributes";
120
- readonly domain: Option.Option<Schema.Top>;
121
- readonly over: AnyOperator;
122
- } | {
123
- readonly _tag: "Idempotent";
124
- readonly domain: Option.Option<Schema.Top>;
125
- } | {
126
- readonly _tag: "Identity";
127
- readonly domain: Option.Option<Schema.Top>;
128
- readonly value: unknown;
129
- readonly side: Side;
130
- } | {
131
- readonly _tag: "Inverse";
132
- readonly domain: Option.Option<Schema.Top>;
133
- readonly other: AnyOperator;
134
- readonly identity: unknown;
135
- } | {
136
- readonly _tag: "Monotonic";
137
- readonly domain: Option.Option<Schema.Top>;
138
- readonly direction: 'increasing' | 'decreasing';
139
- readonly position: number;
140
- } | {
141
- readonly _tag: "PreservesCollation";
142
- readonly domain: Option.Option<Schema.Top>;
143
- }, {
144
- readonly _tag: Tag;
145
- }>) => any; }>(cases: Cases): (value: {
146
- readonly _tag: "Absorbing";
147
- readonly domain: Option.Option<Schema.Top>;
148
- readonly value: unknown;
149
- readonly side: Side;
150
- } | {
151
- readonly _tag: "Associative";
152
- readonly domain: Option.Option<Schema.Top>;
153
- } | {
154
- readonly _tag: "Commutative";
155
- readonly domain: Option.Option<Schema.Top>;
156
- } | {
157
- readonly _tag: "Distributes";
158
- readonly domain: Option.Option<Schema.Top>;
159
- readonly over: AnyOperator;
160
- } | {
161
- readonly _tag: "Idempotent";
162
- readonly domain: Option.Option<Schema.Top>;
163
- } | {
164
- readonly _tag: "Identity";
165
- readonly domain: Option.Option<Schema.Top>;
166
- readonly value: unknown;
167
- readonly side: Side;
168
- } | {
169
- readonly _tag: "Inverse";
170
- readonly domain: Option.Option<Schema.Top>;
171
- readonly other: AnyOperator;
172
- readonly identity: unknown;
173
- } | {
174
- readonly _tag: "Monotonic";
175
- readonly domain: Option.Option<Schema.Top>;
176
- readonly direction: 'increasing' | 'decreasing';
177
- readonly position: number;
178
- } | {
179
- readonly _tag: "PreservesCollation";
180
- readonly domain: Option.Option<Schema.Top>;
181
- }) => import("effect/Unify").Unify<ReturnType<Cases["Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]>>;
182
- <Cases extends { readonly [Tag in "Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]: (args: Extract<{
183
- readonly _tag: "Absorbing";
184
- readonly domain: Option.Option<Schema.Top>;
185
- readonly value: unknown;
186
- readonly side: Side;
187
- } | {
188
- readonly _tag: "Associative";
189
- readonly domain: Option.Option<Schema.Top>;
190
- } | {
191
- readonly _tag: "Commutative";
192
- readonly domain: Option.Option<Schema.Top>;
193
- } | {
194
- readonly _tag: "Distributes";
195
- readonly domain: Option.Option<Schema.Top>;
196
- readonly over: AnyOperator;
197
- } | {
198
- readonly _tag: "Idempotent";
199
- readonly domain: Option.Option<Schema.Top>;
200
- } | {
201
- readonly _tag: "Identity";
202
- readonly domain: Option.Option<Schema.Top>;
203
- readonly value: unknown;
204
- readonly side: Side;
205
- } | {
206
- readonly _tag: "Inverse";
207
- readonly domain: Option.Option<Schema.Top>;
208
- readonly other: AnyOperator;
209
- readonly identity: unknown;
210
- } | {
211
- readonly _tag: "Monotonic";
212
- readonly domain: Option.Option<Schema.Top>;
213
- readonly direction: 'increasing' | 'decreasing';
214
- readonly position: number;
215
- } | {
216
- readonly _tag: "PreservesCollation";
217
- readonly domain: Option.Option<Schema.Top>;
218
- }, {
219
- readonly _tag: Tag;
220
- }>) => any; }>(value: {
221
- readonly _tag: "Absorbing";
222
- readonly domain: Option.Option<Schema.Top>;
223
- readonly value: unknown;
224
- readonly side: Side;
225
- } | {
226
- readonly _tag: "Associative";
227
- readonly domain: Option.Option<Schema.Top>;
228
- } | {
229
- readonly _tag: "Commutative";
230
- readonly domain: Option.Option<Schema.Top>;
231
- } | {
232
- readonly _tag: "Distributes";
233
- readonly domain: Option.Option<Schema.Top>;
234
- readonly over: AnyOperator;
235
- } | {
236
- readonly _tag: "Idempotent";
237
- readonly domain: Option.Option<Schema.Top>;
238
- } | {
239
- readonly _tag: "Identity";
240
- readonly domain: Option.Option<Schema.Top>;
241
- readonly value: unknown;
242
- readonly side: Side;
243
- } | {
244
- readonly _tag: "Inverse";
245
- readonly domain: Option.Option<Schema.Top>;
246
- readonly other: AnyOperator;
247
- readonly identity: unknown;
248
- } | {
249
- readonly _tag: "Monotonic";
250
- readonly domain: Option.Option<Schema.Top>;
251
- readonly direction: 'increasing' | 'decreasing';
252
- readonly position: number;
253
- } | {
254
- readonly _tag: "PreservesCollation";
255
- readonly domain: Option.Option<Schema.Top>;
256
- }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]>>;
257
- };
258
- /**
259
- * The operators a law, as JSON, calls besides its own (`inverse`'s and
260
- * `distributes`' witnesses), by name: evidence of it is of their
261
- * implementations too, and goes when one of them is replaced.
262
- */
263
- witnessesNamed: (law: LawDescription) => ReadonlyArray<string>;
264
- /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
265
- describe: (law: Law) => LawDescription;
266
- };
267
- /**
268
- * Whoever asks, as the row they are of `target`: shaped as a `one` relation
269
- * to that Entity, so a path can go on from it. Its value is the row's id; for
270
- * a visitor, or a viewer of another Entity, it is null, which compares as
271
- * SQL's unknown.
272
- */
273
- interface ViewerExpr<T, Name extends string = string> {
274
- readonly _tag: 'Viewer';
275
- readonly entity: EntityIdentity<Name>;
276
- readonly target: () => AnyEntity;
277
- readonly schema: Schema.Codec<T, unknown>;
278
- }
279
- /**
280
- * What the row of whoever asks holds, or the row reached from it through `one`
281
- * relations (`Expr.path(Expr.viewer(User), end)`): a field of that row. Null
282
- * for a visitor, a viewer of another Entity, a null link, or a row the reader
283
- * may not see. `Entity.sets` reads one, and so may a query body or a rule:
284
- * SQL reads the viewer's row under its Entity's `visible` rule, and the client
285
- * judges it from the rows it holds.
286
- */
287
- interface ViewerPathExpr<T> {
288
- readonly _tag: 'ViewerPath';
289
- readonly viewer: ViewerExpr<unknown>;
290
- /** The relations followed from the viewer's row, in order; empty for a field of it. */
291
- readonly via: ReadonlyArray<OneRelation$2>;
292
- readonly field: FieldExpr<T>;
293
- }
294
- /** The time of the write, in milliseconds since the epoch. */
295
- interface NowExpr<T> {
296
- readonly _tag: 'Now';
297
- readonly schema: Schema.Codec<T, unknown>;
298
- }
299
- /**
300
- * What the context terms read, as one side provides it: the viewer as a
301
- * ref, none for a visitor; the time, none where the side has no reading of
302
- * it (a client judging a list, which knows no time the server judged it at).
303
- */
304
- interface ExprContext {
305
- readonly viewer: Option.Option<EntityRef>;
306
- readonly now: Option.Option<number>;
307
- }
308
- /** `Expr.viewer`: whoever asks, as a row of `entity`. */
309
- declare const viewer: <E extends AnyEntity>(entity: E) => ViewerExpr<IdOf<E>, E['name']>;
310
- /** `Expr.now`: the time of the write. */
311
- declare const now: NowExpr<number>;
312
- /**
313
- * What a context term comes to in `context`, as an interpreter binds it: the
314
- * viewer's id when they are a row of the term's Entity, else null, as for a
315
- * visitor; the time. None when the side has no reading of the time, which is
316
- * not a null: an interpreter refuses what it cannot say.
317
- */
318
- declare const contextValue: (term: ViewerExpr<unknown> | NowExpr<unknown>, context: ExprContext) => Option.Option<string | number | null>;
319
- /** The viewer's id, when they are a row of `entity`. */
320
- declare const viewerIdOf: (entity: {
321
- readonly name: string;
322
- }, context: Pick<ExprContext, 'viewer'>) => Option.Option<string>;
323
- /** A constant the query was written with. */
324
- interface LiteralExpr<T> {
325
- readonly _tag: 'Literal';
326
- readonly value: T;
327
- }
328
- /**
329
- * One field of one Entity. `owner` is the Entity's identity rather than its
330
- * name, so two Entities defined with the same name are not one column.
331
- */
332
- interface FieldExpr<T> {
333
- readonly _tag: 'Field';
334
- readonly owner: EntityIdentity<string>;
335
- readonly key: string;
336
- readonly schema: Schema.Codec<T, unknown>;
337
- /**
338
- * How it compares when ordered by, as the field declares (`Collation.of`).
339
- * An id is `binary` unless it says otherwise: its order need only be total
340
- * and agreed, and every order ends on it.
341
- */
342
- readonly collation: Option.Option<Collation>;
343
- }
344
- /**
345
- * A value the query is given when it runs. A definition's body is built once,
346
- * so inside it an input is this placeholder and never the value: there is
347
- * nothing yet to branch on, and a query that wants to depend on what was passed
348
- * says so with an operation over the placeholder.
349
- */
350
- interface InputExpr<T> {
351
- readonly _tag: 'Input';
352
- readonly key: string;
353
- readonly schema: Schema.Codec<T, unknown>;
354
- }
355
- /**
356
- * A field as the row a write would leave holds it: what an invariant reads
357
- * (`after.status`, beside `before.status` over a change). An interpreter that judges stored
358
- * rows alone refuses it, as the operation `next`.
359
- */
360
- interface NextExpr<T> {
361
- readonly _tag: 'Next';
362
- readonly field: FieldExpr<T>;
363
- }
364
- /**
365
- * What an operator is, as the nodes that call it hold it: its identity, the
366
- * stored form of what it takes and gives, and, for an operator defined by an
367
- * expression, how to build that expression. It computes nothing itself.
368
- * Identity is this object; `id` and `version` name it.
369
- */
370
- interface OperatorDescriptor {
371
- readonly _tag: 'Operator';
372
- readonly id: string;
373
- readonly version: number;
374
- readonly description: Option.Option<string>;
375
- /** One schema per argument, read as the stored form. */
376
- readonly input: ReadonlyArray<Schema.Top>;
377
- readonly output: Schema.Top;
378
- /**
379
- * Builds the expression a call means, from its arguments: an operator defined
380
- * by an expression. None for a primitive operator, which each interpreter
381
- * implements (`Operators`).
382
- */
383
- readonly definedAs: Option.Option<(...args: ReadonlyArray<Operandish>) => Operandish>;
384
- /**
385
- * A primitive operator's null rule. `strict`: a null argument gives null, or
386
- * unknown for a predicate, and the implementation never sees one. `handled`:
387
- * the implementation is given nulls and answers for them.
388
- */
389
- readonly nulls: 'strict' | 'handled';
390
- /**
391
- * How a call compares text. `operands`: it carries the collation its collated
392
- * text arguments share, so its text result compares under it. `required`: the
393
- * same, refused where none is declared (it compares text itself, as
394
- * `Text.startsWith` does). `none`: it carries none.
395
- */
396
- readonly collation: 'none' | 'operands' | 'required';
397
- /** The equations every implementation keeps (`Law`), checked where declared, tested by `Conformance.laws`. */
398
- readonly laws: ReadonlyArray<Law>;
399
- }
400
- /** What an interpreter runs, as far as a check of a body needs to know. */
401
- interface OperatorTable {
402
- /** Whether this table implements the operator. */
403
- readonly has: (operator: OperatorDescriptor) => boolean;
404
- /**
405
- * The versions of the operator `id` it implements: what a refusal of a call
406
- * to another version names, since a client and a server on different
407
- * deploys can disagree on one.
408
- */
409
- readonly versions: (id: string) => ReadonlyArray<number>;
410
- }
411
- /** A table implementing nothing: every primitive operator is unsupported by it. */
412
- declare const noOperators: OperatorTable;
413
- /**
414
- * An operator `operators` does not implement, by name, with the versions of it
415
- * the table does implement: `acme.slug@2 (this table has acme.slug)`.
416
- */
417
- declare const missingName: (operator: OperatorDescriptor, operators: OperatorTable) => string;
418
- /**
419
- * A call of an operator whose result is a scalar. `expansion` is the
420
- * expression it means, built from its arguments when it was called: an
421
- * interpreter runs that, and needs nothing of its own for the operator.
422
- */
423
- interface CallExpr<T> {
424
- readonly _tag: 'Call';
425
- readonly operator: OperatorDescriptor;
426
- readonly args: ReadonlyArray<Operandish>;
427
- readonly expansion: Option.Option<Expr<T>>;
428
- /** How its text result compares, from its operator's `collation` rule. */
429
- readonly collation: Option.Option<Collation>;
430
- }
431
- /** A `one` relation of any Entity: what a path follows and an exists points through. */
432
- type OneRelation$2 = EntityRelation<string, string, AnyEntity, 'one', boolean>;
433
- /**
434
- * A field of the row reached from the row judged by following `one`
435
- * relations (`Expr.path`). A null link, or a row the reader may not see,
436
- * reaches no row, and the path reads null.
437
- */
438
- interface PathExpr<T> {
439
- readonly _tag: 'Path';
440
- /** The relations followed, in order, the first one the judged row's own. */
441
- readonly via: Array.NonEmptyReadonlyArray<OneRelation$2>;
442
- /** What is read on the row reached: a field of the last relation's target. */
443
- readonly field: FieldExpr<T>;
444
- }
445
- /** A typed scalar: what a comparison compares. */
446
- type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T> | NextExpr<T> | CallExpr<T> | ViewerExpr<T> | NowExpr<T> | PathExpr<T> | ViewerPathExpr<T>;
447
- /** Any scalar, for the places that hold operands without caring what they are. */
448
- type AnyExpr = Expr<unknown>;
449
- /**
450
- * `Expr<boolean>`, in the shape the operations that exist can actually take.
451
- * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,
452
- * `contains`, …), so a predicate is its own type rather than a phantom
453
- * parameter on a general operation node: `Predicate` and `Expr<string>` cannot
454
- * then be confused, which a structural phantom would allow. A scalar-valued
455
- * operation, if one is ever needed, joins `Expr` instead.
456
- */
457
- type Predicate = EqPredicate | NullPredicate | ContainsPredicate | InPredicate | AndPredicate | OrPredicate | NotPredicate | ComparePredicate | TestPredicate | ExistsPredicate;
458
- /**
459
- * Some row points at the row asked about through `relation`, a `one` relation
460
- * of another Entity, and holds `where` (`Expr.exists`). The row asked about is
461
- * the one judged, or the one `via` reaches from it; a path that reaches none
462
- * makes this unknown, as a path's field reads null. Only rows the reader may
463
- * see are sought.
464
- */
465
- interface ExistsPredicate {
466
- readonly _tag: 'Exists';
467
- /** The relations followed to the row asked about; empty for the row judged itself. */
468
- readonly via: ReadonlyArray<OneRelation$2>;
469
- readonly relation: OneRelation$2;
470
- /** What the pointing row must hold, over its own fields and the input. */
471
- readonly where: Option.Option<Predicate>;
472
- }
473
- /** Two values are the same. */
474
- interface EqPredicate {
475
- readonly _tag: 'Eq';
476
- readonly left: Operandish;
477
- readonly right: Operandish;
478
- }
479
- /**
480
- * Whether a value is absent. `present` says which answer absence gives, so one
481
- * node covers `is null` and `is not null` rather than two that differ by a
482
- * negation nothing else can express.
483
- */
484
- interface NullPredicate {
485
- readonly _tag: 'Null';
486
- readonly operand: AnyExpr;
487
- readonly present: boolean;
488
- }
489
- /**
490
- * Whether a text value contains another. Containing the empty string is
491
- * everything, which is what lets a search box with nothing typed in it be the
492
- * same query as one with something — see `Expr.contains`.
493
- */
494
- interface ContainsPredicate {
495
- readonly _tag: 'Contains';
496
- readonly value: AnyExpr;
497
- readonly search: Operandish;
498
- }
499
- /**
500
- * Whether a value is one of a list. The list is a scalar whose value is an
501
- * array: a literal, or an input (a principal's `projectIds`, a picker's
502
- * chosen ids). Read as SQL's `in`: a null value is unknown, and so is no
503
- * match against a list holding a null; an empty list matches nothing.
504
- */
505
- interface InPredicate {
506
- readonly _tag: 'In';
507
- readonly value: AnyExpr;
508
- readonly among: AnyExpr;
509
- }
510
- /**
511
- * Every operand holds. `Query.where`'s list is already a conjunction; this is
512
- * one inside something else, `or(and(a, b), c)`. Never empty, and never holding
513
- * another `and`: `Expr.and` flattens one into its parent.
514
- */
515
- interface AndPredicate {
516
- readonly _tag: 'And';
517
- readonly operands: Array.NonEmptyReadonlyArray<Predicate>;
518
- }
519
- /** At least one operand holds. Never empty, and never holding another `or`. */
520
- interface OrPredicate {
521
- readonly _tag: 'Or';
522
- readonly operands: Array.NonEmptyReadonlyArray<Predicate>;
523
- }
524
- /**
525
- * The operand does not hold. As SQL's `not`, an unknown stays unknown, so a row
526
- * whose operand is unknown (a null compared) is matched by neither the operand
527
- * nor its `not`.
528
- */
529
- interface NotPredicate {
530
- readonly _tag: 'Not';
531
- readonly operand: Predicate;
532
- }
533
- /** Which way a comparison orders its two sides: `left < right` for `lt`. */
534
- type CompareOperator = 'lt' | 'lte' | 'gt' | 'gte';
535
- /**
536
- * One scalar orders before, or after, the other. A null on either side is
537
- * unknown. `collation` is how text compares, decided where the comparison is
538
- * written (see `Expr.lt`); none for values that order intrinsically, numbers.
539
- */
540
- interface ComparePredicate {
541
- readonly _tag: 'Compare';
542
- readonly operator: CompareOperator;
543
- readonly left: AnyExpr;
544
- readonly right: AnyExpr;
545
- readonly collation: Option.Option<Collation>;
546
- }
547
- /**
548
- * A call of an operator whose result is a boolean, so it stands where any
549
- * predicate does: in `and`, `or` and `not`, a guard, an invariant. `expansion`
550
- * is the predicate it means, built when it was called.
551
- */
552
- interface TestPredicate {
553
- readonly _tag: 'Test';
554
- readonly operator: OperatorDescriptor;
555
- readonly args: ReadonlyArray<Operandish>;
556
- readonly expansion: Option.Option<Predicate>;
557
- /** The collation it compares text under, from its operator's `collation` rule. */
558
- readonly collation: Option.Option<Collation>;
559
- }
560
- /**
561
- * Anything an operation can be given: a scalar, or a predicate where a boolean
562
- * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the
563
- * second case, and it is how a query depends on an input without branching on
564
- * it.
565
- */
566
- type Operandish = AnyExpr | Predicate;
567
- /**
568
- * A field, a `one` relation (the id it points at), a scalar already built from
569
- * one, or a predicate used as a boolean.
570
- */
571
- type Operand<T> = OwnOperand<T> | OneRelation$2;
572
- /** A field, a scalar, or a predicate: what an order term takes, since no list orders by a link. */
573
- type OwnOperand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate;
574
- /**
575
- * Type-only: the Entities a predicate's fields belong to, by name, so
576
- * `Query.where` can refuse one over another Entity where it is written. Never
577
- * set at run time; a predicate built without it (typed plain `Predicate`)
578
- * reads as unknown and is checked at run time only.
579
- */
580
- interface Reads<Names extends string> {
581
- readonly '~reads'?: Names;
582
- }
583
- /**
584
- * The Entity names an operand reads: a field's own, a marked node's, none for
585
- * a value or an input. A node with no marker (a `Predicate` typed plainly)
586
- * reads as `string`, unknown.
587
- */
588
- type ReadsOf<X> = X extends EntityField<infer Name, string, Schema.Constraint> ? Name : X extends EntityRelation<infer Name, string, AnyEntity, 'one', boolean> ? Name : X extends PlainValue | {
589
- readonly _tag: 'Literal' | 'Input' | 'Viewer' | 'Now';
590
- } ? never : X extends {
591
- readonly '~reads'?: infer Names;
592
- } ? unknown extends Names ? string : Names extends string ? Names : never : never;
593
- /**
594
- * Nothing when a query's predicates read its own Entity, none, or one unknown
595
- * to the type (checked at run time instead); else a failure naming both.
596
- */
597
- type OverEntity<Names extends string, Name extends string, What extends string> = string extends Names ? unknown : [Names] extends [Name] ? unknown : Invalid<`foldkit-entity: ${What} reads ${Exclude<Names, Name>}, but the query is from ${Name}`>;
598
- /** A plain value, which `Expr.eq` takes on the right only. */
599
- type PlainValue = string | number | boolean | bigint | null;
600
- /** A compile-time failure whose type is the sentence that says what to do. */
601
- interface Invalid<Message extends string> {
602
- readonly '~invalid': Message;
603
- }
604
- /** What an operand is worth, so a comparison's other side is checked against it. */
605
- type ValueOf<E> = E extends EntityField<string, string, infer S> ? Schema.Schema.Type<S> : E extends EntityRelation<string, string, infer Target, 'one', infer Optional> ? IdOf<Target> | (Optional extends true ? null : never) : E extends Predicate ? boolean : E extends Expr<infer T> ? T : never;
606
- /**
607
- * A field or scalar whose value is text, or absent text.
608
- *
609
- * `Expr.contains` is a case-insensitive **text** search that compiles to
610
- * `lower(column) like lower(?)`. Over a number that is nonsense which reaches
611
- * the database — SQLite coerces and answers something, Postgres raises — so
612
- * the operand is constrained here rather than discovered there.
613
- *
614
- * Null belongs in the type, because a nullable text column is a real and
615
- * documented case: a null contains nothing, not even the empty string, so its
616
- * rows drop out of a search that would otherwise match everything.
617
- *
618
- * Written as a **constraint on the type parameter** rather than as a check
619
- * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for
620
- * an unregistered descriptor). That idiom compares an already-resolved indexed
621
- * access; here the check would be a conditional over the type being inferred,
622
- * and inference falls back to the constraint — whose `Expr<any>` branch makes
623
- * the check vacuously true, so every operand passes. A constraint cannot be
624
- * defeated that way.
625
- */
626
- type TextOperand = EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>> | Expr<string> | Expr<string | null>;
627
- declare const literal: <T>(value: T) => LiteralExpr<T>;
628
- /** Whether a value is a predicate, and so usable where a boolean is wanted. */
629
- declare const isPredicate: (value: unknown) => value is Predicate;
630
- /**
631
- * Every operation the kernel has. An interpreter declares which of them it
632
- * runs, and a body needing one it does not is refused rather than answered
633
- * wrongly — see `Query.unsupported`.
634
- */
635
- type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains' | 'in' | 'and' | 'or' | 'not' | 'compare' | 'next' | 'viewer' | 'now' | 'path' | 'exists';
636
- /** One field an expression reads: its Entity's name and key, and the identity that owns it. */
637
- interface FieldDependency {
638
- /** The owning Entity's name, for display; two Entities may share one. */
639
- readonly entity: string;
640
- readonly key: string;
641
- /** Which Entity it is. Two defined with the same name are two entries. */
642
- readonly owner: EntityIdentity<string>;
643
- }
644
- /** Which fields and inputs an expression reads, and which operations it uses. */
645
- interface Dependencies {
646
- /** One entry per distinct field of each Entity identity. */
647
- readonly fields: ReadonlyArray<FieldDependency>;
648
- /** Each field read as the row a write would leave holds it (`Next`), one entry each. */
649
- readonly next: ReadonlyArray<FieldDependency>;
650
- /** One entry per distinct input key. */
651
- readonly inputs: ReadonlyArray<string>;
652
- /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */
653
- readonly operations: ReadonlyArray<Operation>;
654
- /** Each operator it calls, once per descriptor, defined or not. */
655
- readonly operators: ReadonlyArray<OperatorDescriptor>;
656
- /**
657
- * Each path, exists and path from the viewer, once each: what it reads lies
658
- * in other rows, so none of it is in `fields`. An exists' filter's inputs,
659
- * operations and operators are in the lists above.
660
- */
661
- readonly reaches: ReadonlyArray<PathExpr<unknown> | ExistsPredicate | ViewerPathExpr<unknown>>;
662
- }
663
- /**
664
- * What a query reads, with each field's role. A change to a `predicate` field
665
- * can move a row into or out of the result; a change to an `order` field can
666
- * move it within. A field in both is in both; `fields` is their union.
667
- */
668
- interface QueryDependencies extends Dependencies {
669
- readonly predicate: ReadonlyArray<FieldDependency>;
670
- readonly order: ReadonlyArray<FieldDependency>;
671
- }
672
- /**
673
- * A field or scalar whose value orders: a number, text, a date (which orders by
674
- * its encoded form), or one of those absent. A boolean does not order here.
675
- * A constraint on the type parameter, as `TextOperand` is, so inference cannot
676
- * fall back past it.
677
- */
678
- type OrderedOperand = EntityField<string, string, Schema.Constraint & Schema.Codec<number | string | Date | null, any, any, any>> | Expr<number> | Expr<number | null> | Expr<string> | Expr<string | null> | Expr<Date> | Expr<Date | null>;
679
- /** `Expr.and` and `Expr.or`: one operand is that operand, and two or more are one node. */
680
- interface Connective<Node extends Predicate> {
681
- <P extends Predicate>(only: P): P;
682
- <A extends Predicate, B extends Predicate, Rest extends ReadonlyArray<Predicate>>(first: A, second: B, ...rest: Rest): Node & Reads<ReadsOf<A> | ReadsOf<B> | ReadsOf<Rest[number]>>;
683
- (...operands: Array.NonEmptyReadonlyArray<Predicate>): Predicate;
684
- }
685
- /** A schema's stored form, which is what an operator takes and gives. */
686
- type StoredOf$1<S extends Schema.Top> = Schema.Codec.Encoded<S>;
687
- /**
688
- * One argument an operator may be called with: a field or scalar stored as the
689
- * input's stored type, a predicate where it takes a boolean, or a plain value.
690
- */
691
- type ArgumentOf<S extends Schema.Top> = EntityField<string, string, Schema.Constraint & Schema.Codec<any, StoredOf$1<S>, any, any>> | Expr<StoredOf$1<S>> | (boolean extends StoredOf$1<S> ? Predicate : never) | StoredOf$1<S>;
692
- /** What `definedAs` is handed for one argument: the argument as a node. */
693
- type ParameterOf<S extends Schema.Top> = Expr<StoredOf$1<S>> | (boolean extends StoredOf$1<S> ? Predicate : never);
694
- /** A call's node: a predicate for a boolean result, a scalar for anything else. */
695
- type CallOf<Out extends Schema.Top> = [StoredOf$1<Out>] extends [boolean] ? TestPredicate : CallExpr<StoredOf$1<Out>>;
696
- /** What `definedAs` builds: a predicate for a boolean result, a scalar otherwise. */
697
- type BodyOf<Out extends Schema.Top> = [StoredOf$1<Out>] extends [boolean] ? Predicate : Expr<StoredOf$1<Out>>;
698
- /**
699
- * An operator: called like a function, it builds a node that holds `descriptor`
700
- * and its arguments. See `Expr.operator`.
701
- */
702
- interface Operator<In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top> {
703
- <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]>; }>(...args: A): CallOf<Out> & Reads<ReadsOf<A[number]>>;
704
- /**
705
- * A call comparing text under the collation given, rather than its text
706
- * arguments' declared one: for an operator whose `collation` is `operands`
707
- * or `required`, as `Expr.lt(field, value, { collation })` is.
708
- */
709
- <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]>; }>(...args: [...A, CallOptions]): CallOf<Out> & Reads<ReadsOf<A[number]>>;
710
- readonly descriptor: OperatorDescriptor;
711
- }
712
- /** What a call may say past its arguments. */
713
- interface CallOptions {
714
- /** The collation it compares text under, in place of its arguments' declared one. */
715
- readonly collation: Collation;
716
- }
717
- /** `Expr.path`'s two starts: a relation of the judged row, or the viewer's row. */
718
- interface PathOf {
719
- <Owner extends string, Target extends AnyEntity, E extends PathEnd<Target['name']>>(relation: EntityRelation<Owner, string, Target, 'one', boolean>, end: E): (E extends ExistsPredicate ? ExistsPredicate : PathExpr<ValueOf<E> | null>) & Reads<Owner>;
720
- <Name extends string, E extends Exclude<PathEnd<Name>, ExistsPredicate>>(viewer: ViewerExpr<any, Name>, end: E): ViewerPathExpr<ValueOf<E> | null>;
721
- }
722
- /**
723
- * The most relations one path follows. Each is a subquery in SQL and a lookup
724
- * in memory; the deepest rule a real app here writes follows two.
725
- */
726
- declare const maxPathLength = 4;
727
- /** What a path may end at on a row of `Name`: a field, a further path, or an exists. */
728
- type PathEnd<Name extends string> = EntityField<Name, string, Schema.Constraint> | (PathExpr<any> & Reads<Name>) | (ExistsPredicate & Reads<Name>);
729
- /** `Expr.field`: an Entity field, or an expression refused with what to write instead. */
730
- interface FieldOf {
731
- <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>): FieldExpr<Schema.Schema.Type<S>> & Reads<Name>;
732
- (expression: Expr<unknown> & Invalid<'foldkit-entity: Expr.field takes an Entity field (Post.fields.title); before.x and after.x are expressions already, so compare them as they are'>): never;
733
- }
734
- declare const Expr: {
735
- /**
736
- * An operator, defined by what a call of it means: `definedAs` builds that
737
- * expression from the call's arguments, once per call, and every interpreter
738
- * runs it, so the operator needs no implementation anywhere. What it adds is
739
- * a name: a query, a guard and an invariant that mean the same thing say so,
740
- * and print it.
741
- *
742
- * ```ts
743
- * const published = Expr.operator('cms.published', {
744
- * input: [Schema.Unknown],
745
- * output: Schema.Boolean,
746
- * definedAs: publishedAt => Expr.isNotNull(publishedAt),
747
- * })
748
- * Query.where(published(Post.fields.publishedAt))
749
- * ```
750
- *
751
- * Arguments are checked by their stored form: a field, scalar or plain value
752
- * of the input's stored type, or a predicate where it takes a boolean. A
753
- * boolean output makes a call a predicate. `definedAs` may read only what its
754
- * arguments hold: a field or input it closes over instead is refused when
755
- * called, since nothing asking what the call reads would see it. The id is
756
- * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
757
- * changes when what it means does.
758
- *
759
- * **Without `definedAs` it is primitive**: each interpreter implements it
760
- * (`Operators.implement` in memory), and one without an implementation
761
- * refuses the body by the operator's id. `nulls` (default `strict`: a null
762
- * argument gives null, the implementation never sees one) and `collation`
763
- * (`operands`: a text result carries its text arguments' shared collation;
764
- * `required`: it compares text itself and needs one) are a primitive
765
- * operator's; a defined one means its body for both.
766
- */
767
- operator: <const In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(id: string, options: {
768
- readonly input: In;
769
- readonly output: Out;
770
- readonly version?: number | undefined;
771
- readonly description?: string | undefined;
772
- /** Equations every implementation keeps (`Law.commutative`, `Law.identity('')`, …). */
773
- readonly laws?: ReadonlyArray<Law> | undefined;
774
- } & ({
775
- readonly definedAs: (...args: { readonly [K in keyof In]: ParameterOf<In[K]>; }) => BodyOf<Out>;
776
- readonly nulls?: undefined;
777
- readonly collation?: undefined;
778
- } | {
779
- readonly definedAs?: undefined;
780
- readonly nulls?: OperatorDescriptor['nulls'] | undefined;
781
- readonly collation?: OperatorDescriptor['collation'] | undefined;
782
- })) => Operator<In, Out>;
783
- /**
784
- * The predicate or scalar (an order term's, say) with every call of a
785
- * defined operator replaced by what it means, deeply. An interpreter that
786
- * compiles a body expands it first, and compiles exactly what was written
787
- * out. A call with no definition stays, for the interpreter to run or refuse
788
- * by name.
789
- */
790
- /**
791
- * Whether a constant written in these expressions is one no two backends
792
- * agree on, text holding a NUL or NaN, or a list holding one: SQL refuses
793
- * such a parameter wherever it compiles, so an interpreter refuses the run,
794
- * not one row.
795
- */
796
- givesUnportable: (...nodes: ReadonlyArray<AnyExpr | Predicate>) => boolean;
797
- expanded: <N extends Predicate | AnyExpr>(node: N) => N extends Predicate ? Predicate : AnyExpr;
798
- /**
799
- * What these expressions need that an interpreter lacks, as `Query.unsupported`
800
- * says it for a query: each kernel operation `supported` does not list, then
801
- * each primitive operator `operators` does not implement, by name (`id`, or
802
- * `id@version` past the first). For anything holding expressions that is not a
803
- * query: a guard's rule, an invariant, a write's `when`.
804
- */
805
- unsupported: (nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>, interpreter: {
806
- readonly operations: ReadonlyArray<Operation>;
807
- readonly operators: OperatorTable;
808
- }) => ReadonlyArray<string>;
809
- /** A constant. Comparisons coerce a plain value, so this is rarely written. */
810
- literal: typeof literal;
811
- /**
812
- * A value the query is given when it runs. A definition builds these from its
813
- * `Input` schema; written by hand only when constructing a body directly.
814
- */
815
- input: <T>(key: string, schema: Schema.Codec<T, unknown>) => InputExpr<T>;
816
- /**
817
- * A field as the row a write would leave holds it: what `Entity.invariant`'s
818
- * builder hands out as `after`.
819
- */
820
- next: <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>) => NextExpr<Schema.Schema.Type<S>> & Reads<Name>;
821
- /**
822
- * One field of one Entity, as a scalar. An expression is one already: an
823
- * invariant's `before.x` and `after.x` compare as they are, so wrapping one
824
- * is refused with that sentence.
825
- */
826
- field: FieldOf;
827
- /**
828
- * What the row reached through a `one` relation holds: a field of it, a
829
- * further path from it, or an exists asked of it. The first relation is the
830
- * judged row's own.
831
- *
832
- * ```ts
833
- * Expr.eq(Expr.path(Post.relations.author, User.fields.handle), input.handle)
834
- * Expr.path(Note.relations.project, Expr.path(Project.relations.org, Org.fields.plan))
835
- * ```
836
- *
837
- * A null link, or a row the reader may not see, reaches no row: the field
838
- * reads null, and an exists at the end is unknown, as SQL's scalar subquery
839
- * is. At most `maxPathLength` relations.
840
- */
841
- path: PathOf;
842
- /**
843
- * Some row points at this one through `relation`, a `one` relation of
844
- * another Entity, and holds `where`, a predicate over that row's own fields
845
- * and the input:
846
- *
847
- * ```ts
848
- * // Posts whose author the reader follows.
849
- * Expr.path(Post.relations.author,
850
- * Expr.exists(Follow.relations.followee, Expr.eq(Follow.fields.followerId, input.me)))
851
- * ```
852
- *
853
- * Only rows the reader may see are sought. Never unknown in SQL; in memory,
854
- * unknown when no held row holds and the holder may lack one that would.
855
- */
856
- exists: <Owner extends string, Target extends AnyEntity, W extends Predicate & Reads<Owner> = never>(relation: EntityRelation<Owner, string, Target, 'one', boolean>, where?: W) => ExistsPredicate & Reads<Target['name']>;
857
- /**
858
- * Whoever asks, as a row of `entity`: `Expr.eq(Like.fields.userId,
859
- * Expr.viewer(User))`. Shaped as a `one` relation to `entity`. Its value is
860
- * the row's id, and null for a visitor or a viewer of another Entity, so a
861
- * comparison with it holds of no row. A server reads it from
862
- * `RemoteServer.make`'s `viewer`, a client from `Remote.make`'s.
863
- */
864
- viewer: typeof viewer;
865
- /**
866
- * The time of the write, in milliseconds since the epoch, as a number field
867
- * stores it. A server reads its clock. A client judging a list has no
868
- * reading of the time the server judged it at, so such a list is the
869
- * server's to say.
870
- */
871
- now: NowExpr<number>;
872
- /**
873
- * Two scalars are the same value: a field (or an expression) on the left,
874
- * and the value on the right, typed from it. Fields and plain values are
875
- * coerced, so the common form reads as it means:
876
- *
877
- * ```ts
878
- * Expr.eq(Post.fields.slug, input.slug)
879
- * Expr.eq(Post.fields.status, 'active')
880
- * ```
881
- */
882
- eq: <L extends Operand<any> | PlainValue, R extends (L extends PlainValue ? Invalid<'foldkit-entity: Expr.eq takes the field on the left and the value on the right'> : ValueOf<L> | Expr<ValueOf<L>> | PathExpr<ValueOf<L> | null> | ViewerPathExpr<ValueOf<L> | null> | (boolean extends ValueOf<L> ? Predicate : never))>(left: L, right: R) => EqPredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
883
- /**
884
- * Whether a field holds no value. Its opposite is `isNotNull`; both are the
885
- * one node, since a query asks which of the two it means, and `is not null`
886
- * has no unknown for a `not` to keep.
887
- */
888
- isNull: <L extends Operand<any>>(operand: L) => NullPredicate & Reads<ReadsOf<L>>;
889
- /** Whether a field holds a value. */
890
- isNotNull: <L extends Operand<any>>(operand: L) => NullPredicate & Reads<ReadsOf<L>>;
891
- /**
892
- * Whether a text value contains `search`, anywhere in it. Containing the
893
- * empty string is everything, so a search box with nothing typed in it is the
894
- * same query as one with something — no branch, and no second query.
895
- *
896
- * **Case-insensitive**, which is what a search means, and which has to be
897
- * said rather than left to the interpreter: SQLite's `like` ignores case and
898
- * Postgres's does not, so a body that left it open would mean two things.
899
- * Folding is ASCII-only, because that is what `lower` does in SQLite without
900
- * ICU.
901
- *
902
- * **Over a column that can be null this is not the same as no filter.** A
903
- * null contains nothing, not even the empty string, so its rows drop out. A
904
- * nullable column that should match everything on an empty search says so:
905
- * `Expr.or(Expr.isNull(field), Expr.contains(field, input.search))`.
906
- */
907
- contains: <L extends TextOperand>(value: L, search: string | LiteralExpr<string> | InputExpr<string> | InputExpr<string | null>) => ContainsPredicate & Reads<ReadsOf<L>>;
908
- /**
909
- * Whether a value is one of `among`: a list written out, or an input whose
910
- * value is one. Each element is compared as `eq` compares.
911
- *
912
- * ```ts
913
- * Expr.in(Todo.fields.projectId, input.projectIds)
914
- * Expr.in(Todo.fields.status, ['open', 'blocked'])
915
- * ```
916
- *
917
- * As SQL's `in`: a null value is unknown, as is no match against a list
918
- * holding a null, and an empty list matches no row. A list written out is
919
- * copied, so changing the array afterwards does not change the query.
920
- */
921
- in: <L extends Operand<any>>(value: L, among: ReadonlyArray<ValueOf<L>> | Expr<ReadonlyArray<ValueOf<L>>>) => InPredicate & Reads<ReadsOf<L>>;
922
- /**
923
- * `left` orders before `right`. Numbers compare as numbers; text compares
924
- * under a collation, the one given or the field's declared one, which must be
925
- * `binary` or `asciiFold` (so every backend agrees), and text needs a field on
926
- * one side. A date compares by its encoded form: as text when it is stored as
927
- * an ISO string, so its field declares `Collation.binary`. A null on either
928
- * side is unknown, so the row is matched by neither this nor its `not`.
929
- *
930
- * ```ts
931
- * Expr.lt(fields.cents, 1000)
932
- * Expr.and(Expr.gte(fields.at, input.from), Expr.lt(fields.at, input.until))
933
- * ```
934
- */
935
- lt: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
936
- readonly collation?: Collation | undefined;
937
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
938
- /** `left` orders before `right`, or with it; see `Expr.lt`. */
939
- lte: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
940
- readonly collation?: Collation | undefined;
941
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
942
- /** `left` orders after `right`; see `Expr.lt`. */
943
- gt: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
944
- readonly collation?: Collation | undefined;
945
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
946
- /** `left` orders after `right`, or with it; see `Expr.lt`. */
947
- gte: <L extends OrderedOperand, R extends ValueOf<L> | Expr<ValueOf<L>>>(left: L, right: R, options?: {
948
- readonly collation?: Collation | undefined;
949
- }) => ComparePredicate & Reads<ReadsOf<L> | ReadsOf<R>>;
950
- /**
951
- * Every operand holds, as one predicate to place inside another: `where`'s
952
- * list is already a conjunction, so this is for `or(and(a, b), c)`.
953
- * Unknown as SQL's `and` is: false wins over unknown, which wins over true.
954
- * Needs an operand; a list built at run time is checked non-empty first
955
- * (`Array.isReadonlyArrayNonEmpty`), since an empty `and` would match every row.
956
- */
957
- and: Connective<AndPredicate>;
958
- /**
959
- * At least one operand holds:
960
- *
961
- * ```ts
962
- * Expr.or(Expr.contains(fields.description, input.search), Expr.contains(fields.upc, input.search))
963
- * ```
964
- *
965
- * Unknown as SQL's `or` is: true wins over unknown, which wins over false.
966
- * Needs an operand, since an empty `or` would match no row.
967
- */
968
- or: Connective<OrPredicate>;
969
- /**
970
- * The operand does not hold. **A null is matched by neither side**:
971
- * `not(eq(status, 'draft'))` leaves out a row whose `status` is null, since
972
- * `null = 'draft'` is unknown and so is its `not`, as in SQL. "Everything
973
- * but drafts" over a nullable column is
974
- * `Expr.or(Expr.isNull(status), Expr.not(Expr.eq(status, 'draft')))`.
975
- */
976
- not: <P extends Predicate>(operand: P) => NotPredicate & Reads<ReadsOf<P>>;
977
- /**
978
- * A filter that applies only when its input is given: `or(isNull($x), …)`,
979
- * with the predicate built from the input as never null.
980
- *
981
- * ```ts
982
- * // Every product, or those of the chosen status.
983
- * Expr.whenGiven(input.status, status => Expr.eq(fields.status, status))
984
- * ```
985
- *
986
- * An interpreter that runs per request, as the Drizzle compiler does, decides
987
- * `isNull($x)` before writing SQL, so this compiles to `true`, which filters
988
- * nothing, or to the predicate alone.
989
- */
990
- whenGiven: <T, P extends Predicate>(input: InputExpr<T>, build: (given: InputExpr<NonNullable<T>>) => P) => Predicate & Reads<ReadsOf<P>>;
991
- /** An expression as readable text; see `showExpr` for what it is and is not. */
992
- show: (node: Operandish) => string;
993
- /**
994
- * The predicate with each field after a write (`Next`) that `values` names,
995
- * by key, read as that value: how an invariant is judged where the
996
- * write's new values are known. A field it does not name stays `Next`, for
997
- * the interpreter to read as the row after holds it.
998
- */
999
- substituteNext: (predicate: Predicate, values: Readonly<Record<string, unknown>>) => Predicate;
1000
- };
1001
- /** One term of an ordering: a scalar and the direction to read it in. */
1002
- interface OrderTerm {
1003
- readonly _tag: 'Term';
1004
- readonly direction: 'asc' | 'desc';
1005
- readonly expr: AnyExpr;
1006
- /**
1007
- * Where rows without a value go, in the term's own direction. Databases
1008
- * disagree when it is left unsaid (Postgres puts them last ascending, SQLite
1009
- * first), so it is always said: last ascending and first descending unless
1010
- * a term asks otherwise, which is Postgres's.
1011
- */
1012
- readonly nulls: 'first' | 'last';
1013
- /**
1014
- * How text compares, when the term orders text: the term's own, or its
1015
- * field's. None leaves it to the backend, which a client cannot match.
1016
- */
1017
- readonly collation: Option.Option<Collation>;
1018
- }
1019
- /** What a term may say besides its operand. */
1020
- interface TermOptions {
1021
- readonly nulls?: 'first' | 'last' | undefined;
1022
- /** Overrides the field's declared collation for this term. */
1023
- readonly collation?: Collation | undefined;
1024
- }
1025
- /** How a list is sorted, as its input holds it: one of its named orders, which way, or none. */
1026
- type ChosenSort<By extends string> = {
1027
- readonly by: By;
1028
- readonly direction: 'asc' | 'desc';
1029
- } | null;
1030
- /**
1031
- * An ordering the input chooses: one of several named fields, which way, or
1032
- * none. It is how a list sorts by what its reader picked, said in the body, so
1033
- * the server and the client read one declaration of what each name means.
1034
- */
1035
- interface ChosenOrder {
1036
- readonly _tag: 'Chosen';
1037
- readonly sort: InputExpr<ChosenSort<string>>;
1038
- readonly choices: Readonly<Record<string, FieldExpr<unknown> | CallExpr<unknown>>>;
1039
- }
1040
- /** One entry of a body's ordering: fixed, or chosen by the input. */
1041
- type Ordering = OrderTerm | ChosenOrder;
1042
- declare const Order: {
1043
- /** Smallest first; rows without a value last, unless `nulls` says first. */
1044
- asc: <E extends OwnOperand<any>>(expr: E, options?: TermOptions) => OrderTerm & Reads<ReadsOf<E>>;
1045
- /** Largest first; rows without a value first, unless `nulls` says last. */
1046
- desc: <E extends OwnOperand<any>>(expr: E, options?: TermOptions) => OrderTerm & Reads<ReadsOf<E>>;
1047
- /**
1048
- * The order the input names, among `choices`: every name the sort can hold
1049
- * maps to a field or a call that orders, so a name left out is a type error
1050
- * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
1051
- * it decide.
1052
- *
1053
- * ```ts
1054
- * Query.orderBy(Order.chosen(input.sort, { title: Post.fields.title }))
1055
- * ```
1056
- */
1057
- chosen: <By extends string, const Choices extends { readonly [K in By]: OwnOperand<any>; }>(sort: InputExpr<ChosenSort<By>>, choices: Choices) => ChosenOrder & Reads<ReadsOf<Choices[keyof Choices]>>;
1058
- };
1059
- /**
1060
- * Whether a client can order rows the way the server does, for one input: the
1061
- * answer `Query.placement` gives, and the reason when it cannot.
1062
- */
1063
- type Placement = {
1064
- readonly _tag: 'Placeable';
1065
- } | {
1066
- readonly _tag: 'NotPlaceable';
1067
- readonly reason: string;
1068
- };
1069
- /**
1070
- * What an expression reads and uses, for the planner and for an interpreter
1071
- * deciding whether it can run this query at all. Distinct entries only, in the
1072
- * order first seen, so the answer is stable enough to assert on.
1073
- */
1074
- declare const dependenciesOf: (...nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>) => Dependencies;
1075
- /**
1076
- * Which rows a query is about, as a value: an Entity to read, the predicates
1077
- * every row must satisfy, and the order to read them in. It says nothing about
1078
- * which fields to return — that is a Selection — and nothing about pagination,
1079
- * liveness, or whether absence is an error, which belong to the consumer's read
1080
- * rather than to the relation.
1081
- *
1082
- * Composing one performs no work. `Query.from(Post)` names no table and opens
1083
- * no connection; an interpreter turns the value into a query when something
1084
- * asks it to.
1085
- */
1086
- interface Query<E extends AnyEntity> extends Pipeable.Pipeable {
1087
- readonly _tag: 'Query';
1088
- readonly entity: E;
1089
- /**
1090
- * Every predicate holds: the list *is* the conjunction. Keeping it a list
1091
- * rather than folding it into one `and` is what makes each `where` a reusable
1092
- * fragment, and it means no `Expr.and` exists until a query needs a
1093
- * conjunction nested inside something else.
1094
- */
1095
- readonly where: ReadonlyArray<Predicate>;
1096
- /** In order of significance; a later `orderBy` appends less significant terms. */
1097
- readonly orderBy: ReadonlyArray<Ordering>;
1098
- }
1099
- /** A `Query` over any Entity, for the places that hold one without caring which. */
1100
- type AnyQuery = Query<AnyEntity>;
1101
- /**
1102
- * The most nodes a query's predicates may hold once every shared node is
1103
- * counted on each path that reaches it. Interpreters read a predicate as a
1104
- * tree: `evaluate` once per row, and the SQL compiler into text that repeats a
1105
- * shared operand wherever it appears. So `eq(n, n)` nested thirty deep is
1106
- * thirty-one objects and a billion nodes of work. Real queries are tens.
1107
- */
1108
- declare const maxQueryNodes = 1000;
1109
- declare const Query: {
1110
- /** Every row of an Entity: the query each transformation narrows. */
1111
- from: <E extends AnyEntity>(entity: E) => Query<E>;
1112
- /**
1113
- * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
1114
- * second never replaces the first — so a fragment can be written once and
1115
- * piped into any query over the same Entity:
1116
- *
1117
- * ```ts
1118
- * const published = Query.where(Expr.eq(Post.fields.published, true))
1119
- * Query.from(Post).pipe(published, Query.where(byTitle))
1120
- * ```
1121
- */
1122
- where: <const P extends ReadonlyArray<Predicate>>(...predicates: P) => <E extends AnyEntity>(self: Query<E> & OverEntity<ReadsOf<P[number]>, E['name'], 'a predicate'>) => Query<E>;
1123
- /**
1124
- * Reads the rows in this order. Two `orderBy`s append, so an earlier term
1125
- * stays the more significant one and a later call adds a tie-breaker rather
1126
- * than silently winning.
1127
- */
1128
- orderBy: <const T extends ReadonlyArray<Ordering>>(...terms: T) => <E extends AnyEntity>(self: Query<E> & OverEntity<ReadsOf<T[number]>, E['name'], 'an ordering term'>) => Query<E>;
1129
- /**
1130
- * The fixed terms this query orders by for one input: each chosen order
1131
- * resolved to the field its input names, or to nothing for a `null` sort,
1132
- * and the Entity's id last, ascending, unless the terms already read it. So
1133
- * the order is total, and every interpreter breaks ties the same way: one
1134
- * that broke them its own way would place rows a step apart from another.
1135
- */
1136
- orderFor: (self: AnyQuery, input: Readonly<Record<string, unknown>>) => ReadonlyArray<OrderTerm>;
1137
- /**
1138
- * Whether a client can order this query's rows exactly as the server does,
1139
- * for one input: every term over a number or a boolean (a row may lack it), or over text with a
1140
- * portable collation (`binary`, `asciiFold`), or a call whose primitive
1141
- * operators the client's table (`operators`; none when not given) runs. A
1142
- * body that names no order leaves it to the server, and is never placeable.
1143
- */
1144
- placement: (self: AnyQuery, input: Readonly<Record<string, unknown>>, options?: {
1145
- readonly operators?: OperatorTable | undefined;
1146
- }) => Placement;
1147
- /**
1148
- * Each operator the body calls, by name (`id`, or `id@version` past the
1149
- * first), in the order it first calls them: a defined one, and each
1150
- * primitive one its expansion calls.
1151
- */
1152
- operators: (self: AnyQuery) => ReadonlyArray<string>;
1153
- /**
1154
- * What the whole query reads: the fields and inputs of every predicate and
1155
- * every ordering term, and the operations it uses, with the fields also
1156
- * split by role.
1157
- */
1158
- dependencies: (self: AnyQuery) => QueryDependencies;
1159
- /**
1160
- * The operations this query needs that `supported` does not list, in the
1161
- * order the query uses them, then each primitive operator `operators` does
1162
- * not implement, by name. Without `operators`, every primitive operator is
1163
- * named: a list of operations implements none. Empty means an interpreter
1164
- * declaring both can answer it.
1165
- *
1166
- * An interpreter declares what it runs and refuses the rest, rather than
1167
- * ignoring an operation it does not implement — which would answer a
1168
- * different question and say nothing. The refusal is the interpreter's to
1169
- * raise: this only says what is missing, because what to do about it differs
1170
- * between one that compiles at registration and one that runs a body
1171
- * directly.
1172
- *
1173
- * ```ts
1174
- * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
1175
- * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
1176
- * ```
1177
- */
1178
- unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>, operators?: OperatorTable) => ReadonlyArray<string>;
1179
- /**
1180
- * The whole query as readable text, one clause per line:
1181
- *
1182
- * ```text
1183
- * FROM Post
1184
- * WHERE Post.slug = $slug
1185
- * AND Post.published = true
1186
- * ORDER BY Post.updatedAt DESC
1187
- * ```
1188
- *
1189
- * For an explanation or a diagnostic, never for an interpreter — see
1190
- * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
1191
- * than printing an empty one, so what is shown is what was written.
1192
- */
1193
- show: (self: AnyQuery) => string;
1194
- };
1195
- /** A value a holder has, or why it does not have it. */
1196
- type Held$1<A> = {
1197
- readonly _tag: 'Held';
1198
- readonly value: A;
1199
- } | {
1200
- readonly _tag: 'Unheld';
1201
- readonly reason: string;
1202
- };
1203
- /** The rows pointing at one row through a relation, as far as a holder has them. */
1204
- interface Pointing {
1205
- readonly rows: ReadonlyArray<HeldRow>;
1206
- /** Why a row pointing here may be missing from `rows`; none when it holds every one. */
1207
- readonly missing: Option.Option<string>;
1208
- }
1209
- /**
1210
- * One row as a holder has it. Values are **encoded**, as a store keeps them
1211
- * and as `evaluate` reads a row.
1212
- */
1213
- interface HeldRow {
1214
- /** A field's value; unheld when the holder lacks it or may not see it. */
1215
- readonly field: (key: string) => Held$1<unknown>;
1216
- /**
1217
- * The row a `one` relation of this row points at: none for a null link, or
1218
- * a row the reader may not see when the holder knows it holds every row it may.
1219
- */
1220
- readonly follow: (relation: OneRelation$2) => Held$1<Option.Option<HeldRow>>;
1221
- /** The rows pointing at this one through `relation`, a `one` relation of another Entity. */
1222
- readonly pointing: (relation: OneRelation$2) => Pointing;
1223
- }
1224
- /** One Entity's rows, as `Held.rows` takes them. */
1225
- interface HeldTable {
1226
- readonly entity: AnyEntity;
1227
- /**
1228
- * Each row's values by key, encoded; a `one` relation's under its own key,
1229
- * as the id of the row it points at or null. A key a row lacks is unheld.
1230
- */
1231
- readonly rows: ReadonlyArray<Readonly<Record<string, unknown>>>;
1232
- /**
1233
- * Whether these are every row of the Entity the reader may see, so a row
1234
- * not among them is known absent. True when not given.
1235
- */
1236
- readonly complete?: boolean | undefined;
1237
- /** Keys the reader may not see on any of these rows. */
1238
- readonly hidden?: ReadonlyArray<string> | undefined;
1239
- }
1240
- /** The rows `Held.rows` holds, by Entity. */
1241
- interface HeldRows {
1242
- /** The row of `entity` with this id, when it is held. */
1243
- readonly row: (entity: AnyEntity, id: unknown) => Option.Option<HeldRow>;
1244
- /** Every held row of `entity`. */
1245
- readonly rows: (entity: AnyEntity) => ReadonlyArray<HeldRow>;
1246
- /**
1247
- * The row of `entity` with this id as the holder can say: none when it
1248
- * knows there is no such row it may see, unheld when it cannot tell.
1249
- */
1250
- readonly find: (entity: AnyEntity, id: unknown) => Held$1<Option.Option<HeldRow>>;
1251
- }
1252
- declare const held: <A>(value: A) => Held$1<A>;
1253
- declare const unheld: <A = never>(reason: string) => Held$1<A>;
1254
- /**
1255
- * Rows held as plain records: each table complete or not, with keys hidden.
1256
- * What a test, a conformance check or a server that has the rows in hand
1257
- * judges over.
1258
- */
1259
- declare const rowsOf: (tables: ReadonlyArray<HeldTable>) => HeldRows;
1260
- /**
1261
- * A row as a Source answers it and a Remote store keeps it, each `one`
1262
- * relation as its ref key (`'User:ada'`), given as an interpreter reads it:
1263
- * each link `query` reads as the id it points at. The row itself when the
1264
- * query reads no link.
1265
- */
1266
- declare const fromRefs: (query: AnyQuery, row: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>>;
1267
- /** The id a ref key (`'User:ada'`) names, refusing what is none, as `where` holds it. */
1268
- declare const idOfRef: (ref: unknown, where: string) => string;
1269
- declare const Held$1: {
1270
- /** A value the holder has. */
1271
- of: typeof held;
1272
- /** A value the holder does not have, and why. */
1273
- unheld: typeof unheld;
1274
- match: <A, B>(value: Held$1<A>, cases: {
1275
- readonly onHeld: (value: A) => B;
1276
- readonly onUnheld: (reason: string) => B;
1277
- }) => B;
1278
- /** Rows held as plain records; see `HeldTable`. */
1279
- rows: typeof rowsOf;
1280
- fromRefs: typeof fromRefs;
1281
- };
1282
- declare const stampTested: (record: Evidence, operators: MemoryOperators) => void;
1283
- declare const stampRun: (record: Evidence) => void;
1284
- /** The table `Conformance.laws` tested a record on. */
1285
- declare const tableTested: (record: Evidence) => Option.Option<MemoryOperators>;
1286
- declare const testedByRunner: (record: Evidence) => boolean;
1287
- /** What an implementation is told besides its arguments. */
1288
- interface OperatorContext {
1289
- /** The collation the call compares text under, from its operator's `collation` rule. */
1290
- readonly collation: Option.Option<Collation>;
1291
- }
1292
- /** One operator's in-memory implementation: a pure function of stored values. */
1293
- interface MemoryImplementation {
1294
- readonly operator: OperatorDescriptor;
1295
- readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown;
1296
- }
1297
- /**
1298
- * What is known of a law of an implementation, past its operator claiming it
1299
- * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'
1300
- * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded
1301
- * and never checked here.
1302
- */
1303
- type Evidence = Data.TaggedEnum<{
1304
- Tested: {
1305
- readonly operator: string;
1306
- readonly law: LawDescription;
1307
- readonly implementation: string;
1308
- readonly cases: number;
1309
- readonly seed: number;
1310
- };
1311
- Proven: {
1312
- readonly operator: string;
1313
- readonly law: LawDescription;
1314
- readonly reference: string;
1315
- readonly assumptions: ReadonlyArray<string>;
1316
- };
1317
- }>;
1318
- declare const Evidence: Data.TaggedEnum.Constructor<{
1319
- readonly _tag: "Proven";
1320
- readonly operator: string;
1321
- readonly law: LawDescription;
1322
- readonly reference: string;
1323
- readonly assumptions: ReadonlyArray<string>;
1324
- } | {
1325
- readonly _tag: "Tested";
1326
- readonly operator: string;
1327
- readonly law: LawDescription;
1328
- readonly implementation: string;
1329
- readonly cases: number;
1330
- readonly seed: number;
1331
- }>;
1332
- /** A record of a law passing `Conformance.laws`' cases. */
1333
- type TestedEvidence = Extract<Evidence, {
1334
- readonly _tag: 'Tested';
1335
- }>;
1336
- /**
1337
- * An operator as JSON, by its signature and never its body (a defined
1338
- * operator says `defined`, not what it means): what a server can publish of
1339
- * what a body may call, and a client compare with what it runs. Its schemas
1340
- * are each argument's and the result's stored side, as JSON Schemas.
1341
- */
1342
- declare const OperatorDescription: Schema.Struct<{
1343
- /** By id, and `@version` past the first: what tables, evidence and refusals name. */
1344
- readonly name: Schema.String;
1345
- readonly id: Schema.String;
1346
- readonly version: Schema.Int;
1347
- readonly description: Schema.NullOr<Schema.String>;
1348
- readonly input: Schema.$Array<Schema.$Record<Schema.String, Schema.Unknown>>;
1349
- readonly output: Schema.$Record<Schema.String, Schema.Unknown>;
1350
- readonly nulls: Schema.Literals<readonly ["strict", "handled"]>;
1351
- readonly collation: Schema.Literals<readonly ["none", "operands", "required"]>;
1352
- readonly laws: Schema.$Array<Schema.Struct<{
1353
- readonly kind: Schema.String;
1354
- readonly witnesses: Schema.$Record<Schema.String, Schema.Unknown>;
1355
- readonly domain: Schema.Unknown;
1356
- }>>;
1357
- readonly defined: Schema.Boolean;
1358
- }>;
1359
- type OperatorDescription = typeof OperatorDescription.Type;
1360
- /** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */
1361
- interface ImplementedOperator extends OperatorDescription {
1362
- readonly evidence: ReadonlyArray<Evidence>;
1363
- }
1364
- /** The in-memory interpreter's implementations, by operator. */
1365
- interface MemoryOperators extends OperatorTable {
1366
- readonly _tag: 'MemoryOperators';
1367
- readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>;
1368
- /**
1369
- * The operator it implements under a name (`id`, or `id@version` past the
1370
- * first): how a computed assignment carried as data finds what to run.
1371
- */
1372
- readonly named: (name: string) => Option.Option<OperatorDescriptor>;
1373
- /** Whether each answer is checked against its operator's output schema: for tests. */
1374
- readonly checked: boolean;
1375
- readonly implementations: ReadonlyArray<MemoryImplementation>;
1376
- /** What is known of its implementations' laws: `Operators.withEvidence`. */
1377
- readonly evidence: ReadonlyArray<Evidence>;
1378
- }
1379
- type StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>;
1380
- declare const Operators: {
1381
- /**
1382
- * An implementation of a strict operator: a pure function of its arguments'
1383
- * stored values, never given a null (the kernel answers null, or unknown, for
1384
- * one first), and told the call's collation last.
1385
- *
1386
- * ```ts
1387
- * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
1388
- * ```
1389
- */
1390
- implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(operator: Operator<In, Out>, run: (...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>>; }, OperatorContext]) => StoredOf<Out>) => MemoryImplementation;
1391
- /**
1392
- * An implementation of an operator declared `nulls: 'handled'`: given nulls
1393
- * as they are, it answers for them; a predicate answers `null` for unknown.
1394
- */
1395
- implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(operator: Operator<In, Out>, run: (...args: [...{ readonly [K in keyof In]: StoredOf<In[K]>; }, OperatorContext]) => StoredOf<Out> | null) => MemoryImplementation;
1396
- /** A table of implementations. One operator implemented twice, or two under one name, is refused. */
1397
- memory: (...implementations: ReadonlyArray<MemoryImplementation>) => MemoryOperators;
1398
- /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
1399
- merge: (left: MemoryOperators, right: MemoryOperators) => MemoryOperators;
1400
- /**
1401
- * The table with these implementations in place of its own for the same
1402
- * operators. Evidence of a replaced implementation goes with it: it was
1403
- * that implementation's.
1404
- */
1405
- override: (base: MemoryOperators, ...implementations: ReadonlyArray<MemoryImplementation>) => MemoryOperators;
1406
- /**
1407
- * The table with what is known of its implementations' laws recorded: each
1408
- * record of an operator it implements and a law that operator declares.
1409
- * `Conformance.laws` gives `Tested` records, each of the implementation it
1410
- * ran, and a table takes only those of its own; `Evidence.Proven` says a
1411
- * proof elsewhere covers one.
1412
- */
1413
- withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>) => MemoryOperators;
1414
- /**
1415
- * The memory implementation `Conformance.laws` tested a record on; none for
1416
- * a record of a runner (`Conformance.lawsBy`) or a proof.
1417
- */
1418
- testedOn: (record: Evidence) => Option.Option<MemoryImplementation>;
1419
- /**
1420
- * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL
1421
- * table takes. Which runner it was, the database's or another, is the
1422
- * caller's word; a record built by hand, copied, or tested in memory is not.
1423
- */
1424
- testedByRunner: typeof testedByRunner;
1425
- /**
1426
- * Each operator the table implements, by name, with the laws it declares and
1427
- * the evidence the table records of them: what a server can publish of how
1428
- * it runs a body. JSON as it is.
1429
- */
1430
- describeTable: (base: MemoryOperators) => ReadonlyArray<ImplementedOperator>;
1431
- /**
1432
- * An operator as JSON (`OperatorDescription`): its name, version and
1433
- * description, each argument's and its result's stored side as a JSON
1434
- * Schema (as JSON carries it: a number also admits the strings `"Infinity"`,
1435
- * `"-Infinity"` and `"NaN"`), its null and collation rules, its laws, and
1436
- * whether it is defined. Its signature, never its body.
1437
- */
1438
- describe: (operator: {
1439
- readonly descriptor: OperatorDescriptor;
1440
- }) => OperatorDescription;
1441
- /**
1442
- * The table, checking every answer against its operator's output schema, so
1443
- * an implementation that answers the wrong kind fails where it answered. For
1444
- * tests: it costs a decode per call.
1445
- */
1446
- checked: (base: MemoryOperators) => MemoryOperators;
1447
- /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
1448
- kernel: MemoryOperators;
1449
- };
1450
- /** A row as this interpreter reads one: values by field key. */
1451
- type Row = Readonly<Record<string, unknown>>;
1452
- declare class QueryEvaluateError extends Error {
1453
- constructor(message: string);
1454
- }
1455
- /**
1456
- * A call of a primitive operator the table does not implement. Its own class,
1457
- * because a form judging an invariant reads it as a judgement it cannot make
1458
- * (`Undecided`), not as a failure.
1459
- */
1460
- declare class OperatorMissingError extends QueryEvaluateError {
1461
- readonly operator: OperatorDescriptor;
1462
- /** The operator by its id, and its version past the first. */
1463
- readonly named: string;
1464
- /** `operators`, the table that lacks it, names the versions of it that it does hold. */
1465
- constructor(operator: OperatorDescriptor, operators?: OperatorTable);
1466
- }
1467
- /**
1468
- * A run that reads `Expr.viewer` or `Expr.now` and was given no context. No
1469
- * row causes it, so `evaluateEach` refuses the run rather than each row.
1470
- */
1471
- declare class ContextMissingError extends QueryEvaluateError {
1472
- constructor(term: ViewerExpr<unknown> | NowExpr<unknown>, why: string);
1473
- }
1474
- /**
1475
- * What a run given one row could not decide without another: a path's or an
1476
- * exists' row. It refuses rather than read the others as absent, which would
1477
- * drop a row from a list on no evidence. `Judge` reads them from a holder.
1478
- */
1479
- declare class RowsMissingError extends QueryEvaluateError {
1480
- constructor(reason: string);
1481
- }
1482
- /**
1483
- * A primitive operator over stored values, as a call of it is run: what a
1484
- * computed assignment comes to (`Write.apply`). Refused, as a call is, when
1485
- * `operators` does not implement it.
1486
- */
1487
- declare const applyOperator: (operator: OperatorDescriptor, values: ReadonlyArray<unknown>, options: {
1488
- readonly collation: Option.Option<Collation>;
1489
- readonly operators: MemoryOperators;
1490
- }) => unknown;
1491
- /** SQL's unknown: neither true nor false, and a row is kept only on true. */
1492
- type Truth = boolean | 'unknown';
1493
- /**
1494
- * What an operand comes to over no row: a call of literals and inputs, run by
1495
- * `operators` (the kernel's when not given), a predicate as its truth with
1496
- * unknown as null. How a conformance check asks an implementation one
1497
- * question; refuses what `evaluate` refuses (an operator the table lacks,
1498
- * text holding NUL).
1499
- */
1500
- declare const valueOfOperand: (node: Operandish, options?: {
1501
- readonly input?: Row | undefined;
1502
- readonly operators?: MemoryOperators | undefined;
1503
- readonly context?: ExprContext | undefined;
1504
- }) => unknown;
1505
- /** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */
1506
- type PredicateTruth = Truth;
1507
- /**
1508
- * A predicate's truth from the input (and the context, when given) alone,
1509
- * when it reads no field; none when it reads one, or reads the context and
1510
- * none is given. An interpreter that runs per request decides such a
1511
- * predicate before it builds anything: `isNull($status)` is known before any
1512
- * row is. Refuses what `evaluate` refuses (text holding a NUL).
1513
- */
1514
- declare const decided: (node: Predicate, input: Row, operators?: MemoryOperators, context?: ExprContext) => Option.Option<PredicateTruth>;
1515
- /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
1516
- declare const truthOver: (node: Predicate, row: Row, input?: Row, next?: Row, operators?: MemoryOperators) => PredicateTruth;
1517
- /**
1518
- * What `Judge` comes to: known, or unknown because it rests on something the
1519
- * holder lacks. A known predicate's truth is SQL's three values, its
1520
- * `'unknown'` being SQL's null, which is decided: a row is not kept on it.
1521
- */
1522
- type Verdict<T = PredicateTruth> = {
1523
- readonly _tag: 'Known';
1524
- readonly truth: T;
1525
- } | {
1526
- readonly _tag: 'Unknown';
1527
- readonly reason: string;
1528
- };
1529
- /** What a verdict reads over, besides the row judged. */
1530
- interface JudgeOptions {
1531
- readonly input?: Row | undefined;
1532
- readonly operators?: MemoryOperators | undefined;
1533
- /** What `Expr.viewer` and `Expr.now` read; a predicate reading one refuses a run without it. */
1534
- readonly context?: ExprContext | undefined;
1535
- /**
1536
- * The holder's rows, where a path from the viewer starts. Without them the
1537
- * viewer's row is not held, and such a path is unknown.
1538
- */
1539
- readonly rows?: HeldRows | undefined;
1540
- }
1541
- /**
1542
- * The reference interpreter over what a holder has (`HeldRow`), three-valued:
1543
- * where an answer rests on a row or field the holder lacks or may not see, or
1544
- * on an operator only the server runs, it is unknown, and is never guessed.
1545
- * Where it is known, it is what SQL answers over the same rows: the law the
1546
- * conformance suite checks.
1547
- */
1548
- declare const Judge: {
1549
- /** A predicate over one held row, and, for an invariant, the row a write would leave. */
1550
- predicate: (predicate: Predicate, row: HeldRow, options?: JudgeOptions & {
1551
- readonly next?: HeldRow | undefined;
1552
- }) => Verdict;
1553
- /**
1554
- * Whether a held row is in a query's result: known when every predicate
1555
- * holds (in) or one fails or is null (out), unknown otherwise. `serverOnly`
1556
- * names a filter the server conjoins that this holder does not run (a Read
1557
- * rule, a source's own `where`): a row the body admits is then unknown, and
1558
- * one it refuses is still out. Refuses, as `evaluate` does, a given value
1559
- * holding a NUL.
1560
- */
1561
- query: (body: AnyQuery, input: Row, row: HeldRow, options?: Omit<JudgeOptions, 'input'> & {
1562
- readonly serverOnly?: string | undefined;
1563
- }) => Verdict<boolean>;
1564
- match: <T, A>(verdict: Verdict<T>, cases: {
1565
- readonly onKnown: (truth: T) => A;
1566
- readonly onUnknown: (reason: string) => A;
1567
- }) => A;
1568
- };
1569
- /**
1570
- * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
1571
- * as `evaluate` sorts: negative when it comes first. A call among them runs
1572
- * over each row with `input` and `operators` (the kernel's when not given).
1573
- * Refuses what `evaluate` refuses, for these two rows: a term over neither a
1574
- * field nor a call, a locale collation, keys of different kinds, or an
1575
- * operator the table lacks. For a client placing one row among others it
1576
- * holds.
1577
- */
1578
- declare const compareRows: (terms: ReadonlyArray<OrderTerm>, left: Row, right: Row, query: string, options?: {
1579
- readonly input?: Row | undefined;
1580
- readonly operators?: MemoryOperators | undefined;
1581
- readonly context?: ExprContext | undefined;
1582
- }) => number;
1583
- /**
1584
- * The operations this interpreter runs. It is the reference, so this is the
1585
- * whole kernel — but it is declared rather than assumed, because an
1586
- * interpreter that gains an operator and forgets to say so is exactly what
1587
- * `Query.unsupported` exists to catch.
1588
- */
1589
- declare const supported: ReadonlyArray<Operation>;
1590
- /**
1591
- * Refuses a body needing an operation this interpreter does not run, rather
1592
- * than skipping it and answering a different question. Called by `evaluate`;
1593
- * call it directly to check a body once instead of on every run.
1594
- */
1595
- declare const assertSupported: (body: AnyQuery, operators?: MemoryOperators) => void;
1596
- /**
1597
- * The rows the body matches, in the order it asks for. Pure: it reads the rows
1598
- * it is given and nothing else.
1599
- *
1600
- * `input` holds the values this run was given, by the keys the body's
1601
- * placeholders were built with — the same record the query would be called
1602
- * with anywhere else.
1603
- */
1604
- declare const evaluate: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>, options?: {
1605
- readonly operators?: MemoryOperators | undefined;
1606
- /** What `Expr.viewer` and `Expr.now` read; a body reading one refuses a run without it. */
1607
- readonly context?: ExprContext | undefined;
1608
- }) => ReadonlyArray<Row>;
1609
- /** What `evaluateEach` made of each row: those it matched, in order, and those it refused. */
1610
- interface Evaluated {
1611
- readonly matched: ReadonlyArray<Row>;
1612
- readonly refused: ReadonlyArray<Row>;
1613
- }
1614
- /**
1615
- * As `evaluate`, with each row judged alone: a row whose own values are
1616
- * refused (text holding a NUL, a value an operator fails on) is set aside in
1617
- * `refused` and the others are still answered. A client judging the rows it
1618
- * holds wants this, since one bad stored row says nothing about the rest.
1619
- *
1620
- * What no single row causes still refuses the run: an operation or operator
1621
- * the table lacks, an order by a locale collation, an input the body reads
1622
- * holding a NUL (every row would refuse, and no row is the cause), and order
1623
- * keys of different kinds across rows.
1624
- */
1625
- declare const evaluateEach: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>, options?: {
1626
- readonly operators?: MemoryOperators | undefined;
1627
- /** As `evaluate`'s. */
1628
- readonly context?: ExprContext | undefined;
1629
- }) => Evaluated;
1630
- /** One invariant of an Entity, as its interpreters read it. */
1631
- interface Invariant {
1632
- /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */
1633
- readonly id: string;
1634
- /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */
1635
- readonly entity: string;
1636
- readonly predicate: Predicate;
1637
- /** What someone the rules let write is told when a write would break it. */
1638
- readonly message: string;
1639
- /** The fields a form shows the failure beside. */
1640
- readonly path: ReadonlyArray<string>;
1641
- /** The fields it reads of the row before a write; none for a state invariant. */
1642
- readonly before: ReadonlyArray<string>;
1643
- /** The fields it reads of the row after. */
1644
- readonly after: ReadonlyArray<string>;
1645
- }
1646
- /**
1647
- * Each field as the row before a write holds it: what an invariant reads as
1648
- * `before`. Encoded, as the store holds it and the judge reads it, so a
1649
- * literal is written so too (a date as its ISO text).
1650
- */
1651
- type BeforeRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: FieldExpr<Schema.Codec.Encoded<E['fields'][K]['schema']>> & Reads<E['name']>; };
1652
- /** Each field as the row after a write holds it, encoded: what an invariant reads as `after`. */
1653
- type AfterRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: NextExpr<Schema.Codec.Encoded<E['fields'][K]['schema']>> & Reads<E['name']>; };
1654
- /** A row, or a change from one row to another, as an invariant is judged over it. */
1655
- interface Change {
1656
- readonly after: Row;
1657
- /** The row before an update; none for a create, which judges no transition invariant. */
1658
- readonly before?: Row;
1659
- }
1660
- /** What a row, or a change, comes to under an Entity's invariants. */
1661
- type Judgement = {
1662
- readonly _tag: 'Valid';
1663
- } | {
1664
- readonly _tag: 'Invalid';
1665
- readonly failures: ReadonlyArray<Invariant>;
1666
- } |
1667
- /**
1668
- * Validity is not known: some invariant reads a field the row does not have
1669
- * (`fields`), or calls an operator the table does not run (`operators`, by name).
1670
- */
1671
- {
1672
- readonly _tag: 'Undecided';
1673
- readonly fields: ReadonlyArray<string>;
1674
- readonly operators: ReadonlyArray<string>;
1675
- };
1676
- /** Whether an invariant reads the row before, and so is judged only where there is one. */
1677
- declare const readsBefore: (held: Invariant) => boolean;
1678
- /**
1679
- * An invariant as declared: the step that attaches it to its Entity, carrying
1680
- * its id and, once attached, that Entity's name, so a refusal is matched
1681
- * against the declaration rather than a string spelled again
1682
- * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique
1683
- * only within an Entity, so the name is part of what a refusal names; reading
1684
- * it before the declaration is attached throws.
1685
- */
1686
- interface DeclaredInvariant<E extends AnyEntity> {
1687
- (entity: E): E;
1688
- readonly id: string;
1689
- readonly entity: string;
1690
- }
1691
- declare const invariant: <E extends AnyEntity>(id: string, build: (rows: {
1692
- readonly before: BeforeRow<E>;
1693
- readonly after: AfterRow<E>;
1694
- }) => Predicate & Reads<E['name']>, options: {
1695
- readonly message: string;
1696
- readonly path?: ReadonlyArray<keyof E['fields'] & string>;
1697
- }) => DeclaredInvariant<E>;
1698
- declare const invariantsOf: (entity: AnyEntity) => ReadonlyArray<Invariant>;
1699
- /** `judge` with the invariants given, as a binding that keeps them holds them. */
1700
- declare const judgeAgainst: (invariants: ReadonlyArray<Invariant>, change: Change, operators?: MemoryOperators) => Judgement;
1701
- /**
1702
- * A row, or a change, under every invariant (each row as the store holds it,
1703
- * encoded): valid only when each is true. SQL's unknown, from a null, fails
1704
- * one, as a `WHERE` drops the row; a field a row does not have leaves it
1705
- * undecided, never valid. Without `before` (a create), transition invariants
1706
- * are not judged.
1707
- */
1708
- declare const judge: (entity: AnyEntity, change: Change, operators?: MemoryOperators) => Judgement;
1709
- /**
1710
- * The row an input's value describes, judged under its Entity's state
1711
- * invariants: each key mapped to a field, encoded as the store holds it. An
1712
- * invariant over a field the input does not set (an `Option` holding nothing, a
1713
- * key left out) is undecided, so a partial input is never called valid on its
1714
- * account. It has no row before, so it judges no transition.
1715
- */
1716
- declare const judgeInput: (input: EntityInput<AnyEntity, any, any>, value: Readonly<Record<string, unknown>>, operators?: MemoryOperators) => Judgement;
1717
- /**
1718
- * The Entity's state invariants as an Effect Schema check over its row type:
1719
- * each failure at its path, with its message. The value is encoded first,
1720
- * field by field, so it is judged as the store would hold it. Refused where it
1721
- * is made when an invariant calls an operator `operators` does not run: such a
1722
- * check would pass every value.
1723
- */
1724
- declare const check: <E extends AnyEntity>(entity: E, options?: {
1725
- readonly operators?: MemoryOperators | undefined;
1726
- }) => SchemaAST.Filter<Schema.Schema.Type<E['schema']>>;
1727
- /** The writes that set a member: every insert (`create`), or every insert and update (`write`). */
1728
- type SetOn = 'create' | 'write';
1729
- /** A value the write's context gives: who asks, what their row holds, or when. */
1730
- type ContextValue = ViewerExpr<unknown> | ViewerPathExpr<unknown> | NowExpr<unknown>;
1731
- /** One member `Entity.sets` names: its value, and the writes that set it. */
1732
- interface EntitySet {
1733
- readonly value: ContextValue;
1734
- readonly on: SetOn;
1735
- }
1736
- /**
1737
- * `value` checked against the member `key` it sets, as `Entity.sets` was
1738
- * given them: a relation takes `Expr.viewer` of its target, a field stored as
1739
- * text the viewer's id, a field stored as a number the time.
1740
- */
1741
- declare const checkedSet: (entity: AnyEntity, key: string, value: unknown, on: unknown) => EntitySet;
1742
- declare const Text: {
1743
- /**
1744
- * Whether the first text begins with the second, under the first's collation.
1745
- *
1746
- * | Case | Answer |
1747
- * | --- | --- |
1748
- * | either is null | unknown |
1749
- * | the prefix is `''` | true |
1750
- * | otherwise | whether it begins so, compared under the collation |
1751
- *
1752
- * The collation is the one its text operands share (a field's declared one,
1753
- * or a call's), or one given to the call. `binary` compares exactly;
1754
- * `asciiFold` folds ASCII letters on both sides. Operands declaring
1755
- * different collations, text with none, or a backend's locale are refused
1756
- * where the call is written.
1757
- * Prefixes are by character, so non-ASCII and astral text begin as they read,
1758
- * and half of an astral character begins nothing. A lone surrogate, which
1759
- * UTF-8 cannot hold, compares as U+FFFD, as a database stores it.
1760
- *
1761
- * ```ts
1762
- * Query.where(Text.startsWith(Product.fields.upc, input.search))
1763
- * ```
1764
- */
1765
- startsWith: Operator<readonly [Schema.NullOr<Schema.String>, Schema.NullOr<Schema.String>], Schema.Boolean>;
1766
- };
1767
- type AnyField = EntityField<string, string, Schema.Constraint>;
1768
- type OneRelation$1 = EntityRelation<string, string, AnyEntity, 'one', boolean>;
1769
- /** One input key the write sets, and the field it sets. */
1770
- interface WriteSet {
1771
- readonly key: string;
1772
- readonly field: AnyField;
1773
- }
1774
- /**
1775
- * One input key holding an amount, and the field it moves. `integer` is whether
1776
- * the amount's schema holds it to an integer (`Schema.isInt`): a writer over an
1777
- * integer column refuses an increment without it, which the Entity cannot see.
1778
- */
1779
- interface WriteIncrement extends WriteSet {
1780
- readonly integer: boolean;
1781
- }
1782
- /**
1783
- * One field the write computes (`label := concat(title, ' draft')`): an
1784
- * expression over the row before the write and the input, every defined
1785
- * operator in it expanded, so what is carried is primitive calls alone.
1786
- */
1787
- interface WriteAssignment {
1788
- readonly field: AnyField;
1789
- readonly expr: AnyExpr;
1790
- /**
1791
- * Whether `expr` comes to an integer, by the schemas of what it reads and
1792
- * calls: a writer over an integer column refuses an assignment without it,
1793
- * which the Entity cannot see.
1794
- */
1795
- readonly integer: boolean;
1796
- }
1797
- /**
1798
- * A computed assignment as data, bound to one input: what travels to a server
1799
- * and sits in a client's pending patch, which holds no descriptor and no
1800
- * function. A field of the row before the write, a stored value, or a call of
1801
- * a primitive operator by name (`id`, or `id@version`), with the collation it
1802
- * compares text under (`null` for none: this is JSON).
1803
- */
1804
- type Computation = Data.TaggedEnum<{
1805
- Field: {
1806
- readonly key: string;
1807
- };
1808
- Value: {
1809
- readonly value: unknown;
1810
- };
1811
- Call: {
1812
- readonly operator: string;
1813
- readonly args: ReadonlyArray<Computation>;
1814
- readonly collation: Collation | null;
1815
- };
1816
- }>;
1817
- declare const Computation: Data.TaggedEnum.Constructor<{
1818
- readonly _tag: "Call";
1819
- readonly operator: string;
1820
- readonly args: ReadonlyArray<Computation>;
1821
- readonly collation: Collation | null;
1822
- } | {
1823
- readonly _tag: "Field";
1824
- readonly key: string;
1825
- } | {
1826
- readonly _tag: "Value";
1827
- readonly value: unknown;
1828
- }>;
1829
- /** One input key the write points at another row with: a `one` relation, by the target's id. */
1830
- interface WriteLink {
1831
- readonly key: string;
1832
- readonly relation: OneRelation$1;
1833
- }
1834
- /** One member the write's context sets (`Entity.sets`): a field or a `one` relation, and its value. */
1835
- interface ContextSet {
1836
- readonly member: AnyField | OneRelation$1;
1837
- readonly value: ContextValue;
1838
- }
1839
- /** What a declared write does to its row. */
1840
- type WriteKind = 'Update' | 'Insert' | 'Delete';
1841
- /**
1842
- * One row of an Entity, by id, from an operation's input: updated, inserted
1843
- * with an id the client chose, or deleted. `Kind` is the one its constructor
1844
- * made, so what it may be refused with can follow it.
1845
- */
1846
- interface Write<E extends AnyEntity, Fields extends Schema.Struct.Fields, Kind extends WriteKind = WriteKind> {
1847
- readonly _tag: Kind;
1848
- readonly input: EntityInput<E, Fields, any>;
1849
- /** The input key holding the row's id, and the Entity's `id` field it is. */
1850
- readonly id: WriteSet & {
1851
- readonly key: keyof Fields & string;
1852
- };
1853
- /**
1854
- * The input key holding the revision the row was read at, and its field, when
1855
- * the write is refused for a row that moved on since.
1856
- */
1857
- readonly expect: (WriteSet & {
1858
- readonly key: keyof Fields & string;
1859
- }) | undefined;
1860
- /**
1861
- * What the row must hold for the write to land, over the Entity, read
1862
- * before the write and checked where it commits: an interpreter writes only
1863
- * a row it holds of, and refuses the rest as unmet.
1864
- */
1865
- readonly when: Option.Option<AnyQuery>;
1866
- /** The keys it sets, in the input's order. */
1867
- readonly sets: ReadonlyArray<WriteSet>;
1868
- /**
1869
- * The fields it moves by an amount the input holds (`stock + quantity`),
1870
- * computed where the write commits: the input key, and the field it moves.
1871
- */
1872
- readonly increments: ReadonlyArray<WriteIncrement>;
1873
- /** The fields it computes, each from the row before the write and the input. */
1874
- readonly assignments: ReadonlyArray<WriteAssignment>;
1875
- /** The `one` relations it points elsewhere, in the input's order. */
1876
- readonly links: ReadonlyArray<WriteLink>;
1877
- /**
1878
- * What the write's context sets where it lands (`Entity.sets`): an insert
1879
- * every such member, an update those set `on: 'write'`, a delete none.
1880
- */
1881
- readonly context: ReadonlyArray<ContextSet>;
1882
- }
1883
- type AnyWrite = Write<AnyEntity, any>;
1884
- /** A write declared with a precondition, so it may be refused as unmet. */
1885
- type ConditionedWrite<E extends AnyEntity, Fields extends Schema.Struct.Fields, Kind extends WriteKind = WriteKind> = Write<E, Fields, Kind> & {
1886
- readonly when: Option.Some<AnyQuery>;
1887
- };
1888
- interface RowOptions<Fields extends Schema.Struct.Fields> {
1889
- readonly id: keyof Fields & string;
1890
- readonly expect?: keyof Fields & string;
1891
- }
1892
- /** The keys of `Fields` whose values are numbers. */
1893
- type NumberKeys<Fields> = { [K in keyof Fields & string]: Fields[K] extends Schema.Top ? Schema.Schema.Type<Fields[K]> extends number ? K : never : never; }[keyof Fields & string];
1894
- /** An update's increments: a number field of the Entity, by the input key holding the amount. */
1895
- type WriteIncrements<E extends AnyEntity, Fields extends Schema.Struct.Fields> = { readonly [K in NumberKeys<{ [F in keyof E['fields']]: E['fields'][F]['schema']; }>]?: NumberKeys<Fields>; };
1896
- /**
1897
- * An update's computed fields: each a field of the Entity, by what it comes
1898
- * to over the row before the write (`row`, each field as `Expr.field`) and
1899
- * the input. Its kind is checked against the field's where it is declared.
1900
- */
1901
- type WriteComputations<E extends AnyEntity, Fields extends Schema.Struct.Fields> = { readonly [F in keyof E['fields'] & string]?: (context: {
1902
- readonly row: BeforeRow<E>;
1903
- readonly input: { readonly [K in keyof Fields & string]: InputExpr<Schema.Schema.Type<Fields[K]>>; };
1904
- }) => AnyExpr; };
1905
- /** An update's options: a row's, what it moves by an amount, and what it computes. */
1906
- type UpdateOptions<E extends AnyEntity, Fields extends Schema.Struct.Fields> = RowOptions<Fields> & {
1907
- readonly increment?: WriteIncrements<E, Fields>;
1908
- readonly compute?: WriteComputations<E, Fields>;
1909
- };
1910
- /** `update`: conditioned when given `when`, which the overloads tell apart. */
1911
- interface UpdateWrite {
1912
- <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
1913
- readonly when: WriteCondition<E, Fields>;
1914
- }): ConditionedWrite<E, Fields, 'Update'>;
1915
- <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
1916
- readonly when?: undefined;
1917
- }): Write<E, Fields, 'Update'>;
1918
- }
1919
- /** `delete`: conditioned when given `when`, as an update is. */
1920
- interface DeleteWrite {
1921
- <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
1922
- readonly when: WriteCondition<E, Fields>;
1923
- }): ConditionedWrite<E, Fields, 'Delete'>;
1924
- <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
1925
- readonly when?: undefined;
1926
- }): Write<E, Fields, 'Delete'>;
1927
- }
1928
- /**
1929
- * A write's precondition: a predicate over its Entity's row, given one
1930
- * placeholder per input key, as a `Query.define` body is. It is built once,
1931
- * so `input` stands for what the write will be given.
1932
- */
1933
- type WriteCondition<E extends AnyEntity, Fields extends Schema.Struct.Fields> = (context: {
1934
- readonly input: { readonly [K in keyof Fields & string]: InputExpr<Schema.Schema.Type<Fields[K]>>; };
1935
- }) => Predicate & Reads<E['name']>;
1936
- /** One row's new values, in the store's wire shape: what a client patches and a server writes. */
1937
- interface BoundWrite {
1938
- readonly entity: string;
1939
- readonly id: string;
1940
- readonly values: Readonly<Record<string, unknown>>;
1941
- /**
1942
- * Each `one` relation it points, by the relation's key: the row it points at,
1943
- * or none for an optional relation set to nothing. How a ref is carried (a
1944
- * key on the wire, a foreign key in a table) is each interpreter's.
1945
- */
1946
- readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
1947
- /** Each field it moves, by the amount, encoded: added by the server, and predicted over what a client holds. */
1948
- readonly increments: Readonly<Record<string, number>>;
1949
- /** Each field it computes, as data: run by the server where it writes, predicted by a client. */
1950
- readonly assignments: Readonly<Record<string, Computation>>;
1951
- }
1952
- /** What a write's context comes to: see `Write.contextValues`. */
1953
- interface ContextValues {
1954
- readonly values: Readonly<Record<string, unknown>>;
1955
- readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
1956
- readonly unfilled: ReadonlyArray<string>;
1957
- }
1958
- /**
1959
- * One member of one row, as a holder has it: a field's encoded value, or a
1960
- * `one` relation's ref key (`'User:ada'`) or null; unheld where it lacks it. A
1961
- * server reads every row its asker may see, and reads a hidden one as null.
1962
- */
1963
- type ContextRead<E, R> = (row: EntityRef, key: string) => Effect.Effect<Held$1<unknown>, E, R>;
1964
- declare const Write: {
1965
- /**
1966
- * Sets, on the row whose id is the input's `id` key, every field the input
1967
- * maps a key to. `expect` names the key holding the revision the row was
1968
- * read at: an interpreter writes only a row still at that revision.
1969
- *
1970
- * ```ts
1971
- * const EditPost = Write.update(EditPostInput, { id: 'id' })
1972
- * ```
1973
- *
1974
- * A key mapped to a `one` relation (`Relation.input`) points the row at the
1975
- * id it holds. Refused where it is written: an `id` that is not the Entity's
1976
- * `id` field, a `many` relation or a nested key (not written by an update
1977
- * yet), or nothing to set.
1978
- *
1979
- * `when` is what the row must hold for the update to land, checked where it
1980
- * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
1981
- * does not hold of is refused as unmet.
1982
- *
1983
- * `compute` sets a field to what an expression comes to over the row before
1984
- * the write and the input, run where it commits
1985
- * (`{ label: ({ row }) => concat(row.title, ' draft') }`). It is refused for
1986
- * a field another key writes, an expression over the row after the write or
1987
- * another Entity, or one of a kind the field does not store.
1988
- */
1989
- update: UpdateWrite;
1990
- /**
1991
- * Inserts the row whose id is the input's `id` key, an id the client chose,
1992
- * with every field and `one` relation the input maps a key to. An insert
1993
- * expects no revision: there is no row to have read. A row already there
1994
- * under that id (a retry) is left as it is.
1995
- *
1996
- * What its Entity sets from the write's context (`Entity.sets`: who asks,
1997
- * when) it writes too, never from the input: a server fills them, a client
1998
- * predicts them. An update writes those set `on: 'write'`.
1999
- */
2000
- insert: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: {
2001
- readonly id: keyof Fields & string;
2002
- }) => Write<E, Fields, 'Insert'>;
2003
- /**
2004
- * Deletes the row whose id is the input's `id` key, only while it is still at
2005
- * the revision `expect` names, when it names one. It sets nothing, so a key
2006
- * mapped to a member is refused where it is written. A row already gone (a
2007
- * retry) is gone. `when`, as an update's, is what the row must hold.
2008
- */
2009
- delete: DeleteWrite;
2010
- /**
2011
- * The revision this input says the row was read at, encoded, with its field:
2012
- * what an interpreter writes only a row still at. None for a write that
2013
- * expects none.
2014
- */
2015
- expected: <Fields extends Schema.Struct.Fields>(write: Write<AnyEntity, Fields>, value: Schema.Struct.Type<Fields>) => Option.Option<{
2016
- readonly field: string;
2017
- readonly revision: unknown;
2018
- }>;
2019
- /** The members any invocation may write: what a query reading none of them cannot be changed by. */
2020
- writes: (write: AnyWrite) => ReadonlyArray<AnyField | OneRelation$1>;
2021
- /**
2022
- * What the context sets come to, encoded as the store holds them: each
2023
- * field's value and each relation's link. A path from the viewer is read
2024
- * through `read`, one row at a time. `unfilled` names each member there is
2025
- * no value for: none to read (no reading of the time, a row or field
2026
- * `read` does not hold), or a null where the member holds none (a visitor,
2027
- * a viewer of another Entity, a path reaching no row). A server refuses such
2028
- * a write; a client predicts nothing for the member.
2029
- */
2030
- contextValues: <E, R>(write: AnyWrite, by: ExprContext, read: ContextRead<E, R>) => Effect.Effect<ContextValues, E, R>;
2031
- /** The Entities a write's paths from the viewer read, by name: what a server must have a source of. */
2032
- contextReads: (write: AnyWrite) => ReadonlyArray<string>;
2033
- /**
2034
- * The fields a write reads from the row it writes: those its `when` reads,
2035
- * each it increments, each its assignments read, and the revision it
2036
- * expects. What an interpreter must read, and what a startup check judges
2037
- * it could disclose.
2038
- */
2039
- reads: (write: AnyWrite) => ReadonlyArray<AnyField>;
2040
- /**
2041
- * The row this input writes and its new values, encoded as the store holds
2042
- * them: the patch a client shows before the server answers. `keys`, when
2043
- * given, narrows it to those input keys (what an author changed); the rest of
2044
- * the input is still the whole, validated value.
2045
- */
2046
- bind: <Fields extends Schema.Struct.Fields>(write: Write<AnyEntity, Fields>, value: Schema.Struct.Type<Fields>, keys?: ReadonlyArray<string>) => BoundWrite;
2047
- /**
2048
- * The fields of the row before it that a bound write's amounts and
2049
- * assignments read: what to read to work out the row it leaves.
2050
- */
2051
- boundReads: (bound: Pick<BoundWrite, 'increments' | 'assignments'>) => ReadonlyArray<string>;
2052
- /**
2053
- * The row a bound write leaves over `row`, the row before it: its values
2054
- * set, each amount added (a null stays null, as in SQL), and each
2055
- * assignment computed by `operators` over the row before. `unknown` names
2056
- * each field it could not work out: one `row` lacks, or holds as no number
2057
- * for an amount, or an assignment calling an operator the table lacks. That
2058
- * field keeps what `row` holds. The one computation of this row: a guard
2059
- * judges it, a writer explains a miss with it, a client predicts it.
2060
- */
2061
- apply: (row: Readonly<Record<string, unknown>>, bound: Pick<BoundWrite, 'values' | 'increments' | 'assignments'>, options: {
2062
- readonly operators: MemoryOperators;
2063
- }) => {
2064
- readonly row: Readonly<Record<string, unknown>>;
2065
- readonly unknown: ReadonlyArray<string>;
2066
- };
2067
- };
2068
- declare const EntityTypeId: unique symbol;
2069
- type EntityTypeId = typeof EntityTypeId;
2070
- /**
2071
- * What makes two descriptors the same Entity. A pipe step returns a new
2072
- * descriptor with the same identity, so compare `identity`, never the objects.
2073
- */
2074
- interface EntityIdentity<Name extends string> {
2075
- readonly name: Name;
2076
- /** Distinguishes two Entities that were defined with the same name. */
2077
- readonly token: symbol;
2078
- }
2079
- /** An intrinsic value of the Entity: one property of `entity.schema`. */
2080
- interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {
2081
- readonly _tag: 'Field';
2082
- readonly owner: EntityIdentity<Name>;
2083
- readonly key: Key;
2084
- readonly schema: S;
2085
- readonly metadata: Metadata;
2086
- }
2087
- type Cardinality = 'one' | 'many';
2088
- /** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */
2089
- interface RelationSpec<Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
2090
- readonly target: Target;
2091
- readonly cardinality: C;
2092
- readonly optional: Optional;
2093
- }
2094
- /**
2095
- * A navigation edge as its owner sees it: one or many of `target`. How the edge
2096
- * is stored (a foreign key, a join table, a nested document) is the
2097
- * interpreter's concern.
2098
- */
2099
- interface EntityRelation<Name extends string, Key extends string, Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
2100
- readonly _tag: 'Relation';
2101
- readonly owner: EntityIdentity<Name>;
2102
- readonly key: Key;
2103
- /** The target as `Entity.relate` returned it, so its own relations can be followed. */
2104
- readonly target: () => Target;
2105
- readonly cardinality: C;
2106
- readonly optional: Optional;
2107
- readonly metadata: Metadata;
2108
- }
2109
- type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>;
2110
- /**
2111
- * What a derived member is. `Supplied` (`Derived.make`): an interpreter
2112
- * supplies it, and nothing else can say what it is. `Count`
2113
- * (`Derived.count`): how many rows point at this one through `relation`, a
2114
- * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of
2115
- * a row pointing here through `relation` whose `viewer` relation points at
2116
- * whoever reads it, or none. A client predicts both from the rows it writes,
2117
- * and a server compiles both from the relations' storage.
2118
- */
2119
- type Derivation = Data.TaggedEnum<{
2120
- /**
2121
- * `predict`: how a client foresees it for a row it writes; none, it waits
2122
- * for the server. `forbids`: which write to the row its value refuses, so a
2123
- * client holding it refuses that write where it is made.
2124
- */
2125
- Supplied: {
2126
- readonly predict: Option.Option<Predict>;
2127
- readonly forbids: Option.Option<Forbids>;
2128
- };
2129
- Count: {
2130
- readonly relation: OneRelation;
2131
- };
2132
- Exists: {
2133
- readonly relation: OneRelation;
2134
- readonly viewer: OneRelation;
2135
- };
2136
- }>;
2137
- declare const Derivation: Data.TaggedEnum.Constructor<{
2138
- readonly _tag: "Count";
2139
- readonly relation: OneRelation;
2140
- } | {
2141
- readonly _tag: "Exists";
2142
- readonly relation: OneRelation;
2143
- readonly viewer: OneRelation;
2144
- } | {
2145
- readonly _tag: "Supplied";
2146
- readonly predict: Option.Option<Predict>;
2147
- readonly forbids: Option.Option<Forbids>;
2148
- }>;
2149
- /** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */
2150
- interface Predicting {
2151
- /** The Entity written, as the write declared it. */
2152
- readonly entity: AnyEntity;
2153
- readonly row: HeldRow;
2154
- /** The holder's other rows, where a rule's path reads. */
2155
- readonly rows: HeldRows;
2156
- /** The operation's context: who asks, and the write's time. */
2157
- readonly context: ExprContext;
2158
- }
2159
- /**
2160
- * A supplied member foreseen: its value **encoded**, as the store holds it, or
2161
- * none where the holder cannot know it, so nothing is shown before the answer.
2162
- */
2163
- type Predict = (predicting: Predicting) => Option.Option<unknown>;
2164
- /**
2165
- * What a write does to a row it finds, as a supplied member's `forbids` is
2166
- * asked: an update's members and the relations it points, or a delete.
2167
- */
2168
- interface WriteSurface {
2169
- readonly kind: 'Update' | 'Delete';
2170
- /** The members it sets, moves or computes, relations not among them. */
2171
- readonly members: ReadonlyArray<string>;
2172
- /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */
2173
- readonly relations: ReadonlyArray<{
2174
- readonly relation: string;
2175
- readonly interaction: 'Link' | 'Unlink';
2176
- }>;
2177
- }
2178
- /**
2179
- * Whether a supplied member's value, **encoded** as the store holds it,
2180
- * refuses `surface`, with the reader's words for why when there are any; none
2181
- * where it does not say so for certain. Only a definite refusal: a client
2182
- * refuses the write unseen, and its server would refuse it too.
2183
- */
2184
- type Forbids = (value: unknown, surface: WriteSurface) => Option.Option<{
2185
- readonly reason: Option.Option<string>;
2186
- }>;
2187
- /** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */
2188
- interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {
2189
- readonly schema: S;
2190
- readonly derives: D;
2191
- }
2192
- /** A value consumers may read that is not part of `entity.schema`, and what it derives. */
2193
- interface EntityDerived<Name extends string, Key extends string, S extends Schema.Constraint, D extends Derivation = Derivation> {
2194
- readonly _tag: 'Derived';
2195
- readonly owner: EntityIdentity<Name>;
2196
- readonly key: Key;
2197
- readonly schema: S;
2198
- readonly derives: D;
2199
- readonly metadata: Metadata;
2200
- }
2201
- type EntityMember = EntityField<string, string, Schema.Constraint> | EntityRelation<string, string, AnyEntity, Cardinality, boolean> | EntityDerived<string, string, Schema.Constraint>;
2202
- type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>;
2203
- type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>;
2204
- type FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = { readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>; };
2205
- type RelationsOf<Name extends string, Relations extends RelationSpecs> = { readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<infer Target, infer C, infer Optional> ? EntityRelation<Name, K, Target, C, Optional> : never; };
2206
- type DerivedOf<Name extends string, Derived extends DerivedSpecs> = { readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema'], Derived[K]['derives']>; };
2207
- interface Entity<Name extends string, Fields extends Schema.Struct.Fields, Relations extends RelationSpecs = {}, Derived extends DerivedSpecs = {}> extends Pipeable.Pipeable {
2208
- readonly [EntityTypeId]: EntityTypeId;
2209
- readonly identity: EntityIdentity<Name>;
2210
- readonly name: Name;
2211
- /** The intrinsic value only: no relations, no derived members. */
2212
- readonly schema: Schema.Struct<Fields>;
2213
- readonly fields: FieldsOf<Name, Fields>;
2214
- readonly relations: RelationsOf<Name, Relations>;
2215
- readonly derived: DerivedOf<Name, Derived>;
2216
- /** Every readable member under one namespace; keys never collide. */
2217
- readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>;
2218
- /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */
2219
- readonly sets: Readonly<Record<string, EntitySet>>;
2220
- readonly metadata: Metadata;
2221
- }
2222
- type AnyEntity = Entity<string, any, any, any>;
2223
- /** The keys of an Entity's `one` relations. */
2224
- type OneRelationKeys<E extends AnyEntity> = { [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never; }[keyof E['relations'] & string];
2225
- /**
2226
- * What a field holding `T` may be set to: the time where it holds a number,
2227
- * the viewer's id where text, and what a path from the viewer reads where it
2228
- * holds that.
2229
- */
2230
- type ContextValueFor<T> = (number extends T ? NowExpr<number> : never) | (T extends string ? ViewerExpr<T> : never) | ViewerPathExpr<T | null>;
2231
- /** The name of the Entity the `one` relation `K` points at. */
2232
- type TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<E['relations'][K]['target']>['name'];
2233
- /**
2234
- * What `Entity.sets` takes, by member: a field the value of the write's
2235
- * context it can hold, a `one` relation `Expr.viewer` of its target.
2236
- */
2237
- type EntitySets<E extends AnyEntity> = { readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<Schema.Schema.Type<E['fields'][K]['schema']>>; } & { readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>; };
2238
- /** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */
2239
- type Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never ? unknown : {
2240
- readonly alreadyAMember: keyof New & keyof E['members'];
2241
- };
2242
- /** Unsatisfiable when a `Derived.count` or `Derived.exists` names a relation pointing at another Entity. */
2243
- type PointsHere<E extends AnyEntity, New extends DerivedSpecs> = { [K in keyof New]: New[K]['derives'] extends {
2244
- readonly _tag: 'Count' | 'Exists';
2245
- readonly relation: EntityRelation<any, any, infer Target, any, any>;
2246
- } ? [Target['name']] extends [E['name']] ? never : K : never; }[keyof New] extends (infer Wrong) ? [Wrong] extends [never] ? unknown : {
2247
- readonly countsRowsPointingAtAnotherEntity: Wrong;
2248
- } : never;
2249
- type WithDerived<E, New extends DerivedSpecs> = E extends Entity<infer Name, infer Fields, infer R, infer D> ? Entity<Name, Fields, R, D & New> : never;
2250
- type Entities = Readonly<Record<string, AnyEntity>>;
2251
- type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs; };
2252
- /** The key in `Es` of the Entity a spec targets, matched by name. */
2253
- type TargetKey<Es extends Entities, Target extends AnyEntity> = { [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']] ? K : never; }[keyof Es];
2254
- type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = { readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional> ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional> : never; };
2255
- /**
2256
- * One Entity of an `Entity.relate` result. A relation's target is again a
2257
- * `Related`, so relations can be followed through a cycle; the recursion goes
2258
- * through type arguments, which TypeScript resolves only when asked.
2259
- */
2260
- type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = Es[K] extends Entity<infer Name, infer Fields, infer R, infer D> ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D> : never;
2261
- /** Marks a relation key that is already a member of its owner, or an owner that is not listed. */
2262
- type CheckRelations<Es extends Entities, Rs> = { readonly [K in keyof Rs]: K extends keyof Es ? { readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members'] ? `"${R & string}" is already a member of ${Es[K]['name']}` : Rs[K][R]; } : 'not one of the entities being related'; };
2263
- declare const SelectionTypeId: unique symbol;
2264
- type SelectionTypeId = typeof SelectionTypeId;
2265
- /**
2266
- * The schema that identifies one of an Entity: its `id` field when that is text
2267
- * (a plain string, a brand, a pattern), and plain text otherwise. An id is text
2268
- * because a ref travels and is stored as text; an Entity keyed by a number still
2269
- * has refs, and their ids are the number as text.
2270
- */
2271
- type IdSchemaOf<E> = E extends {
2272
- readonly fields: {
2273
- readonly id: {
2274
- readonly schema: infer S;
2275
- };
2276
- };
2277
- } ? S extends Schema.Constraint ? [S['Type']] extends [string] ? S : Schema.String : Schema.String : Schema.String;
2278
- /** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */
2279
- type IdOf<E> = IdSchemaOf<E>['Type'];
2280
- /**
2281
- * What a relation selected with `true` yields: which Entity, and which one. `Id`
2282
- * is the target's own id type, so a ref to an Author cannot be used as a Post's.
2283
- */
2284
- interface EntityRef<Name extends string = string, Id extends string = string> {
2285
- readonly entity: Name;
2286
- readonly id: Id;
2287
- }
2288
- type RefSchema<Target extends AnyEntity> = Schema.Struct<{
2289
- readonly entity: Schema.Literal<Target['name']>;
2290
- readonly id: IdSchemaOf<Target>;
2291
- }>;
2292
- /**
2293
- * A view of the Entity graph: which members to read, and the schema of the
2294
- * value that results. It says nothing about where the value comes from.
2295
- */
2296
- interface Selection<Name extends string, Members, S extends Schema.Constraint, Id extends string = string> {
2297
- readonly [SelectionTypeId]: SelectionTypeId;
2298
- /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */
2299
- readonly Id?: Id;
2300
- readonly entity: Entity<Name, any, any, any>;
2301
- /** What was selected, by member key: `true`, or a relation's nested Selection. */
2302
- readonly members: Members;
2303
- readonly schema: S;
2304
- }
2305
- type AnySelection<Name extends string = string> = Selection<Name, any, any>;
2306
- /** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */
2307
- type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type'];
2308
- /** `true` for any member; a relation also takes a Selection of its target. */
2309
- /**
2310
- * Which part of a `many` relation to read: the first or last so many, from a
2311
- * cursor or from the end. A cursor is whatever the interpreter handed out with an
2312
- * earlier page; nothing here looks inside it.
2313
- */
2314
- interface PageWindow {
2315
- readonly first?: number | undefined;
2316
- readonly last?: number | undefined;
2317
- readonly after?: string | undefined;
2318
- readonly before?: string | undefined;
2319
- }
2320
- declare const SelectionPageTypeId: unique symbol;
2321
- type SelectionPageTypeId = typeof SelectionPageTypeId;
2322
- /** A Selection of a `many` relation's target, read a page at a time. */
2323
- interface SelectionPage<Name extends string, S extends Schema.Constraint> {
2324
- readonly [SelectionPageTypeId]: SelectionPageTypeId;
2325
- readonly selection: Selection<Name, any, S>;
2326
- readonly window: PageWindow;
2327
- }
2328
- type PageSchema<S extends Schema.Constraint> = Schema.Struct<{
2329
- readonly items: Schema.$Array<S>;
2330
- readonly hasNext: Schema.Boolean;
2331
- readonly hasPrevious: Schema.Boolean;
2332
- }>;
2333
- type SelectionSpec<E extends AnyEntity, Spec> = { readonly [K in keyof Spec]: K extends keyof E['relations'] ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any> ? true | AnySelection<Target['name']> | (C extends 'many' ? SelectionPage<Target['name'], any> : never) : never : K extends keyof E['members'] ? true : `"${K & string}" is not a member of ${E['name']}`; };
2334
- type RelationShape<C extends Cardinality, Optional extends boolean, S extends Schema.Constraint> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S;
2335
- type SelectedSchema<Member, Selected> = Member extends EntityField<any, any, infer S> | EntityDerived<any, any, infer S> ? S : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional> ? Selected extends SelectionPage<any, infer S> ? PageSchema<S> : RelationShape<C, Optional, Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>> : never;
2336
- type SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{ readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>; }>;
2337
- /** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */
2338
- interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {
2339
- readonly _tag: 'RelationInput';
2340
- readonly relation: R;
2341
- }
2342
- /**
2343
- * An input key that carries the relation's target itself, written through an
2344
- * input of its own: a post created with a new author, an order with its lines.
2345
- * A `one` holds that input's value, a `many` a list of them.
2346
- */
2347
- interface NestedInput<R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>> {
2348
- readonly _tag: 'NestedInput';
2349
- readonly relation: R;
2350
- readonly input: I;
2351
- }
2352
- /** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */
2353
- interface Unmapped {
2354
- readonly _tag: 'Unmapped';
2355
- }
2356
- /** What one key of an operation's input means in terms of the Entity. */
2357
- type InputMember = EntityField<string, string, Schema.Constraint> | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>> | NestedInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>, EntityInput<AnyEntity, any, any>> | Unmapped;
2358
- /** The ids a relation takes as input: one id, a nullable id, or a list of ids. */
2359
- type RelationIds<R> = R extends EntityRelation<any, any, infer Target, infer C, infer Optional> ? C extends 'many' ? ReadonlyArray<IdOf<Target>> : Optional extends true ? IdOf<Target> | null : IdOf<Target> : never;
2360
- /** What a nested input takes: the value of the target's input, or a list of them for a `many`. */
2361
- type NestedValues<R, I> = I extends EntityInput<any, infer Fields, any> ? R extends EntityRelation<any, any, any, 'many', any> ? ReadonlyArray<Schema.Struct.Type<Fields>> : Schema.Struct.Type<Fields> : never;
2362
- type Present<T> = Exclude<T, null | undefined>;
2363
- /** What an `Option` holds, else the value itself. */
2364
- type Held<T> = T extends Option.Some<infer A> ? Present<A> : T extends Option.None<any> ? never : Present<T>;
2365
- /**
2366
- * Whether an input value fits a field. Only the value that is present has to
2367
- * fit: an input may leave a key out (a partial update), send `null` to clear
2368
- * it, or hold an `Option` (an id absent for something new), whose value fits as
2369
- * it is (an `Option` field) or as what it holds. Whether it may is the input
2370
- * schema's rule; the fit only guards against mapping the wrong member.
2371
- */
2372
- type Fits<Input, Field> = [Present<Input>] extends [Field] ? true : [Held<Input>] extends [Field] ? true : false;
2373
- type MappingFor<Name extends string, Input, M> = M extends Unmapped ? M : M extends EntityField<infer Owner, any, any> | RelationInput<EntityRelation<infer Owner, any, any, any, any>> | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any> ? [Owner] extends [Name] ? M extends EntityField<any, any, infer S> ? Fits<Input, Schema.Schema.Type<S>> extends true ? M : 'the input value does not fit this field' : M extends RelationInput<infer R> ? Present<Input> extends RelationIds<R> ? M : 'the input value is not the id shape of this relation' : M extends NestedInput<infer R, infer I> ? R extends EntityRelation<any, any, infer Target, any, any> ? I extends EntityInput<infer Of, any, any> ? [Of['name']] extends [Target['name']] ? Present<Input> extends NestedValues<R, I> ? M : 'the input value is not the value of the nested input' : `the nested input is of ${Of['name']}, not ${Target['name']}` : never : never : never : `this member belongs to ${Owner}` : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped';
2374
- /** A key that names a field whose value it fits maps itself; every other key needs an entry. */
2375
- type SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = { [K in keyof Fields]: K extends keyof E['fields'] ? Fits<Schema.Schema.Type<Fields[K]>, Schema.Schema.Type<E['fields'][K]['schema']>> extends true ? K : never : never; }[keyof Fields];
2376
- /**
2377
- * A mapping written as a member's key: `'title'` is that Field, and `'author'` is
2378
- * `Relation.input` of that relation. Nothing is inferred from the input key's own
2379
- * name; the member is still named, only more briefly.
2380
- */
2381
- type Named<E extends AnyEntity, M> = M extends string ? M extends keyof E['fields'] ? E['fields'][M] : M extends keyof E['relations'] ? RelationInput<E['relations'][M]> : `"${M}" names no field or relation of ${E['name']}` : M;
2382
- type InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = { readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown; } & { readonly [K in keyof Mapping]: K extends keyof Fields ? Named<E, Mapping[K]> extends (infer Member) ? Member extends string ? Member : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member ? Mapping[K] : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> : never : `"${K & string}" is not a key of the input`; };
2383
- /** The member each key of an input writes, as `Entity.input` reads it from a mapping. */
2384
- type InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = { readonly [K in keyof Fields]: K extends keyof Mapping ? Named<E, Mapping[K]> : K extends keyof E['fields'] ? E['fields'][K] : never; };
2385
- /**
2386
- * An operation's input read against an Entity: which member each input key
2387
- * writes. The operation decides what may be submitted; the Entity only says
2388
- * what each submitted key means.
2389
- */
2390
- interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {
2391
- readonly entity: E;
2392
- readonly schema: Schema.Struct<Fields>;
2393
- readonly members: Members;
2394
- }
2395
- /** The Entity member an input key writes, by its key; nothing for an unmapped key. */
2396
- type WrittenKey<M> = M extends EntityField<any, infer Key, any> ? Key : M extends RelationInput<EntityRelation<any, infer Key, any, any, any>> | NestedInput<EntityRelation<any, infer Key, any, any, any>, any> ? Key : never;
2397
- /** A nested input reads what it writes of the target; every other member reads as it is. */
2398
- type WrittenAs<M> = M extends NestedInput<any, EntityInput<infer Of, any, infer Members>> ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>> : true;
2399
- /** Every member the input writes: what to read to show the input's current values. */
2400
- type WrittenSpec<Members> = { readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>; };
2401
- declare const isSameEntity: (left: AnyEntity, right: AnyEntity) => boolean;
2402
- declare const isEntity: (value: unknown) => value is AnyEntity;
2403
- declare const Entity: {
2404
- /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
2405
- define: <const Name extends string, Fields extends Schema.Struct.Fields>(name: Name, schema: Schema.Struct<Fields>) => Entity<Name, Fields>;
2406
- /**
2407
- * Declares the relations between a set of Entities in one step, and returns
2408
- * them related. One step, because Entities that point at each other cannot
2409
- * each be declared in terms of the other.
2410
- */
2411
- relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(entities: Es, relations: Rs & CheckRelations<Es, Rs>) => { readonly [K in keyof Es]: Related<Es, Rs, K>; };
2412
- /**
2413
- * Selects members of an Entity and assembles the schema of the result. A
2414
- * relation selected with `true` yields an `EntityRef`; with a Selection of its
2415
- * target, that Selection's value. `many` yields an array, an optional `one`
2416
- * is nullable.
2417
- */
2418
- select: <E extends AnyEntity, const Spec>(entity: E, spec: Spec & SelectionSpec<E, Spec>) => Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>>;
2419
- /**
2420
- * A `many` relation read a page at a time, in place of its Selection:
2421
- * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
2422
- * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
2423
- */
2424
- page: <Name extends string, S extends Schema.Constraint>(selection: Selection<Name, any, S>, window: PageWindow) => SelectionPage<Name, S>;
2425
- /**
2426
- * Adds readable members that are not part of `entity.schema`. A
2427
- * `Derived.count` or `Derived.exists` must read rows pointing at this
2428
- * Entity: one over a relation to another is refused here, as is an exists
2429
- * whose viewer is not another `one` relation of the same pointing Entity.
2430
- */
2431
- derived: <const New extends DerivedSpecs>(specs: New) => <E extends AnyEntity>(entity: E & Free<E, New> & PointsHere<E, New>) => WithDerived<E, New>;
2432
- /**
2433
- * Says which members take their value from the write's context, never its
2434
- * input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a
2435
- * field holding their id), and `Expr.now`, when (a field stored as a
2436
- * number). `on` says which writes set them: `'create'`, every insert, or
2437
- * `'write'`, every insert and every update.
2438
- *
2439
- * ```ts
2440
- * const Post = Blog.Post.pipe(
2441
- * Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),
2442
- * Entity.sets({ editedAt: Expr.now }, { on: 'write' }),
2443
- * )
2444
- * ```
2445
- *
2446
- * Every write of the Entity follows from it: a server writes the values and
2447
- * a client predicts them, and a write whose input sets one is refused where
2448
- * it is declared. Refused here: the id, a member set already, a `many`
2449
- * relation, a relation set to anything but the viewer of its target, and a
2450
- * field that cannot hold its value. Added after `Entity.relate` to set a
2451
- * relation.
2452
- */
2453
- sets: <E extends AnyEntity>(values: EntitySets<E>, options: {
2454
- readonly on: SetOn;
2455
- }) => (entity: E) => E;
2456
- /** Attaches an interpreter's metadata to the Entity itself. */
2457
- annotate: (metadata: Metadata) => <E extends AnyEntity>(entity: E) => E;
2458
- /**
2459
- * Declares what every stored row, or every change of one, must hold:
2460
- * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
2461
- * Expr.lte(after.reserved, after.quantity), { message })` over the row a
2462
- * write leaves, or with `before` too over the change an update makes.
2463
- * Refused where it is declared: an id declared twice, a predicate over another
2464
- * Entity, one reading an input or nothing of `after` (that is a `when`), a path
2465
- * naming no field.
2466
- */
2467
- invariant: typeof invariant;
2468
- /** The Entity's invariants, in the order they were declared. */
2469
- invariants: typeof invariantsOf;
2470
- /**
2471
- * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
2472
- * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
2473
- * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
2474
- * one reads that a row lacks.
2475
- */
2476
- judge: typeof judge;
2477
- /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
2478
- readsBefore: typeof readsBefore;
2479
- /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
2480
- judgeAgainst: typeof judgeAgainst;
2481
- /**
2482
- * The row an `Entity.input`'s value describes, judged: what a form can say
2483
- * before the server does. Undecided for an invariant over a field it leaves unset.
2484
- */
2485
- judgeInput: typeof judgeInput;
2486
- /** The state invariants as a Schema check over the row type, each failure at its path. */
2487
- check: typeof check;
2488
- /** Attaches an interpreter's metadata to members, by key. */
2489
- annotateMembers: <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata; }) => (entity: E) => E;
2490
- /**
2491
- * Reads an operation's input schema against an Entity. A key that names a
2492
- * field maps to it; any other key is mapped explicitly, to a Field, to
2493
- * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
2494
- * from a naming convention such as `authorId`.
2495
- */
2496
- input: <E extends AnyEntity, Fields extends Schema.Struct.Fields, const Mapping = {}>(entity: E, schema: Schema.Struct<Fields>, ...mapping: keyof InputMapping<E, Fields, Mapping> extends never ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>] : [mapping: Mapping & InputMapping<E, Fields, Mapping>]) => EntityInput<E, Fields, InputMembers<E, Fields, Mapping>>;
2497
- /** For an input key that is about the operation rather than the Entity. */
2498
- unmapped: Unmapped;
2499
- /**
2500
- * The schemas of some of an Entity's fields, by key, to spread into an input's
2501
- * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
2502
- * The input then keeps the field's own rules, and its keys map themselves.
2503
- */
2504
- fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(entity: E, ...keys: Keys) => { readonly [K in Keys[number]]: E['fields'][K]['schema']; };
2505
- /**
2506
- * The Selection of every member an input writes, with each relation as refs:
2507
- * what an edit screen loads before it shows the input's current values.
2508
- */
2509
- selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(input: EntityInput<E, Fields, Members>) => Selection<E['name'], WrittenSpec<Members>, SelectionSchema<E, WrittenSpec<Members>>, IdOf<E>>;
2510
- /**
2511
- * The input values that reproduce `value`, a value read through `selectFor`
2512
- * (or any Selection with those members): a field as it is, a relation as the
2513
- * id or ids of its refs. A key whose member `value` lacks is left out, as is
2514
- * an unmapped key, which the Entity knows nothing about.
2515
- */
2516
- valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(input: EntityInput<E, Fields, Members>, value: Readonly<Record<string, unknown>>) => Partial<Schema.Struct.Type<Fields>>;
2517
- is: typeof isEntity;
2518
- /** True when both descriptors are versions of one Entity. */
2519
- same: typeof isSameEntity;
2520
- };
2521
- declare function one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>;
2522
- declare function one<Target extends AnyEntity, const Optional extends boolean>(target: Target, options: {
2523
- readonly optional: Optional;
2524
- }): RelationSpec<Target, 'one', Optional>;
2525
- /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
2526
- declare const Relation: {
2527
- one: typeof one;
2528
- /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
2529
- input: <R extends EntityRelation<any, any, any, any, any>>(relation: R) => RelationInput<R>;
2530
- /**
2531
- * For `Entity.input`: the input key holds the relation's target itself, written
2532
- * through `input`, an `Entity.input` of the target. A `many` holds a list.
2533
- */
2534
- nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(relation: R, input: I) => NestedInput<R, I>;
2535
- many: <Target extends AnyEntity>(target: Target) => RelationSpec<Target, 'many', false>;
2536
- };
2537
- /** A count: never negative, never a fraction. */
2538
- declare const CountSchema: Schema.Number;
2539
- /** The id of the row an exists found, as every Remote id is held: text, or none. */
2540
- declare const WitnessSchema: Schema.OptionFromNullOr<Schema.String>;
2541
- type OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never;
2542
- declare const Derived: {
2543
- /**
2544
- * A member only an interpreter can compute, of type `schema`: it supplies the
2545
- * value. `predict` says how a client foresees it for a row it writes (Guard's
2546
- * `may`); without it the row reads as missing the member until the answer.
2547
- * `forbids` says which write to the row its value refuses (Guard's `may`
2548
- * again), so a client holding it refuses that write where it is made.
2549
- */
2550
- make: <S extends Schema.Constraint>(schema: S, options?: {
2551
- readonly predict?: Predict | undefined;
2552
- readonly forbids?: Forbids | undefined;
2553
- }) => DerivedSpec<S, Extract<Derivation, {
2554
- readonly _tag: 'Supplied';
2555
- }>>;
2556
- /**
2557
- * How many rows point at this one through `relation`, a `one` relation of
2558
- * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on
2559
- * Post. Added after `Entity.relate`, which makes the relation. A server
2560
- * compiles it from the relation's storage, and a client predicts it from
2561
- * the rows a pending write inserts, deletes or points elsewhere.
2562
- */
2563
- count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(relation: R) => DerivedSpec<typeof CountSchema, {
2564
- readonly _tag: 'Count';
2565
- readonly relation: R;
2566
- }>;
2567
- /**
2568
- * Whether a row points at this one through `relation` and at whoever reads
2569
- * it through `viewer`, another `one` relation of the same pointing Entity:
2570
- * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`
2571
- * on Post. Its value is that row's id as the store holds it, or none, so the
2572
- * reader can take it back (`Write.delete` by that id). It depends on who
2573
- * reads it: a server answers it for the principal it reads as, and a client
2574
- * predicts it for the viewer it is told of.
2575
- */
2576
- exists: <R extends OneRelation, V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>>(relation: R, options: {
2577
- readonly viewer: V;
2578
- }) => DerivedSpec<typeof WitnessSchema, {
2579
- readonly _tag: 'Exists';
2580
- readonly relation: R;
2581
- readonly viewer: V;
2582
- }>;
2583
- };
2584
- export { WriteAssignment as $, TextOperand as $n, tableTested as $t, RelationInput as A, NullPredicate as An, QueryEvaluateError as At, Unmapped as B, OrderedOperand as Bn, supported as Bt, NestedInput as C, FieldExpr as Cn, judgeInput as Ct, Related as D, LiteralExpr as Dn, Judge as Dt, Predicting as E, Invalid as En, Evaluated as Et, Selection as F, OperatorDescriptor as Fn, assertSupported as Ft, AnyWrite as G, Placement as Gn, MemoryImplementation as Gt, WrittenAs as H, ParameterOf as Hn, valueOfOperand as Ht, SelectionPage as I, OperatorTable as In, compareRows as It, ConditionedWrite as J, QueryDependencies as Jn, OperatorDescription as Jt, BoundWrite as K, Predicate as Kn, MemoryOperators as Kt, SelectionPageTypeId as L, OrPredicate as Ln, decided as Lt, RelationSpec as M, Operandish as Mn, RowsMissingError as Mt, RelationSpecs as N, Operation as Nn, Verdict as Nt, RelatedSpecs as O, NextExpr as On, OperatorMissingError as Ot, Selected as P, Operator as Pn, applyOperator as Pt, Write as Q, TestPredicate as Qn, stampTested as Qt, SelectionTypeId as R, Order as Rn, evaluate as Rt, InputMembers as S, FieldDependency as Sn, judgeAgainst as St, Predict as T, InputExpr as Tn, ContextMissingError as Tt, WrittenKey as U, PathEnd as Un, Evidence as Ut, WriteSurface as V, Ordering as Vn, truthOver as Vt, WrittenSpec as W, PathExpr as Wn, ImplementedOperator as Wt, ContextSet as X, ReadsOf as Xn, TestedEvidence as Xt, ContextRead as Y, Reads as Yn, Operators as Yt, ContextValues as Z, TermOptions as Zn, stampRun as Zt, EntityTypeId as _, ContainsPredicate as _n, Side as _r, Judgement as _t, DerivedSpec as a, Pointing as an, missingName as ar, WriteLink as at, IdSchemaOf as b, ExistsPredicate as bn, invariantsOf as bt, Entity as c, AnyExpr as cn, NowExpr as cr, ContextValue as ct, EntityIdentity as d, CallExpr as dn, contextValue as dr, checkedSet as dt, testedByRunner as en, ValueOf as er, WriteComputations as et, EntityInput as f, CallOptions as fn, now as fr, AfterRow as ft, EntitySets as g, ComparePredicate as gn, LawDescription as gr, Invariant as gt, EntityRelation as h, CompareOperator as hn, Law as hr, DeclaredInvariant as ht, Derived as i, HeldTable as in, maxQueryNodes as ir, WriteKind as it, RelationMap as j, OneRelation$2 as jn, Row as jt, Relation as k, NotPredicate as kn, PredicateTruth as kt, EntityDerived as l, AnyQuery as ln, ViewerExpr as lr, EntitySet as lt, EntityRef as m, ChosenSort as mn, viewerIdOf as mr, Change as mt, Cardinality as n, HeldRow as nn, isPredicate as nr, WriteIncrement as nt, DerivedSpecs as o, idOfRef as on, noOperators as or, WriteSet as ot, EntityMember as p, ChosenOrder as pn, viewer as pr, BeforeRow as pt, Computation as q, Query as qn, OperatorContext as qt, Derivation as r, HeldRows as rn, maxPathLength as rr, WriteIncrements as rt, Entities as s, AndPredicate as sn, ExprContext as sr, Text as st, AnyEntity as t, Held$1 as tn, dependenciesOf as tr, WriteCondition as tt, EntityField as u, ArgumentOf as un, ViewerPathExpr as ur, SetOn as ut, Forbids as v, Dependencies as vn, check as vt, PageWindow as w, InPredicate as wn, readsBefore as wt, InputMember as x, Expr as xn, judge as xt, IdOf as y, EqPredicate as yn, invariant as yt, TargetKey as z, OrderTerm as zn, evaluateEach as zt };
2585
- //# sourceMappingURL=index-48JeXG0A.d.ts.map