@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,114 @@
1
+ /*
2
+ * Copyright (c) 2020 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 { NoOpLogger, stringifyLogValue } from './logger';
23
+ /**
24
+ * Abstract base class which wraps an existing {@link Logging.ILogger | ILogger} to implement
25
+ * both {@link Logging.ILogger | ILogger} and {@link IResultReporter | IResultReporter}.
26
+ * @public
27
+ */
28
+ export class LogReporter {
29
+ /**
30
+ * Creates a new {@link Logging.LogReporter | LogReporter}.
31
+ * @param params - The parameters for creating the {@link Logging.LogReporter | LogReporter}.
32
+ */
33
+ constructor(params) {
34
+ var _a, _b, _c;
35
+ /* c8 ignore next 1 */
36
+ params = params !== null && params !== void 0 ? params : {};
37
+ this.logger = (_a = params.logger) !== null && _a !== void 0 ? _a : new NoOpLogger();
38
+ this._valueFormatter = (_b = params.valueFormatter) !== null && _b !== void 0 ? _b : LogReporter.tryFormatObject;
39
+ this._messageFormatter = (_c = params.messageFormatter) !== null && _c !== void 0 ? _c : ((message, __detail) => message);
40
+ }
41
+ /**
42
+ * {@inheritDoc Logging.ILogger.logLevel}
43
+ */
44
+ get logLevel() {
45
+ return this.logger.logLevel;
46
+ }
47
+ /**
48
+ * {@inheritDoc Logging.ILogger.detail}
49
+ */
50
+ detail(message, ...parameters) {
51
+ return this.logger.detail(message, ...parameters);
52
+ }
53
+ /**
54
+ * {@inheritDoc Logging.ILogger.info}
55
+ */
56
+ info(message, ...parameters) {
57
+ return this.logger.info(message, ...parameters);
58
+ }
59
+ /**
60
+ * {@inheritDoc Logging.ILogger.warn}
61
+ */
62
+ warn(message, ...parameters) {
63
+ return this.logger.warn(message, ...parameters);
64
+ }
65
+ /**
66
+ * {@inheritDoc Logging.ILogger.error}
67
+ */
68
+ error(message, ...parameters) {
69
+ return this.logger.error(message, ...parameters);
70
+ }
71
+ /**
72
+ * {@inheritDoc Logging.ILogger.log}
73
+ */
74
+ log(level, message, ...parameters) {
75
+ return this.logger.log(level, message, ...parameters);
76
+ }
77
+ /**
78
+ * {@inheritDoc IResultReporter.reportSuccess}
79
+ */
80
+ reportSuccess(level, value, detail, message) {
81
+ const formattedValue = this._valueFormatter(value, detail);
82
+ const formatted = message ? message(formattedValue, detail) : formattedValue;
83
+ this.log(level, formatted);
84
+ }
85
+ /**
86
+ * {@inheritDoc IResultReporter.reportFailure}
87
+ */
88
+ reportFailure(level, message, detail) {
89
+ const formatted = this._messageFormatter(message, detail);
90
+ this.log(level, formatted);
91
+ }
92
+ /**
93
+ * Creates a new {@link Logging.LogReporter | LogReporter} with the same logger but a different value formatter.
94
+ * @param valueFormatter - The value formatter to use.
95
+ * @returns A new {@link Logging.LogReporter | LogReporter} with the same logger but a different value formatter.
96
+ */
97
+ withValueFormatter(valueFormatter) {
98
+ return new LogReporter({
99
+ logger: this.logger,
100
+ valueFormatter,
101
+ messageFormatter: this._messageFormatter
102
+ });
103
+ }
104
+ /**
105
+ * Generic method to try to format an object for logging.
106
+ * @param value - The value to format.
107
+ * @param detail - The detail to format.
108
+ * @returns
109
+ */
110
+ static tryFormatObject(value, detail) {
111
+ return stringifyLogValue(value);
112
+ }
113
+ }
114
+ //# sourceMappingURL=logReporter.js.map
@@ -0,0 +1,258 @@
1
+ /*
2
+ * Copyright (c) 2020 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 { captureResult, succeed } from '../base';
23
+ /**
24
+ * Compares two log levels.
25
+ * @param message - The first log level.
26
+ * @param reporter - The second log level.
27
+ * @returns `true` if the message should be logged, `false` if it should be suppressed.
28
+ * @public
29
+ */
30
+ export function shouldLog(message, reporter) {
31
+ if (reporter === 'all') {
32
+ return true; // 'all' logs everything, including 'quiet'
33
+ }
34
+ if (reporter === 'silent') {
35
+ return false; // 'silent' suppresses everything
36
+ }
37
+ if (message === 'quiet') {
38
+ return false; // 'quiet' messages only show when reporter is 'all'
39
+ }
40
+ switch (reporter) {
41
+ case 'error':
42
+ return message === 'error';
43
+ case 'warning':
44
+ return message === 'warning' || message === 'error';
45
+ case 'info':
46
+ return message !== 'detail';
47
+ }
48
+ return true;
49
+ }
50
+ /**
51
+ * Stringifies an arbitrary value for logging.
52
+ * @param value - The value to stringify.
53
+ * @returns The stringified value.
54
+ * @param maxLength - The maximum length of the stringified value.
55
+ * @public
56
+ */
57
+ export function stringifyLogValue(value, maxLength) {
58
+ maxLength = maxLength !== null && maxLength !== void 0 ? maxLength : 40;
59
+ if (typeof value === 'string') {
60
+ return value;
61
+ }
62
+ const str = String(value);
63
+ if (str === '[object Object]') {
64
+ return captureResult(() => JSON.stringify(value))
65
+ .onSuccess((s) => {
66
+ return succeed(s.length < maxLength ? s : s.substring(0, maxLength - 3) + '...');
67
+ })
68
+ .orDefault(str);
69
+ }
70
+ return str;
71
+ }
72
+ /**
73
+ * Abstract base class which implements {@link Logging.ILogger | ILogger}.
74
+ * @public
75
+ */
76
+ export class LoggerBase {
77
+ constructor(logLevel) {
78
+ /**
79
+ * {@inheritDoc Logging.ILogger.logLevel}
80
+ */
81
+ this.logLevel = 'info';
82
+ this.logLevel = logLevel !== null && logLevel !== void 0 ? logLevel : 'info';
83
+ }
84
+ /**
85
+ * {@inheritDoc Logging.ILogger.detail}
86
+ */
87
+ detail(message, ...parameters) {
88
+ return this.log('detail', message, ...parameters);
89
+ }
90
+ /**
91
+ * {@inheritDoc Logging.ILogger.info}
92
+ */
93
+ info(message, ...parameters) {
94
+ return this.log('info', message, ...parameters);
95
+ }
96
+ /**
97
+ * {@inheritDoc Logging.ILogger.warn}
98
+ */
99
+ warn(message, ...parameters) {
100
+ return this.log('warning', message, ...parameters);
101
+ }
102
+ /**
103
+ * {@inheritDoc Logging.ILogger.error}
104
+ */
105
+ error(message, ...parameters) {
106
+ return this.log('error', message, ...parameters);
107
+ }
108
+ /**
109
+ * {@inheritDoc Logging.ILogger.log}
110
+ */
111
+ log(level, message, ...parameters) {
112
+ if (shouldLog(level, this.logLevel)) {
113
+ const formatted = this._format(message, ...parameters);
114
+ return this._log(formatted, level);
115
+ }
116
+ return this._suppressLog(level, message, ...parameters);
117
+ }
118
+ /**
119
+ * Formats a message and parameters into a string.
120
+ * @param message - The message to format.
121
+ * @param parameters - The parameters to format.
122
+ * @returns The formatted message.
123
+ * @public
124
+ */
125
+ _format(message, ...parameters) {
126
+ const raw = [message, ...parameters];
127
+ const filtered = raw.filter((m) => m !== undefined);
128
+ const strings = filtered.map((m) => stringifyLogValue(m));
129
+ const joined = strings.join('');
130
+ return joined;
131
+ }
132
+ /**
133
+ * Inner method called for suppressed log messages.
134
+ * @public
135
+ */
136
+ _suppressLog(__level, __message, ...__parameters) {
137
+ return succeed(undefined);
138
+ }
139
+ }
140
+ /**
141
+ * An in-memory logger that stores logged and suppressed messages.
142
+ * @public
143
+ */
144
+ export class InMemoryLogger extends LoggerBase {
145
+ /**
146
+ * Creates a new in-memory logger.
147
+ * @param logLevel - The level of logging to be used.
148
+ */
149
+ constructor(logLevel) {
150
+ super(logLevel);
151
+ /**
152
+ * The messages that have been logged.
153
+ * @internal
154
+ */
155
+ this._logged = [];
156
+ /**
157
+ * The messages that have been suppressed.
158
+ * @internal
159
+ */
160
+ this._suppressed = [];
161
+ }
162
+ /**
163
+ * The messages that have been logged.
164
+ */
165
+ get logged() {
166
+ return this._logged;
167
+ }
168
+ /**
169
+ * The messages that have been suppressed.
170
+ */
171
+ get suppressed() {
172
+ return this._suppressed;
173
+ }
174
+ /**
175
+ * Clears the logged and suppressed messages.
176
+ */
177
+ clear() {
178
+ this._logged = [];
179
+ this._suppressed = [];
180
+ }
181
+ /**
182
+ * {@inheritDoc Logging.LoggerBase._log}
183
+ * @internal
184
+ */
185
+ _log(message, __level) {
186
+ this._logged.push(message);
187
+ return succeed(message);
188
+ }
189
+ /**
190
+ * {@inheritDoc Logging.LoggerBase._suppressLog}
191
+ * @param level - The level of the message.
192
+ * @param message - The message to suppress.
193
+ * @param parameters - The parameters to suppress.
194
+ * @returns `Success` with `undefined` if the message is suppressed.
195
+ * @internal
196
+ */
197
+ _suppressLog(level, message, ...parameters) {
198
+ const formatted = this._format(message, ...parameters);
199
+ this._suppressed.push(formatted);
200
+ return succeed(undefined);
201
+ }
202
+ }
203
+ /**
204
+ * A console logger that outputs messages to the console.
205
+ * @public
206
+ */
207
+ export class ConsoleLogger extends LoggerBase {
208
+ /**
209
+ * Creates a new console logger.
210
+ * @param logLevel - The level of logging to be used.
211
+ */
212
+ constructor(logLevel) {
213
+ super(logLevel);
214
+ }
215
+ /**
216
+ * {@inheritDoc Logging.LoggerBase._log}
217
+ * @internal
218
+ */
219
+ _log(message, level) {
220
+ switch (level) {
221
+ case 'error':
222
+ console.error(message);
223
+ break;
224
+ case 'warning':
225
+ console.warn(message);
226
+ break;
227
+ case 'info':
228
+ console.info(message);
229
+ break;
230
+ default:
231
+ console.log(message);
232
+ break;
233
+ }
234
+ return succeed(message);
235
+ }
236
+ }
237
+ /**
238
+ * A no-op {@link Logging.LoggerBase | LoggerBase} that does not log anything.
239
+ * @public
240
+ */
241
+ export class NoOpLogger extends LoggerBase {
242
+ /**
243
+ * Creates a new no-op logger.
244
+ * @param logLevel - The level of logging to be used.
245
+ */
246
+ constructor(logLevel) {
247
+ super(logLevel);
248
+ }
249
+ /**
250
+ * {@inheritDoc Logging.LoggerBase._log}
251
+ * @internal
252
+ */
253
+ _log(message, __level) {
254
+ // no-op
255
+ return succeed(message);
256
+ }
257
+ }
258
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,64 @@
1
+ /*
2
+ * Copyright (c) 2022 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} for arrays of validated
26
+ * values or objects.
27
+ * @public
28
+ */
29
+ export class ArrayValidator extends ValidatorBase {
30
+ /**
31
+ * Constructs a new {@link Validation.Classes.ArrayValidator | ArrayValidator}.
32
+ * @param params - Optional {@link Validation.Classes.ArrayValidatorConstructorParams | init params} for the
33
+ * new {@link Validation.Classes.ArrayValidator | ArrayValidator}.
34
+ */
35
+ constructor(params) {
36
+ var _a;
37
+ super(params);
38
+ this._validateElement = params.validateElement;
39
+ this.options = (_a = params.options) !== null && _a !== void 0 ? _a : {};
40
+ }
41
+ /**
42
+ * Static method which validates that a supplied `unknown` value is a `array`
43
+ * and that every element of the array can be validated by the supplied array
44
+ * validator.
45
+ * @param from - The `unknown` value to be tested.
46
+ * @param context - Optional validation context will be propagated to element validator.
47
+ * @param self - Optional self-reference for recursive validation.
48
+ * @returns Returns `true` if `from` is an `array` of valid elements, or
49
+ * {@link Failure} with an error message if not.
50
+ */
51
+ _validate(from, context, self) {
52
+ if (Array.isArray(from)) {
53
+ for (const elem of from) {
54
+ const result = this._validateElement.validate(elem, context);
55
+ if (!result.isSuccess()) {
56
+ return fail(result.message);
57
+ }
58
+ }
59
+ return true;
60
+ }
61
+ return fail(`"${from}": not an array`);
62
+ }
63
+ }
64
+ //# sourceMappingURL=array.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 `boolean` values.
26
+ * @public
27
+ */
28
+ export class BooleanValidator extends GenericValidator {
29
+ /**
30
+ * Constructs a new {@link Validation.Classes.BooleanValidator | BooleanValidator}.
31
+ * @param params - Optional {@link Validation.Classes.BooleanValidatorConstructorParams | init params} for the
32
+ * new {@link Validation.Classes.BooleanValidator | BooleanValidator}.
33
+ */
34
+ constructor(params) {
35
+ /* c8 ignore next */
36
+ params = params !== null && params !== void 0 ? params : {};
37
+ super(Object.assign({ validator: BooleanValidator.validateBoolean }, params));
38
+ }
39
+ /**
40
+ * Static method which validates that a supplied `unknown` value is a `boolean`.
41
+ * @param from - The `unknown` value to be tested.
42
+ * @returns Returns `true` if `from` is a `boolean`, or {@link Failure} with an error
43
+ * message if not.
44
+ */
45
+ static validateBoolean(from) {
46
+ if (typeof from === 'boolean') {
47
+ return true;
48
+ }
49
+ return fail(`"${from}": not a boolean`);
50
+ }
51
+ }
52
+ //# sourceMappingURL=boolean.js.map
@@ -0,0 +1,31 @@
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
+ /* c8 ignore start */
23
+ export { ArrayValidator } from './array';
24
+ export { BooleanValidator } from './boolean';
25
+ export { NumberValidator } from './number';
26
+ export { ObjectValidator } from './object';
27
+ export { OneOfValidator } from './oneOf';
28
+ export { StringValidator } from './string';
29
+ export { TypeGuardValidator } from './typeGuard';
30
+ /* c8 ignore stop */
31
+ //# sourceMappingURL=classes.js.map
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright (c) 2022 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=common.js.map
@@ -0,0 +1,67 @@
1
+ /*
2
+ * Copyright (c) 2020 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, isKeyOf } from '../base';
23
+ import { ValidatorBase } from './validatorBase';
24
+ /**
25
+ * An in-place {@link Validation.Validator | Validator} for properties
26
+ * an an object.
27
+ * @public
28
+ */
29
+ export class FieldValidator extends ValidatorBase {
30
+ /**
31
+ * Constructs a new {@link Validation.FieldValidator | FieldValidator.}.
32
+ * @param fieldName - The name of the property that this validator should validate.
33
+ * @param fieldValidator - The {@link Validation.Validator | Validator} to be applied
34
+ * against the named property.
35
+ * @param options - Additional {@link Validation.FieldValidatorOptions | options} to be
36
+ * applied to this validation.
37
+ */
38
+ constructor(fieldName, fieldValidator, options) {
39
+ super({ options });
40
+ this.fieldName = fieldName;
41
+ this.fieldValidator = fieldValidator;
42
+ /* c8 ignore next */
43
+ this._fieldOptions = options !== null && options !== void 0 ? options : {};
44
+ }
45
+ /**
46
+ * {@inheritdoc Validation.ValidatorBase._validate}
47
+ */
48
+ _validate(from, context, self) {
49
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
50
+ const optional = this._fieldOptions.optional === true;
51
+ if (isKeyOf(this.fieldName, from)) {
52
+ if (!optional || from[this.fieldName] !== undefined) {
53
+ const result = this.fieldValidator
54
+ .validate(from[this.fieldName], context)
55
+ .onFailure((message) => {
56
+ return fail(`${this.fieldName}: ${message}`);
57
+ });
58
+ return result.success ? true : result;
59
+ }
60
+ }
61
+ return optional ? true : fail(`"${this.fieldName}": Field not found in "${JSON.stringify(from)}`);
62
+ }
63
+ /* c8 ignore next 2 -- defense in depth */
64
+ return fail(`Cannot validate field '${this.fieldName}' from non-object "${JSON.stringify(from)}"`);
65
+ }
66
+ }
67
+ //# sourceMappingURL=field.js.map