@fgv/ts-utils 5.0.1-9 → 5.0.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.
Files changed (89) hide show
  1. package/dist/index.js +32 -0
  2. package/dist/packlets/base/brand.js +23 -0
  3. package/dist/packlets/base/index.js +28 -0
  4. package/dist/packlets/base/mapResults.js +217 -0
  5. package/dist/packlets/base/messageAggregator.js +110 -0
  6. package/dist/packlets/base/normalize.js +132 -0
  7. package/dist/packlets/base/result.js +611 -0
  8. package/dist/packlets/base/utils.js +185 -0
  9. package/dist/packlets/collections/collectible.js +82 -0
  10. package/dist/packlets/collections/collector.js +189 -0
  11. package/dist/packlets/collections/collectorValidator.js +94 -0
  12. package/dist/packlets/collections/common.js +23 -0
  13. package/dist/packlets/collections/convertingCollector.js +118 -0
  14. package/dist/packlets/collections/convertingCollectorValidator.js +95 -0
  15. package/dist/packlets/collections/index.js +37 -0
  16. package/dist/packlets/collections/keyValueConverters.js +100 -0
  17. package/dist/packlets/collections/readonlyResultMap.js +23 -0
  18. package/dist/packlets/collections/resultMap.js +214 -0
  19. package/dist/packlets/collections/resultMapValidator.js +122 -0
  20. package/dist/packlets/collections/utils.js +31 -0
  21. package/dist/packlets/collections/validatingCollector.js +63 -0
  22. package/dist/packlets/collections/validatingConvertingCollector.js +64 -0
  23. package/dist/packlets/collections/validatingResultMap.js +57 -0
  24. package/dist/packlets/conversion/baseConverter.js +242 -0
  25. package/dist/packlets/conversion/converter.js +2 -0
  26. package/dist/packlets/conversion/converters.js +637 -0
  27. package/dist/packlets/conversion/defaultingConverter.js +149 -0
  28. package/dist/packlets/conversion/index.js +29 -0
  29. package/dist/packlets/conversion/objectConverter.js +141 -0
  30. package/dist/packlets/conversion/stringConverter.js +93 -0
  31. package/dist/packlets/hash/crcNormalizer.js +114 -0
  32. package/dist/packlets/hash/hashingNormalizer.js +92 -0
  33. package/dist/packlets/hash/index.js +24 -0
  34. package/dist/packlets/logging/index.js +24 -0
  35. package/dist/packlets/logging/logReporter.js +114 -0
  36. package/dist/packlets/logging/logger.js +258 -0
  37. package/dist/packlets/validation/array.js +64 -0
  38. package/dist/packlets/validation/boolean.js +52 -0
  39. package/dist/packlets/validation/classes.js +31 -0
  40. package/dist/packlets/validation/common.js +23 -0
  41. package/dist/packlets/validation/field.js +67 -0
  42. package/dist/packlets/validation/genericValidator.js +160 -0
  43. package/dist/packlets/validation/index.js +29 -0
  44. package/dist/packlets/validation/number.js +52 -0
  45. package/dist/packlets/validation/object.js +134 -0
  46. package/dist/packlets/validation/oneOf.js +58 -0
  47. package/dist/packlets/validation/string.js +52 -0
  48. package/dist/packlets/validation/traits.js +56 -0
  49. package/dist/packlets/validation/typeGuard.js +59 -0
  50. package/dist/packlets/validation/validator.js +23 -0
  51. package/dist/packlets/validation/validatorBase.js +37 -0
  52. package/dist/packlets/validation/validators.js +191 -0
  53. package/dist/test/helpers/jest/helpers/fsHelpers.js +139 -0
  54. package/dist/test/helpers/jest/helpers/index.js +2 -0
  55. package/dist/test/helpers/jest/index.js +17 -0
  56. package/dist/test/helpers/jest/matchers/index.js +14 -0
  57. package/dist/test/helpers/jest/matchers/toFail/index.js +23 -0
  58. package/dist/test/helpers/jest/matchers/toFail/predicate.js +5 -0
  59. package/dist/test/helpers/jest/matchers/toFailTest/index.js +28 -0
  60. package/dist/test/helpers/jest/matchers/toFailTest/predicate.js +8 -0
  61. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.js +24 -0
  62. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.js +11 -0
  63. package/dist/test/helpers/jest/matchers/toFailTestWith/index.js +29 -0
  64. package/dist/test/helpers/jest/matchers/toFailTestWith/predicate.js +26 -0
  65. package/dist/test/helpers/jest/matchers/toFailWith/index.js +27 -0
  66. package/dist/test/helpers/jest/matchers/toFailWith/predicate.js +16 -0
  67. package/dist/test/helpers/jest/matchers/toFailWithDetail/index.js +27 -0
  68. package/dist/test/helpers/jest/matchers/toFailWithDetail/predicate.js +22 -0
  69. package/dist/test/helpers/jest/matchers/toSucceed/index.js +23 -0
  70. package/dist/test/helpers/jest/matchers/toSucceed/predicate.js +5 -0
  71. package/dist/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.js +24 -0
  72. package/dist/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.js +24 -0
  73. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/index.js +53 -0
  74. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.js +17 -0
  75. package/dist/test/helpers/jest/matchers/toSucceedWith/index.js +27 -0
  76. package/dist/test/helpers/jest/matchers/toSucceedWith/predicate.js +12 -0
  77. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/index.js +27 -0
  78. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/predicate.js +17 -0
  79. package/dist/test/helpers/jest/resolvers/cli.js +10 -0
  80. package/dist/test/helpers/jest/resolvers/ide.js +10 -0
  81. package/dist/test/helpers/jest/ts-utils.js +2 -0
  82. package/dist/test/helpers/jest/types/index.js +3 -0
  83. package/dist/test/helpers/jest/utils/matcherHelpers.js +47 -0
  84. package/dist/test/helpers/jest/utils/snapshotResolver.js +11 -0
  85. package/dist/test/unit/collections/helpers.js +106 -0
  86. package/dist/test/unit/hashTextEncodeCompat.js +23 -0
  87. package/dist/tsdoc-metadata.json +1 -1
  88. package/lib/packlets/hash/crcNormalizer.js +42 -2
  89. package/package.json +12 -2
@@ -0,0 +1,160 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail, succeed } from '../base';
23
+ import { ValidatorTraits } from './traits';
24
+ /**
25
+ * Generic base implementation for an in-place {@link Validation.Validator | Validator}.
26
+ * @public
27
+ */
28
+ export class GenericValidator {
29
+ /**
30
+ * Constructs a new {@link Validation.Base.GenericValidator | GenericValidator<T>}.
31
+ * @param params - The {@link Validation.Base.GenericValidatorConstructorParams | constructor params}
32
+ * used to configure validation.
33
+ */
34
+ constructor(params) {
35
+ var _a;
36
+ if (!params.validator) {
37
+ throw new Error('No validator function supplied');
38
+ }
39
+ this._validator = params.validator;
40
+ this._options = (_a = params.options) !== null && _a !== void 0 ? _a : {};
41
+ this.traits = new ValidatorTraits(params.traits);
42
+ }
43
+ /**
44
+ * {@inheritdoc Validation.Validator.isOptional}
45
+ */
46
+ get isOptional() {
47
+ return this.traits.isOptional;
48
+ }
49
+ /**
50
+ * {@inheritdoc Validation.Validator.brand}
51
+ */
52
+ get brand() {
53
+ return this.traits.brand;
54
+ }
55
+ /**
56
+ * {@inheritdoc Validation.Validator.validate}
57
+ */
58
+ validate(from, context) {
59
+ const result = this._validator(from, this._context(context), this);
60
+ if (typeof result === 'boolean') {
61
+ return result ? succeed(from) : fail('Invalid value');
62
+ }
63
+ return result;
64
+ }
65
+ /**
66
+ * {@inheritdoc Validation.Validator.convert}
67
+ */
68
+ convert(from, context) {
69
+ const result = this._validator(from, this._context(context), this);
70
+ if (typeof result === 'boolean') {
71
+ return result ? succeed(from) : fail('Invalid value');
72
+ }
73
+ return result;
74
+ }
75
+ /**
76
+ * {@inheritdoc Validation.Validator.validateOptional}
77
+ */
78
+ validateOptional(from, context) {
79
+ return from === undefined ? succeed(undefined) : this.validate(from, context);
80
+ }
81
+ /**
82
+ * {@inheritdoc Validation.Validator.guard}
83
+ */
84
+ guard(from, context) {
85
+ return this._validator(from, this._context(context), this) === true;
86
+ }
87
+ /**
88
+ * {@inheritdoc Validation.Validator.optional}
89
+ */
90
+ optional() {
91
+ return new GenericValidator({
92
+ validator: (from, context, self) => {
93
+ return from === undefined || this._validator(from, this._context(context), this);
94
+ },
95
+ traits: { isOptional: true }
96
+ });
97
+ }
98
+ /**
99
+ * {@inheritdoc Validation.Validator.withConstraint}
100
+ */
101
+ withConstraint(constraint, trait) {
102
+ trait = trait !== null && trait !== void 0 ? trait : { type: 'function' };
103
+ return new GenericValidator({
104
+ validator: (from, context, self) => {
105
+ const result = this._validator(from, this._context(context), this);
106
+ if (result === true) {
107
+ const constraintResult = constraint(from);
108
+ if (typeof constraintResult === 'boolean') {
109
+ return constraintResult
110
+ ? true
111
+ : fail(`Invalid value "${JSON.stringify(from)}": does not meet constraint.`);
112
+ }
113
+ return constraintResult;
114
+ }
115
+ return result;
116
+ },
117
+ traits: { constraints: [trait] }
118
+ });
119
+ }
120
+ /**
121
+ * {@inheritdoc Validation.Validator.brand}
122
+ */
123
+ withBrand(brand) {
124
+ if (this.brand) {
125
+ throw new Error(`Cannot replace existing brand "${this.brand}" with "${brand}".`);
126
+ }
127
+ return new GenericValidator({
128
+ validator: (from, context, self) => {
129
+ return this._validator(from, this._context(context), this);
130
+ },
131
+ traits: { brand }
132
+ });
133
+ }
134
+ /**
135
+ * {@inheritdoc Validation.Validator.withFormattedError}
136
+ */
137
+ withFormattedError(formatter) {
138
+ return new GenericValidator({
139
+ validator: (from, context, self) => {
140
+ const result = this._validator(from, this._context(context), this);
141
+ if (result === true) {
142
+ return true;
143
+ }
144
+ /* c8 ignore next - defense in depth */
145
+ const message = result === false ? undefined : result.message;
146
+ return fail(formatter(from, message, this._context(context)));
147
+ }
148
+ });
149
+ }
150
+ /**
151
+ * Gets a default or explicit context.
152
+ * @param explicitContext - Optional explicit context.
153
+ * @returns The appropriate context to use.
154
+ * @internal
155
+ */
156
+ _context(explicitContext) {
157
+ return explicitContext !== null && explicitContext !== void 0 ? explicitContext : this._options.defaultContext;
158
+ }
159
+ }
160
+ //# sourceMappingURL=genericValidator.js.map
@@ -0,0 +1,29 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ export * from './common';
23
+ export * from './traits';
24
+ export * from './validator';
25
+ import * as Classes from './classes';
26
+ import * as Base from './genericValidator';
27
+ import * as Validators from './validators';
28
+ export { Base, Classes, Validators };
29
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,52 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail } from '../base';
23
+ import { GenericValidator } from './genericValidator';
24
+ /**
25
+ * An in-place {@link Validation.Validator | Validator} for `number` values.
26
+ * @public
27
+ */
28
+ export class NumberValidator extends GenericValidator {
29
+ /**
30
+ * Constructs a new {@link Validation.Classes.NumberValidator | NumberValidator}.
31
+ * @param params - Optional {@link Validation.Classes.NumberValidatorConstructorParams | init params} for the
32
+ * new {@link Validation.Classes.NumberValidator | NumberValidator}.
33
+ */
34
+ constructor(params) {
35
+ /* c8 ignore next 1 */
36
+ params = params !== null && params !== void 0 ? params : {};
37
+ super(Object.assign({ validator: NumberValidator.validateNumber }, params));
38
+ }
39
+ /**
40
+ * Static method which validates that a supplied `unknown` value is a `number`.
41
+ * @param from - The `unknown` value to be tested.
42
+ * @returns Returns `true` if `from` is a `number`, or {@link Failure} with an error
43
+ * message if not.
44
+ */
45
+ static validateNumber(from) {
46
+ if (typeof from === 'number') {
47
+ return true;
48
+ }
49
+ return fail(`"${from}": not a number`);
50
+ }
51
+ }
52
+ //# sourceMappingURL=number.js.map
@@ -0,0 +1,134 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail } from '../base';
23
+ import { ValidatorBase } from './validatorBase';
24
+ import { FieldValidator } from './field';
25
+ /**
26
+ * In-place {@link Validation.Validator | Validator} for an object of type `<T>`.
27
+ * @remarks
28
+ * By default, succeeds if all of the required fields exist and are validate, and fails if
29
+ * any required fields do not exist or are invalid. See {@link Validation.Classes.ObjectValidatorOptions}
30
+ * for other validation options.
31
+ * @public
32
+ */
33
+ export class ObjectValidator extends ValidatorBase {
34
+ /**
35
+ * Constructs a new {@link Validation.Classes.ObjectValidator | ObjectValidator<T>}.
36
+ * @param fields - A {@link Validation.Classes.FieldValidators | FieldValidators<T>} containing
37
+ * a {@link Validation.Validator | Validator} for each field.
38
+ * @param options - An optional {@link Validation.Classes.ObjectValidatorOptions} to configure
39
+ * validation.
40
+ */
41
+ constructor(params) {
42
+ var _a;
43
+ super(params);
44
+ this.fields = params.fields;
45
+ this.options = (_a = params.options) !== null && _a !== void 0 ? _a : {};
46
+ this._innerValidators = ObjectValidator._resolveValidators(this.fields, this.options);
47
+ this._allowedFields =
48
+ this.options.strict === true ? new Set(Object.keys(this.fields)) : undefined;
49
+ }
50
+ /**
51
+ * Creates the actual {@link Validation.Classes.FieldValidators | FieldValidators<T>} to be
52
+ * used by this converter by applying any options or traits defined in the options
53
+ * to the field converters passed to the constructor.
54
+ * @param fields - The base {@link Validation.Classes.FieldValidators | FieldValidators<T>} passed
55
+ * in to the constructor.
56
+ * @param options - The {@link Validation.Classes.ObjectValidatorOptions | object validator options}
57
+ * passed in to the constructor.
58
+ * @returns A new {@link Validation.Classes.FieldValidators | FieldValidators} with the fully-configured
59
+ * individual {@link Validation.Validator | field validators} to be applied.
60
+ * @internal
61
+ */
62
+ static _resolveValidators(fields, options) {
63
+ var _a;
64
+ const resolved = {};
65
+ for (const key in fields) {
66
+ if (fields[key]) {
67
+ /* c8 ignore next */
68
+ const optional = fields[key].isOptional || ((_a = options === null || options === void 0 ? void 0 : options.optionalFields) === null || _a === void 0 ? void 0 : _a.includes(key));
69
+ resolved[key] = new FieldValidator(key, fields[key], { optional });
70
+ }
71
+ }
72
+ return resolved;
73
+ }
74
+ /**
75
+ * Creates a new {@link Validation.Classes.ObjectValidator | ObjectValidator} derived from this one but with
76
+ * new optional properties as specified by a supplied
77
+ * {@link Validation.Classes.ObjectValidatorOptions | ObjectValidatorOptions<T>}.
78
+ * @param options - The {@link Validation.Classes.ObjectValidatorOptions | options} to be applied to the new
79
+ * {@link Validation.Classes.ObjectValidator | validator}.
80
+ * @returns A new {@link Validation.Classes.ObjectValidator | ObjectValidator} with the additional optional
81
+ * source properties.
82
+ */
83
+ partial(options) {
84
+ /* c8 ignore next */
85
+ options = options !== null && options !== void 0 ? options : {};
86
+ return new ObjectValidator({
87
+ fields: this.fields,
88
+ options: Object.assign(Object.assign({}, this.options), options),
89
+ traits: this.traits
90
+ });
91
+ }
92
+ /**
93
+ * Creates a new {@link Validation.Classes.ObjectValidator | ObjectValidator} derived from this one but with
94
+ * new optional properties as specified by a supplied array of `keyof T`.
95
+ * @param addOptionalProperties - The keys to be made optional.
96
+ * @returns A new {@link Validation.Classes.ObjectValidator | ObjectValidator} with the additional optional
97
+ * source properties.
98
+ */
99
+ addPartial(addOptionalFields) {
100
+ var _a;
101
+ return this.partial({
102
+ optionalFields: [...((_a = this.options.optionalFields) !== null && _a !== void 0 ? _a : []), ...addOptionalFields]
103
+ });
104
+ }
105
+ /**
106
+ * {@inheritdoc Validation.ValidatorBase._validate}
107
+ * @internal
108
+ */
109
+ _validate(from, context, self) {
110
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
111
+ return fail('source is not an object');
112
+ }
113
+ // eslint bug thinks key is used before defined
114
+ const converted = {};
115
+ const errors = [];
116
+ for (const key in this._innerValidators) {
117
+ if (this._innerValidators[key]) {
118
+ const result = this._innerValidators[key].validate(from, context);
119
+ if (result.success && result.value !== undefined) {
120
+ converted[key] = result.value;
121
+ }
122
+ else if (result.isFailure()) {
123
+ errors.push(result.message);
124
+ }
125
+ }
126
+ }
127
+ if (this._allowedFields) {
128
+ const invalid = Object.keys(from).filter((k) => !this._allowedFields.has(k));
129
+ invalid.forEach((key) => errors.push(`${key}: unexpected field in source object.`));
130
+ }
131
+ return errors.length === 0 ? true : fail(errors.join('\n'));
132
+ }
133
+ }
134
+ //# sourceMappingURL=object.js.map
@@ -0,0 +1,58 @@
1
+ /*
2
+ * Copyright (c) 2024 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail } from '../base';
23
+ import { ValidatorBase } from './validatorBase';
24
+ /**
25
+ * An in-place {@link Validator | Validator} which validates that a supplied
26
+ * value matches one of several other validators.
27
+ * @public
28
+ */
29
+ export class OneOfValidator extends ValidatorBase {
30
+ /**
31
+ * Constructs a new {@link Validation.Classes.OneOfValidator | OneOfValidator}.
32
+ * @param params - Optional {@link Validation.Classes.OneOfValidatorConstructorParams | init params} for the
33
+ * new {@link Validation.Classes.OneOfValidator | OneOfValidator}.
34
+ */
35
+ constructor(params) {
36
+ var _a;
37
+ super(params);
38
+ this._validators = params.validators;
39
+ this.options = (_a = params.options) !== null && _a !== void 0 ? _a : {};
40
+ }
41
+ /**
42
+ * Static method which validates that a supplied `unknown` value matches at least one
43
+ * of the configured validators.
44
+ * @param from - The `unknown` value to be tested.
45
+ * @param context - Optional validation context will be propagated to element validator.
46
+ * @param self - Optional self-reference for recursive validation.
47
+ * @returns Returns `true` if `from` is an `array` of valid elements, or
48
+ * {@link Failure} with an error message if not.
49
+ */
50
+ _validate(from, context, self) {
51
+ const found = this._validators.some((v) => v.validate(from).success);
52
+ if (found) {
53
+ return true;
54
+ }
55
+ return fail(`value "${from}" does not match any validator.`);
56
+ }
57
+ }
58
+ //# sourceMappingURL=oneOf.js.map
@@ -0,0 +1,52 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail } from '../base';
23
+ import { GenericValidator } from './genericValidator';
24
+ /**
25
+ * An in-place {@link Validation.Validator | Validator} for `string` values.
26
+ * @public
27
+ */
28
+ export class StringValidator extends GenericValidator {
29
+ /**
30
+ * Constructs a new {@link Validation.Classes.StringValidator | StringValidator}.
31
+ * @param params - Optional {@link Validation.Classes.StringValidatorConstructorParams | init params}
32
+ * for the new {@link Validation.Classes.StringValidator | StringValidator}.
33
+ */
34
+ constructor(params) {
35
+ /* c8 ignore next */
36
+ params = params !== null && params !== void 0 ? params : {};
37
+ super(Object.assign({ validator: StringValidator.validateString }, params));
38
+ }
39
+ /**
40
+ * Static method which validates that a supplied `unknown` value is a `string`.
41
+ * @param from - The `unknown` value to be tested.
42
+ * @returns Returns `true` if `from` is a `string`, or {@link Failure} with an error
43
+ * message if not.
44
+ */
45
+ static validateString(from) {
46
+ if (typeof from === 'string') {
47
+ return true;
48
+ }
49
+ return fail(`"${from}": not a string`);
50
+ }
51
+ }
52
+ //# sourceMappingURL=string.js.map
@@ -0,0 +1,56 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ /**
23
+ * Default {@link Validation.ValidatorTraitValues | validation traits}.
24
+ * @public
25
+ */
26
+ export const defaultValidatorTraits = {
27
+ isOptional: false,
28
+ constraints: []
29
+ };
30
+ /**
31
+ * Generic implementation of {@link Validation.ValidatorTraitValues | ValidatorTraitValues}.
32
+ * @public
33
+ */
34
+ export class ValidatorTraits {
35
+ /**
36
+ * Constructs a new {@link Validation.ValidatorTraits | ValidatorTraits} optionally
37
+ * initialized with the supplied base and initial values.
38
+ * @remarks
39
+ * Initial values take priority over base values, which fall back to the global default values.
40
+ * @param init - Partial initial values to be set in the resulting {@link Validation.Validator | Validator}.
41
+ * @param base - Base values to be used when no initial values are present.
42
+ */
43
+ constructor(init, base) {
44
+ var _a, _b, _c, _d, _e, _f;
45
+ /* c8 ignore next 2 */
46
+ this.isOptional = (_b = (_a = init === null || init === void 0 ? void 0 : init.isOptional) !== null && _a !== void 0 ? _a : base === null || base === void 0 ? void 0 : base.isOptional) !== null && _b !== void 0 ? _b : defaultValidatorTraits.isOptional;
47
+ this.brand = (_d = (_c = init === null || init === void 0 ? void 0 : init.brand) !== null && _c !== void 0 ? _c : base === null || base === void 0 ? void 0 : base.brand) !== null && _d !== void 0 ? _d : defaultValidatorTraits.brand;
48
+ this.constraints = [
49
+ ...defaultValidatorTraits.constraints,
50
+ /* c8 ignore next 1 */
51
+ ...((_e = base === null || base === void 0 ? void 0 : base.constraints) !== null && _e !== void 0 ? _e : []),
52
+ ...((_f = init === null || init === void 0 ? void 0 : init.constraints) !== null && _f !== void 0 ? _f : [])
53
+ ];
54
+ }
55
+ }
56
+ //# sourceMappingURL=traits.js.map
@@ -0,0 +1,59 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail } from '../base';
23
+ import { ValidatorBase } from './validatorBase';
24
+ /**
25
+ * An in-place {@link Validation.Validator | Validator} that can be instantiated using a type guard
26
+ * function.
27
+ * @public
28
+ */
29
+ export class TypeGuardValidator extends ValidatorBase {
30
+ /**
31
+ * Constructs a new {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator}.
32
+ * @param params - Optional {@link Validation.Classes.TypeGuardValidatorConstructorParams | init params} for the
33
+ * new {@link Validation.Classes.TypeGuardValidator | TypeGuardValidator}.
34
+ */
35
+ constructor(params) {
36
+ var _a;
37
+ super(params);
38
+ this.description = params.description;
39
+ this._guard = params.guard;
40
+ this.options = (_a = params.options) !== null && _a !== void 0 ? _a : {};
41
+ }
42
+ /**
43
+ * Static method which validates that a supplied `unknown` value matches the supplied
44
+ * type guard, returning a `Failure<T>` containing more information about a failure.
45
+ * @param from - Value to be converted.
46
+ * @param context - Optional validation context.
47
+ * @param self - Optional self-reference for recursive validation.
48
+ * @returns `true` if `from` is valid, {@link Failure | Failure<T>}
49
+ * with an error message if `from` is invalid.
50
+ * @internal
51
+ */
52
+ _validate(from, context, self) {
53
+ if (this._guard(from, context)) {
54
+ return true;
55
+ }
56
+ return fail(`invalid ${this.description} (${JSON.stringify(from)})`);
57
+ }
58
+ }
59
+ //# sourceMappingURL=typeGuard.js.map
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ export {};
23
+ //# sourceMappingURL=validator.js.map
@@ -0,0 +1,37 @@
1
+ /*
2
+ * Copyright (c) 2021 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { GenericValidator } from './genericValidator';
23
+ /**
24
+ * Abstract base helper class for specific validator implementations
25
+ * @internal
26
+ */
27
+ export class ValidatorBase extends GenericValidator {
28
+ /**
29
+ * Inner constructor
30
+ * @param params - Initialization params.
31
+ * @internal
32
+ */
33
+ constructor(params) {
34
+ super(Object.assign({ validator: (from, context, self) => this._validate(from, context, self) }, params));
35
+ }
36
+ }
37
+ //# sourceMappingURL=validatorBase.js.map