validup 0.2.2 → 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.
@@ -1,120 +0,0 @@
1
- import type { Path } from 'pathtrace';
2
- import type { OptionalValue } from '../constants';
3
- import type { ValidupError } from '../error';
4
- import type { ObjectLiteral, Validator } from '../types';
5
- export type ContainerOptions<T> = {
6
- /**
7
- * Only one of the mounted container/validators must succeed.
8
- */
9
- oneOf?: boolean;
10
- /**
11
- * Limit mounted paths on execution.
12
- * By default, all mounted containers/validators will
13
- * be considered for execution.
14
- */
15
- pathsToInclude?: Path<T>[];
16
- /**
17
- * Exclude mounted paths on execution.
18
- * By default, all mounted containers/validators will
19
- * be considered for execution.
20
- */
21
- pathsToExclude?: Path<T>[];
22
- };
23
- export type ContainerRunOptions<T extends Record<string, any> = Record<string, any>> = {
24
- /**
25
- * Default values for the container output.
26
- */
27
- defaults?: {
28
- [Key in Path<T>]: any;
29
- };
30
- /**
31
- * Group to execute.
32
- */
33
- group?: string;
34
- /**
35
- * Output flat object?
36
- */
37
- flat?: boolean;
38
- /**
39
- * Passed path from the parent container.
40
- */
41
- path?: PropertyKey[];
42
- /**
43
- * Limit mounted paths on execution.
44
- * By default, all mounted containers/validators will
45
- * be considered for execution.
46
- */
47
- pathsToInclude?: Path<T>[];
48
- /**
49
- * Exclude mounted paths on execution.
50
- * By default, all mounted containers/validators will
51
- * be considered for execution.
52
- */
53
- pathsToExclude?: Path<T>[];
54
- };
55
- export type MountOptions = {
56
- /**
57
- * Group(s) to execute.
58
- */
59
- group?: string | string[];
60
- /**
61
- * Specify if an optional value is also acceptable for the mount key.
62
- * An optional value won't be passed to the underlying container/validator.
63
- *
64
- * default: false
65
- */
66
- optional?: boolean;
67
- /**
68
- * Which values are considered optional.
69
- * An optional value won't be passed to the underlying container/validator.
70
- *
71
- * default: 'undefined'
72
- */
73
- optionalValue?: `${OptionalValue}`;
74
- /**
75
- * Include optional value as property in output.
76
- *
77
- * default: false
78
- */
79
- optionalInclude?: boolean;
80
- };
81
- export type ResultSuccess<T> = {
82
- success: true;
83
- data: T;
84
- error?: never;
85
- };
86
- export type ResultFailure = {
87
- success: false;
88
- data?: never;
89
- error: ValidupError;
90
- };
91
- export type Result<T extends ObjectLiteral = ObjectLiteral> = ResultSuccess<T> | ResultFailure;
92
- export interface IContainer<T extends ObjectLiteral = ObjectLiteral> {
93
- /**
94
- * Run container with given input.
95
- *
96
- * @param input
97
- * @param options
98
- */
99
- run(input?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<T>;
100
- /**
101
- * Safe run container with given input.
102
- *
103
- * @param input
104
- * @param options
105
- */
106
- safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<Result<T>>;
107
- }
108
- export type BaseMount = {
109
- options: MountOptions;
110
- path?: string;
111
- };
112
- export type ContainerMount = BaseMount & {
113
- type: 'container';
114
- data: IContainer;
115
- };
116
- export type ValidatorMount = BaseMount & {
117
- type: 'validator';
118
- data: Validator;
119
- };
120
- export type Mount = ContainerMount | ValidatorMount;
@@ -1,5 +0,0 @@
1
- import type { Issue } from '../issue';
2
- export declare class ValidupError extends Error {
3
- readonly issues: Issue[];
4
- constructor(issues?: Issue[]);
5
- }
@@ -1,5 +0,0 @@
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;
@@ -1,2 +0,0 @@
1
- export * from './base';
2
- export * from './check';
@@ -1,2 +0,0 @@
1
- export declare function buildErrorMessageForAttribute(key: PropertyKey): string;
2
- export declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
@@ -1,3 +0,0 @@
1
- export * from './error';
2
- export * from './optional-value';
3
- export * from './path-stringify';
@@ -1,8 +0,0 @@
1
- import { OptionalValue } from '../constants';
2
- /**
3
- * Check if input value (type of) satisfies optional value type constraint.
4
- *
5
- * @param value
6
- * @param optionalValue
7
- */
8
- export declare function isOptionalValue(value: unknown, optionalValue?: `${OptionalValue}`): boolean;
@@ -1,6 +0,0 @@
1
- /**
2
- * Stringify path array to string.
3
- *
4
- * @param input
5
- */
6
- export declare function stringifyPath(input: PropertyKey[]): string;
package/dist/index.cjs DELETED
@@ -1,494 +0,0 @@
1
- 'use strict';
2
-
3
- var smob = require('smob');
4
- var pathtrace = require('pathtrace');
5
-
6
- function buildErrorMessageForAttribute(key) {
7
- return `Property ${String(key)} is invalid`;
8
- }
9
- function buildErrorMessageForAttributes(input) {
10
- let names;
11
- if (Array.isArray(input)) {
12
- names = smob.distinctArray(input);
13
- } else {
14
- names = Object.keys(input);
15
- }
16
- if (names.length === 0) {
17
- return 'Properties are invalid';
18
- }
19
- if (names.length > 1) {
20
- return `Properties ${names.join(', ')} are invalid.`;
21
- }
22
- return buildErrorMessageForAttribute(names[0]);
23
- }
24
-
25
- /*
26
- * Copyright (c) 2024.
27
- * Author Peter Placzek (tada5hi)
28
- * For the full copyright and license information,
29
- * view the LICENSE file that was distributed with this source code.
30
- */ var GroupKey = /*#__PURE__*/ function(GroupKey) {
31
- GroupKey["WILDCARD"] = "*";
32
- return GroupKey;
33
- }({});
34
- var OptionalValue = /*#__PURE__*/ function(OptionalValue) {
35
- /**
36
- * value: undefined
37
- */ OptionalValue["UNDEFINED"] = "undefined";
38
- /**
39
- * value: null & undefined
40
- */ OptionalValue["NULL"] = "null";
41
- /**
42
- * value: empty string, false, 0
43
- */ OptionalValue["FALSY"] = "falsy";
44
- return OptionalValue;
45
- }({});
46
-
47
- /**
48
- * Check if input value (type of) satisfies optional value type constraint.
49
- *
50
- * @param value
51
- * @param optionalValue
52
- */ function isOptionalValue(value, optionalValue) {
53
- const optionValueNormalized = optionalValue || OptionalValue.UNDEFINED;
54
- if (optionValueNormalized === OptionalValue.NULL) {
55
- return value === null || typeof value === 'undefined';
56
- }
57
- if (optionValueNormalized === OptionalValue.UNDEFINED) {
58
- return typeof value === 'undefined';
59
- }
60
- return !value;
61
- }
62
-
63
- /**
64
- * Stringify path array to string.
65
- *
66
- * @param input
67
- */ function stringifyPath(input) {
68
- return pathtrace.arrayToPath(input);
69
- }
70
-
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;
76
- }
77
- }
78
-
79
- /*
80
- * Copyright (c) 2024.
81
- * Author Peter Placzek (tada5hi)
82
- * For the full copyright and license information,
83
- * view the LICENSE file that was distributed with this source code.
84
- */ // eslint-disable-next-line @typescript-eslint/ban-types
85
- function hasOwnProperty(obj, prop) {
86
- return Object.prototype.hasOwnProperty.call(obj, prop);
87
- }
88
-
89
- /*
90
- * Copyright (c) 2024.
91
- * Author Peter Placzek (tada5hi)
92
- * For the full copyright and license information,
93
- * view the LICENSE file that was distributed with this source code.
94
- */ function isObject(input) {
95
- return !!input && typeof input === 'object' && !Array.isArray(input);
96
- }
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
-
182
- function isContainer(input) {
183
- return isObject(input) && typeof input.run === 'function' && typeof input.safeRun === 'function';
184
- }
185
-
186
- class Container {
187
- mount(...args) {
188
- if (args.length < 1) {
189
- throw new SyntaxError('The mount method requires at least one argument');
190
- }
191
- let path;
192
- let data;
193
- let dataIsContainer = false;
194
- let options = {};
195
- for(let i = 0; i < args.length; i++){
196
- const arg = args[i];
197
- if (typeof arg === 'string') {
198
- path = arg;
199
- continue;
200
- }
201
- if (typeof arg === 'function') {
202
- data = arg;
203
- continue;
204
- }
205
- if (isContainer(arg)) {
206
- data = arg;
207
- dataIsContainer = true;
208
- continue;
209
- }
210
- if (isObject(arg)) {
211
- options = args[i];
212
- }
213
- }
214
- if (!dataIsContainer && (typeof path === 'undefined' || path.length === 0)) {
215
- throw new SyntaxError('Only a container can be mounted without a key.');
216
- }
217
- if (typeof data === 'undefined') {
218
- throw new SyntaxError('No container/validator could be extracted from the fn arguments.');
219
- }
220
- if (isContainer(data)) {
221
- this.items.push({
222
- options,
223
- data,
224
- path,
225
- type: 'container'
226
- });
227
- return;
228
- }
229
- this.items.push({
230
- options,
231
- data,
232
- path,
233
- type: 'validator'
234
- });
235
- }
236
- // ----------------------------------------------
237
- /**
238
- * @throws ValidupError
239
- *
240
- * @param data
241
- * @param options
242
- */ async run(data = {}, options = {}) {
243
- let pathsToInclude;
244
- if (options.pathsToInclude) {
245
- pathsToInclude = options.pathsToInclude;
246
- } else if (this.options.pathsToInclude) {
247
- pathsToInclude = this.options.pathsToInclude;
248
- }
249
- let pathsToExclude;
250
- if (options.pathsToExclude) {
251
- pathsToExclude = options.pathsToExclude;
252
- } else if (this.options.pathsToInclude) {
253
- pathsToExclude = this.options.pathsToExclude;
254
- }
255
- const output = {};
256
- const issues = [];
257
- let itemCount = 0;
258
- let errorCount = 0;
259
- for(let i = 0; i < this.items.length; i++){
260
- const item = this.items[i];
261
- if (!this.isItemGroupIncluded(item, options.group)) {
262
- continue;
263
- }
264
- let pathCount = 0;
265
- let pathFailed = false;
266
- let keys;
267
- if (item.path) {
268
- keys = pathtrace.expandPath(data, item.path);
269
- } else {
270
- keys = [
271
- ''
272
- ];
273
- }
274
- for(let j = 0; j < keys.length; j++){
275
- const key = keys[j];
276
- const keyParts = key ? pathtrace.pathToArray(key) : [];
277
- const pathRelative = keyParts.at(-1);
278
- const pathAbsolute = [
279
- ...options.path ? options.path : [],
280
- ...keyParts
281
- ];
282
- let value;
283
- if (key.length > 0) {
284
- value = hasOwnProperty(output, key) ? output[key] : pathtrace.getPathValue(data, key);
285
- } else {
286
- value = data;
287
- }
288
- if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(key) === -1) {
289
- continue;
290
- }
291
- if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(key) !== -1) {
292
- continue;
293
- }
294
- try {
295
- if (item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
296
- if (item.options.optionalInclude) {
297
- output[key] = value;
298
- }
299
- } else if (item.type === 'container') {
300
- const tmp = await item.data.run(isObject(value) ? value : {}, {
301
- group: options.group,
302
- flat: true,
303
- path: pathAbsolute,
304
- pathsToInclude: options.pathsToInclude
305
- });
306
- const tmpKeys = Object.keys(tmp);
307
- for(let k = 0; k < tmpKeys.length; k++){
308
- output[this.mergePaths(key, tmpKeys[k])] = tmp[tmpKeys[k]];
309
- }
310
- } else if (item.type === 'validator') {
311
- output[key] = await item.data({
312
- key,
313
- path: pathAbsolute,
314
- value,
315
- data,
316
- group: options.group
317
- });
318
- }
319
- } catch (e) {
320
- const childIssues = [];
321
- if (isValidupError(e)) {
322
- for(let i = 0; i < e.issues.length; i++){
323
- const issue = e.issues[i];
324
- childIssues.push({
325
- ...issue,
326
- path: [
327
- ...keyParts,
328
- ...issue.path || []
329
- ]
330
- });
331
- }
332
- } else if (isError(e)) {
333
- childIssues.push(defineIssueItem({
334
- path: keyParts,
335
- message: e.message
336
- }));
337
- }
338
- if (pathRelative) {
339
- if (item.type === 'container' || childIssues.length > 1) {
340
- const group = defineIssueGroup({
341
- message: buildErrorMessageForAttribute(pathRelative),
342
- path: keyParts,
343
- issues: childIssues
344
- });
345
- issues.push(group);
346
- } else {
347
- issues.push(...childIssues);
348
- }
349
- } else {
350
- issues.push(...childIssues);
351
- }
352
- pathFailed = true;
353
- }
354
- pathCount++;
355
- }
356
- if (pathCount > 0) {
357
- itemCount++;
358
- if (pathFailed) {
359
- errorCount++;
360
- }
361
- }
362
- }
363
- if (this.options.oneOf) {
364
- if (errorCount === itemCount) {
365
- const group = defineIssueGroup({
366
- code: IssueCode.ONE_OF_FAILED,
367
- message: 'None of the branches succeeded',
368
- issues,
369
- path: options.path ? options.path : []
370
- });
371
- throw new ValidupError([
372
- group
373
- ]);
374
- }
375
- } else if (errorCount > 0) {
376
- throw new ValidupError(issues);
377
- }
378
- if (options.defaults) {
379
- const defaultKeys = Object.keys(options.defaults);
380
- for(let i = 0; i < defaultKeys.length; i++){
381
- if (!hasOwnProperty(output, defaultKeys[i]) || typeof output[defaultKeys[i]] === 'undefined') {
382
- output[defaultKeys[i]] = options.defaults[defaultKeys[i]];
383
- }
384
- }
385
- }
386
- if (options.flat) {
387
- return output;
388
- }
389
- const temp = {};
390
- const keys = Object.keys(output);
391
- for(let i = 0; i < keys.length; i++){
392
- pathtrace.setPathValue(temp, keys[i], output[keys[i]]);
393
- }
394
- return temp;
395
- }
396
- async safeRun(input = {}, options = {}) {
397
- try {
398
- const data = await this.run(input, options);
399
- return {
400
- success: true,
401
- data
402
- };
403
- } catch (e) {
404
- if (isValidupError(e)) {
405
- return {
406
- success: false,
407
- error: e
408
- };
409
- }
410
- if (isError(e)) {
411
- return {
412
- success: false,
413
- error: new ValidupError([
414
- defineIssueItem({
415
- path: [],
416
- message: e.message
417
- })
418
- ])
419
- };
420
- }
421
- return {
422
- success: false,
423
- error: new ValidupError()
424
- };
425
- }
426
- }
427
- isItemGroupIncluded(item, group) {
428
- if (group === GroupKey.WILDCARD) {
429
- return true;
430
- }
431
- if (item.options.group) {
432
- if (Array.isArray(item.options.group)) {
433
- if (item.options.group.indexOf(GroupKey.WILDCARD) !== -1) {
434
- return true;
435
- }
436
- if (group && item.options.group.indexOf(group) !== -1) {
437
- return true;
438
- }
439
- } else {
440
- if (item.options.group === GroupKey.WILDCARD) {
441
- return true;
442
- }
443
- if (item.options.group === group) {
444
- return true;
445
- }
446
- }
447
- return false;
448
- }
449
- return true;
450
- }
451
- mergePaths(...args) {
452
- let output = '';
453
- for(let i = 0; i < args.length; i++){
454
- const arg = args[i];
455
- if (!arg || arg.length === 0) {
456
- continue;
457
- }
458
- if (arg.at(0) === '.') {
459
- output += arg;
460
- } else {
461
- output += output.length > 0 ? `.${arg}` : arg;
462
- }
463
- }
464
- return output;
465
- }
466
- initialize() {}
467
- // ----------------------------------------------
468
- constructor(options = {}){
469
- this.options = options;
470
- this.items = [];
471
- this.initialize();
472
- }
473
- }
474
-
475
- exports.Container = Container;
476
- exports.GroupKey = GroupKey;
477
- exports.IssueCode = IssueCode;
478
- exports.OptionalValue = OptionalValue;
479
- exports.ValidupError = ValidupError;
480
- exports.buildErrorMessageForAttribute = buildErrorMessageForAttribute;
481
- exports.buildErrorMessageForAttributes = buildErrorMessageForAttributes;
482
- exports.defineIssueGroup = defineIssueGroup;
483
- exports.defineIssueItem = defineIssueItem;
484
- exports.hasOwnProperty = hasOwnProperty;
485
- exports.isContainer = isContainer;
486
- exports.isError = isError;
487
- exports.isIssue = isIssue;
488
- exports.isIssueGroup = isIssueGroup;
489
- exports.isIssueItem = isIssueItem;
490
- exports.isObject = isObject;
491
- exports.isOptionalValue = isOptionalValue;
492
- exports.isValidupError = isValidupError;
493
- exports.stringifyPath = stringifyPath;
494
- //# sourceMappingURL=index.cjs.map