arktype 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/api.cjs +9 -0
  2. package/dist/api.d.ts +10 -0
  3. package/dist/api.mjs +1 -0
  4. package/dist/cjs/nodes/branch.js +15 -6
  5. package/dist/cjs/nodes/compose.js +1 -1
  6. package/dist/cjs/nodes/discriminate.js +89 -21
  7. package/dist/cjs/nodes/node.js +11 -11
  8. package/dist/cjs/nodes/predicate.js +1 -1
  9. package/dist/cjs/nodes/rules/class.js +2 -2
  10. package/dist/cjs/nodes/rules/divisor.js +1 -1
  11. package/dist/cjs/nodes/rules/props.js +1 -2
  12. package/dist/cjs/nodes/rules/range.js +2 -2
  13. package/dist/cjs/nodes/rules/regex.js +1 -1
  14. package/dist/cjs/nodes/rules/rules.js +4 -0
  15. package/dist/cjs/parse/ast/ast.js +4 -0
  16. package/dist/cjs/parse/ast/bound.js +9 -0
  17. package/dist/cjs/parse/{tuple/utils.js → ast/distributableFunction.js} +1 -1
  18. package/dist/cjs/parse/ast/divisor.js +9 -0
  19. package/dist/cjs/parse/{string/ast.js → ast/intersection.js} +2 -8
  20. package/dist/cjs/parse/ast/keyof.js +109 -0
  21. package/dist/cjs/parse/{tuple → ast}/morph.js +1 -1
  22. package/dist/cjs/parse/{tuple → ast}/narrow.js +2 -2
  23. package/dist/cjs/parse/{tuple → ast}/tuple.js +11 -10
  24. package/dist/cjs/parse/ast/union.js +9 -0
  25. package/dist/cjs/parse/ast/utils.js +4 -0
  26. package/dist/cjs/parse/definition.js +12 -2
  27. package/dist/cjs/parse/string/reduce/dynamic.js +7 -7
  28. package/dist/cjs/parse/string/shift/operator/bounds.js +4 -4
  29. package/dist/cjs/parse/string/shift/operator/divisor.js +3 -3
  30. package/dist/cjs/parse/string/string.js +1 -1
  31. package/dist/cjs/scopes/expressions.js +29 -0
  32. package/dist/cjs/scopes/scope.js +59 -6
  33. package/dist/cjs/scopes/validation.js +16 -1
  34. package/dist/cjs/traverse/problems.js +78 -46
  35. package/dist/cjs/traverse/traverse.js +62 -58
  36. package/dist/cjs/utils/data.js +39 -0
  37. package/dist/cjs/utils/freeze.js +2 -3
  38. package/dist/cjs/utils/generics.js +20 -2
  39. package/dist/cjs/utils/numericLiterals.js +2 -14
  40. package/dist/mjs/nodes/branch.js +14 -5
  41. package/dist/mjs/nodes/compose.js +2 -2
  42. package/dist/mjs/nodes/discriminate.js +89 -21
  43. package/dist/mjs/nodes/node.js +8 -8
  44. package/dist/mjs/nodes/predicate.js +2 -2
  45. package/dist/mjs/nodes/rules/class.js +2 -2
  46. package/dist/mjs/nodes/rules/divisor.js +1 -1
  47. package/dist/mjs/nodes/rules/props.js +1 -2
  48. package/dist/mjs/nodes/rules/range.js +2 -2
  49. package/dist/mjs/nodes/rules/regex.js +1 -1
  50. package/dist/mjs/nodes/rules/rules.js +4 -0
  51. package/dist/mjs/parse/ast/ast.js +1 -0
  52. package/dist/mjs/parse/ast/bound.js +1 -0
  53. package/dist/mjs/parse/{tuple/utils.js → ast/distributableFunction.js} +2 -2
  54. package/dist/mjs/parse/ast/divisor.js +1 -0
  55. package/dist/mjs/parse/{string/ast.js → ast/intersection.js} +2 -5
  56. package/dist/mjs/parse/ast/keyof.js +101 -0
  57. package/dist/mjs/parse/{tuple → ast}/morph.js +1 -1
  58. package/dist/mjs/parse/ast/narrow.js +7 -0
  59. package/dist/mjs/parse/{tuple → ast}/tuple.js +12 -11
  60. package/dist/mjs/parse/ast/union.js +1 -0
  61. package/dist/mjs/parse/ast/utils.js +1 -0
  62. package/dist/mjs/parse/definition.js +12 -2
  63. package/dist/mjs/parse/string/reduce/dynamic.js +8 -8
  64. package/dist/mjs/parse/string/shift/operator/bounds.js +4 -4
  65. package/dist/mjs/parse/string/shift/operator/divisor.js +3 -3
  66. package/dist/mjs/parse/string/string.js +2 -2
  67. package/dist/mjs/scopes/expressions.js +9 -0
  68. package/dist/mjs/scopes/scope.js +58 -5
  69. package/dist/mjs/scopes/validation.js +16 -1
  70. package/dist/mjs/traverse/problems.js +76 -44
  71. package/dist/mjs/traverse/traverse.js +37 -34
  72. package/dist/mjs/utils/data.js +24 -0
  73. package/dist/mjs/utils/freeze.js +2 -3
  74. package/dist/mjs/utils/generics.js +18 -1
  75. package/dist/mjs/utils/numericLiterals.js +1 -1
  76. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  77. package/dist/types/nodes/branch.d.ts +3 -12
  78. package/dist/types/nodes/discriminate.d.ts +6 -8
  79. package/dist/types/nodes/infer.d.ts +5 -5
  80. package/dist/types/nodes/node.d.ts +4 -13
  81. package/dist/types/nodes/predicate.d.ts +2 -29
  82. package/dist/types/nodes/rules/range.d.ts +2 -2
  83. package/dist/types/nodes/rules/rules.d.ts +1 -1
  84. package/dist/types/parse/ast/ast.d.ts +24 -0
  85. package/dist/types/parse/ast/bound.d.ts +10 -0
  86. package/dist/types/parse/{tuple/utils.d.ts → ast/distributableFunction.d.ts} +2 -3
  87. package/dist/types/parse/ast/divisor.d.ts +8 -0
  88. package/dist/types/parse/ast/intersection.d.ts +17 -0
  89. package/dist/types/parse/{tuple → ast}/keyof.d.ts +4 -4
  90. package/dist/types/parse/ast/morph.d.ts +18 -0
  91. package/dist/types/parse/ast/narrow.d.ts +21 -0
  92. package/dist/types/parse/ast/tuple.d.ts +40 -0
  93. package/dist/types/parse/ast/union.d.ts +12 -0
  94. package/dist/types/parse/ast/utils.d.ts +7 -0
  95. package/dist/types/parse/definition.d.ts +9 -7
  96. package/dist/types/parse/record.d.ts +2 -2
  97. package/dist/types/parse/string/reduce/shared.d.ts +5 -4
  98. package/dist/types/parse/string/reduce/static.d.ts +11 -6
  99. package/dist/types/parse/string/shift/operand/unenclosed.d.ts +1 -1
  100. package/dist/types/parse/string/shift/operator/bounds.d.ts +3 -2
  101. package/dist/types/parse/string/shift/operator/divisor.d.ts +5 -1
  102. package/dist/types/parse/string/shift/scanner.d.ts +1 -1
  103. package/dist/types/parse/string/string.d.ts +1 -2
  104. package/dist/types/scopes/expressions.d.ts +48 -0
  105. package/dist/types/scopes/scope.d.ts +17 -7
  106. package/dist/types/scopes/standard.d.ts +15 -0
  107. package/dist/types/scopes/type.d.ts +9 -5
  108. package/dist/types/scopes/validation.d.ts +4 -0
  109. package/dist/types/traverse/problems.d.ts +17 -24
  110. package/dist/types/traverse/traverse.d.ts +67 -37
  111. package/dist/types/utils/data.d.ts +13 -0
  112. package/dist/types/utils/domains.d.ts +1 -1
  113. package/dist/types/utils/generics.d.ts +14 -10
  114. package/dist/types/utils/numericLiterals.d.ts +16 -0
  115. package/dist/types/utils/paths.d.ts +2 -0
  116. package/package.json +1 -1
  117. package/dist/cjs/parse/tuple/keyof.js +0 -64
  118. package/dist/cjs/utils/size.js +0 -16
  119. package/dist/mjs/parse/tuple/keyof.js +0 -56
  120. package/dist/mjs/parse/tuple/narrow.js +0 -7
  121. package/dist/mjs/utils/size.js +0 -2
  122. package/dist/types/parse/string/ast.d.ts +0 -46
  123. package/dist/types/parse/tuple/morph.d.ts +0 -15
  124. package/dist/types/parse/tuple/narrow.d.ts +0 -13
  125. package/dist/types/parse/tuple/tuple.d.ts +0 -31
  126. package/dist/types/utils/size.d.ts +0 -3
@@ -7,7 +7,7 @@ export const classIntersection = composeIntersection((l, r, state)=>{
7
7
  });
8
8
  export const checkClass = (expectedClass, state)=>{
9
9
  if (typeof expectedClass === "string") {
10
- return objectKindOf(state.data) === expectedClass || state.problems.add("class", state.data, expectedClass);
10
+ return objectKindOf(state.data) === expectedClass || !state.problems.add("class", expectedClass);
11
11
  }
12
- return state.data instanceof expectedClass || state.problems.add("class", state.data, expectedClass);
12
+ return state.data instanceof expectedClass || !state.problems.add("class", expectedClass);
13
13
  };
@@ -12,4 +12,4 @@ const greatestCommonDivisor = (l, r)=>{
12
12
  }
13
13
  return greatestCommonDivisor;
14
14
  };
15
- export const checkDivisor = (divisor, state)=>state.data % divisor === 0 || state.problems.add("divisor", state.data, divisor);
15
+ export const checkDivisor = (divisor, state)=>state.data % divisor === 0 || !state.problems.add("divisor", divisor);
@@ -1,4 +1,3 @@
1
- import { hasKey } from "../../utils/generics.js";
2
1
  import { composeIntersection, composeKeyedIntersection, equality, isDisjoint, isEquality } from "../compose.js";
3
2
  import { flattenNode, isLiteralNode, nodeIntersection } from "../node.js";
4
3
  export const isOptional = (prop)=>prop[0] === "?";
@@ -18,7 +17,7 @@ export const propsIntersection = composeIntersection((l, r, state)=>{
18
17
  return result;
19
18
  }
20
19
  const lengthValue = getTupleLengthIfPresent(result);
21
- if (lengthValue === undefined || !hasKey(result, mappedKeys.index)) {
20
+ if (lengthValue === undefined || !(mappedKeys.index in result)) {
22
21
  return result;
23
22
  }
24
23
  // if we are at this point, we have an array with an exact length (i.e.
@@ -1,4 +1,4 @@
1
- import { sizeOf } from "../../utils/size.js";
1
+ import { sizeOf } from "../../utils/data.js";
2
2
  import { composeIntersection, equality } from "../compose.js";
3
3
  export const minComparators = {
4
4
  ">": true,
@@ -74,7 +74,7 @@ export const flattenRange = (entries, range, ctx)=>{
74
74
  ]);
75
75
  }
76
76
  };
77
- export const checkBound = (bound, state)=>comparatorCheckers[bound.comparator](sizeOf(state.data), bound.limit) || state.problems.add("bound", state.data, bound);
77
+ export const checkBound = (bound, state)=>comparatorCheckers[bound.comparator](sizeOf(state.data), bound.limit) || !state.problems.add("bound", bound);
78
78
  const comparatorCheckers = {
79
79
  "<": (size, limit)=>size < limit,
80
80
  ">": (size, limit)=>size > limit,
@@ -7,5 +7,5 @@ export const getRegex = (source)=>{
7
7
  }
8
8
  return regexCache[source];
9
9
  };
10
- export const checkRegex = (source, state)=>getRegex(source).test(state.data) || state.problems.add("regex", state.data, `/${source}/`);
10
+ export const checkRegex = (source, state)=>getRegex(source).test(state.data) || !state.problems.add("regex", `/${source}/`);
11
11
  export const regexIntersection = composeIntersection(collapsibleListUnion);
@@ -24,6 +24,10 @@ export const flattenRules = (rules, ctx)=>{
24
24
  for(k in rules){
25
25
  ruleFlatteners[k](entries, rules[k], ctx);
26
26
  }
27
+ // Some entries with the same precedence, e.g. morphs flattened from a list,
28
+ // rely on the fact that JS's builtin sort is stable to behave as expected
29
+ // when traversed:
30
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
27
31
  return entries.sort((l, r)=>precedenceMap[l[0]] - precedenceMap[r[0]]);
28
32
  };
29
33
  const ruleFlatteners = {
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1 @@
1
+ export const writeUnboundableMessage = (root)=>`Bounded expression ${root} must be a number, string or array`;
@@ -1,10 +1,10 @@
1
1
  import { hasDomain } from "../../utils/domains.js";
2
2
  import { throwParseError } from "../../utils/errors.js";
3
- import { keysOf } from "../../utils/generics.js";
3
+ import { objectKeysOf } from "../../utils/generics.js";
4
4
  import { stringify } from "../../utils/serialize.js";
5
5
  export const writeMalformedDistributableFunctionMessage = (def)=>`Expected a Function or Record<Domain, Function> operand (${stringify(def)} was invalid)`;
6
6
  export const distributeFunctionToNode = (distributableFunction, inputNode, ctx, ruleKey)=>{
7
- const domains = keysOf(ctx.type.meta.scope.resolveNode(inputNode));
7
+ const domains = objectKeysOf(ctx.type.meta.scope.resolveNode(inputNode));
8
8
  if (!hasDomain(distributableFunction, "object")) {
9
9
  return throwParseError(writeMalformedDistributableFunctionMessage(distributableFunction));
10
10
  }
@@ -0,0 +1 @@
1
+ export const writeIndivisibleMessage = (root)=>`Divisibility operand ${root} must be a number`;
@@ -1,7 +1,7 @@
1
1
  import { disjointDescriptionWriters } from "../../nodes/compose.js";
2
- import { keysOf } from "../../utils/generics.js";
2
+ import { objectKeysOf } from "../../utils/generics.js";
3
3
  export const compileDisjointReasonsMessage = (disjoints)=>{
4
- const paths = keysOf(disjoints);
4
+ const paths = objectKeysOf(disjoints);
5
5
  if (paths.length === 1) {
6
6
  const path = paths[0];
7
7
  return `${path === "/" ? "" : `At ${path}: `}Intersection of ${disjointDescriptionWriters[disjoints[path].kind](disjoints[path])} results in an unsatisfiable type`;
@@ -14,6 +14,3 @@ export const compileDisjointReasonsMessage = (disjoints)=>{
14
14
  return message;
15
15
  };
16
16
  export const writeImplicitNeverMessage = (path, operator, description)=>`${path.length ? `At ${path}: ` : ""}${operator} ${description ? `${description} ` : ""}results in an unsatisfiable type`;
17
- export const writeUndiscriminatableMorphUnionMessage = (path)=>`${path === "/" ? "A" : `At ${path}, a`} union including one or more morphs must be discriminatable`;
18
- export const writeIndivisibleMessage = (root)=>`Divisibility operand ${root} must be a number`;
19
- export const writeUnboundableMessage = (root)=>`Bounded expression ${root} must be a number, string or array`;
@@ -0,0 +1,101 @@
1
+ var _keyNode, _keyType, _keyNode1, _keyNode2;
2
+ import { mappedKeys } from "../../nodes/rules/props.js";
3
+ import { throwInternalError } from "../../utils/errors.js";
4
+ import { deepFreeze } from "../../utils/freeze.js";
5
+ import { listFrom, objectKeysOf, prototypeKeysOf } from "../../utils/generics.js";
6
+ import { tryParseWellFormedInteger, wellFormedNonNegativeIntegerMatcher } from "../../utils/numericLiterals.js";
7
+ import { defaultObjectKinds } from "../../utils/objectKinds.js";
8
+ import { stringify } from "../../utils/serialize.js";
9
+ import { parseDefinition } from "../definition.js";
10
+ import { writeImplicitNeverMessage } from "./intersection.js";
11
+ const arrayIndexStringBranch = deepFreeze({
12
+ regex: wellFormedNonNegativeIntegerMatcher.source
13
+ });
14
+ const arrayIndexNumberBranch = deepFreeze({
15
+ range: {
16
+ min: {
17
+ comparator: ">=",
18
+ limit: 1
19
+ }
20
+ },
21
+ divisor: 1
22
+ });
23
+ export const parseKeyOfTuple = (def, ctx)=>{
24
+ const resolution = ctx.type.meta.scope.resolveNode(parseDefinition(def[1], ctx));
25
+ const predicateKeys = objectKeysOf(resolution).map((domain)=>keysOfPredicate(domain, resolution[domain]));
26
+ const sharedKeys = sharedKeysOf(predicateKeys);
27
+ if (!sharedKeys.length) {
28
+ return writeImplicitNeverMessage(ctx.path, "keyof");
29
+ }
30
+ const keyNode = {};
31
+ for (const key of sharedKeys){
32
+ const keyType = typeof key;
33
+ if (keyType === "string" || keyType === "number" || keyType === "symbol") {
34
+ (_keyNode = keyNode)[_keyType = keyType] ?? (_keyNode[_keyType] = []);
35
+ keyNode[keyType].push({
36
+ value: key
37
+ });
38
+ } else if (key === wellFormedNonNegativeIntegerMatcher) {
39
+ (_keyNode1 = keyNode).string ?? (_keyNode1.string = []);
40
+ keyNode.string.push(arrayIndexStringBranch);
41
+ (_keyNode2 = keyNode).number ?? (_keyNode2.number = []);
42
+ keyNode.number.push(arrayIndexNumberBranch);
43
+ } else {
44
+ return throwInternalError(`Unexpected keyof key '${stringify(key)}'`);
45
+ }
46
+ }
47
+ return Object.fromEntries(Object.entries(keyNode).map(([domain, branches])=>[
48
+ domain,
49
+ branches.length === 1 ? branches[0] : branches
50
+ ]));
51
+ };
52
+ const baseKeysByDomain = {
53
+ bigint: prototypeKeysOf(0n),
54
+ boolean: prototypeKeysOf(false),
55
+ null: [],
56
+ number: prototypeKeysOf(0),
57
+ // TS doesn't include the Object prototype in keyof, so keyof object is never
58
+ object: [],
59
+ string: prototypeKeysOf(""),
60
+ symbol: prototypeKeysOf(Symbol()),
61
+ undefined: []
62
+ };
63
+ const keysOfPredicate = (domain, predicate)=>domain !== "object" || predicate === true ? baseKeysByDomain[domain] : sharedKeysOf(listFrom(predicate).map((branch)=>keysOfObjectBranch(branch)));
64
+ const sharedKeysOf = (keyBranches)=>{
65
+ if (!keyBranches.length) {
66
+ return [];
67
+ }
68
+ let sharedKeys = keyBranches[0];
69
+ for(let i = 1; i < keyBranches.length; i++){
70
+ // we can filter directly by equality here because the RegExp we're
71
+ // using will always be reference equal to
72
+ // wellFormedNonNegativeIntegerMatcher
73
+ sharedKeys = sharedKeys.filter((k)=>keyBranches[i].includes(k));
74
+ }
75
+ return sharedKeys;
76
+ };
77
+ const keysOfObjectBranch = (branch)=>{
78
+ const result = [];
79
+ if ("props" in branch) {
80
+ for (const key of Object.keys(branch.props)){
81
+ if (key === mappedKeys.index) {
82
+ result.push(wellFormedNonNegativeIntegerMatcher);
83
+ } else if (!result.includes(key)) {
84
+ result.push(key);
85
+ if (wellFormedNonNegativeIntegerMatcher.test(key)) {
86
+ // allow numeric access to keys
87
+ result.push(tryParseWellFormedInteger(key, `Unexpectedly failed to parse an integer from key '${key}'`));
88
+ }
89
+ }
90
+ }
91
+ }
92
+ if ("class" in branch) {
93
+ const constructor = typeof branch.class === "string" ? defaultObjectKinds[branch.class] : branch.class;
94
+ for (const key1 of prototypeKeysOf(constructor.prototype)){
95
+ if (!result.includes(key1)) {
96
+ result.push(key1);
97
+ }
98
+ }
99
+ }
100
+ return result;
101
+ };
@@ -40,4 +40,4 @@ const applyMorph = (branch, morph)=>isMorphBranch(branch) ? {
40
40
  rules: branch,
41
41
  morph
42
42
  };
43
- export const writeMalformedMorphExpressionMessage = (value)=>`Morph expression requires a function following '=>' (was ${typeof value})`;
43
+ export const writeMalformedMorphExpressionMessage = (value)=>`Morph expression requires a function following '|>' (was ${typeof value})`;
@@ -0,0 +1,7 @@
1
+ import { rootIntersection } from "../../nodes/node.js";
2
+ import { parseDefinition } from "../definition.js";
3
+ import { distributeFunctionToNode } from "./distributableFunction.js";
4
+ export const parseNarrowTuple = (def, ctx)=>{
5
+ const inputNode = parseDefinition(def[0], ctx);
6
+ return rootIntersection(inputNode, distributeFunctionToNode(def[2], inputNode, ctx, "narrow"), ctx.type);
7
+ };
@@ -1,4 +1,4 @@
1
- import { arrayOf, intersection, union } from "../../nodes/node.js";
1
+ import { rootIntersection, rootUnion, toArrayNode } from "../../nodes/node.js";
2
2
  import { domainOf } from "../../utils/domains.js";
3
3
  import { throwParseError } from "../../utils/errors.js";
4
4
  import { parseDefinition } from "../definition.js";
@@ -7,10 +7,10 @@ import { parseKeyOfTuple } from "./keyof.js";
7
7
  import { parseMorphTuple } from "./morph.js";
8
8
  import { parseNarrowTuple } from "./narrow.js";
9
9
  export const parseTuple = (def, ctx)=>{
10
- if (isPostfixExpression(def)) {
11
- return postfixParsers[def[1]](def, ctx);
10
+ if (isIndexOneExpression(def)) {
11
+ return indexOneParsers[def[1]](def, ctx);
12
12
  }
13
- if (isPrefixExpression(def)) {
13
+ if (isIndexZeroExpression(def)) {
14
14
  return prefixParsers[def[0]](def, ctx);
15
15
  }
16
16
  const props = {
@@ -44,17 +44,18 @@ const parseBranchTuple = (def, ctx)=>{
44
44
  }
45
45
  const l = parseDefinition(def[0], ctx);
46
46
  const r = parseDefinition(def[2], ctx);
47
- return def[1] === "&" ? intersection(l, r, ctx.type) : union(l, r, ctx.type);
47
+ return def[1] === "&" ? rootIntersection(l, r, ctx.type) : rootUnion(l, r, ctx.type);
48
48
  };
49
- const parseArrayTuple = (def, scope)=>arrayOf(parseDefinition(def[0], scope));
49
+ const parseArrayTuple = (def, scope)=>toArrayNode(parseDefinition(def[0], scope));
50
50
  export const writeMalformedFunctionalExpressionMessage = (operator, rightDef)=>`Expression requires a function following '${operator}' (was ${typeof rightDef})`;
51
- const isPostfixExpression = (def)=>postfixParsers[def[1]] !== undefined;
52
- const postfixParsers = {
51
+ const isIndexOneExpression = (def)=>indexOneParsers[def[1]] !== undefined;
52
+ const indexOneParsers = {
53
53
  "|": parseBranchTuple,
54
54
  "&": parseBranchTuple,
55
55
  "[]": parseArrayTuple,
56
- ":": parseNarrowTuple,
57
- "=>": parseMorphTuple
56
+ "=>": parseNarrowTuple,
57
+ "|>": parseMorphTuple,
58
+ ":": ()=>({})
58
59
  };
59
60
  const prefixParsers = {
60
61
  keyof: parseKeyOfTuple,
@@ -75,4 +76,4 @@ const prefixParsers = {
75
76
  }),
76
77
  node: (def)=>def[1]
77
78
  };
78
- const isPrefixExpression = (def)=>prefixParsers[def[0]] !== undefined;
79
+ const isIndexZeroExpression = (def)=>prefixParsers[def[0]] !== undefined;
@@ -0,0 +1 @@
1
+ export const writeUndiscriminatableMorphUnionMessage = (path)=>`${path === "/" ? "A" : `At ${path}, a`} union including one or more morphs must be discriminatable`;
@@ -0,0 +1 @@
1
+ export { };
@@ -3,9 +3,9 @@ import { domainOf } from "../utils/domains.js";
3
3
  import { throwParseError } from "../utils/errors.js";
4
4
  import { objectKindOf } from "../utils/objectKinds.js";
5
5
  import { stringify } from "../utils/serialize.js";
6
+ import { parseTuple } from "./ast/tuple.js";
6
7
  import { parseRecord } from "./record.js";
7
8
  import { parseString } from "./string/string.js";
8
- import { parseTuple } from "./tuple/tuple.js";
9
9
  export const parseDefinition = (def, ctx)=>{
10
10
  const domain = domainOf(def);
11
11
  if (domain === "string") {
@@ -27,11 +27,21 @@ export const parseDefinition = (def, ctx)=>{
27
27
  }
28
28
  };
29
29
  case "Function":
30
- return isType(def) ? def.node : throwParseError(writeBadDefinitionTypeMessage("Function"));
30
+ if (isType(def)) {
31
+ return def.node;
32
+ }
33
+ if (isThunk(def)) {
34
+ const returned = def();
35
+ if (isType(returned)) {
36
+ return returned.node;
37
+ }
38
+ }
39
+ return throwParseError(writeBadDefinitionTypeMessage("Function"));
31
40
  default:
32
41
  return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? stringify(def)));
33
42
  }
34
43
  };
35
44
  export const as = Symbol("as");
36
45
  export const unknownDefinitionMessage = "Cannot statically parse a definition inferred as unknown. Consider using 'as inferred<...>' to cast it.";
46
+ const isThunk = (def)=>typeof def === "function" && def.length === 0;
37
47
  export const writeBadDefinitionTypeMessage = (actual)=>`Type definitions must be strings or objects (was ${actual})`;
@@ -1,4 +1,4 @@
1
- import { arrayOf, intersection, isLiteralNode, union } from "../../../nodes/node.js";
1
+ import { isLiteralNode, rootIntersection, rootUnion, toArrayNode } from "../../../nodes/node.js";
2
2
  import { minComparators } from "../../../nodes/rules/range.js";
3
3
  import { throwInternalError, throwParseError } from "../../../utils/errors.js";
4
4
  import { isKeyOf } from "../../../utils/generics.js";
@@ -51,10 +51,10 @@ export class DynamicState {
51
51
  this.root = node;
52
52
  }
53
53
  rootToArray() {
54
- this.root = arrayOf(this.ejectRoot());
54
+ this.root = toArrayNode(this.ejectRoot());
55
55
  }
56
56
  intersect(node) {
57
- this.root = intersection(this.ejectRoot(), node, this.ctx.type);
57
+ this.root = rootIntersection(this.ejectRoot(), node, this.ctx.type);
58
58
  }
59
59
  ejectRoot() {
60
60
  this.assertHasRoot();
@@ -81,7 +81,7 @@ export class DynamicState {
81
81
  return this.error(writeUnpairableComparatorMessage(comparator));
82
82
  }
83
83
  if (this.branches.range) {
84
- return this.error(writeMultipleLeftBoundsMessage(this.branches.range.limit, this.branches.range.comparator, limit, invertedComparator));
84
+ return this.error(writeMultipleLeftBoundsMessage(`${this.branches.range.limit}`, this.branches.range.comparator, `${limit}`, invertedComparator));
85
85
  }
86
86
  this.branches.range = {
87
87
  limit,
@@ -94,7 +94,7 @@ export class DynamicState {
94
94
  this.pushRootToBranch("|");
95
95
  this.setRoot(this.branches.union);
96
96
  } else if (this.branches.intersection) {
97
- this.setRoot(intersection(this.branches.intersection, this.ejectRoot(), this.ctx.type));
97
+ this.setRoot(rootIntersection(this.branches.intersection, this.ejectRoot(), this.ctx.type));
98
98
  }
99
99
  }
100
100
  finalizeGroup() {
@@ -107,15 +107,15 @@ export class DynamicState {
107
107
  }
108
108
  pushRootToBranch(token) {
109
109
  this.assertRangeUnset();
110
- this.branches.intersection = this.branches.intersection ? intersection(this.branches.intersection, this.ejectRoot(), this.ctx.type) : this.ejectRoot();
110
+ this.branches.intersection = this.branches.intersection ? rootIntersection(this.branches.intersection, this.ejectRoot(), this.ctx.type) : this.ejectRoot();
111
111
  if (token === "|") {
112
- this.branches.union = this.branches.union ? union(this.branches.union, this.branches.intersection, this.ctx.type) : this.branches.intersection;
112
+ this.branches.union = this.branches.union ? rootUnion(this.branches.union, this.branches.intersection, this.ctx.type) : this.branches.intersection;
113
113
  delete this.branches.intersection;
114
114
  }
115
115
  }
116
116
  assertRangeUnset() {
117
117
  if (this.branches.range) {
118
- return this.error(writeOpenRangeMessage(this.branches.range.limit, this.branches.range.comparator));
118
+ return this.error(writeOpenRangeMessage(`${this.branches.range.limit}`, this.branches.range.comparator));
119
119
  }
120
120
  }
121
121
  reduceGroupOpen() {
@@ -1,9 +1,9 @@
1
1
  import { stringifyRange } from "../../../../nodes/compose.js";
2
2
  import { compareStrictness, maxComparators, minComparators } from "../../../../nodes/rules/range.js";
3
3
  import { throwInternalError } from "../../../../utils/errors.js";
4
- import { hasKey, isKeyOf, keysOf, listFrom } from "../../../../utils/generics.js";
4
+ import { isKeyOf, listFrom, objectKeysOf } from "../../../../utils/generics.js";
5
5
  import { tryParseWellFormedNumber } from "../../../../utils/numericLiterals.js";
6
- import { writeUnboundableMessage } from "../../ast.js";
6
+ import { writeUnboundableMessage } from "../../../ast/bound.js";
7
7
  import { writeUnpairableComparatorMessage } from "../../reduce/shared.js";
8
8
  import { Scanner } from "../scanner.js";
9
9
  export const parseBound = (s, start)=>{
@@ -36,7 +36,7 @@ export const parseRightBound = (s, comparator)=>{
36
36
  };
37
37
  const distributeRange = (range, s)=>{
38
38
  const resolution = s.resolveRoot();
39
- const domains = keysOf(resolution);
39
+ const domains = objectKeysOf(resolution);
40
40
  const distributedRange = {};
41
41
  const rangePredicate = {
42
42
  range
@@ -54,7 +54,7 @@ const distributeRange = (range, s)=>{
54
54
  if (resolution.object === true) {
55
55
  return false;
56
56
  }
57
- return listFrom(resolution.object).every((branch)=>hasKey(branch, "class") && branch.class === "Array");
57
+ return listFrom(resolution.object).every((branch)=>"class" in branch && branch.class === "Array");
58
58
  default:
59
59
  return false;
60
60
  }
@@ -1,13 +1,13 @@
1
- import { keysOf } from "../../../../utils/generics.js";
1
+ import { objectKeysOf } from "../../../../utils/generics.js";
2
2
  import { tryParseWellFormedInteger } from "../../../../utils/numericLiterals.js";
3
- import { writeIndivisibleMessage } from "../../ast.js";
3
+ import { writeIndivisibleMessage } from "../../../ast/divisor.js";
4
4
  export const parseDivisor = (s)=>{
5
5
  const divisorToken = s.scanner.shiftUntilNextTerminator();
6
6
  const divisor = tryParseWellFormedInteger(divisorToken, writeInvalidDivisorMessage(divisorToken));
7
7
  if (divisor === 0) {
8
8
  s.error(writeInvalidDivisorMessage(0));
9
9
  }
10
- const rootDomains = keysOf(s.resolveRoot());
10
+ const rootDomains = objectKeysOf(s.resolveRoot());
11
11
  if (rootDomains.length === 1 && rootDomains[0] === "number") {
12
12
  s.intersect({
13
13
  number: {
@@ -1,4 +1,4 @@
1
- import { arrayOf } from "../../nodes/node.js";
1
+ import { toArrayNode } from "../../nodes/node.js";
2
2
  import { DynamicState } from "./reduce/dynamic.js";
3
3
  import { parseOperand } from "./shift/operand/operand.js";
4
4
  import { parseOperator } from "./shift/operator/operator.js";
@@ -10,7 +10,7 @@ export const maybeNaiveParse = (def, ctx)=>{
10
10
  if (def.endsWith("[]")) {
11
11
  const elementDef = def.slice(0, -2);
12
12
  if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
13
- return arrayOf(elementDef);
13
+ return toArrayNode(elementDef);
14
14
  }
15
15
  }
16
16
  };
@@ -0,0 +1,9 @@
1
+ import { scopes } from "./standard.js";
2
+ export const intersection = scopes.standard.intersection;
3
+ export const union = scopes.standard.union;
4
+ export const arrayOf = scopes.standard.arrayOf;
5
+ export const keyOf = scopes.standard.keyOf;
6
+ export const instanceOf = scopes.standard.instanceOf;
7
+ export const valueOf = scopes.standard.valueOf;
8
+ export const narrow = scopes.standard.narrow;
9
+ export const morph = scopes.standard.morph;
@@ -80,6 +80,7 @@ import { flattenType } from "../nodes/node.js";
80
80
  import { parseDefinition } from "../parse/definition.js";
81
81
  import { chainableNoOpProxy } from "../utils/chainableNoOpProxy.js";
82
82
  import { throwInternalError, throwParseError } from "../utils/errors.js";
83
+ import { deepFreeze } from "../utils/freeze.js";
83
84
  import { Path } from "../utils/paths.js";
84
85
  import { Cache, FreezingCache } from "./cache.js";
85
86
  import { initializeType } from "./type.js";
@@ -143,7 +144,57 @@ export class Scope {
143
144
  _classPrivateFieldSet(this, _resolutions, new Cache());
144
145
  _classPrivateFieldSet(this, _exports, new Cache());
145
146
  _classPrivateFieldSet(this, _anonymousTypeCount, 0);
146
- this.type = (def, opts = {})=>{
147
+ this.expressions = {
148
+ intersection: (l, r, opts)=>this.type([
149
+ l,
150
+ "&",
151
+ r
152
+ ], opts),
153
+ union: (l, r, opts)=>this.type([
154
+ l,
155
+ "|",
156
+ r
157
+ ], opts),
158
+ arrayOf: (def, opts)=>this.type([
159
+ def,
160
+ "[]"
161
+ ], opts),
162
+ keyOf: (def, opts)=>this.type([
163
+ "keyof",
164
+ def
165
+ ], opts),
166
+ fromNode: (def, opts)=>this.type([
167
+ "node",
168
+ def
169
+ ], opts),
170
+ instanceOf: (def, opts)=>this.type([
171
+ "instanceof",
172
+ def
173
+ ], opts),
174
+ valueOf: (def, opts)=>this.type([
175
+ "===",
176
+ def
177
+ ], opts),
178
+ narrow: (def, fn, opts)=>this.type([
179
+ def,
180
+ "=>",
181
+ fn
182
+ ], opts),
183
+ morph: (def, fn, opts)=>this.type([
184
+ def,
185
+ "|>",
186
+ fn
187
+ ], opts)
188
+ };
189
+ this.intersection = this.expressions.intersection;
190
+ this.union = this.expressions.union;
191
+ this.arrayOf = this.expressions.arrayOf;
192
+ this.keyOf = this.expressions.keyOf;
193
+ this.valueOf = this.expressions.valueOf;
194
+ this.instanceOf = this.expressions.instanceOf;
195
+ this.narrow = this.expressions.narrow;
196
+ this.morph = this.expressions.morph;
197
+ this.type = Object.assign((def, opts = {})=>{
147
198
  if (opts.name && this.aliases[opts.name]) {
148
199
  return throwParseError(writeDuplicateAliasesMessage(opts.name));
149
200
  }
@@ -152,7 +203,9 @@ export class Scope {
152
203
  result.node = this.resolveNode(parseDefinition(def, ctx));
153
204
  result.flat = flattenType(result);
154
205
  return result;
155
- };
206
+ }, {
207
+ from: this.expressions.fromNode
208
+ });
156
209
  this.name = _classPrivateMethodGet(this, _register, register).call(this, opts);
157
210
  if (opts.standard !== false) {
158
211
  _classPrivateMethodGet(this, _cacheSpaces, cacheSpaces).call(this, [
@@ -216,13 +269,13 @@ function resolveRecurse(name, onUnresolvable, seen) {
216
269
  seen.push(resolution);
217
270
  resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, resolution, "throw", seen).node;
218
271
  }
219
- type.node = resolution;
220
- type.flat = flattenType(type);
272
+ type.node = deepFreeze(resolution);
273
+ type.flat = deepFreeze(flattenType(type));
221
274
  return type;
222
275
  }
276
+ export const scope = (aliases, opts = {})=>new Scope(aliases, opts);
223
277
  export const writeShallowCycleErrorMessage = (name, seen)=>`Alias '${name}' has a shallow resolution cycle: ${[
224
278
  ...seen,
225
279
  name
226
280
  ].join("=>")}`;
227
- export const scope = (aliases, opts = {})=>new Scope(aliases, opts);
228
281
  export const writeDuplicateAliasesMessage = (name)=>`Alias '${name}' is already defined`;
@@ -1,3 +1,4 @@
1
+ import { wellFormedIntegerMatcher, wellFormedNumberMatcher } from "../utils/numericLiterals.js";
1
2
  import { scope } from "./scope.js";
2
3
  // https://github.com/validatorjs/validator.js
3
4
  export const isLuhnValid = (creditCardInput)=>{
@@ -31,11 +32,25 @@ export const validationScope = scope({
31
32
  lowercase: /^[a-z]*$/,
32
33
  uppercase: /^[A-Z]*$/,
33
34
  // https://github.com/validatorjs/validator.js
34
- creditCard: /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,
35
+ creditCard: [
36
+ /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,
37
+ "=>",
38
+ (s, problems)=>isLuhnValid(s) || !problems.add("mustBe", "a valid credit card number")
39
+ ],
35
40
  // https://www.regular-expressions.info
36
41
  email: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
37
42
  // https://github.com/validatorjs/validator.js
38
43
  uuid: /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/,
44
+ parsedNumber: [
45
+ wellFormedNumberMatcher,
46
+ "|>",
47
+ (s)=>parseFloat(s)
48
+ ],
49
+ parsedInteger: [
50
+ wellFormedIntegerMatcher,
51
+ "|>",
52
+ (s)=>parseInt(s)
53
+ ],
39
54
  integer: [
40
55
  "node",
41
56
  {