@fgv/ts-utils 5.0.2 → 5.1.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 (104) hide show
  1. package/README.md +152 -84
  2. package/dist/index.js +2 -2
  3. package/dist/packlets/base/messageAggregator.js +6 -6
  4. package/dist/packlets/base/result.js +39 -39
  5. package/dist/packlets/base/utils.js +47 -0
  6. package/dist/packlets/collections/aggregatedResultMap.js +722 -0
  7. package/dist/packlets/collections/collector.js +9 -9
  8. package/dist/packlets/collections/collectorValidator.js +4 -4
  9. package/dist/packlets/collections/converters.js +39 -0
  10. package/dist/packlets/collections/convertingCollectorValidator.js +3 -3
  11. package/dist/packlets/collections/convertingResultMap.js +208 -0
  12. package/dist/packlets/collections/index.js +4 -0
  13. package/dist/packlets/collections/keyValueConverters.js +1 -4
  14. package/dist/packlets/collections/readOnlyConvertingResultMap.js +193 -0
  15. package/dist/packlets/collections/resultMapValidator.js +50 -6
  16. package/dist/packlets/collections/validatingConvertingResultMap.js +78 -0
  17. package/dist/packlets/conversion/advancedConverters.js +249 -0
  18. package/dist/packlets/conversion/baseConverter.js +23 -16
  19. package/dist/packlets/conversion/basicConverters.js +571 -0
  20. package/dist/packlets/conversion/converters.js +3 -617
  21. package/dist/packlets/conversion/defaultingConverter.js +21 -15
  22. package/dist/packlets/logging/bootLogger.js +122 -0
  23. package/dist/packlets/logging/index.js +1 -0
  24. package/dist/packlets/logging/logReporter.js +32 -1
  25. package/dist/packlets/logging/logger.js +25 -5
  26. package/dist/packlets/validation/classes.js +1 -0
  27. package/dist/packlets/validation/compositeId.js +60 -0
  28. package/dist/packlets/validation/field.js +1 -1
  29. package/dist/packlets/validation/genericValidator.js +24 -10
  30. package/dist/packlets/validation/object.js +3 -6
  31. package/dist/packlets/validation/validators.js +12 -0
  32. package/dist/ts-utils.d.ts +1633 -200
  33. package/dist/tsdoc-metadata.json +1 -1
  34. package/lib/index.d.ts +2 -2
  35. package/lib/index.js +2 -1
  36. package/lib/packlets/base/mapResults.d.ts +3 -3
  37. package/lib/packlets/base/messageAggregator.d.ts +6 -6
  38. package/lib/packlets/base/messageAggregator.js +6 -6
  39. package/lib/packlets/base/result.d.ts +74 -51
  40. package/lib/packlets/base/result.js +39 -39
  41. package/lib/packlets/base/utils.d.ts +42 -0
  42. package/lib/packlets/base/utils.js +52 -0
  43. package/lib/packlets/collections/aggregatedResultMap.d.ts +433 -0
  44. package/lib/packlets/collections/aggregatedResultMap.js +728 -0
  45. package/lib/packlets/collections/collector.d.ts +11 -10
  46. package/lib/packlets/collections/collector.js +9 -9
  47. package/lib/packlets/collections/collectorValidator.d.ts +12 -10
  48. package/lib/packlets/collections/collectorValidator.js +4 -4
  49. package/lib/packlets/collections/converters.d.ts +18 -0
  50. package/lib/packlets/collections/converters.js +42 -0
  51. package/lib/packlets/collections/convertingCollector.d.ts +4 -4
  52. package/lib/packlets/collections/convertingCollectorValidator.d.ts +10 -7
  53. package/lib/packlets/collections/convertingCollectorValidator.js +3 -3
  54. package/lib/packlets/collections/convertingResultMap.d.ts +176 -0
  55. package/lib/packlets/collections/convertingResultMap.js +213 -0
  56. package/lib/packlets/collections/index.d.ts +4 -0
  57. package/lib/packlets/collections/index.js +4 -0
  58. package/lib/packlets/collections/keyValueConverters.d.ts +1 -4
  59. package/lib/packlets/collections/keyValueConverters.js +1 -4
  60. package/lib/packlets/collections/readOnlyConvertingResultMap.d.ts +153 -0
  61. package/lib/packlets/collections/readOnlyConvertingResultMap.js +197 -0
  62. package/lib/packlets/collections/readonlyResultMap.d.ts +7 -7
  63. package/lib/packlets/collections/resultMap.d.ts +108 -2
  64. package/lib/packlets/collections/resultMapValidator.d.ts +45 -11
  65. package/lib/packlets/collections/resultMapValidator.js +52 -7
  66. package/lib/packlets/collections/validatingCollector.d.ts +5 -5
  67. package/lib/packlets/collections/validatingConvertingCollector.d.ts +3 -3
  68. package/lib/packlets/collections/validatingConvertingResultMap.d.ts +102 -0
  69. package/lib/packlets/collections/validatingConvertingResultMap.js +83 -0
  70. package/lib/packlets/collections/validatingResultMap.d.ts +1 -1
  71. package/lib/packlets/conversion/advancedConverters.d.ts +170 -0
  72. package/lib/packlets/conversion/advancedConverters.js +258 -0
  73. package/lib/packlets/conversion/baseConverter.d.ts +39 -23
  74. package/lib/packlets/conversion/baseConverter.js +23 -16
  75. package/lib/packlets/conversion/basicConverters.d.ts +470 -0
  76. package/lib/packlets/conversion/basicConverters.js +595 -0
  77. package/lib/packlets/conversion/converter.d.ts +7 -0
  78. package/lib/packlets/conversion/converters.d.ts +2 -535
  79. package/lib/packlets/conversion/converters.js +17 -639
  80. package/lib/packlets/conversion/defaultingConverter.d.ts +20 -16
  81. package/lib/packlets/conversion/defaultingConverter.js +21 -15
  82. package/lib/packlets/logging/bootLogger.d.ts +84 -0
  83. package/lib/packlets/logging/bootLogger.js +126 -0
  84. package/lib/packlets/logging/index.d.ts +1 -0
  85. package/lib/packlets/logging/index.js +1 -0
  86. package/lib/packlets/logging/logReporter.d.ts +18 -3
  87. package/lib/packlets/logging/logReporter.js +31 -0
  88. package/lib/packlets/logging/logger.d.ts +39 -6
  89. package/lib/packlets/logging/logger.js +26 -5
  90. package/lib/packlets/validation/classes.d.ts +1 -0
  91. package/lib/packlets/validation/classes.js +3 -1
  92. package/lib/packlets/validation/compositeId.d.ts +29 -0
  93. package/lib/packlets/validation/compositeId.js +64 -0
  94. package/lib/packlets/validation/field.d.ts +1 -1
  95. package/lib/packlets/validation/field.js +1 -1
  96. package/lib/packlets/validation/genericValidator.d.ts +15 -11
  97. package/lib/packlets/validation/genericValidator.js +24 -10
  98. package/lib/packlets/validation/object.d.ts +3 -6
  99. package/lib/packlets/validation/object.js +3 -6
  100. package/lib/packlets/validation/traits.d.ts +3 -3
  101. package/lib/packlets/validation/validator.d.ts +7 -0
  102. package/lib/packlets/validation/validators.d.ts +10 -0
  103. package/lib/packlets/validation/validators.js +13 -0
  104. package/package.json +27 -27
@@ -0,0 +1,595 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.numberArray = exports.stringArray = exports.optionalBoolean = exports.optionalNumber = exports.optionalString = exports.boolean = exports.number = exports.value = exports.string = void 0;
25
+ exports.enumeratedValue = enumeratedValue;
26
+ exports.mappedEnumeratedValue = mappedEnumeratedValue;
27
+ exports.literal = literal;
28
+ exports.delimitedString = delimitedString;
29
+ exports.isValidator = isValidator;
30
+ exports.validated = validated;
31
+ exports.asValidator = asValidator;
32
+ exports.generic = generic;
33
+ exports.isA = isA;
34
+ exports.oneOf = oneOf;
35
+ exports.arrayOf = arrayOf;
36
+ exports.recordOf = recordOf;
37
+ exports.mapOf = mapOf;
38
+ exports.validateWith = validateWith;
39
+ exports.element = element;
40
+ exports.optionalElement = optionalElement;
41
+ exports.field = field;
42
+ exports.optionalField = optionalField;
43
+ exports.object = object;
44
+ exports.strictObject = strictObject;
45
+ exports.discriminatedObject = discriminatedObject;
46
+ const base_1 = require("../base");
47
+ const validation_1 = require("../validation");
48
+ const baseConverter_1 = require("./baseConverter");
49
+ const objectConverter_1 = require("./objectConverter");
50
+ const stringConverter_1 = require("./stringConverter");
51
+ /**
52
+ * A converter to convert unknown to string. Values of type
53
+ * string succeed. Anything else fails.
54
+ * @public
55
+ */
56
+ exports.string = new stringConverter_1.StringConverter();
57
+ /**
58
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied
59
+ * enumerated values. Anything else fails.
60
+ *
61
+ * @remarks
62
+ * Allowed enumerated values can also be supplied as context at conversion time.
63
+ * @param values - Array of allowed values.
64
+ * @returns A new {@link Converter | Converter} returning `<T>`.
65
+ * @public
66
+ */
67
+ function enumeratedValue(values) {
68
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
69
+ const v = context !== null && context !== void 0 ? context : values;
70
+ const index = v.indexOf(from);
71
+ return index >= 0 ? (0, base_1.succeed)(v[index]) : (0, base_1.fail)(`Invalid enumerated value ${JSON.stringify(from)}`);
72
+ });
73
+ }
74
+ /**
75
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied enumerated
76
+ * values, mapping any of multiple supplied values to the enumeration.
77
+ * @remarks
78
+ * Enables mapping of multiple input values to a consistent internal representation (so e.g. `'y'`, `'yes'`,
79
+ * `'true'`, `1` and `true` can all map to boolean `true`)
80
+ * @param map - An array of tuples describing the mapping. The first element of each tuple is the result
81
+ * value, the second is the set of values that map to the result. Tuples are evaluated in the order
82
+ * supplied and are not checked for duplicates.
83
+ * @param message - An optional error message.
84
+ * @returns A {@link Converter | Converter} which applies the mapping and yields `<T>` on success.
85
+ * @public
86
+ */
87
+ function mappedEnumeratedValue(map, message) {
88
+ return new baseConverter_1.BaseConverter((from, __self, __context) => {
89
+ for (const item of map) {
90
+ if (item[1].includes(from)) {
91
+ return (0, base_1.succeed)(item[0]);
92
+ }
93
+ }
94
+ return (0, base_1.fail)(message
95
+ ? `${JSON.stringify(from)}: ${message}`
96
+ : `Cannot map '${JSON.stringify(from)}' to a supported value`);
97
+ });
98
+ }
99
+ /**
100
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to some supplied literal value. Succeeds with
101
+ * the supplied value if an identity comparison succeeds, fails otherwise.
102
+ * @param value - The value to be compared.
103
+ * @returns A {@link Converter | Converter} which returns the supplied value on success.
104
+ * @public
105
+ */
106
+ function literal(value) {
107
+ return new baseConverter_1.BaseConverter((from, __self, __context) => {
108
+ return from === value
109
+ ? (0, base_1.succeed)(value)
110
+ : (0, base_1.fail)(`${JSON.stringify(from)}: does not match ${JSON.stringify(value)}`);
111
+ });
112
+ }
113
+ /**
114
+ * Deprecated alias for @see literal
115
+ * @param value - The value to be compared.
116
+ * @deprecated Use {@link Converters.literal} instead.
117
+ * @internal
118
+ */
119
+ // eslint-disable-next-line @rushstack/typedef-var
120
+ exports.value = literal;
121
+ /**
122
+ * A {@link Converter | Converter} which converts `unknown` to a `number`.
123
+ * @remarks
124
+ * Numbers and strings with a numeric format succeed. Anything else fails.
125
+ * @public
126
+ */
127
+ exports.number = new baseConverter_1.BaseConverter((from) => {
128
+ if (typeof from !== 'number') {
129
+ const num = typeof from === 'string' ? Number(from) : NaN;
130
+ return isNaN(num) ? (0, base_1.fail)(`Not a number: ${JSON.stringify(from)}`) : (0, base_1.succeed)(num);
131
+ }
132
+ return (0, base_1.succeed)(from);
133
+ });
134
+ const booleanConverter = new baseConverter_1.BaseConverter((from) => {
135
+ if (typeof from === 'boolean') {
136
+ return (0, base_1.succeed)(from);
137
+ }
138
+ else if (typeof from === 'string') {
139
+ switch (from.toLowerCase()) {
140
+ case 'true':
141
+ return (0, base_1.succeed)(true);
142
+ case 'false':
143
+ return (0, base_1.succeed)(false);
144
+ }
145
+ }
146
+ return (0, base_1.fail)(`Not a boolean: ${JSON.stringify(from)}`);
147
+ });
148
+ /**
149
+ * A {@link Converter | Converter} which converts `unknown` to `boolean`.
150
+ * @remarks
151
+ * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed.
152
+ * Anything else fails.
153
+ * @public
154
+ */
155
+ exports.boolean = booleanConverter;
156
+ /**
157
+ * A {@link Converter | Converter} which converts an optional `string` value. Values of type
158
+ * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`.
159
+ * @public
160
+ */
161
+ exports.optionalString = exports.string.optional();
162
+ /**
163
+ * Helper function to create a {@link Converter | Converter} which converts any `string` into an
164
+ * array of `string`, by separating at a supplied delimiter.
165
+ * @remarks
166
+ * Delimiter may also be supplied as context at conversion time.
167
+ * @param delimiter - The delimiter at which to split.
168
+ * @returns A new {@link Converter | Converter} returning `string[]`.
169
+ * @public
170
+ */
171
+ function delimitedString(delimiter, options = 'filtered') {
172
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
173
+ const result = exports.string.convert(from);
174
+ if (result.isSuccess()) {
175
+ let strings = result.value.split(context !== null && context !== void 0 ? context : delimiter);
176
+ if (options !== 'all') {
177
+ strings = strings.filter((s) => s.trim().length > 0);
178
+ }
179
+ return (0, base_1.succeed)(strings);
180
+ }
181
+ return (0, base_1.fail)(result.message);
182
+ });
183
+ }
184
+ /**
185
+ * Determines if a supplied {@link Conversion.Converter | Converter} or {@link Validation.Validator | Validator} is
186
+ * a {@link Validation.Validator | Validator}.
187
+ * @param converterOrValidator - The {@link Conversion.Converter | Converter} or {@link Validation.Validator | Validator} to be tested.
188
+ * @returns `true` if `converterOrValidator` is a {@link Validation.Validator | Validator}, `false` otherwise.
189
+ * @public
190
+ */
191
+ function isValidator(converterOrValidator) {
192
+ return 'validate' in converterOrValidator;
193
+ }
194
+ /**
195
+ * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator}
196
+ * @param converterOrValidator - the {@link Validation.Validator} to be wrapped or {@link Converter | Converter}
197
+ * to be used directly.
198
+ * @returns A {@link Converter | Converter} which uses the supplied validator.
199
+ * @public
200
+ */
201
+ function validated(converterOrValidator) {
202
+ if (!isValidator(converterOrValidator)) {
203
+ return converterOrValidator;
204
+ }
205
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
206
+ return converterOrValidator.validate(from, context);
207
+ });
208
+ }
209
+ /**
210
+ * Helper function to create a {@link Validation.Validator | Validator} from any {@link Conversion.Converter | Converter}
211
+ * or {@link Validation.Validator | Validator}.
212
+ * @param converterOrValidator - the {@link Conversion.Converter | Converter} to be wrappped or {@link Validation.Validator | Validator} to be used directly.
213
+ * @returns A {@link Validation.Validator | Validator} which uses the supplied converter or validator.
214
+ * @public
215
+ */
216
+ function asValidator(converterOrValidator) {
217
+ if (isValidator(converterOrValidator)) {
218
+ return converterOrValidator;
219
+ }
220
+ return new validation_1.Base.GenericValidator({
221
+ validator: (from, context) => {
222
+ const result = converterOrValidator.convert(from, context);
223
+ return result.isSuccess() ? true : (0, base_1.fail)(result.message);
224
+ }
225
+ });
226
+ }
227
+ /**
228
+ * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}.
229
+ * @param convert - the function to be wrapped
230
+ * @returns A {@link Converter | Converter} which uses the supplied function.
231
+ * @public
232
+ */
233
+ function generic(convert) {
234
+ return new baseConverter_1.BaseConverter(convert);
235
+ }
236
+ /**
237
+ * Helper function to create a {@link Converter | Converter} from a supplied type guard function.
238
+ * @param description - a description of the thing to be validated for use in error messages
239
+ * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation.
240
+ * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard
241
+ * and returns them in place.
242
+ * @public
243
+ */
244
+ function isA(description, guard) {
245
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
246
+ if (guard(from, context)) {
247
+ return (0, base_1.succeed)(from);
248
+ }
249
+ return (0, base_1.fail)(`invalid ${description} (${JSON.stringify(from)})`);
250
+ });
251
+ }
252
+ /**
253
+ * A {@link Converter | Converter} which converts an optional `number` value.
254
+ * @remarks
255
+ * Values of type `number` or numeric strings are converted and returned.
256
+ * Anything else returns {@link Success | Success} with value `undefined`.
257
+ * @public
258
+ */
259
+ exports.optionalNumber = exports.number.optional();
260
+ /**
261
+ * A {@link Converter | Converter} to convert an optional `boolean` value.
262
+ * @remarks
263
+ * Values of type `boolean` or strings that match (case-insensitive) `'true'`
264
+ * or `'false'` are converted and returned. Anything else returns {@link Success | Success}
265
+ * with value `undefined`.
266
+ * @public
267
+ */
268
+ exports.optionalBoolean = booleanConverter.optional();
269
+ /**
270
+ * A helper function to create a {@link Converter | Converter} for polymorphic values.
271
+ * Returns a converter which invokes the wrapped converters in sequence, returning the
272
+ * first successful result. Returns an error if none of the supplied converters can
273
+ * convert the value.
274
+ * @remarks
275
+ * If `onError` is `ignoreErrors` (default), then errors from any of the
276
+ * converters are ignored provided that some converter succeeds. If
277
+ * onError is `failOnError`, then an error from any converter fails the entire
278
+ * conversion.
279
+ *
280
+ * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators}
281
+ * to be considered.
282
+ * @param onError - Specifies treatment of unconvertible elements.
283
+ * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned
284
+ * by the wrapped converters.
285
+ * @public
286
+ */
287
+ function oneOf(converters, onError = 'ignoreErrors') {
288
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
289
+ const errors = [];
290
+ for (const converter of converters) {
291
+ const result = converter.convert(from, context);
292
+ if (result.isSuccess() && result.value !== undefined) {
293
+ return result;
294
+ }
295
+ if (result.isFailure()) {
296
+ if (onError === 'failOnError') {
297
+ return result;
298
+ }
299
+ errors.push(result.message);
300
+ }
301
+ }
302
+ return (0, base_1.fail)(`No matching converter for ${JSON.stringify(from)}: ${errors.join('\n')}`);
303
+ });
304
+ }
305
+ /**
306
+ * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of `<T>`.
307
+ * @remarks
308
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
309
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
310
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each
311
+ * item in the array.
312
+ * @param onError - Specifies treatment of unconvertible elements.
313
+ * @returns A {@link Converter | Converter} which returns an array of `<T>`.
314
+ * @public
315
+ */
316
+ function arrayOf(converter, onError = 'failOnError') {
317
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
318
+ if (!Array.isArray(from)) {
319
+ return (0, base_1.fail)(`Not an array: ${JSON.stringify(from)}`);
320
+ }
321
+ const successes = [];
322
+ const errors = [];
323
+ for (const item of from) {
324
+ const result = converter.convert(item, context);
325
+ if (result.isSuccess() && result.value !== undefined) {
326
+ successes.push(result.value);
327
+ }
328
+ else if (result.isFailure()) {
329
+ errors.push(result.message);
330
+ }
331
+ }
332
+ return errors.length === 0 || onError === 'ignoreErrors' ? (0, base_1.succeed)(successes) : (0, base_1.fail)(errors.join('\n'));
333
+ });
334
+ }
335
+ /**
336
+ * {@link Converter | Converter} to convert an `unknown` to an array of `string`.
337
+ * @remarks
338
+ * Returns {@link Success | Success} with the the supplied value if it as an array
339
+ * of strings, returns {@link Failure | Failure} with an error message otherwise.
340
+ * @public
341
+ */
342
+ exports.stringArray = arrayOf(exports.string);
343
+ /**
344
+ * {@link Converter | Converter} to convert an `unknown` to an array of `number`.
345
+ * @remarks
346
+ * Returns {@link Success | Success} with the the supplied value if it as an array
347
+ * of numbers, returns {@link Failure | Failure} with an error message otherwise.
348
+ * @public
349
+ */
350
+ exports.numberArray = arrayOf(exports.number);
351
+ /**
352
+ * Concrete implementation of {@link Converters.(recordOf:1) | Converters.recordOf(Converter<T, TC>)},
353
+ * {@link Converters.(recordOf:2) | Converters.recordOf(Converter<T, TC>, 'fail' or 'ignore')}, and
354
+ * {@link Converters.recordOf | Converters.recordOf(Converter<T, TC>, KeyedConverterOptions)}.
355
+ * @internal
356
+ */
357
+ function recordOf(converter, option = 'fail') {
358
+ const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
359
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
360
+ var _a, _b;
361
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
362
+ return (0, base_1.fail)(`Not a string-keyed object: ${JSON.stringify(from)}`);
363
+ }
364
+ const record = {};
365
+ const errors = [];
366
+ for (const key in from) {
367
+ if ((0, base_1.isKeyOf)(key, from)) {
368
+ const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : (0, base_1.succeed)(key);
369
+ writeKeyResult
370
+ .onSuccess((writeKey) => {
371
+ return converter.convert(from[key], context).onSuccess((value) => {
372
+ record[writeKey] = value;
373
+ return (0, base_1.succeed)(true);
374
+ });
375
+ })
376
+ .onFailure((message) => {
377
+ errors.push(message);
378
+ return (0, base_1.fail)(message);
379
+ });
380
+ }
381
+ }
382
+ return errors.length === 0 || options.onError === 'ignore' ? (0, base_1.succeed)(record) : (0, base_1.fail)(errors.join('\n'));
383
+ });
384
+ }
385
+ /**
386
+ * Concrete implementation of {@link Converters.(mapOf:1) | Converters.mapOf(Converter<T, TC>)},
387
+ * {@link Converters.(mapOf:2) | Converters.mapOf(Converter<T, TC>, 'fail' or 'ignore')}, and
388
+ * {@link Converters.mapOf | Converters.mapOf(Converter<T, TC>, KeyedConverterOptions)}.
389
+ * @internal
390
+ */
391
+ function mapOf(converter, option = 'fail') {
392
+ const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
393
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
394
+ var _a, _b;
395
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
396
+ return (0, base_1.fail)(`Not a string-keyed object: ${JSON.stringify(from)}`);
397
+ }
398
+ const map = new Map();
399
+ const errors = [];
400
+ for (const key in from) {
401
+ if ((0, base_1.isKeyOf)(key, from)) {
402
+ const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : (0, base_1.succeed)(key);
403
+ writeKeyResult
404
+ .onSuccess((writeKey) => {
405
+ return converter.convert(from[key], context).onSuccess((value) => {
406
+ map.set(writeKey, value);
407
+ return (0, base_1.succeed)(true);
408
+ });
409
+ })
410
+ .onFailure((message) => {
411
+ errors.push(message);
412
+ return (0, base_1.fail)(message);
413
+ });
414
+ }
415
+ }
416
+ return errors.length === 0 || options.onError === 'ignore' ? (0, base_1.succeed)(map) : (0, base_1.fail)(errors.join('\n'));
417
+ });
418
+ }
419
+ /**
420
+ * Helper function to create a {@link Converter | Converter} which validates that a supplied value is
421
+ * of a type validated by a supplied validator function and returns it.
422
+ * @remarks
423
+ * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied
424
+ * value of `from` coerced to type `<T>`. Returns a {@link Failure | Failure} with additional
425
+ * information otherwise.
426
+ * @param validator - A validator function to determine if the converted value is valid.
427
+ * @param description - A description of the validated type for use in error messages.
428
+ * @returns A new {@link Converter | Converter<T, TC>} which applies the supplied validation.
429
+ * @public
430
+ */
431
+ function validateWith(validator, description) {
432
+ return new baseConverter_1.BaseConverter((from, __self, __context) => {
433
+ if (validator(from)) {
434
+ return (0, base_1.succeed)(from);
435
+ }
436
+ return (0, base_1.fail)(`${JSON.stringify(from)}: invalid ${description !== null && description !== void 0 ? description : 'value'}`);
437
+ });
438
+ }
439
+ /**
440
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array.
441
+ * @remarks
442
+ * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
443
+ * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise.
444
+ * @param index - The index of the element to be extracted.
445
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element.
446
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
447
+ * @public
448
+ */
449
+ function element(index, converter) {
450
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
451
+ if (index < 0) {
452
+ return (0, base_1.fail)(`${index}: cannot convert for a negative element index`);
453
+ }
454
+ else if (!Array.isArray(from)) {
455
+ return (0, base_1.fail)('element converter: source is not an array');
456
+ }
457
+ else if (index >= from.length) {
458
+ return (0, base_1.fail)(`${index}: element converter index out of range (0..${from.length - 1})`);
459
+ }
460
+ return converter.convert(from[index], context);
461
+ });
462
+ }
463
+ /**
464
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array.
465
+ * @remarks
466
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
467
+ * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter
468
+ * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter
469
+ * is not an array, if the requested index is negative, or if the element cannot be converted.
470
+ * @param index - The index of the element to be extracted.
471
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element.
472
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
473
+ * @public
474
+ */
475
+ function optionalElement(index, converter) {
476
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
477
+ if (index < 0) {
478
+ return (0, base_1.fail)(`${index}: cannot convert for a negative element index`);
479
+ }
480
+ else if (!Array.isArray(from)) {
481
+ return (0, base_1.fail)('element converter: source is not an array');
482
+ }
483
+ else if (index >= from.length) {
484
+ return (0, base_1.succeed)(undefined);
485
+ }
486
+ return converter.convert(from[index], context);
487
+ });
488
+ }
489
+ /**
490
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
491
+ * by name from an object.
492
+ * @remarks
493
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding
494
+ * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message
495
+ * otherwise.
496
+ * @param name - The name of the field to be extracted.
497
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted
498
+ * field.
499
+ * @public
500
+ */
501
+ function field(name, converter) {
502
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
503
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
504
+ if ((0, base_1.isKeyOf)(name, from)) {
505
+ return converter.convert(from[name], context).onFailure((message) => {
506
+ return (0, base_1.fail)(`Field ${name}: ${message}`);
507
+ });
508
+ }
509
+ return (0, base_1.fail)(`Field ${name} not found in: ${JSON.stringify(from)}`);
510
+ }
511
+ return (0, base_1.fail)(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
512
+ });
513
+ }
514
+ /**
515
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
516
+ * by name from an object.
517
+ * @remarks
518
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of
519
+ * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success}
520
+ * with `undefined` if the supplied parameter is an object but the named field is not present.
521
+ * Returns {@link Failure | Failure} with an error message otherwise.
522
+ * @param name - The name of the field to be extracted.
523
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field.
524
+ * @public
525
+ */
526
+ function optionalField(name, converter) {
527
+ return new baseConverter_1.BaseConverter((from, __self, context) => {
528
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
529
+ if ((0, base_1.isKeyOf)(name, from)) {
530
+ const result = converter.convert(from[name], context).onFailure((message) => {
531
+ return (0, base_1.fail)(`${name}: ${message}`);
532
+ });
533
+ // if conversion was successful or input was undefined we
534
+ // succeed with 'undefined', but we propagate actual
535
+ // failures.
536
+ if (result.isSuccess() || from[name] !== undefined) {
537
+ return result;
538
+ }
539
+ }
540
+ return (0, base_1.succeed)(undefined);
541
+ }
542
+ return (0, base_1.fail)(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
543
+ }, undefined, { isOptional: true });
544
+ }
545
+ /**
546
+ * Concrete implementation of {@link Converters.(object:1) | Converters.object(fields, options)}
547
+ * and {@link Converters.(object:2) | Converters.objects(fields, optionalKeys)}.
548
+ * @internal
549
+ */
550
+ function object(properties, options) {
551
+ return new objectConverter_1.ObjectConverter(properties, options);
552
+ }
553
+ /**
554
+ * Concrete implementation for {@link Converters.strictObject | Converters.strictObject(fields, options)}
555
+ * and {@link Converters.strictObject | Converters.strictObject(fields, optional)}.
556
+ * @internal
557
+ */
558
+ function strictObject(properties, opt) {
559
+ /* c8 ignore next 2 */
560
+ const options = opt && Array.isArray(opt) ? { strict: true, optionalFields: opt } : Object.assign(Object.assign({}, (opt !== null && opt !== void 0 ? opt : {})), { strict: true });
561
+ return new objectConverter_1.ObjectConverter(properties, options);
562
+ }
563
+ /**
564
+ * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape.
565
+ * @remarks
566
+ * Takes the name of the discriminator property and a
567
+ * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion,
568
+ * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of
569
+ * the discriminator property in the source object.
570
+ *
571
+ * If the source is not an object, the discriminator property is missing, or the discriminator has
572
+ * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information.
573
+ * @param discriminatorProp - Name of the property used to discriminate types.
574
+ * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators}
575
+ * to invoke, where each key corresponds to a value of the discriminator property.
576
+ * @returns A {@link Converter | Converter} which converts the corresponding discriminated object.
577
+ * @public
578
+ */
579
+ function discriminatedObject(discriminatorProp, converters) {
580
+ return new baseConverter_1.BaseConverter((from) => {
581
+ if (typeof from !== 'object' || Array.isArray(from) || from === null) {
582
+ return (0, base_1.fail)(`Not a discriminated object: "${JSON.stringify(from)}"`);
583
+ }
584
+ if (!(0, base_1.isKeyOf)(discriminatorProp, from) || !from[discriminatorProp]) {
585
+ return (0, base_1.fail)(`Discriminator property ${discriminatorProp} not present in "${JSON.stringify(from)}"`);
586
+ }
587
+ const discriminatorValue = from[discriminatorProp];
588
+ const converter = converters[discriminatorValue];
589
+ if (converter === undefined) {
590
+ return (0, base_1.fail)(`No converter for discriminator ${discriminatorProp}="${discriminatorValue}"`);
591
+ }
592
+ return converter.convert(from);
593
+ });
594
+ }
595
+ //# sourceMappingURL=basicConverters.js.map
@@ -40,6 +40,7 @@ export interface ConstraintOptions {
40
40
  */
41
41
  export interface Converter<T, TC = unknown> extends ConverterTraits {
42
42
  /**
43
+ *
43
44
  * Indicates whether this element is explicitly optional.
44
45
  */
45
46
  readonly isOptional: boolean;
@@ -188,6 +189,12 @@ export interface Converter<T, TC = unknown> extends ConverterTraits {
188
189
  * Returns a Converter which always succeeds with a default value rather than failing.
189
190
  */
190
191
  withDefault<TD = T>(dflt: TD): DefaultingConverter<T, TD, TC>;
192
+ /**
193
+ * Chains this converter with another of the same type, to be attempted if this
194
+ * converter fails.
195
+ * @param other -
196
+ */
197
+ or(other: Converter<T, TC>): Converter<T, TC>;
191
198
  }
192
199
  /**
193
200
  * @public