@bolttech/form-engine-core 1.0.10 → 1.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 (64) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/credit-card.d.ts +743 -0
  3. package/credit-card.esm.js +1 -0
  4. package/currency.d.ts +131 -0
  5. package/currency.esm.js +1 -0
  6. package/date.d.ts +582 -0
  7. package/date.esm.js +1 -0
  8. package/document.d.ts +527 -0
  9. package/document.esm.js +1 -0
  10. package/index.d.ts +52 -5
  11. package/index.esm.js +1 -4570
  12. package/lite.d.ts +2393 -0
  13. package/lite.esm.js +1 -0
  14. package/package.json +34 -2
  15. package/src/constants/constants.d.ts +11 -0
  16. package/src/formatters/creditCard.d.ts +23 -0
  17. package/src/formatters/custom.d.ts +29 -0
  18. package/src/formatters/handler.d.ts +2 -0
  19. package/src/formatters/regex.d.ts +47 -0
  20. package/src/formatters/splitter.d.ts +17 -0
  21. package/src/formatters/string.d.ts +88 -0
  22. package/src/helpers/SafeSubject.d.ts +21 -0
  23. package/src/helpers/creditCard.d.ts +95 -0
  24. package/src/helpers/helpers.d.ts +66 -0
  25. package/src/helpers/lodash-replacements.d.ts +41 -0
  26. package/src/helpers/validation.d.ts +28 -0
  27. package/src/index.d.ts +15 -0
  28. package/src/interfaces/schema.d.ts +161 -0
  29. package/src/interfaces/state.d.ts +22 -0
  30. package/src/lite.d.ts +30 -0
  31. package/src/managers/field.d.ts +339 -0
  32. package/src/managers/form.d.ts +357 -0
  33. package/src/managers/formGroup.d.ts +110 -0
  34. package/src/managers/index.d.ts +3 -0
  35. package/src/masks/creditCard.d.ts +60 -0
  36. package/src/masks/currency.d.ts +29 -0
  37. package/src/masks/generic.d.ts +39 -0
  38. package/src/masks/handler.d.ts +2 -0
  39. package/src/masks/string.d.ts +37 -0
  40. package/src/plugins/credit-card.d.ts +4 -0
  41. package/src/plugins/currency.d.ts +2 -0
  42. package/src/plugins/date.d.ts +2 -0
  43. package/src/plugins/document.d.ts +2 -0
  44. package/src/registry.d.ts +20 -0
  45. package/src/types/event.d.ts +175 -0
  46. package/src/types/form.d.ts +55 -0
  47. package/src/types/mapper.d.ts +87 -0
  48. package/src/types/schema.d.ts +1001 -0
  49. package/src/types/template.d.ts +65 -0
  50. package/src/types/utility.d.ts +12 -0
  51. package/src/validations/creditCard.d.ts +52 -0
  52. package/src/validations/custom.d.ts +27 -0
  53. package/src/validations/date.d.ts +79 -0
  54. package/src/validations/document.d.ts +25 -0
  55. package/src/validations/handler.d.ts +2 -0
  56. package/src/validations/length.d.ts +39 -0
  57. package/src/validations/list.d.ts +32 -0
  58. package/src/validations/logical.d.ts +75 -0
  59. package/src/validations/multiple.d.ts +31 -0
  60. package/src/validations/namedRule.d.ts +22 -0
  61. package/src/validations/number.d.ts +145 -0
  62. package/src/validations/object.d.ts +44 -0
  63. package/src/validations/regex.d.ts +217 -0
  64. package/src/validations/string.d.ts +53 -0
package/index.esm.js CHANGED
@@ -1,4570 +1 @@
1
- import { BehaviorSubject, Subject, Subscription, groupBy, mergeMap, debounceTime, filter, combineLatest, startWith, map, distinctUntilKeyChanged } from 'rxjs';
2
- import creditCardType from 'credit-card-type';
3
- import isNumber$1 from 'lodash/isNumber';
4
- import { getCurrencySymbol } from '@gaignoux/currency';
5
- import isFunction from 'lodash/isFunction';
6
- import cloneDeep from 'lodash/cloneDeep';
7
- import get from 'lodash/get';
8
- import isEqual from 'lodash/isEqual';
9
- import isNil from 'lodash/isNil';
10
- import set from 'lodash/set';
11
-
12
- var TMutationEnum;
13
- (function (TMutationEnum) {
14
- TMutationEnum["ON_VALUE"] = "value";
15
- TMutationEnum["ON_PROPS"] = "props";
16
- // ON_VALIDATION = 'valid',
17
- TMutationEnum["ON_VISIBILITY"] = "visibility";
18
- TMutationEnum["ON_API"] = "api";
19
- TMutationEnum["ON_IVARS"] = "iVars";
20
- TMutationEnum["ON_FIELDS"] = "fields";
21
- })(TMutationEnum || (TMutationEnum = {}));
22
-
23
- /******************************************************************************
24
- Copyright (c) Microsoft Corporation.
25
-
26
- Permission to use, copy, modify, and/or distribute this software for any
27
- purpose with or without fee is hereby granted.
28
-
29
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
30
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
31
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
32
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
33
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
35
- PERFORMANCE OF THIS SOFTWARE.
36
- ***************************************************************************** */
37
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
38
-
39
-
40
- function __awaiter(thisArg, _arguments, P, generator) {
41
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
- return new (P || (P = Promise))(function (resolve, reject) {
43
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
44
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
45
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
46
- step((generator = generator.apply(thisArg, _arguments || [])).next());
47
- });
48
- }
49
-
50
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
- var e = new Error(message);
52
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
- };
54
-
55
- const DEFAULT_API_DEBOUNCE_TIME = 1000;
56
- const DEFAULT_STATE_REFRESH_TIME = 100;
57
- const TEMPLATE_REGEX_STRING_CONCATENATION_DETECTOR = /^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/;
58
- const TEMPLATE_REGEX_DELIMITATOR = /\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
59
- const TEMPLATE_REGEX_OPERATOR_SPLITTER = /\s*(\|\||&&|!+)\s*/g;
60
- const TEMPLATE_REGEX_OPERATOR_MATCHER = /^\|\||&&|!+$/;
61
- const TEMPLATE_AVALIABLE_SCOPES = ['fields', 'iVars', 'form'];
62
- const ALLOWED_RESET_PROPS_MUTATIONS = ['api', 'apiSchema', 'props', 'validations', 'visibilityConditions', 'resetValues'];
63
- const DEFAULT_LOG_VERBOSE = false;
64
-
65
- /**
66
- * Makes an HTTP request using XMLHttpRequest.
67
- *
68
- * @param {string} method - The HTTP method (GET, POST, PUT, DELETE, etc.).
69
- * @param {string} url - The URL to which the request is sent.
70
- * @param {OutgoingHttpHeaders} [headers] - Optional request headers.
71
- * @param {Record<string,unknown>} [body] - Optional object body.
72
- * @returns {Promise<string>} A promise that resolves with the response text if the request is successful, otherwise rejects with an error message.
73
- *
74
- * @example
75
- * ```typescript
76
- * const response = await makeRequest('GET', 'https://api.example.com/data');
77
- * ```
78
- */
79
- function makeRequest(method, url, headers, body, queryParams) {
80
- return new Promise(function (resolve, reject) {
81
- const xhr = new XMLHttpRequest();
82
- if (queryParams) {
83
- const [baseUrl, existingParamsString] = url.split('?');
84
- const searchParams = new URLSearchParams(existingParamsString);
85
- Object.keys(queryParams).forEach(param => {
86
- searchParams.append(param, queryParams[param]);
87
- });
88
- url = `${baseUrl}?${searchParams.toString()}`;
89
- }
90
- xhr.open(method, url, true);
91
- if (headers) {
92
- Object.keys(headers).forEach(header => {
93
- xhr.setRequestHeader(header, headers[header]);
94
- });
95
- }
96
- xhr.onload = function () {
97
- resolve({
98
- status: xhr.status,
99
- response: xhr.responseText
100
- });
101
- };
102
- xhr.onerror = function () {
103
- reject(xhr.statusText);
104
- };
105
- xhr.send(JSON.stringify(body) || null);
106
- });
107
- }
108
- /**
109
- * Extracts keys enclosed in `${}` from a given expression.
110
- *
111
- * @param {string} expression - The expression to extract keys from.
112
- * @returns {
113
- * originFieldKeys: string[];
114
- * originPropertyKeys: string[];
115
- * } An object containing the field names and properties from the template expression.
116
- *
117
- * @example
118
- * ```typescript
119
- * const keys = extractFieldKeys('Hello ${name.value}, your age is ${age.props.label}.');
120
- * // keys will be {originFieldKeys:['name', 'age'],originPropertyKeys:[value,props]}
121
- * ```
122
- */
123
- function extractFieldKeys(expression) {
124
- const regex = TEMPLATE_REGEX_DELIMITATOR;
125
- const extractedValues = [];
126
- let match;
127
- while ((match = regex.exec(expression)) !== null) {
128
- extractedValues.push(match[1]);
129
- }
130
- const operatorRegex = TEMPLATE_REGEX_OPERATOR_SPLITTER;
131
- const splittedString = extractedValues.map(el => el.split(operatorRegex).filter(item => !operatorRegex.test(item))).flat().filter(el => el.split('.').length > 1);
132
- return {
133
- originScopeKeys: Array.from(new Set(splittedString.map(el => el.split('.')[0]))),
134
- originFieldKeys: Array.from(new Set(splittedString.map(el => el.split('.')[1]))),
135
- originPropertyKeys: Array.from(new Set(splittedString.map(el => el.split('.')[2])))
136
- };
137
- }
138
- /**
139
- * Traverses an object and extracts expressions containing keys.
140
- *
141
- * @param {any} obj - The object to traverse.
142
- * @param {string} [path] - Optional path within the object (used internally during recursion).
143
- * @returns {TSubscribedTemplates[]} An array of extracted expressions along with their keys and paths.
144
- *
145
- * @example
146
- * ```typescript
147
- * const data = {
148
- * user: {
149
- * name: 'John',
150
- * age: 30,
151
- * address: {
152
- * street: '123 Main St',
153
- * city: 'Example City'
154
- * }
155
- * },
156
- * message: 'Hello ${user.name}, your age is ${user.age}.'
157
- * };
158
- *
159
- * const expressions = traverseObject(data);
160
- * // expressions will contain an array of objects with origin expressions, field keys, and destination paths.
161
- * ```
162
- */
163
- function traverseObject(element, path) {
164
- const result = [];
165
- if (Array.isArray(element)) {
166
- element.forEach((item, index) => {
167
- result.push(...traverseObject(item, `${path ? `${path}.` : ``}${index}`));
168
- });
169
- } else if (typeof element === 'object') {
170
- for (const key in element) {
171
- if (Object.prototype.hasOwnProperty.call(element, key)) {
172
- const value = element[key];
173
- result.push(...traverseObject(value, `${path ? `${path}.` : ``}${key}`));
174
- }
175
- }
176
- } else if (typeof element === 'string') {
177
- if (element.includes('${')) {
178
- // const extractedPath = value.replace(/\$|{|}/g, '').split('.');
179
- const destinationPath = (path ? path : '').split('.');
180
- // if(destinationPath[0])
181
- const originfieldKeys = extractFieldKeys(element);
182
- if (!originfieldKeys.originScopeKeys.every(scopeKey => TEMPLATE_AVALIABLE_SCOPES.includes(scopeKey))) {
183
- console.warn(`scope malformed on this expression: ${element}, ignoring..`);
184
- } else {
185
- result.push(Object.assign(Object.assign({
186
- originExpression: element
187
- }, extractFieldKeys(element)), {
188
- destinationKey: destinationPath[0],
189
- destinationProperty: destinationPath[1],
190
- destinationPath: destinationPath.slice(2)
191
- }));
192
- }
193
- }
194
- }
195
- return result;
196
- }
197
-
198
- /**
199
- * Splits a string by inserting specified values at given positions.
200
- *
201
- * @param value - The value to be processed.
202
- * @param formatters - An object containing formatting options.
203
- * @returns The processed value with splitters applied.
204
- *
205
- * @example
206
- * ```typescript
207
- * import { splitter } from './path/to/formatterFunctions';
208
- *
209
- * const processedValue = splitter('HelloWorld', { splitter: [{ position: 5, value: '_' }] });
210
- * console.log(processedValue); // Output: 'Hello_World'
211
- * ```
212
- */
213
- const splitter = (value, formatters) => {
214
- if (!value || !formatters.splitter || typeof value !== 'string') return value;
215
- formatters.splitter.sort((a, b) => a.position - b.position);
216
- let result = value;
217
- let offset = 0;
218
- for (const splitter of formatters.splitter) {
219
- const {
220
- position,
221
- value
222
- } = splitter;
223
- const adjustedPosition = position + offset;
224
- if (adjustedPosition >= 0 && adjustedPosition <= result.length) {
225
- result = result.slice(0, adjustedPosition) + value + result.slice(adjustedPosition);
226
- offset += value.length;
227
- }
228
- }
229
- return result;
230
- };
231
-
232
- /**
233
- * Capitalizes the first letter of a string.
234
- *
235
- * @param value - The value to be capitalized.
236
- * @returns The value with the first letter capitalized.
237
- *
238
- * @example
239
- * ```typescript
240
- * import { capitalize } from './path/to/formatterFunctions';
241
- *
242
- * const capitalizedValue = capitalize('hello world');
243
- * console.log(capitalizedValue); // Output: 'Hello world'
244
- * ```
245
- */
246
- const capitalize = value => String(value).charAt(0).toUpperCase() + String(value).slice(1);
247
- /**
248
- * Converts a string to uppercase.
249
- *
250
- * @param value - The value to be converted.
251
- * @returns The value in uppercase.
252
- *
253
- * @example
254
- * ```typescript
255
- * import { uppercase } from './path/to/formatterFunctions';
256
- *
257
- * const uppercasedValue = uppercase('hello world');
258
- * console.log(uppercasedValue); // Output: 'HELLO WORLD'
259
- * ```
260
- */
261
- const uppercase = value => String(value).toUpperCase();
262
- /**
263
- * Formats a string as a float number with a specific precision and decimal separator.
264
- *
265
- * @param value - The value to be formatted.
266
- * @param formatters - An object containing formatting options.
267
- * @returns The formatted float number.
268
- *
269
- * @example
270
- * ```typescript
271
- * import { onlyFloatNumber } from './path/to/formatterFunctions';
272
- *
273
- * const formattedNumber = onlyFloatNumber('1234567.89', { onlyFloatNumber: { precision: 2, decimal: '.' } });
274
- * console.log(formattedNumber); // Output: '1234567.89'
275
- * ```
276
- */
277
- const onlyFloatNumber = (value, formatters) => {
278
- const {
279
- onlyFloatNumber
280
- } = formatters;
281
- if (!onlyFloatNumber || typeof value !== 'string' || !value) return value;
282
- const {
283
- precision = 2,
284
- decimal = '.'
285
- } = onlyFloatNumber;
286
- if (!value.includes(decimal)) {
287
- return value;
288
- }
289
- const replacedValue = value.replace(/[^0-9]/g, '');
290
- const partOf = replacedValue.slice(0, replacedValue.length - precision);
291
- const sliceOf = replacedValue.slice(replacedValue.length - precision);
292
- return parseFloat(`${partOf}.${sliceOf}`).toFixed(precision);
293
- };
294
- /**
295
- * Trims whitespace from the beginning and end of a string.
296
- *
297
- * @param value - The value to be trimmed.
298
- * @param formatters - An object containing formatting options.
299
- * @returns The trimmed value.
300
- *
301
- * @example
302
- * ```typescript
303
- * import { trim } from './path/to/formatterFunctions';
304
- *
305
- * const trimmedValue = trim(' hello world ');
306
- * console.log(trimmedValue); // Output: 'hello world'
307
- * ```
308
- */
309
- const trim = (value, formatters) => {
310
- if (!value || (formatters === null || formatters === void 0 ? void 0 : formatters.trim)) return value;
311
- return String(value).trim();
312
- };
313
- /**
314
- * Truncates the input value to a specified maximum length if necessary.
315
- *
316
- * @param {string | number} value - The input value to be formatted.
317
- * @param {TFormatters} formatters - An object containing formatting options.
318
- * @param {number} formatters.maxLength - The maximum allowed length for the input value.
319
- * @returns {string | number} - The formatted value truncated to the maximum length, if applicable.
320
- *
321
- * @example
322
- * ```typescript
323
- * const result = maxLength('Hello, World!', { maxLength: 5 });
324
- * console.log(result); // "Hello"
325
- * ```
326
- * @example
327
- * ```typescript
328
- * const result = maxLength(123456789, { maxLength: 4 });
329
- * console.log(result); // "1234"
330
- * ```
331
- * @example
332
- * ```typescript
333
- * const result = maxLength('Short', { maxLength: 10 });
334
- * console.log(result); // "Short" (no truncation since input is shorter than maxLength)
335
- * ```
336
- */
337
- const maxLength = (value, formatters) => {
338
- if (!value || !formatters.maxLength) return value;
339
- const input = String(value);
340
- if (input.length > formatters.maxLength) {
341
- return input.substring(0, formatters.maxLength);
342
- }
343
- return value;
344
- };
345
-
346
- /**
347
- * Removes all non-numeric characters from a string.
348
- *
349
- * @param value - The value to be processed.
350
- * @returns The processed value with only numbers.
351
- *
352
- * @example
353
- * ```typescript
354
- * import { onlyNumbers } from './path/to/formatterFunctions';
355
- *
356
- * const processedValue = onlyNumbers('abc123def456');
357
- * console.log(processedValue); // Output: '123456'
358
- * ```
359
- */
360
- const onlyNumbers = value => String(value).replace(/(\D)+/gim, '');
361
- /**
362
- * Removes all non-letter characters from a string.
363
- *
364
- * @param value - The value to be processed.
365
- * @returns The processed value with only letters.
366
- *
367
- * @example
368
- * ```typescript
369
- * import { onlyLetters } from './path/to/formatterFunctions';
370
- *
371
- * const processedValue = onlyLetters('abc123def456');
372
- * console.log(processedValue); // Output: 'abcdef'
373
- * ```
374
- */
375
- const onlyLetters$1 = value => String(value).replace(/[^\p{L}\s]/gu, '');
376
- /**
377
- * Applies a regular expression pattern to remove matching substrings from a string.
378
- *
379
- * @param value - The value to be processed.
380
- * @param formatters - An object containing formatting options.
381
- * @returns The processed value with matched substrings removed.
382
- *
383
- * @example
384
- * ```typescript
385
- * import { regex } from './path/to/formatterFunctions';
386
- *
387
- * const processedValue = regex('abc123def456', { regex: '\\d+' });
388
- * console.log(processedValue); // Output: 'abcdef'
389
- * ```
390
- */
391
- const regex$1 = (value, formatters) => {
392
- if (!formatters.regex) return value;
393
- return String(value).replace(new RegExp(formatters.regex, 'g'), '');
394
- };
395
-
396
- /**
397
- * Retrieves the type of the credit card and the raw value without spaces.
398
- *
399
- * @param value - The credit card number as a string.
400
- * @param availableOptions - An optional array of credit card types to consider.
401
- * @returns An array containing the detected credit card type and the raw value without spaces.
402
- *
403
- * @example
404
- * ```typescript
405
- * import { getTypeCard } from './path/to/helperFunctions';
406
- *
407
- * const [creditCardType, rawValue] = getTypeCard('4111 1111 1111 1111');
408
- * console.log(creditCardType); // Output: { niceType: 'Visa', type: 'visa', ... }
409
- * console.log(rawValue); // Output: '4111111111111111'
410
- * ```
411
- */
412
- const getTypeCard = (value, availableOptions) => {
413
- const rawValue = removeGaps(value === null || value === void 0 ? void 0 : value.toString());
414
- const types = creditCardType(rawValue);
415
- const selected = typeof availableOptions === 'object' && availableOptions.length ? types === null || types === void 0 ? void 0 : types.filter(({
416
- type: id1
417
- }) => availableOptions.some(id2 => id2 === id1))[0] : types[0];
418
- return [selected, rawValue];
419
- };
420
- /**
421
- * Removes all spaces from a string.
422
- *
423
- * @param value - The string to remove spaces from.
424
- * @returns The string without spaces.
425
- */
426
- const removeGaps = value => value === null || value === void 0 ? void 0 : value.replace(/ /g, '');
427
- /**
428
- * Adds specified gaps to a string based on given offsets.
429
- *
430
- * @param value - The string to add gaps to.
431
- * @param gaps - An array containing gap positions.
432
- * @returns The string with added gaps.
433
- */
434
- const addGaps = (value, gaps = []) => {
435
- const [regexString, replaceString] = gaps.reduce(([regexString, replaceString], offset, i) => {
436
- const lastOffset = gaps[i - 1] || 0;
437
- const digitNumber = offset - lastOffset;
438
- return [`${regexString}([0-9]{0,${digitNumber}})`, `${replaceString}$${i + 1} `];
439
- }, ['', '']);
440
- return value.replace(new RegExp(regexString), replaceString).trim();
441
- };
442
- /**
443
- * Formats a credit card number according to its type's gaps and lengths.
444
- *
445
- * @param value - The credit card number as a string.
446
- * @param type - The type of the credit card.
447
- * @returns The formatted credit card number.
448
- */
449
- const formatValue = (value, type) => {
450
- const DEFAULT_LENGTH = 19;
451
- return type ? addGaps(value.slice(0, type === null || type === void 0 ? void 0 : type.lengths[0]), type.gaps) : value === null || value === void 0 ? void 0 : value.slice(0, DEFAULT_LENGTH);
452
- };
453
- /**
454
- * Formats a date string by adding a prefix and/or trimming the string based on its length.
455
- *
456
- * @param value - The date string to be formatted.
457
- * @param end - The ending index to slice the string to.
458
- * @param prefix - The prefix to add between date components.
459
- * @returns The formatted date string.
460
- *
461
- * @example
462
- * ```typescript
463
- * import { formatDateCard } from './path/to/helperFunctions';
464
- *
465
- * const formattedDate = formatDateCard('1223', 4, '/');
466
- * console.log(formattedDate); // Output: '12/23'
467
- * ```
468
- */
469
- const formatDateCard = (value, end = 4, prefix = '/') => {
470
- const fixedValue = value.replace(/\D/g, '');
471
- const valZeroTwo = fixedValue.slice(0, 2);
472
- return fixedValue.length >= 5 ? `${valZeroTwo}${prefix}${fixedValue.slice(2, end)}` : fixedValue.length >= 3 ? `${valZeroTwo}${prefix}${fixedValue.slice(2)}` : fixedValue;
473
- };
474
-
475
- /**
476
- * Formats a credit card number by adding gaps based on the card type.
477
- *
478
- * @param {unknown} value - The input value to be formatted, expected to be a string representing a credit card number.
479
- * @param {TFormatters} formatters - An object containing formatting options.
480
- * @param {boolean} formatters.gapsCreditCard - A flag indicating whether to apply credit card gap formatting.
481
- * @returns {unknown} - The formatted credit card number with appropriate gaps, or the original value if formatting is not applied.
482
- *
483
- * @example
484
- * ```typescript
485
- * const formatters = { gapsCreditCard: true };
486
- * const result = gapsCreditCard('4111111111111111', formatters);
487
- * console.log(result); // "4111 1111 1111 1111" (formatted based on card type, e.g., Visa)
488
- * ```
489
- * @example
490
- * ```typescript
491
- * const formatters = { gapsCreditCard: false };
492
- * const result = gapsCreditCard('4111111111111111', formatters);
493
- * console.log(result); // "4111111111111111" (no formatting applied)
494
- * ```
495
- */
496
- const gapsCreditCard = (value, formatters) => {
497
- if (!formatters.gapsCreditCard) return value;
498
- const [type, rawValue] = getTypeCard(value, formatters === null || formatters === void 0 ? void 0 : formatters.gapsCreditCard);
499
- return formatValue(rawValue, type);
500
- };
501
-
502
- /**
503
- * Applies a custom callback function to format a value.
504
- *
505
- * @param {unknown} value - The input value to be formatted.
506
- * @param {TFormatters} formatters - An object containing formatting options.
507
- * @param {(value: unknown) => unknown} formatters.callback - A custom callback function to apply to the value.
508
- * @returns {unknown} - The value after applying the custom callback function, or the original value if no callback is provided.
509
- *
510
- * @example
511
- * ```typescript
512
- * const formatters = { callback: (val) => `Formatted: ${val}` };
513
- * const result = callback('example', formatters);
514
- * console.log(result); // "Formatted: example"
515
- * ```
516
- * @example
517
- * ```typescript
518
- * const formatters = { callback: (val) => val.toString().toUpperCase() };
519
- * const result = callback('example', formatters);
520
- * console.log(result); // "EXAMPLE"
521
- * ```
522
- * @example
523
- * ```typescript
524
- * const formatters = { callback: null };
525
- * const result = callback('example', formatters);
526
- * console.log(result); // "example" (no formatting applied)
527
- * ```
528
- */
529
- const callback$1 = (value, formatters) => {
530
- if (!(formatters === null || formatters === void 0 ? void 0 : formatters.callback)) return value;
531
- return formatters.callback(value);
532
- };
533
-
534
- const formatters = {
535
- capitalize,
536
- uppercase,
537
- onlyNumbers,
538
- onlyLetters: onlyLetters$1,
539
- regex: regex$1,
540
- splitter,
541
- maxLength,
542
- onlyFloatNumber,
543
- trim,
544
- gapsCreditCard,
545
- callback: callback$1,
546
- // todo: to be removed
547
- dotEvery3chars: value => {
548
- const result = String(value).replace(/\./g, '').replace(/(.{3})/g, '$1.');
549
- return result.endsWith('.') ? result.slice(0, -1) : result;
550
- }
551
- };
552
-
553
- /**
554
- * Applies multiple generic masks to a string based on the provided mask configuration.
555
- *
556
- * @param value - The value to be masked.
557
- * @param masks - An object containing the mask configuration.
558
- * @returns The masked value.
559
- *
560
- * @example
561
- * ```typescript
562
- * import maskValue from './path/to/maskFunctions';
563
- *
564
- * const masks = {
565
- * generic: [
566
- * { from: 2, to: 4, mask: '*' },
567
- * { from: 7, to: 9, mask: '#' }
568
- * ]
569
- * };
570
- *
571
- * const maskedValue = maskValue('123456789', masks);
572
- * console.log(maskedValue); // Output: '1**45###9'
573
- *
574
- * // Using from a JSON config
575
- * const config = {
576
- * value: 'abcdefghij',
577
- * masks: {
578
- * generic: [
579
- * { from: 3, to: 6, mask: '*' },
580
- * { from: 8, to: 10, mask: '#' }
581
- * ]
582
- * }
583
- * };
584
- *
585
- * const maskedValue = maskValue(config.value, config.masks);
586
- * console.log(maskedValue); // Output: 'ab***gh###'
587
- * ```
588
- */
589
- var generic = (value, masks) => {
590
- if (!(masks === null || masks === void 0 ? void 0 : masks.generic)) return value;
591
- let masked = value;
592
- masks.generic.forEach(item => {
593
- const {
594
- to = masked.length,
595
- mask
596
- } = item;
597
- let {
598
- from
599
- } = item;
600
- if (to > value.length - 1) return;
601
- if (from === 0) {
602
- from = 1;
603
- }
604
- const maskedPortion = new Array(to - from + 2).join(mask);
605
- masked = masked.slice(0, from - 1) + maskedPortion + masked.slice(to);
606
- });
607
- return masked;
608
- };
609
-
610
- /**
611
- * Replaces all characters in a string with a specified replacement string or character.
612
- *
613
- * @param value - The value to be masked.
614
- * @param masks - An object containing the mask configuration.
615
- * @returns The masked value.
616
- *
617
- * @example
618
- * ```typescript
619
- * import { replaceAll } from './path/to/maskFunctions';
620
- *
621
- * const masks = { replaceAll: '*' };
622
- *
623
- * const maskedValue = replaceAll('12345', masks);
624
- * console.log(maskedValue); // Output: '*****'
625
- *
626
- * // Using from a JSON config
627
- * const config = {
628
- * value: 'hello',
629
- * masks: { replaceAll: '*' }
630
- * };
631
- *
632
- * const maskedValue = replaceAll(config.value, config.masks);
633
- * console.log(maskedValue); // Output: '*****'
634
- * ```
635
- */
636
- const replaceAll = (value, masks) => {
637
- let targetReplaceMask = masks.replaceAll;
638
- if (!targetReplaceMask) return value;
639
- if (typeof targetReplaceMask === 'number') {
640
- targetReplaceMask = targetReplaceMask === null || targetReplaceMask === void 0 ? void 0 : targetReplaceMask.toString();
641
- }
642
- return new Array(String(value).length + 1).join(targetReplaceMask);
643
- };
644
- /**
645
- * Formats a numeric value as a currency string based on the provided mask configuration.
646
- *
647
- * @param value - The numeric value to be formatted.
648
- * @param masks - An object containing the mask configuration.
649
- * @returns The formatted currency string.
650
- *
651
- * @example
652
- * ```typescript
653
- * import { currency } from './path/to/maskFunctions';
654
- *
655
- * const masks = {
656
- * currency: {
657
- * align: 'right',
658
- * decimal: ',',
659
- * precision: 2,
660
- * prefix: 'USD',
661
- * thousands: '.'
662
- * }
663
- * };
664
- *
665
- * const formattedValue = currency(12345.67, masks);
666
- * console.log(formattedValue); // Output: '12.345,67 $'
667
- *
668
- * // Using from a JSON config
669
- * const config = {
670
- * value: 9876.54,
671
- * masks: {
672
- * currency: {
673
- * align: 'right',
674
- * decimal: ',',
675
- * precision: 2,
676
- * prefix: 'EUR',
677
- * thousands: '.'
678
- * }
679
- * }
680
- * };
681
- *
682
- * const formattedValue = currency(config.value, config.masks);
683
- * console.log(formattedValue); // Output: '9.876,54 €'
684
- *
685
- * PS: To unCurrency this value, usage onlyFloatNumber formatter
686
- * ```
687
- */
688
- const currency = (value, masks) => {
689
- if (!(masks === null || masks === void 0 ? void 0 : masks.currency)) return value;
690
- const {
691
- align = '',
692
- decimal = '.',
693
- precision = 2,
694
- prefix = 'BBD',
695
- thousands = ','
696
- } = masks.currency;
697
- const rawValue = isNumber$1(value) ? Number(value).toFixed(precision) : value;
698
- let convertedValue = rawValue.replace(/[^0-9]/g, '');
699
- if (!convertedValue) {
700
- return '';
701
- }
702
- let integerPart = convertedValue.slice(0, convertedValue.length - precision).replace(/^0*/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, thousands);
703
- if (integerPart === '') {
704
- integerPart = '0';
705
- }
706
- if (align === 'right' && String(value).endsWith(' ')) {
707
- convertedValue = convertedValue.slice(0, -1);
708
- }
709
- let newRawValue = integerPart;
710
- let decimalPart = convertedValue.slice(convertedValue.length - precision);
711
- if (precision > 0) {
712
- decimalPart = '0'.repeat(precision - decimalPart.length) + decimalPart;
713
- newRawValue += decimal + decimalPart;
714
- }
715
- if (!align) {
716
- return newRawValue;
717
- }
718
- const symbol = getCurrencySymbol(prefix);
719
- return align === 'left' ? `${symbol} ${newRawValue}` : `${newRawValue} ${symbol}`;
720
- };
721
- /**
722
- * Applies a custom mask to a string based on the provided mask configuration.
723
- *
724
- * @param value - The value to be masked.
725
- * @param masks - An object containing the mask configuration.
726
- * @returns The masked value.
727
- *
728
- * @example
729
- * ```typescript
730
- * import { custom } from './path/to/maskFunctions';
731
- *
732
- * const masks = { custom: '##-##' };
733
- *
734
- * const maskedValue = custom('123456', masks);
735
- * console.log(maskedValue); // Output: '12-34'
736
- *
737
- * // Using from a JSON config
738
- * const config = {
739
- * masks: { custom: '###-###' }
740
- * };
741
- *
742
- * const maskedValue = custom(config.value, config.masks);
743
- * console.log(maskedValue); // Output: '987-654'
744
- * ```
745
- */
746
- const custom = (value, masks) => {
747
- if (!masks.custom || !value) return value;
748
- let mask = '';
749
- let index = 0;
750
- const convertedValue = value.replace(/[^\w\s]/gi, '');
751
- for (const char of masks.custom) {
752
- if (char === '#') {
753
- if (index < convertedValue.length) {
754
- mask += convertedValue[index];
755
- index++;
756
- } else {
757
- break;
758
- }
759
- } else if (index <= convertedValue.length) {
760
- mask += char;
761
- }
762
- }
763
- if (value.length < mask.length) {
764
- mask = mask.replace(/[^\w]+$/, '');
765
- }
766
- return mask;
767
- };
768
-
769
- /**
770
- * Applies a secure mask to a credit card number, hiding most of its digits.
771
- *
772
- * @param value - The credit card number to be masked.
773
- * @returns The masked credit card number.
774
- *
775
- * @example
776
- * ```typescript
777
- * import { secureCreditCard } from './path/to/creditCardFunctions';
778
- *
779
- * const maskedCardNumber = secureCreditCard('1234567890123456');
780
- * console.log(maskedCardNumber); // Output: '1xxxxxxxxxxxx456'
781
- * ```
782
- */
783
- const secureCreditCard = value => {
784
- const maskValue = [{
785
- from: 1,
786
- to: 4,
787
- mask: 'x'
788
- }, {
789
- from: 6,
790
- to: 9,
791
- mask: 'x'
792
- }, {
793
- from: 11,
794
- to: 14,
795
- mask: 'x'
796
- }, {
797
- from: 16,
798
- to: 19,
799
- mask: 'x'
800
- }];
801
- return generic(value, {
802
- generic: maskValue
803
- });
804
- };
805
- /**
806
- * Formats a credit card number by inserting spaces every four characters.
807
- *
808
- * @param value - The credit card number to be formatted.
809
- * @returns The formatted credit card number.
810
- *
811
- * @example
812
- * ```typescript
813
- * import { card } from './path/to/creditCardFunctions';
814
- *
815
- * const formattedCardNumber = card('1234567890123456');
816
- * console.log(formattedCardNumber); // Output: '1234 5678 9012 3456'
817
- * ```
818
- */
819
- const card = value => {
820
- return value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
821
- };
822
- /**
823
- * Formats a credit card expiration date (MM/YY).
824
- *
825
- * @param value - The expiration date to be formatted (in MMYY or MM/YY format).
826
- * @returns The formatted expiration date.
827
- *
828
- * @example
829
- * ```typescript
830
- * import { cardDate } from './path/to/creditCardFunctions';
831
- *
832
- * const formattedCardDate = cardDate('1223');
833
- * console.log(formattedCardDate); // Output: '12/23'
834
- * ```
835
- */
836
- const cardDate = value => formatDateCard(value);
837
- /**
838
- * Formats a credit card FEIN (Federal Employer Identification Number) in a specific format.
839
- *
840
- * @param value - The FEIN to be formatted.
841
- * @returns The formatted FEIN.
842
- *
843
- * @example
844
- * ```typescript
845
- * import { fein } from './path/to/creditCardFunctions';
846
- *
847
- * const formattedFEIN = fein('123456789');
848
- * console.log(formattedFEIN); // Output: '12-3456789'
849
- * ```
850
- */
851
- const fein = value => formatDateCard(value, 9, '-');
852
-
853
- const masks = {
854
- currency,
855
- custom,
856
- callback: (value, masks) => (masks === null || masks === void 0 ? void 0 : masks.callback) && masks.callback(value),
857
- generic,
858
- secureCreditCard,
859
- card,
860
- cardDate,
861
- fein,
862
- replaceAll
863
- };
864
-
865
- /**
866
- * Validates the length of a value based on the provided validation rules.
867
- *
868
- * @param value - The value to be validated. Can be of any type but will be converted to a string for length validation.
869
- * @param validations - An object containing the length validation rules.
870
- * @returns `true` if the value meets the length validation rule, otherwise `false`.
871
- *
872
- * @example
873
- * ```typescript
874
- * import validateLength from './path/to/validationFunctions';
875
- *
876
- * const validations = {
877
- * length: {
878
- * target: 5,
879
- * rule: 'equal'
880
- * }
881
- * };
882
- *
883
- * const isValid = validateLength('hello', validations);
884
- * console.log(isValid); // Output: true
885
- *
886
- * // Using from a JSON config
887
- * const config = {
888
- * inputValue: 'test',
889
- * validations: {
890
- * length: {
891
- * target: 4,
892
- * rule: 'equal'
893
- * }
894
- * }
895
- * };
896
- *
897
- * const isValid = validateLength(config.inputValue, config.validations);
898
- * console.log(isValid); // Output: true or false based on validation
899
- * ```
900
- */
901
- var length = (value, validations) => {
902
- if (!validations.length || !value) return false;
903
- let targetValue = value;
904
- // We want length even if it is a numeric
905
- if (typeof targetValue !== 'string') {
906
- targetValue = (value === null || value === void 0 ? void 0 : value.toString()) || targetValue;
907
- }
908
- const condition = {
909
- equal: targetValue.length !== validations.length.target,
910
- notEqual: targetValue.length === validations.length.target,
911
- less: targetValue.length >= validations.length.target,
912
- lessOrEqual: targetValue.length > validations.length.target,
913
- greater: targetValue.length <= validations.length.target,
914
- greaterOrEqual: targetValue.length < validations.length.target
915
- };
916
- return condition[validations.length.rule];
917
- };
918
-
919
- /**
920
- * Validates a Spanish NIF (Número de Identificación Fiscal).
921
- *
922
- * @param value - The NIF value to validate.
923
- * @returns `true` if the NIF is invalid, otherwise `false`.
924
- */
925
- const NIF_ES = value => {
926
- if (value.length !== 9) return true;
927
- if (!/^\d{8}$/.test(value.slice(0, 8))) {
928
- return true;
929
- }
930
- const validLetters = 'TRWAGMYFPDXBNJZSQVHLCKE';
931
- const numberPart = parseInt(value.slice(0, 8), 10);
932
- const expectedLetter = validLetters[numberPart % 23];
933
- return !(value[8].toUpperCase() === expectedLetter);
934
- };
935
- /**
936
- * Validates a Portuguese NIF (Número de Identificação Fiscal).
937
- *
938
- * @param value - The NIF value to validate.
939
- * @returns `true` if the NIF is valid, otherwise `false`.
940
- */
941
- const NIF_PT = value => {
942
- const regex = /^\d{9}$/;
943
- if (!regex.test(value)) return false;
944
- const checkDigit = parseInt(value[8], 10);
945
- const sum = Array.from(value.substring(0, 8)).reduce((acc, digit, index) => acc + parseInt(digit, 10) * (9 - index), 0);
946
- const calculatedCheckDigit = 11 - sum % 11;
947
- return calculatedCheckDigit === 10 || calculatedCheckDigit === 11 ? 0 === checkDigit : calculatedCheckDigit === checkDigit;
948
- };
949
- /**
950
- * Validates an Italian NIF (Codice Fiscale).
951
- *
952
- * @param value - The NIF value to validate.
953
- * @returns `true` if the NIF is valid, otherwise `false`.
954
- */
955
- const NIF_IT = value => {
956
- const regex = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
957
- return regex.test(value);
958
- };
959
- /**
960
- * Validates a German NIF (Steuerliche Identifikationsnummer).
961
- *
962
- * @param nif - The NIF value to validate.
963
- * @returns `true` if the NIF is valid, otherwise `false`.
964
- */
965
- const NIF_DE = nif => {
966
- const regex = /^\d{11}$/;
967
- return regex.test(nif);
968
- };
969
- /**
970
- * Validates a French NIF (Numéro d'Immatriculation Fiscale).
971
- *
972
- * @param nif - The NIF value to validate.
973
- * @returns `true` if the NIF is valid, otherwise `false`.
974
- */
975
- const NIF_FR = nif => {
976
- const regex = /^\d{2} \d{3} \d{3} \d{3} \d{3}$/;
977
- return regex.test(nif);
978
- };
979
- /**
980
- * Validates a UK NIF (National Insurance Number).
981
- *
982
- * @param value - The NIF value to validate.
983
- * @returns `true` if the NIF is valid, otherwise `false`.
984
- */
985
- const NIF_UK = value => {
986
- const regex = /^GB\d{9}|\d{12}|\d{3}[A-Z]{5}$/;
987
- return regex.test(value);
988
- };
989
- /**
990
- * Validates a Belgian NIF (Numéro d'Identification Fiscale).
991
- *
992
- * @param value - The NIF value to validate.
993
- * @returns `true` if the NIF is valid, otherwise `false`.
994
- */
995
- const NIF_BE = value => {
996
- const regex = /^\d{11}$/;
997
- if (!regex.test(value)) return false;
998
- const number = parseInt(value.substring(0, 9), 10);
999
- const checkDigits = parseInt(value.substring(9), 10);
1000
- const mod = 97 - number % 97;
1001
- return mod === checkDigits;
1002
- };
1003
- /**
1004
- * Validates a Dutch NIF (Burgerservicenummer).
1005
- *
1006
- * @param value - The NIF value to validate.
1007
- * @returns `true` if the NIF is valid, otherwise `false`.
1008
- */
1009
- const NIF_NL = value => {
1010
- const regex = /^\d{9}$/;
1011
- if (!regex.test(value)) return false;
1012
- const total = value.split('').map((digit, index) => parseInt(digit, 10) * (9 - index)).reduce((sum, val) => sum + val, 0);
1013
- return total % 11 === 0;
1014
- };
1015
- /**
1016
- * Validates a Swedish NIF (Personnummer).
1017
- *
1018
- * @param value - The NIF value to validate.
1019
- * @returns `true` if the NIF is valid, otherwise `false`.
1020
- */
1021
- const NIF_SE = value => {
1022
- const regex = /^\d{10,12}$/;
1023
- if (!regex.test(value)) return false;
1024
- const normalizedNIF = value.length === 12 ? value.substring(2) : value;
1025
- const total = normalizedNIF.split('').map((digit, index) => {
1026
- let num = parseInt(digit, 10) * (index % 2 === 0 ? 2 : 1);
1027
- if (num > 9) num -= 9;
1028
- return num;
1029
- }).reduce((sum, val) => sum + val, 0);
1030
- return total % 10 === 0;
1031
- };
1032
- /**
1033
- * Validates a NIF based on the locale.
1034
- *
1035
- * @param nif - The NIF value to validate.
1036
- * @param locale - The locale code to determine the type of NIF.
1037
- * @returns `true` if the NIF is valid, otherwise `false`.
1038
- *
1039
- * @example
1040
- * ```typescript
1041
- * import { NIF } from './path/to/validationFunctions';
1042
- *
1043
- * const isValid = NIF('123456789', 'pt-PT');
1044
- * console.log(isValid); // Output: true or false based on validation
1045
- * ```
1046
- */
1047
- const NIF = (nif, locale) => {
1048
- switch (locale) {
1049
- case 'pt-PT':
1050
- return NIF_PT(nif);
1051
- case 'es-ES':
1052
- return NIF_ES(nif);
1053
- case 'it-IT':
1054
- return NIF_IT(nif);
1055
- case 'de-DE':
1056
- return NIF_DE(nif);
1057
- case 'fr-FR':
1058
- return NIF_FR(nif);
1059
- case 'en-GB':
1060
- return NIF_UK(nif);
1061
- case 'nl-BE':
1062
- case 'fr-BE':
1063
- return NIF_BE(nif);
1064
- case 'nl-NL':
1065
- return NIF_NL(nif);
1066
- case 'sv-SE':
1067
- // Suécia
1068
- return NIF_SE(nif);
1069
- default:
1070
- throw new Error(`NIF validation not supported for locale: ${locale}`);
1071
- }
1072
- };
1073
- /**
1074
- * Validates a Spanish NIE (Número de Identificación de Extranjeros).
1075
- *
1076
- * @param value - The NIE value to validate.
1077
- * @returns `true` if the NIE is invalid, otherwise `false`.
1078
- */
1079
- const NIE = value => {
1080
- if (value.length !== 9) return true;
1081
- const nieRegex = /^[XYZ]\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/;
1082
- if (!nieRegex.test(value)) {
1083
- return true;
1084
- }
1085
- let fixedDocNumber = value.toUpperCase().padStart(9, '0');
1086
- fixedDocNumber = fixedDocNumber[0].replace(/[XYZ]/g, char => {
1087
- return {
1088
- X: '0',
1089
- Y: '1',
1090
- Z: '2'
1091
- }[char] || char;
1092
- }) + fixedDocNumber.slice(1);
1093
- return NIF_ES(fixedDocNumber);
1094
- };
1095
- const mod9710 = validationString => {
1096
- while (validationString.length > 2) {
1097
- const part = validationString.slice(0, 6);
1098
- const partInt = parseInt(part, 10);
1099
- if (isNaN(partInt)) {
1100
- return NaN;
1101
- }
1102
- validationString = partInt % 97 + validationString.slice(part.length);
1103
- }
1104
- return parseInt(validationString, 10) % 97;
1105
- };
1106
- /**
1107
- * Validates an IBAN (International Bank Account Number).
1108
- *
1109
- * @param value - The IBAN value to validate.
1110
- * @returns `true` if the IBAN is invalid, otherwise `false`.
1111
- */
1112
- const IBAN = value => {
1113
- const iban = value.replace(/\s/g, '');
1114
- if (iban.length !== 24) return true;
1115
- const ibanRegex = /^(ES)[0-9]{22}$/;
1116
- if (!ibanRegex.test(iban)) {
1117
- return true;
1118
- }
1119
- const ES_ALPHABET_NUMBER = 1428;
1120
- const transformedIban = iban.substring(4) + ES_ALPHABET_NUMBER + iban.substring(2, 4);
1121
- return mod9710(transformedIban) !== 1;
1122
- };
1123
- /**
1124
- * Validates a Spanish CIF (Código de Identificación Fiscal).
1125
- *
1126
- * @param value - The CIF value to validate.
1127
- * @returns `true` if the CIF is invalid, otherwise `false`.
1128
- */
1129
- const CIF = value => {
1130
- const cifRegex = /^[A-Z][0-9]{7}[A-J0-9]$/;
1131
- return !cifRegex.test(value);
1132
- };
1133
- /**
1134
- * General validation function for various document types based on the provided validation methods.
1135
- *
1136
- * @param value - The document value to validate.
1137
- * @param validations - An object containing validation methods.
1138
- * @returns `true` if the document is valid, otherwise `false`.
1139
- *
1140
- * @example
1141
- * ```typescript
1142
- * import validateDocument from './path/to/validationFunctions';
1143
- *
1144
- * const validations = {
1145
- * document: {
1146
- * type: 'NIF',
1147
- * locale: 'pt-PT'
1148
- * }
1149
- * };
1150
- *
1151
- * const isValid = validateDocument('123456789', validations);
1152
- * console.log(isValid); // Output: true or false based on validation
1153
- * ```
1154
- */
1155
- var document = (value, validations) => {
1156
- if (!value || !validations.document) return true;
1157
- const validation = {
1158
- NIF: (value, locale) => NIF(value, locale),
1159
- NIE: value => NIE(value),
1160
- CIF: value => CIF(value),
1161
- IBAN: value => IBAN(value)
1162
- };
1163
- return validation[validations.document.type](value, validations.document.locale);
1164
- };
1165
-
1166
- /**
1167
- * Validates if a value exceeds the maximum allowed value.
1168
- *
1169
- * @param value - The value to be checked.
1170
- * @param validations - An object containing the maximum value for validation.
1171
- * @returns `true` if the value exceeds the maximum, otherwise `false`.
1172
- *
1173
- * @example
1174
- * ```typescript
1175
- * import { max } from './path/to/validationFunctions';
1176
- *
1177
- * const validations = { max: 10 };
1178
- *
1179
- * const isValid = max(15, validations);
1180
- * console.log(isValid); // Output: true
1181
- *
1182
- * // Using from a JSON config
1183
- * const config = {
1184
- * inputValue: '8',
1185
- * validations: { max: 10 }
1186
- * };
1187
- *
1188
- * const isValid = max(config.inputValue, config.validations);
1189
- * console.log(isValid); // Output: false
1190
- * ```
1191
- */
1192
- const max = (value, validations) => {
1193
- const number = Number(value);
1194
- if (!validations.max || Number.isNaN(number)) return false;
1195
- return number > Number(validations.max);
1196
- };
1197
- /**
1198
- * Validates if a value is less than the minimum allowed value.
1199
- *
1200
- * @param value - The value to be checked.
1201
- * @param validations - An object containing the minimum value for validation.
1202
- * @returns `true` if the value is less than the minimum, otherwise `false`.
1203
- *
1204
- * @example
1205
- * ```typescript
1206
- * import { min } from './path/to/validationFunctions';
1207
- *
1208
- * const validations = { min: 5 };
1209
- *
1210
- * const isValid = min(3, validations);
1211
- * console.log(isValid); // Output: true
1212
- *
1213
- * // Using from a JSON config
1214
- * const config = {
1215
- * inputValue: '8',
1216
- * validations: { min: 10 }
1217
- * };
1218
- *
1219
- * const isValid = min(config.inputValue, config.validations);
1220
- * console.log(isValid); // Output: true
1221
- * ```
1222
- */
1223
- const min = (value, validations) => {
1224
- const number = Number(value);
1225
- if (!validations.min || Number.isNaN(number)) return false;
1226
- return number < Number(validations.min);
1227
- };
1228
- /**
1229
- * Validates if a value falls within a specified range.
1230
- *
1231
- * @param value - The value to be checked.
1232
- * @param validations - An object containing the range (start and end) for validation.
1233
- * @returns `true` if the value falls within the range, otherwise `false`.
1234
- *
1235
- * @example
1236
- * ```typescript
1237
- * import { between } from './path/to/validationFunctions';
1238
- *
1239
- * const validations = { between: { start: 5, end: 10 } };
1240
- *
1241
- * const isValid = between(7, validations);
1242
- * console.log(isValid); // Output: true
1243
- *
1244
- * // Using from a JSON config
1245
- * const config = {
1246
- * inputValue: '4',
1247
- * validations: { between: { start: 5, end: 10 } }
1248
- * };
1249
- *
1250
- * const isValid = between(config.inputValue, config.validations);
1251
- * console.log(isValid); // Output: false
1252
- * ```
1253
- */
1254
- const between = (value, validations) => {
1255
- if (!validations.between || !value) return false;
1256
- const num = Number(value);
1257
- return !Number.isNaN(num) && !(+num >= validations.between.start && +num <= validations.between.end);
1258
- };
1259
- /**
1260
- * Checks if a given value is less than a specified threshold.
1261
- *
1262
- * @param value - The value to be checked. This value will be converted to a number.
1263
- * @param validations - An object containing validation methods, specifically the `lessThan` property which holds the threshold value.
1264
- * @returns Returns `false` if the `lessThan` threshold is not provided or if the value is not a valid number. Otherwise, returns `true` if the value is greater than or equal to the `lessThan` threshold.
1265
- *
1266
- * @example
1267
- * ```typescript
1268
- * const validations = { lessThan: 10 };
1269
- * console.log(lessThan(5, validations)); // true
1270
- * console.log(lessThan(15, validations)); // false
1271
- * ```
1272
- */
1273
- const lessThan = (value, validations) => {
1274
- const number = Number(value);
1275
- if (!validations.lessThan || Number.isNaN(number)) return false;
1276
- return number >= validations.lessThan;
1277
- };
1278
- /**
1279
- * Checks if a given value is greater than a specified threshold.
1280
- *
1281
- * @param value - The value to be checked. This value will be converted to a number.
1282
- * @param validations - An object containing validation methods, specifically the `greaterThan` property which holds the threshold value.
1283
- * @returns Returns `false` if the `greaterThan` threshold is not provided or if the value is not a valid number. Otherwise, returns `true` if the value is less than or equal to the `greaterThan` threshold.
1284
- *
1285
- * @example
1286
- * ```typescript
1287
- * const validations = { greaterThan: 10 };
1288
- * console.log(greaterThan(15, validations)); // true
1289
- * console.log(greaterThan(5, validations)); // false
1290
- * ```
1291
- */
1292
- const greaterThan = (value, validations) => {
1293
- const number = Number(value);
1294
- if (!validations.greaterThan || Number.isNaN(number)) return false;
1295
- return number <= validations.greaterThan;
1296
- };
1297
- /**
1298
- * Validates if a value contains sequential numbers.
1299
- *
1300
- * @param value - The value to be checked.
1301
- * @param validations - An object containing the validation methods.
1302
- * @returns `true` if the value contains sequential numbers, otherwise `false`.
1303
- *
1304
- * @example
1305
- * ```typescript
1306
- * import { sequential } from './path/to/validationFunctions';
1307
- *
1308
- * const validations = { sequential: true };
1309
- *
1310
- * const isValid = sequential('12345', validations);
1311
- * console.log(isValid); // Output: true
1312
- *
1313
- * // Using in a React component
1314
- * const MyComponent = ({ inputValue }) => {
1315
- * const isValid = sequential(inputValue, validations);
1316
- * return <div>{isValid ? 'Valid' : 'Invalid'}</div>;
1317
- * };
1318
- *
1319
- * // Using from a JSON config
1320
- * const config = {
1321
- * inputValue: '98765',
1322
- * validations: { sequential: true }
1323
- * };
1324
- *
1325
- * const isValid = sequential(config.inputValue, config.validations);
1326
- * console.log(isValid); // Output: true
1327
- * ```
1328
- */
1329
- const sequential = (value, validations) => {
1330
- if (!validations.sequential) return false;
1331
- const numbers = '0123456789';
1332
- const numbersRev = '9876543210';
1333
- const replacedValue = String(value).replace(/[^0-9]/g, '');
1334
- return !(numbers.indexOf(replacedValue) === -1 && numbersRev.indexOf(replacedValue) === -1);
1335
- };
1336
-
1337
- /**
1338
- * Validates if a value matches a given regular expression.
1339
- *
1340
- * @param value - The value to be checked.
1341
- * @param validations - An object containing the regex pattern for validation.
1342
- * @returns `true` if the value does not match the regex, otherwise `false`.
1343
- *
1344
- * @example
1345
- * ```typescript
1346
- * import { regex } from './path/to/validationFunctions';
1347
- *
1348
- * const validations = { regex: '^[a-zA-Z0-9]*$' };
1349
- *
1350
- * const isValid = regex('abc123', validations);
1351
- * console.log(isValid); // Output: false
1352
- *
1353
- * // Using from a JSON config
1354
- * const config = {
1355
- * inputValue: 'abc123',
1356
- * validations: { regex: '^[a-zA-Z0-9]*$' }
1357
- * };
1358
- *
1359
- * const isValid = regex(config.inputValue, config.validations);
1360
- * console.log(isValid); // Output: false
1361
- * ```
1362
- */
1363
- const regex = (value, validations) => {
1364
- if (!validations.regex || !value) return false;
1365
- const regex = new RegExp(validations.regex);
1366
- return !regex.test(value);
1367
- };
1368
- /**
1369
- * Validates if a value is a valid email address.
1370
- *
1371
- * @param value - The value to be checked.
1372
- * @param validations - An object containing the email validation flag.
1373
- * @returns `true` if the value is not a valid email, otherwise `false`.
1374
- *
1375
- * @example
1376
- * ```typescript
1377
- * import { email } from './path/to/validationFunctions';
1378
- *
1379
- * const validations = { email: true };
1380
- *
1381
- * const isValid = email('test@example.com', validations);
1382
- * console.log(isValid); // Output: false
1383
- *
1384
- * // Using from a JSON config
1385
- * const config = {
1386
- * inputValue: 'invalid-email',
1387
- * validations: { email: true }
1388
- * };
1389
- *
1390
- * const isValid = email(config.inputValue, config.validations);
1391
- * console.log(isValid); // Output: true
1392
- * ```
1393
- */
1394
- const email = (value, validations) => {
1395
- if (!validations.email || !value) return false;
1396
- const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1397
- return !regex.test(value);
1398
- };
1399
- /**
1400
- * Validates if a value is a valid URL.
1401
- *
1402
- * @param value - The value to be checked.
1403
- * @param validations - An object containing the URL validation flag.
1404
- * @returns `true` if the value is not a valid URL, otherwise `false`.
1405
- *
1406
- * @example
1407
- * ```typescript
1408
- * import { url } from './path/to/validationFunctions';
1409
- *
1410
- * const validations = { url: true };
1411
- *
1412
- * const isValid = url('https://example.com', validations);
1413
- * console.log(isValid); // Output: false
1414
- *
1415
- * // Using from a JSON config
1416
- * const config = {
1417
- * inputValue: 'invalid-url',
1418
- * validations: { url: true }
1419
- * };
1420
- *
1421
- * const isValid = url(config.inputValue, config.validations);
1422
- * console.log(isValid); // Output: true
1423
- * ```
1424
- */
1425
- const url = (value, validations) => {
1426
- if (!validations.url || !value) return false;
1427
- const regex = /[(http(s)?)://(www.)?a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi;
1428
- return !regex.test(value);
1429
- };
1430
- /**
1431
- * Validates if a value contains only letters.
1432
- *
1433
- * @param value - The value to be checked.
1434
- * @param validations - An object containing the onlyLetters validation flag.
1435
- * @returns `true` if the value contains non-letter characters, otherwise `false`.
1436
- *
1437
- * @example
1438
- * ```typescript
1439
- * import { onlyLetters } from './path/to/validationFunctions';
1440
- *
1441
- * const validations = { onlyLetters: true };
1442
- *
1443
- * const isValid = onlyLetters('abc', validations);
1444
- * console.log(isValid); // Output: false
1445
- *
1446
- * // Using from a JSON config
1447
- * const config = {
1448
- * inputValue: '123',
1449
- * validations: { onlyLetters: true }
1450
- * };
1451
- *
1452
- * const isValid = onlyLetters(config.inputValue, config.validations);
1453
- * console.log(isValid); // Output: true
1454
- * ```
1455
- */
1456
- const onlyLetters = (value, validations) => {
1457
- if (!validations.onlyLetters) return false;
1458
- return !/^[\p{L}\s]*$/u.test(value);
1459
- };
1460
- /**
1461
- * Validates if a value does not contain spaces.
1462
- *
1463
- * @param value - The value to be checked.
1464
- * @param validations - An object containing the notAllowSpaces validation flag.
1465
- * @returns `true` if the value contains spaces, otherwise `false`.
1466
- *
1467
- * @example
1468
- * ```typescript
1469
- * import { notAllowSpaces } from './path/to/validationFunctions';
1470
- *
1471
- * const validations = { notAllowSpaces: true };
1472
- *
1473
- * const isValid = notAllowSpaces('no spaces', validations);
1474
- * console.log(isValid); // Output: true
1475
- *
1476
- * // Using from a JSON config
1477
- * const config = {
1478
- * inputValue: 'nospaces',
1479
- * validations: { notAllowSpaces: true }
1480
- * };
1481
- *
1482
- * const isValid = notAllowSpaces(config.inputValue, config.validations);
1483
- * console.log(isValid); // Output: false
1484
- * ```
1485
- */
1486
- const notAllowSpaces = (value, validations) => {
1487
- if (!validations.notAllowSpaces) return false;
1488
- return /\s/.test(value);
1489
- };
1490
- /**
1491
- * Validates if a value is a number.
1492
- *
1493
- * @param value - The value to be checked.
1494
- * @param validations - An object containing the isNumber validation flag.
1495
- * @returns `true` if the value is not a number, otherwise `false`.
1496
- *
1497
- * @example
1498
- * ```typescript
1499
- * import { isNumber } from './path/to/validationFunctions';
1500
- *
1501
- * const validations = { isNumber: true };
1502
- *
1503
- * const isValid = isNumber('123', validations);
1504
- * console.log(isValid); // Output: false
1505
- *
1506
- * // Using from a JSON config
1507
- * const config = {
1508
- * inputValue: 'abc',
1509
- * validations: { isNumber: true }
1510
- * };
1511
- *
1512
- * const isValid = isNumber(config.inputValue, config.validations);
1513
- * console.log(isValid); // Output: true
1514
- * ```
1515
- */
1516
- const isNumber = (value, validations) => {
1517
- if (!validations.isNumber) return false;
1518
- return !!value && !/^[0-9\s]*$/.test(value);
1519
- };
1520
- /**
1521
- * Validates if a value has no trailing or leading spaces.
1522
- *
1523
- * @param value - The value to be checked.
1524
- * @param validations - An object containing the hasNoExtraSpaces validation flag.
1525
- * @returns `true` if the value has trailing or leading spaces, otherwise `false`.
1526
- *
1527
- * @example
1528
- * ```typescript
1529
- * import { hasNoExtraSpaces } from './path/to/validationFunctions';
1530
- *
1531
- * const validations = { hasNoExtraSpaces: true };
1532
- *
1533
- * const isValid = hasNoExtraSpaces('Hello', validations);
1534
- * console.log(isValid); // Output: true
1535
- *
1536
- * // Using from a JSON config
1537
- * const config = {
1538
- * inputValue: ' Hello ',
1539
- * validations: { hasNoExtraSpaces: true }
1540
- * };
1541
- *
1542
- * const isValid = hasNoExtraSpaces(config.inputValue, config.validations);
1543
- * console.log(isValid); // Output: false
1544
- * ```
1545
- */
1546
- const hasNoExtraSpaces = (value, validations) => {
1547
- if (!validations.hasNoExtraSpaces || !value) return false;
1548
- return regex(value, {
1549
- regex: '^[A-Za-zÀ-ÖØ-öø-ÿäöüÄÖÜß0-9]+$'
1550
- });
1551
- };
1552
- /**
1553
- * Validates if a value contains repeated digits.
1554
- *
1555
- * @param value - The value to be checked.
1556
- * @param validations - An object containing the repeated validation flag.
1557
- * @returns `true` if the value contains repeated digits, otherwise `false`.
1558
- *
1559
- * @example
1560
- * ```typescript
1561
- * import { repeated } from './path/to/validationFunctions';
1562
- *
1563
- * const validations = { repeated: true };
1564
- *
1565
- * const isValid = repeated('1231', validations);
1566
- * console.log(isValid); // Output: true
1567
- *
1568
- * // Using from a JSON config
1569
- * const config = {
1570
- * inputValue: '1234',
1571
- * validations: { repeated: true }
1572
- * };
1573
- *
1574
- * const isValid = repeated(config.inputValue, config.validations);
1575
- * console.log(isValid); // Output: false
1576
- * ```
1577
- */
1578
- const repeated = (value, validations) => {
1579
- if (!validations.repeated) return false;
1580
- const numCount = {};
1581
- for (const char of String(value)) {
1582
- if (/\d/.test(char)) {
1583
- if (numCount[char]) {
1584
- return true;
1585
- }
1586
- numCount[char] = 1;
1587
- }
1588
- }
1589
- return false;
1590
- };
1591
-
1592
- /**
1593
- * Executes a custom callback validation function if provided.
1594
- *
1595
- * @param value - The value to be validated.
1596
- * @param validations - An object containing validation methods, including a custom callback function.
1597
- * @param formValues - An object containing the form state, NOTE: validations might be dirty here
1598
- * @returns `true` if the custom callback validation function returns `true`, otherwise `false`.
1599
- *
1600
- * @example
1601
- * ```typescript
1602
- * import { callback } from './path/to/validationFunctions';
1603
- *
1604
- * const validations = {
1605
- * callback: (value) => typeof value === 'string' && value.length > 5
1606
- * };
1607
- *
1608
- * // Or from a JSON config
1609
- * const schema = {
1610
- * validations: {
1611
- * callback: (value) => typeof value === 'string' && value.length > 5
1612
- * }
1613
- * };
1614
- * ```
1615
- */
1616
- const callback = (value, validations, {
1617
- values = [],
1618
- metadata = []
1619
- } = {
1620
- values: [],
1621
- metadata: [],
1622
- erroredFields: [],
1623
- isValid: true
1624
- }) => {
1625
- if (!validations.callback || !((validations === null || validations === void 0 ? void 0 : validations.callback) instanceof Function)) return false;
1626
- return validations.callback(value, {
1627
- values,
1628
- metadata
1629
- });
1630
- };
1631
-
1632
- /**
1633
- * Checks if a value is included in the specified array within the validation rules.
1634
- *
1635
- * @param value - The value to be checked.
1636
- * @param validations - An object containing validation methods, including an array of allowed values.
1637
- * @returns `true` if the value is included in the array, otherwise `false`.
1638
- *
1639
- * @example
1640
- * ```typescript
1641
- * import { includes } from './path/to/validationFunctions';
1642
- *
1643
- * const validations = {
1644
- * includes: ['apple', 'banana', 'cherry']
1645
- * };
1646
- *
1647
- * const isValid = includes('banana', validations);
1648
- * console.log(isValid); // Output: true
1649
- *
1650
- * // Using from a JSON config
1651
- * const config = {
1652
- * inputValue: 'apple',
1653
- * validations: {
1654
- * includes: ['apple', 'banana', 'cherry']
1655
- * }
1656
- * };
1657
- *
1658
- * const isValid = includes(config.inputValue, config.validations);
1659
- * console.log(isValid); // Output: true or false based on validation
1660
- * ```
1661
- */
1662
- const includes = (value, validations) => {
1663
- if (!value || !Array.isArray(validations === null || validations === void 0 ? void 0 : validations.includes)) return false;
1664
- return !(validations === null || validations === void 0 ? void 0 : validations.includes.some(code => code === value || JSON.stringify(code) === value));
1665
- };
1666
-
1667
- /**
1668
- * Validates if a given value is a valid credit card number based on predefined validation methods.
1669
- *
1670
- * @param value - The value to be validated as a credit card number.
1671
- * @param validations - An object containing validation methods.
1672
- * @returns `true` if the value is either falsy or does not match a valid credit card type, otherwise `false`.
1673
- *
1674
- * @example
1675
- * ```typescript
1676
- * import { isCreditCard } from './path/to/validationFunctions';
1677
- * import { validationMethods } from './path/to/validationConfig';
1678
- *
1679
- * const isValid = isCreditCard('4111111111111111', validationMethods);
1680
- * console.log(isValid); // Output: true or false based on validation
1681
- * ```
1682
- */
1683
- const isCreditCard = (value, validations) => {
1684
- if (!value) return true;
1685
- const [type] = getTypeCard(String(value), validations.isCreditCard);
1686
- return !type;
1687
- };
1688
- /**
1689
- * Validates if a given security code matches the expected length for a specified credit card type.
1690
- *
1691
- * @param value - The security code to be validated.
1692
- * @param validations - An object containing validation methods, specifically with `isCreditCodeMatch` details.
1693
- * @returns `true` if the value is either falsy or if the validation methods are not provided. Otherwise, it checks if the security code length matches the expected length for the card type.
1694
- *
1695
- * @example
1696
- * ```typescript
1697
- * import { isCreditCodeMatch } from './path/to/validationFunctions';
1698
- * import { validationMethods } from './path/to/validationConfig';
1699
- *
1700
- * const isValid = isCreditCodeMatch('123', validationMethods);
1701
- * console.log(isValid); // Output: true or false based on validation
1702
- * ```
1703
- */
1704
- const isCreditCodeMatch = (value, validations) => {
1705
- var _a;
1706
- if (!value || !validations.isCreditCodeMatch) return false;
1707
- const [type] = getTypeCard(validations.isCreditCodeMatch.numberCard, validations.isCreditCodeMatch.availableOptions);
1708
- return ((_a = type === null || type === void 0 ? void 0 : type.code) === null || _a === void 0 ? void 0 : _a.size) !== value.length;
1709
- };
1710
- /**
1711
- * Validates if a given value is a valid credit card number and checks if its length matches the expected lengths for the card type.
1712
- *
1713
- * @param value - The credit card number to be validated.
1714
- * @param validations - An object containing validation methods, specifically with `isCreditCardAndLength` details.
1715
- * @returns `true` if the value is either falsy or if the card number does not match any valid lengths for the card type, otherwise `false`.
1716
- *
1717
- * @example
1718
- * ```typescript
1719
- * import { isCreditCardAndLength } from './path/to/validationFunctions';
1720
- * import { validationMethods } from './path/to/validationConfig';
1721
- *
1722
- * const isValid = isCreditCardAndLength('4111111111111111', validationMethods);
1723
- * console.log(isValid); // Output: true or false based on validation
1724
- * ```
1725
- */
1726
- const isCreditCardAndLength = (value, validations) => {
1727
- if (!value || !validations.isCreditCardAndLength) return false;
1728
- const [type, rawValue] = getTypeCard(value, validations.isCreditCardAndLength);
1729
- return type && !type.lengths.includes(rawValue.length);
1730
- };
1731
-
1732
- /**
1733
- * Validates that a string value is not empty.
1734
- *
1735
- * @param {string} value - The value to be validated.
1736
- * @param {TValidationMethods} validations - The validation methods object containing the notEmpty validation rule.
1737
- * @returns {boolean} - Returns `true` if the value is empty and the notEmpty validation rule is set, otherwise `false`.
1738
- *
1739
- * @example
1740
- * ```typescript
1741
- * // Assume validations is an object with a notEmpty property
1742
- * const validations = { notEmpty: true };
1743
- *
1744
- * // Returns true because the string is empty
1745
- * const result1 = notEmpty('', validations);
1746
- * console.log(result1); // true
1747
- *
1748
- * // Returns false because the string is not empty
1749
- * const result2 = notEmpty('hello', validations);
1750
- * console.log(result2); // false
1751
- *
1752
- * // Returns false because the notEmpty validation rule is not set
1753
- * const result3 = notEmpty('', { notEmpty: false });
1754
- * console.log(result3); // false
1755
- * ```
1756
- */
1757
- const notEmpty = (value, validations) => {
1758
- var _a;
1759
- if (!(validations === null || validations === void 0 ? void 0 : validations.notEmpty) || typeof value === 'undefined') return false;
1760
- return value === null || value === '' || value === 0 || !((_a = String(value)) === null || _a === void 0 ? void 0 : _a.trim().length);
1761
- };
1762
- /**
1763
- * Validates that a value matches a specified value.
1764
- *
1765
- * @param {unknown} value - The value to be validated.
1766
- * @param {TValidationMethods} validations - The validation methods object containing the value validation rule.
1767
- * @returns {boolean} - Returns `true` if the value does not match the specified validation value, otherwise `false`.
1768
- *
1769
- * @example
1770
- * ```typescript
1771
- * // Assume validations is an object with a value property
1772
- * const validations = { value: 42 };
1773
- *
1774
- * // Returns true because the value does not match the validation value
1775
- * const result1 = value(10, validations);
1776
- * console.log(result1); // true
1777
- *
1778
- * // Returns false because the value matches the validation value
1779
- * const result2 = value(42, validations);
1780
- * console.log(result2); // false
1781
- *
1782
- * // Returns false because the value validation rule is not set
1783
- * const result3 = value(10, { value: undefined });
1784
- * console.log(result3); // false
1785
- * ```
1786
- */
1787
- const value = (value, validations) => {
1788
- if (typeof (validations === null || validations === void 0 ? void 0 : validations.value) === 'undefined' || (validations === null || validations === void 0 ? void 0 : validations.value) === null || typeof value === 'undefined' || value === null) return false;
1789
- return value != validations.value;
1790
- };
1791
-
1792
- /**
1793
- * Validates that a value is required.
1794
- *
1795
- * @param {unknown} value - The value to be validated.
1796
- * @param {TValidationMethods} validations - The validation methods object containing the required validation rule.
1797
- * @returns {boolean} - Returns `true` if the value is required and is empty or not provided, otherwise `false`.
1798
- *
1799
- * @example
1800
- * ```typescript
1801
- * // Assume validations is an object with a required property
1802
- * const validations = { required: true };
1803
- *
1804
- * // Returns true because the value is required and is empty
1805
- * const result1 = required('', validations);
1806
- * console.log(result1); // true
1807
- *
1808
- * // Returns false because the value is required and is provided
1809
- * const result2 = required('text', validations);
1810
- * console.log(result2); // false
1811
- *
1812
- * // Returns false because the required validation rule is not set
1813
- * const result3 = required('', { required: false });
1814
- * console.log(result3); // false
1815
- * ```
1816
- */
1817
- const required = (value, validations) => !!(validations.required && (!value || typeof value === 'string' && value.trim().length === 0));
1818
- /**
1819
- * Validates that a value matches a boolean rule. Useful with iVars property.
1820
- *
1821
- * @param _
1822
- * @param {TValidationMethods} validations - The validation methods object containing the boolean validation rule.
1823
- * @returns {boolean} - Returns `true` if the boolean validation rule is set and fails, otherwise `false`.
1824
- *
1825
- * @example
1826
- * ```typescript
1827
- * // Assume validations is an object with a bool property
1828
- * const validations = { bool: true };
1829
- *
1830
- * // Returns true because the boolean validation rule is set to fail
1831
- * const result1 = bool(null, validations);
1832
- * console.log(result1); // true
1833
- *
1834
- * // Returns false because the boolean validation rule is not set
1835
- * const result2 = bool(null, { bool: false });
1836
- * console.log(result2); // false
1837
- * ```
1838
- */
1839
- const bool = (_, validations) => {
1840
- if (!(validations === null || validations === void 0 ? void 0 : validations.bool)) return false;
1841
- let fail = false;
1842
- if (typeof validations.bool === 'boolean') {
1843
- fail = validations.bool;
1844
- }
1845
- return fail;
1846
- };
1847
- /**
1848
- * Validates that a value exists. Useful with iVars property.
1849
- *
1850
- * @param {unknown} value - The value to be validated.
1851
- * @param {TValidationMethods} validations - The validation methods object containing the exists validation rule.
1852
- * @returns {boolean} - Returns `true` if the value does not exist when the exists rule is set, otherwise `false`.
1853
- *
1854
- * @example
1855
- * ```typescript
1856
- * // Assume validations is an object with an exists property
1857
- * const validations = { exists: true };
1858
- *
1859
- * // Returns true because the value does not exist
1860
- * const result1 = exists(null, validations);
1861
- * console.log(result1); // true
1862
- *
1863
- * // Returns false because the value exists
1864
- * const result2 = exists('text', validations);
1865
- * console.log(result2); // false
1866
- *
1867
- * // Returns false because the exists validation rule is not set
1868
- * const result3 = exists(null, { exists: false });
1869
- * console.log(result3); // false
1870
- * ```
1871
- */
1872
- const exists = (value, validations) => {
1873
- if (!validations.exists) return false;
1874
- let fail = !validations.exists;
1875
- if (!fail) {
1876
- fail = !value;
1877
- }
1878
- return fail;
1879
- };
1880
-
1881
- /**
1882
- * @internal
1883
- * Evaluates a condition based on the provided rule and value.
1884
- *
1885
- * @param {number | string | boolean} value - The value to be used in the condition evaluation.
1886
- * @param {TConditionsValidationSet} rule - The rule defining the condition to be evaluated.
1887
- * @returns {boolean} - The result of the condition evaluation.
1888
- *
1889
- * @example
1890
- * const rule = {
1891
- * condition: '===',
1892
- * origin: 5,
1893
- * target: 5,
1894
- * };
1895
- * const result = conditionResult(5, rule);
1896
- * console.log(result); // true (5 === 5)
1897
- *
1898
- * @example
1899
- * const rule = {
1900
- * condition: '!==',
1901
- * origin: 5,
1902
- * target: 10,
1903
- * };
1904
- * const result = conditionResult(5, rule);
1905
- * console.log(result); // true (5 !== 10)
1906
- *
1907
- * @example
1908
- * const rule = {
1909
- * condition: '<',
1910
- * origin: 5,
1911
- * target: 10,
1912
- * };
1913
- * const result = conditionResult(5, rule);
1914
- * console.log(result); // true (5 < 10)
1915
- */
1916
- const conditionResult = (value, rule) => {
1917
- if (rule.forceDefinedOrigin && rule.origin === undefined || rule.forceDefinedTarget && rule.target === undefined) {
1918
- return false;
1919
- }
1920
- const origin = rule.origin === undefined ? value : rule.origin;
1921
- const target = rule.target === undefined ? value : rule.target;
1922
- const conditionMapper = {
1923
- '!==': (origin || value) !== (target || value),
1924
- '===': (origin || value) === (target || value),
1925
- '<': (origin || value) < (target || value),
1926
- '>': (origin || value) > (target || value),
1927
- '<=': (origin || value) <= (target || value),
1928
- '>=': (origin || value) >= (target || value),
1929
- '!!origin': !!String(origin || value).trim().length
1930
- };
1931
- return conditionMapper[rule.condition];
1932
- };
1933
- /**
1934
- * Validates that a value meets specified conditions.
1935
- *
1936
- * @param {number | string | boolean} value - The value to be validated.
1937
- * @param {TValidationMethods} validations - The validation methods object containing the conditions validation rule.
1938
- * @returns {boolean} - Returns `true` if the value meets the specified conditions, otherwise `false`.
1939
- *
1940
- * @example
1941
- * ```typescript
1942
- * // Assume validations is an object with a conditions property
1943
- * const validations = {
1944
- * conditions: {
1945
- * rule: 'and',
1946
- * set: [
1947
- * { condition: '===', origin: 10, target: 10 },
1948
- * { condition: '!==', origin: 5, target: 3 }
1949
- * ]
1950
- * }
1951
- * };
1952
- *
1953
- * // Returns true because both conditions are met
1954
- * const result1 = conditions(10, validations);
1955
- * console.log(result1); // true
1956
- *
1957
- * // Returns false because the second condition is not met
1958
- * const result2 = conditions(5, validations);
1959
- * console.log(result2); // false
1960
- *
1961
- * // Returns true because at least one condition is met with 'or' rule
1962
- * const orValidations = {
1963
- * conditions: {
1964
- * rule: 'or',
1965
- * set: [
1966
- * { condition: '===', origin: 10, target: 5 },
1967
- * { condition: '!==', origin: 5, target: 3 }
1968
- * ]
1969
- * }
1970
- * };
1971
- * const result3 = conditions(10, orValidations);
1972
- * console.log(result3); // true
1973
- * ```
1974
- */
1975
- const conditions = (value, validations) => {
1976
- if (!validations.conditions) return false;
1977
- const rulesMapper = {
1978
- and: () => {
1979
- var _a;
1980
- return !!((_a = validations.conditions) === null || _a === void 0 ? void 0 : _a.set.every(validate => conditionResult(value, validate)));
1981
- },
1982
- or: () => {
1983
- var _a;
1984
- return !!((_a = validations.conditions) === null || _a === void 0 ? void 0 : _a.set.some(validate => conditionResult(value, validate)));
1985
- }
1986
- };
1987
- let result = rulesMapper[validations.conditions.rule]();
1988
- if (validations.conditions.conditions) {
1989
- if (validations.conditions.rule === 'and') {
1990
- result = result && conditions(value, {
1991
- conditions: validations.conditions.conditions
1992
- });
1993
- } else {
1994
- result = result || conditions(value, {
1995
- conditions: validations.conditions.conditions
1996
- });
1997
- }
1998
- }
1999
- return !result;
2000
- };
2001
-
2002
- /**
2003
- * @internal
2004
- * Validates if a date string matches a specific date format.
2005
- * The function accepts strings with '/' or '-' separators and removes them before validating the format.
2006
- *
2007
- * @param {string} value - The date string to be validated. It can contain '/' or '-' separators.
2008
- * @param {string} format - The expected date format. It can be one of the following:
2009
- * 'DDMMYYYY', 'YYYYMMDD', 'YYYYDDMM', 'MMDDYYYY',
2010
- * 'DMYYYY', 'YYYYMD', 'YYYYDM', 'MDYYYY'.
2011
- * @returns {boolean} - Returns `false` if the date string matches the specified format, otherwise `true`.
2012
- *
2013
- * @example
2014
- * // Returns false
2015
- * invalidStringDate("25/07/1997", "DDMMYYYY");
2016
- *
2017
- * @example
2018
- * // Returns false
2019
- * invalidStringDate("1997-07-25", "YYYYMMDD");
2020
- *
2021
- * @example
2022
- * // Returns true, as the format does not match
2023
- * invalidStringDate("1997/25/07", "MMDDYYYY");
2024
- */
2025
- const invalidStringDate = (value, format) => {
2026
- if (!value.includes('/') && !value.includes('-') || !format) {
2027
- return true;
2028
- }
2029
- const valueParts = value.replace(/[-/]/g, '');
2030
- const dateMapper = {
2031
- DDMMYYYY: /^(\d{2})(\d{2})(\d{4})$/,
2032
- YYYYMMDD: /^(\d{4})(\d{2})(\d{2})$/,
2033
- YYYYDDMM: /^(\d{4})(\d{2})(\d{2})$/,
2034
- MMDDYYYY: /^(\d{2})(\d{2})(\d{4})$/,
2035
- DMYYYY: /^(\d{1,2})(\d{1,2})(\d{4})$/,
2036
- YYYYMD: /^(\d{4})(\d{1,2})(\d{1,2})$/,
2037
- YYYYDM: /^(\d{4})(\d{1,2})(\d{1,2})$/,
2038
- MDYYYY: /^(\d{1,2})(\d{1,2})(\d{4})$/
2039
- };
2040
- return !dateMapper[format].test(valueParts);
2041
- };
2042
- /**
2043
- * @internal
2044
- * Adjusts a date by adding intervals of years, months, or days.
2045
- *
2046
- * @param {Date} date - The initial date.
2047
- * @param {TDateInterval} intervals - An object specifying the intervals to add.
2048
- * @returns {Date} - The adjusted date.
2049
- *
2050
- * @example
2051
- * const initialDate = new Date('2023-01-01');
2052
- * const intervals = { years: 1, months: 6, days: 15 };
2053
- * const newDate = getIntervalsDate(initialDate, intervals);
2054
- * console.log(newDate); // Expected date: '2024-07-16'
2055
- */
2056
- const getIntervalsDate = (date, intervals) => {
2057
- const intervalsMapper = {
2058
- years: (date, value) => new Date(date.setUTCFullYear(date.getUTCFullYear() + value)),
2059
- months: (date, value) => new Date(date.setUTCMonth(date.getUTCMonth() + value)),
2060
- days: (date, value) => new Date(date.setDate(date.getUTCDate() + value))
2061
- };
2062
- return Object.keys(intervals).reduce((acc, interval) => intervalsMapper[interval](acc, intervals[interval]), new Date(date));
2063
- };
2064
- /**
2065
- * @internal
2066
- * A mapper object for rearranging date strings into different formats.
2067
- *
2068
- * @type {Record<TDateFormatsValidation, (value: string) => string>}
2069
- *
2070
- * @example
2071
- * const formattedDate1 = dateRearrangeMapper['DDMMYYYY']('01-12-2023');
2072
- * console.log(formattedDate1); // '12/01/2023'
2073
- *
2074
- * const formattedDate2 = dateRearrangeMapper['YYYYMMDD']('2023-12-01');
2075
- * console.log(formattedDate2); // '12/01/2023'
2076
- */
2077
- const dateRearrangeMapper = {
2078
- DDMMYYYY: value => {
2079
- if (!value) return '';
2080
- const dateParts = value.split(value.includes('/') ? '/' : '-');
2081
- return `${dateParts[1]}/${dateParts[0]}/${dateParts[2]}`;
2082
- },
2083
- YYYYMMDD: value => {
2084
- if (!value) return '';
2085
- const dateParts = value.split(value.includes('/') ? '/' : '-');
2086
- return `${dateParts[1]}/${dateParts[2]}/${dateParts[0]}`;
2087
- },
2088
- YYYYDDMM: value => {
2089
- if (!value) return '';
2090
- const dateParts = value.split(value.includes('/') ? '/' : '-');
2091
- return `${dateParts[2]}/${dateParts[1]}/${dateParts[0]}`;
2092
- },
2093
- MMDDYYYY: value => value,
2094
- timestamp: value => new Date(value).toString()
2095
- };
2096
- /**
2097
- * @function betweenDates
2098
- * Validates if a date value falls between two specified dates.
2099
- *
2100
- * @param {string} value - The date value to be validated in string format.
2101
- * @param {TValidationMethods} validations - The validation methods object containing the betweenDates validation rules.
2102
- * @returns {boolean} - Returns `true` if the date value fails the betweenDates validation, otherwise `false`.
2103
- *
2104
- * @example
2105
- * ```typescript
2106
- * const validations = {
2107
- * betweenDates: [
2108
- * { origin: { value: '2023-01-01', format: 'yyyy-MM-dd' }, operator: '>=' },
2109
- * { origin: { value: '2023-12-31', format: 'yyyy-MM-dd' }, operator: '<=' }
2110
- * ]
2111
- * };
2112
- *
2113
- * const result1 = betweenDates('2023-06-01', validations);
2114
- * console.log(result1); // false (date is within the range)
2115
- *
2116
- * const result2 = betweenDates('2024-01-01', validations);
2117
- * console.log(result2); // true (date is outside the range)
2118
- * ```
2119
- */
2120
- const betweenDates = (value, validations) => {
2121
- var _a;
2122
- let fail = false;
2123
- if (((_a = validations.betweenDates) === null || _a === void 0 ? void 0 : _a.length) != 2) return false;
2124
- for (const validation of validations.betweenDates) {
2125
- if (date(value, {
2126
- date: validation
2127
- })) {
2128
- fail = true;
2129
- break;
2130
- }
2131
- }
2132
- return fail;
2133
- };
2134
- /**
2135
- * @function date
2136
- * Validates a date value based on various date conditions and intervals.
2137
- *
2138
- * @param {string} value - The date value to be validated in string format.
2139
- * @param {TValidationMethods} validations - The validation methods object containing the date validation rules.
2140
- * @returns {boolean} - Returns `true` if the date validation fails, otherwise `false`.
2141
- *
2142
- * @example
2143
- * ```typescript
2144
- * const validations = {
2145
- * date: {
2146
- * origin: {
2147
- * value: '2023-01-01',
2148
- * format: 'YYYY-MM-DD'
2149
- * },
2150
- * target: {
2151
- * value: '2023-12-31',
2152
- * format: 'YYYY-MM-DD'
2153
- * },
2154
- * operator: '<=',
2155
- * onlyValidDate: true
2156
- * }
2157
- * };
2158
- *
2159
- * const result1 = date('2023-06-01', validations);
2160
- * console.log(result1); // false (date is within the range)
2161
- *
2162
- * const result2 = date('2024-01-01', validations);
2163
- * console.log(result2); // true (date is outside the range)
2164
- * ```
2165
- */
2166
- const date = (value, validations) => {
2167
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
2168
- if (!((_b = (_a = validations.date) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value) && !((_d = (_c = validations.date) === null || _c === void 0 ? void 0 : _c.origin) === null || _d === void 0 ? void 0 : _d.intervals)) {
2169
- return false;
2170
- }
2171
- const originValue = validations.date.origin.value || value;
2172
- const mappedValue = dateRearrangeMapper[(_e = validations.date) === null || _e === void 0 ? void 0 : _e.origin.format](originValue).toString();
2173
- let originDate = new Date(mappedValue);
2174
- let targetDate = new Date();
2175
- let target = new Date();
2176
- if ((_g = (_f = validations.date) === null || _f === void 0 ? void 0 : _f.target) === null || _g === void 0 ? void 0 : _g.format) {
2177
- target = new Date(dateRearrangeMapper[(_j = (_h = validations.date) === null || _h === void 0 ? void 0 : _h.target) === null || _j === void 0 ? void 0 : _j.format](validations.date.target.value).toString());
2178
- targetDate = target;
2179
- }
2180
- if (validations.date.origin.intervals) {
2181
- targetDate = getIntervalsDate(originDate, validations.date.origin.intervals);
2182
- const date = new Date();
2183
- if (((_k = validations.date.target) === null || _k === void 0 ? void 0 : _k.value) && target) {
2184
- date.setDate(target.getDate());
2185
- date.setMonth(target.getMonth());
2186
- }
2187
- originDate = new Date(`${date.getUTCMonth() + 1}/${date.getUTCDate()}/${date.getUTCFullYear()}`);
2188
- }
2189
- if (validations.date.onlyValidDate && (!(targetDate instanceof Date && isFinite(targetDate)) || !(targetDate instanceof Date && isFinite(originDate)) || originValue.length < 8)) {
2190
- return true;
2191
- }
2192
- if (invalidStringDate(mappedValue, (_l = validations.date) === null || _l === void 0 ? void 0 : _l.origin.format)) {
2193
- return false;
2194
- }
2195
- const originTimestamp = originDate.getTime();
2196
- const targetTimestamp = targetDate.getTime();
2197
- const operationsMapper = {
2198
- '>': originTimestamp > targetTimestamp,
2199
- '>=': originTimestamp >= targetTimestamp,
2200
- '<': originTimestamp < targetTimestamp,
2201
- '<=': originTimestamp <= targetTimestamp,
2202
- '===': originTimestamp === targetTimestamp,
2203
- '!==': originTimestamp !== targetTimestamp
2204
- };
2205
- return operationsMapper[(_m = validations.date) === null || _m === void 0 ? void 0 : _m.operator];
2206
- };
2207
- /**
2208
- * @function validDate
2209
- * Validates that a date string is a valid date according to the given format.
2210
- *
2211
- * @param {string} value - The date value to be validated in string format.
2212
- * @param {TValidationMethods} validations - The validation methods object containing the validDate rule.
2213
- * @returns {boolean} - Returns `true` if the date is not valid, otherwise `false`.
2214
- *
2215
- * @example
2216
- * ```typescript
2217
- * const validations = { validDate: 'MM-dd-yyyy' };
2218
- *
2219
- * const result1 = validDate('12-31-2023', validations);
2220
- * console.log(result1); // false (date is valid)
2221
- *
2222
- * const result2 = validDate('02-30-2023', validations);
2223
- * console.log(result2); // true (date is invalid)
2224
- * ```
2225
- */
2226
- const validDate = (value, validations) => {
2227
- if (!validations.validDate || !value) return false;
2228
- if (/[^a-zA-Z0-9\s-]/.test(value)) return true;
2229
- const dateParts = dateRearrangeMapper[validations.validDate](value).toString().split(/[/-]/);
2230
- const year = parseInt(dateParts[2], 10);
2231
- const month = parseInt(dateParts[0], 10) - 1; // Month is zero-based
2232
- const day = parseInt(dateParts[1], 10);
2233
- const date = new Date(year, month, day);
2234
- /*
2235
- * Motivation: due to the scenario in which a date field may be 'typeable',
2236
- * we need to ensure that dates less than a thousand and such years are valid.
2237
- * E.g.: user types 13-07-199 (without this condition, it becomes a valid date, as 199 is a valid year)
2238
- *
2239
- * Ps: 150 is a valid value for now, as we still cannot live more than that, from the
2240
- * the moment we start to live longer, we can rethink this.
2241
- */
2242
- const today = new Date();
2243
- today.setFullYear(today.getFullYear() - 150);
2244
- if (date.getFullYear() < today.getFullYear()) {
2245
- return true;
2246
- }
2247
- // Check if the date is valid
2248
- const isValidDate = date.getFullYear() === year && date.getMonth() === month && date.getDate() === day;
2249
- return !isValidDate;
2250
- };
2251
-
2252
- /**
2253
- * @internal
2254
- * Runs a set of validation handlers against a given value.
2255
- *
2256
- * @param {unknown} value - The value to be validated.
2257
- * @param {TValidationMethods} handlers - An object containing validation methods to be applied.
2258
- * @param {TValidationHandler} validations - An object containing every validation methods to be executed.
2259
- * @returns {boolean[]} - An array of boolean results for each validation method.
2260
- *
2261
- * @example
2262
- * const handlers = {
2263
- * max: { max: 10 },
2264
- * required: true,
2265
- * email: true
2266
- * };
2267
- * const results = run('test@example.com', handlers);
2268
- * console.log(results); // [false, false, true] (value fails 'max', passes 'required', passes 'email')
2269
- */
2270
- function run$1(value, handlers, validations) {
2271
- const runner = [];
2272
- Object.keys(handlers).forEach(rule => {
2273
- runner.push(validations[rule](value, {
2274
- [rule]: handlers[rule]
2275
- }));
2276
- });
2277
- return runner;
2278
- }
2279
- /**
2280
- * Validates a given value based on specified validation methods inside a custom named validation.
2281
- *
2282
- * @param {unknown} value - The value to be validated.
2283
- * @param {TValidationMethods} methods - The validation methods to be applied.
2284
- * @param {TValidationHandler} validations - An object containing every validation methods to be executed.
2285
- * @returns {boolean} - Returns true if any of the validation methods pass, otherwise false.
2286
- *
2287
- * @example
2288
- * const value = 'example@example.com';
2289
- * const methods = {
2290
- * required: true,
2291
- * email: true
2292
- * };
2293
- *
2294
- * const isValid = validateValue(value, methods);
2295
- * console.log(isValid); // Output: true
2296
- */
2297
- var namedRule = (value, methods, validations) => {
2298
- if (!methods) return false;
2299
- return run$1(value, methods, validations).some(validation => validation);
2300
- };
2301
-
2302
- /**
2303
- * @internal
2304
- * An object mapping validation keys to their respective validation functions.
2305
- *
2306
- * @type {Record<keyof TAvailableValidations, (value: unknown, validations: TAvailableValidations) => boolean>}
2307
- *
2308
- * @example
2309
- * const isValid = validations.max(5, { max: 10 });
2310
- * console.log(isValid); // false (5 is not greater than 10)
2311
- */
2312
- const validations$1 = {
2313
- max,
2314
- min,
2315
- lessThan,
2316
- greaterThan,
2317
- length,
2318
- regex,
2319
- url,
2320
- email,
2321
- onlyLetters,
2322
- notAllowSpaces,
2323
- callback,
2324
- hasNoExtraSpaces,
2325
- between,
2326
- sequential,
2327
- includes,
2328
- repeated,
2329
- document,
2330
- isCreditCard,
2331
- isCreditCodeMatch,
2332
- isCreditCardAndLength,
2333
- required,
2334
- value,
2335
- notEmpty,
2336
- bool,
2337
- exists,
2338
- isNumber,
2339
- conditions,
2340
- validDate,
2341
- date,
2342
- betweenDates
2343
- };
2344
- /**
2345
- * @internal
2346
- * Runs a set of validation handlers against a given value.
2347
- *
2348
- * @param {unknown} value - The value to be validated.
2349
- * @param {TValidationMethods} handlers - An object containing validation methods to be applied.
2350
- * @returns {boolean[]} - An array of boolean results for each validation method.
2351
- *
2352
- * @example
2353
- * const handlers = {
2354
- * max: { max: 10 },
2355
- * required: true,
2356
- * email: true
2357
- * };
2358
- * const results = run('test@example.com', handlers);
2359
- * console.log(results); // [false, false, true] (value fails 'max', passes 'required', passes 'email')
2360
- */
2361
- function run(value, handlers) {
2362
- const runner = [];
2363
- Object.keys(handlers).forEach(rule => {
2364
- let handler;
2365
- if (isFunction(validations$1[rule])) {
2366
- handler = validations$1[rule](value, {
2367
- [rule]: handlers[rule]
2368
- });
2369
- } else {
2370
- handler = namedRule(value, handlers[rule], validations$1);
2371
- }
2372
- runner.push(handler);
2373
- });
2374
- return runner;
2375
- }
2376
- /**
2377
- * Validates that a value meets multiple validation rules.
2378
- *
2379
- * @param {number | string | boolean} value - The value to be validated.
2380
- * @param {TValidationMethods} methods - The validation methods object containing the multipleValidations rule set.
2381
- * @returns {boolean} - Returns `true` if the value meets the specified multiple validation rules, otherwise `false`.
2382
- *
2383
- * @example
2384
- * ```typescript
2385
- * // Assume validations is an object with a multipleValidations property
2386
- * const validations = {
2387
- * multipleValidations: {
2388
- * rule: 'AND',
2389
- * validations: {
2390
- * required: true,
2391
- * isNumber: true
2392
- * }
2393
- * }
2394
- * };
2395
- *
2396
- * // Returns true because both required and isNumber validations pass
2397
- * const result1 = multipleValidations(123, validations);
2398
- * console.log(result1); // true
2399
- *
2400
- * // Returns false because the value is not a number
2401
- * const result2 = multipleValidations('abc', validations);
2402
- * console.log(result2); // false
2403
- * ```
2404
- */
2405
- const multipleValidations = (value, methods) => {
2406
- if (!methods.multipleValidations) return false;
2407
- const runner = run(value, methods.multipleValidations.validations);
2408
- const rulesMapper = {
2409
- AND: () => runner.every(validation => validation),
2410
- OR: () => runner.some(validation => validation),
2411
- NOT: () => !runner.every(validation => validation)
2412
- };
2413
- return rulesMapper[methods.multipleValidations.rule]();
2414
- };
2415
-
2416
- const validations = {
2417
- max,
2418
- min,
2419
- lessThan,
2420
- greaterThan,
2421
- length,
2422
- regex,
2423
- url,
2424
- email,
2425
- onlyLetters,
2426
- notAllowSpaces,
2427
- callback,
2428
- hasNoExtraSpaces,
2429
- between,
2430
- sequential,
2431
- includes,
2432
- repeated,
2433
- document,
2434
- isCreditCard,
2435
- isCreditCodeMatch,
2436
- isCreditCardAndLength,
2437
- required,
2438
- value,
2439
- notEmpty,
2440
- bool,
2441
- exists,
2442
- isNumber,
2443
- conditions,
2444
- multipleValidations,
2445
- date,
2446
- betweenDates,
2447
- validDate
2448
- };
2449
-
2450
- /**
2451
- * Custom RXJS Subject to gracefully handle errors on unsubscribed Subjects
2452
- * that were unmounted due to adapter external handling such as visibility
2453
- */
2454
- class SafeSubject extends Subject {
2455
- constructor(isMounted) {
2456
- super();
2457
- this.isMounted = isMounted;
2458
- }
2459
- next(value) {
2460
- if (this.isMounted()) {
2461
- super.next(value);
2462
- }
2463
- }
2464
- }
2465
- /**
2466
- * Custom RXJS BehaviourSubject to gracefully handle errors on unsubscribed Subjects
2467
- * since its fire and forget, no mount status needed to check if its available or not
2468
- */
2469
- class SafeBehaviourSubject extends BehaviorSubject {
2470
- constructor(value) {
2471
- super(value);
2472
- this.defaultValue = value;
2473
- }
2474
- next(value) {
2475
- if (!this.closed) {
2476
- super.next(value);
2477
- }
2478
- }
2479
- get value() {
2480
- if (!this.closed) {
2481
- return super.value;
2482
- } else {
2483
- return this.defaultValue;
2484
- }
2485
- }
2486
- }
2487
-
2488
- /**
2489
- * @internal
2490
- * Handles the validation of a given value based on specified validation methods and rules.
2491
- *
2492
- * @param {string | number | boolean | unknown} value - The value to be validated.
2493
- * @param {TSchemaValidation} validations - The schema validations to be applied.
2494
- * @param {TValidationHandler} methods - The validation handler methods.
2495
- * @param {keyof TValidationMethods} key - The specific key of the validation method to be used.
2496
- * @returns {boolean} - Returns true if the value passes the validation, otherwise false.
2497
- *
2498
- * @example
2499
- * const value = 'example@example.com';
2500
- * const validations = {
2501
- * required: true,
2502
- * customName: { email: true }
2503
- * };
2504
- * const methods = {
2505
- * email: (value) => /\S+@\S+\.\S+/.test(value)
2506
- * };
2507
- * const key = 'required';
2508
- *
2509
- * const isValid = handleValidation(value, validations, methods, key);
2510
- * console.log(isValid); // Output: true
2511
- */
2512
- function handleValidation(value, validations, methods, key, formValues) {
2513
- if (isFunction(methods[key])) {
2514
- return methods[key](value, validations, formValues);
2515
- }
2516
- return namedRule(value, validations[key], methods);
2517
- }
2518
-
2519
- /**
2520
- * Represents a form field with observables for managing form state, validations, and API requests.
2521
- */
2522
- class FormField {
2523
- /**
2524
- * Creates an instance of FormField.
2525
- *
2526
- * @param {object} options - Configuration options for the form field.
2527
- * @param {IComponentSchema} options.schemaComponent - The schema definition for the form field.
2528
- * @param {TSchemaFormConfig} options.config - The schema default configuration for debounced actions.
2529
- * @param {string} [options.path] - The path within the form field (used internally during recursion).
2530
- * @param {string[]} options.children - An array of children fields names.
2531
- * @param {Function} options.validateVisibility - A function to validate the visibility of the field.
2532
- * @param {Function} options.resetValue - A function to reset the field value.
2533
- * @param {Function} options.resetProperty - A function to reset a field property.
2534
- * @param {Subject<{ key: string }>} options.templateSubject$ - A subject for template updates.
2535
- * @param {Subject<TFieldEvent>} options.fieldEventSubject$, - Subject for basic event mapped field emissions, except onData to form instance
2536
- * @param {Subject<{ key: string; event: TEvents }>} options.dataSubject$, - Subject to emit onData events to form instance
2537
- * @param {Subject<{ key: string }>} options.formValidNotification$, - Subject to emit field valid change to form instance
2538
- * @param {TMapper<unknown>} options.mapper, - component generic mapper containing render parameters for adapters
2539
- * @param {() => TFormValues<unknown>} options.getFormValues, - form instance function that builds onData parameter payload from fields
2540
- */
2541
- constructor({
2542
- formIndex,
2543
- schemaComponent,
2544
- config,
2545
- children,
2546
- validateVisibility,
2547
- resetValue,
2548
- resetProperty,
2549
- templateSubject$,
2550
- fieldEventSubject$,
2551
- dataSubject$,
2552
- fieldValidNotification$,
2553
- mountSubject$,
2554
- mapper,
2555
- formValuesStateSubject$,
2556
- submitEvent,
2557
- visibility,
2558
- persistValue
2559
- }) {
2560
- var _a, _b, _c, _d, _e, _f;
2561
- this.valueSubscription$ = new Subscription();
2562
- this.fieldStateSubscription$ = new Subscription();
2563
- this.formIndex = formIndex;
2564
- this.originalSchema = cloneDeep(schemaComponent);
2565
- this.config = {
2566
- defaultAPIdebounceTimeMS: Number(config === null || config === void 0 ? void 0 : config.defaultAPIdebounceTimeMS) ? Number(config === null || config === void 0 ? void 0 : config.defaultAPIdebounceTimeMS) : DEFAULT_API_DEBOUNCE_TIME,
2567
- defaultStateRefreshTimeMS: Number(config === null || config === void 0 ? void 0 : config.defaultStateRefreshTimeMS) ? Number(config === null || config === void 0 ? void 0 : config.defaultStateRefreshTimeMS) : DEFAULT_STATE_REFRESH_TIME,
2568
- defaultLogVerbose: (config === null || config === void 0 ? void 0 : config.defaultLogVerbose) ? config.defaultLogVerbose : DEFAULT_LOG_VERBOSE
2569
- };
2570
- this.name = schemaComponent.name;
2571
- this.nameToSubmit = schemaComponent.nameToSubmit;
2572
- this.component = schemaComponent.component;
2573
- this.children = children;
2574
- this.validations = cloneDeep(schemaComponent.validations);
2575
- this.visibilityConditions = cloneDeep(schemaComponent.visibilityConditions);
2576
- this.resetValues = cloneDeep(schemaComponent.resetValues);
2577
- this.resetPropertyValues = cloneDeep(schemaComponent.resetPropertyValues);
2578
- this.apiSchema = cloneDeep(schemaComponent.api);
2579
- this.formatters = cloneDeep(schemaComponent.formatters);
2580
- this.masks = cloneDeep(schemaComponent.masks);
2581
- if (mapper.valueChangeEvent) this.valueChangeEvent = mapper.valueChangeEvent;
2582
- if ((_a = mapper.events) === null || _a === void 0 ? void 0 : _a.setValue) this.valuePropName = mapper.events.setValue;
2583
- this.mapper = mapper;
2584
- this.validateVisibility = validateVisibility;
2585
- this.resetValue = resetValue;
2586
- this.resetProperty = resetProperty;
2587
- this.submitEvent = submitEvent;
2588
- this.templateSubject$ = templateSubject$;
2589
- this.fieldEventSubject$ = fieldEventSubject$;
2590
- this.dataSubject$ = dataSubject$;
2591
- this.fieldValidNotification$ = fieldValidNotification$;
2592
- this.mountSubject$ = mountSubject$;
2593
- this.formValuesStateSubject$ = formValuesStateSubject$;
2594
- this.getFormValues = () => this.formValuesStateSubject$.value;
2595
- this._props = FormField.filterProps(cloneDeep(schemaComponent.props || {}));
2596
- this._adapterProps = JSON.stringify(schemaComponent.props || {});
2597
- this._metadata = '';
2598
- this.errorsString = '';
2599
- this.errorsList = [];
2600
- this._visibility = typeof visibility === 'boolean' ? visibility : true;
2601
- this._api = {
2602
- default: {
2603
- response: ((_d = (_c = (_b = this.apiSchema) === null || _b === void 0 ? void 0 : _b.defaultConfig) === null || _c === void 0 ? void 0 : _c.config) === null || _d === void 0 ? void 0 : _d.fallbackValue) || '',
2604
- status: null
2605
- },
2606
- named: ((_e = this.apiSchema) === null || _e === void 0 ? void 0 : _e.configs) && Object.keys((_f = this.apiSchema) === null || _f === void 0 ? void 0 : _f.configs).reduce((acc, curr) => {
2607
- var _a, _b;
2608
- acc[curr] = {
2609
- response: ((_b = (_a = this.apiSchema) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b[curr].config.fallbackValue) || '',
2610
- status: null
2611
- };
2612
- return acc;
2613
- }, {}),
2614
- apiState: {
2615
- loading: false
2616
- }
2617
- };
2618
- this._errors = {};
2619
- this._mounted = false;
2620
- this.valid = true;
2621
- this.persistValue = persistValue;
2622
- this.initializeObservers();
2623
- }
2624
- /**
2625
- * method to initialize all recycled Subjects and initialize Observers on field instance creation or rerender
2626
- * due to some visibility conditions unmounts the field from the adapter if they are children of it and avoid
2627
- * emissions to unsubscribed fields
2628
- */
2629
- initializeObservers() {
2630
- if (!this.valueSubject$ || this.valueSubject$.closed) {
2631
- this.valueSubject$ = new SafeSubject(() => this.mounted);
2632
- }
2633
- if (!this.errorSubject$ || this.errorSubject$.closed) {
2634
- this.errorSubject$ = new SafeSubject(() => this.mounted);
2635
- }
2636
- if (!this.visibilitySubject$ || this.visibilitySubject$.closed) {
2637
- this.visibilitySubject$ = new SafeSubject(() => this.mounted);
2638
- }
2639
- if (!this.propsSubject$ || this.propsSubject$.closed) {
2640
- this.propsSubject$ = new SafeSubject(() => this.mounted);
2641
- }
2642
- if (!this.fieldStateSubscription$ || this.fieldStateSubscription$.closed) {
2643
- this.fieldStateSubscription$ = new Subscription();
2644
- }
2645
- if (!this.apiEventQueueSubject$ || this.apiEventQueueSubject$.closed) {
2646
- this.apiEventQueueSubject$ = new SafeSubject(() => this.mounted);
2647
- }
2648
- if (!this.apiEventQueueSubject$.observed) {
2649
- this.apiEventQueueSubject$.pipe(groupBy(({
2650
- event
2651
- }) => event), mergeMap(group$ => group$.pipe(debounceTime(this.config.defaultAPIdebounceTimeMS))), filter(() => this.apiEventQueueSubject$ && !this.apiEventQueueSubject$.closed)).subscribe(payload => {
2652
- this.apiRequest(payload);
2653
- });
2654
- }
2655
- }
2656
- /**
2657
- * Retrieves the raw props sent from the adapter.
2658
- *
2659
- * @returns {string} - raw props from the adapter
2660
- */
2661
- get adapterProps() {
2662
- return this._adapterProps;
2663
- }
2664
- /**
2665
- * compares adapter props changes and emits the change if they effectively changed
2666
- * preventing an emission from the adapter of the same props that can overwrite other prop
2667
- * changes via templating
2668
- */
2669
- set adapterProps(props) {
2670
- const currentProps = JSON.stringify(props || {});
2671
- // it's a very basic comparison to determine if props changed,
2672
- // will need review if we need complex comparisons
2673
- if (currentProps !== this.adapterProps) {
2674
- this.props = FormField.filterProps(props);
2675
- this._adapterProps = currentProps;
2676
- }
2677
- }
2678
- /**
2679
- * Retrieves the properties associated with the form field.
2680
- *
2681
- * @returns {Record<string, unknown>} - The properties of the form field.
2682
- */
2683
- get props() {
2684
- return this._props;
2685
- }
2686
- /**
2687
- * Sets the properties of the form field and notifies subscribers about the change.
2688
- *
2689
- * @param {Record<string, unknown>} props - The new properties to be set.
2690
- */
2691
- set props(props) {
2692
- if (typeof props === 'undefined' || isEqual(props, this.props)) return;
2693
- this._props = props;
2694
- this.propsSubject$.next(this.props);
2695
- this.templateSubject$.next({
2696
- scope: 'fields',
2697
- key: this.name,
2698
- event: 'ON_PROPS'
2699
- });
2700
- }
2701
- /**
2702
- * Static function to remove templates form the component props that will be shown when
2703
- * the field mounts and the template routine executes, to be used on the adapter
2704
- *
2705
- * @param {unknown} props - the properties from the adapter components.
2706
- */
2707
- static filterProps(props) {
2708
- if (Array.isArray(props)) {
2709
- return props.filter(el => typeof el === 'string' && el.includes('${') ? false : true).map(el => FormField.filterProps(el));
2710
- }
2711
- if (typeof props === 'object' && props !== null) {
2712
- if (props instanceof Date) return props;
2713
- return Object.keys(props).reduce((acc, curr) => {
2714
- const propValue = props[curr];
2715
- if (typeof propValue === 'string' && propValue.includes('${')) {
2716
- return acc;
2717
- }
2718
- acc[curr] = FormField.filterProps(props[curr]);
2719
- return acc;
2720
- }, {});
2721
- }
2722
- return props;
2723
- }
2724
- /**
2725
- * Retrieves the current state value of the form field.
2726
- *
2727
- * @returns {Record<string,unknown>} - The current state value of the form field.
2728
- */
2729
- get stateValue() {
2730
- return this._stateValue;
2731
- }
2732
- get metadata() {
2733
- return this._metadata;
2734
- }
2735
- /**
2736
- * Retrieves the current value of the form field.
2737
- *
2738
- * @returns {unknown} - The current value of the form field.
2739
- */
2740
- get value() {
2741
- return this._value;
2742
- }
2743
- /**
2744
- * Sets the value of the form field and notifies subscribers about the change.
2745
- *
2746
- * @param {unknown} value - The new value to be set.
2747
- */
2748
- set value(value) {
2749
- var _a, _b, _c;
2750
- /*
2751
- too much unstable, if the valueChangeEvent parses the template event
2752
- value, might occur unexpected results
2753
- */
2754
- let val;
2755
- if (this.valueChangeEvent) {
2756
- try {
2757
- val = this.valueChangeEvent(value, {
2758
- props: this.props
2759
- });
2760
- } catch (e) {
2761
- val = value;
2762
- }
2763
- } else {
2764
- val = value;
2765
- }
2766
- if (typeof val === 'undefined' || val === null) return;
2767
- if (typeof val === 'object' && '_value' in val && '_metadata' in val) {
2768
- this._value = this.formatValue(val['_value']);
2769
- this._stateValue = ((_a = this.mapper.events) === null || _a === void 0 ? void 0 : _a.setValue) ? {
2770
- [this.mapper.events.setValue]: this.maskValue(this.formatValue(val['_value']))
2771
- } : {};
2772
- this._metadata = val._metadata;
2773
- } else {
2774
- this._value = this.formatValue(val);
2775
- this._stateValue = ((_b = this.mapper.events) === null || _b === void 0 ? void 0 : _b.setValue) ? {
2776
- [(_c = this.mapper.events) === null || _c === void 0 ? void 0 : _c.setValue]: this.maskValue(this.formatValue(val))
2777
- } : {};
2778
- this.maskValue(this.formatValue(val));
2779
- this._metadata = val;
2780
- }
2781
- if (this.stateValue) {
2782
- this.valueSubject$.next(this.stateValue);
2783
- }
2784
- this.templateSubject$.next({
2785
- scope: 'fields',
2786
- key: this.name,
2787
- event: 'ON_VALUE'
2788
- });
2789
- }
2790
- /**
2791
- * Retrieves the visibility status of the form field.
2792
- *
2793
- * @returns {boolean} - The visibility status of the form field.
2794
- */
2795
- get visibility() {
2796
- return this._visibility;
2797
- }
2798
- /**
2799
- * Sets the visibility status of the form field and notifies subscribers about the change.
2800
- *
2801
- * @param {boolean} visible - The new visibility status to be set.
2802
- */
2803
- set visibility(visible) {
2804
- if (typeof visible === 'undefined' || visible === this.visibility) return;
2805
- this._visibility = visible;
2806
- this.visibilitySubject$.next(this.visibility);
2807
- this.templateSubject$.next({
2808
- scope: 'fields',
2809
- key: this.name,
2810
- event: 'ON_VISIBILITY'
2811
- });
2812
- }
2813
- /**
2814
- * sets valid field state and notifies form instance via formValidNotification$
2815
- */
2816
- set valid(valid) {
2817
- if (typeof valid !== 'boolean' && this.valid === valid) return;
2818
- this._valid = valid;
2819
- this.triggerFieldValidNotification();
2820
- }
2821
- /**
2822
- * Retrieves the validity status of the form field.
2823
- *
2824
- * @returns {boolean} - The validity status of the form field.
2825
- */
2826
- get valid() {
2827
- return this._valid;
2828
- }
2829
- /**
2830
- * triggers field valid notification to handle the form instance valid notification
2831
- *
2832
- * Note: since form unmount can occur before field unmount, this subject might already be closed by form instance
2833
- * quick workaround is to check if the subject is already closed before emitting
2834
- * if form instance onValid or template form.valid doesn't work properly, might be due to this workaround
2835
- */
2836
- triggerFieldValidNotification() {
2837
- if (!this.fieldValidNotification$.closed) {
2838
- this.fieldValidNotification$.next({
2839
- fieldTrigger: this.name
2840
- });
2841
- }
2842
- }
2843
- /**
2844
- * Retrieves the error messages associated with the form field.
2845
- *
2846
- * @returns {TErrorMessages} - The error messages associated with the form field.
2847
- */
2848
- get errors() {
2849
- return this._errors;
2850
- }
2851
- /**
2852
- * Sets the error messages associated with the form field and notifies subscribers about the change.
2853
- *
2854
- * @param {TErrorMessages} errors - The new error messages to be set.
2855
- */
2856
- set errors(errors) {
2857
- var _a;
2858
- if (typeof errors === 'undefined' || isEqual(errors, this.errors)) return;
2859
- this._errors = errors;
2860
- this.errorsList = Object.values(this.errors).filter(el => el !== undefined && el !== null);
2861
- this.errorsString = this.errorsList.join(', ');
2862
- /**
2863
- * if any error receives a list of errors, set a prop for it, currently only supporting a single string
2864
- */
2865
- if ((_a = this.mapper.events) === null || _a === void 0 ? void 0 : _a.setErrorMessage) {
2866
- this.errorSubject$.next({
2867
- [this.mapper.events.setErrorMessage]: this.errorsString
2868
- });
2869
- }
2870
- this.templateSubject$.next({
2871
- scope: 'fields',
2872
- key: this.name,
2873
- event: 'ON_PROPS'
2874
- });
2875
- }
2876
- /**
2877
- * Retrieves the API response data associated with the form field.
2878
- *
2879
- * @returns {TApiResponse} - The API response data associated with the form field.
2880
- */
2881
- get api() {
2882
- return this._api;
2883
- }
2884
- /**
2885
- * Sets the API response data associated with the form field and notifies subscribers about the change.
2886
- *
2887
- * @param {TApiResponse} response - The new API response data to be set.
2888
- */
2889
- set api(response) {
2890
- if (typeof response === 'undefined') return;
2891
- this._api = response;
2892
- this.templateSubject$.next({
2893
- scope: 'fields',
2894
- key: this.name,
2895
- event: 'ON_API_RESPONSE'
2896
- });
2897
- // this.apiResponseSubject$.next({ key: this.name });
2898
- this.emitEvents({
2899
- event: 'ON_API_FIELD_RESPONSE'
2900
- });
2901
- }
2902
- /**
2903
- * notifies templates and event binded field configurations that a request starts it's processing
2904
- */
2905
- notifyApiRequest() {
2906
- this._api.apiState.loading = true;
2907
- this.templateSubject$.next({
2908
- scope: 'fields',
2909
- key: this.name,
2910
- event: 'ON_API_REQUEST'
2911
- });
2912
- this.emitEvents({
2913
- event: 'ON_API_FIELD_REQUEST'
2914
- });
2915
- }
2916
- /** Retrieves the mounted status of the field.
2917
- *
2918
- * @returns {boolean} - the mounted status of the field.
2919
- */
2920
- get mounted() {
2921
- return this._mounted;
2922
- }
2923
- /**
2924
- * sets the mountedStatus and notifies the form that the field was mounted on the adapter
2925
- * and it's ready to be handled by the form instance
2926
- *
2927
- * @param {boolean} mountedStatus - the mounted status to be set from the mountField function.
2928
- */
2929
- set mounted(mountedStatus) {
2930
- if (typeof mountedStatus === 'undefined' || mountedStatus === this.mounted) return;
2931
- this._mounted = mountedStatus;
2932
- this.initializeObservers();
2933
- if (!this.mountSubject$.closed) this.mountSubject$.next({
2934
- key: this.name,
2935
- status: this.mounted
2936
- });
2937
- }
2938
- /**
2939
- * Mounts the form field by initializing necessary subjects and combining their streams.
2940
- *
2941
- * @param {object} mountOpts - Adapter mount options.
2942
- * @param {(value: unknown) => unknown} prop.valueSubscription - Adapter value change function
2943
- * @param {(payload: Partial<IState>) => unknown} prop.propsSubscription - Adapter prop change function
2944
- * @returns {void}
2945
- */
2946
- mountField({
2947
- valueSubscription,
2948
- propsSubscription
2949
- }) {
2950
- /*
2951
- NOTE: using emitEvents here will make ON_FIELD_MOUNT emit twice
2952
- mount logic is managed on form.ts mountActions on first render
2953
- */
2954
- this.mounted = true;
2955
- this.subscribeValue(valueSubscription);
2956
- this.subscribeState(propsSubscription);
2957
- this.valueSubject$.next(this.stateValue);
2958
- this.propsSubject$.next(this.props);
2959
- this.visibilitySubject$.next(this.visibility);
2960
- this.fieldEventSubject$.next({
2961
- event: 'ON_FIELD_MOUNT',
2962
- fieldName: this.name,
2963
- fieldInstance: this
2964
- });
2965
- }
2966
- /**
2967
- * Sets the value of the form field and emits associated events.
2968
- *
2969
- * @param {unknown} prop.value - The new value to be set.
2970
- * @param {TEvents} prop.event - The event associated with setting the value.
2971
- * @returns {void}
2972
- */
2973
- emitValue(prop) {
2974
- if (!this.visibility || !this.mounted) return;
2975
- this.value = prop.value;
2976
- this.dataSubject$.next({
2977
- event: prop.event,
2978
- fieldIndex: this.name,
2979
- formIndex: this.formIndex
2980
- });
2981
- this.emitEvents({
2982
- event: prop.event
2983
- });
2984
- }
2985
- /**
2986
- * Emits events to trigger field-related actions such as validation, visibility checks, value resets, and API requests.
2987
- *
2988
- * @param {TEvents} event - The event type that triggers the field actions.
2989
- * @returns {void}
2990
- */
2991
- emitEvents({
2992
- event
2993
- }) {
2994
- if (event === 'ON_FORM_SUBMIT') {
2995
- return this.submitEvent();
2996
- }
2997
- this.validateVisibility({
2998
- event,
2999
- key: this.name
3000
- });
3001
- this.setFieldValidity({
3002
- event
3003
- });
3004
- this.resetValue({
3005
- event,
3006
- key: this.name
3007
- });
3008
- this.resetProperty({
3009
- event,
3010
- key: this.name
3011
- });
3012
- this.apiEventQueueSubject$.next({
3013
- event
3014
- });
3015
- this.fieldEventSubject$.next({
3016
- event,
3017
- fieldName: this.name,
3018
- fieldInstance: this
3019
- });
3020
- }
3021
- /**
3022
- * Sets the validity state of the field based on the provided validation rules and triggers error message updates.
3023
- *
3024
- * @param {TEvents} event - The event type associated with the field action.
3025
- * @returns {void}
3026
- */
3027
- setFieldValidity({
3028
- event
3029
- }) {
3030
- var _a, _b, _c, _d;
3031
- if (!this.validations || !this.visibility) {
3032
- this.errors = {};
3033
- this.valid = true;
3034
- return;
3035
- }
3036
- let valid = true;
3037
- const errors = {};
3038
- const schemaValidations = (_a = this.validations) === null || _a === void 0 ? void 0 : _a.methods;
3039
- if (schemaValidations) {
3040
- Object.keys(schemaValidations).forEach(validationKey => {
3041
- var _a, _b;
3042
- const error = handleValidation(this.value, schemaValidations, validations, validationKey, (_a = this.formValuesStateSubject$) === null || _a === void 0 ? void 0 : _a.value);
3043
- // setting valid flag
3044
- valid = !error && valid;
3045
- // setting error messages
3046
- if (error && ((_b = this.validations) === null || _b === void 0 ? void 0 : _b.messages)) {
3047
- if (validationKey in this.validations.messages) {
3048
- const messages = this.validations.messages;
3049
- errors[validationKey] = messages[validationKey];
3050
- } else if ('default' in this.validations.messages) {
3051
- errors[validationKey] = this.validations.messages.default;
3052
- }
3053
- } else {
3054
- delete errors[validationKey];
3055
- }
3056
- });
3057
- }
3058
- this.valid = valid;
3059
- if ((_c = (_b = this.validations) === null || _b === void 0 ? void 0 : _b.eventMessages) === null || _c === void 0 ? void 0 : _c[event]) {
3060
- const eventMessages = {};
3061
- (_d = this.validations.eventMessages[event]) === null || _d === void 0 ? void 0 : _d.forEach(method => {
3062
- if (method in errors) {
3063
- eventMessages[method] = errors[method];
3064
- }
3065
- });
3066
- this.errors = eventMessages;
3067
- } else if (event === 'ON_FIELD_VALIDATION') {
3068
- this.errors = errors;
3069
- }
3070
- }
3071
- /**
3072
- * Formats the field value using the specified formatters, if available.
3073
- *
3074
- * @param {unknown} value - The value to be formatted.
3075
- * @returns {unknown} - The formatted value.
3076
- */
3077
- formatValue(value) {
3078
- if (this.formatters) {
3079
- return Object.keys(this.formatters).reduce((acc, curr) => {
3080
- return formatters[curr](acc, this.formatters);
3081
- }, value);
3082
- }
3083
- return value;
3084
- }
3085
- /**
3086
- * Masks the field value using the specified masks, if available.
3087
- *
3088
- * @param {unknown} value - The value to be masked.
3089
- * @returns {unknown} - The masked value.
3090
- */
3091
- maskValue(value) {
3092
- if (this.masks) {
3093
- return Object.keys(this.masks).reduce((acc, curr) => {
3094
- return masks[curr](acc, this.masks);
3095
- }, value);
3096
- }
3097
- return value;
3098
- }
3099
- checkApiRequestValidations(config) {
3100
- let valid = true;
3101
- const preConditions = config.preConditions;
3102
- if (preConditions) {
3103
- Object.keys(preConditions).forEach(validationKey => {
3104
- var _a;
3105
- const error = handleValidation(this.value, preConditions, validations, validationKey, (_a = this.formValuesStateSubject$) === null || _a === void 0 ? void 0 : _a.value);
3106
- valid = valid && !error;
3107
- });
3108
- }
3109
- if (config.blockRequestWhenInvalid) {
3110
- valid = valid && this.valid;
3111
- }
3112
- return valid;
3113
- }
3114
- /**
3115
- * Makes an API request based on the field's API configuration and event type, updating the field's API response data.
3116
- *
3117
- * @param {TEvents} event - The event type associated with the API request.
3118
- * @returns {Promise<void>}
3119
- */
3120
- apiRequest(_a) {
3121
- return __awaiter(this, arguments, void 0, function* ({
3122
- event
3123
- }) {
3124
- var _b, _c, _d, _e, _f, _g, _h, _j, _k;
3125
- let requestMadeOnce = false;
3126
- const configRequest = config => __awaiter(this, void 0, void 0, function* () {
3127
- var _a, _b;
3128
- try {
3129
- const {
3130
- status,
3131
- response
3132
- } = yield makeRequest(config.method, config.url, config.headers, config.body, config.queryParams);
3133
- const callbackTransform = (_a = config.transform) === null || _a === void 0 ? void 0 : _a.callback;
3134
- const apiResponseData = callbackTransform ? callbackTransform({
3135
- payload: JSON.parse(String(response)),
3136
- formValues: (_b = this.formValuesStateSubject$) === null || _b === void 0 ? void 0 : _b.value
3137
- }) : JSON.parse(String(response));
3138
- const responseReturn = config.resultPath ? get(apiResponseData, config.resultPath) : apiResponseData;
3139
- // this.apiResponseData = { response };
3140
- return {
3141
- response: responseReturn,
3142
- status
3143
- };
3144
- } catch (e) {
3145
- return {
3146
- response: !isNil(config === null || config === void 0 ? void 0 : config.fallbackValue) ? config.fallbackValue : 'error',
3147
- status: 500
3148
- };
3149
- }
3150
- });
3151
- if (this.api.apiState.lastEvent === 'ON_API_FIELD_RESPONSE' && event === 'ON_API_FIELD_RESPONSE' || !((_c = (_b = this.apiSchema) === null || _b === void 0 ? void 0 : _b.defaultConfig) === null || _c === void 0 ? void 0 : _c.events.includes(event)) && !(((_d = this.apiSchema) === null || _d === void 0 ? void 0 : _d.configs) && Object.keys((_e = this.apiSchema) === null || _e === void 0 ? void 0 : _e.configs).some(key => {
3152
- var _a, _b;
3153
- return (_b = (_a = this.apiSchema) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b[key].events.includes(event);
3154
- }))) return;
3155
- const responses = {
3156
- default: Object.assign({}, this.api.default),
3157
- named: Object.assign({}, this.api.named),
3158
- apiState: Object.assign({}, this.api.apiState)
3159
- };
3160
- const config = (_f = this.apiSchema.defaultConfig) === null || _f === void 0 ? void 0 : _f.config;
3161
- if (config && ((_h = (_g = this.apiSchema) === null || _g === void 0 ? void 0 : _g.defaultConfig) === null || _h === void 0 ? void 0 : _h.events.includes(event)) && this.checkApiRequestValidations(config)) {
3162
- if (!requestMadeOnce) {
3163
- this.notifyApiRequest();
3164
- }
3165
- const {
3166
- response,
3167
- status
3168
- } = yield configRequest(config);
3169
- requestMadeOnce = true;
3170
- responses.default = {
3171
- response,
3172
- status
3173
- };
3174
- }
3175
- if (((_j = this.apiSchema) === null || _j === void 0 ? void 0 : _j.configs) && Object.keys((_k = this.apiSchema) === null || _k === void 0 ? void 0 : _k.configs).some(key => {
3176
- var _a, _b;
3177
- return (_b = (_a = this.apiSchema) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b[key].events.includes(event);
3178
- })) {
3179
- if (this.apiSchema.configs) {
3180
- /*
3181
- @TODO handle promises with error
3182
- */
3183
- const result = yield Promise.all(Object.keys(this.apiSchema.configs).map(configKey => __awaiter(this, void 0, void 0, function* () {
3184
- var _a, _b, _c, _d;
3185
- const config = (_b = (_a = this.apiSchema) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b[configKey].config;
3186
- if (config && ((_d = (_c = this.apiSchema) === null || _c === void 0 ? void 0 : _c.configs) === null || _d === void 0 ? void 0 : _d[configKey].events.includes(event)) && this.checkApiRequestValidations(config)) {
3187
- if (!requestMadeOnce) {
3188
- this.notifyApiRequest();
3189
- }
3190
- const {
3191
- response,
3192
- status
3193
- } = yield configRequest(config);
3194
- requestMadeOnce = true;
3195
- return {
3196
- name: configKey,
3197
- result: {
3198
- response,
3199
- status
3200
- }
3201
- };
3202
- }
3203
- return null;
3204
- })));
3205
- result.forEach(payload => {
3206
- if (payload && responses.named) responses.named[payload.name] = payload.result;
3207
- });
3208
- }
3209
- }
3210
- if (requestMadeOnce) {
3211
- responses.apiState.lastEvent = event;
3212
- responses.apiState.loading = false;
3213
- this.api = responses;
3214
- }
3215
- });
3216
- }
3217
- /**
3218
- * Unsubscribes from all subject subscriptions associated with the field, cleaning up resources.
3219
- *
3220
- * @returns {void}
3221
- */
3222
- destroyField() {
3223
- this.mounted = false;
3224
- this.valueSubscription$.unsubscribe();
3225
- this.visibilitySubject$.unsubscribe();
3226
- this.fieldStateSubscription$.unsubscribe();
3227
- this.propsSubject$.unsubscribe();
3228
- this.errorSubject$.unsubscribe();
3229
- this.apiEventQueueSubject$.unsubscribe();
3230
- if (!this.dataSubject$.closed) this.dataSubject$.next({
3231
- event: 'ON_FIELD_UNMOUNT',
3232
- fieldIndex: this.name,
3233
- formIndex: this.formIndex
3234
- });
3235
- if (!this.fieldEventSubject$.closed) this.fieldEventSubject$.next({
3236
- event: 'ON_FIELD_UNMOUNT',
3237
- fieldName: this.name,
3238
- fieldInstance: this
3239
- });
3240
- }
3241
- /**
3242
- * Subscribes to changes in the field state and executes the provided callback function.
3243
- *
3244
- * @param {Function} callback - The callback function to be executed when the field state changes.
3245
- * @returns {void}
3246
- */
3247
- subscribeState(callback) {
3248
- var _a;
3249
- this.fieldStateSubscription$ = combineLatest({
3250
- visibility: this.visibilitySubject$.pipe(startWith(this.visibility)),
3251
- props: this.propsSubject$.pipe(startWith(this.props)),
3252
- errors: this.errorSubject$.pipe(startWith(Object.assign({}, ((_a = this.mapper.events) === null || _a === void 0 ? void 0 : _a.setErrorMessage) && {
3253
- [this.mapper.events.setErrorMessage]: this.errorsString
3254
- })))
3255
- }).pipe(debounceTime(this.config.defaultStateRefreshTimeMS)).subscribe({
3256
- next: callback
3257
- });
3258
- }
3259
- /**
3260
- * Subscribes to changes in the field value and executes the provided callback function.
3261
- *
3262
- * @param {Function} callback - The callback function to be executed when the field value changes.
3263
- * @returns {void}
3264
- */
3265
- subscribeValue(callback) {
3266
- this.valueSubscription$ = this.valueSubject$.subscribe({
3267
- next: callback
3268
- });
3269
- }
3270
- }
3271
-
3272
- /**
3273
- * Represents the core logic for managing a form, including field management, validation, and submission.
3274
- */
3275
- class FormCore {
3276
- /**
3277
- * Creates an instance of FormCore.
3278
- *
3279
- * @param {TFormEntry & Omit<IFormSchema, 'components'>} entry - Configuration options for the form.
3280
- * @param {IFormSchema} entry.schema - The schema definition for the form.
3281
- * @param {Record<string, unknown> | IFormSchema.initialValues} [entry.initialValues] - Initial values for the form fields.
3282
- * @param {string} [entry.action] - The action attribute of the form.
3283
- * @param {string} [entry.method] - The method attribute of the form.
3284
- * @param {IFormSchema.iVars} [entry.iVars] - The internal variables of the form.
3285
- * @param {((payload: {field: string;data: TFormValues;}) => void) | undefined} [entry.onData] - A callback function to handle data emission.
3286
- */
3287
- constructor(entry) {
3288
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3289
- this.templateSubscription$ = new Subscription();
3290
- this.mappers = new Map();
3291
- this.queuedFieldVisibilityEvents = new Map();
3292
- this.queuedFieldResetValuesEvents = new Map();
3293
- this.queuedFieldResetPropertyEvents = new Map();
3294
- this.queuedInitialValues = new Map();
3295
- this._valid = false;
3296
- this.stopEventsOnSubmit = false;
3297
- this.submitted = false;
3298
- this.isolatedFormInstance = false;
3299
- this.index = entry.index;
3300
- this.schema = entry.schema;
3301
- this.fields = new Map();
3302
- this.action = entry.action || ((_a = entry.schema) === null || _a === void 0 ? void 0 : _a.action);
3303
- this.method = entry.method || ((_b = entry.schema) === null || _b === void 0 ? void 0 : _b.method);
3304
- this.config = {
3305
- defaultAPIdebounceTimeMS: Number((_c = entry.config) === null || _c === void 0 ? void 0 : _c.defaultAPIdebounceTimeMS) ? Number((_d = entry.config) === null || _d === void 0 ? void 0 : _d.defaultAPIdebounceTimeMS) : DEFAULT_API_DEBOUNCE_TIME,
3306
- defaultStateRefreshTimeMS: Number((_e = entry.config) === null || _e === void 0 ? void 0 : _e.defaultStateRefreshTimeMS) ? Number((_f = entry.config) === null || _f === void 0 ? void 0 : _f.defaultStateRefreshTimeMS) : DEFAULT_STATE_REFRESH_TIME,
3307
- defaultLogVerbose: ((_g = entry.config) === null || _g === void 0 ? void 0 : _g.defaultLogVerbose) ? entry.config.defaultLogVerbose : DEFAULT_LOG_VERBOSE
3308
- };
3309
- (_h = entry.mappers) === null || _h === void 0 ? void 0 : _h.map(mapper => {
3310
- this.mappers.set(mapper.componentName, mapper);
3311
- });
3312
- if (!entry.submitSubject$ || !entry.dataSubject$ || !entry.formValidSubject$) {
3313
- this.isolatedFormInstance = true;
3314
- if (this.config.defaultLogVerbose) console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`);
3315
- }
3316
- if (this.schema) {
3317
- FormCore.checkIndexes(this.schema.components);
3318
- }
3319
- this.templateSubject$ = new Subject();
3320
- this.fieldEventSubject$ = new Subject();
3321
- this.mountSubject$ = new Subject();
3322
- this.fieldValidNotification$ = new Subject();
3323
- this.submitSubject$ = entry.submitSubject$ ? entry.submitSubject$ : new Subject();
3324
- this.dataSubject$ = entry.dataSubject$ ? entry.dataSubject$ : new Subject();
3325
- this.formValidSubject$ = entry.formValidSubject$ ? entry.formValidSubject$ : new Subject();
3326
- this.formValuesStateSubject$ = new SafeBehaviourSubject({
3327
- erroredFields: [],
3328
- isValid: true,
3329
- metadata: [],
3330
- values: []
3331
- });
3332
- this.getFormValues = () => this.formValuesStateSubject$.value;
3333
- this.subscribedTemplates = [];
3334
- this.templateSubscription$ = this.templateSubject$.subscribe(this.refreshTemplates.bind(this));
3335
- this.fieldValidNotification$.subscribe(() => {
3336
- this.validateForm();
3337
- });
3338
- /*
3339
- @TODO check if this emissions can be merged
3340
- every value update needs to occur after and before validations on field emitValue change
3341
- so both callback validation and onData values are synced and fields and validations are correct
3342
-
3343
- check field.ts emitValue and emitEvents
3344
- */
3345
- this.fieldEventSubject$.subscribe(() => {
3346
- this.formValuesStateSubject$.next(this.getFormState());
3347
- });
3348
- this.dataSubject$.subscribe(() => {
3349
- this.formValuesStateSubject$.next(this.getFormState());
3350
- });
3351
- this.mountSubject$.subscribe(this.mountActions.bind(this));
3352
- this.initialValues = entry.initialValues || ((_j = entry.schema) === null || _j === void 0 ? void 0 : _j.initialValues);
3353
- this.iVars = entry.iVars || ((_k = entry.schema) === null || _k === void 0 ? void 0 : _k.iVars) || {};
3354
- this.stopEventsOnSubmit = (entry === null || entry === void 0 ? void 0 : entry.stopEventsOnSubmit) || false;
3355
- this.submitted = false;
3356
- }
3357
- /**
3358
- * mock function to simulate form mount onto the adapter
3359
- */
3360
- generateFields() {
3361
- if (this.schema) {
3362
- this.serializeStructure(this.schema.components);
3363
- }
3364
- this.fields.forEach(field => {
3365
- field.mountField({
3366
- valueSubscription: () => null,
3367
- propsSubscription: () => null
3368
- });
3369
- });
3370
- }
3371
- /**
3372
- *flag utility to prevent Subjects from emitting after form submission and stopEventsOnSubmit
3373
- * @returns {boolean} - result of the flag utility.
3374
- */
3375
- submitChecker() {
3376
- return !(this.stopEventsOnSubmit && this.submitted);
3377
- }
3378
- /**
3379
- * callback function passed to field instance to notify field adapter mount status
3380
- * once the field has all field instance properties set, this function will handle all
3381
- * field routines
3382
- *
3383
- * @param { string } entry.key field unique identifier
3384
- * @param { boolean } entry.status mount status notified from field
3385
- */
3386
- mountActions({
3387
- key,
3388
- status
3389
- }) {
3390
- if (status) {
3391
- const field = this.fields.get(key);
3392
- if (!field) {
3393
- /*
3394
- @TODO check a better way to handle nested fields unmounted by visiblity conditions from a parent
3395
- since they are dependent on adapter field recycling runtimes
3396
- */
3397
- if (this.config.defaultLogVerbose) console.warn(`field ${key} was mounted but since it's parent has some visibility condition the field was already removed`);
3398
- return;
3399
- }
3400
- this.subscribeTemplates();
3401
- this.refreshTemplates({
3402
- scope: 'fields',
3403
- event: 'ON_FIELDS'
3404
- });
3405
- this.templateSubject$.next({
3406
- scope: 'iVars',
3407
- event: 'ON_IVARS'
3408
- });
3409
- if (!this.queuedInitialValues.has(key)) if (field.valuePropName && !field.value) {
3410
- field.emitValue({
3411
- event: 'ON_FIELD_MOUNT',
3412
- value: ''
3413
- });
3414
- } else {
3415
- field.emitEvents({
3416
- event: 'ON_FIELD_MOUNT'
3417
- });
3418
- }
3419
- this.checkFieldEventQueues(key);
3420
- }
3421
- }
3422
- /**
3423
- * initialValues setter to handle field values set externally from the adapter
3424
- *
3425
- * @param { Record<string, unknown> | undefined } payload initialValues to set onto fields
3426
- */
3427
- set initialValues(payload) {
3428
- if (payload) {
3429
- Object.keys(payload).forEach(key => {
3430
- const field = this.fields.get(key);
3431
- if (!field || !(field === null || field === void 0 ? void 0 : field.visibility) || !(field === null || field === void 0 ? void 0 : field.mounted)) {
3432
- this.queuedInitialValues.set(key, payload === null || payload === void 0 ? void 0 : payload[key]);
3433
- } else {
3434
- field.emitValue({
3435
- value: payload === null || payload === void 0 ? void 0 : payload[key],
3436
- event: 'ON_FIELD_MOUNT'
3437
- });
3438
- }
3439
- });
3440
- }
3441
- }
3442
- /**
3443
- * Retrieves the internal variables (iVars) of the form.
3444
- *
3445
- * @returns {Record<string, unknown>} - The internal variables of the form.
3446
- */
3447
- get iVars() {
3448
- return this._iVars;
3449
- }
3450
- /**
3451
- * Sets the internal variables (iVars) of the form and notifies subscribers about the change.
3452
- *
3453
- * @param {Record<string, unknown>} payload - The new internal variables to be set.
3454
- */
3455
- set iVars(payload) {
3456
- this._iVars = payload;
3457
- this.templateSubject$.next({
3458
- scope: 'iVars',
3459
- event: 'ON_IVARS'
3460
- });
3461
- }
3462
- /**
3463
- * Validates all form fields and sets the form valid flag
3464
- *
3465
- */
3466
- validateForm() {
3467
- if (this.fields.size === 0) return this.valid = false;
3468
- for (const [, field] of this.fields) {
3469
- if (!field.valid) return this.valid = false;
3470
- }
3471
- return this.valid = true;
3472
- }
3473
- get valid() {
3474
- return this._valid;
3475
- }
3476
- set valid(valid) {
3477
- if (this._valid === valid) return;
3478
- this._valid = valid;
3479
- this.templateSubject$.next({
3480
- event: 'ON_FORM',
3481
- scope: 'form'
3482
- });
3483
- this.formValidSubject$.next({
3484
- formIndex: this.index,
3485
- valid: this.valid
3486
- });
3487
- }
3488
- /**
3489
- * Subscribes to templates for dynamic updates.
3490
- */
3491
- subscribeTemplates() {
3492
- this.subscribedTemplates = [];
3493
- this.fields.forEach(({
3494
- originalSchema: {
3495
- component,
3496
- props,
3497
- name,
3498
- validations,
3499
- visibilityConditions,
3500
- resetValues,
3501
- resetPropertyValues,
3502
- api
3503
- }
3504
- }, key) => {
3505
- const template = {
3506
- component,
3507
- props,
3508
- name,
3509
- validations,
3510
- visibilityConditions,
3511
- resetValues,
3512
- resetPropertyValues,
3513
- apiSchema: api
3514
- };
3515
- traverseObject(template, key).forEach(element => this.subscribedTemplates.push(element));
3516
- });
3517
- }
3518
- /**
3519
- * Gets the value of a property from a field.
3520
- *
3521
- * @param {object} options - Options for getting the value.
3522
- * @param {string} options.key - The key of the field.
3523
- * @param {string} options.property - The property to retrieve.
3524
- * @param {string[]} options.path - The path to the property if it's nested.
3525
- * @returns {unknown | undefined} The value of the property, or undefined if the field doesn't exist.
3526
- */
3527
- getValue({
3528
- scope,
3529
- key,
3530
- property,
3531
- path
3532
- }) {
3533
- switch (scope) {
3534
- case 'iVars':
3535
- {
3536
- const value = get(this.iVars, [key, ...(property ? [property] : []), ...path]);
3537
- return value;
3538
- }
3539
- case 'form':
3540
- {
3541
- const value = get(this, [key, ...(property ? [property] : []), ...path]);
3542
- return value;
3543
- }
3544
- case 'fields':
3545
- {
3546
- const field = this.fields.get(key);
3547
- if (!field) return this.config.defaultLogVerbose && console.warn(`failed to get value from ${key}`);
3548
- if (property === 'props' && path[0] === field.valuePropName) {
3549
- return field.value;
3550
- }
3551
- return path.length > 0 ? get(field[property], path) : field[property];
3552
- }
3553
- }
3554
- }
3555
- /**
3556
- * Sets the value of a property in a field.
3557
- *
3558
- * @param {object} options - Options for setting the value.
3559
- * @param {string} options.key - The key of the field.
3560
- * @param {string} options.property - The property to set.
3561
- * @param {string[]} options.path - The path to the property if it's nested.
3562
- * @param {unknown} options.originKey - field that called templating
3563
- * @param {unknown} options.value - The value to set.
3564
- * @param {TMutationEvents} options.event - Internal Event for template Handling.
3565
- */
3566
- setValue({
3567
- key,
3568
- property,
3569
- path,
3570
- originKey,
3571
- value
3572
- }) {
3573
- const field = this.fields.get(key);
3574
- if (!field) {
3575
- if (this.config.defaultLogVerbose) console.warn(`failed to update field ${key}`);
3576
- return;
3577
- }
3578
- if (path.length > 0) {
3579
- /*
3580
- property value is only allowed to be templated if the value isn't
3581
- changed by itself, else a black hole opens
3582
- previously using event !== 'ON_VALUE' on the condition
3583
- now using key !== originKey, check if any recursion error occurs
3584
- **/
3585
- if (property === 'props' && path[0] === field.valuePropName && key !== originKey) {
3586
- field.emitValue({
3587
- event: 'ON_FIELD_CHANGE',
3588
- value
3589
- });
3590
- return;
3591
- }
3592
- const fieldProp = field[property];
3593
- let propState;
3594
- if (Array.isArray(fieldProp) || typeof fieldProp === 'object' && !isNil(fieldProp)) {
3595
- propState = cloneDeep(fieldProp);
3596
- } else {
3597
- if (this.config.defaultLogVerbose) console.warn(`invalid template property, skipping evaluation of ${field.name} with ${fieldProp}`);
3598
- return;
3599
- }
3600
- set(propState, path, value);
3601
- field[property] = propState;
3602
- return;
3603
- }
3604
- field[property] = value;
3605
- return;
3606
- }
3607
- /**
3608
- * Extracts parameters from an expression.
3609
- *
3610
- * @param {string} expression - The expression containing parameters.
3611
- * @returns {string[]} An array of extracted parameters.
3612
- */
3613
- extractParams(expression) {
3614
- const getTemplateValue = function getTemplvalue(pathOrValue) {
3615
- const element = pathOrValue.split('.');
3616
- return element.length > 1 ? this.getValue({
3617
- scope: element[0],
3618
- key: element[1],
3619
- property: element[2],
3620
- path: element.slice(3)
3621
- }) : element[0];
3622
- }.bind(this);
3623
- const extractedValues = [];
3624
- let match;
3625
- while (!isNil(match = TEMPLATE_REGEX_DELIMITATOR.exec(expression))) {
3626
- extractedValues.push(match[1]);
3627
- }
3628
- const splittedString = extractedValues.map(el => el.split(TEMPLATE_REGEX_OPERATOR_SPLITTER));
3629
- const result = splittedString.map(splittedStringVal => {
3630
- // skip operator logic parsing and pass element directly
3631
- if (splittedStringVal.length <= 1) {
3632
- return {
3633
- parse: false,
3634
- value: getTemplateValue(splittedStringVal[0])
3635
- };
3636
- }
3637
- const value = splittedStringVal.filter(Boolean).reduce((acc, curr) => {
3638
- if (curr.match(TEMPLATE_REGEX_OPERATOR_MATCHER)) {
3639
- return `${acc}${curr}`;
3640
- }
3641
- let value;
3642
- const currElementContent = getTemplateValue(curr);
3643
- let currValue;
3644
- // if any parsable content was passed to the conditions, parse them
3645
- // required to be able to apply conditions
3646
- try {
3647
- currValue = JSON.parse(currElementContent);
3648
- } catch (e) {
3649
- currValue = currElementContent;
3650
- }
3651
- switch (typeof currValue) {
3652
- case 'string':
3653
- value = `\`${currValue}\``;
3654
- break;
3655
- case 'boolean':
3656
- case 'undefined':
3657
- case 'number':
3658
- value = currValue;
3659
- break;
3660
- case 'object':
3661
- if (currValue === null) {
3662
- value = null;
3663
- break;
3664
- }
3665
- if (currValue instanceof Date) {
3666
- value = `new Date(\`${currValue}\`)`;
3667
- break;
3668
- }
3669
- value = JSON.stringify(currValue);
3670
- break;
3671
- default:
3672
- value = currValue;
3673
- }
3674
- return `${acc}${value}`;
3675
- }, '');
3676
- return {
3677
- parse: true,
3678
- value
3679
- };
3680
- });
3681
- return result.map(({
3682
- parse,
3683
- value
3684
- }) => {
3685
- try {
3686
- return parse ? new Function(`return ${value}`)() : value;
3687
- } catch (_a) {
3688
- if (this.config.defaultLogVerbose) {
3689
- console.warn(`unhandled parsing on ${expression} returning`);
3690
- console.warn(value);
3691
- }
3692
- return value;
3693
- }
3694
- });
3695
- }
3696
- /**
3697
- * Replaces expressions marked by ${...} in the expression string with the provided values.
3698
- *
3699
- * @param {string} expression - The expression string containing the marked expressions.
3700
- * @param {string[]} values - The values to be inserted into the marked expressions.
3701
- * @returns {string} The expression string with the replacements made.
3702
- */
3703
- replaceExpression(expression, values) {
3704
- const regex = TEMPLATE_REGEX_DELIMITATOR;
3705
- return expression.replace(regex, () => String(values.shift()) || '');
3706
- }
3707
- /**
3708
- * Checks if an expression string contains string concatenation within a marked expression.
3709
- *
3710
- * @param {string} expression - The expression string to be checked.
3711
- * @returns {boolean} True if the expression contains string concatenation, otherwise false.
3712
- */
3713
- hasStringConcatenation(expression) {
3714
- return !TEMPLATE_REGEX_STRING_CONCATENATION_DETECTOR.test(expression);
3715
- }
3716
- /**
3717
- * Refreshes templates with updated values.
3718
- *
3719
- * @param {object} options - Options for refreshing templates.
3720
- * @param {string} options.key - The key of the field triggering the update.
3721
- * @param {TMutationEvents} options.event - Internal event descriptor to handle templating.
3722
- */
3723
- refreshTemplates({
3724
- key,
3725
- event
3726
- }) {
3727
- this.subscribedTemplates.forEach(({
3728
- destinationKey,
3729
- destinationPath,
3730
- destinationProperty,
3731
- originExpression,
3732
- originFieldKeys
3733
- }) => {
3734
- if (!key || originFieldKeys.includes(key)) {
3735
- const originExpressions = this.extractParams(originExpression);
3736
- let originValue;
3737
- if (this.hasStringConcatenation(originExpression)) {
3738
- originValue = this.replaceExpression(originExpression, [...originExpressions]);
3739
- } else {
3740
- originValue = originExpressions === null || originExpressions === void 0 ? void 0 : originExpressions[0];
3741
- }
3742
- const destinationValue = this.getValue({
3743
- scope: 'fields',
3744
- key: destinationKey,
3745
- property: destinationProperty,
3746
- path: destinationPath
3747
- });
3748
- if (!isEqual(destinationValue, originValue)) {
3749
- this.setValue({
3750
- key: destinationKey,
3751
- property: destinationProperty,
3752
- path: destinationPath,
3753
- originKey: key,
3754
- value: originValue,
3755
- event
3756
- });
3757
- }
3758
- }
3759
- });
3760
- }
3761
- /**
3762
- * executes events that were stored due to field unavaliability
3763
- *
3764
- * @param {string} field field to check
3765
- */
3766
- checkFieldEventQueues(field) {
3767
- var _a;
3768
- if (!((_a = this.fields.get(field)) === null || _a === void 0 ? void 0 : _a.mounted)) return;
3769
- if (this.queuedFieldVisibilityEvents.has(field)) {
3770
- this.setFieldVisibility(Object.assign({
3771
- field: field
3772
- }, this.queuedFieldVisibilityEvents.get(field)));
3773
- this.queuedFieldVisibilityEvents.delete(field);
3774
- }
3775
- if (this.queuedInitialValues.has(field)) {
3776
- const value = this.queuedInitialValues.get(field);
3777
- this.queuedInitialValues.delete(field);
3778
- this.initialValues = {
3779
- [field]: value
3780
- };
3781
- }
3782
- if (this.queuedFieldResetValuesEvents.has(field)) {
3783
- this.setResetFieldValue(Object.assign({
3784
- key: field
3785
- }, this.queuedFieldResetValuesEvents.get(field)));
3786
- this.queuedFieldResetValuesEvents.delete(field);
3787
- }
3788
- if (this.queuedFieldResetPropertyEvents.has(field)) {
3789
- this.setResetPathValue(Object.assign({
3790
- key: field
3791
- }, this.queuedFieldResetPropertyEvents.get(field)));
3792
- this.queuedFieldResetPropertyEvents.delete(field);
3793
- }
3794
- }
3795
- /**
3796
- * @internal
3797
- * Update field visibility accordingly.
3798
- *
3799
- * @param {object} options - options to set field visibility
3800
- * @param {string} options.field - Field name to be updated.
3801
- * @param {boolean} options.hasError - Condition to be used as visibility.
3802
- * @param {boolean|undefined} options.showOnlyIfTrue - Flag to be considered when update field visibility. If it's true, then considered error, if it's false, always considered the opposite.
3803
- */
3804
- setFieldVisibility({
3805
- field,
3806
- hasError,
3807
- showOnlyIfTrue
3808
- }) {
3809
- const fieldInstance = this.fields.get(field);
3810
- if (!fieldInstance || !fieldInstance.mounted) {
3811
- this.queuedFieldVisibilityEvents.set(field, {
3812
- hasError,
3813
- showOnlyIfTrue
3814
- });
3815
- } else {
3816
- const currentVisibility = fieldInstance.visibility;
3817
- const visibility = showOnlyIfTrue ? hasError : !hasError;
3818
- fieldInstance.visibility = visibility;
3819
- if (currentVisibility === visibility) return;
3820
- /**
3821
- * I was sure I would not require to gambiarra, but..
3822
- * in order to ignore an hidden value on a form submit
3823
- * or revalidate it when it comes back to visibility
3824
- * I needed to...
3825
- * I don't recommend setting private properties like this
3826
- * this will force the field to be valid when it's hidden
3827
- * and trigger the validation when it's visible
3828
- */
3829
- if (fieldInstance.visibility) {
3830
- if (this.queuedInitialValues.has(field)) {
3831
- fieldInstance === null || fieldInstance === void 0 ? void 0 : fieldInstance.emitValue({
3832
- value: this.queuedInitialValues.get(field) || '',
3833
- event: 'ON_FIELD_MOUNT'
3834
- });
3835
- this.queuedInitialValues.delete(field);
3836
- } else {
3837
- fieldInstance.emitEvents({
3838
- event: 'ON_FIELD_MOUNT'
3839
- });
3840
- }
3841
- } else {
3842
- fieldInstance.emitEvents({
3843
- event: 'ON_FIELD_UNMOUNT'
3844
- });
3845
- if (fieldInstance.persistValue) {
3846
- this.queuedInitialValues.set(fieldInstance.name, fieldInstance.value);
3847
- }
3848
- fieldInstance.value = '';
3849
- fieldInstance.valid = true;
3850
- }
3851
- }
3852
- }
3853
- /**
3854
- * Validates visibility conditions for a given event and updates field visibility accordingly.
3855
- *
3856
- * @param {object} options - Options for validating visibility.
3857
- * @param {TEvents} options.event - The event triggering visibility validation.
3858
- * @param {string} options.key - The key of the field.
3859
- */
3860
- validateVisibility({
3861
- event,
3862
- key
3863
- }) {
3864
- const field = this.fields.get(key);
3865
- const structVisibility = field === null || field === void 0 ? void 0 : field.visibilityConditions;
3866
- if (!structVisibility || !(structVisibility === null || structVisibility === void 0 ? void 0 : structVisibility.some(config => config.events.includes(event)))) {
3867
- return;
3868
- }
3869
- structVisibility.forEach(structElement => {
3870
- if (!structElement.events.includes(event)) return;
3871
- Object.keys(structElement.validations).forEach(validationKey => {
3872
- const error = handleValidation(field.value, structElement.validations, validations, validationKey, this.formValuesStateSubject$.value);
3873
- if (Array.isArray(structElement.fields)) {
3874
- structElement.fields.forEach(fieldKey => {
3875
- this.setFieldVisibility({
3876
- field: fieldKey,
3877
- hasError: error,
3878
- showOnlyIfTrue: !!(field.value && structElement.showOnlyIfTrue)
3879
- });
3880
- });
3881
- } else if (structElement.fields) {
3882
- this.setFieldVisibility({
3883
- field: structElement.fields,
3884
- hasError: error,
3885
- showOnlyIfTrue: !!(field.value && structElement.showOnlyIfTrue)
3886
- });
3887
- }
3888
- });
3889
- });
3890
- }
3891
- /**
3892
- * @internal
3893
- * Update field value and emit change and cleared event.
3894
- *
3895
- * @param {options} options to reset the field value
3896
- * @param {string} options.key - Field name to be updated.
3897
- * @param {unknown} options.value - Value to be inserted into field.
3898
- */
3899
- setResetFieldValue({
3900
- key,
3901
- value
3902
- }) {
3903
- const field = this.fields.get(key);
3904
- if (!field || !(field === null || field === void 0 ? void 0 : field.mounted)) {
3905
- this.queuedFieldResetValuesEvents.set(key, {
3906
- value
3907
- });
3908
- } else {
3909
- field.emitValue({
3910
- value: value,
3911
- event: 'ON_FIELD_CLEARED'
3912
- });
3913
- }
3914
- }
3915
- /**
3916
- * Resets field values based on reset conditions defined in the schema.
3917
- *
3918
- * @param {object} options - Options for resetting field values.
3919
- * @param {TEvents} options.event - The event triggering the reset.
3920
- * @param {string} options.key - The key of the field.
3921
- */
3922
- resetValue({
3923
- event,
3924
- key
3925
- }) {
3926
- const field = this.fields.get(key);
3927
- const structResetValue = field === null || field === void 0 ? void 0 : field.resetValues;
3928
- if (!structResetValue || !(structResetValue === null || structResetValue === void 0 ? void 0 : structResetValue.some(config => config.events.includes(event)))) return;
3929
- structResetValue.forEach(structElement => {
3930
- if (!structElement.events.includes(event)) return;
3931
- const handleFieldRestoration = () => {
3932
- if (Array.isArray(structElement.fields)) {
3933
- structElement.fields.forEach((fieldKey, index) => {
3934
- const resettledValue = Array.isArray(structElement.resettledValue) ? structElement.resettledValue[index] : structElement.resettledValue;
3935
- this.setResetFieldValue({
3936
- key: fieldKey,
3937
- value: resettledValue
3938
- });
3939
- });
3940
- } else if (structElement.fields) {
3941
- this.setResetFieldValue({
3942
- key: structElement.fields,
3943
- value: structElement.resettledValue
3944
- });
3945
- }
3946
- };
3947
- if (!structElement.validations) {
3948
- return handleFieldRestoration();
3949
- }
3950
- Object.keys(structElement.validations).forEach(validationKey => {
3951
- const error = handleValidation(field.value, structElement.validations, validations, validationKey, this.formValuesStateSubject$.value);
3952
- if (!error) {
3953
- handleFieldRestoration();
3954
- }
3955
- });
3956
- });
3957
- }
3958
- /**
3959
- * @internal
3960
- * Update field property and emit template change.
3961
- *
3962
- * @param {object} options - Options for resetting field property
3963
- * @param {string} options.key - Field name to be updated.
3964
- * @param {string} options.property - field property to change.
3965
- * @param {string} options.path - field property path to change.
3966
- * @param {unknown} options.value - Value to be inserted into field.
3967
- */
3968
- setResetPathValue({
3969
- key,
3970
- property,
3971
- path,
3972
- value
3973
- }) {
3974
- const field = this.fields.get(key);
3975
- if (!field) {
3976
- this.queuedFieldResetPropertyEvents.set(key, {
3977
- property,
3978
- path,
3979
- value
3980
- });
3981
- } else {
3982
- this.setValue({
3983
- key,
3984
- property,
3985
- path: path.split('.'),
3986
- value: value,
3987
- event: 'ON_RESET'
3988
- });
3989
- }
3990
- }
3991
- /**
3992
- * Resets field properties based on reset conditions defined in the schema.
3993
- *
3994
- * @param {object} options - Options for resetting field property.
3995
- * @param {TEvents} options.event - The event triggering the reset.
3996
- * @param {string} options.key - The key of the field.
3997
- */
3998
- resetProperty({
3999
- event,
4000
- key
4001
- }) {
4002
- const field = this.fields.get(key);
4003
- const structResetPath = field === null || field === void 0 ? void 0 : field.resetPropertyValues;
4004
- if (!structResetPath || !(structResetPath === null || structResetPath === void 0 ? void 0 : structResetPath.some(config => config.events.includes(event)))) return;
4005
- structResetPath.forEach(structElement => {
4006
- if (!structElement.events.includes(event)) return;
4007
- if (!ALLOWED_RESET_PROPS_MUTATIONS.includes(structElement.property)) return;
4008
- if (!structElement.validations) {
4009
- return this.setResetPathValue({
4010
- key: structElement.field,
4011
- path: structElement.path,
4012
- property: structElement.property,
4013
- value: structElement.resettledValue
4014
- });
4015
- }
4016
- Object.keys(structElement.validations).forEach(validationKey => {
4017
- const error = handleValidation(field.value, structElement.validations, validations, validationKey, this.formValuesStateSubject$.value);
4018
- if (!error) {
4019
- this.setResetPathValue({
4020
- key: structElement.field,
4021
- path: structElement.path,
4022
- property: structElement.property,
4023
- value: structElement.resettledValue
4024
- });
4025
- }
4026
- });
4027
- });
4028
- }
4029
- /**
4030
- * Adds a field onto the form instance regardless there is a schema or not
4031
- *
4032
- * @param fieldSchema
4033
- * @param mapperElement
4034
- */
4035
- addField({
4036
- fieldSchema,
4037
- mapperElement,
4038
- path
4039
- }) {
4040
- var _a, _b, _c, _d;
4041
- if (this.fields.has(fieldSchema.name)) {
4042
- throw new Error(`field name ${fieldSchema.name} already defined`);
4043
- }
4044
- const mapper = mapperElement || ((_a = this.mappers) === null || _a === void 0 ? void 0 : _a.get(fieldSchema.component));
4045
- if (!mapper) throw new Error(`mapper not found for ${fieldSchema.component}, add it to the mappers configuration`);
4046
- if ((_b = mapper.events) === null || _b === void 0 ? void 0 : _b.setValue) {
4047
- const initialValue = (_c = fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.props) === null || _c === void 0 ? void 0 : _c[(_d = mapper === null || mapper === void 0 ? void 0 : mapper.events) === null || _d === void 0 ? void 0 : _d.setValue];
4048
- if (!(typeof initialValue === 'undefined') && !this.queuedInitialValues.has(fieldSchema.name) && !(typeof initialValue === 'string' && initialValue.includes('${'))) {
4049
- this.queuedInitialValues.set(fieldSchema.name, cloneDeep(initialValue));
4050
- }
4051
- }
4052
- this.fields.set(fieldSchema.name, new FormField({
4053
- formIndex: this.index,
4054
- schemaComponent: fieldSchema,
4055
- mapper,
4056
- children: fieldSchema.children ? fieldSchema.children.map(el => el.name) : [],
4057
- validateVisibility: this.validateVisibility.bind(this),
4058
- resetValue: this.resetValue.bind(this),
4059
- resetProperty: this.resetProperty.bind(this),
4060
- formValuesStateSubject$: this.formValuesStateSubject$,
4061
- templateSubject$: this.templateSubject$,
4062
- fieldEventSubject$: this.fieldEventSubject$,
4063
- dataSubject$: this.dataSubject$,
4064
- fieldValidNotification$: this.fieldValidNotification$,
4065
- mountSubject$: this.mountSubject$,
4066
- config: this.config,
4067
- submitEvent: this.submit.bind(this),
4068
- visibility: fieldSchema.visibility,
4069
- persistValue: fieldSchema.persistValue,
4070
- path
4071
- }));
4072
- }
4073
- /**
4074
- * function to be called from the adapter to remove a field when a field is removed from it
4075
- *
4076
- * @param {{ key: string }} entry.key
4077
- */
4078
- removeField({
4079
- key
4080
- }) {
4081
- var _a;
4082
- (_a = this.fields.get(key)) === null || _a === void 0 ? void 0 : _a.destroyField();
4083
- this.fields.delete(key);
4084
- this.subscribeTemplates();
4085
- this.templateSubject$.next({
4086
- scope: 'fields',
4087
- key,
4088
- event: 'ON_FIELDS'
4089
- });
4090
- this.validateForm();
4091
- }
4092
- /**
4093
- * Serializes the schema structure to create form fields.
4094
- *
4095
- * @param {IComponentSchema[]} [struct] - The schema structure to serialize.
4096
- * @param {string} [path] - The path of the parent component.
4097
- */
4098
- serializeStructure(struct, path) {
4099
- if (!struct) return;
4100
- struct.forEach(structElement => {
4101
- var _a;
4102
- const currField = this.fields.get(structElement.name);
4103
- if (!currField) {
4104
- this.addField({
4105
- fieldSchema: structElement,
4106
- mapperElement: structElement.mapper,
4107
- path
4108
- });
4109
- } else {
4110
- currField.children = ((_a = structElement === null || structElement === void 0 ? void 0 : structElement.children) === null || _a === void 0 ? void 0 : _a.map(el => el.name)) || (currField === null || currField === void 0 ? void 0 : currField.children) || [];
4111
- currField.originalSchema = structElement;
4112
- currField.templateSubject$ = this.templateSubject$;
4113
- }
4114
- if (structElement.children) {
4115
- this.serializeStructure(structElement.children, `${path ? `${path}.` : ``}${structElement.name}`);
4116
- }
4117
- });
4118
- }
4119
- /**
4120
- * Refreshes form fields based on changes in the schema structure.
4121
- *
4122
- * @param {IComponentSchema[]} struct - The updated schema structure.
4123
- */
4124
- refreshFields(struct) {
4125
- const prevKeys = Array.from(this.fields.keys());
4126
- this.serializeStructure(struct);
4127
- const keys = FormCore.checkIndexes(struct);
4128
- this.fields.forEach((_, key) => {
4129
- var _a;
4130
- if (!keys.includes(key)) {
4131
- (_a = this.fields.get(key)) === null || _a === void 0 ? void 0 : _a.destroyField();
4132
- this.fields.delete(key);
4133
- }
4134
- });
4135
- this.subscribeTemplates();
4136
- this.fields.forEach((_, key) => {
4137
- var _a;
4138
- if (!prevKeys.includes(key)) {
4139
- (_a = this.fields.get(key)) === null || _a === void 0 ? void 0 : _a.emitEvents({
4140
- event: 'ON_FIELD_MOUNT'
4141
- });
4142
- this.checkFieldEventQueues(key);
4143
- }
4144
- });
4145
- this.subscribedTemplates.forEach(el => {
4146
- el.originFieldKeys.forEach(field => {
4147
- this.templateSubject$.next({
4148
- scope: 'fields',
4149
- key: field,
4150
- event: 'ON_FIELDS'
4151
- });
4152
- });
4153
- });
4154
- }
4155
- /**
4156
- * Gets a form field by its key.
4157
- *
4158
- * @param {object} options - Options for getting the form field.
4159
- * @param {string} options.key - The key of the form field.
4160
- * @returns {IFormField | undefined} The form field, or undefined if not found.
4161
- */
4162
- getField({
4163
- key
4164
- }) {
4165
- return this.fields.get(key);
4166
- }
4167
- /**
4168
- * Prints the current values of all form fields.
4169
- */
4170
- printValues() {
4171
- console.table(this.formValuesStateSubject$.value.values);
4172
- }
4173
- /**
4174
- * Gets the current values of all form fields.
4175
- *
4176
- * @returns {TFormValues} The current form values.
4177
- */
4178
- getFormState() {
4179
- const values = {};
4180
- const metadata = {};
4181
- const erroredFields = [];
4182
- this.fields.forEach((val, key) => {
4183
- if (!(typeof val.value === 'string' && val.value.length === 0) && typeof val.value !== 'undefined' && val.value !== null) {
4184
- set(values, val.nameToSubmit || key, val.value);
4185
- metadata[key] = val.metadata;
4186
- }
4187
- if (!val.valid) {
4188
- erroredFields.push(key);
4189
- }
4190
- });
4191
- return {
4192
- values,
4193
- metadata,
4194
- erroredFields,
4195
- isValid: this.valid
4196
- };
4197
- }
4198
- /**
4199
- * function to be called to events sent from the adapter
4200
- *
4201
- * @param {{callback: (payload: TFieldEvent) => void}} entry.callback callback function from the adapter
4202
- * @returns
4203
- */
4204
- subscribeFieldEvent({
4205
- callback
4206
- }) {
4207
- const sub = this.fieldEventSubject$.pipe(filter(() => this.submitChecker()), groupBy(payload => `${payload.event}|${payload.fieldName}`), mergeMap(group$ => group$.pipe(debounceTime(this.config.defaultStateRefreshTimeMS)))).subscribe({
4208
- next: callback
4209
- });
4210
- return sub;
4211
- }
4212
- /**
4213
- * to be called from the adapter when the form mounts
4214
- *
4215
- * @param {(payload: TFormValues<T>) => void} callback
4216
- * @returns Subscription
4217
- */
4218
- subscribeOnMount(callback) {
4219
- const sub = this.mountSubject$.pipe(map(() => this.formValuesStateSubject$.value)).subscribe({
4220
- next: callback
4221
- });
4222
- return sub;
4223
- }
4224
- /**
4225
- *
4226
- * @param {(payload: { field: string; data: TFormValues }) => void} callback callback function to call onData
4227
- */
4228
- subscribeData(callback) {
4229
- const sub = this.dataSubject$.pipe(filter(({
4230
- formIndex
4231
- }) => this.index === formIndex && this.submitChecker()), groupBy(payload => payload.event), mergeMap(group$ => group$.pipe(debounceTime(this.config.defaultStateRefreshTimeMS))), map(({
4232
- fieldIndex
4233
- }) => ({
4234
- field: fieldIndex,
4235
- data: this.formValuesStateSubject$.value
4236
- }))).subscribe({
4237
- next: callback
4238
- });
4239
- return sub;
4240
- }
4241
- /**
4242
- * method to register a callback function to be called when the form is valid
4243
- *
4244
- * @param {(payload: TFormValues<T>) => void} callback callback function to call when the submit action occurs
4245
- */
4246
- subscribeOnSubmit(callback) {
4247
- const sub = this.submitSubject$.pipe(filter(({
4248
- formIndex
4249
- }) => formIndex === this.index && this.submitChecker()), map(({
4250
- values
4251
- }) => values)).subscribe({
4252
- next: callback
4253
- });
4254
- return sub;
4255
- }
4256
- /**
4257
- * method to check whenever the validity status of the form changes, only emits on status change
4258
- *
4259
- * @param {(payload: TFormValidationPayload) => void} callback callback function to call onValid
4260
- */
4261
- subscribeFormValidation(callback) {
4262
- const sub = this.formValidSubject$.pipe(filter(({
4263
- formIndex
4264
- }) => this.index === formIndex), map(() => ({
4265
- formIndex: this.index,
4266
- valid: this.valid
4267
- })), distinctUntilKeyChanged('valid'), startWith({
4268
- formIndex: this.index,
4269
- valid: this.valid
4270
- })).subscribe({
4271
- next: callback
4272
- });
4273
- return sub;
4274
- }
4275
- /**
4276
- * Submits the form by triggering form field events and invoking the onSubmit callback.
4277
- */
4278
- submit() {
4279
- this.fields.forEach(field => {
4280
- field.emitEvents({
4281
- event: 'ON_FIELD_VALIDATION'
4282
- });
4283
- });
4284
- if (!this.valid) return;
4285
- const values = this.formValuesStateSubject$.value;
4286
- this.submitSubject$.next({
4287
- formIndex: this.index,
4288
- values
4289
- });
4290
- this.submitted = true;
4291
- }
4292
- /**
4293
- * recycles all the Suscriptions, to be called from the adapter when the form leaves the page
4294
- */
4295
- destroy() {
4296
- this.templateSubject$.unsubscribe();
4297
- this.templateSubscription$.unsubscribe();
4298
- this.mountSubject$.unsubscribe();
4299
- this.fieldEventSubject$.unsubscribe();
4300
- this.fieldValidNotification$.unsubscribe();
4301
- this.formValuesStateSubject$.unsubscribe();
4302
- if (this.isolatedFormInstance) {
4303
- this.submitSubject$.unsubscribe();
4304
- this.dataSubject$.unsubscribe();
4305
- this.formValidSubject$.unsubscribe();
4306
- }
4307
- this.fields.forEach(field => field.destroyField());
4308
- }
4309
- }
4310
- /**
4311
- * Validates and collects the names of form fields in the provided schema structure.
4312
- *
4313
- * @param {IComponentSchema[]} [struct] - The schema structure of the form components.
4314
- * @param {string[]} [indexes=[]] - An array to collect the names of the form fields.
4315
- * @returns {string[]} - An array of form field names.
4316
- * @throws {Error} - Throws an error if a field name matches the reserved name defined by `IVARPROPNAME`.
4317
- * @private
4318
- */
4319
- FormCore.checkIndexes = (struct, indexes = []) => {
4320
- if (!struct) return indexes;
4321
- const helper = (struct, indexes) => {
4322
- for (let i = 0; i < struct.length; i++) {
4323
- const structElement = struct[i];
4324
- indexes.push(structElement.name);
4325
- if (structElement.children) {
4326
- helper(structElement.children, indexes);
4327
- }
4328
- }
4329
- };
4330
- helper(struct, indexes);
4331
- const duppedIndexes = indexes.filter((item, index) => indexes.indexOf(item) !== index);
4332
- if (duppedIndexes.length > 0) {
4333
- throw new Error(`duplicated indexes found on schema: ${JSON.stringify(duppedIndexes)}`);
4334
- }
4335
- return indexes;
4336
- };
4337
-
4338
- /**
4339
- * Represents a group that manages multiple forms.
4340
- */
4341
- class FormGroup {
4342
- /**
4343
- * Creates an instance of FormGroup.
4344
- */
4345
- constructor(entry) {
4346
- var _a, _b, _c, _d, _e;
4347
- this.destroy = () => {
4348
- this.forms.forEach(form => form.destroy());
4349
- this.dataSubject$.unsubscribe();
4350
- this.formValidSubject$.unsubscribe();
4351
- this.submitSubject$.unsubscribe();
4352
- };
4353
- this.forms = new Map();
4354
- this.config = {
4355
- defaultAPIdebounceTimeMS: Number((_a = entry === null || entry === void 0 ? void 0 : entry.config) === null || _a === void 0 ? void 0 : _a.defaultAPIdebounceTimeMS) ? Number((_b = entry === null || entry === void 0 ? void 0 : entry.config) === null || _b === void 0 ? void 0 : _b.defaultAPIdebounceTimeMS) : DEFAULT_API_DEBOUNCE_TIME,
4356
- defaultStateRefreshTimeMS: Number((_c = entry === null || entry === void 0 ? void 0 : entry.config) === null || _c === void 0 ? void 0 : _c.defaultStateRefreshTimeMS) ? Number((_d = entry === null || entry === void 0 ? void 0 : entry.config) === null || _d === void 0 ? void 0 : _d.defaultStateRefreshTimeMS) : DEFAULT_STATE_REFRESH_TIME,
4357
- defaultLogVerbose: ((_e = entry === null || entry === void 0 ? void 0 : entry.config) === null || _e === void 0 ? void 0 : _e.defaultLogVerbose) ? entry.config.defaultLogVerbose : DEFAULT_LOG_VERBOSE
4358
- };
4359
- this.dataSubject$ = new Subject();
4360
- this.formValidSubject$ = new Subject();
4361
- this.submitSubject$ = new Subject();
4362
- this.mappers = entry === null || entry === void 0 ? void 0 : entry.mappers;
4363
- }
4364
- /**
4365
- * Creates an empty form with given index
4366
- *
4367
- * @param {string} options.index
4368
- * @param {TMapper<unknown>} options.mappers
4369
- */
4370
- createFormWithIndex({
4371
- index,
4372
- mappers
4373
- }) {
4374
- this.addForm({
4375
- key: index,
4376
- params: {
4377
- index,
4378
- mappers,
4379
- config: this.config
4380
- }
4381
- });
4382
- }
4383
- /**
4384
- * Adds a form instance to the form group.
4385
- *
4386
- * @param {object} options - Options for adding a form.
4387
- * @param {string} options.key - The key associated with the form instance.
4388
- * @param {TFormCore} options.formInstance - The instance of the form to add.
4389
- */
4390
- addForm({
4391
- key,
4392
- params
4393
- }) {
4394
- this.checkIndexes({
4395
- key: key
4396
- });
4397
- const formInstance = new FormCore(Object.assign(Object.assign({}, params), {
4398
- dataSubject$: this.dataSubject$,
4399
- formValidSubject$: this.formValidSubject$,
4400
- submitSubject$: this.submitSubject$
4401
- }));
4402
- if (!formInstance.config) {
4403
- formInstance.config = this.config;
4404
- }
4405
- this.forms.set(key, formInstance);
4406
- }
4407
- /**
4408
- * Retrieves a form instance from the form group.
4409
- *
4410
- * @param {object} options - Options for retrieving a form.
4411
- * @param {string} options.key - The key associated with the form instance.
4412
- * @returns {TFormCore | undefined} The instance of the form, if found; otherwise, undefined.
4413
- */
4414
- getForm({
4415
- key
4416
- }) {
4417
- return this.forms.get(key);
4418
- }
4419
- /**
4420
- * Removes a form instance from the form group.
4421
- *
4422
- * @param {object} options - Options for removing a form.
4423
- * @param {string} options.key - The key associated with the form instance to remove.
4424
- */
4425
- removeForm({
4426
- key
4427
- }) {
4428
- var _a;
4429
- //@TODO logic to unsubscribe all form related
4430
- (_a = this.forms.get(key)) === null || _a === void 0 ? void 0 : _a.destroy();
4431
- this.forms.delete(key);
4432
- }
4433
- /**
4434
- * removes a field given a form and field index
4435
- *
4436
- * @param {string} options.formIndex
4437
- * @param {string} options.fieldIndex
4438
- */
4439
- removeField({
4440
- formIndex,
4441
- fieldIndex
4442
- }) {
4443
- const form = this.forms.get(formIndex);
4444
- form === null || form === void 0 ? void 0 : form.removeField({
4445
- key: fieldIndex
4446
- });
4447
- if ((form === null || form === void 0 ? void 0 : form.fields.size) === 0) {
4448
- this.removeForm({
4449
- key: formIndex
4450
- });
4451
- }
4452
- }
4453
- /**
4454
- * Checks if the specified key already exists in the form group.
4455
- *
4456
- * @param {object} options - Options for checking the key.
4457
- * @param {string} options.key - The key to check.
4458
- * @throws {Error} Throws an error if the key already exists in the form group.
4459
- */
4460
- checkIndexes({
4461
- key
4462
- }) {
4463
- if (this.forms.has(key)) {
4464
- throw new Error(`duplicate index ${key} on form group`);
4465
- }
4466
- }
4467
- /**
4468
- * Prints the form group instance to the console.
4469
- */
4470
- printFormGroupInstance() {
4471
- console.table(this.forms);
4472
- }
4473
- /**
4474
- * Prototype submit function to multiple forms
4475
- * @param {string[]} indexes form indexes to be submitted
4476
- * @param callback
4477
- * @returns
4478
- */
4479
- submitMultipleFormsByIndex(indexes, callback) {
4480
- let isValid = true;
4481
- let values = {};
4482
- let metadata = {};
4483
- let erroredFields = [];
4484
- indexes.forEach(index => {
4485
- var _a, _b;
4486
- (_a = this.forms.get(index)) === null || _a === void 0 ? void 0 : _a.submit();
4487
- const res = (_b = this.forms.get(index)) === null || _b === void 0 ? void 0 : _b.formValuesStateSubject$.value;
4488
- const formMetadata = typeof (res === null || res === void 0 ? void 0 : res.metadata) === 'object' && res.metadata !== null ? res.metadata : {};
4489
- isValid = isValid && ((res === null || res === void 0 ? void 0 : res.isValid) || false);
4490
- values = Object.assign(Object.assign({}, values), (res === null || res === void 0 ? void 0 : res.values) || {});
4491
- metadata = Object.assign(Object.assign({}, metadata), formMetadata);
4492
- erroredFields = [...erroredFields, ...((res === null || res === void 0 ? void 0 : res.erroredFields) || [])];
4493
- });
4494
- if (isValid && callback) {
4495
- callback({
4496
- erroredFields,
4497
- isValid,
4498
- values,
4499
- metadata
4500
- });
4501
- }
4502
- }
4503
- onDataSubscription({
4504
- ids,
4505
- callback
4506
- }) {
4507
- const sub = this.dataSubject$.pipe(filter(({
4508
- formIndex
4509
- }) => ids.includes(formIndex)), groupBy(({
4510
- event,
4511
- formIndex
4512
- }) => `${event}.${formIndex}`), mergeMap(group$ => group$.pipe(debounceTime(this.config.defaultStateRefreshTimeMS))), map(({
4513
- fieldIndex,
4514
- formIndex
4515
- }) => ids.reduce((acc, curr) => {
4516
- const formInstance = this.forms.get(curr);
4517
- if (formInstance) {
4518
- acc[curr] = {
4519
- formId: formIndex,
4520
- formField: fieldIndex,
4521
- values: formInstance.formValuesStateSubject$.value
4522
- };
4523
- }
4524
- return acc;
4525
- }, {}))).subscribe(callback);
4526
- return sub;
4527
- }
4528
- onValidSubscription({
4529
- ids,
4530
- callback
4531
- }) {
4532
- const sub = this.formValidSubject$.pipe(filter(({
4533
- formIndex
4534
- }) => ids.includes(formIndex)), groupBy(({
4535
- formIndex
4536
- }) => formIndex), mergeMap(group$ => group$.pipe(debounceTime(0))), startWith({
4537
- fieldTrigger: null
4538
- }), map(() => ({
4539
- groupValid: ids.every(id => {
4540
- var _a;
4541
- return !this.forms.get(id) || ((_a = this.forms.get(id)) === null || _a === void 0 ? void 0 : _a.valid);
4542
- }),
4543
- forms: ids.reduce((acc, curr) => {
4544
- const formInstance = this.forms.get(curr);
4545
- if (formInstance) {
4546
- acc[curr] = formInstance.valid;
4547
- }
4548
- return acc;
4549
- }, {})
4550
- }))).subscribe(callback);
4551
- return sub;
4552
- }
4553
- onSubmitSubscription({
4554
- ids,
4555
- callback
4556
- }) {
4557
- const sub = this.submitSubject$.pipe(filter(({
4558
- formIndex
4559
- }) => ids.includes(formIndex)), map(() => ids.reduce((acc, curr) => {
4560
- const formInstance = this.forms.get(curr);
4561
- if (formInstance) {
4562
- acc[curr] = formInstance.formValuesStateSubject$.value;
4563
- }
4564
- return acc;
4565
- }, {}))).subscribe(callback);
4566
- return sub;
4567
- }
4568
- }
4569
-
4570
- export { FormCore, FormField, FormGroup, TMutationEnum };
1
+ import{BehaviorSubject as e,Subject as t,Subscription as i,groupBy as s,mergeMap as n,debounceTime as r,filter as a,combineLatest as l,startWith as o,map as u,distinctUntilKeyChanged as d}from"rxjs";import c from"credit-card-type";import{getCurrencySymbol as h}from"@gaignoux/currency";var v;function f(e,t,i,s){return new(i||(i=Promise))(function(n,r){function a(e){try{o(s.next(e))}catch(e){r(e)}}function l(e){try{o(s.throw(e))}catch(e){r(e)}}function o(e){e.done?n(e.value):function(e){return e instanceof i?e:new i(function(t){t(e)})}(e.value).then(a,l)}o((s=s.apply(e,t||[])).next())})}!function(e){e.ON_VALUE="value",e.ON_PROPS="props",e.ON_VISIBILITY="visibility",e.ON_API="api",e.ON_IVARS="iVars",e.ON_FIELDS="fields"}(v||(v={})),"function"==typeof SuppressedError&&SuppressedError;const p=1e3,m=/^\$\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}$/,b=/\$\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g,g=/\s*(\|\||&&|!+)\s*/g,S=/^\|\||&&|!+$/,y=["fields","iVars","form"],$=["api","apiSchema","props","validations","visibilityConditions","resetValues"],V=!1;function j(e){const t=b,i=[];let s;for(;null!==(s=t.exec(e));)i.push(s[1]);const n=g,r=i.map(e=>e.split(n).filter(e=>!n.test(e))).flat().filter(e=>e.split(".").length>1);return{originScopeKeys:Array.from(new Set(r.map(e=>e.split(".")[0]))),originFieldKeys:Array.from(new Set(r.map(e=>e.split(".")[1]))),originPropertyKeys:Array.from(new Set(r.map(e=>e.split(".")[2])))}}function E(e,t){const i=[];if(Array.isArray(e))e.forEach((e,s)=>{i.push(...E(e,`${t?`${t}.`:""}${s}`))});else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(...E(e[s],`${t?`${t}.`:""}${s}`));else if("string"==typeof e&&e.includes("${")){const s=(t||"").split(".");j(e).originScopeKeys.every(e=>y.includes(e))?i.push(Object.assign(Object.assign({originExpression:e},j(e)),{destinationKey:s[0],destinationProperty:s[1],destinationPath:s.slice(2)})):console.warn(`scope malformed on this expression: ${e}, ignoring..`)}return i}const N={},x={},O={};function I(e){Object.assign(N,e)}function F(e){Object.assign(x,e)}function k(e){Object.assign(O,e)}function w(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>w(e));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=w(e[i]));return t}function _(e,t,i){if(null==e)return i;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length;e++){if(null==n)return i;n=n[s[e]]}return void 0===n?i:n}function D(e,t,i){if(null==e||"object"!=typeof e)return e;const s=Array.isArray(t)?t:t.split(".");let n=e;for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];null!=n[t]&&"object"==typeof n[t]||(n[t]="number"==typeof i||/^\d+$/.test(String(i))?[]:{}),n=n[t]}return n[s[s.length-1]]=i,e}function A(e,t){if(e===t)return!0;if(null==e||null==t)return e===t;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!A(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!A(e[i],t[i]))return!1}return!0}function T(e){return null==e}function M(e){return"function"==typeof e}class P extends t{constructor(e){super(),this.isMounted=e}next(e){this.isMounted()&&super.next(e)}}class C extends e{constructor(e){super(e),this.defaultValue=e}next(e){this.closed||super.next(e)}get value(){return this.closed?this.defaultValue:super.value}}var R=(e,t,i)=>!!t&&function(e,t,i){const s=[];return Object.keys(t).forEach(n=>{s.push(i[n](e,{[n]:t[n]}))}),s}(e,t,i).some(e=>e);function L(e,t,i,s,n){return M(i[s])?i[s](e,t,n):R(e,t[s],i)}class Y{constructor({formIndex:e,schemaComponent:t,config:s,children:n,validateVisibility:r,resetValue:a,resetProperty:l,templateSubject$:o,fieldEventSubject$:u,dataSubject$:d,fieldValidNotification$:c,mountSubject$:h,mapper:v,formValuesStateSubject$:f,submitEvent:m,visibility:b,persistValue:g}){var S,y,$,j,E,N;this.valueSubscription$=new i,this.fieldStateSubscription$=new i,this.formIndex=e,this.originalSchema=w(t),this.config={defaultAPIdebounceTimeMS:Number(null==s?void 0:s.defaultAPIdebounceTimeMS)?Number(null==s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null==s?void 0:s.defaultStateRefreshTimeMS)?Number(null==s?void 0:s.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null==s?void 0:s.defaultLogVerbose)?s.defaultLogVerbose:V},this.name=t.name,this.nameToSubmit=t.nameToSubmit,this.component=t.component,this.children=n,this.validations=w(t.validations),this.visibilityConditions=w(t.visibilityConditions),this.resetValues=w(t.resetValues),this.resetPropertyValues=w(t.resetPropertyValues),this.apiSchema=w(t.api),this.formatters=w(t.formatters),this.masks=w(t.masks),v.valueChangeEvent&&(this.valueChangeEvent=v.valueChangeEvent),(null===(S=v.events)||void 0===S?void 0:S.setValue)&&(this.valuePropName=v.events.setValue),this.mapper=v,this.validateVisibility=r,this.resetValue=a,this.resetProperty=l,this.submitEvent=m,this.templateSubject$=o,this.fieldEventSubject$=u,this.dataSubject$=d,this.fieldValidNotification$=c,this.mountSubject$=h,this.formValuesStateSubject$=f,this.getFormValues=()=>this.formValuesStateSubject$.value,this._props=Y.filterProps(w(t.props||{})),this._adapterProps=JSON.stringify(t.props||{}),this._metadata="",this.errorsString="",this.errorsList=[],this._visibility="boolean"!=typeof b||b,this._api={default:{response:(null===(j=null===($=null===(y=this.apiSchema)||void 0===y?void 0:y.defaultConfig)||void 0===$?void 0:$.config)||void 0===j?void 0:j.fallbackValue)||"",status:null},named:(null===(E=this.apiSchema)||void 0===E?void 0:E.configs)&&Object.keys(null===(N=this.apiSchema)||void 0===N?void 0:N.configs).reduce((e,t)=>{var i,s;return e[t]={response:(null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config.fallbackValue)||"",status:null},e},{}),apiState:{loading:!1}},this._errors={},this._mounted=!1,this.valid=!0,this.persistValue=g,this.initializeObservers()}initializeObservers(){this.valueSubject$&&!this.valueSubject$.closed||(this.valueSubject$=new P(()=>this.mounted)),this.errorSubject$&&!this.errorSubject$.closed||(this.errorSubject$=new P(()=>this.mounted)),this.visibilitySubject$&&!this.visibilitySubject$.closed||(this.visibilitySubject$=new P(()=>this.mounted)),this.propsSubject$&&!this.propsSubject$.closed||(this.propsSubject$=new P(()=>this.mounted)),this.fieldStateSubscription$&&!this.fieldStateSubscription$.closed||(this.fieldStateSubscription$=new i),this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed||(this.apiEventQueueSubject$=new P(()=>this.mounted)),this.apiEventQueueSubject$.observed||this.apiEventQueueSubject$.pipe(s(({event:e})=>e),n(e=>e.pipe(r(this.config.defaultAPIdebounceTimeMS))),a(()=>this.apiEventQueueSubject$&&!this.apiEventQueueSubject$.closed)).subscribe(e=>{this.apiRequest(e)})}get adapterProps(){return this._adapterProps}set adapterProps(e){const t=JSON.stringify(e||{});t!==this.adapterProps&&(this.props=Y.filterProps(e),this._adapterProps=t)}get props(){return this._props}set props(e){void 0===e||A(e,this.props)||(this._props=e,this.propsSubject$.next(this.props),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}static filterProps(e){return Array.isArray(e)?e.filter(e=>"string"!=typeof e||!e.includes("${")).map(e=>Y.filterProps(e)):"object"==typeof e&&null!==e?e instanceof Date?e:Object.keys(e).reduce((t,i)=>{const s=e[i];return"string"==typeof s&&s.includes("${")||(t[i]=Y.filterProps(e[i])),t},{}):e}get stateValue(){return this._stateValue}get metadata(){return this._metadata}get value(){return this._value}set value(e){var t,i,s;let n;if(this.valueChangeEvent)try{n=this.valueChangeEvent(e,{props:this.props})}catch(t){n=e}else n=e;null!=n&&("object"==typeof n&&"_value"in n&&"_metadata"in n?(this._value=this.formatValue(n._value),this._stateValue=(null===(t=this.mapper.events)||void 0===t?void 0:t.setValue)?{[this.mapper.events.setValue]:this.maskValue(this.formatValue(n._value))}:{},this._metadata=n._metadata):(this._value=this.formatValue(n),this._stateValue=(null===(i=this.mapper.events)||void 0===i?void 0:i.setValue)?{[null===(s=this.mapper.events)||void 0===s?void 0:s.setValue]:this.maskValue(this.formatValue(n))}:{},this.maskValue(this.formatValue(n)),this._metadata=n),this.stateValue&&this.valueSubject$.next(this.stateValue),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VALUE"}))}get visibility(){return this._visibility}set visibility(e){void 0!==e&&e!==this.visibility&&(this._visibility=e,this.visibilitySubject$.next(this.visibility),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_VISIBILITY"}))}set valid(e){"boolean"!=typeof e&&this.valid===e||(this._valid=e,this.triggerFieldValidNotification())}get valid(){return this._valid}triggerFieldValidNotification(){this.fieldValidNotification$.closed||this.fieldValidNotification$.next({fieldTrigger:this.name})}get errors(){return this._errors}set errors(e){var t;void 0===e||A(e,this.errors)||(this._errors=e,this.errorsList=Object.values(this.errors).filter(e=>null!=e),this.errorsString=this.errorsList.join(", "),(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&this.errorSubject$.next({[this.mapper.events.setErrorMessage]:this.errorsString}),this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_PROPS"}))}get api(){return this._api}set api(e){void 0!==e&&(this._api=e,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_RESPONSE"}),this.emitEvents({event:"ON_API_FIELD_RESPONSE"}))}notifyApiRequest(){this._api.apiState.loading=!0,this.templateSubject$.next({scope:"fields",key:this.name,event:"ON_API_REQUEST"}),this.emitEvents({event:"ON_API_FIELD_REQUEST"})}get mounted(){return this._mounted}set mounted(e){void 0!==e&&e!==this.mounted&&(this._mounted=e,this.initializeObservers(),this.mountSubject$.closed||this.mountSubject$.next({key:this.name,status:this.mounted}))}mountField({valueSubscription:e,propsSubscription:t}){this.mounted=!0,this.subscribeValue(e),this.subscribeState(t),this.valueSubject$.next(this.stateValue),this.propsSubject$.next(this.props),this.visibilitySubject$.next(this.visibility),this.fieldEventSubject$.next({event:"ON_FIELD_MOUNT",fieldName:this.name,fieldInstance:this})}emitValue(e){this.visibility&&this.mounted&&(this.value=e.value,this.dataSubject$.next({event:e.event,fieldIndex:this.name,formIndex:this.formIndex}),this.emitEvents({event:e.event}))}emitEvents({event:e}){if("ON_FORM_SUBMIT"===e)return this.submitEvent();this.validateVisibility({event:e,key:this.name}),this.setFieldValidity({event:e}),this.resetValue({event:e,key:this.name}),this.resetProperty({event:e,key:this.name}),this.apiEventQueueSubject$.next({event:e}),this.fieldEventSubject$.next({event:e,fieldName:this.name,fieldInstance:this})}setFieldValidity({event:e}){var t,i,s,n;if(!this.validations||!this.visibility)return this.errors={},void(this.valid=!0);let r=!0;const a={},l=null===(t=this.validations)||void 0===t?void 0:t.methods;if(l&&Object.keys(l).forEach(e=>{var t,i;const s=L(this.value,l,N,e,null===(t=this.formValuesStateSubject$)||void 0===t?void 0:t.value);r=!s&&r,s&&(null===(i=this.validations)||void 0===i?void 0:i.messages)?e in this.validations.messages?a[e]=this.validations.messages[e]:"default"in this.validations.messages&&(a[e]=this.validations.messages.default):delete a[e]}),this.valid=r,null===(s=null===(i=this.validations)||void 0===i?void 0:i.eventMessages)||void 0===s?void 0:s[e]){const t={};null===(n=this.validations.eventMessages[e])||void 0===n||n.forEach(e=>{e in a&&(t[e]=a[e])}),this.errors=t}else"ON_FIELD_VALIDATION"===e&&(this.errors=a)}formatValue(e){return this.formatters?Object.keys(this.formatters).reduce((e,t)=>{const i=x[t];return i?i(e,this.formatters):e},e):e}maskValue(e){return this.masks?Object.keys(this.masks).reduce((e,t)=>{const i=O[t];return i?i(e,this.masks):e},e):e}checkApiRequestValidations(e){let t=!0;const i=e.preConditions;return i&&Object.keys(i).forEach(e=>{var s;const n=L(this.value,i,N,e,null===(s=this.formValuesStateSubject$)||void 0===s?void 0:s.value);t=t&&!n}),e.blockRequestWhenInvalid&&(t=t&&this.valid),t}apiRequest(e){return f(this,arguments,void 0,function*({event:e}){var t,i,s,n,r,a,l,o,u;let d=!1;const c=e=>f(this,void 0,void 0,function*(){var t,i;try{const{status:s,response:n}=yield function(e,t,i,s,n){return f(this,void 0,void 0,function*(){if(n){const[e,i]=t.split("?"),s=new URLSearchParams(i);Object.keys(n).forEach(e=>{s.append(e,n[e])}),t=`${e}?${s.toString()}`}const r=yield fetch(t,{method:e,headers:i,body:s?JSON.stringify(s):void 0}),a=yield r.text();return{status:r.status,response:a}})}(e.method,e.url,e.headers,e.body,e.queryParams),r=null===(t=e.transform)||void 0===t?void 0:t.callback,a=r?r({payload:JSON.parse(String(n)),formValues:null===(i=this.formValuesStateSubject$)||void 0===i?void 0:i.value}):JSON.parse(String(n));return{response:e.resultPath?_(a,e.resultPath):a,status:s}}catch(t){return{response:T(null==e?void 0:e.fallbackValue)?"error":e.fallbackValue,status:500}}});if("ON_API_FIELD_RESPONSE"===this.api.apiState.lastEvent&&"ON_API_FIELD_RESPONSE"===e||!(null===(i=null===(t=this.apiSchema)||void 0===t?void 0:t.defaultConfig)||void 0===i?void 0:i.events.includes(e))&&(!(null===(s=this.apiSchema)||void 0===s?void 0:s.configs)||!Object.keys(null===(n=this.apiSchema)||void 0===n?void 0:n.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})))return;const h={default:Object.assign({},this.api.default),named:Object.assign({},this.api.named),apiState:Object.assign({},this.api.apiState)},v=null===(r=this.apiSchema.defaultConfig)||void 0===r?void 0:r.config;if(v&&(null===(l=null===(a=this.apiSchema)||void 0===a?void 0:a.defaultConfig)||void 0===l?void 0:l.events.includes(e))&&this.checkApiRequestValidations(v)){d||this.notifyApiRequest();const{response:e,status:t}=yield c(v);d=!0,h.default={response:e,status:t}}if((null===(o=this.apiSchema)||void 0===o?void 0:o.configs)&&Object.keys(null===(u=this.apiSchema)||void 0===u?void 0:u.configs).some(t=>{var i,s;return null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].events.includes(e)})&&this.apiSchema.configs){const t=yield Promise.all(Object.keys(this.apiSchema.configs).map(t=>f(this,void 0,void 0,function*(){var i,s,n,r;const a=null===(s=null===(i=this.apiSchema)||void 0===i?void 0:i.configs)||void 0===s?void 0:s[t].config;if(a&&(null===(r=null===(n=this.apiSchema)||void 0===n?void 0:n.configs)||void 0===r?void 0:r[t].events.includes(e))&&this.checkApiRequestValidations(a)){d||this.notifyApiRequest();const{response:e,status:i}=yield c(a);return d=!0,{name:t,result:{response:e,status:i}}}return null})));t.forEach(e=>{e&&h.named&&(h.named[e.name]=e.result)})}d&&(h.apiState.lastEvent=e,h.apiState.loading=!1,this.api=h)})}destroyField(){this.mounted=!1,this.valueSubscription$.unsubscribe(),this.visibilitySubject$.unsubscribe(),this.fieldStateSubscription$.unsubscribe(),this.propsSubject$.unsubscribe(),this.errorSubject$.unsubscribe(),this.apiEventQueueSubject$.unsubscribe(),this.dataSubject$.closed||this.dataSubject$.next({event:"ON_FIELD_UNMOUNT",fieldIndex:this.name,formIndex:this.formIndex}),this.fieldEventSubject$.closed||this.fieldEventSubject$.next({event:"ON_FIELD_UNMOUNT",fieldName:this.name,fieldInstance:this})}subscribeState(e){var t;this.fieldStateSubscription$=l({visibility:this.visibilitySubject$.pipe(o(this.visibility)),props:this.propsSubject$.pipe(o(this.props)),errors:this.errorSubject$.pipe(o(Object.assign({},(null===(t=this.mapper.events)||void 0===t?void 0:t.setErrorMessage)&&{[this.mapper.events.setErrorMessage]:this.errorsString})))}).pipe(r(this.config.defaultStateRefreshTimeMS)).subscribe({next:e})}subscribeValue(e){this.valueSubscription$=this.valueSubject$.subscribe({next:e})}}class q{constructor(e){var s,n,r,a,l,o,u,d,c,h,v;this.templateSubscription$=new i,this.mappers=new Map,this.queuedFieldVisibilityEvents=new Map,this.queuedFieldResetValuesEvents=new Map,this.queuedFieldResetPropertyEvents=new Map,this.queuedInitialValues=new Map,this._valid=!1,this.stopEventsOnSubmit=!1,this.submitted=!1,this.isolatedFormInstance=!1,this.index=e.index,this.schema=e.schema,this.fields=new Map,this.action=e.action||(null===(s=e.schema)||void 0===s?void 0:s.action),this.method=e.method||(null===(n=e.schema)||void 0===n?void 0:n.method),this.config={defaultAPIdebounceTimeMS:Number(null===(r=e.config)||void 0===r?void 0:r.defaultAPIdebounceTimeMS)?Number(null===(a=e.config)||void 0===a?void 0:a.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(l=e.config)||void 0===l?void 0:l.defaultStateRefreshTimeMS)?Number(null===(o=e.config)||void 0===o?void 0:o.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(u=e.config)||void 0===u?void 0:u.defaultLogVerbose)?e.config.defaultLogVerbose:V},null===(d=e.mappers)||void 0===d||d.map(e=>{this.mappers.set(e.componentName,e)}),e.submitSubject$&&e.dataSubject$&&e.formValidSubject$||(this.isolatedFormInstance=!0,this.config.defaultLogVerbose&&console.warn(`some formGroup events are not properly instanciated, any onData, onValid, onSubmit events managed by formGroup won't trigger on form: ${this.index}`)),this.schema&&q.checkIndexes(this.schema.components),this.templateSubject$=new t,this.fieldEventSubject$=new t,this.mountSubject$=new t,this.fieldValidNotification$=new t,this.submitSubject$=e.submitSubject$?e.submitSubject$:new t,this.dataSubject$=e.dataSubject$?e.dataSubject$:new t,this.formValidSubject$=e.formValidSubject$?e.formValidSubject$:new t,this.formValuesStateSubject$=new C({erroredFields:[],isValid:!0,metadata:[],values:[]}),this.getFormValues=()=>this.formValuesStateSubject$.value,this.subscribedTemplates=[],this.templateSubscription$=this.templateSubject$.subscribe(this.refreshTemplates.bind(this)),this.fieldValidNotification$.subscribe(()=>{this.validateForm()}),this.fieldEventSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.dataSubject$.subscribe(()=>{this.formValuesStateSubject$.next(this.getFormState())}),this.mountSubject$.subscribe(this.mountActions.bind(this)),this.prefetchedData=null===(c=e.schema)||void 0===c?void 0:c.prefetchedData,this.initialValues=e.initialValues||(null===(h=e.schema)||void 0===h?void 0:h.initialValues),this.iVars=e.iVars||(null===(v=e.schema)||void 0===v?void 0:v.iVars)||{},this.stopEventsOnSubmit=(null==e?void 0:e.stopEventsOnSubmit)||!1,this.submitted=!1}generateFields(){this.schema&&this.serializeStructure(this.schema.components),this.fields.forEach(e=>{e.mountField({valueSubscription:()=>null,propsSubscription:()=>null})})}submitChecker(){return!(this.stopEventsOnSubmit&&this.submitted)}mountActions({key:e,status:t}){if(t){const t=this.fields.get(e);if(!t)return void(this.config.defaultLogVerbose&&console.warn(`field ${e} was mounted but since it's parent has some visibility condition the field was already removed`));this.subscribeTemplates(),this.refreshTemplates({scope:"fields",event:"ON_FIELDS"}),this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"}),this.queuedInitialValues.has(e)||(t.valuePropName&&!t.value?t.emitValue({event:"ON_FIELD_MOUNT",value:""}):t.emitEvents({event:"ON_FIELD_MOUNT"})),this.checkFieldEventQueues(e)}}set initialValues(e){e&&Object.keys(e).forEach(t=>{const i=this.fields.get(t);i&&(null==i?void 0:i.visibility)&&(null==i?void 0:i.mounted)?i.emitValue({value:null==e?void 0:e[t],event:"ON_FIELD_MOUNT"}):this.queuedInitialValues.set(t,null==e?void 0:e[t])})}get iVars(){return this._iVars}set iVars(e){this._iVars=e,this.templateSubject$.next({scope:"iVars",event:"ON_IVARS"})}validateForm(){if(0===this.fields.size)return this.valid=!1;for(const[,e]of this.fields)if(!e.valid)return this.valid=!1;return this.valid=!0}get valid(){return this._valid}set valid(e){this._valid!==e&&(this._valid=e,this.templateSubject$.next({event:"ON_FORM",scope:"form"}),this.formValidSubject$.next({formIndex:this.index,valid:this.valid}))}subscribeTemplates(){this.subscribedTemplates=[],this.fields.forEach(({originalSchema:{component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,api:l}},o)=>{E({component:e,props:t,name:i,validations:s,visibilityConditions:n,resetValues:r,resetPropertyValues:a,apiSchema:l},o).forEach(e=>this.subscribedTemplates.push(e))})}getValue({scope:e,key:t,property:i,path:s}){switch(e){case"iVars":return _(this.iVars,[t,...i?[i]:[],...s]);case"form":return _(this,[t,...i?[i]:[],...s]);case"fields":{const e=this.fields.get(t);return e?"props"===i&&s[0]===e.valuePropName?e.value:s.length>0?_(e[i],s):e[i]:this.config.defaultLogVerbose&&console.warn(`failed to get value from ${t}`)}}}setValue({key:e,property:t,path:i,originKey:s,value:n}){const r=this.fields.get(e);if(r){if(i.length>0){if("props"===t&&i[0]===r.valuePropName&&e!==s)return void r.emitValue({event:"ON_FIELD_CHANGE",value:n});const a=r[t];let l;return Array.isArray(a)||"object"==typeof a&&!T(a)?(l=w(a),D(l,i,n),void(r[t]=l)):void(this.config.defaultLogVerbose&&console.warn(`invalid template property, skipping evaluation of ${r.name} with ${a}`))}r[t]=n}else this.config.defaultLogVerbose&&console.warn(`failed to update field ${e}`)}extractParams(e){const t=function(e){const t=e.split(".");return t.length>1?this.getValue({scope:t[0],key:t[1],property:t[2],path:t.slice(3)}):t[0]}.bind(this),i=[];let s;for(;!T(s=b.exec(e));)i.push(s[1]);const n=i.map(e=>e.split(g)).map(e=>e.length<=1?{parse:!1,value:t(e[0])}:{parse:!0,value:e.filter(Boolean).reduce((e,i)=>{if(i.match(S))return`${e}${i}`;let s;const n=t(i);let r;try{r=JSON.parse(n)}catch(e){r=n}switch(typeof r){case"string":s=`\`${r}\``;break;case"boolean":case"undefined":case"number":default:s=r;break;case"object":if(null===r){s=null;break}if(r instanceof Date){s=`new Date(\`${r}\`)`;break}s=JSON.stringify(r)}return`${e}${s}`},"")});return n.map(({parse:t,value:i})=>{try{return t?new Function(`return ${i}`)():i}catch(t){return this.config.defaultLogVerbose&&(console.warn(`unhandled parsing on ${e} returning`),console.warn(i)),i}})}replaceExpression(e,t){return e.replace(b,()=>String(t.shift())||"")}hasStringConcatenation(e){return!m.test(e)}refreshTemplates({key:e,event:t}){this.subscribedTemplates.forEach(({destinationKey:i,destinationPath:s,destinationProperty:n,originExpression:r,originFieldKeys:a})=>{if(!e||a.includes(e)){const a=this.extractParams(r);let l;l=this.hasStringConcatenation(r)?this.replaceExpression(r,[...a]):null==a?void 0:a[0],A(this.getValue({scope:"fields",key:i,property:n,path:s}),l)||this.setValue({key:i,property:n,path:s,originKey:e,value:l,event:t})}})}checkFieldEventQueues(e){var t;if(null===(t=this.fields.get(e))||void 0===t?void 0:t.mounted){if(this.queuedFieldVisibilityEvents.has(e)&&(this.setFieldVisibility(Object.assign({field:e},this.queuedFieldVisibilityEvents.get(e))),this.queuedFieldVisibilityEvents.delete(e)),this.queuedInitialValues.has(e)){const t=this.queuedInitialValues.get(e);this.queuedInitialValues.delete(e),this.initialValues={[e]:t}}this.queuedFieldResetValuesEvents.has(e)&&(this.setResetFieldValue(Object.assign({key:e},this.queuedFieldResetValuesEvents.get(e))),this.queuedFieldResetValuesEvents.delete(e)),this.queuedFieldResetPropertyEvents.has(e)&&(this.setResetPathValue(Object.assign({key:e},this.queuedFieldResetPropertyEvents.get(e))),this.queuedFieldResetPropertyEvents.delete(e))}}setFieldVisibility({field:e,hasError:t,showOnlyIfTrue:i}){const s=this.fields.get(e);if(s&&s.mounted){const n=s.visibility,r=i?t:!t;if(s.visibility=r,n===r)return;s.visibility?this.queuedInitialValues.has(e)?(null==s||s.emitValue({value:this.queuedInitialValues.get(e)||"",event:"ON_FIELD_MOUNT"}),this.queuedInitialValues.delete(e)):s.emitEvents({event:"ON_FIELD_MOUNT"}):(s.emitEvents({event:"ON_FIELD_UNMOUNT"}),s.persistValue&&this.queuedInitialValues.set(s.name,s.value),s.value="",s.valid=!0)}else this.queuedFieldVisibilityEvents.set(e,{hasError:t,showOnlyIfTrue:i})}validateVisibility({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.visibilityConditions;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{t.events.includes(e)&&Object.keys(t.validations).forEach(e=>{const s=L(i.value,t.validations,N,e,this.formValuesStateSubject$.value);Array.isArray(t.fields)?t.fields.forEach(e=>{this.setFieldVisibility({field:e,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})}):t.fields&&this.setFieldVisibility({field:t.fields,hasError:s,showOnlyIfTrue:!(!i.value||!t.showOnlyIfTrue)})})})}setResetFieldValue({key:e,value:t}){const i=this.fields.get(e);i&&(null==i?void 0:i.mounted)?i.emitValue({value:t,event:"ON_FIELD_CLEARED"}):this.queuedFieldResetValuesEvents.set(e,{value:t})}resetValue({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(!t.events.includes(e))return;const s=()=>{Array.isArray(t.fields)?t.fields.forEach((e,i)=>{const s=Array.isArray(t.resettledValue)?t.resettledValue[i]:t.resettledValue;this.setResetFieldValue({key:e,value:s})}):t.fields&&this.setResetFieldValue({key:t.fields,value:t.resettledValue})};if(!t.validations)return s();Object.keys(t.validations).forEach(e=>{L(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||s()})})}setResetPathValue({key:e,property:t,path:i,value:s}){this.fields.get(e)?this.setValue({key:e,property:t,path:i.split("."),value:s,event:"ON_RESET"}):this.queuedFieldResetPropertyEvents.set(e,{property:t,path:i,value:s})}resetProperty({event:e,key:t}){const i=this.fields.get(t),s=null==i?void 0:i.resetPropertyValues;s&&(null==s?void 0:s.some(t=>t.events.includes(e)))&&s.forEach(t=>{if(t.events.includes(e)&&$.includes(t.property))return t.validations?void Object.keys(t.validations).forEach(e=>{L(i.value,t.validations,N,e,this.formValuesStateSubject$.value)||this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})}):this.setResetPathValue({key:t.field,path:t.path,property:t.property,value:t.resettledValue})})}addField({fieldSchema:e,mapperElement:t,path:i}){var s,n,r,a,l;if(this.fields.has(e.name))throw new Error(`field name ${e.name} already defined`);const o=t||(null===(s=this.mappers)||void 0===s?void 0:s.get(e.component));if(!o)throw new Error(`mapper not found for ${e.component}, add it to the mappers configuration`);if(null===(n=o.events)||void 0===n?void 0:n.setValue){const t=null===(r=null==e?void 0:e.props)||void 0===r?void 0:r[null===(a=null==o?void 0:o.events)||void 0===a?void 0:a.setValue];void 0===t||this.queuedInitialValues.has(e.name)||"string"==typeof t&&t.includes("${")||this.queuedInitialValues.set(e.name,w(t))}if(this.fields.set(e.name,new Y({formIndex:this.index,schemaComponent:e,mapper:o,children:e.children?e.children.map(e=>e.name):[],validateVisibility:this.validateVisibility.bind(this),resetValue:this.resetValue.bind(this),resetProperty:this.resetProperty.bind(this),formValuesStateSubject$:this.formValuesStateSubject$,templateSubject$:this.templateSubject$,fieldEventSubject$:this.fieldEventSubject$,dataSubject$:this.dataSubject$,fieldValidNotification$:this.fieldValidNotification$,mountSubject$:this.mountSubject$,config:this.config,submitEvent:this.submit.bind(this),visibility:e.visibility,persistValue:e.persistValue,path:i})),null===(l=this.prefetchedData)||void 0===l?void 0:l[e.name]){const t=this.fields.get(e.name);if(t){const i=this.prefetchedData[e.name],s=Object.assign({},t.api);void 0!==i.defaultResponse&&(s.default={response:i.defaultResponse,status:200}),i.namedResponses&&(s.named=s.named||{},Object.keys(i.namedResponses).forEach(e=>{s.named[e]={response:i.namedResponses[e],status:200}})),t._api=s}}}removeField({key:e}){var t;null===(t=this.fields.get(e))||void 0===t||t.destroyField(),this.fields.delete(e),this.subscribeTemplates(),this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"}),this.validateForm()}serializeStructure(e,t){e&&e.forEach(e=>{var i;const s=this.fields.get(e.name);s?(s.children=(null===(i=null==e?void 0:e.children)||void 0===i?void 0:i.map(e=>e.name))||(null==s?void 0:s.children)||[],s.originalSchema=e,s.templateSubject$=this.templateSubject$):this.addField({fieldSchema:e,mapperElement:e.mapper,path:t}),e.children&&this.serializeStructure(e.children,`${t?`${t}.`:""}${e.name}`)})}refreshFields(e){const t=Array.from(this.fields.keys());this.serializeStructure(e);const i=q.checkIndexes(e);this.fields.forEach((e,t)=>{var s;i.includes(t)||(null===(s=this.fields.get(t))||void 0===s||s.destroyField(),this.fields.delete(t))}),this.subscribeTemplates(),this.fields.forEach((e,i)=>{var s;t.includes(i)||(null===(s=this.fields.get(i))||void 0===s||s.emitEvents({event:"ON_FIELD_MOUNT"}),this.checkFieldEventQueues(i))}),this.subscribedTemplates.forEach(e=>{e.originFieldKeys.forEach(e=>{this.templateSubject$.next({scope:"fields",key:e,event:"ON_FIELDS"})})})}getField({key:e}){return this.fields.get(e)}printValues(){console.table(this.formValuesStateSubject$.value.values)}getFormState(){const e={},t={},i=[];return this.fields.forEach((s,n)=>{"string"==typeof s.value&&0===s.value.length||null==s.value||(D(e,s.nameToSubmit||n,s.value),t[n]=s.metadata),s.valid||i.push(n)}),{values:e,metadata:t,erroredFields:i,isValid:this.valid}}subscribeFieldEvent({callback:e}){return this.fieldEventSubject$.pipe(a(()=>this.submitChecker()),s(e=>`${e.event}|${e.fieldName}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS)))).subscribe({next:e})}subscribeOnMount(e){return this.mountSubject$.pipe(u(()=>this.formValuesStateSubject$.value)).subscribe({next:e})}subscribeData(e){return this.dataSubject$.pipe(a(({formIndex:e})=>this.index===e&&this.submitChecker()),s(e=>e.event),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:e})=>({field:e,data:this.formValuesStateSubject$.value}))).subscribe({next:e})}subscribeOnSubmit(e){return this.submitSubject$.pipe(a(({formIndex:e})=>e===this.index&&this.submitChecker()),u(({values:e})=>e)).subscribe({next:e})}subscribeFormValidation(e){return this.formValidSubject$.pipe(a(({formIndex:e})=>this.index===e),u(()=>({formIndex:this.index,valid:this.valid})),d("valid"),o({formIndex:this.index,valid:this.valid})).subscribe({next:e})}submit(){this.fields.forEach(e=>{e.emitEvents({event:"ON_FIELD_VALIDATION"})}),this.valid&&(this.submitSubject$.next({formIndex:this.index,values:this.formValuesStateSubject$.value}),this.submitted=!0)}destroy(){this.templateSubject$.unsubscribe(),this.templateSubscription$.unsubscribe(),this.mountSubject$.unsubscribe(),this.fieldEventSubject$.unsubscribe(),this.fieldValidNotification$.unsubscribe(),this.formValuesStateSubject$.unsubscribe(),this.isolatedFormInstance&&(this.submitSubject$.unsubscribe(),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe()),this.fields.forEach(e=>e.destroyField())}}q.checkIndexes=(e,t=[])=>{if(!e)return t;const i=(e,t)=>{for(let s=0;s<e.length;s++){const n=e[s];t.push(n.name),n.children&&i(n.children,t)}};i(e,t);const s=t.filter((e,i)=>t.indexOf(e)!==i);if(s.length>0)throw new Error(`duplicated indexes found on schema: ${JSON.stringify(s)}`);return t};class U{constructor(e){var i,s,n,r,a;this.destroy=()=>{this.forms.forEach(e=>e.destroy()),this.dataSubject$.unsubscribe(),this.formValidSubject$.unsubscribe(),this.submitSubject$.unsubscribe()},this.forms=new Map,this.config={defaultAPIdebounceTimeMS:Number(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.defaultAPIdebounceTimeMS)?Number(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.defaultAPIdebounceTimeMS):p,defaultStateRefreshTimeMS:Number(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.defaultStateRefreshTimeMS)?Number(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.defaultStateRefreshTimeMS):100,defaultLogVerbose:(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.defaultLogVerbose)?e.config.defaultLogVerbose:V},this.dataSubject$=new t,this.formValidSubject$=new t,this.submitSubject$=new t,this.mappers=null==e?void 0:e.mappers}createFormWithIndex({index:e,mappers:t}){this.addForm({key:e,params:{index:e,mappers:t,config:this.config}})}addForm({key:e,params:t}){this.checkIndexes({key:e});const i=new q(Object.assign(Object.assign({},t),{dataSubject$:this.dataSubject$,formValidSubject$:this.formValidSubject$,submitSubject$:this.submitSubject$}));i.config||(i.config=this.config),this.forms.set(e,i)}getForm({key:e}){return this.forms.get(e)}removeForm({key:e}){var t;null===(t=this.forms.get(e))||void 0===t||t.destroy(),this.forms.delete(e)}removeField({formIndex:e,fieldIndex:t}){const i=this.forms.get(e);null==i||i.removeField({key:t}),0===(null==i?void 0:i.fields.size)&&this.removeForm({key:e})}checkIndexes({key:e}){if(this.forms.has(e))throw new Error(`duplicate index ${e} on form group`)}printFormGroupInstance(){console.table(this.forms)}submitMultipleFormsByIndex(e,t){let i=!0,s={},n={},r=[];e.forEach(e=>{var t,a;null===(t=this.forms.get(e))||void 0===t||t.submit();const l=null===(a=this.forms.get(e))||void 0===a?void 0:a.formValuesStateSubject$.value,o="object"==typeof(null==l?void 0:l.metadata)&&null!==l.metadata?l.metadata:{};i=i&&((null==l?void 0:l.isValid)||!1),s=Object.assign(Object.assign({},s),(null==l?void 0:l.values)||{}),n=Object.assign(Object.assign({},n),o),r=[...r,...(null==l?void 0:l.erroredFields)||[]]}),i&&t&&t({erroredFields:r,isValid:i,values:s,metadata:n})}onDataSubscription({ids:e,callback:t}){return this.dataSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({event:e,formIndex:t})=>`${e}.${t}`),n(e=>e.pipe(r(this.config.defaultStateRefreshTimeMS))),u(({fieldIndex:t,formIndex:i})=>e.reduce((e,s)=>{const n=this.forms.get(s);return n&&(e[s]={formId:i,formField:t,values:n.formValuesStateSubject$.value}),e},{}))).subscribe(t)}onValidSubscription({ids:e,callback:t}){return this.formValidSubject$.pipe(a(({formIndex:t})=>e.includes(t)),s(({formIndex:e})=>e),n(e=>e.pipe(r(0))),o({fieldTrigger:null}),u(()=>({groupValid:e.every(e=>{var t;return!this.forms.get(e)||(null===(t=this.forms.get(e))||void 0===t?void 0:t.valid)}),forms:e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.valid),e},{})}))).subscribe(t)}onSubmitSubscription({ids:e,callback:t}){return this.submitSubject$.pipe(a(({formIndex:t})=>e.includes(t)),u(()=>e.reduce((e,t)=>{const i=this.forms.get(t);return i&&(e[t]=i.formValuesStateSubject$.value),e},{}))).subscribe(t)}}var z=(e,t)=>{if(!t.length||!e)return!1;let i=e;return"string"!=typeof i&&(i=(null==e?void 0:e.toString())||i),{equal:i.length!==t.length.target,notEqual:i.length===t.length.target,less:i.length>=t.length.target,lessOrEqual:i.length>t.length.target,greater:i.length<=t.length.target,greaterOrEqual:i.length<t.length.target}[t.length.rule]};const Z=e=>{if(9!==e.length)return!0;if(!/^\d{8}$/.test(e.slice(0,8)))return!0;const t="TRWAGMYFPDXBNJZSQVHLCKE"[parseInt(e.slice(0,8),10)%23];return!(e[8].toUpperCase()===t)};var Q=(e,t)=>{if(!e||!t.document)return!0;const i={NIF:(e,t)=>((e,t)=>{switch(t){case"pt-PT":return(e=>{if(!/^\d{9}$/.test(e))return!1;const t=parseInt(e[8],10),i=11-Array.from(e.substring(0,8)).reduce((e,t,i)=>e+parseInt(t,10)*(9-i),0)%11;return 10===i||11===i?0===t:i===t})(e);case"es-ES":return Z(e);case"it-IT":return(e=>/^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/.test(e))(e);case"de-DE":return(e=>/^\d{11}$/.test(e))(e);case"fr-FR":return(e=>/^\d{2} \d{3} \d{3} \d{3} \d{3}$/.test(e))(e);case"en-GB":return(e=>/^GB\d{9}|\d{12}|\d{3}[A-Z]{5}$/.test(e))(e);case"nl-BE":case"fr-BE":return(e=>!!/^\d{11}$/.test(e)&&97-parseInt(e.substring(0,9),10)%97===parseInt(e.substring(9),10))(e);case"nl-NL":return(e=>!!/^\d{9}$/.test(e)&&e.split("").map((e,t)=>parseInt(e,10)*(9-t)).reduce((e,t)=>e+t,0)%11==0)(e);case"sv-SE":return(e=>!!/^\d{10,12}$/.test(e)&&(12===e.length?e.substring(2):e).split("").map((e,t)=>{let i=parseInt(e,10)*(t%2==0?2:1);return i>9&&(i-=9),i}).reduce((e,t)=>e+t,0)%10==0)(e);default:throw new Error(`NIF validation not supported for locale: ${t}`)}})(e,t),NIE:e=>(e=>{if(9!==e.length)return!0;if(!/^[XYZ]\d{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/.test(e))return!0;let t=e.toUpperCase().padStart(9,"0");return t=t[0].replace(/[XYZ]/g,e=>({X:"0",Y:"1",Z:"2"}[e]||e))+t.slice(1),Z(t)})(e),CIF:e=>(e=>!/^[A-Z][0-9]{7}[A-J0-9]$/.test(e))(e),IBAN:e=>(e=>{const t=e.replace(/\s/g,"");return 24!==t.length||!/^(ES)[0-9]{22}$/.test(t)||1!==(e=>{for(;e.length>2;){const t=e.slice(0,6),i=parseInt(t,10);if(isNaN(i))return NaN;e=i%97+e.slice(t.length)}return parseInt(e,10)%97})(t.substring(4)+1428+t.substring(2,4))})(e)};return i[t.document.type](e,t.document.locale)};const B=(e,t)=>{const i=Number(e);return!(!t.max||Number.isNaN(i))&&i>Number(t.max)},J=(e,t)=>{const i=Number(e);return!(!t.min||Number.isNaN(i))&&i<Number(t.min)},K=(e,t)=>{if(!t.between||!e)return!1;const i=Number(e);return!(Number.isNaN(i)||+i>=t.between.start&&+i<=t.between.end)},G=(e,t)=>{const i=Number(e);return!(!t.lessThan||Number.isNaN(i))&&i>=t.lessThan},W=(e,t)=>{const i=Number(e);return!(!t.greaterThan||Number.isNaN(i))&&i<=t.greaterThan},X=(e,t)=>{if(!t.sequential)return!1;const i=String(e).replace(/[^0-9]/g,"");return!(-1==="0123456789".indexOf(i)&&-1==="9876543210".indexOf(i))},H=(e,t)=>!(!t.regex||!e)&&!new RegExp(t.regex).test(e),ee=(e,t)=>!(!t.email||!e)&&!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e),te=(e,t)=>!(!t.url||!e)&&!/[(http(s)?)://(www.)?a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/gi.test(e),ie=(e,t)=>!!t.onlyLetters&&!/^[\p{L}\s]*$/u.test(e),se=(e,t)=>!!t.notAllowSpaces&&/\s/.test(e),ne=(e,t)=>!!t.isNumber&&!!e&&!/^[0-9\s]*$/.test(e),re=(e,t)=>!(!t.hasNoExtraSpaces||!e)&&H(e,{regex:"^[A-Za-zÀ-ÖØ-öø-ÿäöüÄÖÜß0-9]+$"}),ae=(e,t)=>{if(!t.repeated)return!1;const i={};for(const t of String(e))if(/\d/.test(t)){if(i[t])return!0;i[t]=1}return!1},le=(e,t,{values:i=[],metadata:s=[]}={values:[],metadata:[],erroredFields:[],isValid:!0})=>!!(t.callback&&(null==t?void 0:t.callback)instanceof Function)&&t.callback(e,{values:i,metadata:s}),oe=(e,t)=>!(!e||!Array.isArray(null==t?void 0:t.includes)||(null==t?void 0:t.includes.some(t=>t===e||JSON.stringify(t)===e))),ue=(e,t)=>{const i=de(null==e?void 0:e.toString()),s=c(i);return["object"==typeof t&&t.length?null==s?void 0:s.filter(({type:e})=>t.some(t=>t===e))[0]:s[0],i]},de=e=>null==e?void 0:e.replace(/ /g,""),ce=(e,t=4,i="/")=>{const s=e.replace(/\D/g,""),n=s.slice(0,2);return s.length>=5?`${n}${i}${s.slice(2,t)}`:s.length>=3?`${n}${i}${s.slice(2)}`:s},he=(e,t)=>{if(!e)return!0;const[i]=ue(String(e),t.isCreditCard);return!i},ve=(e,t)=>{var i;if(!e||!t.isCreditCodeMatch)return!1;const[s]=ue(t.isCreditCodeMatch.numberCard,t.isCreditCodeMatch.availableOptions);return(null===(i=null==s?void 0:s.code)||void 0===i?void 0:i.size)!==e.length},fe=(e,t)=>{if(!e||!t.isCreditCardAndLength)return!1;const[i,s]=ue(e,t.isCreditCardAndLength);return i&&!i.lengths.includes(s.length)},pe=(e,t)=>{var i;return!(!(null==t?void 0:t.notEmpty)||void 0===e||null!==e&&""!==e&&0!==e&&(null===(i=String(e))||void 0===i?void 0:i.trim().length))},me=(e,t)=>null!=(null==t?void 0:t.value)&&null!=e&&e!=t.value,be=(e,t)=>!(!t.required||e&&("string"!=typeof e||0!==e.trim().length)),ge=(e,t)=>{if(!(null==t?void 0:t.bool))return!1;let i=!1;return"boolean"==typeof t.bool&&(i=t.bool),i},Se=(e,t)=>{if(!t.exists)return!1;let i=!t.exists;return i||(i=!e),i},ye=(e,t)=>{if(t.forceDefinedOrigin&&void 0===t.origin||t.forceDefinedTarget&&void 0===t.target)return!1;const i=void 0===t.origin?e:t.origin,s=void 0===t.target?e:t.target;return{"!==":(i||e)!==(s||e),"===":(i||e)===(s||e),"<":(i||e)<(s||e),">":(i||e)>(s||e),"<=":(i||e)<=(s||e),">=":(i||e)>=(s||e),"!!origin":!!String(i||e).trim().length}[t.condition]},$e=(e,t)=>{if(!t.conditions)return!1;let i={and:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.every(t=>ye(e,t)))},or:()=>{var i;return!!(null===(i=t.conditions)||void 0===i?void 0:i.set.some(t=>ye(e,t)))}}[t.conditions.rule]();return t.conditions.conditions&&(i="and"===t.conditions.rule?i&&$e(e,{conditions:t.conditions.conditions}):i||$e(e,{conditions:t.conditions.conditions})),!i},Ve={DDMMYYYY:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[0]}/${t[2]}`},YYYYMMDD:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[1]}/${t[2]}/${t[0]}`},YYYYDDMM:e=>{if(!e)return"";const t=e.split(e.includes("/")?"/":"-");return`${t[2]}/${t[1]}/${t[0]}`},MMDDYYYY:e=>e,timestamp:e=>new Date(e).toString()},je=(e,t)=>{var i;let s=!1;if(2!=(null===(i=t.betweenDates)||void 0===i?void 0:i.length))return!1;for(const i of t.betweenDates)if(Ee(e,{date:i})){s=!0;break}return s},Ee=(e,t)=>{var i,s,n,r,a,l,o,u,d,c,h,v;if(!(null===(s=null===(i=t.date)||void 0===i?void 0:i.target)||void 0===s?void 0:s.value)&&!(null===(r=null===(n=t.date)||void 0===n?void 0:n.origin)||void 0===r?void 0:r.intervals))return!1;const f=t.date.origin.value||e,p=Ve[null===(a=t.date)||void 0===a?void 0:a.origin.format](f).toString();let m=new Date(p),b=new Date,g=new Date;if((null===(o=null===(l=t.date)||void 0===l?void 0:l.target)||void 0===o?void 0:o.format)&&(g=new Date(Ve[null===(d=null===(u=t.date)||void 0===u?void 0:u.target)||void 0===d?void 0:d.format](t.date.target.value).toString()),b=g),t.date.origin.intervals){b=((e,t)=>{const i={years:(e,t)=>new Date(e.setUTCFullYear(e.getUTCFullYear()+t)),months:(e,t)=>new Date(e.setUTCMonth(e.getUTCMonth()+t)),days:(e,t)=>new Date(e.setDate(e.getUTCDate()+t))};return Object.keys(t).reduce((e,s)=>i[s](e,t[s]),new Date(e))})(m,t.date.origin.intervals);const e=new Date;(null===(c=t.date.target)||void 0===c?void 0:c.value)&&g&&(e.setDate(g.getDate()),e.setMonth(g.getMonth())),m=new Date(`${e.getUTCMonth()+1}/${e.getUTCDate()}/${e.getUTCFullYear()}`)}if(t.date.onlyValidDate&&(!(b instanceof Date&&isFinite(b))||!(b instanceof Date&&isFinite(m))||f.length<8))return!0;if(((e,t)=>{if(!e.includes("/")&&!e.includes("-")||!t)return!0;const i=e.replace(/[-/]/g,"");return!{DDMMYYYY:/^(\d{2})(\d{2})(\d{4})$/,YYYYMMDD:/^(\d{4})(\d{2})(\d{2})$/,YYYYDDMM:/^(\d{4})(\d{2})(\d{2})$/,MMDDYYYY:/^(\d{2})(\d{2})(\d{4})$/,DMYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/,YYYYMD:/^(\d{4})(\d{1,2})(\d{1,2})$/,YYYYDM:/^(\d{4})(\d{1,2})(\d{1,2})$/,MDYYYY:/^(\d{1,2})(\d{1,2})(\d{4})$/}[t].test(i)})(p,null===(h=t.date)||void 0===h?void 0:h.origin.format))return!1;const S=m.getTime(),y=b.getTime();return{">":S>y,">=":S>=y,"<":S<y,"<=":S<=y,"===":S===y,"!==":S!==y}[null===(v=t.date)||void 0===v?void 0:v.operator]},Ne=(e,t)=>{if(!t.validDate||!e)return!1;if(/[^a-zA-Z0-9\s-]/.test(e))return!0;const i=Ve[t.validDate](e).toString().split(/[/-]/),s=parseInt(i[2],10),n=parseInt(i[0],10)-1,r=parseInt(i[1],10),a=new Date(s,n,r),l=new Date;return l.setFullYear(l.getFullYear()-150),a.getFullYear()<l.getFullYear()||!(a.getFullYear()===s&&a.getMonth()===n&&a.getDate()===r)},xe={max:B,min:J,lessThan:G,greaterThan:W,length:z,regex:H,url:te,email:ee,onlyLetters:ie,notAllowSpaces:se,callback:le,hasNoExtraSpaces:re,between:K,sequential:X,includes:oe,repeated:ae,document:Q,isCreditCard:he,isCreditCodeMatch:ve,isCreditCardAndLength:fe,required:be,value:me,notEmpty:pe,bool:ge,exists:Se,isNumber:ne,conditions:$e,validDate:Ne,date:Ee,betweenDates:je},Oe={max:B,min:J,lessThan:G,greaterThan:W,length:z,regex:H,url:te,email:ee,onlyLetters:ie,notAllowSpaces:se,callback:le,hasNoExtraSpaces:re,between:K,sequential:X,includes:oe,repeated:ae,document:Q,isCreditCard:he,isCreditCodeMatch:ve,isCreditCardAndLength:fe,required:be,value:me,notEmpty:pe,bool:ge,exists:Se,isNumber:ne,conditions:$e,multipleValidations:(e,t)=>{if(!t.multipleValidations)return!1;const i=function(e,t){const i=[];return Object.keys(t).forEach(s=>{let n;n=M(xe[s])?xe[s](e,{[s]:t[s]}):R(e,t[s],xe),i.push(n)}),i}(e,t.multipleValidations.validations);return{AND:()=>i.every(e=>e),OR:()=>i.some(e=>e),NOT:()=>!i.every(e=>e)}[t.multipleValidations.rule]()},date:Ee,betweenDates:je,validDate:Ne};I(Oe);const Ie={capitalize:e=>String(e).charAt(0).toUpperCase()+String(e).slice(1),uppercase:e=>String(e).toUpperCase(),onlyNumbers:e=>String(e).replace(/(\D)+/gim,""),onlyLetters:e=>String(e).replace(/[^\p{L}\s]/gu,""),regex:(e,t)=>t.regex?String(e).replace(new RegExp(t.regex,"g"),""):e,splitter:(e,t)=>{if(!e||!t.splitter||"string"!=typeof e)return e;t.splitter.sort((e,t)=>e.position-t.position);let i=e,s=0;for(const e of t.splitter){const{position:t,value:n}=e,r=t+s;r>=0&&r<=i.length&&(i=i.slice(0,r)+n+i.slice(r),s+=n.length)}return i},maxLength:(e,t)=>{if(!e||!t.maxLength)return e;const i=String(e);return i.length>t.maxLength?i.substring(0,t.maxLength):e},onlyFloatNumber:(e,t)=>{const{onlyFloatNumber:i}=t;if(!i||"string"!=typeof e||!e)return e;const{precision:s=2,decimal:n="."}=i;if(!e.includes(n))return e;const r=e.replace(/[^0-9]/g,""),a=r.slice(0,r.length-s),l=r.slice(r.length-s);return parseFloat(`${a}.${l}`).toFixed(s)},trim:(e,t)=>!e||(null==t?void 0:t.trim)?e:String(e).trim(),gapsCreditCard:(e,t)=>{if(!t.gapsCreditCard)return e;const[i,s]=ue(e,null==t?void 0:t.gapsCreditCard);return((e,t)=>t?((e,t=[])=>{const[i,s]=t.reduce(([e,i],s,n)=>[`${e}([0-9]{0,${s-(t[n-1]||0)}})`,`${i}$${n+1} `],["",""]);return e.replace(new RegExp(i),s).trim()})(e.slice(0,null==t?void 0:t.lengths[0]),t.gaps):null==e?void 0:e.slice(0,19))(s,i)},callback:(e,t)=>(null==t?void 0:t.callback)?t.callback(e):e,dotEvery3chars:e=>{const t=String(e).replace(/\./g,"").replace(/(.{3})/g,"$1.");return t.endsWith(".")?t.slice(0,-1):t}};F(Ie);var Fe=(e,t)=>{if(!(null==t?void 0:t.generic))return e;let i=e;return t.generic.forEach(t=>{const{to:s=i.length,mask:n}=t;let{from:r}=t;if(s>e.length-1)return;0===r&&(r=1);const a=new Array(s-r+2).join(n);i=i.slice(0,r-1)+a+i.slice(s)}),i};const ke={currency:(e,t)=>{if(!(null==t?void 0:t.currency))return e;const{align:i="",decimal:s=".",precision:n=2,prefix:r="BBD",thousands:a=","}=t.currency;let l=(function(e){return"number"==typeof e||"object"==typeof e&&null!==e&&"[object Number]"===Object.prototype.toString.call(e)}(e)?Number(e).toFixed(n):e).replace(/[^0-9]/g,"");if(!l)return"";let o=l.slice(0,l.length-n).replace(/^0*/g,"").replace(/\B(?=(\d{3})+(?!\d))/g,a);""===o&&(o="0"),"right"===i&&String(e).endsWith(" ")&&(l=l.slice(0,-1));let u=o,d=l.slice(l.length-n);if(n>0&&(d="0".repeat(n-d.length)+d,u+=s+d),!i)return u;const c=h(r);return"left"===i?`${c} ${u}`:`${u} ${c}`},custom:(e,t)=>{if(!t.custom||!e)return e;let i="",s=0;const n=e.replace(/[^\w\s]/gi,"");for(const e of t.custom)if("#"===e){if(!(s<n.length))break;i+=n[s],s++}else s<=n.length&&(i+=e);return e.length<i.length&&(i=i.replace(/[^\w]+$/,"")),i},callback:(e,t)=>(null==t?void 0:t.callback)&&t.callback(e),generic:Fe,secureCreditCard:e=>Fe(e,{generic:[{from:1,to:4,mask:"x"},{from:6,to:9,mask:"x"},{from:11,to:14,mask:"x"},{from:16,to:19,mask:"x"}]}),card:e=>e.replace(/[^\dA-Z]/g,"").replace(/(.{4})/g,"$1 ").trim(),cardDate:e=>ce(e),fein:e=>ce(e,9,"-"),replaceAll:(e,t)=>{let i=t.replaceAll;return i?("number"==typeof i&&(i=null==i?void 0:i.toString()),new Array(String(e).length+1).join(i)):e}};k(ke);export{q as FormCore,Y as FormField,U as FormGroup,v as TMutationEnum,x as formatterRegistry,O as maskRegistry,F as registerFormatters,k as registerMasks,I as registerValidations,N as validationRegistry};