validup 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +229 -31
- package/dist/index.d.mts +969 -110
- package/dist/index.mjs +974 -191
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,518 @@
|
|
|
1
|
+
import { BaseError, interpolate, interpolate as interpolate$1 } from "@ebec/core";
|
|
1
2
|
import { distinctArray } from "smob";
|
|
2
3
|
import { arrayToPath, expandPath, getPathValue, pathToArray, setPathValue } from "pathtrace";
|
|
3
|
-
|
|
4
|
+
//#region src/utils/has-own-property.ts
|
|
5
|
+
function hasOwnProperty(obj, prop) {
|
|
6
|
+
return Object.prototype.hasOwnProperty.call(obj, prop);
|
|
7
|
+
}
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region src/utils/object.ts
|
|
10
|
+
function isObject(input) {
|
|
11
|
+
return !!input && typeof input === "object" && !Array.isArray(input);
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/container/check.ts
|
|
15
|
+
function isContainer(input) {
|
|
16
|
+
return isObject(input) && typeof input.run === "function" && typeof input.safeRun === "function";
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/error/base.ts
|
|
20
|
+
var ValidupError = class extends BaseError {
|
|
21
|
+
issues;
|
|
22
|
+
constructor(issues = []) {
|
|
23
|
+
const paths = issues.map((issue) => stringifyPath(issue.path));
|
|
24
|
+
super({ message: buildErrorMessageForAttributes(paths) });
|
|
25
|
+
this.issues = issues;
|
|
26
|
+
}
|
|
27
|
+
toJSON() {
|
|
28
|
+
return {
|
|
29
|
+
...super.toJSON(),
|
|
30
|
+
issues: this.issues
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/issue/check.ts
|
|
36
|
+
function isIssuePath(input) {
|
|
37
|
+
if (!Array.isArray(input)) return false;
|
|
38
|
+
return input.every((el) => typeof el === "string" || typeof el === "number" || typeof el === "symbol");
|
|
39
|
+
}
|
|
40
|
+
function isBaseIssue(input) {
|
|
41
|
+
if (!isObject(input)) return false;
|
|
42
|
+
if (typeof input.message !== "string") return false;
|
|
43
|
+
if (!isIssuePath(input.path)) return false;
|
|
44
|
+
return typeof input.meta === "undefined" || isObject(input.meta);
|
|
45
|
+
}
|
|
46
|
+
function isIssueItem(input) {
|
|
47
|
+
if (!isBaseIssue(input)) return false;
|
|
48
|
+
if (input.type !== "item") return false;
|
|
49
|
+
return typeof input.code === "string";
|
|
50
|
+
}
|
|
51
|
+
function isIssueGroup(input) {
|
|
52
|
+
if (!isBaseIssue(input)) return false;
|
|
53
|
+
if (input.type !== "group") return false;
|
|
54
|
+
return Array.isArray(input.issues) && input.issues.every((issue) => isIssueItem(issue) || isIssueGroup(issue));
|
|
55
|
+
}
|
|
56
|
+
function isIssue(input) {
|
|
57
|
+
return isIssueGroup(input) || isIssueItem(input);
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/issue/constants.ts
|
|
61
|
+
/**
|
|
62
|
+
* Vocabulary of well-known issue codes. Adapter packages map foreign
|
|
63
|
+
* validator codes onto these so consumer-side translation catalogs
|
|
64
|
+
* (e.g. `@ilingo/validup`) can ship one localized message per code
|
|
65
|
+
* instead of falling back to a generic "invalid value" fallback.
|
|
66
|
+
*
|
|
67
|
+
* Tracks the common ground between vuelidate, zod, joi, and yup. The
|
|
68
|
+
* core lifts from vuelidate's catalog (snake_cased to match validup's
|
|
69
|
+
* convention); modern format codes (`PATTERN`, `UUID`, `DATE`,
|
|
70
|
+
* `JSON`, `BASE64`, `STRONG_PASSWORD`, …) cover ground vuelidate
|
|
71
|
+
* predates. Every format code names the format positively (`UUID`,
|
|
72
|
+
* `EMAIL`, `URL`, …) rather than the failure mode (`NOT_UUID`,
|
|
73
|
+
* `INVALID_EMAIL`) so the registry reads consistently.
|
|
74
|
+
*
|
|
75
|
+
* Ad-hoc / project-specific codes still work — `IssueItem.code` is
|
|
76
|
+
* widened to `IssueCode | (string & {})`, so `defineIssueItem({ code:
|
|
77
|
+
* 'email_taken', ... })` is valid. If you want a typed const for your
|
|
78
|
+
* own codes, define one alongside this one:
|
|
79
|
+
*
|
|
80
|
+
* ```ts
|
|
81
|
+
* import { IssueCode } from 'validup';
|
|
82
|
+
*
|
|
83
|
+
* export const AppCode = {
|
|
84
|
+
* ...IssueCode,
|
|
85
|
+
* EMAIL_TAKEN: 'email_taken',
|
|
86
|
+
* } as const;
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* Each entry's JSDoc documents the structured `data` adapters should
|
|
90
|
+
* attach when constructing the issue — templates can rely on those
|
|
91
|
+
* placeholders being present (`{{min}}`, `{{max}}`, `{{other}}`, etc.).
|
|
92
|
+
*/
|
|
93
|
+
const IssueCode = {
|
|
94
|
+
/** Generic fallback when no more-specific code applies. `data`: — */
|
|
95
|
+
VALUE_INVALID: "value_invalid",
|
|
96
|
+
/** Every branch of a `oneOf` container failed. `data`: — */
|
|
97
|
+
ONE_OF_FAILED: "one_of_failed",
|
|
98
|
+
/** Value is missing, `undefined`, `null`, or empty per the validator's semantics. `data`: — */
|
|
99
|
+
REQUIRED: "required",
|
|
100
|
+
/** Value contains characters outside the alphabetical set. `data`: — */
|
|
101
|
+
ALPHA: "alpha",
|
|
102
|
+
/** Value contains characters outside the alphanumeric set. `data`: — */
|
|
103
|
+
ALPHA_NUM: "alpha_num",
|
|
104
|
+
/** Value is not a number. `data`: — */
|
|
105
|
+
NUMERIC: "numeric",
|
|
106
|
+
/** Value is not an integer. `data`: — */
|
|
107
|
+
INTEGER: "integer",
|
|
108
|
+
/** Value is not a decimal number. `data`: — */
|
|
109
|
+
DECIMAL: "decimal",
|
|
110
|
+
/** Value is shorter than the configured minimum. `data`: `{ min: number }` */
|
|
111
|
+
MIN_LENGTH: "min_length",
|
|
112
|
+
/** Value is longer than the configured maximum. `data`: `{ max: number }` */
|
|
113
|
+
MAX_LENGTH: "max_length",
|
|
114
|
+
/** Numeric value is below the configured minimum. `data`: `{ min: number }` */
|
|
115
|
+
MIN_VALUE: "min_value",
|
|
116
|
+
/** Numeric value is above the configured maximum. `data`: `{ max: number }` */
|
|
117
|
+
MAX_VALUE: "max_value",
|
|
118
|
+
/** Numeric value falls outside the configured `[min, max]` range. `data`: `{ min: number, max: number }` */
|
|
119
|
+
BETWEEN: "between",
|
|
120
|
+
/** Value is not a valid email address. `data`: — */
|
|
121
|
+
EMAIL: "email",
|
|
122
|
+
/** Value is not a valid URL. `data`: — */
|
|
123
|
+
URL: "url",
|
|
124
|
+
/** Value is not a valid IP address. `data`: — */
|
|
125
|
+
IP_ADDRESS: "ip_address",
|
|
126
|
+
/** Value is not a valid MAC address. `data`: — */
|
|
127
|
+
MAC_ADDRESS: "mac_address",
|
|
128
|
+
/** Value is not a valid UUID. `data`: — */
|
|
129
|
+
UUID: "uuid",
|
|
130
|
+
/** Value is not a valid date / cannot be parsed as a date. `data`: — */
|
|
131
|
+
DATE: "date",
|
|
132
|
+
/**
|
|
133
|
+
* Value does not match the expected regex pattern. `data`:
|
|
134
|
+
* `{ pattern: string }` — source of the regex without flags so
|
|
135
|
+
* catalogs can quote it in human-readable form.
|
|
136
|
+
*/
|
|
137
|
+
PATTERN: "pattern",
|
|
138
|
+
/** Value is not valid JSON. `data`: — */
|
|
139
|
+
JSON: "json",
|
|
140
|
+
/** Value is not valid base64. `data`: — */
|
|
141
|
+
BASE64: "base64",
|
|
142
|
+
/**
|
|
143
|
+
* Value does not meet the configured strong-password rules. `data`:
|
|
144
|
+
* `{ minLength?: number, minLowercase?: number, minUppercase?: number,
|
|
145
|
+
* minNumbers?: number, minSymbols?: number }` — only the keys the
|
|
146
|
+
* adapter chose to surface; missing keys mean "the default for that
|
|
147
|
+
* setting wasn't configured."
|
|
148
|
+
*/
|
|
149
|
+
STRONG_PASSWORD: "strong_password",
|
|
150
|
+
/**
|
|
151
|
+
* Value must equal another named field's value (sibling-field assertion,
|
|
152
|
+
* e.g. password-confirm). `data`: `{ other: string }` — the name of
|
|
153
|
+
* the field being compared against.
|
|
154
|
+
*/
|
|
155
|
+
SAME_AS: "same_as"
|
|
156
|
+
};
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/issue/define.ts
|
|
159
|
+
/**
|
|
160
|
+
* Build an `IssueItem`. TS uses the supplied `code` to pick the right
|
|
161
|
+
* `data` requirement at the call site — passing `MIN_LENGTH` without
|
|
162
|
+
* `data: { min }` is a compile error; passing `STRONG_PASSWORD` with
|
|
163
|
+
* `data: { pointsPerUnique: 5 }` is a compile error.
|
|
164
|
+
*
|
|
165
|
+
* `code` may be omitted (defaults to `IssueCode.VALUE_INVALID` — bare,
|
|
166
|
+
* no data).
|
|
167
|
+
*/
|
|
168
|
+
function defineIssueItem(data) {
|
|
169
|
+
return {
|
|
170
|
+
type: "item",
|
|
171
|
+
...data,
|
|
172
|
+
code: data.code || IssueCode.VALUE_INVALID
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function defineIssueGroup(data) {
|
|
176
|
+
return {
|
|
177
|
+
type: "group",
|
|
178
|
+
...data
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
//#region src/issue/flatten.ts
|
|
183
|
+
function flattenIssueItems(issues) {
|
|
184
|
+
const output = [];
|
|
185
|
+
for (const issue of issues) if (isIssueItem(issue)) output.push(issue);
|
|
186
|
+
else output.push(...flattenIssueItems(issue.issues));
|
|
187
|
+
return output;
|
|
188
|
+
}
|
|
189
|
+
function flattenIssueGroups(issues) {
|
|
190
|
+
const output = [];
|
|
191
|
+
for (const issue of issues) if (isIssueGroup(issue)) {
|
|
192
|
+
output.push(issue);
|
|
193
|
+
output.push(...flattenIssueGroups(issue.issues));
|
|
194
|
+
}
|
|
195
|
+
return output;
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region src/issue/format.ts
|
|
199
|
+
/**
|
|
200
|
+
* Render an issue's user-facing message.
|
|
201
|
+
*
|
|
202
|
+
* Resolution order:
|
|
203
|
+
* 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.
|
|
204
|
+
* 2. Else return `issue.message` (the default English rendering set at
|
|
205
|
+
* construction time).
|
|
206
|
+
* 3. Else return `fallback`.
|
|
207
|
+
*/
|
|
208
|
+
function formatIssue(issue, templates, fallback = "") {
|
|
209
|
+
if (templates && issue.code) {
|
|
210
|
+
const template = templates[issue.code];
|
|
211
|
+
if (typeof template === "string") return interpolate$1(template, issue.data || {});
|
|
212
|
+
}
|
|
213
|
+
if (typeof issue.message === "string" && issue.message.length > 0) return issue.message;
|
|
214
|
+
return fallback;
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/error/check.ts
|
|
218
|
+
function isError(input) {
|
|
219
|
+
if (input instanceof Error) return true;
|
|
220
|
+
if (!isObject(input)) return false;
|
|
221
|
+
return typeof input.message === "string" && typeof input.name === "string";
|
|
222
|
+
}
|
|
223
|
+
function isValidupError(error) {
|
|
224
|
+
if (!isError(error)) return false;
|
|
225
|
+
if (error instanceof ValidupError) return true;
|
|
226
|
+
if (!hasOwnProperty(error, "issues")) return false;
|
|
227
|
+
return Array.isArray(error.issues) && error.issues.every((issue) => isIssue(issue));
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/helpers/error-to-issues.ts
|
|
231
|
+
/**
|
|
232
|
+
* The "given an unknown throw, produce `Issue[]`" cascade shared by
|
|
233
|
+
* the validator-orchestrating helpers. The branching is identical
|
|
234
|
+
* at each site — `ValidupError` fans out, `Error` becomes one item,
|
|
235
|
+
* anything else gets a defensive stringify — so it lives here.
|
|
236
|
+
*
|
|
237
|
+
* - `ValidupError` → returns a fresh array containing each of its
|
|
238
|
+
* `issues` verbatim (callers can map/prefix after).
|
|
239
|
+
* - `Error` → returns one `IssueItem` carrying the message + supplied
|
|
240
|
+
* code/path.
|
|
241
|
+
* - Anything else (string, plain object, `null`, …) → returns one
|
|
242
|
+
* defensively-stringified `IssueItem` so the aggregate is never
|
|
243
|
+
* silently missing a contributing failure.
|
|
244
|
+
*
|
|
245
|
+
* Callers layer their own per-site concerns on top of the returned
|
|
246
|
+
* issues: path prefixing, optional stamping, per-branch index
|
|
247
|
+
* stamping, etc.
|
|
248
|
+
*/
|
|
249
|
+
function errorToIssues(error, options = {}) {
|
|
250
|
+
const code = options.code ?? IssueCode.VALUE_INVALID;
|
|
251
|
+
const path = options.path ?? [];
|
|
252
|
+
if (isValidupError(error)) return [...error.issues];
|
|
253
|
+
if (isError(error)) return [defineIssueItem({
|
|
254
|
+
path,
|
|
255
|
+
code,
|
|
256
|
+
message: error.message
|
|
257
|
+
})];
|
|
258
|
+
return [defineIssueItem({
|
|
259
|
+
path,
|
|
260
|
+
code,
|
|
261
|
+
message: typeof error === "string" && error.length > 0 ? error : `Non-Error throw: ${String(error)}`
|
|
262
|
+
})];
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/helpers/one-of-failed.ts
|
|
266
|
+
/**
|
|
267
|
+
* Build the `IssueGroup` that wraps an every-branch-failed aggregate
|
|
268
|
+
* — used by `composeAnyOf` (validator-level oneOf) AND
|
|
269
|
+
* `Container.finalizeOutput` (container-level `oneOf` option). Sharing
|
|
270
|
+
* the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so
|
|
271
|
+
* consumers / i18n catalogs only need one format for both modes.
|
|
272
|
+
*/
|
|
273
|
+
function buildOneOfFailedGroup(branchIssues, options = {}) {
|
|
274
|
+
return defineIssueGroup({
|
|
275
|
+
code: IssueCode.ONE_OF_FAILED,
|
|
276
|
+
message: options.message ?? "None of the branches succeeded",
|
|
277
|
+
path: options.path ?? [],
|
|
278
|
+
issues: branchIssues
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/helpers/compose.ts
|
|
283
|
+
/**
|
|
284
|
+
* Compose multiple validators into a single `Validator`.
|
|
285
|
+
*
|
|
286
|
+
* Default (`oneOf: false`) — validators run in order; each stage's
|
|
287
|
+
* return value feeds the next as `ctx.value`. A stage that returns
|
|
288
|
+
* `undefined` is treated as a pass-through (upstream value continues
|
|
289
|
+
* down the chain), so pure checks that don't re-emit `ctx.value`
|
|
290
|
+
* compose cleanly with transformers. `bail: true` (default) stops at
|
|
291
|
+
* the first failure; `bail: false` collects every failure into a
|
|
292
|
+
* single `ValidupError`.
|
|
293
|
+
*
|
|
294
|
+
* `oneOf: true` — branches run as alternatives in registration order;
|
|
295
|
+
* the first branch to succeed wins and subsequent branches are not
|
|
296
|
+
* invoked. When every branch fails, the composed validator throws a
|
|
297
|
+
* `ValidupError` whose first issue is an `IssueGroup` with
|
|
298
|
+
* `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.
|
|
299
|
+
*
|
|
300
|
+
* Elements can be bare `Validator<C>` functions OR fully-built
|
|
301
|
+
* `IContainer<T, C>` instances — the dispatcher detects which and
|
|
302
|
+
* either calls the function with the threaded `ctx` or invokes the
|
|
303
|
+
* container's `run(value, { group, context, signal, path })` with
|
|
304
|
+
* the threaded value as input. Containers participate with the same
|
|
305
|
+
* transform-or-throw contract; their output replaces the threaded
|
|
306
|
+
* value in the all-strategy chain, and a successful container wins
|
|
307
|
+
* the branch in `oneOf` mode.
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* // Fail-fast (default) — sanitize then validate
|
|
311
|
+
* container.mount('email', compose([
|
|
312
|
+
* trim(),
|
|
313
|
+
* isEmail(),
|
|
314
|
+
* isLength({ max: 254 }),
|
|
315
|
+
* ]));
|
|
316
|
+
*
|
|
317
|
+
* // Collect-all — surface every broken rule for a richer error UI
|
|
318
|
+
* container.mount('password', compose([
|
|
319
|
+
* isLength({ min: 8 }),
|
|
320
|
+
* isAlphanumeric(),
|
|
321
|
+
* matches(/[0-9]/),
|
|
322
|
+
* ], { bail: false }));
|
|
323
|
+
*
|
|
324
|
+
* // Any-of — accept either an email or a phone number on the same field
|
|
325
|
+
* container.mount('contact', compose([
|
|
326
|
+
* isEmail(),
|
|
327
|
+
* isMobilePhone(),
|
|
328
|
+
* ], { oneOf: true }));
|
|
329
|
+
*
|
|
330
|
+
* // Any-of with a container branch — accept a contact string OR a
|
|
331
|
+
* // nested address object validated by its own container.
|
|
332
|
+
* container.mount('contact', composeOneOf([
|
|
333
|
+
* isEmail(),
|
|
334
|
+
* isMobilePhone(),
|
|
335
|
+
* addressContainer,
|
|
336
|
+
* ]));
|
|
337
|
+
*
|
|
338
|
+
* Throws that aren't `ValidupError` / `Error` (raw strings, plain
|
|
339
|
+
* objects, null) are synthesized into a single `IssueItem` so the
|
|
340
|
+
* aggregate is never silently missing a contributing failure — mirrors
|
|
341
|
+
* `Container.recordMountError`'s defensive behavior.
|
|
342
|
+
*/
|
|
343
|
+
function compose(elements, options = {}) {
|
|
344
|
+
if (options.oneOf === true) return composeAnyOf(elements);
|
|
345
|
+
const bail = options.bail ?? true;
|
|
346
|
+
return async (ctx) => {
|
|
347
|
+
const issues = [];
|
|
348
|
+
let { value } = ctx;
|
|
349
|
+
for (const element of elements) try {
|
|
350
|
+
const result = await invokeComposeElement(element, {
|
|
351
|
+
...ctx,
|
|
352
|
+
value
|
|
353
|
+
});
|
|
354
|
+
if (typeof result !== "undefined") value = result;
|
|
355
|
+
} catch (e) {
|
|
356
|
+
if (bail) throw e;
|
|
357
|
+
for (const issue of errorToIssues(e)) issues.push(issue);
|
|
358
|
+
}
|
|
359
|
+
if (issues.length > 0) throw new ValidupError(issues);
|
|
360
|
+
return value;
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Sugar for `compose(elements, { oneOf: true })`. Reads more
|
|
365
|
+
* naturally at the call site when the alternative semantic is the
|
|
366
|
+
* intent, mirrors `Container`'s own `oneOf` option.
|
|
367
|
+
*/
|
|
368
|
+
function composeOneOf(elements) {
|
|
369
|
+
return compose(elements, { oneOf: true });
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* The `oneOf` execution path. Carved out so `compose`'s body stays
|
|
373
|
+
* focused on the all-strategy chain and so the abort / per-branch
|
|
374
|
+
* issue plumbing has somewhere to live without nesting.
|
|
375
|
+
*
|
|
376
|
+
* Each branch sees the original `ctx.value` (no threading across
|
|
377
|
+
* alternatives). The first defined return wins; an `undefined` return
|
|
378
|
+
* from a successful branch falls back to `ctx.value` so the
|
|
379
|
+
* pass-through rule stays symmetric with the all-strategy path.
|
|
380
|
+
*
|
|
381
|
+
* Aborts are re-raised verbatim from inside the try (matches Container
|
|
382
|
+
* behavior): a cancelled run isn't a validation outcome to wrap.
|
|
383
|
+
*/
|
|
384
|
+
function composeAnyOf(elements) {
|
|
385
|
+
return async (ctx) => {
|
|
386
|
+
const branchIssues = [];
|
|
387
|
+
for (const [index, element] of elements.entries()) {
|
|
388
|
+
ctx.signal?.throwIfAborted();
|
|
389
|
+
try {
|
|
390
|
+
const result = await invokeComposeElement(element, { ...ctx });
|
|
391
|
+
return typeof result === "undefined" ? ctx.value : result;
|
|
392
|
+
} catch (e) {
|
|
393
|
+
if (ctx.signal?.aborted) throw e;
|
|
394
|
+
const wrapped = wrapBranchIssues(e, index);
|
|
395
|
+
for (const issue of wrapped) branchIssues.push(issue);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
throw new ValidupError([buildOneOfFailedGroup(branchIssues)]);
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Dispatch one compose element against the current `ctx`. Containers
|
|
403
|
+
* receive `ctx.value` as their input (normalised to `{}` for non-object
|
|
404
|
+
* values, mirroring how the `Container.run` loop handles a nested
|
|
405
|
+
* container mounted against a non-object value); validators receive
|
|
406
|
+
* `ctx` itself.
|
|
407
|
+
*
|
|
408
|
+
* Forwarded to the child container's `run`:
|
|
409
|
+
*
|
|
410
|
+
* - `group`, `context`, `signal` — the threaded run-level options
|
|
411
|
+
* surfaced on `ctx`. Letting the child see `ctx.signal` matters for
|
|
412
|
+
* aborting in-flight child validation when the outer run is
|
|
413
|
+
* cancelled.
|
|
414
|
+
* - `path: ctx.path` — used by the child's mounts to compute their
|
|
415
|
+
* own `ctx.path`, so a validator inside the child sees the
|
|
416
|
+
* absolute path it sits at (`['foo', 'street']`, not just
|
|
417
|
+
* `['street']`). Issue *paths* in the final thrown error don't
|
|
418
|
+
* depend on this forwarding — the outer Container's
|
|
419
|
+
* `prefixIssuePath` step rebuilds them from each level's own
|
|
420
|
+
* `keyParts` — but validators that inspect `ctx.path` (for
|
|
421
|
+
* logging, custom error formatting, etc.) would see a misleading
|
|
422
|
+
* relative path without it.
|
|
423
|
+
* - `cache: ctx.cache` — the outer Container surfaces its run-level
|
|
424
|
+
* `IResultCache` on `ctx`, so threading it here keeps a
|
|
425
|
+
* container-as-branch participating in the same per-mount cache
|
|
426
|
+
* the outer container is using. Without this forward, mounts
|
|
427
|
+
* inside a compose-branch container would silently bypass the
|
|
428
|
+
* cache, breaking the cache contract for the
|
|
429
|
+
* `composeOneOf([…, childContainer])` shape.
|
|
430
|
+
*
|
|
431
|
+
* Other run-level options (`pathsToInclude`, `pathsToExclude`,
|
|
432
|
+
* `defaults`, `parallel`) are intentionally NOT forwarded — they're
|
|
433
|
+
* normally narrowed per-mount by the parent's run loop
|
|
434
|
+
* (`resolvePathFilter`, `resolveDefaults`), and compose doesn't have
|
|
435
|
+
* the parent mount key it would need to compute the equivalent
|
|
436
|
+
* narrowing. A `composeOneOf` branch that's a container therefore
|
|
437
|
+
* runs all of its mounts regardless of the outer's include/exclude
|
|
438
|
+
* filter; if you need that level of inheritance, mount the container
|
|
439
|
+
* directly with `container.mount(...)` instead of routing it through
|
|
440
|
+
* compose.
|
|
441
|
+
*/
|
|
442
|
+
async function invokeComposeElement(element, ctx) {
|
|
443
|
+
if (isContainer(element)) return element.run(isObject(ctx.value) ? ctx.value : {}, {
|
|
444
|
+
path: ctx.path,
|
|
445
|
+
group: ctx.group,
|
|
446
|
+
context: ctx.context,
|
|
447
|
+
signal: ctx.signal,
|
|
448
|
+
cache: ctx.cache
|
|
449
|
+
});
|
|
450
|
+
return element(ctx);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Normalize one branch's failure into `Issue[]` ready to merge into
|
|
454
|
+
* the outer `ONE_OF_FAILED` group. Each issue is tagged with
|
|
455
|
+
* `data: { branch: index }` so a tree-walking consumer can report
|
|
456
|
+
* "branch N failed because ..." without needing to reconstruct
|
|
457
|
+
* registration order.
|
|
458
|
+
*
|
|
459
|
+
* Delegates the unknown-throw → `Issue[]` fold to the shared
|
|
460
|
+
* `errorToIssues` cascade; only the per-branch stamping is local
|
|
461
|
+
* concern. Spread issues are shallow-cloned before stamping so the
|
|
462
|
+
* `ValidupError` instance's `issues` array on the caller side isn't
|
|
463
|
+
* mutated when a consumer reads `.data.branch` later.
|
|
464
|
+
*/
|
|
465
|
+
function wrapBranchIssues(error, index) {
|
|
466
|
+
const stamp = (issue) => {
|
|
467
|
+
issue.data = {
|
|
468
|
+
...issue.data ?? {},
|
|
469
|
+
branch: index
|
|
470
|
+
};
|
|
471
|
+
return issue;
|
|
472
|
+
};
|
|
473
|
+
return errorToIssues(error).map((issue) => stamp({ ...issue }));
|
|
474
|
+
}
|
|
475
|
+
//#endregion
|
|
476
|
+
//#region src/helpers/create-error.ts
|
|
477
|
+
/**
|
|
478
|
+
* Build a `ValidupError` carrying a single `IssueItem` with the supplied
|
|
479
|
+
* code / message / data. Sugar for the common one-issue failure
|
|
480
|
+
* construction used by adapters and hand-rolled validators.
|
|
481
|
+
*
|
|
482
|
+
* The caller throws — keeping the `throw` keyword at the call site
|
|
483
|
+
* makes the failure path obvious in the validator function body:
|
|
484
|
+
*
|
|
485
|
+
* ```ts
|
|
486
|
+
* if (!validator.isEmail(s)) {
|
|
487
|
+
* throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');
|
|
488
|
+
* }
|
|
489
|
+
*
|
|
490
|
+
* if (!isInRange(s)) {
|
|
491
|
+
* throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });
|
|
492
|
+
* }
|
|
493
|
+
* ```
|
|
494
|
+
*
|
|
495
|
+
* The `code` you pass selects the `data` requirement at compile time:
|
|
496
|
+
* parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their
|
|
497
|
+
* typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any
|
|
498
|
+
* other string falls through to an open `Record<string, unknown>` data
|
|
499
|
+
* argument.
|
|
500
|
+
*
|
|
501
|
+
* For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),
|
|
502
|
+
* build a `ValidupError` directly with
|
|
503
|
+
* `new ValidupError([defineIssueItem(...), …])`.
|
|
504
|
+
*/
|
|
505
|
+
function createValidupError(received, code, message, ...rest) {
|
|
506
|
+
const data = rest[0];
|
|
507
|
+
return new ValidupError([defineIssueItem({
|
|
508
|
+
path: [],
|
|
509
|
+
message,
|
|
510
|
+
code,
|
|
511
|
+
data,
|
|
512
|
+
received
|
|
513
|
+
})]);
|
|
514
|
+
}
|
|
515
|
+
//#endregion
|
|
4
516
|
//#region src/helpers/defaults.ts
|
|
5
517
|
/**
|
|
6
518
|
* Slice a parent `defaults` map down to entries that target paths inside a
|
|
@@ -43,15 +555,22 @@ let GroupKey = /* @__PURE__ */ function(GroupKey) {
|
|
|
43
555
|
}({});
|
|
44
556
|
let OptionalValue = /* @__PURE__ */ function(OptionalValue) {
|
|
45
557
|
/**
|
|
46
|
-
*
|
|
558
|
+
* Treats only `undefined` as optional. Default.
|
|
47
559
|
*/
|
|
48
560
|
OptionalValue["UNDEFINED"] = "undefined";
|
|
49
561
|
/**
|
|
50
|
-
*
|
|
562
|
+
* Treats `null` and `undefined` as optional.
|
|
51
563
|
*/
|
|
52
564
|
OptionalValue["NULL"] = "null";
|
|
53
565
|
/**
|
|
54
|
-
* value
|
|
566
|
+
* Treats any JS falsy value as optional — `undefined`, `null`, `false`,
|
|
567
|
+
* `0`, `''`, `NaN`.
|
|
568
|
+
*
|
|
569
|
+
* **Warning**: this includes `0` and `''`. For quantity / numeric fields
|
|
570
|
+
* where `0` is a meaningful value, prefer the predicate form
|
|
571
|
+
* `optional: (value) => boolean` so you keep control over what counts as
|
|
572
|
+
* missing (e.g. `optional: (v) => v === '' || v === undefined` drops the
|
|
573
|
+
* empty string but keeps `0`).
|
|
55
574
|
*/
|
|
56
575
|
OptionalValue["FALSY"] = "falsy";
|
|
57
576
|
return OptionalValue;
|
|
@@ -136,129 +655,41 @@ function stringifyPath(input) {
|
|
|
136
655
|
return arrayToPath(input);
|
|
137
656
|
}
|
|
138
657
|
//#endregion
|
|
139
|
-
//#region src/
|
|
140
|
-
var ValidupError = class extends BaseError {
|
|
141
|
-
issues;
|
|
142
|
-
constructor(issues = []) {
|
|
143
|
-
const paths = issues.map((issue) => stringifyPath(issue.path));
|
|
144
|
-
super({ message: buildErrorMessageForAttributes(paths) });
|
|
145
|
-
this.issues = issues;
|
|
146
|
-
}
|
|
147
|
-
toJSON() {
|
|
148
|
-
return {
|
|
149
|
-
...super.toJSON(),
|
|
150
|
-
issues: this.issues
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
};
|
|
154
|
-
//#endregion
|
|
155
|
-
//#region src/utils/has-own-property.ts
|
|
156
|
-
function hasOwnProperty(obj, prop) {
|
|
157
|
-
return Object.prototype.hasOwnProperty.call(obj, prop);
|
|
158
|
-
}
|
|
159
|
-
//#endregion
|
|
160
|
-
//#region src/utils/object.ts
|
|
161
|
-
function isObject(input) {
|
|
162
|
-
return !!input && typeof input === "object" && !Array.isArray(input);
|
|
163
|
-
}
|
|
164
|
-
//#endregion
|
|
165
|
-
//#region src/issue/check.ts
|
|
166
|
-
function isIssuePath(input) {
|
|
167
|
-
if (!Array.isArray(input)) return false;
|
|
168
|
-
return input.every((el) => typeof el === "string" || typeof el === "number" || typeof el === "symbol");
|
|
169
|
-
}
|
|
170
|
-
function isBaseIssue(input) {
|
|
171
|
-
if (!isObject(input)) return false;
|
|
172
|
-
if (typeof input.message !== "string") return false;
|
|
173
|
-
if (!isIssuePath(input.path)) return false;
|
|
174
|
-
return typeof input.meta === "undefined" || isObject(input.meta);
|
|
175
|
-
}
|
|
176
|
-
function isIssueItem(input) {
|
|
177
|
-
if (!isBaseIssue(input)) return false;
|
|
178
|
-
if (input.type !== "item") return false;
|
|
179
|
-
return typeof input.code === "string";
|
|
180
|
-
}
|
|
181
|
-
function isIssueGroup(input) {
|
|
182
|
-
if (!isBaseIssue(input)) return false;
|
|
183
|
-
if (input.type !== "group") return false;
|
|
184
|
-
return Array.isArray(input.issues) && input.issues.every((issue) => isIssueItem(issue) || isIssueGroup(issue));
|
|
185
|
-
}
|
|
186
|
-
function isIssue(input) {
|
|
187
|
-
return isIssueGroup(input) || isIssueItem(input);
|
|
188
|
-
}
|
|
189
|
-
//#endregion
|
|
190
|
-
//#region src/issue/constants.ts
|
|
191
|
-
const IssueCode = {
|
|
192
|
-
VALUE_INVALID: "value_invalid",
|
|
193
|
-
ONE_OF_FAILED: "one_of_failed"
|
|
194
|
-
};
|
|
195
|
-
//#endregion
|
|
196
|
-
//#region src/issue/define.ts
|
|
197
|
-
function defineIssueItem(data) {
|
|
198
|
-
return {
|
|
199
|
-
type: "item",
|
|
200
|
-
...data,
|
|
201
|
-
code: data.code || IssueCode.VALUE_INVALID
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
function defineIssueGroup(data) {
|
|
205
|
-
return {
|
|
206
|
-
type: "group",
|
|
207
|
-
...data
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
//#endregion
|
|
211
|
-
//#region src/issue/flatten.ts
|
|
212
|
-
function flattenIssueItems(issues) {
|
|
213
|
-
const output = [];
|
|
214
|
-
for (const issue of issues) if (isIssueItem(issue)) output.push(issue);
|
|
215
|
-
else output.push(...flattenIssueItems(issue.issues));
|
|
216
|
-
return output;
|
|
217
|
-
}
|
|
218
|
-
function flattenIssueGroups(issues) {
|
|
219
|
-
const output = [];
|
|
220
|
-
for (const issue of issues) if (isIssueGroup(issue)) {
|
|
221
|
-
output.push(issue);
|
|
222
|
-
output.push(...flattenIssueGroups(issue.issues));
|
|
223
|
-
}
|
|
224
|
-
return output;
|
|
225
|
-
}
|
|
226
|
-
//#endregion
|
|
227
|
-
//#region src/issue/format.ts
|
|
658
|
+
//#region src/validator/check.ts
|
|
228
659
|
/**
|
|
229
|
-
*
|
|
660
|
+
* Duck-typed guard for {@link ValidatorDescriptor}. Used by `mount()` to
|
|
661
|
+
* distinguish a descriptor from a bare `Validator` function and from a
|
|
662
|
+
* nested `IContainer` (which is also an object but carries `run` /
|
|
663
|
+
* `safeRun` methods — the descriptor has a `run` function but no
|
|
664
|
+
* `safeRun`).
|
|
230
665
|
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
* construction time).
|
|
235
|
-
* 3. Else return `fallback`.
|
|
666
|
+
* Duck-typed (not `instanceof`) so descriptors built from a different
|
|
667
|
+
* copy of the package — adapters bundling their own `validup` dependency,
|
|
668
|
+
* pnpm workspaces with multiple installs — still round-trip cleanly.
|
|
236
669
|
*/
|
|
237
|
-
function
|
|
238
|
-
if (templates && issue.code) {
|
|
239
|
-
const template = templates[issue.code];
|
|
240
|
-
if (typeof template === "string") return interpolate$1(template, issue.params || {});
|
|
241
|
-
}
|
|
242
|
-
if (typeof issue.message === "string" && issue.message.length > 0) return issue.message;
|
|
243
|
-
return fallback;
|
|
244
|
-
}
|
|
245
|
-
//#endregion
|
|
246
|
-
//#region src/error/check.ts
|
|
247
|
-
function isError(input) {
|
|
248
|
-
if (input instanceof Error) return true;
|
|
670
|
+
function isValidatorDescriptor(input) {
|
|
249
671
|
if (!isObject(input)) return false;
|
|
250
|
-
return typeof input.
|
|
251
|
-
}
|
|
252
|
-
function isValidupError(error) {
|
|
253
|
-
if (!isError(error)) return false;
|
|
254
|
-
if (error instanceof ValidupError) return true;
|
|
255
|
-
if (!hasOwnProperty(error, "issues")) return false;
|
|
256
|
-
return Array.isArray(error.issues) && error.issues.every((issue) => isIssue(issue));
|
|
672
|
+
return typeof input.run === "function" && typeof input.safeRun !== "function";
|
|
257
673
|
}
|
|
258
674
|
//#endregion
|
|
259
|
-
//#region src/
|
|
260
|
-
|
|
261
|
-
|
|
675
|
+
//#region src/validator/define.ts
|
|
676
|
+
/**
|
|
677
|
+
* Factory for a {@link ValidatorDescriptor}. Mirrors the
|
|
678
|
+
* `defineIssueItem` / `defineIssueGroup` shape used elsewhere in the
|
|
679
|
+
* library so authored validators get a stable, typed construction site.
|
|
680
|
+
*
|
|
681
|
+
* @example
|
|
682
|
+
* const validateEmailUnique = defineValidator({
|
|
683
|
+
* sideEffect: true,
|
|
684
|
+
* run: async (ctx) => {
|
|
685
|
+
* const taken = await api.isEmailTaken(ctx.value as string);
|
|
686
|
+
* if (taken) throw new Error('Email is already taken');
|
|
687
|
+
* return ctx.value;
|
|
688
|
+
* },
|
|
689
|
+
* });
|
|
690
|
+
*/
|
|
691
|
+
function defineValidator(descriptor) {
|
|
692
|
+
return descriptor;
|
|
262
693
|
}
|
|
263
694
|
//#endregion
|
|
264
695
|
//#region src/container/run-sync-violation.ts
|
|
@@ -295,29 +726,51 @@ var Container = class {
|
|
|
295
726
|
}
|
|
296
727
|
mount(...args) {
|
|
297
728
|
if (args.length < 1) throw new SyntaxError("The mount method requires at least one argument");
|
|
729
|
+
if (args.length > 3) throw new SyntaxError(`mount() accepts at most 3 arguments, got ${args.length}`);
|
|
298
730
|
let path;
|
|
731
|
+
let pathSeen = false;
|
|
299
732
|
let data;
|
|
300
|
-
let
|
|
733
|
+
let dataSeen = false;
|
|
734
|
+
let dataKind;
|
|
301
735
|
let options = {};
|
|
736
|
+
let optionsSeen = false;
|
|
302
737
|
for (const arg of args) {
|
|
303
738
|
if (typeof arg === "string") {
|
|
739
|
+
if (pathSeen) throw new SyntaxError("mount() received multiple string arguments — only one path is supported.");
|
|
740
|
+
pathSeen = true;
|
|
304
741
|
path = arg;
|
|
305
742
|
continue;
|
|
306
743
|
}
|
|
307
744
|
if (typeof arg === "function") {
|
|
745
|
+
if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
|
|
746
|
+
dataSeen = true;
|
|
308
747
|
data = arg;
|
|
748
|
+
dataKind = "validator";
|
|
309
749
|
continue;
|
|
310
750
|
}
|
|
311
751
|
if (isContainer(arg)) {
|
|
752
|
+
if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
|
|
753
|
+
dataSeen = true;
|
|
754
|
+
data = arg;
|
|
755
|
+
dataKind = "container";
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (isValidatorDescriptor(arg)) {
|
|
759
|
+
if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
|
|
760
|
+
dataSeen = true;
|
|
312
761
|
data = arg;
|
|
313
|
-
|
|
762
|
+
dataKind = "descriptor";
|
|
314
763
|
continue;
|
|
315
764
|
}
|
|
316
|
-
if (isObject(arg))
|
|
765
|
+
if (isObject(arg)) {
|
|
766
|
+
if (optionsSeen) throw new SyntaxError("mount() received multiple options objects.");
|
|
767
|
+
optionsSeen = true;
|
|
768
|
+
options = arg;
|
|
769
|
+
}
|
|
317
770
|
}
|
|
318
|
-
if (
|
|
319
|
-
if (typeof data === "undefined") throw new SyntaxError("No container/validator could be extracted from the fn arguments.");
|
|
320
|
-
if (
|
|
771
|
+
if (dataKind !== "container" && (typeof path === "undefined" || path.length === 0)) throw new SyntaxError("Only a container can be mounted without a key.");
|
|
772
|
+
if (typeof data === "undefined" || typeof dataKind === "undefined") throw new SyntaxError("No container/validator could be extracted from the fn arguments.");
|
|
773
|
+
if (dataKind === "container") {
|
|
321
774
|
this.items.push({
|
|
322
775
|
options,
|
|
323
776
|
data,
|
|
@@ -326,6 +779,17 @@ var Container = class {
|
|
|
326
779
|
});
|
|
327
780
|
return;
|
|
328
781
|
}
|
|
782
|
+
if (dataKind === "descriptor") {
|
|
783
|
+
const descriptor = data;
|
|
784
|
+
this.items.push({
|
|
785
|
+
options,
|
|
786
|
+
data: descriptor.run,
|
|
787
|
+
path,
|
|
788
|
+
type: "validator",
|
|
789
|
+
sideEffect: descriptor.sideEffect
|
|
790
|
+
});
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
329
793
|
this.items.push({
|
|
330
794
|
options,
|
|
331
795
|
data,
|
|
@@ -334,10 +798,32 @@ var Container = class {
|
|
|
334
798
|
});
|
|
335
799
|
}
|
|
336
800
|
/**
|
|
337
|
-
*
|
|
801
|
+
* Run the container against `data`. Default execution mode — async,
|
|
802
|
+
* sequential, throws `ValidupError` on validation failure.
|
|
338
803
|
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
804
|
+
* Variants for the other execution modes:
|
|
805
|
+
* - `run(data, { parallel: true })` — async, sequential→concurrent. Each
|
|
806
|
+
* mount captures `value` from `data` before any sibling runs, so chained
|
|
807
|
+
* sanitize-then-validate patterns are not supported.
|
|
808
|
+
* - {@link Container.safeRun} — same as `run` but returns a discriminated
|
|
809
|
+
* `Result<T>` instead of throwing on validation failure (still rethrows
|
|
810
|
+
* on abort).
|
|
811
|
+
* - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous
|
|
812
|
+
* variants for graphs where every validator (and every nested container's
|
|
813
|
+
* `runSync`) is synchronous.
|
|
814
|
+
*
|
|
815
|
+
* Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`
|
|
816
|
+
* between mounts (which throws `signal.reason`), and any error raised by a
|
|
817
|
+
* mid-flight validator during an aborted run is re-thrown as-is rather than
|
|
818
|
+
* folded into the issue tree. Callers can therefore distinguish "validation
|
|
819
|
+
* failed" from "operation cancelled," but should not assume the thrown value
|
|
820
|
+
* is always `signal.reason` — a validator that throws its own error before
|
|
821
|
+
* the next abort check produces that error instead.
|
|
822
|
+
*
|
|
823
|
+
* @throws ValidupError on validation failure.
|
|
824
|
+
* @throws signal.reason when the abort check fires between mounts.
|
|
825
|
+
* @throws (mid-flight validator error) when a validator throws during an
|
|
826
|
+
* already-aborted run — re-raised as-is rather than wrapped.
|
|
341
827
|
*/
|
|
342
828
|
async run(data = {}, options = {}) {
|
|
343
829
|
if (options.parallel) return this.runParallel(data, options);
|
|
@@ -352,6 +838,7 @@ var Container = class {
|
|
|
352
838
|
if (!this.isItemGroupIncluded(item, options.group)) continue;
|
|
353
839
|
let pathCount = 0;
|
|
354
840
|
let pathFailed = false;
|
|
841
|
+
const branchStart = issues.length;
|
|
355
842
|
const keys = item.path ? expandPath(data, item.path) : [""];
|
|
356
843
|
for (const key of keys) {
|
|
357
844
|
const keyParts = key ? pathToArray(key) : [];
|
|
@@ -374,28 +861,64 @@ var Container = class {
|
|
|
374
861
|
pathsToExclude: filter.pathsToExclude,
|
|
375
862
|
defaults: resolveDefaults(options.defaults, key),
|
|
376
863
|
context: options.context,
|
|
377
|
-
signal: options.signal
|
|
864
|
+
signal: options.signal,
|
|
865
|
+
cache: options.cache
|
|
378
866
|
});
|
|
379
867
|
const tmpKeys = Object.keys(tmp);
|
|
380
868
|
for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
|
|
381
|
-
} else if (item.type === "validator")
|
|
382
|
-
|
|
383
|
-
|
|
869
|
+
} else if (item.type === "validator") {
|
|
870
|
+
const snapshot = {
|
|
871
|
+
value,
|
|
872
|
+
context: options.context,
|
|
873
|
+
group: options.group
|
|
874
|
+
};
|
|
875
|
+
const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
|
|
876
|
+
if (cached) if (cached.ok) output[key] = cached.value;
|
|
877
|
+
else throw cached.error;
|
|
878
|
+
else try {
|
|
879
|
+
const result = await item.data({
|
|
880
|
+
key,
|
|
881
|
+
path: pathAbsolute,
|
|
882
|
+
value,
|
|
883
|
+
data,
|
|
884
|
+
group: options.group,
|
|
885
|
+
context: options.context,
|
|
886
|
+
signal: options.signal,
|
|
887
|
+
cache: options.cache
|
|
888
|
+
});
|
|
889
|
+
output[key] = result;
|
|
890
|
+
this.writeCachedOutcome(item, key, snapshot, {
|
|
891
|
+
ok: true,
|
|
892
|
+
value: result
|
|
893
|
+
}, options.cache, options.signal);
|
|
894
|
+
} catch (e) {
|
|
895
|
+
this.writeCachedOutcome(item, key, snapshot, {
|
|
896
|
+
ok: false,
|
|
897
|
+
error: e
|
|
898
|
+
}, options.cache, options.signal);
|
|
899
|
+
throw e;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
} catch (e) {
|
|
903
|
+
this.collectExecutionFailure({
|
|
904
|
+
error: e,
|
|
905
|
+
item,
|
|
384
906
|
value,
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
907
|
+
keyParts,
|
|
908
|
+
pathRelative,
|
|
909
|
+
issues,
|
|
388
910
|
signal: options.signal
|
|
389
911
|
});
|
|
390
|
-
} catch (e) {
|
|
391
|
-
this.recordMountError(e, item, keyParts, pathRelative, issues, options.signal);
|
|
392
912
|
pathFailed = true;
|
|
393
913
|
}
|
|
394
914
|
pathCount++;
|
|
395
915
|
}
|
|
396
916
|
if (pathCount > 0) {
|
|
397
917
|
itemCount++;
|
|
398
|
-
if (pathFailed)
|
|
918
|
+
if (pathFailed) {
|
|
919
|
+
errorCount++;
|
|
920
|
+
this.wrapBranchForOneOf(issues, branchStart, item, i);
|
|
921
|
+
}
|
|
399
922
|
}
|
|
400
923
|
}
|
|
401
924
|
return this.finalizeOutput(output, options, issues, errorCount, itemCount);
|
|
@@ -441,30 +964,61 @@ var Container = class {
|
|
|
441
964
|
defaults: resolveDefaults(options.defaults, key),
|
|
442
965
|
context: options.context,
|
|
443
966
|
signal: options.signal,
|
|
444
|
-
parallel: true
|
|
967
|
+
parallel: true,
|
|
968
|
+
cache: options.cache
|
|
445
969
|
});
|
|
446
970
|
else {
|
|
447
|
-
const
|
|
448
|
-
promise = (async () => itemData({
|
|
449
|
-
key,
|
|
450
|
-
path: pathAbsolute,
|
|
971
|
+
const snapshot = {
|
|
451
972
|
value,
|
|
452
|
-
data,
|
|
453
|
-
group: options.group,
|
|
454
973
|
context: options.context,
|
|
455
|
-
|
|
456
|
-
}
|
|
974
|
+
group: options.group
|
|
975
|
+
};
|
|
976
|
+
const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
|
|
977
|
+
if (cached) promise = cached.ok ? Promise.resolve(cached.value) : Promise.reject(cached.error);
|
|
978
|
+
else {
|
|
979
|
+
const itemData = item.data;
|
|
980
|
+
const captureItem = item;
|
|
981
|
+
const captureKey = key;
|
|
982
|
+
const captureSnapshot = snapshot;
|
|
983
|
+
promise = (async () => {
|
|
984
|
+
try {
|
|
985
|
+
const result = await itemData({
|
|
986
|
+
key,
|
|
987
|
+
path: pathAbsolute,
|
|
988
|
+
value,
|
|
989
|
+
data,
|
|
990
|
+
group: options.group,
|
|
991
|
+
context: options.context,
|
|
992
|
+
signal: options.signal,
|
|
993
|
+
cache: options.cache
|
|
994
|
+
});
|
|
995
|
+
this.writeCachedOutcome(captureItem, captureKey, captureSnapshot, {
|
|
996
|
+
ok: true,
|
|
997
|
+
value: result
|
|
998
|
+
}, options.cache, options.signal);
|
|
999
|
+
return result;
|
|
1000
|
+
} catch (e) {
|
|
1001
|
+
this.writeCachedOutcome(captureItem, captureKey, captureSnapshot, {
|
|
1002
|
+
ok: false,
|
|
1003
|
+
error: e
|
|
1004
|
+
}, options.cache, options.signal);
|
|
1005
|
+
throw e;
|
|
1006
|
+
}
|
|
1007
|
+
})();
|
|
1008
|
+
}
|
|
457
1009
|
}
|
|
458
1010
|
tasks.push({
|
|
459
1011
|
key,
|
|
460
1012
|
keyParts,
|
|
461
1013
|
pathRelative,
|
|
1014
|
+
value,
|
|
462
1015
|
promise,
|
|
463
1016
|
kind: item.type
|
|
464
1017
|
});
|
|
465
1018
|
}
|
|
466
1019
|
if (tasks.length > 0 || syncPathCount > 0) itemGroups.push({
|
|
467
1020
|
item,
|
|
1021
|
+
mountIndex: i,
|
|
468
1022
|
tasks,
|
|
469
1023
|
syncPathCount
|
|
470
1024
|
});
|
|
@@ -473,9 +1027,10 @@ var Container = class {
|
|
|
473
1027
|
options.signal?.throwIfAborted();
|
|
474
1028
|
let itemCount = 0;
|
|
475
1029
|
let errorCount = 0;
|
|
476
|
-
for (const [i, { item, tasks, syncPathCount }] of itemGroups.entries()) {
|
|
1030
|
+
for (const [i, { item, mountIndex, tasks, syncPathCount }] of itemGroups.entries()) {
|
|
477
1031
|
const settled = settledByGroup[i];
|
|
478
1032
|
let pathFailed = false;
|
|
1033
|
+
const branchStart = issues.length;
|
|
479
1034
|
for (const [j, task] of tasks.entries()) {
|
|
480
1035
|
const result = settled[j];
|
|
481
1036
|
if (result.status === "fulfilled") if (task.kind === "container") {
|
|
@@ -484,13 +1039,24 @@ var Container = class {
|
|
|
484
1039
|
for (const tmpKey of tmpKeys) output[this.mergePaths(task.key, tmpKey)] = tmp[tmpKey];
|
|
485
1040
|
} else output[task.key] = result.value;
|
|
486
1041
|
else {
|
|
487
|
-
this.
|
|
1042
|
+
this.collectExecutionFailure({
|
|
1043
|
+
error: result.reason,
|
|
1044
|
+
item,
|
|
1045
|
+
value: task.value,
|
|
1046
|
+
keyParts: task.keyParts,
|
|
1047
|
+
pathRelative: task.pathRelative,
|
|
1048
|
+
issues,
|
|
1049
|
+
signal: options.signal
|
|
1050
|
+
});
|
|
488
1051
|
pathFailed = true;
|
|
489
1052
|
}
|
|
490
1053
|
}
|
|
491
1054
|
if (tasks.length + syncPathCount > 0) {
|
|
492
1055
|
itemCount++;
|
|
493
|
-
if (pathFailed)
|
|
1056
|
+
if (pathFailed) {
|
|
1057
|
+
errorCount++;
|
|
1058
|
+
this.wrapBranchForOneOf(issues, branchStart, item, mountIndex);
|
|
1059
|
+
}
|
|
494
1060
|
}
|
|
495
1061
|
}
|
|
496
1062
|
options.signal?.throwIfAborted();
|
|
@@ -507,13 +1073,33 @@ var Container = class {
|
|
|
507
1073
|
}
|
|
508
1074
|
}
|
|
509
1075
|
/**
|
|
510
|
-
* @
|
|
1076
|
+
* Synchronous variant of {@link Container.run}. Use it for purely
|
|
1077
|
+
* synchronous validator graphs where the microtask overhead of `await`
|
|
1078
|
+
* per mount matters (e.g. driving a reactive UI without a `pending`
|
|
1079
|
+
* flicker on every keystroke).
|
|
1080
|
+
*
|
|
1081
|
+
* Each mounted validator's return value MUST NOT be a thenable, and every
|
|
1082
|
+
* nested container MUST implement `runSync`. Either violation throws
|
|
1083
|
+
* `RunSyncViolationError` (structural — distinct from validation
|
|
1084
|
+
* failures), so the diagnostic is surfaced verbatim rather than wrapped
|
|
1085
|
+
* into a `ValidupError`. The companion {@link Container.safeRunSync}
|
|
1086
|
+
* still rethrows these for the same reason.
|
|
511
1087
|
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
1088
|
+
* No `parallel` variant — synchronous graphs don't benefit from
|
|
1089
|
+
* concurrency, and `Promise.allSettled` is async by definition.
|
|
1090
|
+
*
|
|
1091
|
+
* Aborts surface the same way as {@link Container.run}: the
|
|
1092
|
+
* `signal.throwIfAborted()` check between mounts throws `signal.reason`,
|
|
1093
|
+
* and a mid-flight validator throw during an already-aborted run is
|
|
1094
|
+
* re-raised verbatim. Don't assume the thrown value is always
|
|
1095
|
+
* `signal.reason`.
|
|
1096
|
+
*
|
|
1097
|
+
* @throws ValidupError on validation failure.
|
|
1098
|
+
* @throws RunSyncViolationError when a validator returns a Promise or a
|
|
1099
|
+
* nested container does not implement `runSync`.
|
|
1100
|
+
* @throws signal.reason when the abort check fires between mounts.
|
|
1101
|
+
* @throws (mid-flight validator error) when a validator throws during an
|
|
1102
|
+
* already-aborted run.
|
|
517
1103
|
*/
|
|
518
1104
|
runSync(data = {}, options = {}) {
|
|
519
1105
|
const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
|
|
@@ -527,6 +1113,7 @@ var Container = class {
|
|
|
527
1113
|
if (!this.isItemGroupIncluded(item, options.group)) continue;
|
|
528
1114
|
let pathCount = 0;
|
|
529
1115
|
let pathFailed = false;
|
|
1116
|
+
const branchStart = issues.length;
|
|
530
1117
|
const keys = item.path ? expandPath(data, item.path) : [""];
|
|
531
1118
|
for (const key of keys) {
|
|
532
1119
|
const keyParts = key ? pathToArray(key) : [];
|
|
@@ -551,32 +1138,65 @@ var Container = class {
|
|
|
551
1138
|
pathsToExclude: filter.pathsToExclude,
|
|
552
1139
|
defaults: resolveDefaults(options.defaults, key),
|
|
553
1140
|
context: options.context,
|
|
554
|
-
signal: options.signal
|
|
1141
|
+
signal: options.signal,
|
|
1142
|
+
cache: options.cache
|
|
555
1143
|
});
|
|
556
1144
|
const tmpKeys = Object.keys(tmp);
|
|
557
1145
|
for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
|
|
558
1146
|
} else if (item.type === "validator") {
|
|
559
|
-
const
|
|
560
|
-
key,
|
|
561
|
-
path: pathAbsolute,
|
|
1147
|
+
const snapshot = {
|
|
562
1148
|
value,
|
|
563
|
-
data,
|
|
564
|
-
group: options.group,
|
|
565
1149
|
context: options.context,
|
|
566
|
-
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
output[key] =
|
|
1150
|
+
group: options.group
|
|
1151
|
+
};
|
|
1152
|
+
const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
|
|
1153
|
+
if (cached) if (cached.ok) output[key] = cached.value;
|
|
1154
|
+
else throw cached.error;
|
|
1155
|
+
else try {
|
|
1156
|
+
const result = item.data({
|
|
1157
|
+
key,
|
|
1158
|
+
path: pathAbsolute,
|
|
1159
|
+
value,
|
|
1160
|
+
data,
|
|
1161
|
+
group: options.group,
|
|
1162
|
+
context: options.context,
|
|
1163
|
+
signal: options.signal,
|
|
1164
|
+
cache: options.cache
|
|
1165
|
+
});
|
|
1166
|
+
if (result !== null && typeof result === "object" && typeof result.then === "function") throw new RunSyncViolationError(`runSync: validator at "${key || "<root>"}" returned a Promise`);
|
|
1167
|
+
output[key] = result;
|
|
1168
|
+
this.writeCachedOutcome(item, key, snapshot, {
|
|
1169
|
+
ok: true,
|
|
1170
|
+
value: result
|
|
1171
|
+
}, options.cache, options.signal);
|
|
1172
|
+
} catch (e) {
|
|
1173
|
+
if (!isRunSyncViolation(e)) this.writeCachedOutcome(item, key, snapshot, {
|
|
1174
|
+
ok: false,
|
|
1175
|
+
error: e
|
|
1176
|
+
}, options.cache, options.signal);
|
|
1177
|
+
throw e;
|
|
1178
|
+
}
|
|
570
1179
|
}
|
|
571
1180
|
} catch (e) {
|
|
572
|
-
this.
|
|
1181
|
+
this.collectExecutionFailure({
|
|
1182
|
+
error: e,
|
|
1183
|
+
item,
|
|
1184
|
+
value,
|
|
1185
|
+
keyParts,
|
|
1186
|
+
pathRelative,
|
|
1187
|
+
issues,
|
|
1188
|
+
signal: options.signal
|
|
1189
|
+
});
|
|
573
1190
|
pathFailed = true;
|
|
574
1191
|
}
|
|
575
1192
|
pathCount++;
|
|
576
1193
|
}
|
|
577
1194
|
if (pathCount > 0) {
|
|
578
1195
|
itemCount++;
|
|
579
|
-
if (pathFailed)
|
|
1196
|
+
if (pathFailed) {
|
|
1197
|
+
errorCount++;
|
|
1198
|
+
this.wrapBranchForOneOf(issues, branchStart, item, i);
|
|
1199
|
+
}
|
|
580
1200
|
}
|
|
581
1201
|
}
|
|
582
1202
|
return this.finalizeOutput(output, options, issues, errorCount, itemCount);
|
|
@@ -591,6 +1211,47 @@ var Container = class {
|
|
|
591
1211
|
return this.wrapSafeRunError(e, options);
|
|
592
1212
|
}
|
|
593
1213
|
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Lookup helper for the per-mount result cache.
|
|
1216
|
+
*
|
|
1217
|
+
* Returns `undefined` (forcing a real run) for any of:
|
|
1218
|
+
* - No `cache` supplied — caller didn't opt in.
|
|
1219
|
+
* - Mount isn't a validator — container mounts run their own
|
|
1220
|
+
* inner loop, which consults the cache for their own mounts.
|
|
1221
|
+
* - Validator declared `sideEffect: true` — its result depends on
|
|
1222
|
+
* inputs the snapshot doesn't capture (sibling fields, network,
|
|
1223
|
+
* global state), so caching would be unsound.
|
|
1224
|
+
* - No prior entry stored for this `(mount, key)` pair.
|
|
1225
|
+
* - Stored snapshot's `value` / `context` / `group` don't all match
|
|
1226
|
+
* the current invocation by `Object.is`.
|
|
1227
|
+
*/
|
|
1228
|
+
resolveCachedOutcome(item, key, snapshot, cache) {
|
|
1229
|
+
if (!cache || item.type !== "validator" || item.sideEffect === true) return;
|
|
1230
|
+
const entry = cache.get(item, key);
|
|
1231
|
+
if (!entry) return;
|
|
1232
|
+
if (Object.is(entry.snapshot.value, snapshot.value) && Object.is(entry.snapshot.context, snapshot.context) && Object.is(entry.snapshot.group, snapshot.group)) return entry.outcome;
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Store the outcome of a fresh validator invocation. No-ops in the
|
|
1236
|
+
* same cases `resolveCachedOutcome` returns `undefined` for, plus:
|
|
1237
|
+
*
|
|
1238
|
+
* - `signal.aborted` — the throw was caused by cancellation, not by
|
|
1239
|
+
* a validation outcome we want to remember. Caching the abort
|
|
1240
|
+
* would mean future replays surface "AbortError" as a fake
|
|
1241
|
+
* validation issue every time the same snapshot is seen, even
|
|
1242
|
+
* in fully-completed runs.
|
|
1243
|
+
*
|
|
1244
|
+
* `RunSyncViolationError`s are filtered out at the call site
|
|
1245
|
+
* (`runSync` only) because they're structural — the validator
|
|
1246
|
+
* graph is wrong, not the input.
|
|
1247
|
+
*/
|
|
1248
|
+
writeCachedOutcome(item, key, snapshot, outcome, cache, signal) {
|
|
1249
|
+
if (!cache || item.type !== "validator" || item.sideEffect === true || signal?.aborted) return;
|
|
1250
|
+
cache.set(item, key, {
|
|
1251
|
+
snapshot,
|
|
1252
|
+
outcome
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
594
1255
|
resolveContainerFilters(options) {
|
|
595
1256
|
let pathsToInclude;
|
|
596
1257
|
if (options.pathsToInclude) pathsToInclude = options.pathsToInclude;
|
|
@@ -621,41 +1282,100 @@ var Container = class {
|
|
|
621
1282
|
return prefixed;
|
|
622
1283
|
}
|
|
623
1284
|
/**
|
|
624
|
-
* Translate a
|
|
1285
|
+
* Translate a throw raised by one execution step (one validator or
|
|
1286
|
+
* nested-container invocation, from the surrounding `run` loop) into
|
|
1287
|
+
* accumulated issues and push them onto `context.issues`. Re-throws when
|
|
625
1288
|
* the run was aborted (signal-aware validators) so abort errors are not
|
|
626
|
-
* mangled into validation issues.
|
|
627
|
-
*
|
|
1289
|
+
* mangled into validation issues.
|
|
1290
|
+
*
|
|
1291
|
+
* "Mount" is the *setup-time* verb (`container.mount(...)`); what failed
|
|
1292
|
+
* here is the *execution* of an already-mounted unit — hence the name.
|
|
1293
|
+
*
|
|
1294
|
+
* The context object captures everything the error path needs to know
|
|
1295
|
+
* about the failing step: the thrown value (`error`), the mount
|
|
1296
|
+
* descriptor (`item`), the current input (`value` — kept around so we
|
|
1297
|
+
* can re-evaluate predicate-optional declarations at error time), the
|
|
1298
|
+
* expanded path (`keyParts` — used to prepend to nested `ValidupError`
|
|
1299
|
+
* issues) and the trailing segment (`pathRelative` — used when wrapping
|
|
1300
|
+
* multi-issue or container emissions into an `IssueGroup`). The
|
|
1301
|
+
* destination accumulator (`issues`) and the abort `signal` round out
|
|
1302
|
+
* what's needed to handle the failure.
|
|
1303
|
+
*
|
|
1304
|
+
* @modifies context.issues — appends one or more entries per call.
|
|
628
1305
|
*/
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
if (
|
|
1306
|
+
collectExecutionFailure(context) {
|
|
1307
|
+
const { error, item, value, keyParts, pathRelative, issues, signal } = context;
|
|
1308
|
+
if (signal?.aborted) throw error;
|
|
1309
|
+
if (isRunSyncViolation(error)) throw error;
|
|
1310
|
+
const isOptionalMount = typeof item.options.optional === "function" ? Boolean(item.options.optional(value)) : item.options.optional === true;
|
|
1311
|
+
const markOptional = (issue) => {
|
|
1312
|
+
if (!isOptionalMount) return issue;
|
|
1313
|
+
issue.meta = {
|
|
1314
|
+
...issue.meta ?? {},
|
|
1315
|
+
optional: true
|
|
1316
|
+
};
|
|
1317
|
+
return issue;
|
|
1318
|
+
};
|
|
1319
|
+
const markOptionalDeep = (issue) => {
|
|
1320
|
+
if (!isOptionalMount) return issue;
|
|
1321
|
+
markOptional(issue);
|
|
1322
|
+
if (issue.type === "group") issue.issues = issue.issues.map((nested) => markOptionalDeep(nested));
|
|
1323
|
+
return issue;
|
|
1324
|
+
};
|
|
632
1325
|
const childIssues = [];
|
|
633
|
-
if (isValidupError(
|
|
634
|
-
|
|
1326
|
+
if (isValidupError(error)) for (let i = 0; i < error.issues.length; i++) {
|
|
1327
|
+
const prefixed = this.prefixIssuePath(error.issues[i], keyParts);
|
|
1328
|
+
childIssues.push(item.type === "validator" ? markOptionalDeep(prefixed) : prefixed);
|
|
1329
|
+
}
|
|
1330
|
+
else if (isError(error)) childIssues.push(markOptional(defineIssueItem({
|
|
635
1331
|
path: keyParts,
|
|
636
|
-
message:
|
|
637
|
-
}));
|
|
638
|
-
|
|
1332
|
+
message: error.message
|
|
1333
|
+
})));
|
|
1334
|
+
else childIssues.push(markOptional(defineIssueItem({
|
|
1335
|
+
path: keyParts,
|
|
1336
|
+
message: typeof error === "string" && error.length > 0 ? error : `Non-Error throw: ${String(error)}`
|
|
1337
|
+
})));
|
|
1338
|
+
if (pathRelative) if (item.type === "container" || childIssues.length > 1) issues.push(markOptional(defineIssueGroup({
|
|
639
1339
|
message: buildErrorMessageForAttribute(String(pathRelative)),
|
|
640
|
-
|
|
1340
|
+
data: { name: String(pathRelative) },
|
|
641
1341
|
path: keyParts,
|
|
642
1342
|
issues: childIssues
|
|
643
|
-
}));
|
|
1343
|
+
})));
|
|
644
1344
|
else issues.push(...childIssues);
|
|
645
1345
|
else issues.push(...childIssues);
|
|
646
1346
|
}
|
|
647
1347
|
/**
|
|
1348
|
+
* For `oneOf` containers, wrap the issues produced by a single branch
|
|
1349
|
+
* (slice from `branchStart` to the end of `issues`) into one sub-group
|
|
1350
|
+
* so per-branch identity is preserved in the final aggregate. Non-oneOf
|
|
1351
|
+
* containers leave the issue list untouched — they don't need branch
|
|
1352
|
+
* partitioning.
|
|
1353
|
+
*
|
|
1354
|
+
* The wrapping group's `path` is `[]` (the branch wraps everything
|
|
1355
|
+
* inside it; per-leaf paths are unchanged); `data.branch` is the
|
|
1356
|
+
* mount index; and `data.name` (when set) is the mount path so
|
|
1357
|
+
* consumers can label "branch X failed" without recomputing the
|
|
1358
|
+
* registration order.
|
|
1359
|
+
*/
|
|
1360
|
+
wrapBranchForOneOf(issues, branchStart, item, branchIndex) {
|
|
1361
|
+
if (!this.options.oneOf) return;
|
|
1362
|
+
const branchIssues = issues.splice(branchStart);
|
|
1363
|
+
const data = { branch: branchIndex };
|
|
1364
|
+
if (item.path) data.name = item.path;
|
|
1365
|
+
issues.push(defineIssueGroup({
|
|
1366
|
+
message: item.path ? `Branch "${item.path}" failed` : `Branch ${branchIndex} failed`,
|
|
1367
|
+
data,
|
|
1368
|
+
path: [],
|
|
1369
|
+
issues: branchIssues
|
|
1370
|
+
}));
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
648
1373
|
* Apply post-loop semantics: oneOf aggregation, error throw, defaults
|
|
649
1374
|
* fill, and flat-vs-nested output expansion.
|
|
650
1375
|
*/
|
|
651
1376
|
finalizeOutput(output, options, issues, errorCount, itemCount) {
|
|
652
1377
|
if (this.options.oneOf) {
|
|
653
|
-
if (itemCount > 0 && errorCount === itemCount) throw new ValidupError([
|
|
654
|
-
code: IssueCode.ONE_OF_FAILED,
|
|
655
|
-
message: "None of the branches succeeded",
|
|
656
|
-
issues,
|
|
657
|
-
path: options.path ? options.path : []
|
|
658
|
-
})]);
|
|
1378
|
+
if (itemCount > 0 && errorCount === itemCount) throw new ValidupError([buildOneOfFailedGroup(issues, { path: options.path ? options.path : [] })]);
|
|
659
1379
|
} else if (errorCount > 0) throw new ValidupError(issues);
|
|
660
1380
|
if (options.defaults) {
|
|
661
1381
|
const defaultKeys = Object.keys(options.defaults);
|
|
@@ -683,7 +1403,10 @@ var Container = class {
|
|
|
683
1403
|
};
|
|
684
1404
|
return {
|
|
685
1405
|
success: false,
|
|
686
|
-
error: new ValidupError(
|
|
1406
|
+
error: new ValidupError([defineIssueItem({
|
|
1407
|
+
path: [],
|
|
1408
|
+
message: typeof e === "string" && e.length > 0 ? e : `Non-Error throw: ${String(e)}`
|
|
1409
|
+
})])
|
|
687
1410
|
};
|
|
688
1411
|
}
|
|
689
1412
|
isItemGroupIncluded(item, group) {
|
|
@@ -797,6 +1520,66 @@ function defineSchema() {
|
|
|
797
1520
|
return new Builder({}, []);
|
|
798
1521
|
}
|
|
799
1522
|
//#endregion
|
|
800
|
-
|
|
1523
|
+
//#region src/cache/check.ts
|
|
1524
|
+
/**
|
|
1525
|
+
* Duck-typed guard for {@link IResultCache}. Avoids `instanceof`
|
|
1526
|
+
* checks so caches constructed from a different copy of the package
|
|
1527
|
+
* (workspaces with duplicated `validup` installs, adapter bundles)
|
|
1528
|
+
* still round-trip cleanly.
|
|
1529
|
+
*/
|
|
1530
|
+
function isResultCache(input) {
|
|
1531
|
+
if (!isObject(input)) return false;
|
|
1532
|
+
return typeof input.get === "function" && typeof input.set === "function" && typeof input.delete === "function" && typeof input.clear === "function";
|
|
1533
|
+
}
|
|
1534
|
+
//#endregion
|
|
1535
|
+
//#region src/cache/module.ts
|
|
1536
|
+
/**
|
|
1537
|
+
* Default in-memory {@link IResultCache} implementation.
|
|
1538
|
+
*
|
|
1539
|
+
* Backed by a two-level `Map`:
|
|
1540
|
+
* - outer key — Mount reference (opaque object)
|
|
1541
|
+
* - inner key — expanded path (string)
|
|
1542
|
+
*
|
|
1543
|
+
* `Map` is used for both levels (rather than a `WeakMap` on the outer)
|
|
1544
|
+
* so `clear()` is supported. Cache entries become unreachable when the
|
|
1545
|
+
* owning composable / caller drops its reference to the
|
|
1546
|
+
* `ResultCache` instance; in the typical `@validup/vue` flow that
|
|
1547
|
+
* happens on `onScopeDispose`, which lines up with component unmount.
|
|
1548
|
+
*
|
|
1549
|
+
* Snapshot equality (the "is this still valid?" check) is the run
|
|
1550
|
+
* loop's job — see `container/module.ts`. This class is dumb storage.
|
|
1551
|
+
*/
|
|
1552
|
+
var ResultCache = class {
|
|
1553
|
+
store;
|
|
1554
|
+
constructor() {
|
|
1555
|
+
this.store = /* @__PURE__ */ new Map();
|
|
1556
|
+
}
|
|
1557
|
+
get(mount, key) {
|
|
1558
|
+
return this.store.get(mount)?.get(key);
|
|
1559
|
+
}
|
|
1560
|
+
set(mount, key, entry) {
|
|
1561
|
+
let inner = this.store.get(mount);
|
|
1562
|
+
if (!inner) {
|
|
1563
|
+
inner = /* @__PURE__ */ new Map();
|
|
1564
|
+
this.store.set(mount, inner);
|
|
1565
|
+
}
|
|
1566
|
+
inner.set(key, entry);
|
|
1567
|
+
}
|
|
1568
|
+
delete(mount, key) {
|
|
1569
|
+
if (typeof key === "undefined") {
|
|
1570
|
+
this.store.delete(mount);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
const inner = this.store.get(mount);
|
|
1574
|
+
if (!inner) return;
|
|
1575
|
+
inner.delete(key);
|
|
1576
|
+
if (inner.size === 0) this.store.delete(mount);
|
|
1577
|
+
}
|
|
1578
|
+
clear() {
|
|
1579
|
+
this.store.clear();
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
//#endregion
|
|
1583
|
+
export { Builder, Container, GroupKey, IssueCode, OptionalValue, ResultCache, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, buildOneOfFailedGroup, compose, composeOneOf, createValidupError, defineIssueGroup, defineIssueItem, defineSchema, defineValidator, errorToIssues, flattenIssueGroups, flattenIssueItems, formatIssue, hasOwnProperty, interpolate, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isResultCache, isValidatorDescriptor, isValidupError, resolveDefaults, resolvePathFilter, stringifyPath };
|
|
801
1584
|
|
|
802
1585
|
//# sourceMappingURL=index.mjs.map
|