arktype 0.1.4 → 0.3.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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/api.cjs +4 -3
  3. package/dist/api.d.ts +3 -2
  4. package/dist/api.mjs +2 -1
  5. package/dist/cjs/nodes/{branches.js → branch.js} +56 -10
  6. package/dist/cjs/nodes/compose.js +1 -2
  7. package/dist/cjs/nodes/discriminate.js +7 -13
  8. package/dist/cjs/nodes/node.js +32 -4
  9. package/dist/cjs/nodes/predicate.js +7 -7
  10. package/dist/cjs/nodes/rules/class.js +10 -4
  11. package/dist/cjs/nodes/rules/divisor.js +1 -5
  12. package/dist/cjs/nodes/rules/props.js +75 -25
  13. package/dist/cjs/nodes/rules/range.js +1 -5
  14. package/dist/cjs/nodes/rules/regex.js +2 -44
  15. package/dist/cjs/nodes/rules/rules.js +21 -61
  16. package/dist/cjs/parse/definition.js +2 -2
  17. package/dist/cjs/parse/string/reduce/dynamic.js +1 -2
  18. package/dist/cjs/parse/string/shift/operator/bounds.js +1 -1
  19. package/dist/cjs/parse/string/string.js +2 -2
  20. package/dist/cjs/parse/tuple/keyof.js +37 -18
  21. package/dist/cjs/parse/tuple/morph.js +7 -6
  22. package/dist/cjs/parse/tuple/tuple.js +16 -9
  23. package/dist/cjs/scopes/cache.js +39 -0
  24. package/dist/cjs/scopes/jsObjects.js +133 -0
  25. package/dist/cjs/{main.js → scopes/scope.js} +31 -364
  26. package/dist/cjs/scopes/standard.js +44 -0
  27. package/dist/cjs/scopes/tsKeywords.js +113 -0
  28. package/dist/cjs/scopes/type.js +67 -0
  29. package/dist/cjs/scopes/validation.js +64 -0
  30. package/dist/cjs/traverse/problems.js +55 -95
  31. package/dist/cjs/traverse/traverse.js +127 -134
  32. package/dist/cjs/utils/numericLiterals.js +3 -0
  33. package/dist/cjs/utils/objectKinds.js +1 -2
  34. package/dist/mjs/nodes/{branches.js → branch.js} +45 -2
  35. package/dist/mjs/nodes/compose.js +1 -2
  36. package/dist/mjs/nodes/discriminate.js +6 -12
  37. package/dist/mjs/nodes/node.js +30 -3
  38. package/dist/mjs/nodes/predicate.js +2 -2
  39. package/dist/mjs/nodes/rules/class.js +10 -4
  40. package/dist/mjs/nodes/rules/divisor.js +1 -5
  41. package/dist/mjs/nodes/rules/props.js +74 -27
  42. package/dist/mjs/nodes/rules/range.js +1 -5
  43. package/dist/mjs/nodes/rules/regex.js +1 -43
  44. package/dist/mjs/nodes/rules/rules.js +22 -61
  45. package/dist/mjs/parse/definition.js +1 -1
  46. package/dist/mjs/parse/string/reduce/dynamic.js +2 -3
  47. package/dist/mjs/parse/string/shift/operator/bounds.js +1 -1
  48. package/dist/mjs/parse/string/string.js +2 -2
  49. package/dist/mjs/parse/tuple/keyof.js +38 -19
  50. package/dist/mjs/parse/tuple/morph.js +7 -6
  51. package/dist/mjs/parse/tuple/tuple.js +17 -10
  52. package/dist/mjs/scopes/cache.js +25 -0
  53. package/dist/mjs/scopes/jsObjects.js +119 -0
  54. package/dist/mjs/{main.js → scopes/scope.js} +15 -344
  55. package/dist/mjs/scopes/standard.js +27 -0
  56. package/dist/mjs/scopes/tsKeywords.js +99 -0
  57. package/dist/mjs/scopes/type.js +53 -0
  58. package/dist/mjs/scopes/validation.js +51 -0
  59. package/dist/mjs/traverse/problems.js +55 -95
  60. package/dist/mjs/traverse/traverse.js +129 -135
  61. package/dist/mjs/utils/numericLiterals.js +2 -1
  62. package/dist/mjs/utils/objectKinds.js +1 -1
  63. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  64. package/dist/types/nodes/branch.d.ts +36 -0
  65. package/dist/types/nodes/compose.d.ts +6 -11
  66. package/dist/types/nodes/discriminate.d.ts +1 -1
  67. package/dist/types/nodes/infer.d.ts +16 -15
  68. package/dist/types/nodes/node.d.ts +18 -9
  69. package/dist/types/nodes/predicate.d.ts +18 -57
  70. package/dist/types/nodes/rules/class.d.ts +3 -2
  71. package/dist/types/nodes/rules/divisor.d.ts +2 -1
  72. package/dist/types/nodes/rules/props.d.ts +19 -11
  73. package/dist/types/nodes/rules/range.d.ts +2 -1
  74. package/dist/types/nodes/rules/regex.d.ts +2 -11
  75. package/dist/types/nodes/rules/rules.d.ts +11 -21
  76. package/dist/types/parse/definition.d.ts +1 -1
  77. package/dist/types/parse/string/ast.d.ts +4 -2
  78. package/dist/types/parse/string/reduce/shared.d.ts +1 -1
  79. package/dist/types/parse/string/reduce/static.d.ts +1 -1
  80. package/dist/types/parse/string/shift/operator/bounds.d.ts +1 -1
  81. package/dist/types/parse/string/string.d.ts +1 -1
  82. package/dist/types/parse/tuple/keyof.d.ts +2 -2
  83. package/dist/types/parse/tuple/morph.d.ts +1 -1
  84. package/dist/types/parse/tuple/narrow.d.ts +1 -1
  85. package/dist/types/parse/tuple/tuple.d.ts +1 -1
  86. package/dist/types/scopes/cache.d.ts +14 -0
  87. package/dist/types/scopes/jsObjects.d.ts +36 -0
  88. package/dist/types/scopes/scope.d.ts +76 -0
  89. package/dist/types/scopes/standard.d.ts +280 -0
  90. package/dist/types/scopes/tsKeywords.d.ts +32 -0
  91. package/dist/types/scopes/type.d.ts +47 -0
  92. package/dist/types/scopes/validation.d.ts +21 -0
  93. package/dist/types/traverse/problems.d.ts +35 -53
  94. package/dist/types/traverse/traverse.d.ts +30 -24
  95. package/dist/types/utils/generics.d.ts +0 -1
  96. package/dist/types/utils/numericLiterals.d.ts +2 -0
  97. package/dist/types/utils/objectKinds.d.ts +43 -43
  98. package/package.json +2 -3
  99. package/dist/cjs/nodes/functors.js +0 -35
  100. package/dist/cjs/nodes/rules/objectKind.js +0 -78
  101. package/dist/mjs/nodes/functors.js +0 -27
  102. package/dist/mjs/nodes/rules/objectKind.js +0 -63
  103. package/dist/types/main.d.ts +0 -324
  104. package/dist/types/nodes/branches.d.ts +0 -14
  105. package/dist/types/nodes/functors.d.ts +0 -6
  106. package/dist/types/nodes/rules/objectKind.d.ts +0 -15
@@ -1,8 +1,8 @@
1
- var _definitions_code, _definitions_code1, _definitions_code2, _clausesByPath, _pathKey;
1
+ var _definitions_code, _definitions_code1;
2
2
  import { Scanner } from "../parse/string/shift/scanner.js";
3
3
  import { domainDescriptions, domainOf } from "../utils/domains.js";
4
- import { keysOf } from "../utils/generics.js";
5
- import { objectKindDescriptions, objectKindOf } from "../utils/objectKinds.js";
4
+ import { isWellFormedInteger } from "../utils/numericLiterals.js";
5
+ import { objectKindDescriptions } from "../utils/objectKinds.js";
6
6
  import { Path } from "../utils/paths.js";
7
7
  import { stringify } from "../utils/serialize.js";
8
8
  export class ArkTypeError extends TypeError {
@@ -16,51 +16,54 @@ export class Problem {
16
16
  return this.message;
17
17
  }
18
18
  get message() {
19
- return this.writers.message(this.reason, this.path);
19
+ return this.writers.addContext(this.reason, this.path);
20
20
  }
21
21
  get reason() {
22
- return this.writers.reason(this.mustBe, this.was);
22
+ return this.writers.writeReason(this.mustBe, new DataWrapper(this.data));
23
23
  }
24
24
  get mustBe() {
25
- return this.writers.mustBe(this.rule);
25
+ return this.writers.mustBe(this.source);
26
26
  }
27
- get was() {
28
- return this.writers.was(new DataWrapper(this.data));
29
- }
30
- constructor(code, path, data, rule, writers){
27
+ constructor(code, path, data, source, writers){
31
28
  this.code = code;
32
29
  this.path = path;
33
30
  this.data = data;
34
- this.rule = rule;
31
+ this.source = source;
35
32
  this.writers = writers;
33
+ if (this.code === "multi") {
34
+ this.parts = this.source;
35
+ }
36
36
  }
37
37
  }
38
38
  class ProblemArray extends Array {
39
- add(code, data, input) {
40
- const problem = new Problem(code, // copy the path to avoid future mutations affecting it
41
- Path.from(this.state.path), data, input, this.state.type.meta.problems[code]);
42
- const pathKey = `${this.state.path}`;
43
- // TODO: Fix multi
44
- // const existing = this.byPath[pathKey]
45
- // if (existing) {
46
- // if (existing.code === "multi") {
47
- // existing.message += `\n• ${problem.message}`
48
- // } else {
49
- // this.byPath[pathKey] = new Problem(
50
- // "multi",
51
- // existing.path,
52
- // `• ${existing.message}\n• ${problem.message}`
53
- // )
54
- // }
55
- // } else {
56
- // }
57
- this.byPath[pathKey] = problem;
58
- this.push(problem);
39
+ add(code, data, source, opts) {
40
+ // copy the path to avoid future mutations affecting it
41
+ const path = opts?.path ?? Path.from(this.state.path);
42
+ const problem = new Problem(code, path, data, source, this.state.getConfigForProblemCode(code));
43
+ const pathKey = `${path}`;
44
+ const existing = this.byPath[pathKey];
45
+ if (existing) {
46
+ if (existing.parts) {
47
+ existing.parts.push(problem);
48
+ } else {
49
+ const problemIntersection = new Problem("multi", existing.path, data, [
50
+ existing,
51
+ problem
52
+ ], this.state.getConfigForProblemCode("multi"));
53
+ const existingIndex = this.indexOf(existing);
54
+ // If existing is found (which it always should be unless this was externally mutated),
55
+ // replace it with the new problem intersection. In case it isn't for whatever reason,
56
+ // just append the intersection.
57
+ this[existingIndex === -1 ? this.length : existingIndex] = problemIntersection;
58
+ this.byPath[pathKey] = problemIntersection;
59
+ }
60
+ } else {
61
+ this.byPath[pathKey] = problem;
62
+ this.push(problem);
63
+ }
64
+ return false;
59
65
  }
60
66
  get summary() {
61
- if (this.length === 1) {
62
- return this[0].message;
63
- }
64
67
  return this.join("\n");
65
68
  }
66
69
  toString() {
@@ -104,9 +107,6 @@ export class DataWrapper {
104
107
  get domain() {
105
108
  return domainOf(this.value);
106
109
  }
107
- get objectKind() {
108
- return objectKindOf(this.value) ?? "non-object";
109
- }
110
110
  get size() {
111
111
  return typeof this.value === "string" || Array.isArray(this.value) ? this.value.length : typeof this.value === "number" ? this.value : 0;
112
112
  }
@@ -120,48 +120,42 @@ export class DataWrapper {
120
120
  this.value = value;
121
121
  }
122
122
  }
123
- const writeDefaultWasDescription = (data)=>`${data}`;
124
- const writeDefaultProblemReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
125
- const writeDefaultProblemMessage = (reason, path)=>path.length ? `${path} ${reason}` : capitalize(reason);
123
+ const writeDefaultReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
124
+ const addDefaultContext = (reason, path)=>path.length === 0 ? capitalize(reason) : path.length === 1 && isWellFormedInteger(path[0]) ? `Item at index ${path[0]} ${reason}` : `${path} ${reason}`;
126
125
  const compileDefaultProblemWriters = (definitions)=>{
127
126
  let code;
128
127
  for(code in definitions){
129
- (_definitions_code = definitions[code]).was ?? (_definitions_code.was = writeDefaultWasDescription);
130
- (_definitions_code1 = definitions[code]).reason ?? (_definitions_code1.reason = writeDefaultProblemReason);
131
- (_definitions_code2 = definitions[code]).message ?? (_definitions_code2.message = writeDefaultProblemMessage);
128
+ (_definitions_code = definitions[code]).writeReason ?? (_definitions_code.writeReason = writeDefaultReason);
129
+ (_definitions_code1 = definitions[code]).addContext ?? (_definitions_code1.addContext = addDefaultContext);
132
130
  }
133
131
  return definitions;
134
132
  };
135
133
  export const defaultProblemWriters = compileDefaultProblemWriters({
136
134
  divisor: {
137
- mustBe: (divisor)=>divisor === 1 ? `an integer` : `divisible by ${divisor}`
135
+ mustBe: (divisor)=>divisor === 1 ? `an integer` : `a multiple of ${divisor}`
138
136
  },
139
137
  class: {
140
- mustBe: (constructor)=>`an instance of ${constructor.name}`,
141
- was: (data)=>data.className
138
+ mustBe: (expected)=>typeof expected === "string" ? objectKindDescriptions[expected] : `an instance of ${expected.name}`,
139
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.className)
142
140
  },
143
141
  domain: {
144
142
  mustBe: (domain)=>domainDescriptions[domain],
145
- was: (data)=>data.domain
143
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.domain)
146
144
  },
147
145
  domainBranches: {
148
146
  mustBe: (domains)=>describeDomains(domains),
149
- was: (data)=>data.domain
150
- },
151
- objectKind: {
152
- mustBe: (kind)=>objectKindDescriptions[kind],
153
- was: (data)=>data.objectKind
147
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.domain)
154
148
  },
155
149
  missing: {
156
150
  mustBe: ()=>"defined",
157
- was: ()=>""
151
+ writeReason: (mustBe)=>writeDefaultReason(mustBe, "")
158
152
  },
159
153
  bound: {
160
154
  mustBe: (bound)=>`${Scanner.comparatorDescriptions[bound.comparator]} ${bound.limit}${bound.units ? ` ${bound.units}` : ""}`,
161
- was: (data)=>`${data.size}`
155
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, `${data.size}`)
162
156
  },
163
157
  regex: {
164
- mustBe: (regex)=>`a string matching /${regex.source}/`
158
+ mustBe: (expression)=>`a string matching ${expression}`
165
159
  },
166
160
  value: {
167
161
  mustBe: stringify
@@ -170,47 +164,13 @@ export const defaultProblemWriters = compileDefaultProblemWriters({
170
164
  mustBe: (values)=>describeBranches(values.map(stringify))
171
165
  },
172
166
  branches: {
173
- mustBe: (branchProblems)=>{
174
- const clausesByPath = {};
175
- for (const problem of branchProblems){
176
- const pathKey = `${problem.path}`;
177
- (_clausesByPath = clausesByPath)[_pathKey = pathKey] ?? (_clausesByPath[_pathKey] = []);
178
- clausesByPath[pathKey].push(problem.mustBe);
179
- }
180
- return describeBranches(Object.entries(clausesByPath).map(([path, clauses])=>`${path} must be ${clauses.length === 1 ? clauses[0] : describeBranches(clauses)}`));
181
- },
182
- reason: (mustBe, data)=>`${mustBe} (was ${data})`,
183
- message: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
167
+ mustBe: (branchProblems)=>describeBranches(branchProblems.map((problem)=>`${problem.path} must be ${problem.parts ? describeBranches(problem.parts.map((part)=>part.mustBe)) : problem.mustBe}`)),
168
+ writeReason: (mustBe, data)=>`${mustBe} (was ${data})`,
169
+ addContext: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
184
170
  },
185
171
  multi: {
186
- mustBe: (problems)=>"• " + problems.join("\n• "),
187
- reason: (mustBe)=>mustBe
172
+ mustBe: (problems)=>"• " + problems.map((_)=>_.mustBe).join("\n• "),
173
+ writeReason: (mustBe, data)=>`${data} must be...\n${mustBe}`,
174
+ addContext: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
188
175
  }
189
176
  });
190
- const codes = keysOf(defaultProblemWriters);
191
- // TODO: remove all copy from codes?
192
- export const compileProblemOptions = (opts, base = defaultProblemWriters)=>{
193
- if (!opts) {
194
- return base;
195
- }
196
- const { all , ...byCode } = opts;
197
- const result = {};
198
- let code;
199
- if (all) {
200
- for (code of codes){
201
- result[code] = {
202
- ...base[code],
203
- ...all,
204
- ...byCode[code]
205
- };
206
- }
207
- } else {
208
- for (code of codes){
209
- result[code] = byCode[code] ? {
210
- ...base[code],
211
- ...byCode[code]
212
- } : base[code];
213
- }
214
- }
215
- return result;
216
- };
@@ -45,17 +45,44 @@ import { checkBound } from "../nodes/rules/range.js";
45
45
  import { checkRegex } from "../nodes/rules/regex.js";
46
46
  import { precedenceMap } from "../nodes/rules/rules.js";
47
47
  import { domainOf, hasDomain } from "../utils/domains.js";
48
- import { throwInternalError } from "../utils/errors.js";
49
48
  import { hasKey, keysOf } from "../utils/generics.js";
50
- import { objectKindOf } from "../utils/objectKinds.js";
51
49
  import { getPath, Path } from "../utils/paths.js";
52
- import { deserializePrimitive, stringify } from "../utils/serialize.js";
53
- import { Problems } from "./problems.js";
50
+ import { deserializePrimitive } from "../utils/serialize.js";
51
+ import { defaultProblemWriters, Problems } from "./problems.js";
54
52
  var _seen = /*#__PURE__*/ new WeakMap();
53
+ // TODO: include data wrapper in state
55
54
  export class TraversalState {
56
- traverseResolution(data, name) {
55
+ getConfigForProblemCode(code) {
56
+ if (!this.configs.length) {
57
+ return defaultProblemWriters[code];
58
+ }
59
+ for(let i = this.configs.length - 1; i >= 0; i--){
60
+ if (this.configs[i][code] || this.configs[i]["defaults"]) {
61
+ return {
62
+ ...defaultProblemWriters[code],
63
+ ...this.configs[i]["defaults"],
64
+ ...this.configs[i][code]
65
+ };
66
+ }
67
+ }
68
+ return defaultProblemWriters[code];
69
+ }
70
+ traverseKey(key, node) {
71
+ const lastData = this.data;
72
+ this.data = this.data[key];
73
+ // TODO: make path externally readonly
74
+ this.path.push(key);
75
+ const isValid = traverse(node, this);
76
+ this.path.pop();
77
+ lastData[key] = this.data;
78
+ this.data = lastData;
79
+ return isValid;
80
+ }
81
+ traverseResolution(name) {
57
82
  const resolution = this.type.meta.scope.resolve(name);
58
83
  const id = resolution.meta.id;
84
+ // this assignment helps with narrowing
85
+ const data = this.data;
59
86
  const isObject = hasDomain(data, "object");
60
87
  if (isObject) {
61
88
  if (hasKey(_classPrivateFieldGet(this, _seen), id)) {
@@ -63,7 +90,7 @@ export class TraversalState {
63
90
  // if data has already been checked by this alias as part of
64
91
  // a resolution higher up on the call stack, it must be valid
65
92
  // or we wouldn't be here
66
- return;
93
+ return true;
67
94
  }
68
95
  _classPrivateFieldGet(this, _seen)[id].push(data);
69
96
  } else {
@@ -72,181 +99,148 @@ export class TraversalState {
72
99
  ];
73
100
  }
74
101
  }
75
- // TODO: type not an accurate reflection of context because not always included
76
- const lastType = this.type;
102
+ const lastResolution = this.type;
77
103
  this.type = resolution;
78
- traverse(data, resolution.flat, this);
79
- this.type = lastType;
104
+ const isValid = traverse(resolution.flat, this);
105
+ this.type = lastResolution;
80
106
  if (isObject) {
81
107
  _classPrivateFieldGet(this, _seen)[id].pop();
82
108
  }
109
+ return isValid;
83
110
  }
84
- traverseBranches(data, branches) {
85
- const lastProblems = this.problems;
86
- const lastPath = this.path;
111
+ traverseBranches(branches) {
87
112
  const lastFailFast = this.failFast;
88
113
  this.failFast = true;
89
- const branchProblems = [];
114
+ const lastProblems = this.problems;
115
+ const branchProblems = new Problems(this);
116
+ this.problems = branchProblems;
117
+ const lastPath = this.path;
118
+ let hasValidBranch = false;
90
119
  for (const branch of branches){
91
- this.problems = new Problems(this);
92
120
  this.path = new Path();
93
- checkEntries(data, branch, this);
94
- if (!this.problems.length) {
121
+ if (checkEntries(branch, this)) {
122
+ hasValidBranch = true;
95
123
  break;
96
124
  }
97
- branchProblems.push(this.problems[0]);
98
125
  }
99
- this.failFast = lastFailFast;
100
126
  this.path = lastPath;
101
127
  this.problems = lastProblems;
102
- if (branchProblems.length === branches.length) {
103
- this.problems.add("branches", data, branchProblems);
104
- }
128
+ this.failFast = lastFailFast;
129
+ return hasValidBranch || this.problems.add("branches", this.data, branchProblems);
105
130
  }
106
- constructor(type){
131
+ constructor(data, type){
107
132
  _classPrivateFieldInit(this, _seen, {
108
133
  writable: true,
109
134
  value: void 0
110
135
  });
136
+ this.data = data;
111
137
  this.type = type;
112
138
  this.path = new Path();
113
139
  this.problems = new Problems(this);
114
140
  this.failFast = false;
115
141
  _classPrivateFieldSet(this, _seen, {});
142
+ this.configs = type.meta.scope.config ? [
143
+ type.meta.scope.config
144
+ ] : [];
116
145
  }
117
146
  }
118
- export const traverse = (data, node, state)=>{
119
- if (typeof node === "string") {
120
- if (domainOf(data) !== node) {
121
- return state.problems.add("domain", data, node);
122
- }
123
- return;
124
- }
125
- return checkEntries(data, node, state);
126
- };
127
- export const checkEntries = (data, entries, state)=>{
128
- let problemsPrecedence = Number.POSITIVE_INFINITY;
129
- const initialProblemsCount = state.problems.length;
130
- for (const [k, v] of entries){
131
- if (precedenceMap[k] > problemsPrecedence) {
132
- return;
133
- }
147
+ export const traverse = (node, state)=>typeof node === "string" ? domainOf(state.data) === node || state.problems.add("domain", state.data, node) : checkEntries(node, state);
148
+ export const checkEntries = (entries, state)=>{
149
+ let isValid = true;
150
+ for(let i = 0; i < entries.length; i++){
151
+ const [k, v] = entries[i];
134
152
  if (k === "morph") {
135
153
  if (typeof v === "function") {
136
- return v(data);
137
- }
138
- let out = data;
139
- for (const morph of v){
140
- out = morph(out);
141
- }
142
- return out;
143
- } else {
144
- checkers[k](data, v, state);
145
- if (state.problems.length > initialProblemsCount) {
146
- if (state.failFast) {
147
- return;
154
+ // TODO: allow problem from morph
155
+ state.data = v(state.data);
156
+ } else {
157
+ for (const morph of v){
158
+ state.data = morph(state.data);
148
159
  }
149
- problemsPrecedence = precedenceMap[k];
150
160
  }
161
+ return true;
151
162
  }
152
- }
153
- return data;
154
- };
155
- const createPropChecker = (propKind)=>(data, props, state)=>{
156
- const rootPath = state.path;
157
- for (const [propKey, propNode] of props){
158
- state.path.push(propKey);
159
- if (!hasKey(data, propKey)) {
160
- if (propKind !== "optionalProps") {
161
- state.problems.add("missing", undefined, undefined);
162
- }
163
- } else {
164
- traverse(data[propKey], propNode, state);
163
+ const entryAllowsData = entryCheckers[k](v, state);
164
+ isValid && (isValid = entryAllowsData);
165
+ if (!isValid) {
166
+ if (state.failFast) {
167
+ return false;
168
+ }
169
+ if (i < entries.length - 1 && precedenceMap[k] < precedenceMap[entries[i + 1][0]]) {
170
+ // if we've encountered a problem, there is at least one entry
171
+ // remaining, and the next entry is of a higher precedence level
172
+ // than the current entry, return immediately
173
+ return false;
165
174
  }
166
- state.path.pop();
167
- }
168
- state.path = rootPath;
169
- };
170
- const checkRequiredProps = createPropChecker("requiredProps");
171
- const checkOptionalProps = createPropChecker("optionalProps");
172
- export const checkObjectKind = (data, rule, state)=>{
173
- const dataObjectKind = objectKindOf(data);
174
- if (typeof rule === "string") {
175
- if (dataObjectKind !== rule) {
176
- return state.problems.add("objectKind", data, rule);
177
- }
178
- return;
179
- }
180
- if (dataObjectKind !== rule[0]) {
181
- return state.problems.add("objectKind", data, rule[0]);
182
- }
183
- if (dataObjectKind === "Array" && typeof rule[2] === "number") {
184
- const actual = data.length;
185
- const expected = rule[2];
186
- if (expected !== actual) {
187
- return state.problems.add("bound", data, {
188
- comparator: "==",
189
- limit: expected,
190
- units: "items"
191
- });
192
175
  }
193
176
  }
194
- if (dataObjectKind === "Array" || dataObjectKind === "Set") {
195
- let i = 0;
196
- for (const item of data){
197
- state.path.push(`${i}`);
198
- traverse(item, rule[1], state);
199
- state.path.pop();
200
- i++;
201
- }
202
- } else {
203
- return throwInternalError(`Unexpected objectKind entry ${stringify(rule)}`);
177
+ return isValid;
178
+ };
179
+ export const checkRequiredProp = (prop, state)=>{
180
+ if (prop[0] in state.data) {
181
+ return state.traverseKey(prop[0], prop[1]);
204
182
  }
205
- return true;
183
+ return state.problems.add("missing", undefined, undefined, {
184
+ path: state.path.concat(prop[0])
185
+ });
206
186
  };
207
- const checkers = {
187
+ const entryCheckers = {
208
188
  regex: checkRegex,
209
189
  divisor: checkDivisor,
210
- domains: (data, domains, state)=>{
211
- const entries = domains[domainOf(data)];
212
- if (entries) {
213
- checkEntries(data, entries, state);
214
- } else {
215
- state.problems.add("domainBranches", data, keysOf(domains));
190
+ domains: (domains, state)=>{
191
+ const entries = domains[domainOf(state.data)];
192
+ return entries ? checkEntries(entries, state) : state.problems.add("domainBranches", state.data, keysOf(domains));
193
+ },
194
+ // TODO: remove data from problem params
195
+ domain: (domain, state)=>domainOf(state.data) === domain || state.problems.add("domain", state.data, domain),
196
+ bound: checkBound,
197
+ optionalProp: (prop, state)=>{
198
+ if (prop[0] in state.data) {
199
+ return state.traverseKey(prop[0], prop[1]);
216
200
  }
201
+ return true;
217
202
  },
218
- domain: (data, domain, state)=>{
219
- if (domainOf(data) !== domain) {
220
- state.problems.add("domain", data, domain);
203
+ // these checks work the same way, the keys are only distinct so that
204
+ // prerequisite props can have a higher precedence
205
+ requiredProp: checkRequiredProp,
206
+ prerequisiteProp: checkRequiredProp,
207
+ indexProp: (node, state)=>{
208
+ if (!Array.isArray(state.data)) {
209
+ return state.problems.add("class", state.data, "Array");
210
+ }
211
+ let isValid = true;
212
+ for(let i = 0; i < state.data.length; i++){
213
+ isValid && (isValid = state.traverseKey(`${i}`, node));
214
+ if (!isValid && state.failFast) {
215
+ return false;
216
+ }
221
217
  }
218
+ return isValid;
222
219
  },
223
- objectKind: checkObjectKind,
224
- bound: checkBound,
225
- requiredProps: checkRequiredProps,
226
- optionalProps: checkOptionalProps,
227
- branches: (data, branches, state)=>state.traverseBranches(data, branches),
228
- switch: (data, rule, state)=>{
229
- const dataAtPath = getPath(data, rule.path);
220
+ branches: (branches, state)=>state.traverseBranches(branches),
221
+ switch: (rule, state)=>{
222
+ const dataAtPath = getPath(state.data, rule.path);
230
223
  const caseKey = serializeCase(rule.kind, dataAtPath);
231
224
  if (hasKey(rule.cases, caseKey)) {
232
- return checkEntries(data, rule.cases[caseKey], state);
225
+ return checkEntries(rule.cases[caseKey], state);
233
226
  }
234
227
  const caseKeys = keysOf(rule.cases);
235
- const lastPath = state.path;
236
- state.path = state.path.concat(rule.path);
237
- if (rule.kind === "value") {
238
- state.problems.add("valueBranches", dataAtPath, caseKeys.map((k)=>deserializePrimitive(k)));
239
- } else {
240
- state.problems.add("domainBranches", dataAtPath, caseKeys);
241
- }
242
- state.path = lastPath;
228
+ const missingCasePath = state.path.concat(rule.path);
229
+ return rule.kind === "value" ? state.problems.add("valueBranches", dataAtPath, caseKeys.map((k)=>deserializePrimitive(k)), {
230
+ path: missingCasePath
231
+ }) : state.problems.add("domainBranches", dataAtPath, caseKeys, {
232
+ path: missingCasePath
233
+ });
243
234
  },
244
- alias: (data, name, state)=>state.traverseResolution(data, name),
235
+ alias: (name, state)=>state.traverseResolution(name),
245
236
  class: checkClass,
246
- narrow: (data, narrow, state)=>narrow(data, state.problems),
247
- value: (data, value, state)=>{
248
- if (data !== value) {
249
- state.problems.add("value", data, value);
250
- }
251
- }
237
+ // TODO: fix
238
+ narrow: (narrow, state)=>narrow(state.data, state.problems),
239
+ config: ({ config , node }, state)=>{
240
+ state.configs.push(config);
241
+ const result = traverse(node, state);
242
+ state.configs.pop();
243
+ return result;
244
+ },
245
+ value: (value, state)=>state.data === value || state.problems.add("value", state.data, value)
252
246
  };
@@ -21,7 +21,8 @@ const isNumberLike = (s)=>s.length !== 0 && numberLikeMatcher.test(s);
21
21
  * 1. Must begin with an integer, the first digit of which cannot be 0 unless the entire value is 0
22
22
  * 2. The value may not be "-0"
23
23
  */ export const wellFormedIntegerMatcher = /^(?:0|(?:-?[1-9]\d*))$/;
24
- const isWellFormedInteger = (s)=>wellFormedIntegerMatcher.test(s);
24
+ export const isWellFormedInteger = (s)=>wellFormedIntegerMatcher.test(s);
25
+ export const wellFormedNonNegativeIntegerMatcher = /^(?:0|(?:[1-9]\d*))$/;
25
26
  const integerLikeMatcher = /^-?\d+$/;
26
27
  const isIntegerLike = (s)=>integerLikeMatcher.test(s);
27
28
  const numericLiteralDescriptions = {
@@ -1,7 +1,7 @@
1
1
  import { domainOf } from "./domains.js";
2
2
  // Built-in object constructors based on a subset of:
3
3
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
4
- const defaultObjectKinds = {
4
+ export const defaultObjectKinds = {
5
5
  Array,
6
6
  Date,
7
7
  Error,