@atscript/typescript 0.1.109 → 0.2.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/dist/cli.cjs +3349 -2548
- package/dist/index.cjs +8 -3
- package/dist/index.d.ts +74 -2
- package/dist/index.mjs +3 -3
- package/dist/plugin-DhesoKce.mjs +3717 -0
- package/dist/plugin-oUSsb3Ri.cjs +3780 -0
- package/dist/realm-runtime.js +6328 -0
- package/dist/test-utils.cjs +79 -5
- package/dist/test-utils.d.ts +366 -1
- package/dist/test-utils.mjs +76 -5
- package/dist/unique-name-hg1CyPIs.mjs +3451 -0
- package/dist/unique-name-xWd9uO-k.cjs +3703 -0
- package/dist/utils.cjs +1303 -250
- package/dist/utils.d.ts +392 -20
- package/dist/utils.mjs +1262 -228
- package/package.json +13 -3
- package/dist/json-schema-9OBvrg9D.cjs +0 -1964
- package/dist/json-schema-CioBVi6F.mjs +0 -1880
- package/dist/plugin-6r27w6rG.cjs +0 -1683
- package/dist/plugin-D3_BnRrI.mjs +0 -1644
|
@@ -1,1964 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
//#region packages/typescript/src/runtime/validator-fast-check.ts
|
|
3
|
-
function _define_property$1(obj, key, value) {
|
|
4
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
5
|
-
value,
|
|
6
|
-
enumerable: true,
|
|
7
|
-
configurable: true,
|
|
8
|
-
writable: true
|
|
9
|
-
});
|
|
10
|
-
else obj[key] = value;
|
|
11
|
-
return obj;
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Allocation-free boolean pre-check used by {@link Validator.validate} before the
|
|
15
|
-
* error-collecting walk.
|
|
16
|
-
*
|
|
17
|
-
* Nodes are checked by the generic functions below, which read the type tree and metadata
|
|
18
|
-
* LIVE on every visit. Array items — the same type visited many times per call — go
|
|
19
|
-
* through a compiled {@link Plan} of the item type instead (cached per node, shared by every
|
|
20
|
-
* validator and option set). A plan snapshots what its node's check reads and re-verifies
|
|
21
|
-
* every snapshot against the live node lazily, once per call, right before first using it
|
|
22
|
-
* (rebuilding it when anything differs); constraint objects and pattern arrays are read
|
|
23
|
-
* live on every visit. Either way `annotate()` / `metadata.set()` / prop mutations made
|
|
24
|
-
* after a validator was created are always honoured — the same as the full walk.
|
|
25
|
-
*
|
|
26
|
-
* Result contract (relative to the full walk over the same node and value):
|
|
27
|
-
* - `PASS` — the walk returns `true`, collects no errors and has no side effects other
|
|
28
|
-
* than the strips recorded here (see below).
|
|
29
|
-
* - `FAIL` — the walk returns `false`. Inside a union, every node the walk would visit
|
|
30
|
-
* was visited here too (so a walk that would throw makes this throw first) and the
|
|
31
|
-
* walk's only side effects for this node are the strips recorded here. Outside unions
|
|
32
|
-
* a `FAIL` always ends in the walk, so it may be returned early.
|
|
33
|
-
* - `BAIL` — not decidable here; the caller must run the full walk.
|
|
34
|
-
*
|
|
35
|
-
* Union branches are tried in declared order, continuing past `FAIL` and stopping
|
|
36
|
-
* at `BAIL`, which keeps union results identical to the walk.
|
|
37
|
-
*
|
|
38
|
-
* `unknownProps: 'strip'`: the walk deletes an object's unknown keys right after the object
|
|
39
|
-
* passes (even when an ancestor fails later). This check records those deletions only for
|
|
40
|
-
* the top-level object (`pendingKeys`), whose strip is the walk's last read of the input:
|
|
41
|
-
* deferring an earlier strip past later reads could be observed by them (a prototype, a
|
|
42
|
-
* proxy or an accessor over the stripped object), so a nested object with unknown keys
|
|
43
|
-
* bails, as does any object visit once a strip is pending (a later intersection member).
|
|
44
|
-
* The recorded keys are deleted, in the walk's order, only when the whole value passes —
|
|
45
|
-
* so a `PASS` result still has exactly the walk's side effects, and `FAIL` / `BAIL` leave
|
|
46
|
-
* the value untouched for the walk.
|
|
47
|
-
*/ const FAIL = 0;
|
|
48
|
-
const PASS = 1;
|
|
49
|
-
const BAIL = 2;
|
|
50
|
-
/** Node is at walk depth 0 (only object props / array & tuple items increase depth). */ const TOP = 1;
|
|
51
|
-
/** Node is inside a union branch — failures must be exhaustive (see contract). */ const IN_UNION = 2;
|
|
52
|
-
/** Incremented per {@link fastCheckPasses} call; snapshots verified in older calls re-verify. */ let stamp = 0;
|
|
53
|
-
/** A 'strip' {@link fastCheckPasses} call is in progress (the pending strips below are its own). */ let stripping = false;
|
|
54
|
-
/**
|
|
55
|
-
* Unknown keys of the top-level object the walk would delete (`unknownProps: 'strip'`), in
|
|
56
|
-
* the walk's deletion order. Deleted when the call passes, dropped otherwise.
|
|
57
|
-
*/ const pendingKeys = [];
|
|
58
|
-
/**
|
|
59
|
-
* `true` only when the full walk over `value` is guaranteed to pass with no errors and
|
|
60
|
-
* no side effects other than its 'strip' deletions, which are then performed here, as the
|
|
61
|
-
* walk would. Any other outcome (including a throw) leaves `value` untouched and means
|
|
62
|
-
* "run the walk".
|
|
63
|
-
*/ function fastCheckPasses(def, value, opts) {
|
|
64
|
-
if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
|
|
65
|
-
stamp++;
|
|
66
|
-
try {
|
|
67
|
-
return fastCheck(def, value, TOP, opts) === PASS;
|
|
68
|
-
} catch {
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
/** {@link fastCheckPasses} for `unknownProps: 'strip'`: performs the recorded strips on a pass. */ function fastCheckStripping(def, value, opts) {
|
|
73
|
-
if (stripping) return false;
|
|
74
|
-
stamp++;
|
|
75
|
-
stripping = true;
|
|
76
|
-
let passed;
|
|
77
|
-
try {
|
|
78
|
-
passed = fastCheck(def, value, TOP, opts) === PASS;
|
|
79
|
-
} catch {
|
|
80
|
-
passed = false;
|
|
81
|
-
} finally {
|
|
82
|
-
stripping = false;
|
|
83
|
-
}
|
|
84
|
-
try {
|
|
85
|
-
if (passed) for (const key of pendingKeys) delete value[key];
|
|
86
|
-
} finally {
|
|
87
|
-
pendingKeys.length = 0;
|
|
88
|
-
}
|
|
89
|
-
return passed;
|
|
90
|
-
}
|
|
91
|
-
const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
|
|
92
|
-
const regexCache = /* @__PURE__ */ new Map();
|
|
93
|
-
/** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
|
|
94
|
-
let byFlags = regexCache.get(pattern);
|
|
95
|
-
if (!byFlags) {
|
|
96
|
-
byFlags = /* @__PURE__ */ new Map();
|
|
97
|
-
regexCache.set(pattern, byFlags);
|
|
98
|
-
}
|
|
99
|
-
const flagsKey = flags || "";
|
|
100
|
-
let regex = byFlags.get(flagsKey);
|
|
101
|
-
if (!regex) {
|
|
102
|
-
regex = new RegExp(pattern, flags);
|
|
103
|
-
byFlags.set(flagsKey, regex);
|
|
104
|
-
}
|
|
105
|
-
return regex;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* `true` when `def` (an optional field holding `null`) carries `@meta.required` and its
|
|
109
|
-
* type does not itself accept `null`. Shared by the walk and the fast pre-check.
|
|
110
|
-
*/ function rejectsNullAsRequired(def) {
|
|
111
|
-
return def.metadata.size > 0 && !!def.metadata.get("meta.required") && !acceptsNull(def);
|
|
112
|
-
}
|
|
113
|
-
function acceptsNull(def) {
|
|
114
|
-
const type = def.type;
|
|
115
|
-
if (type.kind === "") {
|
|
116
|
-
const designType = type.designType;
|
|
117
|
-
return designType === "null" || designType === "any";
|
|
118
|
-
}
|
|
119
|
-
if (type.kind === "union") {
|
|
120
|
-
for (const item of type.items) if (item.optional || acceptsNull(item)) return true;
|
|
121
|
-
}
|
|
122
|
-
return false;
|
|
123
|
-
}
|
|
124
|
-
function fastCheck(def, value, flags, opts) {
|
|
125
|
-
if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
|
|
126
|
-
const type = def.type;
|
|
127
|
-
switch (type.kind) {
|
|
128
|
-
case "": return fastCheckFinal(def, value);
|
|
129
|
-
case "object": return fastCheckObject(def, value, flags, opts);
|
|
130
|
-
case "array": return fastCheckArray(def, value, flags, opts);
|
|
131
|
-
case "union": {
|
|
132
|
-
const branchFlags = flags | IN_UNION;
|
|
133
|
-
for (const item of type.items) {
|
|
134
|
-
const result = fastCheck(item, value, branchFlags, opts);
|
|
135
|
-
if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
|
|
136
|
-
if (pendingKeys.length > 0) return BAIL;
|
|
137
|
-
}
|
|
138
|
-
return FAIL;
|
|
139
|
-
}
|
|
140
|
-
case "intersection":
|
|
141
|
-
for (const item of type.items) {
|
|
142
|
-
const result = fastCheck(item, value, flags, opts);
|
|
143
|
-
if (result !== PASS) return result;
|
|
144
|
-
}
|
|
145
|
-
return PASS;
|
|
146
|
-
case "tuple": {
|
|
147
|
-
const items = type.items;
|
|
148
|
-
if (!Array.isArray(value) || value.length !== items.length) return FAIL;
|
|
149
|
-
const itemFlags = flags & IN_UNION;
|
|
150
|
-
for (let i = 0; i < items.length; i++) {
|
|
151
|
-
const result = fastCheck(items[i], value[i], itemFlags, opts);
|
|
152
|
-
if (result !== PASS) return result;
|
|
153
|
-
}
|
|
154
|
-
return PASS;
|
|
155
|
-
}
|
|
156
|
-
default: return BAIL;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
function fastCheckFinal(def, value) {
|
|
160
|
-
const type = def.type;
|
|
161
|
-
const designType = type.designType;
|
|
162
|
-
if (designType === "phantom") return PASS;
|
|
163
|
-
if (type.value !== void 0) return value === type.value ? PASS : FAIL;
|
|
164
|
-
switch (designType) {
|
|
165
|
-
case "string": return typeof value === "string" ? fastCheckString(def.metadata, value) : FAIL;
|
|
166
|
-
case "number": return typeof value === "number" && Number.isFinite(value) ? fastCheckNumber(def.metadata, value) : FAIL;
|
|
167
|
-
case "boolean": return typeof value === "boolean" ? fastCheckBoolean(def.metadata, value) : FAIL;
|
|
168
|
-
case "any": return PASS;
|
|
169
|
-
case "never": return FAIL;
|
|
170
|
-
case "undefined": return value === void 0 ? PASS : FAIL;
|
|
171
|
-
case "null": return value === null ? PASS : FAIL;
|
|
172
|
-
case "decimal": return typeof value === "string" && DECIMAL_RE.test(value) ? PASS : FAIL;
|
|
173
|
-
default: return BAIL;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
/** Result of a union whose branch `item` did not fail (`PASS` or `BAIL`). */ function unionMatchResult(result, item, metadata, value) {
|
|
177
|
-
return result === PASS && item.type.value === void 0 ? fastCheckUnionConstraints(metadata, value) : result;
|
|
178
|
-
}
|
|
179
|
-
/**
|
|
180
|
-
* Mirrors Validator.validateUnionConstraints: union-level constraints on the matched value
|
|
181
|
-
* (`null` / objects pass; the caller skips literal branches).
|
|
182
|
-
*/ function fastCheckUnionConstraints(metadata, value) {
|
|
183
|
-
if (metadata.size === 0) return PASS;
|
|
184
|
-
switch (typeof value) {
|
|
185
|
-
case "string": return fastCheckString(metadata, value);
|
|
186
|
-
case "number": return fastCheckNumber(metadata, value);
|
|
187
|
-
case "boolean": return fastCheckBoolean(metadata, value);
|
|
188
|
-
case "object": return Array.isArray(value) ? fastCheckArrayConstraints(metadata, value) : PASS;
|
|
189
|
-
default: return PASS;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
function fastCheckBoolean(metadata, value) {
|
|
193
|
-
return metadata.size === 0 ? PASS : booleanConstraints(value, metadata.get("meta.required"));
|
|
194
|
-
}
|
|
195
|
-
function fastCheckString(metadata, value) {
|
|
196
|
-
if (metadata.size === 0) return PASS;
|
|
197
|
-
if (metadata.get("meta.required") && value.trim().length === 0) return FAIL;
|
|
198
|
-
const minLength = metadata.get("expect.minLength");
|
|
199
|
-
if (minLength !== void 0 && value.length < (typeof minLength === "number" ? minLength : minLength.length)) return FAIL;
|
|
200
|
-
const maxLength = metadata.get("expect.maxLength");
|
|
201
|
-
if (maxLength !== void 0 && value.length > (typeof maxLength === "number" ? maxLength : maxLength.length)) return FAIL;
|
|
202
|
-
const patterns = metadata.get("expect.pattern");
|
|
203
|
-
if (patterns) for (const { pattern, flags } of patterns) {
|
|
204
|
-
if (!pattern) continue;
|
|
205
|
-
const regex = getRegex(pattern, flags);
|
|
206
|
-
if (regex.global || regex.sticky) return BAIL;
|
|
207
|
-
if (!regex.test(value)) return FAIL;
|
|
208
|
-
}
|
|
209
|
-
return PASS;
|
|
210
|
-
}
|
|
211
|
-
function fastCheckNumber(metadata, value) {
|
|
212
|
-
if (metadata.size === 0) return PASS;
|
|
213
|
-
return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"), metadata.get("expect.exclusiveMin"), metadata.get("expect.exclusiveMax"));
|
|
214
|
-
}
|
|
215
|
-
function booleanConstraints(value, required) {
|
|
216
|
-
return required && value !== true ? FAIL : PASS;
|
|
217
|
-
}
|
|
218
|
-
function numberConstraints(value, int, min, max, exMin, exMax) {
|
|
219
|
-
if (int && value % 1 !== 0) return FAIL;
|
|
220
|
-
if (min !== void 0 && value < (typeof min === "number" ? min : min.minValue)) return FAIL;
|
|
221
|
-
if (max !== void 0 && value > (typeof max === "number" ? max : max.maxValue)) return FAIL;
|
|
222
|
-
if (exMin !== void 0 && value <= (typeof exMin === "number" ? exMin : exMin.exclusiveMinValue)) return FAIL;
|
|
223
|
-
if (exMax !== void 0 && value >= (typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue)) return FAIL;
|
|
224
|
-
return PASS;
|
|
225
|
-
}
|
|
226
|
-
/** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
|
|
227
|
-
return minLength !== void 0 && length < (typeof minLength === "number" ? minLength : minLength.length) || maxLength !== void 0 && length > (typeof maxLength === "number" ? maxLength : maxLength.length);
|
|
228
|
-
}
|
|
229
|
-
/** Array constraints; duplicate detection (`uniqueItems`) is left to the walk. */ function arrayConstraints(length, minLength, maxLength, uniqueItems) {
|
|
230
|
-
if (lengthFails(length, minLength, maxLength)) return FAIL;
|
|
231
|
-
return uniqueItems ? BAIL : PASS;
|
|
232
|
-
}
|
|
233
|
-
function fastCheckObject(def, value, flags, opts) {
|
|
234
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
|
|
235
|
-
const type = def.type;
|
|
236
|
-
if (type.propsPatterns.length > 0) return BAIL;
|
|
237
|
-
if (pendingKeys.length > 0) return BAIL;
|
|
238
|
-
const unknownProps = opts.unknownProps;
|
|
239
|
-
const inUnion = (flags & IN_UNION) !== 0;
|
|
240
|
-
if (unknownProps === "error" && !inUnion && hasUnknownKey(type.props, value)) return FAIL;
|
|
241
|
-
const partial = opts.partial;
|
|
242
|
-
const skipUndefined = partial === "deep" || partial === true && (flags & TOP) !== 0;
|
|
243
|
-
const propFlags = flags & IN_UNION;
|
|
244
|
-
let result = PASS;
|
|
245
|
-
for (const [key, item] of type.props) {
|
|
246
|
-
if (isPhantomType(item)) continue;
|
|
247
|
-
const propValue = value[key];
|
|
248
|
-
if (propValue === void 0 && skipUndefined) continue;
|
|
249
|
-
const propResult = fastCheck(item, propValue, propFlags, opts);
|
|
250
|
-
if (propResult !== PASS) {
|
|
251
|
-
if (propResult === BAIL || !inUnion) return propResult;
|
|
252
|
-
result = FAIL;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
if (result !== PASS) return result;
|
|
256
|
-
if (unknownProps === "strip") return pendStrips(type.props, value, flags);
|
|
257
|
-
return unknownProps === "error" && inUnion && hasUnknownKey(type.props, value) ? FAIL : PASS;
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Records the unknown keys of a passing top-level object: the walk deletes them at this
|
|
261
|
-
* point, after its last read of the input. A nested object's strip would be followed by
|
|
262
|
-
* more reads, so it is left to the walk.
|
|
263
|
-
*/ function pendStrips(props, value, flags) {
|
|
264
|
-
for (const key of Object.keys(value)) if (isUnknownKey(props, key)) {
|
|
265
|
-
if ((flags & TOP) === 0) return BAIL;
|
|
266
|
-
pendingKeys.push(key);
|
|
267
|
-
}
|
|
268
|
-
return PASS;
|
|
269
|
-
}
|
|
270
|
-
/** `true` when `value` has a key the walk treats as unknown. */ function hasUnknownKey(props, value) {
|
|
271
|
-
for (const key of Object.keys(value)) if (isUnknownKey(props, key)) return true;
|
|
272
|
-
return false;
|
|
273
|
-
}
|
|
274
|
-
/** `true` when the walk treats `key` as unknown (no prop, or a phantom one). */ function isUnknownKey(props, key) {
|
|
275
|
-
const known = props.get(key);
|
|
276
|
-
return known === void 0 || isPhantomType(known);
|
|
277
|
-
}
|
|
278
|
-
function fastCheckArray(def, value, flags, opts) {
|
|
279
|
-
if (!Array.isArray(value)) return FAIL;
|
|
280
|
-
const metadata = def.metadata;
|
|
281
|
-
if (metadata.size > 0) {
|
|
282
|
-
const result = fastCheckArrayConstraints(metadata, value);
|
|
283
|
-
if (result !== PASS) return result;
|
|
284
|
-
}
|
|
285
|
-
return checkItems(planFor(def.type.of), value, flags, opts);
|
|
286
|
-
}
|
|
287
|
-
/** Checks every array item against the item type's plan. */ function checkItems(of, value, flags, opts) {
|
|
288
|
-
const inUnion = (flags & IN_UNION) !== 0;
|
|
289
|
-
const itemFlags = flags & IN_UNION;
|
|
290
|
-
let result = PASS;
|
|
291
|
-
for (const item of value) {
|
|
292
|
-
const itemResult = checkPlan(of, item, itemFlags, opts);
|
|
293
|
-
if (itemResult !== PASS) {
|
|
294
|
-
if (itemResult === BAIL || !inUnion) return itemResult;
|
|
295
|
-
result = FAIL;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
return result;
|
|
299
|
-
}
|
|
300
|
-
function fastCheckArrayConstraints(metadata, value) {
|
|
301
|
-
return arrayConstraints(value.length, metadata.get("expect.minLength"), metadata.get("expect.maxLength"), metadata.get("expect.array.uniqueItems"));
|
|
302
|
-
}
|
|
303
|
-
const OP_GENERIC = 0;
|
|
304
|
-
const OP_PHANTOM = 1;
|
|
305
|
-
const OP_STRING = 2;
|
|
306
|
-
const OP_NUMBER = 3;
|
|
307
|
-
const OP_BOOLEAN = 4;
|
|
308
|
-
/** Any other final node: checked by {@link fastCheckFinal}. */ const OP_FINAL = 5;
|
|
309
|
-
const OP_OBJECT = 6;
|
|
310
|
-
const OP_ARRAY = 7;
|
|
311
|
-
const OP_UNION = 8;
|
|
312
|
-
function isFinalOp(op) {
|
|
313
|
-
return op !== OP_GENERIC && op <= OP_FINAL;
|
|
314
|
-
}
|
|
315
|
-
/** Shared placeholder for the per-kind arrays of plans that don't use them. */ const EMPTY = Object.freeze([]);
|
|
316
|
-
const plans = /* @__PURE__ */ new WeakMap();
|
|
317
|
-
/** One shape for every plan, so plan field access stays monomorphic. */ let Plan = class Plan {
|
|
318
|
-
constructor(def) {
|
|
319
|
-
_define_property$1(this, "def", void 0);
|
|
320
|
-
/** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$1(this, "stamp", void 0);
|
|
321
|
-
/** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$1(this, "metaStamp", void 0);
|
|
322
|
-
_define_property$1(this, "op", void 0);
|
|
323
|
-
_define_property$1(this, "type", void 0);
|
|
324
|
-
_define_property$1(this, "optional", void 0);
|
|
325
|
-
_define_property$1(this, "metadata", void 0);
|
|
326
|
-
_define_property$1(this, "kind", void 0);
|
|
327
|
-
_define_property$1(this, "designType", void 0);
|
|
328
|
-
_define_property$1(this, "literal", void 0);
|
|
329
|
-
/** String plans: compiled `@expect.pattern` regexes by position (checked against the live entry). */ _define_property$1(this, "regexes", void 0);
|
|
330
|
-
/**
|
|
331
|
-
* Annotation keys the node's check reads, and their values (`undefined` when absent):
|
|
332
|
-
* string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
|
|
333
|
-
* max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
|
|
334
|
-
*/ _define_property$1(this, "k0", void 0);
|
|
335
|
-
_define_property$1(this, "k1", void 0);
|
|
336
|
-
_define_property$1(this, "k2", void 0);
|
|
337
|
-
_define_property$1(this, "k3", void 0);
|
|
338
|
-
_define_property$1(this, "k4", void 0);
|
|
339
|
-
_define_property$1(this, "m0", void 0);
|
|
340
|
-
_define_property$1(this, "m1", void 0);
|
|
341
|
-
_define_property$1(this, "m2", void 0);
|
|
342
|
-
_define_property$1(this, "m3", void 0);
|
|
343
|
-
_define_property$1(this, "m4", void 0);
|
|
344
|
-
_define_property$1(this, "props", void 0);
|
|
345
|
-
_define_property$1(this, "propsPatterns", void 0);
|
|
346
|
-
_define_property$1(this, "keys", void 0);
|
|
347
|
-
/** Call in which `props.get(keys[i]) === nodes[i]` was last verified. */ _define_property$1(this, "edges", void 0);
|
|
348
|
-
/** Prop plans by key (the entries of `props`, verified per visit via `edges`). */ _define_property$1(this, "byKey", void 0);
|
|
349
|
-
_define_property$1(this, "nodes", void 0);
|
|
350
|
-
_define_property$1(this, "children", void 0);
|
|
351
|
-
_define_property$1(this, "of", void 0);
|
|
352
|
-
_define_property$1(this, "ofPlan", void 0);
|
|
353
|
-
_define_property$1(this, "items", void 0);
|
|
354
|
-
this.def = def;
|
|
355
|
-
this.stamp = -1;
|
|
356
|
-
this.metaStamp = -1;
|
|
357
|
-
this.op = OP_GENERIC;
|
|
358
|
-
this.type = void 0;
|
|
359
|
-
this.optional = void 0;
|
|
360
|
-
this.metadata = void 0;
|
|
361
|
-
this.kind = void 0;
|
|
362
|
-
this.designType = void 0;
|
|
363
|
-
this.literal = void 0;
|
|
364
|
-
this.regexes = EMPTY;
|
|
365
|
-
this.k0 = void 0;
|
|
366
|
-
this.k1 = void 0;
|
|
367
|
-
this.k2 = void 0;
|
|
368
|
-
this.k3 = void 0;
|
|
369
|
-
this.k4 = void 0;
|
|
370
|
-
this.m0 = void 0;
|
|
371
|
-
this.m1 = void 0;
|
|
372
|
-
this.m2 = void 0;
|
|
373
|
-
this.m3 = void 0;
|
|
374
|
-
this.m4 = void 0;
|
|
375
|
-
this.props = void 0;
|
|
376
|
-
this.propsPatterns = void 0;
|
|
377
|
-
this.keys = EMPTY;
|
|
378
|
-
this.edges = EMPTY;
|
|
379
|
-
this.byKey = void 0;
|
|
380
|
-
this.nodes = EMPTY;
|
|
381
|
-
this.children = EMPTY;
|
|
382
|
-
this.of = void 0;
|
|
383
|
-
this.ofPlan = void 0;
|
|
384
|
-
this.items = void 0;
|
|
385
|
-
}
|
|
386
|
-
};
|
|
387
|
-
function planFor(def) {
|
|
388
|
-
let plan = plans.get(def);
|
|
389
|
-
if (plan === void 0) {
|
|
390
|
-
plan = new Plan(def);
|
|
391
|
-
plans.set(def, plan);
|
|
392
|
-
}
|
|
393
|
-
return plan;
|
|
394
|
-
}
|
|
395
|
-
/** Brings the plan's structure up to date with its live node (once per call). */ function refresh(plan) {
|
|
396
|
-
if (!(isFinalOp(plan.op) ? verifyFinal(plan) : verify(plan))) build(plan);
|
|
397
|
-
plan.stamp = stamp;
|
|
398
|
-
}
|
|
399
|
-
/** Structure check for final ops; small enough to be inlined into the hot loops. */ function verifyFinal(plan) {
|
|
400
|
-
const def = plan.def;
|
|
401
|
-
const type = def.type;
|
|
402
|
-
return plan.stamp !== -1 && type === plan.type && def.optional === plan.optional && def.metadata === plan.metadata && type.kind === "" && type.designType === plan.designType && type.value === plan.literal;
|
|
403
|
-
}
|
|
404
|
-
/** Structure check for objects, arrays, unions and generic nodes. */ function verify(plan) {
|
|
405
|
-
if (plan.stamp === -1) return false;
|
|
406
|
-
const def = plan.def;
|
|
407
|
-
const type = def.type;
|
|
408
|
-
if (type !== plan.type || def.optional !== plan.optional || def.metadata !== plan.metadata || type.kind !== plan.kind) return false;
|
|
409
|
-
switch (plan.op) {
|
|
410
|
-
case OP_OBJECT: return type.props === plan.props && plan.props.size === plan.keys.length && type.propsPatterns === plan.propsPatterns && plan.propsPatterns.length === 0;
|
|
411
|
-
case OP_ARRAY: return type.of === plan.of;
|
|
412
|
-
case OP_UNION: {
|
|
413
|
-
const items = plan.items;
|
|
414
|
-
const nodes = plan.nodes;
|
|
415
|
-
if (type.items !== items || items.length !== nodes.length) return false;
|
|
416
|
-
for (let i = 0; i < nodes.length; i++) if (items[i] !== nodes[i]) return false;
|
|
417
|
-
return true;
|
|
418
|
-
}
|
|
419
|
-
default: return type.kind !== "object" || type.propsPatterns.length > 0;
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
/** Brings the annotation values up to date (once per call, when a constraint is read). */ function refreshMeta(plan) {
|
|
423
|
-
const metadata = plan.metadata;
|
|
424
|
-
if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
|
|
425
|
-
plan.metaStamp = stamp;
|
|
426
|
-
}
|
|
427
|
-
function snapshotMeta(plan) {
|
|
428
|
-
const metadata = plan.metadata;
|
|
429
|
-
plan.m0 = metadata.get(plan.k0);
|
|
430
|
-
plan.m1 = metadata.get(plan.k1);
|
|
431
|
-
plan.m2 = metadata.get(plan.k2);
|
|
432
|
-
plan.m3 = metadata.get(plan.k3);
|
|
433
|
-
plan.m4 = metadata.get(plan.k4);
|
|
434
|
-
}
|
|
435
|
-
function setMetaKeys(plan, k0, k1, k2, k3, k4) {
|
|
436
|
-
plan.k0 = k0;
|
|
437
|
-
plan.k1 = k1;
|
|
438
|
-
plan.k2 = k2;
|
|
439
|
-
plan.k3 = k3;
|
|
440
|
-
plan.k4 = k4;
|
|
441
|
-
snapshotMeta(plan);
|
|
442
|
-
plan.metaStamp = stamp;
|
|
443
|
-
}
|
|
444
|
-
/** (Re)compiles `plan` from its live node. */ function build(plan) {
|
|
445
|
-
plan.stamp = -1;
|
|
446
|
-
plan.op = OP_GENERIC;
|
|
447
|
-
const def = plan.def;
|
|
448
|
-
const type = def.type;
|
|
449
|
-
plan.type = type;
|
|
450
|
-
plan.optional = def.optional;
|
|
451
|
-
plan.metadata = def.metadata;
|
|
452
|
-
plan.kind = type.kind;
|
|
453
|
-
plan.designType = type.designType;
|
|
454
|
-
plan.literal = type.value;
|
|
455
|
-
plan.regexes = EMPTY;
|
|
456
|
-
plan.props = void 0;
|
|
457
|
-
plan.propsPatterns = void 0;
|
|
458
|
-
plan.keys = EMPTY;
|
|
459
|
-
plan.edges = EMPTY;
|
|
460
|
-
plan.byKey = void 0;
|
|
461
|
-
plan.nodes = EMPTY;
|
|
462
|
-
plan.children = EMPTY;
|
|
463
|
-
plan.of = void 0;
|
|
464
|
-
plan.ofPlan = void 0;
|
|
465
|
-
plan.items = void 0;
|
|
466
|
-
setMetaKeys(plan);
|
|
467
|
-
switch (type.kind) {
|
|
468
|
-
case "":
|
|
469
|
-
if (type.designType === "phantom") plan.op = OP_PHANTOM;
|
|
470
|
-
else if (type.value !== void 0) plan.op = OP_FINAL;
|
|
471
|
-
else if (type.designType === "string") {
|
|
472
|
-
setMetaKeys(plan, "meta.required", "expect.minLength", "expect.maxLength", "expect.pattern");
|
|
473
|
-
plan.regexes = [];
|
|
474
|
-
plan.op = OP_STRING;
|
|
475
|
-
} else if (type.designType === "number") {
|
|
476
|
-
setMetaKeys(plan, "expect.int", "expect.min", "expect.max", "expect.exclusiveMin", "expect.exclusiveMax");
|
|
477
|
-
plan.op = OP_NUMBER;
|
|
478
|
-
} else if (type.designType === "boolean") {
|
|
479
|
-
setMetaKeys(plan, "meta.required");
|
|
480
|
-
plan.op = OP_BOOLEAN;
|
|
481
|
-
} else plan.op = OP_FINAL;
|
|
482
|
-
break;
|
|
483
|
-
case "object": {
|
|
484
|
-
if (type.propsPatterns.length > 0) break;
|
|
485
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
486
|
-
plan.keys = [];
|
|
487
|
-
plan.edges = [];
|
|
488
|
-
plan.nodes = [];
|
|
489
|
-
plan.children = [];
|
|
490
|
-
for (const [key, node] of type.props) {
|
|
491
|
-
const child = planFor(node);
|
|
492
|
-
plan.keys.push(key);
|
|
493
|
-
plan.edges.push(stamp);
|
|
494
|
-
plan.nodes.push(node);
|
|
495
|
-
plan.children.push(child);
|
|
496
|
-
byKey.set(key, child);
|
|
497
|
-
}
|
|
498
|
-
plan.byKey = byKey;
|
|
499
|
-
plan.props = type.props;
|
|
500
|
-
plan.propsPatterns = type.propsPatterns;
|
|
501
|
-
plan.op = OP_OBJECT;
|
|
502
|
-
break;
|
|
503
|
-
}
|
|
504
|
-
case "array":
|
|
505
|
-
setMetaKeys(plan, "expect.minLength", "expect.maxLength", "expect.array.uniqueItems");
|
|
506
|
-
plan.of = type.of;
|
|
507
|
-
plan.ofPlan = planFor(type.of);
|
|
508
|
-
plan.op = OP_ARRAY;
|
|
509
|
-
break;
|
|
510
|
-
case "union":
|
|
511
|
-
plan.nodes = [];
|
|
512
|
-
plan.children = [];
|
|
513
|
-
for (const node of type.items) {
|
|
514
|
-
plan.nodes.push(node);
|
|
515
|
-
plan.children.push(planFor(node));
|
|
516
|
-
}
|
|
517
|
-
plan.items = type.items;
|
|
518
|
-
plan.op = OP_UNION;
|
|
519
|
-
break;
|
|
520
|
-
default:
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
/** Plan counterpart of {@link fastCheck}. */ function checkPlan(plan, value, flags, opts) {
|
|
524
|
-
if (plan.stamp !== stamp) refresh(plan);
|
|
525
|
-
if (plan.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(plan.def) ? FAIL : PASS;
|
|
526
|
-
switch (plan.op) {
|
|
527
|
-
case OP_STRING: return typeof value === "string" ? checkString(plan, value) : FAIL;
|
|
528
|
-
case OP_NUMBER: return typeof value === "number" && Number.isFinite(value) ? checkNumber(plan, value) : FAIL;
|
|
529
|
-
case OP_OBJECT: return checkObject(plan, value, flags, opts);
|
|
530
|
-
case OP_ARRAY: return checkArray(plan, value, flags, opts);
|
|
531
|
-
case OP_UNION: {
|
|
532
|
-
const branchFlags = flags | IN_UNION;
|
|
533
|
-
for (const child of plan.children) {
|
|
534
|
-
const result = checkPlan(child, value, branchFlags, opts);
|
|
535
|
-
if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
|
|
536
|
-
}
|
|
537
|
-
return FAIL;
|
|
538
|
-
}
|
|
539
|
-
case OP_BOOLEAN:
|
|
540
|
-
if (typeof value !== "boolean") return FAIL;
|
|
541
|
-
if (plan.metaStamp !== stamp) refreshMeta(plan);
|
|
542
|
-
return booleanConstraints(value, plan.m0);
|
|
543
|
-
case OP_PHANTOM:
|
|
544
|
-
case OP_FINAL: return fastCheckFinal(plan.def, value);
|
|
545
|
-
default: return fastCheck(plan.def, value, flags, opts);
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
/** Plan counterpart of {@link fastCheckString}; constraint objects are read live. */ function checkString(plan, value) {
|
|
549
|
-
if (plan.metaStamp !== stamp) refreshMeta(plan);
|
|
550
|
-
if (plan.m0 && value.trim().length === 0) return FAIL;
|
|
551
|
-
if (lengthFails(value.length, plan.m1, plan.m2)) return FAIL;
|
|
552
|
-
const patterns = plan.m3;
|
|
553
|
-
if (patterns) {
|
|
554
|
-
if (!Array.isArray(patterns)) return fastCheckString(plan.metadata, value);
|
|
555
|
-
for (let i = 0; i < patterns.length; i++) {
|
|
556
|
-
const { pattern, flags } = patterns[i];
|
|
557
|
-
if (!pattern) continue;
|
|
558
|
-
let entry = plan.regexes[i];
|
|
559
|
-
if (entry === void 0 || entry.pattern !== pattern || entry.flags !== flags) {
|
|
560
|
-
const re = getRegex(pattern, flags);
|
|
561
|
-
entry = {
|
|
562
|
-
pattern,
|
|
563
|
-
flags,
|
|
564
|
-
re,
|
|
565
|
-
stateful: re.global || re.sticky
|
|
566
|
-
};
|
|
567
|
-
plan.regexes[i] = entry;
|
|
568
|
-
}
|
|
569
|
-
if (entry.stateful) return BAIL;
|
|
570
|
-
if (!entry.re.test(value)) return FAIL;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
return PASS;
|
|
574
|
-
}
|
|
575
|
-
/** Plan counterpart of {@link fastCheckNumber}; constraint objects are read live. */ function checkNumber(plan, value) {
|
|
576
|
-
if (plan.metaStamp !== stamp) refreshMeta(plan);
|
|
577
|
-
return numberConstraints(value, plan.m0, plan.m1, plan.m2, plan.m3, plan.m4);
|
|
578
|
-
}
|
|
579
|
-
/** Plan counterpart of {@link fastCheckObject}. */ function checkObject(plan, value, flags, opts) {
|
|
580
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
|
|
581
|
-
const partial = opts.partial;
|
|
582
|
-
const skipUndefined = partial === "deep" || partial === true && (flags & TOP) !== 0;
|
|
583
|
-
const inUnion = (flags & IN_UNION) !== 0;
|
|
584
|
-
const propFlags = flags & IN_UNION;
|
|
585
|
-
const keys = plan.keys;
|
|
586
|
-
const children = plan.children;
|
|
587
|
-
const edges = plan.edges;
|
|
588
|
-
let result = PASS;
|
|
589
|
-
for (let i = 0; i < keys.length; i++) {
|
|
590
|
-
if (edges[i] !== stamp) {
|
|
591
|
-
if (plan.props.get(keys[i]) !== plan.nodes[i]) {
|
|
592
|
-
plan.stamp = -1;
|
|
593
|
-
return BAIL;
|
|
594
|
-
}
|
|
595
|
-
edges[i] = stamp;
|
|
596
|
-
}
|
|
597
|
-
const child = children[i];
|
|
598
|
-
if (child.stamp !== stamp) refresh(child);
|
|
599
|
-
const op = child.op;
|
|
600
|
-
if (op === OP_PHANTOM) continue;
|
|
601
|
-
const propValue = value[keys[i]];
|
|
602
|
-
if (propValue === void 0 && skipUndefined) continue;
|
|
603
|
-
if (typeof propValue === "string" && op === OP_STRING) {
|
|
604
|
-
const r = checkString(child, propValue);
|
|
605
|
-
if (r === PASS) continue;
|
|
606
|
-
if (r === BAIL || !inUnion) return r;
|
|
607
|
-
result = FAIL;
|
|
608
|
-
continue;
|
|
609
|
-
}
|
|
610
|
-
if (typeof propValue === "number" && op === OP_NUMBER) {
|
|
611
|
-
if (Number.isFinite(propValue) && checkNumber(child, propValue) === PASS) continue;
|
|
612
|
-
if (!inUnion) return FAIL;
|
|
613
|
-
result = FAIL;
|
|
614
|
-
continue;
|
|
615
|
-
}
|
|
616
|
-
const propResult = checkPlan(child, propValue, propFlags, opts);
|
|
617
|
-
if (propResult !== PASS) {
|
|
618
|
-
if (propResult === BAIL || !inUnion) return propResult;
|
|
619
|
-
result = FAIL;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
if (result !== PASS) return result;
|
|
623
|
-
const unknownProps = opts.unknownProps;
|
|
624
|
-
if (unknownProps === "error" || unknownProps === "strip") {
|
|
625
|
-
const byKey = plan.byKey;
|
|
626
|
-
for (const key of Object.keys(value)) {
|
|
627
|
-
const known = byKey.get(key);
|
|
628
|
-
if (known === void 0 || known.op === OP_PHANTOM) return unknownProps === "error" ? FAIL : BAIL;
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
return PASS;
|
|
632
|
-
}
|
|
633
|
-
/** Plan counterpart of {@link fastCheckArray}. */ function checkArray(plan, value, flags, opts) {
|
|
634
|
-
if (!Array.isArray(value)) return FAIL;
|
|
635
|
-
if (plan.metaStamp !== stamp) refreshMeta(plan);
|
|
636
|
-
const result = arrayConstraints(value.length, plan.m0, plan.m1, plan.m2);
|
|
637
|
-
if (result !== PASS) return result;
|
|
638
|
-
return checkItems(plan.ofPlan, value, flags, opts);
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
//#endregion
|
|
642
|
-
//#region packages/typescript/src/runtime/validator.ts
|
|
643
|
-
function _define_property(obj, key, value) {
|
|
644
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
645
|
-
value,
|
|
646
|
-
enumerable: true,
|
|
647
|
-
configurable: true,
|
|
648
|
-
writable: true
|
|
649
|
-
});
|
|
650
|
-
else obj[key] = value;
|
|
651
|
-
return obj;
|
|
652
|
-
}
|
|
653
|
-
/**
|
|
654
|
-
* Validates values against an {@link TAtscriptAnnotatedType} definition.
|
|
655
|
-
*
|
|
656
|
-
* `DataType` is automatically inferred from the type definition's phantom generic,
|
|
657
|
-
* enabling the {@link validate} method to act as a type guard.
|
|
658
|
-
*
|
|
659
|
-
* @example
|
|
660
|
-
* ```ts
|
|
661
|
-
* // From a generated interface class:
|
|
662
|
-
* const validator = new Validator(MyInterface)
|
|
663
|
-
* if (validator.validate(data, true)) {
|
|
664
|
-
* data // narrowed to MyInterface
|
|
665
|
-
* }
|
|
666
|
-
*
|
|
667
|
-
* // Or use the built-in factory:
|
|
668
|
-
* MyInterface.validator().validate(data)
|
|
669
|
-
* ```
|
|
670
|
-
*
|
|
671
|
-
* @typeParam T - The annotated type definition.
|
|
672
|
-
* @typeParam DataType - The TypeScript type that `validate` narrows to (auto-inferred).
|
|
673
|
-
*/ var Validator = class Validator {
|
|
674
|
-
buildPath() {
|
|
675
|
-
if (this.depth <= 0) return "";
|
|
676
|
-
let path = this.pathSegments[0];
|
|
677
|
-
for (let i = 1; i < this.depth; i++) path += `.${this.pathSegments[i]}`;
|
|
678
|
-
return path;
|
|
679
|
-
}
|
|
680
|
-
push(name) {
|
|
681
|
-
this.pathSegments[this.depth] = name;
|
|
682
|
-
this.depth++;
|
|
683
|
-
this.stackErrors.push(null);
|
|
684
|
-
}
|
|
685
|
-
pop(saveErrors) {
|
|
686
|
-
this.depth--;
|
|
687
|
-
const popped = this.stackErrors.pop();
|
|
688
|
-
if (saveErrors && popped !== null && popped !== void 0 && popped.length > 0) for (const err of popped) this.error(err.message, err.path, err.details);
|
|
689
|
-
return popped;
|
|
690
|
-
}
|
|
691
|
-
clear() {
|
|
692
|
-
this.stackErrors[this.stackErrors.length - 1] = null;
|
|
693
|
-
if (this.limitExceeded) this.limitExceeded = false;
|
|
694
|
-
}
|
|
695
|
-
error(message, path, details) {
|
|
696
|
-
let errors = this.stackErrors[this.stackErrors.length - 1];
|
|
697
|
-
if (!errors) if (this.stackErrors.length > 0) {
|
|
698
|
-
errors = [];
|
|
699
|
-
this.stackErrors[this.stackErrors.length - 1] = errors;
|
|
700
|
-
} else errors = this.errors;
|
|
701
|
-
const error = {
|
|
702
|
-
path: path || this.buildPath(),
|
|
703
|
-
message
|
|
704
|
-
};
|
|
705
|
-
if (details?.length) error.details = details;
|
|
706
|
-
errors.push(error);
|
|
707
|
-
if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
|
|
708
|
-
}
|
|
709
|
-
throw() {
|
|
710
|
-
throw new ValidatorError(this.errors);
|
|
711
|
-
}
|
|
712
|
-
/**
|
|
713
|
-
* Validates a value against the type definition.
|
|
714
|
-
*
|
|
715
|
-
* Acts as a TypeScript type guard — when it returns `true`, the value
|
|
716
|
-
* is narrowed to `DataType`.
|
|
717
|
-
*
|
|
718
|
-
* @param value - The value to validate.
|
|
719
|
-
* @param safe - If `true`, returns `false` on failure instead of throwing.
|
|
720
|
-
* @returns `true` if the value matches the type definition.
|
|
721
|
-
* @throws {ValidatorError} When validation fails and `safe` is not `true`.
|
|
722
|
-
*/ validate(value, safe, context) {
|
|
723
|
-
this.errors = [];
|
|
724
|
-
this.stackErrors.length = 0;
|
|
725
|
-
this.depth = 0;
|
|
726
|
-
this.limitExceeded = false;
|
|
727
|
-
if (this.shortcuts && !this.opts.skipList && typeof this.opts.partial !== "function" && fastCheckPasses(this.def, value, this.opts)) return true;
|
|
728
|
-
this.context = context;
|
|
729
|
-
const passed = this.validateSafe(this.def, value);
|
|
730
|
-
this.context = void 0;
|
|
731
|
-
if (!passed) {
|
|
732
|
-
if (safe) return false;
|
|
733
|
-
this.throw();
|
|
734
|
-
}
|
|
735
|
-
return true;
|
|
736
|
-
}
|
|
737
|
-
/**
|
|
738
|
-
* Plain `Validator` without plugins / `replace`: eligible for the allocation-free
|
|
739
|
-
* shortcuts. Subclasses may override the protected `validate*` hooks, so they
|
|
740
|
-
* always take the full walk. (A getter, not a constructor-set field: validators are
|
|
741
|
-
* often built per call, so construction stays as cheap as before.)
|
|
742
|
-
*/ get shortcuts() {
|
|
743
|
-
return this.constructor === Validator && !this.hasPlugins && !this.hasReplace;
|
|
744
|
-
}
|
|
745
|
-
validateSafe(def, value) {
|
|
746
|
-
if (this.limitExceeded) return false;
|
|
747
|
-
if (this.hasReplace) {
|
|
748
|
-
let replaced = this.replaceCache.get(def);
|
|
749
|
-
if (replaced === void 0) {
|
|
750
|
-
replaced = this.opts.replace(def, this.buildPath());
|
|
751
|
-
this.replaceCache.set(def, replaced);
|
|
752
|
-
}
|
|
753
|
-
def = replaced;
|
|
754
|
-
}
|
|
755
|
-
if (def.optional && (value === void 0 || value === null)) {
|
|
756
|
-
if (value === null && rejectsNullAsRequired(def)) {
|
|
757
|
-
this.error(requiredMessage(def));
|
|
758
|
-
return false;
|
|
759
|
-
}
|
|
760
|
-
return true;
|
|
761
|
-
}
|
|
762
|
-
if (this.hasPlugins) for (const plugin of this.opts.plugins) {
|
|
763
|
-
const result = plugin(this, def, value);
|
|
764
|
-
if (result === false || result === true) return result;
|
|
765
|
-
}
|
|
766
|
-
return this.validateAnnotatedType(def, value);
|
|
767
|
-
}
|
|
768
|
-
get path() {
|
|
769
|
-
return this.buildPath();
|
|
770
|
-
}
|
|
771
|
-
/** The type this validator was created for (see {@link TValidatorPluginContext.root}). */ get root() {
|
|
772
|
-
return this.def;
|
|
773
|
-
}
|
|
774
|
-
validateAnnotatedType(def, value) {
|
|
775
|
-
switch (def.type.kind) {
|
|
776
|
-
case "":
|
|
777
|
-
if (def.type.designType === "phantom") return true;
|
|
778
|
-
return this.validatePrimitive(def, value);
|
|
779
|
-
case "object": return this.validateObject(def, value);
|
|
780
|
-
case "array": return this.validateArray(def, value);
|
|
781
|
-
case "union": return this.validateUnion(def, value);
|
|
782
|
-
case "intersection": return this.validateIntersection(def, value);
|
|
783
|
-
case "tuple": return this.validateTuple(def, value);
|
|
784
|
-
default: throw new Error(`Unknown type kind "${def.type.kind}"`);
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
validateUnion(def, value) {
|
|
788
|
-
const items = def.type.items;
|
|
789
|
-
if (this.shortcuts) for (const item of items) {
|
|
790
|
-
const type = item.type;
|
|
791
|
-
if (item.optional || type.kind !== "" || type.value === void 0 || type.designType === "phantom") break;
|
|
792
|
-
if (type.value === value) return true;
|
|
793
|
-
}
|
|
794
|
-
let details;
|
|
795
|
-
for (const item of items) {
|
|
796
|
-
this.stackErrors.push(null);
|
|
797
|
-
if (this.validateSafe(item, value)) {
|
|
798
|
-
this.stackErrors.pop();
|
|
799
|
-
return this.validateUnionConstraints(def, item, value);
|
|
800
|
-
}
|
|
801
|
-
const branchErrors = this.stackErrors.pop();
|
|
802
|
-
if (this.limitExceeded) this.limitExceeded = false;
|
|
803
|
-
if (branchErrors) if (details) for (const err of branchErrors) details.push(err);
|
|
804
|
-
else details = branchErrors;
|
|
805
|
-
}
|
|
806
|
-
const expected = items.map((item, i) => `[${item.type.kind || item.type.designType}(${i})]`).join(", ");
|
|
807
|
-
this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
|
|
808
|
-
return false;
|
|
809
|
-
}
|
|
810
|
-
/**
|
|
811
|
-
* Constraints annotated on the union itself (`@expect.min 0` on `number | null`)
|
|
812
|
-
* apply to the non-null value that matched `branch`, on top of the branch's own.
|
|
813
|
-
* A literal branch (an enum value) is exempt: its value is fixed.
|
|
814
|
-
*/ validateUnionConstraints(def, branch, value) {
|
|
815
|
-
const metadata = def.metadata;
|
|
816
|
-
if (metadata.size === 0 || branch.type.value !== void 0) return true;
|
|
817
|
-
switch (typeof value) {
|
|
818
|
-
case "string": return this.validateStringConstraints(metadata, value);
|
|
819
|
-
case "number": return this.validateNumberConstraints(metadata, value);
|
|
820
|
-
case "boolean": return this.validateBooleanConstraints(metadata, value);
|
|
821
|
-
case "object":
|
|
822
|
-
if (Array.isArray(value)) return this.validateArrayConstraints(metadata, value, arrayElementType(branch));
|
|
823
|
-
return true;
|
|
824
|
-
default: return true;
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
validateIntersection(def, value) {
|
|
828
|
-
for (const item of def.type.items) if (!this.validateSafe(item, value)) return false;
|
|
829
|
-
return true;
|
|
830
|
-
}
|
|
831
|
-
validateTuple(def, value) {
|
|
832
|
-
if (!Array.isArray(value) || value.length !== def.type.items.length) {
|
|
833
|
-
this.error(`Expected array of length ${def.type.items.length}`);
|
|
834
|
-
return false;
|
|
835
|
-
}
|
|
836
|
-
let i = 0;
|
|
837
|
-
for (const item of def.type.items) {
|
|
838
|
-
this.push(String(i));
|
|
839
|
-
if (!this.validateSafe(item, value[i])) {
|
|
840
|
-
this.pop(true);
|
|
841
|
-
return false;
|
|
842
|
-
}
|
|
843
|
-
this.pop(false);
|
|
844
|
-
i++;
|
|
845
|
-
}
|
|
846
|
-
return true;
|
|
847
|
-
}
|
|
848
|
-
validateArray(def, value) {
|
|
849
|
-
if (!Array.isArray(value)) {
|
|
850
|
-
this.error("Expected array");
|
|
851
|
-
return false;
|
|
852
|
-
}
|
|
853
|
-
if (def.metadata.size > 0 && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
|
|
854
|
-
let i = 0;
|
|
855
|
-
let passed = true;
|
|
856
|
-
for (const item of value) {
|
|
857
|
-
this.push(String(i));
|
|
858
|
-
if (!this.validateSafe(def.type.of, item)) {
|
|
859
|
-
passed = false;
|
|
860
|
-
this.pop(true);
|
|
861
|
-
if (this.limitExceeded) return false;
|
|
862
|
-
} else this.pop(false);
|
|
863
|
-
i++;
|
|
864
|
-
}
|
|
865
|
-
return passed;
|
|
866
|
-
}
|
|
867
|
-
/** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */ validateArrayConstraints(metadata, value, of) {
|
|
868
|
-
const minLength = metadata.get("expect.minLength");
|
|
869
|
-
if (minLength !== void 0) {
|
|
870
|
-
const length = typeof minLength === "number" ? minLength : minLength.length;
|
|
871
|
-
if (value.length < length) {
|
|
872
|
-
const message = typeof minLength === "object" && minLength.message ? minLength.message : `Expected minimum length of ${length} items, got ${value.length} items`;
|
|
873
|
-
this.error(message);
|
|
874
|
-
return false;
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
const maxLength = metadata.get("expect.maxLength");
|
|
878
|
-
if (maxLength !== void 0) {
|
|
879
|
-
const length = typeof maxLength === "number" ? maxLength : maxLength.length;
|
|
880
|
-
if (value.length > length) {
|
|
881
|
-
const message = typeof maxLength === "object" && maxLength.message ? maxLength.message : `Expected maximum length of ${length} items, got ${value.length} items`;
|
|
882
|
-
this.error(message);
|
|
883
|
-
return false;
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
const uniqueItems = metadata.get("expect.array.uniqueItems");
|
|
887
|
-
if (uniqueItems) {
|
|
888
|
-
const separator = "▼↩";
|
|
889
|
-
const seen = /* @__PURE__ */ new Set();
|
|
890
|
-
const keyProps = /* @__PURE__ */ new Set();
|
|
891
|
-
if (of?.type.kind === "object") {
|
|
892
|
-
for (const [key, val] of of.type.props.entries()) if (val.metadata.get("expect.array.key")) keyProps.add(key);
|
|
893
|
-
}
|
|
894
|
-
for (let idx = 0; idx < value.length; idx++) {
|
|
895
|
-
const item = value[idx];
|
|
896
|
-
let key;
|
|
897
|
-
if (keyProps.size > 0) {
|
|
898
|
-
key = "";
|
|
899
|
-
for (const prop of keyProps) key += JSON.stringify(item[prop]) + separator;
|
|
900
|
-
} else key = JSON.stringify(item);
|
|
901
|
-
if (seen.has(key)) {
|
|
902
|
-
this.push(String(idx));
|
|
903
|
-
this.error(uniqueItems.message || "Duplicate items are not allowed");
|
|
904
|
-
this.pop(true);
|
|
905
|
-
return false;
|
|
906
|
-
}
|
|
907
|
-
seen.add(key);
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
return true;
|
|
911
|
-
}
|
|
912
|
-
validateObject(def, value) {
|
|
913
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
914
|
-
this.error("Expected object");
|
|
915
|
-
return false;
|
|
916
|
-
}
|
|
917
|
-
let passed = true;
|
|
918
|
-
let keysToStrip;
|
|
919
|
-
let skipList;
|
|
920
|
-
if (this.opts.skipList) {
|
|
921
|
-
const path = this.depth > 0 ? `${this.buildPath()}.` : "";
|
|
922
|
-
for (const item of this.opts.skipList) if (item.startsWith(path)) {
|
|
923
|
-
const key = item.slice(path.length);
|
|
924
|
-
if (!skipList) skipList = /* @__PURE__ */ new Set();
|
|
925
|
-
skipList.add(key);
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
let partialFunctionMatched = false;
|
|
929
|
-
if (typeof this.opts.partial === "function") partialFunctionMatched = this.opts.partial(def, this.buildPath());
|
|
930
|
-
for (const [key, item] of def.type.props.entries()) {
|
|
931
|
-
if (skipList && skipList.has(key) || isPhantomType(item)) continue;
|
|
932
|
-
if (value[key] === void 0) {
|
|
933
|
-
if (partialFunctionMatched || this.opts.partial === "deep" || this.opts.partial === true && this.depth === 0) continue;
|
|
934
|
-
}
|
|
935
|
-
this.push(key);
|
|
936
|
-
if (this.validateSafe(item, value[key])) this.pop(false);
|
|
937
|
-
else {
|
|
938
|
-
passed = false;
|
|
939
|
-
this.pop(true);
|
|
940
|
-
if (this.limitExceeded) return false;
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
const hasPatterns = def.type.propsPatterns.length > 0;
|
|
944
|
-
if (this.opts.unknownProps !== "ignore" || hasPatterns) {
|
|
945
|
-
const keys = Object.keys(value);
|
|
946
|
-
for (const key of keys) {
|
|
947
|
-
if (skipList && skipList.has(key)) continue;
|
|
948
|
-
const knownProp = def.type.props.get(key);
|
|
949
|
-
if (knownProp && !isPhantomType(knownProp)) continue;
|
|
950
|
-
const matched = [];
|
|
951
|
-
for (const { pattern, def: propDef } of def.type.propsPatterns) if (pattern.test(key)) matched.push({
|
|
952
|
-
pattern,
|
|
953
|
-
def: propDef
|
|
954
|
-
});
|
|
955
|
-
if (matched.length > 0) {
|
|
956
|
-
this.push(key);
|
|
957
|
-
let keyPassed = false;
|
|
958
|
-
for (const { def: propDef } of matched) {
|
|
959
|
-
if (this.validateSafe(propDef, value[key])) {
|
|
960
|
-
keyPassed = true;
|
|
961
|
-
break;
|
|
962
|
-
}
|
|
963
|
-
this.clear();
|
|
964
|
-
}
|
|
965
|
-
if (!keyPassed) {
|
|
966
|
-
this.validateSafe(matched[0].def, value[key]);
|
|
967
|
-
this.pop(true);
|
|
968
|
-
passed = false;
|
|
969
|
-
if (this.limitExceeded) return false;
|
|
970
|
-
} else this.pop(false);
|
|
971
|
-
} else if (this.opts.unknownProps === "error") {
|
|
972
|
-
this.push(key);
|
|
973
|
-
this.error(`Unexpected property`);
|
|
974
|
-
this.pop(true);
|
|
975
|
-
if (this.limitExceeded) return false;
|
|
976
|
-
passed = false;
|
|
977
|
-
} else if (this.opts.unknownProps === "strip") {
|
|
978
|
-
if (!keysToStrip) keysToStrip = [];
|
|
979
|
-
keysToStrip.push(key);
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
if (passed && keysToStrip) for (const key of keysToStrip) delete value[key];
|
|
984
|
-
return passed;
|
|
985
|
-
}
|
|
986
|
-
validatePrimitive(def, value) {
|
|
987
|
-
if (def.type.value !== void 0) {
|
|
988
|
-
if (value !== def.type.value) {
|
|
989
|
-
this.error(`Expected ${def.type.value}, got ${printValue(value)}`);
|
|
990
|
-
return false;
|
|
991
|
-
}
|
|
992
|
-
return true;
|
|
993
|
-
}
|
|
994
|
-
const typeOfValue = Array.isArray(value) ? "array" : typeof value;
|
|
995
|
-
switch (def.type.designType) {
|
|
996
|
-
case "never":
|
|
997
|
-
this.error(`This type is impossible, must be an internal problem`);
|
|
998
|
-
return false;
|
|
999
|
-
case "any": return true;
|
|
1000
|
-
case "string":
|
|
1001
|
-
if (typeOfValue !== def.type.designType) {
|
|
1002
|
-
this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
|
|
1003
|
-
return false;
|
|
1004
|
-
}
|
|
1005
|
-
return this.validateString(def, value);
|
|
1006
|
-
case "number":
|
|
1007
|
-
if (typeOfValue !== def.type.designType) {
|
|
1008
|
-
this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
|
|
1009
|
-
return false;
|
|
1010
|
-
}
|
|
1011
|
-
if (!Number.isFinite(value)) {
|
|
1012
|
-
this.error(`Expected finite number, got ${value}`);
|
|
1013
|
-
return false;
|
|
1014
|
-
}
|
|
1015
|
-
return this.validateNumber(def, value);
|
|
1016
|
-
case "boolean":
|
|
1017
|
-
if (typeOfValue !== def.type.designType) {
|
|
1018
|
-
this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
|
|
1019
|
-
return false;
|
|
1020
|
-
}
|
|
1021
|
-
return this.validateBoolean(def, value);
|
|
1022
|
-
case "undefined":
|
|
1023
|
-
if (value !== void 0) {
|
|
1024
|
-
this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
|
|
1025
|
-
return false;
|
|
1026
|
-
}
|
|
1027
|
-
return true;
|
|
1028
|
-
case "null":
|
|
1029
|
-
if (value !== null) {
|
|
1030
|
-
this.error(`Expected ${def.type.designType}, got ${typeOfValue}`);
|
|
1031
|
-
return false;
|
|
1032
|
-
}
|
|
1033
|
-
return true;
|
|
1034
|
-
case "decimal":
|
|
1035
|
-
if (typeOfValue !== "string") {
|
|
1036
|
-
this.error(`Expected string (decimal), got ${typeOfValue}`);
|
|
1037
|
-
return false;
|
|
1038
|
-
}
|
|
1039
|
-
if (!DECIMAL_RE.test(value)) {
|
|
1040
|
-
this.error(`Invalid decimal format: ${JSON.stringify(value)}`);
|
|
1041
|
-
return false;
|
|
1042
|
-
}
|
|
1043
|
-
return true;
|
|
1044
|
-
default: throw new Error(`Unknown type "${def.type.designType}"`);
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
validateString(def, value) {
|
|
1048
|
-
return this.validateStringConstraints(def.metadata, value);
|
|
1049
|
-
}
|
|
1050
|
-
/** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */ validateStringConstraints(metadata, value) {
|
|
1051
|
-
if (metadata.size === 0) return true;
|
|
1052
|
-
const filled = metadata.get("meta.required");
|
|
1053
|
-
if (filled) {
|
|
1054
|
-
if (value.trim().length === 0) {
|
|
1055
|
-
const message = typeof filled === "object" && filled.message ? filled.message : `Must not be empty`;
|
|
1056
|
-
this.error(message);
|
|
1057
|
-
return false;
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
const minLength = metadata.get("expect.minLength");
|
|
1061
|
-
if (minLength !== void 0) {
|
|
1062
|
-
const length = typeof minLength === "number" ? minLength : minLength.length;
|
|
1063
|
-
if (value.length < length) {
|
|
1064
|
-
const message = typeof minLength === "object" && minLength.message ? minLength.message : `Expected minimum length of ${length} characters, got ${value.length} characters`;
|
|
1065
|
-
this.error(message);
|
|
1066
|
-
return false;
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
const maxLength = metadata.get("expect.maxLength");
|
|
1070
|
-
if (maxLength !== void 0) {
|
|
1071
|
-
const length = typeof maxLength === "number" ? maxLength : maxLength.length;
|
|
1072
|
-
if (value.length > length) {
|
|
1073
|
-
const message = typeof maxLength === "object" && maxLength.message ? maxLength.message : `Expected maximum length of ${length} characters, got ${value.length} characters`;
|
|
1074
|
-
this.error(message);
|
|
1075
|
-
return false;
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
const patterns = metadata.get("expect.pattern");
|
|
1079
|
-
for (const { pattern, flags, message } of patterns || []) {
|
|
1080
|
-
if (!pattern) continue;
|
|
1081
|
-
if (!getRegex(pattern, flags).test(value)) {
|
|
1082
|
-
this.error(message || `Value is expected to match pattern "${pattern}"`);
|
|
1083
|
-
return false;
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
return true;
|
|
1087
|
-
}
|
|
1088
|
-
validateNumber(def, value) {
|
|
1089
|
-
return this.validateNumberConstraints(def.metadata, value);
|
|
1090
|
-
}
|
|
1091
|
-
/** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(metadata, value) {
|
|
1092
|
-
if (metadata.size === 0) return true;
|
|
1093
|
-
const int = metadata.get("expect.int");
|
|
1094
|
-
if (int && value % 1 !== 0) {
|
|
1095
|
-
const message = typeof int === "object" && int.message ? int.message : `Expected integer, got ${value}`;
|
|
1096
|
-
this.error(message);
|
|
1097
|
-
return false;
|
|
1098
|
-
}
|
|
1099
|
-
const min = metadata.get("expect.min");
|
|
1100
|
-
if (min !== void 0) {
|
|
1101
|
-
const minValue = typeof min === "number" ? min : min.minValue;
|
|
1102
|
-
if (value < minValue) return this.numberBoundFailed(min, "minimum", minValue, value);
|
|
1103
|
-
}
|
|
1104
|
-
const max = metadata.get("expect.max");
|
|
1105
|
-
if (max !== void 0) {
|
|
1106
|
-
const maxValue = typeof max === "number" ? max : max.maxValue;
|
|
1107
|
-
if (value > maxValue) return this.numberBoundFailed(max, "maximum", maxValue, value);
|
|
1108
|
-
}
|
|
1109
|
-
const exMin = metadata.get("expect.exclusiveMin");
|
|
1110
|
-
if (exMin !== void 0) {
|
|
1111
|
-
const bound = typeof exMin === "number" ? exMin : exMin.exclusiveMinValue;
|
|
1112
|
-
if (value <= bound) return this.numberBoundFailed(exMin, "greater than", bound, value);
|
|
1113
|
-
}
|
|
1114
|
-
const exMax = metadata.get("expect.exclusiveMax");
|
|
1115
|
-
if (exMax !== void 0) {
|
|
1116
|
-
const bound = typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue;
|
|
1117
|
-
if (value >= bound) return this.numberBoundFailed(exMax, "less than", bound, value);
|
|
1118
|
-
}
|
|
1119
|
-
return true;
|
|
1120
|
-
}
|
|
1121
|
-
/** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */ numberBoundFailed(annotation, label, bound, value) {
|
|
1122
|
-
const message = typeof annotation === "object" && annotation.message ? annotation.message : `Expected ${label} ${bound}, got ${value}`;
|
|
1123
|
-
this.error(message);
|
|
1124
|
-
return false;
|
|
1125
|
-
}
|
|
1126
|
-
validateBoolean(def, value) {
|
|
1127
|
-
return this.validateBooleanConstraints(def.metadata, value);
|
|
1128
|
-
}
|
|
1129
|
-
/** `@meta.required` check for a boolean value (must be `true`). */ validateBooleanConstraints(metadata, value) {
|
|
1130
|
-
if (metadata.size === 0) return true;
|
|
1131
|
-
const filled = metadata.get("meta.required");
|
|
1132
|
-
if (filled) {
|
|
1133
|
-
if (value !== true) {
|
|
1134
|
-
const message = typeof filled === "object" && filled.message ? filled.message : `Must be checked`;
|
|
1135
|
-
this.error(message);
|
|
1136
|
-
return false;
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
return true;
|
|
1140
|
-
}
|
|
1141
|
-
constructor(def, opts) {
|
|
1142
|
-
_define_property(this, "def", void 0);
|
|
1143
|
-
_define_property(this, "opts", void 0);
|
|
1144
|
-
_define_property(this, "hasPlugins", void 0);
|
|
1145
|
-
_define_property(this, "hasReplace", void 0);
|
|
1146
|
-
_define_property(this, "replaceCache", void 0);
|
|
1147
|
-
/** Validation errors collected during the last {@link validate} call. */ _define_property(this, "errors", void 0);
|
|
1148
|
-
_define_property(this, "stackErrors", void 0);
|
|
1149
|
-
_define_property(this, "pathSegments", void 0);
|
|
1150
|
-
_define_property(this, "depth", void 0);
|
|
1151
|
-
_define_property(this, "limitExceeded", void 0);
|
|
1152
|
-
_define_property(this, "context", void 0);
|
|
1153
|
-
this.def = def;
|
|
1154
|
-
this.errors = [];
|
|
1155
|
-
this.stackErrors = [];
|
|
1156
|
-
this.pathSegments = [];
|
|
1157
|
-
this.depth = 0;
|
|
1158
|
-
this.limitExceeded = false;
|
|
1159
|
-
this.opts = {
|
|
1160
|
-
partial: false,
|
|
1161
|
-
unknownProps: "error",
|
|
1162
|
-
errorLimit: 10,
|
|
1163
|
-
...opts,
|
|
1164
|
-
plugins: opts?.plugins || []
|
|
1165
|
-
};
|
|
1166
|
-
this.hasPlugins = this.opts.plugins.length > 0;
|
|
1167
|
-
this.hasReplace = typeof this.opts.replace === "function";
|
|
1168
|
-
if (this.hasReplace) this.replaceCache = /* @__PURE__ */ new WeakMap();
|
|
1169
|
-
}
|
|
1170
|
-
};
|
|
1171
|
-
/** The `@meta.required` error message for `def` (custom message or the type's default). */ function requiredMessage(def) {
|
|
1172
|
-
const filled = def.metadata.get("meta.required");
|
|
1173
|
-
if (typeof filled === "object" && filled.message) return filled.message;
|
|
1174
|
-
return def.type.kind === "" && def.type.designType === "boolean" ? "Must be checked" : "Must not be empty";
|
|
1175
|
-
}
|
|
1176
|
-
/**
|
|
1177
|
-
* Element type of the array a union branch holds — through nested unions too
|
|
1178
|
-
* (`Items | undefined` with `type Items = Item[] | null`), so `@expect.array.key`
|
|
1179
|
-
* fields of the elements are found.
|
|
1180
|
-
*/ function arrayElementType(branch) {
|
|
1181
|
-
const type = branch.type;
|
|
1182
|
-
if (type.kind === "array") return type.of;
|
|
1183
|
-
if (type.kind === "union") for (const item of type.items) {
|
|
1184
|
-
const of = arrayElementType(item);
|
|
1185
|
-
if (of) return of;
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
/** `${value}` throws for symbols and null-prototype objects: `String()` handles symbols, the tag the rest. */ function printValue(value) {
|
|
1189
|
-
try {
|
|
1190
|
-
return String(value);
|
|
1191
|
-
} catch {
|
|
1192
|
-
return Object.prototype.toString.call(value);
|
|
1193
|
-
}
|
|
1194
|
-
}
|
|
1195
|
-
/** Error thrown by {@link Validator.validate} when validation fails. Contains structured error details. */ var ValidatorError = class extends Error {
|
|
1196
|
-
constructor(errors) {
|
|
1197
|
-
super(`${errors[0].path ? errors[0].path + ": " : ""}${errors[0].message}`), _define_property(this, "errors", void 0), _define_property(this, "name", void 0), this.errors = errors, this.name = "Validation Error";
|
|
1198
|
-
}
|
|
1199
|
-
};
|
|
1200
|
-
|
|
1201
|
-
//#endregion
|
|
1202
|
-
//#region packages/typescript/src/runtime/annotated-type.ts
|
|
1203
|
-
const COMPLEX_KINDS = new Set([
|
|
1204
|
-
"union",
|
|
1205
|
-
"intersection",
|
|
1206
|
-
"tuple"
|
|
1207
|
-
]);
|
|
1208
|
-
const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
|
|
1209
|
-
/** Shared validator method reused by all annotated type nodes. */ function validatorMethod(opts) {
|
|
1210
|
-
return new Validator(this, opts);
|
|
1211
|
-
}
|
|
1212
|
-
/**
|
|
1213
|
-
* Creates a minimal annotated type node from a type def and metadata map.
|
|
1214
|
-
* Centralises the shape so callers never duplicate the boilerplate.
|
|
1215
|
-
*/ function createAnnotatedTypeNode(type, metadata, opts) {
|
|
1216
|
-
return {
|
|
1217
|
-
__is_atscript_annotated_type: true,
|
|
1218
|
-
type,
|
|
1219
|
-
metadata,
|
|
1220
|
-
validator: validatorMethod,
|
|
1221
|
-
id: opts?.id,
|
|
1222
|
-
optional: opts?.optional,
|
|
1223
|
-
ref: opts?.ref
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
/**
|
|
1227
|
-
* Type Guard to check if a type is atscript-annotated
|
|
1228
|
-
*/ function isAnnotatedType(type) {
|
|
1229
|
-
return type && type.__is_atscript_annotated_type;
|
|
1230
|
-
}
|
|
1231
|
-
/**
|
|
1232
|
-
* Standalone annotate function that handles both replace and append (array) strategies.
|
|
1233
|
-
* Used by the handle's .annotate() method and by generated mutation statements.
|
|
1234
|
-
*/ function annotate(metadata, key, value, asArray) {
|
|
1235
|
-
if (!metadata) return;
|
|
1236
|
-
if (asArray) if (metadata.has(key)) {
|
|
1237
|
-
const a = metadata.get(key);
|
|
1238
|
-
if (Array.isArray(a)) a.push(value);
|
|
1239
|
-
else metadata.set(key, [a, value]);
|
|
1240
|
-
} else metadata.set(key, [value]);
|
|
1241
|
-
else metadata.set(key, value);
|
|
1242
|
-
}
|
|
1243
|
-
/**
|
|
1244
|
-
* Clones a property's type tree in-place so mutations don't leak to shared refs.
|
|
1245
|
-
* Used by mutating annotate codegen when paths cross ref boundaries.
|
|
1246
|
-
*/ function cloneRefProp(parentType, propName) {
|
|
1247
|
-
if (parentType.kind !== "object") return;
|
|
1248
|
-
const objType = parentType;
|
|
1249
|
-
const existing = objType.props.get(propName);
|
|
1250
|
-
if (!existing) return;
|
|
1251
|
-
const clonedType = cloneTypeDef(existing.type);
|
|
1252
|
-
objType.props.set(propName, createAnnotatedTypeNode(clonedType, new Map(existing.metadata), {
|
|
1253
|
-
id: existing.id,
|
|
1254
|
-
optional: existing.optional,
|
|
1255
|
-
ref: existing.ref
|
|
1256
|
-
}));
|
|
1257
|
-
}
|
|
1258
|
-
function cloneTypeDef(type) {
|
|
1259
|
-
if (type.kind === "object") {
|
|
1260
|
-
const obj = type;
|
|
1261
|
-
const props = /* @__PURE__ */ new Map();
|
|
1262
|
-
for (const [k, v] of obj.props) props.set(k, createAnnotatedTypeNode(v.type, new Map(v.metadata), {
|
|
1263
|
-
id: v.id,
|
|
1264
|
-
optional: v.optional,
|
|
1265
|
-
ref: v.ref
|
|
1266
|
-
}));
|
|
1267
|
-
return {
|
|
1268
|
-
kind: "object",
|
|
1269
|
-
props,
|
|
1270
|
-
propsPatterns: [...obj.propsPatterns],
|
|
1271
|
-
tags: new Set(obj.tags)
|
|
1272
|
-
};
|
|
1273
|
-
}
|
|
1274
|
-
if (type.kind === "array") {
|
|
1275
|
-
const arr = type;
|
|
1276
|
-
return {
|
|
1277
|
-
kind: "array",
|
|
1278
|
-
of: arr.of,
|
|
1279
|
-
tags: new Set(arr.tags)
|
|
1280
|
-
};
|
|
1281
|
-
}
|
|
1282
|
-
if (type.kind === "union" || type.kind === "intersection" || type.kind === "tuple") {
|
|
1283
|
-
const complex = type;
|
|
1284
|
-
return {
|
|
1285
|
-
kind: type.kind,
|
|
1286
|
-
items: [...complex.items],
|
|
1287
|
-
tags: new Set(complex.tags)
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
return {
|
|
1291
|
-
...type,
|
|
1292
|
-
tags: new Set(type.tags)
|
|
1293
|
-
};
|
|
1294
|
-
}
|
|
1295
|
-
/**
|
|
1296
|
-
* Creates a builder handle for constructing a {@link TAtscriptAnnotatedType} at runtime.
|
|
1297
|
-
*
|
|
1298
|
-
* This is primarily used by generated `.as.js` code. The returned handle provides
|
|
1299
|
-
* a fluent API for setting the type definition, metadata, and properties.
|
|
1300
|
-
*
|
|
1301
|
-
* @example
|
|
1302
|
-
* ```ts
|
|
1303
|
-
* const handle = defineAnnotatedType('object')
|
|
1304
|
-
* .prop('name', defineAnnotatedType().designType('string').$type)
|
|
1305
|
-
* .prop('age', defineAnnotatedType().designType('number').$type)
|
|
1306
|
-
*
|
|
1307
|
-
* handle.$type // the resulting TAtscriptAnnotatedType
|
|
1308
|
-
* ```
|
|
1309
|
-
*
|
|
1310
|
-
* @param _kind - The kind of type to create (e.g. `'object'`, `'array'`, `'union'`). Defaults to `''` (primitive/final).
|
|
1311
|
-
* @param base - Optional existing object to augment with annotated type fields.
|
|
1312
|
-
* @returns A builder handle for fluent type construction.
|
|
1313
|
-
*/ function defineAnnotatedType(_kind, base) {
|
|
1314
|
-
const kind = _kind || "";
|
|
1315
|
-
const baseProvided = base !== void 0;
|
|
1316
|
-
const type = base?.type || {};
|
|
1317
|
-
type.kind = kind;
|
|
1318
|
-
if (COMPLEX_KINDS.has(kind)) type.items = [];
|
|
1319
|
-
if (kind === "object") {
|
|
1320
|
-
type.props = /* @__PURE__ */ new Map();
|
|
1321
|
-
type.propsPatterns = [];
|
|
1322
|
-
}
|
|
1323
|
-
type.tags = /* @__PURE__ */ new Set();
|
|
1324
|
-
const metadata = base?.metadata || /* @__PURE__ */ new Map();
|
|
1325
|
-
const payload = {
|
|
1326
|
-
__is_atscript_annotated_type: true,
|
|
1327
|
-
metadata,
|
|
1328
|
-
type,
|
|
1329
|
-
validator: validatorMethod
|
|
1330
|
-
};
|
|
1331
|
-
base = base ? Object.assign(base, payload) : payload;
|
|
1332
|
-
return {
|
|
1333
|
-
$type: base,
|
|
1334
|
-
$def: type,
|
|
1335
|
-
$metadata: metadata,
|
|
1336
|
-
tags(...tags) {
|
|
1337
|
-
for (const tag of tags) this.$def.tags.add(tag);
|
|
1338
|
-
return this;
|
|
1339
|
-
},
|
|
1340
|
-
designType(value) {
|
|
1341
|
-
this.$def.designType = value;
|
|
1342
|
-
return this;
|
|
1343
|
-
},
|
|
1344
|
-
value(value) {
|
|
1345
|
-
this.$def.value = value;
|
|
1346
|
-
return this;
|
|
1347
|
-
},
|
|
1348
|
-
of(value) {
|
|
1349
|
-
this.$def.of = value;
|
|
1350
|
-
return this;
|
|
1351
|
-
},
|
|
1352
|
-
item(value) {
|
|
1353
|
-
this.$def.items.push(value);
|
|
1354
|
-
return this;
|
|
1355
|
-
},
|
|
1356
|
-
prop(name, value) {
|
|
1357
|
-
this.$def.props.set(name, value);
|
|
1358
|
-
return this;
|
|
1359
|
-
},
|
|
1360
|
-
propPattern(pattern, def) {
|
|
1361
|
-
this.$def.propsPatterns.push({
|
|
1362
|
-
pattern,
|
|
1363
|
-
def
|
|
1364
|
-
});
|
|
1365
|
-
return this;
|
|
1366
|
-
},
|
|
1367
|
-
optional(value = true) {
|
|
1368
|
-
this.$type.optional = value;
|
|
1369
|
-
return this;
|
|
1370
|
-
},
|
|
1371
|
-
copyMetadata(fromMetadata, ignore) {
|
|
1372
|
-
for (const [key, value] of fromMetadata.entries()) if (!ignore || !ignore.has(key)) this.$metadata.set(key, value);
|
|
1373
|
-
return this;
|
|
1374
|
-
},
|
|
1375
|
-
refTo(type, chain) {
|
|
1376
|
-
const node = this.$type;
|
|
1377
|
-
const field = chain ? chain.join(".") : "";
|
|
1378
|
-
if (isAnnotatedType(type)) {
|
|
1379
|
-
let newBase = type;
|
|
1380
|
-
const typeName = type.name || "Unknown";
|
|
1381
|
-
if (chain) for (let i = 0; i < chain.length; i++) {
|
|
1382
|
-
const c = chain[i];
|
|
1383
|
-
if (newBase.type.kind === "object" && newBase.type.props.has(c)) newBase = newBase.type.props.get(c);
|
|
1384
|
-
else {
|
|
1385
|
-
const keys = chain.slice(0, i + 1).map((k) => `["${k}"]`).join("");
|
|
1386
|
-
throw new Error(`Can't find prop ${typeName}${keys}`);
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
node.type = baseProvided ? cloneTypeDef(newBase.type) : newBase.type;
|
|
1390
|
-
node.id = node.id ?? newBase.id;
|
|
1391
|
-
node.ref = {
|
|
1392
|
-
type: () => type,
|
|
1393
|
-
field
|
|
1394
|
-
};
|
|
1395
|
-
} else if (typeof type === "function") {
|
|
1396
|
-
const lazyType = type;
|
|
1397
|
-
const ownId = node.id;
|
|
1398
|
-
node.ref = {
|
|
1399
|
-
type: lazyType,
|
|
1400
|
-
field
|
|
1401
|
-
};
|
|
1402
|
-
const placeholder = node.type;
|
|
1403
|
-
Object.defineProperty(node, "type", {
|
|
1404
|
-
get() {
|
|
1405
|
-
const t = lazyType();
|
|
1406
|
-
if (!isAnnotatedType(t)) {
|
|
1407
|
-
Object.defineProperty(node, "type", {
|
|
1408
|
-
value: placeholder,
|
|
1409
|
-
writable: false,
|
|
1410
|
-
configurable: true
|
|
1411
|
-
});
|
|
1412
|
-
return placeholder;
|
|
1413
|
-
}
|
|
1414
|
-
let target = t;
|
|
1415
|
-
if (chain) for (const c of chain) if (target.type.kind === "object" && target.type.props.has(c)) target = target.type.props.get(c);
|
|
1416
|
-
else return t.type;
|
|
1417
|
-
node.id = ownId ?? target.id;
|
|
1418
|
-
const resolved = baseProvided ? cloneTypeDef(target.type) : target.type;
|
|
1419
|
-
Object.defineProperty(node, "type", {
|
|
1420
|
-
value: resolved,
|
|
1421
|
-
writable: false,
|
|
1422
|
-
configurable: true
|
|
1423
|
-
});
|
|
1424
|
-
return resolved;
|
|
1425
|
-
},
|
|
1426
|
-
configurable: true
|
|
1427
|
-
});
|
|
1428
|
-
} else throw new TypeError(`${type} is not annotated type`);
|
|
1429
|
-
return this;
|
|
1430
|
-
},
|
|
1431
|
-
annotate(key, value, asArray) {
|
|
1432
|
-
annotate(this.$metadata, key, value, asArray);
|
|
1433
|
-
return this;
|
|
1434
|
-
},
|
|
1435
|
-
id(value) {
|
|
1436
|
-
this.$type.id = value;
|
|
1437
|
-
return this;
|
|
1438
|
-
}
|
|
1439
|
-
};
|
|
1440
|
-
}
|
|
1441
|
-
/**
|
|
1442
|
-
* Checks whether an annotated type is a phantom type.
|
|
1443
|
-
*
|
|
1444
|
-
* Phantom types do not affect the data type, validation, or schema,
|
|
1445
|
-
* but are discoverable via runtime type traversal.
|
|
1446
|
-
*/ function isPhantomType(def) {
|
|
1447
|
-
return def.type.kind === "" && def.type.designType === "phantom";
|
|
1448
|
-
}
|
|
1449
|
-
/**
|
|
1450
|
-
* Checks whether an annotated type resolves to a primitive (non-object, non-array) shape.
|
|
1451
|
-
*
|
|
1452
|
-
* Returns `true` for final types and for unions/intersections/tuples
|
|
1453
|
-
* whose members are all primitives.
|
|
1454
|
-
*/ function isAnnotatedTypeOfPrimitive(t) {
|
|
1455
|
-
if (NON_PRIMITIVE_KINDS.has(t.type.kind)) return false;
|
|
1456
|
-
if (!t.type.kind) return true;
|
|
1457
|
-
if (COMPLEX_KINDS.has(t.type.kind)) {
|
|
1458
|
-
for (const item of t.type.items) if (!isAnnotatedTypeOfPrimitive(item)) return false;
|
|
1459
|
-
return true;
|
|
1460
|
-
}
|
|
1461
|
-
return false;
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
//#endregion
|
|
1465
|
-
//#region packages/typescript/src/runtime/traverse.ts
|
|
1466
|
-
/**
|
|
1467
|
-
* Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
|
|
1468
|
-
*
|
|
1469
|
-
* Provides the common `switch (def.type.kind)` pattern used by
|
|
1470
|
-
* the validator, JSON-schema builder, and serializer.
|
|
1471
|
-
* Each caller supplies its own handlers that control recursion.
|
|
1472
|
-
*
|
|
1473
|
-
* When a `phantom` handler is provided, phantom types (`designType === 'phantom'`)
|
|
1474
|
-
* are dispatched to it instead of `final`. This allows consumers to skip or
|
|
1475
|
-
* handle phantom props without polluting their `final` handler.
|
|
1476
|
-
*/ function forAnnotatedType(def, handlers) {
|
|
1477
|
-
switch (def.type.kind) {
|
|
1478
|
-
case "": {
|
|
1479
|
-
const typed = def;
|
|
1480
|
-
if (handlers.phantom && typed.type.designType === "phantom") return handlers.phantom(typed);
|
|
1481
|
-
return handlers.final(typed);
|
|
1482
|
-
}
|
|
1483
|
-
case "object": return handlers.object(def);
|
|
1484
|
-
case "array": return handlers.array(def);
|
|
1485
|
-
case "union": return handlers.union(def);
|
|
1486
|
-
case "intersection": return handlers.intersection(def);
|
|
1487
|
-
case "tuple": return handlers.tuple(def);
|
|
1488
|
-
default: throw new Error(`Unknown type kind "${def.type.kind}"`);
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
//#endregion
|
|
1493
|
-
//#region packages/typescript/src/runtime/json-schema.ts
|
|
1494
|
-
/**
|
|
1495
|
-
* Detects a discriminator property across union items.
|
|
1496
|
-
*
|
|
1497
|
-
* Scans all items for object-typed members that share a common property
|
|
1498
|
-
* with distinct const/literal values. If exactly one such property exists,
|
|
1499
|
-
* it is returned as the discriminator. Returns `null` when no qualifying
|
|
1500
|
-
* property exists, or when more than one does (ambiguous).
|
|
1501
|
-
*/ function detectDiscriminator(items) {
|
|
1502
|
-
if (items.length < 2) return null;
|
|
1503
|
-
for (const item of items) if (item.type.kind !== "object") return null;
|
|
1504
|
-
const firstObj = items[0].type;
|
|
1505
|
-
const candidates = [];
|
|
1506
|
-
for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
|
|
1507
|
-
let result = null;
|
|
1508
|
-
for (const candidate of candidates) {
|
|
1509
|
-
const values = /* @__PURE__ */ new Set();
|
|
1510
|
-
const indexMapping = {};
|
|
1511
|
-
let valid = true;
|
|
1512
|
-
for (let i = 0; i < items.length; i++) {
|
|
1513
|
-
const prop = items[i].type.props.get(candidate);
|
|
1514
|
-
if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
|
|
1515
|
-
valid = false;
|
|
1516
|
-
break;
|
|
1517
|
-
}
|
|
1518
|
-
const val = prop.type.value;
|
|
1519
|
-
if (values.has(val)) {
|
|
1520
|
-
valid = false;
|
|
1521
|
-
break;
|
|
1522
|
-
}
|
|
1523
|
-
values.add(val);
|
|
1524
|
-
indexMapping[String(val)] = i;
|
|
1525
|
-
}
|
|
1526
|
-
if (valid) {
|
|
1527
|
-
if (result) return null;
|
|
1528
|
-
result = {
|
|
1529
|
-
propertyName: candidate,
|
|
1530
|
-
indexMapping
|
|
1531
|
-
};
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
|
-
return result;
|
|
1535
|
-
}
|
|
1536
|
-
/**
|
|
1537
|
-
* Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
|
|
1538
|
-
*
|
|
1539
|
-
* Translates the atscript type structure and validation metadata
|
|
1540
|
-
* (min/max, patterns, integer constraints, etc.) into a standard JSON Schema.
|
|
1541
|
-
*
|
|
1542
|
-
* @example
|
|
1543
|
-
* ```ts
|
|
1544
|
-
* import { buildJsonSchema } from '@atscript/typescript'
|
|
1545
|
-
*
|
|
1546
|
-
* const schema = buildJsonSchema(MyInterface)
|
|
1547
|
-
* // { type: 'object', properties: { ... }, required: [...] }
|
|
1548
|
-
* ```
|
|
1549
|
-
*
|
|
1550
|
-
* @param type - The annotated type to convert.
|
|
1551
|
-
* @returns A JSON Schema object.
|
|
1552
|
-
*/ function buildJsonSchema(type) {
|
|
1553
|
-
const defs = {};
|
|
1554
|
-
let hasDefs = false;
|
|
1555
|
-
const buildObject = (d) => {
|
|
1556
|
-
const properties = {};
|
|
1557
|
-
const required = [];
|
|
1558
|
-
for (const [key, val] of d.type.props.entries()) {
|
|
1559
|
-
if (isPhantomType(val)) continue;
|
|
1560
|
-
properties[key] = build(val);
|
|
1561
|
-
if (!val.optional) required.push(key);
|
|
1562
|
-
}
|
|
1563
|
-
const schema = {
|
|
1564
|
-
type: "object",
|
|
1565
|
-
properties
|
|
1566
|
-
};
|
|
1567
|
-
if (required.length > 0) schema.required = required;
|
|
1568
|
-
return schema;
|
|
1569
|
-
};
|
|
1570
|
-
const build = (def) => {
|
|
1571
|
-
if (def.id && def.type.kind === "object" && def !== type) {
|
|
1572
|
-
const name = def.id;
|
|
1573
|
-
if (!defs[name]) {
|
|
1574
|
-
hasDefs = true;
|
|
1575
|
-
defs[name] = {};
|
|
1576
|
-
defs[name] = buildObject(def);
|
|
1577
|
-
}
|
|
1578
|
-
return { $ref: `#/$defs/${name}` };
|
|
1579
|
-
}
|
|
1580
|
-
const meta = def.metadata;
|
|
1581
|
-
return forAnnotatedType(def, {
|
|
1582
|
-
phantom() {
|
|
1583
|
-
return {};
|
|
1584
|
-
},
|
|
1585
|
-
object(d) {
|
|
1586
|
-
return buildObject(d);
|
|
1587
|
-
},
|
|
1588
|
-
array(d) {
|
|
1589
|
-
const schema = {
|
|
1590
|
-
type: "array",
|
|
1591
|
-
items: build(d.type.of)
|
|
1592
|
-
};
|
|
1593
|
-
applyArrayConstraints(schema, meta);
|
|
1594
|
-
return schema;
|
|
1595
|
-
},
|
|
1596
|
-
union(d) {
|
|
1597
|
-
const disc = detectDiscriminator(d.type.items);
|
|
1598
|
-
if (disc) {
|
|
1599
|
-
const oneOf = d.type.items.map(build);
|
|
1600
|
-
const mapping = {};
|
|
1601
|
-
for (const [val, idx] of Object.entries(disc.indexMapping)) {
|
|
1602
|
-
const item = d.type.items[idx];
|
|
1603
|
-
mapping[val] = item.id && defs[item.id] ? `#/$defs/${item.id}` : `#/oneOf/${idx}`;
|
|
1604
|
-
}
|
|
1605
|
-
return {
|
|
1606
|
-
oneOf,
|
|
1607
|
-
discriminator: {
|
|
1608
|
-
propertyName: disc.propertyName,
|
|
1609
|
-
mapping
|
|
1610
|
-
}
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
const anyOf = d.type.items.map(build);
|
|
1614
|
-
if (meta.size > 0) applyUnionConstraints(anyOf, meta);
|
|
1615
|
-
return { anyOf };
|
|
1616
|
-
},
|
|
1617
|
-
intersection(d) {
|
|
1618
|
-
return { allOf: d.type.items.map(build) };
|
|
1619
|
-
},
|
|
1620
|
-
tuple(d) {
|
|
1621
|
-
return {
|
|
1622
|
-
type: "array",
|
|
1623
|
-
items: d.type.items.map(build),
|
|
1624
|
-
additionalItems: false
|
|
1625
|
-
};
|
|
1626
|
-
},
|
|
1627
|
-
final(d) {
|
|
1628
|
-
const schema = {};
|
|
1629
|
-
if (d.type.value !== void 0) schema.const = d.type.value;
|
|
1630
|
-
if (d.type.designType && d.type.designType !== "any") {
|
|
1631
|
-
const dt = d.type.designType;
|
|
1632
|
-
schema.type = dt === "undefined" ? "null" : dt === "decimal" ? "string" : dt;
|
|
1633
|
-
}
|
|
1634
|
-
applyScalarConstraints(schema, meta);
|
|
1635
|
-
return schema;
|
|
1636
|
-
}
|
|
1637
|
-
});
|
|
1638
|
-
};
|
|
1639
|
-
const schema = build(type);
|
|
1640
|
-
if (hasDefs) return {
|
|
1641
|
-
...schema,
|
|
1642
|
-
$defs: defs
|
|
1643
|
-
};
|
|
1644
|
-
return schema;
|
|
1645
|
-
}
|
|
1646
|
-
/** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
|
|
1647
|
-
const minLength = meta.get("expect.minLength");
|
|
1648
|
-
if (minLength !== void 0) schema.minItems = typeof minLength === "number" ? minLength : minLength.length;
|
|
1649
|
-
const maxLength = meta.get("expect.maxLength");
|
|
1650
|
-
if (maxLength !== void 0) schema.maxItems = typeof maxLength === "number" ? maxLength : maxLength.length;
|
|
1651
|
-
}
|
|
1652
|
-
/** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
|
|
1653
|
-
if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
|
|
1654
|
-
if (schema.type === "string") {
|
|
1655
|
-
if (meta.get("meta.required")) schema.minLength = 1;
|
|
1656
|
-
const minLength = meta.get("expect.minLength");
|
|
1657
|
-
if (minLength !== void 0) schema.minLength = typeof minLength === "number" ? minLength : minLength.length;
|
|
1658
|
-
const maxLength = meta.get("expect.maxLength");
|
|
1659
|
-
if (maxLength !== void 0) schema.maxLength = typeof maxLength === "number" ? maxLength : maxLength.length;
|
|
1660
|
-
const patterns = meta.get("expect.pattern");
|
|
1661
|
-
if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
|
|
1662
|
-
else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
|
|
1663
|
-
}
|
|
1664
|
-
if (schema.type === "number" || schema.type === "integer") {
|
|
1665
|
-
const min = meta.get("expect.min");
|
|
1666
|
-
if (min !== void 0) schema.minimum = boundOf(min, "minValue");
|
|
1667
|
-
const max = meta.get("expect.max");
|
|
1668
|
-
if (max !== void 0) schema.maximum = boundOf(max, "maxValue");
|
|
1669
|
-
const exMin = meta.get("expect.exclusiveMin");
|
|
1670
|
-
if (exMin !== void 0) schema.exclusiveMinimum = boundOf(exMin, "exclusiveMinValue");
|
|
1671
|
-
const exMax = meta.get("expect.exclusiveMax");
|
|
1672
|
-
if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
|
|
1673
|
-
}
|
|
1674
|
-
}
|
|
1675
|
-
/** A number-bound annotation's value: the bare number, or its `field` in the object form. */ function boundOf(m, field) {
|
|
1676
|
-
return typeof m === "number" ? m : m[field];
|
|
1677
|
-
}
|
|
1678
|
-
const LOWER_BOUNDS = new Set([
|
|
1679
|
-
"minimum",
|
|
1680
|
-
"exclusiveMinimum",
|
|
1681
|
-
"minLength",
|
|
1682
|
-
"minItems"
|
|
1683
|
-
]);
|
|
1684
|
-
const UPPER_BOUNDS = new Set([
|
|
1685
|
-
"maximum",
|
|
1686
|
-
"exclusiveMaximum",
|
|
1687
|
-
"maxLength",
|
|
1688
|
-
"maxItems"
|
|
1689
|
-
]);
|
|
1690
|
-
/**
|
|
1691
|
-
* Puts union-level constraints onto the matching `anyOf` members (numbers, strings,
|
|
1692
|
-
* arrays; nested `anyOf` members recursively). When a member already has the same
|
|
1693
|
-
* bound, the stricter one wins; patterns accumulate.
|
|
1694
|
-
*/ function applyUnionConstraints(members, meta) {
|
|
1695
|
-
for (const member of members) {
|
|
1696
|
-
if (Array.isArray(member.anyOf)) {
|
|
1697
|
-
applyUnionConstraints(member.anyOf, meta);
|
|
1698
|
-
continue;
|
|
1699
|
-
}
|
|
1700
|
-
if (member.const !== void 0) continue;
|
|
1701
|
-
const type = member.type;
|
|
1702
|
-
const extra = { type };
|
|
1703
|
-
if (type === "array") applyArrayConstraints(extra, meta);
|
|
1704
|
-
else if (type === "string" || type === "number" || type === "integer") applyScalarConstraints(extra, meta);
|
|
1705
|
-
else continue;
|
|
1706
|
-
if (extra.type === "integer") member.type = "integer";
|
|
1707
|
-
for (const [key, value] of Object.entries(extra)) {
|
|
1708
|
-
if (key === "type") continue;
|
|
1709
|
-
if (key === "pattern" || key === "allOf") {
|
|
1710
|
-
const patterns = key === "pattern" ? [{ pattern: value }] : value;
|
|
1711
|
-
if (member.pattern === void 0 && key === "pattern" && !member.allOf) member.pattern = value;
|
|
1712
|
-
else member.allOf = (member.allOf || []).concat(patterns);
|
|
1713
|
-
} else if (member[key] === void 0) member[key] = value;
|
|
1714
|
-
else if (LOWER_BOUNDS.has(key)) member[key] = Math.max(member[key], value);
|
|
1715
|
-
else if (UPPER_BOUNDS.has(key)) member[key] = Math.min(member[key], value);
|
|
1716
|
-
}
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
/**
|
|
1720
|
-
* Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
|
|
1721
|
-
*
|
|
1722
|
-
* This is the inverse of {@link buildJsonSchema}. A round-trip
|
|
1723
|
-
* `buildJsonSchema(fromJsonSchema(schema))` preserves structure and constraints.
|
|
1724
|
-
*
|
|
1725
|
-
* Supports the JSON Schema subset produced by `buildJsonSchema` plus
|
|
1726
|
-
* common extensions like `oneOf` (treated as union) and `enum` (union of literals).
|
|
1727
|
-
*
|
|
1728
|
-
* @example
|
|
1729
|
-
* ```ts
|
|
1730
|
-
* import { fromJsonSchema } from '@atscript/typescript'
|
|
1731
|
-
*
|
|
1732
|
-
* const type = fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } }, required: ['name'] })
|
|
1733
|
-
* type.validator().validate({ name: 'Alice' }) // passes
|
|
1734
|
-
* ```
|
|
1735
|
-
*
|
|
1736
|
-
* @param schema - A JSON Schema object.
|
|
1737
|
-
* @returns An annotated type with full validator support.
|
|
1738
|
-
*/ function fromJsonSchema(schema) {
|
|
1739
|
-
const defsSource = schema.$defs || schema.definitions || {};
|
|
1740
|
-
const resolved = /* @__PURE__ */ new Map();
|
|
1741
|
-
const convert = (s) => {
|
|
1742
|
-
if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
|
|
1743
|
-
if (s.$ref) {
|
|
1744
|
-
const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
|
|
1745
|
-
if (resolved.has(refName)) return resolved.get(refName);
|
|
1746
|
-
if (defsSource[refName]) {
|
|
1747
|
-
const placeholder = defineAnnotatedType().designType("any").$type;
|
|
1748
|
-
resolved.set(refName, placeholder);
|
|
1749
|
-
const type = convert(defsSource[refName]);
|
|
1750
|
-
resolved.set(refName, type);
|
|
1751
|
-
return type;
|
|
1752
|
-
}
|
|
1753
|
-
throw new Error(`Unresolvable $ref: ${s.$ref}`);
|
|
1754
|
-
}
|
|
1755
|
-
if ("const" in s) {
|
|
1756
|
-
const val = s.const;
|
|
1757
|
-
const dt = val === null ? "null" : typeof val;
|
|
1758
|
-
return defineAnnotatedType().designType(dt).value(val).$type;
|
|
1759
|
-
}
|
|
1760
|
-
if (s.enum) {
|
|
1761
|
-
const handle = defineAnnotatedType("union");
|
|
1762
|
-
for (const val of s.enum) {
|
|
1763
|
-
const dt = val === null ? "null" : typeof val;
|
|
1764
|
-
handle.item(defineAnnotatedType().designType(dt).value(val).$type);
|
|
1765
|
-
}
|
|
1766
|
-
return handle.$type;
|
|
1767
|
-
}
|
|
1768
|
-
if (s.anyOf) {
|
|
1769
|
-
const handle = defineAnnotatedType("union");
|
|
1770
|
-
for (const item of s.anyOf) handle.item(convert(item));
|
|
1771
|
-
return handle.$type;
|
|
1772
|
-
}
|
|
1773
|
-
if (s.oneOf) {
|
|
1774
|
-
const handle = defineAnnotatedType("union");
|
|
1775
|
-
for (const item of s.oneOf) handle.item(convert(item));
|
|
1776
|
-
return handle.$type;
|
|
1777
|
-
}
|
|
1778
|
-
if (s.allOf && !s.type) {
|
|
1779
|
-
const handle = defineAnnotatedType("intersection");
|
|
1780
|
-
for (const item of s.allOf) handle.item(convert(item));
|
|
1781
|
-
return handle.$type;
|
|
1782
|
-
}
|
|
1783
|
-
if (Array.isArray(s.type)) {
|
|
1784
|
-
const handle = defineAnnotatedType("union");
|
|
1785
|
-
for (const t of s.type) handle.item(convert({
|
|
1786
|
-
...s,
|
|
1787
|
-
type: t
|
|
1788
|
-
}));
|
|
1789
|
-
return handle.$type;
|
|
1790
|
-
}
|
|
1791
|
-
if (s.type === "object") {
|
|
1792
|
-
const handle = defineAnnotatedType("object");
|
|
1793
|
-
const required = new Set(s.required || []);
|
|
1794
|
-
if (s.properties) for (const [key, propSchema] of Object.entries(s.properties)) {
|
|
1795
|
-
const propType = convert(propSchema);
|
|
1796
|
-
if (!required.has(key)) propType.optional = true;
|
|
1797
|
-
handle.prop(key, propType);
|
|
1798
|
-
}
|
|
1799
|
-
return handle.$type;
|
|
1800
|
-
}
|
|
1801
|
-
if (s.type === "array") {
|
|
1802
|
-
if (Array.isArray(s.items)) {
|
|
1803
|
-
const handle = defineAnnotatedType("tuple");
|
|
1804
|
-
for (const item of s.items) handle.item(convert(item));
|
|
1805
|
-
return handle.$type;
|
|
1806
|
-
}
|
|
1807
|
-
const itemType = s.items ? convert(s.items) : defineAnnotatedType().designType("any").$type;
|
|
1808
|
-
const handle = defineAnnotatedType("array").of(itemType);
|
|
1809
|
-
if (typeof s.minItems === "number") handle.annotate("expect.minLength", { length: s.minItems });
|
|
1810
|
-
if (typeof s.maxItems === "number") handle.annotate("expect.maxLength", { length: s.maxItems });
|
|
1811
|
-
return handle.$type;
|
|
1812
|
-
}
|
|
1813
|
-
if (s.type === "string") {
|
|
1814
|
-
const handle = defineAnnotatedType().designType("string").tags("string");
|
|
1815
|
-
if (typeof s.minLength === "number") handle.annotate("expect.minLength", { length: s.minLength });
|
|
1816
|
-
if (typeof s.maxLength === "number") handle.annotate("expect.maxLength", { length: s.maxLength });
|
|
1817
|
-
if (s.pattern) handle.annotate("expect.pattern", { pattern: s.pattern }, true);
|
|
1818
|
-
if (s.allOf) {
|
|
1819
|
-
for (const item of s.allOf) if (item.pattern) handle.annotate("expect.pattern", { pattern: item.pattern }, true);
|
|
1820
|
-
}
|
|
1821
|
-
return handle.$type;
|
|
1822
|
-
}
|
|
1823
|
-
if (s.type === "integer") {
|
|
1824
|
-
const handle = defineAnnotatedType().designType("number").tags("number");
|
|
1825
|
-
handle.annotate("expect.int", true);
|
|
1826
|
-
annotateNumberBounds(handle, s);
|
|
1827
|
-
return handle.$type;
|
|
1828
|
-
}
|
|
1829
|
-
if (s.type === "number") {
|
|
1830
|
-
const handle = defineAnnotatedType().designType("number").tags("number");
|
|
1831
|
-
annotateNumberBounds(handle, s);
|
|
1832
|
-
return handle.$type;
|
|
1833
|
-
}
|
|
1834
|
-
if (s.type === "boolean") return defineAnnotatedType().designType("boolean").tags("boolean").$type;
|
|
1835
|
-
if (s.type === "null") return defineAnnotatedType().designType("null").tags("null").$type;
|
|
1836
|
-
return defineAnnotatedType().designType("any").$type;
|
|
1837
|
-
};
|
|
1838
|
-
return convert(schema);
|
|
1839
|
-
}
|
|
1840
|
-
/**
|
|
1841
|
-
* Maps `minimum` / `maximum` / `exclusiveMinimum` / `exclusiveMaximum` onto
|
|
1842
|
-
* `@expect.min` / `max` / `exclusiveMin` / `exclusiveMax`. Also reads the draft-4 form,
|
|
1843
|
-
* where `exclusiveMinimum: true` makes `minimum` exclusive.
|
|
1844
|
-
*/ function annotateNumberBounds(handle, s) {
|
|
1845
|
-
if (typeof s.minimum === "number") if (s.exclusiveMinimum === true) handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.minimum });
|
|
1846
|
-
else handle.annotate("expect.min", { minValue: s.minimum });
|
|
1847
|
-
if (typeof s.maximum === "number") if (s.exclusiveMaximum === true) handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.maximum });
|
|
1848
|
-
else handle.annotate("expect.max", { maxValue: s.maximum });
|
|
1849
|
-
if (typeof s.exclusiveMinimum === "number") handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.exclusiveMinimum });
|
|
1850
|
-
if (typeof s.exclusiveMaximum === "number") handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.exclusiveMaximum });
|
|
1851
|
-
}
|
|
1852
|
-
/**
|
|
1853
|
-
* Merges multiple annotated types into a combined schema map with shared `$defs`.
|
|
1854
|
-
*
|
|
1855
|
-
* Each type must have an `id`. The returned `schemas` object contains individual
|
|
1856
|
-
* schemas keyed by type id, and `$defs` contains all shared type definitions
|
|
1857
|
-
* deduplicated across schemas.
|
|
1858
|
-
*
|
|
1859
|
-
* @param types - Array of annotated types, each with an `id`.
|
|
1860
|
-
* @returns An object with `schemas` (keyed by id) and shared `$defs`.
|
|
1861
|
-
*/ function mergeJsonSchemas(types) {
|
|
1862
|
-
const mergedDefs = {};
|
|
1863
|
-
const schemas = {};
|
|
1864
|
-
for (const type of types) {
|
|
1865
|
-
const name = type.id;
|
|
1866
|
-
if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
|
|
1867
|
-
const schema = buildJsonSchema(type);
|
|
1868
|
-
if (schema.$defs) {
|
|
1869
|
-
for (const [defName, defSchema] of Object.entries(schema.$defs)) if (!mergedDefs[defName]) mergedDefs[defName] = defSchema;
|
|
1870
|
-
const { $defs: _, ...rest } = schema;
|
|
1871
|
-
schemas[name] = rest;
|
|
1872
|
-
} else schemas[name] = schema;
|
|
1873
|
-
}
|
|
1874
|
-
return {
|
|
1875
|
-
schemas,
|
|
1876
|
-
$defs: mergedDefs
|
|
1877
|
-
};
|
|
1878
|
-
}
|
|
1879
|
-
|
|
1880
|
-
//#endregion
|
|
1881
|
-
Object.defineProperty(exports, 'Validator', {
|
|
1882
|
-
enumerable: true,
|
|
1883
|
-
get: function () {
|
|
1884
|
-
return Validator;
|
|
1885
|
-
}
|
|
1886
|
-
});
|
|
1887
|
-
Object.defineProperty(exports, 'ValidatorError', {
|
|
1888
|
-
enumerable: true,
|
|
1889
|
-
get: function () {
|
|
1890
|
-
return ValidatorError;
|
|
1891
|
-
}
|
|
1892
|
-
});
|
|
1893
|
-
Object.defineProperty(exports, 'annotate', {
|
|
1894
|
-
enumerable: true,
|
|
1895
|
-
get: function () {
|
|
1896
|
-
return annotate;
|
|
1897
|
-
}
|
|
1898
|
-
});
|
|
1899
|
-
Object.defineProperty(exports, 'buildJsonSchema', {
|
|
1900
|
-
enumerable: true,
|
|
1901
|
-
get: function () {
|
|
1902
|
-
return buildJsonSchema;
|
|
1903
|
-
}
|
|
1904
|
-
});
|
|
1905
|
-
Object.defineProperty(exports, 'cloneRefProp', {
|
|
1906
|
-
enumerable: true,
|
|
1907
|
-
get: function () {
|
|
1908
|
-
return cloneRefProp;
|
|
1909
|
-
}
|
|
1910
|
-
});
|
|
1911
|
-
Object.defineProperty(exports, 'createAnnotatedTypeNode', {
|
|
1912
|
-
enumerable: true,
|
|
1913
|
-
get: function () {
|
|
1914
|
-
return createAnnotatedTypeNode;
|
|
1915
|
-
}
|
|
1916
|
-
});
|
|
1917
|
-
Object.defineProperty(exports, 'defineAnnotatedType', {
|
|
1918
|
-
enumerable: true,
|
|
1919
|
-
get: function () {
|
|
1920
|
-
return defineAnnotatedType;
|
|
1921
|
-
}
|
|
1922
|
-
});
|
|
1923
|
-
Object.defineProperty(exports, 'detectDiscriminator', {
|
|
1924
|
-
enumerable: true,
|
|
1925
|
-
get: function () {
|
|
1926
|
-
return detectDiscriminator;
|
|
1927
|
-
}
|
|
1928
|
-
});
|
|
1929
|
-
Object.defineProperty(exports, 'forAnnotatedType', {
|
|
1930
|
-
enumerable: true,
|
|
1931
|
-
get: function () {
|
|
1932
|
-
return forAnnotatedType;
|
|
1933
|
-
}
|
|
1934
|
-
});
|
|
1935
|
-
Object.defineProperty(exports, 'fromJsonSchema', {
|
|
1936
|
-
enumerable: true,
|
|
1937
|
-
get: function () {
|
|
1938
|
-
return fromJsonSchema;
|
|
1939
|
-
}
|
|
1940
|
-
});
|
|
1941
|
-
Object.defineProperty(exports, 'isAnnotatedType', {
|
|
1942
|
-
enumerable: true,
|
|
1943
|
-
get: function () {
|
|
1944
|
-
return isAnnotatedType;
|
|
1945
|
-
}
|
|
1946
|
-
});
|
|
1947
|
-
Object.defineProperty(exports, 'isAnnotatedTypeOfPrimitive', {
|
|
1948
|
-
enumerable: true,
|
|
1949
|
-
get: function () {
|
|
1950
|
-
return isAnnotatedTypeOfPrimitive;
|
|
1951
|
-
}
|
|
1952
|
-
});
|
|
1953
|
-
Object.defineProperty(exports, 'isPhantomType', {
|
|
1954
|
-
enumerable: true,
|
|
1955
|
-
get: function () {
|
|
1956
|
-
return isPhantomType;
|
|
1957
|
-
}
|
|
1958
|
-
});
|
|
1959
|
-
Object.defineProperty(exports, 'mergeJsonSchemas', {
|
|
1960
|
-
enumerable: true,
|
|
1961
|
-
get: function () {
|
|
1962
|
-
return mergeJsonSchemas;
|
|
1963
|
-
}
|
|
1964
|
-
});
|