@magiclabs.ai/magicbook-client 0.6.3 → 0.6.6

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/index.cjs ADDED
@@ -0,0 +1,4853 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ DesignRequest: () => DesignRequest,
24
+ DesignRequestOptions: () => DesignRequestOptions,
25
+ ImageServer: () => ImageServer,
26
+ Images: () => Images,
27
+ MagicBookClient: () => MagicBookClient,
28
+ designOptionsSchema: () => designOptionsSchema,
29
+ designOptionsServerSchema: () => designOptionsServerSchema,
30
+ imageDensityOptionSchema: () => imageDensityOptionSchema,
31
+ imageDensityOptionServerSchema: () => imageDensityOptionServerSchema,
32
+ imageDensityOptionsSchema: () => imageDensityOptionsSchema,
33
+ imageDensityOptionsServerSchema: () => imageDensityOptionsServerSchema,
34
+ imageServerSchema: () => imageServerSchema
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // ../../core/data/design-request.ts
39
+ var states = [
40
+ "new",
41
+ "ingesting",
42
+ "submitted",
43
+ "storyboarding",
44
+ "deduplication",
45
+ "image-selection",
46
+ "designing",
47
+ "layouting",
48
+ "embellishing",
49
+ "polishing",
50
+ "ready",
51
+ "timeout",
52
+ "error",
53
+ "cancelled"
54
+ ];
55
+ var statesToCloseWS = ["error", "timeout", "ready", "cancelled"];
56
+ var statesToReport = ["error", "timeout"];
57
+ var isDesignRequestSubmitted = (state) => !["new", "ingesting"].includes(state);
58
+ var occasions = [
59
+ "baby",
60
+ "birthday",
61
+ "default",
62
+ "everyday",
63
+ "family",
64
+ "kids",
65
+ "life-stories",
66
+ "portfolio",
67
+ "school-memories",
68
+ "seasonal-holidays",
69
+ "special-celebrations",
70
+ "sports-and-hobbies",
71
+ "travel",
72
+ "wedding",
73
+ "year-in-review"
74
+ ];
75
+ var styles = {
76
+ 1005: { slug: "modern-black-sfly" },
77
+ 1101: { slug: "bon-voyage-sfly" },
78
+ 1103: { slug: "fun-in-the-sun-sfly" },
79
+ 1201: { slug: "modern-wedding-sfly" },
80
+ 3001: { slug: "digiscrap-sfly" },
81
+ 4034: { slug: "travel-snapshots-sfly" },
82
+ 4035: { slug: "vintage-travel-sfly" },
83
+ 5017: { slug: "natural-neutrals-sfly" },
84
+ 5033: { slug: "chalkboard-chic-sfly" },
85
+ 5079: { slug: "hello-spring-sfly" },
86
+ 5082: { slug: "familygram-sfly" },
87
+ 5085: { slug: "best-day-ever-sfly" },
88
+ 5091: { slug: "little-love-sfly" },
89
+ 5118: { slug: "a-year-in-color-sfly" },
90
+ 5120: { slug: "milestone-anniversaries-sfly" },
91
+ 5121: { slug: "the-travel-bug-sfly" },
92
+ 5122: { slug: "modern-white-sfly" },
93
+ 5127: { slug: "outdoor-wedding-sfly" },
94
+ 5134: { slug: "classic-wedding-sfly" },
95
+ 5138: { slug: "kraft-pop-sfly" },
96
+ 5142: { slug: "simply-black-sfly" },
97
+ 5144: { slug: "autumn-memories-sfly" },
98
+ 5146: { slug: "everyday-sentiments-sfly" },
99
+ 5149: { slug: "everyday-happiness-sfly" },
100
+ 5150: { slug: "its-a-girl-thing-sfly" },
101
+ 5155: { slug: "made-with-love-sfly" },
102
+ 5157: { slug: "high-school-memories-sfly" },
103
+ 5161: { slug: "rustic-wedding-sfly" },
104
+ 5165: { slug: "life-is-grand-sfly" },
105
+ 5167: { slug: "adventure-awaits-sfly" },
106
+ 5168: { slug: "disney-adventure-sfly" },
107
+ 5171: { slug: "world-travel-sfly" },
108
+ 5174: { slug: "hello-summer-sfly" },
109
+ 5183: { slug: "everything-sports-sfly" },
110
+ 5188: { slug: "everyday-watercolor-sfly" },
111
+ 5189: { slug: "holiday-memories-sfly" },
112
+ 5213: { slug: "love-and-thanks-sfly" },
113
+ 5218: { slug: "babys-first-year-sfly" },
114
+ 5219: { slug: "usa-travel-sfly" },
115
+ 5220: { slug: "vintage-wedding-sfly" },
116
+ 5226: { slug: "love-you-because-sfly" },
117
+ 5228: { slug: "reunion-sfly" },
118
+ 5238: { slug: "whimsy-chalkboard-sfly" },
119
+ 5242: { slug: "modern-indigo-sfly" },
120
+ 5250: { slug: "family-yearbook-sfly" },
121
+ 5255: { slug: "elegant-wedding-sfly" },
122
+ 5258: { slug: "family-vacation-sfly" },
123
+ 5259: { slug: "beach-travel-sfly" },
124
+ 5261: { slug: "sparkle-and-shine-sfly" },
125
+ 5262: { slug: "welcome-baby-sfly" },
126
+ 5265: { slug: "vivid-watercolor-sfly" },
127
+ 5266: { slug: "what-i-love-about-you-sfly" },
128
+ 5272: { slug: "love-grows-sfly" },
129
+ 5274: { slug: "painted-seasons-sfly" },
130
+ 5278: { slug: "vintage-disney-sfly" },
131
+ 5292: { slug: "modern-grey-sfly" },
132
+ 5297: { slug: "modern-love-story-sfly" },
133
+ 5299: { slug: "modern-travel-sfly" },
134
+ 5304: { slug: "beach-wedding-sfly" },
135
+ 5305: { slug: "rustic-farmhouse-sfly" },
136
+ 5308: { slug: "tropical-travel-sfly" },
137
+ 6e3: { slug: "travel-abroad-sfly" },
138
+ 6001: { slug: "everyday-rustic-sfly" },
139
+ 6002: { slug: "simply-modern-sfly" },
140
+ 6003: { slug: "modern-baby-sfly" },
141
+ 6004: { slug: "modern-photo-album-sfly" },
142
+ 6005: { slug: "travel-adventures-sfly" },
143
+ 6006: { slug: "watercolor-year-in-review-sfly" },
144
+ 6007: { slug: "beach-bliss-sfly" },
145
+ 6008: { slug: "simply-gray-sfly" },
146
+ 6009: { slug: "family-favorites-by-lure-design-sfly" },
147
+ 6010: { slug: "travel-gallery-sfly" },
148
+ 6011: { slug: "our-wedding-day-sfly" },
149
+ 6012: { slug: "chic-celebrations-by-float-paperie-sfly" },
150
+ 6013: { slug: "simply-bold-type-sfly" },
151
+ 6014: { slug: "colorful-florals-by-potts-design-sfly" },
152
+ 6015: { slug: "softly-rustic-sfly" },
153
+ 6016: { slug: "ombre-watercolor-sfly" },
154
+ 6017: { slug: "forever-love-by-with-merriment-sfly" },
155
+ 6018: { slug: "colorful-memories-by-britt-bass-sfly" },
156
+ 6019: { slug: "celebrate-family-by-float-paperie-sfly" },
157
+ 6020: { slug: "disney-family-adventures-sfly" },
158
+ 6021: { slug: "everyday-neutrals-sfly" },
159
+ 6022: { slug: "colorful-childhood-sfly" },
160
+ 6023: { slug: "everyday-indigo-sfly" },
161
+ 6024: { slug: "shimmer-and-shine-sfly" },
162
+ 6025: { slug: "summertime-fun-sfly" },
163
+ 6026: { slug: "pet-lover-sfly" },
164
+ 6027: { slug: "modern-wedding-story-sfly" },
165
+ 6028: { slug: "family-blessings-by-potts-design-sfly" },
166
+ 6030: { slug: "outdoor-adventures-by-sarah-hawkins-designs-sfly" },
167
+ 6031: { slug: "travel-memories-sfly" },
168
+ 6032: { slug: "tropical-travels-sfly" },
169
+ 6033: { slug: "everyday-chalkboard-by-potts-design-sfly" },
170
+ 6034: { slug: "classic-disney-sfly" },
171
+ 6035: { slug: "cheerful-color-sfly" },
172
+ 6036: { slug: "colorful-birthday-sfly" },
173
+ 6038: { slug: "classic-baby-sfly" },
174
+ 6039: { slug: "bold-year-in-review-by-float-paperie-sfly" },
175
+ 6040: { slug: "colorfully-fun-sfly" },
176
+ 6041: { slug: "colorful-year-in-review-by-sarah-hawkins-designs-sfly" },
177
+ 6042: { slug: "gilded-wedding-sfly" },
178
+ 6043: { slug: "road-trip-travel-by-sarah-hawkins-designs-sfly" },
179
+ 6044: { slug: "rustic-gilded-wedding-sfly" },
180
+ 6045: { slug: "elegantly-scripted-year-in-review-sfly" },
181
+ 6047: { slug: "2020-what-a-year-sfly" },
182
+ 6057: { slug: "best-mom-ever-sfly" },
183
+ 6052: { slug: "celebration-of-life-by-sarah-hawkins-designs-sfly" },
184
+ 6054: { slug: "colorful-school-days-by-float-paperie-sfly" },
185
+ 6051: { slug: "love-is-all-we-need-sfly" },
186
+ 6058: { slug: "graduation-celebration-sfly" },
187
+ 6056: { slug: "our-wedding-day-guestbook-sfly" },
188
+ 6055: { slug: "muted-everyday-abstract-sfly" },
189
+ 6046: { slug: "winter-memories-by-sarah-hawkins-design-sfly" },
190
+ 6053: { slug: "best-dad-ever-sfly" },
191
+ 6050: { slug: "watercolor-greenery-by-sarah-hawkins-designs-sfly" },
192
+ 6063: { slug: "watercolor-floral-wedding-by-kim-thoa-sfly" },
193
+ 6060: { slug: "watercolor-baby-girl-sfly" },
194
+ 6059: { slug: "watercolor-baby-boy-sfly" },
195
+ 6048: { slug: "simple-elegant-wedding-sfly" },
196
+ 6049: { slug: "gilded-wedding-guestbook-sfly" },
197
+ 6037: { slug: "everyday-fairytale-by-jenny-romanski-sfly" },
198
+ 6061: { slug: "best-grandparents-ever-sfly" },
199
+ 6068: { slug: "winter-getaway-sfly" },
200
+ 6067: { slug: "national-parks-travel-by-eiman-design-co-sfly" },
201
+ 6065: { slug: "go-sports-by-lure-design-sfly" },
202
+ 6066: { slug: "elegant-wedding-greenery-by-kim-thoa-sfly" },
203
+ 6064: { slug: "boho-travel-by-umaiana-studio-sfly" },
204
+ 6071: { slug: "modern-dark-neutrals-sfly" },
205
+ 6072: { slug: "modern-light-neutrals-sfly" },
206
+ 6073: { slug: "modern-celebrations-sfly" },
207
+ 6074: { slug: "bright-and-bold-kids-year-in-review-by-sarah-hawkins-designs-sfly" },
208
+ 6085: { slug: "classic-school-yearbook-sfly" },
209
+ 6084: { slug: "colorful-elementary-school-yearbook-sfly" },
210
+ 5402: { slug: "everyday-recipes-by-slightly-stationery-sfly" },
211
+ 6083: { slug: "school-days-yearbook-sfly" },
212
+ 6082: { slug: "the-story-of-me-sfly" },
213
+ 6086: { slug: "whimsical-recipes-by-slightly-stationery-sfly" },
214
+ 6101: { slug: "babys-first-sfly" },
215
+ 6103: { slug: "classic-recipes-sfly" },
216
+ 6104: { slug: "elevated-rustic-sfly" },
217
+ 6105: { slug: "boho-summer-sfly" },
218
+ 6116: { slug: "boho-baby-sfly" },
219
+ 6117: { slug: "simply-gallery-sfly" },
220
+ 6118: { slug: "this-is-love-sfly" },
221
+ 6120: { slug: "wedding-gallery-sfly" },
222
+ 6121: { slug: "watercolorwashes-sfly" },
223
+ 6124: { slug: "graduation-photo-album-sfly" },
224
+ 6125: { slug: "modern-year-in-review-photo-album-sfly" },
225
+ 6126: { slug: "black-white-photo-album-sfly" },
226
+ 6132: { slug: "travel-journal-sfly" },
227
+ 6133: { slug: "rustic-gallery-sfly" },
228
+ 6137: { slug: "summer-adventures-sfly" },
229
+ 6075: { slug: "together-again-sfly" },
230
+ 6078: { slug: "everyday-boho-by-umaiana-studio-sfly" },
231
+ 6089: { slug: "colorful-gradients-sfly" },
232
+ 6096: { slug: "simply-scrapbook-sfly" },
233
+ 6097: { slug: "boho-wedding-sfly" },
234
+ 6098: { slug: "black-and-white-rustic-sfly" },
235
+ 6099: { slug: "bright-color-pop-sfly" }
236
+ };
237
+ var bookSizes = ["8x8", "10x10", "12x12", "8x11", "11x8", "11x14"];
238
+ var coverTypes = ["sc", "hc", "pl"];
239
+ var pageTypes = ["sp", "sl", "dl"];
240
+ var imageDensities = ["low", "medium", "high"];
241
+ var imageFilteringLevels = ["best", "most", "all"];
242
+ var embellishmentLevels = ["none", "few", "lots"];
243
+ var textStickerLevels = ["none", "few", "lots"];
244
+ var timeoutMessage = {
245
+ state: "timeout",
246
+ slug: "timeout",
247
+ progress: 100,
248
+ message: "Design timed out"
249
+ };
250
+ var cancelledMessage = {
251
+ state: "cancelled",
252
+ slug: "cancelled",
253
+ progress: 100,
254
+ message: "Design canceled"
255
+ };
256
+
257
+ // ../../core/utils/toolbox.ts
258
+ function mergeNestedObject(obj, objToMerge) {
259
+ Object.keys(objToMerge).map((key) => {
260
+ if (typeof obj[key] === "object" && typeof objToMerge[key] === "object") {
261
+ mergeNestedObject(obj[key], objToMerge[key]);
262
+ } else {
263
+ obj[key] = objToMerge[key];
264
+ }
265
+ });
266
+ return obj;
267
+ }
268
+ function camelCaseToSnakeCase(str) {
269
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
270
+ }
271
+ function camelCaseObjectKeysToSnakeCase(camelCaseObject) {
272
+ Object.keys(camelCaseObject).map((key) => {
273
+ const snakeCaseKey = camelCaseToSnakeCase(key);
274
+ if (snakeCaseKey.includes("_")) {
275
+ camelCaseObject[snakeCaseKey] = camelCaseObject[key];
276
+ delete camelCaseObject[key];
277
+ }
278
+ if (typeof camelCaseObject[snakeCaseKey] === "object") {
279
+ camelCaseObject[snakeCaseKey] = camelCaseObjectKeysToSnakeCase(camelCaseObject[snakeCaseKey]);
280
+ }
281
+ });
282
+ return camelCaseObject;
283
+ }
284
+ function snakeCaseToCamelCase(str) {
285
+ return str.replace(/([-_][a-z])/g, ($1) => $1.toUpperCase().replace("-", "").replace("_", ""));
286
+ }
287
+ function snakeCaseObjectKeysToCamelCase(snakeCaseObject) {
288
+ Object.keys(snakeCaseObject).map((key) => {
289
+ const camelCaseKey = snakeCaseToCamelCase(key);
290
+ if (camelCaseKey !== key) {
291
+ snakeCaseObject[camelCaseKey] = snakeCaseObject[key];
292
+ delete snakeCaseObject[key];
293
+ }
294
+ if (typeof snakeCaseObject[camelCaseKey] === "object") {
295
+ snakeCaseObject[camelCaseKey] = snakeCaseObjectKeysToCamelCase(snakeCaseObject[camelCaseKey]);
296
+ }
297
+ });
298
+ return snakeCaseObject;
299
+ }
300
+ async function handleAsyncFunction(fn) {
301
+ try {
302
+ return await fn();
303
+ } catch (error) {
304
+ return Promise.reject(error);
305
+ }
306
+ }
307
+ function bindThisToFunctions(instance) {
308
+ for (const name of Object.getOwnPropertyNames(
309
+ Object.getPrototypeOf(instance)
310
+ )) {
311
+ if (typeof instance[name] === "function" && name !== "constructor") {
312
+ instance[name] = instance[name].bind(instance);
313
+ }
314
+ }
315
+ }
316
+ function cleanJSON(obj) {
317
+ return JSON.parse(JSON.stringify(obj));
318
+ }
319
+ function getStyleIdBySlug(slug) {
320
+ for (const id in styles) {
321
+ const style = styles[id];
322
+ if (style.slug === slug) {
323
+ return parseInt(id);
324
+ }
325
+ }
326
+ return void 0;
327
+ }
328
+
329
+ // ../../node_modules/.pnpm/zod@3.21.4/node_modules/zod/lib/index.mjs
330
+ var util;
331
+ (function(util2) {
332
+ util2.assertEqual = (val) => val;
333
+ function assertIs(_arg) {
334
+ }
335
+ util2.assertIs = assertIs;
336
+ function assertNever(_x) {
337
+ throw new Error();
338
+ }
339
+ util2.assertNever = assertNever;
340
+ util2.arrayToEnum = (items) => {
341
+ const obj = {};
342
+ for (const item of items) {
343
+ obj[item] = item;
344
+ }
345
+ return obj;
346
+ };
347
+ util2.getValidEnumValues = (obj) => {
348
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
349
+ const filtered = {};
350
+ for (const k of validKeys) {
351
+ filtered[k] = obj[k];
352
+ }
353
+ return util2.objectValues(filtered);
354
+ };
355
+ util2.objectValues = (obj) => {
356
+ return util2.objectKeys(obj).map(function(e) {
357
+ return obj[e];
358
+ });
359
+ };
360
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
361
+ const keys = [];
362
+ for (const key in object) {
363
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
364
+ keys.push(key);
365
+ }
366
+ }
367
+ return keys;
368
+ };
369
+ util2.find = (arr, checker) => {
370
+ for (const item of arr) {
371
+ if (checker(item))
372
+ return item;
373
+ }
374
+ return void 0;
375
+ };
376
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
377
+ function joinValues(array, separator = " | ") {
378
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
379
+ }
380
+ util2.joinValues = joinValues;
381
+ util2.jsonStringifyReplacer = (_, value) => {
382
+ if (typeof value === "bigint") {
383
+ return value.toString();
384
+ }
385
+ return value;
386
+ };
387
+ })(util || (util = {}));
388
+ var objectUtil;
389
+ (function(objectUtil2) {
390
+ objectUtil2.mergeShapes = (first, second) => {
391
+ return {
392
+ ...first,
393
+ ...second
394
+ // second overwrites first
395
+ };
396
+ };
397
+ })(objectUtil || (objectUtil = {}));
398
+ var ZodParsedType = util.arrayToEnum([
399
+ "string",
400
+ "nan",
401
+ "number",
402
+ "integer",
403
+ "float",
404
+ "boolean",
405
+ "date",
406
+ "bigint",
407
+ "symbol",
408
+ "function",
409
+ "undefined",
410
+ "null",
411
+ "array",
412
+ "object",
413
+ "unknown",
414
+ "promise",
415
+ "void",
416
+ "never",
417
+ "map",
418
+ "set"
419
+ ]);
420
+ var getParsedType = (data) => {
421
+ const t = typeof data;
422
+ switch (t) {
423
+ case "undefined":
424
+ return ZodParsedType.undefined;
425
+ case "string":
426
+ return ZodParsedType.string;
427
+ case "number":
428
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
429
+ case "boolean":
430
+ return ZodParsedType.boolean;
431
+ case "function":
432
+ return ZodParsedType.function;
433
+ case "bigint":
434
+ return ZodParsedType.bigint;
435
+ case "symbol":
436
+ return ZodParsedType.symbol;
437
+ case "object":
438
+ if (Array.isArray(data)) {
439
+ return ZodParsedType.array;
440
+ }
441
+ if (data === null) {
442
+ return ZodParsedType.null;
443
+ }
444
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
445
+ return ZodParsedType.promise;
446
+ }
447
+ if (typeof Map !== "undefined" && data instanceof Map) {
448
+ return ZodParsedType.map;
449
+ }
450
+ if (typeof Set !== "undefined" && data instanceof Set) {
451
+ return ZodParsedType.set;
452
+ }
453
+ if (typeof Date !== "undefined" && data instanceof Date) {
454
+ return ZodParsedType.date;
455
+ }
456
+ return ZodParsedType.object;
457
+ default:
458
+ return ZodParsedType.unknown;
459
+ }
460
+ };
461
+ var ZodIssueCode = util.arrayToEnum([
462
+ "invalid_type",
463
+ "invalid_literal",
464
+ "custom",
465
+ "invalid_union",
466
+ "invalid_union_discriminator",
467
+ "invalid_enum_value",
468
+ "unrecognized_keys",
469
+ "invalid_arguments",
470
+ "invalid_return_type",
471
+ "invalid_date",
472
+ "invalid_string",
473
+ "too_small",
474
+ "too_big",
475
+ "invalid_intersection_types",
476
+ "not_multiple_of",
477
+ "not_finite"
478
+ ]);
479
+ var quotelessJson = (obj) => {
480
+ const json = JSON.stringify(obj, null, 2);
481
+ return json.replace(/"([^"]+)":/g, "$1:");
482
+ };
483
+ var ZodError = class extends Error {
484
+ constructor(issues) {
485
+ super();
486
+ this.issues = [];
487
+ this.addIssue = (sub) => {
488
+ this.issues = [...this.issues, sub];
489
+ };
490
+ this.addIssues = (subs = []) => {
491
+ this.issues = [...this.issues, ...subs];
492
+ };
493
+ const actualProto = new.target.prototype;
494
+ if (Object.setPrototypeOf) {
495
+ Object.setPrototypeOf(this, actualProto);
496
+ } else {
497
+ this.__proto__ = actualProto;
498
+ }
499
+ this.name = "ZodError";
500
+ this.issues = issues;
501
+ }
502
+ get errors() {
503
+ return this.issues;
504
+ }
505
+ format(_mapper) {
506
+ const mapper = _mapper || function(issue) {
507
+ return issue.message;
508
+ };
509
+ const fieldErrors = { _errors: [] };
510
+ const processError = (error) => {
511
+ for (const issue of error.issues) {
512
+ if (issue.code === "invalid_union") {
513
+ issue.unionErrors.map(processError);
514
+ } else if (issue.code === "invalid_return_type") {
515
+ processError(issue.returnTypeError);
516
+ } else if (issue.code === "invalid_arguments") {
517
+ processError(issue.argumentsError);
518
+ } else if (issue.path.length === 0) {
519
+ fieldErrors._errors.push(mapper(issue));
520
+ } else {
521
+ let curr = fieldErrors;
522
+ let i = 0;
523
+ while (i < issue.path.length) {
524
+ const el = issue.path[i];
525
+ const terminal = i === issue.path.length - 1;
526
+ if (!terminal) {
527
+ curr[el] = curr[el] || { _errors: [] };
528
+ } else {
529
+ curr[el] = curr[el] || { _errors: [] };
530
+ curr[el]._errors.push(mapper(issue));
531
+ }
532
+ curr = curr[el];
533
+ i++;
534
+ }
535
+ }
536
+ }
537
+ };
538
+ processError(this);
539
+ return fieldErrors;
540
+ }
541
+ toString() {
542
+ return this.message;
543
+ }
544
+ get message() {
545
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
546
+ }
547
+ get isEmpty() {
548
+ return this.issues.length === 0;
549
+ }
550
+ flatten(mapper = (issue) => issue.message) {
551
+ const fieldErrors = {};
552
+ const formErrors = [];
553
+ for (const sub of this.issues) {
554
+ if (sub.path.length > 0) {
555
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
556
+ fieldErrors[sub.path[0]].push(mapper(sub));
557
+ } else {
558
+ formErrors.push(mapper(sub));
559
+ }
560
+ }
561
+ return { formErrors, fieldErrors };
562
+ }
563
+ get formErrors() {
564
+ return this.flatten();
565
+ }
566
+ };
567
+ ZodError.create = (issues) => {
568
+ const error = new ZodError(issues);
569
+ return error;
570
+ };
571
+ var errorMap = (issue, _ctx) => {
572
+ let message;
573
+ switch (issue.code) {
574
+ case ZodIssueCode.invalid_type:
575
+ if (issue.received === ZodParsedType.undefined) {
576
+ message = "Required";
577
+ } else {
578
+ message = `Expected ${issue.expected}, received ${issue.received}`;
579
+ }
580
+ break;
581
+ case ZodIssueCode.invalid_literal:
582
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
583
+ break;
584
+ case ZodIssueCode.unrecognized_keys:
585
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
586
+ break;
587
+ case ZodIssueCode.invalid_union:
588
+ message = `Invalid input`;
589
+ break;
590
+ case ZodIssueCode.invalid_union_discriminator:
591
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
592
+ break;
593
+ case ZodIssueCode.invalid_enum_value:
594
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
595
+ break;
596
+ case ZodIssueCode.invalid_arguments:
597
+ message = `Invalid function arguments`;
598
+ break;
599
+ case ZodIssueCode.invalid_return_type:
600
+ message = `Invalid function return type`;
601
+ break;
602
+ case ZodIssueCode.invalid_date:
603
+ message = `Invalid date`;
604
+ break;
605
+ case ZodIssueCode.invalid_string:
606
+ if (typeof issue.validation === "object") {
607
+ if ("includes" in issue.validation) {
608
+ message = `Invalid input: must include "${issue.validation.includes}"`;
609
+ if (typeof issue.validation.position === "number") {
610
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
611
+ }
612
+ } else if ("startsWith" in issue.validation) {
613
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
614
+ } else if ("endsWith" in issue.validation) {
615
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
616
+ } else {
617
+ util.assertNever(issue.validation);
618
+ }
619
+ } else if (issue.validation !== "regex") {
620
+ message = `Invalid ${issue.validation}`;
621
+ } else {
622
+ message = "Invalid";
623
+ }
624
+ break;
625
+ case ZodIssueCode.too_small:
626
+ if (issue.type === "array")
627
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
628
+ else if (issue.type === "string")
629
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
630
+ else if (issue.type === "number")
631
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
632
+ else if (issue.type === "date")
633
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
634
+ else
635
+ message = "Invalid input";
636
+ break;
637
+ case ZodIssueCode.too_big:
638
+ if (issue.type === "array")
639
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
640
+ else if (issue.type === "string")
641
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
642
+ else if (issue.type === "number")
643
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
644
+ else if (issue.type === "bigint")
645
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
646
+ else if (issue.type === "date")
647
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
648
+ else
649
+ message = "Invalid input";
650
+ break;
651
+ case ZodIssueCode.custom:
652
+ message = `Invalid input`;
653
+ break;
654
+ case ZodIssueCode.invalid_intersection_types:
655
+ message = `Intersection results could not be merged`;
656
+ break;
657
+ case ZodIssueCode.not_multiple_of:
658
+ message = `Number must be a multiple of ${issue.multipleOf}`;
659
+ break;
660
+ case ZodIssueCode.not_finite:
661
+ message = "Number must be finite";
662
+ break;
663
+ default:
664
+ message = _ctx.defaultError;
665
+ util.assertNever(issue);
666
+ }
667
+ return { message };
668
+ };
669
+ var overrideErrorMap = errorMap;
670
+ function setErrorMap(map) {
671
+ overrideErrorMap = map;
672
+ }
673
+ function getErrorMap() {
674
+ return overrideErrorMap;
675
+ }
676
+ var makeIssue = (params) => {
677
+ const { data, path, errorMaps, issueData } = params;
678
+ const fullPath = [...path, ...issueData.path || []];
679
+ const fullIssue = {
680
+ ...issueData,
681
+ path: fullPath
682
+ };
683
+ let errorMessage = "";
684
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
685
+ for (const map of maps) {
686
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
687
+ }
688
+ return {
689
+ ...issueData,
690
+ path: fullPath,
691
+ message: issueData.message || errorMessage
692
+ };
693
+ };
694
+ var EMPTY_PATH = [];
695
+ function addIssueToContext(ctx, issueData) {
696
+ const issue = makeIssue({
697
+ issueData,
698
+ data: ctx.data,
699
+ path: ctx.path,
700
+ errorMaps: [
701
+ ctx.common.contextualErrorMap,
702
+ ctx.schemaErrorMap,
703
+ getErrorMap(),
704
+ errorMap
705
+ // then global default map
706
+ ].filter((x) => !!x)
707
+ });
708
+ ctx.common.issues.push(issue);
709
+ }
710
+ var ParseStatus = class _ParseStatus {
711
+ constructor() {
712
+ this.value = "valid";
713
+ }
714
+ dirty() {
715
+ if (this.value === "valid")
716
+ this.value = "dirty";
717
+ }
718
+ abort() {
719
+ if (this.value !== "aborted")
720
+ this.value = "aborted";
721
+ }
722
+ static mergeArray(status, results) {
723
+ const arrayValue = [];
724
+ for (const s of results) {
725
+ if (s.status === "aborted")
726
+ return INVALID;
727
+ if (s.status === "dirty")
728
+ status.dirty();
729
+ arrayValue.push(s.value);
730
+ }
731
+ return { status: status.value, value: arrayValue };
732
+ }
733
+ static async mergeObjectAsync(status, pairs) {
734
+ const syncPairs = [];
735
+ for (const pair of pairs) {
736
+ syncPairs.push({
737
+ key: await pair.key,
738
+ value: await pair.value
739
+ });
740
+ }
741
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
742
+ }
743
+ static mergeObjectSync(status, pairs) {
744
+ const finalObject = {};
745
+ for (const pair of pairs) {
746
+ const { key, value } = pair;
747
+ if (key.status === "aborted")
748
+ return INVALID;
749
+ if (value.status === "aborted")
750
+ return INVALID;
751
+ if (key.status === "dirty")
752
+ status.dirty();
753
+ if (value.status === "dirty")
754
+ status.dirty();
755
+ if (typeof value.value !== "undefined" || pair.alwaysSet) {
756
+ finalObject[key.value] = value.value;
757
+ }
758
+ }
759
+ return { status: status.value, value: finalObject };
760
+ }
761
+ };
762
+ var INVALID = Object.freeze({
763
+ status: "aborted"
764
+ });
765
+ var DIRTY = (value) => ({ status: "dirty", value });
766
+ var OK = (value) => ({ status: "valid", value });
767
+ var isAborted = (x) => x.status === "aborted";
768
+ var isDirty = (x) => x.status === "dirty";
769
+ var isValid = (x) => x.status === "valid";
770
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
771
+ var errorUtil;
772
+ (function(errorUtil2) {
773
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
774
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
775
+ })(errorUtil || (errorUtil = {}));
776
+ var ParseInputLazyPath = class {
777
+ constructor(parent, value, path, key) {
778
+ this._cachedPath = [];
779
+ this.parent = parent;
780
+ this.data = value;
781
+ this._path = path;
782
+ this._key = key;
783
+ }
784
+ get path() {
785
+ if (!this._cachedPath.length) {
786
+ if (this._key instanceof Array) {
787
+ this._cachedPath.push(...this._path, ...this._key);
788
+ } else {
789
+ this._cachedPath.push(...this._path, this._key);
790
+ }
791
+ }
792
+ return this._cachedPath;
793
+ }
794
+ };
795
+ var handleResult = (ctx, result) => {
796
+ if (isValid(result)) {
797
+ return { success: true, data: result.value };
798
+ } else {
799
+ if (!ctx.common.issues.length) {
800
+ throw new Error("Validation failed but no issues detected.");
801
+ }
802
+ return {
803
+ success: false,
804
+ get error() {
805
+ if (this._error)
806
+ return this._error;
807
+ const error = new ZodError(ctx.common.issues);
808
+ this._error = error;
809
+ return this._error;
810
+ }
811
+ };
812
+ }
813
+ };
814
+ function processCreateParams(params) {
815
+ if (!params)
816
+ return {};
817
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
818
+ if (errorMap2 && (invalid_type_error || required_error)) {
819
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
820
+ }
821
+ if (errorMap2)
822
+ return { errorMap: errorMap2, description };
823
+ const customMap = (iss, ctx) => {
824
+ if (iss.code !== "invalid_type")
825
+ return { message: ctx.defaultError };
826
+ if (typeof ctx.data === "undefined") {
827
+ return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
828
+ }
829
+ return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
830
+ };
831
+ return { errorMap: customMap, description };
832
+ }
833
+ var ZodType = class {
834
+ constructor(def) {
835
+ this.spa = this.safeParseAsync;
836
+ this._def = def;
837
+ this.parse = this.parse.bind(this);
838
+ this.safeParse = this.safeParse.bind(this);
839
+ this.parseAsync = this.parseAsync.bind(this);
840
+ this.safeParseAsync = this.safeParseAsync.bind(this);
841
+ this.spa = this.spa.bind(this);
842
+ this.refine = this.refine.bind(this);
843
+ this.refinement = this.refinement.bind(this);
844
+ this.superRefine = this.superRefine.bind(this);
845
+ this.optional = this.optional.bind(this);
846
+ this.nullable = this.nullable.bind(this);
847
+ this.nullish = this.nullish.bind(this);
848
+ this.array = this.array.bind(this);
849
+ this.promise = this.promise.bind(this);
850
+ this.or = this.or.bind(this);
851
+ this.and = this.and.bind(this);
852
+ this.transform = this.transform.bind(this);
853
+ this.brand = this.brand.bind(this);
854
+ this.default = this.default.bind(this);
855
+ this.catch = this.catch.bind(this);
856
+ this.describe = this.describe.bind(this);
857
+ this.pipe = this.pipe.bind(this);
858
+ this.isNullable = this.isNullable.bind(this);
859
+ this.isOptional = this.isOptional.bind(this);
860
+ }
861
+ get description() {
862
+ return this._def.description;
863
+ }
864
+ _getType(input) {
865
+ return getParsedType(input.data);
866
+ }
867
+ _getOrReturnCtx(input, ctx) {
868
+ return ctx || {
869
+ common: input.parent.common,
870
+ data: input.data,
871
+ parsedType: getParsedType(input.data),
872
+ schemaErrorMap: this._def.errorMap,
873
+ path: input.path,
874
+ parent: input.parent
875
+ };
876
+ }
877
+ _processInputParams(input) {
878
+ return {
879
+ status: new ParseStatus(),
880
+ ctx: {
881
+ common: input.parent.common,
882
+ data: input.data,
883
+ parsedType: getParsedType(input.data),
884
+ schemaErrorMap: this._def.errorMap,
885
+ path: input.path,
886
+ parent: input.parent
887
+ }
888
+ };
889
+ }
890
+ _parseSync(input) {
891
+ const result = this._parse(input);
892
+ if (isAsync(result)) {
893
+ throw new Error("Synchronous parse encountered promise.");
894
+ }
895
+ return result;
896
+ }
897
+ _parseAsync(input) {
898
+ const result = this._parse(input);
899
+ return Promise.resolve(result);
900
+ }
901
+ parse(data, params) {
902
+ const result = this.safeParse(data, params);
903
+ if (result.success)
904
+ return result.data;
905
+ throw result.error;
906
+ }
907
+ safeParse(data, params) {
908
+ var _a;
909
+ const ctx = {
910
+ common: {
911
+ issues: [],
912
+ async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
913
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
914
+ },
915
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
916
+ schemaErrorMap: this._def.errorMap,
917
+ parent: null,
918
+ data,
919
+ parsedType: getParsedType(data)
920
+ };
921
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
922
+ return handleResult(ctx, result);
923
+ }
924
+ async parseAsync(data, params) {
925
+ const result = await this.safeParseAsync(data, params);
926
+ if (result.success)
927
+ return result.data;
928
+ throw result.error;
929
+ }
930
+ async safeParseAsync(data, params) {
931
+ const ctx = {
932
+ common: {
933
+ issues: [],
934
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
935
+ async: true
936
+ },
937
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
938
+ schemaErrorMap: this._def.errorMap,
939
+ parent: null,
940
+ data,
941
+ parsedType: getParsedType(data)
942
+ };
943
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
944
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
945
+ return handleResult(ctx, result);
946
+ }
947
+ refine(check, message) {
948
+ const getIssueProperties = (val) => {
949
+ if (typeof message === "string" || typeof message === "undefined") {
950
+ return { message };
951
+ } else if (typeof message === "function") {
952
+ return message(val);
953
+ } else {
954
+ return message;
955
+ }
956
+ };
957
+ return this._refinement((val, ctx) => {
958
+ const result = check(val);
959
+ const setError = () => ctx.addIssue({
960
+ code: ZodIssueCode.custom,
961
+ ...getIssueProperties(val)
962
+ });
963
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
964
+ return result.then((data) => {
965
+ if (!data) {
966
+ setError();
967
+ return false;
968
+ } else {
969
+ return true;
970
+ }
971
+ });
972
+ }
973
+ if (!result) {
974
+ setError();
975
+ return false;
976
+ } else {
977
+ return true;
978
+ }
979
+ });
980
+ }
981
+ refinement(check, refinementData) {
982
+ return this._refinement((val, ctx) => {
983
+ if (!check(val)) {
984
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
985
+ return false;
986
+ } else {
987
+ return true;
988
+ }
989
+ });
990
+ }
991
+ _refinement(refinement) {
992
+ return new ZodEffects({
993
+ schema: this,
994
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
995
+ effect: { type: "refinement", refinement }
996
+ });
997
+ }
998
+ superRefine(refinement) {
999
+ return this._refinement(refinement);
1000
+ }
1001
+ optional() {
1002
+ return ZodOptional.create(this, this._def);
1003
+ }
1004
+ nullable() {
1005
+ return ZodNullable.create(this, this._def);
1006
+ }
1007
+ nullish() {
1008
+ return this.nullable().optional();
1009
+ }
1010
+ array() {
1011
+ return ZodArray.create(this, this._def);
1012
+ }
1013
+ promise() {
1014
+ return ZodPromise.create(this, this._def);
1015
+ }
1016
+ or(option) {
1017
+ return ZodUnion.create([this, option], this._def);
1018
+ }
1019
+ and(incoming) {
1020
+ return ZodIntersection.create(this, incoming, this._def);
1021
+ }
1022
+ transform(transform) {
1023
+ return new ZodEffects({
1024
+ ...processCreateParams(this._def),
1025
+ schema: this,
1026
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1027
+ effect: { type: "transform", transform }
1028
+ });
1029
+ }
1030
+ default(def) {
1031
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1032
+ return new ZodDefault({
1033
+ ...processCreateParams(this._def),
1034
+ innerType: this,
1035
+ defaultValue: defaultValueFunc,
1036
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1037
+ });
1038
+ }
1039
+ brand() {
1040
+ return new ZodBranded({
1041
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1042
+ type: this,
1043
+ ...processCreateParams(this._def)
1044
+ });
1045
+ }
1046
+ catch(def) {
1047
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1048
+ return new ZodCatch({
1049
+ ...processCreateParams(this._def),
1050
+ innerType: this,
1051
+ catchValue: catchValueFunc,
1052
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1053
+ });
1054
+ }
1055
+ describe(description) {
1056
+ const This = this.constructor;
1057
+ return new This({
1058
+ ...this._def,
1059
+ description
1060
+ });
1061
+ }
1062
+ pipe(target) {
1063
+ return ZodPipeline.create(this, target);
1064
+ }
1065
+ isOptional() {
1066
+ return this.safeParse(void 0).success;
1067
+ }
1068
+ isNullable() {
1069
+ return this.safeParse(null).success;
1070
+ }
1071
+ };
1072
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1073
+ var cuid2Regex = /^[a-z][a-z0-9]*$/;
1074
+ var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
1075
+ var uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1076
+ var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
1077
+ var emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
1078
+ var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
1079
+ var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1080
+ var datetimeRegex = (args) => {
1081
+ if (args.precision) {
1082
+ if (args.offset) {
1083
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1084
+ } else {
1085
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
1086
+ }
1087
+ } else if (args.precision === 0) {
1088
+ if (args.offset) {
1089
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1090
+ } else {
1091
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
1092
+ }
1093
+ } else {
1094
+ if (args.offset) {
1095
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1096
+ } else {
1097
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
1098
+ }
1099
+ }
1100
+ };
1101
+ function isValidIP(ip, version) {
1102
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1103
+ return true;
1104
+ }
1105
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1106
+ return true;
1107
+ }
1108
+ return false;
1109
+ }
1110
+ var ZodString = class _ZodString extends ZodType {
1111
+ constructor() {
1112
+ super(...arguments);
1113
+ this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
1114
+ validation,
1115
+ code: ZodIssueCode.invalid_string,
1116
+ ...errorUtil.errToObj(message)
1117
+ });
1118
+ this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
1119
+ this.trim = () => new _ZodString({
1120
+ ...this._def,
1121
+ checks: [...this._def.checks, { kind: "trim" }]
1122
+ });
1123
+ this.toLowerCase = () => new _ZodString({
1124
+ ...this._def,
1125
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1126
+ });
1127
+ this.toUpperCase = () => new _ZodString({
1128
+ ...this._def,
1129
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1130
+ });
1131
+ }
1132
+ _parse(input) {
1133
+ if (this._def.coerce) {
1134
+ input.data = String(input.data);
1135
+ }
1136
+ const parsedType = this._getType(input);
1137
+ if (parsedType !== ZodParsedType.string) {
1138
+ const ctx2 = this._getOrReturnCtx(input);
1139
+ addIssueToContext(
1140
+ ctx2,
1141
+ {
1142
+ code: ZodIssueCode.invalid_type,
1143
+ expected: ZodParsedType.string,
1144
+ received: ctx2.parsedType
1145
+ }
1146
+ //
1147
+ );
1148
+ return INVALID;
1149
+ }
1150
+ const status = new ParseStatus();
1151
+ let ctx = void 0;
1152
+ for (const check of this._def.checks) {
1153
+ if (check.kind === "min") {
1154
+ if (input.data.length < check.value) {
1155
+ ctx = this._getOrReturnCtx(input, ctx);
1156
+ addIssueToContext(ctx, {
1157
+ code: ZodIssueCode.too_small,
1158
+ minimum: check.value,
1159
+ type: "string",
1160
+ inclusive: true,
1161
+ exact: false,
1162
+ message: check.message
1163
+ });
1164
+ status.dirty();
1165
+ }
1166
+ } else if (check.kind === "max") {
1167
+ if (input.data.length > check.value) {
1168
+ ctx = this._getOrReturnCtx(input, ctx);
1169
+ addIssueToContext(ctx, {
1170
+ code: ZodIssueCode.too_big,
1171
+ maximum: check.value,
1172
+ type: "string",
1173
+ inclusive: true,
1174
+ exact: false,
1175
+ message: check.message
1176
+ });
1177
+ status.dirty();
1178
+ }
1179
+ } else if (check.kind === "length") {
1180
+ const tooBig = input.data.length > check.value;
1181
+ const tooSmall = input.data.length < check.value;
1182
+ if (tooBig || tooSmall) {
1183
+ ctx = this._getOrReturnCtx(input, ctx);
1184
+ if (tooBig) {
1185
+ addIssueToContext(ctx, {
1186
+ code: ZodIssueCode.too_big,
1187
+ maximum: check.value,
1188
+ type: "string",
1189
+ inclusive: true,
1190
+ exact: true,
1191
+ message: check.message
1192
+ });
1193
+ } else if (tooSmall) {
1194
+ addIssueToContext(ctx, {
1195
+ code: ZodIssueCode.too_small,
1196
+ minimum: check.value,
1197
+ type: "string",
1198
+ inclusive: true,
1199
+ exact: true,
1200
+ message: check.message
1201
+ });
1202
+ }
1203
+ status.dirty();
1204
+ }
1205
+ } else if (check.kind === "email") {
1206
+ if (!emailRegex.test(input.data)) {
1207
+ ctx = this._getOrReturnCtx(input, ctx);
1208
+ addIssueToContext(ctx, {
1209
+ validation: "email",
1210
+ code: ZodIssueCode.invalid_string,
1211
+ message: check.message
1212
+ });
1213
+ status.dirty();
1214
+ }
1215
+ } else if (check.kind === "emoji") {
1216
+ if (!emojiRegex.test(input.data)) {
1217
+ ctx = this._getOrReturnCtx(input, ctx);
1218
+ addIssueToContext(ctx, {
1219
+ validation: "emoji",
1220
+ code: ZodIssueCode.invalid_string,
1221
+ message: check.message
1222
+ });
1223
+ status.dirty();
1224
+ }
1225
+ } else if (check.kind === "uuid") {
1226
+ if (!uuidRegex.test(input.data)) {
1227
+ ctx = this._getOrReturnCtx(input, ctx);
1228
+ addIssueToContext(ctx, {
1229
+ validation: "uuid",
1230
+ code: ZodIssueCode.invalid_string,
1231
+ message: check.message
1232
+ });
1233
+ status.dirty();
1234
+ }
1235
+ } else if (check.kind === "cuid") {
1236
+ if (!cuidRegex.test(input.data)) {
1237
+ ctx = this._getOrReturnCtx(input, ctx);
1238
+ addIssueToContext(ctx, {
1239
+ validation: "cuid",
1240
+ code: ZodIssueCode.invalid_string,
1241
+ message: check.message
1242
+ });
1243
+ status.dirty();
1244
+ }
1245
+ } else if (check.kind === "cuid2") {
1246
+ if (!cuid2Regex.test(input.data)) {
1247
+ ctx = this._getOrReturnCtx(input, ctx);
1248
+ addIssueToContext(ctx, {
1249
+ validation: "cuid2",
1250
+ code: ZodIssueCode.invalid_string,
1251
+ message: check.message
1252
+ });
1253
+ status.dirty();
1254
+ }
1255
+ } else if (check.kind === "ulid") {
1256
+ if (!ulidRegex.test(input.data)) {
1257
+ ctx = this._getOrReturnCtx(input, ctx);
1258
+ addIssueToContext(ctx, {
1259
+ validation: "ulid",
1260
+ code: ZodIssueCode.invalid_string,
1261
+ message: check.message
1262
+ });
1263
+ status.dirty();
1264
+ }
1265
+ } else if (check.kind === "url") {
1266
+ try {
1267
+ new URL(input.data);
1268
+ } catch (_a) {
1269
+ ctx = this._getOrReturnCtx(input, ctx);
1270
+ addIssueToContext(ctx, {
1271
+ validation: "url",
1272
+ code: ZodIssueCode.invalid_string,
1273
+ message: check.message
1274
+ });
1275
+ status.dirty();
1276
+ }
1277
+ } else if (check.kind === "regex") {
1278
+ check.regex.lastIndex = 0;
1279
+ const testResult = check.regex.test(input.data);
1280
+ if (!testResult) {
1281
+ ctx = this._getOrReturnCtx(input, ctx);
1282
+ addIssueToContext(ctx, {
1283
+ validation: "regex",
1284
+ code: ZodIssueCode.invalid_string,
1285
+ message: check.message
1286
+ });
1287
+ status.dirty();
1288
+ }
1289
+ } else if (check.kind === "trim") {
1290
+ input.data = input.data.trim();
1291
+ } else if (check.kind === "includes") {
1292
+ if (!input.data.includes(check.value, check.position)) {
1293
+ ctx = this._getOrReturnCtx(input, ctx);
1294
+ addIssueToContext(ctx, {
1295
+ code: ZodIssueCode.invalid_string,
1296
+ validation: { includes: check.value, position: check.position },
1297
+ message: check.message
1298
+ });
1299
+ status.dirty();
1300
+ }
1301
+ } else if (check.kind === "toLowerCase") {
1302
+ input.data = input.data.toLowerCase();
1303
+ } else if (check.kind === "toUpperCase") {
1304
+ input.data = input.data.toUpperCase();
1305
+ } else if (check.kind === "startsWith") {
1306
+ if (!input.data.startsWith(check.value)) {
1307
+ ctx = this._getOrReturnCtx(input, ctx);
1308
+ addIssueToContext(ctx, {
1309
+ code: ZodIssueCode.invalid_string,
1310
+ validation: { startsWith: check.value },
1311
+ message: check.message
1312
+ });
1313
+ status.dirty();
1314
+ }
1315
+ } else if (check.kind === "endsWith") {
1316
+ if (!input.data.endsWith(check.value)) {
1317
+ ctx = this._getOrReturnCtx(input, ctx);
1318
+ addIssueToContext(ctx, {
1319
+ code: ZodIssueCode.invalid_string,
1320
+ validation: { endsWith: check.value },
1321
+ message: check.message
1322
+ });
1323
+ status.dirty();
1324
+ }
1325
+ } else if (check.kind === "datetime") {
1326
+ const regex = datetimeRegex(check);
1327
+ if (!regex.test(input.data)) {
1328
+ ctx = this._getOrReturnCtx(input, ctx);
1329
+ addIssueToContext(ctx, {
1330
+ code: ZodIssueCode.invalid_string,
1331
+ validation: "datetime",
1332
+ message: check.message
1333
+ });
1334
+ status.dirty();
1335
+ }
1336
+ } else if (check.kind === "ip") {
1337
+ if (!isValidIP(input.data, check.version)) {
1338
+ ctx = this._getOrReturnCtx(input, ctx);
1339
+ addIssueToContext(ctx, {
1340
+ validation: "ip",
1341
+ code: ZodIssueCode.invalid_string,
1342
+ message: check.message
1343
+ });
1344
+ status.dirty();
1345
+ }
1346
+ } else {
1347
+ util.assertNever(check);
1348
+ }
1349
+ }
1350
+ return { status: status.value, value: input.data };
1351
+ }
1352
+ _addCheck(check) {
1353
+ return new _ZodString({
1354
+ ...this._def,
1355
+ checks: [...this._def.checks, check]
1356
+ });
1357
+ }
1358
+ email(message) {
1359
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1360
+ }
1361
+ url(message) {
1362
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1363
+ }
1364
+ emoji(message) {
1365
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1366
+ }
1367
+ uuid(message) {
1368
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1369
+ }
1370
+ cuid(message) {
1371
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1372
+ }
1373
+ cuid2(message) {
1374
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1375
+ }
1376
+ ulid(message) {
1377
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1378
+ }
1379
+ ip(options) {
1380
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1381
+ }
1382
+ datetime(options) {
1383
+ var _a;
1384
+ if (typeof options === "string") {
1385
+ return this._addCheck({
1386
+ kind: "datetime",
1387
+ precision: null,
1388
+ offset: false,
1389
+ message: options
1390
+ });
1391
+ }
1392
+ return this._addCheck({
1393
+ kind: "datetime",
1394
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1395
+ offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1396
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1397
+ });
1398
+ }
1399
+ regex(regex, message) {
1400
+ return this._addCheck({
1401
+ kind: "regex",
1402
+ regex,
1403
+ ...errorUtil.errToObj(message)
1404
+ });
1405
+ }
1406
+ includes(value, options) {
1407
+ return this._addCheck({
1408
+ kind: "includes",
1409
+ value,
1410
+ position: options === null || options === void 0 ? void 0 : options.position,
1411
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
1412
+ });
1413
+ }
1414
+ startsWith(value, message) {
1415
+ return this._addCheck({
1416
+ kind: "startsWith",
1417
+ value,
1418
+ ...errorUtil.errToObj(message)
1419
+ });
1420
+ }
1421
+ endsWith(value, message) {
1422
+ return this._addCheck({
1423
+ kind: "endsWith",
1424
+ value,
1425
+ ...errorUtil.errToObj(message)
1426
+ });
1427
+ }
1428
+ min(minLength, message) {
1429
+ return this._addCheck({
1430
+ kind: "min",
1431
+ value: minLength,
1432
+ ...errorUtil.errToObj(message)
1433
+ });
1434
+ }
1435
+ max(maxLength, message) {
1436
+ return this._addCheck({
1437
+ kind: "max",
1438
+ value: maxLength,
1439
+ ...errorUtil.errToObj(message)
1440
+ });
1441
+ }
1442
+ length(len, message) {
1443
+ return this._addCheck({
1444
+ kind: "length",
1445
+ value: len,
1446
+ ...errorUtil.errToObj(message)
1447
+ });
1448
+ }
1449
+ get isDatetime() {
1450
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1451
+ }
1452
+ get isEmail() {
1453
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1454
+ }
1455
+ get isURL() {
1456
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1457
+ }
1458
+ get isEmoji() {
1459
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1460
+ }
1461
+ get isUUID() {
1462
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1463
+ }
1464
+ get isCUID() {
1465
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1466
+ }
1467
+ get isCUID2() {
1468
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1469
+ }
1470
+ get isULID() {
1471
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1472
+ }
1473
+ get isIP() {
1474
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1475
+ }
1476
+ get minLength() {
1477
+ let min = null;
1478
+ for (const ch of this._def.checks) {
1479
+ if (ch.kind === "min") {
1480
+ if (min === null || ch.value > min)
1481
+ min = ch.value;
1482
+ }
1483
+ }
1484
+ return min;
1485
+ }
1486
+ get maxLength() {
1487
+ let max = null;
1488
+ for (const ch of this._def.checks) {
1489
+ if (ch.kind === "max") {
1490
+ if (max === null || ch.value < max)
1491
+ max = ch.value;
1492
+ }
1493
+ }
1494
+ return max;
1495
+ }
1496
+ };
1497
+ ZodString.create = (params) => {
1498
+ var _a;
1499
+ return new ZodString({
1500
+ checks: [],
1501
+ typeName: ZodFirstPartyTypeKind.ZodString,
1502
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
1503
+ ...processCreateParams(params)
1504
+ });
1505
+ };
1506
+ function floatSafeRemainder(val, step) {
1507
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1508
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1509
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1510
+ const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
1511
+ const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
1512
+ return valInt % stepInt / Math.pow(10, decCount);
1513
+ }
1514
+ var ZodNumber = class _ZodNumber extends ZodType {
1515
+ constructor() {
1516
+ super(...arguments);
1517
+ this.min = this.gte;
1518
+ this.max = this.lte;
1519
+ this.step = this.multipleOf;
1520
+ }
1521
+ _parse(input) {
1522
+ if (this._def.coerce) {
1523
+ input.data = Number(input.data);
1524
+ }
1525
+ const parsedType = this._getType(input);
1526
+ if (parsedType !== ZodParsedType.number) {
1527
+ const ctx2 = this._getOrReturnCtx(input);
1528
+ addIssueToContext(ctx2, {
1529
+ code: ZodIssueCode.invalid_type,
1530
+ expected: ZodParsedType.number,
1531
+ received: ctx2.parsedType
1532
+ });
1533
+ return INVALID;
1534
+ }
1535
+ let ctx = void 0;
1536
+ const status = new ParseStatus();
1537
+ for (const check of this._def.checks) {
1538
+ if (check.kind === "int") {
1539
+ if (!util.isInteger(input.data)) {
1540
+ ctx = this._getOrReturnCtx(input, ctx);
1541
+ addIssueToContext(ctx, {
1542
+ code: ZodIssueCode.invalid_type,
1543
+ expected: "integer",
1544
+ received: "float",
1545
+ message: check.message
1546
+ });
1547
+ status.dirty();
1548
+ }
1549
+ } else if (check.kind === "min") {
1550
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1551
+ if (tooSmall) {
1552
+ ctx = this._getOrReturnCtx(input, ctx);
1553
+ addIssueToContext(ctx, {
1554
+ code: ZodIssueCode.too_small,
1555
+ minimum: check.value,
1556
+ type: "number",
1557
+ inclusive: check.inclusive,
1558
+ exact: false,
1559
+ message: check.message
1560
+ });
1561
+ status.dirty();
1562
+ }
1563
+ } else if (check.kind === "max") {
1564
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1565
+ if (tooBig) {
1566
+ ctx = this._getOrReturnCtx(input, ctx);
1567
+ addIssueToContext(ctx, {
1568
+ code: ZodIssueCode.too_big,
1569
+ maximum: check.value,
1570
+ type: "number",
1571
+ inclusive: check.inclusive,
1572
+ exact: false,
1573
+ message: check.message
1574
+ });
1575
+ status.dirty();
1576
+ }
1577
+ } else if (check.kind === "multipleOf") {
1578
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1579
+ ctx = this._getOrReturnCtx(input, ctx);
1580
+ addIssueToContext(ctx, {
1581
+ code: ZodIssueCode.not_multiple_of,
1582
+ multipleOf: check.value,
1583
+ message: check.message
1584
+ });
1585
+ status.dirty();
1586
+ }
1587
+ } else if (check.kind === "finite") {
1588
+ if (!Number.isFinite(input.data)) {
1589
+ ctx = this._getOrReturnCtx(input, ctx);
1590
+ addIssueToContext(ctx, {
1591
+ code: ZodIssueCode.not_finite,
1592
+ message: check.message
1593
+ });
1594
+ status.dirty();
1595
+ }
1596
+ } else {
1597
+ util.assertNever(check);
1598
+ }
1599
+ }
1600
+ return { status: status.value, value: input.data };
1601
+ }
1602
+ gte(value, message) {
1603
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1604
+ }
1605
+ gt(value, message) {
1606
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1607
+ }
1608
+ lte(value, message) {
1609
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1610
+ }
1611
+ lt(value, message) {
1612
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1613
+ }
1614
+ setLimit(kind, value, inclusive, message) {
1615
+ return new _ZodNumber({
1616
+ ...this._def,
1617
+ checks: [
1618
+ ...this._def.checks,
1619
+ {
1620
+ kind,
1621
+ value,
1622
+ inclusive,
1623
+ message: errorUtil.toString(message)
1624
+ }
1625
+ ]
1626
+ });
1627
+ }
1628
+ _addCheck(check) {
1629
+ return new _ZodNumber({
1630
+ ...this._def,
1631
+ checks: [...this._def.checks, check]
1632
+ });
1633
+ }
1634
+ int(message) {
1635
+ return this._addCheck({
1636
+ kind: "int",
1637
+ message: errorUtil.toString(message)
1638
+ });
1639
+ }
1640
+ positive(message) {
1641
+ return this._addCheck({
1642
+ kind: "min",
1643
+ value: 0,
1644
+ inclusive: false,
1645
+ message: errorUtil.toString(message)
1646
+ });
1647
+ }
1648
+ negative(message) {
1649
+ return this._addCheck({
1650
+ kind: "max",
1651
+ value: 0,
1652
+ inclusive: false,
1653
+ message: errorUtil.toString(message)
1654
+ });
1655
+ }
1656
+ nonpositive(message) {
1657
+ return this._addCheck({
1658
+ kind: "max",
1659
+ value: 0,
1660
+ inclusive: true,
1661
+ message: errorUtil.toString(message)
1662
+ });
1663
+ }
1664
+ nonnegative(message) {
1665
+ return this._addCheck({
1666
+ kind: "min",
1667
+ value: 0,
1668
+ inclusive: true,
1669
+ message: errorUtil.toString(message)
1670
+ });
1671
+ }
1672
+ multipleOf(value, message) {
1673
+ return this._addCheck({
1674
+ kind: "multipleOf",
1675
+ value,
1676
+ message: errorUtil.toString(message)
1677
+ });
1678
+ }
1679
+ finite(message) {
1680
+ return this._addCheck({
1681
+ kind: "finite",
1682
+ message: errorUtil.toString(message)
1683
+ });
1684
+ }
1685
+ safe(message) {
1686
+ return this._addCheck({
1687
+ kind: "min",
1688
+ inclusive: true,
1689
+ value: Number.MIN_SAFE_INTEGER,
1690
+ message: errorUtil.toString(message)
1691
+ })._addCheck({
1692
+ kind: "max",
1693
+ inclusive: true,
1694
+ value: Number.MAX_SAFE_INTEGER,
1695
+ message: errorUtil.toString(message)
1696
+ });
1697
+ }
1698
+ get minValue() {
1699
+ let min = null;
1700
+ for (const ch of this._def.checks) {
1701
+ if (ch.kind === "min") {
1702
+ if (min === null || ch.value > min)
1703
+ min = ch.value;
1704
+ }
1705
+ }
1706
+ return min;
1707
+ }
1708
+ get maxValue() {
1709
+ let max = null;
1710
+ for (const ch of this._def.checks) {
1711
+ if (ch.kind === "max") {
1712
+ if (max === null || ch.value < max)
1713
+ max = ch.value;
1714
+ }
1715
+ }
1716
+ return max;
1717
+ }
1718
+ get isInt() {
1719
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1720
+ }
1721
+ get isFinite() {
1722
+ let max = null, min = null;
1723
+ for (const ch of this._def.checks) {
1724
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1725
+ return true;
1726
+ } else if (ch.kind === "min") {
1727
+ if (min === null || ch.value > min)
1728
+ min = ch.value;
1729
+ } else if (ch.kind === "max") {
1730
+ if (max === null || ch.value < max)
1731
+ max = ch.value;
1732
+ }
1733
+ }
1734
+ return Number.isFinite(min) && Number.isFinite(max);
1735
+ }
1736
+ };
1737
+ ZodNumber.create = (params) => {
1738
+ return new ZodNumber({
1739
+ checks: [],
1740
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1741
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
1742
+ ...processCreateParams(params)
1743
+ });
1744
+ };
1745
+ var ZodBigInt = class _ZodBigInt extends ZodType {
1746
+ constructor() {
1747
+ super(...arguments);
1748
+ this.min = this.gte;
1749
+ this.max = this.lte;
1750
+ }
1751
+ _parse(input) {
1752
+ if (this._def.coerce) {
1753
+ input.data = BigInt(input.data);
1754
+ }
1755
+ const parsedType = this._getType(input);
1756
+ if (parsedType !== ZodParsedType.bigint) {
1757
+ const ctx2 = this._getOrReturnCtx(input);
1758
+ addIssueToContext(ctx2, {
1759
+ code: ZodIssueCode.invalid_type,
1760
+ expected: ZodParsedType.bigint,
1761
+ received: ctx2.parsedType
1762
+ });
1763
+ return INVALID;
1764
+ }
1765
+ let ctx = void 0;
1766
+ const status = new ParseStatus();
1767
+ for (const check of this._def.checks) {
1768
+ if (check.kind === "min") {
1769
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1770
+ if (tooSmall) {
1771
+ ctx = this._getOrReturnCtx(input, ctx);
1772
+ addIssueToContext(ctx, {
1773
+ code: ZodIssueCode.too_small,
1774
+ type: "bigint",
1775
+ minimum: check.value,
1776
+ inclusive: check.inclusive,
1777
+ message: check.message
1778
+ });
1779
+ status.dirty();
1780
+ }
1781
+ } else if (check.kind === "max") {
1782
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1783
+ if (tooBig) {
1784
+ ctx = this._getOrReturnCtx(input, ctx);
1785
+ addIssueToContext(ctx, {
1786
+ code: ZodIssueCode.too_big,
1787
+ type: "bigint",
1788
+ maximum: check.value,
1789
+ inclusive: check.inclusive,
1790
+ message: check.message
1791
+ });
1792
+ status.dirty();
1793
+ }
1794
+ } else if (check.kind === "multipleOf") {
1795
+ if (input.data % check.value !== BigInt(0)) {
1796
+ ctx = this._getOrReturnCtx(input, ctx);
1797
+ addIssueToContext(ctx, {
1798
+ code: ZodIssueCode.not_multiple_of,
1799
+ multipleOf: check.value,
1800
+ message: check.message
1801
+ });
1802
+ status.dirty();
1803
+ }
1804
+ } else {
1805
+ util.assertNever(check);
1806
+ }
1807
+ }
1808
+ return { status: status.value, value: input.data };
1809
+ }
1810
+ gte(value, message) {
1811
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1812
+ }
1813
+ gt(value, message) {
1814
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1815
+ }
1816
+ lte(value, message) {
1817
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1818
+ }
1819
+ lt(value, message) {
1820
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1821
+ }
1822
+ setLimit(kind, value, inclusive, message) {
1823
+ return new _ZodBigInt({
1824
+ ...this._def,
1825
+ checks: [
1826
+ ...this._def.checks,
1827
+ {
1828
+ kind,
1829
+ value,
1830
+ inclusive,
1831
+ message: errorUtil.toString(message)
1832
+ }
1833
+ ]
1834
+ });
1835
+ }
1836
+ _addCheck(check) {
1837
+ return new _ZodBigInt({
1838
+ ...this._def,
1839
+ checks: [...this._def.checks, check]
1840
+ });
1841
+ }
1842
+ positive(message) {
1843
+ return this._addCheck({
1844
+ kind: "min",
1845
+ value: BigInt(0),
1846
+ inclusive: false,
1847
+ message: errorUtil.toString(message)
1848
+ });
1849
+ }
1850
+ negative(message) {
1851
+ return this._addCheck({
1852
+ kind: "max",
1853
+ value: BigInt(0),
1854
+ inclusive: false,
1855
+ message: errorUtil.toString(message)
1856
+ });
1857
+ }
1858
+ nonpositive(message) {
1859
+ return this._addCheck({
1860
+ kind: "max",
1861
+ value: BigInt(0),
1862
+ inclusive: true,
1863
+ message: errorUtil.toString(message)
1864
+ });
1865
+ }
1866
+ nonnegative(message) {
1867
+ return this._addCheck({
1868
+ kind: "min",
1869
+ value: BigInt(0),
1870
+ inclusive: true,
1871
+ message: errorUtil.toString(message)
1872
+ });
1873
+ }
1874
+ multipleOf(value, message) {
1875
+ return this._addCheck({
1876
+ kind: "multipleOf",
1877
+ value,
1878
+ message: errorUtil.toString(message)
1879
+ });
1880
+ }
1881
+ get minValue() {
1882
+ let min = null;
1883
+ for (const ch of this._def.checks) {
1884
+ if (ch.kind === "min") {
1885
+ if (min === null || ch.value > min)
1886
+ min = ch.value;
1887
+ }
1888
+ }
1889
+ return min;
1890
+ }
1891
+ get maxValue() {
1892
+ let max = null;
1893
+ for (const ch of this._def.checks) {
1894
+ if (ch.kind === "max") {
1895
+ if (max === null || ch.value < max)
1896
+ max = ch.value;
1897
+ }
1898
+ }
1899
+ return max;
1900
+ }
1901
+ };
1902
+ ZodBigInt.create = (params) => {
1903
+ var _a;
1904
+ return new ZodBigInt({
1905
+ checks: [],
1906
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1907
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
1908
+ ...processCreateParams(params)
1909
+ });
1910
+ };
1911
+ var ZodBoolean = class extends ZodType {
1912
+ _parse(input) {
1913
+ if (this._def.coerce) {
1914
+ input.data = Boolean(input.data);
1915
+ }
1916
+ const parsedType = this._getType(input);
1917
+ if (parsedType !== ZodParsedType.boolean) {
1918
+ const ctx = this._getOrReturnCtx(input);
1919
+ addIssueToContext(ctx, {
1920
+ code: ZodIssueCode.invalid_type,
1921
+ expected: ZodParsedType.boolean,
1922
+ received: ctx.parsedType
1923
+ });
1924
+ return INVALID;
1925
+ }
1926
+ return OK(input.data);
1927
+ }
1928
+ };
1929
+ ZodBoolean.create = (params) => {
1930
+ return new ZodBoolean({
1931
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1932
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
1933
+ ...processCreateParams(params)
1934
+ });
1935
+ };
1936
+ var ZodDate = class _ZodDate extends ZodType {
1937
+ _parse(input) {
1938
+ if (this._def.coerce) {
1939
+ input.data = new Date(input.data);
1940
+ }
1941
+ const parsedType = this._getType(input);
1942
+ if (parsedType !== ZodParsedType.date) {
1943
+ const ctx2 = this._getOrReturnCtx(input);
1944
+ addIssueToContext(ctx2, {
1945
+ code: ZodIssueCode.invalid_type,
1946
+ expected: ZodParsedType.date,
1947
+ received: ctx2.parsedType
1948
+ });
1949
+ return INVALID;
1950
+ }
1951
+ if (isNaN(input.data.getTime())) {
1952
+ const ctx2 = this._getOrReturnCtx(input);
1953
+ addIssueToContext(ctx2, {
1954
+ code: ZodIssueCode.invalid_date
1955
+ });
1956
+ return INVALID;
1957
+ }
1958
+ const status = new ParseStatus();
1959
+ let ctx = void 0;
1960
+ for (const check of this._def.checks) {
1961
+ if (check.kind === "min") {
1962
+ if (input.data.getTime() < check.value) {
1963
+ ctx = this._getOrReturnCtx(input, ctx);
1964
+ addIssueToContext(ctx, {
1965
+ code: ZodIssueCode.too_small,
1966
+ message: check.message,
1967
+ inclusive: true,
1968
+ exact: false,
1969
+ minimum: check.value,
1970
+ type: "date"
1971
+ });
1972
+ status.dirty();
1973
+ }
1974
+ } else if (check.kind === "max") {
1975
+ if (input.data.getTime() > check.value) {
1976
+ ctx = this._getOrReturnCtx(input, ctx);
1977
+ addIssueToContext(ctx, {
1978
+ code: ZodIssueCode.too_big,
1979
+ message: check.message,
1980
+ inclusive: true,
1981
+ exact: false,
1982
+ maximum: check.value,
1983
+ type: "date"
1984
+ });
1985
+ status.dirty();
1986
+ }
1987
+ } else {
1988
+ util.assertNever(check);
1989
+ }
1990
+ }
1991
+ return {
1992
+ status: status.value,
1993
+ value: new Date(input.data.getTime())
1994
+ };
1995
+ }
1996
+ _addCheck(check) {
1997
+ return new _ZodDate({
1998
+ ...this._def,
1999
+ checks: [...this._def.checks, check]
2000
+ });
2001
+ }
2002
+ min(minDate, message) {
2003
+ return this._addCheck({
2004
+ kind: "min",
2005
+ value: minDate.getTime(),
2006
+ message: errorUtil.toString(message)
2007
+ });
2008
+ }
2009
+ max(maxDate, message) {
2010
+ return this._addCheck({
2011
+ kind: "max",
2012
+ value: maxDate.getTime(),
2013
+ message: errorUtil.toString(message)
2014
+ });
2015
+ }
2016
+ get minDate() {
2017
+ let min = null;
2018
+ for (const ch of this._def.checks) {
2019
+ if (ch.kind === "min") {
2020
+ if (min === null || ch.value > min)
2021
+ min = ch.value;
2022
+ }
2023
+ }
2024
+ return min != null ? new Date(min) : null;
2025
+ }
2026
+ get maxDate() {
2027
+ let max = null;
2028
+ for (const ch of this._def.checks) {
2029
+ if (ch.kind === "max") {
2030
+ if (max === null || ch.value < max)
2031
+ max = ch.value;
2032
+ }
2033
+ }
2034
+ return max != null ? new Date(max) : null;
2035
+ }
2036
+ };
2037
+ ZodDate.create = (params) => {
2038
+ return new ZodDate({
2039
+ checks: [],
2040
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
2041
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2042
+ ...processCreateParams(params)
2043
+ });
2044
+ };
2045
+ var ZodSymbol = class extends ZodType {
2046
+ _parse(input) {
2047
+ const parsedType = this._getType(input);
2048
+ if (parsedType !== ZodParsedType.symbol) {
2049
+ const ctx = this._getOrReturnCtx(input);
2050
+ addIssueToContext(ctx, {
2051
+ code: ZodIssueCode.invalid_type,
2052
+ expected: ZodParsedType.symbol,
2053
+ received: ctx.parsedType
2054
+ });
2055
+ return INVALID;
2056
+ }
2057
+ return OK(input.data);
2058
+ }
2059
+ };
2060
+ ZodSymbol.create = (params) => {
2061
+ return new ZodSymbol({
2062
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2063
+ ...processCreateParams(params)
2064
+ });
2065
+ };
2066
+ var ZodUndefined = class extends ZodType {
2067
+ _parse(input) {
2068
+ const parsedType = this._getType(input);
2069
+ if (parsedType !== ZodParsedType.undefined) {
2070
+ const ctx = this._getOrReturnCtx(input);
2071
+ addIssueToContext(ctx, {
2072
+ code: ZodIssueCode.invalid_type,
2073
+ expected: ZodParsedType.undefined,
2074
+ received: ctx.parsedType
2075
+ });
2076
+ return INVALID;
2077
+ }
2078
+ return OK(input.data);
2079
+ }
2080
+ };
2081
+ ZodUndefined.create = (params) => {
2082
+ return new ZodUndefined({
2083
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2084
+ ...processCreateParams(params)
2085
+ });
2086
+ };
2087
+ var ZodNull = class extends ZodType {
2088
+ _parse(input) {
2089
+ const parsedType = this._getType(input);
2090
+ if (parsedType !== ZodParsedType.null) {
2091
+ const ctx = this._getOrReturnCtx(input);
2092
+ addIssueToContext(ctx, {
2093
+ code: ZodIssueCode.invalid_type,
2094
+ expected: ZodParsedType.null,
2095
+ received: ctx.parsedType
2096
+ });
2097
+ return INVALID;
2098
+ }
2099
+ return OK(input.data);
2100
+ }
2101
+ };
2102
+ ZodNull.create = (params) => {
2103
+ return new ZodNull({
2104
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2105
+ ...processCreateParams(params)
2106
+ });
2107
+ };
2108
+ var ZodAny = class extends ZodType {
2109
+ constructor() {
2110
+ super(...arguments);
2111
+ this._any = true;
2112
+ }
2113
+ _parse(input) {
2114
+ return OK(input.data);
2115
+ }
2116
+ };
2117
+ ZodAny.create = (params) => {
2118
+ return new ZodAny({
2119
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2120
+ ...processCreateParams(params)
2121
+ });
2122
+ };
2123
+ var ZodUnknown = class extends ZodType {
2124
+ constructor() {
2125
+ super(...arguments);
2126
+ this._unknown = true;
2127
+ }
2128
+ _parse(input) {
2129
+ return OK(input.data);
2130
+ }
2131
+ };
2132
+ ZodUnknown.create = (params) => {
2133
+ return new ZodUnknown({
2134
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2135
+ ...processCreateParams(params)
2136
+ });
2137
+ };
2138
+ var ZodNever = class extends ZodType {
2139
+ _parse(input) {
2140
+ const ctx = this._getOrReturnCtx(input);
2141
+ addIssueToContext(ctx, {
2142
+ code: ZodIssueCode.invalid_type,
2143
+ expected: ZodParsedType.never,
2144
+ received: ctx.parsedType
2145
+ });
2146
+ return INVALID;
2147
+ }
2148
+ };
2149
+ ZodNever.create = (params) => {
2150
+ return new ZodNever({
2151
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2152
+ ...processCreateParams(params)
2153
+ });
2154
+ };
2155
+ var ZodVoid = class extends ZodType {
2156
+ _parse(input) {
2157
+ const parsedType = this._getType(input);
2158
+ if (parsedType !== ZodParsedType.undefined) {
2159
+ const ctx = this._getOrReturnCtx(input);
2160
+ addIssueToContext(ctx, {
2161
+ code: ZodIssueCode.invalid_type,
2162
+ expected: ZodParsedType.void,
2163
+ received: ctx.parsedType
2164
+ });
2165
+ return INVALID;
2166
+ }
2167
+ return OK(input.data);
2168
+ }
2169
+ };
2170
+ ZodVoid.create = (params) => {
2171
+ return new ZodVoid({
2172
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2173
+ ...processCreateParams(params)
2174
+ });
2175
+ };
2176
+ var ZodArray = class _ZodArray extends ZodType {
2177
+ _parse(input) {
2178
+ const { ctx, status } = this._processInputParams(input);
2179
+ const def = this._def;
2180
+ if (ctx.parsedType !== ZodParsedType.array) {
2181
+ addIssueToContext(ctx, {
2182
+ code: ZodIssueCode.invalid_type,
2183
+ expected: ZodParsedType.array,
2184
+ received: ctx.parsedType
2185
+ });
2186
+ return INVALID;
2187
+ }
2188
+ if (def.exactLength !== null) {
2189
+ const tooBig = ctx.data.length > def.exactLength.value;
2190
+ const tooSmall = ctx.data.length < def.exactLength.value;
2191
+ if (tooBig || tooSmall) {
2192
+ addIssueToContext(ctx, {
2193
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2194
+ minimum: tooSmall ? def.exactLength.value : void 0,
2195
+ maximum: tooBig ? def.exactLength.value : void 0,
2196
+ type: "array",
2197
+ inclusive: true,
2198
+ exact: true,
2199
+ message: def.exactLength.message
2200
+ });
2201
+ status.dirty();
2202
+ }
2203
+ }
2204
+ if (def.minLength !== null) {
2205
+ if (ctx.data.length < def.minLength.value) {
2206
+ addIssueToContext(ctx, {
2207
+ code: ZodIssueCode.too_small,
2208
+ minimum: def.minLength.value,
2209
+ type: "array",
2210
+ inclusive: true,
2211
+ exact: false,
2212
+ message: def.minLength.message
2213
+ });
2214
+ status.dirty();
2215
+ }
2216
+ }
2217
+ if (def.maxLength !== null) {
2218
+ if (ctx.data.length > def.maxLength.value) {
2219
+ addIssueToContext(ctx, {
2220
+ code: ZodIssueCode.too_big,
2221
+ maximum: def.maxLength.value,
2222
+ type: "array",
2223
+ inclusive: true,
2224
+ exact: false,
2225
+ message: def.maxLength.message
2226
+ });
2227
+ status.dirty();
2228
+ }
2229
+ }
2230
+ if (ctx.common.async) {
2231
+ return Promise.all([...ctx.data].map((item, i) => {
2232
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2233
+ })).then((result2) => {
2234
+ return ParseStatus.mergeArray(status, result2);
2235
+ });
2236
+ }
2237
+ const result = [...ctx.data].map((item, i) => {
2238
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2239
+ });
2240
+ return ParseStatus.mergeArray(status, result);
2241
+ }
2242
+ get element() {
2243
+ return this._def.type;
2244
+ }
2245
+ min(minLength, message) {
2246
+ return new _ZodArray({
2247
+ ...this._def,
2248
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2249
+ });
2250
+ }
2251
+ max(maxLength, message) {
2252
+ return new _ZodArray({
2253
+ ...this._def,
2254
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2255
+ });
2256
+ }
2257
+ length(len, message) {
2258
+ return new _ZodArray({
2259
+ ...this._def,
2260
+ exactLength: { value: len, message: errorUtil.toString(message) }
2261
+ });
2262
+ }
2263
+ nonempty(message) {
2264
+ return this.min(1, message);
2265
+ }
2266
+ };
2267
+ ZodArray.create = (schema, params) => {
2268
+ return new ZodArray({
2269
+ type: schema,
2270
+ minLength: null,
2271
+ maxLength: null,
2272
+ exactLength: null,
2273
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2274
+ ...processCreateParams(params)
2275
+ });
2276
+ };
2277
+ function deepPartialify(schema) {
2278
+ if (schema instanceof ZodObject) {
2279
+ const newShape = {};
2280
+ for (const key in schema.shape) {
2281
+ const fieldSchema = schema.shape[key];
2282
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2283
+ }
2284
+ return new ZodObject({
2285
+ ...schema._def,
2286
+ shape: () => newShape
2287
+ });
2288
+ } else if (schema instanceof ZodArray) {
2289
+ return new ZodArray({
2290
+ ...schema._def,
2291
+ type: deepPartialify(schema.element)
2292
+ });
2293
+ } else if (schema instanceof ZodOptional) {
2294
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2295
+ } else if (schema instanceof ZodNullable) {
2296
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2297
+ } else if (schema instanceof ZodTuple) {
2298
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2299
+ } else {
2300
+ return schema;
2301
+ }
2302
+ }
2303
+ var ZodObject = class _ZodObject extends ZodType {
2304
+ constructor() {
2305
+ super(...arguments);
2306
+ this._cached = null;
2307
+ this.nonstrict = this.passthrough;
2308
+ this.augment = this.extend;
2309
+ }
2310
+ _getCached() {
2311
+ if (this._cached !== null)
2312
+ return this._cached;
2313
+ const shape = this._def.shape();
2314
+ const keys = util.objectKeys(shape);
2315
+ return this._cached = { shape, keys };
2316
+ }
2317
+ _parse(input) {
2318
+ const parsedType = this._getType(input);
2319
+ if (parsedType !== ZodParsedType.object) {
2320
+ const ctx2 = this._getOrReturnCtx(input);
2321
+ addIssueToContext(ctx2, {
2322
+ code: ZodIssueCode.invalid_type,
2323
+ expected: ZodParsedType.object,
2324
+ received: ctx2.parsedType
2325
+ });
2326
+ return INVALID;
2327
+ }
2328
+ const { status, ctx } = this._processInputParams(input);
2329
+ const { shape, keys: shapeKeys } = this._getCached();
2330
+ const extraKeys = [];
2331
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2332
+ for (const key in ctx.data) {
2333
+ if (!shapeKeys.includes(key)) {
2334
+ extraKeys.push(key);
2335
+ }
2336
+ }
2337
+ }
2338
+ const pairs = [];
2339
+ for (const key of shapeKeys) {
2340
+ const keyValidator = shape[key];
2341
+ const value = ctx.data[key];
2342
+ pairs.push({
2343
+ key: { status: "valid", value: key },
2344
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2345
+ alwaysSet: key in ctx.data
2346
+ });
2347
+ }
2348
+ if (this._def.catchall instanceof ZodNever) {
2349
+ const unknownKeys = this._def.unknownKeys;
2350
+ if (unknownKeys === "passthrough") {
2351
+ for (const key of extraKeys) {
2352
+ pairs.push({
2353
+ key: { status: "valid", value: key },
2354
+ value: { status: "valid", value: ctx.data[key] }
2355
+ });
2356
+ }
2357
+ } else if (unknownKeys === "strict") {
2358
+ if (extraKeys.length > 0) {
2359
+ addIssueToContext(ctx, {
2360
+ code: ZodIssueCode.unrecognized_keys,
2361
+ keys: extraKeys
2362
+ });
2363
+ status.dirty();
2364
+ }
2365
+ } else if (unknownKeys === "strip")
2366
+ ;
2367
+ else {
2368
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2369
+ }
2370
+ } else {
2371
+ const catchall = this._def.catchall;
2372
+ for (const key of extraKeys) {
2373
+ const value = ctx.data[key];
2374
+ pairs.push({
2375
+ key: { status: "valid", value: key },
2376
+ value: catchall._parse(
2377
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
2378
+ //, ctx.child(key), value, getParsedType(value)
2379
+ ),
2380
+ alwaysSet: key in ctx.data
2381
+ });
2382
+ }
2383
+ }
2384
+ if (ctx.common.async) {
2385
+ return Promise.resolve().then(async () => {
2386
+ const syncPairs = [];
2387
+ for (const pair of pairs) {
2388
+ const key = await pair.key;
2389
+ syncPairs.push({
2390
+ key,
2391
+ value: await pair.value,
2392
+ alwaysSet: pair.alwaysSet
2393
+ });
2394
+ }
2395
+ return syncPairs;
2396
+ }).then((syncPairs) => {
2397
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2398
+ });
2399
+ } else {
2400
+ return ParseStatus.mergeObjectSync(status, pairs);
2401
+ }
2402
+ }
2403
+ get shape() {
2404
+ return this._def.shape();
2405
+ }
2406
+ strict(message) {
2407
+ errorUtil.errToObj;
2408
+ return new _ZodObject({
2409
+ ...this._def,
2410
+ unknownKeys: "strict",
2411
+ ...message !== void 0 ? {
2412
+ errorMap: (issue, ctx) => {
2413
+ var _a, _b, _c, _d;
2414
+ const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
2415
+ if (issue.code === "unrecognized_keys")
2416
+ return {
2417
+ message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
2418
+ };
2419
+ return {
2420
+ message: defaultError
2421
+ };
2422
+ }
2423
+ } : {}
2424
+ });
2425
+ }
2426
+ strip() {
2427
+ return new _ZodObject({
2428
+ ...this._def,
2429
+ unknownKeys: "strip"
2430
+ });
2431
+ }
2432
+ passthrough() {
2433
+ return new _ZodObject({
2434
+ ...this._def,
2435
+ unknownKeys: "passthrough"
2436
+ });
2437
+ }
2438
+ // const AugmentFactory =
2439
+ // <Def extends ZodObjectDef>(def: Def) =>
2440
+ // <Augmentation extends ZodRawShape>(
2441
+ // augmentation: Augmentation
2442
+ // ): ZodObject<
2443
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2444
+ // Def["unknownKeys"],
2445
+ // Def["catchall"]
2446
+ // > => {
2447
+ // return new ZodObject({
2448
+ // ...def,
2449
+ // shape: () => ({
2450
+ // ...def.shape(),
2451
+ // ...augmentation,
2452
+ // }),
2453
+ // }) as any;
2454
+ // };
2455
+ extend(augmentation) {
2456
+ return new _ZodObject({
2457
+ ...this._def,
2458
+ shape: () => ({
2459
+ ...this._def.shape(),
2460
+ ...augmentation
2461
+ })
2462
+ });
2463
+ }
2464
+ /**
2465
+ * Prior to zod@1.0.12 there was a bug in the
2466
+ * inferred type of merged objects. Please
2467
+ * upgrade if you are experiencing issues.
2468
+ */
2469
+ merge(merging) {
2470
+ const merged = new _ZodObject({
2471
+ unknownKeys: merging._def.unknownKeys,
2472
+ catchall: merging._def.catchall,
2473
+ shape: () => ({
2474
+ ...this._def.shape(),
2475
+ ...merging._def.shape()
2476
+ }),
2477
+ typeName: ZodFirstPartyTypeKind.ZodObject
2478
+ });
2479
+ return merged;
2480
+ }
2481
+ // merge<
2482
+ // Incoming extends AnyZodObject,
2483
+ // Augmentation extends Incoming["shape"],
2484
+ // NewOutput extends {
2485
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2486
+ // ? Augmentation[k]["_output"]
2487
+ // : k extends keyof Output
2488
+ // ? Output[k]
2489
+ // : never;
2490
+ // },
2491
+ // NewInput extends {
2492
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2493
+ // ? Augmentation[k]["_input"]
2494
+ // : k extends keyof Input
2495
+ // ? Input[k]
2496
+ // : never;
2497
+ // }
2498
+ // >(
2499
+ // merging: Incoming
2500
+ // ): ZodObject<
2501
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2502
+ // Incoming["_def"]["unknownKeys"],
2503
+ // Incoming["_def"]["catchall"],
2504
+ // NewOutput,
2505
+ // NewInput
2506
+ // > {
2507
+ // const merged: any = new ZodObject({
2508
+ // unknownKeys: merging._def.unknownKeys,
2509
+ // catchall: merging._def.catchall,
2510
+ // shape: () =>
2511
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2512
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2513
+ // }) as any;
2514
+ // return merged;
2515
+ // }
2516
+ setKey(key, schema) {
2517
+ return this.augment({ [key]: schema });
2518
+ }
2519
+ // merge<Incoming extends AnyZodObject>(
2520
+ // merging: Incoming
2521
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2522
+ // ZodObject<
2523
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2524
+ // Incoming["_def"]["unknownKeys"],
2525
+ // Incoming["_def"]["catchall"]
2526
+ // > {
2527
+ // // const mergedShape = objectUtil.mergeShapes(
2528
+ // // this._def.shape(),
2529
+ // // merging._def.shape()
2530
+ // // );
2531
+ // const merged: any = new ZodObject({
2532
+ // unknownKeys: merging._def.unknownKeys,
2533
+ // catchall: merging._def.catchall,
2534
+ // shape: () =>
2535
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2536
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2537
+ // }) as any;
2538
+ // return merged;
2539
+ // }
2540
+ catchall(index) {
2541
+ return new _ZodObject({
2542
+ ...this._def,
2543
+ catchall: index
2544
+ });
2545
+ }
2546
+ pick(mask) {
2547
+ const shape = {};
2548
+ util.objectKeys(mask).forEach((key) => {
2549
+ if (mask[key] && this.shape[key]) {
2550
+ shape[key] = this.shape[key];
2551
+ }
2552
+ });
2553
+ return new _ZodObject({
2554
+ ...this._def,
2555
+ shape: () => shape
2556
+ });
2557
+ }
2558
+ omit(mask) {
2559
+ const shape = {};
2560
+ util.objectKeys(this.shape).forEach((key) => {
2561
+ if (!mask[key]) {
2562
+ shape[key] = this.shape[key];
2563
+ }
2564
+ });
2565
+ return new _ZodObject({
2566
+ ...this._def,
2567
+ shape: () => shape
2568
+ });
2569
+ }
2570
+ /**
2571
+ * @deprecated
2572
+ */
2573
+ deepPartial() {
2574
+ return deepPartialify(this);
2575
+ }
2576
+ partial(mask) {
2577
+ const newShape = {};
2578
+ util.objectKeys(this.shape).forEach((key) => {
2579
+ const fieldSchema = this.shape[key];
2580
+ if (mask && !mask[key]) {
2581
+ newShape[key] = fieldSchema;
2582
+ } else {
2583
+ newShape[key] = fieldSchema.optional();
2584
+ }
2585
+ });
2586
+ return new _ZodObject({
2587
+ ...this._def,
2588
+ shape: () => newShape
2589
+ });
2590
+ }
2591
+ required(mask) {
2592
+ const newShape = {};
2593
+ util.objectKeys(this.shape).forEach((key) => {
2594
+ if (mask && !mask[key]) {
2595
+ newShape[key] = this.shape[key];
2596
+ } else {
2597
+ const fieldSchema = this.shape[key];
2598
+ let newField = fieldSchema;
2599
+ while (newField instanceof ZodOptional) {
2600
+ newField = newField._def.innerType;
2601
+ }
2602
+ newShape[key] = newField;
2603
+ }
2604
+ });
2605
+ return new _ZodObject({
2606
+ ...this._def,
2607
+ shape: () => newShape
2608
+ });
2609
+ }
2610
+ keyof() {
2611
+ return createZodEnum(util.objectKeys(this.shape));
2612
+ }
2613
+ };
2614
+ ZodObject.create = (shape, params) => {
2615
+ return new ZodObject({
2616
+ shape: () => shape,
2617
+ unknownKeys: "strip",
2618
+ catchall: ZodNever.create(),
2619
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2620
+ ...processCreateParams(params)
2621
+ });
2622
+ };
2623
+ ZodObject.strictCreate = (shape, params) => {
2624
+ return new ZodObject({
2625
+ shape: () => shape,
2626
+ unknownKeys: "strict",
2627
+ catchall: ZodNever.create(),
2628
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2629
+ ...processCreateParams(params)
2630
+ });
2631
+ };
2632
+ ZodObject.lazycreate = (shape, params) => {
2633
+ return new ZodObject({
2634
+ shape,
2635
+ unknownKeys: "strip",
2636
+ catchall: ZodNever.create(),
2637
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2638
+ ...processCreateParams(params)
2639
+ });
2640
+ };
2641
+ var ZodUnion = class extends ZodType {
2642
+ _parse(input) {
2643
+ const { ctx } = this._processInputParams(input);
2644
+ const options = this._def.options;
2645
+ function handleResults(results) {
2646
+ for (const result of results) {
2647
+ if (result.result.status === "valid") {
2648
+ return result.result;
2649
+ }
2650
+ }
2651
+ for (const result of results) {
2652
+ if (result.result.status === "dirty") {
2653
+ ctx.common.issues.push(...result.ctx.common.issues);
2654
+ return result.result;
2655
+ }
2656
+ }
2657
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2658
+ addIssueToContext(ctx, {
2659
+ code: ZodIssueCode.invalid_union,
2660
+ unionErrors
2661
+ });
2662
+ return INVALID;
2663
+ }
2664
+ if (ctx.common.async) {
2665
+ return Promise.all(options.map(async (option) => {
2666
+ const childCtx = {
2667
+ ...ctx,
2668
+ common: {
2669
+ ...ctx.common,
2670
+ issues: []
2671
+ },
2672
+ parent: null
2673
+ };
2674
+ return {
2675
+ result: await option._parseAsync({
2676
+ data: ctx.data,
2677
+ path: ctx.path,
2678
+ parent: childCtx
2679
+ }),
2680
+ ctx: childCtx
2681
+ };
2682
+ })).then(handleResults);
2683
+ } else {
2684
+ let dirty = void 0;
2685
+ const issues = [];
2686
+ for (const option of options) {
2687
+ const childCtx = {
2688
+ ...ctx,
2689
+ common: {
2690
+ ...ctx.common,
2691
+ issues: []
2692
+ },
2693
+ parent: null
2694
+ };
2695
+ const result = option._parseSync({
2696
+ data: ctx.data,
2697
+ path: ctx.path,
2698
+ parent: childCtx
2699
+ });
2700
+ if (result.status === "valid") {
2701
+ return result;
2702
+ } else if (result.status === "dirty" && !dirty) {
2703
+ dirty = { result, ctx: childCtx };
2704
+ }
2705
+ if (childCtx.common.issues.length) {
2706
+ issues.push(childCtx.common.issues);
2707
+ }
2708
+ }
2709
+ if (dirty) {
2710
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2711
+ return dirty.result;
2712
+ }
2713
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2714
+ addIssueToContext(ctx, {
2715
+ code: ZodIssueCode.invalid_union,
2716
+ unionErrors
2717
+ });
2718
+ return INVALID;
2719
+ }
2720
+ }
2721
+ get options() {
2722
+ return this._def.options;
2723
+ }
2724
+ };
2725
+ ZodUnion.create = (types, params) => {
2726
+ return new ZodUnion({
2727
+ options: types,
2728
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2729
+ ...processCreateParams(params)
2730
+ });
2731
+ };
2732
+ var getDiscriminator = (type) => {
2733
+ if (type instanceof ZodLazy) {
2734
+ return getDiscriminator(type.schema);
2735
+ } else if (type instanceof ZodEffects) {
2736
+ return getDiscriminator(type.innerType());
2737
+ } else if (type instanceof ZodLiteral) {
2738
+ return [type.value];
2739
+ } else if (type instanceof ZodEnum) {
2740
+ return type.options;
2741
+ } else if (type instanceof ZodNativeEnum) {
2742
+ return Object.keys(type.enum);
2743
+ } else if (type instanceof ZodDefault) {
2744
+ return getDiscriminator(type._def.innerType);
2745
+ } else if (type instanceof ZodUndefined) {
2746
+ return [void 0];
2747
+ } else if (type instanceof ZodNull) {
2748
+ return [null];
2749
+ } else {
2750
+ return null;
2751
+ }
2752
+ };
2753
+ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2754
+ _parse(input) {
2755
+ const { ctx } = this._processInputParams(input);
2756
+ if (ctx.parsedType !== ZodParsedType.object) {
2757
+ addIssueToContext(ctx, {
2758
+ code: ZodIssueCode.invalid_type,
2759
+ expected: ZodParsedType.object,
2760
+ received: ctx.parsedType
2761
+ });
2762
+ return INVALID;
2763
+ }
2764
+ const discriminator = this.discriminator;
2765
+ const discriminatorValue = ctx.data[discriminator];
2766
+ const option = this.optionsMap.get(discriminatorValue);
2767
+ if (!option) {
2768
+ addIssueToContext(ctx, {
2769
+ code: ZodIssueCode.invalid_union_discriminator,
2770
+ options: Array.from(this.optionsMap.keys()),
2771
+ path: [discriminator]
2772
+ });
2773
+ return INVALID;
2774
+ }
2775
+ if (ctx.common.async) {
2776
+ return option._parseAsync({
2777
+ data: ctx.data,
2778
+ path: ctx.path,
2779
+ parent: ctx
2780
+ });
2781
+ } else {
2782
+ return option._parseSync({
2783
+ data: ctx.data,
2784
+ path: ctx.path,
2785
+ parent: ctx
2786
+ });
2787
+ }
2788
+ }
2789
+ get discriminator() {
2790
+ return this._def.discriminator;
2791
+ }
2792
+ get options() {
2793
+ return this._def.options;
2794
+ }
2795
+ get optionsMap() {
2796
+ return this._def.optionsMap;
2797
+ }
2798
+ /**
2799
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2800
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2801
+ * have a different value for each object in the union.
2802
+ * @param discriminator the name of the discriminator property
2803
+ * @param types an array of object schemas
2804
+ * @param params
2805
+ */
2806
+ static create(discriminator, options, params) {
2807
+ const optionsMap = /* @__PURE__ */ new Map();
2808
+ for (const type of options) {
2809
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2810
+ if (!discriminatorValues) {
2811
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2812
+ }
2813
+ for (const value of discriminatorValues) {
2814
+ if (optionsMap.has(value)) {
2815
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2816
+ }
2817
+ optionsMap.set(value, type);
2818
+ }
2819
+ }
2820
+ return new _ZodDiscriminatedUnion({
2821
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2822
+ discriminator,
2823
+ options,
2824
+ optionsMap,
2825
+ ...processCreateParams(params)
2826
+ });
2827
+ }
2828
+ };
2829
+ function mergeValues(a, b) {
2830
+ const aType = getParsedType(a);
2831
+ const bType = getParsedType(b);
2832
+ if (a === b) {
2833
+ return { valid: true, data: a };
2834
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2835
+ const bKeys = util.objectKeys(b);
2836
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2837
+ const newObj = { ...a, ...b };
2838
+ for (const key of sharedKeys) {
2839
+ const sharedValue = mergeValues(a[key], b[key]);
2840
+ if (!sharedValue.valid) {
2841
+ return { valid: false };
2842
+ }
2843
+ newObj[key] = sharedValue.data;
2844
+ }
2845
+ return { valid: true, data: newObj };
2846
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2847
+ if (a.length !== b.length) {
2848
+ return { valid: false };
2849
+ }
2850
+ const newArray = [];
2851
+ for (let index = 0; index < a.length; index++) {
2852
+ const itemA = a[index];
2853
+ const itemB = b[index];
2854
+ const sharedValue = mergeValues(itemA, itemB);
2855
+ if (!sharedValue.valid) {
2856
+ return { valid: false };
2857
+ }
2858
+ newArray.push(sharedValue.data);
2859
+ }
2860
+ return { valid: true, data: newArray };
2861
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2862
+ return { valid: true, data: a };
2863
+ } else {
2864
+ return { valid: false };
2865
+ }
2866
+ }
2867
+ var ZodIntersection = class extends ZodType {
2868
+ _parse(input) {
2869
+ const { status, ctx } = this._processInputParams(input);
2870
+ const handleParsed = (parsedLeft, parsedRight) => {
2871
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2872
+ return INVALID;
2873
+ }
2874
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2875
+ if (!merged.valid) {
2876
+ addIssueToContext(ctx, {
2877
+ code: ZodIssueCode.invalid_intersection_types
2878
+ });
2879
+ return INVALID;
2880
+ }
2881
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2882
+ status.dirty();
2883
+ }
2884
+ return { status: status.value, value: merged.data };
2885
+ };
2886
+ if (ctx.common.async) {
2887
+ return Promise.all([
2888
+ this._def.left._parseAsync({
2889
+ data: ctx.data,
2890
+ path: ctx.path,
2891
+ parent: ctx
2892
+ }),
2893
+ this._def.right._parseAsync({
2894
+ data: ctx.data,
2895
+ path: ctx.path,
2896
+ parent: ctx
2897
+ })
2898
+ ]).then(([left, right]) => handleParsed(left, right));
2899
+ } else {
2900
+ return handleParsed(this._def.left._parseSync({
2901
+ data: ctx.data,
2902
+ path: ctx.path,
2903
+ parent: ctx
2904
+ }), this._def.right._parseSync({
2905
+ data: ctx.data,
2906
+ path: ctx.path,
2907
+ parent: ctx
2908
+ }));
2909
+ }
2910
+ }
2911
+ };
2912
+ ZodIntersection.create = (left, right, params) => {
2913
+ return new ZodIntersection({
2914
+ left,
2915
+ right,
2916
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2917
+ ...processCreateParams(params)
2918
+ });
2919
+ };
2920
+ var ZodTuple = class _ZodTuple extends ZodType {
2921
+ _parse(input) {
2922
+ const { status, ctx } = this._processInputParams(input);
2923
+ if (ctx.parsedType !== ZodParsedType.array) {
2924
+ addIssueToContext(ctx, {
2925
+ code: ZodIssueCode.invalid_type,
2926
+ expected: ZodParsedType.array,
2927
+ received: ctx.parsedType
2928
+ });
2929
+ return INVALID;
2930
+ }
2931
+ if (ctx.data.length < this._def.items.length) {
2932
+ addIssueToContext(ctx, {
2933
+ code: ZodIssueCode.too_small,
2934
+ minimum: this._def.items.length,
2935
+ inclusive: true,
2936
+ exact: false,
2937
+ type: "array"
2938
+ });
2939
+ return INVALID;
2940
+ }
2941
+ const rest = this._def.rest;
2942
+ if (!rest && ctx.data.length > this._def.items.length) {
2943
+ addIssueToContext(ctx, {
2944
+ code: ZodIssueCode.too_big,
2945
+ maximum: this._def.items.length,
2946
+ inclusive: true,
2947
+ exact: false,
2948
+ type: "array"
2949
+ });
2950
+ status.dirty();
2951
+ }
2952
+ const items = [...ctx.data].map((item, itemIndex) => {
2953
+ const schema = this._def.items[itemIndex] || this._def.rest;
2954
+ if (!schema)
2955
+ return null;
2956
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2957
+ }).filter((x) => !!x);
2958
+ if (ctx.common.async) {
2959
+ return Promise.all(items).then((results) => {
2960
+ return ParseStatus.mergeArray(status, results);
2961
+ });
2962
+ } else {
2963
+ return ParseStatus.mergeArray(status, items);
2964
+ }
2965
+ }
2966
+ get items() {
2967
+ return this._def.items;
2968
+ }
2969
+ rest(rest) {
2970
+ return new _ZodTuple({
2971
+ ...this._def,
2972
+ rest
2973
+ });
2974
+ }
2975
+ };
2976
+ ZodTuple.create = (schemas, params) => {
2977
+ if (!Array.isArray(schemas)) {
2978
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2979
+ }
2980
+ return new ZodTuple({
2981
+ items: schemas,
2982
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2983
+ rest: null,
2984
+ ...processCreateParams(params)
2985
+ });
2986
+ };
2987
+ var ZodRecord = class _ZodRecord extends ZodType {
2988
+ get keySchema() {
2989
+ return this._def.keyType;
2990
+ }
2991
+ get valueSchema() {
2992
+ return this._def.valueType;
2993
+ }
2994
+ _parse(input) {
2995
+ const { status, ctx } = this._processInputParams(input);
2996
+ if (ctx.parsedType !== ZodParsedType.object) {
2997
+ addIssueToContext(ctx, {
2998
+ code: ZodIssueCode.invalid_type,
2999
+ expected: ZodParsedType.object,
3000
+ received: ctx.parsedType
3001
+ });
3002
+ return INVALID;
3003
+ }
3004
+ const pairs = [];
3005
+ const keyType = this._def.keyType;
3006
+ const valueType = this._def.valueType;
3007
+ for (const key in ctx.data) {
3008
+ pairs.push({
3009
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3010
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
3011
+ });
3012
+ }
3013
+ if (ctx.common.async) {
3014
+ return ParseStatus.mergeObjectAsync(status, pairs);
3015
+ } else {
3016
+ return ParseStatus.mergeObjectSync(status, pairs);
3017
+ }
3018
+ }
3019
+ get element() {
3020
+ return this._def.valueType;
3021
+ }
3022
+ static create(first, second, third) {
3023
+ if (second instanceof ZodType) {
3024
+ return new _ZodRecord({
3025
+ keyType: first,
3026
+ valueType: second,
3027
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3028
+ ...processCreateParams(third)
3029
+ });
3030
+ }
3031
+ return new _ZodRecord({
3032
+ keyType: ZodString.create(),
3033
+ valueType: first,
3034
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3035
+ ...processCreateParams(second)
3036
+ });
3037
+ }
3038
+ };
3039
+ var ZodMap = class extends ZodType {
3040
+ _parse(input) {
3041
+ const { status, ctx } = this._processInputParams(input);
3042
+ if (ctx.parsedType !== ZodParsedType.map) {
3043
+ addIssueToContext(ctx, {
3044
+ code: ZodIssueCode.invalid_type,
3045
+ expected: ZodParsedType.map,
3046
+ received: ctx.parsedType
3047
+ });
3048
+ return INVALID;
3049
+ }
3050
+ const keyType = this._def.keyType;
3051
+ const valueType = this._def.valueType;
3052
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3053
+ return {
3054
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3055
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3056
+ };
3057
+ });
3058
+ if (ctx.common.async) {
3059
+ const finalMap = /* @__PURE__ */ new Map();
3060
+ return Promise.resolve().then(async () => {
3061
+ for (const pair of pairs) {
3062
+ const key = await pair.key;
3063
+ const value = await pair.value;
3064
+ if (key.status === "aborted" || value.status === "aborted") {
3065
+ return INVALID;
3066
+ }
3067
+ if (key.status === "dirty" || value.status === "dirty") {
3068
+ status.dirty();
3069
+ }
3070
+ finalMap.set(key.value, value.value);
3071
+ }
3072
+ return { status: status.value, value: finalMap };
3073
+ });
3074
+ } else {
3075
+ const finalMap = /* @__PURE__ */ new Map();
3076
+ for (const pair of pairs) {
3077
+ const key = pair.key;
3078
+ const value = pair.value;
3079
+ if (key.status === "aborted" || value.status === "aborted") {
3080
+ return INVALID;
3081
+ }
3082
+ if (key.status === "dirty" || value.status === "dirty") {
3083
+ status.dirty();
3084
+ }
3085
+ finalMap.set(key.value, value.value);
3086
+ }
3087
+ return { status: status.value, value: finalMap };
3088
+ }
3089
+ }
3090
+ };
3091
+ ZodMap.create = (keyType, valueType, params) => {
3092
+ return new ZodMap({
3093
+ valueType,
3094
+ keyType,
3095
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3096
+ ...processCreateParams(params)
3097
+ });
3098
+ };
3099
+ var ZodSet = class _ZodSet extends ZodType {
3100
+ _parse(input) {
3101
+ const { status, ctx } = this._processInputParams(input);
3102
+ if (ctx.parsedType !== ZodParsedType.set) {
3103
+ addIssueToContext(ctx, {
3104
+ code: ZodIssueCode.invalid_type,
3105
+ expected: ZodParsedType.set,
3106
+ received: ctx.parsedType
3107
+ });
3108
+ return INVALID;
3109
+ }
3110
+ const def = this._def;
3111
+ if (def.minSize !== null) {
3112
+ if (ctx.data.size < def.minSize.value) {
3113
+ addIssueToContext(ctx, {
3114
+ code: ZodIssueCode.too_small,
3115
+ minimum: def.minSize.value,
3116
+ type: "set",
3117
+ inclusive: true,
3118
+ exact: false,
3119
+ message: def.minSize.message
3120
+ });
3121
+ status.dirty();
3122
+ }
3123
+ }
3124
+ if (def.maxSize !== null) {
3125
+ if (ctx.data.size > def.maxSize.value) {
3126
+ addIssueToContext(ctx, {
3127
+ code: ZodIssueCode.too_big,
3128
+ maximum: def.maxSize.value,
3129
+ type: "set",
3130
+ inclusive: true,
3131
+ exact: false,
3132
+ message: def.maxSize.message
3133
+ });
3134
+ status.dirty();
3135
+ }
3136
+ }
3137
+ const valueType = this._def.valueType;
3138
+ function finalizeSet(elements2) {
3139
+ const parsedSet = /* @__PURE__ */ new Set();
3140
+ for (const element of elements2) {
3141
+ if (element.status === "aborted")
3142
+ return INVALID;
3143
+ if (element.status === "dirty")
3144
+ status.dirty();
3145
+ parsedSet.add(element.value);
3146
+ }
3147
+ return { status: status.value, value: parsedSet };
3148
+ }
3149
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3150
+ if (ctx.common.async) {
3151
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3152
+ } else {
3153
+ return finalizeSet(elements);
3154
+ }
3155
+ }
3156
+ min(minSize, message) {
3157
+ return new _ZodSet({
3158
+ ...this._def,
3159
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3160
+ });
3161
+ }
3162
+ max(maxSize, message) {
3163
+ return new _ZodSet({
3164
+ ...this._def,
3165
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3166
+ });
3167
+ }
3168
+ size(size, message) {
3169
+ return this.min(size, message).max(size, message);
3170
+ }
3171
+ nonempty(message) {
3172
+ return this.min(1, message);
3173
+ }
3174
+ };
3175
+ ZodSet.create = (valueType, params) => {
3176
+ return new ZodSet({
3177
+ valueType,
3178
+ minSize: null,
3179
+ maxSize: null,
3180
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3181
+ ...processCreateParams(params)
3182
+ });
3183
+ };
3184
+ var ZodFunction = class _ZodFunction extends ZodType {
3185
+ constructor() {
3186
+ super(...arguments);
3187
+ this.validate = this.implement;
3188
+ }
3189
+ _parse(input) {
3190
+ const { ctx } = this._processInputParams(input);
3191
+ if (ctx.parsedType !== ZodParsedType.function) {
3192
+ addIssueToContext(ctx, {
3193
+ code: ZodIssueCode.invalid_type,
3194
+ expected: ZodParsedType.function,
3195
+ received: ctx.parsedType
3196
+ });
3197
+ return INVALID;
3198
+ }
3199
+ function makeArgsIssue(args, error) {
3200
+ return makeIssue({
3201
+ data: args,
3202
+ path: ctx.path,
3203
+ errorMaps: [
3204
+ ctx.common.contextualErrorMap,
3205
+ ctx.schemaErrorMap,
3206
+ getErrorMap(),
3207
+ errorMap
3208
+ ].filter((x) => !!x),
3209
+ issueData: {
3210
+ code: ZodIssueCode.invalid_arguments,
3211
+ argumentsError: error
3212
+ }
3213
+ });
3214
+ }
3215
+ function makeReturnsIssue(returns, error) {
3216
+ return makeIssue({
3217
+ data: returns,
3218
+ path: ctx.path,
3219
+ errorMaps: [
3220
+ ctx.common.contextualErrorMap,
3221
+ ctx.schemaErrorMap,
3222
+ getErrorMap(),
3223
+ errorMap
3224
+ ].filter((x) => !!x),
3225
+ issueData: {
3226
+ code: ZodIssueCode.invalid_return_type,
3227
+ returnTypeError: error
3228
+ }
3229
+ });
3230
+ }
3231
+ const params = { errorMap: ctx.common.contextualErrorMap };
3232
+ const fn = ctx.data;
3233
+ if (this._def.returns instanceof ZodPromise) {
3234
+ return OK(async (...args) => {
3235
+ const error = new ZodError([]);
3236
+ const parsedArgs = await this._def.args.parseAsync(args, params).catch((e) => {
3237
+ error.addIssue(makeArgsIssue(args, e));
3238
+ throw error;
3239
+ });
3240
+ const result = await fn(...parsedArgs);
3241
+ const parsedReturns = await this._def.returns._def.type.parseAsync(result, params).catch((e) => {
3242
+ error.addIssue(makeReturnsIssue(result, e));
3243
+ throw error;
3244
+ });
3245
+ return parsedReturns;
3246
+ });
3247
+ } else {
3248
+ return OK((...args) => {
3249
+ const parsedArgs = this._def.args.safeParse(args, params);
3250
+ if (!parsedArgs.success) {
3251
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3252
+ }
3253
+ const result = fn(...parsedArgs.data);
3254
+ const parsedReturns = this._def.returns.safeParse(result, params);
3255
+ if (!parsedReturns.success) {
3256
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3257
+ }
3258
+ return parsedReturns.data;
3259
+ });
3260
+ }
3261
+ }
3262
+ parameters() {
3263
+ return this._def.args;
3264
+ }
3265
+ returnType() {
3266
+ return this._def.returns;
3267
+ }
3268
+ args(...items) {
3269
+ return new _ZodFunction({
3270
+ ...this._def,
3271
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3272
+ });
3273
+ }
3274
+ returns(returnType) {
3275
+ return new _ZodFunction({
3276
+ ...this._def,
3277
+ returns: returnType
3278
+ });
3279
+ }
3280
+ implement(func) {
3281
+ const validatedFunc = this.parse(func);
3282
+ return validatedFunc;
3283
+ }
3284
+ strictImplement(func) {
3285
+ const validatedFunc = this.parse(func);
3286
+ return validatedFunc;
3287
+ }
3288
+ static create(args, returns, params) {
3289
+ return new _ZodFunction({
3290
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3291
+ returns: returns || ZodUnknown.create(),
3292
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3293
+ ...processCreateParams(params)
3294
+ });
3295
+ }
3296
+ };
3297
+ var ZodLazy = class extends ZodType {
3298
+ get schema() {
3299
+ return this._def.getter();
3300
+ }
3301
+ _parse(input) {
3302
+ const { ctx } = this._processInputParams(input);
3303
+ const lazySchema = this._def.getter();
3304
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3305
+ }
3306
+ };
3307
+ ZodLazy.create = (getter, params) => {
3308
+ return new ZodLazy({
3309
+ getter,
3310
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3311
+ ...processCreateParams(params)
3312
+ });
3313
+ };
3314
+ var ZodLiteral = class extends ZodType {
3315
+ _parse(input) {
3316
+ if (input.data !== this._def.value) {
3317
+ const ctx = this._getOrReturnCtx(input);
3318
+ addIssueToContext(ctx, {
3319
+ received: ctx.data,
3320
+ code: ZodIssueCode.invalid_literal,
3321
+ expected: this._def.value
3322
+ });
3323
+ return INVALID;
3324
+ }
3325
+ return { status: "valid", value: input.data };
3326
+ }
3327
+ get value() {
3328
+ return this._def.value;
3329
+ }
3330
+ };
3331
+ ZodLiteral.create = (value, params) => {
3332
+ return new ZodLiteral({
3333
+ value,
3334
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3335
+ ...processCreateParams(params)
3336
+ });
3337
+ };
3338
+ function createZodEnum(values, params) {
3339
+ return new ZodEnum({
3340
+ values,
3341
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3342
+ ...processCreateParams(params)
3343
+ });
3344
+ }
3345
+ var ZodEnum = class _ZodEnum extends ZodType {
3346
+ _parse(input) {
3347
+ if (typeof input.data !== "string") {
3348
+ const ctx = this._getOrReturnCtx(input);
3349
+ const expectedValues = this._def.values;
3350
+ addIssueToContext(ctx, {
3351
+ expected: util.joinValues(expectedValues),
3352
+ received: ctx.parsedType,
3353
+ code: ZodIssueCode.invalid_type
3354
+ });
3355
+ return INVALID;
3356
+ }
3357
+ if (this._def.values.indexOf(input.data) === -1) {
3358
+ const ctx = this._getOrReturnCtx(input);
3359
+ const expectedValues = this._def.values;
3360
+ addIssueToContext(ctx, {
3361
+ received: ctx.data,
3362
+ code: ZodIssueCode.invalid_enum_value,
3363
+ options: expectedValues
3364
+ });
3365
+ return INVALID;
3366
+ }
3367
+ return OK(input.data);
3368
+ }
3369
+ get options() {
3370
+ return this._def.values;
3371
+ }
3372
+ get enum() {
3373
+ const enumValues = {};
3374
+ for (const val of this._def.values) {
3375
+ enumValues[val] = val;
3376
+ }
3377
+ return enumValues;
3378
+ }
3379
+ get Values() {
3380
+ const enumValues = {};
3381
+ for (const val of this._def.values) {
3382
+ enumValues[val] = val;
3383
+ }
3384
+ return enumValues;
3385
+ }
3386
+ get Enum() {
3387
+ const enumValues = {};
3388
+ for (const val of this._def.values) {
3389
+ enumValues[val] = val;
3390
+ }
3391
+ return enumValues;
3392
+ }
3393
+ extract(values) {
3394
+ return _ZodEnum.create(values);
3395
+ }
3396
+ exclude(values) {
3397
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
3398
+ }
3399
+ };
3400
+ ZodEnum.create = createZodEnum;
3401
+ var ZodNativeEnum = class extends ZodType {
3402
+ _parse(input) {
3403
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3404
+ const ctx = this._getOrReturnCtx(input);
3405
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3406
+ const expectedValues = util.objectValues(nativeEnumValues);
3407
+ addIssueToContext(ctx, {
3408
+ expected: util.joinValues(expectedValues),
3409
+ received: ctx.parsedType,
3410
+ code: ZodIssueCode.invalid_type
3411
+ });
3412
+ return INVALID;
3413
+ }
3414
+ if (nativeEnumValues.indexOf(input.data) === -1) {
3415
+ const expectedValues = util.objectValues(nativeEnumValues);
3416
+ addIssueToContext(ctx, {
3417
+ received: ctx.data,
3418
+ code: ZodIssueCode.invalid_enum_value,
3419
+ options: expectedValues
3420
+ });
3421
+ return INVALID;
3422
+ }
3423
+ return OK(input.data);
3424
+ }
3425
+ get enum() {
3426
+ return this._def.values;
3427
+ }
3428
+ };
3429
+ ZodNativeEnum.create = (values, params) => {
3430
+ return new ZodNativeEnum({
3431
+ values,
3432
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3433
+ ...processCreateParams(params)
3434
+ });
3435
+ };
3436
+ var ZodPromise = class extends ZodType {
3437
+ unwrap() {
3438
+ return this._def.type;
3439
+ }
3440
+ _parse(input) {
3441
+ const { ctx } = this._processInputParams(input);
3442
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3443
+ addIssueToContext(ctx, {
3444
+ code: ZodIssueCode.invalid_type,
3445
+ expected: ZodParsedType.promise,
3446
+ received: ctx.parsedType
3447
+ });
3448
+ return INVALID;
3449
+ }
3450
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3451
+ return OK(promisified.then((data) => {
3452
+ return this._def.type.parseAsync(data, {
3453
+ path: ctx.path,
3454
+ errorMap: ctx.common.contextualErrorMap
3455
+ });
3456
+ }));
3457
+ }
3458
+ };
3459
+ ZodPromise.create = (schema, params) => {
3460
+ return new ZodPromise({
3461
+ type: schema,
3462
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3463
+ ...processCreateParams(params)
3464
+ });
3465
+ };
3466
+ var ZodEffects = class extends ZodType {
3467
+ innerType() {
3468
+ return this._def.schema;
3469
+ }
3470
+ sourceType() {
3471
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3472
+ }
3473
+ _parse(input) {
3474
+ const { status, ctx } = this._processInputParams(input);
3475
+ const effect = this._def.effect || null;
3476
+ if (effect.type === "preprocess") {
3477
+ const processed = effect.transform(ctx.data);
3478
+ if (ctx.common.async) {
3479
+ return Promise.resolve(processed).then((processed2) => {
3480
+ return this._def.schema._parseAsync({
3481
+ data: processed2,
3482
+ path: ctx.path,
3483
+ parent: ctx
3484
+ });
3485
+ });
3486
+ } else {
3487
+ return this._def.schema._parseSync({
3488
+ data: processed,
3489
+ path: ctx.path,
3490
+ parent: ctx
3491
+ });
3492
+ }
3493
+ }
3494
+ const checkCtx = {
3495
+ addIssue: (arg) => {
3496
+ addIssueToContext(ctx, arg);
3497
+ if (arg.fatal) {
3498
+ status.abort();
3499
+ } else {
3500
+ status.dirty();
3501
+ }
3502
+ },
3503
+ get path() {
3504
+ return ctx.path;
3505
+ }
3506
+ };
3507
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3508
+ if (effect.type === "refinement") {
3509
+ const executeRefinement = (acc) => {
3510
+ const result = effect.refinement(acc, checkCtx);
3511
+ if (ctx.common.async) {
3512
+ return Promise.resolve(result);
3513
+ }
3514
+ if (result instanceof Promise) {
3515
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3516
+ }
3517
+ return acc;
3518
+ };
3519
+ if (ctx.common.async === false) {
3520
+ const inner = this._def.schema._parseSync({
3521
+ data: ctx.data,
3522
+ path: ctx.path,
3523
+ parent: ctx
3524
+ });
3525
+ if (inner.status === "aborted")
3526
+ return INVALID;
3527
+ if (inner.status === "dirty")
3528
+ status.dirty();
3529
+ executeRefinement(inner.value);
3530
+ return { status: status.value, value: inner.value };
3531
+ } else {
3532
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3533
+ if (inner.status === "aborted")
3534
+ return INVALID;
3535
+ if (inner.status === "dirty")
3536
+ status.dirty();
3537
+ return executeRefinement(inner.value).then(() => {
3538
+ return { status: status.value, value: inner.value };
3539
+ });
3540
+ });
3541
+ }
3542
+ }
3543
+ if (effect.type === "transform") {
3544
+ if (ctx.common.async === false) {
3545
+ const base = this._def.schema._parseSync({
3546
+ data: ctx.data,
3547
+ path: ctx.path,
3548
+ parent: ctx
3549
+ });
3550
+ if (!isValid(base))
3551
+ return base;
3552
+ const result = effect.transform(base.value, checkCtx);
3553
+ if (result instanceof Promise) {
3554
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3555
+ }
3556
+ return { status: status.value, value: result };
3557
+ } else {
3558
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3559
+ if (!isValid(base))
3560
+ return base;
3561
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
3562
+ });
3563
+ }
3564
+ }
3565
+ util.assertNever(effect);
3566
+ }
3567
+ };
3568
+ ZodEffects.create = (schema, effect, params) => {
3569
+ return new ZodEffects({
3570
+ schema,
3571
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3572
+ effect,
3573
+ ...processCreateParams(params)
3574
+ });
3575
+ };
3576
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3577
+ return new ZodEffects({
3578
+ schema,
3579
+ effect: { type: "preprocess", transform: preprocess },
3580
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3581
+ ...processCreateParams(params)
3582
+ });
3583
+ };
3584
+ var ZodOptional = class extends ZodType {
3585
+ _parse(input) {
3586
+ const parsedType = this._getType(input);
3587
+ if (parsedType === ZodParsedType.undefined) {
3588
+ return OK(void 0);
3589
+ }
3590
+ return this._def.innerType._parse(input);
3591
+ }
3592
+ unwrap() {
3593
+ return this._def.innerType;
3594
+ }
3595
+ };
3596
+ ZodOptional.create = (type, params) => {
3597
+ return new ZodOptional({
3598
+ innerType: type,
3599
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3600
+ ...processCreateParams(params)
3601
+ });
3602
+ };
3603
+ var ZodNullable = class extends ZodType {
3604
+ _parse(input) {
3605
+ const parsedType = this._getType(input);
3606
+ if (parsedType === ZodParsedType.null) {
3607
+ return OK(null);
3608
+ }
3609
+ return this._def.innerType._parse(input);
3610
+ }
3611
+ unwrap() {
3612
+ return this._def.innerType;
3613
+ }
3614
+ };
3615
+ ZodNullable.create = (type, params) => {
3616
+ return new ZodNullable({
3617
+ innerType: type,
3618
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3619
+ ...processCreateParams(params)
3620
+ });
3621
+ };
3622
+ var ZodDefault = class extends ZodType {
3623
+ _parse(input) {
3624
+ const { ctx } = this._processInputParams(input);
3625
+ let data = ctx.data;
3626
+ if (ctx.parsedType === ZodParsedType.undefined) {
3627
+ data = this._def.defaultValue();
3628
+ }
3629
+ return this._def.innerType._parse({
3630
+ data,
3631
+ path: ctx.path,
3632
+ parent: ctx
3633
+ });
3634
+ }
3635
+ removeDefault() {
3636
+ return this._def.innerType;
3637
+ }
3638
+ };
3639
+ ZodDefault.create = (type, params) => {
3640
+ return new ZodDefault({
3641
+ innerType: type,
3642
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3643
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3644
+ ...processCreateParams(params)
3645
+ });
3646
+ };
3647
+ var ZodCatch = class extends ZodType {
3648
+ _parse(input) {
3649
+ const { ctx } = this._processInputParams(input);
3650
+ const newCtx = {
3651
+ ...ctx,
3652
+ common: {
3653
+ ...ctx.common,
3654
+ issues: []
3655
+ }
3656
+ };
3657
+ const result = this._def.innerType._parse({
3658
+ data: newCtx.data,
3659
+ path: newCtx.path,
3660
+ parent: {
3661
+ ...newCtx
3662
+ }
3663
+ });
3664
+ if (isAsync(result)) {
3665
+ return result.then((result2) => {
3666
+ return {
3667
+ status: "valid",
3668
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3669
+ get error() {
3670
+ return new ZodError(newCtx.common.issues);
3671
+ },
3672
+ input: newCtx.data
3673
+ })
3674
+ };
3675
+ });
3676
+ } else {
3677
+ return {
3678
+ status: "valid",
3679
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3680
+ get error() {
3681
+ return new ZodError(newCtx.common.issues);
3682
+ },
3683
+ input: newCtx.data
3684
+ })
3685
+ };
3686
+ }
3687
+ }
3688
+ removeCatch() {
3689
+ return this._def.innerType;
3690
+ }
3691
+ };
3692
+ ZodCatch.create = (type, params) => {
3693
+ return new ZodCatch({
3694
+ innerType: type,
3695
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3696
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3697
+ ...processCreateParams(params)
3698
+ });
3699
+ };
3700
+ var ZodNaN = class extends ZodType {
3701
+ _parse(input) {
3702
+ const parsedType = this._getType(input);
3703
+ if (parsedType !== ZodParsedType.nan) {
3704
+ const ctx = this._getOrReturnCtx(input);
3705
+ addIssueToContext(ctx, {
3706
+ code: ZodIssueCode.invalid_type,
3707
+ expected: ZodParsedType.nan,
3708
+ received: ctx.parsedType
3709
+ });
3710
+ return INVALID;
3711
+ }
3712
+ return { status: "valid", value: input.data };
3713
+ }
3714
+ };
3715
+ ZodNaN.create = (params) => {
3716
+ return new ZodNaN({
3717
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3718
+ ...processCreateParams(params)
3719
+ });
3720
+ };
3721
+ var BRAND = Symbol("zod_brand");
3722
+ var ZodBranded = class extends ZodType {
3723
+ _parse(input) {
3724
+ const { ctx } = this._processInputParams(input);
3725
+ const data = ctx.data;
3726
+ return this._def.type._parse({
3727
+ data,
3728
+ path: ctx.path,
3729
+ parent: ctx
3730
+ });
3731
+ }
3732
+ unwrap() {
3733
+ return this._def.type;
3734
+ }
3735
+ };
3736
+ var ZodPipeline = class _ZodPipeline extends ZodType {
3737
+ _parse(input) {
3738
+ const { status, ctx } = this._processInputParams(input);
3739
+ if (ctx.common.async) {
3740
+ const handleAsync = async () => {
3741
+ const inResult = await this._def.in._parseAsync({
3742
+ data: ctx.data,
3743
+ path: ctx.path,
3744
+ parent: ctx
3745
+ });
3746
+ if (inResult.status === "aborted")
3747
+ return INVALID;
3748
+ if (inResult.status === "dirty") {
3749
+ status.dirty();
3750
+ return DIRTY(inResult.value);
3751
+ } else {
3752
+ return this._def.out._parseAsync({
3753
+ data: inResult.value,
3754
+ path: ctx.path,
3755
+ parent: ctx
3756
+ });
3757
+ }
3758
+ };
3759
+ return handleAsync();
3760
+ } else {
3761
+ const inResult = this._def.in._parseSync({
3762
+ data: ctx.data,
3763
+ path: ctx.path,
3764
+ parent: ctx
3765
+ });
3766
+ if (inResult.status === "aborted")
3767
+ return INVALID;
3768
+ if (inResult.status === "dirty") {
3769
+ status.dirty();
3770
+ return {
3771
+ status: "dirty",
3772
+ value: inResult.value
3773
+ };
3774
+ } else {
3775
+ return this._def.out._parseSync({
3776
+ data: inResult.value,
3777
+ path: ctx.path,
3778
+ parent: ctx
3779
+ });
3780
+ }
3781
+ }
3782
+ }
3783
+ static create(a, b) {
3784
+ return new _ZodPipeline({
3785
+ in: a,
3786
+ out: b,
3787
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3788
+ });
3789
+ }
3790
+ };
3791
+ var custom = (check, params = {}, fatal) => {
3792
+ if (check)
3793
+ return ZodAny.create().superRefine((data, ctx) => {
3794
+ var _a, _b;
3795
+ if (!check(data)) {
3796
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3797
+ const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
3798
+ const p2 = typeof p === "string" ? { message: p } : p;
3799
+ ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
3800
+ }
3801
+ });
3802
+ return ZodAny.create();
3803
+ };
3804
+ var late = {
3805
+ object: ZodObject.lazycreate
3806
+ };
3807
+ var ZodFirstPartyTypeKind;
3808
+ (function(ZodFirstPartyTypeKind2) {
3809
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3810
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3811
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3812
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3813
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3814
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3815
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3816
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3817
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3818
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3819
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3820
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3821
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3822
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3823
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3824
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3825
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3826
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3827
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3828
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3829
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3830
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3831
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3832
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3833
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3834
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3835
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3836
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3837
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3838
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3839
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3840
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3841
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3842
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3843
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3844
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3845
+ var instanceOfType = (cls, params = {
3846
+ message: `Input not instance of ${cls.name}`
3847
+ }) => custom((data) => data instanceof cls, params);
3848
+ var stringType = ZodString.create;
3849
+ var numberType = ZodNumber.create;
3850
+ var nanType = ZodNaN.create;
3851
+ var bigIntType = ZodBigInt.create;
3852
+ var booleanType = ZodBoolean.create;
3853
+ var dateType = ZodDate.create;
3854
+ var symbolType = ZodSymbol.create;
3855
+ var undefinedType = ZodUndefined.create;
3856
+ var nullType = ZodNull.create;
3857
+ var anyType = ZodAny.create;
3858
+ var unknownType = ZodUnknown.create;
3859
+ var neverType = ZodNever.create;
3860
+ var voidType = ZodVoid.create;
3861
+ var arrayType = ZodArray.create;
3862
+ var objectType = ZodObject.create;
3863
+ var strictObjectType = ZodObject.strictCreate;
3864
+ var unionType = ZodUnion.create;
3865
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
3866
+ var intersectionType = ZodIntersection.create;
3867
+ var tupleType = ZodTuple.create;
3868
+ var recordType = ZodRecord.create;
3869
+ var mapType = ZodMap.create;
3870
+ var setType = ZodSet.create;
3871
+ var functionType = ZodFunction.create;
3872
+ var lazyType = ZodLazy.create;
3873
+ var literalType = ZodLiteral.create;
3874
+ var enumType = ZodEnum.create;
3875
+ var nativeEnumType = ZodNativeEnum.create;
3876
+ var promiseType = ZodPromise.create;
3877
+ var effectsType = ZodEffects.create;
3878
+ var optionalType = ZodOptional.create;
3879
+ var nullableType = ZodNullable.create;
3880
+ var preprocessType = ZodEffects.createWithPreprocess;
3881
+ var pipelineType = ZodPipeline.create;
3882
+ var ostring = () => stringType().optional();
3883
+ var onumber = () => numberType().optional();
3884
+ var oboolean = () => booleanType().optional();
3885
+ var coerce = {
3886
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
3887
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
3888
+ boolean: (arg) => ZodBoolean.create({
3889
+ ...arg,
3890
+ coerce: true
3891
+ }),
3892
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
3893
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
3894
+ };
3895
+ var NEVER = INVALID;
3896
+ var z = /* @__PURE__ */ Object.freeze({
3897
+ __proto__: null,
3898
+ defaultErrorMap: errorMap,
3899
+ setErrorMap,
3900
+ getErrorMap,
3901
+ makeIssue,
3902
+ EMPTY_PATH,
3903
+ addIssueToContext,
3904
+ ParseStatus,
3905
+ INVALID,
3906
+ DIRTY,
3907
+ OK,
3908
+ isAborted,
3909
+ isDirty,
3910
+ isValid,
3911
+ isAsync,
3912
+ get util() {
3913
+ return util;
3914
+ },
3915
+ get objectUtil() {
3916
+ return objectUtil;
3917
+ },
3918
+ ZodParsedType,
3919
+ getParsedType,
3920
+ ZodType,
3921
+ ZodString,
3922
+ ZodNumber,
3923
+ ZodBigInt,
3924
+ ZodBoolean,
3925
+ ZodDate,
3926
+ ZodSymbol,
3927
+ ZodUndefined,
3928
+ ZodNull,
3929
+ ZodAny,
3930
+ ZodUnknown,
3931
+ ZodNever,
3932
+ ZodVoid,
3933
+ ZodArray,
3934
+ ZodObject,
3935
+ ZodUnion,
3936
+ ZodDiscriminatedUnion,
3937
+ ZodIntersection,
3938
+ ZodTuple,
3939
+ ZodRecord,
3940
+ ZodMap,
3941
+ ZodSet,
3942
+ ZodFunction,
3943
+ ZodLazy,
3944
+ ZodLiteral,
3945
+ ZodEnum,
3946
+ ZodNativeEnum,
3947
+ ZodPromise,
3948
+ ZodEffects,
3949
+ ZodTransformer: ZodEffects,
3950
+ ZodOptional,
3951
+ ZodNullable,
3952
+ ZodDefault,
3953
+ ZodCatch,
3954
+ ZodNaN,
3955
+ BRAND,
3956
+ ZodBranded,
3957
+ ZodPipeline,
3958
+ custom,
3959
+ Schema: ZodType,
3960
+ ZodSchema: ZodType,
3961
+ late,
3962
+ get ZodFirstPartyTypeKind() {
3963
+ return ZodFirstPartyTypeKind;
3964
+ },
3965
+ coerce,
3966
+ any: anyType,
3967
+ array: arrayType,
3968
+ bigint: bigIntType,
3969
+ boolean: booleanType,
3970
+ date: dateType,
3971
+ discriminatedUnion: discriminatedUnionType,
3972
+ effect: effectsType,
3973
+ "enum": enumType,
3974
+ "function": functionType,
3975
+ "instanceof": instanceOfType,
3976
+ intersection: intersectionType,
3977
+ lazy: lazyType,
3978
+ literal: literalType,
3979
+ map: mapType,
3980
+ nan: nanType,
3981
+ nativeEnum: nativeEnumType,
3982
+ never: neverType,
3983
+ "null": nullType,
3984
+ nullable: nullableType,
3985
+ number: numberType,
3986
+ object: objectType,
3987
+ oboolean,
3988
+ onumber,
3989
+ optional: optionalType,
3990
+ ostring,
3991
+ pipeline: pipelineType,
3992
+ preprocess: preprocessType,
3993
+ promise: promiseType,
3994
+ record: recordType,
3995
+ set: setType,
3996
+ strictObject: strictObjectType,
3997
+ string: stringType,
3998
+ symbol: symbolType,
3999
+ transformer: effectsType,
4000
+ tuple: tupleType,
4001
+ "undefined": undefinedType,
4002
+ union: unionType,
4003
+ unknown: unknownType,
4004
+ "void": voidType,
4005
+ NEVER,
4006
+ ZodIssueCode,
4007
+ quotelessJson,
4008
+ ZodError
4009
+ });
4010
+
4011
+ // ../../core/models/book.ts
4012
+ var BookDesignRequest = class {
4013
+ occasion;
4014
+ style;
4015
+ book_size;
4016
+ cover_type;
4017
+ page_type;
4018
+ image_density;
4019
+ image_filtering_level;
4020
+ embellishment_level;
4021
+ text_sticker_level;
4022
+ constructor(props) {
4023
+ this.occasion = props.occasion;
4024
+ this.style = props.style;
4025
+ this.book_size = props.book_size;
4026
+ this.cover_type = props.cover_type;
4027
+ this.page_type = props.page_type;
4028
+ this.image_density = props.image_density;
4029
+ this.image_filtering_level = props.image_filtering_level;
4030
+ this.embellishment_level = props.embellishment_level;
4031
+ this.text_sticker_level = props.text_sticker_level;
4032
+ }
4033
+ };
4034
+ var bookDesignRequestSchema = z.object({
4035
+ occasion: z.enum(occasions),
4036
+ style: z.string(),
4037
+ book_size: z.enum(bookSizes),
4038
+ cover_type: z.enum(coverTypes),
4039
+ page_type: z.enum(pageTypes),
4040
+ image_density: z.enum(imageDensities),
4041
+ image_filtering_level: z.enum(imageFilteringLevels),
4042
+ embellishment_level: z.enum(embellishmentLevels),
4043
+ text_sticker_level: z.enum(textStickerLevels)
4044
+ });
4045
+ var BookPropsSchema = z.object({
4046
+ id: z.string().optional(),
4047
+ title: z.string(),
4048
+ design_request: bookDesignRequestSchema,
4049
+ state: z.enum(states).optional(),
4050
+ guid: z.string().optional(),
4051
+ cancelled_at: z.string().optional()
4052
+ });
4053
+ var Book = class {
4054
+ id;
4055
+ title;
4056
+ design_request;
4057
+ state;
4058
+ guid;
4059
+ cancelled_at;
4060
+ constructor(props) {
4061
+ this.id = props.id || "";
4062
+ this.title = props.title;
4063
+ this.design_request = new BookDesignRequest(props.design_request);
4064
+ this.state = props.state;
4065
+ this.guid = props.guid;
4066
+ this.cancelled_at = props.cancelled_at;
4067
+ }
4068
+ toDesignRequestProps() {
4069
+ const props = { ...this, ...this.design_request };
4070
+ props.style = getStyleIdBySlug(props.style);
4071
+ delete props.design_request;
4072
+ return snakeCaseObjectKeysToCamelCase(props);
4073
+ }
4074
+ };
4075
+
4076
+ // ../../core/models/design-request/image.ts
4077
+ var Images = class {
4078
+ // eslint-disable-next-line no-unused-vars
4079
+ constructor(client, parentId) {
4080
+ this.client = client;
4081
+ this.parentId = parentId;
4082
+ this.images = [];
4083
+ this.length = this.images.length;
4084
+ }
4085
+ parentId;
4086
+ images;
4087
+ length;
4088
+ async add(image) {
4089
+ this.images.push(image);
4090
+ this.length = this.images.length;
4091
+ await this.client.engineAPI.images.addToBook(this.parentId, new ImageServer(image));
4092
+ return new Promise((resolve) => {
4093
+ resolve(this.length);
4094
+ });
4095
+ }
4096
+ };
4097
+ var imageServerSchema = z.object({
4098
+ id: z.string().optional(),
4099
+ handle: z.string(),
4100
+ url: z.string(),
4101
+ width: z.number(),
4102
+ height: z.number(),
4103
+ orientation: z.number(),
4104
+ taken_at: z.string(),
4105
+ camera_make: z.string().optional(),
4106
+ camera: z.string().optional(),
4107
+ filename: z.string()
4108
+ });
4109
+ var ImageServer = class {
4110
+ handle;
4111
+ url;
4112
+ width;
4113
+ height;
4114
+ orientation;
4115
+ taken_at;
4116
+ camera_make;
4117
+ camera;
4118
+ filename;
4119
+ constructor(image) {
4120
+ this.handle = image.handle;
4121
+ this.url = image.url;
4122
+ this.width = image.width;
4123
+ this.height = image.height;
4124
+ this.orientation = image.rotation;
4125
+ this.taken_at = image.captureTime;
4126
+ this.camera_make = image.cameraMake;
4127
+ this.camera = image.cameraModel;
4128
+ this.filename = image.filename;
4129
+ }
4130
+ };
4131
+
4132
+ // ../../core/models/design-request/design-options.ts
4133
+ var imageDensityOptionSchema = z.object({
4134
+ maxPageCount: z.number(),
4135
+ minPageCount: z.number(),
4136
+ maxImageCount: z.number(),
4137
+ avgImageCount: z.number(),
4138
+ minImageCount: z.number()
4139
+ });
4140
+ var imageDensityOptionsSchema = z.object({
4141
+ high: imageDensityOptionSchema,
4142
+ medium: imageDensityOptionSchema,
4143
+ low: imageDensityOptionSchema
4144
+ });
4145
+ var designOptionsSchema = z.object({
4146
+ densities: imageDensityOptionsSchema
4147
+ });
4148
+ var imageDensityOptionServerSchema = z.object({
4149
+ max_page_count: z.number(),
4150
+ min_page_count: z.number(),
4151
+ max_image_count: z.number(),
4152
+ avg_image_count: z.number(),
4153
+ min_image_count: z.number()
4154
+ });
4155
+ var imageDensityOptionsServerSchema = z.object({
4156
+ high: imageDensityOptionServerSchema,
4157
+ medium: imageDensityOptionServerSchema,
4158
+ low: imageDensityOptionServerSchema
4159
+ });
4160
+ var designOptionsServerSchema = z.object({
4161
+ densities: imageDensityOptionsServerSchema
4162
+ });
4163
+
4164
+ // ../../core/config.ts
4165
+ var defaultApiHost = "https://api.dev-sls.magicbook.io";
4166
+ var defaultWebSocketHost = "wss://socket.dev-sls.magicbook.io";
4167
+ var designRequestTimeout = parseInt("30000"?.toString() || "3000");
4168
+
4169
+ // ../../core/models/design-request/index.ts
4170
+ var DesignRequestOptions = {
4171
+ occasion: occasions,
4172
+ style: Object.keys(styles).map((key) => parseInt(key)),
4173
+ bookSize: bookSizes,
4174
+ coverType: coverTypes,
4175
+ pageType: pageTypes,
4176
+ imageDensity: imageDensities,
4177
+ imageFilteringLevel: imageFilteringLevels,
4178
+ embellishmentLevel: embellishmentLevels,
4179
+ textStickerLevel: textStickerLevels
4180
+ };
4181
+ var DesignRequest = class {
4182
+ // eslint-disable-next-line no-unused-vars
4183
+ constructor(parentId, client, designRequestProps) {
4184
+ this.client = client;
4185
+ this.parentId = parentId;
4186
+ this.webSocket = new WebSocket(`${this.client.webSocketHost}/?book_id=${this.parentId}`);
4187
+ this.state = designRequestProps?.state || states[0];
4188
+ this.title = designRequestProps?.title || "";
4189
+ this.occasion = designRequestProps?.occasion || occasions[0];
4190
+ this.style = designRequestProps?.style || parseInt(Object.keys(styles)[0]);
4191
+ this.bookSize = designRequestProps?.bookSize || bookSizes[0];
4192
+ this.coverType = designRequestProps?.coverType || coverTypes[0];
4193
+ this.pageType = designRequestProps?.pageType || pageTypes[0];
4194
+ this.imageDensity = designRequestProps?.imageDensity || imageDensities[0];
4195
+ this.imageFilteringLevel = designRequestProps?.imageFilteringLevel || imageFilteringLevels[0];
4196
+ this.embellishmentLevel = designRequestProps?.embellishmentLevel || embellishmentLevels[0];
4197
+ this.textStickerLevel = designRequestProps?.textStickerLevel || textStickerLevels[0];
4198
+ this.images = new Images(this.client, this.parentId);
4199
+ }
4200
+ webSocket;
4201
+ // private events: DesignRequestEvent[]
4202
+ state;
4203
+ parentId;
4204
+ title;
4205
+ occasion;
4206
+ style;
4207
+ bookSize;
4208
+ coverType;
4209
+ pageType;
4210
+ imageDensity;
4211
+ imageFilteringLevel;
4212
+ embellishmentLevel;
4213
+ textStickerLevel;
4214
+ images;
4215
+ guid;
4216
+ updateDesignRequest(designRequestProps) {
4217
+ Object.assign(this, designRequestProps);
4218
+ }
4219
+ async getOptions(imageCount) {
4220
+ const options = designOptionsSchema.parse(snakeCaseObjectKeysToCamelCase(
4221
+ await this.client.engineAPI.designOptions.retrieve(
4222
+ this.bookSize,
4223
+ imageCount || this.images.length,
4224
+ this.imageFilteringLevel
4225
+ )
4226
+ ));
4227
+ return options;
4228
+ }
4229
+ async submit(submitDesignRequestProps) {
4230
+ if (isDesignRequestSubmitted(this.state)) {
4231
+ throw new Error("Design request already submitted");
4232
+ } else {
4233
+ submitDesignRequestProps && Object.assign(this, submitDesignRequestProps);
4234
+ this.getProgress();
4235
+ this.updateDesignRequest(
4236
+ (await this.client.engineAPI.books.update(this.parentId, this.toBook())).toDesignRequestProps()
4237
+ );
4238
+ this.state = states[1];
4239
+ return this;
4240
+ }
4241
+ }
4242
+ async setGuid(guid) {
4243
+ this.guid = guid;
4244
+ if (isDesignRequestSubmitted(this.state)) {
4245
+ this.updateDesignRequest(
4246
+ (await this.client.engineAPI.books.update(this.parentId, this.toBook())).toDesignRequestProps()
4247
+ );
4248
+ }
4249
+ return this.guid;
4250
+ }
4251
+ async cancel() {
4252
+ if (this.state === "cancelled") {
4253
+ throw new Error("Design request already cancelled");
4254
+ } else if (this.state === "ready") {
4255
+ throw new Error("Design request already finished");
4256
+ } else if (!isDesignRequestSubmitted(this.state)) {
4257
+ throw new Error("Design request not submitted");
4258
+ } else {
4259
+ this.updateDesignRequest(
4260
+ (await this.client.engineAPI.books.cancel(this.parentId)).toDesignRequestProps()
4261
+ );
4262
+ this.state = "cancelled";
4263
+ await this.eventHandler(cancelledMessage);
4264
+ return this;
4265
+ }
4266
+ }
4267
+ async getJSON() {
4268
+ if (this.state === "ready") {
4269
+ return await this.client.engineAPI.books.retrieveGalleon(this.parentId);
4270
+ } else {
4271
+ throw new Error("Design request not ready");
4272
+ }
4273
+ }
4274
+ async eventHandler(detail, type = "MagicBook.designRequestUpdated") {
4275
+ const customEvent = new CustomEvent(type, { detail });
4276
+ window.dispatchEvent(customEvent);
4277
+ if (statesToCloseWS.includes(detail.slug)) {
4278
+ this.webSocket.close();
4279
+ if (statesToReport.includes(detail.slug)) {
4280
+ await this.client.engineAPI.books.report(this.parentId, {
4281
+ error: detail.slug === "error" ? "design" : "timeout",
4282
+ step: this.state
4283
+ });
4284
+ }
4285
+ }
4286
+ this.state = detail.slug;
4287
+ }
4288
+ timeoutHandler() {
4289
+ return setTimeout(async () => {
4290
+ this.eventHandler(timeoutMessage);
4291
+ }, designRequestTimeout);
4292
+ }
4293
+ async getProgress() {
4294
+ let timeout;
4295
+ this.webSocket.onmessage = (event) => {
4296
+ const detail = JSON.parse(event.data);
4297
+ if (this.state !== detail.slug) {
4298
+ timeout && clearTimeout(timeout);
4299
+ timeout = this.timeoutHandler();
4300
+ this.eventHandler(detail);
4301
+ }
4302
+ };
4303
+ this.webSocket.onclose = () => clearTimeout(timeout);
4304
+ }
4305
+ toBook() {
4306
+ const designRequest = { ...this };
4307
+ delete designRequest["client"];
4308
+ delete designRequest["images"]["client"];
4309
+ delete designRequest["webSocket"];
4310
+ const styleSlug = styles[this.style].slug;
4311
+ const bookDesignRequest = camelCaseObjectKeysToSnakeCase(cleanJSON(designRequest));
4312
+ bookDesignRequest.style = styleSlug;
4313
+ return new Book({
4314
+ id: designRequest.parentId,
4315
+ guid: designRequest.guid,
4316
+ title: designRequest.title,
4317
+ design_request: bookDesignRequest,
4318
+ state: designRequest.state
4319
+ });
4320
+ }
4321
+ };
4322
+
4323
+ // ../../core/models/galleon.ts
4324
+ var imageAssignmentSchema = z.object({
4325
+ photoRefId: z.string(),
4326
+ finalCrop: z.array(z.number())
4327
+ });
4328
+ var positionSchema = z.object({
4329
+ x: z.number(),
4330
+ y: z.number(),
4331
+ width: z.number().optional(),
4332
+ height: z.number().optional(),
4333
+ rotation: z.number()
4334
+ });
4335
+ var photoMetadataSchema = z.object({
4336
+ id: z.string(),
4337
+ llx: z.number(),
4338
+ lly: z.number(),
4339
+ urx: z.number(),
4340
+ ury: z.number(),
4341
+ data: z.string().nullable(),
4342
+ title: z.string(),
4343
+ width: z.number(),
4344
+ effect: z.string(),
4345
+ height: z.number(),
4346
+ source: z.string(),
4347
+ rotation: z.number(),
4348
+ uploadTime: z.string()
4349
+ });
4350
+ var propertySchema = z.object({
4351
+ key: z.string(),
4352
+ value: z.any()
4353
+ });
4354
+ var assetSchema = z.object({
4355
+ type: z.string(),
4356
+ imageAssignment: imageAssignmentSchema.optional(),
4357
+ position: positionSchema,
4358
+ seqNum: z.number(),
4359
+ z: z.number(),
4360
+ id: z.string().optional(),
4361
+ horizJustification: z.string().optional(),
4362
+ vertJustification: z.string().optional().nullable(),
4363
+ text: z.string().optional(),
4364
+ fontId: z.string().optional(),
4365
+ fontSize: z.number().optional(),
4366
+ fontColor: z.string().optional(),
4367
+ frame: z.string().optional()
4368
+ });
4369
+ var photoStripSchema = z.object({
4370
+ url: z.string(),
4371
+ encryptId: z.string(),
4372
+ photoRefId: z.string(),
4373
+ photoId: z.string(),
4374
+ photoMetadata: photoMetadataSchema
4375
+ });
4376
+ var reportingDataSchema = z.object({
4377
+ properties: z.array(propertySchema)
4378
+ });
4379
+ var canvasSchema = z.object({
4380
+ backgroundId: z.string().nullable(),
4381
+ assets: z.array(assetSchema).optional()
4382
+ });
4383
+ var pageSchema = z.object({
4384
+ pageNum: z.number(),
4385
+ type: z.string(),
4386
+ canvas: canvasSchema
4387
+ });
4388
+ var magicShopBookSchema = z.object({
4389
+ pages: z.array(pageSchema),
4390
+ photoStrip: z.array(photoStripSchema)
4391
+ });
4392
+ var bookCreationRequestSchema = z.object({
4393
+ title: z.string(),
4394
+ binding: z.string(),
4395
+ coverSpecId: z.string(),
4396
+ styleId: z.number(),
4397
+ userId: z.string(),
4398
+ magicShopBook: magicShopBookSchema,
4399
+ reportingData: reportingDataSchema
4400
+ });
4401
+
4402
+ // ../../core/models/engine-api/endpoints/books.ts
4403
+ var BooksEndpoints = class {
4404
+ // eslint-disable-next-line no-unused-vars
4405
+ constructor(engineAPI) {
4406
+ this.engineAPI = engineAPI;
4407
+ bindThisToFunctions(this);
4408
+ }
4409
+ create() {
4410
+ return handleAsyncFunction(async () => {
4411
+ const res = await this.engineAPI.fetcher.call({
4412
+ path: "/v1/books",
4413
+ options: {
4414
+ method: "POST"
4415
+ }
4416
+ });
4417
+ BookPropsSchema.safeParse(res);
4418
+ return new Book(res);
4419
+ });
4420
+ }
4421
+ retrieve(bookId) {
4422
+ return handleAsyncFunction(async () => {
4423
+ const res = await this.engineAPI.fetcher.call({ path: `/v1/books/${bookId}` });
4424
+ BookPropsSchema.safeParse(res);
4425
+ return new Book(res);
4426
+ });
4427
+ }
4428
+ update(bookId, book) {
4429
+ return handleAsyncFunction(async () => {
4430
+ const res = await this.engineAPI.fetcher.call({
4431
+ path: `/v1/books/${bookId}`,
4432
+ options: {
4433
+ method: "PUT",
4434
+ body: cleanJSON(book)
4435
+ }
4436
+ });
4437
+ BookPropsSchema.safeParse(res);
4438
+ return new Book(res);
4439
+ });
4440
+ }
4441
+ cancel(bookId) {
4442
+ return handleAsyncFunction(async () => {
4443
+ const res = await this.engineAPI.fetcher.call({
4444
+ path: `/v1/books/${bookId}/cancel`,
4445
+ options: { method: "POST" }
4446
+ });
4447
+ BookPropsSchema.safeParse(res);
4448
+ return new Book(res);
4449
+ });
4450
+ }
4451
+ report(bookId, report) {
4452
+ return handleAsyncFunction(async () => {
4453
+ await this.engineAPI.fetcher.call({
4454
+ path: `/v1/books/${bookId}/report`,
4455
+ options: {
4456
+ method: "POST",
4457
+ body: cleanJSON(report)
4458
+ }
4459
+ });
4460
+ });
4461
+ }
4462
+ delete(bookId) {
4463
+ return handleAsyncFunction(async () => {
4464
+ await this.engineAPI.fetcher.call({
4465
+ path: `/v1/books/${bookId}`,
4466
+ options: { method: "DELETE" }
4467
+ });
4468
+ });
4469
+ }
4470
+ retrieveGalleon(bookId) {
4471
+ return handleAsyncFunction(async () => {
4472
+ const res = await this.engineAPI.fetcher.call({
4473
+ path: `/v1/books/${bookId}/format/galleon`
4474
+ });
4475
+ return bookCreationRequestSchema.parse(res);
4476
+ });
4477
+ }
4478
+ };
4479
+
4480
+ // ../../core/models/engine-api/endpoints/design-options.ts
4481
+ var DesignOptionsEndpoints = class {
4482
+ // eslint-disable-next-line no-unused-vars
4483
+ constructor(engineAPI) {
4484
+ this.engineAPI = engineAPI;
4485
+ bindThisToFunctions(this);
4486
+ }
4487
+ retrieve(bookSize, imageCount, imageFilteringLevel) {
4488
+ return handleAsyncFunction(async () => {
4489
+ const res = await this.engineAPI.fetcher.call({
4490
+ // eslint-disable-next-line max-len
4491
+ path: `/v1/designoptions/booksize/${bookSize}/imagecount/${imageCount}/imagefilteringlevel/${imageFilteringLevel}`
4492
+ });
4493
+ return designOptionsServerSchema.parse(res);
4494
+ });
4495
+ }
4496
+ };
4497
+
4498
+ // ../../core/models/fetcher.ts
4499
+ var baseOptions = {
4500
+ headers: {
4501
+ "Content-Type": "application/json"
4502
+ },
4503
+ method: "GET"
4504
+ };
4505
+ var Fetcher = class {
4506
+ baseUrl;
4507
+ options;
4508
+ constructor(baseUrl, options) {
4509
+ this.baseUrl = new URL(baseUrl);
4510
+ this.options = mergeNestedObject(baseOptions, options || {});
4511
+ }
4512
+ async call(props) {
4513
+ try {
4514
+ if (props.options?.body && typeof props.options.body !== "string") {
4515
+ props.options.body = JSON.stringify(props.options?.body);
4516
+ }
4517
+ const baseOptions2 = { ...this.options };
4518
+ const options = props.options ? mergeNestedObject(baseOptions2, props.options) : baseOptions2;
4519
+ const res = await fetch(this.cleanUrl(new URL(props.path, this.baseUrl).href), options);
4520
+ if (res.status >= 200 && res.status < 300) {
4521
+ try {
4522
+ return await res.json();
4523
+ } catch (error) {
4524
+ return {};
4525
+ }
4526
+ } else {
4527
+ let detail = res.statusText;
4528
+ try {
4529
+ detail = JSON.stringify((await res.json())?.detail);
4530
+ } catch (error) {
4531
+ }
4532
+ throw Error(`${res.status} ${detail}`);
4533
+ }
4534
+ } catch (error) {
4535
+ return Promise.reject(error);
4536
+ }
4537
+ }
4538
+ cleanUrl(url) {
4539
+ return url.replaceAll(" ", "").trim();
4540
+ }
4541
+ };
4542
+
4543
+ // ../../core/models/engine-api/endpoints/images.ts
4544
+ var ImagesEndpoints = class {
4545
+ // eslint-disable-next-line no-unused-vars
4546
+ constructor(engineAPI) {
4547
+ this.engineAPI = engineAPI;
4548
+ bindThisToFunctions(this);
4549
+ }
4550
+ list(bookId) {
4551
+ return handleAsyncFunction(async () => {
4552
+ const res = await this.engineAPI.fetcher.call({
4553
+ path: `/v1/images/book/${bookId}`
4554
+ });
4555
+ return z.array(imageServerSchema).parse(res);
4556
+ });
4557
+ }
4558
+ retrieve(imageId, bookId) {
4559
+ return handleAsyncFunction(async () => {
4560
+ const res = await this.engineAPI.fetcher.call({
4561
+ path: `/v1/images/${imageId}/book/${bookId}/`
4562
+ });
4563
+ return imageServerSchema.parse(res);
4564
+ });
4565
+ }
4566
+ update(imageId, bookId, image) {
4567
+ return handleAsyncFunction(async () => {
4568
+ const res = await this.engineAPI.fetcher.call({
4569
+ path: `/v1/images/${imageId}/book/${bookId}/`,
4570
+ options: {
4571
+ method: "PUT",
4572
+ body: cleanJSON(image)
4573
+ }
4574
+ });
4575
+ return imageServerSchema.parse(res);
4576
+ });
4577
+ }
4578
+ delete(imageId, bookId) {
4579
+ return handleAsyncFunction(async () => {
4580
+ await this.engineAPI.fetcher.call({
4581
+ path: `/v1/images/${imageId}/book/${bookId}/`,
4582
+ options: {
4583
+ method: "DELETE"
4584
+ }
4585
+ });
4586
+ });
4587
+ }
4588
+ addToBook(bookId, image) {
4589
+ return handleAsyncFunction(async () => {
4590
+ const res = await this.engineAPI.fetcher.call({
4591
+ path: `/v1/images/book/${bookId}`,
4592
+ options: {
4593
+ method: "POST",
4594
+ body: cleanJSON(image)
4595
+ }
4596
+ });
4597
+ return imageServerSchema.parse(res);
4598
+ });
4599
+ }
4600
+ };
4601
+
4602
+ // ../../core/models/spread.ts
4603
+ var spreadServerSchema = z.object({
4604
+ id: z.string().optional(),
4605
+ book_id: z.string(),
4606
+ state: z.string(),
4607
+ spread_type: z.string(),
4608
+ width: z.number().optional(),
4609
+ height: z.number().optional(),
4610
+ sequence: z.number(),
4611
+ wells: z.array(z.unknown()),
4612
+ background: z.unknown(),
4613
+ laid_out_at: z.string().nullable(),
4614
+ embellished_at: z.string().nullable(),
4615
+ polished_at: z.string().nullable(),
4616
+ metadata: z.unknown(),
4617
+ url: z.string().nullable().optional()
4618
+ });
4619
+ var spreadSchema = z.object({
4620
+ id: z.string().optional(),
4621
+ bookId: z.string(),
4622
+ state: z.string(),
4623
+ spreadType: z.string(),
4624
+ width: z.number().optional(),
4625
+ height: z.number().optional(),
4626
+ sequence: z.number(),
4627
+ wells: z.array(z.unknown()),
4628
+ background: z.unknown(),
4629
+ laidOutAt: z.string().nullable(),
4630
+ embellishedAt: z.string().nullable(),
4631
+ polishedAt: z.string().nullable(),
4632
+ metadata: z.unknown(),
4633
+ url: z.string().nullable().optional()
4634
+ });
4635
+
4636
+ // ../../core/models/engine-api/endpoints/spreads.ts
4637
+ var SpreadsEndpoints = class {
4638
+ // eslint-disable-next-line no-unused-vars
4639
+ constructor(engineAPI) {
4640
+ this.engineAPI = engineAPI;
4641
+ bindThisToFunctions(this);
4642
+ }
4643
+ list(bookId) {
4644
+ return handleAsyncFunction(async () => {
4645
+ const res = await this.engineAPI.fetcher.call({
4646
+ path: `/v1/spreads/book/${bookId}`
4647
+ });
4648
+ return z.array(spreadServerSchema).parse(res);
4649
+ });
4650
+ }
4651
+ create(bookId, spread) {
4652
+ return handleAsyncFunction(async () => {
4653
+ const res = await this.engineAPI.fetcher.call({
4654
+ path: `/v1/spreads/book/${bookId}`,
4655
+ options: {
4656
+ method: "POST",
4657
+ body: cleanJSON(spread)
4658
+ }
4659
+ });
4660
+ return spreadServerSchema.parse(res);
4661
+ });
4662
+ }
4663
+ retrieve(spreadId, bookId) {
4664
+ return handleAsyncFunction(async () => {
4665
+ const res = await this.engineAPI.fetcher.call({
4666
+ path: `/v1/spreads/${spreadId}/book/${bookId}`
4667
+ });
4668
+ return spreadServerSchema.parse(res);
4669
+ });
4670
+ }
4671
+ update(spreadId, bookId, spread) {
4672
+ return handleAsyncFunction(async () => {
4673
+ const res = await this.engineAPI.fetcher.call({
4674
+ path: `/v1/spreads/${spreadId}/book/${bookId}`,
4675
+ options: {
4676
+ method: "PUT",
4677
+ body: cleanJSON(spread)
4678
+ }
4679
+ });
4680
+ return spreadServerSchema.parse(res);
4681
+ });
4682
+ }
4683
+ delete(spreadId, bookId) {
4684
+ return handleAsyncFunction(async () => {
4685
+ await this.engineAPI.fetcher.call({
4686
+ path: `/v1/spreads/${spreadId}/book/${bookId}`,
4687
+ options: {
4688
+ method: "DELETE"
4689
+ }
4690
+ });
4691
+ });
4692
+ }
4693
+ };
4694
+
4695
+ // ../../core/models/storyboard-item.ts
4696
+ var StoryboardItemImageFaceServerSchema = z.object({
4697
+ score: z.number(),
4698
+ bounding_box: z.object({
4699
+ x: z.number(),
4700
+ y: z.number(),
4701
+ width: z.number(),
4702
+ height: z.number()
4703
+ }),
4704
+ size: z.number(),
4705
+ eyes_open_score: z.number(),
4706
+ smile_score: z.number(),
4707
+ facing_camera_score: z.number()
4708
+ });
4709
+ var StoryboardItemImageFaceSchema = z.object({
4710
+ score: z.number(),
4711
+ boundingBox: z.object({
4712
+ x: z.number(),
4713
+ y: z.number(),
4714
+ width: z.number(),
4715
+ height: z.number()
4716
+ }),
4717
+ size: z.number(),
4718
+ eyesOpenScore: z.number(),
4719
+ smileScore: z.number(),
4720
+ facingCameraScore: z.number()
4721
+ });
4722
+ var StoryboardItemImageServerSchema = z.object({
4723
+ id: z.string(),
4724
+ url: z.string(),
4725
+ category: z.string(),
4726
+ aesthetic_score: z.number(),
4727
+ faces: z.array(StoryboardItemImageFaceServerSchema),
4728
+ roi: z.object({
4729
+ x: z.number(),
4730
+ y: z.number(),
4731
+ width: z.number(),
4732
+ height: z.number()
4733
+ }),
4734
+ taken_at: z.number(),
4735
+ width: z.number(),
4736
+ height: z.number()
4737
+ });
4738
+ var StoryboardItemImageSchema = z.object({
4739
+ id: z.string(),
4740
+ url: z.string(),
4741
+ category: z.string(),
4742
+ aestheticScore: z.number(),
4743
+ faces: z.array(StoryboardItemImageFaceSchema),
4744
+ roi: z.object({
4745
+ x: z.number(),
4746
+ y: z.number(),
4747
+ width: z.number(),
4748
+ height: z.number()
4749
+ }),
4750
+ takenAt: z.number(),
4751
+ width: z.number(),
4752
+ height: z.number()
4753
+ });
4754
+ var StoryboardItemServerSchema = z.object({
4755
+ id: z.string(),
4756
+ sequence: z.number(),
4757
+ book_id: z.string(),
4758
+ similarity: z.number(),
4759
+ duplicate: z.boolean(),
4760
+ selected: z.boolean(),
4761
+ surface_weight: z.number(),
4762
+ front_cover: z.boolean().optional(),
4763
+ back_cover: z.boolean().optional(),
4764
+ scene: z.number(),
4765
+ subscene: z.number(),
4766
+ spine_break: z.boolean().optional(),
4767
+ image: StoryboardItemImageServerSchema
4768
+ });
4769
+ var StoryboardItemSchema = z.object({
4770
+ id: z.string(),
4771
+ sequence: z.number(),
4772
+ bookId: z.string(),
4773
+ similarity: z.number(),
4774
+ duplicate: z.boolean(),
4775
+ selected: z.boolean(),
4776
+ surfaceWeight: z.number(),
4777
+ frontCover: z.boolean().optional(),
4778
+ backCover: z.boolean().optional(),
4779
+ scene: z.number(),
4780
+ subscene: z.number(),
4781
+ spineBreak: z.boolean().optional(),
4782
+ image: StoryboardItemImageSchema
4783
+ });
4784
+
4785
+ // ../../core/models/engine-api/endpoints/storyboard-items.ts
4786
+ var StoryboardItemsEndpoints = class {
4787
+ // eslint-disable-next-line no-unused-vars
4788
+ constructor(engineAPI) {
4789
+ this.engineAPI = engineAPI;
4790
+ bindThisToFunctions(this);
4791
+ }
4792
+ list(bookId) {
4793
+ return handleAsyncFunction(async () => {
4794
+ const res = await this.engineAPI.fetcher.call({
4795
+ path: `/v1/storyboarditems/book/${bookId}`
4796
+ });
4797
+ return z.array(StoryboardItemServerSchema).parse(res);
4798
+ });
4799
+ }
4800
+ };
4801
+
4802
+ // ../../core/models/engine-api/index.ts
4803
+ var EngineAPI = class {
4804
+ baseUrl;
4805
+ apiKey;
4806
+ fetcher;
4807
+ constructor(baseUrl, apiKey) {
4808
+ this.baseUrl = new URL(baseUrl);
4809
+ this.apiKey = apiKey;
4810
+ const options = {
4811
+ headers: {
4812
+ "Authorization": `API-Key ${this.apiKey}`
4813
+ }
4814
+ };
4815
+ this.fetcher = new Fetcher(baseUrl, options);
4816
+ }
4817
+ books = new BooksEndpoints(this);
4818
+ designOptions = new DesignOptionsEndpoints(this);
4819
+ storyboardItems = new StoryboardItemsEndpoints(this);
4820
+ images = new ImagesEndpoints(this);
4821
+ spreads = new SpreadsEndpoints(this);
4822
+ };
4823
+
4824
+ // ../../core/models/client.ts
4825
+ var MagicBookClient = class {
4826
+ constructor(apiKey, apiHost = defaultApiHost, webSocketHost = defaultWebSocketHost) {
4827
+ this.apiKey = apiKey;
4828
+ this.apiHost = apiHost;
4829
+ this.webSocketHost = webSocketHost;
4830
+ this.engineAPI = new EngineAPI(this.apiHost, this.apiKey);
4831
+ }
4832
+ engineAPI;
4833
+ async createDesignRequest(designRequestProps) {
4834
+ const book = await this.engineAPI.books.create();
4835
+ return new DesignRequest(book.id, this, designRequestProps);
4836
+ }
4837
+ };
4838
+ // Annotate the CommonJS export names for ESM import in node:
4839
+ 0 && (module.exports = {
4840
+ DesignRequest,
4841
+ DesignRequestOptions,
4842
+ ImageServer,
4843
+ Images,
4844
+ MagicBookClient,
4845
+ designOptionsSchema,
4846
+ designOptionsServerSchema,
4847
+ imageDensityOptionSchema,
4848
+ imageDensityOptionServerSchema,
4849
+ imageDensityOptionsSchema,
4850
+ imageDensityOptionsServerSchema,
4851
+ imageServerSchema
4852
+ });
4853
+ //# sourceMappingURL=index.cjs.map