validup 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,474 +1,802 @@
1
- import { distinctArray } from 'smob';
2
- import { arrayToPath, expandPath, pathToArray, getPathValue, setPathValue } from 'pathtrace';
3
-
1
+ import { distinctArray } from "smob";
2
+ import { arrayToPath, expandPath, getPathValue, pathToArray, setPathValue } from "pathtrace";
3
+ import { BaseError, interpolate, interpolate as interpolate$1 } from "@ebec/core";
4
+ //#region src/helpers/defaults.ts
5
+ /**
6
+ * Slice a parent `defaults` map down to entries that target paths inside a
7
+ * single nested container mount, with the mount-key prefix stripped so the
8
+ * child sees them as local keys. Exact-key matches (the default targets the
9
+ * mount root itself) are skipped — the parent's post-loop fill handles those
10
+ * once the child has returned, since the child is run with `flat: true` and
11
+ * cannot address its own root.
12
+ */
13
+ function resolveDefaults(defaults, key) {
14
+ if (typeof defaults === "undefined") return;
15
+ if (key.length === 0) return defaults;
16
+ const output = {};
17
+ let matched = false;
18
+ const keys = Object.keys(defaults);
19
+ for (const k of keys) if (k.startsWith(`${key}.`)) {
20
+ output[k.slice(key.length + 1)] = defaults[k];
21
+ matched = true;
22
+ }
23
+ return matched ? output : void 0;
24
+ }
25
+ //#endregion
26
+ //#region src/helpers/error.ts
4
27
  function buildErrorMessageForAttribute(key) {
5
- return `Property ${String(key)} is invalid`;
28
+ return `Property ${String(key)} is invalid`;
6
29
  }
7
30
  function buildErrorMessageForAttributes(input) {
8
- let names;
9
- if (Array.isArray(input)) {
10
- names = distinctArray(input);
11
- } else {
12
- names = Object.keys(input);
13
- }
14
- if (names.length === 0) {
15
- return 'Properties are invalid';
16
- }
17
- if (names.length > 1) {
18
- return `Properties ${names.join(', ')} are invalid.`;
19
- }
20
- return buildErrorMessageForAttribute(names[0]);
31
+ let names;
32
+ if (Array.isArray(input)) names = distinctArray(input);
33
+ else names = Object.keys(input);
34
+ if (names.length === 0) return "Properties are invalid";
35
+ if (names.length > 1) return `Properties ${names.join(", ")} are invalid.`;
36
+ return buildErrorMessageForAttribute(names[0]);
21
37
  }
22
-
23
- /*
24
- * Copyright (c) 2024.
25
- * Author Peter Placzek (tada5hi)
26
- * For the full copyright and license information,
27
- * view the LICENSE file that was distributed with this source code.
28
- */ var GroupKey = /*#__PURE__*/ function(GroupKey) {
29
- GroupKey["WILDCARD"] = "*";
30
- return GroupKey;
38
+ //#endregion
39
+ //#region src/constants.ts
40
+ let GroupKey = /* @__PURE__ */ function(GroupKey) {
41
+ GroupKey["WILDCARD"] = "*";
42
+ return GroupKey;
31
43
  }({});
32
- var OptionalValue = /*#__PURE__*/ function(OptionalValue) {
33
- /**
34
- * value: undefined
35
- */ OptionalValue["UNDEFINED"] = "undefined";
36
- /**
37
- * value: null & undefined
38
- */ OptionalValue["NULL"] = "null";
39
- /**
40
- * value: empty string, false, 0
41
- */ OptionalValue["FALSY"] = "falsy";
42
- return OptionalValue;
44
+ let OptionalValue = /* @__PURE__ */ function(OptionalValue) {
45
+ /**
46
+ * value: undefined
47
+ */
48
+ OptionalValue["UNDEFINED"] = "undefined";
49
+ /**
50
+ * value: null & undefined
51
+ */
52
+ OptionalValue["NULL"] = "null";
53
+ /**
54
+ * value: empty string, false, 0
55
+ */
56
+ OptionalValue["FALSY"] = "falsy";
57
+ return OptionalValue;
43
58
  }({});
44
-
59
+ //#endregion
60
+ //#region src/helpers/optional-value.ts
45
61
  /**
46
- * Check if input value (type of) satisfies optional value type constraint.
47
- *
48
- * @param value
49
- * @param optionalValue
50
- */ function isOptionalValue(value, optionalValue) {
51
- const optionValueNormalized = optionalValue || OptionalValue.UNDEFINED;
52
- if (optionValueNormalized === OptionalValue.NULL) {
53
- return value === null || typeof value === 'undefined';
54
- }
55
- if (optionValueNormalized === OptionalValue.UNDEFINED) {
56
- return typeof value === 'undefined';
57
- }
58
- return !value;
62
+ * Check if input value (type of) satisfies optional value type constraint.
63
+ *
64
+ * @param value
65
+ * @param optionalValue
66
+ */
67
+ function isOptionalValue(value, optionalValue) {
68
+ const optionValueNormalized = optionalValue || "undefined";
69
+ if (optionValueNormalized === "null") return value === null || typeof value === "undefined";
70
+ if (optionValueNormalized === "undefined") return typeof value === "undefined";
71
+ return !value;
59
72
  }
60
-
73
+ //#endregion
74
+ //#region src/helpers/path-filter.ts
61
75
  /**
62
- * Stringify path array to string.
63
- *
64
- * @param input
65
- */ function stringifyPath(input) {
66
- return arrayToPath(input);
76
+ * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's
77
+ * (already-expanded) local `key`. Returns whether to skip the item, plus the
78
+ * filter sub-lists to forward into a child container — with the parent prefix
79
+ * stripped so the child can match purely against its own local keys.
80
+ *
81
+ * Semantics:
82
+ * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so
83
+ * filters are forwarded verbatim.
84
+ * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.
85
+ * - Prefix match (`<key>.…`) only descends into container mounts; leaf
86
+ * validators with deeper-target filters fall through (skipped for include,
87
+ * kept for exclude).
88
+ */
89
+ function resolvePathFilter(pathsToInclude, pathsToExclude, key, isContainer) {
90
+ if (key.length === 0) return {
91
+ skip: false,
92
+ pathsToInclude,
93
+ pathsToExclude
94
+ };
95
+ let includeForward;
96
+ if (typeof pathsToInclude !== "undefined") {
97
+ let exact = false;
98
+ const stripped = [];
99
+ for (const path of pathsToInclude) if (path === key) exact = true;
100
+ else if (isContainer && path.startsWith(`${key}.`)) stripped.push(path.slice(key.length + 1));
101
+ if (exact) includeForward = void 0;
102
+ else if (stripped.length > 0) includeForward = stripped;
103
+ else return {
104
+ skip: true,
105
+ pathsToInclude: void 0,
106
+ pathsToExclude: void 0
107
+ };
108
+ }
109
+ let excludeForward;
110
+ if (typeof pathsToExclude !== "undefined") {
111
+ const stripped = [];
112
+ for (const path of pathsToExclude) {
113
+ if (path === key) return {
114
+ skip: true,
115
+ pathsToInclude: void 0,
116
+ pathsToExclude: void 0
117
+ };
118
+ if (isContainer && path.startsWith(`${key}.`)) stripped.push(path.slice(key.length + 1));
119
+ }
120
+ if (stripped.length > 0) excludeForward = stripped;
121
+ }
122
+ return {
123
+ skip: false,
124
+ pathsToInclude: includeForward,
125
+ pathsToExclude: excludeForward
126
+ };
67
127
  }
68
-
69
- class ValidupError extends Error {
70
- constructor(issues = []){
71
- const paths = issues.map((issue)=>stringifyPath(issue.path));
72
- super(buildErrorMessageForAttributes(paths));
73
- this.issues = issues;
74
- }
128
+ //#endregion
129
+ //#region src/helpers/path-stringify.ts
130
+ /**
131
+ * Stringify path array to string.
132
+ *
133
+ * @param input
134
+ */
135
+ function stringifyPath(input) {
136
+ return arrayToPath(input);
75
137
  }
76
-
77
- /*
78
- * Copyright (c) 2024.
79
- * Author Peter Placzek (tada5hi)
80
- * For the full copyright and license information,
81
- * view the LICENSE file that was distributed with this source code.
82
- */ // eslint-disable-next-line @typescript-eslint/ban-types
138
+ //#endregion
139
+ //#region src/error/base.ts
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
83
156
  function hasOwnProperty(obj, prop) {
84
- return Object.prototype.hasOwnProperty.call(obj, prop);
157
+ return Object.prototype.hasOwnProperty.call(obj, prop);
85
158
  }
86
-
87
- /*
88
- * Copyright (c) 2024.
89
- * Author Peter Placzek (tada5hi)
90
- * For the full copyright and license information,
91
- * view the LICENSE file that was distributed with this source code.
92
- */ function isObject(input) {
93
- return !!input && typeof input === 'object' && !Array.isArray(input);
159
+ //#endregion
160
+ //#region src/utils/object.ts
161
+ function isObject(input) {
162
+ return !!input && typeof input === "object" && !Array.isArray(input);
94
163
  }
95
-
164
+ //#endregion
165
+ //#region src/issue/check.ts
96
166
  function isIssuePath(input) {
97
- if (!Array.isArray(input)) {
98
- return false;
99
- }
100
- return input.every((el)=>typeof el === 'string' || typeof el === 'number' || typeof el === 'symbol');
167
+ if (!Array.isArray(input)) return false;
168
+ return input.every((el) => typeof el === "string" || typeof el === "number" || typeof el === "symbol");
101
169
  }
102
170
  function isBaseIssue(input) {
103
- if (!isObject(input)) {
104
- return false;
105
- }
106
- if (typeof input.message !== 'string') {
107
- return false;
108
- }
109
- if (!isIssuePath(input.path)) {
110
- return false;
111
- }
112
- return typeof input.meta === 'undefined' || isObject(input.meta);
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);
113
175
  }
114
176
  function isIssueItem(input) {
115
- if (!isBaseIssue(input)) {
116
- return false;
117
- }
118
- if (input.type !== 'item') {
119
- return false;
120
- }
121
- return typeof input.code === 'string';
177
+ if (!isBaseIssue(input)) return false;
178
+ if (input.type !== "item") return false;
179
+ return typeof input.code === "string";
122
180
  }
123
181
  function isIssueGroup(input) {
124
- if (!isBaseIssue(input)) {
125
- return false;
126
- }
127
- if (input.type !== 'group') {
128
- return false;
129
- }
130
- return Array.isArray(input.issues) && input.issues.every((issue)=>isIssueItem(issue) || isIssueGroup(issue));
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));
131
185
  }
132
186
  function isIssue(input) {
133
- return isIssueGroup(input) || isIssueItem(input);
187
+ return isIssueGroup(input) || isIssueItem(input);
134
188
  }
135
-
136
- /*
137
- * Copyright (c) 2026.
138
- * Author Peter Placzek (tada5hi)
139
- * For the full copyright and license information,
140
- * view the LICENSE file that was distributed with this source code.
141
- */ var IssueCode = /*#__PURE__*/ function(IssueCode) {
142
- IssueCode["VALUE_INVALID"] = "value_invalid";
143
- IssueCode["ONE_OF_FAILED"] = "one_of_failed";
144
- return IssueCode;
145
- }({});
146
-
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
147
197
  function defineIssueItem(data) {
148
- return {
149
- type: 'item',
150
- ...data,
151
- code: IssueCode.VALUE_INVALID || data.code
152
- };
198
+ return {
199
+ type: "item",
200
+ ...data,
201
+ code: data.code || IssueCode.VALUE_INVALID
202
+ };
153
203
  }
154
204
  function defineIssueGroup(data) {
155
- return {
156
- type: 'group',
157
- ...data
158
- };
205
+ return {
206
+ type: "group",
207
+ ...data
208
+ };
159
209
  }
160
-
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
228
+ /**
229
+ * Render an issue's user-facing message.
230
+ *
231
+ * Resolution order:
232
+ * 1. If `templates[code]` exists, return `interpolate(template, issue.params)`.
233
+ * 2. Else return `issue.message` (the default English rendering set at
234
+ * construction time).
235
+ * 3. Else return `fallback`.
236
+ */
237
+ function formatIssue(issue, templates, fallback = "") {
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
161
247
  function isError(input) {
162
- if (!isObject(input)) {
163
- return false;
164
- }
165
- return typeof input.message === 'string';
248
+ if (input instanceof Error) return true;
249
+ if (!isObject(input)) return false;
250
+ return typeof input.message === "string" && typeof input.name === "string";
166
251
  }
167
252
  function isValidupError(error) {
168
- if (!isError(error)) {
169
- return false;
170
- }
171
- if (error instanceof ValidupError) {
172
- return true;
173
- }
174
- if (!hasOwnProperty(error, 'issues')) {
175
- return false;
176
- }
177
- return Array.isArray(error.issues) && error.issues.every((issue)=>isIssue(issue));
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));
178
257
  }
179
-
258
+ //#endregion
259
+ //#region src/container/check.ts
180
260
  function isContainer(input) {
181
- return isObject(input) && typeof input.run === 'function' && typeof input.safeRun === 'function';
261
+ return isObject(input) && typeof input.run === "function" && typeof input.safeRun === "function";
182
262
  }
183
-
184
- class Container {
185
- mount(...args) {
186
- if (args.length < 1) {
187
- throw new SyntaxError('The mount method requires at least one argument');
188
- }
189
- let path;
190
- let data;
191
- let dataIsContainer = false;
192
- let options = {};
193
- for(let i = 0; i < args.length; i++){
194
- const arg = args[i];
195
- if (typeof arg === 'string') {
196
- path = arg;
197
- continue;
198
- }
199
- if (typeof arg === 'function') {
200
- data = arg;
201
- continue;
202
- }
203
- if (isContainer(arg)) {
204
- data = arg;
205
- dataIsContainer = true;
206
- continue;
207
- }
208
- if (isObject(arg)) {
209
- options = args[i];
210
- }
211
- }
212
- if (!dataIsContainer && (typeof path === 'undefined' || path.length === 0)) {
213
- throw new SyntaxError('Only a container can be mounted without a key.');
214
- }
215
- if (typeof data === 'undefined') {
216
- throw new SyntaxError('No container/validator could be extracted from the fn arguments.');
217
- }
218
- if (isContainer(data)) {
219
- this.items.push({
220
- options,
221
- data,
222
- path,
223
- type: 'container'
224
- });
225
- return;
226
- }
227
- this.items.push({
228
- options,
229
- data,
230
- path,
231
- type: 'validator'
232
- });
233
- }
234
- // ----------------------------------------------
235
- /**
236
- * @throws ValidupError
237
- *
238
- * @param data
239
- * @param options
240
- */ async run(data = {}, options = {}) {
241
- let pathsToInclude;
242
- if (options.pathsToInclude) {
243
- pathsToInclude = options.pathsToInclude;
244
- } else if (this.options.pathsToInclude) {
245
- pathsToInclude = this.options.pathsToInclude;
246
- }
247
- let pathsToExclude;
248
- if (options.pathsToExclude) {
249
- pathsToExclude = options.pathsToExclude;
250
- } else if (this.options.pathsToInclude) {
251
- pathsToExclude = this.options.pathsToExclude;
252
- }
253
- const output = {};
254
- const issues = [];
255
- let itemCount = 0;
256
- let errorCount = 0;
257
- for(let i = 0; i < this.items.length; i++){
258
- const item = this.items[i];
259
- if (!this.isItemGroupIncluded(item, options.group)) {
260
- continue;
261
- }
262
- let pathCount = 0;
263
- let pathFailed = false;
264
- let keys;
265
- if (item.path) {
266
- keys = expandPath(data, item.path);
267
- } else {
268
- keys = [
269
- ''
270
- ];
271
- }
272
- for(let j = 0; j < keys.length; j++){
273
- const key = keys[j];
274
- const keyParts = key ? pathToArray(key) : [];
275
- const pathRelative = keyParts.at(-1);
276
- const pathAbsolute = [
277
- ...options.path ? options.path : [],
278
- ...keyParts
279
- ];
280
- let value;
281
- if (key.length > 0) {
282
- value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
283
- } else {
284
- value = data;
285
- }
286
- if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(key) === -1) {
287
- continue;
288
- }
289
- if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(key) !== -1) {
290
- continue;
291
- }
292
- try {
293
- if (item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
294
- if (item.options.optionalInclude) {
295
- output[key] = value;
296
- }
297
- } else if (item.type === 'container') {
298
- const tmp = await item.data.run(isObject(value) ? value : {}, {
299
- group: options.group,
300
- flat: true,
301
- path: pathAbsolute,
302
- pathsToInclude: options.pathsToInclude
303
- });
304
- const tmpKeys = Object.keys(tmp);
305
- for(let k = 0; k < tmpKeys.length; k++){
306
- output[this.mergePaths(key, tmpKeys[k])] = tmp[tmpKeys[k]];
307
- }
308
- } else if (item.type === 'validator') {
309
- output[key] = await item.data({
310
- key,
311
- path: pathAbsolute,
312
- value,
313
- data,
314
- group: options.group
315
- });
316
- }
317
- } catch (e) {
318
- const childIssues = [];
319
- if (isValidupError(e)) {
320
- for(let i = 0; i < e.issues.length; i++){
321
- const issue = e.issues[i];
322
- childIssues.push({
323
- ...issue,
324
- path: [
325
- ...keyParts,
326
- ...issue.path || []
327
- ]
328
- });
329
- }
330
- } else if (isError(e)) {
331
- childIssues.push(defineIssueItem({
332
- path: keyParts,
333
- message: e.message
334
- }));
335
- }
336
- if (pathRelative) {
337
- if (item.type === 'container' || childIssues.length > 1) {
338
- const group = defineIssueGroup({
339
- message: buildErrorMessageForAttribute(pathRelative),
340
- path: keyParts,
341
- issues: childIssues
342
- });
343
- issues.push(group);
344
- } else {
345
- issues.push(...childIssues);
346
- }
347
- } else {
348
- issues.push(...childIssues);
349
- }
350
- pathFailed = true;
351
- }
352
- pathCount++;
353
- }
354
- if (pathCount > 0) {
355
- itemCount++;
356
- if (pathFailed) {
357
- errorCount++;
358
- }
359
- }
360
- }
361
- if (this.options.oneOf) {
362
- if (errorCount === itemCount) {
363
- const group = defineIssueGroup({
364
- code: IssueCode.ONE_OF_FAILED,
365
- message: 'None of the branches succeeded',
366
- issues,
367
- path: options.path ? options.path : []
368
- });
369
- throw new ValidupError([
370
- group
371
- ]);
372
- }
373
- } else if (errorCount > 0) {
374
- throw new ValidupError(issues);
375
- }
376
- if (options.defaults) {
377
- const defaultKeys = Object.keys(options.defaults);
378
- for(let i = 0; i < defaultKeys.length; i++){
379
- if (!hasOwnProperty(output, defaultKeys[i]) || typeof output[defaultKeys[i]] === 'undefined') {
380
- output[defaultKeys[i]] = options.defaults[defaultKeys[i]];
381
- }
382
- }
383
- }
384
- if (options.flat) {
385
- return output;
386
- }
387
- const temp = {};
388
- const keys = Object.keys(output);
389
- for(let i = 0; i < keys.length; i++){
390
- setPathValue(temp, keys[i], output[keys[i]]);
391
- }
392
- return temp;
393
- }
394
- async safeRun(input = {}, options = {}) {
395
- try {
396
- const data = await this.run(input, options);
397
- return {
398
- success: true,
399
- data
400
- };
401
- } catch (e) {
402
- if (isValidupError(e)) {
403
- return {
404
- success: false,
405
- error: e
406
- };
407
- }
408
- if (isError(e)) {
409
- return {
410
- success: false,
411
- error: new ValidupError([
412
- defineIssueItem({
413
- path: [],
414
- message: e.message
415
- })
416
- ])
417
- };
418
- }
419
- return {
420
- success: false,
421
- error: new ValidupError()
422
- };
423
- }
424
- }
425
- isItemGroupIncluded(item, group) {
426
- if (group === GroupKey.WILDCARD) {
427
- return true;
428
- }
429
- if (item.options.group) {
430
- if (Array.isArray(item.options.group)) {
431
- if (item.options.group.indexOf(GroupKey.WILDCARD) !== -1) {
432
- return true;
433
- }
434
- if (group && item.options.group.indexOf(group) !== -1) {
435
- return true;
436
- }
437
- } else {
438
- if (item.options.group === GroupKey.WILDCARD) {
439
- return true;
440
- }
441
- if (item.options.group === group) {
442
- return true;
443
- }
444
- }
445
- return false;
446
- }
447
- return true;
448
- }
449
- mergePaths(...args) {
450
- let output = '';
451
- for(let i = 0; i < args.length; i++){
452
- const arg = args[i];
453
- if (!arg || arg.length === 0) {
454
- continue;
455
- }
456
- if (arg.at(0) === '.') {
457
- output += arg;
458
- } else {
459
- output += output.length > 0 ? `.${arg}` : arg;
460
- }
461
- }
462
- return output;
463
- }
464
- initialize() {}
465
- // ----------------------------------------------
466
- constructor(options = {}){
467
- this.options = options;
468
- this.items = [];
469
- this.initialize();
470
- }
263
+ //#endregion
264
+ //#region src/container/run-sync-violation.ts
265
+ /**
266
+ * Thrown by `Container.runSync` when a validator returns a Promise or a
267
+ * nested container does not implement `runSync`. Marked separately from
268
+ * generic `Error` so the per-mount catch can re-throw it instead of folding
269
+ * it into the issue list (otherwise users would get "Property X is invalid"
270
+ * instead of the structural diagnostic).
271
+ *
272
+ * Internal — not exported from the package barrel.
273
+ */
274
+ var RunSyncViolationError = class extends Error {
275
+ name = "RunSyncViolationError";
276
+ };
277
+ /**
278
+ * Duck-typed check — robust against `instanceof` mismatches when a duplicate
279
+ * copy of the package exists in the dependency tree, or when the throw
280
+ * crosses a realm boundary. Mirrors the `isValidupError` pattern.
281
+ */
282
+ function isRunSyncViolation(e) {
283
+ if (e instanceof RunSyncViolationError) return true;
284
+ return typeof e === "object" && e !== null && e.name === "RunSyncViolationError";
285
+ }
286
+ //#endregion
287
+ //#region src/container/module.ts
288
+ var Container = class {
289
+ options;
290
+ items;
291
+ constructor(options = {}) {
292
+ this.options = options;
293
+ this.items = [];
294
+ this.initialize();
295
+ }
296
+ mount(...args) {
297
+ if (args.length < 1) throw new SyntaxError("The mount method requires at least one argument");
298
+ let path;
299
+ let data;
300
+ let dataIsContainer = false;
301
+ let options = {};
302
+ for (const arg of args) {
303
+ if (typeof arg === "string") {
304
+ path = arg;
305
+ continue;
306
+ }
307
+ if (typeof arg === "function") {
308
+ data = arg;
309
+ continue;
310
+ }
311
+ if (isContainer(arg)) {
312
+ data = arg;
313
+ dataIsContainer = true;
314
+ continue;
315
+ }
316
+ if (isObject(arg)) options = arg;
317
+ }
318
+ if (!dataIsContainer && (typeof path === "undefined" || path.length === 0)) throw new SyntaxError("Only a container can be mounted without a key.");
319
+ if (typeof data === "undefined") throw new SyntaxError("No container/validator could be extracted from the fn arguments.");
320
+ if (isContainer(data)) {
321
+ this.items.push({
322
+ options,
323
+ data,
324
+ path,
325
+ type: "container"
326
+ });
327
+ return;
328
+ }
329
+ this.items.push({
330
+ options,
331
+ data,
332
+ path,
333
+ type: "validator"
334
+ });
335
+ }
336
+ /**
337
+ * @throws ValidupError
338
+ *
339
+ * @param data
340
+ * @param options
341
+ */
342
+ async run(data = {}, options = {}) {
343
+ if (options.parallel) return this.runParallel(data, options);
344
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
345
+ const output = {};
346
+ const issues = [];
347
+ let itemCount = 0;
348
+ let errorCount = 0;
349
+ for (let i = 0; i < this.items.length; i++) {
350
+ options.signal?.throwIfAborted();
351
+ const item = this.items[i];
352
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
353
+ let pathCount = 0;
354
+ let pathFailed = false;
355
+ const keys = item.path ? expandPath(data, item.path) : [""];
356
+ for (const key of keys) {
357
+ const keyParts = key ? pathToArray(key) : [];
358
+ const pathRelative = keyParts.at(-1);
359
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
360
+ let value;
361
+ if (key.length > 0) value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
362
+ else value = data;
363
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
364
+ if (filter.skip) continue;
365
+ try {
366
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
367
+ if (item.options.optionalInclude) output[key] = value;
368
+ } else if (item.type === "container") {
369
+ const tmp = await item.data.run(isObject(value) ? value : {}, {
370
+ group: options.group,
371
+ flat: true,
372
+ path: pathAbsolute,
373
+ pathsToInclude: filter.pathsToInclude,
374
+ pathsToExclude: filter.pathsToExclude,
375
+ defaults: resolveDefaults(options.defaults, key),
376
+ context: options.context,
377
+ signal: options.signal
378
+ });
379
+ const tmpKeys = Object.keys(tmp);
380
+ for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
381
+ } else if (item.type === "validator") output[key] = await item.data({
382
+ key,
383
+ path: pathAbsolute,
384
+ value,
385
+ data,
386
+ group: options.group,
387
+ context: options.context,
388
+ signal: options.signal
389
+ });
390
+ } catch (e) {
391
+ this.recordMountError(e, item, keyParts, pathRelative, issues, options.signal);
392
+ pathFailed = true;
393
+ }
394
+ pathCount++;
395
+ }
396
+ if (pathCount > 0) {
397
+ itemCount++;
398
+ if (pathFailed) errorCount++;
399
+ }
400
+ }
401
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
402
+ }
403
+ /**
404
+ * Parallel-execution variant of `run()`. All mounts kick off their
405
+ * promises eagerly and the results are merged after `Promise.allSettled`.
406
+ * See `ContainerRunOptions.parallel` for the trade-off note.
407
+ */
408
+ async runParallel(data, options) {
409
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
410
+ const output = {};
411
+ const issues = [];
412
+ const itemGroups = [];
413
+ for (let i = 0; i < this.items.length; i++) {
414
+ options.signal?.throwIfAborted();
415
+ const item = this.items[i];
416
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
417
+ const tasks = [];
418
+ let syncPathCount = 0;
419
+ const keys = item.path ? expandPath(data, item.path) : [""];
420
+ for (const key of keys) {
421
+ const keyParts = key ? pathToArray(key) : [];
422
+ const pathRelative = keyParts.at(-1);
423
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
424
+ let value;
425
+ if (key.length > 0) value = getPathValue(data, key);
426
+ else value = data;
427
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
428
+ if (filter.skip) continue;
429
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
430
+ if (item.options.optionalInclude) output[key] = value;
431
+ syncPathCount++;
432
+ continue;
433
+ }
434
+ let promise;
435
+ if (item.type === "container") promise = item.data.run(isObject(value) ? value : {}, {
436
+ group: options.group,
437
+ flat: true,
438
+ path: pathAbsolute,
439
+ pathsToInclude: filter.pathsToInclude,
440
+ pathsToExclude: filter.pathsToExclude,
441
+ defaults: resolveDefaults(options.defaults, key),
442
+ context: options.context,
443
+ signal: options.signal,
444
+ parallel: true
445
+ });
446
+ else {
447
+ const itemData = item.data;
448
+ promise = (async () => itemData({
449
+ key,
450
+ path: pathAbsolute,
451
+ value,
452
+ data,
453
+ group: options.group,
454
+ context: options.context,
455
+ signal: options.signal
456
+ }))();
457
+ }
458
+ tasks.push({
459
+ key,
460
+ keyParts,
461
+ pathRelative,
462
+ promise,
463
+ kind: item.type
464
+ });
465
+ }
466
+ if (tasks.length > 0 || syncPathCount > 0) itemGroups.push({
467
+ item,
468
+ tasks,
469
+ syncPathCount
470
+ });
471
+ }
472
+ const settledByGroup = await Promise.all(itemGroups.map((group) => Promise.allSettled(group.tasks.map((t) => t.promise))));
473
+ options.signal?.throwIfAborted();
474
+ let itemCount = 0;
475
+ let errorCount = 0;
476
+ for (const [i, { item, tasks, syncPathCount }] of itemGroups.entries()) {
477
+ const settled = settledByGroup[i];
478
+ let pathFailed = false;
479
+ for (const [j, task] of tasks.entries()) {
480
+ const result = settled[j];
481
+ if (result.status === "fulfilled") if (task.kind === "container") {
482
+ const tmp = result.value;
483
+ const tmpKeys = Object.keys(tmp);
484
+ for (const tmpKey of tmpKeys) output[this.mergePaths(task.key, tmpKey)] = tmp[tmpKey];
485
+ } else output[task.key] = result.value;
486
+ else {
487
+ this.recordMountError(result.reason, item, task.keyParts, task.pathRelative, issues, options.signal);
488
+ pathFailed = true;
489
+ }
490
+ }
491
+ if (tasks.length + syncPathCount > 0) {
492
+ itemCount++;
493
+ if (pathFailed) errorCount++;
494
+ }
495
+ }
496
+ options.signal?.throwIfAborted();
497
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
498
+ }
499
+ async safeRun(input = {}, options = {}) {
500
+ try {
501
+ return {
502
+ success: true,
503
+ data: await this.run(input, options)
504
+ };
505
+ } catch (e) {
506
+ return this.wrapSafeRunError(e, options);
507
+ }
508
+ }
509
+ /**
510
+ * @throws ValidupError
511
+ *
512
+ * Synchronous variant of `run()`. Throws synchronously if any validator
513
+ * returns a thenable, or if a nested container does not implement
514
+ * `runSync`. Use it for purely synchronous validator graphs where the
515
+ * microtask overhead of `await` per mount matters (e.g. driving a
516
+ * reactive UI without a `pending` flicker).
517
+ */
518
+ runSync(data = {}, options = {}) {
519
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
520
+ const output = {};
521
+ const issues = [];
522
+ let itemCount = 0;
523
+ let errorCount = 0;
524
+ for (let i = 0; i < this.items.length; i++) {
525
+ options.signal?.throwIfAborted();
526
+ const item = this.items[i];
527
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
528
+ let pathCount = 0;
529
+ let pathFailed = false;
530
+ const keys = item.path ? expandPath(data, item.path) : [""];
531
+ for (const key of keys) {
532
+ const keyParts = key ? pathToArray(key) : [];
533
+ const pathRelative = keyParts.at(-1);
534
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
535
+ let value;
536
+ if (key.length > 0) value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
537
+ else value = data;
538
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
539
+ if (filter.skip) continue;
540
+ try {
541
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
542
+ if (item.options.optionalInclude) output[key] = value;
543
+ } else if (item.type === "container") {
544
+ const childRunSync = item.data.runSync;
545
+ if (typeof childRunSync !== "function") throw new RunSyncViolationError(`runSync: nested container at "${key || "<root>"}" does not implement runSync`);
546
+ const tmp = childRunSync.call(item.data, isObject(value) ? value : {}, {
547
+ group: options.group,
548
+ flat: true,
549
+ path: pathAbsolute,
550
+ pathsToInclude: filter.pathsToInclude,
551
+ pathsToExclude: filter.pathsToExclude,
552
+ defaults: resolveDefaults(options.defaults, key),
553
+ context: options.context,
554
+ signal: options.signal
555
+ });
556
+ const tmpKeys = Object.keys(tmp);
557
+ for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
558
+ } else if (item.type === "validator") {
559
+ const result = item.data({
560
+ key,
561
+ path: pathAbsolute,
562
+ value,
563
+ data,
564
+ group: options.group,
565
+ context: options.context,
566
+ signal: options.signal
567
+ });
568
+ if (result !== null && typeof result === "object" && typeof result.then === "function") throw new RunSyncViolationError(`runSync: validator at "${key || "<root>"}" returned a Promise`);
569
+ output[key] = result;
570
+ }
571
+ } catch (e) {
572
+ this.recordMountError(e, item, keyParts, pathRelative, issues, options.signal);
573
+ pathFailed = true;
574
+ }
575
+ pathCount++;
576
+ }
577
+ if (pathCount > 0) {
578
+ itemCount++;
579
+ if (pathFailed) errorCount++;
580
+ }
581
+ }
582
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
583
+ }
584
+ safeRunSync(input = {}, options = {}) {
585
+ try {
586
+ return {
587
+ success: true,
588
+ data: this.runSync(input, options)
589
+ };
590
+ } catch (e) {
591
+ return this.wrapSafeRunError(e, options);
592
+ }
593
+ }
594
+ resolveContainerFilters(options) {
595
+ let pathsToInclude;
596
+ if (options.pathsToInclude) pathsToInclude = options.pathsToInclude;
597
+ else if (this.options.pathsToInclude) pathsToInclude = this.options.pathsToInclude;
598
+ let pathsToExclude;
599
+ if (options.pathsToExclude) pathsToExclude = options.pathsToExclude;
600
+ else if (this.options.pathsToExclude) pathsToExclude = this.options.pathsToExclude;
601
+ return {
602
+ pathsToInclude,
603
+ pathsToExclude
604
+ };
605
+ }
606
+ /**
607
+ * Prepend `keyParts` to a child issue's `path` and — when the child is
608
+ * an `IssueGroup` — recurse into its nested issues so every leaf carries
609
+ * the parent prefix. Without recursion, a child container that already
610
+ * wrapped its own multi-issue mount in a group (or a `oneOf` child) would
611
+ * surface inner items with paths missing the parent segment, breaking
612
+ * downstream consumers that rely on `flattenIssueItems` for per-field
613
+ * lookup (e.g. `@validup/vue`).
614
+ */
615
+ prefixIssuePath(issue, keyParts) {
616
+ const prefixed = {
617
+ ...issue,
618
+ path: [...keyParts, ...issue.path || []]
619
+ };
620
+ if (prefixed.type === "group") prefixed.issues = prefixed.issues.map((nested) => this.prefixIssuePath(nested, keyParts));
621
+ return prefixed;
622
+ }
623
+ /**
624
+ * Translate a per-mount throw into accumulated `issues`. Re-throws when
625
+ * the run was aborted (signal-aware validators) so abort errors are not
626
+ * mangled into validation issues. `keyParts` is the current mount's
627
+ * expanded path (used to prepend to nested `ValidupError` issues).
628
+ */
629
+ recordMountError(e, item, keyParts, pathRelative, issues, signal) {
630
+ if (signal?.aborted) throw e;
631
+ if (isRunSyncViolation(e)) throw e;
632
+ const childIssues = [];
633
+ if (isValidupError(e)) for (let i = 0; i < e.issues.length; i++) childIssues.push(this.prefixIssuePath(e.issues[i], keyParts));
634
+ else if (isError(e)) childIssues.push(defineIssueItem({
635
+ path: keyParts,
636
+ message: e.message
637
+ }));
638
+ if (pathRelative) if (item.type === "container" || childIssues.length > 1) issues.push(defineIssueGroup({
639
+ message: buildErrorMessageForAttribute(String(pathRelative)),
640
+ params: { name: String(pathRelative) },
641
+ path: keyParts,
642
+ issues: childIssues
643
+ }));
644
+ else issues.push(...childIssues);
645
+ else issues.push(...childIssues);
646
+ }
647
+ /**
648
+ * Apply post-loop semantics: oneOf aggregation, error throw, defaults
649
+ * fill, and flat-vs-nested output expansion.
650
+ */
651
+ finalizeOutput(output, options, issues, errorCount, itemCount) {
652
+ if (this.options.oneOf) {
653
+ if (itemCount > 0 && errorCount === itemCount) throw new ValidupError([defineIssueGroup({
654
+ code: IssueCode.ONE_OF_FAILED,
655
+ message: "None of the branches succeeded",
656
+ issues,
657
+ path: options.path ? options.path : []
658
+ })]);
659
+ } else if (errorCount > 0) throw new ValidupError(issues);
660
+ if (options.defaults) {
661
+ const defaultKeys = Object.keys(options.defaults);
662
+ for (const defaultKey of defaultKeys) if (!hasOwnProperty(output, defaultKey) || typeof output[defaultKey] === "undefined") output[defaultKey] = options.defaults[defaultKey];
663
+ }
664
+ if (options.flat) return output;
665
+ const temp = {};
666
+ const keys = Object.keys(output);
667
+ for (const key of keys) setPathValue(temp, key, output[key]);
668
+ return temp;
669
+ }
670
+ wrapSafeRunError(e, options) {
671
+ if (options.signal?.aborted) throw e;
672
+ if (isRunSyncViolation(e)) throw e;
673
+ if (isValidupError(e)) return {
674
+ success: false,
675
+ error: e
676
+ };
677
+ if (isError(e)) return {
678
+ success: false,
679
+ error: new ValidupError([defineIssueItem({
680
+ path: [],
681
+ message: e.message
682
+ })])
683
+ };
684
+ return {
685
+ success: false,
686
+ error: new ValidupError()
687
+ };
688
+ }
689
+ isItemGroupIncluded(item, group) {
690
+ if (group === "*") return true;
691
+ if (item.options.group) {
692
+ if (Array.isArray(item.options.group)) {
693
+ if (item.options.group.includes("*")) return true;
694
+ if (group && item.options.group.includes(group)) return true;
695
+ } else {
696
+ if (item.options.group === "*") return true;
697
+ if (item.options.group === group) return true;
698
+ }
699
+ return false;
700
+ }
701
+ return true;
702
+ }
703
+ /**
704
+ * Join flat-output keys with `.` separators, preserving any pre-existing
705
+ * leading dot on the right-hand side. Note: keys containing a *literal*
706
+ * dot collide with the dotted-path syntax used for nested-output
707
+ * expansion (see `setPathValue` in `pathtrace`) and will produce
708
+ * ambiguous output when re-expanded — avoid mounting/returning such keys.
709
+ */
710
+ mergePaths(...args) {
711
+ let output = "";
712
+ for (const arg of args) {
713
+ if (!arg || arg.length === 0) continue;
714
+ if (arg.at(0) === ".") output += arg;
715
+ else output += output.length > 0 ? `.${arg}` : arg;
716
+ }
717
+ return output;
718
+ }
719
+ initialize() {}
720
+ };
721
+ //#endregion
722
+ //#region src/builder/module.ts
723
+ function isBuilder(value) {
724
+ return typeof value === "object" && value !== null && typeof value.build === "function" && typeof value.mount === "function";
725
+ }
726
+ var Builder = class Builder {
727
+ options;
728
+ steps;
729
+ constructor(options, steps) {
730
+ this.options = options;
731
+ this.steps = steps;
732
+ }
733
+ mount(key, ...rest) {
734
+ let options = {};
735
+ let target;
736
+ if (rest.length === 1) target = rest[0];
737
+ else {
738
+ options = rest[0];
739
+ target = rest[1];
740
+ }
741
+ let step;
742
+ if (isBuilder(target)) step = {
743
+ kind: "nest",
744
+ key,
745
+ child: target.build(),
746
+ options
747
+ };
748
+ else if (isContainer(target)) step = {
749
+ kind: "nest",
750
+ key,
751
+ child: target,
752
+ options
753
+ };
754
+ else step = {
755
+ kind: "validator",
756
+ key,
757
+ validator: target,
758
+ options
759
+ };
760
+ return new Builder(this.options, [...this.steps, step]);
761
+ }
762
+ oneOf() {
763
+ return new Builder({
764
+ ...this.options,
765
+ oneOf: true
766
+ }, this.steps);
767
+ }
768
+ pathsToInclude(...paths) {
769
+ return new Builder({
770
+ ...this.options,
771
+ pathsToInclude: [...this.options.pathsToInclude ?? [], ...paths]
772
+ }, this.steps);
773
+ }
774
+ pathsToExclude(...paths) {
775
+ return new Builder({
776
+ ...this.options,
777
+ pathsToExclude: [...this.options.pathsToExclude ?? [], ...paths]
778
+ }, this.steps);
779
+ }
780
+ build() {
781
+ const container = new Container(this.options);
782
+ for (const step of this.steps) if (step.kind === "nest") container.mount(step.key, step.options, step.child);
783
+ else container.mount(step.key, step.options, step.validator);
784
+ return container;
785
+ }
786
+ };
787
+ /**
788
+ * Entry point for the compile-time-typed schema builder. The accumulator
789
+ * starts at `{}` and grows as `.mount(...)` calls are chained;
790
+ * `.build()` returns a `Container<T, C>` whose `run()` reflects the
791
+ * accumulated shape.
792
+ *
793
+ * Pass the context type as the generic parameter to flow it through nested
794
+ * builders and validator factories: `defineSchema<MyContext>()`.
795
+ */
796
+ function defineSchema() {
797
+ return new Builder({}, []);
471
798
  }
799
+ //#endregion
800
+ export { Builder, Container, GroupKey, IssueCode, OptionalValue, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, defineIssueGroup, defineIssueItem, defineSchema, flattenIssueGroups, flattenIssueItems, formatIssue, hasOwnProperty, interpolate, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isValidupError, resolveDefaults, resolvePathFilter, stringifyPath };
472
801
 
473
- export { Container, GroupKey, IssueCode, OptionalValue, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, defineIssueGroup, defineIssueItem, hasOwnProperty, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isValidupError, stringifyPath };
474
- //# sourceMappingURL=index.mjs.map
802
+ //# sourceMappingURL=index.mjs.map