foldkit-entity 0.16.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.
- package/README.md +582 -240
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +30 -4
- package/dist/conformance/index.js.map +1 -1
- package/dist/conformance/operator.d.ts.map +1 -1
- package/dist/conformance/operator.js +13 -4
- package/dist/conformance/operator.js.map +1 -1
- package/dist/descriptor.d.ts +5 -1
- package/dist/descriptor.d.ts.map +1 -1
- package/dist/descriptor.js +6 -2
- package/dist/descriptor.js.map +1 -1
- package/dist/entity.d.ts +16 -3
- package/dist/entity.d.ts.map +1 -1
- package/dist/entity.js +44 -14
- package/dist/entity.js.map +1 -1
- package/dist/enumerate.d.ts +44 -0
- package/dist/enumerate.d.ts.map +1 -0
- package/dist/enumerate.js +128 -0
- package/dist/enumerate.js.map +1 -0
- package/dist/evaluate.d.ts +12 -6
- package/dist/evaluate.d.ts.map +1 -1
- package/dist/evaluate.js +48 -23
- package/dist/evaluate.js.map +1 -1
- package/dist/expr.d.ts +78 -22
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +86 -57
- package/dist/expr.js.map +1 -1
- package/dist/footprint.d.ts +120 -0
- package/dist/footprint.d.ts.map +1 -0
- package/dist/footprint.js +41 -0
- package/dist/footprint.js.map +1 -0
- package/dist/held.js +11 -3
- package/dist/held.js.map +1 -1
- package/dist/index.d.ts +24 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -6
- package/dist/index.js.map +1 -1
- package/dist/invariant.d.ts +41 -11
- package/dist/invariant.d.ts.map +1 -1
- package/dist/invariant.js +102 -51
- package/dist/invariant.js.map +1 -1
- package/dist/law.d.ts.map +1 -1
- package/dist/law.js +3 -9
- package/dist/law.js.map +1 -1
- package/dist/lawCore.d.ts +42 -0
- package/dist/lawCore.d.ts.map +1 -0
- package/dist/lawCore.js +12 -0
- package/dist/lawCore.js.map +1 -0
- package/dist/lawIds.d.ts +15 -0
- package/dist/lawIds.d.ts.map +1 -0
- package/dist/lawIds.js +13 -0
- package/dist/lawIds.js.map +1 -0
- package/dist/laws.d.ts +308 -0
- package/dist/laws.d.ts.map +1 -0
- package/dist/laws.js +566 -0
- package/dist/laws.js.map +1 -0
- package/dist/memoryTable.d.ts +11 -0
- package/dist/memoryTable.d.ts.map +1 -0
- package/dist/memoryTable.js +69 -0
- package/dist/memoryTable.js.map +1 -0
- package/dist/operators.d.ts +1 -1
- package/dist/operators.d.ts.map +1 -1
- package/dist/operators.js +2 -66
- package/dist/operators.js.map +1 -1
- package/dist/refine.d.ts +64 -0
- package/dist/refine.d.ts.map +1 -0
- package/dist/refine.js +104 -0
- package/dist/refine.js.map +1 -0
- package/dist/rows.d.ts +15 -0
- package/dist/rows.d.ts.map +1 -0
- package/dist/rows.js +23 -0
- package/dist/rows.js.map +1 -0
- package/dist/sets.js.map +1 -1
- package/dist/uncollated.d.ts +10 -0
- package/dist/uncollated.d.ts.map +1 -0
- package/dist/uncollated.js +18 -0
- package/dist/uncollated.js.map +1 -0
- package/dist/write.d.ts +65 -7
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +128 -30
- package/dist/write.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { Collation } from "./collation.js";
|
|
3
|
+
import { Text } from "./text.js";
|
|
4
|
+
// src/memoryTable.ts
|
|
5
|
+
/**
|
|
6
|
+
* The in-memory operator table and the kernel's own operators. Apart from
|
|
7
|
+
* `Operators` so evaluating a body keeps none of what describes an operator.
|
|
8
|
+
*/
|
|
9
|
+
/** An operator by its id, and its version when that is not the first. */
|
|
10
|
+
const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
11
|
+
const fail = (what) => {
|
|
12
|
+
throw new Error(`[foldkit-entity] Operators: ${what}`);
|
|
13
|
+
};
|
|
14
|
+
const table = (implementations, checked, evidence) => {
|
|
15
|
+
const byOperator = /* @__PURE__ */ new Map();
|
|
16
|
+
const byName = /* @__PURE__ */ new Map();
|
|
17
|
+
for (const { operator, run } of implementations) {
|
|
18
|
+
if (byOperator.has(operator)) fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
|
|
19
|
+
const named = byName.get(nameOf(operator));
|
|
20
|
+
if (named !== void 0 && named !== operator) fail(`two operators are named ${nameOf(operator)}; give one another id or version`);
|
|
21
|
+
byName.set(nameOf(operator), operator);
|
|
22
|
+
byOperator.set(operator, run);
|
|
23
|
+
}
|
|
24
|
+
return Object.freeze({
|
|
25
|
+
_tag: "MemoryOperators",
|
|
26
|
+
has: (operator) => byOperator.has(operator),
|
|
27
|
+
versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
|
|
28
|
+
get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
|
|
29
|
+
named: (name) => Option.fromUndefinedOr(byName.get(name)),
|
|
30
|
+
checked,
|
|
31
|
+
implementations: Object.freeze([...implementations]),
|
|
32
|
+
evidence: Object.freeze([...evidence])
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
/** An implementation, its operator's null rule checked against the function chosen for it. */
|
|
36
|
+
const implementation = (operator, nulls, run) => {
|
|
37
|
+
if (Option.isSome(operator.definedAs)) fail(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
|
|
38
|
+
if (operator.nulls !== nulls) fail(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
|
|
39
|
+
return Object.freeze({
|
|
40
|
+
operator,
|
|
41
|
+
run: (args, context) => run(...args, context)
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
const REPLACEMENT = String.fromCharCode(65533);
|
|
45
|
+
/**
|
|
46
|
+
* Text's characters as a database holds them: a lone surrogate, which UTF-8
|
|
47
|
+
* cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.
|
|
48
|
+
*/
|
|
49
|
+
const charactersOf = (text) => Array.from(text, (each) => {
|
|
50
|
+
const code = each.codePointAt(0);
|
|
51
|
+
return code >= 55296 && code <= 57343 ? REPLACEMENT : each;
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* Whether `text` begins with `prefix` by character, as SQL's `substr` and
|
|
55
|
+
* `left` count: `String.prototype.startsWith` compares UTF-16 units, so half
|
|
56
|
+
* of an astral character would begin the text that holds all of it.
|
|
57
|
+
*/
|
|
58
|
+
const beginsWith = (text, prefix) => {
|
|
59
|
+
const [characters, start] = [charactersOf(text), charactersOf(prefix)];
|
|
60
|
+
return start.length <= characters.length && start.every((each, i) => each === characters[i]);
|
|
61
|
+
};
|
|
62
|
+
/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
|
|
63
|
+
const kernelOperators = table([implementation(Text.startsWith.descriptor, "strict", (...given) => {
|
|
64
|
+
const [text, prefix, { collation }] = given;
|
|
65
|
+
return Option.exists(collation, (each) => each._tag === "AsciiFold") ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix)) : beginsWith(text, prefix);
|
|
66
|
+
})], false, []);
|
|
67
|
+
export { fail, implementation, kernelOperators, nameOf, table };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=memoryTable.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memoryTable.js","names":[],"sources":["../src/memoryTable.ts"],"sourcesContent":["/**\n * The in-memory operator table and the kernel's own operators. Apart from\n * `Operators` so evaluating a body keeps none of what describes an operator.\n */\nimport { Option } from 'effect'\nimport { Collation } from './collation.js'\nimport type { OperatorDescriptor } from './expr.js'\nimport type {\n Evidence,\n MemoryImplementation,\n MemoryOperators,\n OperatorContext,\n} from './operators.js'\nimport { Text } from './text.js'\n\n/** An operator by its id, and its version when that is not the first. */\nexport const nameOf = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\nexport const fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Operators: ${what}`)\n}\n\nexport const table = (\n implementations: ReadonlyArray<MemoryImplementation>,\n checked: boolean,\n evidence: ReadonlyArray<Evidence>,\n): MemoryOperators => {\n const byOperator = new Map<OperatorDescriptor, MemoryImplementation['run']>()\n const byName = new Map<string, OperatorDescriptor>()\n for (const { operator, run } of implementations) {\n if (byOperator.has(operator)) {\n fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`)\n }\n // Two descriptors under one name would leave a body's call ambiguous.\n const named = byName.get(nameOf(operator))\n if (named !== undefined && named !== operator) {\n fail(`two operators are named ${nameOf(operator)}; give one another id or version`)\n }\n byName.set(nameOf(operator), operator)\n byOperator.set(operator, run)\n }\n return Object.freeze({\n _tag: 'MemoryOperators',\n has: (operator: OperatorDescriptor) => byOperator.has(operator),\n versions: (id: string) =>\n implementations\n .filter(({ operator }) => operator.id === id)\n .map(({ operator }) => operator.version),\n get: (operator: OperatorDescriptor) => Option.fromUndefinedOr(byOperator.get(operator)),\n named: (name: string) => Option.fromUndefinedOr(byName.get(name)),\n checked,\n implementations: Object.freeze([...implementations]),\n evidence: Object.freeze([...evidence]),\n })\n}\n\n/** An implementation, its operator's null rule checked against the function chosen for it. */\nexport const implementation = (\n operator: OperatorDescriptor,\n nulls: OperatorDescriptor['nulls'],\n run: (...args: ReadonlyArray<unknown>) => unknown,\n): MemoryImplementation => {\n // SQL compiles what a defined operator means, so an implementation here would\n // be a second meaning that only memory runs.\n if (Option.isSome(operator.definedAs)) {\n fail(\n `${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`,\n )\n }\n if (operator.nulls !== nulls) {\n fail(\n nulls === 'strict'\n ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls`\n : `${nameOf(operator)} is strict about null; implement it with Operators.implement`,\n )\n }\n return Object.freeze({\n operator,\n run: (args: ReadonlyArray<unknown>, context: OperatorContext) => run(...args, context),\n })\n}\n\nconst REPLACEMENT = String.fromCharCode(0xfffd)\n\n/**\n * Text's characters as a database holds them: a lone surrogate, which UTF-8\n * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.\n */\nconst charactersOf = (text: string): ReadonlyArray<string> =>\n Array.from(text, each => {\n const code = each.codePointAt(0)!\n return code >= 0xd800 && code <= 0xdfff ? REPLACEMENT : each\n })\n\n/**\n * Whether `text` begins with `prefix` by character, as SQL's `substr` and\n * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half\n * of an astral character would begin the text that holds all of it.\n */\nconst beginsWith = (text: string, prefix: string): boolean => {\n const [characters, start] = [charactersOf(text), charactersOf(prefix)]\n return start.length <= characters.length && start.every((each, i) => each === characters[i])\n}\n\nconst startsWith = implementation(Text.startsWith.descriptor, 'strict', (...given) => {\n const [text, prefix, { collation }] = given as [string, string, OperatorContext]\n const folded = Option.exists(collation, each => each._tag === 'AsciiFold')\n return folded\n ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix))\n : beginsWith(text, prefix)\n})\n\n/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\nexport const kernelOperators = table([startsWith], false, [])\n"],"mappings":";;;;;;;;;AAgBA,MAAa,UAAU,aACrB,SAAS,YAAY,IAAI,SAAS,KAAK,GAAG,SAAS,GAAG,GAAG,SAAS;AAEpE,MAAa,QAAQ,SAAwB;CAC3C,MAAM,IAAI,MAAM,+BAA+B,MAAM;AACvD;AAEA,MAAa,SACX,iBACA,SACA,aACoB;CACpB,MAAM,6BAAa,IAAI,IAAqD;CAC5E,MAAM,yBAAS,IAAI,IAAgC;CACnD,KAAK,MAAM,EAAE,UAAU,SAAS,iBAAiB;EAC/C,IAAI,WAAW,IAAI,QAAQ,GACzB,KAAK,GAAG,OAAO,QAAQ,EAAE,2DAA2D;EAGtF,MAAM,QAAQ,OAAO,IAAI,OAAO,QAAQ,CAAC;EACzC,IAAI,UAAU,KAAA,KAAa,UAAU,UACnC,KAAK,2BAA2B,OAAO,QAAQ,EAA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,kBAAkB,MAAM,CATlB,eAAe,KAAK,WAAW,YAAY,WAAW,GAAG,UAAU;CACpF,MAAM,CAAC,MAAM,QAAQ,EAAE,eAAe;CAEtC,OADe,OAAO,OAAO,YAAW,SAAQ,KAAK,SAAS,WAClD,IACR,WAAW,UAAU,UAAU,IAAI,GAAG,UAAU,UAAU,MAAM,CAAC,IACjE,WAAW,MAAM,MAAM;AAC7B,CAGsC,CAAU,GAAG,OAAO,CAAC,CAAC"}
|
package/dist/operators.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Data, Option, Schema } from "effect";
|
|
2
|
-
import { Collation } from "./collation.js";
|
|
3
2
|
import { Operator, OperatorDescriptor, OperatorTable } from "./expr.js";
|
|
3
|
+
import { Collation } from "./collation.js";
|
|
4
4
|
import { LawDescription } from "./law.js";
|
|
5
5
|
import { testedByRunner } from "./tested.js";
|
|
6
6
|
/** What an implementation is told besides its arguments. */
|
package/dist/operators.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operators.d.ts","names":[],"sources":["../src/operators.ts"],"mappings":";;;;;;iBAeiB;;WAEN,WAAW,OAAO,OAAO;;;iBAInB;WACN,UAAU;WACV,MAAM,MAAM,wBAAwB,SAAS;;;;;;;;YAS5C,WAAW,KAAK;EAC1B;aACW;aACA,KAAK;aACL;aACA;aACA;;EAEX;aACW;aACA,KAAK;aACL;aACA,aAAa;;;qBAGb,UAAQ,KAAA,WAAA;;WANE;WACL,KAAA;WACM;WACE,aAAA;;;WAVH;WACL,KAAA;WACW;WACT;WACD;;;YAYP,iBAAiB,QAAQ;WAAqB;;;;;;;;qBAW7C,qBAAmB,OAAA;;;;;;;;;;;;;;;;;YAapB,6BAA6B,oBAAoB;;iBAG5C,4BAA4B;WAClC,UAAU,cAAc;;;iBAiBlB,wBAAwB;WAC9B;WACA,MAAM,UAAU,uBAAuB,OAAO,OAAO;;;;;WAKrD,QAAQ,iBAAiB,OAAO,OAAO;;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iBACD,cAAc,0BACjC;;;;;;;;EAwBkB,eAAA,MAAA,iBAAe,UAAY,cAAc,cAAY;;;;;EAmCvD,WAAA,QAAA,aAAW,OAAO,OAAO;;;;;;;;;;;;EAmBtB,gBAAA,MAAA,oBAAkB,cAAc;;;;;;;;EAajC,WAAA;aAAW,YAAY;QAAuB;;;;;;EAQnD,UAAA,MAAA,oBAAkB"}
|
package/dist/operators.js
CHANGED
|
@@ -1,16 +1,9 @@
|
|
|
1
1
|
import { Data, Equivalence, Option, Schema } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
import { fail, implementation, kernelOperators, nameOf, table } from "./memoryTable.js";
|
|
3
3
|
import { Law, LawDescription } from "./law.js";
|
|
4
|
-
import { Text } from "./text.js";
|
|
5
4
|
import { jsonSchemaOf } from "./jsonSchema.js";
|
|
6
5
|
import { tableTested, testedByRunner } from "./tested.js";
|
|
7
6
|
// src/operators.ts
|
|
8
|
-
/**
|
|
9
|
-
* How the in-memory interpreter runs primitive operators: a table of
|
|
10
|
-
* implementations, passed to `evaluate` and every judge as a value. A table is
|
|
11
|
-
* immutable and implements each operator once; nothing registers anything
|
|
12
|
-
* globally. See `docs/design/expr-operations-DESIGN.md` §5.4.
|
|
13
|
-
*/
|
|
14
7
|
const Evidence = Data.taggedEnum();
|
|
15
8
|
/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */
|
|
16
9
|
const JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
|
|
@@ -49,68 +42,11 @@ const described = (operator) => ({
|
|
|
49
42
|
laws: operator.laws.map(Law.describe),
|
|
50
43
|
defined: Option.isSome(operator.definedAs)
|
|
51
44
|
});
|
|
52
|
-
/** An operator by its id, and its version when that is not the first. */
|
|
53
|
-
const nameOf = (operator) => operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`;
|
|
54
|
-
const fail = (what) => {
|
|
55
|
-
throw new Error(`[foldkit-entity] Operators: ${what}`);
|
|
56
|
-
};
|
|
57
|
-
const table = (implementations, checked, evidence) => {
|
|
58
|
-
const byOperator = /* @__PURE__ */ new Map();
|
|
59
|
-
const byName = /* @__PURE__ */ new Map();
|
|
60
|
-
for (const { operator, run } of implementations) {
|
|
61
|
-
if (byOperator.has(operator)) fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`);
|
|
62
|
-
const named = byName.get(nameOf(operator));
|
|
63
|
-
if (named !== void 0 && named !== operator) fail(`two operators are named ${nameOf(operator)}; give one another id or version`);
|
|
64
|
-
byName.set(nameOf(operator), operator);
|
|
65
|
-
byOperator.set(operator, run);
|
|
66
|
-
}
|
|
67
|
-
return Object.freeze({
|
|
68
|
-
_tag: "MemoryOperators",
|
|
69
|
-
has: (operator) => byOperator.has(operator),
|
|
70
|
-
versions: (id) => implementations.filter(({ operator }) => operator.id === id).map(({ operator }) => operator.version),
|
|
71
|
-
get: (operator) => Option.fromUndefinedOr(byOperator.get(operator)),
|
|
72
|
-
named: (name) => Option.fromUndefinedOr(byName.get(name)),
|
|
73
|
-
checked,
|
|
74
|
-
implementations: Object.freeze([...implementations]),
|
|
75
|
-
evidence: Object.freeze([...evidence])
|
|
76
|
-
});
|
|
77
|
-
};
|
|
78
45
|
/** Whether two laws, as JSON, are the same law. */
|
|
79
46
|
const sameLaw = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
80
47
|
/** What a table runs for the operator under `name`: none when it implements none. */
|
|
81
48
|
const runNamed = (operators, name) => Option.flatMap(operators.named(name), operators.get);
|
|
82
49
|
const sameRun = Option.makeEquivalence(Equivalence.strictEqual());
|
|
83
|
-
/** An implementation, its operator's null rule checked against the function chosen for it. */
|
|
84
|
-
const implementation = (operator, nulls, run) => {
|
|
85
|
-
if (Option.isSome(operator.definedAs)) fail(`${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`);
|
|
86
|
-
if (operator.nulls !== nulls) fail(nulls === "strict" ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls` : `${nameOf(operator)} is strict about null; implement it with Operators.implement`);
|
|
87
|
-
return Object.freeze({
|
|
88
|
-
operator,
|
|
89
|
-
run: (args, context) => run(...args, context)
|
|
90
|
-
});
|
|
91
|
-
};
|
|
92
|
-
const REPLACEMENT = String.fromCharCode(65533);
|
|
93
|
-
/**
|
|
94
|
-
* Text's characters as a database holds them: a lone surrogate, which UTF-8
|
|
95
|
-
* cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.
|
|
96
|
-
*/
|
|
97
|
-
const charactersOf = (text) => Array.from(text, (each) => {
|
|
98
|
-
const code = each.codePointAt(0);
|
|
99
|
-
return code >= 55296 && code <= 57343 ? REPLACEMENT : each;
|
|
100
|
-
});
|
|
101
|
-
/**
|
|
102
|
-
* Whether `text` begins with `prefix` by character, as SQL's `substr` and
|
|
103
|
-
* `left` count: `String.prototype.startsWith` compares UTF-16 units, so half
|
|
104
|
-
* of an astral character would begin the text that holds all of it.
|
|
105
|
-
*/
|
|
106
|
-
const beginsWith = (text, prefix) => {
|
|
107
|
-
const [characters, start] = [charactersOf(text), charactersOf(prefix)];
|
|
108
|
-
return start.length <= characters.length && start.every((each, i) => each === characters[i]);
|
|
109
|
-
};
|
|
110
|
-
const startsWith = implementation(Text.startsWith.descriptor, "strict", (...given) => {
|
|
111
|
-
const [text, prefix, { collation }] = given;
|
|
112
|
-
return Option.exists(collation, (each) => each._tag === "AsciiFold") ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix)) : beginsWith(text, prefix);
|
|
113
|
-
});
|
|
114
50
|
const Operators = {
|
|
115
51
|
/**
|
|
116
52
|
* An implementation of a strict operator: a pure function of its arguments'
|
|
@@ -200,7 +136,7 @@ const Operators = {
|
|
|
200
136
|
*/
|
|
201
137
|
checked: (base) => table(base.implementations, true, base.evidence),
|
|
202
138
|
/** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */
|
|
203
|
-
kernel:
|
|
139
|
+
kernel: kernelOperators
|
|
204
140
|
};
|
|
205
141
|
export { Evidence, OperatorDescription, Operators };
|
|
206
142
|
|
package/dist/operators.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operators.js","names":[],"sources":["../src/operators.ts"],"sourcesContent":["/**\n * How the in-memory interpreter runs primitive operators: a table of\n * implementations, passed to `evaluate` and every judge as a value. A table is\n * immutable and implements each operator once; nothing registers anything\n * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.\n */\nimport { Data, Equivalence, Option, Schema } from 'effect'\nimport { Collation } from './collation.js'\nimport type { Operator, OperatorDescriptor, OperatorTable } from './expr.js'\nimport { Law, LawDescription } from './law.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { tableTested, testedByRunner } from './tested.js'\nimport { Text } from './text.js'\n\n/** What an implementation is told besides its arguments. */\nexport interface OperatorContext {\n /** The collation the call compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** One operator's in-memory implementation: a pure function of stored values. */\nexport interface MemoryImplementation {\n readonly operator: OperatorDescriptor\n readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown\n}\n\n/**\n * What is known of a law of an implementation, past its operator claiming it\n * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'\n * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded\n * and never checked here.\n */\nexport type Evidence = Data.TaggedEnum<{\n Tested: {\n readonly operator: string\n readonly law: LawDescription\n readonly implementation: string\n readonly cases: number\n readonly seed: number\n }\n Proven: {\n readonly operator: string\n readonly law: LawDescription\n readonly reference: string\n readonly assumptions: ReadonlyArray<string>\n }\n}>\nexport const Evidence = Data.taggedEnum<Evidence>()\n\n/** A record of a law passing `Conformance.laws`' cases. */\nexport type TestedEvidence = Extract<Evidence, { readonly _tag: 'Tested' }>\n\n/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */\nconst JsonSchema = Schema.Record(Schema.String, Schema.Unknown)\n\n/**\n * An operator as JSON, by its signature and never its body (a defined\n * operator says `defined`, not what it means): what a server can publish of\n * what a body may call, and a client compare with what it runs. Its schemas\n * are each argument's and the result's stored side, as JSON Schemas.\n */\nexport const OperatorDescription = Schema.Struct({\n /** By id, and `@version` past the first: what tables, evidence and refusals name. */\n name: Schema.String,\n id: Schema.String,\n version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n description: Schema.NullOr(Schema.String),\n input: Schema.Array(JsonSchema),\n output: JsonSchema,\n nulls: Schema.Literals(['strict', 'handled']),\n collation: Schema.Literals(['none', 'operands', 'required']),\n laws: Schema.Array(LawDescription),\n defined: Schema.Boolean,\n})\nexport type OperatorDescription = typeof OperatorDescription.Type\n\n/** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */\nexport interface ImplementedOperator extends OperatorDescription {\n readonly evidence: ReadonlyArray<Evidence>\n}\n\nconst described = (operator: OperatorDescriptor): OperatorDescription => ({\n name: nameOf(operator),\n id: operator.id,\n version: operator.version,\n description: Option.getOrNull(operator.description),\n input: operator.input.map(jsonSchemaOf),\n output: jsonSchemaOf(operator.output),\n nulls: operator.nulls,\n collation: operator.collation,\n laws: operator.laws.map(Law.describe),\n defined: Option.isSome(operator.definedAs),\n})\n\n/** The in-memory interpreter's implementations, by operator. */\nexport interface MemoryOperators extends OperatorTable {\n readonly _tag: 'MemoryOperators'\n readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>\n /**\n * The operator it implements under a name (`id`, or `id@version` past the\n * first): how a computed assignment carried as data finds what to run.\n */\n readonly named: (name: string) => Option.Option<OperatorDescriptor>\n /** Whether each answer is checked against its operator's output schema: for tests. */\n readonly checked: boolean\n readonly implementations: ReadonlyArray<MemoryImplementation>\n /** What is known of its implementations' laws: `Operators.withEvidence`. */\n readonly evidence: ReadonlyArray<Evidence>\n}\n\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: OperatorDescriptor): string =>\n operator.version === 1 ? operator.id : `${operator.id}@${operator.version}`\n\nconst fail = (what: string): never => {\n throw new Error(`[foldkit-entity] Operators: ${what}`)\n}\n\nconst table = (\n implementations: ReadonlyArray<MemoryImplementation>,\n checked: boolean,\n evidence: ReadonlyArray<Evidence>,\n): MemoryOperators => {\n const byOperator = new Map<OperatorDescriptor, MemoryImplementation['run']>()\n const byName = new Map<string, OperatorDescriptor>()\n for (const { operator, run } of implementations) {\n if (byOperator.has(operator)) {\n fail(`${nameOf(operator)} is implemented twice; replace one with Operators.override`)\n }\n // Two descriptors under one name would leave a body's call ambiguous.\n const named = byName.get(nameOf(operator))\n if (named !== undefined && named !== operator) {\n fail(`two operators are named ${nameOf(operator)}; give one another id or version`)\n }\n byName.set(nameOf(operator), operator)\n byOperator.set(operator, run)\n }\n return Object.freeze({\n _tag: 'MemoryOperators',\n has: (operator: OperatorDescriptor) => byOperator.has(operator),\n versions: (id: string) =>\n implementations\n .filter(({ operator }) => operator.id === id)\n .map(({ operator }) => operator.version),\n get: (operator: OperatorDescriptor) => Option.fromUndefinedOr(byOperator.get(operator)),\n named: (name: string) => Option.fromUndefinedOr(byName.get(name)),\n checked,\n implementations: Object.freeze([...implementations]),\n evidence: Object.freeze([...evidence]),\n })\n}\n\n/** Whether two laws, as JSON, are the same law. */\nconst sameLaw = (left: LawDescription, right: LawDescription): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** What a table runs for the operator under `name`: none when it implements none. */\nconst runNamed = (operators: MemoryOperators, name: string) =>\n Option.flatMap(operators.named(name), operators.get)\n\nconst sameRun = Option.makeEquivalence(Equivalence.strictEqual<MemoryImplementation['run']>())\n\n/** An implementation, its operator's null rule checked against the function chosen for it. */\nconst implementation = (\n operator: OperatorDescriptor,\n nulls: OperatorDescriptor['nulls'],\n run: (...args: ReadonlyArray<unknown>) => unknown,\n): MemoryImplementation => {\n // SQL compiles what a defined operator means, so an implementation here would\n // be a second meaning that only memory runs.\n if (Option.isSome(operator.definedAs)) {\n fail(\n `${nameOf(operator)} is defined by an expression, which every interpreter runs; it takes no implementation`,\n )\n }\n if (operator.nulls !== nulls) {\n fail(\n nulls === 'strict'\n ? `${nameOf(operator)} handles null itself; implement it with Operators.implementHandlingNulls`\n : `${nameOf(operator)} is strict about null; implement it with Operators.implement`,\n )\n }\n return Object.freeze({\n operator,\n run: (args: ReadonlyArray<unknown>, context: OperatorContext) => run(...args, context),\n })\n}\n\nconst REPLACEMENT = String.fromCharCode(0xfffd)\n\n/**\n * Text's characters as a database holds them: a lone surrogate, which UTF-8\n * cannot encode, as U+FFFD, which SQLite's and Postgres's drivers send instead.\n */\nconst charactersOf = (text: string): ReadonlyArray<string> =>\n Array.from(text, each => {\n const code = each.codePointAt(0)!\n return code >= 0xd800 && code <= 0xdfff ? REPLACEMENT : each\n })\n\n/**\n * Whether `text` begins with `prefix` by character, as SQL's `substr` and\n * `left` count: `String.prototype.startsWith` compares UTF-16 units, so half\n * of an astral character would begin the text that holds all of it.\n */\nconst beginsWith = (text: string, prefix: string): boolean => {\n const [characters, start] = [charactersOf(text), charactersOf(prefix)]\n return start.length <= characters.length && start.every((each, i) => each === characters[i])\n}\n\nconst startsWith = implementation(Text.startsWith.descriptor, 'strict', (...given) => {\n const [text, prefix, { collation }] = given as [string, string, OperatorContext]\n const folded = Option.exists(collation, each => each._tag === 'AsciiFold')\n return folded\n ? beginsWith(Collation.foldAscii(text), Collation.foldAscii(prefix))\n : beginsWith(text, prefix)\n})\n\nexport const Operators = {\n /**\n * An implementation of a strict operator: a pure function of its arguments'\n * stored values, never given a null (the kernel answers null, or unknown, for\n * one first), and told the call's collation last.\n *\n * ```ts\n * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))\n * ```\n */\n implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>> }, OperatorContext]\n ) => StoredOf<Out>,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'strict',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /**\n * An implementation of an operator declared `nulls: 'handled'`: given nulls\n * as they are, it answers for them; a predicate answers `null` for unknown.\n */\n implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: StoredOf<In[K]> }, OperatorContext]\n ) => StoredOf<Out> | null,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'handled',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /** A table of implementations. One operator implemented twice, or two under one name, is refused. */\n memory: (...implementations: ReadonlyArray<MemoryImplementation>): MemoryOperators =>\n table(implementations, false, []),\n\n /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */\n merge: (left: MemoryOperators, right: MemoryOperators): MemoryOperators => {\n const both = right.implementations.filter(({ operator }) => left.has(operator))\n if (both.length > 0) {\n fail(\n `both tables implement ${both.map(({ operator }) => nameOf(operator)).join(', ')}; replace with Operators.override`,\n )\n }\n return table(\n [...left.implementations, ...right.implementations],\n left.checked || right.checked,\n [...left.evidence, ...right.evidence],\n )\n },\n\n /**\n * The table with these implementations in place of its own for the same\n * operators. Evidence of a replaced implementation goes with it: it was\n * that implementation's.\n */\n override: (\n base: MemoryOperators,\n ...implementations: ReadonlyArray<MemoryImplementation>\n ): MemoryOperators => {\n const replaced = new Set(implementations.map(({ operator }) => operator))\n const names = new Set([...replaced].map(nameOf))\n return table(\n [\n ...base.implementations.filter(({ operator }) => !replaced.has(operator)),\n ...implementations,\n ],\n base.checked,\n // A replaced operator's evidence goes, and so does a law's that called it as a witness.\n base.evidence.filter(\n ({ operator, law }) =>\n !names.has(operator) && !Law.witnessesNamed(law).some(name => names.has(name)),\n ),\n )\n },\n\n /**\n * The table with what is known of its implementations' laws recorded: each\n * record of an operator it implements and a law that operator declares.\n * `Conformance.laws` gives `Tested` records, each of the implementation it\n * ran, and a table takes only those of its own; `Evidence.Proven` says a\n * proof elsewhere covers one.\n */\n withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>): MemoryOperators => {\n const own = new Map(base.implementations.map(each => [nameOf(each.operator), each]))\n for (const record of evidence) {\n const implemented =\n own.get(record.operator) ??\n fail(`evidence names ${record.operator}, which this table does not implement`)\n if (!implemented.operator.laws.map(Law.describe).some(law => sameLaw(law, record.law))) {\n fail(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`)\n }\n if (record._tag !== 'Tested') continue\n // Evidence of another implementation, or of a runner, says nothing of this one.\n const tested = tableTested(record)\n if (!Option.exists(tested, table => table.implementations.includes(implemented))) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`,\n )\n }\n // Nor with another implementation of a witness the law calls (`distributes`, `inverse`).\n const other = Law.witnessesNamed(record.law).find(\n name =>\n !Option.exists(tested, table => sameRun(runNamed(table, name), runNamed(base, name))),\n )\n if (other !== undefined) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was tested with another implementation of ${other}, which it calls; test it with Conformance.laws(op, table)`,\n )\n }\n }\n return table(base.implementations, base.checked, [...base.evidence, ...evidence])\n },\n\n /**\n * The memory implementation `Conformance.laws` tested a record on; none for\n * a record of a runner (`Conformance.lawsBy`) or a proof.\n */\n testedOn: (record: Evidence): Option.Option<MemoryImplementation> =>\n Option.flatMap(tableTested(record), table =>\n Option.fromUndefinedOr(\n table.implementations.find(({ operator }) => nameOf(operator) === record.operator),\n ),\n ),\n\n /**\n * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL\n * table takes. Which runner it was, the database's or another, is the\n * caller's word; a record built by hand, copied, or tested in memory is not.\n */\n testedByRunner,\n\n /**\n * Each operator the table implements, by name, with the laws it declares and\n * the evidence the table records of them: what a server can publish of how\n * it runs a body. JSON as it is.\n */\n describeTable: (base: MemoryOperators): ReadonlyArray<ImplementedOperator> =>\n base.implementations.map(({ operator }) => ({\n ...described(operator),\n evidence: base.evidence.filter(record => record.operator === nameOf(operator)),\n })),\n\n /**\n * An operator as JSON (`OperatorDescription`): its name, version and\n * description, each argument's and its result's stored side as a JSON\n * Schema (as JSON carries it: a number also admits the strings `\"Infinity\"`,\n * `\"-Infinity\"` and `\"NaN\"`), its null and collation rules, its laws, and\n * whether it is defined. Its signature, never its body.\n */\n describe: (operator: { readonly descriptor: OperatorDescriptor }): OperatorDescription =>\n described(operator.descriptor),\n\n /**\n * The table, checking every answer against its operator's output schema, so\n * an implementation that answers the wrong kind fails where it answered. For\n * tests: it costs a decode per call.\n */\n checked: (base: MemoryOperators): MemoryOperators =>\n table(base.implementations, true, base.evidence),\n\n /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\n kernel: table([startsWith], false, []),\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,MAAa,WAAW,KAAK,WAAqB;;AAMlD,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;;;;;;;AAQ9D,MAAa,sBAAsB,OAAO,OAAO;;CAE/C,MAAM,OAAO;CACb,IAAI,OAAO;CACX,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC1D,aAAa,OAAO,OAAO,OAAO,MAAM;CACxC,OAAO,OAAO,MAAM,UAAU;CAC9B,QAAQ;CACR,OAAO,OAAO,SAAS,CAAC,UAAU,SAAS,CAAC;CAC5C,WAAW,OAAO,SAAS;EAAC;EAAQ;EAAY;CAAU,CAAC;CAC3D,MAAM,OAAO,MAAM,cAAc;CACjC,SAAS,OAAO;AAClB,CAAC;AAQD,MAAM,aAAa,cAAuD;CACxE,MAAM,OAAO,QAAQ;CACrB,IAAI,SAAS;CACb,SAAS,SAAS;CAClB,aAAa,OAAO,UAAU,SAAS,WAAW;CAClD,OAAO,SAAS,MAAM,IAAI,YAAY;CACtC,QAAQ,aAAa,SAAS,MAAM;CACpC,OAAO,SAAS;CAChB,WAAW,SAAS;CACpB,MAAM,SAAS,KAAK,IAAI,IAAI,QAAQ;CACpC,SAAS,OAAO,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I,OAAO,SAAS,UAAU;GAE9B,MAAM,SAAS,YAAY,MAAM;GACjC,IAAI,CAAC,OAAO,OAAO,SAAQ,UAAS,MAAM,gBAAgB,SAAS,WAAW,CAAC,GAC7E,KACE,eAAe,OAAO,SAAS,KAAK,OAAO,IAAI,KAAK,6FACtD;GAGF,MAAM,QAAQ,IAAI,eAAe,OAAO,GAAG,CAAC,CAAC,MAC3C,SACE,CAAC,OAAO,OAAO,SAAQ,UAAS,QAAQ,SAAS,OAAO,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC,CAAC,CACxF;GACA,IAAI,UAAU,KAAA,GACZ,KACE,eAAe,OAAO,SAAS,KAAK,OAAO,IAAI,KAAK,iDAAiD,MAAM,2DAC7G;EAEJ;EACA,OAAO,MAAM,KAAK,iBAAiB,KAAK,SAAS,CAAC,GAAG,KAAK,UAAU,GAAG,QAAQ,CAAC;CAClF;;;;;CAMA,WAAW,WACT,OAAO,QAAQ,YAAY,MAAM,IAAG,UAClC,OAAO,gBACL,MAAM,gBAAgB,MAAM,EAAE,eAAe,OAAO,QAAQ,MAAM,OAAO,QAAQ,CACnF,CACF;;;;;;CAOF;;;;;;CAOA,gBAAgB,SACd,KAAK,gBAAgB,KAAK,EAAE,gBAAgB;EAC1C,GAAG,UAAU,QAAQ;EACrB,UAAU,KAAK,SAAS,QAAO,WAAU,OAAO,aAAa,OAAO,QAAQ,CAAC;CAC/E,EAAE;;;;;;;;CASJ,WAAW,aACT,UAAU,SAAS,UAAU;;;;;;CAO/B,UAAU,SACR,MAAM,KAAK,iBAAiB,MAAM,KAAK,QAAQ;;CAGjD,QAAQ,MAAM,CAAC,UAAU,GAAG,OAAO,CAAC,CAAC;AACvC"}
|
|
1
|
+
{"version":3,"file":"operators.js","names":[],"sources":["../src/operators.ts"],"sourcesContent":["/**\n * How the in-memory interpreter runs primitive operators: a table of\n * implementations, passed to `evaluate` and every judge as a value. A table is\n * immutable and implements each operator once; nothing registers anything\n * globally. See `docs/design/expr-operations-DESIGN.md` §5.4.\n */\nimport type { Collation } from './collation.js'\nimport { Data, Equivalence, Option, Schema } from 'effect'\nimport type { Operator, OperatorDescriptor, OperatorTable } from './expr.js'\nimport { Law, LawDescription } from './law.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { tableTested, testedByRunner } from './tested.js'\nimport { fail, implementation, kernelOperators, nameOf, table } from './memoryTable.js'\n\n/** What an implementation is told besides its arguments. */\nexport interface OperatorContext {\n /** The collation the call compares text under, from its operator's `collation` rule. */\n readonly collation: Option.Option<Collation>\n}\n\n/** One operator's in-memory implementation: a pure function of stored values. */\nexport interface MemoryImplementation {\n readonly operator: OperatorDescriptor\n readonly run: (args: ReadonlyArray<unknown>, context: OperatorContext) => unknown\n}\n\n/**\n * What is known of a law of an implementation, past its operator claiming it\n * (expr-operations-DESIGN §10.3): `Tested`, it passed `Conformance.laws`'\n * cases; `Proven`, a proof elsewhere says so under its assumptions, recorded\n * and never checked here.\n */\nexport type Evidence = Data.TaggedEnum<{\n Tested: {\n readonly operator: string\n readonly law: LawDescription\n readonly implementation: string\n readonly cases: number\n readonly seed: number\n }\n Proven: {\n readonly operator: string\n readonly law: LawDescription\n readonly reference: string\n readonly assumptions: ReadonlyArray<string>\n }\n}>\nexport const Evidence = Data.taggedEnum<Evidence>()\n\n/** A record of a law passing `Conformance.laws`' cases. */\nexport type TestedEvidence = Extract<Evidence, { readonly _tag: 'Tested' }>\n\n/** A JSON Schema document's root: an object (`$defs` holds what it refers to). */\nconst JsonSchema = Schema.Record(Schema.String, Schema.Unknown)\n\n/**\n * An operator as JSON, by its signature and never its body (a defined\n * operator says `defined`, not what it means): what a server can publish of\n * what a body may call, and a client compare with what it runs. Its schemas\n * are each argument's and the result's stored side, as JSON Schemas.\n */\nexport const OperatorDescription = Schema.Struct({\n /** By id, and `@version` past the first: what tables, evidence and refusals name. */\n name: Schema.String,\n id: Schema.String,\n version: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n description: Schema.NullOr(Schema.String),\n input: Schema.Array(JsonSchema),\n output: JsonSchema,\n nulls: Schema.Literals(['strict', 'handled']),\n collation: Schema.Literals(['none', 'operands', 'required']),\n laws: Schema.Array(LawDescription),\n defined: Schema.Boolean,\n})\nexport type OperatorDescription = typeof OperatorDescription.Type\n\n/** One operator a table implements, as `Operators.describeTable` lists it: described, with its evidence. */\nexport interface ImplementedOperator extends OperatorDescription {\n readonly evidence: ReadonlyArray<Evidence>\n}\n\nconst described = (operator: OperatorDescriptor): OperatorDescription => ({\n name: nameOf(operator),\n id: operator.id,\n version: operator.version,\n description: Option.getOrNull(operator.description),\n input: operator.input.map(jsonSchemaOf),\n output: jsonSchemaOf(operator.output),\n nulls: operator.nulls,\n collation: operator.collation,\n laws: operator.laws.map(Law.describe),\n defined: Option.isSome(operator.definedAs),\n})\n\n/** The in-memory interpreter's implementations, by operator. */\nexport interface MemoryOperators extends OperatorTable {\n readonly _tag: 'MemoryOperators'\n readonly get: (operator: OperatorDescriptor) => Option.Option<MemoryImplementation['run']>\n /**\n * The operator it implements under a name (`id`, or `id@version` past the\n * first): how a computed assignment carried as data finds what to run.\n */\n readonly named: (name: string) => Option.Option<OperatorDescriptor>\n /** Whether each answer is checked against its operator's output schema: for tests. */\n readonly checked: boolean\n readonly implementations: ReadonlyArray<MemoryImplementation>\n /** What is known of its implementations' laws: `Operators.withEvidence`. */\n readonly evidence: ReadonlyArray<Evidence>\n}\n\ntype StoredOf<S extends Schema.Top> = Schema.Codec.Encoded<S>\n\n/** Whether two laws, as JSON, are the same law. */\nconst sameLaw = (left: LawDescription, right: LawDescription): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** What a table runs for the operator under `name`: none when it implements none. */\nconst runNamed = (operators: MemoryOperators, name: string) =>\n Option.flatMap(operators.named(name), operators.get)\n\nconst sameRun = Option.makeEquivalence(Equivalence.strictEqual<MemoryImplementation['run']>())\n\nexport const Operators = {\n /**\n * An implementation of a strict operator: a pure function of its arguments'\n * stored values, never given a null (the kernel answers null, or unknown, for\n * one first), and told the call's collation last.\n *\n * ```ts\n * Operators.implement(startsWith, (text, prefix, { collation }) => text.startsWith(prefix))\n * ```\n */\n implement: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: NonNullable<StoredOf<In[K]>> }, OperatorContext]\n ) => StoredOf<Out>,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'strict',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /**\n * An implementation of an operator declared `nulls: 'handled'`: given nulls\n * as they are, it answers for them; a predicate answers `null` for unknown.\n */\n implementHandlingNulls: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n operator: Operator<In, Out>,\n run: (\n ...args: [...{ readonly [K in keyof In]: StoredOf<In[K]> }, OperatorContext]\n ) => StoredOf<Out> | null,\n ): MemoryImplementation =>\n implementation(\n operator.descriptor,\n 'handled',\n run as (...args: ReadonlyArray<unknown>) => unknown,\n ),\n\n /** A table of implementations. One operator implemented twice, or two under one name, is refused. */\n memory: (...implementations: ReadonlyArray<MemoryImplementation>): MemoryOperators =>\n table(implementations, false, []),\n\n /** Both tables' implementations. An operator both implement is refused: say which wins with `override`. */\n merge: (left: MemoryOperators, right: MemoryOperators): MemoryOperators => {\n const both = right.implementations.filter(({ operator }) => left.has(operator))\n if (both.length > 0) {\n fail(\n `both tables implement ${both.map(({ operator }) => nameOf(operator)).join(', ')}; replace with Operators.override`,\n )\n }\n return table(\n [...left.implementations, ...right.implementations],\n left.checked || right.checked,\n [...left.evidence, ...right.evidence],\n )\n },\n\n /**\n * The table with these implementations in place of its own for the same\n * operators. Evidence of a replaced implementation goes with it: it was\n * that implementation's.\n */\n override: (\n base: MemoryOperators,\n ...implementations: ReadonlyArray<MemoryImplementation>\n ): MemoryOperators => {\n const replaced = new Set(implementations.map(({ operator }) => operator))\n const names = new Set([...replaced].map(nameOf))\n return table(\n [\n ...base.implementations.filter(({ operator }) => !replaced.has(operator)),\n ...implementations,\n ],\n base.checked,\n // A replaced operator's evidence goes, and so does a law's that called it as a witness.\n base.evidence.filter(\n ({ operator, law }) =>\n !names.has(operator) && !Law.witnessesNamed(law).some(name => names.has(name)),\n ),\n )\n },\n\n /**\n * The table with what is known of its implementations' laws recorded: each\n * record of an operator it implements and a law that operator declares.\n * `Conformance.laws` gives `Tested` records, each of the implementation it\n * ran, and a table takes only those of its own; `Evidence.Proven` says a\n * proof elsewhere covers one.\n */\n withEvidence: (base: MemoryOperators, evidence: ReadonlyArray<Evidence>): MemoryOperators => {\n const own = new Map(base.implementations.map(each => [nameOf(each.operator), each]))\n for (const record of evidence) {\n const implemented =\n own.get(record.operator) ??\n fail(`evidence names ${record.operator}, which this table does not implement`)\n if (!implemented.operator.laws.map(Law.describe).some(law => sameLaw(law, record.law))) {\n fail(`evidence names a law of ${record.operator} it does not declare (${record.law.kind})`)\n }\n if (record._tag !== 'Tested') continue\n // Evidence of another implementation, or of a runner, says nothing of this one.\n const tested = tableTested(record)\n if (!Option.exists(tested, table => table.implementations.includes(implemented))) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was not tested on this table's implementation; test it with Conformance.laws(op, table)`,\n )\n }\n // Nor with another implementation of a witness the law calls (`distributes`, `inverse`).\n const other = Law.witnessesNamed(record.law).find(\n name =>\n !Option.exists(tested, table => sameRun(runNamed(table, name), runNamed(base, name))),\n )\n if (other !== undefined) {\n fail(\n `evidence of ${record.operator}'s ${record.law.kind} law was tested with another implementation of ${other}, which it calls; test it with Conformance.laws(op, table)`,\n )\n }\n }\n return table(base.implementations, base.checked, [...base.evidence, ...evidence])\n },\n\n /**\n * The memory implementation `Conformance.laws` tested a record on; none for\n * a record of a runner (`Conformance.lawsBy`) or a proof.\n */\n testedOn: (record: Evidence): Option.Option<MemoryImplementation> =>\n Option.flatMap(tableTested(record), table =>\n Option.fromUndefinedOr(\n table.implementations.find(({ operator }) => nameOf(operator) === record.operator),\n ),\n ),\n\n /**\n * Whether `Conformance.lawsBy` made a record, through a runner: what an SQL\n * table takes. Which runner it was, the database's or another, is the\n * caller's word; a record built by hand, copied, or tested in memory is not.\n */\n testedByRunner,\n\n /**\n * Each operator the table implements, by name, with the laws it declares and\n * the evidence the table records of them: what a server can publish of how\n * it runs a body. JSON as it is.\n */\n describeTable: (base: MemoryOperators): ReadonlyArray<ImplementedOperator> =>\n base.implementations.map(({ operator }) => ({\n ...described(operator),\n evidence: base.evidence.filter(record => record.operator === nameOf(operator)),\n })),\n\n /**\n * An operator as JSON (`OperatorDescription`): its name, version and\n * description, each argument's and its result's stored side as a JSON\n * Schema (as JSON carries it: a number also admits the strings `\"Infinity\"`,\n * `\"-Infinity\"` and `\"NaN\"`), its null and collation rules, its laws, and\n * whether it is defined. Its signature, never its body.\n */\n describe: (operator: { readonly descriptor: OperatorDescriptor }): OperatorDescription =>\n described(operator.descriptor),\n\n /**\n * The table, checking every answer against its operator's output schema, so\n * an implementation that answers the wrong kind fails where it answered. For\n * tests: it costs a decode per call.\n */\n checked: (base: MemoryOperators): MemoryOperators =>\n table(base.implementations, true, base.evidence),\n\n /** The kernel's own operators (`Text.startsWith`): every memory interpreter's default. */\n kernel: kernelOperators,\n}\n"],"mappings":";;;;;;AA+CA,MAAa,WAAW,KAAK,WAAqB;;AAMlD,MAAM,aAAa,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;;;;;;;AAQ9D,MAAa,sBAAsB,OAAO,OAAO;;CAE/C,MAAM,OAAO;CACb,IAAI,OAAO;CACX,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC1D,aAAa,OAAO,OAAO,OAAO,MAAM;CACxC,OAAO,OAAO,MAAM,UAAU;CAC9B,QAAQ;CACR,OAAO,OAAO,SAAS,CAAC,UAAU,SAAS,CAAC;CAC5C,WAAW,OAAO,SAAS;EAAC;EAAQ;EAAY;CAAU,CAAC;CAC3D,MAAM,OAAO,MAAM,cAAc;CACjC,SAAS,OAAO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C7G;EAEJ;EACA,OAAO,MAAM,KAAK,iBAAiB,KAAK,SAAS,CAAC,GAAG,KAAK,UAAU,GAAG,QAAQ,CAAC;CAClF;;;;;CAMA,WAAW,WACT,OAAO,QAAQ,YAAY,MAAM,IAAG,UAClC,OAAO,gBACL,MAAM,gBAAgB,MAAM,EAAE,eAAe,OAAO,QAAQ,MAAM,OAAO,QAAQ,CACnF,CACF;;;;;;CAOF;;;;;;CAOA,gBAAgB,SACd,KAAK,gBAAgB,KAAK,EAAE,gBAAgB;EAC1C,GAAG,UAAU,QAAQ;EACrB,UAAU,KAAK,SAAS,QAAO,WAAU,OAAO,aAAa,OAAO,QAAQ,CAAC;CAC/E,EAAE;;;;;;;;CASJ,WAAW,aACT,UAAU,SAAS,UAAU;;;;;;CAO/B,UAAU,SACR,MAAM,KAAK,iBAAiB,MAAM,KAAK,QAAQ;;CAGjD,QAAQ;AACV"}
|
package/dist/refine.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
import { AnyEntity } from "./index.js";
|
|
3
|
+
import { BeforeRow } from "./invariant.js";
|
|
4
|
+
import { Row } from "./evaluate.js";
|
|
5
|
+
import { Predicate, Reads } from "./expr.js";
|
|
6
|
+
import { MemoryOperators as MemoryOperators$1 } from "./operators.js";
|
|
7
|
+
/**
|
|
8
|
+
* A named state of `E`'s row. `Narrow` is what `is` narrows a row to: the
|
|
9
|
+
* fields a literal form names, nothing for a predicate form.
|
|
10
|
+
*/
|
|
11
|
+
export interface Refinement<E extends AnyEntity, Name extends string, Narrow> {
|
|
12
|
+
readonly _tag: 'Refinement';
|
|
13
|
+
readonly entity: E;
|
|
14
|
+
readonly name: Name;
|
|
15
|
+
/** Over the row as stored: a `Query.where`, a guard row rule, a write's `when`. */
|
|
16
|
+
readonly predicate: Predicate & Reads<E['name']>;
|
|
17
|
+
/**
|
|
18
|
+
* Over the row a write leaves (each field as `Expr.next`): what an invariant
|
|
19
|
+
* reads. Throws for a refinement that reaches another row.
|
|
20
|
+
*/
|
|
21
|
+
readonly after: Predicate & Reads<E['name']>;
|
|
22
|
+
/** Whether it reads its own row alone: only such a one is a write's `from` or `becomes`. */
|
|
23
|
+
readonly local: boolean;
|
|
24
|
+
/** The fields of its own row it reads, by key. */
|
|
25
|
+
readonly reads: ReadonlyArray<string>;
|
|
26
|
+
/**
|
|
27
|
+
* Whether a row (as an application holds it, decoded) is definitely in the
|
|
28
|
+
* state, narrowing the fields a literal form names. False where it lacks a
|
|
29
|
+
* field the state reads, and for a refinement reaching another row.
|
|
30
|
+
*/
|
|
31
|
+
is<R extends object>(row: R): row is R & Narrow;
|
|
32
|
+
}
|
|
33
|
+
export type AnyRefinement = Refinement<AnyEntity, string, unknown>;
|
|
34
|
+
/** A refinement of the Entity named `Name`, as a write over any descriptor of it takes one. */
|
|
35
|
+
export type RefinementOf<E extends AnyEntity> = Refinement<AnyEntity & {
|
|
36
|
+
readonly name: E['name'];
|
|
37
|
+
}, string, unknown>;
|
|
38
|
+
/** The literal form: a value per field, each typed by what the field stores. */
|
|
39
|
+
export type RefinementLiteral<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]?: Schema.Codec.Encoded<E['fields'][K]['schema']>; };
|
|
40
|
+
/** The predicate form: built over `row`, each field as `Expr.field`, and nothing of the past. */
|
|
41
|
+
export type RefinementBuild<E extends AnyEntity> = (rows: {
|
|
42
|
+
readonly row: BeforeRow<E>;
|
|
43
|
+
}) => Predicate & Reads<E['name']>;
|
|
44
|
+
/**
|
|
45
|
+
* Declares a named state of `entity`'s row, on the Entity itself (every
|
|
46
|
+
* descriptor of it sees it), and returns it. The literal form is a value per
|
|
47
|
+
* field (`{ status: 'draft' }`); the predicate form is built over `row`
|
|
48
|
+
* (`({ row }) => Expr.gt(row.stock, row.reserved)`), and may reach another
|
|
49
|
+
* row (`Expr.exists`, `Expr.path`), which makes it no write's `from` or
|
|
50
|
+
* `becomes`. A name declared twice on one Entity throws.
|
|
51
|
+
*/
|
|
52
|
+
export declare function refine<E extends AnyEntity, const Name extends string, const L extends RefinementLiteral<E>>(entity: E, name: Name, literal: L & { readonly [K in Exclude<keyof L, keyof E['fields']>]: never; }): Refinement<E, Name, { readonly [K in keyof L]: L[K]; }>;
|
|
53
|
+
export declare function refine<E extends AnyEntity, const Name extends string>(entity: E, name: Name, build: RefinementBuild<E>): Refinement<E, Name, {}>;
|
|
54
|
+
/** Every state declared on the Entity, in the order they were declared. */
|
|
55
|
+
export declare const states: (entity: AnyEntity) => ReadonlyArray<AnyRefinement>;
|
|
56
|
+
/**
|
|
57
|
+
* Whether a row as stored (encoded, as `Entity.judge` reads it) is in the
|
|
58
|
+
* state: none where the row lacks a field the state reads, an operator it calls
|
|
59
|
+
* is not in `operators`, or the state reaches another row.
|
|
60
|
+
*/
|
|
61
|
+
export declare const inState: (refinement: AnyRefinement, row: Row, operators?: MemoryOperators$1) => Option.Option<boolean>;
|
|
62
|
+
/** Refuses a refinement of another Entity, or one reaching another row, as a write's `role`. */
|
|
63
|
+
export declare const localTo: (entity: AnyEntity, refinement: AnyRefinement, role: 'from' | 'becomes') => AnyRefinement;
|
|
64
|
+
//# sourceMappingURL=refine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refine.d.ts","names":["MemoryOperators"],"sources":["../src/refine.ts"],"mappings":";;;;;;;;;;iBA+BiB,WAAW,UAAU,WAAW,qBAAqB;WAC3D;WACA,QAAQ;WACR,MAAM;;WAEN,WAAW,YAAY,MAAM;;;;;WAK7B,OAAO,YAAY,MAAM;;WAEzB;;WAEA,OAAO;;;;;;EAMhB,GAAG,kBAAkB,KAAK,IAAI,OAAO,IAAI;;YAG/B,gBAAgB,WAAW;;YAG3B,aAAa,UAAU,aAAa,WAC9C;WAAuB,MAAM;;;YAMnB,kBAAkB,UAAU,yBAC5B,WAAW,wBAAwB,OAAO,MAAM,QAAQ,YAAY;;YAIpE,gBAAgB,UAAU,cAAc;WACzC,KAAK,UAAU;MACpB,YAAY,MAAM;;;;;;;;;wBAuER,OACd,UAAU,iBACJ,2BACA,UAAU,kBAAkB,IAElC,QAAQ,GACR,MAAM,MACN,SAAS,gBAAgB,KAAK,cAAc,SAAS,0BACpD,WAAW,GAAG,kBAAkB,WAAW,IAAI,EAAE;wBACpC,OAAO,UAAU,iBAAiB,qBAChD,QAAQ,GACR,MAAM,MACN,OAAO,gBAAgB,KACtB,WAAW,GAAG;;qBA2DJ,SAAM,QAAY,cAAY,cAAc;;;;;;qBAQ5C,UAAO,YACN,eAAa,KACpB,KAAG,YACGA,sBACV,OAAO;;qBAGG,UAAO,QACV,WAAS,YACL,eAAa,6BAExB"}
|
package/dist/refine.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Match, Option, Schema } from "effect";
|
|
2
|
+
import { heldRow, oneRelations } from "./rows.js";
|
|
3
|
+
import { Judge, OperatorMissingError } from "./evaluate.js";
|
|
4
|
+
import { Expr, Query, nameNode } from "./expr.js";
|
|
5
|
+
import { kernelOperators } from "./memoryTable.js";
|
|
6
|
+
// src/refine.ts
|
|
7
|
+
/**
|
|
8
|
+
* Refinements: a named state of an Entity's row (`Draft`, `Published`,
|
|
9
|
+
* `InStock`), declared once on the Entity and read as a value. Not a
|
|
10
|
+
* descriptor: every reader of an Entity would have to tell one apart, and one
|
|
11
|
+
* that did not would treat `Draft` as `Product` and say nothing. A query, a
|
|
12
|
+
* guard rule or a write's `from` and `becomes` read the predicate it holds.
|
|
13
|
+
*/
|
|
14
|
+
const declared = /* @__PURE__ */ new WeakMap();
|
|
15
|
+
const fail$1 = (entity, name, message) => {
|
|
16
|
+
throw new Error(`[foldkit-entity] Entity.refine ${entity.name}.${name}: ${message}`);
|
|
17
|
+
};
|
|
18
|
+
/** The row `build` reads: each field, and each `one` relation as the id it points at, read by `read`. */
|
|
19
|
+
const rowOf = (entity, read) => {
|
|
20
|
+
const links = oneRelations(entity);
|
|
21
|
+
return Object.fromEntries([...Object.entries(entity.fields).map(([key, field]) => [key, read(field)]), ...links.map((link) => [link.key, read(link)])]);
|
|
22
|
+
};
|
|
23
|
+
const literalPredicate = (entity, name, literal, row) => {
|
|
24
|
+
const fields = entity.fields;
|
|
25
|
+
const checks = Object.entries(literal).map(([key, value]) => {
|
|
26
|
+
if (!Object.hasOwn(fields, key)) return fail$1(entity, name, `"${key}" is not a field`);
|
|
27
|
+
const stored = Schema.toEncoded(fields[key].schema);
|
|
28
|
+
if (!Schema.is(stored)(value)) fail$1(entity, name, `${JSON.stringify(value)} is no value "${key}" stores`);
|
|
29
|
+
return value === null ? Expr.isNull(row[key]) : Expr.eq(row[key], value);
|
|
30
|
+
});
|
|
31
|
+
if (checks.length === 0) fail$1(entity, name, "the literal form names no field");
|
|
32
|
+
return checks.length === 1 ? checks[0] : Expr.and(checks[0], ...checks.slice(1));
|
|
33
|
+
};
|
|
34
|
+
/** Whether a stored row is in the state: none where it lacks a field the state reads. */
|
|
35
|
+
const judged = (refinement, row, operators) => {
|
|
36
|
+
if (!refinement.local) return Option.none();
|
|
37
|
+
try {
|
|
38
|
+
const verdict = Judge.predicate(refinement.predicate, heldRow(refinement.entity, row), { operators });
|
|
39
|
+
return Match.valueTags(verdict, {
|
|
40
|
+
Unknown: () => Option.none(),
|
|
41
|
+
Known: ({ truth }) => Option.some(truth === true)
|
|
42
|
+
});
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error instanceof OperatorMissingError) return Option.none();
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
function refine(entity, name, form) {
|
|
49
|
+
if (name.length === 0) fail$1(entity, name, "a state needs a name");
|
|
50
|
+
const known = declared.get(entity.identity) ?? [];
|
|
51
|
+
if (known.some((state) => state.name === name)) fail$1(entity, name, "is declared twice");
|
|
52
|
+
const build = (row) => typeof form === "function" ? form({ row }) : literalPredicate(entity, name, form, row);
|
|
53
|
+
const predicate = build(rowOf(entity, (member) => Expr.field(member)));
|
|
54
|
+
const read = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)));
|
|
55
|
+
if (read.inputs.length > 0) fail$1(entity, name, `reads the input ${read.inputs.join(", ")}; a state is of the row alone`);
|
|
56
|
+
if (read.next.length > 0) fail$1(entity, name, "reads the row after a write; build it over `row`");
|
|
57
|
+
const local = read.reaches.length === 0;
|
|
58
|
+
const after = local ? Option.some(build(rowOf(entity, (member) => Expr.next(member)))) : Option.none();
|
|
59
|
+
nameNode(predicate, `${entity.name}.${name}`);
|
|
60
|
+
Option.map(after, (node) => nameNode(node, `next ${entity.name}.${name}`));
|
|
61
|
+
const reads = Object.freeze(read.predicate.map((field) => field.key));
|
|
62
|
+
const refinement = Object.freeze({
|
|
63
|
+
_tag: "Refinement",
|
|
64
|
+
entity,
|
|
65
|
+
name,
|
|
66
|
+
predicate,
|
|
67
|
+
get after() {
|
|
68
|
+
return Option.getOrElse(after, () => fail$1(entity, name, "reaches another row, so it has no row after a write"));
|
|
69
|
+
},
|
|
70
|
+
local,
|
|
71
|
+
reads,
|
|
72
|
+
is: (row) => {
|
|
73
|
+
const fields = entity.fields;
|
|
74
|
+
const values = row;
|
|
75
|
+
const stored = {};
|
|
76
|
+
for (const key of reads) {
|
|
77
|
+
if (!Object.hasOwn(values, key)) return false;
|
|
78
|
+
const encoded = Schema.encodeUnknownOption(fields[key].schema)(values[key]);
|
|
79
|
+
if (Option.isNone(encoded)) return false;
|
|
80
|
+
stored[key] = encoded.value;
|
|
81
|
+
}
|
|
82
|
+
return Option.getOrElse(judged(refinement, stored, kernelOperators), () => false);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
declared.set(entity.identity, [...known, refinement]);
|
|
86
|
+
return refinement;
|
|
87
|
+
}
|
|
88
|
+
/** Every state declared on the Entity, in the order they were declared. */
|
|
89
|
+
const states = (entity) => declared.get(entity.identity) ?? [];
|
|
90
|
+
/**
|
|
91
|
+
* Whether a row as stored (encoded, as `Entity.judge` reads it) is in the
|
|
92
|
+
* state: none where the row lacks a field the state reads, an operator it calls
|
|
93
|
+
* is not in `operators`, or the state reaches another row.
|
|
94
|
+
*/
|
|
95
|
+
const inState = (refinement, row, operators = kernelOperators) => judged(refinement, row, operators);
|
|
96
|
+
/** Refuses a refinement of another Entity, or one reaching another row, as a write's `role`. */
|
|
97
|
+
const localTo = (entity, refinement, role) => {
|
|
98
|
+
if (refinement.entity.identity !== entity.identity) throw new Error(`[foldkit-entity] Write of ${entity.name}: its ${role} is ${refinement.entity.name}.${refinement.name}, a state of another Entity`);
|
|
99
|
+
if (!refinement.local) throw new Error(`[foldkit-entity] Write of ${entity.name}: its ${role} ${entity.name}.${refinement.name} reaches another row, and a writer judges the row it writes alone`);
|
|
100
|
+
return refinement;
|
|
101
|
+
};
|
|
102
|
+
export { inState, localTo, refine, states };
|
|
103
|
+
|
|
104
|
+
//# sourceMappingURL=refine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refine.js","names":["fail"],"sources":["../src/refine.ts"],"sourcesContent":["/**\n * Refinements: a named state of an Entity's row (`Draft`, `Published`,\n * `InStock`), declared once on the Entity and read as a value. Not a\n * descriptor: every reader of an Entity would have to tell one apart, and one\n * that did not would treat `Draft` as `Product` and say nothing. A query, a\n * guard rule or a write's `from` and `becomes` read the predicate it holds.\n */\nimport { Match, Option, Schema } from 'effect'\nimport { Judge, OperatorMissingError, type Row } from './evaluate.js'\nimport {\n Expr,\n Query,\n nameNode,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport type { AnyEntity, EntityField, EntityIdentity } from './index.js'\nimport type { BeforeRow } from './invariant.js'\nimport { kernelOperators } from './memoryTable.js'\nimport { heldRow, oneRelations } from './rows.js'\nimport type { MemoryOperators } from './operators.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/**\n * A named state of `E`'s row. `Narrow` is what `is` narrows a row to: the\n * fields a literal form names, nothing for a predicate form.\n */\nexport interface Refinement<E extends AnyEntity, Name extends string, Narrow> {\n readonly _tag: 'Refinement'\n readonly entity: E\n readonly name: Name\n /** Over the row as stored: a `Query.where`, a guard row rule, a write's `when`. */\n readonly predicate: Predicate & Reads<E['name']>\n /**\n * Over the row a write leaves (each field as `Expr.next`): what an invariant\n * reads. Throws for a refinement that reaches another row.\n */\n readonly after: Predicate & Reads<E['name']>\n /** Whether it reads its own row alone: only such a one is a write's `from` or `becomes`. */\n readonly local: boolean\n /** The fields of its own row it reads, by key. */\n readonly reads: ReadonlyArray<string>\n /**\n * Whether a row (as an application holds it, decoded) is definitely in the\n * state, narrowing the fields a literal form names. False where it lacks a\n * field the state reads, and for a refinement reaching another row.\n */\n is<R extends object>(row: R): row is R & Narrow\n}\n\nexport type AnyRefinement = Refinement<AnyEntity, string, unknown>\n\n/** A refinement of the Entity named `Name`, as a write over any descriptor of it takes one. */\nexport type RefinementOf<E extends AnyEntity> = Refinement<\n AnyEntity & { readonly name: E['name'] },\n string,\n unknown\n>\n\n/** The literal form: a value per field, each typed by what the field stores. */\nexport type RefinementLiteral<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]?: Schema.Codec.Encoded<E['fields'][K]['schema']>\n}\n\n/** The predicate form: built over `row`, each field as `Expr.field`, and nothing of the past. */\nexport type RefinementBuild<E extends AnyEntity> = (rows: {\n readonly row: BeforeRow<E>\n}) => Predicate & Reads<E['name']>\n\nconst declared = new WeakMap<EntityIdentity<string>, Array<AnyRefinement>>()\n\nconst fail = (entity: AnyEntity, name: string, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.refine ${entity.name}.${name}: ${message}`)\n}\n\n/** The row `build` reads: each field, and each `one` relation as the id it points at, read by `read`. */\nconst rowOf = (\n entity: AnyEntity,\n read: (member: AnyField | OneRelation) => FieldExpr<unknown> | NextExpr<unknown>,\n): Readonly<Record<string, unknown>> => {\n const links = oneRelations(entity)\n return Object.fromEntries([\n ...Object.entries(entity.fields as Readonly<Record<string, AnyField>>).map(\n ([key, field]) => [key, read(field)] as const,\n ),\n ...links.map(link => [link.key, read(link)] as const),\n ])\n}\n\nconst literalPredicate = (\n entity: AnyEntity,\n name: string,\n literal: Readonly<Record<string, unknown>>,\n row: Readonly<Record<string, unknown>>,\n): Predicate => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const checks = Object.entries(literal).map(([key, value]) => {\n if (!Object.hasOwn(fields, key)) return fail(entity, name, `\"${key}\" is not a field`)\n const stored = Schema.toEncoded(fields[key]!.schema as unknown as Schema.Top)\n if (!Schema.is(stored as Schema.Codec<unknown>)(value))\n fail(entity, name, `${JSON.stringify(value)} is no value \"${key}\" stores`)\n return value === null\n ? Expr.isNull(row[key] as FieldExpr<unknown>)\n : Expr.eq(row[key] as FieldExpr<unknown>, value as never)\n })\n if (checks.length === 0) fail(entity, name, 'the literal form names no field')\n return checks.length === 1 ? checks[0]! : Expr.and(checks[0]!, ...checks.slice(1))\n}\n\n/** Whether a stored row is in the state: none where it lacks a field the state reads. */\nconst judged = (\n refinement: AnyRefinement,\n row: Row,\n operators: MemoryOperators,\n): Option.Option<boolean> => {\n if (!refinement.local) return Option.none()\n try {\n const verdict = Judge.predicate(refinement.predicate, heldRow(refinement.entity, row), {\n operators,\n })\n return Match.valueTags(verdict, {\n Unknown: () => Option.none(),\n Known: ({ truth }) => Option.some(truth === true),\n })\n } catch (error) {\n if (error instanceof OperatorMissingError) return Option.none()\n throw error\n }\n}\n\n/**\n * Declares a named state of `entity`'s row, on the Entity itself (every\n * descriptor of it sees it), and returns it. The literal form is a value per\n * field (`{ status: 'draft' }`); the predicate form is built over `row`\n * (`({ row }) => Expr.gt(row.stock, row.reserved)`), and may reach another\n * row (`Expr.exists`, `Expr.path`), which makes it no write's `from` or\n * `becomes`. A name declared twice on one Entity throws.\n */\nexport function refine<\n E extends AnyEntity,\n const Name extends string,\n const L extends RefinementLiteral<E>,\n>(\n entity: E,\n name: Name,\n literal: L & { readonly [K in Exclude<keyof L, keyof E['fields']>]: never },\n): Refinement<E, Name, { readonly [K in keyof L]: L[K] }>\nexport function refine<E extends AnyEntity, const Name extends string>(\n entity: E,\n name: Name,\n build: RefinementBuild<E>,\n): Refinement<E, Name, {}>\nexport function refine(\n entity: AnyEntity,\n name: string,\n form: Readonly<Record<string, unknown>> | RefinementBuild<AnyEntity>,\n): AnyRefinement {\n if (name.length === 0) fail(entity, name, 'a state needs a name')\n const known = declared.get(entity.identity) ?? []\n if (known.some(state => state.name === name)) fail(entity, name, 'is declared twice')\n const build = (row: Readonly<Record<string, unknown>>): Predicate =>\n typeof form === 'function'\n ? (form({ row: row as BeforeRow<AnyEntity> }) as Predicate)\n : literalPredicate(entity, name, form, row)\n const predicate = build(rowOf(entity, member => Expr.field(member as never)))\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const read = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n if (read.inputs.length > 0)\n fail(entity, name, `reads the input ${read.inputs.join(', ')}; a state is of the row alone`)\n if (read.next.length > 0) fail(entity, name, 'reads the row after a write; build it over `row`')\n const local = read.reaches.length === 0\n // Built again over the row after, as an invariant's `after` is; a reach would still read the row before.\n const after = local\n ? Option.some(build(rowOf(entity, member => Expr.next(member as never) as never)))\n : Option.none<Predicate>()\n nameNode(predicate, `${entity.name}.${name}`)\n Option.map(after, node => nameNode(node, `next ${entity.name}.${name}`))\n const reads = Object.freeze(read.predicate.map(field => field.key))\n const refinement: AnyRefinement = Object.freeze({\n _tag: 'Refinement' as const,\n entity,\n name,\n predicate,\n get after(): Predicate {\n return Option.getOrElse(after, () =>\n fail(entity, name, 'reaches another row, so it has no row after a write'),\n )\n },\n local,\n reads,\n is: (row: object): row is never => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const values = row as Readonly<Record<string, unknown>>\n const stored: Record<string, unknown> = {}\n for (const key of reads) {\n if (!Object.hasOwn(values, key)) return false\n const encoded = Schema.encodeUnknownOption(\n fields[key]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(values[key])\n if (Option.isNone(encoded)) return false\n stored[key] = encoded.value\n }\n return Option.getOrElse(judged(refinement, stored, kernelOperators), () => false)\n },\n })\n declared.set(entity.identity, [...known, refinement])\n return refinement\n}\n\n/** Every state declared on the Entity, in the order they were declared. */\nexport const states = (entity: AnyEntity): ReadonlyArray<AnyRefinement> =>\n declared.get(entity.identity) ?? []\n\n/**\n * Whether a row as stored (encoded, as `Entity.judge` reads it) is in the\n * state: none where the row lacks a field the state reads, an operator it calls\n * is not in `operators`, or the state reaches another row.\n */\nexport const inState = (\n refinement: AnyRefinement,\n row: Row,\n operators: MemoryOperators = kernelOperators,\n): Option.Option<boolean> => judged(refinement, row, operators)\n\n/** Refuses a refinement of another Entity, or one reaching another row, as a write's `role`. */\nexport const localTo = (\n entity: AnyEntity,\n refinement: AnyRefinement,\n role: 'from' | 'becomes',\n): AnyRefinement => {\n if (refinement.entity.identity !== entity.identity)\n throw new Error(\n `[foldkit-entity] Write of ${entity.name}: its ${role} is ${refinement.entity.name}.${refinement.name}, a state of another Entity`,\n )\n if (!refinement.local)\n throw new Error(\n `[foldkit-entity] Write of ${entity.name}: its ${role} ${entity.name}.${refinement.name} reaches another row, and a writer judges the row it writes alone`,\n )\n return refinement\n}\n"],"mappings":";;;;;;;;;;;;;AAyEA,MAAM,2BAAW,IAAI,QAAsD;AAE3E,MAAMA,UAAQ,QAAmB,MAAc,YAA2B;CACxE,MAAM,IAAI,MAAM,kCAAkC,OAAO,KAAK,GAAG,KAAK,IAAI,SAAS;AACrF;;AAGA,MAAM,SACJ,QACA,SACsC;CACtC,MAAM,QAAQ,aAAa,MAAM;CACjC,OAAO,OAAO,YAAY,CACxB,GAAG,OAAO,QAAQ,OAAO,MAA4C,CAAC,CAAC,KACpE,CAAC,KAAK,WAAW,CAAC,KAAK,KAAK,KAAK,CAAC,CACrC,GACA,GAAG,MAAM,KAAI,SAAQ,CAAC,KAAK,KAAK,KAAK,IAAI,CAAC,CAAU,CACtD,CAAC;AACH;AAEA,MAAM,oBACJ,QACA,MACA,SACA,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CAAC,OAAO,IAAI;IACb,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO;IACnC,OAAO,OAAO,QAAQ;GACxB;GACA,OAAO,OAAO,UAAU,OAAO,YAAY,QAAQ,eAAe,SAAS,KAAK;EAClF;CACF,CAAC;CACD,SAAS,IAAI,OAAO,UAAU,CAAC,GAAG,OAAO,UAAU,CAAC;CACpD,OAAO;AACT;;AAGA,MAAa,UAAU,WACrB,SAAS,IAAI,OAAO,QAAQ,KAAK,CAAC;;;;;;AAOpC,MAAa,WACX,YACA,KACA,YAA6B,oBACF,OAAO,YAAY,KAAK,SAAS;;AAG9D,MAAa,WACX,QACA,YACA,SACkB;CAClB,IAAI,WAAW,OAAO,aAAa,OAAO,UACxC,MAAM,IAAI,MACR,6BAA6B,OAAO,KAAK,QAAQ,KAAK,MAAM,WAAW,OAAO,KAAK,GAAG,WAAW,KAAK,4BACxG;CACF,IAAI,CAAC,WAAW,OACd,MAAM,IAAI,MACR,6BAA6B,OAAO,KAAK,QAAQ,KAAK,GAAG,OAAO,KAAK,GAAG,WAAW,KAAK,kEAC1F;CACF,OAAO;AACT"}
|
package/dist/rows.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { AnyEntity } from "./index.js";
|
|
3
|
+
import { Row } from "./evaluate.js";
|
|
4
|
+
import { OneRelation } from "./expr.js";
|
|
5
|
+
/** An Entity's `one` relations: a row holds each as the id it points at; a `many` holds no one value. */
|
|
6
|
+
export declare const oneRelations: (entity: AnyEntity) => ReadonlyArray<OneRelation>;
|
|
7
|
+
/** A row as stored, held: a key it lacks is unheld, so a rule reading it is undecided. */
|
|
8
|
+
export declare const heldRow: (entity: AnyEntity, row: Row) => import("./held.js").HeldRow;
|
|
9
|
+
/**
|
|
10
|
+
* The id a `one` relation's value names, as a row holds it: a ref's or a
|
|
11
|
+
* nested Selection value's `id`, an id as it is, and null for one pointing
|
|
12
|
+
* nowhere. None for a value naming no id (a nested Selection that left `id` out).
|
|
13
|
+
*/
|
|
14
|
+
export declare const linkId: (held: unknown) => Option.Option<string | number | null>;
|
|
15
|
+
//# sourceMappingURL=rows.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rows.d.ts","names":[],"sources":["../src/rows.ts"],"mappings":";;;;;qBAQa,eAAY,QAAY,cAAY,cAAc;;qBAWlD,UAAO,QAAY,WAAS,KAAO,4BAAG;;;;;;qBAYtC,SAAM,kBAAoB,OAAO"}
|
package/dist/rows.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Match, Option } from "effect";
|
|
2
|
+
import { Held } from "./held.js";
|
|
3
|
+
// src/rows.ts
|
|
4
|
+
/** What invariants, refinements and the enumerator share in reading an Entity's rows. */
|
|
5
|
+
/** An Entity's `one` relations: a row holds each as the id it points at; a `many` holds no one value. */
|
|
6
|
+
const oneRelations = (entity) => Object.values(entity.relations).flatMap((member) => Match.value(member).pipe(Match.tag("Relation", (relation) => relation.cardinality === "one" ? [relation] : []), Match.orElse(() => [])));
|
|
7
|
+
/** A row as stored, held: a key it lacks is unheld, so a rule reading it is undecided. */
|
|
8
|
+
const heldRow = (entity, row) => Held.rows([{
|
|
9
|
+
entity,
|
|
10
|
+
rows: [row],
|
|
11
|
+
complete: false
|
|
12
|
+
}]).rows(entity)[0];
|
|
13
|
+
/** An id as an Entity's id Schema may type it. */
|
|
14
|
+
const isId = (value) => typeof value === "string" || typeof value === "number";
|
|
15
|
+
/**
|
|
16
|
+
* The id a `one` relation's value names, as a row holds it: a ref's or a
|
|
17
|
+
* nested Selection value's `id`, an id as it is, and null for one pointing
|
|
18
|
+
* nowhere. None for a value naming no id (a nested Selection that left `id` out).
|
|
19
|
+
*/
|
|
20
|
+
const linkId = (held) => held === null ? Option.some(null) : isId(held) ? Option.some(held) : typeof held === "object" && "id" in held && isId(held.id) ? Option.some(held.id) : Option.none();
|
|
21
|
+
export { heldRow, linkId, oneRelations };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=rows.js.map
|
package/dist/rows.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rows.js","names":[],"sources":["../src/rows.ts"],"sourcesContent":["/** What invariants, refinements and the enumerator share in reading an Entity's rows. */\nimport { Match, Option } from 'effect'\nimport type { Row } from './evaluate.js'\nimport { Held } from './held.js'\nimport type { OneRelation } from './expr.js'\nimport type { AnyEntity, EntityMember } from './index.js'\n\n/** An Entity's `one` relations: a row holds each as the id it points at; a `many` holds no one value. */\nexport const oneRelations = (entity: AnyEntity): ReadonlyArray<OneRelation> =>\n Object.values(entity.relations as Readonly<Record<string, EntityMember>>).flatMap(member =>\n Match.value(member).pipe(\n Match.tag('Relation', relation =>\n relation.cardinality === 'one' ? [relation as OneRelation] : [],\n ),\n Match.orElse(() => []),\n ),\n )\n\n/** A row as stored, held: a key it lacks is unheld, so a rule reading it is undecided. */\nexport const heldRow = (entity: AnyEntity, row: Row) =>\n Held.rows([{ entity, rows: [row], complete: false }]).rows(entity)[0]!\n\n/** An id as an Entity's id Schema may type it. */\nconst isId = (value: unknown): value is string | number =>\n typeof value === 'string' || typeof value === 'number'\n\n/**\n * The id a `one` relation's value names, as a row holds it: a ref's or a\n * nested Selection value's `id`, an id as it is, and null for one pointing\n * nowhere. None for a value naming no id (a nested Selection that left `id` out).\n */\nexport const linkId = (held: unknown): Option.Option<string | number | null> =>\n held === null\n ? Option.some(null)\n : isId(held)\n ? Option.some(held)\n : typeof held === 'object' && 'id' in held && isId(held.id)\n ? Option.some(held.id)\n : Option.none()\n"],"mappings":";;;;;AAQA,MAAa,gBAAgB,WAC3B,OAAO,OAAO,OAAO,SAAmD,CAAC,CAAC,SAAQ,WAChF,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,IAAI,aAAY,aACpB,SAAS,gBAAgB,QAAQ,CAAC,QAAuB,IAAI,CAAC,CAChE,GACA,MAAM,aAAa,CAAC,CAAC,CACvB,CACF;;AAGF,MAAa,WAAW,QAAmB,QACzC,KAAK,KAAK,CAAC;CAAE;CAAQ,MAAM,CAAC,GAAG;CAAG,UAAU;AAAM,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC;;AAGrE,MAAM,QAAQ,UACZ,OAAO,UAAU,YAAY,OAAO,UAAU;;;;;;AAOhD,MAAa,UAAU,SACrB,SAAS,OACL,OAAO,KAAK,IAAI,IAChB,KAAK,IAAI,IACP,OAAO,KAAK,IAAI,IAChB,OAAO,SAAS,YAAY,QAAQ,QAAQ,KAAK,KAAK,EAAE,IACtD,OAAO,KAAK,KAAK,EAAE,IACnB,OAAO,KAAK"}
|
package/dist/sets.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sets.js","names":[],"sources":["../src/sets.ts"],"sourcesContent":["/**\n * What `Entity.sets` declares: members whose value is the write's context,\n * never its input, and the writes that set them.\n */\nimport { Match, Schema, SchemaAST } from 'effect'\nimport type { NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { AnyEntity, EntityMember } from './index.js'\nimport { SchemaShape } from './shape.js'\n\n/** The writes that set a member: every insert (`create`), or every insert and update (`write`). */\nexport type SetOn = 'create' | 'write'\n\n/** A value the write's context gives: who asks, what their row holds, or when. */\nexport type ContextValue = ViewerExpr<unknown> | ViewerPathExpr<unknown> | NowExpr<unknown>\n\n/** One member `Entity.sets` names: its value, and the writes that set it. */\nexport interface EntitySet {\n readonly value: ContextValue\n readonly on: SetOn\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\n/** How a field's values are stored, nulls aside: as text, as a number, or otherwise. */\nconst storedAs = (schema: Schema.Top): 'text' | 'number' | 'other' => {\n const stored = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (stored.every(SchemaShape.isText)) return 'text'\n if (stored.every(SchemaAST.isNumber)) return 'number'\n return 'other'\n}\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * `value` checked against the member `key` it sets, as `Entity.sets` was\n * given them: a relation takes `Expr.viewer` of its target, a field stored as\n * text the viewer's id, a field stored as a number the time.\n */\nexport const checkedSet = (\n entity: AnyEntity,\n key: string,\n value: unknown,\n on: unknown,\n): EntitySet => {\n if (on !== 'create' && on !== 'write') {\n return fail(entity, `sets \"${key}\" on ${String(on)}; say on: 'create' or on: 'write'`)\n }\n if (key === 'id') return fail(entity, 'sets the id, which the client names')\n if (Object.hasOwn(entity.sets, key)) return fail(entity, `\"${key}\" is set already`)\n const tag = tagOf(value)\n if (tag !== 'Viewer' && tag !== 'Now' && tag !== 'ViewerPath') {\n return fail(\n entity,\n `sets \"${key}\" to what is no value of the write's context (Expr.viewer, a path from it, Expr.now); a value from the input is a computed assignment`,\n )\n }\n const context = value as ContextValue\n const relations: Readonly<Record<string, EntityMember>> = entity.relations\n const fields: Readonly<Record<string, EntityMember>> = entity.fields\n const member = Object.hasOwn(relations, key)\n ? relations[key]\n : Object.hasOwn(fields, key)\n ? fields[key]\n : undefined\n if (member === undefined) {\n return fail(entity, `sets \"${key}\", which is not a field or relation`)\n }\n if (member._tag === 'Relation') {\n if (member.cardinality !== 'one') return fail(entity, `sets \"${key}\", a many relation`)\n const target = member.target()\n if (context._tag !== 'Viewer' || context.entity.token !== target.identity.token) {\n return fail(entity, `sets the relation \"${key}\" to what is not Expr.viewer(${target.name})`)\n }\n return { value: context, on }\n }\n const stored = storedAs(member.schema as Schema.Top)\n Match.value(context).pipe(\n Match.tagsExhaustive({\n Now: () =>\n stored === 'number' ||\n fail(entity, `sets \"${key}\" to the time, but it is not stored as a number`),\n Viewer: () =>\n stored === 'text' ||\n fail(entity, `sets \"${key}\" to the viewer's id, but it is not stored as text`),\n ViewerPath: ({ field }) =>\n (stored !== 'other' && storedAs(field.schema as unknown as Schema.Top) === stored) ||\n fail(\n entity,\n `sets \"${key}\" to what ${field.owner.name}.${field.key} holds, which it is not stored as`,\n ),\n }),\n )\n return { value: context, on }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,WAAW,OAAO,KAAK,KAAK,SAAS;AACvD;;AAGA,MAAM,YAAY,WAAoD;CACpE,MAAM,SAAS,YAAY,QAAQ,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG;CAC/D,IAAI,OAAO,MAAM,YAAY,MAAM,GAAG,OAAO;CAC7C,IAAI,OAAO,MAAM,UAAU,QAAQ,GAAG,OAAO;CAC7C,OAAO;AACT;AAEA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;AAOhF,MAAa,cACX,QACA,KACA,OACA,OACc;CACd,IAAI,OAAO,YAAY,OAAO,SAC5B,OAAO,KAAK,QAAQ,SAAS,IAAI,OAAO,OAAO,EAAE,EAAE,kCAAkC;CAEvF,IAAI,QAAQ,MAAM,OAAO,KAAK,QAAQ,qCAAqC;CAC3E,IAAI,OAAO,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAK,QAAQ,IAAI,IAAI,iBAAiB;CAClF,MAAM,MAAM,MAAM,KAAK;
|
|
1
|
+
{"version":3,"file":"sets.js","names":[],"sources":["../src/sets.ts"],"sourcesContent":["/**\n * What `Entity.sets` declares: members whose value is the write's context,\n * never its input, and the writes that set them.\n */\nimport { Match, Schema, SchemaAST } from 'effect'\nimport type { NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { AnyEntity, EntityMember } from './index.js'\nimport { SchemaShape } from './shape.js'\n\n/** The writes that set a member: every insert (`create`), or every insert and update (`write`). */\nexport type SetOn = 'create' | 'write'\n\n/** A value the write's context gives: who asks, what their row holds, or when. */\nexport type ContextValue = ViewerExpr<unknown> | ViewerPathExpr<unknown> | NowExpr<unknown>\n\n/** One member `Entity.sets` names: its value, and the writes that set it. */\nexport interface EntitySet {\n readonly value: ContextValue\n readonly on: SetOn\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\n/** How a field's values are stored, nulls aside: as text, as a number, or otherwise. */\nconst storedAs = (schema: Schema.Top): 'text' | 'number' | 'other' => {\n const stored = SchemaShape.present(Schema.toEncoded(schema).ast)\n if (stored.every(SchemaShape.isText)) return 'text'\n if (stored.every(SchemaAST.isNumber)) return 'number'\n return 'other'\n}\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * `value` checked against the member `key` it sets, as `Entity.sets` was\n * given them: a relation takes `Expr.viewer` of its target, a field stored as\n * text the viewer's id, a field stored as a number the time.\n */\nexport const checkedSet = (\n entity: AnyEntity,\n key: string,\n value: unknown,\n on: unknown,\n): EntitySet => {\n if (on !== 'create' && on !== 'write') {\n return fail(entity, `sets \"${key}\" on ${String(on)}; say on: 'create' or on: 'write'`)\n }\n if (key === 'id') return fail(entity, 'sets the id, which the client names')\n if (Object.hasOwn(entity.sets, key)) return fail(entity, `\"${key}\" is set already`)\n const tag = tagOf(value)\n // tag-check: open, the value is whatever the application wrote\n if (tag !== 'Viewer' && tag !== 'Now' && tag !== 'ViewerPath') {\n return fail(\n entity,\n `sets \"${key}\" to what is no value of the write's context (Expr.viewer, a path from it, Expr.now); a value from the input is a computed assignment`,\n )\n }\n const context = value as ContextValue\n const relations: Readonly<Record<string, EntityMember>> = entity.relations\n const fields: Readonly<Record<string, EntityMember>> = entity.fields\n const member = Object.hasOwn(relations, key)\n ? relations[key]\n : Object.hasOwn(fields, key)\n ? fields[key]\n : undefined\n if (member === undefined) {\n return fail(entity, `sets \"${key}\", which is not a field or relation`)\n }\n if (member._tag === 'Relation') {\n if (member.cardinality !== 'one') return fail(entity, `sets \"${key}\", a many relation`)\n const target = member.target()\n if (context._tag !== 'Viewer' || context.entity.token !== target.identity.token) {\n return fail(entity, `sets the relation \"${key}\" to what is not Expr.viewer(${target.name})`)\n }\n return { value: context, on }\n }\n const stored = storedAs(member.schema as Schema.Top)\n Match.value(context).pipe(\n Match.tagsExhaustive({\n Now: () =>\n stored === 'number' ||\n fail(entity, `sets \"${key}\" to the time, but it is not stored as a number`),\n Viewer: () =>\n stored === 'text' ||\n fail(entity, `sets \"${key}\" to the viewer's id, but it is not stored as text`),\n ViewerPath: ({ field }) =>\n (stored !== 'other' && storedAs(field.schema as unknown as Schema.Top) === stored) ||\n fail(\n entity,\n `sets \"${key}\" to what ${field.owner.name}.${field.key} holds, which it is not stored as`,\n ),\n }),\n )\n return { value: context, on }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,WAAW,OAAO,KAAK,KAAK,SAAS;AACvD;;AAGA,MAAM,YAAY,WAAoD;CACpE,MAAM,SAAS,YAAY,QAAQ,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG;CAC/D,IAAI,OAAO,MAAM,YAAY,MAAM,GAAG,OAAO;CAC7C,IAAI,OAAO,MAAM,UAAU,QAAQ,GAAG,OAAO;CAC7C,OAAO;AACT;AAEA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;AAOhF,MAAa,cACX,QACA,KACA,OACA,OACc;CACd,IAAI,OAAO,YAAY,OAAO,SAC5B,OAAO,KAAK,QAAQ,SAAS,IAAI,OAAO,OAAO,EAAE,EAAE,kCAAkC;CAEvF,IAAI,QAAQ,MAAM,OAAO,KAAK,QAAQ,qCAAqC;CAC3E,IAAI,OAAO,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAK,QAAQ,IAAI,IAAI,iBAAiB;CAClF,MAAM,MAAM,MAAM,KAAK;CAEvB,IAAI,QAAQ,YAAY,QAAQ,SAAS,QAAQ,cAC/C,OAAO,KACL,QACA,SAAS,IAAI,sIACf;CAEF,MAAM,UAAU;CAChB,MAAM,YAAoD,OAAO;CACjE,MAAM,SAAiD,OAAO;CAC9D,MAAM,SAAS,OAAO,OAAO,WAAW,GAAG,IACvC,UAAU,OACV,OAAO,OAAO,QAAQ,GAAG,IACvB,OAAO,OACP,KAAA;CACN,IAAI,WAAW,KAAA,GACb,OAAO,KAAK,QAAQ,SAAS,IAAI,oCAAoC;CAEvE,IAAI,OAAO,SAAS,YAAY;EAC9B,IAAI,OAAO,gBAAgB,OAAO,OAAO,KAAK,QAAQ,SAAS,IAAI,mBAAmB;EACtF,MAAM,SAAS,OAAO,OAAO;EAC7B,IAAI,QAAQ,SAAS,YAAY,QAAQ,OAAO,UAAU,OAAO,SAAS,OACxE,OAAO,KAAK,QAAQ,sBAAsB,IAAI,+BAA+B,OAAO,KAAK,EAAE;EAE7F,OAAO;GAAE,OAAO;GAAS;EAAG;CAC9B;CACA,MAAM,SAAS,SAAS,OAAO,MAAoB;CACnD,MAAM,MAAM,OAAO,CAAC,CAAC,KACnB,MAAM,eAAe;EACnB,WACE,WAAW,YACX,KAAK,QAAQ,SAAS,IAAI,gDAAgD;EAC5E,cACE,WAAW,UACX,KAAK,QAAQ,SAAS,IAAI,mDAAmD;EAC/E,aAAa,EAAE,YACZ,WAAW,WAAW,SAAS,MAAM,MAA+B,MAAM,UAC3E,KACE,QACA,SAAS,IAAI,YAAY,MAAM,MAAM,KAAK,GAAG,MAAM,IAAI,kCACzD;CACJ,CAAC,CACH;CACA,OAAO;EAAE,OAAO;EAAS;CAAG;AAC9B"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { OrderTerm } from "./expr.js";
|
|
3
|
+
/**
|
|
4
|
+
* Why an order term cannot be answered the same by every reader for want of a
|
|
5
|
+
* collation: a field of text that declares none. SQLite compares bytes,
|
|
6
|
+
* Postgres follows its database's locale and JavaScript compares UTF-16 units,
|
|
7
|
+
* so `Query.placement` and `evaluate` both refuse it, for this reason.
|
|
8
|
+
*/
|
|
9
|
+
export declare const uncollatedText: (orderTerm: OrderTerm) => Option.Option<string>;
|
|
10
|
+
//# sourceMappingURL=uncollated.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uncollated.d.ts","names":[],"sources":["../src/uncollated.ts"],"mappings":";;;;;;;;qBAqBa,iBAAc,WAAe,cAAY,OAAO"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Match, Option, Schema, SchemaAST } from "effect";
|
|
2
|
+
// src/uncollated.ts
|
|
3
|
+
/**
|
|
4
|
+
* Whether values encoded by `ast` order the same everywhere: numbers and
|
|
5
|
+
* booleans, never text. A null among them does too: where it goes is said on
|
|
6
|
+
* every order term.
|
|
7
|
+
*/
|
|
8
|
+
const ordersIntrinsically = (ast) => SchemaAST.isNumber(ast) || SchemaAST.isBoolean(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal !== "string" || SchemaAST.isUnion(ast) && ast.types.every((member) => SchemaAST.isNull(member) || ordersIntrinsically(member));
|
|
9
|
+
/**
|
|
10
|
+
* Why an order term cannot be answered the same by every reader for want of a
|
|
11
|
+
* collation: a field of text that declares none. SQLite compares bytes,
|
|
12
|
+
* Postgres follows its database's locale and JavaScript compares UTF-16 units,
|
|
13
|
+
* so `Query.placement` and `evaluate` both refuse it, for this reason.
|
|
14
|
+
*/
|
|
15
|
+
const uncollatedText = (orderTerm) => Match.value(orderTerm.expr).pipe(Match.tag("Field", (field) => Option.isNone(orderTerm.collation) && !ordersIntrinsically(Schema.toEncoded(field.schema).ast) ? Option.some(`it orders by ${field.owner.name}.${field.key}, text with no declared collation`) : Option.none()), Match.orElse(() => Option.none()));
|
|
16
|
+
export { uncollatedText };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=uncollated.js.map
|