foldkit-entity 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -355,6 +355,129 @@ optional relation set to nothing), and each interpreter carries it its own way,
355
355
  a ref key in a store, a foreign key in a table. A `many` relation or a nested
356
356
  key is refused where the write is declared.
357
357
 
358
+ An update or a delete may also say when it makes sense: `when` is what the row
359
+ must hold for it to land, written as a query body is: `() =>
360
+ Expr.eq(Post.fields.title, 'Draft')`, or with the input, `({ input }) =>
361
+ Expr.eq(Post.fields.title, input.from)`. It reads the row as it is before the write and the input,
362
+ never who is asking (that is a guard's), and only its own Entity: a field of
363
+ another is a type error, and refused where the write is declared. It is held as
364
+ a query body (`write.when`), so an interpreter checks it in the statement that
365
+ writes, and a row it does not hold of is refused as unmet. A write declared with
366
+ one is a `ConditionedWrite`, which is how `Mutation.write` knows it may be
367
+ refused so.
368
+
369
+ An update may move a number field by an amount the input holds, rather than set
370
+ it: `increment: { stock: 'quantity' }` adds the input's `quantity` (an unmapped
371
+ key, a number; negative takes away) to the stored `stock`, in the statement that
372
+ writes, so no concurrent change is lost. A retry must not add twice, so either it
373
+ expects a revision (a retry of a write that landed is then a conflict), or its
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
378
+ client can add them to the value it holds as it reads it (Remote does), never
379
+ 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).
383
+
384
+ ## What every row and change must hold: invariants
385
+
386
+ A Schema judges a value, and a write's `when` the row before it. Neither judges
387
+ the row a write leaves: with `quantity = 10, reserved = 5`, an update setting
388
+ `quantity = 3` decodes, and leaves a row that holds more reserved than there is.
389
+ An **invariant** is what every stored row must hold, read over the row after a
390
+ write (`after`):
391
+
392
+ ```ts
393
+ import { Schema } from 'effect'
394
+ import { Entity, Expr } from 'foldkit-entity'
395
+
396
+ const InventoryFields = Entity.define(
397
+ 'Inventory',
398
+ Schema.Struct({ id: Schema.String, quantity: Schema.Number, reserved: Schema.Number }),
399
+ )
400
+ const Inventory = InventoryFields.pipe(
401
+ Entity.invariant(
402
+ 'reservedWithinQuantity',
403
+ ({ after }) => Expr.lte(after.reserved, after.quantity),
404
+ { message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
405
+ ),
406
+ )
407
+
408
+ Entity.judge(Inventory, { after: { id: 'i1', quantity: 3, reserved: 5 } })
409
+ // { _tag: 'Invalid', failures: [{ id: 'reservedWithinQuantity', … }] }
410
+ ```
411
+
412
+ One that reads the row before too (`before`) relates the two, each of which may
413
+ be valid on its own: an order that shipped stays shipped.
414
+
415
+ ```ts
416
+ const OrderFields = Entity.define(
417
+ 'Order',
418
+ Schema.Struct({ id: Schema.String, status: Schema.Literals(['placed', 'shipped']) }),
419
+ )
420
+ const Order = OrderFields.pipe(
421
+ Entity.invariant(
422
+ 'shippedStaysShipped',
423
+ ({ before, after }) =>
424
+ Expr.or(Expr.not(Expr.eq(before.status, 'shipped')), Expr.eq(after.status, 'shipped')),
425
+ { message: 'A shipped order stays shipped', path: ['status'] },
426
+ ),
427
+ )
428
+
429
+ const shipped = { id: 'o1', status: 'shipped' }
430
+ Entity.judge(Order, { before: shipped, after: { ...shipped, status: 'placed' } })
431
+ // { _tag: 'Invalid', failures: [{ id: 'shippedStaysShipped', … }] }
432
+ ```
433
+
434
+ What an invariant reads decides when it is judged; nothing else is declared:
435
+
436
+ ```text
437
+ reads after only -> state invariant: every create and update; a CHECK constraint
438
+ reads before too -> transition invariant: every update, the only write with a row before
439
+ ```
440
+
441
+ `Entity.readsBefore(invariant)` says which one is.
442
+
443
+ `Entity.invariant` returns the step that attaches it, carrying its `id`. Hoist
444
+ it to export it, naming the Entity's type (what it reads is checked against
445
+ it), and match a refusal against it rather than spelling the id again:
446
+
447
+ ```ts
448
+ export const reservedWithinQuantity = Entity.invariant<typeof InventoryFields>(
449
+ 'reservedWithinQuantity',
450
+ ({ after }) => Expr.lte(after.reserved, after.quantity),
451
+ { message: 'Reserved stock cannot exceed the quantity', path: ['reserved'] },
452
+ )
453
+ export const Inventory = InventoryFields.pipe(reservedWithinQuantity)
454
+
455
+ // Where a write's refusal is read (foldkit-remote):
456
+ Refusal.isInvalidBy(refusal, reservedWithinQuantity)
457
+ ```
458
+
459
+ - `before` is each field as the row before holds it (`Expr.field`), and `after`
460
+ each as the row after holds it (`Expr.next`), both typed as the field.
461
+ - It is declared once, on the Entity's metadata, and attaching more adds to it;
462
+ the Entity stays the same (`Entity.same`). Its interpreters read it from there.
463
+ - It reads stored rows only: one over another Entity, or reading an input, is
464
+ refused where it is declared, as is an id declared twice or a `path` naming no
465
+ field. So is one reading nothing of `after`: which rows a write may start from
466
+ is its `when`. Who may write is a guard's; whether a write applies now is its `when`'s.
467
+ - `Entity.judge(entity, { after, before? })` judges rows as the store holds them
468
+ (encoded) and is pure. Without `before` (a create) it skips transition
469
+ invariants. A row holds one only when it is true: a null fails it, as SQL's
470
+ unknown drops a row from a `WHERE`. A row without a field it reads is
471
+ `Undecided`, never `Valid`.
472
+ - `Entity.check(entity)` is the state invariants as a Schema check over the row
473
+ type (`entity.schema.check(Entity.check(entity))`): it encodes the value, and
474
+ reports each failure at its `path` with its `message`.
475
+
476
+ Text compares only under a declared collation, here too: a date stored as text
477
+ needs `{ collation: Collation.binary }` on its comparison. An interpreter that
478
+ judges stored rows alone refuses `after`'s nodes as the operation `next`;
479
+ `Expr.substituteNext` reads the ones a write sets as their values.
480
+
358
481
  ## Attaching metadata
359
482
 
360
483
  An interpreter declares a [`foldkit-metadata`](../metadata/README.md) key and
@@ -585,10 +708,11 @@ Query.placement(byName, {}) // { _tag: 'Placeable' }
585
708
  never by a client.
586
709
 
587
710
  A term overrides its field's: `Order.asc(field, { collation })`.
588
- `Query.placement(query, input)` says whether a client can order the rows exactly
589
- as the server does: every term over a number or a boolean (a row may lack it), or over text with a
590
- portable collation. A body with no order, text with none declared, or a locale
591
- is `NotPlaceable`, with the reason.
711
+ `Query.placement(query, input, { operators })` says whether a client can order the rows exactly
712
+ as the server does: every term over a number or a boolean (a row may lack it), over text with a
713
+ portable collation, or a call whose primitive operators the client's table runs. A body with no
714
+ order, text with none declared, a locale, or an operator the table lacks is `NotPlaceable`, with
715
+ the reason.
592
716
  `foldkit-crud`'s `Sort.make(['title', 'id']).Schema` is such a sort.
593
717
 
594
718
  The list of predicates **is** the conjunction: a query wanting three
@@ -596,7 +720,7 @@ conditions writes three `where`s. `Expr.and` is for a conjunction inside
596
720
  something else, and `Expr.or` and `Expr.not` are the other two connectives:
597
721
 
598
722
  ```ts
599
- // A search over two fields: the registry finds a product by description or UPC.
723
+ // A search over two fields: a product whose description or UPC holds the text.
600
724
  Expr.or(
601
725
  Expr.contains(Product.fields.description, input.search),
602
726
  Expr.contains(Product.fields.upc, input.search),
@@ -661,6 +785,180 @@ matters is that it refuses rather than skipping the operation — an interpreter
661
785
  that quietly drops a `contains` it cannot compile answers a different question
662
786
  in full confidence, and every test it does support still passes.
663
787
 
788
+ ### Naming a question: operators
789
+
790
+ A predicate an application asks in many places (in a public query, a
791
+ visitor's Read rule, an invariant) can be given a name. `Expr.operator`
792
+ declares one by what a call of it means:
793
+
794
+ ```ts
795
+ import { Schema } from 'effect'
796
+ import { Entity, Expr, Query } from 'foldkit-entity'
797
+
798
+ const Story = Entity.define(
799
+ 'Story',
800
+ Schema.Struct({ id: Schema.String, publishedAt: Schema.NullOr(Schema.String) }),
801
+ )
802
+
803
+ const published = Expr.operator('acme.published', {
804
+ input: [Schema.Unknown],
805
+ output: Schema.Boolean,
806
+ definedAs: publishedAt => Expr.isNotNull(publishedAt),
807
+ })
808
+
809
+ const PublicStories = Query.from(Story).pipe(Query.where(published(Story.fields.publishedAt)))
810
+ Query.show(PublicStories)
811
+ // FROM Story
812
+ // WHERE acme.published(Story.publishedAt)
813
+ ```
814
+
815
+ - **It computes nothing of its own.** `definedAs` builds an expression from a
816
+ call's arguments, once per call, and every interpreter runs that expression
817
+ (`Expr.expanded` writes a predicate's calls out), so the operator needs no
818
+ SQL, no evaluator, and no support list. The SQL a body compiles to is the SQL
819
+ of the body written out by hand.
820
+ - **What it adds is a name.** `Query.show` prints the call, and
821
+ `Query.dependencies(body).operators` lists each operator a body uses.
822
+ - **It reads only its arguments.** A `definedAs` that closes over a field or an
823
+ input, instead of taking it, is refused when called: nothing asking what the
824
+ call reads (Guard's checks, Remote's matching) would see it.
825
+ - **Arguments are checked by their stored form**, at compile time and when
826
+ called: a field, scalar or plain value of the input's stored type, or a
827
+ predicate where it takes a boolean. A boolean `output` makes a call a
828
+ predicate, usable in `and`, `or`, `not`, a guard or an invariant with no cast;
829
+ any other makes it a scalar of that type.
830
+ - **Ids are namespaced** (`acme.published`), and `foldkit.` is reserved.
831
+ `version` (default 1) changes when what it means does; a call prints it after
832
+ the first (`acme.published@2(…)`).
833
+
834
+ `foldkit-cms` declares one over its `published` role: `Cms.published(entity)`.
835
+
836
+ ### Operators each interpreter implements
837
+
838
+ Without `definedAs`, an operator is **primitive**: it means what each
839
+ interpreter's implementation does, and every implementation is held to the
840
+ same statement of it. The kernel ships one, `Text.startsWith`; an application
841
+ declares its own and implements it, here for the in-memory interpreter:
842
+
843
+ ```ts
844
+ import { Schema } from 'effect'
845
+ import { Collation, Entity, Expr, Operators, Query, Text, evaluate } from 'foldkit-entity'
846
+
847
+ const Product = Entity.define(
848
+ 'Product',
849
+ Schema.Struct({ id: Schema.String, upc: Schema.String, label: Schema.String }),
850
+ ).pipe(Entity.annotateMembers({ upc: Collation.of(Collation.binary) }))
851
+ const search = Expr.input('search', Schema.String)
852
+
853
+ // The UPC declares `binary`, so it compares exactly; the label declares nothing,
854
+ // so this call is given a collation.
855
+ const ByCode = Query.from(Product).pipe(Query.where(Text.startsWith(Product.fields.upc, search)))
856
+ Text.startsWith(Product.fields.label, search, { collation: Collation.asciiFold })
857
+
858
+ const joined = Expr.operator('acme.joined', {
859
+ input: [Schema.String, Schema.String],
860
+ output: Schema.String,
861
+ collation: 'operands',
862
+ })
863
+ const operators = Operators.merge(
864
+ Operators.kernel,
865
+ Operators.memory(Operators.implement(joined, (left, right) => `${left}${right}`)),
866
+ )
867
+ evaluate(ByCode, { search: '012' }, [{ id: 'p1', upc: '0123', label: 'Bolt' }], { operators })
868
+ // [{ id: 'p1', upc: '0123', label: 'Bolt' }]
869
+ ```
870
+
871
+ `startsWith` compares under its text's collation (`binary` exactly, `asciiFold`
872
+ folding ASCII letters on both sides), is unknown when either side is null, and
873
+ holds for the empty prefix; text with no collation, or a backend's locale, is
874
+ refused where it is written.
875
+
876
+ - **A table is a value.** `Operators.memory` refuses one operator implemented
877
+ twice, or two under one name; `merge` refuses an overlap, and `override`
878
+ replaces on purpose. `Operators.checked(table)` checks each answer against
879
+ the operator's output schema, for tests. Nothing registers globally:
880
+ `evaluate`, `decided`, `truthOver`, `Entity.judge`, `Entity.judgeInput` and
881
+ `Entity.check(entity, { operators })` each take the table, `Operators.kernel`
882
+ by default.
883
+ - **Null is strict by default.** A null argument gives null (unknown for a
884
+ predicate) and the implementation never sees one. `nulls: 'handled'`
885
+ operators are implemented with `Operators.implementHandlingNulls` and answer
886
+ for null themselves; a predicate answers `null` for unknown.
887
+ - **Text has a collation or no comparison.** `collation: 'operands'` makes a
888
+ text result carry the collation its text arguments share, so
889
+ `Expr.lt(joined(a, b), x)` compares under it; `'required'` (as
890
+ `startsWith`) refuses text with none. A call may be given one:
891
+ `op(a, b, { collation })`.
892
+ - **A call orders when its result does.** `Order.asc(joined(Product.fields.upc, '!'))`
893
+ orders by the call's text under the collation it carries, and a call giving a
894
+ number orders as one; anything else, text with no collation included, is
895
+ refused where the term or `Order.chosen` alternative is written. `evaluate`
896
+ runs it per row by its table, and `compareRows(terms, a, b, query, { input,
897
+ operators })` compares two rows the same way.
898
+ - **What a table lacks is refused by name.** `Query.unsupported(body,
899
+ supported, operators)` and `Expr.unsupported(nodes, { operations,
900
+ operators })` name each operation and operator missing; `evaluate` refuses
901
+ such a body. An invariant calling an operator its judge's table lacks is
902
+ `Undecided` with that operator in `operators`, which a form passes and a
903
+ server refuses to start without.
904
+ - **NUL is refused** in any text argument, and an implementation that throws
905
+ is reported as a `QueryEvaluateError` naming its operator.
906
+
907
+ ### Laws, and holding an implementation to them
908
+
909
+ An operator may declare the equations every implementation of it keeps. A law
910
+ describes: nothing rewrites a body by one. `Conformance.laws` tests an
911
+ implementation against them, and what it finds is evidence its table records.
912
+
913
+ ```ts
914
+ import { Schema } from 'effect'
915
+ import { Expr, Law, Operators } from 'foldkit-entity'
916
+ import { Conformance } from 'foldkit-entity/conformance'
917
+
918
+ const concat = Expr.operator('acme.concat', {
919
+ input: [Schema.String, Schema.String],
920
+ output: Schema.String,
921
+ collation: 'operands',
922
+ laws: [Law.associative, Law.identity(''), Law.preservesCollation],
923
+ })
924
+ const table = Operators.memory(Operators.implement(concat, (left, right) => `${left}${right}`))
925
+
926
+ const verdict = Conformance.laws(concat, table) // { _tag: 'Holds', evidence: [...] }
927
+ const recorded =
928
+ verdict._tag === 'Holds' ? Operators.withEvidence(table, verdict.evidence) : table
929
+ Operators.describeTable(recorded) // [{ operator: 'acme.concat', laws, evidence }]
930
+ ```
931
+
932
+ - **A law is checked where it is declared.** `Law.commutative`, `associative`,
933
+ `idempotent`, `identity(value, side?)`, `absorbing(value, side?)`,
934
+ `inverse(other, identity)` and `distributes(over)` are laws of an operator of
935
+ two arguments; `monotonic(direction, position)` names an argument it has, and
936
+ `preservesCollation` needs `collation: 'operands'`. A witness that is not a
937
+ value the argument's schema stores is refused.
938
+ - **Its domain** is every non-null value of the input schemas, narrowed with
939
+ `Law.within(law, schema)` where a law holds of less (a square is increasing
940
+ over the non-negative numbers only). Strict null makes both sides null, so no
941
+ law needs a null case.
942
+ - **Testing is sampling, seeded.** Cases come from a fixed sample of each kind
943
+ (the empty string, mixed case, non-ASCII and astral text; zero, negatives, a
944
+ 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
947
+ finds `"a"` and `"A"`, which give `"aA"` and `"Aa"`.
948
+ - **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.
952
+
953
+ `Conformance.operator(op, { implementations })` runs one set of calls through
954
+ every implementation given and reports where they disagree, a refusal included:
955
+ generated from each argument's samples, null where its schema admits one, and
956
+ text holding NUL, under `binary` and `asciiFold` where the operator compares
957
+ text. `Conformance.memory(table)` is the reference interpreter's runner; a
958
+ defined operator's expansion runs beside the others. `foldkit-remote-drizzle`
959
+ runs the kernel's operators and an application's through it on SQLite and
960
+ Postgres.
961
+
664
962
  ### Reading one back
665
963
 
666
964
  `Query.show(query)` renders a body as text, one clause per line:
@@ -698,7 +996,8 @@ from queries, not from what a database could express.
698
996
  | `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result. |
699
997
  | `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
700
998
  | `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
701
- | `Write.update(input, { id, expect? })` | A declared update of one row: every key the input maps to a field, but the id and the expected revision. |
999
+ | `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. |
702
1001
  | `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. |
703
1002
  | `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
704
1003
  | `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
@@ -719,14 +1018,23 @@ from queries, not from what a database could express.
719
1018
  | `Expr.not(predicate)` | The predicate does not hold; an unknown stays unknown, so a null matches neither side. |
720
1019
  | `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. |
721
1020
  | `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. |
1022
+ | `Expr.unsupported(nodes, { operations, operators })` | What these expressions need that an interpreter lacks: operations, then primitive operators by name. |
1023
+ | `Text.startsWith(text, prefix, { collation? })` | Whether text begins with a prefix, under its collation; the kernel's primitive operator. |
1024
+ | `Operators.memory(...)` / `implement` / `implementHandlingNulls` / `merge` / `override` / `checked` / `kernel` | Tables of in-memory implementations of primitive operators, passed to `evaluate` and every judge. |
1025
+ | `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
+ | `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. |
1028
+ | `valueOfOperand(node, { operators })` | What an operand, a call of literals say, comes to over no row. |
1029
+ | `Expr.expanded(predicate)` | The predicate with every call of a defined operator written out as what it means, deeply; what an interpreter compiles. |
722
1030
  | `Expr.field(field)` | One field of one Entity, as a scalar. |
723
1031
  | `Expr.input(key, schema)` | A value the query is given when it runs, as a placeholder. |
724
1032
  | `Expr.literal(value)` | A constant. Comparisons coerce one, so this is rarely written. |
725
1033
  | `Order.asc(expr, { nulls? })` / `Order.desc(expr, { nulls? })` | One term of an ordering, over a field or a scalar. Rows without a value go last ascending and first descending unless `nulls` says otherwise; every interpreter is told, since databases disagree when it is unsaid. |
726
1034
  | `Collation.binary` / `.asciiFold` / `.locale(name)` / `.of(collation)` | How a text field orders, as member metadata; see above. |
727
1035
  | `ReadFilter.of(members)` / `.members(metadata)` | Entity metadata: the members a server filters rows by under a rule the client does not run (an authorization rule; `foldkit-guard` attaches it). A client placing rows in a list fetches the list instead when one changes. Annotations add up. |
728
- | `Query.placement(query, input)` | `Placeable`, or `NotPlaceable` with why: whether a client can order as the server does. |
729
- | `Order.chosen(sort, choices)` | The field an input's sort names (`{ by, direction }`, or `null` for none), among `choices`. |
1036
+ | `Query.placement(query, input, { operators })` | `Placeable`, or `NotPlaceable` with why: whether a client running `operators` can order as the server does. |
1037
+ | `Order.chosen(sort, choices)` | The field or call an input's sort names (`{ by, direction }`, or `null` for none), among `choices`. |
730
1038
  | `dependenciesOf(...nodes)` | The distinct fields, inputs, and operations those expressions use. |
731
1039
  | `Query.from(entity)` | Every row of an Entity: the query each step narrows. |
732
1040
  | `Query.where(...predicates)` | Pipe step keeping the rows those hold for; conjoins with what is there. |
@@ -1,6 +1,198 @@
1
- import { rt as AnyQuery, s as Entity } from "../index-_x1ScI4v.mjs";
2
- import { Schema } from "effect";
3
- //#region src/conformance/index.d.ts
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";
2
+ import { Data, Option, Schema } from "effect";
3
+ /** What an implementation said of one call: a value, or that it refused it. */
4
+ export type Outcome = Data.TaggedEnum<{
5
+ Value: {
6
+ readonly value: unknown;
7
+ };
8
+ Refused: {
9
+ readonly reason: string;
10
+ };
11
+ }>;
12
+ export declare const Outcome: {
13
+ readonly $is: <Tag extends "Refused" | "Value">(tag: Tag) => (u: unknown) => u is Extract<{
14
+ readonly _tag: "Refused";
15
+ readonly reason: string;
16
+ }, {
17
+ readonly _tag: Tag;
18
+ }> | Extract<{
19
+ readonly _tag: "Value";
20
+ readonly value: unknown;
21
+ }, {
22
+ readonly _tag: Tag;
23
+ }>;
24
+ readonly $match: {
25
+ <Cases extends { readonly [Tag in "Refused" | "Value"]: (args: Extract<{
26
+ readonly _tag: "Refused";
27
+ readonly reason: string;
28
+ } | {
29
+ readonly _tag: "Value";
30
+ readonly value: unknown;
31
+ }, {
32
+ readonly _tag: Tag;
33
+ }>) => any; }>(cases: Cases): (value: {
34
+ readonly _tag: "Refused";
35
+ readonly reason: string;
36
+ } | {
37
+ readonly _tag: "Value";
38
+ readonly value: unknown;
39
+ }) => import("effect/Unify").Unify<ReturnType<Cases["Refused" | "Value"]>>;
40
+ <Cases extends { readonly [Tag in "Refused" | "Value"]: (args: Extract<{
41
+ readonly _tag: "Refused";
42
+ readonly reason: string;
43
+ } | {
44
+ readonly _tag: "Value";
45
+ readonly value: unknown;
46
+ }, {
47
+ readonly _tag: Tag;
48
+ }>) => any; }>(value: {
49
+ readonly _tag: "Refused";
50
+ readonly reason: string;
51
+ } | {
52
+ readonly _tag: "Value";
53
+ readonly value: unknown;
54
+ }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Refused" | "Value"]>>;
55
+ };
56
+ readonly Refused: Data.TaggedEnum.ConstructorFrom<{
57
+ readonly _tag: "Refused";
58
+ readonly reason: string;
59
+ }, "_tag">;
60
+ readonly Value: Data.TaggedEnum.ConstructorFrom<{
61
+ readonly _tag: "Value";
62
+ readonly value: unknown;
63
+ }, "_tag">;
64
+ };
65
+ /** What `Conformance.laws` found: every law held, with the evidence, or the first case one did not. */
66
+ export type LawsVerdict = Data.TaggedEnum<{
67
+ Holds: {
68
+ readonly evidence: ReadonlyArray<TestedEvidence>;
69
+ };
70
+ Counterexample: {
71
+ readonly law: LawDescription;
72
+ readonly args: ReadonlyArray<unknown>;
73
+ readonly left: Outcome;
74
+ readonly right: Outcome;
75
+ };
76
+ }>;
77
+ export declare const LawsVerdict: {
78
+ readonly $is: <Tag extends "Counterexample" | "Holds">(tag: Tag) => (u: unknown) => u is Extract<{
79
+ readonly _tag: "Counterexample";
80
+ readonly law: LawDescription;
81
+ readonly args: ReadonlyArray<unknown>;
82
+ readonly left: Outcome;
83
+ readonly right: Outcome;
84
+ }, {
85
+ readonly _tag: Tag;
86
+ }> | Extract<{
87
+ readonly _tag: "Holds";
88
+ readonly evidence: ReadonlyArray<TestedEvidence>;
89
+ }, {
90
+ readonly _tag: Tag;
91
+ }>;
92
+ readonly $match: {
93
+ <Cases extends { readonly [Tag in "Counterexample" | "Holds"]: (args: Extract<{
94
+ readonly _tag: "Counterexample";
95
+ readonly law: LawDescription;
96
+ readonly args: ReadonlyArray<unknown>;
97
+ readonly left: Outcome;
98
+ readonly right: Outcome;
99
+ } | {
100
+ readonly _tag: "Holds";
101
+ readonly evidence: ReadonlyArray<TestedEvidence>;
102
+ }, {
103
+ readonly _tag: Tag;
104
+ }>) => any; }>(cases: Cases): (value: {
105
+ readonly _tag: "Counterexample";
106
+ readonly law: LawDescription;
107
+ readonly args: ReadonlyArray<unknown>;
108
+ readonly left: Outcome;
109
+ readonly right: Outcome;
110
+ } | {
111
+ readonly _tag: "Holds";
112
+ readonly evidence: ReadonlyArray<TestedEvidence>;
113
+ }) => import("effect/Unify").Unify<ReturnType<Cases["Counterexample" | "Holds"]>>;
114
+ <Cases extends { readonly [Tag in "Counterexample" | "Holds"]: (args: Extract<{
115
+ readonly _tag: "Counterexample";
116
+ readonly law: LawDescription;
117
+ readonly args: ReadonlyArray<unknown>;
118
+ readonly left: Outcome;
119
+ readonly right: Outcome;
120
+ } | {
121
+ readonly _tag: "Holds";
122
+ readonly evidence: ReadonlyArray<TestedEvidence>;
123
+ }, {
124
+ readonly _tag: Tag;
125
+ }>) => any; }>(value: {
126
+ readonly _tag: "Counterexample";
127
+ readonly law: LawDescription;
128
+ readonly args: ReadonlyArray<unknown>;
129
+ readonly left: Outcome;
130
+ readonly right: Outcome;
131
+ } | {
132
+ readonly _tag: "Holds";
133
+ readonly evidence: ReadonlyArray<TestedEvidence>;
134
+ }, cases: Cases): import("effect/Unify").Unify<ReturnType<Cases["Counterexample" | "Holds"]>>;
135
+ };
136
+ readonly Counterexample: Data.TaggedEnum.ConstructorFrom<{
137
+ readonly _tag: "Counterexample";
138
+ readonly law: LawDescription;
139
+ readonly args: ReadonlyArray<unknown>;
140
+ readonly left: Outcome;
141
+ readonly right: Outcome;
142
+ }, "_tag">;
143
+ readonly Holds: Data.TaggedEnum.ConstructorFrom<{
144
+ readonly _tag: "Holds";
145
+ readonly evidence: ReadonlyArray<TestedEvidence>;
146
+ }, "_tag">;
147
+ };
148
+ /**
149
+ * One way to run a call: its value, or a throw for a call it refuses. A call
150
+ * of a predicate answers its truth, unknown as `null`.
151
+ */
152
+ export type Runner = (call: Operandish) => unknown;
153
+ /** A call the implementations did not agree on, with what each said. */
154
+ export interface Disagreement {
155
+ readonly args: ReadonlyArray<unknown>;
156
+ readonly collation: Option.Option<Collation>;
157
+ readonly outcomes: Readonly<Record<string, Outcome>>;
158
+ }
159
+ export interface OperatorReport {
160
+ /** How many calls ran, each through every implementation. */
161
+ readonly cases: number;
162
+ readonly disagreements: ReadonlyArray<Disagreement>;
163
+ }
164
+ export declare const Conformance: {
165
+ /** A runner of calls through a memory table: `Conformance.operator`'s for the in-memory interpreter. */
166
+ memory: (operators: MemoryOperators) => Runner;
167
+ /**
168
+ * Tests every law `op` declares against `operators`' implementation of it,
169
+ * 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.
173
+ */
174
+ laws: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(op: Operator<In, Out>, operators: MemoryOperators, options?: {
175
+ readonly implementation?: string | undefined;
176
+ readonly cases?: number | undefined;
177
+ readonly seed?: number | undefined;
178
+ }) => LawsVerdict;
179
+ /**
180
+ * Runs one set of calls of `op` through every implementation and compares
181
+ * what each answered or refused. The calls are `cases` (argument tuples, as
182
+ * stored), or generated: each argument a sample of its kind, null where its
183
+ * schema admits one, and text holding NUL, under `binary` and `asciiFold` where the operator compares
184
+ * text, up to `limit` (300) chosen by `seed` (0). A defined operator's
185
+ * expansion is run beside the others, as `expansion`, by `expansionTable`
186
+ * (the kernel's when not given).
187
+ */
188
+ operator: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(op: Operator<In, Out>, options: {
189
+ readonly implementations: Readonly<Record<string, Runner>>;
190
+ readonly cases?: ReadonlyArray<ReadonlyArray<unknown>> | undefined;
191
+ readonly limit?: number | undefined;
192
+ readonly seed?: number | undefined;
193
+ readonly expansionTable?: MemoryOperators | undefined;
194
+ }) => Promise<OperatorReport>;
195
+ };
4
196
  /** The one Entity every case reads, with a column of each kind that matters. */
5
197
  export declare const Subject: Entity<"Subject", {
6
198
  readonly id: Schema.String;
@@ -42,6 +234,12 @@ export interface ConformanceCase {
42
234
  readonly expected: ReadonlyArray<string>;
43
235
  }
44
236
  export declare const cases: ReadonlyArray<ConformanceCase>;
237
+ /**
238
+ * Bodies calling the kernel's primitive operators (`Text.startsWith`). An
239
+ * interpreter runs these once it implements them: the in-memory one through
240
+ * `Operators.kernel`, a compiler through its own table.
241
+ */
242
+ export declare const primitiveCases: ReadonlyArray<ConformanceCase>;
45
243
  /**
46
244
  * A body whose answer no two interpreters agree on, so every interpreter must
47
245
  * refuse it rather than answer. Run each through yours and expect a failure.
@@ -53,5 +251,6 @@ export interface ConformanceRefusal {
53
251
  readonly input: Readonly<Record<string, unknown>>;
54
252
  }
55
253
  export declare const refusals: ReadonlyArray<ConformanceRefusal>;
56
- //#endregion
254
+ /** As `refusals`, for bodies calling the kernel's primitive operators. */
255
+ export declare const primitiveRefusals: ReadonlyArray<ConformanceRefusal>;
57
256
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/conformance/index.ts"],"mappings":";;;;qBA4Ca,SAAO;;;;;;;;;;;;;;;iBAmBH;WACN;WACA;WACA;WACA;;WAEA;YACC;;qBAGC,MAAM,cAAc;iBAQhB;;WAEN;WACA,MAAM;;;;;;;WAON,OAAO,SAAS;;WAEhB,UAAU;;qBA6BR,OAAO,cAAc;;;;;iBAudjB;WACN;WACA,MAAM;;WAEN,OAAO,SAAS;;qBAKd,UAAU,cAAc"}
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;;;;YAMf,cAAc,KAAK;EAC7B;aAAkB,UAAU,cAAc;;EAC1C;aACW,KAAK;aACL,MAAM;aACN,MAAM;aACN,OAAO;;;qBAGP;;;aANK,KAAA;aACC,MAAA;aACA,MAAA;aACC,OAAA;;;;;aALU,UAAA,cAAc;;;;;;;eAE1B,KAAA;eACC,MAAA;eACA,MAAA;eACC,OAAA;;;eALU,UAAA,cAAc;;;;;;;;;;;;;;;eAE1B,KAAA;eACC,MAAA;eACA,MAAA;eACC,OAAA;;;eALU,UAAA,cAAc;;;;;;;;;;;;;;;;aAE1B,KAAA;aACC,MAAA;aACA,MAAA;aACC,OAAA;;;;aALU,UAAA,cAAc;;;;;;;YAchC,UAAU,MAAM;;iBAGX;WACN,MAAM;WACN,WAAW,OAAO,OAAO;WACzB,UAAU,SAAS,eAAe;;iBAG5B;;WAEN;WACA,eAAe,cAAc;;qBA0G3B;;EAEX,SAAM,WACQ,oBAAkB;;;;;;;;EAWhC,OAAO,WAAW,cAAc,OAAO,MAAM,YAAY,OAAO,KAAG,IAC7D,SAAS,IAAI,MAAI,WACV,iBAAe;aAEf;aACA;aACA;QAEV;;;;;;;;;;EAwIH,WAAiB,WAAW,cAAc,OAAO,MAAM,YAAY,OAAO,KAAG,IACvE,SAAS,IAAI,MAAI;aAEV,iBAAiB,SAAS,eAAe;aACzC,QAAQ,cAAc;aACtB;aACA;aACA,iBAAiB;QAE3B,QAAQ;;;qBCrSA,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"}