@orioro/util 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +1 -0
  2. package/babel.config.cjs +13 -0
  3. package/coverage/clover.xml +488 -45
  4. package/coverage/coverage-final.json +28 -2
  5. package/coverage/lcov-report/ValidationError.ts.html +184 -0
  6. package/coverage/lcov-report/base.css +19 -7
  7. package/coverage/lcov-report/block-navigation.js +87 -0
  8. package/coverage/lcov-report/favicon.png +0 -0
  9. package/coverage/lcov-report/index.html +248 -58
  10. package/coverage/lcov-report/prettify.js +1 -0
  11. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  12. package/coverage/lcov-report/sorter.js +52 -14
  13. package/coverage/lcov-report/src/debug/deepFreeze.ts.html +157 -0
  14. package/coverage/lcov-report/src/debug/index.html +146 -0
  15. package/coverage/lcov-report/src/debug/index.ts.html +91 -0
  16. package/coverage/lcov-report/src/debug/wait.ts.html +127 -0
  17. package/coverage/lcov-report/src/index.html +131 -0
  18. package/coverage/lcov-report/src/interpolate/index.html +116 -0
  19. package/coverage/lcov-report/src/interpolate/index.ts.html +277 -0
  20. package/coverage/lcov-report/src/maybeFn.ts.html +94 -0
  21. package/coverage/lcov-report/src/promise/index.html +146 -0
  22. package/coverage/lcov-report/src/promise/index.ts.html +91 -0
  23. package/coverage/lcov-report/src/promise/promiseReduce.ts.html +130 -0
  24. package/coverage/lcov-report/src/promise/resolveNestedPromises.ts.html +271 -0
  25. package/coverage/lcov-report/src/switchValue.ts.html +253 -0
  26. package/coverage/lcov-report/src/typeOf.ts.html +328 -0
  27. package/coverage/lcov-report/src/validate/ValidationError.ts.html +184 -0
  28. package/coverage/lcov-report/src/validate/async/index.html +131 -0
  29. package/coverage/lcov-report/src/validate/async/index.ts.html +241 -0
  30. package/coverage/lcov-report/src/validate/async/parseValidator.ts.html +136 -0
  31. package/coverage/lcov-report/src/validate/async/validateAsyncFn.ts.html +208 -0
  32. package/coverage/lcov-report/src/validate/async/validators/and.ts.html +154 -0
  33. package/coverage/lcov-report/src/validate/async/validators/index.html +146 -0
  34. package/coverage/lcov-report/src/validate/async/validators/index.ts.html +91 -0
  35. package/coverage/lcov-report/src/validate/async/validators/logical.ts.html +253 -0
  36. package/coverage/lcov-report/src/validate/async/validators/or.ts.html +151 -0
  37. package/coverage/lcov-report/src/validate/async/validators/shape.ts.html +565 -0
  38. package/coverage/lcov-report/src/validate/common/ValidationError.ts.html +184 -0
  39. package/coverage/lcov-report/src/validate/common/index.html +116 -0
  40. package/coverage/lcov-report/src/validate/common/util/defaultErrorMessage.ts.html +163 -0
  41. package/coverage/lcov-report/src/validate/common/util/index.html +161 -0
  42. package/coverage/lcov-report/src/validate/common/util/index.ts.html +94 -0
  43. package/coverage/lcov-report/src/validate/common/util/parseValidator.ts.html +316 -0
  44. package/coverage/lcov-report/src/validate/common/util/parseValidatorInput.ts.html +316 -0
  45. package/coverage/lcov-report/src/validate/common/util/resolveValidationResult.ts.html +277 -0
  46. package/coverage/lcov-report/src/validate/common/util/validatorParser.ts.html +316 -0
  47. package/coverage/lcov-report/src/validate/common/validators/index.html +131 -0
  48. package/coverage/lcov-report/src/validate/common/validators/index.ts.html +88 -0
  49. package/coverage/lcov-report/src/validate/common/validators/type.ts.html +388 -0
  50. package/coverage/lcov-report/src/validate/fmtValidationResult.ts.html +268 -0
  51. package/coverage/lcov-report/src/validate/index.html +116 -0
  52. package/coverage/lcov-report/src/validate/index.ts.html +94 -0
  53. package/coverage/lcov-report/src/validate/makeValidate.ts.html +634 -0
  54. package/coverage/lcov-report/src/validate/specUtil/commonTests.js.html +1324 -0
  55. package/coverage/lcov-report/src/validate/specUtil/index.html +116 -0
  56. package/coverage/lcov-report/src/validate/sync/index.html +131 -0
  57. package/coverage/lcov-report/src/validate/sync/index.ts.html +244 -0
  58. package/coverage/lcov-report/src/validate/sync/parseValidator.ts.html +136 -0
  59. package/coverage/lcov-report/src/validate/sync/validateSyncFn.ts.html +223 -0
  60. package/coverage/lcov-report/src/validate/sync/validators/and.ts.html +148 -0
  61. package/coverage/lcov-report/src/validate/sync/validators/index.html +146 -0
  62. package/coverage/lcov-report/src/validate/sync/validators/index.ts.html +91 -0
  63. package/coverage/lcov-report/src/validate/sync/validators/logical.ts.html +226 -0
  64. package/coverage/lcov-report/src/validate/sync/validators/or.ts.html +130 -0
  65. package/coverage/lcov-report/src/validate/sync/validators/shape.ts.html +523 -0
  66. package/coverage/lcov-report/src/validate/sync/validators/type.ts.html +154 -0
  67. package/coverage/lcov-report/src/validate/syncValidators/and.ts.html +157 -0
  68. package/coverage/lcov-report/src/validate/syncValidators/index.html +176 -0
  69. package/coverage/lcov-report/src/validate/syncValidators/index.ts.html +97 -0
  70. package/coverage/lcov-report/src/validate/syncValidators/or.ts.html +127 -0
  71. package/coverage/lcov-report/src/validate/syncValidators/shape.ts.html +559 -0
  72. package/coverage/lcov-report/src/validate/syncValidators/string.ts.html +163 -0
  73. package/coverage/lcov-report/src/validate/syncValidators/type.ts.html +154 -0
  74. package/coverage/lcov-report/src/validate/util/defaultErrorMessage.ts.html +169 -0
  75. package/coverage/lcov-report/src/validate/util/index.html +146 -0
  76. package/coverage/lcov-report/src/validate/util/index.ts.html +91 -0
  77. package/coverage/lcov-report/src/validate/util/resolveValidationResult.ts.html +253 -0
  78. package/coverage/lcov-report/src/validate/validate.ts.html +220 -0
  79. package/coverage/lcov-report/src/validate/validateAsync.ts.html +220 -0
  80. package/coverage/lcov-report/src/validate/validators/and.ts.html +157 -0
  81. package/coverage/lcov-report/src/validate/validators/index.html +176 -0
  82. package/coverage/lcov-report/src/validate/validators/index.ts.html +97 -0
  83. package/coverage/lcov-report/src/validate/validators/or.ts.html +127 -0
  84. package/coverage/lcov-report/src/validate/validators/shape.ts.html +541 -0
  85. package/coverage/lcov-report/src/validate/validators/type.ts.html +154 -0
  86. package/coverage/lcov-report/src/validate_/ValidationError.ts.html +184 -0
  87. package/coverage/lcov-report/src/validate_/fmtValidationResult.ts.html +268 -0
  88. package/coverage/lcov-report/src/validate_/index.html +161 -0
  89. package/coverage/lcov-report/src/validate_/makeValidate.ts.html +634 -0
  90. package/coverage/lcov-report/src/validate_/validate.ts.html +220 -0
  91. package/coverage/lcov-report/switchValue.ts.html +253 -0
  92. package/coverage/lcov-report/typeOf.ts.html +331 -0
  93. package/coverage/lcov-report/validate.ts.html +757 -0
  94. package/coverage/lcov.info +1045 -74
  95. package/dist/index.mjs +1428 -74
  96. package/jest.config.js +6 -0
  97. package/package.json +27 -27
  98. package/rollup.config.mjs +6 -0
  99. package/src/PromiseLikeEventEmitter/index.ts +35 -0
  100. package/src/array/arrayChunk.ts +7 -0
  101. package/src/array/index.ts +1 -0
  102. package/src/debug/debugFn/index.ts +48 -0
  103. package/src/debug/debugFn/util.ts +27 -0
  104. package/src/debug/deepFreeze.ts +26 -0
  105. package/src/debug/index.ts +3 -0
  106. package/src/debug/wait.ts +14 -0
  107. package/src/index.ts +8 -0
  108. package/src/interpolate/index.spec.ts +20 -0
  109. package/src/interpolate/index.ts +64 -0
  110. package/src/maybeFn.ts +3 -0
  111. package/src/promise/batchFn.spec.ts +92 -0
  112. package/src/promise/batchFn.ts +176 -0
  113. package/src/promise/index.ts +3 -0
  114. package/src/promise/promiseReduce.ts +15 -0
  115. package/src/promise/resolveNestedPromises.spec.ts +205 -0
  116. package/src/promise/resolveNestedPromises.ts +83 -0
  117. package/src/promise/types.ts +2 -0
  118. package/src/switchValue.spec.ts +30 -0
  119. package/src/switchValue.ts +59 -0
  120. package/src/typeOf.spec.ts +47 -0
  121. package/src/typeOf.ts +81 -0
  122. package/src/validate/__snapshots__/index.spec.ts.snap +9 -0
  123. package/src/validate/async/index.spec.ts +236 -0
  124. package/src/validate/async/index.ts +52 -0
  125. package/src/validate/async/validateAsyncFn.ts +41 -0
  126. package/src/validate/async/validators/index.ts +2 -0
  127. package/src/validate/async/validators/logical.ts +56 -0
  128. package/src/validate/async/validators/shape.ts +160 -0
  129. package/src/validate/async/validators/tmpand.ts +24 -0
  130. package/src/validate/async/validators/tmpor.ts +21 -0
  131. package/src/validate/common/ValidationError.ts +33 -0
  132. package/src/validate/common/util/defaultErrorMessage.ts +26 -0
  133. package/src/validate/common/util/index.ts +3 -0
  134. package/src/validate/common/util/parseValidatorInput.ts +77 -0
  135. package/src/validate/common/util/resolveValidationResult.ts +64 -0
  136. package/src/validate/common/validators/index.ts +1 -0
  137. package/src/validate/common/validators/type.ts +101 -0
  138. package/src/validate/index.spec.ts +5 -0
  139. package/src/validate/index.ts +3 -0
  140. package/src/validate/specUtil/commonTests.js +413 -0
  141. package/src/validate/sync/index.spec.ts +81 -0
  142. package/src/validate/sync/index.ts +53 -0
  143. package/src/validate/sync/validateSyncFn.ts +46 -0
  144. package/src/validate/sync/validators/index.ts +2 -0
  145. package/src/validate/sync/validators/logical.ts +47 -0
  146. package/src/validate/sync/validators/shape.ts +146 -0
  147. package/src/validate/types/async.ts +20 -0
  148. package/src/validate/types/common.ts +70 -0
  149. package/src/validate/types/index.ts +3 -0
  150. package/src/validate/types/sync.ts +20 -0
  151. package/tsconfig.json +11 -0
  152. package/array/index.js +0 -11
  153. package/coverage/lcov-report/array/index.html +0 -93
  154. package/coverage/lcov-report/array/index.js.html +0 -98
  155. package/coverage/lcov-report/coverage/coverage-final.json.html +0 -95
  156. package/coverage/lcov-report/coverage/index.html +0 -93
  157. package/coverage/lcov-report/coverage/lcov-report/index.html +0 -106
  158. package/coverage/lcov-report/coverage/lcov-report/prettify.js.html +0 -68
  159. package/coverage/lcov-report/coverage/lcov-report/sorter.js.html +0 -539
  160. package/coverage/lcov-report/fn/index.html +0 -93
  161. package/coverage/lcov-report/fn/index.js.html +0 -215
  162. package/dist/index.js +0 -116
  163. package/fn/index.js +0 -50
package/dist/index.mjs CHANGED
@@ -1,111 +1,1465 @@
1
- function _typeof(obj) {
2
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
3
- _typeof = function (obj) {
4
- return typeof obj;
5
- };
6
- } else {
7
- _typeof = function (obj) {
8
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
9
- };
10
- }
1
+ import { getProperty } from 'dot-prop';
2
+ import traverse from 'traverse';
3
+ import copy from 'fast-copy';
4
+ import EventEmitter from 'eventemitter3';
5
+
6
+ function _typeof(o) {
7
+ "@babel/helpers - typeof";
11
8
 
12
- return _typeof(obj);
9
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
10
+ return typeof o;
11
+ } : function (o) {
12
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
13
+ }, _typeof(o);
13
14
  }
14
15
 
15
- function _toConsumableArray(arr) {
16
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
16
+ /*!
17
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
18
+ *
19
+ * Copyright (c) 2014-2017, Jon Schlinkert.
20
+ * Released under the MIT License.
21
+ */
22
+
23
+ function isObject(o) {
24
+ return Object.prototype.toString.call(o) === '[object Object]';
17
25
  }
26
+ function isPlainObject(o) {
27
+ var ctor, prot;
28
+ if (isObject(o) === false) return false;
29
+
30
+ // If has modified constructor
31
+ ctor = o.constructor;
32
+ if (ctor === undefined) return true;
18
33
 
19
- function _arrayWithoutHoles(arr) {
20
- if (Array.isArray(arr)) {
21
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
34
+ // If has modified prototype
35
+ prot = ctor.prototype;
36
+ if (isObject(prot) === false) return false;
22
37
 
23
- return arr2;
38
+ // If constructor does not have an Object-specific method
39
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
40
+ return false;
24
41
  }
42
+
43
+ // Most likely a plain Object
44
+ return true;
25
45
  }
26
46
 
27
- function _iterableToArray(iter) {
28
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
47
+ //
48
+ // The only role of this function is to let typescript
49
+ // be aware of the available types
50
+ //
51
+ function typeMap(typeMap) {
52
+ return typeMap;
53
+ }
54
+ function makeTypeOf(typeMap) {
55
+ return function typeOf(value) {
56
+ for (var typeName in typeMap) {
57
+ if (typeMap[typeName](value)) {
58
+ return typeName;
59
+ }
60
+ }
61
+ return null;
62
+ };
63
+ }
64
+ function basicType(typeName) {
65
+ return function (value) {
66
+ return _typeof(value) === typeName;
67
+ };
29
68
  }
69
+ var DEFAULT_TYPES = typeMap({
70
+ //
71
+ // Primitives
72
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#primitive_values
73
+ //
74
+ "null": function _null(value) {
75
+ return value === null;
76
+ },
77
+ undefined: basicType('undefined'),
78
+ "boolean": basicType('boolean'),
79
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
80
+ number: function number(value) {
81
+ return typeof value === 'number' && !Number.isNaN(value);
82
+ },
83
+ bigint: basicType('bigint'),
84
+ string: basicType('string'),
85
+ symbol: basicType('symbol'),
86
+ "function": basicType('function'),
87
+ object: isPlainObject,
88
+ array: function array(value) {
89
+ return Array.isArray(value);
90
+ },
91
+ regexp: function regexp(value) {
92
+ return value instanceof RegExp;
93
+ },
94
+ nan: function nan(value) {
95
+ return Number.isNaN(value);
96
+ },
97
+ date: function date(value) {
98
+ return value instanceof Date;
99
+ },
100
+ map: function map(value) {
101
+ return value instanceof Map;
102
+ },
103
+ weakmap: function weakmap(value) {
104
+ return value instanceof WeakMap;
105
+ },
106
+ set: function set(value) {
107
+ return value instanceof Set;
108
+ },
109
+ weakset: function weakset(value) {
110
+ return value instanceof WeakSet;
111
+ },
112
+ promise: function promise(value) {
113
+ return value instanceof Promise;
114
+ },
115
+ error: function error(value) {
116
+ return value instanceof Error;
117
+ }
118
+ });
119
+ var typeOf = makeTypeOf(DEFAULT_TYPES);
30
120
 
31
- function _nonIterableSpread() {
32
- throw new TypeError("Invalid attempt to spread non-iterable instance");
121
+ function testCriteria(criteria, input) {
122
+ switch (_typeof(criteria)) {
123
+ case 'function':
124
+ {
125
+ return criteria(input);
126
+ }
127
+ case 'object':
128
+ {
129
+ if (criteria instanceof RegExp) {
130
+ return criteria.test(input);
131
+ } else {
132
+ throw new Error('Unsupported criteria');
133
+ }
134
+ }
135
+ case 'string':
136
+ case 'symbol':
137
+ {
138
+ return criteria === input;
139
+ }
140
+ }
141
+ }
142
+ function switchValue(input, cases) {
143
+ if (Array.isArray(cases)) {
144
+ var matching = cases.find(function (case_) {
145
+ return case_.length === 1 || testCriteria(case_[0], input);
146
+ });
147
+ return matching ? matching.length === 1 ? matching[0] : matching[1] : undefined;
148
+ } else {
149
+ return cases[input] || cases["default"];
150
+ }
151
+ }
152
+ function switchExec(input, cases) {
153
+ var args = [];
154
+ for (var _i = 2; _i < arguments.length; _i++) {
155
+ args[_i - 2] = arguments[_i];
156
+ }
157
+ var fn = switchValue(input, cases);
158
+ return fn.apply(void 0, args);
33
159
  }
34
160
 
35
- var mingo = require('mingo');
161
+ var TYPE_RE = /([a-z0-9]+)(\!)?$/i;
162
+ var TYPE_SEPARATOR_RE = /\s*\|\s*/g;
163
+ function parseSingleType(typeInput) {
164
+ var match = typeInput.match(TYPE_RE);
165
+ if (!match) {
166
+ throw new Error("Invalid type ".concat(typeInput));
167
+ } else {
168
+ var typeName = match[1],
169
+ requiredSignal = match[2];
170
+ return {
171
+ type: typeName,
172
+ required: requiredSignal === '!'
173
+ };
174
+ }
175
+ }
176
+ function serializeExpectedTypes(expectedTypes) {
177
+ return expectedTypes.map(function (expectedType) {
178
+ return "".concat(expectedType.type).concat(expectedType.required ? '!' : '');
179
+ }).join(' | ');
180
+ }
181
+ function parseExpectedTypes(expectedTypesInput) {
182
+ switch (typeOf(expectedTypesInput)) {
183
+ case 'string':
184
+ {
185
+ return expectedTypesInput.split(TYPE_SEPARATOR_RE).map(function (typeInput) {
186
+ return parseSingleType(typeInput);
187
+ });
188
+ }
189
+ case 'array':
190
+ {
191
+ return expectedTypesInput.map(function (expectedType) {
192
+ return typeof expectedType === 'string' ? parseSingleType(expectedType) : expectedType;
193
+ });
194
+ }
195
+ case 'object':
196
+ {
197
+ return [expectedTypesInput];
198
+ }
199
+ default:
200
+ {
201
+ throw new Error("Invalid expectedType ".concat(expectedTypesInput));
202
+ }
203
+ }
204
+ }
205
+ function typeValidator(expectedTypesInput) {
206
+ var expectedTypes = parseExpectedTypes(expectedTypesInput);
207
+ return function validateType(input) {
208
+ var inputType = typeOf(input);
209
+ var nullOrUndefined = function nullOrUndefined() {
210
+ return expectedTypes.some(function (expectedType) {
211
+ return expectedType.type === 'undefined' || expectedType.type === 'null' || expectedType.required === false;
212
+ });
213
+ };
214
+ var isValid = switchExec(inputType, {
215
+ "null": nullOrUndefined,
216
+ undefined: nullOrUndefined,
217
+ "default": function _default() {
218
+ return expectedTypes.some(function (expectedType) {
219
+ return expectedType.type === inputType;
220
+ });
221
+ }
222
+ });
223
+ if (isValid) {
224
+ return true;
225
+ } else {
226
+ return {
227
+ expectedTypes: serializeExpectedTypes(expectedTypes),
228
+ input: input
229
+ };
230
+ }
231
+ };
232
+ }
36
233
 
37
- var _test = function _test(criteria) {
38
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
39
- args[_key - 1] = arguments[_key];
234
+ //
235
+ // And operator (serial)
236
+ //
237
+ function and$1(validators) {
238
+ return function validateAnd(input, _a) {
239
+ var validateSync = _a.validateSync;
240
+ var result = validators.reduce(function (acc, validator) {
241
+ return acc !== true ? acc : validateSync(validator, input);
242
+ }, true);
243
+ if (result === true) {
244
+ return true;
245
+ } else {
246
+ return result;
247
+ }
248
+ };
249
+ }
250
+ //
251
+ // Or operator (serial)
252
+ //
253
+ function or$1(validators) {
254
+ return function validateOr(input, _a) {
255
+ var validateSync = _a.validateSync;
256
+ var someIsValid = validators.some(function (validator) {
257
+ return validateSync(validator, input) === true;
258
+ });
259
+ return someIsValid;
260
+ };
261
+ }
262
+ //
263
+ // Not
264
+ //
265
+ function not$1(validator) {
266
+ return function validateNot(input, _a) {
267
+ var validateSync = _a.validateSync;
268
+ return validateSync(validator, input) !== true;
269
+ };
270
+ }
271
+
272
+ /******************************************************************************
273
+ Copyright (c) Microsoft Corporation.
274
+
275
+ Permission to use, copy, modify, and/or distribute this software for any
276
+ purpose with or without fee is hereby granted.
277
+
278
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
279
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
280
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
281
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
282
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
283
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
284
+ PERFORMANCE OF THIS SOFTWARE.
285
+ ***************************************************************************** */
286
+ /* global Reflect, Promise, SuppressedError, Symbol */
287
+
288
+ var _extendStatics = function extendStatics(d, b) {
289
+ _extendStatics = Object.setPrototypeOf || {
290
+ __proto__: []
291
+ } instanceof Array && function (d, b) {
292
+ d.__proto__ = b;
293
+ } || function (d, b) {
294
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
295
+ };
296
+ return _extendStatics(d, b);
297
+ };
298
+ function __extends(d, b) {
299
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
300
+ _extendStatics(d, b);
301
+ function __() {
302
+ this.constructor = d;
40
303
  }
304
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
305
+ }
306
+ var _assign = function __assign() {
307
+ _assign = Object.assign || function __assign(t) {
308
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
309
+ s = arguments[i];
310
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
311
+ }
312
+ return t;
313
+ };
314
+ return _assign.apply(this, arguments);
315
+ };
316
+ function __rest(s, e) {
317
+ var t = {};
318
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
319
+ if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
320
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
321
+ }
322
+ return t;
323
+ }
324
+ function __awaiter(thisArg, _arguments, P, generator) {
325
+ function adopt(value) {
326
+ return value instanceof P ? value : new P(function (resolve) {
327
+ resolve(value);
328
+ });
329
+ }
330
+ return new (P || (P = Promise))(function (resolve, reject) {
331
+ function fulfilled(value) {
332
+ try {
333
+ step(generator.next(value));
334
+ } catch (e) {
335
+ reject(e);
336
+ }
337
+ }
338
+ function rejected(value) {
339
+ try {
340
+ step(generator["throw"](value));
341
+ } catch (e) {
342
+ reject(e);
343
+ }
344
+ }
345
+ function step(result) {
346
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
347
+ }
348
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
349
+ });
350
+ }
351
+ function __generator(thisArg, body) {
352
+ var _ = {
353
+ label: 0,
354
+ sent: function sent() {
355
+ if (t[0] & 1) throw t[1];
356
+ return t[1];
357
+ },
358
+ trys: [],
359
+ ops: []
360
+ },
361
+ f,
362
+ y,
363
+ t,
364
+ g;
365
+ return g = {
366
+ next: verb(0),
367
+ "throw": verb(1),
368
+ "return": verb(2)
369
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
370
+ return this;
371
+ }), g;
372
+ function verb(n) {
373
+ return function (v) {
374
+ return step([n, v]);
375
+ };
376
+ }
377
+ function step(op) {
378
+ if (f) throw new TypeError("Generator is already executing.");
379
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
380
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
381
+ if (y = 0, t) op = [op[0] & 2, t.value];
382
+ switch (op[0]) {
383
+ case 0:
384
+ case 1:
385
+ t = op;
386
+ break;
387
+ case 4:
388
+ _.label++;
389
+ return {
390
+ value: op[1],
391
+ done: false
392
+ };
393
+ case 5:
394
+ _.label++;
395
+ y = op[1];
396
+ op = [0];
397
+ continue;
398
+ case 7:
399
+ op = _.ops.pop();
400
+ _.trys.pop();
401
+ continue;
402
+ default:
403
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
404
+ _ = 0;
405
+ continue;
406
+ }
407
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
408
+ _.label = op[1];
409
+ break;
410
+ }
411
+ if (op[0] === 6 && _.label < t[1]) {
412
+ _.label = t[1];
413
+ t = op;
414
+ break;
415
+ }
416
+ if (t && _.label < t[2]) {
417
+ _.label = t[2];
418
+ _.ops.push(op);
419
+ break;
420
+ }
421
+ if (t[2]) _.ops.pop();
422
+ _.trys.pop();
423
+ continue;
424
+ }
425
+ op = body.call(thisArg, _);
426
+ } catch (e) {
427
+ op = [6, e];
428
+ y = 0;
429
+ } finally {
430
+ f = t = 0;
431
+ }
432
+ if (op[0] & 5) throw op[1];
433
+ return {
434
+ value: op[0] ? op[1] : void 0,
435
+ done: true
436
+ };
437
+ }
438
+ }
439
+ function __spreadArray(to, from, pack) {
440
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
441
+ if (ar || !(i in from)) {
442
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
443
+ ar[i] = from[i];
444
+ }
445
+ }
446
+ return to.concat(ar || Array.prototype.slice.call(from));
447
+ }
448
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
449
+ var e = new Error(message);
450
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
451
+ };
452
+
453
+ function _shapeGeneralValidator$1(_a) {
454
+ var input = _a.input,
455
+ baseType = _a.baseType,
456
+ collectNestedErrors = _a.collectNestedErrors,
457
+ validateSync = _a.validateSync;
458
+ var baseTypeValidation = validateSync(typeValidator({
459
+ type: baseType,
460
+ required: true
461
+ }), input);
462
+ if (baseTypeValidation !== true) {
463
+ return baseTypeValidation;
464
+ }
465
+ var nestedErrors = collectNestedErrors();
466
+ return nestedErrors.length === 0 ? true : {
467
+ input: input,
468
+ nestedErrors: nestedErrors
469
+ };
470
+ }
471
+ function obj$1(objShape) {
472
+ return function validateObject(input, _a) {
473
+ var validateSync = _a.validateSync;
474
+ return _shapeGeneralValidator$1({
475
+ input: input,
476
+ baseType: 'object',
477
+ validateSync: validateSync,
478
+ collectNestedErrors: function collectNestedErrors() {
479
+ return Object.entries(objShape).reduce(function (acc, _a) {
480
+ var path = _a[0],
481
+ pathValidator = _a[1];
482
+ var pathInput = getProperty(input, path);
483
+ var pathResult = validateSync(pathValidator, pathInput);
484
+ return pathResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, pathResult), {
485
+ path: path
486
+ })], false);
487
+ }, []);
488
+ }
489
+ });
490
+ };
491
+ }
492
+ function objOf$1(ofType) {
493
+ return function validateObjOf(input, _a) {
494
+ var validateSync = _a.validateSync;
495
+ return _shapeGeneralValidator$1({
496
+ input: input,
497
+ baseType: 'object',
498
+ validateSync: validateSync,
499
+ collectNestedErrors: function collectNestedErrors() {
500
+ return Object.entries(input).reduce(function (acc, _a) {
501
+ var key = _a[0],
502
+ keyInput = _a[1];
503
+ var indexResult = validateSync(ofType, keyInput);
504
+ return indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
505
+ path: key
506
+ })], false);
507
+ }, []);
508
+ }
509
+ });
510
+ };
511
+ }
512
+ function tuple$1(tupleShape) {
513
+ return function validateTuple(input, _a) {
514
+ var validateSync = _a.validateSync;
515
+ return _shapeGeneralValidator$1({
516
+ input: input,
517
+ baseType: 'array',
518
+ validateSync: validateSync,
519
+ collectNestedErrors: function collectNestedErrors() {
520
+ return tupleShape.reduce(function (acc, indexValidator, index) {
521
+ var indexInput = input[index];
522
+ var indexResult = validateSync(indexValidator, indexInput);
523
+ return indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
524
+ path: index + ''
525
+ })], false);
526
+ }, []);
527
+ }
528
+ });
529
+ };
530
+ }
531
+ function arrayOf$1(ofType) {
532
+ return function validateArrayOf(input, _a) {
533
+ var validateSync = _a.validateSync;
534
+ return _shapeGeneralValidator$1({
535
+ input: input,
536
+ baseType: 'array',
537
+ validateSync: validateSync,
538
+ collectNestedErrors: function collectNestedErrors() {
539
+ return input.reduce(function (acc, indexInput, index) {
540
+ var indexResult = validateSync(ofType, indexInput);
541
+ return indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
542
+ path: index + ''
543
+ })], false);
544
+ }, []);
545
+ }
546
+ });
547
+ };
548
+ }
41
549
 
42
- if (_typeof(criteria) === 'object') {
43
- var query = new mingo.Query(criteria);
44
- return query.test(args[0]);
45
- } else if (typeof criteria === 'function') {
46
- return criteria.apply(void 0, args);
550
+ function defaultErrorMessage(_a) {
551
+ var input = _a.input,
552
+ message = _a.message,
553
+ nestedErrors = _a.nestedErrors,
554
+ expectedTypes = _a.expectedTypes;
555
+ if (message) {
556
+ return message;
557
+ }
558
+ if (nestedErrors) {
559
+ return "Invalid input: `".concat(JSON.stringify(input), "`.\n").concat(nestedErrors.map(function (error) {
560
+ return " - ".concat(error.path, ": ").concat(error.message);
561
+ }).join('\n'));
562
+ } else if (expectedTypes) {
563
+ var inputType = typeOf(input);
564
+ return "Invalid input: '".concat(input, "'. Expected type(s) `").concat(expectedTypes, "`, but got type `").concat(inputType === null ? 'unknown' : inputType, "`");
47
565
  } else {
48
- return criteria;
566
+ return "Invalid input: '".concat(input, "'.");
49
567
  }
50
- };
568
+ }
51
569
 
52
- var _fnApply = function _fnApply(fnSpec) {
53
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
54
- args[_key2 - 1] = arguments[_key2];
570
+ function resolveValidationResult(_a) {
571
+ var input = _a.input,
572
+ result = _a.result,
573
+ errorMessage = _a.errorMessage;
574
+ if (result === true) {
575
+ return true;
576
+ } else {
577
+ var _falseLikeResult = function _falseLikeResult() {
578
+ return {
579
+ message: errorMessage({
580
+ input: input
581
+ })
582
+ };
583
+ };
584
+ return _assign({
585
+ input: input
586
+ }, switchExec(typeOf(result), {
587
+ string: function string() {
588
+ return {
589
+ message: result
590
+ };
591
+ },
592
+ error: function error() {
593
+ return {
594
+ message: result.message,
595
+ error: result
596
+ };
597
+ },
598
+ object: function object() {
599
+ var result_ = result;
600
+ return _assign(_assign({}, result_), {
601
+ message: errorMessage(result_)
602
+ });
603
+ },
604
+ //
605
+ // Boolean result here MUST be false, as true was tested earlier
606
+ //
607
+ "boolean": _falseLikeResult,
608
+ "null": _falseLikeResult,
609
+ undefined: _falseLikeResult,
610
+ //
611
+ // Unsupported validation result
612
+ //
613
+ "default": function _default() {
614
+ throw new Error("Invalid validation result: ".concat(result, " (").concat(typeOf(result), ")"));
615
+ }
616
+ }));
55
617
  }
618
+ }
56
619
 
57
- return typeof fnSpec === 'function' ? fnSpec.apply(void 0, args) : fnSpec.fn.apply(fnSpec, args);
58
- };
620
+ /**
621
+ * /\$\{\s*([\w$.]+)\s*\}/g
622
+ * ![](docs/resources/interpolation_regexp.png)
623
+ *
624
+ * RegExp used for matching interpolation expressions.
625
+ * Allows a non-interrupted sequence of alphanumeric chars ([A-Za-z0-9_]),
626
+ * dollar signs ($) and dots (.) wrapped in curly braces ({})
627
+ * with or without any number of whitespace chars (' ') between braces and the
628
+ * value identifier.
629
+ *
630
+ * Some resources on RegExp safety concerning RegExp Denial of Service (ReDOS)
631
+ * through Catastrophic backtracking, for future study and reference:
632
+ *
633
+ * - [Catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)
634
+ * - [Regular expression visualizer](https://github.com/CJex/regulex)
635
+ * - [Validator.js](https://github.com/validatorjs/validator.js)
636
+ * - [Stack Overflow interesting question](https://stackoverflow.com/questions/63127145/safe-regex-patterns-from-redos-attack)
637
+ * - [Catastrophic backtracking - JavaScript Info](https://javascript.info/regexp-catastrophic-backtracking#preventing-backtracking)
638
+ * - [Google re2 library](https://github.com/google/re2)
639
+ * - [Google re2 for Node.js - re2](https://github.com/uhop/node-re2/)
640
+ *
641
+ * @const {RegExp} INTERPOLATION_REGEXP
642
+ */
643
+ var INTERPOLATION_REGEXP = /\$\{\s*([\w$.]+)\s*\}/g;
644
+ /**
645
+ * @function $stringInterpolate
646
+ * @param {String} template Basic JS template string like `${value.path}` value
647
+ * interpolation. It is possible to access nested properties
648
+ * through dot `.` notation. Keywords between braces are
649
+ * only interpreted as paths to the value. No logic
650
+ * supported: loops, conditionals, etc.
651
+ * @param {Object | Array} data Data context to be used for interpolation
652
+ */
653
+ function interpolate(template, data, _a) {
654
+ var _b = _a === void 0 ? {} : _a,
655
+ _c = _b.maxLength,
656
+ maxLength = _c === void 0 ? 10000 : _c;
657
+ if (template.length > maxLength) {
658
+ throw new Error("Template exceeds maxLength ".concat(maxLength));
659
+ }
660
+ return template.replace(INTERPOLATION_REGEXP, function (_, path) {
661
+ var value = getProperty(data, path);
662
+ switch (_typeof(value)) {
663
+ case 'number':
664
+ {
665
+ return value + '';
666
+ }
667
+ case 'string':
668
+ {
669
+ return value;
670
+ }
671
+ default:
672
+ {
673
+ console.warn("Attempting to use non interpolatable value in interpolate ".concat(value));
674
+ return '';
675
+ }
676
+ }
677
+ });
678
+ }
59
679
 
60
- var applyMatching = function applyMatching(fnSpecList) {
61
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
62
- args[_key3 - 1] = arguments[_key3];
680
+ function parseValidatorInput(_a, validatorInput) {
681
+ var objValidator = _a.objValidator;
682
+ //
683
+ // Parses the validator fn.
684
+ // If provided with a string, will return a type validator
685
+ // If provided with a function, will return the function itself
686
+ //
687
+ function _parseValidatorFn(fnInput) {
688
+ switch (typeOf(fnInput)) {
689
+ case 'string':
690
+ {
691
+ return typeValidator(fnInput);
692
+ }
693
+ case 'object':
694
+ {
695
+ return objValidator(fnInput);
696
+ }
697
+ case 'function':
698
+ {
699
+ return fnInput;
700
+ }
701
+ default:
702
+ {
703
+ throw new TypeError("Unsupported fnInput ".concat(fnInput));
704
+ }
705
+ }
706
+ }
707
+ function _parseValidatorErrorMessageFn(fnInput) {
708
+ switch (_typeof(fnInput)) {
709
+ case 'string':
710
+ {
711
+ return function (details) {
712
+ return interpolate(fnInput, details);
713
+ };
714
+ }
715
+ case 'function':
716
+ {
717
+ return fnInput;
718
+ }
719
+ default:
720
+ {
721
+ throw new TypeError("Unsupported error message input ".concat(fnInput));
722
+ }
723
+ }
63
724
  }
725
+ //
726
+ // Parses the validator input. For more details, see:
727
+ // types/common.ts -> ValidatorSystem
728
+ //
729
+ // Ensures the return result is always of the following format:
730
+ // [ValidatorFn, ValidatorErrorMessageInput]
731
+ //
732
+ var _b = Array.isArray(validatorInput) ? validatorInput : [validatorInput, defaultErrorMessage],
733
+ fnInput = _b[0],
734
+ errorMessageInput = _b[1];
735
+ return [_parseValidatorFn(fnInput), _parseValidatorErrorMessageFn(errorMessageInput)];
736
+ }
64
737
 
65
- var matching = fnSpecList.find(function (fnSpec) {
66
- return _test.apply(void 0, [fnSpec.criteria].concat(args));
738
+ function validateSyncFn(validatorInput, input) {
739
+ var result;
740
+ var _a = parseValidatorInput({
741
+ objValidator: obj$1
742
+ }, validatorInput),
743
+ validatorFn = _a[0],
744
+ errorMessage = _a[1];
745
+ try {
746
+ result = validatorFn(input, {
747
+ validateSync: validateSyncFn
748
+ });
749
+ } catch (err) {
750
+ result = err;
751
+ }
752
+ if (result instanceof Promise) {
753
+ throw new Error('Promises not supported in sync validation method');
754
+ }
755
+ return resolveValidationResult({
756
+ errorMessage: errorMessage,
757
+ input: input,
758
+ result: result
67
759
  });
760
+ }
68
761
 
69
- if (matching) {
70
- return _fnApply.apply(void 0, [matching].concat(args));
762
+ var ValidationError = /** @class */function (_super) {
763
+ __extends(ValidationError, _super);
764
+ function ValidationError(_a) {
765
+ var _this = this;
766
+ var message = _a.message,
767
+ details = __rest(_a, ["message"]);
768
+ _this = _super.call(this, message || "Invalid input ".concat(details.input)) || this;
769
+ _this.name = 'ValidationError';
770
+ // Capture correct stack trace in V8 environments (Node.js, Google Chrome)
771
+ if (Error.captureStackTrace) {
772
+ Error.captureStackTrace(_this, ValidationError);
773
+ }
774
+ Object.assign(_this, details);
775
+ return _this;
776
+ }
777
+ ValidationError.prototype.toJSON = function () {
778
+ return {
779
+ message: this.message,
780
+ input: this.input,
781
+ code: this.code,
782
+ error: this.error,
783
+ path: this.path,
784
+ nestedErrors: this.nestedErrors
785
+ };
786
+ };
787
+ return ValidationError;
788
+ }(Error);
789
+
790
+ function assertValidSync(validator, input) {
791
+ var validationResult = validate(validator, input);
792
+ if (validationResult === true) {
793
+ return input;
71
794
  } else {
72
- throw new Error('No matching spec');
795
+ throw new ValidationError(validationResult);
73
796
  }
74
- };
797
+ }
798
+ var validate = validateSyncFn;
799
+ validate.type = typeValidator;
800
+ validate.obj = obj$1;
801
+ validate.objOf = objOf$1;
802
+ validate.tuple = tuple$1;
803
+ validate.arrayOf = arrayOf$1;
804
+ validate.and = and$1;
805
+ validate.or = or$1;
806
+ validate.not = not$1;
807
+ validate.assertValid = assertValidSync;
808
+
809
+ function promiseReduce(inputArr, reducerFn, initial) {
810
+ return inputArr.reduce(function (prevPromise, input, index) {
811
+ return prevPromise.then(function (acc) {
812
+ return reducerFn(acc, input, index);
813
+ });
814
+ }, Promise.resolve(initial));
815
+ }
75
816
 
76
- var applyMatchingReduce = function applyMatchingReduce(fnSpecList, arg) {
77
- var injectArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
78
- return fnSpecList.reduce(function (acc, fnSpec) {
79
- return _test(fnSpec.criteria, acc) ? _fnApply.apply(void 0, [fnSpec, acc].concat(_toConsumableArray(injectArgs))) : acc;
80
- }, arg);
817
+ var DEFAULT_OPTIONS = {
818
+ mode: 'eager',
819
+ maxDepth: 30,
820
+ clone: copy
81
821
  };
822
+ function _echo(input) {
823
+ return input;
824
+ }
825
+ function resolveNestedPromises(node, options, ctx) {
826
+ if (options === void 0) {
827
+ options = {};
828
+ }
829
+ if (ctx === void 0) {
830
+ ctx = {
831
+ root: node,
832
+ depth: 0
833
+ };
834
+ }
835
+ return __awaiter(this, void 0, void 0, function () {
836
+ var opts, promises, _cloneFn, clonedNode, resolved;
837
+ return __generator(this, function (_a) {
838
+ opts = _assign(_assign({}, DEFAULT_OPTIONS), options);
839
+ promises = [];
840
+ _cloneFn = opts.clone || _echo;
841
+ clonedNode = _cloneFn(node);
842
+ resolved = traverse(clonedNode).forEach(function (value) {
843
+ var _this = this;
844
+ var depth = ctx.depth + this.path.length;
845
+ if (depth > opts.maxDepth) {
846
+ throw new Error("Max depth exceeded: { depth: ".concat(depth, ", maxDepth: ").concat(opts.maxDepth, " }"));
847
+ }
848
+ if (value instanceof Promise) {
849
+ var updatePromise = value.then(function (resolvedValue) {
850
+ return __awaiter(_this, void 0, void 0, function () {
851
+ var _a, _b;
852
+ return __generator(this, function (_c) {
853
+ switch (_c.label) {
854
+ case 0:
855
+ // Arrow function;
856
+ // this refers to outside this ctx
857
+ _a = this.update;
858
+ if (!(opts.mode === 'eager')) return [3 /*break*/, 2];
859
+ return [4 /*yield*/, resolveNestedPromises(resolvedValue, opts, _assign(_assign({}, ctx), {
860
+ // pass the base depth of the current value
861
+ depth: depth
862
+ }))];
863
+ case 1:
864
+ _b = _c.sent();
865
+ return [3 /*break*/, 3];
866
+ case 2:
867
+ _b = resolvedValue;
868
+ _c.label = 3;
869
+ case 3:
870
+ // Arrow function;
871
+ // this refers to outside this ctx
872
+ _a.apply(this, [_b]);
873
+ return [2 /*return*/];
874
+ }
875
+ });
876
+ });
877
+ });
878
+ promises = __spreadArray(__spreadArray([], promises, true), [updatePromise], false);
879
+ }
880
+ });
881
+ return [2 /*return*/, Promise.all(promises).then(function () {
882
+ return resolved;
883
+ })];
884
+ });
885
+ });
886
+ }
887
+
888
+ function arrayChunk(array, chunkSize) {
889
+ var chunks = [];
890
+ for (var i = 0; i < array.length; i += chunkSize) {
891
+ chunks.push(array.slice(i, i + chunkSize));
892
+ }
893
+ return chunks;
894
+ }
82
895
 
83
- var applyMatchingReduceAsync = function applyMatchingReduceAsync(fnSpecList, arg) {
84
- var injectArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
85
- return fnSpecList.reduce(function (previous, fnSpec) {
86
- return previous.then(function (res) {
87
- return _test(fnSpec.criteria, res) ? Promise.resolve(_fnApply.apply(void 0, [fnSpec, res].concat(_toConsumableArray(injectArgs)))) : Promise.resolve(res);
896
+ var PromiseLikeEventEmitter = /** @class */function (_super) {
897
+ __extends(PromiseLikeEventEmitter, _super);
898
+ function PromiseLikeEventEmitter() {
899
+ var _this = _super.call(this) || this;
900
+ _this.promise = new Promise(function (resolve, reject) {
901
+ _this.resolve = resolve;
902
+ _this.reject = reject;
88
903
  });
89
- }, Promise.resolve(arg));
90
- };
904
+ return _this;
905
+ }
906
+ PromiseLikeEventEmitter.prototype.then = function (onFulfilled, onRejected) {
907
+ return this.promise.then(onFulfilled, onRejected);
908
+ };
909
+ PromiseLikeEventEmitter.prototype["catch"] = function (onRejected) {
910
+ return this.promise["catch"](onRejected);
911
+ };
912
+ PromiseLikeEventEmitter.prototype["finally"] = function (onFinally) {
913
+ return this.promise["finally"](onFinally);
914
+ };
915
+ return PromiseLikeEventEmitter;
916
+ }(EventEmitter);
91
917
 
92
- module.exports = {
93
- applyMatching: applyMatching,
94
- applyMatchingReduce: applyMatchingReduce,
95
- applyMatchingReduceAsync: applyMatchingReduceAsync
96
- };
918
+ var SKIPPED = Symbol();
919
+ function batchFn(fn, _a) {
920
+ var _b = _a === void 0 ? {} : _a,
921
+ _c = _b.batchSize,
922
+ batchSize = _c === void 0 ? 10 : _c,
923
+ skip = _b.skip;
924
+ return function batchExec(items) {
925
+ var _this = this;
926
+ var batches = arrayChunk(items, batchSize);
927
+ var promise = new PromiseLikeEventEmitter();
928
+ // const events = new EventEmitter<EventTypes>()
929
+ var progressCount = 0;
930
+ var resultsPromise = promiseReduce(batches, function (acc, batchItems, index) {
931
+ return __awaiter(_this, void 0, void 0, function () {
932
+ var batch, batchResults;
933
+ var _this = this;
934
+ return __generator(this, function (_a) {
935
+ switch (_a.label) {
936
+ case 0:
937
+ batch = {
938
+ index: index,
939
+ items: batchItems
940
+ };
941
+ promise.emit('batchStart', {
942
+ batch: batch
943
+ });
944
+ return [4 /*yield*/, Promise.all(batchItems.map(function (item) {
945
+ return __awaiter(_this, void 0, void 0, function () {
946
+ var itemSkip, itemResult, _a, err_1;
947
+ return __generator(this, function (_b) {
948
+ switch (_b.label) {
949
+ case 0:
950
+ _b.trys.push([0, 5,, 6]);
951
+ promise.emit('itemStart', {
952
+ batch: batch,
953
+ item: item
954
+ });
955
+ return [4 /*yield*/, typeof skip === 'function' && skip(item)];
956
+ case 1:
957
+ itemSkip = _b.sent();
958
+ if (itemSkip) {
959
+ promise.emit('itemSkip', {
960
+ batch: batch,
961
+ item: item
962
+ });
963
+ }
964
+ if (!itemSkip) return [3 /*break*/, 2];
965
+ _a = SKIPPED;
966
+ return [3 /*break*/, 4];
967
+ case 2:
968
+ return [4 /*yield*/, fn(item)];
969
+ case 3:
970
+ _a = _b.sent();
971
+ _b.label = 4;
972
+ case 4:
973
+ itemResult = _a;
974
+ progressCount += 1;
975
+ promise.emit('progress', {
976
+ type: itemSkip ? 'skip' : 'data',
977
+ batch: batch,
978
+ progress: progressCount / items.length,
979
+ item: item,
980
+ result: itemResult
981
+ });
982
+ return [2 /*return*/, itemResult];
983
+ case 5:
984
+ err_1 = _b.sent();
985
+ progressCount += 1;
986
+ promise.emit('progress', {
987
+ type: 'error',
988
+ batch: batch,
989
+ progress: progressCount / items.length,
990
+ item: item,
991
+ result: err_1
992
+ });
993
+ return [2 /*return*/, err_1];
994
+ case 6:
995
+ return [2 /*return*/];
996
+ }
997
+ });
998
+ });
999
+ }))];
1000
+ case 1:
1001
+ batchResults = _a.sent();
1002
+ promise.emit('batchProgress', {
1003
+ batch: batch,
1004
+ progress: batch.index + 1 / batches.length,
1005
+ results: batchResults
1006
+ });
1007
+ return [2 /*return*/, __spreadArray(__spreadArray([], acc, true), batchResults, true)];
1008
+ }
1009
+ });
1010
+ });
1011
+ }, []);
1012
+ resultsPromise.then(function (results) {
1013
+ promise.resolve(results);
1014
+ promise.emit('results', {
1015
+ results: results
1016
+ });
1017
+ }, function (err) {
1018
+ promise.reject(err);
1019
+ promise.emit('error', err);
1020
+ });
1021
+ return promise;
1022
+ };
1023
+ }
1024
+ function parseBatchedResults(inputs, results) {
1025
+ return results.reduce(function (acc, result, index) {
1026
+ if (result === SKIPPED) {
1027
+ return _assign(_assign({}, acc), {
1028
+ skipped: __spreadArray(__spreadArray([], acc.skipped, true), [inputs[index]], false)
1029
+ });
1030
+ } else if (result instanceof Error) {
1031
+ return _assign(_assign({}, acc), {
1032
+ errors: __spreadArray(__spreadArray([], acc.errors, true), [result], false)
1033
+ });
1034
+ } else {
1035
+ return _assign(_assign({}, acc), {
1036
+ results: __spreadArray(__spreadArray([], acc.results, true), [result], false)
1037
+ });
1038
+ }
1039
+ }, {
1040
+ results: [],
1041
+ errors: [],
1042
+ skipped: []
1043
+ });
1044
+ }
97
1045
 
98
- var arrayReduceAsync = function arrayReduceAsync(arr, fn, initial) {
99
- return arr.reduce(function (previousPromise, item, index) {
100
- return previousPromise.then(function (acc) {
101
- return Promise.resolve(fn(acc, item, index, arr));
1046
+ function _shapeGeneralValidator(_a) {
1047
+ var input = _a.input,
1048
+ baseType = _a.baseType,
1049
+ validateAsync = _a.validateAsync,
1050
+ collectNestedErrors = _a.collectNestedErrors;
1051
+ return __awaiter(this, void 0, void 0, function () {
1052
+ var objectValidation, nestedErrors;
1053
+ return __generator(this, function (_b) {
1054
+ switch (_b.label) {
1055
+ case 0:
1056
+ return [4 /*yield*/, validateAsync(typeValidator({
1057
+ type: baseType,
1058
+ required: true
1059
+ }), input)];
1060
+ case 1:
1061
+ objectValidation = _b.sent();
1062
+ if (objectValidation !== true) {
1063
+ return [2 /*return*/, objectValidation];
1064
+ }
1065
+ return [4 /*yield*/, collectNestedErrors()];
1066
+ case 2:
1067
+ nestedErrors = _b.sent();
1068
+ return [2 /*return*/, nestedErrors.length === 0 ? true : {
1069
+ input: input,
1070
+ nestedErrors: nestedErrors
1071
+ }];
1072
+ }
102
1073
  });
103
- }, Promise.resolve(initial));
104
- };
1074
+ });
1075
+ }
1076
+ function obj(objShape) {
1077
+ return function asyncValidateObj(input, _a) {
1078
+ var validateAsync = _a.validateAsync;
1079
+ return __awaiter(this, void 0, void 0, function () {
1080
+ var _this = this;
1081
+ return __generator(this, function (_b) {
1082
+ return [2 /*return*/, _shapeGeneralValidator({
1083
+ input: input,
1084
+ baseType: 'object',
1085
+ validateAsync: validateAsync,
1086
+ collectNestedErrors: function collectNestedErrors() {
1087
+ return promiseReduce(Object.entries(objShape), function (acc, _a) {
1088
+ var path = _a[0],
1089
+ pathValidator = _a[1];
1090
+ return __awaiter(_this, void 0, void 0, function () {
1091
+ var pathInput, pathResult;
1092
+ return __generator(this, function (_b) {
1093
+ switch (_b.label) {
1094
+ case 0:
1095
+ pathInput = getProperty(input, path);
1096
+ return [4 /*yield*/, validateAsync(pathValidator, pathInput)];
1097
+ case 1:
1098
+ pathResult = _b.sent();
1099
+ return [2 /*return*/, pathResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, pathResult), {
1100
+ path: path
1101
+ })], false)];
1102
+ }
1103
+ });
1104
+ });
1105
+ }, []);
1106
+ }
1107
+ })];
1108
+ });
1109
+ });
1110
+ };
1111
+ }
1112
+ function objOf(ofType) {
1113
+ return function asyncValidateObjOf(input, _a) {
1114
+ var validateAsync = _a.validateAsync;
1115
+ return __awaiter(this, void 0, void 0, function () {
1116
+ var _this = this;
1117
+ return __generator(this, function (_b) {
1118
+ return [2 /*return*/, _shapeGeneralValidator({
1119
+ input: input,
1120
+ baseType: 'object',
1121
+ validateAsync: validateAsync,
1122
+ collectNestedErrors: function collectNestedErrors() {
1123
+ return promiseReduce(Object.entries(input), function (acc, _a) {
1124
+ var key = _a[0],
1125
+ keyInput = _a[1];
1126
+ return __awaiter(_this, void 0, void 0, function () {
1127
+ var indexResult;
1128
+ return __generator(this, function (_b) {
1129
+ switch (_b.label) {
1130
+ case 0:
1131
+ return [4 /*yield*/, validateAsync(ofType, keyInput)];
1132
+ case 1:
1133
+ indexResult = _b.sent();
1134
+ return [2 /*return*/, indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
1135
+ path: key
1136
+ })], false)];
1137
+ }
1138
+ });
1139
+ });
1140
+ }, []);
1141
+ }
1142
+ })];
1143
+ });
1144
+ });
1145
+ };
1146
+ }
1147
+ function tuple(tupleShape) {
1148
+ return function asyncValidateTuple(input, _a) {
1149
+ var validateAsync = _a.validateAsync;
1150
+ return __awaiter(this, void 0, void 0, function () {
1151
+ var _this = this;
1152
+ return __generator(this, function (_b) {
1153
+ return [2 /*return*/, _shapeGeneralValidator({
1154
+ input: input,
1155
+ baseType: 'array',
1156
+ validateAsync: validateAsync,
1157
+ collectNestedErrors: function collectNestedErrors() {
1158
+ return promiseReduce(tupleShape, function (acc, indexValidator, index) {
1159
+ return __awaiter(_this, void 0, void 0, function () {
1160
+ var indexInput, indexResult;
1161
+ return __generator(this, function (_a) {
1162
+ switch (_a.label) {
1163
+ case 0:
1164
+ indexInput = input[index];
1165
+ return [4 /*yield*/, validateAsync(indexValidator, indexInput)];
1166
+ case 1:
1167
+ indexResult = _a.sent();
1168
+ return [2 /*return*/, indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
1169
+ path: index + ''
1170
+ })], false)];
1171
+ }
1172
+ });
1173
+ });
1174
+ }, []);
1175
+ }
1176
+ })];
1177
+ });
1178
+ });
1179
+ };
1180
+ }
1181
+ function arrayOf(ofType) {
1182
+ return function asyncValidateArrayOf(input, _a) {
1183
+ var validateAsync = _a.validateAsync;
1184
+ return __awaiter(this, void 0, void 0, function () {
1185
+ var _this = this;
1186
+ return __generator(this, function (_b) {
1187
+ return [2 /*return*/, _shapeGeneralValidator({
1188
+ input: input,
1189
+ baseType: 'array',
1190
+ validateAsync: validateAsync,
1191
+ collectNestedErrors: function collectNestedErrors() {
1192
+ return promiseReduce(input, function (acc, indexInput, index) {
1193
+ return __awaiter(_this, void 0, void 0, function () {
1194
+ var indexResult;
1195
+ return __generator(this, function (_a) {
1196
+ switch (_a.label) {
1197
+ case 0:
1198
+ return [4 /*yield*/, validateAsync(ofType, indexInput)];
1199
+ case 1:
1200
+ indexResult = _a.sent();
1201
+ return [2 /*return*/, indexResult === true ? acc : __spreadArray(__spreadArray([], acc, true), [_assign(_assign({}, indexResult), {
1202
+ path: index + ''
1203
+ })], false)];
1204
+ }
1205
+ });
1206
+ });
1207
+ }, []);
1208
+ }
1209
+ })];
1210
+ });
1211
+ });
1212
+ };
1213
+ }
105
1214
 
106
- var array = {
107
- arrayReduceAsync: arrayReduceAsync
108
- };
109
- var array_1 = array.arrayReduceAsync;
1215
+ //
1216
+ // And operator (serial)
1217
+ //
1218
+ function and(validators) {
1219
+ return function validateAnd(input, _a) {
1220
+ var validateAsync = _a.validateAsync;
1221
+ return __awaiter(this, void 0, void 0, function () {
1222
+ var result;
1223
+ return __generator(this, function (_b) {
1224
+ switch (_b.label) {
1225
+ case 0:
1226
+ return [4 /*yield*/, promiseReduce(validators, function (acc, validator) {
1227
+ return acc !== true ? acc : validateAsync(validator, input);
1228
+ }, true)];
1229
+ case 1:
1230
+ result = _b.sent();
1231
+ if (result === true) {
1232
+ return [2 /*return*/, true];
1233
+ } else {
1234
+ return [2 /*return*/, result];
1235
+ }
1236
+ }
1237
+ });
1238
+ });
1239
+ };
1240
+ }
1241
+ //
1242
+ // Or operator (serial)
1243
+ //
1244
+ function or(validators) {
1245
+ return function validateOr(input, _a) {
1246
+ var validateAsync = _a.validateAsync;
1247
+ return __awaiter(this, void 0, void 0, function () {
1248
+ var someIsValid;
1249
+ var _this = this;
1250
+ return __generator(this, function (_b) {
1251
+ switch (_b.label) {
1252
+ case 0:
1253
+ return [4 /*yield*/, promiseReduce(validators, function (acc, validator) {
1254
+ return __awaiter(_this, void 0, void 0, function () {
1255
+ var _a;
1256
+ return __generator(this, function (_b) {
1257
+ switch (_b.label) {
1258
+ case 0:
1259
+ _a = acc === true;
1260
+ if (_a) return [3 /*break*/, 2];
1261
+ return [4 /*yield*/, validateAsync(validator, input)];
1262
+ case 1:
1263
+ _a = _b.sent() === true;
1264
+ _b.label = 2;
1265
+ case 2:
1266
+ return [2 /*return*/, _a];
1267
+ }
1268
+ });
1269
+ });
1270
+ }, false)];
1271
+ case 1:
1272
+ someIsValid = _b.sent();
1273
+ return [2 /*return*/, someIsValid];
1274
+ }
1275
+ });
1276
+ });
1277
+ };
1278
+ }
1279
+ //
1280
+ // Not
1281
+ //
1282
+ function not(validator) {
1283
+ return function validateNot(input, _a) {
1284
+ var validateAsync = _a.validateAsync;
1285
+ return __awaiter(this, void 0, void 0, function () {
1286
+ var result;
1287
+ return __generator(this, function (_b) {
1288
+ switch (_b.label) {
1289
+ case 0:
1290
+ return [4 /*yield*/, validateAsync(validator, input)];
1291
+ case 1:
1292
+ result = _b.sent();
1293
+ return [2 /*return*/, result !== true];
1294
+ }
1295
+ });
1296
+ });
1297
+ };
1298
+ }
1299
+
1300
+ function validateAsyncFn(validatorInput, input) {
1301
+ return __awaiter(this, void 0, void 0, function () {
1302
+ var result, _a, validatorFn, errorMessage, err_1;
1303
+ return __generator(this, function (_b) {
1304
+ switch (_b.label) {
1305
+ case 0:
1306
+ _a = parseValidatorInput({
1307
+ objValidator: obj
1308
+ }, validatorInput), validatorFn = _a[0], errorMessage = _a[1];
1309
+ _b.label = 1;
1310
+ case 1:
1311
+ _b.trys.push([1, 3,, 4]);
1312
+ return [4 /*yield*/, validatorFn(input, {
1313
+ validateAsync: validateAsyncFn
1314
+ })];
1315
+ case 2:
1316
+ result = _b.sent();
1317
+ return [3 /*break*/, 4];
1318
+ case 3:
1319
+ err_1 = _b.sent();
1320
+ result = err_1;
1321
+ return [3 /*break*/, 4];
1322
+ case 4:
1323
+ return [2 /*return*/, resolveValidationResult({
1324
+ errorMessage: errorMessage,
1325
+ input: input,
1326
+ result: result
1327
+ })];
1328
+ }
1329
+ });
1330
+ });
1331
+ }
1332
+
1333
+ function assertValidAsync(validator, input) {
1334
+ return __awaiter(this, void 0, void 0, function () {
1335
+ var validationResult;
1336
+ return __generator(this, function (_a) {
1337
+ switch (_a.label) {
1338
+ case 0:
1339
+ return [4 /*yield*/, validateAsync(validator, input)];
1340
+ case 1:
1341
+ validationResult = _a.sent();
1342
+ if (validationResult === true) {
1343
+ return [2 /*return*/, input];
1344
+ } else {
1345
+ throw new ValidationError(validationResult);
1346
+ }
1347
+ }
1348
+ });
1349
+ });
1350
+ }
1351
+ var validateAsync = validateAsyncFn;
1352
+ validateAsync.type = typeValidator;
1353
+ validateAsync.obj = obj;
1354
+ validateAsync.objOf = objOf;
1355
+ validateAsync.tuple = tuple;
1356
+ validateAsync.arrayOf = arrayOf;
1357
+ validateAsync.and = and;
1358
+ validateAsync.or = or;
1359
+ validateAsync.not = not;
1360
+ validateAsync.assertValid = assertValidAsync;
1361
+
1362
+ function maybeFn(input) {
1363
+ var args = [];
1364
+ for (var _i = 1; _i < arguments.length; _i++) {
1365
+ args[_i - 1] = arguments[_i];
1366
+ }
1367
+ return typeof input === 'function' ? input.apply(void 0, args) : input;
1368
+ }
1369
+
1370
+ function wait(ms, result) {
1371
+ if (ms === void 0) {
1372
+ ms = 1000;
1373
+ }
1374
+ return __awaiter(this, void 0, void 0, function () {
1375
+ return __generator(this, function (_a) {
1376
+ return [2 /*return*/, new Promise(function (resolve, reject) {
1377
+ setTimeout(function () {
1378
+ if (result instanceof Error) {
1379
+ reject(result);
1380
+ } else {
1381
+ resolve(result);
1382
+ }
1383
+ }, ms);
1384
+ })];
1385
+ });
1386
+ });
1387
+ }
1388
+
1389
+ function deepFreeze(object) {
1390
+ Object.freeze(object);
1391
+ if (Array.isArray(object)) {
1392
+ // Handle the array case
1393
+ object.forEach(function (item) {
1394
+ if (item && _typeof(item) === 'object' && !Object.isFrozen(item)) {
1395
+ deepFreeze(item);
1396
+ }
1397
+ });
1398
+ } else {
1399
+ // Handle the object case
1400
+ Object.keys(object).forEach(function (key) {
1401
+ var value = object[key];
1402
+ if (value && _typeof(value) === 'object' && !Object.isFrozen(value)) {
1403
+ deepFreeze(value);
1404
+ }
1405
+ });
1406
+ }
1407
+ return object;
1408
+ }
1409
+
1410
+ function stringifyReplacer(key, value) {
1411
+ if (typeof value === 'function') {
1412
+ // Convert functions to a consistent string representation
1413
+ return "function:".concat(value.toString());
1414
+ }
1415
+ return value;
1416
+ }
1417
+ function simpleHash(str) {
1418
+ var hash = 0;
1419
+ for (var i = 0; i < str.length; i++) {
1420
+ var _char = str.charCodeAt(i);
1421
+ hash = (hash << 5) - hash + _char;
1422
+ hash |= 0; // Convert to 32bit integer
1423
+ }
1424
+ // Ensure the hash is positive to avoid '-' signals
1425
+ hash = Math.abs(hash);
1426
+ return hash.toString(36); // Convert to base36 to ensure the result is alphanumeric
1427
+ }
1428
+ function generateDeterministicId(args) {
1429
+ // Convert arguments to a JSON string using the custom replacer
1430
+ var argsString = JSON.stringify(args, stringifyReplacer);
1431
+ // Generate a simple hash of the string
1432
+ return simpleHash(argsString);
1433
+ }
1434
+
1435
+ function debugFn(fnName, fn, logCall, logResult) {
1436
+ return function () {
1437
+ var args = [];
1438
+ for (var _i = 0; _i < arguments.length; _i++) {
1439
+ args[_i] = arguments[_i];
1440
+ }
1441
+ var callId = generateDeterministicId(__spreadArray([fnName, fn], args, true));
1442
+ if (typeof logCall === 'function') {
1443
+ // Deep clone args, so that we may detect mutations later on
1444
+ logCall({
1445
+ type: 'call',
1446
+ callId: callId,
1447
+ args: copy(args),
1448
+ fnName: fnName
1449
+ });
1450
+ }
1451
+ var result = fn.apply(void 0, args);
1452
+ if (typeof logResult === 'function') {
1453
+ logResult({
1454
+ type: 'result',
1455
+ callId: callId,
1456
+ args: args,
1457
+ result: result,
1458
+ fnName: fnName
1459
+ });
1460
+ }
1461
+ return result;
1462
+ };
1463
+ }
110
1464
 
111
- export { array as __moduleExports, array_1 as arrayReduceAsync };
1465
+ export { PromiseLikeEventEmitter, SKIPPED, ValidationError, batchFn, debugFn, deepFreeze, interpolate, makeTypeOf, maybeFn, parseBatchedResults, promiseReduce, resolveNestedPromises, switchExec, switchValue, typeMap, typeOf, validate, validateAsync, wait };