foldkit-entity 0.17.0 → 0.18.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 (62) hide show
  1. package/README.md +466 -227
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +10 -4
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/descriptor.d.ts +5 -1
  6. package/dist/descriptor.d.ts.map +1 -1
  7. package/dist/descriptor.js +6 -2
  8. package/dist/descriptor.js.map +1 -1
  9. package/dist/entity.d.ts +3 -2
  10. package/dist/entity.d.ts.map +1 -1
  11. package/dist/entity.js +5 -3
  12. package/dist/entity.js.map +1 -1
  13. package/dist/enumerate.d.ts +44 -0
  14. package/dist/enumerate.d.ts.map +1 -0
  15. package/dist/enumerate.js +128 -0
  16. package/dist/enumerate.js.map +1 -0
  17. package/dist/evaluate.d.ts +11 -5
  18. package/dist/evaluate.d.ts.map +1 -1
  19. package/dist/evaluate.js +27 -6
  20. package/dist/evaluate.js.map +1 -1
  21. package/dist/expr.d.ts +8 -2
  22. package/dist/expr.d.ts.map +1 -1
  23. package/dist/expr.js +19 -10
  24. package/dist/expr.js.map +1 -1
  25. package/dist/footprint.d.ts +120 -0
  26. package/dist/footprint.d.ts.map +1 -0
  27. package/dist/footprint.js +41 -0
  28. package/dist/footprint.js.map +1 -0
  29. package/dist/index.d.ts +8 -3
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +6 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/invariant.d.ts +41 -11
  34. package/dist/invariant.d.ts.map +1 -1
  35. package/dist/invariant.js +83 -38
  36. package/dist/invariant.js.map +1 -1
  37. package/dist/lawIds.d.ts +15 -0
  38. package/dist/lawIds.d.ts.map +1 -0
  39. package/dist/lawIds.js +13 -0
  40. package/dist/lawIds.js.map +1 -0
  41. package/dist/laws.d.ts +308 -0
  42. package/dist/laws.d.ts.map +1 -0
  43. package/dist/laws.js +566 -0
  44. package/dist/laws.js.map +1 -0
  45. package/dist/operators.d.ts +1 -1
  46. package/dist/refine.d.ts +64 -0
  47. package/dist/refine.d.ts.map +1 -0
  48. package/dist/refine.js +104 -0
  49. package/dist/refine.js.map +1 -0
  50. package/dist/rows.d.ts +15 -0
  51. package/dist/rows.d.ts.map +1 -0
  52. package/dist/rows.js +23 -0
  53. package/dist/rows.js.map +1 -0
  54. package/dist/uncollated.d.ts +10 -0
  55. package/dist/uncollated.d.ts.map +1 -0
  56. package/dist/uncollated.js +18 -0
  57. package/dist/uncollated.js.map +1 -0
  58. package/dist/write.d.ts +64 -6
  59. package/dist/write.d.ts.map +1 -1
  60. package/dist/write.js +88 -12
  61. package/dist/write.js.map +1 -1
  62. package/package.json +3 -3
package/README.md CHANGED
@@ -1,23 +1,15 @@
1
1
  # foldkit-entity
2
2
 
3
- A domain declared once as typed values: each entity's intrinsic fields, its
4
- relations to other entities, and the derived values consumers may read; and,
5
- over that, a small language for saying which rows (`Expr`, `Query`), what a
6
- write does to one (`Write`), and what every stored row must hold
7
- (invariants). Other packages interpret these declarations; this one only
8
- describes, and gives the reference meaning of the language over rows already
9
- in hand.
10
-
11
- > **Who reads it.** `foldkit-remote`
12
- > [registers Entities and reads Selections and query bodies](../remote/README.md#entities-declared-with-foldkit-entity),
13
- > and judges the rows it holds by them. `foldkit-remote-drizzle` binds a related
14
- > set to tables with
15
- > [`bind`](../remote-drizzle/README.md#binding-a-foldkit-entity-domain) and
16
- > compiles bodies, writes and invariants to SQL. [`foldkit-form`](../form/README.md)
17
- > builds a form from `Entity.input`, [`foldkit-crud`](../crud/README.md) joins
18
- > one to a Remote operation, and `foldkit-guard` writes its rules as `Expr`.
19
-
20
- For the whole path in one runnable trace, domain to client to SQL, see
3
+ A domain declared once as typed values, which other packages interpret: each
4
+ Entity's fields, relations and derived members, and over them a small language
5
+ for which rows (`Expr`, `Query`), what a write does to one (`Write`), and what
6
+ every stored row must hold (invariants). This package only describes, and
7
+ gives the language its reference meaning over rows already in hand.
8
+
9
+ New to the idea of one declared domain? Start with the guide,
10
+ [One domain declaration](../../docs/entity.md), which carries a small domain
11
+ through every reader; this README is the reference for each declaration. For
12
+ the whole path in one runnable trace, domain to client to SQL, see
21
13
  [`examples/entity`](../../examples/entity).
22
14
 
23
15
  ## What it owns
@@ -42,46 +34,37 @@ It does not own:
42
34
  - **Who may.** Authorization is `foldkit-guard`'s, written in the same `Expr`.
43
35
  - **Application state.** Nothing here touches a Model or dispatches a Message.
44
36
 
37
+ Its readers are the neighbouring packages. `foldkit-remote`
38
+ [registers Entities and reads Selections and query bodies](../remote/README.md#entities-declared-with-foldkit-entity),
39
+ and judges the rows it holds by them. `foldkit-remote-drizzle` binds a related
40
+ set to tables with
41
+ [`bind`](../remote-drizzle/README.md#binding-a-foldkit-entity-domain) and
42
+ compiles bodies, writes and invariants to SQL. [`foldkit-form`](../form/README.md)
43
+ builds a form from `Entity.input`, [`foldkit-crud`](../crud/README.md) joins
44
+ one to a Remote operation, and `foldkit-guard` writes its rules as `Expr`.
45
+
45
46
  ## Mental model
46
47
 
47
- ```text
48
- Entity
49
- ├── fields intrinsic values: the properties of entity.schema
50
- ├── relations navigation edges: one / many of another Entity (Entity.relate)
51
- ├── derived readable values an interpreter supplies, counts or finds
52
- ├── members all three under one namespace; keys never collide
53
- ├── sets members the write's context fills (who asks, when)
54
- └── invariants what every stored row must hold (kept in its metadata)
55
-
56
- over it, as data:
57
- Selection which members a consumer reads Entity.select
58
- Query which rows, in which order Query.from · Expr
59
- Write what one operation does to one row Write.update / insert / delete
60
-
61
- interpreter ──(foldkit-metadata)──► Entity / member attaches what it needs
62
- interpreter ◄── reads all of the above, and runs it (SQL, the client's store)
63
- ```
48
+ An Entity is declared once, as data. It has:
64
49
 
65
- An Entity has **one set of members**. `Entity.relate`, `Entity.derived` and
66
- `Entity.sets` add to it, and every descriptor of the Entity reads it: the one
67
- declared before `relate`, the one a relation's `target()` returns, the one a
68
- query captured. Metadata is the exception: `Entity.annotate`,
69
- `Entity.annotateMembers` and `Entity.invariant` return a new descriptor that
70
- carries its own, so one reader's view (a form's labels) stays its own. Compare
71
- descriptors with `Entity.same(a, b)`, not `a === b`.
50
+ - **fields**: intrinsic values, the properties of `entity.schema`;
51
+ - **relations**: navigation edges, one or many of another Entity (`Entity.relate`);
52
+ - **derived** values: readable values an interpreter supplies, such as counts or finds;
53
+ - **members**: all three under one namespace, so keys never collide;
54
+ - **sets**: members the write's context fills (who asks, when);
55
+ - **invariants**: what every stored row must hold (`Entity.invariant`).
72
56
 
73
- ```text
74
- identity ── relations, derived, sets one per Entity; relate / derived / sets add
75
- ├── descriptor fields, metadata define, relate, derived, sets return it
76
- └── descriptor fields, metadata' annotate / annotateMembers / invariant make one
77
- ```
57
+ Over an Entity, also as data, a **Selection** says which members a consumer reads
58
+ (`Entity.select`), a **Query** says which rows in which order (`Query.from` and
59
+ `Expr`), and a **Write** says what one operation does to one row (`Write.update`,
60
+ `insert`, `delete`).
78
61
 
79
- A descriptor's *type* still shows only the steps it came through: read typed
80
- members from the descriptor `relate` returned, or a later one.
62
+ An interpreter reads all of that and runs it: SQL, or the client's store. Through
63
+ `foldkit-metadata` it can attach to an Entity or a member what it needs.
81
64
 
82
- Everything here is checked where it is declared: a type error where the types
83
- can see it, and a throw for what they cannot. An interpreter that cannot run
84
- something refuses it by name rather than skipping it.
65
+ A declaration is checked where it is made wherever it can be: a type error
66
+ where the types can see it, a throw for what they cannot. An interpreter that
67
+ cannot run something refuses it by name rather than skipping it.
85
68
 
86
69
  ## Install
87
70
 
@@ -114,6 +97,16 @@ Next, hand the Entity to Remote for client reads or bind it to Drizzle tables
114
97
  on the server. Declare operation input separately when adding a form: selecting
115
98
  readable fields does not grant permission to write them.
116
99
 
100
+ ## Where to go next
101
+
102
+ | To | Reference, here | Taught in |
103
+ | --- | --- | --- |
104
+ | Declare Entities, relations and derived members, and select what a reader wants | [Relations and derived values](#relations-and-derived-values), [Selecting a view](#selecting-a-view), [variants](#rows-of-several-shapes-variants) | [One domain declaration](../../docs/entity.md) |
105
+ | Say which rows, and judge one you hold | [`Expr`, `Query`, `Judge`](#saying-something-about-a-row-expr) | [Expressions](../../docs/expressions.md) |
106
+ | Read an operation's input and declare what it writes | [Reading an operation's input](#reading-an-operations-input), [Declaring what an input writes](#declaring-what-an-input-writes) | [Declared writes](../../docs/declared-writes.md) |
107
+ | Say what every row must hold, and check every write against it | [Invariants](#what-every-row-and-change-must-hold-invariants), [States and `Laws.check`](#states-of-a-row-and-what-every-write-does-to-them) | [Laws](../../docs/laws.md) |
108
+ | Name a question an interpreter answers its own way | [Operators](#naming-a-question-operators) | [Operators](../../docs/operators.md) |
109
+
117
110
  ## Relations and derived values
118
111
 
119
112
  ```ts
@@ -188,12 +181,44 @@ Object.keys(Blog.Post.members) // id, title, published, author, editor, comments
188
181
  - `Entity.relate` takes the entities and every relation between them, adds
189
182
  the relations to them, and returns them typed with their relations. Use the
190
183
  returned ones (`Blog.Post`) for their types; the `Post` you passed in has the
191
- same relations at runtime.
184
+ same relations at runtime. It is one step over Entities that already
185
+ exist because Entities point at each other, and TypeScript cannot infer two
186
+ constants each typed by the other.
192
187
  - `Relation.one` / `Relation.many` state what the owner sees. `Post.author: one`
193
188
  and `Author.posts: many` together are the familiar one-to-many; neither side
194
189
  names it.
195
190
  - `target()` returns the related entity, so relations can be followed from
196
191
  there, around a cycle too.
192
+ `Entity.relate` throws for a relation key that is already a member, an owner
193
+ that is not in the first argument, and a target that is not in the first
194
+ argument. The types reject the first two where they are written; a stray
195
+ target is found when `relate` runs.
196
+
197
+ ### One Entity, several descriptors
198
+
199
+ An Entity has **one set of members**, and one set of invariants.
200
+ `Entity.relate`, `Entity.derived`, `Entity.sets` and `Entity.invariant` add
201
+ to it, and every descriptor of the Entity reads it: the one declared before
202
+ `relate`, the one a relation's `target()` returns, the one a query captured.
203
+ Metadata is the exception: `Entity.annotate` and `Entity.annotateMembers`
204
+ return a new descriptor that carries its own, so one reader's view (a form's
205
+ labels) stays its own. Compare descriptors with `Entity.same(a, b)`, not
206
+ `a === b`.
207
+
208
+ ```text
209
+ identity ── relations, derived, sets, invariants one per Entity; relate / derived / sets / invariant add
210
+ ├── descriptor fields, metadata define, relate, derived, sets, invariant return it
211
+ └── descriptor fields, metadata' annotate / annotateMembers make one
212
+ ```
213
+
214
+ A descriptor's *type* still shows only the steps it came through: read typed
215
+ members from the descriptor `relate` returned, or a later one.
216
+
217
+ ### What a delete does to the rows pointing at it
218
+
219
+ A `one` relation may say what happens to its row when the row it points at
220
+ is deleted.
221
+
197
222
  - `Relation.one(Post, { onDelete: 'cascade' })` says a row goes when the row
198
223
  it points at is deleted: a comment with its post, a reply with the post it
199
224
  answers. It is declared on the link the row holds, as its foreign key is,
@@ -204,9 +229,10 @@ Object.keys(Blog.Post.members) // id, title, published, author, editor, comments
204
229
  without foreign keys too.
205
230
  - `Relation.one(Topic, { onDelete: 'restrict' })` says the row it points at
206
231
  cannot be deleted while it points there: a topic with notes under it.
207
- `Entity.restricting(Topic)` lists those relations, and `remote-drizzle`'s
208
- writer refuses such a delete as `Refusal.referenced`, naming the relation
209
- and none of the rows.
232
+ `Entity.restricting(Topic)` lists those relations; `remote-drizzle`'s
233
+ writer finds such a delete and `RemoteServer.write` refuses it as
234
+ `Refusal.referenced` (`foldkit-remote`), naming the relation and none of
235
+ the rows.
210
236
  - `Relation.one(Folder, { optional: true, onDelete: 'setNull' })` says the
211
237
  row stays and points nowhere when the row it points at is deleted: a doc
212
238
  whose folder went. Only a link that may point nowhere can say it, and the
@@ -221,18 +247,9 @@ Object.keys(Blog.Post.members) // id, title, published, author, editor, comments
221
247
  post may take these rows with it, whoever wrote them: a post's author
222
248
  removing everyone's likes of it. `authorizedBy` is said only beside
223
249
  `onDelete: 'cascade'`, and reads back as the relation's `authorizedBy`.
224
-
225
- `Entity.relate` throws, and the types reject, a relation key that is already a
226
- member, an owner that is not in the first argument, and a target that is not
227
- in the first argument.
228
-
229
- ### Why relations are declared in one step
230
-
231
- Entities point at each other: a Post has Comments and a Comment has a Post. If
232
- each entity declared its own relations, `Post` would be typed in terms of
233
- `Comment` and `Comment` in terms of `Post`, and TypeScript cannot infer two
234
- constants that way. Declaring the relations over entities that already exist
235
- avoids the cycle, and lets `relate` check every target up front.
250
+ - A cascade may not reach an Entity whose rows are themselves pointed at
251
+ through a `setNull` or `restrict` relation: `RemoteServer.write` refuses
252
+ such a delete where the server is defined.
236
253
 
237
254
  ## Ids of their own
238
255
 
@@ -268,8 +285,8 @@ Entity.input(Press.Article, Schema.Struct({ authorId: AuthorId }), {
268
285
  - A Selection carries its Entity's id type, so `foldkit-remote`'s
269
286
  `Data.get(PostPage, id)` takes a `PostId` and refuses an `AuthorId`, or plain
270
287
  text.
271
- - Nothing here is new API to opt into. An Entity with `id: Schema.String` types
272
- exactly as before.
288
+ - An Entity with `id: Schema.String` has plain `string` ids and refs: a brand
289
+ is opt-in.
273
290
 
274
291
  ## Selecting a view
275
292
 
@@ -324,7 +341,9 @@ const PostWithComments = Entity.select(Blog.Post, {
324
341
  // { title: string, comments: { items: { body: string }[], hasNext: boolean, hasPrevious: boolean } }
325
342
  ```
326
343
 
327
- The window is `first` or `last`, with `after` or `before` a cursor. A page is a
344
+ The window is `first` with an optional `after`, or `last` with an optional
345
+ `before`, each cursor a string and each size a non-negative integer;
346
+ `Entity.page` throws for any other combination. A page is a
328
347
  view's shape, as neutral as "`many` means an array", so it is declared here.
329
348
  What a cursor is and how the rows are ordered belong to whoever fetches: the
330
349
  cursor is an opaque string an earlier answer handed out. Reading on is another
@@ -332,7 +351,9 @@ Selection with another window.
332
351
 
333
352
  An unknown member, a nested Selection on a field, a page of a `one` relation,
334
353
  and a Selection of the wrong
335
- Entity are type errors, and `Entity.select` throws for untyped callers.
354
+ Entity are type errors, and `Entity.select` throws for untyped callers. The
355
+ types tell Entities apart by name, so a Selection of another Entity that
356
+ shares the name is caught only by the throw.
336
357
 
337
358
  ## Attaching metadata
338
359
 
@@ -380,24 +401,9 @@ Words.of(Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1)))
380
401
  ## Saying something about a row: `Expr`
381
402
 
382
403
  An Entity says what a domain has. An `Expr` says something about one row of it,
383
- as a value:
384
-
385
- > **Why query semantics live in this package.** They describe and interpret
386
- > nothing, which is the line this package already draws: an `Expr` says which
387
- > rows and fetches none of them, and the interpreters that *fetch* live
388
- > elsewhere — `foldkit-remote-drizzle` compiles a body to SQL against a
389
- > database.
390
- >
391
- > `evaluate` is here rather than there because it is the **reference
392
- > semantics** of the IR: what the operator definitions mean, operationally, over
393
- > rows already in hand. A specification's reference implementation belongs with
394
- > the specification, and it reaches nothing — no database, no transport, no
395
- > Remote concept. The rule that keeps it honest is that **it may depend on the
396
- > IR and nothing else**; the moment it wants one of those it has moved to the
397
- > wrong place. Nothing that imports only
398
- > `Entity` pays for them: they are ordinary consts in a `sideEffects: false`
399
- > package, so a bundler drops them, and a package like `foldkit-form` imports
400
- > only types from here in any case.
404
+ as a value. This section is the reference; the
405
+ [Expressions guide](../../docs/expressions.md) teaches the language in order,
406
+ with one body answered by SQL, by `evaluate` and by `Judge`.
401
407
 
402
408
  ```ts
403
409
  import { Schema } from 'effect'
@@ -409,9 +415,14 @@ const newestTerms = [Order.desc(Blog.Post.fields.title), Order.asc(Blog.Post.fie
409
415
  ```
410
416
 
411
417
  Building one performs no work: it reads nothing, names no database, and runs no
412
- query. An interpreter compiles it — `foldkit-remote-drizzle` to SQL, an
413
- in-memory evaluator to a predicate over rows — which is what lets one query mean
414
- the same thing in more than one place.
418
+ query. An interpreter runs it (`foldkit-remote-drizzle` compiles it to SQL,
419
+ `evaluate` judges rows in memory), which is what lets one query mean the same
420
+ thing in more than one place.
421
+
422
+ > **Why `evaluate` lives here.** It is the reference semantics of the
423
+ > language: what each operation means over rows already in hand. It may depend
424
+ > on the language and nothing else (no database, no transport, no Remote
425
+ > concept), and a page importing only `Entity` does not carry it.
415
426
 
416
427
  A comparison coerces what it is given, so the common forms read as they mean: a
417
428
  field becomes a reference, a plain value becomes a literal, and an `Expr` is
@@ -422,13 +433,6 @@ the field on the left; `Expr.eq('Hello', Blog.Post.fields.title)` is refused wit
422
433
  that sentence. The comparisons (`lt`, `gte`, …) also take a field second,
423
434
  wrapped in `Expr.field(…)`.
424
435
 
425
- **An input is a placeholder, not a value.** A query's body is built once, so
426
- `Expr.input('title', …)` stands for whatever the query is given when it runs —
427
- there is nothing there yet to branch on. An `InputExpr` is an object, so a
428
- `condition ? a : b` over one is always truthy and decides itself once, forever.
429
- A query that depends on what it was passed says so with a comparison over the
430
- placeholder instead of a branch around it.
431
-
432
436
  `dependenciesOf(...)` says which fields and inputs an expression reads and which
433
437
  operations it uses, so a planner knows what it needs and an interpreter can
434
438
  refuse a query it cannot run. Each field names its `owner`, the Entity's
@@ -473,10 +477,11 @@ const anyStatus = draftOrLive(Post.fields.status)
473
477
  member and not the function's own data-last form.
474
478
  - A wrong value is refused at the step: `pipe(Post.fields.status, Expr.eq.step(42))`
475
479
  is an error where it is written. `Expr.eq(Post.fields.status)` is still an arity error.
476
- - A comparison's `step` takes the options its builder takes
480
+ - The `step` of `lt`, `lte`, `gt` and `gte` takes the options its builder takes
477
481
  (`Expr.lt.step('m', { collation })`); an operator's takes none, so a call that
478
482
  needs a collation is written data-first. A step takes the arguments past the
479
- first, then the first: `trim.step()` takes nothing, `Text.startsWith.step(prefix)` one.
483
+ first, then the first: an operator of one argument has a `step()` that takes
484
+ nothing, and `Text.startsWith.step(prefix)` takes one.
480
485
  - Data-first stays the form to learn first; a step earns its place in a chain.
481
486
 
482
487
  ### Asking a question that depends on an input, without branching on it
@@ -517,23 +522,20 @@ not match `é`, though each matches itself. Text holding a NUL character is
517
522
  refused by every interpreter here, in `contains`, `eq` and `in` alike, since
518
523
  Postgres text cannot hold one and SQLite compares only up to it.
519
524
 
520
- **`in` asks whether a value is one of a list**, written out or given as an
521
- input: `Expr.in(Todo.fields.projectId, input.projectIds)`. Each element is
525
+ **`in` asks whether a value is one of a list**, written out
526
+ (`Expr.in(Post.fields.status, ['draft', 'live'])`) or given as an input of a
527
+ list. Each element is
522
528
  compared as `eq` compares, and it reads as SQL's `in`: a null value is
523
529
  unknown, so is no match against a list holding a null, and an empty list
524
530
  matches no row (on Postgres too, which refuses `in ()`; the compiler says
525
531
  `false` instead).
526
532
 
527
- **It searches text, and the operand is constrained to text.** `contains` over a
528
- number would compile to `lower(rank) like …`, which SQLite coerces into an
529
- answer and Postgres rejects at runtime — so a non-text operand is a compile
530
- error where it is written rather than a surprise where it runs. Nullable text is
531
- allowed, because it is a real case with a real meaning:
532
-
533
- **Over a column that can be null it is not the same as no filter.** A null
534
- contains nothing, not even the empty string, so its rows drop out. The column
535
- the CMS searches is declared not-null, which is what makes an empty search
536
- exactly everything there.
533
+ **`contains` searches text, and its operand is constrained to text.** Over a
534
+ number it would compile to `lower(rank) like …`, which SQLite coerces into an
535
+ answer and Postgres rejects at runtime, so a non-text operand is a compile
536
+ error where it is written. Nullable text is allowed, and there an empty search
537
+ is not the same as no filter: a null contains nothing, not even the empty
538
+ string, so its rows drop out.
537
539
 
538
540
  ### Who asks, and when: the context
539
541
 
@@ -651,9 +653,15 @@ unless the terms already read the id, so rows with equal keys come out in one
651
653
  order on every interpreter rather than each breaking ties its own way.
652
654
 
653
655
  **How text orders is declared, or left to the server.** Left unsaid, SQLite
654
- compares bytes, Postgres follows the database's locale and a JavaScript sort
655
- follows UTF-16 code units. A field declares its collation, and every
656
- interpreter that can honour it orders the same; one that cannot refuses:
656
+ compares bytes, Postgres follows the database's locale and a plain JavaScript
657
+ sort follows UTF-16 code units. A field declares its collation, which SQL
658
+ compiles, and `Query.placement` says whether a client can order the same way.
659
+ `evaluate` refuses an order over text with no declared collation, with the
660
+ reason `Query.placement` gives, so a page and the reference agree on whether
661
+ the question can be answered; a database orders such text by its own default,
662
+ which differs between SQLite and Postgres. `evaluateEach`, which only judges
663
+ membership, does not refuse, and its `matched` list is then in code point
664
+ order:
657
665
 
658
666
  ```ts
659
667
  const Tagged = Entity.define('Tagged', Schema.Struct({ id: Schema.String, name: Schema.String })).pipe(
@@ -734,11 +742,11 @@ Expr.and(
734
742
  ```
735
743
 
736
744
  Numbers compare as numbers, and nothing compares across kinds or for a value
737
- stored as neither a number nor text. Text orders by a collation, and backends disagree
738
- about the default one (SQLite's `BINARY`, the Postgres database's locale,
739
- JavaScript's UTF-16 units), so text is compared only under `Collation.binary`
740
- or `Collation.asciiFold`, declared on the field or passed, and only against a
741
- field: anything else is refused where the comparison is written. A value is
745
+ stored as neither a number nor text. Text orders by a collation, and the
746
+ defaults disagree (above), so text is compared only under `Collation.binary`
747
+ or `Collation.asciiFold`, passed or declared on a side that carries one (a
748
+ field, a path to one, an operator call with a collation): anything else
749
+ throws where the comparison is built. A value is
742
750
  compared in its encoded form, which is why a date stored as an ISO string is
743
751
  text here. A null on either side is unknown, as in SQL. There is no `between`;
744
752
  it is the `and` above.
@@ -788,8 +796,9 @@ it declares.)
788
796
  does. At most four relations.
789
797
  - `Expr.exists(relation, where?)` names the pointing edge, a `one` relation of
790
798
  another Entity (`Follow.followee`), as `Derived.count` does. Only rows the
791
- reader may see count. `where` reads the pointing row's own fields and the
792
- input; anything past them is refused where it is written.
799
+ reader may see count. `where` reads the pointing row's own fields, the
800
+ input and the context (`Expr.viewer`, `Expr.now`); another Entity's field or
801
+ a further path or exists is refused where it is written.
793
802
  - A list does not order by a path.
794
803
 
795
804
  A `one` relation is itself an operand: the id it points at, typed as the
@@ -807,7 +816,7 @@ does not order by a link: a client holds it as a ref, not as the id it would
807
816
  order by.
808
817
 
809
818
  `foldkit-remote-drizzle` compiles both to subqueries under each reached
810
- table's `visible` rule. `evaluate`, given one row, cannot follow them: it
819
+ table's `visible` rule. `evaluate`, given one table's rows, cannot follow them: it
811
820
  refuses such a body, as it refuses any operation it does not run. `Judge`,
812
821
  below, reads them from what a holder has.
813
822
 
@@ -856,6 +865,7 @@ an interpreter does not have:
856
865
 
857
866
  ```ts
858
867
  const missing = Query.unsupported(ByHandle, ['eq', 'isNull', 'isNotNull'])
868
+ // ['path']: ByHandle reads a path, which this interpreter does not list
859
869
  if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
860
870
  ```
861
871
 
@@ -877,21 +887,15 @@ WHERE Post.slug = $slug
877
887
  ORDER BY Post.updatedAt DESC
878
888
  ```
879
889
 
880
- For a person — an explanation, a diagnostic, a test asserting on a whole
881
- predicate at once — and never for an interpreter. It is close enough to SQL to
882
- read at a glance and unlike it everywhere that matters: an input is `$slug`
883
- rather than a bound parameter, `contains` is named rather than rendered as
884
- somebody's `like`, and no dialect's escaping or collation is implied. What
885
- actually ran is whatever that backend compiled, which is not this.
886
- `Expr.show(node)` does the same for one expression.
890
+ It is for a person (an explanation, a diagnostic, a test asserting on a whole
891
+ predicate at once), never for an interpreter: an input is `$slug` rather than
892
+ a bound parameter, `contains` is named rather than rendered as somebody's
893
+ `like`, and no dialect's escaping or collation is implied. `Expr.show(node)`
894
+ does the same for one expression.
887
895
 
888
- A `Query` says which rows. It does not say which fields — that is a Selection —
889
- and it does not say how many, whether absence is an error, or whether to watch
890
- for changes: those belong to the consumer doing the reading, not to the
891
- relation.
892
-
893
- Only the operations a real query in this repository needs exist. The set grows
894
- from queries, not from what a database could express.
896
+ A `Query` says which rows. It does not say which fields (a Selection does),
897
+ how many, whether absence is an error, or whether to watch for changes: those
898
+ belong to the consumer doing the reading.
895
899
 
896
900
  ## Rows of several shapes: variants
897
901
 
@@ -933,9 +937,11 @@ stored row Domain.fields { _tag, id, name, price | null, years | null }
933
937
  reading which fields are null. `Entity.variantsOf(Domain)` holds the codec
934
938
  between the two (`stored`): a stored row, encoded, decodes to its case, and
935
939
  one holding another case's field is refused.
936
- - **Each case says what it holds.** A case with fields of its own gets an
937
- invariant (`variant_Available`: an Available holds `price` and `years`;
938
- `variant_Unconfirmed`: an Unconfirmed holds none of them), so `Entity.judge`
940
+ - **Each case says what it holds.** A case gets an invariant wherever a stored
941
+ row could break it: it has a field of its own that may not be null, or
942
+ another case has a field it must not hold (`variant_Available`: an Available
943
+ holds `price` and `years`; `variant_Unconfirmed`: an Unconfirmed holds none
944
+ of them), so `Entity.judge`
939
945
  and a form refuse a row that mixes cases, and `foldkit-remote-drizzle`
940
946
  writes each as a CHECK.
941
947
 
@@ -1005,7 +1011,8 @@ CreatePostById.members.authorId.relation.target() // Blog.Author: what a picker
1005
1011
  CreatePostById.members.notify // Entity.unmapped: about the operation, not the Post
1006
1012
  ```
1007
1013
 
1008
- - A key that names a field, with a value that fits it, maps itself. Only the
1014
+ - A key that names a field, with a value that fits it, maps itself (the fit is
1015
+ the types' to check; at run time any key naming a field maps). Only the
1009
1016
  present value has to fit: a key may be optional (a partial update), admit
1010
1017
  `null` (clearing it), or hold an `Option` (an id absent for something new),
1011
1018
  which is the input schema's rule to make.
@@ -1041,9 +1048,9 @@ const CreatePost = Entity.input(
1041
1048
  )
1042
1049
  ```
1043
1050
 
1044
- A `one` holds the nested input's value, a `many` a list of them; the nested
1045
- input must be of the relation's target, and both are checked by type and at
1046
- runtime. `Entity.selectFor` then loads what the nested input writes of the
1051
+ A `one` holds the nested input's value, a `many` a list of them, which the
1052
+ types check; the nested input must be of the relation's target, checked by
1053
+ type and at runtime. `Entity.selectFor` then loads what the nested input writes of the
1047
1054
  target, and `Entity.valuesFor` turns the loaded target back into nested values.
1048
1055
  What a nested write *does* (insert, update, replace the list) is the
1049
1056
  operation's handler to decide.
@@ -1054,10 +1061,10 @@ An edit screen has to load the current values and turn them into input values.
1054
1061
  Both follow from the reading, so neither is written by hand:
1055
1062
 
1056
1063
  ```ts
1057
- const PostForEdit = Entity.selectFor(CreatePost)
1064
+ const PostForEdit = Entity.selectFor(CreatePostById)
1058
1065
  // a Selection of `title` and `author`, the members the input writes; `author` as a ref
1059
1066
 
1060
- Entity.valuesFor(CreatePost, { title: 'Hello', author: { entity: 'Author', id: 'a1' } })
1067
+ Entity.valuesFor(CreatePostById, { title: 'Hello', author: { entity: 'Author', id: 'a1' } })
1061
1068
  // { title: 'Hello', authorId: 'a1' }
1062
1069
  ```
1063
1070
 
@@ -1143,8 +1150,11 @@ An update or a delete may also say when it makes sense: `when` is what the row
1143
1150
  must hold for it to land, written as a query body is: `() =>
1144
1151
  Expr.eq(Post.fields.title, 'Draft')`, or with the input, `({ input }) =>
1145
1152
  Expr.eq(Post.fields.title, input.from)`. It reads the row as it is before the write and the input,
1146
- never who is asking (that is a guard's), and only its own Entity: a field of
1147
- another is a type error, and refused where the write is declared. It is held as
1153
+ and only its own Entity: a field of another is a type error, and refused where
1154
+ the write is declared. Who is asking is a guard's: a `when` reading
1155
+ `Expr.viewer` or `Expr.now` (also through a path from the viewer or an exists)
1156
+ is refused where the write is declared; a writer, given neither, refuses a
1157
+ hand-built one again where it is served. It is held as
1148
1158
  a query body (`write.when`), so an interpreter checks it in the statement that
1149
1159
  writes, and a row it does not hold of is refused as unmet. A write declared with
1150
1160
  one is a `ConditionedWrite`, which is how `Mutation.write` knows it may be
@@ -1159,10 +1169,13 @@ writes, so no concurrent change is lost. A retry must not add twice, so either i
1159
1169
  expects a revision (a retry of a write that landed is then a conflict), or its
1160
1170
  writer keeps a ledger, which answers the retry from its record and lets two
1161
1171
  concurrent increments both land. `RemoteServer.write` refuses one with neither,
1162
- and one of a real number with no revision even under a ledger: floating-point
1163
- addition does not associate, so two concurrent sums could land as two results.
1164
- The field must be stored as a number, and may not be the id, the revision, or
1165
- set by another key. `Write.bind` gives the amounts apart from the values (`increments`), so a
1172
+ and one of a real number with no revision even under a ledger, unless its
1173
+ writer pins the row it read (`foldkit-guard`'s writer with a `revision`):
1174
+ floating-point addition does not associate, so two concurrent sums could land
1175
+ as two results. The field must be stored as a number that is never null, and
1176
+ may not be the id, the revision, or set by another key; the amount is an
1177
+ unmapped key, and an integer field takes an integer amount. Each is refused
1178
+ where the write is declared. `Write.bind` gives the amounts apart from the values (`increments`), so a
1166
1179
  client can add them to the value it holds as it reads it (Remote does), never
1167
1180
  fixing a sum over a row that may since have moved. `Write.reads(write)` is what a write
1168
1181
  reads from its row: what its `when` reads, each field it increments, what its
@@ -1193,8 +1206,9 @@ value for each implementation the writer runs (`Conformance.laws` in memory,
1193
1206
  the row before it: values set, amounts added (a null stays null, as in SQL),
1194
1207
  assignments computed. It is the one computation of that row: a guard judges
1195
1208
  it, a writer explains a miss by it, a client predicts it. `unknown` names each
1196
- field it could not work out (one the row lacks, or an operator the table lacks),
1197
- which keeps what the row holds.
1209
+ field it could not work out (one the row lacks, an amount added to a value
1210
+ that is no number, or an operator the table lacks), which keeps what the row
1211
+ holds.
1198
1212
 
1199
1213
  ### What a client foresees of a supplied member
1200
1214
 
@@ -1310,10 +1324,23 @@ A row judged holds each relation it reads as that id (null where an optional
1310
1324
  one points nowhere); `Entity.judgeInput` reads an input key mapped to the
1311
1325
  relation as it. A `many` relation holds no one value, so it is not there.
1312
1326
 
1327
+ An input describes a whole row only when it creates one. An edit sets a few
1328
+ fields of a row that exists, so `Entity.judgeInput(input, value, { over })`
1329
+ takes that row, encoded (`Entity.rowFrom(entity, value)` gives it from a
1330
+ read value): the input's keys are laid over it, and it is the row before, so
1331
+ an invariant over a field the input does not set, and a transition, are
1332
+ judged. Without `over` such an invariant is `Undecided`. `Entity.judgedBy(input)`
1333
+ names the members outside the input that its invariants read beside a key it
1334
+ sets (`{ approvedBy: true }`), for `Entity.selectFor(input, { also })` to load:
1335
+ `foldkit-crud`'s editor does both.
1336
+
1313
1337
  `Entity.invariant` returns the step that attaches it, carrying its `id` and,
1314
1338
  once attached, its Entity's name as `entity`: an id is unique only within an
1315
1339
  Entity, so a refusal names both. A declaration attaches to one Entity; reading
1316
- `entity` before it is attached throws. Hoist it to export it, naming the
1340
+ `entity` before it is attached throws, and applying it to that Entity again
1341
+ adds nothing. The invariant is the Entity's, so `InventoryFields` below judges
1342
+ it as `Inventory` does: a form, a write or a server binding made from either
1343
+ name holds it. Hoist it to export it, naming the
1317
1344
  Entity's type (what it reads is checked against it), and match a refusal
1318
1345
  against it rather than spelling the id again:
1319
1346
 
@@ -1342,17 +1369,19 @@ Refusal.isInvalidBy(refusal, reservedWithinQuantity)
1342
1369
  ```
1343
1370
 
1344
1371
  - `before` is each field as the row before holds it (`Expr.field`), and `after`
1345
- each as the row after holds it (`Expr.next`), both typed as the field. Each
1346
- is an expression already, so it goes on either side as it is; `Expr.field`
1347
- wraps an Entity's own field, and refuses one of these:
1372
+ each as the row after holds it (`Expr.next`), both typed as the field's
1373
+ encoded, stored form. Each is an expression already, so it goes on either
1374
+ side as it is; `Expr.field` wraps an Entity's own field, and one of these is
1375
+ a type error there:
1348
1376
 
1349
1377
  | Write | Not |
1350
1378
  | --- | --- |
1351
1379
  | `Expr.gte(after.quantity, before.quantity)` | `Expr.gte(after.quantity, Expr.field(before.quantity))` |
1352
- - It is declared once, on the Entity's metadata, and attaching more adds to it;
1380
+ - It is declared once, on the Entity itself, and attaching more adds to it;
1353
1381
  the Entity stays the same (`Entity.same`). Its interpreters read it from there.
1354
1382
  - It reads stored rows only: one over another Entity, or reading an input, is
1355
- refused where it is declared, as is an id declared twice or a `path` naming
1383
+ refused when it is attached to its Entity (a `DeclaredInvariant` held apart
1384
+ is checked when it is piped on), as is an id declared twice or a `path` naming
1356
1385
  neither a field nor a `one` relation. So is one reading nothing of `after`: which rows a write may start from
1357
1386
  is its `when`. Who may write is a guard's; whether a write applies now is its `when`'s.
1358
1387
  - `Entity.judge(entity, { after, before? })` judges rows as the store holds them
@@ -1371,6 +1400,234 @@ needs `{ collation: Collation.binary }` on its comparison. An interpreter that
1371
1400
  judges stored rows alone refuses `after`'s nodes as the operation `next`;
1372
1401
  `Expr.substituteNext` reads the ones a write sets as their values.
1373
1402
 
1403
+ ## States of a row, and what every write does to them
1404
+
1405
+ An invariant says what every row holds. A row also passes through states a
1406
+ reader names (a draft, a published product), and a write makes sense from some
1407
+ and leads to others. `Entity.refine` names one, as a value: a predicate over
1408
+ the row, declared once on the Entity (every descriptor of it lists it, as it
1409
+ judges its invariants). It is not another descriptor: a store, a compiler or a
1410
+ guard given `Draft` where it wants `Product` would read every product.
1411
+
1412
+ <!-- docs-check standalone
1413
+ import { Schema } from 'effect'
1414
+ import { Entity, Expr, Query, Write } from 'foldkit-entity'
1415
+ -->
1416
+
1417
+ ```ts
1418
+ const Product = Entity.define(
1419
+ 'Product',
1420
+ Schema.Struct({
1421
+ id: Schema.String,
1422
+ status: Schema.Literals(['draft', 'published', 'archived']),
1423
+ stock: Schema.Number,
1424
+ }),
1425
+ )
1426
+
1427
+ const Draft = Entity.refine(Product, 'Draft', { status: 'draft' }) // a value per field
1428
+ const Published = Entity.refine(Product, 'Published', { status: 'published' })
1429
+ const InStock = Entity.refine(Product, 'InStock', ({ row }) => Expr.gt(row.stock, 0)) // any predicate
1430
+
1431
+ const drafts = Query.from(Draft) // every product in the state: its predicate in `where`
1432
+ Expr.show(Draft.predicate) // 'Product.Draft'
1433
+ Entity.inState(Draft, { status: 'draft' }) // Option.some(true); none for a row without `status`
1434
+ ```
1435
+
1436
+ - The literal form is one `Expr.eq` per key (`Expr.isNull` for a `null`), each typed by what its field
1437
+ stores: a key that is no field, or a value the field cannot hold, does not
1438
+ compile. Its `is(row)` is a type guard narrowing the fields it names
1439
+ (`row.status` is `'draft'` inside `if (Draft.is(row))`); the predicate form's
1440
+ narrows nothing. A Selection is never narrowed by state: a held row is
1441
+ updated in place, and goes on being read after it left the state.
1442
+ - `build` is given `row` alone, so a state cannot read the past: "was ever
1443
+ published" is a field.
1444
+ - A state may reach another row (`Expr.path`, `Expr.exists`). It is queried
1445
+ as any predicate is, but it is not `local`: `inState` and `is` cannot judge
1446
+ it from one row, and it is no write's `from` or `becomes`, since a writer
1447
+ judges the row it writes alone.
1448
+
1449
+ A write says which state it starts from and which it leaves:
1450
+
1451
+ ```ts
1452
+ const Publish = Write.update(
1453
+ Entity.input(Product, Schema.Struct({ id: Schema.String, status: Schema.Literal('published') })),
1454
+ { id: 'id', from: Draft, becomes: Published },
1455
+ )
1456
+ ```
1457
+
1458
+ - `from: Draft` joins the state's predicate to the write's `when`, so a row in
1459
+ another state is refused as unmet, as any `when` refuses, and the write is a
1460
+ `ConditionedWrite`.
1461
+ - `becomes: Published` claims every row the write can start from is published
1462
+ once it lands. It is decided where the write is declared, by enumerating
1463
+ those rows: a claim the patch cannot keep throws there, naming a row it
1464
+ breaks. A claim enumeration cannot decide (a sale `becomes: InStock` moves a
1465
+ number) is the write's postcondition, `ensures`: an invariant of that write
1466
+ alone, id `becomes:InStock`, which each writer judges where the write commits
1467
+ and refuses as `Invalid`. `Write.ensured(Sell.write)` is that invariant, for
1468
+ `Refusal.isInvalidBy`; `Laws.check` reports the arrow `enforced`.
1469
+
1470
+ ### Checking every write: `Laws.check`
1471
+
1472
+ `Laws.check` judges each write against each invariant of its Entity, and
1473
+ reports the arrows the writes make between its states. It is pure, needs no
1474
+ database, and reads declarations only:
1475
+
1476
+ <!-- docs-check standalone
1477
+ import { Schema } from 'effect'
1478
+ import { Entity, Footprint, Laws, Write } from 'foldkit-entity'
1479
+
1480
+ const Product = Entity.define(
1481
+ 'Product',
1482
+ Schema.Struct({
1483
+ id: Schema.String,
1484
+ name: Schema.String,
1485
+ status: Schema.Literals(['draft', 'published', 'archived']),
1486
+ stock: Schema.Number,
1487
+ }),
1488
+ )
1489
+ const Draft = Entity.refine(Product, 'Draft', { status: 'draft' })
1490
+ const Published = Entity.refine(Product, 'Published', { status: 'published' })
1491
+ const ToPublished = Entity.input(
1492
+ Product,
1493
+ Schema.Struct({ id: Schema.String, status: Schema.Literal('published') }),
1494
+ )
1495
+ const ToDraft = Entity.input(
1496
+ Product,
1497
+ Schema.Struct({ id: Schema.String, status: Schema.Literal('draft') }),
1498
+ )
1499
+ const Rename = {
1500
+ name: 'Rename',
1501
+ write: Write.update(
1502
+ Entity.input(Product, Schema.Struct({ id: Schema.String, name: Schema.String })),
1503
+ { id: 'id' },
1504
+ ),
1505
+ }
1506
+ const Publish = {
1507
+ name: 'Publish',
1508
+ write: Write.update(ToPublished, { id: 'id', from: Draft, becomes: Published }),
1509
+ }
1510
+ const Revert = { name: 'Revert', write: Write.update(ToDraft, { id: 'id' }) }
1511
+ const Sell = {
1512
+ name: 'Sell',
1513
+ write: Write.update(
1514
+ Entity.input(Product, Schema.Struct({ id: Schema.String, quantity: Schema.Int }), {
1515
+ quantity: Entity.unmapped,
1516
+ }),
1517
+ { id: 'id', increment: { stock: 'quantity' } },
1518
+ ),
1519
+ }
1520
+ -->
1521
+
1522
+ ```ts
1523
+ const report = Laws.check({ writes: [Rename, Publish, Revert, Sell] })
1524
+ Laws.show(report)
1525
+ ```
1526
+
1527
+
1528
+ For the writes example, whose domain has a `reservedWithinStock` state
1529
+ invariant, a `publishedStaysPublished` transition invariant and an `Archived`
1530
+ state that the snippet above does not, it prints lines such as these (abridged;
1531
+ [`examples/writes/LAWS.md`](https://github.com/doeixd/foldkit-plus/blob/main/examples/writes/LAWS.md)
1532
+ keeps the whole report, so a write added changes a checked-in file):
1533
+
1534
+ ```text
1535
+ Product
1536
+ Draft -> Published Publish holds
1537
+ Published -> Draft Revert refused by publishedStaysPublished
1538
+ Archived -> Draft Revert undeclared
1539
+ Archived unreached
1540
+
1541
+ Rename x reservedWithinStock kept: writes no member it reads
1542
+ Revert x publishedStaysPublished refused: from {"status":"published"} it leaves {"status":"draft"}
1543
+ Sell x reservedWithinStock undecided: stock is incremented
1544
+ ```
1545
+
1546
+ One write against one invariant comes to one of three verdicts:
1547
+
1548
+ | Case | Verdict |
1549
+ | --- | --- |
1550
+ | A state invariant, and the write writes no member it reads | `Kept`, by disjointness |
1551
+ | Every member it reads is finite (a literal, a union of literals, a boolean, with or without null), and the write changes each only by setting it | Enumerated: `Kept`, or `Refused` with the rows that break it |
1552
+ | Anything else: a number, free text, an increment, a computed field, a link, an operator the table lacks, more than 4,096 rows | `Undecided`, with the reason |
1553
+
1554
+ A transition invariant is never kept by disjointness: `after.count >
1555
+ before.count` is broken by every write that leaves `count` alone. Rows are not
1556
+ filtered by the invariants before enumeration, since a row may be invalid
1557
+ before a write; a row the write's `when` (and `from`) definitely refuses is
1558
+ dropped, and one it cannot judge stays.
1559
+
1560
+ The findings (`holds`, `enforced`, `undeclared`, `refused`, `unreached`,
1561
+ `terminal`) are reports, never faults: a write an invariant can refuse is
1562
+ legitimate. `enforced` (`* -> InStock Sell enforced`) is a `becomes` held by
1563
+ its postcondition where the write commits, and that postcondition is a pair of
1564
+ the write alone (`Sell x becomes:InStock`).
1565
+
1566
+ A transition that is no declared write (another package's command, an
1567
+ import) is an entry with a `Footprint`: what its author says it writes, or
1568
+ `Footprint.unknown`, which writes every member and is `Undecided` against
1569
+ every invariant:
1570
+
1571
+ ```ts
1572
+ Laws.check({
1573
+ writes: [
1574
+ { name: 'Touch', entity: Product, footprint: Footprint.declared({ writes: [Product.fields.name], by: 'the import' }) },
1575
+ { name: 'Import', entity: Product, footprint: Footprint.unknown },
1576
+ ],
1577
+ })
1578
+ ```
1579
+
1580
+ A declared footprint names fields by reference, so one of another Entity is a
1581
+ type error where the entry names its Entity. It keeps a state invariant only
1582
+ by disjointness, and decides no transition invariant. `Write.footprint(write)`
1583
+ is a declared write's own.
1584
+
1585
+ #### Evidence, and the graph's facts
1586
+
1587
+ A pair the check keeps by reading the declarations (by disjointness, by
1588
+ enumeration, a create against a transition invariant, a delete) carries an
1589
+ `Enumerated` record in `evidence`, issued by `foldkit-entity/laws`. A pair
1590
+ kept on its author's word (`declared`), refused or undecided carries none:
1591
+ for those, the evidence is a walk through the writer, a scenario, or
1592
+ `Evidence.runtimeOnly` with its reason. These records are
1593
+ `foldkit-metadata`'s `Evidence`; the `Evidence` this package exports is an
1594
+ operator law's (`Tested`, `Proven`, [below](#laws-and-holding-an-implementation-to-them)).
1595
+
1596
+ ```ts
1597
+ import { Option } from 'effect'
1598
+ import { lawFactsOf } from 'foldkit-entity'
1599
+ import { Evidence } from 'foldkit-metadata'
1600
+
1601
+ const records = report.pairs.flatMap(pair => Option.toArray(pair.evidence))
1602
+ records.map(Evidence.issuedBy) // some('foldkit-entity/laws') for each kept pair
1603
+ Laws.transition(Rename) // 'write:Rename'
1604
+ const { nodes, edges } = Laws.facts(report)
1605
+ lawFactsOf([Rename]) // the same shape, read off the declarations, with no check run
1606
+ ```
1607
+
1608
+ Records and the graph name a transition `write:<name>` (`Laws.transition`)
1609
+ and a law `<Entity>.<id>` (`Laws.law(invariant)`), so `Laws.check` throws for
1610
+ two entries of one name. `lawId` and `transitionId` are the same two
1611
+ functions by name, in a module of their own, for code that must not carry the
1612
+ check.
1613
+ `Laws.facts(report)` is the law half of `foldkit-surface`'s graph as plain
1614
+ data in that graph's own shape (`GraphFacts`), since this package does not
1615
+ import Surface: a `Law` per invariant, a `Transition` per write in a pair or an
1616
+ arrow, a `State` per local state, `Reads` and `Writes` over `space: 'entity'`
1617
+ paths such as `['Product', 'stock']`, `From` and `To` per arrow, and a `Keeps`
1618
+ edge per transition and law whose every pair carries a record. A write's own
1619
+ `ensures` is marked `postcondition` on its pair and is no law of the Entity,
1620
+ so the facts leave it out; an `Unknown` footprint writes every member, so it
1621
+ has a `Writes` edge to each member a law of its Entity reads. A transition
1622
+ invariant (`pair.readsBefore`) also reads its whole row (`['Product']`), since
1623
+ a write leaving every member it reads alone can still break it.
1624
+ `lawFactsOf(entries)` gives the same shape from `Laws.check`'s entries without
1625
+ judging them, so not the same facts: a `State` for every state, local or not,
1626
+ `From` and `To` from each write's declared `from` and `becomes`, a `Writes`
1627
+ edge to every field for an `Unknown` footprint, and no `Keeps`. It is what Surface's `Graph.of` derives a contract's
1628
+ `laws.entities` with (a Remote domain declares its writes there), so only a
1629
+ page that asks for the graph carries it, and never the check.
1630
+
1374
1631
  ## Naming a question: operators
1375
1632
 
1376
1633
  What operators make possible, end to end (a rule named once, search and order
@@ -1403,16 +1660,14 @@ Query.show(PublicStories)
1403
1660
  // WHERE acme.published(Story.publishedAt)
1404
1661
  ```
1405
1662
 
1406
- - **It computes nothing of its own.** `definedAs` builds an expression from a
1407
- call's arguments, once per call, and every interpreter runs that expression
1408
- (`Expr.expanded` writes a predicate's calls out), so the operator needs no
1409
- SQL, no evaluator, and no support list. The SQL a body compiles to is the SQL
1410
- of the body written out by hand.
1411
- - **What it adds is a name.** `Query.show` prints the call, and
1412
- `Query.dependencies(body).operators` lists each operator a body uses.
1413
- - **It reads only its arguments.** A `definedAs` that closes over a field or an
1414
- input, instead of taking it, is refused when called: nothing asking what the
1415
- call reads (Guard's checks, Remote's matching) would see it.
1663
+ - **It computes nothing of its own, and reads only its arguments.**
1664
+ `definedAs` builds an expression from a call's arguments, once per call, and
1665
+ every interpreter runs that expression (`Expr.expanded` writes a predicate's
1666
+ calls out); one that closes over a field or an input instead of taking it is
1667
+ refused when called. `Query.show` prints the call, and
1668
+ `Query.dependencies(body).operators` lists each operator a body uses. The
1669
+ guide's [What the calls mean](../../docs/operators.md#what-the-calls-mean)
1670
+ says why.
1416
1671
  - **Arguments are checked by their stored form**, at compile time and when
1417
1672
  called: a field, scalar or plain value of the input's stored type, or a
1418
1673
  predicate where it takes a boolean. A boolean `output` makes a call a
@@ -1468,7 +1723,8 @@ refused where it is written.
1468
1723
  twice, or two under one name; `merge` refuses an overlap, and `override`
1469
1724
  replaces on purpose. `Operators.checked(table)` checks each answer against
1470
1725
  the operator's output schema, for tests. Nothing registers globally:
1471
- `evaluate`, `evaluateEach`, `decided`, `truthOver`, `Entity.judge`, `Entity.judgeInput` and
1726
+ `evaluate`, `evaluateEach`, `decided`, `truthOver`, `Entity.judge`,
1727
+ `Entity.judgeInput(input, value, { operators })` and
1472
1728
  `Entity.check(entity, { operators })` each take the table, `Operators.kernel`
1473
1729
  by default.
1474
1730
  - **Null is strict by default.** A null argument gives null (unknown for a
@@ -1546,7 +1802,7 @@ Operators.describeTable(recorded) // [{ name: 'acme.concat', …, laws, evidence
1546
1802
  first `Counterexample` with both sides and its collation: declaring `concat` commutative
1547
1803
  finds `"a"` and `"A"`, which give `"aA"` and `"Aa"`. Two sides that both refuse agree,
1548
1804
  but are no case: a record counts only cases whose sides both answered, and a law with
1549
- none is `Unanswered`, with the first refusal's reason, and records nothing.
1805
+ none is `Unanswered`, with the reason the first left side refused for, and records nothing.
1550
1806
  - **Evidence is an implementation's.** `Operators.withEvidence` refuses a record
1551
1807
  of an operator the table lacks or a law it does not declare, and a `Tested`
1552
1808
  record `Conformance.laws` did not make of this table's own implementation
@@ -1571,42 +1827,16 @@ generated from each argument's samples, null where its schema admits one, and
1571
1827
  text holding NUL, under `binary` and `asciiFold` where the operator compares
1572
1828
  text. `Conformance.memory(table)` is the reference interpreter's runner; a
1573
1829
  defined operator's expansion runs beside the others as `expansion`, a name an
1574
- implementation of it may not take. `foldkit-remote-drizzle`
1830
+ implementation of a defined operator may not take. `foldkit-remote-drizzle`
1575
1831
  runs the kernel's operators and an application's through it on SQLite and
1576
1832
  Postgres.
1577
1833
 
1578
- ### One operator, from declaration to description
1579
-
1580
- The `concat` above, as an application ships it: declared once, implemented for
1581
- each interpreter that runs it, held to itself, and described for whoever asks
1582
- what a server runs.
1834
+ ### Describing what a table runs
1583
1835
 
1584
- ```ts
1585
- import { sql } from 'drizzle-orm'
1586
- import { Operators } from 'foldkit-entity'
1587
- import { Conformance } from 'foldkit-entity/conformance'
1588
- import { DrizzleOperators } from 'foldkit-remote-drizzle'
1589
-
1590
- // In memory, as above; in SQL, for a binding (`bind(…, { operators: { memory, sql } })`).
1591
- const memory = Operators.memory(Operators.implement(concat, (left, right) => `${left}${right}`))
1592
- const sqlTable = DrizzleOperators.make(
1593
- DrizzleOperators.implement(concat, ({ args: [left, right] }) => sql`(${left} || ${right})`),
1594
- )
1595
-
1596
- // Its laws, against the memory implementation.
1597
- const held = Conformance.laws(concat, memory)
1598
-
1599
- // The two implementations against each other: an SQL runner selects
1600
- // `compileCall(call, binding, name)` from a database (foldkit-remote-drizzle's
1601
- // test/operatorConformance.test.ts has one); here the memory one alone.
1602
- const report = await Conformance.operator(concat, {
1603
- implementations: { memory: Conformance.memory(memory) },
1604
- })
1605
-
1606
- // Its signature as JSON: name, version, each argument and the result as a JSON
1607
- // Schema of what is stored, its null and collation rules, its laws.
1608
- Operators.describe(concat)
1609
- ```
1836
+ Declared once, implemented per interpreter, held to its laws and described for
1837
+ whoever asks what a server runs: the guide carries one operator the whole way
1838
+ ([An operator of your own](../../docs/operators.md#an-operator-of-your-own) to
1839
+ [Publishing what a server runs](../../docs/operators.md#publishing-what-a-server-runs)).
1610
1840
 
1611
1841
  `Operators.describe` gives an `OperatorDescription`, a Schema whose decoder
1612
1842
  checks a description another server publishes; it says what an operator takes
@@ -1618,6 +1848,24 @@ holding `acme.slug` does not answer a body calling `acme.slug@2`, and the
1618
1848
  refusal names both (`acme.slug@2 (this table has acme.slug)`), so a client and a
1619
1849
  server on different deploys see which side is behind.
1620
1850
 
1851
+ ## Limits
1852
+
1853
+ - The identifier is the field named `id`; no other field can be declared as it,
1854
+ because Remote keys its store by `id`.
1855
+ - A Selection has no filtering or ordering, and a page has no total; those
1856
+ belong to the interpreter that fetches.
1857
+ - A relation reaches only the entities of its own `Entity.relate` call; relate
1858
+ them again to add relations between them.
1859
+ - `target()` returns the entity as `relate` returned it: every member added
1860
+ since is on it (`likeCount`), but metadata annotated afterwards (`CmsPost`
1861
+ above) is on that new descriptor only, so annotate before relating when a
1862
+ target should carry it. Its type shows the members as related; read a later
1863
+ one as an `AnyEntity`.
1864
+ - A member is added once per Entity: two pipe chains from one descriptor that
1865
+ each add `score` are refused, as one chain adding it twice is. Adding the very
1866
+ spec again (`Guards.may` on a second view) is the member it added.
1867
+ - No registry: nothing checks that two different entities share a name.
1868
+
1621
1869
  ## API
1622
1870
 
1623
1871
  | Call | Meaning |
@@ -1630,8 +1878,17 @@ server on different deploys see which side is behind.
1630
1878
  | `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result; a tagged union of cases for a variant Entity whose `_tag` is selected. |
1631
1879
  | `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
1632
1880
  | `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
1633
- | `Write.update(input, { id, expect?, when?, increment? })` | A declared update of one row: every key the input maps to a field, but the id and the expected revision; `when`, what the row must hold for it to land; `increment`, the number fields it moves by an input amount. |
1634
- | `Write.insert(input, { id })` / `Write.delete(input, { id, expect?, when? })` | A declared insert under an id the client chose; a declared delete of one row, which sets nothing. |
1881
+ | `Write.update(input, { id, expect?, when?, from?, becomes?, increment? })` | A declared update of one row: every key the input maps to a field, but the id and the expected revision; `when`, what the row must hold for it to land; `from`, a state whose predicate joins the `when`; `becomes`, the state every row it starts from is in once it lands, proved where declared or else held where it commits (`ensures`); `increment`, the number fields it moves by an input amount. |
1882
+ | `Write.insert(input, { id, becomes? })` / `Write.delete(input, { id, expect?, when?, from? })` | A declared insert under an id the client chose; a declared delete of one row, which sets nothing. |
1883
+ | `Write.ensured(write)` | The postcondition a `becomes` enumeration could not decide holds the write to where it commits (`becomes:<State>`), for `Refusal.isInvalidBy`; throws for a write with none. |
1884
+ | `Write.footprint(write)` | What a write reads and writes of its row, by field key, as a `Footprint.Derived`. |
1885
+ | `Entity.refine(entity, name, { field: value } or ({ row }) => predicate)` | A named state of the row, declared on the Entity: `predicate`, `after`, `local`, `reads`, `is(row)`. |
1886
+ | `Entity.states(entity)` / `Entity.inState(state, row, operators?)` | Every state declared on an Entity; whether a stored row is in one (`Option`, none where it lacks a field the state reads). |
1887
+ | `Query.from(state)` | Every row in a state: the Entity's query with its predicate in `where`. |
1888
+ | `Laws.check({ writes, operators? })` / `Laws.show(report)` | Each write (`{ name, write }` or `{ name, entity, footprint }`) against each invariant of its Entity, and the arrows between its states, by enumeration over finite fields: a `LawReport` of `pairs` (each with its `Enumerated` `evidence`, if decided kept), `arrows`, `states` and `findings`; the report as text. |
1889
+ | `Laws.facts(report)` / `Laws.transition(entry)` / `Laws.law(invariant)` | The report as graph facts (`LawFacts`: `LawNode`s and `LawEdge`s); a transition's id (`write:Sell`) and a law's (`Product.reservedWithinStock`) in evidence and the graph. |
1890
+ | `lawFactsOf(entries)` | `Laws.check`'s entries as graph facts, read off the declarations with no check run: what `Graph.of` derives a contract's `laws.entities` with. |
1891
+ | `Footprint.declared({ reads?, writes, by })` / `Footprint.unknown` | What a transition that is no declared write reads and writes, on whose word; or nothing known, which writes every member. |
1635
1892
  | `Write.reads(write)` | The fields a write reads from its row: its `when`'s, each it increments, its assignments', the revision. |
1636
1893
  | `Write.update(input, { …, compute })` / `Computation` | A field computed from the row before the write and the input, carried as data. |
1637
1894
  | `Write.apply(row, bound, { operators })` / `Write.boundReads(bound)` | The row a bound write leaves, and what of the row before it that needs. |
@@ -1677,7 +1934,7 @@ server on different deploys see which side is behind.
1677
1934
  | `Operators.memory(...)` / `implement` / `implementHandlingNulls` / `merge` / `override` / `checked` / `kernel` | Tables of in-memory implementations of primitive operators, passed to `evaluate` and every judge. |
1678
1935
  | `Law.associative` / `commutative` / `idempotent` / `identity` / `absorbing` / `inverse` / `distributes` / `monotonic` / `preservesCollation` / `within` / `describe` | Laws an operator declares (`Expr.operator(id, { laws })`), checked where declared, described as JSON. |
1679
1936
  | `Operators.withEvidence(table, evidence)` / `describeTable(table)` / `Evidence.Proven` | What is known of a table's implementations' laws, and the table as JSON. |
1680
- | `Conformance.laws(op, table)` / `lawsBy(op, runner)` / `operator(op, { implementations })` / `memory(table)` (`foldkit-entity/conformance`) | Test an implementation's laws, in memory or through any runner; run one set of calls through several implementations. |
1937
+ | `Conformance.laws(op, table)` / `lawsBy(op, runner, { implementation })` (a Promise) / `operator(op, { implementations })` / `memory(table)` (`foldkit-entity/conformance`) | Test an implementation's laws, in memory or through any runner; run one set of calls through several implementations. |
1681
1938
  | `Operators.describe(op)` / `OperatorDescription` / `Query.operators(body)` | An operator's signature as JSON, the Schema it keeps, and the operators a body calls, by name. |
1682
1939
  | `valueOfOperand(node, { operators })` | What an operand, a call of literals say, comes to over no row. |
1683
1940
  | `Expr.expanded(predicate)` | The predicate with every call of a defined operator written out as what it means, deeply; what an interpreter compiles. |
@@ -1697,21 +1954,3 @@ server on different deploys see which side is behind.
1697
1954
  | `Query.dependencies(query)` | What the whole query reads, with its fields also split by role: `predicate` (can change which rows match) and `order` (can change where a row sits). |
1698
1955
  | `Query.unsupported(query, supported)` | The operations it needs that an interpreter does not run. |
1699
1956
  | `Query.show(query)` / `Expr.show(node)` | The query or expression as readable text, for a person and not for an interpreter. |
1700
-
1701
- ## Limits
1702
-
1703
- - The identifier is the field named `id`; no other field can be declared as it,
1704
- because Remote keys its store by `id`.
1705
- - A Selection has no filtering or ordering, and a page has no total; those
1706
- belong to the interpreter that fetches.
1707
- - A relation reaches only the entities of its own `Entity.relate` call; relate
1708
- them again to add relations between them.
1709
- - `target()` returns the entity as `relate` returned it: every member added
1710
- since is on it (`likeCount`), but metadata annotated afterwards (`CmsPost`
1711
- above) is on that new descriptor only, so annotate before relating when a
1712
- target should carry it. Its type shows the members as related; read a later
1713
- one as an `AnyEntity`.
1714
- - A member is added once per Entity: two pipe chains from one descriptor that
1715
- each add `score` are refused, as one chain adding it twice is. Adding the very
1716
- spec again (`Guards.may` on a second view) is the member it added.
1717
- - No registry: nothing checks that two different entities share a name.