arktype 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +101 -0
  3. package/dist/api.cjs +15 -0
  4. package/dist/api.d.ts +2 -0
  5. package/dist/api.mjs +1 -0
  6. package/dist/cjs/main.js +462 -0
  7. package/dist/cjs/nodes/branches.js +85 -0
  8. package/dist/cjs/nodes/compose.js +140 -0
  9. package/dist/cjs/nodes/discriminate.js +199 -0
  10. package/dist/cjs/nodes/functors.js +35 -0
  11. package/dist/cjs/nodes/infer.js +4 -0
  12. package/dist/cjs/nodes/node.js +108 -0
  13. package/dist/cjs/nodes/predicate.js +87 -0
  14. package/dist/cjs/nodes/rules/class.js +21 -0
  15. package/dist/cjs/nodes/rules/collapsibleSet.js +49 -0
  16. package/dist/cjs/nodes/rules/divisor.js +33 -0
  17. package/dist/cjs/nodes/rules/props.js +72 -0
  18. package/dist/cjs/nodes/rules/range.js +109 -0
  19. package/dist/cjs/nodes/rules/regex.js +68 -0
  20. package/dist/cjs/nodes/rules/rules.js +156 -0
  21. package/dist/cjs/nodes/rules/subdomain.js +78 -0
  22. package/dist/cjs/package.json +3 -0
  23. package/dist/cjs/parse/definition.js +33 -0
  24. package/dist/cjs/parse/record.js +37 -0
  25. package/dist/cjs/parse/string/ast.js +36 -0
  26. package/dist/cjs/parse/string/reduce/dynamic.js +150 -0
  27. package/dist/cjs/parse/string/reduce/shared.js +23 -0
  28. package/dist/cjs/parse/string/reduce/static.js +4 -0
  29. package/dist/cjs/parse/string/shift/operand/enclosed.js +54 -0
  30. package/dist/cjs/parse/string/shift/operand/operand.js +11 -0
  31. package/dist/cjs/parse/string/shift/operand/unenclosed.js +53 -0
  32. package/dist/cjs/parse/string/shift/operator/bounds.js +87 -0
  33. package/dist/cjs/parse/string/shift/operator/divisor.js +35 -0
  34. package/dist/cjs/parse/string/shift/operator/operator.js +26 -0
  35. package/dist/cjs/parse/string/shift/scanner.js +99 -0
  36. package/dist/cjs/parse/string/string.js +43 -0
  37. package/dist/cjs/parse/tuple/keyof.js +46 -0
  38. package/dist/cjs/parse/tuple/morph.js +56 -0
  39. package/dist/cjs/parse/tuple/narrow.js +15 -0
  40. package/dist/cjs/parse/tuple/tuple.js +85 -0
  41. package/dist/cjs/parse/tuple/utils.js +48 -0
  42. package/dist/cjs/traverse/problems.js +249 -0
  43. package/dist/cjs/traverse/traverse.js +268 -0
  44. package/dist/cjs/utils/chainableNoOpProxy.js +23 -0
  45. package/dist/cjs/utils/domains.js +67 -0
  46. package/dist/cjs/utils/errors.js +26 -0
  47. package/dist/cjs/utils/freeze.js +16 -0
  48. package/dist/cjs/utils/generics.js +36 -0
  49. package/dist/cjs/utils/numericLiterals.js +84 -0
  50. package/dist/cjs/utils/paths.js +32 -0
  51. package/dist/cjs/utils/serialize.js +98 -0
  52. package/dist/cjs/utils/unionToTuple.js +4 -0
  53. package/dist/mjs/main.js +442 -0
  54. package/dist/mjs/nodes/branches.js +71 -0
  55. package/dist/mjs/nodes/compose.js +118 -0
  56. package/dist/mjs/nodes/discriminate.js +184 -0
  57. package/dist/mjs/nodes/functors.js +27 -0
  58. package/dist/mjs/nodes/infer.js +1 -0
  59. package/dist/mjs/nodes/node.js +90 -0
  60. package/dist/mjs/nodes/predicate.js +69 -0
  61. package/dist/mjs/nodes/rules/class.js +7 -0
  62. package/dist/mjs/nodes/rules/collapsibleSet.js +35 -0
  63. package/dist/mjs/nodes/rules/divisor.js +19 -0
  64. package/dist/mjs/nodes/rules/props.js +57 -0
  65. package/dist/mjs/nodes/rules/range.js +90 -0
  66. package/dist/mjs/nodes/rules/regex.js +53 -0
  67. package/dist/mjs/nodes/rules/rules.js +138 -0
  68. package/dist/mjs/nodes/rules/subdomain.js +63 -0
  69. package/dist/mjs/package.json +3 -0
  70. package/dist/mjs/parse/definition.js +17 -0
  71. package/dist/mjs/parse/record.js +29 -0
  72. package/dist/mjs/parse/string/ast.js +19 -0
  73. package/dist/mjs/parse/string/reduce/dynamic.js +142 -0
  74. package/dist/mjs/parse/string/reduce/shared.js +6 -0
  75. package/dist/mjs/parse/string/reduce/static.js +1 -0
  76. package/dist/mjs/parse/string/shift/operand/enclosed.js +39 -0
  77. package/dist/mjs/parse/string/shift/operand/operand.js +3 -0
  78. package/dist/mjs/parse/string/shift/operand/unenclosed.js +36 -0
  79. package/dist/mjs/parse/string/shift/operator/bounds.js +70 -0
  80. package/dist/mjs/parse/string/shift/operator/divisor.js +21 -0
  81. package/dist/mjs/parse/string/shift/operator/operator.js +11 -0
  82. package/dist/mjs/parse/string/shift/scanner.js +91 -0
  83. package/dist/mjs/parse/string/string.js +28 -0
  84. package/dist/mjs/parse/tuple/keyof.js +38 -0
  85. package/dist/mjs/parse/tuple/morph.js +42 -0
  86. package/dist/mjs/parse/tuple/narrow.js +7 -0
  87. package/dist/mjs/parse/tuple/tuple.js +71 -0
  88. package/dist/mjs/parse/tuple/utils.js +34 -0
  89. package/dist/mjs/traverse/problems.js +229 -0
  90. package/dist/mjs/traverse/traverse.js +252 -0
  91. package/dist/mjs/utils/chainableNoOpProxy.js +15 -0
  92. package/dist/mjs/utils/domains.js +48 -0
  93. package/dist/mjs/utils/errors.js +10 -0
  94. package/dist/mjs/utils/freeze.js +8 -0
  95. package/dist/mjs/utils/generics.js +15 -0
  96. package/dist/mjs/utils/numericLiterals.js +71 -0
  97. package/dist/mjs/utils/paths.js +18 -0
  98. package/dist/mjs/utils/serialize.js +81 -0
  99. package/dist/mjs/utils/unionToTuple.js +1 -0
  100. package/dist/tsconfig.temp.tsbuildinfo +1 -0
  101. package/dist/types/main.d.ts +257 -0
  102. package/dist/types/nodes/branches.d.ts +14 -0
  103. package/dist/types/nodes/compose.d.ts +92 -0
  104. package/dist/types/nodes/discriminate.d.ts +27 -0
  105. package/dist/types/nodes/functors.d.ts +6 -0
  106. package/dist/types/nodes/infer.d.ts +35 -0
  107. package/dist/types/nodes/node.d.ts +51 -0
  108. package/dist/types/nodes/predicate.d.ts +88 -0
  109. package/dist/types/nodes/rules/class.d.ts +3 -0
  110. package/dist/types/nodes/rules/collapsibleSet.d.ts +4 -0
  111. package/dist/types/nodes/rules/divisor.d.ts +2 -0
  112. package/dist/types/nodes/rules/props.d.ts +20 -0
  113. package/dist/types/nodes/rules/range.d.ts +33 -0
  114. package/dist/types/nodes/rules/regex.d.ts +14 -0
  115. package/dist/types/nodes/rules/rules.d.ts +44 -0
  116. package/dist/types/nodes/rules/subdomain.d.ts +15 -0
  117. package/dist/types/parse/definition.d.ts +29 -0
  118. package/dist/types/parse/record.d.ts +24 -0
  119. package/dist/types/parse/string/ast.d.ts +42 -0
  120. package/dist/types/parse/string/reduce/dynamic.d.ts +34 -0
  121. package/dist/types/parse/string/reduce/shared.d.ts +24 -0
  122. package/dist/types/parse/string/reduce/static.d.ts +115 -0
  123. package/dist/types/parse/string/shift/operand/enclosed.d.ts +28 -0
  124. package/dist/types/parse/string/shift/operand/operand.d.ts +9 -0
  125. package/dist/types/parse/string/shift/operand/unenclosed.d.ts +18 -0
  126. package/dist/types/parse/string/shift/operator/bounds.d.ts +20 -0
  127. package/dist/types/parse/string/shift/operator/divisor.d.ts +9 -0
  128. package/dist/types/parse/string/shift/operator/operator.d.ts +13 -0
  129. package/dist/types/parse/string/shift/scanner.d.ts +89 -0
  130. package/dist/types/parse/string/string.d.ts +27 -0
  131. package/dist/types/parse/tuple/keyof.d.ts +2 -0
  132. package/dist/types/parse/tuple/morph.d.ts +15 -0
  133. package/dist/types/parse/tuple/narrow.d.ts +13 -0
  134. package/dist/types/parse/tuple/tuple.d.ts +37 -0
  135. package/dist/types/parse/tuple/utils.d.ts +19 -0
  136. package/dist/types/traverse/problems.d.ts +123 -0
  137. package/dist/types/traverse/traverse.d.ts +48 -0
  138. package/dist/types/utils/chainableNoOpProxy.d.ts +14 -0
  139. package/dist/types/utils/domains.d.ts +58 -0
  140. package/dist/types/utils/errors.d.ts +6 -0
  141. package/dist/types/utils/freeze.d.ts +2 -0
  142. package/dist/types/utils/generics.d.ts +118 -0
  143. package/dist/types/utils/numericLiterals.d.ts +28 -0
  144. package/dist/types/utils/paths.d.ts +7 -0
  145. package/dist/types/utils/serialize.d.ts +38 -0
  146. package/dist/types/utils/unionToTuple.d.ts +11 -0
  147. package/package.json +102 -2
@@ -0,0 +1,91 @@
1
+ export class Scanner {
2
+ /** Get lookahead and advance scanner by one */ shift() {
3
+ return this.chars[this.i++] ?? "";
4
+ }
5
+ get lookahead() {
6
+ return this.chars[this.i] ?? "";
7
+ }
8
+ shiftUntil(condition) {
9
+ let shifted = "";
10
+ while(this.lookahead){
11
+ if (condition(this, shifted)) {
12
+ if (shifted[shifted.length - 1] === Scanner.escapeToken) {
13
+ shifted = shifted.slice(0, -1);
14
+ } else {
15
+ break;
16
+ }
17
+ }
18
+ shifted += this.shift();
19
+ }
20
+ return shifted;
21
+ }
22
+ shiftUntilNextTerminator() {
23
+ this.shiftUntil(Scanner.lookaheadIsNotWhitespace);
24
+ return this.shiftUntil(Scanner.lookaheadIsTerminator);
25
+ }
26
+ get unscanned() {
27
+ return this.chars.slice(this.i, this.chars.length).join("");
28
+ }
29
+ lookaheadIs(char) {
30
+ return this.lookahead === char;
31
+ }
32
+ lookaheadIsIn(tokens) {
33
+ return this.lookahead in tokens;
34
+ }
35
+ constructor(def){
36
+ this.finalized = false;
37
+ this.chars = [
38
+ ...def
39
+ ];
40
+ this.i = 0;
41
+ }
42
+ }
43
+ (function(Scanner) {
44
+ var lookaheadIsTerminator = Scanner.lookaheadIsTerminator = (scanner)=>scanner.lookahead in terminatingChars;
45
+ var lookaheadIsNotWhitespace = Scanner.lookaheadIsNotWhitespace = (scanner)=>scanner.lookahead !== whiteSpaceToken;
46
+ var comparatorStartChars = Scanner.comparatorStartChars = {
47
+ "<": true,
48
+ ">": true,
49
+ "=": true
50
+ };
51
+ var terminatingChars = Scanner.terminatingChars = {
52
+ ...comparatorStartChars,
53
+ "|": true,
54
+ "&": true,
55
+ ")": true,
56
+ "[": true,
57
+ "%": true,
58
+ " ": true
59
+ };
60
+ var comparators = Scanner.comparators = {
61
+ "<": true,
62
+ ">": true,
63
+ "<=": true,
64
+ ">=": true,
65
+ "==": true
66
+ };
67
+ var oneCharComparators = Scanner.oneCharComparators = {
68
+ "<": true,
69
+ ">": true
70
+ };
71
+ var comparatorDescriptions = Scanner.comparatorDescriptions = {
72
+ "<": "less than",
73
+ ">": "greater than",
74
+ "<=": "at most",
75
+ ">=": "at least",
76
+ "==": "exactly"
77
+ };
78
+ var invertedComparators = Scanner.invertedComparators = {
79
+ "<": ">",
80
+ ">": "<",
81
+ "<=": ">=",
82
+ ">=": "<=",
83
+ "==": "=="
84
+ };
85
+ var branchTokens = Scanner.branchTokens = {
86
+ "|": true,
87
+ "&": true
88
+ };
89
+ var escapeToken = Scanner.escapeToken = "\\";
90
+ var whiteSpaceToken = Scanner.whiteSpaceToken = " ";
91
+ })(Scanner || (Scanner = {}));
@@ -0,0 +1,28 @@
1
+ import { functors } from "../../nodes/functors.js";
2
+ import { DynamicState } from "./reduce/dynamic.js";
3
+ import { parseOperand } from "./shift/operand/operand.js";
4
+ import { parseOperator } from "./shift/operator/operator.js";
5
+ export const parseString = (def, ctx)=>ctx.type.meta.scope.parseCache.get(def) ?? ctx.type.meta.scope.parseCache.set(def, maybeNaiveParse(def, ctx) ?? fullStringParse(def, ctx));
6
+ export const maybeNaiveParse = (def, ctx)=>{
7
+ if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
8
+ return def;
9
+ }
10
+ if (def.endsWith("[]")) {
11
+ const elementDef = def.slice(0, -2);
12
+ if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
13
+ return functors.Array(elementDef);
14
+ }
15
+ }
16
+ };
17
+ export const fullStringParse = (def, ctx)=>{
18
+ const s = new DynamicState(def, ctx);
19
+ parseOperand(s);
20
+ return loop(s);
21
+ };
22
+ const loop = (s)=>{
23
+ while(!s.scanner.finalized){
24
+ next(s);
25
+ }
26
+ return s.ejectFinalizedRoot();
27
+ };
28
+ const next = (s)=>s.hasRoot() ? parseOperator(s) : parseOperand(s);
@@ -0,0 +1,38 @@
1
+ import { resolutionExtendsDomain } from "../../nodes/predicate.js";
2
+ import { throwParseError } from "../../utils/errors.js";
3
+ import { hasKey, listFrom } from "../../utils/generics.js";
4
+ import { parseDefinition } from "../definition.js";
5
+ export const parseKeyOfTuple = (def, ctx)=>{
6
+ const resolution = ctx.type.meta.scope.resolveNode(parseDefinition(def[1], ctx));
7
+ if (!resolutionExtendsDomain(resolution, "object")) {
8
+ return throwParseError("never");
9
+ }
10
+ if (resolution.object === true) {
11
+ return {
12
+ string: true
13
+ };
14
+ }
15
+ const branchKeys = [];
16
+ const objectBranches = listFrom(resolution.object);
17
+ const initialKeys = getPropsFromBranch(objectBranches[0]);
18
+ for(let i = 1; i < objectBranches.length; i++){
19
+ const keys = getPropsFromBranch(objectBranches[i]);
20
+ if (!keys.length) {
21
+ return throwParseError("never");
22
+ }
23
+ branchKeys.push(keys);
24
+ }
25
+ const result = [];
26
+ initialKeys.forEach((key)=>{
27
+ const hasKey = branchKeys.every((keySet)=>keySet.includes(key));
28
+ if (hasKey) {
29
+ result.push({
30
+ value: key
31
+ });
32
+ }
33
+ });
34
+ return {
35
+ string: result
36
+ };
37
+ };
38
+ const getPropsFromBranch = (branch)=>hasKey(branch, "props") ? Object.keys(branch.props) : [];
@@ -0,0 +1,42 @@
1
+ import { hasSubdomain } from "../../utils/domains.js";
2
+ import { throwInternalError, throwParseError } from "../../utils/errors.js";
3
+ import { stringify } from "../../utils/serialize.js";
4
+ import { parseDefinition } from "../definition.js";
5
+ export const parseMorphTuple = (def, ctx)=>{
6
+ if (typeof def[2] !== "function") {
7
+ return throwParseError(writeMalformedMorphExpressionMessage(def[2]));
8
+ }
9
+ const resolution = ctx.type.meta.scope.resolveNode(parseDefinition(def[0], ctx));
10
+ const morph = def[2];
11
+ ctx.type.meta.includesMorph = true;
12
+ let domain;
13
+ const result = {};
14
+ for(domain in resolution){
15
+ const predicate = resolution[domain];
16
+ if (predicate === true) {
17
+ result[domain] = {
18
+ input: {},
19
+ morph
20
+ };
21
+ } else if (typeof predicate === "object") {
22
+ result[domain] = hasSubdomain(predicate, "Array") ? predicate.map((branch)=>applyMorph(branch, morph)) : applyMorph(predicate, morph);
23
+ } else {
24
+ throwInternalError(`Unexpected predicate value for domain '${domain}': ${stringify(predicate)}`);
25
+ }
26
+ }
27
+ return result;
28
+ };
29
+ const applyMorph = (branch, morph)=>branch.morph ? {
30
+ input: branch.input,
31
+ morph: Array.isArray(branch.morph) ? [
32
+ ...branch.morph,
33
+ morph
34
+ ] : [
35
+ branch.morph,
36
+ morph
37
+ ]
38
+ } : {
39
+ input: branch,
40
+ morph
41
+ };
42
+ export const writeMalformedMorphExpressionMessage = (value)=>`Morph expression requires a function following '=>' (was ${typeof value})`;
@@ -0,0 +1,7 @@
1
+ import { intersection } from "../../nodes/node.js";
2
+ import { parseDefinition } from "../definition.js";
3
+ import { distributeFunctionToNode } from "./utils.js";
4
+ export const parseNarrowTuple = (def, ctx)=>{
5
+ const inputNode = parseDefinition(def[0], ctx);
6
+ return intersection(inputNode, distributeFunctionToNode(def[2], inputNode, ctx, "narrow"), ctx.type);
7
+ };
@@ -0,0 +1,71 @@
1
+ import { functors } from "../../nodes/functors.js";
2
+ import { intersection, union } from "../../nodes/node.js";
3
+ import { domainOf } from "../../utils/domains.js";
4
+ import { throwParseError } from "../../utils/errors.js";
5
+ import { parseDefinition } from "../definition.js";
6
+ import { writeMissingRightOperandMessage } from "../string/shift/operand/unenclosed.js";
7
+ import { parseKeyOfTuple } from "./keyof.js";
8
+ import { parseMorphTuple } from "./morph.js";
9
+ import { parseNarrowTuple } from "./narrow.js";
10
+ export const parseTuple = (def, ctx)=>{
11
+ if (isPostfixExpression(def)) {
12
+ return postfixParsers[def[1]](def, ctx);
13
+ }
14
+ if (isPrefixExpression(def)) {
15
+ return prefixParsers[def[0]](def, ctx);
16
+ }
17
+ const props = {};
18
+ for(let i = 0; i < def.length; i++){
19
+ ctx.path.push(`${i}`);
20
+ props[i] = parseDefinition(def[i], ctx);
21
+ ctx.path.pop();
22
+ }
23
+ return {
24
+ object: {
25
+ subdomain: "Array",
26
+ props,
27
+ range: {
28
+ comparator: "==",
29
+ limit: def.length
30
+ }
31
+ }
32
+ };
33
+ };
34
+ const parseBranchTuple = (def, ctx)=>{
35
+ if (def[2] === undefined) {
36
+ return throwParseError(writeMissingRightOperandMessage(def[1], ""));
37
+ }
38
+ const l = parseDefinition(def[0], ctx);
39
+ const r = parseDefinition(def[2], ctx);
40
+ return def[1] === "&" ? intersection(l, r, ctx.type) : union(l, r, ctx.type);
41
+ };
42
+ const parseArrayTuple = (def, scope)=>functors.Array(parseDefinition(def[0], scope));
43
+ export const writeMalformedFunctionalExpressionMessage = (operator, rightDef)=>`Expression requires a function following '${operator}' (was ${typeof rightDef})`;
44
+ const isPostfixExpression = (def)=>postfixParsers[def[1]] !== undefined;
45
+ const postfixParsers = {
46
+ "|": parseBranchTuple,
47
+ "&": parseBranchTuple,
48
+ "[]": parseArrayTuple,
49
+ ":": parseNarrowTuple,
50
+ "=>": parseMorphTuple
51
+ };
52
+ const prefixParsers = {
53
+ keyof: parseKeyOfTuple,
54
+ instanceof: (def)=>{
55
+ if (typeof def[1] !== "function") {
56
+ return throwParseError(`Expected a constructor following 'instanceof' operator (was ${typeof def[1]}).`);
57
+ }
58
+ return {
59
+ object: {
60
+ class: def[1]
61
+ }
62
+ };
63
+ },
64
+ "===": (def)=>({
65
+ [domainOf(def[1])]: {
66
+ value: def[1]
67
+ }
68
+ }),
69
+ node: (def)=>def[1]
70
+ };
71
+ const isPrefixExpression = (def)=>prefixParsers[def[0]] !== undefined;
@@ -0,0 +1,34 @@
1
+ import { hasDomain } from "../../utils/domains.js";
2
+ import { throwParseError } from "../../utils/errors.js";
3
+ import { keysOf } from "../../utils/generics.js";
4
+ import { stringify } from "../../utils/serialize.js";
5
+ export const writeMalformedDistributableFunctionMessage = (def)=>`Expected a Function or Record<Domain, Function> operand (${stringify(def)} was invalid)`;
6
+ export const distributeFunctionToNode = (distributableFunction, inputNode, ctx, ruleKey)=>{
7
+ const domains = keysOf(ctx.type.meta.scope.resolveNode(inputNode));
8
+ if (!hasDomain(distributableFunction, "object")) {
9
+ return throwParseError(writeMalformedDistributableFunctionMessage(distributableFunction));
10
+ }
11
+ const distributed = {};
12
+ if (typeof distributableFunction === "function") {
13
+ const domainFunction = {
14
+ [ruleKey]: distributableFunction
15
+ };
16
+ for (const domain of domains){
17
+ distributed[domain] = domainFunction;
18
+ }
19
+ } else {
20
+ for (const domain1 of domains){
21
+ if (distributableFunction[domain1] === undefined) {
22
+ continue;
23
+ }
24
+ const functionInDomain = {
25
+ [ruleKey]: distributableFunction[domain1]
26
+ };
27
+ if (typeof functionInDomain[ruleKey] !== "function") {
28
+ return throwParseError(writeMalformedDistributableFunctionMessage(functionInDomain));
29
+ }
30
+ distributed[domain1] = functionInDomain;
31
+ }
32
+ }
33
+ return distributed;
34
+ };
@@ -0,0 +1,229 @@
1
+ var _definitions_code, _definitions_code1, _definitions_code2, _clausesByPath, _pathKey;
2
+ import { Scanner } from "../parse/string/shift/scanner.js";
3
+ import { classNameOf, domainOf, sizeOf, subdomainOf, unitsOf } from "../utils/domains.js";
4
+ import { keysOf } from "../utils/generics.js";
5
+ import { Path } from "../utils/paths.js";
6
+ import { stringify } from "../utils/serialize.js";
7
+ export class ArkTypeError extends TypeError {
8
+ constructor(problems){
9
+ super(problems.summary);
10
+ this.cause = problems;
11
+ }
12
+ }
13
+ export class Problem {
14
+ toString() {
15
+ return this.message;
16
+ }
17
+ get message() {
18
+ return this.writers.message(this.reason, this.path);
19
+ }
20
+ get reason() {
21
+ return this.writers.reason(this.mustBe, this.was);
22
+ }
23
+ get mustBe() {
24
+ return this.writers.mustBe(this.rule);
25
+ }
26
+ get was() {
27
+ return this.writers.was(new DataWrapper(this.data));
28
+ }
29
+ constructor(code, path, data, rule, writers){
30
+ this.code = code;
31
+ this.path = path;
32
+ this.data = data;
33
+ this.rule = rule;
34
+ this.writers = writers;
35
+ }
36
+ }
37
+ class ProblemArray extends Array {
38
+ add(code, data, input) {
39
+ const problem = new Problem(code, // copy the path to avoid future mutations affecting it
40
+ Path.from(this.state.path), data, input, this.state.type.meta.problems[code]);
41
+ const pathKey = `${this.state.path}`;
42
+ // TODO: Fix multi
43
+ // const existing = this.byPath[pathKey]
44
+ // if (existing) {
45
+ // if (existing.code === "multi") {
46
+ // existing.message += `\n• ${problem.message}`
47
+ // } else {
48
+ // this.byPath[pathKey] = new Problem(
49
+ // "multi",
50
+ // existing.path,
51
+ // `• ${existing.message}\n• ${problem.message}`
52
+ // )
53
+ // }
54
+ // } else {
55
+ // }
56
+ this.byPath[pathKey] = problem;
57
+ this.push(problem);
58
+ }
59
+ get summary() {
60
+ if (this.length === 1) {
61
+ return this[0].message;
62
+ }
63
+ return this.join("\n");
64
+ }
65
+ toString() {
66
+ return this.summary;
67
+ }
68
+ throw() {
69
+ throw new ArkTypeError(this);
70
+ }
71
+ constructor(state){
72
+ super();
73
+ this.state = state;
74
+ this.byPath = {};
75
+ }
76
+ }
77
+ export const Problems = ProblemArray;
78
+ const capitalize = (s)=>s[0].toUpperCase() + s.slice(1);
79
+ export const describeSubdomains = (subdomains)=>{
80
+ if (subdomains.length === 1) {
81
+ return subdomainDescriptions[subdomains[0]];
82
+ }
83
+ if (subdomains.length === 0) {
84
+ return "never";
85
+ }
86
+ return describeBranches(subdomains.map((subdomain)=>subdomainDescriptions[subdomain]));
87
+ };
88
+ export const describeBranches = (descriptions)=>{
89
+ let description = "";
90
+ for(let i = 0; i < descriptions.length - 1; i++){
91
+ description += descriptions[i];
92
+ if (i < descriptions.length - 2) {
93
+ description += ", ";
94
+ }
95
+ }
96
+ description += ` or ${descriptions[descriptions.length - 1]}`;
97
+ return description;
98
+ };
99
+ /** Each Subdomain's completion for the phrase "Must be _____" */ export const subdomainDescriptions = {
100
+ bigint: "a bigint",
101
+ boolean: "boolean",
102
+ null: "null",
103
+ number: "a number",
104
+ object: "an object",
105
+ string: "a string",
106
+ symbol: "a symbol",
107
+ undefined: "undefined",
108
+ Array: "an array",
109
+ Function: "a function",
110
+ Date: "a Date",
111
+ RegExp: "a RegExp",
112
+ Error: "an Error",
113
+ Map: "a Map",
114
+ Set: "a Set"
115
+ };
116
+ export class DataWrapper {
117
+ toString() {
118
+ return stringify(this.value);
119
+ }
120
+ get domain() {
121
+ return domainOf(this.value);
122
+ }
123
+ // TODO: object kind?
124
+ get subdomain() {
125
+ return subdomainOf(this.value);
126
+ }
127
+ get size() {
128
+ return sizeOf(this.value);
129
+ }
130
+ get units() {
131
+ return unitsOf(this.value);
132
+ }
133
+ get className() {
134
+ return classNameOf(this.value);
135
+ }
136
+ constructor(value){
137
+ this.value = value;
138
+ }
139
+ }
140
+ const writeDefaultWasDescription = (data)=>`${data}`;
141
+ const writeDefaultProblemReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
142
+ const writeDefaultProblemMessage = (reason, path)=>path.length ? `${path} ${reason}` : capitalize(reason);
143
+ const compileDefaultProblemWriters = (definitions)=>{
144
+ let code;
145
+ for(code in definitions){
146
+ (_definitions_code = definitions[code]).was ?? (_definitions_code.was = writeDefaultWasDescription);
147
+ (_definitions_code1 = definitions[code]).reason ?? (_definitions_code1.reason = writeDefaultProblemReason);
148
+ (_definitions_code2 = definitions[code]).message ?? (_definitions_code2.message = writeDefaultProblemMessage);
149
+ }
150
+ return definitions;
151
+ };
152
+ export const defaultProblemWriters = compileDefaultProblemWriters({
153
+ divisor: {
154
+ mustBe: (divisor)=>divisor === 1 ? `an integer` : `divisible by ${divisor}`
155
+ },
156
+ class: {
157
+ mustBe: (constructor)=>`an instance of ${constructor.name}`,
158
+ was: (data)=>data.className
159
+ },
160
+ domain: {
161
+ mustBe: (domain)=>subdomainDescriptions[domain],
162
+ was: (data)=>data.domain
163
+ },
164
+ domainBranches: {
165
+ mustBe: (domains)=>describeSubdomains(domains),
166
+ was: (data)=>data.domain
167
+ },
168
+ missing: {
169
+ mustBe: ()=>"defined",
170
+ was: ()=>""
171
+ },
172
+ bound: {
173
+ mustBe: (bound)=>`${Scanner.comparatorDescriptions[bound.comparator]} ${bound.limit}${bound.units ? ` ${bound.units}` : ""}`,
174
+ was: (data)=>`${data.size}`
175
+ },
176
+ regex: {
177
+ mustBe: (regex)=>`a string matching /${regex.source}/`
178
+ },
179
+ value: {
180
+ mustBe: stringify
181
+ },
182
+ valueBranches: {
183
+ mustBe: (values)=>describeBranches(values.map(stringify))
184
+ },
185
+ branches: {
186
+ mustBe: (branchProblems)=>{
187
+ const clausesByPath = {};
188
+ for (const problem of branchProblems){
189
+ const pathKey = `${problem.path}`;
190
+ (_clausesByPath = clausesByPath)[_pathKey = pathKey] ?? (_clausesByPath[_pathKey] = []);
191
+ clausesByPath[pathKey].push(problem.mustBe);
192
+ }
193
+ return describeBranches(Object.entries(clausesByPath).map(([path, clauses])=>`${path} must be ${clauses.length === 1 ? clauses[0] : describeBranches(clauses)}`));
194
+ },
195
+ reason: (mustBe, data)=>`${mustBe} (was ${data})`,
196
+ message: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
197
+ },
198
+ multi: {
199
+ mustBe: (problems)=>"• " + problems.join("\n• "),
200
+ reason: (mustBe)=>mustBe
201
+ }
202
+ });
203
+ const codes = keysOf(defaultProblemWriters);
204
+ // TODO: remove all copy from codes?
205
+ export const compileProblemOptions = (opts, base = defaultProblemWriters)=>{
206
+ if (!opts) {
207
+ return base;
208
+ }
209
+ const { all , ...byCode } = opts;
210
+ const result = {};
211
+ let code;
212
+ if (all) {
213
+ for (code of codes){
214
+ result[code] = {
215
+ ...base[code],
216
+ ...all,
217
+ ...byCode[code]
218
+ };
219
+ }
220
+ } else {
221
+ for (code of codes){
222
+ result[code] = byCode[code] ? {
223
+ ...base[code],
224
+ ...byCode[code]
225
+ } : base[code];
226
+ }
227
+ }
228
+ return result;
229
+ };