wizzard-stepper-react 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,2845 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+
29
+ // node_modules/property-expr/index.js
30
+ var require_property_expr = __commonJS({
31
+ "node_modules/property-expr/index.js"(exports, module) {
32
+ "use strict";
33
+ function Cache(maxSize) {
34
+ this._maxSize = maxSize;
35
+ this.clear();
36
+ }
37
+ Cache.prototype.clear = function() {
38
+ this._size = 0;
39
+ this._values = /* @__PURE__ */ Object.create(null);
40
+ };
41
+ Cache.prototype.get = function(key) {
42
+ return this._values[key];
43
+ };
44
+ Cache.prototype.set = function(key, value) {
45
+ this._size >= this._maxSize && this.clear();
46
+ if (!(key in this._values)) this._size++;
47
+ return this._values[key] = value;
48
+ };
49
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g;
50
+ var DIGIT_REGEX = /^\d+$/;
51
+ var LEAD_DIGIT_REGEX = /^\d/;
52
+ var SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g;
53
+ var CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/;
54
+ var MAX_CACHE_SIZE = 512;
55
+ var pathCache = new Cache(MAX_CACHE_SIZE);
56
+ var setCache = new Cache(MAX_CACHE_SIZE);
57
+ var getCache = new Cache(MAX_CACHE_SIZE);
58
+ module.exports = {
59
+ Cache,
60
+ split: split2,
61
+ normalizePath: normalizePath2,
62
+ setter: function(path) {
63
+ var parts = normalizePath2(path);
64
+ return setCache.get(path) || setCache.set(path, function setter(obj, value) {
65
+ var index = 0;
66
+ var len = parts.length;
67
+ var data = obj;
68
+ while (index < len - 1) {
69
+ var part = parts[index];
70
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
71
+ return obj;
72
+ }
73
+ data = data[parts[index++]];
74
+ }
75
+ data[parts[index]] = value;
76
+ });
77
+ },
78
+ getter: function(path, safe) {
79
+ var parts = normalizePath2(path);
80
+ return getCache.get(path) || getCache.set(path, function getter2(data) {
81
+ var index = 0, len = parts.length;
82
+ while (index < len) {
83
+ if (data != null || !safe) data = data[parts[index++]];
84
+ else return;
85
+ }
86
+ return data;
87
+ });
88
+ },
89
+ join: function(segments) {
90
+ return segments.reduce(function(path, part) {
91
+ return path + (isQuoted(part) || DIGIT_REGEX.test(part) ? "[" + part + "]" : (path ? "." : "") + part);
92
+ }, "");
93
+ },
94
+ forEach: function(path, cb, thisArg) {
95
+ forEach2(Array.isArray(path) ? path : split2(path), cb, thisArg);
96
+ }
97
+ };
98
+ function normalizePath2(path) {
99
+ return pathCache.get(path) || pathCache.set(
100
+ path,
101
+ split2(path).map(function(part) {
102
+ return part.replace(CLEAN_QUOTES_REGEX, "$2");
103
+ })
104
+ );
105
+ }
106
+ function split2(path) {
107
+ return path.match(SPLIT_REGEX) || [""];
108
+ }
109
+ function forEach2(parts, iter, thisArg) {
110
+ var len = parts.length, part, idx, isArray, isBracket;
111
+ for (idx = 0; idx < len; idx++) {
112
+ part = parts[idx];
113
+ if (part) {
114
+ if (shouldBeQuoted(part)) {
115
+ part = '"' + part + '"';
116
+ }
117
+ isBracket = isQuoted(part);
118
+ isArray = !isBracket && /^\d+$/.test(part);
119
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
120
+ }
121
+ }
122
+ }
123
+ function isQuoted(str) {
124
+ return typeof str === "string" && str && ["'", '"'].indexOf(str.charAt(0)) !== -1;
125
+ }
126
+ function hasLeadingNumber(part) {
127
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX);
128
+ }
129
+ function hasSpecialChars(part) {
130
+ return SPEC_CHAR_REGEX.test(part);
131
+ }
132
+ function shouldBeQuoted(part) {
133
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part));
134
+ }
135
+ }
136
+ });
137
+
138
+ // node_modules/tiny-case/index.js
139
+ var require_tiny_case = __commonJS({
140
+ "node_modules/tiny-case/index.js"(exports, module) {
141
+ "use strict";
142
+ var 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;
143
+ var words = (str) => str.match(reWords) || [];
144
+ var upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
145
+ var join2 = (str, d) => words(str).join(d).toLowerCase();
146
+ var camelCase2 = (str) => words(str).reduce(
147
+ (acc, next) => `${acc}${!acc ? next.toLowerCase() : next[0].toUpperCase() + next.slice(1).toLowerCase()}`,
148
+ ""
149
+ );
150
+ var pascalCase = (str) => upperFirst(camelCase2(str));
151
+ var snakeCase2 = (str) => join2(str, "_");
152
+ var kebabCase = (str) => join2(str, "-");
153
+ var sentenceCase = (str) => upperFirst(join2(str, " "));
154
+ var titleCase = (str) => words(str).map(upperFirst).join(" ");
155
+ module.exports = {
156
+ words,
157
+ upperFirst,
158
+ camelCase: camelCase2,
159
+ pascalCase,
160
+ snakeCase: snakeCase2,
161
+ kebabCase,
162
+ sentenceCase,
163
+ titleCase
164
+ };
165
+ }
166
+ });
167
+
168
+ // node_modules/toposort/index.js
169
+ var require_toposort = __commonJS({
170
+ "node_modules/toposort/index.js"(exports, module) {
171
+ "use strict";
172
+ module.exports = function(edges) {
173
+ return toposort2(uniqueNodes(edges), edges);
174
+ };
175
+ module.exports.array = toposort2;
176
+ function toposort2(nodes, edges) {
177
+ var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes);
178
+ edges.forEach(function(edge) {
179
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
180
+ throw new Error("Unknown node. There is an unknown node in the supplied edges.");
181
+ }
182
+ });
183
+ while (i--) {
184
+ if (!visited[i]) visit(nodes[i], i, /* @__PURE__ */ new Set());
185
+ }
186
+ return sorted;
187
+ function visit(node, i2, predecessors) {
188
+ if (predecessors.has(node)) {
189
+ var nodeRep;
190
+ try {
191
+ nodeRep = ", node was:" + JSON.stringify(node);
192
+ } catch (e) {
193
+ nodeRep = "";
194
+ }
195
+ throw new Error("Cyclic dependency" + nodeRep);
196
+ }
197
+ if (!nodesHash.has(node)) {
198
+ throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node));
199
+ }
200
+ if (visited[i2]) return;
201
+ visited[i2] = true;
202
+ var outgoing = outgoingEdges.get(node) || /* @__PURE__ */ new Set();
203
+ outgoing = Array.from(outgoing);
204
+ if (i2 = outgoing.length) {
205
+ predecessors.add(node);
206
+ do {
207
+ var child = outgoing[--i2];
208
+ visit(child, nodesHash.get(child), predecessors);
209
+ } while (i2);
210
+ predecessors.delete(node);
211
+ }
212
+ sorted[--cursor] = node;
213
+ }
214
+ }
215
+ function uniqueNodes(arr) {
216
+ var res = /* @__PURE__ */ new Set();
217
+ for (var i = 0, len = arr.length; i < len; i++) {
218
+ var edge = arr[i];
219
+ res.add(edge[0]);
220
+ res.add(edge[1]);
221
+ }
222
+ return Array.from(res);
223
+ }
224
+ function makeOutgoingEdges(arr) {
225
+ var edges = /* @__PURE__ */ new Map();
226
+ for (var i = 0, len = arr.length; i < len; i++) {
227
+ var edge = arr[i];
228
+ if (!edges.has(edge[0])) edges.set(edge[0], /* @__PURE__ */ new Set());
229
+ if (!edges.has(edge[1])) edges.set(edge[1], /* @__PURE__ */ new Set());
230
+ edges.get(edge[0]).add(edge[1]);
231
+ }
232
+ return edges;
233
+ }
234
+ function makeNodesHash(arr) {
235
+ var res = /* @__PURE__ */ new Map();
236
+ for (var i = 0, len = arr.length; i < len; i++) {
237
+ res.set(arr[i], i);
238
+ }
239
+ return res;
240
+ }
241
+ }
242
+ });
243
+
244
+ // src/context/WizardContext.tsx
245
+ import { createContext, useContext, useEffect, useMemo, useState, useCallback } from "react";
246
+
247
+ // src/adapters/persistence/MemoryAdapter.ts
248
+ var MemoryAdapter = class {
249
+ constructor() {
250
+ __publicField(this, "storage", {});
251
+ }
252
+ saveStep(stepId, data) {
253
+ this.storage[stepId] = data;
254
+ }
255
+ getStep(stepId) {
256
+ return this.storage[stepId];
257
+ }
258
+ clear() {
259
+ this.storage = {};
260
+ }
261
+ };
262
+
263
+ // src/context/WizardContext.tsx
264
+ import { jsx } from "react/jsx-runtime";
265
+ var WizardContext = createContext(void 0);
266
+ function WizardProvider({
267
+ config,
268
+ initialData,
269
+ children
270
+ }) {
271
+ const [currentStepId, setCurrentStepId] = useState("");
272
+ const [wizardData, setWizardData] = useState(initialData || {});
273
+ const [visitedSteps, setVisitedSteps] = useState(/* @__PURE__ */ new Set());
274
+ const [completedSteps, setCompletedSteps] = useState(/* @__PURE__ */ new Set());
275
+ const [errorSteps, setErrorSteps] = useState(/* @__PURE__ */ new Set());
276
+ const [allErrors, setAllErrors] = useState({});
277
+ const [isLoading, setIsLoading] = useState(true);
278
+ const persistenceAdapter = useMemo(() => {
279
+ return config.persistence?.adapter || new MemoryAdapter();
280
+ }, [config.persistence?.adapter]);
281
+ const persistenceMode = config.persistence?.mode || "onStepChange";
282
+ const activeSteps = useMemo(() => {
283
+ return config.steps.filter((step) => {
284
+ if (step.condition) {
285
+ return step.condition(wizardData);
286
+ }
287
+ return true;
288
+ });
289
+ }, [config.steps, wizardData]);
290
+ useEffect(() => {
291
+ if (!currentStepId && activeSteps.length > 0) {
292
+ setCurrentStepId(activeSteps[0].id);
293
+ setIsLoading(false);
294
+ }
295
+ }, [activeSteps, currentStepId]);
296
+ const currentStep = useMemo(() => activeSteps.find((s) => s.id === currentStepId) || null, [activeSteps, currentStepId]);
297
+ const currentStepIndex = useMemo(() => activeSteps.findIndex((s) => s.id === currentStepId), [activeSteps, currentStepId]);
298
+ const isFirstStep = currentStepIndex === 0;
299
+ const isLastStep = currentStepIndex === activeSteps.length - 1;
300
+ const META_KEY = "__wizzard_meta__";
301
+ const hydrate = useCallback(() => {
302
+ setIsLoading(true);
303
+ const metaFn = persistenceAdapter.getStep(META_KEY);
304
+ if (metaFn) {
305
+ if (metaFn.currentStepId) setCurrentStepId(metaFn.currentStepId);
306
+ if (metaFn.visited) setVisitedSteps(new Set(metaFn.visited));
307
+ if (metaFn.completed) setCompletedSteps(new Set(metaFn.completed));
308
+ }
309
+ const loadedData = {};
310
+ config.steps.forEach((step) => {
311
+ const stepData = persistenceAdapter.getStep(step.id);
312
+ if (stepData) {
313
+ Object.assign(loadedData, stepData);
314
+ }
315
+ });
316
+ if (Object.keys(loadedData).length > 0) {
317
+ setWizardData((prev) => ({ ...prev, ...loadedData }));
318
+ }
319
+ setIsLoading(false);
320
+ }, [config.steps, persistenceAdapter]);
321
+ useEffect(() => {
322
+ hydrate();
323
+ }, [hydrate]);
324
+ const saveData = useCallback((mode, stepId, data) => {
325
+ if (mode === persistenceMode || mode === "manual") {
326
+ persistenceAdapter.saveStep(stepId, data);
327
+ }
328
+ }, [persistenceAdapter, persistenceMode]);
329
+ const setStepData = useCallback((stepId, data) => {
330
+ setWizardData((prev) => {
331
+ const newData = { ...prev, ...data };
332
+ if (persistenceMode === "onChange") {
333
+ saveData("onChange", stepId, newData);
334
+ }
335
+ return newData;
336
+ });
337
+ }, [persistenceMode, saveData]);
338
+ const handleStepChange = useCallback((field, value2) => {
339
+ if (!currentStepId) return;
340
+ setStepData(currentStepId, { [field]: value2 });
341
+ }, [currentStepId, setStepData]);
342
+ const validateStep = useCallback(async (stepId) => {
343
+ const step = config.steps.find((s) => s.id === stepId);
344
+ if (!step) return true;
345
+ if (!step.validationAdapter) return true;
346
+ const result = await step.validationAdapter.validate(wizardData);
347
+ if (!result.isValid) {
348
+ setAllErrors((prev) => ({
349
+ ...prev,
350
+ [stepId]: result.errors || {}
351
+ }));
352
+ setErrorSteps((prev) => new Set(prev).add(stepId));
353
+ return false;
354
+ } else {
355
+ setAllErrors((prev) => {
356
+ const next = { ...prev };
357
+ delete next[stepId];
358
+ return next;
359
+ });
360
+ setErrorSteps((prev) => {
361
+ const next = new Set(prev);
362
+ next.delete(stepId);
363
+ return next;
364
+ });
365
+ return true;
366
+ }
367
+ }, [config.steps, wizardData]);
368
+ const validateAll = useCallback(async () => {
369
+ let isValid = true;
370
+ for (const step of activeSteps) {
371
+ const stepValid = await validateStep(step.id);
372
+ if (!stepValid) isValid = false;
373
+ }
374
+ return isValid;
375
+ }, [activeSteps, validateStep]);
376
+ const goToStep = useCallback(async (stepId) => {
377
+ const targetIndex = activeSteps.findIndex((s) => s.id === stepId);
378
+ if (targetIndex === -1) return;
379
+ if (targetIndex > currentStepIndex) {
380
+ const shouldValidate = currentStep?.autoValidate ?? config.autoValidate ?? true;
381
+ if (shouldValidate) {
382
+ const isValid = await validateStep(currentStepId);
383
+ if (!isValid) return;
384
+ }
385
+ }
386
+ if (persistenceMode === "onStepChange" && currentStep) {
387
+ saveData("onStepChange", currentStepId, wizardData);
388
+ }
389
+ const nextVisited = new Set(visitedSteps).add(currentStepId);
390
+ setVisitedSteps(nextVisited);
391
+ setCurrentStepId(stepId);
392
+ if (persistenceMode !== "manual") {
393
+ persistenceAdapter.saveStep(META_KEY, {
394
+ currentStepId: stepId,
395
+ visited: Array.from(nextVisited),
396
+ completed: Array.from(completedSteps)
397
+ });
398
+ }
399
+ window.scrollTo(0, 0);
400
+ }, [activeSteps, currentStepId, currentStep, currentStepIndex, config.autoValidate, persistenceMode, saveData, wizardData, validateStep, visitedSteps, completedSteps, persistenceAdapter]);
401
+ const goToNextStep = useCallback(async () => {
402
+ if (isLastStep) return;
403
+ const nextStep = activeSteps[currentStepIndex + 1];
404
+ if (nextStep) {
405
+ const nextCompleted = new Set(completedSteps).add(currentStepId);
406
+ setCompletedSteps(nextCompleted);
407
+ await goToStep(nextStep.id);
408
+ if (persistenceMode !== "manual") {
409
+ persistenceAdapter.saveStep(META_KEY, {
410
+ currentStepId: nextStep.id,
411
+ visited: Array.from(new Set(visitedSteps).add(currentStepId)),
412
+ completed: Array.from(nextCompleted)
413
+ });
414
+ }
415
+ }
416
+ }, [activeSteps, currentStepIndex, isLastStep, currentStepId, goToStep, visitedSteps, completedSteps, persistenceMode, persistenceAdapter]);
417
+ const goToPrevStep = useCallback(() => {
418
+ if (isFirstStep) return;
419
+ const prevStep = activeSteps[currentStepIndex - 1];
420
+ if (prevStep) {
421
+ goToStep(prevStep.id);
422
+ }
423
+ }, [activeSteps, currentStepIndex, isFirstStep, goToStep]);
424
+ const value = {
425
+ currentStep,
426
+ currentStepIndex,
427
+ isFirstStep,
428
+ isLastStep,
429
+ isLoading,
430
+ activeSteps,
431
+ wizardData,
432
+ allErrors,
433
+ visitedSteps,
434
+ completedSteps,
435
+ errorSteps,
436
+ goToNextStep,
437
+ goToPrevStep,
438
+ goToStep,
439
+ setStepData,
440
+ handleStepChange,
441
+ validateStep,
442
+ validateAll,
443
+ save: () => saveData("manual", currentStepId, wizardData),
444
+ clearStorage: () => persistenceAdapter.clear()
445
+ };
446
+ return /* @__PURE__ */ jsx(WizardContext.Provider, { value, children });
447
+ }
448
+ function useWizardContext() {
449
+ const context = useContext(WizardContext);
450
+ if (!context) {
451
+ throw new Error("useWizardContext must be used within a WizardProvider");
452
+ }
453
+ return context;
454
+ }
455
+
456
+ // src/hooks/useWizard.ts
457
+ var useWizard = () => {
458
+ return useWizardContext();
459
+ };
460
+
461
+ // src/adapters/persistence/LocalStorageAdapter.ts
462
+ var LocalStorageAdapter = class {
463
+ constructor(prefix = "wizard_") {
464
+ __publicField(this, "prefix");
465
+ this.prefix = prefix;
466
+ }
467
+ getKey(stepId) {
468
+ return `${this.prefix}${stepId}`;
469
+ }
470
+ saveStep(stepId, data) {
471
+ if (typeof window === "undefined") return;
472
+ try {
473
+ localStorage.setItem(this.getKey(stepId), JSON.stringify(data));
474
+ } catch (error) {
475
+ console.warn("LocalStorageAdapter: Failed to save step", error);
476
+ }
477
+ }
478
+ getStep(stepId) {
479
+ if (typeof window === "undefined") return void 0;
480
+ try {
481
+ const item = localStorage.getItem(this.getKey(stepId));
482
+ return item ? JSON.parse(item) : void 0;
483
+ } catch (error) {
484
+ console.warn("LocalStorageAdapter: Failed to get step", error);
485
+ return void 0;
486
+ }
487
+ }
488
+ clear() {
489
+ if (typeof window === "undefined") return;
490
+ Object.keys(localStorage).forEach((key) => {
491
+ if (key.startsWith(this.prefix)) {
492
+ localStorage.removeItem(key);
493
+ }
494
+ });
495
+ }
496
+ };
497
+
498
+ // src/adapters/validation/ZodAdapter.ts
499
+ var ZodAdapter = class {
500
+ constructor(schema) {
501
+ this.schema = schema;
502
+ }
503
+ async validate(data) {
504
+ const result = await this.schema.safeParseAsync(data);
505
+ if (result.success) {
506
+ return { isValid: true };
507
+ }
508
+ const errors = {};
509
+ result.error.issues.forEach((err) => {
510
+ const path = err.path.join(".");
511
+ errors[path] = err.message;
512
+ });
513
+ return { isValid: false, errors };
514
+ }
515
+ };
516
+
517
+ // node_modules/yup/index.esm.js
518
+ var import_property_expr = __toESM(require_property_expr());
519
+ var import_tiny_case = __toESM(require_tiny_case());
520
+ var import_toposort = __toESM(require_toposort());
521
+ var toString = Object.prototype.toString;
522
+ var errorToString = Error.prototype.toString;
523
+ var regExpToString = RegExp.prototype.toString;
524
+ var symbolToString = typeof Symbol !== "undefined" ? Symbol.prototype.toString : () => "";
525
+ var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
526
+ function printNumber(val) {
527
+ if (val != +val) return "NaN";
528
+ const isNegativeZero = val === 0 && 1 / val < 0;
529
+ return isNegativeZero ? "-0" : "" + val;
530
+ }
531
+ function printSimpleValue(val, quoteStrings = false) {
532
+ if (val == null || val === true || val === false) return "" + val;
533
+ const typeOf = typeof val;
534
+ if (typeOf === "number") return printNumber(val);
535
+ if (typeOf === "string") return quoteStrings ? `"${val}"` : val;
536
+ if (typeOf === "function") return "[Function " + (val.name || "anonymous") + "]";
537
+ if (typeOf === "symbol") return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)");
538
+ const tag = toString.call(val).slice(8, -1);
539
+ if (tag === "Date") return isNaN(val.getTime()) ? "" + val : val.toISOString(val);
540
+ if (tag === "Error" || val instanceof Error) return "[" + errorToString.call(val) + "]";
541
+ if (tag === "RegExp") return regExpToString.call(val);
542
+ return null;
543
+ }
544
+ function printValue(value, quoteStrings) {
545
+ let result = printSimpleValue(value, quoteStrings);
546
+ if (result !== null) return result;
547
+ return JSON.stringify(value, function(key, value2) {
548
+ let result2 = printSimpleValue(this[key], quoteStrings);
549
+ if (result2 !== null) return result2;
550
+ return value2;
551
+ }, 2);
552
+ }
553
+ function toArray(value) {
554
+ return value == null ? [] : [].concat(value);
555
+ }
556
+ var _Symbol$toStringTag;
557
+ var _Symbol$hasInstance;
558
+ var _Symbol$toStringTag2;
559
+ var strReg = /\$\{\s*(\w+)\s*\}/g;
560
+ _Symbol$toStringTag = Symbol.toStringTag;
561
+ var ValidationErrorNoStack = class {
562
+ constructor(errorOrErrors, value, field, type) {
563
+ this.name = void 0;
564
+ this.message = void 0;
565
+ this.value = void 0;
566
+ this.path = void 0;
567
+ this.type = void 0;
568
+ this.params = void 0;
569
+ this.errors = void 0;
570
+ this.inner = void 0;
571
+ this[_Symbol$toStringTag] = "Error";
572
+ this.name = "ValidationError";
573
+ this.value = value;
574
+ this.path = field;
575
+ this.type = type;
576
+ this.errors = [];
577
+ this.inner = [];
578
+ toArray(errorOrErrors).forEach((err) => {
579
+ if (ValidationError.isError(err)) {
580
+ this.errors.push(...err.errors);
581
+ const innerErrors = err.inner.length ? err.inner : [err];
582
+ this.inner.push(...innerErrors);
583
+ } else {
584
+ this.errors.push(err);
585
+ }
586
+ });
587
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
588
+ }
589
+ };
590
+ _Symbol$hasInstance = Symbol.hasInstance;
591
+ _Symbol$toStringTag2 = Symbol.toStringTag;
592
+ var ValidationError = class _ValidationError extends Error {
593
+ static formatError(message, params) {
594
+ const path = params.label || params.path || "this";
595
+ params = Object.assign({}, params, {
596
+ path,
597
+ originalPath: params.path
598
+ });
599
+ if (typeof message === "string") return message.replace(strReg, (_, key) => printValue(params[key]));
600
+ if (typeof message === "function") return message(params);
601
+ return message;
602
+ }
603
+ static isError(err) {
604
+ return err && err.name === "ValidationError";
605
+ }
606
+ constructor(errorOrErrors, value, field, type, disableStack) {
607
+ const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);
608
+ if (disableStack) {
609
+ return errorNoStack;
610
+ }
611
+ super();
612
+ this.value = void 0;
613
+ this.path = void 0;
614
+ this.type = void 0;
615
+ this.params = void 0;
616
+ this.errors = [];
617
+ this.inner = [];
618
+ this[_Symbol$toStringTag2] = "Error";
619
+ this.name = errorNoStack.name;
620
+ this.message = errorNoStack.message;
621
+ this.type = errorNoStack.type;
622
+ this.value = errorNoStack.value;
623
+ this.path = errorNoStack.path;
624
+ this.errors = errorNoStack.errors;
625
+ this.inner = errorNoStack.inner;
626
+ if (Error.captureStackTrace) {
627
+ Error.captureStackTrace(this, _ValidationError);
628
+ }
629
+ }
630
+ static [_Symbol$hasInstance](inst) {
631
+ return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);
632
+ }
633
+ };
634
+ var mixed = {
635
+ default: "${path} is invalid",
636
+ required: "${path} is a required field",
637
+ defined: "${path} must be defined",
638
+ notNull: "${path} cannot be null",
639
+ oneOf: "${path} must be one of the following values: ${values}",
640
+ notOneOf: "${path} must not be one of the following values: ${values}",
641
+ notType: ({
642
+ path,
643
+ type,
644
+ value,
645
+ originalValue
646
+ }) => {
647
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : ".";
648
+ 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;
649
+ }
650
+ };
651
+ var string = {
652
+ length: "${path} must be exactly ${length} characters",
653
+ min: "${path} must be at least ${min} characters",
654
+ max: "${path} must be at most ${max} characters",
655
+ matches: '${path} must match the following: "${regex}"',
656
+ email: "${path} must be a valid email",
657
+ url: "${path} must be a valid URL",
658
+ uuid: "${path} must be a valid UUID",
659
+ datetime: "${path} must be a valid ISO date-time",
660
+ datetime_precision: "${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits",
661
+ datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone',
662
+ trim: "${path} must be a trimmed string",
663
+ lowercase: "${path} must be a lowercase string",
664
+ uppercase: "${path} must be a upper case string"
665
+ };
666
+ var number = {
667
+ min: "${path} must be greater than or equal to ${min}",
668
+ max: "${path} must be less than or equal to ${max}",
669
+ lessThan: "${path} must be less than ${less}",
670
+ moreThan: "${path} must be greater than ${more}",
671
+ positive: "${path} must be a positive number",
672
+ negative: "${path} must be a negative number",
673
+ integer: "${path} must be an integer"
674
+ };
675
+ var date = {
676
+ min: "${path} field must be later than ${min}",
677
+ max: "${path} field must be at earlier than ${max}"
678
+ };
679
+ var boolean = {
680
+ isValue: "${path} field must be ${value}"
681
+ };
682
+ var object = {
683
+ noUnknown: "${path} field has unspecified keys: ${unknown}",
684
+ exact: "${path} object contains unknown properties: ${properties}"
685
+ };
686
+ var array = {
687
+ min: "${path} field must have at least ${min} items",
688
+ max: "${path} field must have less than or equal to ${max} items",
689
+ length: "${path} must have ${length} items"
690
+ };
691
+ var tuple = {
692
+ notType: (params) => {
693
+ const {
694
+ path,
695
+ value,
696
+ spec
697
+ } = params;
698
+ const typeLen = spec.types.length;
699
+ if (Array.isArray(value)) {
700
+ 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)}\``;
701
+ 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)}\``;
702
+ }
703
+ return ValidationError.formatError(mixed.notType, params);
704
+ }
705
+ };
706
+ var locale = Object.assign(/* @__PURE__ */ Object.create(null), {
707
+ mixed,
708
+ string,
709
+ number,
710
+ date,
711
+ object,
712
+ array,
713
+ boolean,
714
+ tuple
715
+ });
716
+ var isSchema = (obj) => obj && obj.__isYupSchema__;
717
+ var Condition = class _Condition {
718
+ static fromOptions(refs, config) {
719
+ if (!config.then && !config.otherwise) throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");
720
+ let {
721
+ is,
722
+ then,
723
+ otherwise
724
+ } = config;
725
+ let check = typeof is === "function" ? is : (...values) => values.every((value) => value === is);
726
+ return new _Condition(refs, (values, schema) => {
727
+ var _branch;
728
+ let branch = check(...values) ? then : otherwise;
729
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
730
+ });
731
+ }
732
+ constructor(refs, builder) {
733
+ this.fn = void 0;
734
+ this.refs = refs;
735
+ this.refs = refs;
736
+ this.fn = builder;
737
+ }
738
+ resolve(base, options) {
739
+ let values = this.refs.map((ref) => (
740
+ // TODO: ? operator here?
741
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context)
742
+ ));
743
+ let schema = this.fn(values, base, options);
744
+ if (schema === void 0 || // @ts-ignore this can be base
745
+ schema === base) {
746
+ return base;
747
+ }
748
+ if (!isSchema(schema)) throw new TypeError("conditions must return a schema object");
749
+ return schema.resolve(options);
750
+ }
751
+ };
752
+ var prefixes = {
753
+ context: "$",
754
+ value: "."
755
+ };
756
+ var Reference = class {
757
+ constructor(key, options = {}) {
758
+ this.key = void 0;
759
+ this.isContext = void 0;
760
+ this.isValue = void 0;
761
+ this.isSibling = void 0;
762
+ this.path = void 0;
763
+ this.getter = void 0;
764
+ this.map = void 0;
765
+ if (typeof key !== "string") throw new TypeError("ref must be a string, got: " + key);
766
+ this.key = key.trim();
767
+ if (key === "") throw new TypeError("ref must be a non-empty string");
768
+ this.isContext = this.key[0] === prefixes.context;
769
+ this.isValue = this.key[0] === prefixes.value;
770
+ this.isSibling = !this.isContext && !this.isValue;
771
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : "";
772
+ this.path = this.key.slice(prefix.length);
773
+ this.getter = this.path && (0, import_property_expr.getter)(this.path, true);
774
+ this.map = options.map;
775
+ }
776
+ getValue(value, parent, context) {
777
+ let result = this.isContext ? context : this.isValue ? value : parent;
778
+ if (this.getter) result = this.getter(result || {});
779
+ if (this.map) result = this.map(result);
780
+ return result;
781
+ }
782
+ /**
783
+ *
784
+ * @param {*} value
785
+ * @param {Object} options
786
+ * @param {Object=} options.context
787
+ * @param {Object=} options.parent
788
+ */
789
+ cast(value, options) {
790
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
791
+ }
792
+ resolve() {
793
+ return this;
794
+ }
795
+ describe() {
796
+ return {
797
+ type: "ref",
798
+ key: this.key
799
+ };
800
+ }
801
+ toString() {
802
+ return `Ref(${this.key})`;
803
+ }
804
+ static isRef(value) {
805
+ return value && value.__isYupRef;
806
+ }
807
+ };
808
+ Reference.prototype.__isYupRef = true;
809
+ var isAbsent = (value) => value == null;
810
+ function createValidation(config) {
811
+ function validate({
812
+ value,
813
+ path = "",
814
+ options,
815
+ originalValue,
816
+ schema
817
+ }, panic, next) {
818
+ const {
819
+ name,
820
+ test,
821
+ params,
822
+ message,
823
+ skipAbsent
824
+ } = config;
825
+ let {
826
+ parent,
827
+ context,
828
+ abortEarly = schema.spec.abortEarly,
829
+ disableStackTrace = schema.spec.disableStackTrace
830
+ } = options;
831
+ const resolveOptions = {
832
+ value,
833
+ parent,
834
+ context
835
+ };
836
+ function createError(overrides = {}) {
837
+ const nextParams = resolveParams(Object.assign({
838
+ value,
839
+ originalValue,
840
+ label: schema.spec.label,
841
+ path: overrides.path || path,
842
+ spec: schema.spec,
843
+ disableStackTrace: overrides.disableStackTrace || disableStackTrace
844
+ }, params, overrides.params), resolveOptions);
845
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);
846
+ error.params = nextParams;
847
+ return error;
848
+ }
849
+ const invalid = abortEarly ? panic : next;
850
+ let ctx = {
851
+ path,
852
+ parent,
853
+ type: name,
854
+ from: options.from,
855
+ createError,
856
+ resolve(item) {
857
+ return resolveMaybeRef(item, resolveOptions);
858
+ },
859
+ options,
860
+ originalValue,
861
+ schema
862
+ };
863
+ const handleResult = (validOrError) => {
864
+ if (ValidationError.isError(validOrError)) invalid(validOrError);
865
+ else if (!validOrError) invalid(createError());
866
+ else next(null);
867
+ };
868
+ const handleError = (err) => {
869
+ if (ValidationError.isError(err)) invalid(err);
870
+ else panic(err);
871
+ };
872
+ const shouldSkip = skipAbsent && isAbsent(value);
873
+ if (shouldSkip) {
874
+ return handleResult(true);
875
+ }
876
+ let result;
877
+ try {
878
+ var _result;
879
+ result = test.call(ctx, value, ctx);
880
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === "function") {
881
+ if (options.sync) {
882
+ 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`);
883
+ }
884
+ return Promise.resolve(result).then(handleResult, handleError);
885
+ }
886
+ } catch (err) {
887
+ handleError(err);
888
+ return;
889
+ }
890
+ handleResult(result);
891
+ }
892
+ validate.OPTIONS = config;
893
+ return validate;
894
+ }
895
+ function resolveParams(params, options) {
896
+ if (!params) return params;
897
+ for (const key of Object.keys(params)) {
898
+ params[key] = resolveMaybeRef(params[key], options);
899
+ }
900
+ return params;
901
+ }
902
+ function resolveMaybeRef(item, options) {
903
+ return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item;
904
+ }
905
+ function getIn(schema, path, value, context = value) {
906
+ let parent, lastPart, lastPartDebug;
907
+ if (!path) return {
908
+ parent,
909
+ parentPath: path,
910
+ schema
911
+ };
912
+ (0, import_property_expr.forEach)(path, (_part, isBracket, isArray) => {
913
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
914
+ schema = schema.resolve({
915
+ context,
916
+ parent,
917
+ value
918
+ });
919
+ let isTuple = schema.type === "tuple";
920
+ let idx = isArray ? parseInt(part, 10) : 0;
921
+ if (schema.innerType || isTuple) {
922
+ 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]"`);
923
+ if (value && idx >= value.length) {
924
+ 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. `);
925
+ }
926
+ parent = value;
927
+ value = value && value[idx];
928
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
929
+ }
930
+ if (!isArray) {
931
+ 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}")`);
932
+ parent = value;
933
+ value = value && value[part];
934
+ schema = schema.fields[part];
935
+ }
936
+ lastPart = part;
937
+ lastPartDebug = isBracket ? "[" + _part + "]" : "." + _part;
938
+ });
939
+ return {
940
+ schema,
941
+ parent,
942
+ parentPath: lastPart
943
+ };
944
+ }
945
+ var ReferenceSet = class _ReferenceSet extends Set {
946
+ describe() {
947
+ const description = [];
948
+ for (const item of this.values()) {
949
+ description.push(Reference.isRef(item) ? item.describe() : item);
950
+ }
951
+ return description;
952
+ }
953
+ resolveAll(resolve) {
954
+ let result = [];
955
+ for (const item of this.values()) {
956
+ result.push(resolve(item));
957
+ }
958
+ return result;
959
+ }
960
+ clone() {
961
+ return new _ReferenceSet(this.values());
962
+ }
963
+ merge(newItems, removeItems) {
964
+ const next = this.clone();
965
+ newItems.forEach((value) => next.add(value));
966
+ removeItems.forEach((value) => next.delete(value));
967
+ return next;
968
+ }
969
+ };
970
+ function clone(src, seen = /* @__PURE__ */ new Map()) {
971
+ if (isSchema(src) || !src || typeof src !== "object") return src;
972
+ if (seen.has(src)) return seen.get(src);
973
+ let copy;
974
+ if (src instanceof Date) {
975
+ copy = new Date(src.getTime());
976
+ seen.set(src, copy);
977
+ } else if (src instanceof RegExp) {
978
+ copy = new RegExp(src);
979
+ seen.set(src, copy);
980
+ } else if (Array.isArray(src)) {
981
+ copy = new Array(src.length);
982
+ seen.set(src, copy);
983
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
984
+ } else if (src instanceof Map) {
985
+ copy = /* @__PURE__ */ new Map();
986
+ seen.set(src, copy);
987
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
988
+ } else if (src instanceof Set) {
989
+ copy = /* @__PURE__ */ new Set();
990
+ seen.set(src, copy);
991
+ for (const v of src) copy.add(clone(v, seen));
992
+ } else if (src instanceof Object) {
993
+ copy = {};
994
+ seen.set(src, copy);
995
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
996
+ } else {
997
+ throw Error(`Unable to clone ${src}`);
998
+ }
999
+ return copy;
1000
+ }
1001
+ function createStandardPath(path) {
1002
+ if (!(path != null && path.length)) {
1003
+ return void 0;
1004
+ }
1005
+ const segments = [];
1006
+ let currentSegment = "";
1007
+ let inBrackets = false;
1008
+ let inQuotes = false;
1009
+ for (let i = 0; i < path.length; i++) {
1010
+ const char = path[i];
1011
+ if (char === "[" && !inQuotes) {
1012
+ if (currentSegment) {
1013
+ segments.push(...currentSegment.split(".").filter(Boolean));
1014
+ currentSegment = "";
1015
+ }
1016
+ inBrackets = true;
1017
+ continue;
1018
+ }
1019
+ if (char === "]" && !inQuotes) {
1020
+ if (currentSegment) {
1021
+ if (/^\d+$/.test(currentSegment)) {
1022
+ segments.push(currentSegment);
1023
+ } else {
1024
+ segments.push(currentSegment.replace(/^"|"$/g, ""));
1025
+ }
1026
+ currentSegment = "";
1027
+ }
1028
+ inBrackets = false;
1029
+ continue;
1030
+ }
1031
+ if (char === '"') {
1032
+ inQuotes = !inQuotes;
1033
+ continue;
1034
+ }
1035
+ if (char === "." && !inBrackets && !inQuotes) {
1036
+ if (currentSegment) {
1037
+ segments.push(currentSegment);
1038
+ currentSegment = "";
1039
+ }
1040
+ continue;
1041
+ }
1042
+ currentSegment += char;
1043
+ }
1044
+ if (currentSegment) {
1045
+ segments.push(...currentSegment.split(".").filter(Boolean));
1046
+ }
1047
+ return segments;
1048
+ }
1049
+ function createStandardIssues(error, parentPath) {
1050
+ const path = parentPath ? `${parentPath}.${error.path}` : error.path;
1051
+ return error.errors.map((err) => ({
1052
+ message: err,
1053
+ path: createStandardPath(path)
1054
+ }));
1055
+ }
1056
+ function issuesFromValidationError(error, parentPath) {
1057
+ var _error$inner;
1058
+ if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) {
1059
+ return createStandardIssues(error, parentPath);
1060
+ }
1061
+ const path = parentPath ? `${parentPath}.${error.path}` : error.path;
1062
+ return error.inner.flatMap((err) => issuesFromValidationError(err, path));
1063
+ }
1064
+ var Schema = class {
1065
+ constructor(options) {
1066
+ this.type = void 0;
1067
+ this.deps = [];
1068
+ this.tests = void 0;
1069
+ this.transforms = void 0;
1070
+ this.conditions = [];
1071
+ this._mutate = void 0;
1072
+ this.internalTests = {};
1073
+ this._whitelist = new ReferenceSet();
1074
+ this._blacklist = new ReferenceSet();
1075
+ this.exclusiveTests = /* @__PURE__ */ Object.create(null);
1076
+ this._typeCheck = void 0;
1077
+ this.spec = void 0;
1078
+ this.tests = [];
1079
+ this.transforms = [];
1080
+ this.withMutation(() => {
1081
+ this.typeError(mixed.notType);
1082
+ });
1083
+ this.type = options.type;
1084
+ this._typeCheck = options.check;
1085
+ this.spec = Object.assign({
1086
+ strip: false,
1087
+ strict: false,
1088
+ abortEarly: true,
1089
+ recursive: true,
1090
+ disableStackTrace: false,
1091
+ nullable: false,
1092
+ optional: true,
1093
+ coerce: true
1094
+ }, options == null ? void 0 : options.spec);
1095
+ this.withMutation((s) => {
1096
+ s.nonNullable();
1097
+ });
1098
+ }
1099
+ // TODO: remove
1100
+ get _type() {
1101
+ return this.type;
1102
+ }
1103
+ clone(spec) {
1104
+ if (this._mutate) {
1105
+ if (spec) Object.assign(this.spec, spec);
1106
+ return this;
1107
+ }
1108
+ const next = Object.create(Object.getPrototypeOf(this));
1109
+ next.type = this.type;
1110
+ next._typeCheck = this._typeCheck;
1111
+ next._whitelist = this._whitelist.clone();
1112
+ next._blacklist = this._blacklist.clone();
1113
+ next.internalTests = Object.assign({}, this.internalTests);
1114
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
1115
+ next.deps = [...this.deps];
1116
+ next.conditions = [...this.conditions];
1117
+ next.tests = [...this.tests];
1118
+ next.transforms = [...this.transforms];
1119
+ next.spec = clone(Object.assign({}, this.spec, spec));
1120
+ return next;
1121
+ }
1122
+ label(label) {
1123
+ let next = this.clone();
1124
+ next.spec.label = label;
1125
+ return next;
1126
+ }
1127
+ meta(...args) {
1128
+ if (args.length === 0) return this.spec.meta;
1129
+ let next = this.clone();
1130
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
1131
+ return next;
1132
+ }
1133
+ withMutation(fn) {
1134
+ let before = this._mutate;
1135
+ this._mutate = true;
1136
+ let result = fn(this);
1137
+ this._mutate = before;
1138
+ return result;
1139
+ }
1140
+ concat(schema) {
1141
+ if (!schema || schema === this) return this;
1142
+ if (schema.type !== this.type && this.type !== "mixed") throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
1143
+ let base = this;
1144
+ let combined = schema.clone();
1145
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
1146
+ combined.spec = mergedSpec;
1147
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
1148
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
1149
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
1150
+ combined.tests = base.tests;
1151
+ combined.exclusiveTests = base.exclusiveTests;
1152
+ combined.withMutation((next) => {
1153
+ schema.tests.forEach((fn) => {
1154
+ next.test(fn.OPTIONS);
1155
+ });
1156
+ });
1157
+ combined.transforms = [...base.transforms, ...combined.transforms];
1158
+ return combined;
1159
+ }
1160
+ isType(v) {
1161
+ if (v == null) {
1162
+ if (this.spec.nullable && v === null) return true;
1163
+ if (this.spec.optional && v === void 0) return true;
1164
+ return false;
1165
+ }
1166
+ return this._typeCheck(v);
1167
+ }
1168
+ resolve(options) {
1169
+ let schema = this;
1170
+ if (schema.conditions.length) {
1171
+ let conditions = schema.conditions;
1172
+ schema = schema.clone();
1173
+ schema.conditions = [];
1174
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
1175
+ schema = schema.resolve(options);
1176
+ }
1177
+ return schema;
1178
+ }
1179
+ resolveOptions(options) {
1180
+ var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
1181
+ return Object.assign({}, options, {
1182
+ from: options.from || [],
1183
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
1184
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
1185
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
1186
+ disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
1187
+ });
1188
+ }
1189
+ /**
1190
+ * Run the configured transform pipeline over an input value.
1191
+ */
1192
+ cast(value, options = {}) {
1193
+ let resolvedSchema = this.resolve(Object.assign({}, options, {
1194
+ value
1195
+ // parent: options.parent,
1196
+ // context: options.context,
1197
+ }));
1198
+ let allowOptionality = options.assert === "ignore-optionality";
1199
+ let result = resolvedSchema._cast(value, options);
1200
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
1201
+ if (allowOptionality && isAbsent(result)) {
1202
+ return result;
1203
+ }
1204
+ let formattedValue = printValue(value);
1205
+ let formattedResult = printValue(result);
1206
+ throw new TypeError(`The value of ${options.path || "field"} could not be cast to a value that satisfies the schema type: "${resolvedSchema.type}".
1207
+
1208
+ attempted value: ${formattedValue}
1209
+ ` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ""));
1210
+ }
1211
+ return result;
1212
+ }
1213
+ _cast(rawValue, options) {
1214
+ let value = rawValue === void 0 ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue);
1215
+ if (value === void 0) {
1216
+ value = this.getDefault(options);
1217
+ }
1218
+ return value;
1219
+ }
1220
+ _validate(_value, options = {}, panic, next) {
1221
+ let {
1222
+ path,
1223
+ originalValue = _value,
1224
+ strict = this.spec.strict
1225
+ } = options;
1226
+ let value = _value;
1227
+ if (!strict) {
1228
+ value = this._cast(value, Object.assign({
1229
+ assert: false
1230
+ }, options));
1231
+ }
1232
+ let initialTests = [];
1233
+ for (let test of Object.values(this.internalTests)) {
1234
+ if (test) initialTests.push(test);
1235
+ }
1236
+ this.runTests({
1237
+ path,
1238
+ value,
1239
+ originalValue,
1240
+ options,
1241
+ tests: initialTests
1242
+ }, panic, (initialErrors) => {
1243
+ if (initialErrors.length) {
1244
+ return next(initialErrors, value);
1245
+ }
1246
+ this.runTests({
1247
+ path,
1248
+ value,
1249
+ originalValue,
1250
+ options,
1251
+ tests: this.tests
1252
+ }, panic, next);
1253
+ });
1254
+ }
1255
+ /**
1256
+ * Executes a set of validations, either schema, produced Tests or a nested
1257
+ * schema validate result.
1258
+ */
1259
+ runTests(runOptions, panic, next) {
1260
+ let fired = false;
1261
+ let {
1262
+ tests,
1263
+ value,
1264
+ originalValue,
1265
+ path,
1266
+ options
1267
+ } = runOptions;
1268
+ let panicOnce = (arg) => {
1269
+ if (fired) return;
1270
+ fired = true;
1271
+ panic(arg, value);
1272
+ };
1273
+ let nextOnce = (arg) => {
1274
+ if (fired) return;
1275
+ fired = true;
1276
+ next(arg, value);
1277
+ };
1278
+ let count = tests.length;
1279
+ let nestedErrors = [];
1280
+ if (!count) return nextOnce([]);
1281
+ let args = {
1282
+ value,
1283
+ originalValue,
1284
+ path,
1285
+ options,
1286
+ schema: this
1287
+ };
1288
+ for (let i = 0; i < tests.length; i++) {
1289
+ const test = tests[i];
1290
+ test(args, panicOnce, function finishTestRun(err) {
1291
+ if (err) {
1292
+ Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
1293
+ }
1294
+ if (--count <= 0) {
1295
+ nextOnce(nestedErrors);
1296
+ }
1297
+ });
1298
+ }
1299
+ }
1300
+ asNestedTest({
1301
+ key,
1302
+ index,
1303
+ parent,
1304
+ parentPath,
1305
+ originalParent,
1306
+ options
1307
+ }) {
1308
+ const k = key != null ? key : index;
1309
+ if (k == null) {
1310
+ throw TypeError("Must include `key` or `index` for nested validations");
1311
+ }
1312
+ const isIndex = typeof k === "number";
1313
+ let value = parent[k];
1314
+ const testOptions = Object.assign({}, options, {
1315
+ // Nested validations fields are always strict:
1316
+ // 1. parent isn't strict so the casting will also have cast inner values
1317
+ // 2. parent is strict in which case the nested values weren't cast either
1318
+ strict: true,
1319
+ parent,
1320
+ value,
1321
+ originalValue: originalParent[k],
1322
+ // FIXME: tests depend on `index` being passed around deeply,
1323
+ // we should not let the options.key/index bleed through
1324
+ key: void 0,
1325
+ // index: undefined,
1326
+ [isIndex ? "index" : "key"]: k,
1327
+ path: isIndex || k.includes(".") ? `${parentPath || ""}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : "") + key
1328
+ });
1329
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
1330
+ }
1331
+ validate(value, options) {
1332
+ var _options$disableStack2;
1333
+ let schema = this.resolve(Object.assign({}, options, {
1334
+ value
1335
+ }));
1336
+ let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
1337
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
1338
+ if (ValidationError.isError(error)) error.value = parsed;
1339
+ reject(error);
1340
+ }, (errors, validated) => {
1341
+ if (errors.length) reject(new ValidationError(errors, validated, void 0, void 0, disableStackTrace));
1342
+ else resolve(validated);
1343
+ }));
1344
+ }
1345
+ validateSync(value, options) {
1346
+ var _options$disableStack3;
1347
+ let schema = this.resolve(Object.assign({}, options, {
1348
+ value
1349
+ }));
1350
+ let result;
1351
+ let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
1352
+ schema._validate(value, Object.assign({}, options, {
1353
+ sync: true
1354
+ }), (error, parsed) => {
1355
+ if (ValidationError.isError(error)) error.value = parsed;
1356
+ throw error;
1357
+ }, (errors, validated) => {
1358
+ if (errors.length) throw new ValidationError(errors, value, void 0, void 0, disableStackTrace);
1359
+ result = validated;
1360
+ });
1361
+ return result;
1362
+ }
1363
+ isValid(value, options) {
1364
+ return this.validate(value, options).then(() => true, (err) => {
1365
+ if (ValidationError.isError(err)) return false;
1366
+ throw err;
1367
+ });
1368
+ }
1369
+ isValidSync(value, options) {
1370
+ try {
1371
+ this.validateSync(value, options);
1372
+ return true;
1373
+ } catch (err) {
1374
+ if (ValidationError.isError(err)) return false;
1375
+ throw err;
1376
+ }
1377
+ }
1378
+ _getDefault(options) {
1379
+ let defaultValue = this.spec.default;
1380
+ if (defaultValue == null) {
1381
+ return defaultValue;
1382
+ }
1383
+ return typeof defaultValue === "function" ? defaultValue.call(this, options) : clone(defaultValue);
1384
+ }
1385
+ getDefault(options) {
1386
+ let schema = this.resolve(options || {});
1387
+ return schema._getDefault(options);
1388
+ }
1389
+ default(def) {
1390
+ if (arguments.length === 0) {
1391
+ return this._getDefault();
1392
+ }
1393
+ let next = this.clone({
1394
+ default: def
1395
+ });
1396
+ return next;
1397
+ }
1398
+ strict(isStrict = true) {
1399
+ return this.clone({
1400
+ strict: isStrict
1401
+ });
1402
+ }
1403
+ nullability(nullable, message) {
1404
+ const next = this.clone({
1405
+ nullable
1406
+ });
1407
+ next.internalTests.nullable = createValidation({
1408
+ message,
1409
+ name: "nullable",
1410
+ test(value) {
1411
+ return value === null ? this.schema.spec.nullable : true;
1412
+ }
1413
+ });
1414
+ return next;
1415
+ }
1416
+ optionality(optional, message) {
1417
+ const next = this.clone({
1418
+ optional
1419
+ });
1420
+ next.internalTests.optionality = createValidation({
1421
+ message,
1422
+ name: "optionality",
1423
+ test(value) {
1424
+ return value === void 0 ? this.schema.spec.optional : true;
1425
+ }
1426
+ });
1427
+ return next;
1428
+ }
1429
+ optional() {
1430
+ return this.optionality(true);
1431
+ }
1432
+ defined(message = mixed.defined) {
1433
+ return this.optionality(false, message);
1434
+ }
1435
+ nullable() {
1436
+ return this.nullability(true);
1437
+ }
1438
+ nonNullable(message = mixed.notNull) {
1439
+ return this.nullability(false, message);
1440
+ }
1441
+ required(message = mixed.required) {
1442
+ return this.clone().withMutation((next) => next.nonNullable(message).defined(message));
1443
+ }
1444
+ notRequired() {
1445
+ return this.clone().withMutation((next) => next.nullable().optional());
1446
+ }
1447
+ transform(fn) {
1448
+ let next = this.clone();
1449
+ next.transforms.push(fn);
1450
+ return next;
1451
+ }
1452
+ /**
1453
+ * Adds a test function to the schema's queue of tests.
1454
+ * tests can be exclusive or non-exclusive.
1455
+ *
1456
+ * - exclusive tests, will replace any existing tests of the same name.
1457
+ * - non-exclusive: can be stacked
1458
+ *
1459
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
1460
+ * the exclusive test is removed and further tests of the same name will be stacked.
1461
+ *
1462
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
1463
+ * the previous tests are removed and further tests of the same name will replace each other.
1464
+ */
1465
+ test(...args) {
1466
+ let opts;
1467
+ if (args.length === 1) {
1468
+ if (typeof args[0] === "function") {
1469
+ opts = {
1470
+ test: args[0]
1471
+ };
1472
+ } else {
1473
+ opts = args[0];
1474
+ }
1475
+ } else if (args.length === 2) {
1476
+ opts = {
1477
+ name: args[0],
1478
+ test: args[1]
1479
+ };
1480
+ } else {
1481
+ opts = {
1482
+ name: args[0],
1483
+ message: args[1],
1484
+ test: args[2]
1485
+ };
1486
+ }
1487
+ if (opts.message === void 0) opts.message = mixed.default;
1488
+ if (typeof opts.test !== "function") throw new TypeError("`test` is a required parameters");
1489
+ let next = this.clone();
1490
+ let validate = createValidation(opts);
1491
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
1492
+ if (opts.exclusive) {
1493
+ if (!opts.name) throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");
1494
+ }
1495
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
1496
+ next.tests = next.tests.filter((fn) => {
1497
+ if (fn.OPTIONS.name === opts.name) {
1498
+ if (isExclusive) return false;
1499
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
1500
+ }
1501
+ return true;
1502
+ });
1503
+ next.tests.push(validate);
1504
+ return next;
1505
+ }
1506
+ when(keys, options) {
1507
+ if (!Array.isArray(keys) && typeof keys !== "string") {
1508
+ options = keys;
1509
+ keys = ".";
1510
+ }
1511
+ let next = this.clone();
1512
+ let deps = toArray(keys).map((key) => new Reference(key));
1513
+ deps.forEach((dep) => {
1514
+ if (dep.isSibling) next.deps.push(dep.key);
1515
+ });
1516
+ next.conditions.push(typeof options === "function" ? new Condition(deps, options) : Condition.fromOptions(deps, options));
1517
+ return next;
1518
+ }
1519
+ typeError(message) {
1520
+ let next = this.clone();
1521
+ next.internalTests.typeError = createValidation({
1522
+ message,
1523
+ name: "typeError",
1524
+ skipAbsent: true,
1525
+ test(value) {
1526
+ if (!this.schema._typeCheck(value)) return this.createError({
1527
+ params: {
1528
+ type: this.schema.type
1529
+ }
1530
+ });
1531
+ return true;
1532
+ }
1533
+ });
1534
+ return next;
1535
+ }
1536
+ oneOf(enums, message = mixed.oneOf) {
1537
+ let next = this.clone();
1538
+ enums.forEach((val) => {
1539
+ next._whitelist.add(val);
1540
+ next._blacklist.delete(val);
1541
+ });
1542
+ next.internalTests.whiteList = createValidation({
1543
+ message,
1544
+ name: "oneOf",
1545
+ skipAbsent: true,
1546
+ test(value) {
1547
+ let valids = this.schema._whitelist;
1548
+ let resolved = valids.resolveAll(this.resolve);
1549
+ return resolved.includes(value) ? true : this.createError({
1550
+ params: {
1551
+ values: Array.from(valids).join(", "),
1552
+ resolved
1553
+ }
1554
+ });
1555
+ }
1556
+ });
1557
+ return next;
1558
+ }
1559
+ notOneOf(enums, message = mixed.notOneOf) {
1560
+ let next = this.clone();
1561
+ enums.forEach((val) => {
1562
+ next._blacklist.add(val);
1563
+ next._whitelist.delete(val);
1564
+ });
1565
+ next.internalTests.blacklist = createValidation({
1566
+ message,
1567
+ name: "notOneOf",
1568
+ test(value) {
1569
+ let invalids = this.schema._blacklist;
1570
+ let resolved = invalids.resolveAll(this.resolve);
1571
+ if (resolved.includes(value)) return this.createError({
1572
+ params: {
1573
+ values: Array.from(invalids).join(", "),
1574
+ resolved
1575
+ }
1576
+ });
1577
+ return true;
1578
+ }
1579
+ });
1580
+ return next;
1581
+ }
1582
+ strip(strip = true) {
1583
+ let next = this.clone();
1584
+ next.spec.strip = strip;
1585
+ return next;
1586
+ }
1587
+ /**
1588
+ * Return a serialized description of the schema including validations, flags, types etc.
1589
+ *
1590
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
1591
+ */
1592
+ describe(options) {
1593
+ const next = (options ? this.resolve(options) : this).clone();
1594
+ const {
1595
+ label,
1596
+ meta,
1597
+ optional,
1598
+ nullable
1599
+ } = next.spec;
1600
+ const description = {
1601
+ meta,
1602
+ label,
1603
+ optional,
1604
+ nullable,
1605
+ default: next.getDefault(options),
1606
+ type: next.type,
1607
+ oneOf: next._whitelist.describe(),
1608
+ notOneOf: next._blacklist.describe(),
1609
+ tests: next.tests.filter((n, idx, list) => list.findIndex((c) => c.OPTIONS.name === n.OPTIONS.name) === idx).map((fn) => {
1610
+ const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params;
1611
+ return {
1612
+ name: fn.OPTIONS.name,
1613
+ params
1614
+ };
1615
+ })
1616
+ };
1617
+ return description;
1618
+ }
1619
+ get ["~standard"]() {
1620
+ const schema = this;
1621
+ const standard = {
1622
+ version: 1,
1623
+ vendor: "yup",
1624
+ async validate(value) {
1625
+ try {
1626
+ const result = await schema.validate(value, {
1627
+ abortEarly: false
1628
+ });
1629
+ return {
1630
+ value: result
1631
+ };
1632
+ } catch (err) {
1633
+ if (err instanceof ValidationError) {
1634
+ return {
1635
+ issues: issuesFromValidationError(err)
1636
+ };
1637
+ }
1638
+ throw err;
1639
+ }
1640
+ }
1641
+ };
1642
+ return standard;
1643
+ }
1644
+ };
1645
+ Schema.prototype.__isYupSchema__ = true;
1646
+ for (const method of ["validate", "validateSync"]) Schema.prototype[`${method}At`] = function(path, value, options = {}) {
1647
+ const {
1648
+ parent,
1649
+ parentPath,
1650
+ schema
1651
+ } = getIn(this, path, value, options.context);
1652
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
1653
+ parent,
1654
+ path
1655
+ }));
1656
+ };
1657
+ for (const alias of ["equals", "is"]) Schema.prototype[alias] = Schema.prototype.oneOf;
1658
+ for (const alias of ["not", "nope"]) Schema.prototype[alias] = Schema.prototype.notOneOf;
1659
+ var returnsTrue = () => true;
1660
+ function create$8(spec) {
1661
+ return new MixedSchema(spec);
1662
+ }
1663
+ var MixedSchema = class extends Schema {
1664
+ constructor(spec) {
1665
+ super(typeof spec === "function" ? {
1666
+ type: "mixed",
1667
+ check: spec
1668
+ } : Object.assign({
1669
+ type: "mixed",
1670
+ check: returnsTrue
1671
+ }, spec));
1672
+ }
1673
+ };
1674
+ create$8.prototype = MixedSchema.prototype;
1675
+ function create$7() {
1676
+ return new BooleanSchema();
1677
+ }
1678
+ var BooleanSchema = class extends Schema {
1679
+ constructor() {
1680
+ super({
1681
+ type: "boolean",
1682
+ check(v) {
1683
+ if (v instanceof Boolean) v = v.valueOf();
1684
+ return typeof v === "boolean";
1685
+ }
1686
+ });
1687
+ this.withMutation(() => {
1688
+ this.transform((value, _raw) => {
1689
+ if (this.spec.coerce && !this.isType(value)) {
1690
+ if (/^(true|1)$/i.test(String(value))) return true;
1691
+ if (/^(false|0)$/i.test(String(value))) return false;
1692
+ }
1693
+ return value;
1694
+ });
1695
+ });
1696
+ }
1697
+ isTrue(message = boolean.isValue) {
1698
+ return this.test({
1699
+ message,
1700
+ name: "is-value",
1701
+ exclusive: true,
1702
+ params: {
1703
+ value: "true"
1704
+ },
1705
+ test(value) {
1706
+ return isAbsent(value) || value === true;
1707
+ }
1708
+ });
1709
+ }
1710
+ isFalse(message = boolean.isValue) {
1711
+ return this.test({
1712
+ message,
1713
+ name: "is-value",
1714
+ exclusive: true,
1715
+ params: {
1716
+ value: "false"
1717
+ },
1718
+ test(value) {
1719
+ return isAbsent(value) || value === false;
1720
+ }
1721
+ });
1722
+ }
1723
+ default(def) {
1724
+ return super.default(def);
1725
+ }
1726
+ defined(msg) {
1727
+ return super.defined(msg);
1728
+ }
1729
+ optional() {
1730
+ return super.optional();
1731
+ }
1732
+ required(msg) {
1733
+ return super.required(msg);
1734
+ }
1735
+ notRequired() {
1736
+ return super.notRequired();
1737
+ }
1738
+ nullable() {
1739
+ return super.nullable();
1740
+ }
1741
+ nonNullable(msg) {
1742
+ return super.nonNullable(msg);
1743
+ }
1744
+ strip(v) {
1745
+ return super.strip(v);
1746
+ }
1747
+ };
1748
+ create$7.prototype = BooleanSchema.prototype;
1749
+ var isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
1750
+ function parseIsoDate(date2) {
1751
+ const struct = parseDateStruct(date2);
1752
+ if (!struct) return Date.parse ? Date.parse(date2) : Number.NaN;
1753
+ if (struct.z === void 0 && struct.plusMinus === void 0) {
1754
+ return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
1755
+ }
1756
+ let totalMinutesOffset = 0;
1757
+ if (struct.z !== "Z" && struct.plusMinus !== void 0) {
1758
+ totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
1759
+ if (struct.plusMinus === "+") totalMinutesOffset = 0 - totalMinutesOffset;
1760
+ }
1761
+ return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
1762
+ }
1763
+ function parseDateStruct(date2) {
1764
+ var _regexResult$7$length, _regexResult$;
1765
+ const regexResult = isoReg.exec(date2);
1766
+ if (!regexResult) return null;
1767
+ return {
1768
+ year: toNumber(regexResult[1]),
1769
+ month: toNumber(regexResult[2], 1) - 1,
1770
+ day: toNumber(regexResult[3], 1),
1771
+ hour: toNumber(regexResult[4]),
1772
+ minute: toNumber(regexResult[5]),
1773
+ second: toNumber(regexResult[6]),
1774
+ millisecond: regexResult[7] ? (
1775
+ // allow arbitrary sub-second precision beyond milliseconds
1776
+ toNumber(regexResult[7].substring(0, 3))
1777
+ ) : 0,
1778
+ precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : void 0,
1779
+ z: regexResult[8] || void 0,
1780
+ plusMinus: regexResult[9] || void 0,
1781
+ hourOffset: toNumber(regexResult[10]),
1782
+ minuteOffset: toNumber(regexResult[11])
1783
+ };
1784
+ }
1785
+ function toNumber(str, defaultValue = 0) {
1786
+ return Number(str) || defaultValue;
1787
+ }
1788
+ var rEmail = (
1789
+ // eslint-disable-next-line
1790
+ /^[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])?)*$/
1791
+ );
1792
+ var rUrl = (
1793
+ // eslint-disable-next-line
1794
+ /^((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
1795
+ );
1796
+ var 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;
1797
+ var yearMonthDay = "^\\d{4}-\\d{2}-\\d{2}";
1798
+ var hourMinuteSecond = "\\d{2}:\\d{2}:\\d{2}";
1799
+ var zOrOffset = "(([+-]\\d{2}(:?\\d{2})?)|Z)";
1800
+ var rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`);
1801
+ var isTrimmed = (value) => isAbsent(value) || value === value.trim();
1802
+ var objStringTag = {}.toString();
1803
+ function create$6() {
1804
+ return new StringSchema();
1805
+ }
1806
+ var StringSchema = class extends Schema {
1807
+ constructor() {
1808
+ super({
1809
+ type: "string",
1810
+ check(value) {
1811
+ if (value instanceof String) value = value.valueOf();
1812
+ return typeof value === "string";
1813
+ }
1814
+ });
1815
+ this.withMutation(() => {
1816
+ this.transform((value, _raw) => {
1817
+ if (!this.spec.coerce || this.isType(value)) return value;
1818
+ if (Array.isArray(value)) return value;
1819
+ const strValue = value != null && value.toString ? value.toString() : value;
1820
+ if (strValue === objStringTag) return value;
1821
+ return strValue;
1822
+ });
1823
+ });
1824
+ }
1825
+ required(message) {
1826
+ return super.required(message).withMutation((schema) => schema.test({
1827
+ message: message || mixed.required,
1828
+ name: "required",
1829
+ skipAbsent: true,
1830
+ test: (value) => !!value.length
1831
+ }));
1832
+ }
1833
+ notRequired() {
1834
+ return super.notRequired().withMutation((schema) => {
1835
+ schema.tests = schema.tests.filter((t) => t.OPTIONS.name !== "required");
1836
+ return schema;
1837
+ });
1838
+ }
1839
+ length(length, message = string.length) {
1840
+ return this.test({
1841
+ message,
1842
+ name: "length",
1843
+ exclusive: true,
1844
+ params: {
1845
+ length
1846
+ },
1847
+ skipAbsent: true,
1848
+ test(value) {
1849
+ return value.length === this.resolve(length);
1850
+ }
1851
+ });
1852
+ }
1853
+ min(min, message = string.min) {
1854
+ return this.test({
1855
+ message,
1856
+ name: "min",
1857
+ exclusive: true,
1858
+ params: {
1859
+ min
1860
+ },
1861
+ skipAbsent: true,
1862
+ test(value) {
1863
+ return value.length >= this.resolve(min);
1864
+ }
1865
+ });
1866
+ }
1867
+ max(max, message = string.max) {
1868
+ return this.test({
1869
+ name: "max",
1870
+ exclusive: true,
1871
+ message,
1872
+ params: {
1873
+ max
1874
+ },
1875
+ skipAbsent: true,
1876
+ test(value) {
1877
+ return value.length <= this.resolve(max);
1878
+ }
1879
+ });
1880
+ }
1881
+ matches(regex, options) {
1882
+ let excludeEmptyString = false;
1883
+ let message;
1884
+ let name;
1885
+ if (options) {
1886
+ if (typeof options === "object") {
1887
+ ({
1888
+ excludeEmptyString = false,
1889
+ message,
1890
+ name
1891
+ } = options);
1892
+ } else {
1893
+ message = options;
1894
+ }
1895
+ }
1896
+ return this.test({
1897
+ name: name || "matches",
1898
+ message: message || string.matches,
1899
+ params: {
1900
+ regex
1901
+ },
1902
+ skipAbsent: true,
1903
+ test: (value) => value === "" && excludeEmptyString || value.search(regex) !== -1
1904
+ });
1905
+ }
1906
+ email(message = string.email) {
1907
+ return this.matches(rEmail, {
1908
+ name: "email",
1909
+ message,
1910
+ excludeEmptyString: true
1911
+ });
1912
+ }
1913
+ url(message = string.url) {
1914
+ return this.matches(rUrl, {
1915
+ name: "url",
1916
+ message,
1917
+ excludeEmptyString: true
1918
+ });
1919
+ }
1920
+ uuid(message = string.uuid) {
1921
+ return this.matches(rUUID, {
1922
+ name: "uuid",
1923
+ message,
1924
+ excludeEmptyString: false
1925
+ });
1926
+ }
1927
+ datetime(options) {
1928
+ let message = "";
1929
+ let allowOffset;
1930
+ let precision;
1931
+ if (options) {
1932
+ if (typeof options === "object") {
1933
+ ({
1934
+ message = "",
1935
+ allowOffset = false,
1936
+ precision = void 0
1937
+ } = options);
1938
+ } else {
1939
+ message = options;
1940
+ }
1941
+ }
1942
+ return this.matches(rIsoDateTime, {
1943
+ name: "datetime",
1944
+ message: message || string.datetime,
1945
+ excludeEmptyString: true
1946
+ }).test({
1947
+ name: "datetime_offset",
1948
+ message: message || string.datetime_offset,
1949
+ params: {
1950
+ allowOffset
1951
+ },
1952
+ skipAbsent: true,
1953
+ test: (value) => {
1954
+ if (!value || allowOffset) return true;
1955
+ const struct = parseDateStruct(value);
1956
+ if (!struct) return false;
1957
+ return !!struct.z;
1958
+ }
1959
+ }).test({
1960
+ name: "datetime_precision",
1961
+ message: message || string.datetime_precision,
1962
+ params: {
1963
+ precision
1964
+ },
1965
+ skipAbsent: true,
1966
+ test: (value) => {
1967
+ if (!value || precision == void 0) return true;
1968
+ const struct = parseDateStruct(value);
1969
+ if (!struct) return false;
1970
+ return struct.precision === precision;
1971
+ }
1972
+ });
1973
+ }
1974
+ //-- transforms --
1975
+ ensure() {
1976
+ return this.default("").transform((val) => val === null ? "" : val);
1977
+ }
1978
+ trim(message = string.trim) {
1979
+ return this.transform((val) => val != null ? val.trim() : val).test({
1980
+ message,
1981
+ name: "trim",
1982
+ test: isTrimmed
1983
+ });
1984
+ }
1985
+ lowercase(message = string.lowercase) {
1986
+ return this.transform((value) => !isAbsent(value) ? value.toLowerCase() : value).test({
1987
+ message,
1988
+ name: "string_case",
1989
+ exclusive: true,
1990
+ skipAbsent: true,
1991
+ test: (value) => isAbsent(value) || value === value.toLowerCase()
1992
+ });
1993
+ }
1994
+ uppercase(message = string.uppercase) {
1995
+ return this.transform((value) => !isAbsent(value) ? value.toUpperCase() : value).test({
1996
+ message,
1997
+ name: "string_case",
1998
+ exclusive: true,
1999
+ skipAbsent: true,
2000
+ test: (value) => isAbsent(value) || value === value.toUpperCase()
2001
+ });
2002
+ }
2003
+ };
2004
+ create$6.prototype = StringSchema.prototype;
2005
+ var isNaN$1 = (value) => value != +value;
2006
+ function create$5() {
2007
+ return new NumberSchema();
2008
+ }
2009
+ var NumberSchema = class extends Schema {
2010
+ constructor() {
2011
+ super({
2012
+ type: "number",
2013
+ check(value) {
2014
+ if (value instanceof Number) value = value.valueOf();
2015
+ return typeof value === "number" && !isNaN$1(value);
2016
+ }
2017
+ });
2018
+ this.withMutation(() => {
2019
+ this.transform((value, _raw) => {
2020
+ if (!this.spec.coerce) return value;
2021
+ let parsed = value;
2022
+ if (typeof parsed === "string") {
2023
+ parsed = parsed.replace(/\s/g, "");
2024
+ if (parsed === "") return NaN;
2025
+ parsed = +parsed;
2026
+ }
2027
+ if (this.isType(parsed) || parsed === null) return parsed;
2028
+ return parseFloat(parsed);
2029
+ });
2030
+ });
2031
+ }
2032
+ min(min, message = number.min) {
2033
+ return this.test({
2034
+ message,
2035
+ name: "min",
2036
+ exclusive: true,
2037
+ params: {
2038
+ min
2039
+ },
2040
+ skipAbsent: true,
2041
+ test(value) {
2042
+ return value >= this.resolve(min);
2043
+ }
2044
+ });
2045
+ }
2046
+ max(max, message = number.max) {
2047
+ return this.test({
2048
+ message,
2049
+ name: "max",
2050
+ exclusive: true,
2051
+ params: {
2052
+ max
2053
+ },
2054
+ skipAbsent: true,
2055
+ test(value) {
2056
+ return value <= this.resolve(max);
2057
+ }
2058
+ });
2059
+ }
2060
+ lessThan(less, message = number.lessThan) {
2061
+ return this.test({
2062
+ message,
2063
+ name: "max",
2064
+ exclusive: true,
2065
+ params: {
2066
+ less
2067
+ },
2068
+ skipAbsent: true,
2069
+ test(value) {
2070
+ return value < this.resolve(less);
2071
+ }
2072
+ });
2073
+ }
2074
+ moreThan(more, message = number.moreThan) {
2075
+ return this.test({
2076
+ message,
2077
+ name: "min",
2078
+ exclusive: true,
2079
+ params: {
2080
+ more
2081
+ },
2082
+ skipAbsent: true,
2083
+ test(value) {
2084
+ return value > this.resolve(more);
2085
+ }
2086
+ });
2087
+ }
2088
+ positive(msg = number.positive) {
2089
+ return this.moreThan(0, msg);
2090
+ }
2091
+ negative(msg = number.negative) {
2092
+ return this.lessThan(0, msg);
2093
+ }
2094
+ integer(message = number.integer) {
2095
+ return this.test({
2096
+ name: "integer",
2097
+ message,
2098
+ skipAbsent: true,
2099
+ test: (val) => Number.isInteger(val)
2100
+ });
2101
+ }
2102
+ truncate() {
2103
+ return this.transform((value) => !isAbsent(value) ? value | 0 : value);
2104
+ }
2105
+ round(method) {
2106
+ var _method;
2107
+ let avail = ["ceil", "floor", "round", "trunc"];
2108
+ method = ((_method = method) == null ? void 0 : _method.toLowerCase()) || "round";
2109
+ if (method === "trunc") return this.truncate();
2110
+ if (avail.indexOf(method.toLowerCase()) === -1) throw new TypeError("Only valid options for round() are: " + avail.join(", "));
2111
+ return this.transform((value) => !isAbsent(value) ? Math[method](value) : value);
2112
+ }
2113
+ };
2114
+ create$5.prototype = NumberSchema.prototype;
2115
+ var invalidDate = /* @__PURE__ */ new Date("");
2116
+ var isDate = (obj) => Object.prototype.toString.call(obj) === "[object Date]";
2117
+ function create$4() {
2118
+ return new DateSchema();
2119
+ }
2120
+ var DateSchema = class _DateSchema extends Schema {
2121
+ constructor() {
2122
+ super({
2123
+ type: "date",
2124
+ check(v) {
2125
+ return isDate(v) && !isNaN(v.getTime());
2126
+ }
2127
+ });
2128
+ this.withMutation(() => {
2129
+ this.transform((value, _raw) => {
2130
+ if (!this.spec.coerce || this.isType(value) || value === null) return value;
2131
+ value = parseIsoDate(value);
2132
+ return !isNaN(value) ? new Date(value) : _DateSchema.INVALID_DATE;
2133
+ });
2134
+ });
2135
+ }
2136
+ prepareParam(ref, name) {
2137
+ let param;
2138
+ if (!Reference.isRef(ref)) {
2139
+ let cast = this.cast(ref);
2140
+ if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
2141
+ param = cast;
2142
+ } else {
2143
+ param = ref;
2144
+ }
2145
+ return param;
2146
+ }
2147
+ min(min, message = date.min) {
2148
+ let limit = this.prepareParam(min, "min");
2149
+ return this.test({
2150
+ message,
2151
+ name: "min",
2152
+ exclusive: true,
2153
+ params: {
2154
+ min
2155
+ },
2156
+ skipAbsent: true,
2157
+ test(value) {
2158
+ return value >= this.resolve(limit);
2159
+ }
2160
+ });
2161
+ }
2162
+ max(max, message = date.max) {
2163
+ let limit = this.prepareParam(max, "max");
2164
+ return this.test({
2165
+ message,
2166
+ name: "max",
2167
+ exclusive: true,
2168
+ params: {
2169
+ max
2170
+ },
2171
+ skipAbsent: true,
2172
+ test(value) {
2173
+ return value <= this.resolve(limit);
2174
+ }
2175
+ });
2176
+ }
2177
+ };
2178
+ DateSchema.INVALID_DATE = invalidDate;
2179
+ create$4.prototype = DateSchema.prototype;
2180
+ create$4.INVALID_DATE = invalidDate;
2181
+ function sortFields(fields, excludedEdges = []) {
2182
+ let edges = [];
2183
+ let nodes = /* @__PURE__ */ new Set();
2184
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
2185
+ function addNode(depPath, key) {
2186
+ let node = (0, import_property_expr.split)(depPath)[0];
2187
+ nodes.add(node);
2188
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
2189
+ }
2190
+ for (const key of Object.keys(fields)) {
2191
+ let value = fields[key];
2192
+ nodes.add(key);
2193
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);
2194
+ else if (isSchema(value) && "deps" in value) value.deps.forEach((path) => addNode(path, key));
2195
+ }
2196
+ return import_toposort.default.array(Array.from(nodes), edges).reverse();
2197
+ }
2198
+ function findIndex(arr, err) {
2199
+ let idx = Infinity;
2200
+ arr.some((key, ii) => {
2201
+ var _err$path;
2202
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
2203
+ idx = ii;
2204
+ return true;
2205
+ }
2206
+ });
2207
+ return idx;
2208
+ }
2209
+ function sortByKeyOrder(keys) {
2210
+ return (a, b) => {
2211
+ return findIndex(keys, a) - findIndex(keys, b);
2212
+ };
2213
+ }
2214
+ var parseJson = (value, _, schema) => {
2215
+ if (typeof value !== "string") {
2216
+ return value;
2217
+ }
2218
+ let parsed = value;
2219
+ try {
2220
+ parsed = JSON.parse(value);
2221
+ } catch (err) {
2222
+ }
2223
+ return schema.isType(parsed) ? parsed : value;
2224
+ };
2225
+ function deepPartial(schema) {
2226
+ if ("fields" in schema) {
2227
+ const partial = {};
2228
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
2229
+ partial[key] = deepPartial(fieldSchema);
2230
+ }
2231
+ return schema.setFields(partial);
2232
+ }
2233
+ if (schema.type === "array") {
2234
+ const nextArray = schema.optional();
2235
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
2236
+ return nextArray;
2237
+ }
2238
+ if (schema.type === "tuple") {
2239
+ return schema.optional().clone({
2240
+ types: schema.spec.types.map(deepPartial)
2241
+ });
2242
+ }
2243
+ if ("optional" in schema) {
2244
+ return schema.optional();
2245
+ }
2246
+ return schema;
2247
+ }
2248
+ var deepHas = (obj, p) => {
2249
+ const path = [...(0, import_property_expr.normalizePath)(p)];
2250
+ if (path.length === 1) return path[0] in obj;
2251
+ let last = path.pop();
2252
+ let parent = (0, import_property_expr.getter)((0, import_property_expr.join)(path), true)(obj);
2253
+ return !!(parent && last in parent);
2254
+ };
2255
+ var isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
2256
+ function unknown(ctx, value) {
2257
+ let known = Object.keys(ctx.fields);
2258
+ return Object.keys(value).filter((key) => known.indexOf(key) === -1);
2259
+ }
2260
+ var defaultSort = sortByKeyOrder([]);
2261
+ function create$3(spec) {
2262
+ return new ObjectSchema(spec);
2263
+ }
2264
+ var ObjectSchema = class extends Schema {
2265
+ constructor(spec) {
2266
+ super({
2267
+ type: "object",
2268
+ check(value) {
2269
+ return isObject(value) || typeof value === "function";
2270
+ }
2271
+ });
2272
+ this.fields = /* @__PURE__ */ Object.create(null);
2273
+ this._sortErrors = defaultSort;
2274
+ this._nodes = [];
2275
+ this._excludedEdges = [];
2276
+ this.withMutation(() => {
2277
+ if (spec) {
2278
+ this.shape(spec);
2279
+ }
2280
+ });
2281
+ }
2282
+ _cast(_value, options = {}) {
2283
+ var _options$stripUnknown;
2284
+ let value = super._cast(_value, options);
2285
+ if (value === void 0) return this.getDefault(options);
2286
+ if (!this._typeCheck(value)) return value;
2287
+ let fields = this.fields;
2288
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
2289
+ let props = [].concat(this._nodes, Object.keys(value).filter((v) => !this._nodes.includes(v)));
2290
+ let intermediateValue = {};
2291
+ let innerOptions = Object.assign({}, options, {
2292
+ parent: intermediateValue,
2293
+ __validating: options.__validating || false
2294
+ });
2295
+ let isChanged = false;
2296
+ for (const prop of props) {
2297
+ let field = fields[prop];
2298
+ let exists = prop in value;
2299
+ let inputValue = value[prop];
2300
+ if (field) {
2301
+ let fieldValue;
2302
+ innerOptions.path = (options.path ? `${options.path}.` : "") + prop;
2303
+ field = field.resolve({
2304
+ value: inputValue,
2305
+ context: options.context,
2306
+ parent: intermediateValue
2307
+ });
2308
+ let fieldSpec = field instanceof Schema ? field.spec : void 0;
2309
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
2310
+ if (fieldSpec != null && fieldSpec.strip) {
2311
+ isChanged = isChanged || prop in value;
2312
+ continue;
2313
+ }
2314
+ fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue;
2315
+ if (fieldValue !== void 0) {
2316
+ intermediateValue[prop] = fieldValue;
2317
+ }
2318
+ } else if (exists && !strip) {
2319
+ intermediateValue[prop] = inputValue;
2320
+ }
2321
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) {
2322
+ isChanged = true;
2323
+ }
2324
+ }
2325
+ return isChanged ? intermediateValue : value;
2326
+ }
2327
+ _validate(_value, options = {}, panic, next) {
2328
+ let {
2329
+ from = [],
2330
+ originalValue = _value,
2331
+ recursive = this.spec.recursive
2332
+ } = options;
2333
+ options.from = [{
2334
+ schema: this,
2335
+ value: originalValue
2336
+ }, ...from];
2337
+ options.__validating = true;
2338
+ options.originalValue = originalValue;
2339
+ super._validate(_value, options, panic, (objectErrors, value) => {
2340
+ if (!recursive || !isObject(value)) {
2341
+ next(objectErrors, value);
2342
+ return;
2343
+ }
2344
+ originalValue = originalValue || value;
2345
+ let tests = [];
2346
+ for (let key of this._nodes) {
2347
+ let field = this.fields[key];
2348
+ if (!field || Reference.isRef(field)) {
2349
+ continue;
2350
+ }
2351
+ tests.push(field.asNestedTest({
2352
+ options,
2353
+ key,
2354
+ parent: value,
2355
+ parentPath: options.path,
2356
+ originalParent: originalValue
2357
+ }));
2358
+ }
2359
+ this.runTests({
2360
+ tests,
2361
+ value,
2362
+ originalValue,
2363
+ options
2364
+ }, panic, (fieldErrors) => {
2365
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
2366
+ });
2367
+ });
2368
+ }
2369
+ clone(spec) {
2370
+ const next = super.clone(spec);
2371
+ next.fields = Object.assign({}, this.fields);
2372
+ next._nodes = this._nodes;
2373
+ next._excludedEdges = this._excludedEdges;
2374
+ next._sortErrors = this._sortErrors;
2375
+ return next;
2376
+ }
2377
+ concat(schema) {
2378
+ let next = super.concat(schema);
2379
+ let nextFields = next.fields;
2380
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
2381
+ const target = nextFields[field];
2382
+ nextFields[field] = target === void 0 ? schemaOrRef : target;
2383
+ }
2384
+ return next.withMutation((s) => (
2385
+ // XXX: excludes here is wrong
2386
+ s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges])
2387
+ ));
2388
+ }
2389
+ _getDefault(options) {
2390
+ if ("default" in this.spec) {
2391
+ return super._getDefault(options);
2392
+ }
2393
+ if (!this._nodes.length) {
2394
+ return void 0;
2395
+ }
2396
+ let dft = {};
2397
+ this._nodes.forEach((key) => {
2398
+ var _innerOptions;
2399
+ const field = this.fields[key];
2400
+ let innerOptions = options;
2401
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
2402
+ innerOptions = Object.assign({}, innerOptions, {
2403
+ parent: innerOptions.value,
2404
+ value: innerOptions.value[key]
2405
+ });
2406
+ }
2407
+ dft[key] = field && "getDefault" in field ? field.getDefault(innerOptions) : void 0;
2408
+ });
2409
+ return dft;
2410
+ }
2411
+ setFields(shape, excludedEdges) {
2412
+ let next = this.clone();
2413
+ next.fields = shape;
2414
+ next._nodes = sortFields(shape, excludedEdges);
2415
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
2416
+ if (excludedEdges) next._excludedEdges = excludedEdges;
2417
+ return next;
2418
+ }
2419
+ shape(additions, excludes = []) {
2420
+ return this.clone().withMutation((next) => {
2421
+ let edges = next._excludedEdges;
2422
+ if (excludes.length) {
2423
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
2424
+ edges = [...next._excludedEdges, ...excludes];
2425
+ }
2426
+ return next.setFields(Object.assign(next.fields, additions), edges);
2427
+ });
2428
+ }
2429
+ partial() {
2430
+ const partial = {};
2431
+ for (const [key, schema] of Object.entries(this.fields)) {
2432
+ partial[key] = "optional" in schema && schema.optional instanceof Function ? schema.optional() : schema;
2433
+ }
2434
+ return this.setFields(partial);
2435
+ }
2436
+ deepPartial() {
2437
+ const next = deepPartial(this);
2438
+ return next;
2439
+ }
2440
+ pick(keys) {
2441
+ const picked = {};
2442
+ for (const key of keys) {
2443
+ if (this.fields[key]) picked[key] = this.fields[key];
2444
+ }
2445
+ return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
2446
+ }
2447
+ omit(keys) {
2448
+ const remaining = [];
2449
+ for (const key of Object.keys(this.fields)) {
2450
+ if (keys.includes(key)) continue;
2451
+ remaining.push(key);
2452
+ }
2453
+ return this.pick(remaining);
2454
+ }
2455
+ from(from, to, alias) {
2456
+ let fromGetter = (0, import_property_expr.getter)(from, true);
2457
+ return this.transform((obj) => {
2458
+ if (!obj) return obj;
2459
+ let newObj = obj;
2460
+ if (deepHas(obj, from)) {
2461
+ newObj = Object.assign({}, obj);
2462
+ if (!alias) delete newObj[from];
2463
+ newObj[to] = fromGetter(obj);
2464
+ }
2465
+ return newObj;
2466
+ });
2467
+ }
2468
+ /** Parse an input JSON string to an object */
2469
+ json() {
2470
+ return this.transform(parseJson);
2471
+ }
2472
+ /**
2473
+ * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys
2474
+ */
2475
+ exact(message) {
2476
+ return this.test({
2477
+ name: "exact",
2478
+ exclusive: true,
2479
+ message: message || object.exact,
2480
+ test(value) {
2481
+ if (value == null) return true;
2482
+ const unknownKeys = unknown(this.schema, value);
2483
+ return unknownKeys.length === 0 || this.createError({
2484
+ params: {
2485
+ properties: unknownKeys.join(", ")
2486
+ }
2487
+ });
2488
+ }
2489
+ });
2490
+ }
2491
+ stripUnknown() {
2492
+ return this.clone({
2493
+ noUnknown: true
2494
+ });
2495
+ }
2496
+ noUnknown(noAllow = true, message = object.noUnknown) {
2497
+ if (typeof noAllow !== "boolean") {
2498
+ message = noAllow;
2499
+ noAllow = true;
2500
+ }
2501
+ let next = this.test({
2502
+ name: "noUnknown",
2503
+ exclusive: true,
2504
+ message,
2505
+ test(value) {
2506
+ if (value == null) return true;
2507
+ const unknownKeys = unknown(this.schema, value);
2508
+ return !noAllow || unknownKeys.length === 0 || this.createError({
2509
+ params: {
2510
+ unknown: unknownKeys.join(", ")
2511
+ }
2512
+ });
2513
+ }
2514
+ });
2515
+ next.spec.noUnknown = noAllow;
2516
+ return next;
2517
+ }
2518
+ unknown(allow = true, message = object.noUnknown) {
2519
+ return this.noUnknown(!allow, message);
2520
+ }
2521
+ transformKeys(fn) {
2522
+ return this.transform((obj) => {
2523
+ if (!obj) return obj;
2524
+ const result = {};
2525
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
2526
+ return result;
2527
+ });
2528
+ }
2529
+ camelCase() {
2530
+ return this.transformKeys(import_tiny_case.camelCase);
2531
+ }
2532
+ snakeCase() {
2533
+ return this.transformKeys(import_tiny_case.snakeCase);
2534
+ }
2535
+ constantCase() {
2536
+ return this.transformKeys((key) => (0, import_tiny_case.snakeCase)(key).toUpperCase());
2537
+ }
2538
+ describe(options) {
2539
+ const next = (options ? this.resolve(options) : this).clone();
2540
+ const base = super.describe(options);
2541
+ base.fields = {};
2542
+ for (const [key, value] of Object.entries(next.fields)) {
2543
+ var _innerOptions2;
2544
+ let innerOptions = options;
2545
+ if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {
2546
+ innerOptions = Object.assign({}, innerOptions, {
2547
+ parent: innerOptions.value,
2548
+ value: innerOptions.value[key]
2549
+ });
2550
+ }
2551
+ base.fields[key] = value.describe(innerOptions);
2552
+ }
2553
+ return base;
2554
+ }
2555
+ };
2556
+ create$3.prototype = ObjectSchema.prototype;
2557
+ function create$2(type) {
2558
+ return new ArraySchema(type);
2559
+ }
2560
+ var ArraySchema = class extends Schema {
2561
+ constructor(type) {
2562
+ super({
2563
+ type: "array",
2564
+ spec: {
2565
+ types: type
2566
+ },
2567
+ check(v) {
2568
+ return Array.isArray(v);
2569
+ }
2570
+ });
2571
+ this.innerType = void 0;
2572
+ this.innerType = type;
2573
+ }
2574
+ _cast(_value, _opts) {
2575
+ const value = super._cast(_value, _opts);
2576
+ if (!this._typeCheck(value) || !this.innerType) {
2577
+ return value;
2578
+ }
2579
+ let isChanged = false;
2580
+ const castArray = value.map((v, idx) => {
2581
+ const castElement = this.innerType.cast(v, Object.assign({}, _opts, {
2582
+ path: `${_opts.path || ""}[${idx}]`,
2583
+ parent: value,
2584
+ originalValue: v,
2585
+ value: v,
2586
+ index: idx
2587
+ }));
2588
+ if (castElement !== v) {
2589
+ isChanged = true;
2590
+ }
2591
+ return castElement;
2592
+ });
2593
+ return isChanged ? castArray : value;
2594
+ }
2595
+ _validate(_value, options = {}, panic, next) {
2596
+ var _options$recursive;
2597
+ let innerType = this.innerType;
2598
+ let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;
2599
+ options.originalValue != null ? options.originalValue : _value;
2600
+ super._validate(_value, options, panic, (arrayErrors, value) => {
2601
+ var _options$originalValu2;
2602
+ if (!recursive || !innerType || !this._typeCheck(value)) {
2603
+ next(arrayErrors, value);
2604
+ return;
2605
+ }
2606
+ let tests = new Array(value.length);
2607
+ for (let index = 0; index < value.length; index++) {
2608
+ var _options$originalValu;
2609
+ tests[index] = innerType.asNestedTest({
2610
+ options,
2611
+ index,
2612
+ parent: value,
2613
+ parentPath: options.path,
2614
+ originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
2615
+ });
2616
+ }
2617
+ this.runTests({
2618
+ value,
2619
+ tests,
2620
+ originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
2621
+ options
2622
+ }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(arrayErrors), value));
2623
+ });
2624
+ }
2625
+ clone(spec) {
2626
+ const next = super.clone(spec);
2627
+ next.innerType = this.innerType;
2628
+ return next;
2629
+ }
2630
+ /** Parse an input JSON string to an object */
2631
+ json() {
2632
+ return this.transform(parseJson);
2633
+ }
2634
+ concat(schema) {
2635
+ let next = super.concat(schema);
2636
+ next.innerType = this.innerType;
2637
+ if (schema.innerType)
2638
+ next.innerType = next.innerType ? (
2639
+ // @ts-expect-error Lazy doesn't have concat and will break
2640
+ next.innerType.concat(schema.innerType)
2641
+ ) : schema.innerType;
2642
+ return next;
2643
+ }
2644
+ of(schema) {
2645
+ let next = this.clone();
2646
+ if (!isSchema(schema)) throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: " + printValue(schema));
2647
+ next.innerType = schema;
2648
+ next.spec = Object.assign({}, next.spec, {
2649
+ types: schema
2650
+ });
2651
+ return next;
2652
+ }
2653
+ length(length, message = array.length) {
2654
+ return this.test({
2655
+ message,
2656
+ name: "length",
2657
+ exclusive: true,
2658
+ params: {
2659
+ length
2660
+ },
2661
+ skipAbsent: true,
2662
+ test(value) {
2663
+ return value.length === this.resolve(length);
2664
+ }
2665
+ });
2666
+ }
2667
+ min(min, message) {
2668
+ message = message || array.min;
2669
+ return this.test({
2670
+ message,
2671
+ name: "min",
2672
+ exclusive: true,
2673
+ params: {
2674
+ min
2675
+ },
2676
+ skipAbsent: true,
2677
+ // FIXME(ts): Array<typeof T>
2678
+ test(value) {
2679
+ return value.length >= this.resolve(min);
2680
+ }
2681
+ });
2682
+ }
2683
+ max(max, message) {
2684
+ message = message || array.max;
2685
+ return this.test({
2686
+ message,
2687
+ name: "max",
2688
+ exclusive: true,
2689
+ params: {
2690
+ max
2691
+ },
2692
+ skipAbsent: true,
2693
+ test(value) {
2694
+ return value.length <= this.resolve(max);
2695
+ }
2696
+ });
2697
+ }
2698
+ ensure() {
2699
+ return this.default(() => []).transform((val, original) => {
2700
+ if (this._typeCheck(val)) return val;
2701
+ return original == null ? [] : [].concat(original);
2702
+ });
2703
+ }
2704
+ compact(rejector) {
2705
+ let reject = !rejector ? (v) => !!v : (v, i, a) => !rejector(v, i, a);
2706
+ return this.transform((values) => values != null ? values.filter(reject) : values);
2707
+ }
2708
+ describe(options) {
2709
+ const next = (options ? this.resolve(options) : this).clone();
2710
+ const base = super.describe(options);
2711
+ if (next.innerType) {
2712
+ var _innerOptions;
2713
+ let innerOptions = options;
2714
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
2715
+ innerOptions = Object.assign({}, innerOptions, {
2716
+ parent: innerOptions.value,
2717
+ value: innerOptions.value[0]
2718
+ });
2719
+ }
2720
+ base.innerType = next.innerType.describe(innerOptions);
2721
+ }
2722
+ return base;
2723
+ }
2724
+ };
2725
+ create$2.prototype = ArraySchema.prototype;
2726
+ function create$1(schemas) {
2727
+ return new TupleSchema(schemas);
2728
+ }
2729
+ var TupleSchema = class extends Schema {
2730
+ constructor(schemas) {
2731
+ super({
2732
+ type: "tuple",
2733
+ spec: {
2734
+ types: schemas
2735
+ },
2736
+ check(v) {
2737
+ const types = this.spec.types;
2738
+ return Array.isArray(v) && v.length === types.length;
2739
+ }
2740
+ });
2741
+ this.withMutation(() => {
2742
+ this.typeError(tuple.notType);
2743
+ });
2744
+ }
2745
+ _cast(inputValue, options) {
2746
+ const {
2747
+ types
2748
+ } = this.spec;
2749
+ const value = super._cast(inputValue, options);
2750
+ if (!this._typeCheck(value)) {
2751
+ return value;
2752
+ }
2753
+ let isChanged = false;
2754
+ const castArray = types.map((type, idx) => {
2755
+ const castElement = type.cast(value[idx], Object.assign({}, options, {
2756
+ path: `${options.path || ""}[${idx}]`,
2757
+ parent: value,
2758
+ originalValue: value[idx],
2759
+ value: value[idx],
2760
+ index: idx
2761
+ }));
2762
+ if (castElement !== value[idx]) isChanged = true;
2763
+ return castElement;
2764
+ });
2765
+ return isChanged ? castArray : value;
2766
+ }
2767
+ _validate(_value, options = {}, panic, next) {
2768
+ let itemTypes = this.spec.types;
2769
+ super._validate(_value, options, panic, (tupleErrors, value) => {
2770
+ var _options$originalValu2;
2771
+ if (!this._typeCheck(value)) {
2772
+ next(tupleErrors, value);
2773
+ return;
2774
+ }
2775
+ let tests = [];
2776
+ for (let [index, itemSchema] of itemTypes.entries()) {
2777
+ var _options$originalValu;
2778
+ tests[index] = itemSchema.asNestedTest({
2779
+ options,
2780
+ index,
2781
+ parent: value,
2782
+ parentPath: options.path,
2783
+ originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
2784
+ });
2785
+ }
2786
+ this.runTests({
2787
+ value,
2788
+ tests,
2789
+ originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
2790
+ options
2791
+ }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(tupleErrors), value));
2792
+ });
2793
+ }
2794
+ describe(options) {
2795
+ const next = (options ? this.resolve(options) : this).clone();
2796
+ const base = super.describe(options);
2797
+ base.innerType = next.spec.types.map((schema, index) => {
2798
+ var _innerOptions;
2799
+ let innerOptions = options;
2800
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
2801
+ innerOptions = Object.assign({}, innerOptions, {
2802
+ parent: innerOptions.value,
2803
+ value: innerOptions.value[index]
2804
+ });
2805
+ }
2806
+ return schema.describe(innerOptions);
2807
+ });
2808
+ return base;
2809
+ }
2810
+ };
2811
+ create$1.prototype = TupleSchema.prototype;
2812
+
2813
+ // src/adapters/validation/YupAdapter.ts
2814
+ var YupAdapter = class {
2815
+ constructor(schema) {
2816
+ this.schema = schema;
2817
+ }
2818
+ async validate(data) {
2819
+ try {
2820
+ await this.schema.validate(data, { abortEarly: false });
2821
+ return { isValid: true };
2822
+ } catch (err) {
2823
+ if (err instanceof ValidationError) {
2824
+ const errors = {};
2825
+ err.inner.forEach((error) => {
2826
+ if (error.path) {
2827
+ errors[error.path] = error.message;
2828
+ }
2829
+ });
2830
+ return { isValid: false, errors };
2831
+ }
2832
+ throw err;
2833
+ }
2834
+ }
2835
+ };
2836
+ export {
2837
+ LocalStorageAdapter,
2838
+ MemoryAdapter,
2839
+ WizardProvider,
2840
+ YupAdapter,
2841
+ ZodAdapter,
2842
+ useWizard,
2843
+ useWizardContext
2844
+ };
2845
+ //# sourceMappingURL=index.js.map