@visiion/forms-library 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,2840 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var React = require('react');
5
+
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
+
22
+
23
+ var __assign$1 = function() {
24
+ __assign$1 = Object.assign || function __assign(t) {
25
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
26
+ s = arguments[i];
27
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
28
+ }
29
+ return t;
30
+ };
31
+ return __assign$1.apply(this, arguments);
32
+ };
33
+
34
+ function __awaiter(thisArg, _arguments, P, generator) {
35
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
+ return new (P || (P = Promise))(function (resolve, reject) {
37
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
41
+ });
42
+ }
43
+
44
+ function __generator(thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ }
71
+
72
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
73
+ var e = new Error(message);
74
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
75
+ };
76
+
77
+ var DefaultContext = {
78
+ color: undefined,
79
+ size: undefined,
80
+ className: undefined,
81
+ style: undefined,
82
+ attr: undefined
83
+ };
84
+ var IconContext = React.createContext && React.createContext(DefaultContext);
85
+
86
+ var __assign = undefined && undefined.__assign || function () {
87
+ __assign = Object.assign || function (t) {
88
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
89
+ s = arguments[i];
90
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
91
+ }
92
+ return t;
93
+ };
94
+ return __assign.apply(this, arguments);
95
+ };
96
+ var __rest = undefined && undefined.__rest || function (s, e) {
97
+ var t = {};
98
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
99
+ if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
100
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
101
+ }
102
+ return t;
103
+ };
104
+ function Tree2Element(tree) {
105
+ return tree && tree.map(function (node, i) {
106
+ return React.createElement(node.tag, __assign({
107
+ key: i
108
+ }, node.attr), Tree2Element(node.child));
109
+ });
110
+ }
111
+ function GenIcon(data) {
112
+ // eslint-disable-next-line react/display-name
113
+ return function (props) {
114
+ return React.createElement(IconBase, __assign({
115
+ attr: __assign({}, data.attr)
116
+ }, props), Tree2Element(data.child));
117
+ };
118
+ }
119
+ function IconBase(props) {
120
+ var elem = function (conf) {
121
+ var attr = props.attr,
122
+ size = props.size,
123
+ title = props.title,
124
+ svgProps = __rest(props, ["attr", "size", "title"]);
125
+ var computedSize = size || conf.size || "1em";
126
+ var className;
127
+ if (conf.className) className = conf.className;
128
+ if (props.className) className = (className ? className + " " : "") + props.className;
129
+ return React.createElement("svg", __assign({
130
+ stroke: "currentColor",
131
+ fill: "currentColor",
132
+ strokeWidth: "0"
133
+ }, conf.attr, attr, svgProps, {
134
+ className: className,
135
+ style: __assign(__assign({
136
+ color: props.color || conf.color
137
+ }, conf.style), props.style),
138
+ height: computedSize,
139
+ width: computedSize,
140
+ xmlns: "http://www.w3.org/2000/svg"
141
+ }), title && React.createElement("title", null, title), props.children);
142
+ };
143
+ return IconContext !== undefined ? React.createElement(IconContext.Consumer, null, function (conf) {
144
+ return elem(conf);
145
+ }) : elem(DefaultContext);
146
+ }
147
+
148
+ // THIS FILE IS AUTO GENERATED
149
+ function IoHelpCircle (props) {
150
+ return GenIcon({"attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M256 64C150 64 64 150 64 256s86 192 192 192 192-86 192-192S362 64 256 64zm-6 304a20 20 0 1120-20 20 20 0 01-20 20zm33.44-102C267.23 276.88 265 286.85 265 296a14 14 0 01-28 0c0-21.91 10.08-39.33 30.82-53.26C287.1 229.8 298 221.6 298 203.57c0-12.26-7-21.57-21.49-28.46-3.41-1.62-11-3.2-20.34-3.09-11.72.15-20.82 2.95-27.83 8.59C215.12 191.25 214 202.83 214 203a14 14 0 11-28-1.35c.11-2.43 1.8-24.32 24.77-42.8 11.91-9.58 27.06-14.56 45-14.78 12.7-.15 24.63 2 32.72 5.82C312.7 161.34 326 180.43 326 203.57c0 33.83-22.61 49.02-42.56 62.43z"}}]})(props);
151
+ }
152
+
153
+ var InputWrapper = function (_a) {
154
+ var label = _a.label, error = _a.error, tooltip = _a.tooltip, required = _a.required, children = _a.children, _b = _a.className, className = _b === void 0 ? '' : _b;
155
+ return (jsxRuntime.jsxs("fieldset", { className: "flex max-w-1xl mx-auto flex-col gap-4 w-full ".concat(className), children: [label && (jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntime.jsxs("label", { className: "font-roboto font-medium text-gray-700 text-sm leading-4", children: [label, required && jsxRuntime.jsx("span", { className: "text-red-500 ml-1", children: "*" })] }), tooltip && (jsxRuntime.jsxs("div", { className: "relative group flex-shrink-0", children: [jsxRuntime.jsx(IoHelpCircle, { className: "w-5 h-5 text-gray-400 cursor-help" }), jsxRuntime.jsxs("div", { className: "absolute left-full top-1/2 transform -translate-y-1/2 ml-2 px-3 py-2 bg-gray-800 text-white text-sm rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-10", children: [tooltip, jsxRuntime.jsx("div", { className: "absolute top-1/2 right-full transform -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-800" })] })] }))] })), children, error && (jsxRuntime.jsx("p", { className: "text-red-500 text-xs mt-1", children: error }))] }));
156
+ };
157
+
158
+ var TextInput = function (_a) {
159
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
160
+ return (jsxRuntime.jsx(InputWrapper, { label: field.label, error: error, tooltip: field.tooltip, required: field.required, children: jsxRuntime.jsxs("div", { className: "relative", children: [jsxRuntime.jsx("input", { id: field.id, name: field.name, type: "text", placeholder: field.placeholder, value: value || '', onChange: onChange, disabled: field.disabled, required: field.required, minLength: field.minLength, maxLength: field.maxLength, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(field.disabled ? 'bg-gray-100 cursor-not-allowed' : '') }), field.addon && (jsxRuntime.jsx("span", { className: "absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm", children: field.addon }))] }) }));
161
+ };
162
+
163
+ var SelectInput = function (_a) {
164
+ var _b;
165
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
166
+ return (jsxRuntime.jsx(InputWrapper, { label: field.label, error: error, tooltip: field.tooltip, required: field.required, children: jsxRuntime.jsxs("select", { id: field.id, name: field.name, value: value || '', onChange: onChange, disabled: field.disabled, required: field.required, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(field.disabled ? 'bg-gray-100 cursor-not-allowed' : ''), children: [jsxRuntime.jsx("option", { value: "", children: field.placeholder || 'Seleccione una opción' }), Array.isArray(field === null || field === void 0 ? void 0 : field.options) &&
167
+ ((_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.map(function (option) { return (jsxRuntime.jsx("option", { value: option.value, children: option.label }, option.value)); }))] }) }));
168
+ };
169
+
170
+ var CheckboxInput = function (_a) {
171
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
172
+ return (jsxRuntime.jsxs("div", { className: "flex flex-col gap-2", children: [jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [jsxRuntime.jsx("input", { id: field.id, name: field.name, type: "checkbox", checked: value || false, onChange: onChange, disabled: field.disabled, required: field.required, className: "w-4 h-4 text-orange-600 border-gray-300 rounded focus:ring-orange-500" }), jsxRuntime.jsxs("label", { htmlFor: field.id, className: "font-medium text-gray-700 cursor-pointer", children: [field.label, field.required && jsxRuntime.jsx("span", { className: "text-red-500 ml-1", children: "*" })] })] }), error && jsxRuntime.jsx("span", { className: "text-red-500 text-xs", children: error })] }));
173
+ };
174
+
175
+ var TextareaInput = function (_a) {
176
+ var field = _a.field, _b = _a.value, value = _b === void 0 ? '' : _b, onChange = _a.onChange, error = _a.error, id = _a.id, name = _a.name, label = _a.label, placeholder = _a.placeholder, className = _a.className, disabled = _a.disabled, required = _a.required, _c = _a.maxLength, maxLength = _c === void 0 ? 500 : _c, _d = _a.rows, rows = _d === void 0 ? 4 : _d, tooltip = _a.tooltip;
177
+ var _e = React.useState(value.length), charCount = _e[0], setCharCount = _e[1];
178
+ // Si se pasa un field, usar sus propiedades
179
+ var finalId = id || (field === null || field === void 0 ? void 0 : field.id);
180
+ var finalName = name || (field === null || field === void 0 ? void 0 : field.name);
181
+ var finalLabel = label || (field === null || field === void 0 ? void 0 : field.label);
182
+ var finalPlaceholder = placeholder || (field === null || field === void 0 ? void 0 : field.placeholder);
183
+ var finalDisabled = disabled !== undefined ? disabled : field === null || field === void 0 ? void 0 : field.disabled;
184
+ var finalRequired = required !== undefined ? required : field === null || field === void 0 ? void 0 : field.required;
185
+ var finalMaxLength = maxLength || (field === null || field === void 0 ? void 0 : field.maxLength) || 500;
186
+ var finalTooltip = tooltip || (field === null || field === void 0 ? void 0 : field.tooltip);
187
+ React.useEffect(function () {
188
+ setCharCount(value.length);
189
+ }, [value]);
190
+ var handleChange = function (e) {
191
+ var newValue = e.target.value;
192
+ if (newValue.length <= finalMaxLength) {
193
+ setCharCount(newValue.length);
194
+ if (onChange) {
195
+ // Crear un evento sintético compatible
196
+ var syntheticEvent = __assign$1(__assign$1({}, e), { target: __assign$1(__assign$1({}, e.target), { name: finalName || '', value: newValue }) });
197
+ onChange(syntheticEvent);
198
+ }
199
+ }
200
+ };
201
+ return (jsxRuntime.jsx(InputWrapper, { label: finalLabel, tooltip: finalTooltip, required: finalRequired, error: error, children: jsxRuntime.jsxs("div", { className: "space-y-2", children: [jsxRuntime.jsx("textarea", { id: finalId, name: finalName, placeholder: finalPlaceholder, value: value, onChange: handleChange, disabled: finalDisabled, required: finalRequired, rows: rows, className: "w-full px-3 py-2 font-roboto font-normal text-gray-800 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 resize-none ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(finalDisabled ? 'bg-gray-100 cursor-not-allowed' : '', " ").concat(className || '') }), jsxRuntime.jsxs("div", { className: "flex justify-end text-gray-400 text-sm", children: [charCount, "/", finalMaxLength] })] }) }));
202
+ };
203
+
204
+ function clean(rut) {
205
+ return typeof rut === 'string' ? rut.replace(/^0+|[^0-9kK]+/g, '').toUpperCase() : '';
206
+ }
207
+ function formatRut(rut) {
208
+ rut = clean(rut);
209
+ var result = '';
210
+ if (rut.length > 0) {
211
+ result = "".concat(rut.slice(-4, -1), "-").concat(rut.substr(rut.length - 1));
212
+ }
213
+ for (var i = 4; i < rut.length; i += 3) {
214
+ result = "".concat(rut.slice(-3 - i, -i), ".").concat(result);
215
+ }
216
+ return result;
217
+ }
218
+ var serialRegex = /^[a-zA-Z0-9]+$/;
219
+ var validateOnlyNumbersAndLetters = function (value) {
220
+ if (value === '')
221
+ return true;
222
+ return serialRegex.test(value);
223
+ };
224
+ function validate(rut) {
225
+ if (typeof rut !== 'string') {
226
+ return false;
227
+ }
228
+ if (!/^0*(\d{1,3}(\.?\d{3})*)-?([\dkK])$/.test(rut)) {
229
+ return false;
230
+ }
231
+ rut = clean(rut);
232
+ var t = parseInt(rut.slice(0, -1), 10);
233
+ var m = 0;
234
+ var s = 1;
235
+ while (t > 0) {
236
+ // eslint-disable-next-line
237
+ s = (s + (t % 10) * (9 - (m++ % 6))) % 11;
238
+ t = Math.floor(t / 10);
239
+ }
240
+ var v = s > 0 ? "".concat(s - 1) : 'k';
241
+ return v.toLowerCase() === rut.slice(-1).toLowerCase();
242
+ }
243
+ /**
244
+ * Enmascara un RUT ocultando los dígitos del medio
245
+ * @param rut - RUT formateado (ej: "19.178.946-6")
246
+ * @returns RUT enmascarado (ej: "19.178.XXX-6")
247
+ */
248
+ function maskRut(rut) {
249
+ if (!rut || typeof rut !== 'string') {
250
+ return '';
251
+ }
252
+ // Limpiar el RUT para obtener solo números y dígito verificador
253
+ var cleanRut = clean(rut);
254
+ if (cleanRut.length < 2) {
255
+ return rut;
256
+ }
257
+ // Separar el dígito verificador
258
+ var numbers = cleanRut.slice(0, -1);
259
+ // Si el RUT tiene menos de 4 dígitos, no enmascarar
260
+ if (numbers.length < 4) {
261
+ return formatRut(cleanRut);
262
+ }
263
+ // Mantener la estructura completa pero enmascarar los dígitos del medio
264
+ var maskedRut = '';
265
+ if (numbers.length <= 3) {
266
+ // Para RUTs de 3 dígitos o menos
267
+ maskedRut = "".concat(numbers, "XXX-X");
268
+ }
269
+ else if (numbers.length <= 6) {
270
+ // Para RUTs de 4-6 dígitos: XX.XXX-X
271
+ var firstPart = numbers.slice(0, 2);
272
+ maskedRut = "".concat(firstPart, ".XXX-X");
273
+ }
274
+ else if (numbers.length === 7) {
275
+ // Para RUTs de 7 dígitos: X.XXX.XXX-X
276
+ var firstPart = numbers.slice(0, 1);
277
+ var secondPart = numbers.slice(1, 4);
278
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
279
+ }
280
+ else if (numbers.length === 8) {
281
+ // Para RUTs de 8 dígitos: XX.XXX.XXX-X
282
+ var firstPart = numbers.slice(0, 2);
283
+ var secondPart = numbers.slice(2, 5);
284
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
285
+ }
286
+ else if (numbers.length <= 9) {
287
+ // Para RUTs de 9 dígitos: XXX.XXX-X
288
+ var firstPart = numbers.slice(0, 3);
289
+ maskedRut = "".concat(firstPart, ".XXX-X");
290
+ }
291
+ else {
292
+ // Para RUTs de más de 9 dígitos: XX.XXX.XXX-X
293
+ var firstPart = numbers.slice(0, 2);
294
+ var secondPart = numbers.slice(2, 5);
295
+ maskedRut = "".concat(firstPart, ".").concat(secondPart, ".XXX-X");
296
+ }
297
+ return maskedRut;
298
+ }
299
+
300
+ var RutInput = function (_a) {
301
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error, onSearch = _a.onSearch, _b = _a.disabled, disabled = _b === void 0 ? false : _b, _c = _a.placeholder, placeholder = _c === void 0 ? '0.000.000-0' : _c, _d = _a.minLength, minLength = _d === void 0 ? 12 : _d, _e = _a.maxLength, maxLength = _e === void 0 ? 12 : _e;
302
+ var inputRef = React.useRef(null);
303
+ var _f = React.useState(false), isValidRut = _f[0], setIsValidRut = _f[1];
304
+ var _g = React.useState(clean(value)), displayValue = _g[0], setDisplayValue = _g[1];
305
+ React.useEffect(function () {
306
+ setIsValidRut(validate(clean(value)));
307
+ setDisplayValue(formatRut(clean(value)));
308
+ }, [value]);
309
+ // Validar RUT en tiempo real
310
+ var handleRutChange = function (e) {
311
+ var rutValue = e.target.value;
312
+ setIsValidRut(validate(clean(rutValue)));
313
+ onChange(e);
314
+ };
315
+ // Manejar búsqueda
316
+ var handleSearch = function () {
317
+ if (onSearch && value && isValidRut) {
318
+ onSearch(clean(displayValue));
319
+ }
320
+ };
321
+ // Manejar tecla Enter para búsqueda
322
+ var handleKeyDown = function (e) {
323
+ if (e.key === 'Enter' && onSearch && value && isValidRut) {
324
+ e.preventDefault();
325
+ onSearch(clean(displayValue));
326
+ }
327
+ };
328
+ return (jsxRuntime.jsxs(InputWrapper, { label: field.label, tooltip: field.tooltip, required: field.required, error: error, children: [jsxRuntime.jsxs("div", { className: "flex", children: [jsxRuntime.jsx("input", { ref: inputRef, id: field.id, name: field.name, type: "text", value: displayValue || '', onChange: handleRutChange, onKeyDown: handleKeyDown, placeholder: placeholder, minLength: minLength, maxLength: maxLength, disabled: disabled, className: "flex-1 px-3 py-2 border rounded-l-md focus:outline-none focus:ring-2 focus:ring-orange-500 h-10 ".concat(error ? 'border-red-500' : 'border-gray-300', " ").concat(disabled ? 'bg-gray-100 cursor-not-allowed' : '') }), onSearch && (jsxRuntime.jsx("button", { type: "button", onClick: handleSearch, disabled: !isValidRut || disabled, className: "flex items-center justify-center w-10 h-10 rounded-r-md border-l-0 border bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed ".concat(error ? 'border-red-500' : 'border-gray-300'), children: jsxRuntime.jsx("svg", { className: "w-5 h-5", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" }) }) }))] }), displayValue && !error && (jsxRuntime.jsx("span", { className: "text-sm ".concat(isValidRut ? 'text-green-600' : 'text-orange-600'), children: isValidRut ? '✓ RUT válido' : '⚠ Verificar formato del RUT' }))] }));
329
+ };
330
+
331
+ var Alert = function (_a) {
332
+ var _b = _a.type, type = _b === void 0 ? 'info' : _b, text = _a.text, icon = _a.icon, _c = _a.className, className = _c === void 0 ? '' : _c, _d = _a.iconClassName, iconClassName = _d === void 0 ? 'w-5 h-5' : _d, _e = _a.textClassName, textClassName = _e === void 0 ? 'ml-2 text-sm' : _e;
333
+ var getAlertStyles = function () {
334
+ switch (type) {
335
+ case 'info':
336
+ return 'bg-blue-50 border-blue-200 text-blue-800';
337
+ case 'warning':
338
+ return 'bg-yellow-50 border-yellow-200 text-yellow-800';
339
+ case 'error':
340
+ return 'bg-red-50 border-red-200 text-red-800';
341
+ default:
342
+ return 'bg-blue-50 border-blue-200 text-blue-800';
343
+ }
344
+ };
345
+ var getIcon = function () {
346
+ if (icon) {
347
+ if (typeof icon === 'string') {
348
+ return (jsxRuntime.jsx("span", { className: iconClassName, dangerouslySetInnerHTML: { __html: icon } }));
349
+ }
350
+ return React.createElement(icon, { className: iconClassName });
351
+ }
352
+ // Iconos por defecto
353
+ switch (type) {
354
+ case 'info':
355
+ return (jsxRuntime.jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsxRuntime.jsx("path", { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z", clipRule: "evenodd" }) }));
356
+ case 'warning':
357
+ return (jsxRuntime.jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsxRuntime.jsx("path", { fillRule: "evenodd", d: "M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z", clipRule: "evenodd" }) }));
358
+ case 'error':
359
+ return (jsxRuntime.jsx("svg", { className: iconClassName, fill: "currentColor", viewBox: "0 0 20 20", children: jsxRuntime.jsx("path", { fillRule: "evenodd", d: "M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z", clipRule: "evenodd" }) }));
360
+ default:
361
+ return null;
362
+ }
363
+ };
364
+ return (jsxRuntime.jsxs("div", { className: "flex items-center p-4 border rounded-lg ".concat(getAlertStyles(), " ").concat(className), children: [getIcon(), jsxRuntime.jsx("span", { className: textClassName, dangerouslySetInnerHTML: { __html: text || '' } })] }));
365
+ };
366
+
367
+ var DynamicInput = function (_a) {
368
+ var _b, _c;
369
+ var field = _a.field, value = _a.value, onChange = _a.onChange, error = _a.error;
370
+ switch (field.type) {
371
+ case 'select':
372
+ return (jsxRuntime.jsx(SelectInput, { field: field, value: value, onChange: onChange, error: error }));
373
+ case 'textarea':
374
+ return (jsxRuntime.jsx(TextareaInput, { field: field, value: value, onChange: onChange, error: error }));
375
+ case 'checkbox':
376
+ return (jsxRuntime.jsx(CheckboxInput, { field: field, value: value, onChange: onChange, error: error }));
377
+ case 'rut':
378
+ return (jsxRuntime.jsx(RutInput, { field: field, value: value, onChange: onChange, error: error, onSearch: field.onSearch, disabled: field.disabled, placeholder: field.placeholder, minLength: field.minLength, maxLength: field.maxLength }));
379
+ case 'alert':
380
+ return jsxRuntime.jsx(Alert, __assign$1({}, field.props));
381
+ case 'subtitle':
382
+ return (jsxRuntime.jsxs("div", { className: "col-span-12", children: [jsxRuntime.jsx("h3", { className: "text-xl font-bold text-gray-800 mb-2", children: ((_b = field.props) === null || _b === void 0 ? void 0 : _b.title) || field.label }), ((_c = field.props) === null || _c === void 0 ? void 0 : _c.description) && (jsxRuntime.jsx("p", { className: "text-gray-600", children: field.props.description }))] }));
383
+ case 'text':
384
+ default:
385
+ return (jsxRuntime.jsx(TextInput, { field: field, value: value, onChange: onChange, error: error }));
386
+ }
387
+ };
388
+
389
+ var NavigationButton = function (_a) {
390
+ var direction = _a.direction, onClick = _a.onClick, _b = _a.disabled, disabled = _b === void 0 ? false : _b, _c = _a.label, label = _c === void 0 ? '' : _c;
391
+ var getButtonProps = function () {
392
+ switch (direction) {
393
+ case 'default':
394
+ return {
395
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
396
+ label: label || 'Volver',
397
+ };
398
+ case 'next':
399
+ return {
400
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
401
+ label: label || 'Siguiente',
402
+ icon: (jsxRuntime.jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5l7 7-7 7" }) })),
403
+ };
404
+ case 'back':
405
+ return {
406
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
407
+ label: label || 'Volver',
408
+ icon: (jsxRuntime.jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M15 19l-7-7 7-7" }) })),
409
+ };
410
+ case 'guardar':
411
+ return {
412
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
413
+ label: label || 'Guardar',
414
+ icon: (jsxRuntime.jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" }) })),
415
+ };
416
+ case 'success':
417
+ return {
418
+ className: "flex items-center align-middle text-nowrap disabled:bg-gray-400 min-w-40 h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] bg-green-600 text-white hover:bg-green-700 disabled:cursor-not-allowed",
419
+ label: label,
420
+ icon: null,
421
+ };
422
+ case 'out-light':
423
+ return {
424
+ className: "flex items-center align-middle text-nowrap w-fit h-[40px] px-4 py-2 bg-white text-[16px] rounded border border-blue-600 text-blue-600 font-medium font-['Roboto'] hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed",
425
+ label: label || 'Salir',
426
+ icon: (jsxRuntime.jsx("svg", { className: "mr-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" }) })),
427
+ };
428
+ case 'out':
429
+ return {
430
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
431
+ label: 'Salir',
432
+ icon: (jsxRuntime.jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" }) })),
433
+ };
434
+ default:
435
+ return {
436
+ className: "flex items-center align-middle text-nowrap bg-blue-600 disabled:bg-gray-400 w-fit h-[40px] px-4 py-2 rounded border text-lg font-medium font-['Roboto'] text-white hover:bg-blue-700 disabled:cursor-not-allowed",
437
+ label: label || 'Siguiente',
438
+ icon: (jsxRuntime.jsx("svg", { className: "ml-2 h-4 w-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntime.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5l7 7-7 7" }) })),
439
+ };
440
+ }
441
+ };
442
+ var _d = getButtonProps(), className = _d.className, buttonLabel = _d.label, icon = _d.icon;
443
+ return (jsxRuntime.jsxs("button", { onClick: onClick, disabled: disabled, className: className, children: [(direction === 'back' || direction === 'out-light' || direction === 'guardar') && icon, buttonLabel, (direction === 'next' || direction === 'out') && icon] }));
444
+ };
445
+
446
+ function getDefaultExportFromCjs (x) {
447
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
448
+ }
449
+
450
+ /**
451
+ * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>
452
+ */
453
+
454
+ function Cache(maxSize) {
455
+ this._maxSize = maxSize;
456
+ this.clear();
457
+ }
458
+ Cache.prototype.clear = function () {
459
+ this._size = 0;
460
+ this._values = Object.create(null);
461
+ };
462
+ Cache.prototype.get = function (key) {
463
+ return this._values[key]
464
+ };
465
+ Cache.prototype.set = function (key, value) {
466
+ this._size >= this._maxSize && this.clear();
467
+ if (!(key in this._values)) this._size++;
468
+
469
+ return (this._values[key] = value)
470
+ };
471
+
472
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,
473
+ DIGIT_REGEX = /^\d+$/,
474
+ LEAD_DIGIT_REGEX = /^\d/,
475
+ SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,
476
+ CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,
477
+ MAX_CACHE_SIZE = 512;
478
+
479
+ var pathCache = new Cache(MAX_CACHE_SIZE),
480
+ setCache = new Cache(MAX_CACHE_SIZE),
481
+ getCache = new Cache(MAX_CACHE_SIZE);
482
+
483
+ var propertyExpr = {
484
+ Cache: Cache,
485
+
486
+ split: split,
487
+
488
+ normalizePath: normalizePath,
489
+
490
+ setter: function (path) {
491
+ var parts = normalizePath(path);
492
+
493
+ return (
494
+ setCache.get(path) ||
495
+ setCache.set(path, function setter(obj, value) {
496
+ var index = 0;
497
+ var len = parts.length;
498
+ var data = obj;
499
+
500
+ while (index < len - 1) {
501
+ var part = parts[index];
502
+ if (
503
+ part === '__proto__' ||
504
+ part === 'constructor' ||
505
+ part === 'prototype'
506
+ ) {
507
+ return obj
508
+ }
509
+
510
+ data = data[parts[index++]];
511
+ }
512
+ data[parts[index]] = value;
513
+ })
514
+ )
515
+ },
516
+
517
+ getter: function (path, safe) {
518
+ var parts = normalizePath(path);
519
+ return (
520
+ getCache.get(path) ||
521
+ getCache.set(path, function getter(data) {
522
+ var index = 0,
523
+ len = parts.length;
524
+ while (index < len) {
525
+ if (data != null || !safe) data = data[parts[index++]];
526
+ else return
527
+ }
528
+ return data
529
+ })
530
+ )
531
+ },
532
+
533
+ join: function (segments) {
534
+ return segments.reduce(function (path, part) {
535
+ return (
536
+ path +
537
+ (isQuoted(part) || DIGIT_REGEX.test(part)
538
+ ? '[' + part + ']'
539
+ : (path ? '.' : '') + part)
540
+ )
541
+ }, '')
542
+ },
543
+
544
+ forEach: function (path, cb, thisArg) {
545
+ forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
546
+ },
547
+ };
548
+
549
+ function normalizePath(path) {
550
+ return (
551
+ pathCache.get(path) ||
552
+ pathCache.set(
553
+ path,
554
+ split(path).map(function (part) {
555
+ return part.replace(CLEAN_QUOTES_REGEX, '$2')
556
+ })
557
+ )
558
+ )
559
+ }
560
+
561
+ function split(path) {
562
+ return path.match(SPLIT_REGEX) || ['']
563
+ }
564
+
565
+ function forEach(parts, iter, thisArg) {
566
+ var len = parts.length,
567
+ part,
568
+ idx,
569
+ isArray,
570
+ isBracket;
571
+
572
+ for (idx = 0; idx < len; idx++) {
573
+ part = parts[idx];
574
+
575
+ if (part) {
576
+ if (shouldBeQuoted(part)) {
577
+ part = '"' + part + '"';
578
+ }
579
+
580
+ isBracket = isQuoted(part);
581
+ isArray = !isBracket && /^\d+$/.test(part);
582
+
583
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
584
+ }
585
+ }
586
+ }
587
+
588
+ function isQuoted(str) {
589
+ return (
590
+ typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1
591
+ )
592
+ }
593
+
594
+ function hasLeadingNumber(part) {
595
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)
596
+ }
597
+
598
+ function hasSpecialChars(part) {
599
+ return SPEC_CHAR_REGEX.test(part)
600
+ }
601
+
602
+ function shouldBeQuoted(part) {
603
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))
604
+ }
605
+
606
+ const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
607
+
608
+ const words = (str) => str.match(reWords) || [];
609
+
610
+ const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
611
+
612
+ const join = (str, d) => words(str).join(d).toLowerCase();
613
+
614
+ const camelCase = (str) =>
615
+ words(str).reduce(
616
+ (acc, next) =>
617
+ `${acc}${
618
+ !acc
619
+ ? next.toLowerCase()
620
+ : next[0].toUpperCase() + next.slice(1).toLowerCase()
621
+ }`,
622
+ '',
623
+ );
624
+
625
+ const pascalCase = (str) => upperFirst(camelCase(str));
626
+
627
+ const snakeCase = (str) => join(str, '_');
628
+
629
+ const kebabCase = (str) => join(str, '-');
630
+
631
+ const sentenceCase = (str) => upperFirst(join(str, ' '));
632
+
633
+ const titleCase = (str) => words(str).map(upperFirst).join(' ');
634
+
635
+ var tinyCase = {
636
+ words,
637
+ upperFirst,
638
+ camelCase,
639
+ pascalCase,
640
+ snakeCase,
641
+ kebabCase,
642
+ sentenceCase,
643
+ titleCase,
644
+ };
645
+
646
+ var toposort$2 = {exports: {}};
647
+
648
+ /**
649
+ * Topological sorting function
650
+ *
651
+ * @param {Array} edges
652
+ * @returns {Array}
653
+ */
654
+
655
+ toposort$2.exports = function(edges) {
656
+ return toposort(uniqueNodes(edges), edges)
657
+ };
658
+
659
+ toposort$2.exports.array = toposort;
660
+
661
+ function toposort(nodes, edges) {
662
+ var cursor = nodes.length
663
+ , sorted = new Array(cursor)
664
+ , visited = {}
665
+ , i = cursor
666
+ // Better data structures make algorithm much faster.
667
+ , outgoingEdges = makeOutgoingEdges(edges)
668
+ , nodesHash = makeNodesHash(nodes);
669
+
670
+ // check for unknown nodes
671
+ edges.forEach(function(edge) {
672
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
673
+ throw new Error('Unknown node. There is an unknown node in the supplied edges.')
674
+ }
675
+ });
676
+
677
+ while (i--) {
678
+ if (!visited[i]) visit(nodes[i], i, new Set());
679
+ }
680
+
681
+ return sorted
682
+
683
+ function visit(node, i, predecessors) {
684
+ if(predecessors.has(node)) {
685
+ var nodeRep;
686
+ try {
687
+ nodeRep = ", node was:" + JSON.stringify(node);
688
+ } catch(e) {
689
+ nodeRep = "";
690
+ }
691
+ throw new Error('Cyclic dependency' + nodeRep)
692
+ }
693
+
694
+ if (!nodesHash.has(node)) {
695
+ throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))
696
+ }
697
+
698
+ if (visited[i]) return;
699
+ visited[i] = true;
700
+
701
+ var outgoing = outgoingEdges.get(node) || new Set();
702
+ outgoing = Array.from(outgoing);
703
+
704
+ if (i = outgoing.length) {
705
+ predecessors.add(node);
706
+ do {
707
+ var child = outgoing[--i];
708
+ visit(child, nodesHash.get(child), predecessors);
709
+ } while (i)
710
+ predecessors.delete(node);
711
+ }
712
+
713
+ sorted[--cursor] = node;
714
+ }
715
+ }
716
+
717
+ function uniqueNodes(arr){
718
+ var res = new Set();
719
+ for (var i = 0, len = arr.length; i < len; i++) {
720
+ var edge = arr[i];
721
+ res.add(edge[0]);
722
+ res.add(edge[1]);
723
+ }
724
+ return Array.from(res)
725
+ }
726
+
727
+ function makeOutgoingEdges(arr){
728
+ var edges = new Map();
729
+ for (var i = 0, len = arr.length; i < len; i++) {
730
+ var edge = arr[i];
731
+ if (!edges.has(edge[0])) edges.set(edge[0], new Set());
732
+ if (!edges.has(edge[1])) edges.set(edge[1], new Set());
733
+ edges.get(edge[0]).add(edge[1]);
734
+ }
735
+ return edges
736
+ }
737
+
738
+ function makeNodesHash(arr){
739
+ var res = new Map();
740
+ for (var i = 0, len = arr.length; i < len; i++) {
741
+ res.set(arr[i], i);
742
+ }
743
+ return res
744
+ }
745
+
746
+ var toposortExports = toposort$2.exports;
747
+ var toposort$1 = /*@__PURE__*/getDefaultExportFromCjs(toposortExports);
748
+
749
+ const toString = Object.prototype.toString;
750
+ const errorToString = Error.prototype.toString;
751
+ const regExpToString = RegExp.prototype.toString;
752
+ const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';
753
+ const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
754
+ function printNumber(val) {
755
+ if (val != +val) return 'NaN';
756
+ const isNegativeZero = val === 0 && 1 / val < 0;
757
+ return isNegativeZero ? '-0' : '' + val;
758
+ }
759
+ function printSimpleValue(val, quoteStrings = false) {
760
+ if (val == null || val === true || val === false) return '' + val;
761
+ const typeOf = typeof val;
762
+ if (typeOf === 'number') return printNumber(val);
763
+ if (typeOf === 'string') return quoteStrings ? `"${val}"` : val;
764
+ if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';
765
+ if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
766
+ const tag = toString.call(val).slice(8, -1);
767
+ if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);
768
+ if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';
769
+ if (tag === 'RegExp') return regExpToString.call(val);
770
+ return null;
771
+ }
772
+ function printValue(value, quoteStrings) {
773
+ let result = printSimpleValue(value, quoteStrings);
774
+ if (result !== null) return result;
775
+ return JSON.stringify(value, function (key, value) {
776
+ let result = printSimpleValue(this[key], quoteStrings);
777
+ if (result !== null) return result;
778
+ return value;
779
+ }, 2);
780
+ }
781
+
782
+ function toArray(value) {
783
+ return value == null ? [] : [].concat(value);
784
+ }
785
+
786
+ let _Symbol$toStringTag, _Symbol$hasInstance, _Symbol$toStringTag2;
787
+ let strReg = /\$\{\s*(\w+)\s*\}/g;
788
+ _Symbol$toStringTag = Symbol.toStringTag;
789
+ class ValidationErrorNoStack {
790
+ constructor(errorOrErrors, value, field, type) {
791
+ this.name = void 0;
792
+ this.message = void 0;
793
+ this.value = void 0;
794
+ this.path = void 0;
795
+ this.type = void 0;
796
+ this.params = void 0;
797
+ this.errors = void 0;
798
+ this.inner = void 0;
799
+ this[_Symbol$toStringTag] = 'Error';
800
+ this.name = 'ValidationError';
801
+ this.value = value;
802
+ this.path = field;
803
+ this.type = type;
804
+ this.errors = [];
805
+ this.inner = [];
806
+ toArray(errorOrErrors).forEach(err => {
807
+ if (ValidationError.isError(err)) {
808
+ this.errors.push(...err.errors);
809
+ const innerErrors = err.inner.length ? err.inner : [err];
810
+ this.inner.push(...innerErrors);
811
+ } else {
812
+ this.errors.push(err);
813
+ }
814
+ });
815
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
816
+ }
817
+ }
818
+ _Symbol$hasInstance = Symbol.hasInstance;
819
+ _Symbol$toStringTag2 = Symbol.toStringTag;
820
+ class ValidationError extends Error {
821
+ static formatError(message, params) {
822
+ // Attempt to make the path more friendly for error message interpolation.
823
+ const path = params.label || params.path || 'this';
824
+ // Store the original path under `originalPath` so it isn't lost to custom
825
+ // message functions; e.g., ones provided in `setLocale()` calls.
826
+ params = Object.assign({}, params, {
827
+ path,
828
+ originalPath: params.path
829
+ });
830
+ if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));
831
+ if (typeof message === 'function') return message(params);
832
+ return message;
833
+ }
834
+ static isError(err) {
835
+ return err && err.name === 'ValidationError';
836
+ }
837
+ constructor(errorOrErrors, value, field, type, disableStack) {
838
+ const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);
839
+ if (disableStack) {
840
+ return errorNoStack;
841
+ }
842
+ super();
843
+ this.value = void 0;
844
+ this.path = void 0;
845
+ this.type = void 0;
846
+ this.params = void 0;
847
+ this.errors = [];
848
+ this.inner = [];
849
+ this[_Symbol$toStringTag2] = 'Error';
850
+ this.name = errorNoStack.name;
851
+ this.message = errorNoStack.message;
852
+ this.type = errorNoStack.type;
853
+ this.value = errorNoStack.value;
854
+ this.path = errorNoStack.path;
855
+ this.errors = errorNoStack.errors;
856
+ this.inner = errorNoStack.inner;
857
+ if (Error.captureStackTrace) {
858
+ Error.captureStackTrace(this, ValidationError);
859
+ }
860
+ }
861
+ static [_Symbol$hasInstance](inst) {
862
+ return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);
863
+ }
864
+ }
865
+
866
+ let mixed = {
867
+ default: '${path} is invalid',
868
+ required: '${path} is a required field',
869
+ defined: '${path} must be defined',
870
+ notNull: '${path} cannot be null',
871
+ oneOf: '${path} must be one of the following values: ${values}',
872
+ notOneOf: '${path} must not be one of the following values: ${values}',
873
+ notType: ({
874
+ path,
875
+ type,
876
+ value,
877
+ originalValue
878
+ }) => {
879
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.';
880
+ return type !== 'mixed' ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg;
881
+ }
882
+ };
883
+ let string = {
884
+ length: '${path} must be exactly ${length} characters',
885
+ min: '${path} must be at least ${min} characters',
886
+ max: '${path} must be at most ${max} characters',
887
+ matches: '${path} must match the following: "${regex}"',
888
+ email: '${path} must be a valid email',
889
+ url: '${path} must be a valid URL',
890
+ uuid: '${path} must be a valid UUID',
891
+ datetime: '${path} must be a valid ISO date-time',
892
+ datetime_precision: '${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits',
893
+ datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone',
894
+ trim: '${path} must be a trimmed string',
895
+ lowercase: '${path} must be a lowercase string',
896
+ uppercase: '${path} must be a upper case string'
897
+ };
898
+ let number = {
899
+ min: '${path} must be greater than or equal to ${min}',
900
+ max: '${path} must be less than or equal to ${max}',
901
+ lessThan: '${path} must be less than ${less}',
902
+ moreThan: '${path} must be greater than ${more}',
903
+ positive: '${path} must be a positive number',
904
+ negative: '${path} must be a negative number',
905
+ integer: '${path} must be an integer'
906
+ };
907
+ let date = {
908
+ min: '${path} field must be later than ${min}',
909
+ max: '${path} field must be at earlier than ${max}'
910
+ };
911
+ let boolean = {
912
+ isValue: '${path} field must be ${value}'
913
+ };
914
+ let object = {
915
+ noUnknown: '${path} field has unspecified keys: ${unknown}',
916
+ exact: '${path} object contains unknown properties: ${properties}'
917
+ };
918
+ let array = {
919
+ min: '${path} field must have at least ${min} items',
920
+ max: '${path} field must have less than or equal to ${max} items',
921
+ length: '${path} must have ${length} items'
922
+ };
923
+ let tuple = {
924
+ notType: params => {
925
+ const {
926
+ path,
927
+ value,
928
+ spec
929
+ } = params;
930
+ const typeLen = spec.types.length;
931
+ if (Array.isArray(value)) {
932
+ if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
933
+ if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
934
+ }
935
+ return ValidationError.formatError(mixed.notType, params);
936
+ }
937
+ };
938
+ Object.assign(Object.create(null), {
939
+ mixed,
940
+ string,
941
+ number,
942
+ date,
943
+ object,
944
+ array,
945
+ boolean,
946
+ tuple
947
+ });
948
+
949
+ const isSchema = obj => obj && obj.__isYupSchema__;
950
+
951
+ class Condition {
952
+ static fromOptions(refs, config) {
953
+ if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
954
+ let {
955
+ is,
956
+ then,
957
+ otherwise
958
+ } = config;
959
+ let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);
960
+ return new Condition(refs, (values, schema) => {
961
+ var _branch;
962
+ let branch = check(...values) ? then : otherwise;
963
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
964
+ });
965
+ }
966
+ constructor(refs, builder) {
967
+ this.fn = void 0;
968
+ this.refs = refs;
969
+ this.refs = refs;
970
+ this.fn = builder;
971
+ }
972
+ resolve(base, options) {
973
+ let values = this.refs.map(ref =>
974
+ // TODO: ? operator here?
975
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));
976
+ let schema = this.fn(values, base, options);
977
+ if (schema === undefined ||
978
+ // @ts-ignore this can be base
979
+ schema === base) {
980
+ return base;
981
+ }
982
+ if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
983
+ return schema.resolve(options);
984
+ }
985
+ }
986
+
987
+ const prefixes = {
988
+ context: '$',
989
+ value: '.'
990
+ };
991
+ class Reference {
992
+ constructor(key, options = {}) {
993
+ this.key = void 0;
994
+ this.isContext = void 0;
995
+ this.isValue = void 0;
996
+ this.isSibling = void 0;
997
+ this.path = void 0;
998
+ this.getter = void 0;
999
+ this.map = void 0;
1000
+ if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);
1001
+ this.key = key.trim();
1002
+ if (key === '') throw new TypeError('ref must be a non-empty string');
1003
+ this.isContext = this.key[0] === prefixes.context;
1004
+ this.isValue = this.key[0] === prefixes.value;
1005
+ this.isSibling = !this.isContext && !this.isValue;
1006
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';
1007
+ this.path = this.key.slice(prefix.length);
1008
+ this.getter = this.path && propertyExpr.getter(this.path, true);
1009
+ this.map = options.map;
1010
+ }
1011
+ getValue(value, parent, context) {
1012
+ let result = this.isContext ? context : this.isValue ? value : parent;
1013
+ if (this.getter) result = this.getter(result || {});
1014
+ if (this.map) result = this.map(result);
1015
+ return result;
1016
+ }
1017
+
1018
+ /**
1019
+ *
1020
+ * @param {*} value
1021
+ * @param {Object} options
1022
+ * @param {Object=} options.context
1023
+ * @param {Object=} options.parent
1024
+ */
1025
+ cast(value, options) {
1026
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
1027
+ }
1028
+ resolve() {
1029
+ return this;
1030
+ }
1031
+ describe() {
1032
+ return {
1033
+ type: 'ref',
1034
+ key: this.key
1035
+ };
1036
+ }
1037
+ toString() {
1038
+ return `Ref(${this.key})`;
1039
+ }
1040
+ static isRef(value) {
1041
+ return value && value.__isYupRef;
1042
+ }
1043
+ }
1044
+
1045
+ // @ts-ignore
1046
+ Reference.prototype.__isYupRef = true;
1047
+
1048
+ const isAbsent = value => value == null;
1049
+
1050
+ function createValidation(config) {
1051
+ function validate({
1052
+ value,
1053
+ path = '',
1054
+ options,
1055
+ originalValue,
1056
+ schema
1057
+ }, panic, next) {
1058
+ const {
1059
+ name,
1060
+ test,
1061
+ params,
1062
+ message,
1063
+ skipAbsent
1064
+ } = config;
1065
+ let {
1066
+ parent,
1067
+ context,
1068
+ abortEarly = schema.spec.abortEarly,
1069
+ disableStackTrace = schema.spec.disableStackTrace
1070
+ } = options;
1071
+ function resolve(item) {
1072
+ return Reference.isRef(item) ? item.getValue(value, parent, context) : item;
1073
+ }
1074
+ function createError(overrides = {}) {
1075
+ const nextParams = Object.assign({
1076
+ value,
1077
+ originalValue,
1078
+ label: schema.spec.label,
1079
+ path: overrides.path || path,
1080
+ spec: schema.spec,
1081
+ disableStackTrace: overrides.disableStackTrace || disableStackTrace
1082
+ }, params, overrides.params);
1083
+ for (const key of Object.keys(nextParams)) nextParams[key] = resolve(nextParams[key]);
1084
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);
1085
+ error.params = nextParams;
1086
+ return error;
1087
+ }
1088
+ const invalid = abortEarly ? panic : next;
1089
+ let ctx = {
1090
+ path,
1091
+ parent,
1092
+ type: name,
1093
+ from: options.from,
1094
+ createError,
1095
+ resolve,
1096
+ options,
1097
+ originalValue,
1098
+ schema
1099
+ };
1100
+ const handleResult = validOrError => {
1101
+ if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);
1102
+ };
1103
+ const handleError = err => {
1104
+ if (ValidationError.isError(err)) invalid(err);else panic(err);
1105
+ };
1106
+ const shouldSkip = skipAbsent && isAbsent(value);
1107
+ if (shouldSkip) {
1108
+ return handleResult(true);
1109
+ }
1110
+ let result;
1111
+ try {
1112
+ var _result;
1113
+ result = test.call(ctx, value, ctx);
1114
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {
1115
+ if (options.sync) {
1116
+ throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);
1117
+ }
1118
+ return Promise.resolve(result).then(handleResult, handleError);
1119
+ }
1120
+ } catch (err) {
1121
+ handleError(err);
1122
+ return;
1123
+ }
1124
+ handleResult(result);
1125
+ }
1126
+ validate.OPTIONS = config;
1127
+ return validate;
1128
+ }
1129
+
1130
+ function getIn(schema, path, value, context = value) {
1131
+ let parent, lastPart, lastPartDebug;
1132
+
1133
+ // root path: ''
1134
+ if (!path) return {
1135
+ parent,
1136
+ parentPath: path,
1137
+ schema
1138
+ };
1139
+ propertyExpr.forEach(path, (_part, isBracket, isArray) => {
1140
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
1141
+ schema = schema.resolve({
1142
+ context,
1143
+ parent,
1144
+ value
1145
+ });
1146
+ let isTuple = schema.type === 'tuple';
1147
+ let idx = isArray ? parseInt(part, 10) : 0;
1148
+ if (schema.innerType || isTuple) {
1149
+ if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
1150
+ if (value && idx >= value.length) {
1151
+ throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);
1152
+ }
1153
+ parent = value;
1154
+ value = value && value[idx];
1155
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
1156
+ }
1157
+
1158
+ // sometimes the array index part of a path doesn't exist: "nested.arr.child"
1159
+ // in these cases the current part is the next schema and should be processed
1160
+ // in this iteration. For cases where the index signature is included this
1161
+ // check will fail and we'll handle the `child` part on the next iteration like normal
1162
+ if (!isArray) {
1163
+ if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
1164
+ parent = value;
1165
+ value = value && value[part];
1166
+ schema = schema.fields[part];
1167
+ }
1168
+ lastPart = part;
1169
+ lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;
1170
+ });
1171
+ return {
1172
+ schema,
1173
+ parent,
1174
+ parentPath: lastPart
1175
+ };
1176
+ }
1177
+
1178
+ class ReferenceSet extends Set {
1179
+ describe() {
1180
+ const description = [];
1181
+ for (const item of this.values()) {
1182
+ description.push(Reference.isRef(item) ? item.describe() : item);
1183
+ }
1184
+ return description;
1185
+ }
1186
+ resolveAll(resolve) {
1187
+ let result = [];
1188
+ for (const item of this.values()) {
1189
+ result.push(resolve(item));
1190
+ }
1191
+ return result;
1192
+ }
1193
+ clone() {
1194
+ return new ReferenceSet(this.values());
1195
+ }
1196
+ merge(newItems, removeItems) {
1197
+ const next = this.clone();
1198
+ newItems.forEach(value => next.add(value));
1199
+ removeItems.forEach(value => next.delete(value));
1200
+ return next;
1201
+ }
1202
+ }
1203
+
1204
+ // tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js
1205
+ function clone(src, seen = new Map()) {
1206
+ if (isSchema(src) || !src || typeof src !== 'object') return src;
1207
+ if (seen.has(src)) return seen.get(src);
1208
+ let copy;
1209
+ if (src instanceof Date) {
1210
+ // Date
1211
+ copy = new Date(src.getTime());
1212
+ seen.set(src, copy);
1213
+ } else if (src instanceof RegExp) {
1214
+ // RegExp
1215
+ copy = new RegExp(src);
1216
+ seen.set(src, copy);
1217
+ } else if (Array.isArray(src)) {
1218
+ // Array
1219
+ copy = new Array(src.length);
1220
+ seen.set(src, copy);
1221
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
1222
+ } else if (src instanceof Map) {
1223
+ // Map
1224
+ copy = new Map();
1225
+ seen.set(src, copy);
1226
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
1227
+ } else if (src instanceof Set) {
1228
+ // Set
1229
+ copy = new Set();
1230
+ seen.set(src, copy);
1231
+ for (const v of src) copy.add(clone(v, seen));
1232
+ } else if (src instanceof Object) {
1233
+ // Object
1234
+ copy = {};
1235
+ seen.set(src, copy);
1236
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
1237
+ } else {
1238
+ throw Error(`Unable to clone ${src}`);
1239
+ }
1240
+ return copy;
1241
+ }
1242
+
1243
+ // If `CustomSchemaMeta` isn't extended with any keys, we'll fall back to a
1244
+ // loose Record definition allowing free form usage.
1245
+ class Schema {
1246
+ constructor(options) {
1247
+ this.type = void 0;
1248
+ this.deps = [];
1249
+ this.tests = void 0;
1250
+ this.transforms = void 0;
1251
+ this.conditions = [];
1252
+ this._mutate = void 0;
1253
+ this.internalTests = {};
1254
+ this._whitelist = new ReferenceSet();
1255
+ this._blacklist = new ReferenceSet();
1256
+ this.exclusiveTests = Object.create(null);
1257
+ this._typeCheck = void 0;
1258
+ this.spec = void 0;
1259
+ this.tests = [];
1260
+ this.transforms = [];
1261
+ this.withMutation(() => {
1262
+ this.typeError(mixed.notType);
1263
+ });
1264
+ this.type = options.type;
1265
+ this._typeCheck = options.check;
1266
+ this.spec = Object.assign({
1267
+ strip: false,
1268
+ strict: false,
1269
+ abortEarly: true,
1270
+ recursive: true,
1271
+ disableStackTrace: false,
1272
+ nullable: false,
1273
+ optional: true,
1274
+ coerce: true
1275
+ }, options == null ? void 0 : options.spec);
1276
+ this.withMutation(s => {
1277
+ s.nonNullable();
1278
+ });
1279
+ }
1280
+
1281
+ // TODO: remove
1282
+ get _type() {
1283
+ return this.type;
1284
+ }
1285
+ clone(spec) {
1286
+ if (this._mutate) {
1287
+ if (spec) Object.assign(this.spec, spec);
1288
+ return this;
1289
+ }
1290
+
1291
+ // if the nested value is a schema we can skip cloning, since
1292
+ // they are already immutable
1293
+ const next = Object.create(Object.getPrototypeOf(this));
1294
+
1295
+ // @ts-expect-error this is readonly
1296
+ next.type = this.type;
1297
+ next._typeCheck = this._typeCheck;
1298
+ next._whitelist = this._whitelist.clone();
1299
+ next._blacklist = this._blacklist.clone();
1300
+ next.internalTests = Object.assign({}, this.internalTests);
1301
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
1302
+
1303
+ // @ts-expect-error this is readonly
1304
+ next.deps = [...this.deps];
1305
+ next.conditions = [...this.conditions];
1306
+ next.tests = [...this.tests];
1307
+ next.transforms = [...this.transforms];
1308
+ next.spec = clone(Object.assign({}, this.spec, spec));
1309
+ return next;
1310
+ }
1311
+ label(label) {
1312
+ let next = this.clone();
1313
+ next.spec.label = label;
1314
+ return next;
1315
+ }
1316
+ meta(...args) {
1317
+ if (args.length === 0) return this.spec.meta;
1318
+ let next = this.clone();
1319
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
1320
+ return next;
1321
+ }
1322
+ withMutation(fn) {
1323
+ let before = this._mutate;
1324
+ this._mutate = true;
1325
+ let result = fn(this);
1326
+ this._mutate = before;
1327
+ return result;
1328
+ }
1329
+ concat(schema) {
1330
+ if (!schema || schema === this) return this;
1331
+ if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
1332
+ let base = this;
1333
+ let combined = schema.clone();
1334
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
1335
+ combined.spec = mergedSpec;
1336
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
1337
+
1338
+ // manually merge the blacklist/whitelist (the other `schema` takes
1339
+ // precedence in case of conflicts)
1340
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
1341
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
1342
+
1343
+ // start with the current tests
1344
+ combined.tests = base.tests;
1345
+ combined.exclusiveTests = base.exclusiveTests;
1346
+
1347
+ // manually add the new tests to ensure
1348
+ // the deduping logic is consistent
1349
+ combined.withMutation(next => {
1350
+ schema.tests.forEach(fn => {
1351
+ next.test(fn.OPTIONS);
1352
+ });
1353
+ });
1354
+ combined.transforms = [...base.transforms, ...combined.transforms];
1355
+ return combined;
1356
+ }
1357
+ isType(v) {
1358
+ if (v == null) {
1359
+ if (this.spec.nullable && v === null) return true;
1360
+ if (this.spec.optional && v === undefined) return true;
1361
+ return false;
1362
+ }
1363
+ return this._typeCheck(v);
1364
+ }
1365
+ resolve(options) {
1366
+ let schema = this;
1367
+ if (schema.conditions.length) {
1368
+ let conditions = schema.conditions;
1369
+ schema = schema.clone();
1370
+ schema.conditions = [];
1371
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
1372
+ schema = schema.resolve(options);
1373
+ }
1374
+ return schema;
1375
+ }
1376
+ resolveOptions(options) {
1377
+ var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
1378
+ return Object.assign({}, options, {
1379
+ from: options.from || [],
1380
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
1381
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
1382
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
1383
+ disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
1384
+ });
1385
+ }
1386
+
1387
+ /**
1388
+ * Run the configured transform pipeline over an input value.
1389
+ */
1390
+
1391
+ cast(value, options = {}) {
1392
+ let resolvedSchema = this.resolve(Object.assign({
1393
+ value
1394
+ }, options));
1395
+ let allowOptionality = options.assert === 'ignore-optionality';
1396
+ let result = resolvedSchema._cast(value, options);
1397
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
1398
+ if (allowOptionality && isAbsent(result)) {
1399
+ return result;
1400
+ }
1401
+ let formattedValue = printValue(value);
1402
+ let formattedResult = printValue(result);
1403
+ throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". \n\n` + `attempted value: ${formattedValue} \n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));
1404
+ }
1405
+ return result;
1406
+ }
1407
+ _cast(rawValue, options) {
1408
+ let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this), rawValue);
1409
+ if (value === undefined) {
1410
+ value = this.getDefault(options);
1411
+ }
1412
+ return value;
1413
+ }
1414
+ _validate(_value, options = {}, panic, next) {
1415
+ let {
1416
+ path,
1417
+ originalValue = _value,
1418
+ strict = this.spec.strict
1419
+ } = options;
1420
+ let value = _value;
1421
+ if (!strict) {
1422
+ value = this._cast(value, Object.assign({
1423
+ assert: false
1424
+ }, options));
1425
+ }
1426
+ let initialTests = [];
1427
+ for (let test of Object.values(this.internalTests)) {
1428
+ if (test) initialTests.push(test);
1429
+ }
1430
+ this.runTests({
1431
+ path,
1432
+ value,
1433
+ originalValue,
1434
+ options,
1435
+ tests: initialTests
1436
+ }, panic, initialErrors => {
1437
+ // even if we aren't ending early we can't proceed further if the types aren't correct
1438
+ if (initialErrors.length) {
1439
+ return next(initialErrors, value);
1440
+ }
1441
+ this.runTests({
1442
+ path,
1443
+ value,
1444
+ originalValue,
1445
+ options,
1446
+ tests: this.tests
1447
+ }, panic, next);
1448
+ });
1449
+ }
1450
+
1451
+ /**
1452
+ * Executes a set of validations, either schema, produced Tests or a nested
1453
+ * schema validate result.
1454
+ */
1455
+ runTests(runOptions, panic, next) {
1456
+ let fired = false;
1457
+ let {
1458
+ tests,
1459
+ value,
1460
+ originalValue,
1461
+ path,
1462
+ options
1463
+ } = runOptions;
1464
+ let panicOnce = arg => {
1465
+ if (fired) return;
1466
+ fired = true;
1467
+ panic(arg, value);
1468
+ };
1469
+ let nextOnce = arg => {
1470
+ if (fired) return;
1471
+ fired = true;
1472
+ next(arg, value);
1473
+ };
1474
+ let count = tests.length;
1475
+ let nestedErrors = [];
1476
+ if (!count) return nextOnce([]);
1477
+ let args = {
1478
+ value,
1479
+ originalValue,
1480
+ path,
1481
+ options,
1482
+ schema: this
1483
+ };
1484
+ for (let i = 0; i < tests.length; i++) {
1485
+ const test = tests[i];
1486
+ test(args, panicOnce, function finishTestRun(err) {
1487
+ if (err) {
1488
+ Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
1489
+ }
1490
+ if (--count <= 0) {
1491
+ nextOnce(nestedErrors);
1492
+ }
1493
+ });
1494
+ }
1495
+ }
1496
+ asNestedTest({
1497
+ key,
1498
+ index,
1499
+ parent,
1500
+ parentPath,
1501
+ originalParent,
1502
+ options
1503
+ }) {
1504
+ const k = key != null ? key : index;
1505
+ if (k == null) {
1506
+ throw TypeError('Must include `key` or `index` for nested validations');
1507
+ }
1508
+ const isIndex = typeof k === 'number';
1509
+ let value = parent[k];
1510
+ const testOptions = Object.assign({}, options, {
1511
+ // Nested validations fields are always strict:
1512
+ // 1. parent isn't strict so the casting will also have cast inner values
1513
+ // 2. parent is strict in which case the nested values weren't cast either
1514
+ strict: true,
1515
+ parent,
1516
+ value,
1517
+ originalValue: originalParent[k],
1518
+ // FIXME: tests depend on `index` being passed around deeply,
1519
+ // we should not let the options.key/index bleed through
1520
+ key: undefined,
1521
+ // index: undefined,
1522
+ [isIndex ? 'index' : 'key']: k,
1523
+ path: isIndex || k.includes('.') ? `${parentPath || ''}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : '') + key
1524
+ });
1525
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
1526
+ }
1527
+ validate(value, options) {
1528
+ var _options$disableStack2;
1529
+ let schema = this.resolve(Object.assign({}, options, {
1530
+ value
1531
+ }));
1532
+ let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
1533
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
1534
+ if (ValidationError.isError(error)) error.value = parsed;
1535
+ reject(error);
1536
+ }, (errors, validated) => {
1537
+ if (errors.length) reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace));else resolve(validated);
1538
+ }));
1539
+ }
1540
+ validateSync(value, options) {
1541
+ var _options$disableStack3;
1542
+ let schema = this.resolve(Object.assign({}, options, {
1543
+ value
1544
+ }));
1545
+ let result;
1546
+ let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
1547
+ schema._validate(value, Object.assign({}, options, {
1548
+ sync: true
1549
+ }), (error, parsed) => {
1550
+ if (ValidationError.isError(error)) error.value = parsed;
1551
+ throw error;
1552
+ }, (errors, validated) => {
1553
+ if (errors.length) throw new ValidationError(errors, value, undefined, undefined, disableStackTrace);
1554
+ result = validated;
1555
+ });
1556
+ return result;
1557
+ }
1558
+ isValid(value, options) {
1559
+ return this.validate(value, options).then(() => true, err => {
1560
+ if (ValidationError.isError(err)) return false;
1561
+ throw err;
1562
+ });
1563
+ }
1564
+ isValidSync(value, options) {
1565
+ try {
1566
+ this.validateSync(value, options);
1567
+ return true;
1568
+ } catch (err) {
1569
+ if (ValidationError.isError(err)) return false;
1570
+ throw err;
1571
+ }
1572
+ }
1573
+ _getDefault(options) {
1574
+ let defaultValue = this.spec.default;
1575
+ if (defaultValue == null) {
1576
+ return defaultValue;
1577
+ }
1578
+ return typeof defaultValue === 'function' ? defaultValue.call(this, options) : clone(defaultValue);
1579
+ }
1580
+ getDefault(options
1581
+ // If schema is defaulted we know it's at least not undefined
1582
+ ) {
1583
+ let schema = this.resolve(options || {});
1584
+ return schema._getDefault(options);
1585
+ }
1586
+ default(def) {
1587
+ if (arguments.length === 0) {
1588
+ return this._getDefault();
1589
+ }
1590
+ let next = this.clone({
1591
+ default: def
1592
+ });
1593
+ return next;
1594
+ }
1595
+ strict(isStrict = true) {
1596
+ return this.clone({
1597
+ strict: isStrict
1598
+ });
1599
+ }
1600
+ nullability(nullable, message) {
1601
+ const next = this.clone({
1602
+ nullable
1603
+ });
1604
+ next.internalTests.nullable = createValidation({
1605
+ message,
1606
+ name: 'nullable',
1607
+ test(value) {
1608
+ return value === null ? this.schema.spec.nullable : true;
1609
+ }
1610
+ });
1611
+ return next;
1612
+ }
1613
+ optionality(optional, message) {
1614
+ const next = this.clone({
1615
+ optional
1616
+ });
1617
+ next.internalTests.optionality = createValidation({
1618
+ message,
1619
+ name: 'optionality',
1620
+ test(value) {
1621
+ return value === undefined ? this.schema.spec.optional : true;
1622
+ }
1623
+ });
1624
+ return next;
1625
+ }
1626
+ optional() {
1627
+ return this.optionality(true);
1628
+ }
1629
+ defined(message = mixed.defined) {
1630
+ return this.optionality(false, message);
1631
+ }
1632
+ nullable() {
1633
+ return this.nullability(true);
1634
+ }
1635
+ nonNullable(message = mixed.notNull) {
1636
+ return this.nullability(false, message);
1637
+ }
1638
+ required(message = mixed.required) {
1639
+ return this.clone().withMutation(next => next.nonNullable(message).defined(message));
1640
+ }
1641
+ notRequired() {
1642
+ return this.clone().withMutation(next => next.nullable().optional());
1643
+ }
1644
+ transform(fn) {
1645
+ let next = this.clone();
1646
+ next.transforms.push(fn);
1647
+ return next;
1648
+ }
1649
+
1650
+ /**
1651
+ * Adds a test function to the schema's queue of tests.
1652
+ * tests can be exclusive or non-exclusive.
1653
+ *
1654
+ * - exclusive tests, will replace any existing tests of the same name.
1655
+ * - non-exclusive: can be stacked
1656
+ *
1657
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
1658
+ * the exclusive test is removed and further tests of the same name will be stacked.
1659
+ *
1660
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
1661
+ * the previous tests are removed and further tests of the same name will replace each other.
1662
+ */
1663
+
1664
+ test(...args) {
1665
+ let opts;
1666
+ if (args.length === 1) {
1667
+ if (typeof args[0] === 'function') {
1668
+ opts = {
1669
+ test: args[0]
1670
+ };
1671
+ } else {
1672
+ opts = args[0];
1673
+ }
1674
+ } else if (args.length === 2) {
1675
+ opts = {
1676
+ name: args[0],
1677
+ test: args[1]
1678
+ };
1679
+ } else {
1680
+ opts = {
1681
+ name: args[0],
1682
+ message: args[1],
1683
+ test: args[2]
1684
+ };
1685
+ }
1686
+ if (opts.message === undefined) opts.message = mixed.default;
1687
+ if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');
1688
+ let next = this.clone();
1689
+ let validate = createValidation(opts);
1690
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
1691
+ if (opts.exclusive) {
1692
+ if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');
1693
+ }
1694
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
1695
+ next.tests = next.tests.filter(fn => {
1696
+ if (fn.OPTIONS.name === opts.name) {
1697
+ if (isExclusive) return false;
1698
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
1699
+ }
1700
+ return true;
1701
+ });
1702
+ next.tests.push(validate);
1703
+ return next;
1704
+ }
1705
+ when(keys, options) {
1706
+ if (!Array.isArray(keys) && typeof keys !== 'string') {
1707
+ options = keys;
1708
+ keys = '.';
1709
+ }
1710
+ let next = this.clone();
1711
+ let deps = toArray(keys).map(key => new Reference(key));
1712
+ deps.forEach(dep => {
1713
+ // @ts-ignore readonly array
1714
+ if (dep.isSibling) next.deps.push(dep.key);
1715
+ });
1716
+ next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));
1717
+ return next;
1718
+ }
1719
+ typeError(message) {
1720
+ let next = this.clone();
1721
+ next.internalTests.typeError = createValidation({
1722
+ message,
1723
+ name: 'typeError',
1724
+ skipAbsent: true,
1725
+ test(value) {
1726
+ if (!this.schema._typeCheck(value)) return this.createError({
1727
+ params: {
1728
+ type: this.schema.type
1729
+ }
1730
+ });
1731
+ return true;
1732
+ }
1733
+ });
1734
+ return next;
1735
+ }
1736
+ oneOf(enums, message = mixed.oneOf) {
1737
+ let next = this.clone();
1738
+ enums.forEach(val => {
1739
+ next._whitelist.add(val);
1740
+ next._blacklist.delete(val);
1741
+ });
1742
+ next.internalTests.whiteList = createValidation({
1743
+ message,
1744
+ name: 'oneOf',
1745
+ skipAbsent: true,
1746
+ test(value) {
1747
+ let valids = this.schema._whitelist;
1748
+ let resolved = valids.resolveAll(this.resolve);
1749
+ return resolved.includes(value) ? true : this.createError({
1750
+ params: {
1751
+ values: Array.from(valids).join(', '),
1752
+ resolved
1753
+ }
1754
+ });
1755
+ }
1756
+ });
1757
+ return next;
1758
+ }
1759
+ notOneOf(enums, message = mixed.notOneOf) {
1760
+ let next = this.clone();
1761
+ enums.forEach(val => {
1762
+ next._blacklist.add(val);
1763
+ next._whitelist.delete(val);
1764
+ });
1765
+ next.internalTests.blacklist = createValidation({
1766
+ message,
1767
+ name: 'notOneOf',
1768
+ test(value) {
1769
+ let invalids = this.schema._blacklist;
1770
+ let resolved = invalids.resolveAll(this.resolve);
1771
+ if (resolved.includes(value)) return this.createError({
1772
+ params: {
1773
+ values: Array.from(invalids).join(', '),
1774
+ resolved
1775
+ }
1776
+ });
1777
+ return true;
1778
+ }
1779
+ });
1780
+ return next;
1781
+ }
1782
+ strip(strip = true) {
1783
+ let next = this.clone();
1784
+ next.spec.strip = strip;
1785
+ return next;
1786
+ }
1787
+
1788
+ /**
1789
+ * Return a serialized description of the schema including validations, flags, types etc.
1790
+ *
1791
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
1792
+ */
1793
+ describe(options) {
1794
+ const next = (options ? this.resolve(options) : this).clone();
1795
+ const {
1796
+ label,
1797
+ meta,
1798
+ optional,
1799
+ nullable
1800
+ } = next.spec;
1801
+ const description = {
1802
+ meta,
1803
+ label,
1804
+ optional,
1805
+ nullable,
1806
+ default: next.getDefault(options),
1807
+ type: next.type,
1808
+ oneOf: next._whitelist.describe(),
1809
+ notOneOf: next._blacklist.describe(),
1810
+ tests: next.tests.map(fn => ({
1811
+ name: fn.OPTIONS.name,
1812
+ params: fn.OPTIONS.params
1813
+ })).filter((n, idx, list) => list.findIndex(c => c.name === n.name) === idx)
1814
+ };
1815
+ return description;
1816
+ }
1817
+ }
1818
+ // @ts-expect-error
1819
+ Schema.prototype.__isYupSchema__ = true;
1820
+ for (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {
1821
+ const {
1822
+ parent,
1823
+ parentPath,
1824
+ schema
1825
+ } = getIn(this, path, value, options.context);
1826
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
1827
+ parent,
1828
+ path
1829
+ }));
1830
+ };
1831
+ for (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;
1832
+ for (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;
1833
+
1834
+ /**
1835
+ * This file is a modified version of the file from the following repository:
1836
+ * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
1837
+ * NON-CONFORMANT EDITION.
1838
+ * © 2011 Colin Snover <http://zetafleet.com>
1839
+ * Released under MIT license.
1840
+ */
1841
+
1842
+ // prettier-ignore
1843
+ // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
1844
+ const isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
1845
+ function parseIsoDate(date) {
1846
+ const struct = parseDateStruct(date);
1847
+ if (!struct) return Date.parse ? Date.parse(date) : Number.NaN;
1848
+
1849
+ // timestamps without timezone identifiers should be considered local time
1850
+ if (struct.z === undefined && struct.plusMinus === undefined) {
1851
+ return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
1852
+ }
1853
+ let totalMinutesOffset = 0;
1854
+ if (struct.z !== 'Z' && struct.plusMinus !== undefined) {
1855
+ totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
1856
+ if (struct.plusMinus === '+') totalMinutesOffset = 0 - totalMinutesOffset;
1857
+ }
1858
+ return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
1859
+ }
1860
+ function parseDateStruct(date) {
1861
+ var _regexResult$7$length, _regexResult$;
1862
+ const regexResult = isoReg.exec(date);
1863
+ if (!regexResult) return null;
1864
+
1865
+ // use of toNumber() avoids NaN timestamps caused by “undefined”
1866
+ // values being passed to Date constructor
1867
+ return {
1868
+ year: toNumber(regexResult[1]),
1869
+ month: toNumber(regexResult[2], 1) - 1,
1870
+ day: toNumber(regexResult[3], 1),
1871
+ hour: toNumber(regexResult[4]),
1872
+ minute: toNumber(regexResult[5]),
1873
+ second: toNumber(regexResult[6]),
1874
+ millisecond: regexResult[7] ?
1875
+ // allow arbitrary sub-second precision beyond milliseconds
1876
+ toNumber(regexResult[7].substring(0, 3)) : 0,
1877
+ precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : undefined,
1878
+ z: regexResult[8] || undefined,
1879
+ plusMinus: regexResult[9] || undefined,
1880
+ hourOffset: toNumber(regexResult[10]),
1881
+ minuteOffset: toNumber(regexResult[11])
1882
+ };
1883
+ }
1884
+ function toNumber(str, defaultValue = 0) {
1885
+ return Number(str) || defaultValue;
1886
+ }
1887
+
1888
+ // Taken from HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
1889
+ let rEmail =
1890
+ // eslint-disable-next-line
1891
+ /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1892
+ let rUrl =
1893
+ // eslint-disable-next-line
1894
+ /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
1895
+
1896
+ // eslint-disable-next-line
1897
+ let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1898
+ let yearMonthDay = '^\\d{4}-\\d{2}-\\d{2}';
1899
+ let hourMinuteSecond = '\\d{2}:\\d{2}:\\d{2}';
1900
+ let zOrOffset = '(([+-]\\d{2}(:?\\d{2})?)|Z)';
1901
+ let rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`);
1902
+ let isTrimmed = value => isAbsent(value) || value === value.trim();
1903
+ let objStringTag = {}.toString();
1904
+ function create$6() {
1905
+ return new StringSchema();
1906
+ }
1907
+ class StringSchema extends Schema {
1908
+ constructor() {
1909
+ super({
1910
+ type: 'string',
1911
+ check(value) {
1912
+ if (value instanceof String) value = value.valueOf();
1913
+ return typeof value === 'string';
1914
+ }
1915
+ });
1916
+ this.withMutation(() => {
1917
+ this.transform((value, _raw, ctx) => {
1918
+ if (!ctx.spec.coerce || ctx.isType(value)) return value;
1919
+
1920
+ // don't ever convert arrays
1921
+ if (Array.isArray(value)) return value;
1922
+ const strValue = value != null && value.toString ? value.toString() : value;
1923
+
1924
+ // no one wants plain objects converted to [Object object]
1925
+ if (strValue === objStringTag) return value;
1926
+ return strValue;
1927
+ });
1928
+ });
1929
+ }
1930
+ required(message) {
1931
+ return super.required(message).withMutation(schema => schema.test({
1932
+ message: message || mixed.required,
1933
+ name: 'required',
1934
+ skipAbsent: true,
1935
+ test: value => !!value.length
1936
+ }));
1937
+ }
1938
+ notRequired() {
1939
+ return super.notRequired().withMutation(schema => {
1940
+ schema.tests = schema.tests.filter(t => t.OPTIONS.name !== 'required');
1941
+ return schema;
1942
+ });
1943
+ }
1944
+ length(length, message = string.length) {
1945
+ return this.test({
1946
+ message,
1947
+ name: 'length',
1948
+ exclusive: true,
1949
+ params: {
1950
+ length
1951
+ },
1952
+ skipAbsent: true,
1953
+ test(value) {
1954
+ return value.length === this.resolve(length);
1955
+ }
1956
+ });
1957
+ }
1958
+ min(min, message = string.min) {
1959
+ return this.test({
1960
+ message,
1961
+ name: 'min',
1962
+ exclusive: true,
1963
+ params: {
1964
+ min
1965
+ },
1966
+ skipAbsent: true,
1967
+ test(value) {
1968
+ return value.length >= this.resolve(min);
1969
+ }
1970
+ });
1971
+ }
1972
+ max(max, message = string.max) {
1973
+ return this.test({
1974
+ name: 'max',
1975
+ exclusive: true,
1976
+ message,
1977
+ params: {
1978
+ max
1979
+ },
1980
+ skipAbsent: true,
1981
+ test(value) {
1982
+ return value.length <= this.resolve(max);
1983
+ }
1984
+ });
1985
+ }
1986
+ matches(regex, options) {
1987
+ let excludeEmptyString = false;
1988
+ let message;
1989
+ let name;
1990
+ if (options) {
1991
+ if (typeof options === 'object') {
1992
+ ({
1993
+ excludeEmptyString = false,
1994
+ message,
1995
+ name
1996
+ } = options);
1997
+ } else {
1998
+ message = options;
1999
+ }
2000
+ }
2001
+ return this.test({
2002
+ name: name || 'matches',
2003
+ message: message || string.matches,
2004
+ params: {
2005
+ regex
2006
+ },
2007
+ skipAbsent: true,
2008
+ test: value => value === '' && excludeEmptyString || value.search(regex) !== -1
2009
+ });
2010
+ }
2011
+ email(message = string.email) {
2012
+ return this.matches(rEmail, {
2013
+ name: 'email',
2014
+ message,
2015
+ excludeEmptyString: true
2016
+ });
2017
+ }
2018
+ url(message = string.url) {
2019
+ return this.matches(rUrl, {
2020
+ name: 'url',
2021
+ message,
2022
+ excludeEmptyString: true
2023
+ });
2024
+ }
2025
+ uuid(message = string.uuid) {
2026
+ return this.matches(rUUID, {
2027
+ name: 'uuid',
2028
+ message,
2029
+ excludeEmptyString: false
2030
+ });
2031
+ }
2032
+ datetime(options) {
2033
+ let message = '';
2034
+ let allowOffset;
2035
+ let precision;
2036
+ if (options) {
2037
+ if (typeof options === 'object') {
2038
+ ({
2039
+ message = '',
2040
+ allowOffset = false,
2041
+ precision = undefined
2042
+ } = options);
2043
+ } else {
2044
+ message = options;
2045
+ }
2046
+ }
2047
+ return this.matches(rIsoDateTime, {
2048
+ name: 'datetime',
2049
+ message: message || string.datetime,
2050
+ excludeEmptyString: true
2051
+ }).test({
2052
+ name: 'datetime_offset',
2053
+ message: message || string.datetime_offset,
2054
+ params: {
2055
+ allowOffset
2056
+ },
2057
+ skipAbsent: true,
2058
+ test: value => {
2059
+ if (!value || allowOffset) return true;
2060
+ const struct = parseDateStruct(value);
2061
+ if (!struct) return false;
2062
+ return !!struct.z;
2063
+ }
2064
+ }).test({
2065
+ name: 'datetime_precision',
2066
+ message: message || string.datetime_precision,
2067
+ params: {
2068
+ precision
2069
+ },
2070
+ skipAbsent: true,
2071
+ test: value => {
2072
+ if (!value || precision == undefined) return true;
2073
+ const struct = parseDateStruct(value);
2074
+ if (!struct) return false;
2075
+ return struct.precision === precision;
2076
+ }
2077
+ });
2078
+ }
2079
+
2080
+ //-- transforms --
2081
+ ensure() {
2082
+ return this.default('').transform(val => val === null ? '' : val);
2083
+ }
2084
+ trim(message = string.trim) {
2085
+ return this.transform(val => val != null ? val.trim() : val).test({
2086
+ message,
2087
+ name: 'trim',
2088
+ test: isTrimmed
2089
+ });
2090
+ }
2091
+ lowercase(message = string.lowercase) {
2092
+ return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({
2093
+ message,
2094
+ name: 'string_case',
2095
+ exclusive: true,
2096
+ skipAbsent: true,
2097
+ test: value => isAbsent(value) || value === value.toLowerCase()
2098
+ });
2099
+ }
2100
+ uppercase(message = string.uppercase) {
2101
+ return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({
2102
+ message,
2103
+ name: 'string_case',
2104
+ exclusive: true,
2105
+ skipAbsent: true,
2106
+ test: value => isAbsent(value) || value === value.toUpperCase()
2107
+ });
2108
+ }
2109
+ }
2110
+ create$6.prototype = StringSchema.prototype;
2111
+
2112
+ //
2113
+ // Number Interfaces
2114
+ //
2115
+
2116
+ let invalidDate = new Date('');
2117
+ let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';
2118
+ class DateSchema extends Schema {
2119
+ constructor() {
2120
+ super({
2121
+ type: 'date',
2122
+ check(v) {
2123
+ return isDate(v) && !isNaN(v.getTime());
2124
+ }
2125
+ });
2126
+ this.withMutation(() => {
2127
+ this.transform((value, _raw, ctx) => {
2128
+ // null -> InvalidDate isn't useful; treat all nulls as null and let it fail on
2129
+ // nullability check vs TypeErrors
2130
+ if (!ctx.spec.coerce || ctx.isType(value) || value === null) return value;
2131
+ value = parseIsoDate(value);
2132
+
2133
+ // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.
2134
+ return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;
2135
+ });
2136
+ });
2137
+ }
2138
+ prepareParam(ref, name) {
2139
+ let param;
2140
+ if (!Reference.isRef(ref)) {
2141
+ let cast = this.cast(ref);
2142
+ if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
2143
+ param = cast;
2144
+ } else {
2145
+ param = ref;
2146
+ }
2147
+ return param;
2148
+ }
2149
+ min(min, message = date.min) {
2150
+ let limit = this.prepareParam(min, 'min');
2151
+ return this.test({
2152
+ message,
2153
+ name: 'min',
2154
+ exclusive: true,
2155
+ params: {
2156
+ min
2157
+ },
2158
+ skipAbsent: true,
2159
+ test(value) {
2160
+ return value >= this.resolve(limit);
2161
+ }
2162
+ });
2163
+ }
2164
+ max(max, message = date.max) {
2165
+ let limit = this.prepareParam(max, 'max');
2166
+ return this.test({
2167
+ message,
2168
+ name: 'max',
2169
+ exclusive: true,
2170
+ params: {
2171
+ max
2172
+ },
2173
+ skipAbsent: true,
2174
+ test(value) {
2175
+ return value <= this.resolve(limit);
2176
+ }
2177
+ });
2178
+ }
2179
+ }
2180
+ DateSchema.INVALID_DATE = invalidDate;
2181
+
2182
+ // @ts-expect-error
2183
+ function sortFields(fields, excludedEdges = []) {
2184
+ let edges = [];
2185
+ let nodes = new Set();
2186
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
2187
+ function addNode(depPath, key) {
2188
+ let node = propertyExpr.split(depPath)[0];
2189
+ nodes.add(node);
2190
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
2191
+ }
2192
+ for (const key of Object.keys(fields)) {
2193
+ let value = fields[key];
2194
+ nodes.add(key);
2195
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));
2196
+ }
2197
+ return toposort$1.array(Array.from(nodes), edges).reverse();
2198
+ }
2199
+
2200
+ function findIndex(arr, err) {
2201
+ let idx = Infinity;
2202
+ arr.some((key, ii) => {
2203
+ var _err$path;
2204
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
2205
+ idx = ii;
2206
+ return true;
2207
+ }
2208
+ });
2209
+ return idx;
2210
+ }
2211
+ function sortByKeyOrder(keys) {
2212
+ return (a, b) => {
2213
+ return findIndex(keys, a) - findIndex(keys, b);
2214
+ };
2215
+ }
2216
+
2217
+ const parseJson = (value, _, ctx) => {
2218
+ if (typeof value !== 'string') {
2219
+ return value;
2220
+ }
2221
+ let parsed = value;
2222
+ try {
2223
+ parsed = JSON.parse(value);
2224
+ } catch (err) {
2225
+ /* */
2226
+ }
2227
+ return ctx.isType(parsed) ? parsed : value;
2228
+ };
2229
+
2230
+ // @ts-ignore
2231
+ function deepPartial(schema) {
2232
+ if ('fields' in schema) {
2233
+ const partial = {};
2234
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
2235
+ partial[key] = deepPartial(fieldSchema);
2236
+ }
2237
+ return schema.setFields(partial);
2238
+ }
2239
+ if (schema.type === 'array') {
2240
+ const nextArray = schema.optional();
2241
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
2242
+ return nextArray;
2243
+ }
2244
+ if (schema.type === 'tuple') {
2245
+ return schema.optional().clone({
2246
+ types: schema.spec.types.map(deepPartial)
2247
+ });
2248
+ }
2249
+ if ('optional' in schema) {
2250
+ return schema.optional();
2251
+ }
2252
+ return schema;
2253
+ }
2254
+ const deepHas = (obj, p) => {
2255
+ const path = [...propertyExpr.normalizePath(p)];
2256
+ if (path.length === 1) return path[0] in obj;
2257
+ let last = path.pop();
2258
+ let parent = propertyExpr.getter(propertyExpr.join(path), true)(obj);
2259
+ return !!(parent && last in parent);
2260
+ };
2261
+ let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
2262
+ function unknown(ctx, value) {
2263
+ let known = Object.keys(ctx.fields);
2264
+ return Object.keys(value).filter(key => known.indexOf(key) === -1);
2265
+ }
2266
+ const defaultSort = sortByKeyOrder([]);
2267
+ function create$3(spec) {
2268
+ return new ObjectSchema(spec);
2269
+ }
2270
+ class ObjectSchema extends Schema {
2271
+ constructor(spec) {
2272
+ super({
2273
+ type: 'object',
2274
+ check(value) {
2275
+ return isObject(value) || typeof value === 'function';
2276
+ }
2277
+ });
2278
+ this.fields = Object.create(null);
2279
+ this._sortErrors = defaultSort;
2280
+ this._nodes = [];
2281
+ this._excludedEdges = [];
2282
+ this.withMutation(() => {
2283
+ if (spec) {
2284
+ this.shape(spec);
2285
+ }
2286
+ });
2287
+ }
2288
+ _cast(_value, options = {}) {
2289
+ var _options$stripUnknown;
2290
+ let value = super._cast(_value, options);
2291
+
2292
+ //should ignore nulls here
2293
+ if (value === undefined) return this.getDefault(options);
2294
+ if (!this._typeCheck(value)) return value;
2295
+ let fields = this.fields;
2296
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
2297
+ let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));
2298
+ let intermediateValue = {}; // is filled during the transform below
2299
+ let innerOptions = Object.assign({}, options, {
2300
+ parent: intermediateValue,
2301
+ __validating: options.__validating || false
2302
+ });
2303
+ let isChanged = false;
2304
+ for (const prop of props) {
2305
+ let field = fields[prop];
2306
+ let exists = (prop in value);
2307
+ if (field) {
2308
+ let fieldValue;
2309
+ let inputValue = value[prop];
2310
+
2311
+ // safe to mutate since this is fired in sequence
2312
+ innerOptions.path = (options.path ? `${options.path}.` : '') + prop;
2313
+ field = field.resolve({
2314
+ value: inputValue,
2315
+ context: options.context,
2316
+ parent: intermediateValue
2317
+ });
2318
+ let fieldSpec = field instanceof Schema ? field.spec : undefined;
2319
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
2320
+ if (fieldSpec != null && fieldSpec.strip) {
2321
+ isChanged = isChanged || prop in value;
2322
+ continue;
2323
+ }
2324
+ fieldValue = !options.__validating || !strict ?
2325
+ // TODO: use _cast, this is double resolving
2326
+ field.cast(value[prop], innerOptions) : value[prop];
2327
+ if (fieldValue !== undefined) {
2328
+ intermediateValue[prop] = fieldValue;
2329
+ }
2330
+ } else if (exists && !strip) {
2331
+ intermediateValue[prop] = value[prop];
2332
+ }
2333
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== value[prop]) {
2334
+ isChanged = true;
2335
+ }
2336
+ }
2337
+ return isChanged ? intermediateValue : value;
2338
+ }
2339
+ _validate(_value, options = {}, panic, next) {
2340
+ let {
2341
+ from = [],
2342
+ originalValue = _value,
2343
+ recursive = this.spec.recursive
2344
+ } = options;
2345
+ options.from = [{
2346
+ schema: this,
2347
+ value: originalValue
2348
+ }, ...from];
2349
+ // this flag is needed for handling `strict` correctly in the context of
2350
+ // validation vs just casting. e.g strict() on a field is only used when validating
2351
+ options.__validating = true;
2352
+ options.originalValue = originalValue;
2353
+ super._validate(_value, options, panic, (objectErrors, value) => {
2354
+ if (!recursive || !isObject(value)) {
2355
+ next(objectErrors, value);
2356
+ return;
2357
+ }
2358
+ originalValue = originalValue || value;
2359
+ let tests = [];
2360
+ for (let key of this._nodes) {
2361
+ let field = this.fields[key];
2362
+ if (!field || Reference.isRef(field)) {
2363
+ continue;
2364
+ }
2365
+ tests.push(field.asNestedTest({
2366
+ options,
2367
+ key,
2368
+ parent: value,
2369
+ parentPath: options.path,
2370
+ originalParent: originalValue
2371
+ }));
2372
+ }
2373
+ this.runTests({
2374
+ tests,
2375
+ value,
2376
+ originalValue,
2377
+ options
2378
+ }, panic, fieldErrors => {
2379
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
2380
+ });
2381
+ });
2382
+ }
2383
+ clone(spec) {
2384
+ const next = super.clone(spec);
2385
+ next.fields = Object.assign({}, this.fields);
2386
+ next._nodes = this._nodes;
2387
+ next._excludedEdges = this._excludedEdges;
2388
+ next._sortErrors = this._sortErrors;
2389
+ return next;
2390
+ }
2391
+ concat(schema) {
2392
+ let next = super.concat(schema);
2393
+ let nextFields = next.fields;
2394
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
2395
+ const target = nextFields[field];
2396
+ nextFields[field] = target === undefined ? schemaOrRef : target;
2397
+ }
2398
+ return next.withMutation(s =>
2399
+ // XXX: excludes here is wrong
2400
+ s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges]));
2401
+ }
2402
+ _getDefault(options) {
2403
+ if ('default' in this.spec) {
2404
+ return super._getDefault(options);
2405
+ }
2406
+
2407
+ // if there is no default set invent one
2408
+ if (!this._nodes.length) {
2409
+ return undefined;
2410
+ }
2411
+ let dft = {};
2412
+ this._nodes.forEach(key => {
2413
+ var _innerOptions;
2414
+ const field = this.fields[key];
2415
+ let innerOptions = options;
2416
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
2417
+ innerOptions = Object.assign({}, innerOptions, {
2418
+ parent: innerOptions.value,
2419
+ value: innerOptions.value[key]
2420
+ });
2421
+ }
2422
+ dft[key] = field && 'getDefault' in field ? field.getDefault(innerOptions) : undefined;
2423
+ });
2424
+ return dft;
2425
+ }
2426
+ setFields(shape, excludedEdges) {
2427
+ let next = this.clone();
2428
+ next.fields = shape;
2429
+ next._nodes = sortFields(shape, excludedEdges);
2430
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
2431
+ // XXX: this carries over edges which may not be what you want
2432
+ if (excludedEdges) next._excludedEdges = excludedEdges;
2433
+ return next;
2434
+ }
2435
+ shape(additions, excludes = []) {
2436
+ return this.clone().withMutation(next => {
2437
+ let edges = next._excludedEdges;
2438
+ if (excludes.length) {
2439
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
2440
+ edges = [...next._excludedEdges, ...excludes];
2441
+ }
2442
+
2443
+ // XXX: excludes here is wrong
2444
+ return next.setFields(Object.assign(next.fields, additions), edges);
2445
+ });
2446
+ }
2447
+ partial() {
2448
+ const partial = {};
2449
+ for (const [key, schema] of Object.entries(this.fields)) {
2450
+ partial[key] = 'optional' in schema && schema.optional instanceof Function ? schema.optional() : schema;
2451
+ }
2452
+ return this.setFields(partial);
2453
+ }
2454
+ deepPartial() {
2455
+ const next = deepPartial(this);
2456
+ return next;
2457
+ }
2458
+ pick(keys) {
2459
+ const picked = {};
2460
+ for (const key of keys) {
2461
+ if (this.fields[key]) picked[key] = this.fields[key];
2462
+ }
2463
+ return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
2464
+ }
2465
+ omit(keys) {
2466
+ const remaining = [];
2467
+ for (const key of Object.keys(this.fields)) {
2468
+ if (keys.includes(key)) continue;
2469
+ remaining.push(key);
2470
+ }
2471
+ return this.pick(remaining);
2472
+ }
2473
+ from(from, to, alias) {
2474
+ let fromGetter = propertyExpr.getter(from, true);
2475
+ return this.transform(obj => {
2476
+ if (!obj) return obj;
2477
+ let newObj = obj;
2478
+ if (deepHas(obj, from)) {
2479
+ newObj = Object.assign({}, obj);
2480
+ if (!alias) delete newObj[from];
2481
+ newObj[to] = fromGetter(obj);
2482
+ }
2483
+ return newObj;
2484
+ });
2485
+ }
2486
+
2487
+ /** Parse an input JSON string to an object */
2488
+ json() {
2489
+ return this.transform(parseJson);
2490
+ }
2491
+
2492
+ /**
2493
+ * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys
2494
+ */
2495
+ exact(message) {
2496
+ return this.test({
2497
+ name: 'exact',
2498
+ exclusive: true,
2499
+ message: message || object.exact,
2500
+ test(value) {
2501
+ if (value == null) return true;
2502
+ const unknownKeys = unknown(this.schema, value);
2503
+ return unknownKeys.length === 0 || this.createError({
2504
+ params: {
2505
+ properties: unknownKeys.join(', ')
2506
+ }
2507
+ });
2508
+ }
2509
+ });
2510
+ }
2511
+ stripUnknown() {
2512
+ return this.clone({
2513
+ noUnknown: true
2514
+ });
2515
+ }
2516
+ noUnknown(noAllow = true, message = object.noUnknown) {
2517
+ if (typeof noAllow !== 'boolean') {
2518
+ message = noAllow;
2519
+ noAllow = true;
2520
+ }
2521
+ let next = this.test({
2522
+ name: 'noUnknown',
2523
+ exclusive: true,
2524
+ message: message,
2525
+ test(value) {
2526
+ if (value == null) return true;
2527
+ const unknownKeys = unknown(this.schema, value);
2528
+ return !noAllow || unknownKeys.length === 0 || this.createError({
2529
+ params: {
2530
+ unknown: unknownKeys.join(', ')
2531
+ }
2532
+ });
2533
+ }
2534
+ });
2535
+ next.spec.noUnknown = noAllow;
2536
+ return next;
2537
+ }
2538
+ unknown(allow = true, message = object.noUnknown) {
2539
+ return this.noUnknown(!allow, message);
2540
+ }
2541
+ transformKeys(fn) {
2542
+ return this.transform(obj => {
2543
+ if (!obj) return obj;
2544
+ const result = {};
2545
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
2546
+ return result;
2547
+ });
2548
+ }
2549
+ camelCase() {
2550
+ return this.transformKeys(tinyCase.camelCase);
2551
+ }
2552
+ snakeCase() {
2553
+ return this.transformKeys(tinyCase.snakeCase);
2554
+ }
2555
+ constantCase() {
2556
+ return this.transformKeys(key => tinyCase.snakeCase(key).toUpperCase());
2557
+ }
2558
+ describe(options) {
2559
+ const next = (options ? this.resolve(options) : this).clone();
2560
+ const base = super.describe(options);
2561
+ base.fields = {};
2562
+ for (const [key, value] of Object.entries(next.fields)) {
2563
+ var _innerOptions2;
2564
+ let innerOptions = options;
2565
+ if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {
2566
+ innerOptions = Object.assign({}, innerOptions, {
2567
+ parent: innerOptions.value,
2568
+ value: innerOptions.value[key]
2569
+ });
2570
+ }
2571
+ base.fields[key] = value.describe(innerOptions);
2572
+ }
2573
+ return base;
2574
+ }
2575
+ }
2576
+ create$3.prototype = ObjectSchema.prototype;
2577
+
2578
+ var createValidationSchema = function (fields) {
2579
+ var schema = {};
2580
+ fields.forEach(function (field) {
2581
+ // Excluir campos que no tienen name o son de tipos especiales
2582
+ if (!field.name ||
2583
+ ['declaration', 'subtitle', 'alert', 'status'].includes(field.type)) {
2584
+ return;
2585
+ }
2586
+ if (field.validations && field.validations.length > 0) {
2587
+ var fieldSchema_1 = create$6();
2588
+ field.validations.forEach(function (validation) {
2589
+ switch (validation.type) {
2590
+ case 'required':
2591
+ fieldSchema_1 = fieldSchema_1.required(validation.params[0] || 'Este campo es requerido');
2592
+ break;
2593
+ case 'min':
2594
+ var minLength = parseInt(validation.params[0]);
2595
+ var minMessage = validation.params[1] || "M\u00EDnimo ".concat(minLength, " caracteres");
2596
+ fieldSchema_1 = fieldSchema_1.min(minLength, minMessage);
2597
+ break;
2598
+ case 'max':
2599
+ var maxLength = parseInt(validation.params[0]);
2600
+ var maxMessage = validation.params[1] || "M\u00E1ximo ".concat(maxLength, " caracteres");
2601
+ fieldSchema_1 = fieldSchema_1.max(maxLength, maxMessage);
2602
+ break;
2603
+ case 'email':
2604
+ var emailMessage = validation.params[0] || 'Email inválido';
2605
+ fieldSchema_1 = fieldSchema_1.email(emailMessage);
2606
+ break;
2607
+ case 'pattern':
2608
+ var pattern = new RegExp(validation.params[0]);
2609
+ var patternMessage = validation.params[1] || 'Formato inválido';
2610
+ fieldSchema_1 = fieldSchema_1.matches(pattern, patternMessage);
2611
+ break;
2612
+ case 'custom':
2613
+ // Para validaciones personalizadas
2614
+ var customValidator = validation.params[0];
2615
+ if (customValidator === 'rut') {
2616
+ fieldSchema_1 = fieldSchema_1.test('rut', validation.params[1] || 'RUT inválido', function (value) {
2617
+ if (!value)
2618
+ return true; // Si está vacío, la validación required se encargará
2619
+ return validate(clean(value));
2620
+ });
2621
+ }
2622
+ else {
2623
+ fieldSchema_1 = fieldSchema_1.test('custom', validation.params[1] || 'Validación fallida', function (value) {
2624
+ // Aquí puedes implementar lógica personalizada
2625
+ return value; // Por defecto pasa la validación
2626
+ });
2627
+ }
2628
+ break;
2629
+ }
2630
+ });
2631
+ schema[field.name] = fieldSchema_1;
2632
+ }
2633
+ else if (field.required) {
2634
+ // Validación básica de requerido si no hay validaciones específicas
2635
+ schema[field.name] = create$6().required("El campo ".concat(field.label, " es requerido"));
2636
+ }
2637
+ });
2638
+ return create$3().shape(schema);
2639
+ };
2640
+ // Validaciones predefinidas
2641
+ var commonValidations = {
2642
+ required: function (message) { return ({
2643
+ type: 'required',
2644
+ params: [message || 'Este campo es requerido'],
2645
+ }); },
2646
+ min: function (length, message) { return ({
2647
+ type: 'min',
2648
+ params: [length.toString(), message || "M\u00EDnimo ".concat(length, " caracteres")],
2649
+ }); },
2650
+ max: function (length, message) { return ({
2651
+ type: 'max',
2652
+ params: [length.toString(), message || "M\u00E1ximo ".concat(length, " caracteres")],
2653
+ }); },
2654
+ email: function (message) { return ({
2655
+ type: 'email',
2656
+ params: [message || 'Email inválido'],
2657
+ }); },
2658
+ pattern: function (regex, message) { return ({
2659
+ type: 'pattern',
2660
+ params: [regex, message || 'Formato inválido'],
2661
+ }); },
2662
+ };
2663
+
2664
+ var GenericForm = function (_a) {
2665
+ var _b, _c, _d, _e, _f, _g, _h;
2666
+ var config = _a.config, _j = _a.stepperData, stepperData = _j === void 0 ? {} : _j, onStepComplete = _a.onStepComplete, _k = _a.loading, loading = _k === void 0 ? false : _k, _l = _a.className, className = _l === void 0 ? '' : _l;
2667
+ // Función para obtener datos del stepper o valores por defecto
2668
+ var getFieldValue = function (field) {
2669
+ var _a;
2670
+ // Prioridad 1: Valor por defecto del campo (máxima prioridad)
2671
+ if ((field === null || field === void 0 ? void 0 : field.value) !== undefined) {
2672
+ return field.value;
2673
+ }
2674
+ // Prioridad 2: Datos del stepper si existe
2675
+ if ((stepperData === null || stepperData === void 0 ? void 0 : stepperData[field === null || field === void 0 ? void 0 : field.name]) !== undefined) {
2676
+ return stepperData[field === null || field === void 0 ? void 0 : field.name];
2677
+ }
2678
+ // Prioridad 3: Datos iniciales de la configuración
2679
+ if (((_a = config.initialData) === null || _a === void 0 ? void 0 : _a[field.name]) !== undefined) {
2680
+ return config.initialData[field.name];
2681
+ }
2682
+ // Prioridad 4: Valor vacío
2683
+ return '';
2684
+ };
2685
+ // Inicializar formData con datos existentes o valores por defecto
2686
+ var getInitialFormData = function () {
2687
+ var initialData = {};
2688
+ if (Array.isArray(config.fields)) {
2689
+ config.fields.forEach(function (field) {
2690
+ initialData[field.name] = getFieldValue(field);
2691
+ });
2692
+ }
2693
+ return initialData;
2694
+ };
2695
+ var _m = React.useState(getInitialFormData), formData = _m[0], setFormData = _m[1];
2696
+ var _o = React.useState({}), errors = _o[0], setErrors = _o[1];
2697
+ // Sincronizar formData cuando cambie stepperData
2698
+ React.useEffect(function () {
2699
+ if (stepperData && Array.isArray(config.fields)) {
2700
+ var updatedFormData_1 = {};
2701
+ config.fields.forEach(function (field) {
2702
+ updatedFormData_1[field.name] =
2703
+ (stepperData === null || stepperData === void 0 ? void 0 : stepperData[field.name]) ||
2704
+ formData[field.name] ||
2705
+ (field === null || field === void 0 ? void 0 : field.value);
2706
+ });
2707
+ setFormData(function (prev) { return (__assign$1(__assign$1({}, prev), updatedFormData_1)); });
2708
+ }
2709
+ }, [stepperData, config.fields]);
2710
+ var handleInputChange = function (e) {
2711
+ var _a = e.target, name = _a.name, value = _a.value, type = _a.type;
2712
+ var checked = type === 'checkbox' ? e.target.checked : undefined;
2713
+ var newValue = type === 'checkbox' ? checked : value;
2714
+ // Actualizar estado local
2715
+ setFormData(function (prevData) {
2716
+ var _a;
2717
+ return (__assign$1(__assign$1({}, prevData), (_a = {}, _a[name] = newValue, _a)));
2718
+ });
2719
+ // Limpiar error del campo
2720
+ if (errors[name]) {
2721
+ setErrors(function (prev) {
2722
+ var _a;
2723
+ return (__assign$1(__assign$1({}, prev), (_a = {}, _a[name] = '', _a)));
2724
+ });
2725
+ }
2726
+ };
2727
+ var validateForm = function () { return __awaiter(void 0, void 0, void 0, function () {
2728
+ var validationSchema, validationError_1, newErrors_1;
2729
+ return __generator(this, function (_a) {
2730
+ switch (_a.label) {
2731
+ case 0:
2732
+ _a.trys.push([0, 2, , 3]);
2733
+ validationSchema = createValidationSchema(config.fields);
2734
+ // Validar los datos del formulario
2735
+ return [4 /*yield*/, validationSchema.validate(__assign$1(__assign$1({}, formData), stepperData), { abortEarly: false })];
2736
+ case 1:
2737
+ // Validar los datos del formulario
2738
+ _a.sent();
2739
+ // Si llega aquí, la validación fue exitosa
2740
+ setErrors({});
2741
+ return [2 /*return*/, true];
2742
+ case 2:
2743
+ validationError_1 = _a.sent();
2744
+ newErrors_1 = {};
2745
+ if (validationError_1.inner) {
2746
+ validationError_1.inner.forEach(function (error) {
2747
+ newErrors_1[error.path] = error.message;
2748
+ });
2749
+ }
2750
+ setErrors(newErrors_1);
2751
+ return [2 /*return*/, false];
2752
+ case 3: return [2 /*return*/];
2753
+ }
2754
+ });
2755
+ }); };
2756
+ var handleNext = function () { return __awaiter(void 0, void 0, void 0, function () {
2757
+ var isValid;
2758
+ return __generator(this, function (_a) {
2759
+ switch (_a.label) {
2760
+ case 0: return [4 /*yield*/, validateForm()];
2761
+ case 1:
2762
+ isValid = _a.sent();
2763
+ if (isValid) {
2764
+ if (onStepComplete) {
2765
+ onStepComplete(2); // Asumiendo que es el paso 2, se puede hacer configurable
2766
+ }
2767
+ if (config.onNext) {
2768
+ config.onNext(__assign$1(__assign$1({}, stepperData), formData));
2769
+ }
2770
+ }
2771
+ return [2 /*return*/];
2772
+ }
2773
+ });
2774
+ }); };
2775
+ var handleOut = function () {
2776
+ if (config.onOut) {
2777
+ config.onOut();
2778
+ }
2779
+ };
2780
+ var handleBack = function () {
2781
+ if (config.onBack) {
2782
+ config.onBack();
2783
+ }
2784
+ };
2785
+ var renderField = function (field) {
2786
+ var _a, _b, _c;
2787
+ // Prioridad: field.value > formData > getFieldValue
2788
+ var fieldValue = (_b = (_a = formData[field.name]) !== null && _a !== void 0 ? _a : field.value) !== null && _b !== void 0 ? _b : getFieldValue(field);
2789
+ // Preparar el campo con las funciones de búsqueda si están disponibles
2790
+ var fieldWithHandlers = __assign$1(__assign$1({}, field), { onSearch: function (value) {
2791
+ var _a;
2792
+ if (field.onSearch) {
2793
+ (_a = config.onSearch) === null || _a === void 0 ? void 0 : _a.call(config, field, value, __assign$1(__assign$1({}, stepperData), formData));
2794
+ }
2795
+ } });
2796
+ return (jsxRuntime.jsx("div", { className: (_c = field.className) !== null && _c !== void 0 ? _c : 'col-span-12 md:col-span-6', children: jsxRuntime.jsx(DynamicInput, { field: fieldWithHandlers, value: fieldValue, onChange: handleInputChange, error: errors[field.name] }) }, field.id));
2797
+ };
2798
+ var buttonHandlers = {
2799
+ handleBack: handleBack,
2800
+ handleNext: handleNext,
2801
+ handleOut: handleOut,
2802
+ // agrega más handlers si es necesario
2803
+ };
2804
+ var isButtonDisabled = function (btn) {
2805
+ if (config.fields.length === 0)
2806
+ return false;
2807
+ if (btn.direction === 'back' || btn.direction === 'out-light')
2808
+ return false;
2809
+ // Tu lógica de disabled para los demás botones:
2810
+ return (btn.disabled ||
2811
+ loading ||
2812
+ !Object.values(formData).some(function (value) { return value !== '' && value !== false; }));
2813
+ };
2814
+ if (loading) {
2815
+ return (jsxRuntime.jsxs("div", { className: "min-h-[550px] flex flex-col justify-between gap-10 ".concat(className), children: [jsxRuntime.jsxs("div", { className: "flex flex-col gap-10", children: [jsxRuntime.jsxs("div", { id: "title", children: [jsxRuntime.jsx("div", { className: "h-8 bg-gray-200 rounded animate-pulse w-3/4 mb-2" }), jsxRuntime.jsx("div", { className: "w-full h-[3px] bg-gray-200 rounded-full animate-pulse" })] }), jsxRuntime.jsxs("div", { className: "text-gray-500 text-lg font-normal flex flex-col gap-2", children: [jsxRuntime.jsx("div", { className: "h-6 bg-gray-200 rounded animate-pulse w-1/2 ml-5" }), jsxRuntime.jsx("div", { className: "w-full h-[1px] bg-gray-200 animate-pulse" })] }), jsxRuntime.jsx("div", { children: jsxRuntime.jsx("div", { className: "flex max-w-1xl mx-auto flex-col gap-4", children: jsxRuntime.jsx("div", { className: "grid grid-cols-12 gap-4", children: (_b = config === null || config === void 0 ? void 0 : config.fields) === null || _b === void 0 ? void 0 : _b.map(function (field) { return (jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-6", children: [jsxRuntime.jsx("div", { className: "h-4 bg-gray-200 rounded animate-pulse w-1/3 mb-2" }), jsxRuntime.jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-full" })] }, field.id)); }) }) }) })] }), jsxRuntime.jsxs("div", { className: "flex justify-between", children: [jsxRuntime.jsxs("div", { className: "flex gap-2", children: [jsxRuntime.jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-20" }), jsxRuntime.jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-20" })] }), jsxRuntime.jsx("div", { className: "h-10 bg-gray-200 rounded animate-pulse w-24" })] })] }));
2816
+ }
2817
+ return (jsxRuntime.jsxs("div", { className: "min-h-[550px] flex flex-col justify-between gap-10 ".concat(className), children: [jsxRuntime.jsxs("div", { className: "flex flex-col gap-10", children: [jsxRuntime.jsxs("div", { id: "title", children: [jsxRuntime.jsx("h1", { className: "text-gray-800 text-3xl font-bold font-roboto", children: config.title }), jsxRuntime.jsx("div", { className: "w-full h-[3px] bg-orange-500 rounded-full mt-2" })] }), (config === null || config === void 0 ? void 0 : config.subtitle) && (jsxRuntime.jsx(jsxRuntime.Fragment, { children: jsxRuntime.jsxs("div", { className: "text-gray-500 text-lg font-normal flex flex-col gap-2", children: [jsxRuntime.jsx("h3", { className: "pl-5 text-[24px] text-gray-800 text-xl font-bold font-roboto", children: config.subtitle }), jsxRuntime.jsx("hr", { className: "w-full border-gray-400" })] }) })), config.showInfoAlert && config.infoMessage && (jsxRuntime.jsx(Alert, { type: (_c = config.infoMessage.type) !== null && _c !== void 0 ? _c : 'info', text: config.infoMessage.message })), jsxRuntime.jsx("div", { children: jsxRuntime.jsx("form", { className: "flex max-w-1xl mx-auto flex-col gap-4", children: jsxRuntime.jsx("div", { className: "grid grid-cols-12 gap-4", children: config.fields.map(renderField) }) }) })] }), ((_d = config === null || config === void 0 ? void 0 : config.navigation) === null || _d === void 0 ? void 0 : _d.buttons) && (jsxRuntime.jsx("div", { className: (_f = (_e = config.navigation) === null || _e === void 0 ? void 0 : _e.containerClass) !== null && _f !== void 0 ? _f : 'flex justify-between', children: (_h = (_g = config === null || config === void 0 ? void 0 : config.navigation) === null || _g === void 0 ? void 0 : _g.buttons) === null || _h === void 0 ? void 0 : _h.map(function (btn) {
2818
+ var _a;
2819
+ return btn.show ? (jsxRuntime.jsx("div", { className: (_a = btn.className) !== null && _a !== void 0 ? _a : '', children: jsxRuntime.jsx(NavigationButton, { direction: btn.direction, onClick: buttonHandlers[btn.onClick], disabled: isButtonDisabled(btn), label: btn.label }) }, btn.key)) : null;
2820
+ }) }))] }));
2821
+ };
2822
+
2823
+ exports.Alert = Alert;
2824
+ exports.CheckboxInput = CheckboxInput;
2825
+ exports.DynamicInput = DynamicInput;
2826
+ exports.GenericForm = GenericForm;
2827
+ exports.InputWrapper = InputWrapper;
2828
+ exports.NavigationButton = NavigationButton;
2829
+ exports.RutInput = RutInput;
2830
+ exports.SelectInput = SelectInput;
2831
+ exports.TextInput = TextInput;
2832
+ exports.TextareaInput = TextareaInput;
2833
+ exports.cleanRut = clean;
2834
+ exports.commonValidations = commonValidations;
2835
+ exports.createValidationSchema = createValidationSchema;
2836
+ exports.formatRut = formatRut;
2837
+ exports.maskRut = maskRut;
2838
+ exports.validateOnlyNumbersAndLetters = validateOnlyNumbersAndLetters;
2839
+ exports.validateRut = validate;
2840
+ //# sourceMappingURL=index.js.map