@magiclabs.ai/magicbook-client 0.6.8-canary → 0.6.9

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