foldkit-entity 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,5 @@
1
- import { Array, Option, Pipeable, Schema, SchemaAST } from "effect";
1
+ import { Array, Data, Option, Pipeable, Schema, SchemaAST } from "effect";
2
2
  import { Metadata } from "foldkit-metadata";
3
- //#region src/collation.d.ts
4
3
  type Collation =
5
4
  /** By code point: SQLite `BINARY`, Postgres `COLLATE "C"`. */
6
5
  {
@@ -23,9 +22,265 @@ declare const Collation: {
23
22
  of: (collation: Collation) => Metadata;
24
23
  /** The collation a member's metadata declares, if any. */
25
24
  declared: (metadata: Metadata) => Option.Option<Collation>;
25
+ /**
26
+ * Text as `asciiFold` compares it: ASCII letters lowercased, every other
27
+ * character as it is, which is what SQLite's `lower` does without ICU and so
28
+ * what compiled SQL folds to. `toLowerCase` would fold `É` to `é` here and not
29
+ * there. An operator implementing `asciiFold` folds with this.
30
+ */
31
+ foldAscii: (text: string) => string;
32
+ };
33
+ /** An operator a law names as a witness: the inverse, or the operator distributed over. */
34
+ type AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>;
35
+ /** Which argument a witness stands in. */
36
+ type Side = 'left' | 'right' | 'both';
37
+ /**
38
+ * A law, over its domain: by default every non-null value of the operator's
39
+ * input schemas; narrowed by `Law.within`.
40
+ */
41
+ type Law = Data.TaggedEnum<{
42
+ /** `op(op(a, b), c) = op(a, op(b, c))` */
43
+ Associative: {
44
+ readonly domain: Option.Option<Schema.Top>;
45
+ };
46
+ /** `op(a, b) = op(b, a)` */
47
+ Commutative: {
48
+ readonly domain: Option.Option<Schema.Top>;
49
+ };
50
+ /** `op(a, a) = a` */
51
+ Idempotent: {
52
+ readonly domain: Option.Option<Schema.Top>;
53
+ };
54
+ /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */
55
+ Identity: {
56
+ readonly domain: Option.Option<Schema.Top>;
57
+ readonly value: unknown;
58
+ readonly side: Side;
59
+ };
60
+ /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */
61
+ Absorbing: {
62
+ readonly domain: Option.Option<Schema.Top>;
63
+ readonly value: unknown;
64
+ readonly side: Side;
65
+ };
66
+ /** `op(a, other(a)) = identity` */
67
+ Inverse: {
68
+ readonly domain: Option.Option<Schema.Top>;
69
+ readonly other: AnyOperator;
70
+ readonly identity: unknown;
71
+ };
72
+ /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */
73
+ Distributes: {
74
+ readonly domain: Option.Option<Schema.Top>;
75
+ readonly over: AnyOperator;
76
+ };
77
+ /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */
78
+ Monotonic: {
79
+ readonly domain: Option.Option<Schema.Top>;
80
+ readonly direction: 'increasing' | 'decreasing';
81
+ readonly position: number;
82
+ };
83
+ /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */
84
+ PreservesCollation: {
85
+ readonly domain: Option.Option<Schema.Top>;
86
+ };
87
+ }>;
88
+ /** A law as JSON says it: what `describeTable` lists and evidence names. */
89
+ interface LawDescription {
90
+ readonly kind: string;
91
+ /** Its witnesses: values as stored, operators by name. */
92
+ readonly witnesses: Readonly<Record<string, unknown>>;
93
+ /** Its domain as a JSON Schema, or `null` for the operator's whole input. */
94
+ readonly domain: unknown;
95
+ }
96
+ declare const Law: {
97
+ associative: {
98
+ readonly _tag: "Associative";
99
+ readonly domain: Option.Option<Schema.Top>;
100
+ };
101
+ commutative: {
102
+ readonly _tag: "Commutative";
103
+ readonly domain: Option.Option<Schema.Top>;
104
+ };
105
+ idempotent: {
106
+ readonly _tag: "Idempotent";
107
+ readonly domain: Option.Option<Schema.Top>;
108
+ };
109
+ preservesCollation: {
110
+ readonly _tag: "PreservesCollation";
111
+ readonly domain: Option.Option<Schema.Top>;
112
+ };
113
+ /** `value` leaves the other argument as it is, from `side` (both by default). */
114
+ identity: (value: unknown, side?: Side) => Law;
115
+ /** `value` is the answer whatever the other argument, from `side` (both by default). */
116
+ absorbing: (value: unknown, side?: Side) => Law;
117
+ /** `other` undoes the operator: `op(a, other(a))` is `identity`. */
118
+ inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(other: Operator<In, Out>, identity: unknown) => Law;
119
+ /** The operator distributes over `over`, from the left. */
120
+ distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(over: Operator<In, Out>) => Law;
121
+ /** Moving the argument at `position` up moves the result up (or down, decreasing). */
122
+ monotonic: (direction: 'increasing' | 'decreasing', position: number) => Law;
123
+ /**
124
+ * The law over the values `domain` accepts only: a law that holds of the
125
+ * integers and not of every number, say, narrowed so it is tested where it
126
+ * is claimed.
127
+ */
128
+ within: (law: Law, domain: Schema.Top) => Law;
129
+ $match: {
130
+ <Cases extends { readonly [Tag in "Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]: (args: Extract<{
131
+ readonly _tag: "Absorbing";
132
+ readonly domain: Option.Option<Schema.Top>;
133
+ readonly value: unknown;
134
+ readonly side: Side;
135
+ } | {
136
+ readonly _tag: "Associative";
137
+ readonly domain: Option.Option<Schema.Top>;
138
+ } | {
139
+ readonly _tag: "Commutative";
140
+ readonly domain: Option.Option<Schema.Top>;
141
+ } | {
142
+ readonly _tag: "Distributes";
143
+ readonly domain: Option.Option<Schema.Top>;
144
+ readonly over: AnyOperator;
145
+ } | {
146
+ readonly _tag: "Idempotent";
147
+ readonly domain: Option.Option<Schema.Top>;
148
+ } | {
149
+ readonly _tag: "Identity";
150
+ readonly domain: Option.Option<Schema.Top>;
151
+ readonly value: unknown;
152
+ readonly side: Side;
153
+ } | {
154
+ readonly _tag: "Inverse";
155
+ readonly domain: Option.Option<Schema.Top>;
156
+ readonly other: AnyOperator;
157
+ readonly identity: unknown;
158
+ } | {
159
+ readonly _tag: "Monotonic";
160
+ readonly domain: Option.Option<Schema.Top>;
161
+ readonly direction: 'increasing' | 'decreasing';
162
+ readonly position: number;
163
+ } | {
164
+ readonly _tag: "PreservesCollation";
165
+ readonly domain: Option.Option<Schema.Top>;
166
+ }, {
167
+ readonly _tag: Tag;
168
+ }>) => any; }>(cases: Cases): (value: {
169
+ readonly _tag: "Absorbing";
170
+ readonly domain: Option.Option<Schema.Top>;
171
+ readonly value: unknown;
172
+ readonly side: Side;
173
+ } | {
174
+ readonly _tag: "Associative";
175
+ readonly domain: Option.Option<Schema.Top>;
176
+ } | {
177
+ readonly _tag: "Commutative";
178
+ readonly domain: Option.Option<Schema.Top>;
179
+ } | {
180
+ readonly _tag: "Distributes";
181
+ readonly domain: Option.Option<Schema.Top>;
182
+ readonly over: AnyOperator;
183
+ } | {
184
+ readonly _tag: "Idempotent";
185
+ readonly domain: Option.Option<Schema.Top>;
186
+ } | {
187
+ readonly _tag: "Identity";
188
+ readonly domain: Option.Option<Schema.Top>;
189
+ readonly value: unknown;
190
+ readonly side: Side;
191
+ } | {
192
+ readonly _tag: "Inverse";
193
+ readonly domain: Option.Option<Schema.Top>;
194
+ readonly other: AnyOperator;
195
+ readonly identity: unknown;
196
+ } | {
197
+ readonly _tag: "Monotonic";
198
+ readonly domain: Option.Option<Schema.Top>;
199
+ readonly direction: 'increasing' | 'decreasing';
200
+ readonly position: number;
201
+ } | {
202
+ readonly _tag: "PreservesCollation";
203
+ readonly domain: Option.Option<Schema.Top>;
204
+ }) => import("effect/Unify").Unify<ReturnType<Cases["Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]>>;
205
+ <Cases extends { readonly [Tag in "Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]: (args: Extract<{
206
+ readonly _tag: "Absorbing";
207
+ readonly domain: Option.Option<Schema.Top>;
208
+ readonly value: unknown;
209
+ readonly side: Side;
210
+ } | {
211
+ readonly _tag: "Associative";
212
+ readonly domain: Option.Option<Schema.Top>;
213
+ } | {
214
+ readonly _tag: "Commutative";
215
+ readonly domain: Option.Option<Schema.Top>;
216
+ } | {
217
+ readonly _tag: "Distributes";
218
+ readonly domain: Option.Option<Schema.Top>;
219
+ readonly over: AnyOperator;
220
+ } | {
221
+ readonly _tag: "Idempotent";
222
+ readonly domain: Option.Option<Schema.Top>;
223
+ } | {
224
+ readonly _tag: "Identity";
225
+ readonly domain: Option.Option<Schema.Top>;
226
+ readonly value: unknown;
227
+ readonly side: Side;
228
+ } | {
229
+ readonly _tag: "Inverse";
230
+ readonly domain: Option.Option<Schema.Top>;
231
+ readonly other: AnyOperator;
232
+ readonly identity: unknown;
233
+ } | {
234
+ readonly _tag: "Monotonic";
235
+ readonly domain: Option.Option<Schema.Top>;
236
+ readonly direction: 'increasing' | 'decreasing';
237
+ readonly position: number;
238
+ } | {
239
+ readonly _tag: "PreservesCollation";
240
+ readonly domain: Option.Option<Schema.Top>;
241
+ }, {
242
+ readonly _tag: Tag;
243
+ }>) => any; }>(value: {
244
+ readonly _tag: "Absorbing";
245
+ readonly domain: Option.Option<Schema.Top>;
246
+ readonly value: unknown;
247
+ readonly side: Side;
248
+ } | {
249
+ readonly _tag: "Associative";
250
+ readonly domain: Option.Option<Schema.Top>;
251
+ } | {
252
+ readonly _tag: "Commutative";
253
+ readonly domain: Option.Option<Schema.Top>;
254
+ } | {
255
+ readonly _tag: "Distributes";
256
+ readonly domain: Option.Option<Schema.Top>;
257
+ readonly over: AnyOperator;
258
+ } | {
259
+ readonly _tag: "Idempotent";
260
+ readonly domain: Option.Option<Schema.Top>;
261
+ } | {
262
+ readonly _tag: "Identity";
263
+ readonly domain: Option.Option<Schema.Top>;
264
+ readonly value: unknown;
265
+ readonly side: Side;
266
+ } | {
267
+ readonly _tag: "Inverse";
268
+ readonly domain: Option.Option<Schema.Top>;
269
+ readonly other: AnyOperator;
270
+ readonly identity: unknown;
271
+ } | {
272
+ readonly _tag: "Monotonic";
273
+ readonly domain: Option.Option<Schema.Top>;
274
+ readonly direction: 'increasing' | 'decreasing';
275
+ readonly position: number;
276
+ } | {
277
+ readonly _tag: "PreservesCollation";
278
+ readonly domain: Option.Option<Schema.Top>;
279
+ }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Absorbing" | "Associative" | "Commutative" | "Distributes" | "Idempotent" | "Identity" | "Inverse" | "Monotonic" | "PreservesCollation"]>>;
280
+ };
281
+ /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */
282
+ describe: (law: Law) => LawDescription;
26
283
  };
27
- //#endregion
28
- //#region src/expr.d.ts
29
284
  /** A constant the query was written with. */
30
285
  interface LiteralExpr<T> {
31
286
  readonly _tag: 'Literal';
@@ -58,8 +313,73 @@ interface InputExpr<T> {
58
313
  readonly key: string;
59
314
  readonly schema: Schema.Codec<T, unknown>;
60
315
  }
316
+ /**
317
+ * A field as the row a write would leave holds it: what an invariant reads
318
+ * (`after.status`, beside `before.status` over a change). An interpreter that judges stored
319
+ * rows alone refuses it, as the operation `next`.
320
+ */
321
+ interface NextExpr<T> {
322
+ readonly _tag: 'Next';
323
+ readonly field: FieldExpr<T>;
324
+ }
325
+ /**
326
+ * What an operator is, as the nodes that call it hold it: its identity, the
327
+ * stored form of what it takes and gives, and, for an operator defined by an
328
+ * expression, how to build that expression. It computes nothing itself.
329
+ * Identity is this object; `id` and `version` name it.
330
+ */
331
+ interface OperatorDescriptor {
332
+ readonly _tag: 'Operator';
333
+ readonly id: string;
334
+ readonly version: number;
335
+ readonly description: Option.Option<string>;
336
+ /** One schema per argument, read as the stored form. */
337
+ readonly input: ReadonlyArray<Schema.Top>;
338
+ readonly output: Schema.Top;
339
+ /**
340
+ * Builds the expression a call means, from its arguments: an operator defined
341
+ * by an expression. None for a primitive operator, which each interpreter
342
+ * implements (`Operators`).
343
+ */
344
+ readonly definedAs: Option.Option<(...args: ReadonlyArray<Operandish>) => Operandish>;
345
+ /**
346
+ * A primitive operator's null rule. `strict`: a null argument gives null, or
347
+ * unknown for a predicate, and the implementation never sees one. `handled`:
348
+ * the implementation is given nulls and answers for them.
349
+ */
350
+ readonly nulls: 'strict' | 'handled';
351
+ /**
352
+ * How a call compares text. `operands`: it carries the collation its collated
353
+ * text arguments share, so its text result compares under it. `required`: the
354
+ * same, refused where none is declared (it compares text itself, as
355
+ * `Text.startsWith` does). `none`: it carries none.
356
+ */
357
+ readonly collation: 'none' | 'operands' | 'required';
358
+ /** The equations every implementation keeps (`Law`), checked where declared, tested by `Conformance.laws`. */
359
+ readonly laws: ReadonlyArray<Law>;
360
+ }
361
+ /** What an interpreter runs, as far as a check of a body needs to know. */
362
+ interface OperatorTable {
363
+ /** Whether this table implements the operator. */
364
+ readonly has: (operator: OperatorDescriptor) => boolean;
365
+ }
366
+ /** A table implementing nothing: every primitive operator is unsupported by it. */
367
+ declare const noOperators: OperatorTable;
368
+ /**
369
+ * A call of an operator whose result is a scalar. `expansion` is the
370
+ * expression it means, built from its arguments when it was called: an
371
+ * interpreter runs that, and needs nothing of its own for the operator.
372
+ */
373
+ interface CallExpr<T> {
374
+ readonly _tag: 'Call';
375
+ readonly operator: OperatorDescriptor;
376
+ readonly args: ReadonlyArray<Operandish>;
377
+ readonly expansion: Option.Option<Expr<T>>;
378
+ /** How its text result compares, from its operator's `collation` rule. */
379
+ readonly collation: Option.Option<Collation>;
380
+ }
61
381
  /** A typed scalar: what a comparison compares. */
62
- type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>;
382
+ type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T> | NextExpr<T> | CallExpr<T>;
63
383
  /** Any scalar, for the places that hold operands without caring what they are. */
64
384
  type AnyExpr = Expr<unknown>;
65
385
  /**
@@ -70,7 +390,7 @@ type AnyExpr = Expr<unknown>;
70
390
  * then be confused, which a structural phantom would allow. A scalar-valued
71
391
  * operation, if one is ever needed, joins `Expr` instead.
72
392
  */
73
- type Predicate = EqPredicate | NullPredicate | ContainsPredicate | InPredicate | AndPredicate | OrPredicate | NotPredicate | ComparePredicate;
393
+ type Predicate = EqPredicate | NullPredicate | ContainsPredicate | InPredicate | AndPredicate | OrPredicate | NotPredicate | ComparePredicate | TestPredicate;
74
394
  /** Two values are the same. */
75
395
  interface EqPredicate {
76
396
  readonly _tag: 'Eq';
@@ -145,6 +465,19 @@ interface ComparePredicate {
145
465
  readonly right: AnyExpr;
146
466
  readonly collation: Option.Option<Collation>;
147
467
  }
468
+ /**
469
+ * A call of an operator whose result is a boolean, so it stands where any
470
+ * predicate does: in `and`, `or` and `not`, a guard, an invariant. `expansion`
471
+ * is the predicate it means, built when it was called.
472
+ */
473
+ interface TestPredicate {
474
+ readonly _tag: 'Test';
475
+ readonly operator: OperatorDescriptor;
476
+ readonly args: ReadonlyArray<Operandish>;
477
+ readonly expansion: Option.Option<Predicate>;
478
+ /** The collation it compares text under, from its operator's `collation` rule. */
479
+ readonly collation: Option.Option<Collation>;
480
+ }
148
481
  /**
149
482
  * Anything an operation can be given: a scalar, or a predicate where a boolean
150
483
  * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the
@@ -215,7 +548,7 @@ declare const isPredicate: (value: unknown) => value is Predicate;
215
548
  * runs, and a body needing one it does not is refused rather than answered
216
549
  * wrongly — see `Query.unsupported`.
217
550
  */
218
- type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains' | 'in' | 'and' | 'or' | 'not' | 'compare';
551
+ type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains' | 'in' | 'and' | 'or' | 'not' | 'compare' | 'next';
219
552
  /** One field an expression reads: its Entity's name and key, and the identity that owns it. */
220
553
  interface FieldDependency {
221
554
  /** The owning Entity's name, for display; two Entities may share one. */
@@ -228,10 +561,14 @@ interface FieldDependency {
228
561
  interface Dependencies {
229
562
  /** One entry per distinct field of each Entity identity. */
230
563
  readonly fields: ReadonlyArray<FieldDependency>;
564
+ /** Each field read as the row a write would leave holds it (`Next`), one entry each. */
565
+ readonly next: ReadonlyArray<FieldDependency>;
231
566
  /** One entry per distinct input key. */
232
567
  readonly inputs: ReadonlyArray<string>;
233
568
  /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */
234
569
  readonly operations: ReadonlyArray<Operation>;
570
+ /** Each operator it calls, once per descriptor, defined or not. */
571
+ readonly operators: ReadonlyArray<OperatorDescriptor>;
235
572
  }
236
573
  /**
237
574
  * What a query reads, with each field's role. A change to a `predicate` field
@@ -255,7 +592,106 @@ interface Connective<Node extends Predicate> {
255
592
  <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]>>;
256
593
  (...operands: Array.NonEmptyReadonlyArray<Predicate>): Predicate;
257
594
  }
595
+ /** A schema's stored form, which is what an operator takes and gives. */
596
+ type StoredOf$1<S extends Schema.Top> = Schema.Codec.Encoded<S>;
597
+ /**
598
+ * One argument an operator may be called with: a field or scalar stored as the
599
+ * input's stored type, a predicate where it takes a boolean, or a plain value.
600
+ */
601
+ 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>;
602
+ /** What `definedAs` is handed for one argument: the argument as a node. */
603
+ type ParameterOf<S extends Schema.Top> = Expr<StoredOf$1<S>> | (boolean extends StoredOf$1<S> ? Predicate : never);
604
+ /** A call's node: a predicate for a boolean result, a scalar for anything else. */
605
+ type CallOf<Out extends Schema.Top> = [StoredOf$1<Out>] extends [boolean] ? TestPredicate : CallExpr<StoredOf$1<Out>>;
606
+ /** What `definedAs` builds: a predicate for a boolean result, a scalar otherwise. */
607
+ type BodyOf<Out extends Schema.Top> = [StoredOf$1<Out>] extends [boolean] ? Predicate : Expr<StoredOf$1<Out>>;
608
+ /**
609
+ * An operator: called like a function, it builds a node that holds `descriptor`
610
+ * and its arguments. See `Expr.operator`.
611
+ */
612
+ interface Operator<In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top> {
613
+ <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]>; }>(...args: A): CallOf<Out> & Reads<ReadsOf<A[number]>>;
614
+ /**
615
+ * A call comparing text under the collation given, rather than its text
616
+ * arguments' declared one: for an operator whose `collation` is `operands`
617
+ * or `required`, as `Expr.lt(field, value, { collation })` is.
618
+ */
619
+ <const A extends { readonly [K in keyof In]: ArgumentOf<In[K]>; }>(...args: [...A, CallOptions]): CallOf<Out> & Reads<ReadsOf<A[number]>>;
620
+ readonly descriptor: OperatorDescriptor;
621
+ }
622
+ /** What a call may say past its arguments. */
623
+ interface CallOptions {
624
+ /** The collation it compares text under, in place of its arguments' declared one. */
625
+ readonly collation: Collation;
626
+ }
258
627
  declare const Expr: {
628
+ /**
629
+ * An operator, defined by what a call of it means: `definedAs` builds that
630
+ * expression from the call's arguments, once per call, and every interpreter
631
+ * runs it, so the operator needs no implementation anywhere. What it adds is
632
+ * a name: a query, a guard and an invariant that mean the same thing say so,
633
+ * and print it.
634
+ *
635
+ * ```ts
636
+ * const published = Expr.operator('cms.published', {
637
+ * input: [Schema.Unknown],
638
+ * output: Schema.Boolean,
639
+ * definedAs: publishedAt => Expr.isNotNull(publishedAt),
640
+ * })
641
+ * Query.where(published(Post.fields.publishedAt))
642
+ * ```
643
+ *
644
+ * Arguments are checked by their stored form: a field, scalar or plain value
645
+ * of the input's stored type, or a predicate where it takes a boolean. A
646
+ * boolean output makes a call a predicate. `definedAs` may read only what its
647
+ * arguments hold: a field or input it closes over instead is refused when
648
+ * called, since nothing asking what the call reads would see it. The id is
649
+ * namespaced (`cms.published`); `foldkit.` is reserved; `version` (default 1)
650
+ * changes when what it means does.
651
+ *
652
+ * **Without `definedAs` it is primitive**: each interpreter implements it
653
+ * (`Operators.implement` in memory), and one without an implementation
654
+ * refuses the body by the operator's id. `nulls` (default `strict`: a null
655
+ * argument gives null, the implementation never sees one) and `collation`
656
+ * (`operands`: a text result carries its text arguments' shared collation;
657
+ * `required`: it compares text itself and needs one) are a primitive
658
+ * operator's; a defined one means its body for both.
659
+ */
660
+ operator: <const In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(id: string, options: {
661
+ readonly input: In;
662
+ readonly output: Out;
663
+ readonly version?: number | undefined;
664
+ readonly description?: string | undefined;
665
+ /** Equations every implementation keeps (`Law.commutative`, `Law.identity('')`, …). */
666
+ readonly laws?: ReadonlyArray<Law> | undefined;
667
+ } & ({
668
+ readonly definedAs: (...args: { readonly [K in keyof In]: ParameterOf<In[K]>; }) => BodyOf<Out>;
669
+ readonly nulls?: undefined;
670
+ readonly collation?: undefined;
671
+ } | {
672
+ readonly definedAs?: undefined;
673
+ readonly nulls?: OperatorDescriptor['nulls'] | undefined;
674
+ readonly collation?: OperatorDescriptor['collation'] | undefined;
675
+ })) => Operator<In, Out>;
676
+ /**
677
+ * The predicate or scalar (an order term's, say) with every call of a
678
+ * defined operator replaced by what it means, deeply. An interpreter that
679
+ * compiles a body expands it first, and compiles exactly what was written
680
+ * out. A call with no definition stays, for the interpreter to run or refuse
681
+ * by name.
682
+ */
683
+ expanded: <N extends Predicate | AnyExpr>(node: N) => N extends Predicate ? Predicate : AnyExpr;
684
+ /**
685
+ * What these expressions need that an interpreter lacks, as `Query.unsupported`
686
+ * says it for a query: each kernel operation `supported` does not list, then
687
+ * each primitive operator `operators` does not implement, by name (`id`, or
688
+ * `id@version` past the first). For anything holding expressions that is not a
689
+ * query: a guard's rule, an invariant, a write's `when`.
690
+ */
691
+ unsupported: (nodes: ReadonlyArray<AnyExpr | Predicate | Ordering>, interpreter: {
692
+ readonly operations: ReadonlyArray<Operation>;
693
+ readonly operators: OperatorTable;
694
+ }) => ReadonlyArray<string>;
259
695
  /** A constant. Comparisons coerce a plain value, so this is rarely written. */
260
696
  literal: typeof literal;
261
697
  /**
@@ -263,6 +699,11 @@ declare const Expr: {
263
699
  * `Input` schema; written by hand only when constructing a body directly.
264
700
  */
265
701
  input: <T>(key: string, schema: Schema.Codec<T, unknown>) => InputExpr<T>;
702
+ /**
703
+ * A field as the row a write would leave holds it: what `Entity.invariant`'s
704
+ * builder hands out as `after`.
705
+ */
706
+ next: <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>) => NextExpr<Schema.Schema.Type<S>> & Reads<Name>;
266
707
  /** One field of one Entity, as a scalar. */
267
708
  field: <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>) => FieldExpr<Schema.Schema.Type<S>> & Reads<Name>;
268
709
  /**
@@ -386,6 +827,13 @@ declare const Expr: {
386
827
  whenGiven: <T, P extends Predicate>(input: InputExpr<T>, build: (given: InputExpr<NonNullable<T>>) => P) => Predicate & Reads<ReadsOf<P>>;
387
828
  /** An expression as readable text; see `showExpr` for what it is and is not. */
388
829
  show: (node: Operandish) => string;
830
+ /**
831
+ * The predicate with each field after a write (`Next`) that `values` names,
832
+ * by key, read as that value: how an invariant is judged where the
833
+ * write's new values are known. A field it does not name stays `Next`, for
834
+ * the interpreter to read as the row after holds it.
835
+ */
836
+ substituteNext: (predicate: Predicate, values: Readonly<Record<string, unknown>>) => Predicate;
389
837
  };
390
838
  /** One term of an ordering: a scalar and the direction to read it in. */
391
839
  interface OrderTerm {
@@ -424,7 +872,7 @@ type ChosenSort<By extends string> = {
424
872
  interface ChosenOrder {
425
873
  readonly _tag: 'Chosen';
426
874
  readonly sort: InputExpr<ChosenSort<string>>;
427
- readonly choices: Readonly<Record<string, FieldExpr<unknown>>>;
875
+ readonly choices: Readonly<Record<string, FieldExpr<unknown> | CallExpr<unknown>>>;
428
876
  }
429
877
  /** One entry of a body's ordering: fixed, or chosen by the input. */
430
878
  type Ordering = OrderTerm | ChosenOrder;
@@ -435,8 +883,8 @@ declare const Order: {
435
883
  desc: <E extends Operand<any>>(expr: E, options?: TermOptions) => OrderTerm & Reads<ReadsOf<E>>;
436
884
  /**
437
885
  * The order the input names, among `choices`: every name the sort can hold
438
- * maps to a field, so a name left out is a type error here, not a query that
439
- * silently orders by nothing. A `null` sort chooses none, and the terms after
886
+ * maps to a field or a call that orders, so a name left out is a type error
887
+ * here, not a query that silently orders by nothing. A `null` sort chooses none, and the terms after
440
888
  * it decide.
441
889
  *
442
890
  * ```ts
@@ -526,10 +974,13 @@ declare const Query: {
526
974
  /**
527
975
  * Whether a client can order this query's rows exactly as the server does,
528
976
  * for one input: every term over a number or a boolean (a row may lack it), or over text with a
529
- * portable collation (`binary`, `asciiFold`). A body that names no order
530
- * leaves it to the server, and is never placeable.
977
+ * portable collation (`binary`, `asciiFold`), or a call whose primitive
978
+ * operators the client's table (`operators`; none when not given) runs. A
979
+ * body that names no order leaves it to the server, and is never placeable.
531
980
  */
532
- placement: (self: AnyQuery, input: Readonly<Record<string, unknown>>) => Placement;
981
+ placement: (self: AnyQuery, input: Readonly<Record<string, unknown>>, options?: {
982
+ readonly operators?: OperatorTable | undefined;
983
+ }) => Placement;
533
984
  /**
534
985
  * What the whole query reads: the fields and inputs of every predicate and
535
986
  * every ordering term, and the operations it uses, with the fields also
@@ -538,8 +989,10 @@ declare const Query: {
538
989
  dependencies: (self: AnyQuery) => QueryDependencies;
539
990
  /**
540
991
  * The operations this query needs that `supported` does not list, in the
541
- * order the query uses them. Empty means an interpreter declaring
542
- * `supported` can answer it.
992
+ * order the query uses them, then each primitive operator `operators` does
993
+ * not implement, by name. Without `operators`, every primitive operator is
994
+ * named: a list of operations implements none. Empty means an interpreter
995
+ * declaring both can answer it.
543
996
  *
544
997
  * An interpreter declares what it runs and refuses the rest, rather than
545
998
  * ignoring an operation it does not implement — which would answer a
@@ -553,7 +1006,7 @@ declare const Query: {
553
1006
  * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
554
1007
  * ```
555
1008
  */
556
- unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>) => ReadonlyArray<Operation>;
1009
+ unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>, operators?: OperatorTable) => ReadonlyArray<string>;
557
1010
  /**
558
1011
  * The whole query as readable text, one clause per line:
559
1012
  *
@@ -570,56 +1023,231 @@ declare const Query: {
570
1023
  */
571
1024
  show: (self: AnyQuery) => string;
572
1025
  };
573
- //#endregion
574
- //#region src/readFilter.d.ts
575
- declare const ReadFilter: {
576
- /** Entity metadata: the rows the server lists depend on these members. */
577
- of: (members: ReadonlyArray<string>) => Metadata;
578
- /** The members an Entity's metadata names, every attachment's together. */
579
- members: (metadata: Metadata) => ReadonlyArray<string>;
1026
+ /** What an implementation is told besides its arguments. */
1027
+ interface OperatorContext {
1028
+ /** The collation the call compares text under, from its operator's `collation` rule. */
1029
+ readonly collation: Option.Option<Collation>;
1030
+ }
1031
+ /** One operator's in-memory implementation: a pure function of stored values. */
1032
+ interface MemoryImplementation {
1033
+ readonly operator: OperatorDescriptor;
1034
+ readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown;
1035
+ }
1036
+ /**
1037
+ * What is known of a law of an implementation, past its operator claiming it
1038
+ * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'
1039
+ * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded
1040
+ * and never checked here.
1041
+ */
1042
+ type Evidence = Data.TaggedEnum<{
1043
+ Tested: {
1044
+ readonly operator: string;
1045
+ readonly law: LawDescription;
1046
+ readonly implementation: string;
1047
+ readonly cases: number;
1048
+ readonly seed: number;
1049
+ };
1050
+ Proven: {
1051
+ readonly operator: string;
1052
+ readonly law: LawDescription;
1053
+ readonly reference: string;
1054
+ readonly assumptions: ReadonlyArray<string>;
1055
+ };
1056
+ }>;
1057
+ declare const Evidence: {
1058
+ readonly $is: <Tag extends "Proven" | "Tested">(tag: Tag) => (u: unknown) => u is Extract<{
1059
+ readonly _tag: "Proven";
1060
+ readonly operator: string;
1061
+ readonly law: LawDescription;
1062
+ readonly reference: string;
1063
+ readonly assumptions: ReadonlyArray<string>;
1064
+ }, {
1065
+ readonly _tag: Tag;
1066
+ }> | Extract<{
1067
+ readonly _tag: "Tested";
1068
+ readonly operator: string;
1069
+ readonly law: LawDescription;
1070
+ readonly implementation: string;
1071
+ readonly cases: number;
1072
+ readonly seed: number;
1073
+ }, {
1074
+ readonly _tag: Tag;
1075
+ }>;
1076
+ readonly $match: {
1077
+ <Cases extends { readonly [Tag in "Proven" | "Tested"]: (args: Extract<{
1078
+ readonly _tag: "Proven";
1079
+ readonly operator: string;
1080
+ readonly law: LawDescription;
1081
+ readonly reference: string;
1082
+ readonly assumptions: ReadonlyArray<string>;
1083
+ } | {
1084
+ readonly _tag: "Tested";
1085
+ readonly operator: string;
1086
+ readonly law: LawDescription;
1087
+ readonly implementation: string;
1088
+ readonly cases: number;
1089
+ readonly seed: number;
1090
+ }, {
1091
+ readonly _tag: Tag;
1092
+ }>) => any; }>(cases: Cases): (value: {
1093
+ readonly _tag: "Proven";
1094
+ readonly operator: string;
1095
+ readonly law: LawDescription;
1096
+ readonly reference: string;
1097
+ readonly assumptions: ReadonlyArray<string>;
1098
+ } | {
1099
+ readonly _tag: "Tested";
1100
+ readonly operator: string;
1101
+ readonly law: LawDescription;
1102
+ readonly implementation: string;
1103
+ readonly cases: number;
1104
+ readonly seed: number;
1105
+ }) => import("effect/Unify").Unify<ReturnType<Cases["Proven" | "Tested"]>>;
1106
+ <Cases extends { readonly [Tag in "Proven" | "Tested"]: (args: Extract<{
1107
+ readonly _tag: "Proven";
1108
+ readonly operator: string;
1109
+ readonly law: LawDescription;
1110
+ readonly reference: string;
1111
+ readonly assumptions: ReadonlyArray<string>;
1112
+ } | {
1113
+ readonly _tag: "Tested";
1114
+ readonly operator: string;
1115
+ readonly law: LawDescription;
1116
+ readonly implementation: string;
1117
+ readonly cases: number;
1118
+ readonly seed: number;
1119
+ }, {
1120
+ readonly _tag: Tag;
1121
+ }>) => any; }>(value: {
1122
+ readonly _tag: "Proven";
1123
+ readonly operator: string;
1124
+ readonly law: LawDescription;
1125
+ readonly reference: string;
1126
+ readonly assumptions: ReadonlyArray<string>;
1127
+ } | {
1128
+ readonly _tag: "Tested";
1129
+ readonly operator: string;
1130
+ readonly law: LawDescription;
1131
+ readonly implementation: string;
1132
+ readonly cases: number;
1133
+ readonly seed: number;
1134
+ }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Proven" | "Tested"]>>;
1135
+ };
1136
+ readonly Proven: Data.TaggedEnum.ConstructorFrom<{
1137
+ readonly _tag: "Proven";
1138
+ readonly operator: string;
1139
+ readonly law: LawDescription;
1140
+ readonly reference: string;
1141
+ readonly assumptions: ReadonlyArray<string>;
1142
+ }, "_tag">;
1143
+ readonly Tested: Data.TaggedEnum.ConstructorFrom<{
1144
+ readonly _tag: "Tested";
1145
+ readonly operator: string;
1146
+ readonly law: LawDescription;
1147
+ readonly implementation: string;
1148
+ readonly cases: number;
1149
+ readonly seed: number;
1150
+ }, "_tag">;
580
1151
  };
581
- //#endregion
582
- //#region src/words.d.ts
583
- /** What a schema says of itself to a person: its `title` and `description`. */
584
- interface SchemaWords {
585
- readonly title: Option.Option<string>;
586
- readonly description: Option.Option<string>;
1152
+ /** A record of a law passing `Conformance.laws`' cases. */
1153
+ type TestedEvidence = Extract<Evidence, {
1154
+ readonly _tag: 'Tested';
1155
+ }>;
1156
+ /** One operator a table implements, as `Operators.describeTable` lists it. */
1157
+ interface ImplementedOperator {
1158
+ /** By id, and `@version` past the first. */
1159
+ readonly operator: string;
1160
+ readonly laws: ReadonlyArray<LawDescription>;
1161
+ readonly evidence: ReadonlyArray<Evidence>;
587
1162
  }
588
- declare const Words: {
1163
+ /** The in-memory interpreter's implementations, by operator. */
1164
+ interface MemoryOperators extends OperatorTable {
1165
+ readonly _tag: 'MemoryOperators';
1166
+ readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>;
1167
+ /** Whether each answer is checked against its operator's output schema: for tests. */
1168
+ readonly checked: boolean;
1169
+ readonly implementations: ReadonlyArray<MemoryImplementation>;
1170
+ /** What is known of its implementations' laws: `Operators.withEvidence`. */
1171
+ readonly evidence: ReadonlyArray<Evidence>;
1172
+ }
1173
+ type StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>;
1174
+ declare const Operators: {
589
1175
  /**
590
- * A schema's words, as a label and its help text. Under Effect 4 a checked
591
- * schema resolves to its last check's annotations, which say what the check
592
- * expects and carry no `title`, so a title given before the check is read from
593
- * the schema's own annotations. Read words through this, never through
594
- * `Schema.resolveAnnotations` directly.
1176
+ * An implementation of a strict operator: a pure function of its arguments'
1177
+ * stored values, never given a null (the kernel answers null, or unknown, for
1178
+ * one first), and told the call's collation last.
1179
+ *
1180
+ * ```ts
1181
+ * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))
1182
+ * ```
595
1183
  */
596
- of: (schema: Schema.Top) => SchemaWords;
597
- };
598
- //#endregion
599
- //#region src/shape.d.ts
600
- declare const isNullish: (ast: SchemaAST.AST) => boolean;
601
- declare const isText: (ast: SchemaAST.AST) => boolean;
602
- /** What a schema's AST holds, read through Effect's own guards. */
603
- declare const SchemaShape: {
604
- /** True for the `null` and `undefined` members that make a schema optional. */
605
- isNullish: typeof isNullish;
1184
+ 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;
606
1185
  /**
607
- * The members of a schema with `null` and `undefined` set aside, so optional
608
- * text is still text; a schema that is not a union is its one member.
1186
+ * An implementation of an operator declared `nulls: 'handled'`: given nulls
1187
+ * as they are, it answers for them; a predicate answers `null` for unknown.
609
1188
  */
610
- present: (ast: SchemaAST.AST) => ReadonlyArray<SchemaAST.AST>;
611
- /** True when every value the schema admits is a string. */
612
- isText: typeof isText;
1189
+ 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;
1190
+ /** A table of implementations. One operator implemented twice, or two under one name, is refused. */
1191
+ memory: (...implementations: ReadonlyArray<MemoryImplementation>) => MemoryOperators;
1192
+ /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */
1193
+ merge: (left: MemoryOperators, right: MemoryOperators) => MemoryOperators;
1194
+ /**
1195
+ * The table with these implementations in place of its own for the same
1196
+ * operators. Evidence of a replaced implementation goes with it: it was
1197
+ * that implementation's.
1198
+ */
1199
+ override: (base: MemoryOperators, ...implementations: ReadonlyArray<MemoryImplementation>) => MemoryOperators;
1200
+ /**
1201
+ * The table with what is known of its implementations' laws recorded: each
1202
+ * record of an operator it implements and a law that operator declares.
1203
+ * `Conformance.laws` gives `Tested` records; `Evidence.Proven` says a proof
1204
+ * elsewhere covers one.
1205
+ */
1206
+ withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>) => MemoryOperators;
1207
+ /**
1208
+ * Each operator the table implements, by name, with the laws it declares and
1209
+ * the evidence the table records of them: what a server can publish of how
1210
+ * it runs a body. JSON as it is.
1211
+ */
1212
+ describeTable: (base: MemoryOperators) => ReadonlyArray<ImplementedOperator>;
1213
+ /**
1214
+ * The table, checking every answer against its operator's output schema, so
1215
+ * an implementation that answers the wrong kind fails where it answered. For
1216
+ * tests: it costs a decode per call.
1217
+ */
1218
+ checked: (base: MemoryOperators) => MemoryOperators;
1219
+ /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
1220
+ kernel: MemoryOperators;
613
1221
  };
614
- //#endregion
615
- //#region src/evaluate.d.ts
616
1222
  /** A row as this interpreter reads one: values by field key. */
617
1223
  type Row = Readonly<Record<string, unknown>>;
618
1224
  declare class QueryEvaluateError extends Error {
619
1225
  constructor(message: string);
620
1226
  }
1227
+ /**
1228
+ * A call of a primitive operator the table does not implement. Its own class,
1229
+ * because a form judging an invariant reads it as a judgement it cannot make
1230
+ * (`Undecided`), not as a failure.
1231
+ */
1232
+ declare class OperatorMissingError extends QueryEvaluateError {
1233
+ readonly operator: OperatorDescriptor;
1234
+ /** The operator by its id, and its version past the first. */
1235
+ readonly named: string;
1236
+ constructor(operator: OperatorDescriptor);
1237
+ }
621
1238
  /** SQL's unknown: neither true nor false, and a row is kept only on true. */
622
1239
  type Truth = boolean | 'unknown';
1240
+ /**
1241
+ * What an operand comes to over no row: a call of literals and inputs, run by
1242
+ * `operators` (the kernel's when not given), a predicate as its truth with
1243
+ * unknown as null. How a conformance check asks an implementation one
1244
+ * question; refuses what `evaluate` refuses (an operator the table lacks,
1245
+ * text holding NUL).
1246
+ */
1247
+ declare const valueOfOperand: (node: Operandish, options?: {
1248
+ readonly input?: Row | undefined;
1249
+ readonly operators?: MemoryOperators | undefined;
1250
+ }) => unknown;
623
1251
  /** What a predicate comes to: SQL's three values, of which a row is kept only on `true`. */
624
1252
  type PredicateTruth = Truth;
625
1253
  /**
@@ -628,15 +1256,22 @@ type PredicateTruth = Truth;
628
1256
  * before it builds anything: `isNull($status)` is known before any row is.
629
1257
  * Refuses what `evaluate` refuses (text holding a NUL).
630
1258
  */
631
- declare const decided: (node: Predicate, input: Row) => Option.Option<PredicateTruth>;
1259
+ declare const decided: (node: Predicate, input: Row, operators?: MemoryOperators) => Option.Option<PredicateTruth>;
1260
+ /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
1261
+ declare const truthOver: (node: Predicate, row: Row, input?: Row, next?: Row, operators?: MemoryOperators) => PredicateTruth;
632
1262
  /**
633
1263
  * Where `left` sorts against `right` under these terms (`Query.orderFor`'s),
634
- * as `evaluate` sorts: negative when it comes first. Refuses what `evaluate`
635
- * refuses, for these two rows: a term not over a field, a locale collation,
636
- * or keys of different kinds. For a client placing one row among others it
1264
+ * as `evaluate` sorts: negative when it comes first. A call among them runs
1265
+ * over each row with `input` and `operators` (the kernel's when not given).
1266
+ * Refuses what `evaluate` refuses, for these two rows: a term over neither a
1267
+ * field nor a call, a locale collation, keys of different kinds, or an
1268
+ * operator the table lacks. For a client placing one row among others it
637
1269
  * holds.
638
1270
  */
639
- declare const compareRows: (terms: ReadonlyArray<OrderTerm>, left: Row, right: Row, query: string) => number;
1271
+ declare const compareRows: (terms: ReadonlyArray<OrderTerm>, left: Row, right: Row, query: string, options?: {
1272
+ readonly input?: Row | undefined;
1273
+ readonly operators?: MemoryOperators | undefined;
1274
+ }) => number;
640
1275
  /**
641
1276
  * The operations this interpreter runs. It is the reference, so this is the
642
1277
  * whole kernel — but it is declared rather than assumed, because an
@@ -649,7 +1284,7 @@ declare const supported: ReadonlyArray<Operation>;
649
1284
  * than skipping it and answering a different question. Called by `evaluate`;
650
1285
  * call it directly to check a body once instead of on every run.
651
1286
  */
652
- declare const assertSupported: (body: AnyQuery) => void;
1287
+ declare const assertSupported: (body: AnyQuery, operators?: MemoryOperators) => void;
653
1288
  /**
654
1289
  * The rows the body matches, in the order it asks for. Pure: it reads the rows
655
1290
  * it is given and nothing else.
@@ -658,9 +1293,156 @@ declare const assertSupported: (body: AnyQuery) => void;
658
1293
  * placeholders were built with — the same record the query would be called
659
1294
  * with anywhere else.
660
1295
  */
661
- declare const evaluate: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>) => ReadonlyArray<Row>;
662
- //#endregion
663
- //#region src/write.d.ts
1296
+ declare const evaluate: (body: AnyQuery, input: Row, rows: ReadonlyArray<Row>, options?: {
1297
+ readonly operators?: MemoryOperators | undefined;
1298
+ }) => ReadonlyArray<Row>;
1299
+ /** One invariant of an Entity, as its interpreters read it. */
1300
+ interface Invariant {
1301
+ /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */
1302
+ readonly id: string;
1303
+ readonly predicate: Predicate;
1304
+ /** What someone the rules let write is told when a write would break it. */
1305
+ readonly message: string;
1306
+ /** The fields a form shows the failure beside. */
1307
+ readonly path: ReadonlyArray<string>;
1308
+ /** The fields it reads of the row before a write; none for a state invariant. */
1309
+ readonly before: ReadonlyArray<string>;
1310
+ /** The fields it reads of the row after. */
1311
+ readonly after: ReadonlyArray<string>;
1312
+ }
1313
+ /** Each field as the row before a write holds it: what an invariant reads as `before`. */
1314
+ type BeforeRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: FieldExpr<Schema.Schema.Type<E['fields'][K]['schema']>> & Reads<E['name']>; };
1315
+ /** Each field as the row after a write holds it: what an invariant reads as `after`. */
1316
+ type AfterRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: NextExpr<Schema.Schema.Type<E['fields'][K]['schema']>> & Reads<E['name']>; };
1317
+ /** A row, or a change from one row to another, as an invariant is judged over it. */
1318
+ interface Change {
1319
+ readonly after: Row;
1320
+ /** The row before an update; none for a create, which judges no transition invariant. */
1321
+ readonly before?: Row;
1322
+ }
1323
+ /** What a row, or a change, comes to under an Entity's invariants. */
1324
+ type Judgement = {
1325
+ readonly _tag: 'Valid';
1326
+ } | {
1327
+ readonly _tag: 'Invalid';
1328
+ readonly failures: ReadonlyArray<Invariant>;
1329
+ } |
1330
+ /**
1331
+ * Validity is not known: some invariant reads a field the row does not have
1332
+ * (`fields`), or calls an operator the table does not run (`operators`, by name).
1333
+ */
1334
+ {
1335
+ readonly _tag: 'Undecided';
1336
+ readonly fields: ReadonlyArray<string>;
1337
+ readonly operators: ReadonlyArray<string>;
1338
+ };
1339
+ /** Whether an invariant reads the row before, and so is judged only where there is one. */
1340
+ declare const readsBefore: (held: Invariant) => boolean;
1341
+ /**
1342
+ * An invariant as declared: the step that attaches it to its Entity, carrying
1343
+ * its id, so a refusal is matched against the declaration rather than a
1344
+ * string spelled again (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`).
1345
+ */
1346
+ interface DeclaredInvariant<E extends AnyEntity> {
1347
+ (entity: E): E;
1348
+ readonly id: string;
1349
+ }
1350
+ declare const invariant: <E extends AnyEntity>(id: string, build: (rows: {
1351
+ readonly before: BeforeRow<E>;
1352
+ readonly after: AfterRow<E>;
1353
+ }) => Predicate & Reads<E['name']>, options: {
1354
+ readonly message: string;
1355
+ readonly path?: ReadonlyArray<keyof E['fields'] & string>;
1356
+ }) => DeclaredInvariant<E>;
1357
+ declare const invariantsOf: (entity: AnyEntity) => ReadonlyArray<Invariant>;
1358
+ /** `judge` with the invariants given, as a binding that keeps them holds them. */
1359
+ declare const judgeAgainst: (invariants: ReadonlyArray<Invariant>, change: Change, operators?: MemoryOperators) => Judgement;
1360
+ /**
1361
+ * A row, or a change, under every invariant (each row as the store holds it,
1362
+ * encoded): valid only when each is true. SQL's unknown, from a null, fails
1363
+ * one, as a `WHERE` drops the row; a field a row does not have leaves it
1364
+ * undecided, never valid. Without `before` (a create), transition invariants
1365
+ * are not judged.
1366
+ */
1367
+ declare const judge: (entity: AnyEntity, change: Change, operators?: MemoryOperators) => Judgement;
1368
+ /**
1369
+ * The row an input's value describes, judged under its Entity's state
1370
+ * invariants: each key mapped to a field, encoded as the store holds it. An
1371
+ * invariant over a field the input does not set (an `Option` holding nothing, a
1372
+ * key left out) is undecided, so a partial input is never called valid on its
1373
+ * account. It has no row before, so it judges no transition.
1374
+ */
1375
+ declare const judgeInput: (input: EntityInput<AnyEntity, any, any>, value: Readonly<Record<string, unknown>>, operators?: MemoryOperators) => Judgement;
1376
+ /**
1377
+ * The Entity's state invariants as an Effect Schema check over its row type:
1378
+ * each failure at its path, with its message. The value is encoded first,
1379
+ * field by field, so it is judged as the store would hold it.
1380
+ */
1381
+ declare const check: <E extends AnyEntity>(entity: E, options?: {
1382
+ readonly operators?: MemoryOperators | undefined;
1383
+ }) => SchemaAST.Filter<Schema.Schema.Type<E['schema']>>;
1384
+ declare const Text: {
1385
+ /**
1386
+ * Whether the first text begins with the second, under the first's collation.
1387
+ *
1388
+ * | Case | Answer |
1389
+ * | --- | --- |
1390
+ * | either is null | unknown |
1391
+ * | the prefix is `''` | true |
1392
+ * | otherwise | whether it begins so, compared under the collation |
1393
+ *
1394
+ * The collation is the text's: a field's declared one, or a call's. `binary`
1395
+ * compares exactly; `asciiFold` folds ASCII letters on both sides. Text with
1396
+ * none, or with a backend's locale, is refused where the call is written.
1397
+ * Prefixes are by character, so non-ASCII and astral text begin as they read.
1398
+ *
1399
+ * ```ts
1400
+ * Query.where(Text.startsWith(Product.fields.upc, input.search))
1401
+ * ```
1402
+ */
1403
+ startsWith: Operator<readonly [Schema.NullOr<Schema.String>, Schema.NullOr<Schema.String>], Schema.Boolean>;
1404
+ };
1405
+ declare const ReadFilter: {
1406
+ /** Entity metadata: the rows the server lists depend on these members. */
1407
+ of: (members: ReadonlyArray<string>) => Metadata;
1408
+ /** The members an Entity's metadata names, every attachment's together. */
1409
+ members: (metadata: Metadata) => ReadonlyArray<string>;
1410
+ };
1411
+ /** What a schema says of itself to a person: its `title` and `description`. */
1412
+ interface SchemaWords {
1413
+ readonly title: Option.Option<string>;
1414
+ readonly description: Option.Option<string>;
1415
+ }
1416
+ declare const Words: {
1417
+ /**
1418
+ * A schema's words, as a label and its help text. Under Effect 4 a checked
1419
+ * schema resolves to its last check's annotations, which say what the check
1420
+ * expects and carry no `title`, so a title given before the check is read from
1421
+ * the schema's own annotations. Read words through this, never through
1422
+ * `Schema.resolveAnnotations` directly.
1423
+ */
1424
+ of: (schema: Schema.Top) => SchemaWords;
1425
+ };
1426
+ declare const isNullish: (ast: SchemaAST.AST) => boolean;
1427
+ declare const isText: (ast: SchemaAST.AST) => boolean;
1428
+ /** What a schema's AST holds, read through Effect's own guards. */
1429
+ declare const SchemaShape: {
1430
+ /** True for the `null` and `undefined` members that make a schema optional. */
1431
+ isNullish: typeof isNullish;
1432
+ /**
1433
+ * The members of a schema with `null` and `undefined` set aside, so optional
1434
+ * text is still text; a schema that is not a union is its one member.
1435
+ */
1436
+ present: (ast: SchemaAST.AST) => ReadonlyArray<SchemaAST.AST>;
1437
+ /** True when every value the schema admits is a string. */
1438
+ isText: typeof isText;
1439
+ /**
1440
+ * True when the AST is checked to hold integers (`Schema.isInt`, alone or in
1441
+ * a group such as `isInt32`). Read it from a schema's encoded side to ask
1442
+ * what the store holds.
1443
+ */
1444
+ holdsIntegers: (ast: SchemaAST.AST) => boolean;
1445
+ };
664
1446
  type AnyField = EntityField<string, string, Schema.Constraint>;
665
1447
  type OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>;
666
1448
  /** One input key the write sets, and the field it sets. */
@@ -668,6 +1450,14 @@ interface WriteSet {
668
1450
  readonly key: string;
669
1451
  readonly field: AnyField;
670
1452
  }
1453
+ /**
1454
+ * One input key holding an amount, and the field it moves. `integer` is whether
1455
+ * the amount's schema holds it to an integer (`Schema.isInt`): a writer over an
1456
+ * integer column refuses an increment without it, which the Entity cannot see.
1457
+ */
1458
+ interface WriteIncrement extends WriteSet {
1459
+ readonly integer: boolean;
1460
+ }
671
1461
  /** One input key the write points at another row with: a `one` relation, by the target's id. */
672
1462
  interface WriteLink {
673
1463
  readonly key: string;
@@ -691,12 +1481,65 @@ interface Write<E extends AnyEntity, Fields extends Schema.Struct.Fields> {
691
1481
  readonly expect: (WriteSet & {
692
1482
  readonly key: keyof Fields & string;
693
1483
  }) | undefined;
1484
+ /**
1485
+ * What the row must hold for the write to land, over the Entity, read
1486
+ * before the write and checked where it commits: an interpreter writes only
1487
+ * a row it holds of, and refuses the rest as unmet.
1488
+ */
1489
+ readonly when: Option.Option<AnyQuery>;
694
1490
  /** The keys it sets, in the input's order. */
695
1491
  readonly sets: ReadonlyArray<WriteSet>;
1492
+ /**
1493
+ * The fields it moves by an amount the input holds (`stock + quantity`),
1494
+ * computed where the write commits: the input key, and the field it moves.
1495
+ */
1496
+ readonly increments: ReadonlyArray<WriteIncrement>;
696
1497
  /** The `one` relations it points elsewhere, in the input's order. */
697
1498
  readonly links: ReadonlyArray<WriteLink>;
698
1499
  }
699
1500
  type AnyWrite = Write<AnyEntity, any>;
1501
+ /** A write declared with a precondition, so it may be refused as unmet. */
1502
+ type ConditionedWrite<E extends AnyEntity, Fields extends Schema.Struct.Fields> = Write<E, Fields> & {
1503
+ readonly when: Option.Some<AnyQuery>;
1504
+ };
1505
+ interface RowOptions<Fields extends Schema.Struct.Fields> {
1506
+ readonly id: keyof Fields & string;
1507
+ readonly expect?: keyof Fields & string;
1508
+ }
1509
+ /** The keys of `Fields` whose values are numbers. */
1510
+ 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];
1511
+ /** An update's increments: a number field of the Entity, by the input key holding the amount. */
1512
+ 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>; };
1513
+ /** An update's options: a row's, and what it moves by an amount. */
1514
+ type UpdateOptions<E extends AnyEntity, Fields extends Schema.Struct.Fields> = RowOptions<Fields> & {
1515
+ readonly increment?: WriteIncrements<E, Fields>;
1516
+ };
1517
+ /** `update`: conditioned when given `when`, which the overloads tell apart. */
1518
+ interface UpdateWrite {
1519
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
1520
+ readonly when: WriteCondition<E, Fields>;
1521
+ }): ConditionedWrite<E, Fields>;
1522
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
1523
+ readonly when?: undefined;
1524
+ }): Write<E, Fields>;
1525
+ }
1526
+ /** `delete`: conditioned when given `when`, as an update is. */
1527
+ interface DeleteWrite {
1528
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
1529
+ readonly when: WriteCondition<E, Fields>;
1530
+ }): ConditionedWrite<E, Fields>;
1531
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
1532
+ readonly when?: undefined;
1533
+ }): Write<E, Fields>;
1534
+ }
1535
+ /**
1536
+ * A write's precondition: a predicate over its Entity's row, given one
1537
+ * placeholder per input key, as a `Query.define` body is. It is built once,
1538
+ * so `input` stands for what the write will be given.
1539
+ */
1540
+ type WriteCondition<E extends AnyEntity, Fields extends Schema.Struct.Fields> = (context: {
1541
+ readonly input: { readonly [K in keyof Fields & string]: InputExpr<Schema.Schema.Type<Fields[K]>>; };
1542
+ }) => Predicate & Reads<E['name']>;
700
1543
  /** One row's new values, in the store's wire shape: what a client patches and a server writes. */
701
1544
  interface BoundWrite {
702
1545
  readonly entity: string;
@@ -708,6 +1551,8 @@ interface BoundWrite {
708
1551
  * key on the wire, a foreign key in a table) is each interpreter's.
709
1552
  */
710
1553
  readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
1554
+ /** Each field it moves, by the amount, encoded: added by the server, and predicted over what a client holds. */
1555
+ readonly increments: Readonly<Record<string, number>>;
711
1556
  }
712
1557
  declare const Write: {
713
1558
  /**
@@ -723,11 +1568,12 @@ declare const Write: {
723
1568
  * id it holds. Refused where it is written: an `id` that is not the Entity's
724
1569
  * `id` field, a `many` relation or a nested key (not written by an update
725
1570
  * yet), or nothing to set.
1571
+ *
1572
+ * `when` is what the row must hold for the update to land, checked where it
1573
+ * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
1574
+ * does not hold of is refused as unmet.
726
1575
  */
727
- update: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: {
728
- readonly id: keyof Fields & string;
729
- readonly expect?: keyof Fields & string;
730
- }) => Write<E, Fields>;
1576
+ update: UpdateWrite;
731
1577
  /**
732
1578
  * Inserts the row whose id is the input's `id` key, an id the client chose,
733
1579
  * with every field and `one` relation the input maps a key to. An insert
@@ -741,12 +1587,9 @@ declare const Write: {
741
1587
  * Deletes the row whose id is the input's `id` key, only while it is still at
742
1588
  * the revision `expect` names, when it names one. It sets nothing, so a key
743
1589
  * mapped to a member is refused where it is written. A row already gone (a
744
- * retry) is gone.
1590
+ * retry) is gone. `when`, as an update's, is what the row must hold.
745
1591
  */
746
- delete: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: {
747
- readonly id: keyof Fields & string;
748
- readonly expect?: keyof Fields & string;
749
- }) => Write<E, Fields>;
1592
+ delete: DeleteWrite;
750
1593
  /**
751
1594
  * The revision this input says the row was read at, encoded, with its field:
752
1595
  * what an interpreter writes only a row still at. None for a write that
@@ -758,6 +1601,12 @@ declare const Write: {
758
1601
  }>;
759
1602
  /** The members any invocation may write: what a query reading none of them cannot be changed by. */
760
1603
  writes: (write: AnyWrite) => ReadonlyArray<AnyField | OneRelation>;
1604
+ /**
1605
+ * The fields a write reads from the row it writes: those its `when` reads,
1606
+ * each it increments, and the revision it expects. What an interpreter
1607
+ * must read, and what a startup check judges it could disclose.
1608
+ */
1609
+ reads: (write: AnyWrite) => ReadonlyArray<AnyField>;
761
1610
  /**
762
1611
  * The row this input writes and its new values, encoded as the store holds
763
1612
  * them: the patch a client shows before the server answers. `keys`, when
@@ -766,8 +1615,6 @@ declare const Write: {
766
1615
  */
767
1616
  bind: <Fields extends Schema.Struct.Fields>(write: Write<AnyEntity, Fields>, value: Schema.Struct.Type<Fields>, keys?: ReadonlyArray<string>) => BoundWrite;
768
1617
  };
769
- //#endregion
770
- //#region src/index.d.ts
771
1618
  declare const EntityTypeId: unique symbol;
772
1619
  type EntityTypeId = typeof EntityTypeId;
773
1620
  /**
@@ -1027,6 +1874,36 @@ declare const Entity: {
1027
1874
  derived: <const New extends DerivedSpecs>(specs: New) => <E extends AnyEntity>(entity: E & Free<E, New>) => WithDerived<E, New>;
1028
1875
  /** Attaches an interpreter's metadata to the Entity itself. */
1029
1876
  annotate: (metadata: Metadata) => <E extends AnyEntity>(entity: E) => E;
1877
+ /**
1878
+ * Declares what every stored row, or every change of one, must hold:
1879
+ * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
1880
+ * Expr.lte(after.reserved, after.quantity), { message })` over the row a
1881
+ * write leaves, or with `before` too over the change an update makes.
1882
+ * Refused where it is declared: an id declared twice, a predicate over another
1883
+ * Entity, one reading an input or nothing of `after` (that is a `when`), a path
1884
+ * naming no field.
1885
+ */
1886
+ invariant: typeof invariant;
1887
+ /** The Entity's invariants, in the order they were declared. */
1888
+ invariants: typeof invariantsOf;
1889
+ /**
1890
+ * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
1891
+ * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
1892
+ * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
1893
+ * one reads that a row lacks.
1894
+ */
1895
+ judge: typeof judge;
1896
+ /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
1897
+ readsBefore: typeof readsBefore;
1898
+ /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
1899
+ judgeAgainst: typeof judgeAgainst;
1900
+ /**
1901
+ * The row an `Entity.input`'s value describes, judged: what a form can say
1902
+ * before the server does. Undecided for an invariant over a field it leaves unset.
1903
+ */
1904
+ judgeInput: typeof judgeInput;
1905
+ /** The state invariants as a Schema check over the row type, each failure at its path. */
1906
+ check: typeof check;
1030
1907
  /** Attaches an interpreter's metadata to members, by key. */
1031
1908
  annotateMembers: <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata; }) => (entity: E) => E;
1032
1909
  /**
@@ -1079,6 +1956,5 @@ declare const Relation: {
1079
1956
  declare const Derived: {
1080
1957
  make: <S extends Schema.Constraint>(schema: S) => DerivedSpec<S>;
1081
1958
  };
1082
- //#endregion
1083
- export { Words as $, SelectionPage as A, QueryDependencies as At, Write as B, Relation as C, Order as Ct, RelationSpecs as D, Placement as Dt, RelationSpec as E, Ordering as Et, WrittenAs as F, ValueOf as Ft, Row as G, WriteSet as H, WrittenKey as I, dependenciesOf as It, decided as J, assertSupported as K, WrittenSpec as L, isPredicate as Lt, SelectionTypeId as M, ReadsOf as Mt, TargetKey as N, TermOptions as Nt, Selected as O, Predicate as Ot, Unmapped as P, TextOperand as Pt, SchemaWords as Q, AnyWrite as R, maxQueryNodes as Rt, RelatedSpecs as S, OrPredicate as St, RelationMap as T, OrderedOperand as Tt, PredicateTruth as U, WriteLink as V, QueryEvaluateError as W, supported as X, evaluate as Y, SchemaShape as Z, IdSchemaOf as _, LiteralExpr as _t, DerivedSpecs as a, ChosenSort as at, PageWindow as b, Operandish as bt, EntityDerived as c, ContainsPredicate as ct, EntityInput as d, Expr as dt, ReadFilter as et, EntityMember as f, FieldDependency as ft, IdOf as g, Invalid as gt, EntityTypeId as h, InputExpr as ht, DerivedSpec as i, ChosenOrder as it, SelectionPageTypeId as j, Reads as jt, Selection as k, Query as kt, EntityField as l, Dependencies as lt, EntityRelation as m, InPredicate as mt, Cardinality as n, AnyExpr as nt, Entities as o, CompareOperator as ot, EntityRef as p, FieldExpr as pt, compareRows as q, Derived as r, AnyQuery as rt, Entity as s, ComparePredicate as st, AnyEntity as t, AndPredicate as tt, EntityIdentity as u, EqPredicate as ut, InputMember as v, NotPredicate as vt, RelationInput as w, OrderTerm as wt, Related as x, Operation as xt, NestedInput as y, NullPredicate as yt, BoundWrite as z, Collation as zt };
1084
- //# sourceMappingURL=index-_x1ScI4v.d.mts.map
1959
+ export { Change as $, Ordering as $t, SelectionPage as A, ComparePredicate as At, ConditionedWrite as B, LiteralExpr as Bt, Relation as C, AnyQuery as Ct, RelationSpecs as D, ChosenOrder as Dt, RelationSpec as E, CallOptions as Et, WrittenAs as F, FieldDependency as Ft, WriteSet as G, Operation as Gt, WriteCondition as H, NotPredicate as Ht, WrittenKey as I, FieldExpr as It, Words as J, OperatorTable as Jt, SchemaShape as K, Operator as Kt, WrittenSpec as L, InPredicate as Lt, SelectionTypeId as M, Dependencies as Mt, TargetKey as N, EqPredicate as Nt, Selected as O, ChosenSort as Ot, Unmapped as P, Expr as Pt, BeforeRow as Q, OrderedOperand as Qt, AnyWrite as R, InputExpr as Rt, RelatedSpecs as S, AnyExpr as St, RelationMap as T, CallExpr as Tt, WriteIncrement as U, NullPredicate as Ut, Write as V, NextExpr as Vt, WriteLink as W, Operandish as Wt, Text as X, Order as Xt, ReadFilter as Y, OrPredicate as Yt, AfterRow as Z, OrderTerm as Zt, IdSchemaOf as _, Side as _n, MemoryOperators as _t, DerivedSpecs as a, Reads as an, QueryEvaluateError as at, PageWindow as b, TestedEvidence as bt, EntityDerived as c, TestPredicate as cn, compareRows as ct, EntityInput as d, dependenciesOf as dn, supported as dt, ParameterOf as en, DeclaredInvariant as et, EntityMember as f, isPredicate as fn, truthOver as ft, IdOf as g, LawDescription as gn, MemoryImplementation as gt, EntityTypeId as h, Law as hn, ImplementedOperator as ht, DerivedSpec as i, QueryDependencies as in, PredicateTruth as it, SelectionPageTypeId as j, ContainsPredicate as jt, Selection as k, CompareOperator as kt, EntityField as l, TextOperand as ln, decided as lt, EntityRelation as m, noOperators as mn, Evidence as mt, Cardinality as n, Predicate as nn, Judgement as nt, Entities as o, ReadsOf as on, Row as ot, EntityRef as p, maxQueryNodes as pn, valueOfOperand as pt, SchemaWords as q, OperatorDescriptor as qt, Derived as r, Query as rn, OperatorMissingError as rt, Entity as s, TermOptions as sn, assertSupported as st, AnyEntity as t, Placement as tn, Invariant as tt, EntityIdentity as u, ValueOf as un, evaluate as ut, InputMember as v, Collation as vn, OperatorContext as vt, RelationInput as w, ArgumentOf as wt, Related as x, AndPredicate as xt, NestedInput as y, Operators as yt, BoundWrite as z, Invalid as zt };
1960
+ //# sourceMappingURL=index-B9fbDo_-.d.mts.map