validup 0.1.10 → 0.2.1

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 CHANGED
@@ -88,11 +88,11 @@ console.log(output);
88
88
 
89
89
  ### Errors
90
90
 
91
- During the execution of a [validator](#validator), a ValidupValidatorError or ValidupNestedError can be thrown.
92
- A ValidupNestedError bundles multiple ValidupValidationErrors.
91
+ During the execution of a [validator](#validator), a ValidupError can be thrown.
92
+ An error can contain multiple issues.
93
93
 
94
- When the execution of a Container fails, the container will always throw a ValidupNestedError.
95
- Unknown errors will be converted to a ValidupValidatorError.
94
+ When the execution of a Container fails, the container will always throw a ValidupError.
95
+ Unknown errors will be converted.
96
96
 
97
97
  ### Mounting
98
98
 
@@ -149,23 +149,23 @@ type ValidatorContext = {
149
149
  /**
150
150
  * The expanded mount path in the current container.
151
151
  */
152
- path: string,
153
- /**
154
- * The unexpanded mount path in the current container.
155
- */
156
- pathRaw: string,
152
+ key: string,
153
+
157
154
  /**
158
155
  * The global mount path of the parent container.
159
156
  */
160
- pathAbsolute: string,
157
+ path: PropertyKey[],
158
+
161
159
  /**
162
160
  * The actual value, which should be validated.
163
161
  */
164
162
  value: unknown,
163
+
165
164
  /**
166
165
  * The input data of the current container.
167
166
  */
168
167
  data: Record<string, any>,
168
+
169
169
  /**
170
170
  * The group name for which the validator is executed.
171
171
  */
@@ -1,13 +1,19 @@
1
- import type { ObjectPropertyPathExtended, Validator } from '../types';
2
- import type { ContainerItem, ContainerMountOptions, ContainerOptions, ContainerRunOptions, IContainer } from './types';
1
+ import type { Path } from 'pathtrace';
2
+ import type { Validator } from '../types';
3
+ import type { ContainerOptions, ContainerRunOptions, IContainer, Mount, MountOptions } from './types';
3
4
  export declare class Container<T extends Record<string, any> = Record<string, any>> implements IContainer {
4
5
  protected options: ContainerOptions<T>;
5
- protected items: ContainerItem[];
6
+ protected items: Mount[];
6
7
  constructor(options?: ContainerOptions<T>);
7
8
  mount(container: IContainer): void;
8
- mount(options: ContainerMountOptions, container: IContainer): void;
9
- mount(key: ObjectPropertyPathExtended<T>, data: IContainer | Validator): void;
10
- mount(key: ObjectPropertyPathExtended<T>, options: ContainerMountOptions, data: IContainer | Validator): void;
9
+ mount(options: MountOptions, container: IContainer): void;
10
+ mount(key: Path<T> | (string & {}), data: IContainer | Validator): void;
11
+ mount(key: Path<T> | (string & {}), options: MountOptions, data: IContainer | Validator): void;
12
+ /**
13
+ * @throws ValidupError
14
+ * @param data
15
+ * @param options
16
+ */
11
17
  run(data?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<T>;
12
18
  private isItemGroupIncluded;
13
19
  private mergePaths;
@@ -1,5 +1,6 @@
1
+ import type { Path } from 'pathtrace';
1
2
  import type { OptionalValue } from '../constants';
2
- import type { ObjectLiteral, ObjectPropertyPath, Validator } from '../types';
3
+ import type { ObjectLiteral, Validator } from '../types';
3
4
  export type ContainerOptions<T> = {
4
5
  /**
5
6
  * Only one of the mounted container/validators must succeed.
@@ -10,20 +11,20 @@ export type ContainerOptions<T> = {
10
11
  * By default, all mounted containers/validators will
11
12
  * be considered for execution.
12
13
  */
13
- pathsToInclude?: ObjectPropertyPath<T>[];
14
+ pathsToInclude?: Path<T>[];
14
15
  /**
15
16
  * Exclude mounted paths on execution.
16
17
  * By default, all mounted containers/validators will
17
18
  * be considered for execution.
18
19
  */
19
- pathsToExclude?: ObjectPropertyPath<T>[];
20
+ pathsToExclude?: Path<T>[];
20
21
  };
21
22
  export type ContainerRunOptions<T extends Record<string, any> = Record<string, any>> = {
22
23
  /**
23
24
  * Default values for the container output.
24
25
  */
25
26
  defaults?: {
26
- [Key in ObjectPropertyPath<T>]: any;
27
+ [Key in Path<T>]: any;
27
28
  };
28
29
  /**
29
30
  * Group to execute.
@@ -36,21 +37,21 @@ export type ContainerRunOptions<T extends Record<string, any> = Record<string, a
36
37
  /**
37
38
  * Passed path from the parent container.
38
39
  */
39
- path?: string;
40
+ path?: PropertyKey[];
40
41
  /**
41
42
  * Limit mounted paths on execution.
42
43
  * By default, all mounted containers/validators will
43
44
  * be considered for execution.
44
45
  */
45
- pathsToInclude?: ObjectPropertyPath<T>[];
46
+ pathsToInclude?: Path<T>[];
46
47
  /**
47
48
  * Exclude mounted paths on execution.
48
49
  * By default, all mounted containers/validators will
49
50
  * be considered for execution.
50
51
  */
51
- pathsToExclude?: ObjectPropertyPath<T>[];
52
+ pathsToExclude?: Path<T>[];
52
53
  };
53
- export type ContainerMountOptions = {
54
+ export type MountOptions = {
54
55
  /**
55
56
  * Group(s) to execute.
56
57
  */
@@ -85,7 +86,16 @@ export interface IContainer<T extends ObjectLiteral = ObjectLiteral> {
85
86
  */
86
87
  run(data?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<T>;
87
88
  }
88
- export type ContainerItem = ContainerMountOptions & {
89
+ export type BaseMount = {
90
+ options: MountOptions;
89
91
  path?: string;
90
- data: Validator | IContainer;
91
92
  };
93
+ export type ContainerMount = BaseMount & {
94
+ type: 'container';
95
+ data: IContainer;
96
+ };
97
+ export type ValidatorMount = BaseMount & {
98
+ type: 'validator';
99
+ data: Validator;
100
+ };
101
+ export type Mount = ContainerMount | ValidatorMount;
@@ -0,0 +1,5 @@
1
+ import type { Issue } from '../issue';
2
+ export declare class ValidupError extends Error {
3
+ readonly issues: Issue[];
4
+ constructor(issues?: Issue[]);
5
+ }
@@ -0,0 +1,5 @@
1
+ import { ValidupError } from './base';
2
+ export declare function isError(input: unknown): input is Error & {
3
+ [key: string]: any;
4
+ };
5
+ export declare function isValidupError(error: unknown): error is ValidupError;
@@ -0,0 +1,2 @@
1
+ export * from './base';
2
+ export * from './check';
@@ -1,2 +1,2 @@
1
- export declare function buildErrorMessageForAttribute(key: string | number): string;
2
- export declare function buildErrorMessageForAttributes(input: (number | string)[] | Record<string, any>): string;
1
+ export declare function buildErrorMessageForAttribute(key: PropertyKey): string;
2
+ export declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
@@ -1,2 +1,3 @@
1
1
  export * from './error';
2
2
  export * from './optional-value';
3
+ export * from './path-stringify';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Stringify path array to string.
3
+ *
4
+ * @param input
5
+ */
6
+ export declare function stringifyPath(input: PropertyKey[]): string;
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@ var smob = require('smob');
4
4
  var pathtrace = require('pathtrace');
5
5
 
6
6
  function buildErrorMessageForAttribute(key) {
7
- return `The attribute ${String(key)} is invalid.`;
7
+ return `Property ${String(key)} is invalid`;
8
8
  }
9
9
  function buildErrorMessageForAttributes(input) {
10
10
  let names;
@@ -14,10 +14,10 @@ function buildErrorMessageForAttributes(input) {
14
14
  names = Object.keys(input);
15
15
  }
16
16
  if (names.length === 0) {
17
- return 'An unexpected error occurred.';
17
+ return 'Properties are invalid';
18
18
  }
19
19
  if (names.length > 1) {
20
- return `The attributes ${names.join(', ')} are invalid.`;
20
+ return `Properties ${names.join(', ')} are invalid.`;
21
21
  }
22
22
  return buildErrorMessageForAttribute(names[0]);
23
23
  }
@@ -60,32 +60,19 @@ var OptionalValue = /*#__PURE__*/ function(OptionalValue) {
60
60
  return !value;
61
61
  }
62
62
 
63
- /*
64
- * Copyright (c) 2024-2024.
65
- * Author Peter Placzek (tada5hi)
66
- * For the full copyright and license information,
67
- * view the LICENSE file that was distributed with this source code.
68
- */ class ValidupError extends Error {
69
- }
70
-
71
- class ValidupValidatorError extends ValidupError {
72
- constructor(options){
73
- super(options.message);
74
- this.path = options.path;
75
- this.pathAbsolute = options.pathAbsolute ?? options.path;
76
- this.code = options.code;
77
- this.received = options.received;
78
- this.expected = options.expected;
79
- }
63
+ /**
64
+ * Stringify path array to string.
65
+ *
66
+ * @param input
67
+ */ function stringifyPath(input) {
68
+ return pathtrace.arrayToPath(input);
80
69
  }
81
70
 
82
- class ValidupNestedError extends ValidupError {
83
- addChild(child) {
84
- this.children.push(child);
85
- }
86
- constructor(options = {}){
87
- super(options.message || 'One or many attributes may be invalid.');
88
- this.children = options.children || [];
71
+ class ValidupError extends Error {
72
+ constructor(issues = []){
73
+ const paths = issues.map((issue)=>stringifyPath(issue.path));
74
+ super(buildErrorMessageForAttributes(paths));
75
+ this.issues = issues;
89
76
  }
90
77
  }
91
78
 
@@ -108,6 +95,90 @@ function hasOwnProperty(obj, prop) {
108
95
  return !!input && typeof input === 'object' && !Array.isArray(input);
109
96
  }
110
97
 
98
+ function isIssuePath(input) {
99
+ if (!Array.isArray(input)) {
100
+ return false;
101
+ }
102
+ return input.every((el)=>typeof el === 'string' || typeof el === 'number' || typeof el === 'symbol');
103
+ }
104
+ function isBaseIssue(input) {
105
+ if (!isObject(input)) {
106
+ return false;
107
+ }
108
+ if (typeof input.message !== 'string') {
109
+ return false;
110
+ }
111
+ if (!isIssuePath(input.path)) {
112
+ return false;
113
+ }
114
+ return typeof input.meta === 'undefined' || isObject(input.meta);
115
+ }
116
+ function isIssueItem(input) {
117
+ if (!isBaseIssue(input)) {
118
+ return false;
119
+ }
120
+ if (input.type !== 'item') {
121
+ return false;
122
+ }
123
+ return typeof input.code === 'string';
124
+ }
125
+ function isIssueGroup(input) {
126
+ if (!isBaseIssue(input)) {
127
+ return false;
128
+ }
129
+ if (input.type !== 'group') {
130
+ return false;
131
+ }
132
+ return Array.isArray(input.issues) && input.issues.every((issue)=>isIssueItem(issue) || isIssueGroup(issue));
133
+ }
134
+ function isIssue(input) {
135
+ return isIssueGroup(input) || isIssueItem(input);
136
+ }
137
+
138
+ /*
139
+ * Copyright (c) 2026.
140
+ * Author Peter Placzek (tada5hi)
141
+ * For the full copyright and license information,
142
+ * view the LICENSE file that was distributed with this source code.
143
+ */ var IssueCode = /*#__PURE__*/ function(IssueCode) {
144
+ IssueCode["VALUE_INVALID"] = "value_invalid";
145
+ IssueCode["ONE_OF_FAILED"] = "one_of_failed";
146
+ return IssueCode;
147
+ }({});
148
+
149
+ function defineIssueItem(data) {
150
+ return {
151
+ type: 'item',
152
+ ...data,
153
+ code: IssueCode.VALUE_INVALID || data.code
154
+ };
155
+ }
156
+ function defineIssueGroup(data) {
157
+ return {
158
+ type: 'group',
159
+ ...data
160
+ };
161
+ }
162
+
163
+ function isError(input) {
164
+ if (!isObject(input)) {
165
+ return false;
166
+ }
167
+ return typeof input.message === 'string';
168
+ }
169
+ function isValidupError(error) {
170
+ if (!isError(error)) {
171
+ return false;
172
+ }
173
+ if (error instanceof ValidupError) {
174
+ return true;
175
+ }
176
+ if (!hasOwnProperty(error, 'issues')) {
177
+ return false;
178
+ }
179
+ return Array.isArray(error.issues) && error.issues.every((issue)=>isIssue(issue));
180
+ }
181
+
111
182
  function isContainer(input) {
112
183
  return isObject(input) && typeof input.run === 'function';
113
184
  }
@@ -146,17 +217,28 @@ class Container {
146
217
  if (typeof data === 'undefined') {
147
218
  throw new SyntaxError('No container/validator could be extracted from the fn arguments.');
148
219
  }
220
+ if (isContainer(data)) {
221
+ this.items.push({
222
+ options,
223
+ data,
224
+ path,
225
+ type: 'container'
226
+ });
227
+ return;
228
+ }
149
229
  this.items.push({
150
- ...options,
230
+ options,
151
231
  data,
152
- path
232
+ path,
233
+ type: 'validator'
153
234
  });
154
235
  }
155
236
  // ----------------------------------------------
156
- async run(data = {}, options = {}) {
157
- const output = {};
158
- const errors = [];
159
- const errorKeys = [];
237
+ /**
238
+ * @throws ValidupError
239
+ * @param data
240
+ * @param options
241
+ */ async run(data = {}, options = {}) {
160
242
  let pathsToInclude;
161
243
  if (options.pathsToInclude) {
162
244
  pathsToInclude = options.pathsToInclude;
@@ -169,44 +251,51 @@ class Container {
169
251
  } else if (this.options.pathsToInclude) {
170
252
  pathsToExclude = this.options.pathsToExclude;
171
253
  }
254
+ const output = {};
255
+ const issues = [];
172
256
  let itemCount = 0;
257
+ let errorCount = 0;
173
258
  for(let i = 0; i < this.items.length; i++){
174
259
  const item = this.items[i];
175
260
  if (!this.isItemGroupIncluded(item, options.group)) {
176
261
  continue;
177
262
  }
178
- let pathsCount = 0;
179
- let paths;
263
+ let pathCount = 0;
264
+ let pathFailed = false;
265
+ let keys;
180
266
  if (item.path) {
181
- paths = pathtrace.expandPath(data, item.path);
267
+ keys = pathtrace.expandPath(data, item.path);
182
268
  } else {
183
- paths = [
269
+ keys = [
184
270
  ''
185
271
  ];
186
272
  }
187
- for(let j = 0; j < paths.length; j++){
188
- const path = paths[j];
189
- const pathAbsolute = this.mergePaths(options.path, paths[j]);
273
+ for(let j = 0; j < keys.length; j++){
274
+ const key = keys[j];
275
+ const keyParts = key ? pathtrace.pathToArray(key) : [];
276
+ const pathRelative = keyParts.at(-1);
277
+ const pathAbsolute = [
278
+ ...options.path ? options.path : [],
279
+ ...keyParts
280
+ ];
190
281
  let value;
191
- if (hasOwnProperty(output, path)) {
192
- value = output[path];
193
- } else if (path.length > 0) {
194
- value = pathtrace.getPathValue(data, path);
282
+ if (key.length > 0) {
283
+ value = hasOwnProperty(output, key) ? output[key] : pathtrace.getPathValue(data, key);
195
284
  } else {
196
285
  value = data;
197
286
  }
198
- if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(path) === -1) {
287
+ if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(key) === -1) {
199
288
  continue;
200
289
  }
201
- if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(path) !== -1) {
290
+ if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(key) !== -1) {
202
291
  continue;
203
292
  }
204
293
  try {
205
- if (item.optional && isOptionalValue(value, item.optionalValue)) {
206
- if (item.optionalInclude) {
207
- output[path] = value;
294
+ if (item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
295
+ if (item.options.optionalInclude) {
296
+ output[key] = value;
208
297
  }
209
- } else if (isContainer(item.data)) {
298
+ } else if (item.type === 'container') {
210
299
  const tmp = await item.data.run(isObject(value) ? value : {}, {
211
300
  group: options.group,
212
301
  flat: true,
@@ -215,61 +304,75 @@ class Container {
215
304
  });
216
305
  const tmpKeys = Object.keys(tmp);
217
306
  for(let k = 0; k < tmpKeys.length; k++){
218
- output[this.mergePaths(path, tmpKeys[k])] = tmp[tmpKeys[k]];
307
+ output[this.mergePaths(key, tmpKeys[k])] = tmp[tmpKeys[k]];
219
308
  }
220
- } else {
221
- output[path] = await item.data({
222
- path,
223
- pathRaw: item.path ?? '',
224
- pathAbsolute,
309
+ } else if (item.type === 'validator') {
310
+ output[key] = await item.data({
311
+ key,
312
+ path: pathAbsolute,
225
313
  value,
226
314
  data,
227
315
  group: options.group
228
316
  });
229
317
  }
230
318
  } catch (e) {
231
- if (e instanceof ValidupValidatorError) {
232
- errors.push(e);
233
- errorKeys.push(pathAbsolute);
234
- } else if (e instanceof ValidupNestedError) {
235
- errors.push(...e.children);
236
- if (pathAbsolute.length > 0) {
237
- errorKeys.push(pathAbsolute);
319
+ const childIssues = [];
320
+ if (isValidupError(e)) {
321
+ for(let i = 0; i < e.issues.length; i++){
322
+ const issue = e.issues[i];
323
+ childIssues.push({
324
+ ...issue,
325
+ path: [
326
+ ...keyParts,
327
+ ...issue.path || []
328
+ ]
329
+ });
330
+ }
331
+ } else if (isError(e)) {
332
+ childIssues.push(defineIssueItem({
333
+ path: keyParts,
334
+ message: e.message
335
+ }));
336
+ }
337
+ if (pathRelative) {
338
+ if (item.type === 'container' || childIssues.length > 1) {
339
+ const group = defineIssueGroup({
340
+ message: buildErrorMessageForAttribute(pathRelative),
341
+ path: keyParts,
342
+ issues: childIssues
343
+ });
344
+ issues.push(group);
238
345
  } else {
239
- errorKeys.push(...e.children.map((child)=>child.pathAbsolute));
346
+ issues.push(...childIssues);
240
347
  }
241
348
  } else {
242
- const error = new ValidupValidatorError({
243
- path,
244
- pathAbsolute,
245
- received: value
246
- });
247
- if (e instanceof Error) {
248
- error.cause = e;
249
- error.message = e.message;
250
- }
251
- errors.push(error);
252
- errorKeys.push(pathAbsolute);
349
+ issues.push(...childIssues);
253
350
  }
351
+ pathFailed = true;
254
352
  }
255
- pathsCount++;
353
+ pathCount++;
256
354
  }
257
- if (pathsCount > 0) {
355
+ if (pathCount > 0) {
258
356
  itemCount++;
357
+ if (pathFailed) {
358
+ errorCount++;
359
+ }
259
360
  }
260
361
  }
261
362
  if (this.options.oneOf) {
262
- if (errors.length === itemCount) {
263
- throw new ValidupNestedError({
264
- message: buildErrorMessageForAttributes(errorKeys),
265
- children: errors
363
+ if (errorCount === itemCount) {
364
+ const group = defineIssueGroup({
365
+ code: IssueCode.ONE_OF_FAILED,
366
+ message: 'None of the branches succeeded',
367
+ issues,
368
+ path: options.path ? options.path : []
266
369
  });
370
+ throw new ValidupError([
371
+ group
372
+ ]);
267
373
  }
268
- } else if (errors.length > 0) {
269
- throw new ValidupNestedError({
270
- message: buildErrorMessageForAttributes(errorKeys),
271
- children: errors
272
- });
374
+ } else if (errorCount > 0) {
375
+ throw new ValidupError(issues);
273
376
  }
274
377
  if (options.defaults) {
275
378
  const defaultKeys = Object.keys(options.defaults);
@@ -293,19 +396,19 @@ class Container {
293
396
  if (group === GroupKey.WILDCARD) {
294
397
  return true;
295
398
  }
296
- if (item.group) {
297
- if (Array.isArray(item.group)) {
298
- if (item.group.indexOf(GroupKey.WILDCARD) !== -1) {
399
+ if (item.options.group) {
400
+ if (Array.isArray(item.options.group)) {
401
+ if (item.options.group.indexOf(GroupKey.WILDCARD) !== -1) {
299
402
  return true;
300
403
  }
301
- if (group && item.group.indexOf(group) !== -1) {
404
+ if (group && item.options.group.indexOf(group) !== -1) {
302
405
  return true;
303
406
  }
304
407
  } else {
305
- if (item.group === GroupKey.WILDCARD) {
408
+ if (item.options.group === GroupKey.WILDCARD) {
306
409
  return true;
307
410
  }
308
- if (item.group === group) {
411
+ if (item.options.group === group) {
309
412
  return true;
310
413
  }
311
414
  }
@@ -339,14 +442,21 @@ class Container {
339
442
 
340
443
  exports.Container = Container;
341
444
  exports.GroupKey = GroupKey;
445
+ exports.IssueCode = IssueCode;
342
446
  exports.OptionalValue = OptionalValue;
343
447
  exports.ValidupError = ValidupError;
344
- exports.ValidupNestedError = ValidupNestedError;
345
- exports.ValidupValidatorError = ValidupValidatorError;
346
448
  exports.buildErrorMessageForAttribute = buildErrorMessageForAttribute;
347
449
  exports.buildErrorMessageForAttributes = buildErrorMessageForAttributes;
450
+ exports.defineIssueGroup = defineIssueGroup;
451
+ exports.defineIssueItem = defineIssueItem;
348
452
  exports.hasOwnProperty = hasOwnProperty;
349
453
  exports.isContainer = isContainer;
454
+ exports.isError = isError;
455
+ exports.isIssue = isIssue;
456
+ exports.isIssueGroup = isIssueGroup;
457
+ exports.isIssueItem = isIssueItem;
350
458
  exports.isObject = isObject;
351
459
  exports.isOptionalValue = isOptionalValue;
460
+ exports.isValidupError = isValidupError;
461
+ exports.stringifyPath = stringifyPath;
352
462
  //# sourceMappingURL=index.cjs.map