foldkit-entity 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -372,14 +372,39 @@ key, a number; negative takes away) to the stored `stock`, in the statement that
372
372
  writes, so no concurrent change is lost. A retry must not add twice, so either it
373
373
  expects a revision (a retry of a write that landed is then a conflict), or its
374
374
  writer keeps a ledger, which answers the retry from its record and lets two
375
- concurrent increments both land. `RemoteServer.write` refuses one with neither. The field must
376
- be stored as a number, and may not be the id, the revision, or set by another
377
- key. `Write.bind` gives the amounts apart from the values (`increments`), so a
375
+ concurrent increments both land. `RemoteServer.write` refuses one with neither,
376
+ and one of a real number with no revision even under a ledger: floating-point
377
+ addition does not associate, so two concurrent sums could land as two results.
378
+ The field must be stored as a number, and may not be the id, the revision, or
379
+ set by another key. `Write.bind` gives the amounts apart from the values (`increments`), so a
378
380
  client can add them to the value it holds as it reads it (Remote does), never
379
381
  fixing a sum over a row that may since have moved. `Write.reads(write)` is what a write
380
- reads from its row: what its `when` reads, each field it increments, and the
381
- revision. How a declaration, its guard, its writer and the client fit together is
382
- the [declared writes guide](../../docs/declared-writes.md).
382
+ reads from its row: what its `when` reads, each field it increments, what its
383
+ assignments read, and the revision. How a declaration, its guard, its writer and
384
+ the client fit together is the [declared writes guide](../../docs/declared-writes.md).
385
+
386
+ An update may also compute a field from the row before it and the input:
387
+ `compute: { label: ({ row, input }) => concat(input.prefix, row.name) }`, with an
388
+ operator such as the `concat` [below](#operators-each-interpreter-implements). It
389
+ reads neither the row after the write nor another Entity, so assignments never
390
+ depend on each other, and is refused where it is declared for a field another
391
+ key writes or a value of a kind the field does not store. A defined operator in
392
+ it is expanded there, so `Write.bind` carries it as data (`assignments`, each a
393
+ `Computation`: fields by key, values encoded, operators by name), which a writer
394
+ compiles into the statement and a client predicts by its own table. A
395
+ computation does not repeat without effect, so a retry of one is held to it as
396
+ an increment's is; without a revision it lands only under a ledger, and there
397
+ only where the writer pins the row it read (a guarded writer with a `revision`)
398
+ or by an operator whose commutativity and associativity are tested over every
399
+ value for each implementation the writer runs (`Conformance.laws` in memory,
400
+ `Conformance.lawsBy` in SQL).
401
+
402
+ `Write.apply(row, bound, { operators })` is the row a bound write leaves over
403
+ the row before it: values set, amounts added (a null stays null, as in SQL),
404
+ assignments computed. It is the one computation of that row: a guard judges
405
+ it, a writer explains a miss by it, a client predicts it. `unknown` names each
406
+ field it could not work out (one the row lacks, or an operator the table lacks),
407
+ which keeps what the row holds.
383
408
 
384
409
  ## What every row and change must hold: invariants
385
410
 
@@ -787,6 +812,11 @@ in full confidence, and every test it does support still passes.
787
812
 
788
813
  ### Naming a question: operators
789
814
 
815
+ What operators make possible, end to end (a rule named once, search and order
816
+ the kernel lacks, writes that compute, one meaning checked across
817
+ interpreters), is the [operators guide](../../docs/operators.md); this section
818
+ and the next three are the reference.
819
+
790
820
  A predicate an application asks in many places (in a public query, a
791
821
  visitor's Read rule, an invariant) can be given a name. `Expr.operator`
792
822
  declares one by what a call of it means:
@@ -877,7 +907,7 @@ refused where it is written.
877
907
  twice, or two under one name; `merge` refuses an overlap, and `override`
878
908
  replaces on purpose. `Operators.checked(table)` checks each answer against
879
909
  the operator's output schema, for tests. Nothing registers globally:
880
- `evaluate`, `decided`, `truthOver`, `Entity.judge`, `Entity.judgeInput` and
910
+ `evaluate`, `evaluateEach`, `decided`, `truthOver`, `Entity.judge`, `Entity.judgeInput` and
881
911
  `Entity.check(entity, { operators })` each take the table, `Operators.kernel`
882
912
  by default.
883
913
  - **Null is strict by default.** A null argument gives null (unknown for a
@@ -901,6 +931,13 @@ refused where it is written.
901
931
  such a body. An invariant calling an operator its judge's table lacks is
902
932
  `Undecided` with that operator in `operators`, which a form passes and a
903
933
  server refuses to start without.
934
+ - **One refusing row refuses the run, unless each row is judged alone.**
935
+ `evaluate` refuses a run when any row holds what no interpreter answers for
936
+ (text with a NUL). `evaluateEach(body, input, rows, { operators })` sets such
937
+ a row aside in `refused` and still answers the others, in order; what no one
938
+ row causes (an operator the table lacks, an input the body reads holding a
939
+ NUL, order keys of different kinds) still refuses it. A client judging the
940
+ rows it holds wants the second.
904
941
  - **NUL is refused** in any text argument, and an implementation that throws
905
942
  is reported as a `QueryEvaluateError` naming its operator.
906
943
 
@@ -926,7 +963,7 @@ const table = Operators.memory(Operators.implement(concat, (left, right) => `${l
926
963
  const verdict = Conformance.laws(concat, table) // { _tag: 'Holds', evidence: [...] }
927
964
  const recorded =
928
965
  verdict._tag === 'Holds' ? Operators.withEvidence(table, verdict.evidence) : table
929
- Operators.describeTable(recorded) // [{ operator: 'acme.concat', laws, evidence }]
966
+ Operators.describeTable(recorded) // [{ name: 'acme.concat', …, laws, evidence }]
930
967
  ```
931
968
 
932
969
  - **A law is checked where it is declared.** `Law.commutative`, `associative`,
@@ -942,13 +979,27 @@ Operators.describeTable(recorded) // [{ operator: 'acme.concat', laws, evidence
942
979
  - **Testing is sampling, seeded.** Cases come from a fixed sample of each kind
943
980
  (the empty string, mixed case, non-ASCII and astral text; zero, negatives, a
944
981
  fraction), kept where the schemas decode them, up to `cases` (200) a law
945
- chosen by `seed` (0). The verdict is `Holds` with one `Tested` record a law,
946
- or the first `Counterexample` with both sides: declaring `concat` commutative
982
+ chosen by `seed` (0), under each of `binary` and `asciiFold` where the
983
+ operator or a witness its law calls compares text (so a record of such a law
984
+ counts twice the cases). The verdict is `Holds` with one `Tested` record a law, or the
985
+ first `Counterexample` with both sides and its collation: declaring `concat` commutative
947
986
  finds `"a"` and `"A"`, which give `"aA"` and `"Aa"`.
948
987
  - **Evidence is an implementation's.** `Operators.withEvidence` refuses a record
949
- of an operator the table lacks or a law it does not declare; `override` drops
950
- a replaced implementation's records, `merge` keeps both tables'.
951
- `Evidence.Proven` records a proof made elsewhere, never checked here.
988
+ of an operator the table lacks or a law it does not declare, and a `Tested`
989
+ record `Conformance.laws` did not make of this table's own implementation
990
+ (`Operators.testedOn(record)` names the one it did); `override` drops a
991
+ replaced implementation's records, and those of a law that called it as a
992
+ witness (`inverse`, `distributes`); `merge` keeps both tables'. An SQL table
993
+ (`DrizzleOperators.withEvidence`) takes only records `Conformance.lawsBy`
994
+ made (`Operators.testedByRunner`): not one built by hand, copied, or tested
995
+ in memory. Which runner made it, the database's or another, is the caller's
996
+ word, so run it over the table's own SQL (`compileCall`). `Evidence.Proven`
997
+ records a proof made elsewhere, never checked here. A law's domain is
998
+ described as a JSON Schema with the definitions it refers to.
999
+ - **A defined operator's laws describe it; nothing records them.** It has no
1000
+ implementation to hold evidence. A write computing through it is expanded
1001
+ first, so it commutes by the primitive operator it calls, by that one's
1002
+ evidence.
952
1003
 
953
1004
  `Conformance.operator(op, { implementations })` runs one set of calls through
954
1005
  every implementation given and reports where they disagree, a refusal included:
@@ -959,6 +1010,49 @@ defined operator's expansion runs beside the others. `foldkit-remote-drizzle`
959
1010
  runs the kernel's operators and an application's through it on SQLite and
960
1011
  Postgres.
961
1012
 
1013
+ ### One operator, from declaration to description
1014
+
1015
+ The `concat` above, as an application ships it: declared once, implemented for
1016
+ each interpreter that runs it, held to itself, and described for whoever asks
1017
+ what a server runs.
1018
+
1019
+ ```ts
1020
+ import { sql } from 'drizzle-orm'
1021
+ import { Operators } from 'foldkit-entity'
1022
+ import { Conformance } from 'foldkit-entity/conformance'
1023
+ import { DrizzleOperators } from 'foldkit-remote-drizzle'
1024
+
1025
+ // In memory, as above; in SQL, for a binding (`bind(…, { operators: { memory, sql } })`).
1026
+ const memory = Operators.memory(Operators.implement(concat, (left, right) => `${left}${right}`))
1027
+ const sqlTable = DrizzleOperators.make(
1028
+ DrizzleOperators.implement(concat, ({ args: [left, right] }) => sql`(${left} || ${right})`),
1029
+ )
1030
+
1031
+ // Its laws, against the memory implementation.
1032
+ const held = Conformance.laws(concat, memory)
1033
+
1034
+ // The two implementations against each other: an SQL runner selects
1035
+ // `compileCall(call, binding, name)` from a database (foldkit-remote-drizzle's
1036
+ // test/operatorConformance.test.ts has one); here the memory one alone.
1037
+ const report = await Conformance.operator(concat, {
1038
+ implementations: { memory: Conformance.memory(memory) },
1039
+ })
1040
+
1041
+ // Its signature as JSON: name, version, each argument and the result as a JSON
1042
+ // Schema of what is stored, its null and collation rules, its laws.
1043
+ Operators.describe(concat)
1044
+ ```
1045
+
1046
+ `Operators.describe` gives an `OperatorDescription`, a Schema whose decoder
1047
+ checks a description another server publishes; it says what an operator takes
1048
+ and keeps, never a defined operator's body. `Operators.describeTable(table)`
1049
+ lists each operator a table implements so, with its evidence, and
1050
+ `Query.operators(body)` names each operator a body calls (a defined one and the
1051
+ primitive ones it calls). A version is part of an operator's name: a table
1052
+ holding `acme.slug` does not answer a body calling `acme.slug@2`, and the
1053
+ refusal names both (`acme.slug@2 (this table has acme.slug)`), so a client and a
1054
+ server on different deploys see which side is behind.
1055
+
962
1056
  ### Reading one back
963
1057
 
964
1058
  `Query.show(query)` renders a body as text, one clause per line:
@@ -997,7 +1091,9 @@ from queries, not from what a database could express.
997
1091
  | `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
998
1092
  | `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
999
1093
  | `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. |
1000
- | `Write.reads(write)` | The fields a write reads from its row: its `when`'s, each it increments, the revision. |
1094
+ | `Write.reads(write)` | The fields a write reads from its row: its `when`'s, each it increments, its assignments', the revision. |
1095
+ | `Write.update(input, { …, compute })` / `Computation` | A field computed from the row before the write and the input, carried as data. |
1096
+ | `Write.apply(row, bound, { operators })` / `Write.boundReads(bound)` | The row a bound write leaves, and what of the row before it that needs. |
1001
1097
  | `Write.writes(write)` / `Write.bind(write, value, keys?)` | The fields it may change; the row and values one input writes, encoded as the store holds them. |
1002
1098
  | `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
1003
1099
  | `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
@@ -1012,19 +1108,20 @@ from queries, not from what a database could express.
1012
1108
  | `Entity.is(value)` | Whether a value is an Entity descriptor. |
1013
1109
  | `Expr.eq(left, right)` | Two values are the same: a field (or an expression) on the left, and the value on the right, which is typed from it; a predicate may stand where a boolean is wanted. A plain value on the left is a compile error that says so. |
1014
1110
  | `Expr.isNull(field)` / `Expr.isNotNull(field)` | Whether a value is absent; one node, with the answer absence gives flipped. |
1015
- | `Expr.contains(field, search)` | Whether text contains text, over a text or nullable-text operand only. Containing the empty string is everything, but a null contains nothing. |
1111
+ | `Expr.contains(field, search)` | Whether text contains a value or an input's text, over a text or nullable-text operand only. Containing the empty string is everything, but a null contains nothing. |
1016
1112
  | `Expr.in(field, among)` | Whether a value is one of a list (written out, or an input), each compared as `eq` compares; SQL's `in`, an empty list matching nothing. |
1017
1113
  | `Expr.and(a, b, …)` / `Expr.or(a, b, …)` | Every operand holds / at least one does, as SQL's three-valued `and` and `or`. At least one operand; a nested one of the same kind is flattened in. |
1018
1114
  | `Expr.not(predicate)` | The predicate does not hold; an unknown stays unknown, so a null matches neither side. |
1019
1115
  | `Expr.lt` / `lte` / `gt` / `gte(left, right, { collation? })` | One value orders before or after the other. Numbers as numbers; text only under `binary` or `asciiFold` (the field's declared collation, or the one given), and only against a field. |
1020
1116
  | `Expr.whenGiven(input, given => predicate)` | A filter applying only when a nullable input is given: `or(isNull(input), predicate)`, the predicate seeing the input as never null. |
1021
- | `Expr.operator(id, { input, output, definedAs, version?, description? })` | An operator defined by what a call means; calling it builds a `Test` predicate (a boolean output) or a `Call` scalar, whose expansion every interpreter runs. |
1117
+ | `Expr.operator(id, { input, output, definedAs?, version?, description?, nulls?, collation?, laws? })` | An operator: defined by what a call means (`definedAs`, whose expansion every interpreter runs) or primitive (each interpreter's table implements it). Calling it builds a `Test` predicate (a boolean output) or a `Call` scalar. |
1022
1118
  | `Expr.unsupported(nodes, { operations, operators })` | What these expressions need that an interpreter lacks: operations, then primitive operators by name. |
1023
1119
  | `Text.startsWith(text, prefix, { collation? })` | Whether text begins with a prefix, under its collation; the kernel's primitive operator. |
1024
1120
  | `Operators.memory(...)` / `implement` / `implementHandlingNulls` / `merge` / `override` / `checked` / `kernel` | Tables of in-memory implementations of primitive operators, passed to `evaluate` and every judge. |
1025
1121
  | `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. |
1026
1122
  | `Operators.withEvidence(table, evidence)` / `describeTable(table)` / `Evidence.Proven` | What is known of a table's implementations' laws, and the table as JSON. |
1027
- | `Conformance.laws(op, table)` / `operator(op, { implementations })` / `memory(table)` (`foldkit-entity/conformance`) | Test an implementation's laws; run one set of calls through several implementations. |
1123
+ | `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. |
1124
+ | `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. |
1028
1125
  | `valueOfOperand(node, { operators })` | What an operand, a call of literals say, comes to over no row. |
1029
1126
  | `Expr.expanded(predicate)` | The predicate with every call of a defined operator written out as what it means, deeply; what an interpreter compiles. |
1030
1127
  | `Expr.field(field)` | One field of one Entity, as a scalar. |
@@ -1,4 +1,4 @@
1
- import { Ct as AnyQuery, Kt as Operator, Wt as Operandish, _t as MemoryOperators, bt as TestedEvidence, gn as LawDescription, s as Entity, vn as Collation } from "../index-B9fbDo_-.mjs";
1
+ import { $t as Operator, At as AnyQuery, Ct as MemoryOperators, Dt as TestedEvidence, En as Collation, Zt as Operandish, s as Entity, wn as LawDescription } from "../index-hu8IYlNc.mjs";
2
2
  import { Data, Option, Schema } from "effect";
3
3
  /** What an implementation said of one call: a value, or that it refused it. */
4
4
  export type Outcome = Data.TaggedEnum<{
@@ -70,6 +70,8 @@ export type LawsVerdict = Data.TaggedEnum<{
70
70
  Counterexample: {
71
71
  readonly law: LawDescription;
72
72
  readonly args: ReadonlyArray<unknown>;
73
+ /** The collation the calls were made under, for an operator that compares text. */
74
+ readonly collation: Option.Option<Collation>;
73
75
  readonly left: Outcome;
74
76
  readonly right: Outcome;
75
77
  };
@@ -79,6 +81,7 @@ export declare const LawsVerdict: {
79
81
  readonly _tag: "Counterexample";
80
82
  readonly law: LawDescription;
81
83
  readonly args: ReadonlyArray<unknown>;
84
+ readonly collation: Option.Option<Collation>;
82
85
  readonly left: Outcome;
83
86
  readonly right: Outcome;
84
87
  }, {
@@ -94,6 +97,7 @@ export declare const LawsVerdict: {
94
97
  readonly _tag: "Counterexample";
95
98
  readonly law: LawDescription;
96
99
  readonly args: ReadonlyArray<unknown>;
100
+ readonly collation: Option.Option<Collation>;
97
101
  readonly left: Outcome;
98
102
  readonly right: Outcome;
99
103
  } | {
@@ -105,6 +109,7 @@ export declare const LawsVerdict: {
105
109
  readonly _tag: "Counterexample";
106
110
  readonly law: LawDescription;
107
111
  readonly args: ReadonlyArray<unknown>;
112
+ readonly collation: Option.Option<Collation>;
108
113
  readonly left: Outcome;
109
114
  readonly right: Outcome;
110
115
  } | {
@@ -115,6 +120,7 @@ export declare const LawsVerdict: {
115
120
  readonly _tag: "Counterexample";
116
121
  readonly law: LawDescription;
117
122
  readonly args: ReadonlyArray<unknown>;
123
+ readonly collation: Option.Option<Collation>;
118
124
  readonly left: Outcome;
119
125
  readonly right: Outcome;
120
126
  } | {
@@ -126,6 +132,7 @@ export declare const LawsVerdict: {
126
132
  readonly _tag: "Counterexample";
127
133
  readonly law: LawDescription;
128
134
  readonly args: ReadonlyArray<unknown>;
135
+ readonly collation: Option.Option<Collation>;
129
136
  readonly left: Outcome;
130
137
  readonly right: Outcome;
131
138
  } | {
@@ -137,6 +144,7 @@ export declare const LawsVerdict: {
137
144
  readonly _tag: "Counterexample";
138
145
  readonly law: LawDescription;
139
146
  readonly args: ReadonlyArray<unknown>;
147
+ readonly collation: Option.Option<Collation>;
140
148
  readonly left: Outcome;
141
149
  readonly right: Outcome;
142
150
  }, "_tag">;
@@ -167,15 +175,25 @@ export declare const Conformance: {
167
175
  /**
168
176
  * Tests every law `op` declares against `operators`' implementation of it,
169
177
  * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law
170
- * of both sides checks each tuple from each. Holds
171
- * with a `Tested` record a law, which `Operators.withEvidence` keeps; or the
172
- * first case a law fails, with both sides.
178
+ * of both sides checks each tuple from each. Holds with a `Tested` record a
179
+ * law, which `Operators.withEvidence` keeps; or the first case a law fails,
180
+ * with both sides.
173
181
  */
174
182
  laws: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(op: Operator<In, Out>, operators: MemoryOperators, options?: {
175
183
  readonly implementation?: string | undefined;
176
184
  readonly cases?: number | undefined;
177
185
  readonly seed?: number | undefined;
178
186
  }) => LawsVerdict;
187
+ /**
188
+ * As `laws`, each call run by `run` instead of a memory table: an SQL
189
+ * implementation selected from a database, say, whose evidence a binding's
190
+ * SQL table records. A throw is a refusal.
191
+ */
192
+ lawsBy: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(op: Operator<In, Out>, run: Runner, options: {
193
+ readonly implementation: string;
194
+ readonly cases?: number | undefined;
195
+ readonly seed?: number | undefined;
196
+ }) => Promise<LawsVerdict>;
179
197
  /**
180
198
  * Runs one set of calls of `op` through every implementation and compares
181
199
  * what each answered or refused. The calls are `cases` (argument tuples, as
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/conformance/operator.ts","../../src/conformance/index.ts"],"mappings":";;;YA8BY,UAAU,KAAK;EACzB;aAAkB;;EAClB;aAAoB;;;qBAET;;;aAFiB;;;;;aADH;;;;;;;eACG;;;eADH;;;;;;;;;;;;eACG;;;eADH;;;;;;;;;;;;;aACG;;;;aADH;;;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;aAEV,iBAAiB,SAAS,eAAe;aACzC,QAAQ,cAAc;aACtB;aACA;aACA,iBAAiB;QAE3B,QAAQ;;;qBCjdA,SAAO;;;;;;;;;;;;;;;iBAmBH;WACN;WACA;WACA;WACA;;WAEA;YACC;;qBAGC,MAAM,cAAc;iBAQhB;;WAEN;WACA,MAAM;;;;;;;WAON,OAAO,SAAS;;WAEhB,UAAU;;qBAwCR,OAAO,cAAc;;;;;;qBAqfrB,gBAAgB,cAAc;;;;;iBA0D1B;WACN;WACA,MAAM;;WAEN,OAAO,SAAS;;qBAKd,UAAU,cAAc;;qBAuBxB,mBAAmB,cAAc"}
@@ -1,4 +1,4 @@
1
- import { A as Law, C as Expr, S as Text, T as Query, b as Evidence, f as QueryEvaluateError, j as Collation, n as Entity, w as Order, x as Operators, y as valueOfOperand } from "../src-CSxcKUv6.mjs";
1
+ import { A as Query, D as stampTested, E as stampRun, I as Law, O as Expr, S as Evidence, T as Text, f as QueryEvaluateError, k as Order, n as Entity, w as Operators, x as valueOfOperand, z as Collation } from "../src-DBAilaDV.mjs";
2
2
  import { Data, Option, Schema, SchemaAST, SchemaGetter } from "effect";
3
3
  // src/conformance/operator.ts
4
4
  /**
@@ -79,117 +79,232 @@ const chosen$1 = (tuples, limit, seed) => {
79
79
  }
80
80
  return shuffled.slice(0, limit);
81
81
  };
82
+ /** A plain object: what JSON makes, and nothing whose data sits in a prototype. */
83
+ const isRecord = (value) => {
84
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
85
+ const prototype = Object.getPrototypeOf(value);
86
+ return prototype === Object.prototype || prototype === null;
87
+ };
88
+ /** A plain object's keys holding a value: one holding `undefined` is as absent, as JSON writes it. */
89
+ const keysOf = (record) => Object.keys(record).filter((key) => record[key] !== void 0);
90
+ /**
91
+ * Two stored values alike, structurally. Not by their JSON, which writes
92
+ * `Infinity` and `NaN` as `null`: a division by zero answering `Infinity` in
93
+ * memory and null in SQL would read as agreeing. An object that is not plain
94
+ * (its data in a prototype: a Date) is compared by its JSON, a Date's its time.
95
+ */
96
+ const sameValue = (left, right) => {
97
+ if (typeof left === "number" && typeof right === "number") return left === right || Number.isNaN(left) && Number.isNaN(right);
98
+ if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((each, i) => sameValue(each, right[i]));
99
+ if (isRecord(left) && isRecord(right)) {
100
+ const keys = keysOf(left);
101
+ return keys.length === keysOf(right).length && keys.every((key) => Object.hasOwn(right, key) && sameValue(left[key], right[key]));
102
+ }
103
+ if (typeof left === "object" && left !== null && typeof right === "object" && right !== null) return JSON.stringify(left) === JSON.stringify(right);
104
+ return left === right;
105
+ };
82
106
  /** Two outcomes alike: equal values as stored, or both refusals. */
83
- const same = (left, right) => left._tag === "Refused" || right._tag === "Refused" ? left._tag === right._tag : JSON.stringify(left.value) === JSON.stringify(right.value);
107
+ const same = (left, right) => left._tag === "Refused" || right._tag === "Refused" ? left._tag === right._tag : sameValue(left.value, right.value);
108
+ /** Text by code point, as every interpreter's `binary` orders it; `<` compares UTF-16 units. */
109
+ const byCodePoint = (left, right) => {
110
+ const [a, b] = [[...left], [...right]];
111
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
112
+ const sign = a[i].codePointAt(0) - b[i].codePointAt(0);
113
+ if (sign !== 0) return sign;
114
+ }
115
+ return a.length - b.length;
116
+ };
84
117
  /** Two values of one kind in order: numbers, booleans, text by code point. */
85
- const order = (left, right) => typeof left === "string" && typeof right === "string" ? left < right ? -1 : left > right ? 1 : 0 : Number(left) - Number(right);
118
+ const orderOf = (left, right) => typeof left === "string" && typeof right === "string" ? byCodePoint(left, right) : Number(left) - Number(right);
86
119
  /** A call of `op`, given `collation` when its rule takes one. */
87
120
  const callOf = (op, args, collation) => Option.match(collation, {
88
121
  onNone: () => op(...args),
89
122
  onSome: (each) => op(...args, { collation: each })
90
123
  });
91
124
  const foldText = (value) => typeof value === "string" ? Collation.foldAscii(value) : value;
92
- const Conformance = {
93
- /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */
94
- memory: (operators) => (call) => valueOfOperand(call, { operators }),
95
- /**
96
- * Tests every law `op` declares against `operators`' implementation of it,
97
- * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law
98
- * of both sides checks each tuple from each. Holds
99
- * with a `Tested` record a law, which `Operators.withEvidence` keeps; or the
100
- * first case a law fails, with both sides.
101
- */
102
- laws: (op, operators, options = {}) => {
103
- const operator = op;
104
- const { descriptor } = operator;
105
- const limit = options.cases ?? 200;
106
- const seed = options.seed ?? 0;
107
- const name = descriptor.version === 1 ? descriptor.id : `${descriptor.id}@${descriptor.version}`;
108
- const collation = descriptor.collation === "none" ? Option.none() : Option.some(Collation.binary);
109
- const outcome = (node) => {
110
- try {
111
- return Outcome.Value({ value: valueOfOperand(node, { operators }) });
112
- } catch (error) {
113
- if (error instanceof QueryEvaluateError) return Outcome.Refused({ reason: error.message });
114
- throw error;
115
- }
116
- };
117
- const call = (...args) => callOf(operator, args, collation);
118
- const check = (args, left, right) => ({
119
- args,
120
- left,
121
- right,
122
- holds: same(left, right)
123
- });
124
- const evidence = [];
125
- for (const law of descriptor.laws) {
126
- const shared = samplesOf(descriptor.input, law.domain);
127
- const tuples = (arity) => chosen$1(product(Array.from({ length: arity }, () => shared)), limit, seed);
128
- const sided = (value, side, answer) => tuples(1).flatMap(([a]) => [...side === "right" ? [] : [check([value, a], outcome(call(value, a)), Outcome.Value({ value: answer(a) }))], ...side === "left" ? [] : [check([a, value], outcome(call(a, value)), Outcome.Value({ value: answer(a) }))]]);
129
- const checks = Law.$match(law, {
130
- Associative: () => tuples(3).map(([a, b, c]) => check([
125
+ const nameOf = (op) => op.descriptor.version === 1 ? op.descriptor.id : `${op.descriptor.id}@${op.descriptor.version}`;
126
+ /**
127
+ * The equations of every law `op` declares, over up to `limit` tuples a law
128
+ * chosen by `seed`. Nothing is run: a memory table and an SQL runner
129
+ * evaluate the same plans.
130
+ */
131
+ const lawPlans = (op, limit, seed) => {
132
+ const { descriptor } = op;
133
+ const comparesText = (each) => each.descriptor.collation !== "none";
134
+ const under = (each, collation) => comparesText(each) ? collation : Option.none();
135
+ const run = (node) => ({
136
+ node,
137
+ fold: false
138
+ });
139
+ const value = (held) => ({ value: held });
140
+ return descriptor.laws.map((law) => {
141
+ const shared = samplesOf(descriptor.input, law.domain);
142
+ const tuples = (arity) => chosen$1(product(Array.from({ length: arity }, () => shared)), limit, seed);
143
+ const plans = ([op, ...Law.$match(law, {
144
+ Inverse: ({ other }) => [other],
145
+ Distributes: ({ over }) => [over],
146
+ Associative: () => [],
147
+ Commutative: () => [],
148
+ Idempotent: () => [],
149
+ Identity: () => [],
150
+ Absorbing: () => [],
151
+ Monotonic: () => [],
152
+ PreservesCollation: () => []
153
+ })].some(comparesText) ? [Option.some(Collation.binary), Option.some(Collation.asciiFold)] : [Option.none()]).flatMap((collation) => {
154
+ const call = (...args) => callOf(op, args, under(op, collation));
155
+ const witness = (other, ...args) => callOf(other, args, under(other, collation));
156
+ const equal = (args, left, right) => ({
157
+ args,
158
+ collation,
159
+ left,
160
+ right,
161
+ holds: same
162
+ });
163
+ const sided = (witness, side, answer) => tuples(1).flatMap(([a]) => [...side === "right" ? [] : [equal([witness, a], run(call(witness, a)), value(answer(a)))], ...side === "left" ? [] : [equal([a, witness], run(call(a, witness)), value(answer(a)))]]);
164
+ return Law.$match(law, {
165
+ Associative: () => tuples(3).map(([a, b, c]) => equal([
131
166
  a,
132
167
  b,
133
168
  c
134
- ], outcome(call(call(a, b), c)), outcome(call(a, call(b, c))))),
135
- Commutative: () => tuples(2).map(([a, b]) => check([a, b], outcome(call(a, b)), outcome(call(b, a)))),
136
- Idempotent: () => tuples(1).map(([a]) => check([a], outcome(call(a, a)), Outcome.Value({ value: a }))),
137
- Identity: ({ value, side }) => sided(value, side, (a) => a),
138
- Absorbing: ({ value, side }) => sided(value, side, () => value),
139
- Inverse: ({ other, identity }) => tuples(1).map(([a]) => check([a], outcome(call(a, other(a))), Outcome.Value({ value: identity }))),
140
- Distributes: ({ over }) => tuples(3).map(([a, b, c]) => check([
169
+ ], run(call(call(a, b), c)), run(call(a, call(b, c))))),
170
+ Commutative: () => tuples(2).map(([a, b]) => equal([a, b], run(call(a, b)), run(call(b, a)))),
171
+ Idempotent: () => tuples(1).map(([a]) => equal([a], run(call(a, a)), value(a))),
172
+ Identity: ({ value: witness, side }) => sided(witness, side, (a) => a),
173
+ Absorbing: ({ value: witness, side }) => sided(witness, side, () => witness),
174
+ Inverse: ({ other, identity }) => tuples(1).map(([a]) => equal([a], run(call(a, witness(other, a))), value(identity))),
175
+ Distributes: ({ over }) => tuples(3).map(([a, b, c]) => equal([
141
176
  a,
142
177
  b,
143
178
  c
144
- ], outcome(call(a, over(b, c))), outcome(over(call(a, b), call(a, c))))),
179
+ ], run(call(a, witness(over, b, c))), run(witness(over, call(a, b), call(a, c))))),
145
180
  Monotonic: ({ direction, position }) => {
181
+ const under = (held) => Option.exists(collation, (each) => each._tag === "AsciiFold") ? foldText(held) : held;
182
+ const order = (left, right) => orderOf(under(left), under(right));
146
183
  const each = descriptor.input.map((schema) => samplesOf([schema], law.domain));
147
184
  const pairs = each[position].flatMap((low) => each[position].filter((high) => order(low, high) < 0).map((high) => [low, high]));
148
185
  const rest = product(each.filter((_, index) => index !== position));
186
+ const sign = direction === "increasing" ? 1 : -1;
149
187
  return chosen$1(product([pairs, rest]), limit, seed).map(([pair, others]) => {
150
188
  const [low, high] = pair;
151
- const at = (value) => {
189
+ const at = (held) => {
152
190
  const args = [...others];
153
- args.splice(position, 0, value);
191
+ args.splice(position, 0, held);
154
192
  return args;
155
193
  };
156
- const left = outcome(call(...at(low)));
157
- const right = outcome(call(...at(high)));
158
- const sign = direction === "increasing" ? 1 : -1;
159
194
  return {
160
195
  args: at(low),
161
- left,
162
- right,
163
- holds: left._tag === "Value" && right._tag === "Value" && sign * order(left.value, right.value) <= 0
196
+ collation,
197
+ left: run(call(...at(low))),
198
+ right: run(call(...at(high))),
199
+ holds: (left, right) => left._tag === "Value" && right._tag === "Value" && sign * order(left.value, right.value) <= 0
164
200
  };
165
201
  });
166
202
  },
167
- PreservesCollation: () => tuples(2).map(([a, b]) => {
168
- const folded = (node) => Outcome.$match(outcome(node), {
169
- Value: ({ value }) => Outcome.Value({ value: foldText(value) }),
170
- Refused: (refused) => refused
171
- });
172
- const under = (x, y) => callOf(operator, [x, y], Option.some(Collation.asciiFold));
173
- return check([a, b], folded(under(a, b)), folded(under(foldText(a), foldText(b))));
174
- })
203
+ PreservesCollation: () => Option.exists(collation, (each) => each._tag === "AsciiFold") ? tuples(2).map(([a, b]) => equal([a, b], {
204
+ node: call(a, b),
205
+ fold: true
206
+ }, {
207
+ node: call(foldText(a), foldText(b)),
208
+ fold: true
209
+ })) : []
175
210
  });
176
- if (checks.length === 0) throw new Error(`[foldkit-entity] Conformance.laws: no sample of ${name}'s arguments is in ${Law.describe(law).kind}'s domain`);
177
- const failed = checks.find((each) => !each.holds);
178
- if (failed !== void 0) return LawsVerdict.Counterexample({
179
- law: Law.describe(law),
180
- args: failed.args,
181
- left: failed.left,
182
- right: failed.right
211
+ });
212
+ if (plans.length === 0) throw new Error(`[foldkit-entity] Conformance.laws: no sample of ${nameOf(op)}'s arguments is in ${Law.describe(law).kind}'s domain`);
213
+ return {
214
+ law: Law.describe(law),
215
+ plans
216
+ };
217
+ });
218
+ };
219
+ /**
220
+ * The verdict over laws whose calls' outcomes `answered` gives: the first
221
+ * failure, or evidence of each.
222
+ */
223
+ const verdictOf = (op, laws, answered, options) => {
224
+ const outcomes = (side) => {
225
+ if ("value" in side) return Outcome.Value({ value: side.value });
226
+ const outcome = answered(side.node);
227
+ return side.fold ? Outcome.$match(outcome, {
228
+ Value: ({ value }) => Outcome.Value({ value: foldText(value) }),
229
+ Refused: (refused) => refused
230
+ }) : outcome;
231
+ };
232
+ const evidence = [];
233
+ for (const { law, plans } of laws) {
234
+ for (const plan of plans) {
235
+ const left = outcomes(plan.left);
236
+ const right = outcomes(plan.right);
237
+ if (!plan.holds(left, right)) return LawsVerdict.Counterexample({
238
+ law,
239
+ args: plan.args,
240
+ collation: plan.collation,
241
+ left,
242
+ right
183
243
  });
184
- evidence.push(Evidence.Tested({
185
- operator: name,
186
- law: Law.describe(law),
187
- implementation: options.implementation ?? "memory",
188
- cases: checks.length,
189
- seed
190
- }));
191
244
  }
192
- return LawsVerdict.Holds({ evidence });
245
+ evidence.push(Evidence.Tested({
246
+ operator: nameOf(op),
247
+ law,
248
+ implementation: options.implementation,
249
+ cases: plans.length,
250
+ seed: options.seed
251
+ }));
252
+ }
253
+ return LawsVerdict.Holds({ evidence });
254
+ };
255
+ const Conformance = {
256
+ /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */
257
+ memory: (operators) => (call) => valueOfOperand(call, { operators }),
258
+ /**
259
+ * Tests every law `op` declares against `operators`' implementation of it,
260
+ * up to `cases` tuples a law (200 by default), chosen by `seed` (0); a law
261
+ * of both sides checks each tuple from each. Holds with a `Tested` record a
262
+ * law, which `Operators.withEvidence` keeps; or the first case a law fails,
263
+ * with both sides.
264
+ */
265
+ laws: (op, operators, options = {}) => {
266
+ const operator = op;
267
+ const seed = options.seed ?? 0;
268
+ const outcome = (node) => {
269
+ try {
270
+ return Outcome.Value({ value: valueOfOperand(node, { operators }) });
271
+ } catch (error) {
272
+ if (error instanceof QueryEvaluateError) return Outcome.Refused({ reason: error.message });
273
+ throw error;
274
+ }
275
+ };
276
+ const verdict = verdictOf(operator, lawPlans(operator, options.cases ?? 200, seed), outcome, {
277
+ implementation: options.implementation ?? "memory",
278
+ seed
279
+ });
280
+ const tested = operators.implementations.find((each) => each.operator === operator.descriptor);
281
+ if (verdict._tag === "Holds" && tested !== void 0) verdict.evidence.forEach((record) => stampTested(record, tested));
282
+ return verdict;
283
+ },
284
+ /**
285
+ * As `laws`, each call run by `run` instead of a memory table: an SQL
286
+ * implementation selected from a database, say, whose evidence a binding's
287
+ * SQL table records. A throw is a refusal.
288
+ */
289
+ lawsBy: async (op, run, options) => {
290
+ const operator = op;
291
+ const seed = options.seed ?? 0;
292
+ const laws = lawPlans(operator, options.cases ?? 200, seed);
293
+ const answers = /* @__PURE__ */ new Map();
294
+ for (const { plans } of laws) for (const side of plans.flatMap((plan) => [plan.left, plan.right])) {
295
+ if (!("node" in side) || answers.has(side.node)) continue;
296
+ try {
297
+ answers.set(side.node, Outcome.Value({ value: await run(side.node) }));
298
+ } catch (error) {
299
+ answers.set(side.node, Outcome.Refused({ reason: String(error) }));
300
+ }
301
+ }
302
+ const verdict = verdictOf(operator, laws, (node) => answers.get(node), {
303
+ implementation: options.implementation,
304
+ seed
305
+ });
306
+ if (verdict._tag === "Holds") verdict.evidence.forEach(stampRun);
307
+ return verdict;
193
308
  },
194
309
  /**
195
310
  * Runs one set of calls of `op` through every implementation and compares