@dajiaoai/algeo-sdk 1.1.0 → 1.2.1

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.
@@ -1,24 +1,3911 @@
1
1
  'use strict';
2
2
 
3
+ // src/embed.ts
4
+ var EMBED_ERROR_CODES = {
5
+ LOAD_SHARE_FAILED: "EMBED_LOAD_SHARE_FAILED",
6
+ LOAD_FILE_FAILED: "EMBED_LOAD_FILE_FAILED",
7
+ APPLY_CONTENT_FAILED: "EMBED_APPLY_CONTENT_FAILED",
8
+ SWITCH_SLIDE_FAILED: "EMBED_SWITCH_SLIDE_FAILED",
9
+ INVALID_SLIDE_INDEX: "EMBED_INVALID_SLIDE_INDEX",
10
+ GET_SLIDE_COUNT_FAILED: "EMBED_GET_SLIDE_COUNT_FAILED",
11
+ INVALID_REPL_COMMAND: "EMBED_INVALID_REPL_COMMAND",
12
+ REPL_EXECUTE_FAILED: "EMBED_REPL_EXECUTE_FAILED",
13
+ UNKNOWN_METHOD: "EMBED_UNKNOWN_METHOD",
14
+ UNKNOWN_ERROR: "EMBED_UNKNOWN_ERROR",
15
+ BAD_REQUEST: "EMBED_BAD_REQUEST",
16
+ IFRAME_NOT_READY: "EMBED_IFRAME_NOT_READY",
17
+ TIMEOUT: "EMBED_TIMEOUT",
18
+ DESTROYED: "EMBED_DESTROYED"
19
+ };
20
+ var AlgeoError = class extends Error {
21
+ constructor(message, code, details) {
22
+ super(message);
23
+ this.code = code;
24
+ this.details = details;
25
+ this.name = "AlgeoError";
26
+ }
27
+ };
28
+
29
+ var util;
30
+ (function (util) {
31
+ util.assertEqual = (_) => { };
32
+ function assertIs(_arg) { }
33
+ util.assertIs = assertIs;
34
+ function assertNever(_x) {
35
+ throw new Error();
36
+ }
37
+ util.assertNever = assertNever;
38
+ util.arrayToEnum = (items) => {
39
+ const obj = {};
40
+ for (const item of items) {
41
+ obj[item] = item;
42
+ }
43
+ return obj;
44
+ };
45
+ util.getValidEnumValues = (obj) => {
46
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
47
+ const filtered = {};
48
+ for (const k of validKeys) {
49
+ filtered[k] = obj[k];
50
+ }
51
+ return util.objectValues(filtered);
52
+ };
53
+ util.objectValues = (obj) => {
54
+ return util.objectKeys(obj).map(function (e) {
55
+ return obj[e];
56
+ });
57
+ };
58
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
59
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
60
+ : (object) => {
61
+ const keys = [];
62
+ for (const key in object) {
63
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
64
+ keys.push(key);
65
+ }
66
+ }
67
+ return keys;
68
+ };
69
+ util.find = (arr, checker) => {
70
+ for (const item of arr) {
71
+ if (checker(item))
72
+ return item;
73
+ }
74
+ return undefined;
75
+ };
76
+ util.isInteger = typeof Number.isInteger === "function"
77
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
78
+ : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
79
+ function joinValues(array, separator = " | ") {
80
+ return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
81
+ }
82
+ util.joinValues = joinValues;
83
+ util.jsonStringifyReplacer = (_, value) => {
84
+ if (typeof value === "bigint") {
85
+ return value.toString();
86
+ }
87
+ return value;
88
+ };
89
+ })(util || (util = {}));
90
+ var objectUtil;
91
+ (function (objectUtil) {
92
+ objectUtil.mergeShapes = (first, second) => {
93
+ return {
94
+ ...first,
95
+ ...second, // second overwrites first
96
+ };
97
+ };
98
+ })(objectUtil || (objectUtil = {}));
99
+ const ZodParsedType = util.arrayToEnum([
100
+ "string",
101
+ "nan",
102
+ "number",
103
+ "integer",
104
+ "float",
105
+ "boolean",
106
+ "date",
107
+ "bigint",
108
+ "symbol",
109
+ "function",
110
+ "undefined",
111
+ "null",
112
+ "array",
113
+ "object",
114
+ "unknown",
115
+ "promise",
116
+ "void",
117
+ "never",
118
+ "map",
119
+ "set",
120
+ ]);
121
+ const getParsedType = (data) => {
122
+ const t = typeof data;
123
+ switch (t) {
124
+ case "undefined":
125
+ return ZodParsedType.undefined;
126
+ case "string":
127
+ return ZodParsedType.string;
128
+ case "number":
129
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
130
+ case "boolean":
131
+ return ZodParsedType.boolean;
132
+ case "function":
133
+ return ZodParsedType.function;
134
+ case "bigint":
135
+ return ZodParsedType.bigint;
136
+ case "symbol":
137
+ return ZodParsedType.symbol;
138
+ case "object":
139
+ if (Array.isArray(data)) {
140
+ return ZodParsedType.array;
141
+ }
142
+ if (data === null) {
143
+ return ZodParsedType.null;
144
+ }
145
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
146
+ return ZodParsedType.promise;
147
+ }
148
+ if (typeof Map !== "undefined" && data instanceof Map) {
149
+ return ZodParsedType.map;
150
+ }
151
+ if (typeof Set !== "undefined" && data instanceof Set) {
152
+ return ZodParsedType.set;
153
+ }
154
+ if (typeof Date !== "undefined" && data instanceof Date) {
155
+ return ZodParsedType.date;
156
+ }
157
+ return ZodParsedType.object;
158
+ default:
159
+ return ZodParsedType.unknown;
160
+ }
161
+ };
162
+
163
+ const ZodIssueCode = util.arrayToEnum([
164
+ "invalid_type",
165
+ "invalid_literal",
166
+ "custom",
167
+ "invalid_union",
168
+ "invalid_union_discriminator",
169
+ "invalid_enum_value",
170
+ "unrecognized_keys",
171
+ "invalid_arguments",
172
+ "invalid_return_type",
173
+ "invalid_date",
174
+ "invalid_string",
175
+ "too_small",
176
+ "too_big",
177
+ "invalid_intersection_types",
178
+ "not_multiple_of",
179
+ "not_finite",
180
+ ]);
181
+ class ZodError extends Error {
182
+ get errors() {
183
+ return this.issues;
184
+ }
185
+ constructor(issues) {
186
+ super();
187
+ this.issues = [];
188
+ this.addIssue = (sub) => {
189
+ this.issues = [...this.issues, sub];
190
+ };
191
+ this.addIssues = (subs = []) => {
192
+ this.issues = [...this.issues, ...subs];
193
+ };
194
+ const actualProto = new.target.prototype;
195
+ if (Object.setPrototypeOf) {
196
+ // eslint-disable-next-line ban/ban
197
+ Object.setPrototypeOf(this, actualProto);
198
+ }
199
+ else {
200
+ this.__proto__ = actualProto;
201
+ }
202
+ this.name = "ZodError";
203
+ this.issues = issues;
204
+ }
205
+ format(_mapper) {
206
+ const mapper = _mapper ||
207
+ function (issue) {
208
+ return issue.message;
209
+ };
210
+ const fieldErrors = { _errors: [] };
211
+ const processError = (error) => {
212
+ for (const issue of error.issues) {
213
+ if (issue.code === "invalid_union") {
214
+ issue.unionErrors.map(processError);
215
+ }
216
+ else if (issue.code === "invalid_return_type") {
217
+ processError(issue.returnTypeError);
218
+ }
219
+ else if (issue.code === "invalid_arguments") {
220
+ processError(issue.argumentsError);
221
+ }
222
+ else if (issue.path.length === 0) {
223
+ fieldErrors._errors.push(mapper(issue));
224
+ }
225
+ else {
226
+ let curr = fieldErrors;
227
+ let i = 0;
228
+ while (i < issue.path.length) {
229
+ const el = issue.path[i];
230
+ const terminal = i === issue.path.length - 1;
231
+ if (!terminal) {
232
+ curr[el] = curr[el] || { _errors: [] };
233
+ // if (typeof el === "string") {
234
+ // curr[el] = curr[el] || { _errors: [] };
235
+ // } else if (typeof el === "number") {
236
+ // const errorArray: any = [];
237
+ // errorArray._errors = [];
238
+ // curr[el] = curr[el] || errorArray;
239
+ // }
240
+ }
241
+ else {
242
+ curr[el] = curr[el] || { _errors: [] };
243
+ curr[el]._errors.push(mapper(issue));
244
+ }
245
+ curr = curr[el];
246
+ i++;
247
+ }
248
+ }
249
+ }
250
+ };
251
+ processError(this);
252
+ return fieldErrors;
253
+ }
254
+ static assert(value) {
255
+ if (!(value instanceof ZodError)) {
256
+ throw new Error(`Not a ZodError: ${value}`);
257
+ }
258
+ }
259
+ toString() {
260
+ return this.message;
261
+ }
262
+ get message() {
263
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
264
+ }
265
+ get isEmpty() {
266
+ return this.issues.length === 0;
267
+ }
268
+ flatten(mapper = (issue) => issue.message) {
269
+ const fieldErrors = {};
270
+ const formErrors = [];
271
+ for (const sub of this.issues) {
272
+ if (sub.path.length > 0) {
273
+ const firstEl = sub.path[0];
274
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
275
+ fieldErrors[firstEl].push(mapper(sub));
276
+ }
277
+ else {
278
+ formErrors.push(mapper(sub));
279
+ }
280
+ }
281
+ return { formErrors, fieldErrors };
282
+ }
283
+ get formErrors() {
284
+ return this.flatten();
285
+ }
286
+ }
287
+ ZodError.create = (issues) => {
288
+ const error = new ZodError(issues);
289
+ return error;
290
+ };
291
+
292
+ const errorMap = (issue, _ctx) => {
293
+ let message;
294
+ switch (issue.code) {
295
+ case ZodIssueCode.invalid_type:
296
+ if (issue.received === ZodParsedType.undefined) {
297
+ message = "Required";
298
+ }
299
+ else {
300
+ message = `Expected ${issue.expected}, received ${issue.received}`;
301
+ }
302
+ break;
303
+ case ZodIssueCode.invalid_literal:
304
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
305
+ break;
306
+ case ZodIssueCode.unrecognized_keys:
307
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
308
+ break;
309
+ case ZodIssueCode.invalid_union:
310
+ message = `Invalid input`;
311
+ break;
312
+ case ZodIssueCode.invalid_union_discriminator:
313
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
314
+ break;
315
+ case ZodIssueCode.invalid_enum_value:
316
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
317
+ break;
318
+ case ZodIssueCode.invalid_arguments:
319
+ message = `Invalid function arguments`;
320
+ break;
321
+ case ZodIssueCode.invalid_return_type:
322
+ message = `Invalid function return type`;
323
+ break;
324
+ case ZodIssueCode.invalid_date:
325
+ message = `Invalid date`;
326
+ break;
327
+ case ZodIssueCode.invalid_string:
328
+ if (typeof issue.validation === "object") {
329
+ if ("includes" in issue.validation) {
330
+ message = `Invalid input: must include "${issue.validation.includes}"`;
331
+ if (typeof issue.validation.position === "number") {
332
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
333
+ }
334
+ }
335
+ else if ("startsWith" in issue.validation) {
336
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
337
+ }
338
+ else if ("endsWith" in issue.validation) {
339
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
340
+ }
341
+ else {
342
+ util.assertNever(issue.validation);
343
+ }
344
+ }
345
+ else if (issue.validation !== "regex") {
346
+ message = `Invalid ${issue.validation}`;
347
+ }
348
+ else {
349
+ message = "Invalid";
350
+ }
351
+ break;
352
+ case ZodIssueCode.too_small:
353
+ if (issue.type === "array")
354
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
355
+ else if (issue.type === "string")
356
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
357
+ else if (issue.type === "number")
358
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
359
+ else if (issue.type === "bigint")
360
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
361
+ else if (issue.type === "date")
362
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
363
+ else
364
+ message = "Invalid input";
365
+ break;
366
+ case ZodIssueCode.too_big:
367
+ if (issue.type === "array")
368
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
369
+ else if (issue.type === "string")
370
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
371
+ else if (issue.type === "number")
372
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
373
+ else if (issue.type === "bigint")
374
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
375
+ else if (issue.type === "date")
376
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
377
+ else
378
+ message = "Invalid input";
379
+ break;
380
+ case ZodIssueCode.custom:
381
+ message = `Invalid input`;
382
+ break;
383
+ case ZodIssueCode.invalid_intersection_types:
384
+ message = `Intersection results could not be merged`;
385
+ break;
386
+ case ZodIssueCode.not_multiple_of:
387
+ message = `Number must be a multiple of ${issue.multipleOf}`;
388
+ break;
389
+ case ZodIssueCode.not_finite:
390
+ message = "Number must be finite";
391
+ break;
392
+ default:
393
+ message = _ctx.defaultError;
394
+ util.assertNever(issue);
395
+ }
396
+ return { message };
397
+ };
398
+
399
+ let overrideErrorMap = errorMap;
400
+ function getErrorMap() {
401
+ return overrideErrorMap;
402
+ }
403
+
404
+ const makeIssue = (params) => {
405
+ const { data, path, errorMaps, issueData } = params;
406
+ const fullPath = [...path, ...(issueData.path || [])];
407
+ const fullIssue = {
408
+ ...issueData,
409
+ path: fullPath,
410
+ };
411
+ if (issueData.message !== undefined) {
412
+ return {
413
+ ...issueData,
414
+ path: fullPath,
415
+ message: issueData.message,
416
+ };
417
+ }
418
+ let errorMessage = "";
419
+ const maps = errorMaps
420
+ .filter((m) => !!m)
421
+ .slice()
422
+ .reverse();
423
+ for (const map of maps) {
424
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
425
+ }
426
+ return {
427
+ ...issueData,
428
+ path: fullPath,
429
+ message: errorMessage,
430
+ };
431
+ };
432
+ function addIssueToContext(ctx, issueData) {
433
+ const overrideMap = getErrorMap();
434
+ const issue = makeIssue({
435
+ issueData: issueData,
436
+ data: ctx.data,
437
+ path: ctx.path,
438
+ errorMaps: [
439
+ ctx.common.contextualErrorMap, // contextual error map is first priority
440
+ ctx.schemaErrorMap, // then schema-bound map if available
441
+ overrideMap, // then global override map
442
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
443
+ ].filter((x) => !!x),
444
+ });
445
+ ctx.common.issues.push(issue);
446
+ }
447
+ class ParseStatus {
448
+ constructor() {
449
+ this.value = "valid";
450
+ }
451
+ dirty() {
452
+ if (this.value === "valid")
453
+ this.value = "dirty";
454
+ }
455
+ abort() {
456
+ if (this.value !== "aborted")
457
+ this.value = "aborted";
458
+ }
459
+ static mergeArray(status, results) {
460
+ const arrayValue = [];
461
+ for (const s of results) {
462
+ if (s.status === "aborted")
463
+ return INVALID;
464
+ if (s.status === "dirty")
465
+ status.dirty();
466
+ arrayValue.push(s.value);
467
+ }
468
+ return { status: status.value, value: arrayValue };
469
+ }
470
+ static async mergeObjectAsync(status, pairs) {
471
+ const syncPairs = [];
472
+ for (const pair of pairs) {
473
+ const key = await pair.key;
474
+ const value = await pair.value;
475
+ syncPairs.push({
476
+ key,
477
+ value,
478
+ });
479
+ }
480
+ return ParseStatus.mergeObjectSync(status, syncPairs);
481
+ }
482
+ static mergeObjectSync(status, pairs) {
483
+ const finalObject = {};
484
+ for (const pair of pairs) {
485
+ const { key, value } = pair;
486
+ if (key.status === "aborted")
487
+ return INVALID;
488
+ if (value.status === "aborted")
489
+ return INVALID;
490
+ if (key.status === "dirty")
491
+ status.dirty();
492
+ if (value.status === "dirty")
493
+ status.dirty();
494
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
495
+ finalObject[key.value] = value.value;
496
+ }
497
+ }
498
+ return { status: status.value, value: finalObject };
499
+ }
500
+ }
501
+ const INVALID = Object.freeze({
502
+ status: "aborted",
503
+ });
504
+ const DIRTY = (value) => ({ status: "dirty", value });
505
+ const OK = (value) => ({ status: "valid", value });
506
+ const isAborted = (x) => x.status === "aborted";
507
+ const isDirty = (x) => x.status === "dirty";
508
+ const isValid = (x) => x.status === "valid";
509
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
510
+
511
+ var errorUtil;
512
+ (function (errorUtil) {
513
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
514
+ // biome-ignore lint:
515
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
516
+ })(errorUtil || (errorUtil = {}));
517
+
518
+ class ParseInputLazyPath {
519
+ constructor(parent, value, path, key) {
520
+ this._cachedPath = [];
521
+ this.parent = parent;
522
+ this.data = value;
523
+ this._path = path;
524
+ this._key = key;
525
+ }
526
+ get path() {
527
+ if (!this._cachedPath.length) {
528
+ if (Array.isArray(this._key)) {
529
+ this._cachedPath.push(...this._path, ...this._key);
530
+ }
531
+ else {
532
+ this._cachedPath.push(...this._path, this._key);
533
+ }
534
+ }
535
+ return this._cachedPath;
536
+ }
537
+ }
538
+ const handleResult = (ctx, result) => {
539
+ if (isValid(result)) {
540
+ return { success: true, data: result.value };
541
+ }
542
+ else {
543
+ if (!ctx.common.issues.length) {
544
+ throw new Error("Validation failed but no issues detected.");
545
+ }
546
+ return {
547
+ success: false,
548
+ get error() {
549
+ if (this._error)
550
+ return this._error;
551
+ const error = new ZodError(ctx.common.issues);
552
+ this._error = error;
553
+ return this._error;
554
+ },
555
+ };
556
+ }
557
+ };
558
+ function processCreateParams(params) {
559
+ if (!params)
560
+ return {};
561
+ const { errorMap, invalid_type_error, required_error, description } = params;
562
+ if (errorMap && (invalid_type_error || required_error)) {
563
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
564
+ }
565
+ if (errorMap)
566
+ return { errorMap: errorMap, description };
567
+ const customMap = (iss, ctx) => {
568
+ const { message } = params;
569
+ if (iss.code === "invalid_enum_value") {
570
+ return { message: message ?? ctx.defaultError };
571
+ }
572
+ if (typeof ctx.data === "undefined") {
573
+ return { message: message ?? required_error ?? ctx.defaultError };
574
+ }
575
+ if (iss.code !== "invalid_type")
576
+ return { message: ctx.defaultError };
577
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
578
+ };
579
+ return { errorMap: customMap, description };
580
+ }
581
+ class ZodType {
582
+ get description() {
583
+ return this._def.description;
584
+ }
585
+ _getType(input) {
586
+ return getParsedType(input.data);
587
+ }
588
+ _getOrReturnCtx(input, ctx) {
589
+ return (ctx || {
590
+ common: input.parent.common,
591
+ data: input.data,
592
+ parsedType: getParsedType(input.data),
593
+ schemaErrorMap: this._def.errorMap,
594
+ path: input.path,
595
+ parent: input.parent,
596
+ });
597
+ }
598
+ _processInputParams(input) {
599
+ return {
600
+ status: new ParseStatus(),
601
+ ctx: {
602
+ common: input.parent.common,
603
+ data: input.data,
604
+ parsedType: getParsedType(input.data),
605
+ schemaErrorMap: this._def.errorMap,
606
+ path: input.path,
607
+ parent: input.parent,
608
+ },
609
+ };
610
+ }
611
+ _parseSync(input) {
612
+ const result = this._parse(input);
613
+ if (isAsync(result)) {
614
+ throw new Error("Synchronous parse encountered promise.");
615
+ }
616
+ return result;
617
+ }
618
+ _parseAsync(input) {
619
+ const result = this._parse(input);
620
+ return Promise.resolve(result);
621
+ }
622
+ parse(data, params) {
623
+ const result = this.safeParse(data, params);
624
+ if (result.success)
625
+ return result.data;
626
+ throw result.error;
627
+ }
628
+ safeParse(data, params) {
629
+ const ctx = {
630
+ common: {
631
+ issues: [],
632
+ async: params?.async ?? false,
633
+ contextualErrorMap: params?.errorMap,
634
+ },
635
+ path: params?.path || [],
636
+ schemaErrorMap: this._def.errorMap,
637
+ parent: null,
638
+ data,
639
+ parsedType: getParsedType(data),
640
+ };
641
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
642
+ return handleResult(ctx, result);
643
+ }
644
+ "~validate"(data) {
645
+ const ctx = {
646
+ common: {
647
+ issues: [],
648
+ async: !!this["~standard"].async,
649
+ },
650
+ path: [],
651
+ schemaErrorMap: this._def.errorMap,
652
+ parent: null,
653
+ data,
654
+ parsedType: getParsedType(data),
655
+ };
656
+ if (!this["~standard"].async) {
657
+ try {
658
+ const result = this._parseSync({ data, path: [], parent: ctx });
659
+ return isValid(result)
660
+ ? {
661
+ value: result.value,
662
+ }
663
+ : {
664
+ issues: ctx.common.issues,
665
+ };
666
+ }
667
+ catch (err) {
668
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
669
+ this["~standard"].async = true;
670
+ }
671
+ ctx.common = {
672
+ issues: [],
673
+ async: true,
674
+ };
675
+ }
676
+ }
677
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
678
+ ? {
679
+ value: result.value,
680
+ }
681
+ : {
682
+ issues: ctx.common.issues,
683
+ });
684
+ }
685
+ async parseAsync(data, params) {
686
+ const result = await this.safeParseAsync(data, params);
687
+ if (result.success)
688
+ return result.data;
689
+ throw result.error;
690
+ }
691
+ async safeParseAsync(data, params) {
692
+ const ctx = {
693
+ common: {
694
+ issues: [],
695
+ contextualErrorMap: params?.errorMap,
696
+ async: true,
697
+ },
698
+ path: params?.path || [],
699
+ schemaErrorMap: this._def.errorMap,
700
+ parent: null,
701
+ data,
702
+ parsedType: getParsedType(data),
703
+ };
704
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
705
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
706
+ return handleResult(ctx, result);
707
+ }
708
+ refine(check, message) {
709
+ const getIssueProperties = (val) => {
710
+ if (typeof message === "string" || typeof message === "undefined") {
711
+ return { message };
712
+ }
713
+ else if (typeof message === "function") {
714
+ return message(val);
715
+ }
716
+ else {
717
+ return message;
718
+ }
719
+ };
720
+ return this._refinement((val, ctx) => {
721
+ const result = check(val);
722
+ const setError = () => ctx.addIssue({
723
+ code: ZodIssueCode.custom,
724
+ ...getIssueProperties(val),
725
+ });
726
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
727
+ return result.then((data) => {
728
+ if (!data) {
729
+ setError();
730
+ return false;
731
+ }
732
+ else {
733
+ return true;
734
+ }
735
+ });
736
+ }
737
+ if (!result) {
738
+ setError();
739
+ return false;
740
+ }
741
+ else {
742
+ return true;
743
+ }
744
+ });
745
+ }
746
+ refinement(check, refinementData) {
747
+ return this._refinement((val, ctx) => {
748
+ if (!check(val)) {
749
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
750
+ return false;
751
+ }
752
+ else {
753
+ return true;
754
+ }
755
+ });
756
+ }
757
+ _refinement(refinement) {
758
+ return new ZodEffects({
759
+ schema: this,
760
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
761
+ effect: { type: "refinement", refinement },
762
+ });
763
+ }
764
+ superRefine(refinement) {
765
+ return this._refinement(refinement);
766
+ }
767
+ constructor(def) {
768
+ /** Alias of safeParseAsync */
769
+ this.spa = this.safeParseAsync;
770
+ this._def = def;
771
+ this.parse = this.parse.bind(this);
772
+ this.safeParse = this.safeParse.bind(this);
773
+ this.parseAsync = this.parseAsync.bind(this);
774
+ this.safeParseAsync = this.safeParseAsync.bind(this);
775
+ this.spa = this.spa.bind(this);
776
+ this.refine = this.refine.bind(this);
777
+ this.refinement = this.refinement.bind(this);
778
+ this.superRefine = this.superRefine.bind(this);
779
+ this.optional = this.optional.bind(this);
780
+ this.nullable = this.nullable.bind(this);
781
+ this.nullish = this.nullish.bind(this);
782
+ this.array = this.array.bind(this);
783
+ this.promise = this.promise.bind(this);
784
+ this.or = this.or.bind(this);
785
+ this.and = this.and.bind(this);
786
+ this.transform = this.transform.bind(this);
787
+ this.brand = this.brand.bind(this);
788
+ this.default = this.default.bind(this);
789
+ this.catch = this.catch.bind(this);
790
+ this.describe = this.describe.bind(this);
791
+ this.pipe = this.pipe.bind(this);
792
+ this.readonly = this.readonly.bind(this);
793
+ this.isNullable = this.isNullable.bind(this);
794
+ this.isOptional = this.isOptional.bind(this);
795
+ this["~standard"] = {
796
+ version: 1,
797
+ vendor: "zod",
798
+ validate: (data) => this["~validate"](data),
799
+ };
800
+ }
801
+ optional() {
802
+ return ZodOptional.create(this, this._def);
803
+ }
804
+ nullable() {
805
+ return ZodNullable.create(this, this._def);
806
+ }
807
+ nullish() {
808
+ return this.nullable().optional();
809
+ }
810
+ array() {
811
+ return ZodArray.create(this);
812
+ }
813
+ promise() {
814
+ return ZodPromise.create(this, this._def);
815
+ }
816
+ or(option) {
817
+ return ZodUnion.create([this, option], this._def);
818
+ }
819
+ and(incoming) {
820
+ return ZodIntersection.create(this, incoming, this._def);
821
+ }
822
+ transform(transform) {
823
+ return new ZodEffects({
824
+ ...processCreateParams(this._def),
825
+ schema: this,
826
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
827
+ effect: { type: "transform", transform },
828
+ });
829
+ }
830
+ default(def) {
831
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
832
+ return new ZodDefault({
833
+ ...processCreateParams(this._def),
834
+ innerType: this,
835
+ defaultValue: defaultValueFunc,
836
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
837
+ });
838
+ }
839
+ brand() {
840
+ return new ZodBranded({
841
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
842
+ type: this,
843
+ ...processCreateParams(this._def),
844
+ });
845
+ }
846
+ catch(def) {
847
+ const catchValueFunc = typeof def === "function" ? def : () => def;
848
+ return new ZodCatch({
849
+ ...processCreateParams(this._def),
850
+ innerType: this,
851
+ catchValue: catchValueFunc,
852
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
853
+ });
854
+ }
855
+ describe(description) {
856
+ const This = this.constructor;
857
+ return new This({
858
+ ...this._def,
859
+ description,
860
+ });
861
+ }
862
+ pipe(target) {
863
+ return ZodPipeline.create(this, target);
864
+ }
865
+ readonly() {
866
+ return ZodReadonly.create(this);
867
+ }
868
+ isOptional() {
869
+ return this.safeParse(undefined).success;
870
+ }
871
+ isNullable() {
872
+ return this.safeParse(null).success;
873
+ }
874
+ }
875
+ const cuidRegex = /^c[^\s-]{8,}$/i;
876
+ const cuid2Regex = /^[0-9a-z]+$/;
877
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
878
+ // const uuidRegex =
879
+ // /^([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;
880
+ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
881
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
882
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
883
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
884
+ // from https://stackoverflow.com/a/46181/1550155
885
+ // old version: too slow, didn't support unicode
886
+ // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
887
+ //old email regex
888
+ // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
889
+ // eslint-disable-next-line
890
+ // const emailRegex =
891
+ // /^(([^<>()[\]\\.,;:\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,})+))$/;
892
+ // const emailRegex =
893
+ // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
894
+ // const emailRegex =
895
+ // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
896
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
897
+ // const emailRegex =
898
+ // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
899
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
900
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
901
+ let emojiRegex;
902
+ // faster, simpler, safer
903
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
904
+ const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
905
+ // const ipv6Regex =
906
+ // /^(([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})))$/;
907
+ const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
908
+ const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
909
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
910
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
911
+ // https://base64.guru/standards/base64url
912
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
913
+ // simple
914
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
915
+ // no leap year validation
916
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
917
+ // with leap year validation
918
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
919
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
920
+ function timeRegexSource(args) {
921
+ let secondsRegexSource = `[0-5]\\d`;
922
+ if (args.precision) {
923
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
924
+ }
925
+ else if (args.precision == null) {
926
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
927
+ }
928
+ const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
929
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
930
+ }
931
+ function timeRegex(args) {
932
+ return new RegExp(`^${timeRegexSource(args)}$`);
933
+ }
934
+ // Adapted from https://stackoverflow.com/a/3143231
935
+ function datetimeRegex(args) {
936
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
937
+ const opts = [];
938
+ opts.push(args.local ? `Z?` : `Z`);
939
+ if (args.offset)
940
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
941
+ regex = `${regex}(${opts.join("|")})`;
942
+ return new RegExp(`^${regex}$`);
943
+ }
944
+ function isValidIP(ip, version) {
945
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
946
+ return true;
947
+ }
948
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
949
+ return true;
950
+ }
951
+ return false;
952
+ }
953
+ function isValidJWT(jwt, alg) {
954
+ if (!jwtRegex.test(jwt))
955
+ return false;
956
+ try {
957
+ const [header] = jwt.split(".");
958
+ if (!header)
959
+ return false;
960
+ // Convert base64url to base64
961
+ const base64 = header
962
+ .replace(/-/g, "+")
963
+ .replace(/_/g, "/")
964
+ .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
965
+ const decoded = JSON.parse(atob(base64));
966
+ if (typeof decoded !== "object" || decoded === null)
967
+ return false;
968
+ if ("typ" in decoded && decoded?.typ !== "JWT")
969
+ return false;
970
+ if (!decoded.alg)
971
+ return false;
972
+ if (alg && decoded.alg !== alg)
973
+ return false;
974
+ return true;
975
+ }
976
+ catch {
977
+ return false;
978
+ }
979
+ }
980
+ function isValidCidr(ip, version) {
981
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
982
+ return true;
983
+ }
984
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
985
+ return true;
986
+ }
987
+ return false;
988
+ }
989
+ class ZodString extends ZodType {
990
+ _parse(input) {
991
+ if (this._def.coerce) {
992
+ input.data = String(input.data);
993
+ }
994
+ const parsedType = this._getType(input);
995
+ if (parsedType !== ZodParsedType.string) {
996
+ const ctx = this._getOrReturnCtx(input);
997
+ addIssueToContext(ctx, {
998
+ code: ZodIssueCode.invalid_type,
999
+ expected: ZodParsedType.string,
1000
+ received: ctx.parsedType,
1001
+ });
1002
+ return INVALID;
1003
+ }
1004
+ const status = new ParseStatus();
1005
+ let ctx = undefined;
1006
+ for (const check of this._def.checks) {
1007
+ if (check.kind === "min") {
1008
+ if (input.data.length < check.value) {
1009
+ ctx = this._getOrReturnCtx(input, ctx);
1010
+ addIssueToContext(ctx, {
1011
+ code: ZodIssueCode.too_small,
1012
+ minimum: check.value,
1013
+ type: "string",
1014
+ inclusive: true,
1015
+ exact: false,
1016
+ message: check.message,
1017
+ });
1018
+ status.dirty();
1019
+ }
1020
+ }
1021
+ else if (check.kind === "max") {
1022
+ if (input.data.length > check.value) {
1023
+ ctx = this._getOrReturnCtx(input, ctx);
1024
+ addIssueToContext(ctx, {
1025
+ code: ZodIssueCode.too_big,
1026
+ maximum: check.value,
1027
+ type: "string",
1028
+ inclusive: true,
1029
+ exact: false,
1030
+ message: check.message,
1031
+ });
1032
+ status.dirty();
1033
+ }
1034
+ }
1035
+ else if (check.kind === "length") {
1036
+ const tooBig = input.data.length > check.value;
1037
+ const tooSmall = input.data.length < check.value;
1038
+ if (tooBig || tooSmall) {
1039
+ ctx = this._getOrReturnCtx(input, ctx);
1040
+ if (tooBig) {
1041
+ addIssueToContext(ctx, {
1042
+ code: ZodIssueCode.too_big,
1043
+ maximum: check.value,
1044
+ type: "string",
1045
+ inclusive: true,
1046
+ exact: true,
1047
+ message: check.message,
1048
+ });
1049
+ }
1050
+ else if (tooSmall) {
1051
+ addIssueToContext(ctx, {
1052
+ code: ZodIssueCode.too_small,
1053
+ minimum: check.value,
1054
+ type: "string",
1055
+ inclusive: true,
1056
+ exact: true,
1057
+ message: check.message,
1058
+ });
1059
+ }
1060
+ status.dirty();
1061
+ }
1062
+ }
1063
+ else if (check.kind === "email") {
1064
+ if (!emailRegex.test(input.data)) {
1065
+ ctx = this._getOrReturnCtx(input, ctx);
1066
+ addIssueToContext(ctx, {
1067
+ validation: "email",
1068
+ code: ZodIssueCode.invalid_string,
1069
+ message: check.message,
1070
+ });
1071
+ status.dirty();
1072
+ }
1073
+ }
1074
+ else if (check.kind === "emoji") {
1075
+ if (!emojiRegex) {
1076
+ emojiRegex = new RegExp(_emojiRegex, "u");
1077
+ }
1078
+ if (!emojiRegex.test(input.data)) {
1079
+ ctx = this._getOrReturnCtx(input, ctx);
1080
+ addIssueToContext(ctx, {
1081
+ validation: "emoji",
1082
+ code: ZodIssueCode.invalid_string,
1083
+ message: check.message,
1084
+ });
1085
+ status.dirty();
1086
+ }
1087
+ }
1088
+ else if (check.kind === "uuid") {
1089
+ if (!uuidRegex.test(input.data)) {
1090
+ ctx = this._getOrReturnCtx(input, ctx);
1091
+ addIssueToContext(ctx, {
1092
+ validation: "uuid",
1093
+ code: ZodIssueCode.invalid_string,
1094
+ message: check.message,
1095
+ });
1096
+ status.dirty();
1097
+ }
1098
+ }
1099
+ else if (check.kind === "nanoid") {
1100
+ if (!nanoidRegex.test(input.data)) {
1101
+ ctx = this._getOrReturnCtx(input, ctx);
1102
+ addIssueToContext(ctx, {
1103
+ validation: "nanoid",
1104
+ code: ZodIssueCode.invalid_string,
1105
+ message: check.message,
1106
+ });
1107
+ status.dirty();
1108
+ }
1109
+ }
1110
+ else if (check.kind === "cuid") {
1111
+ if (!cuidRegex.test(input.data)) {
1112
+ ctx = this._getOrReturnCtx(input, ctx);
1113
+ addIssueToContext(ctx, {
1114
+ validation: "cuid",
1115
+ code: ZodIssueCode.invalid_string,
1116
+ message: check.message,
1117
+ });
1118
+ status.dirty();
1119
+ }
1120
+ }
1121
+ else if (check.kind === "cuid2") {
1122
+ if (!cuid2Regex.test(input.data)) {
1123
+ ctx = this._getOrReturnCtx(input, ctx);
1124
+ addIssueToContext(ctx, {
1125
+ validation: "cuid2",
1126
+ code: ZodIssueCode.invalid_string,
1127
+ message: check.message,
1128
+ });
1129
+ status.dirty();
1130
+ }
1131
+ }
1132
+ else if (check.kind === "ulid") {
1133
+ if (!ulidRegex.test(input.data)) {
1134
+ ctx = this._getOrReturnCtx(input, ctx);
1135
+ addIssueToContext(ctx, {
1136
+ validation: "ulid",
1137
+ code: ZodIssueCode.invalid_string,
1138
+ message: check.message,
1139
+ });
1140
+ status.dirty();
1141
+ }
1142
+ }
1143
+ else if (check.kind === "url") {
1144
+ try {
1145
+ new URL(input.data);
1146
+ }
1147
+ catch {
1148
+ ctx = this._getOrReturnCtx(input, ctx);
1149
+ addIssueToContext(ctx, {
1150
+ validation: "url",
1151
+ code: ZodIssueCode.invalid_string,
1152
+ message: check.message,
1153
+ });
1154
+ status.dirty();
1155
+ }
1156
+ }
1157
+ else if (check.kind === "regex") {
1158
+ check.regex.lastIndex = 0;
1159
+ const testResult = check.regex.test(input.data);
1160
+ if (!testResult) {
1161
+ ctx = this._getOrReturnCtx(input, ctx);
1162
+ addIssueToContext(ctx, {
1163
+ validation: "regex",
1164
+ code: ZodIssueCode.invalid_string,
1165
+ message: check.message,
1166
+ });
1167
+ status.dirty();
1168
+ }
1169
+ }
1170
+ else if (check.kind === "trim") {
1171
+ input.data = input.data.trim();
1172
+ }
1173
+ else if (check.kind === "includes") {
1174
+ if (!input.data.includes(check.value, check.position)) {
1175
+ ctx = this._getOrReturnCtx(input, ctx);
1176
+ addIssueToContext(ctx, {
1177
+ code: ZodIssueCode.invalid_string,
1178
+ validation: { includes: check.value, position: check.position },
1179
+ message: check.message,
1180
+ });
1181
+ status.dirty();
1182
+ }
1183
+ }
1184
+ else if (check.kind === "toLowerCase") {
1185
+ input.data = input.data.toLowerCase();
1186
+ }
1187
+ else if (check.kind === "toUpperCase") {
1188
+ input.data = input.data.toUpperCase();
1189
+ }
1190
+ else if (check.kind === "startsWith") {
1191
+ if (!input.data.startsWith(check.value)) {
1192
+ ctx = this._getOrReturnCtx(input, ctx);
1193
+ addIssueToContext(ctx, {
1194
+ code: ZodIssueCode.invalid_string,
1195
+ validation: { startsWith: check.value },
1196
+ message: check.message,
1197
+ });
1198
+ status.dirty();
1199
+ }
1200
+ }
1201
+ else if (check.kind === "endsWith") {
1202
+ if (!input.data.endsWith(check.value)) {
1203
+ ctx = this._getOrReturnCtx(input, ctx);
1204
+ addIssueToContext(ctx, {
1205
+ code: ZodIssueCode.invalid_string,
1206
+ validation: { endsWith: check.value },
1207
+ message: check.message,
1208
+ });
1209
+ status.dirty();
1210
+ }
1211
+ }
1212
+ else if (check.kind === "datetime") {
1213
+ const regex = datetimeRegex(check);
1214
+ if (!regex.test(input.data)) {
1215
+ ctx = this._getOrReturnCtx(input, ctx);
1216
+ addIssueToContext(ctx, {
1217
+ code: ZodIssueCode.invalid_string,
1218
+ validation: "datetime",
1219
+ message: check.message,
1220
+ });
1221
+ status.dirty();
1222
+ }
1223
+ }
1224
+ else if (check.kind === "date") {
1225
+ const regex = dateRegex;
1226
+ if (!regex.test(input.data)) {
1227
+ ctx = this._getOrReturnCtx(input, ctx);
1228
+ addIssueToContext(ctx, {
1229
+ code: ZodIssueCode.invalid_string,
1230
+ validation: "date",
1231
+ message: check.message,
1232
+ });
1233
+ status.dirty();
1234
+ }
1235
+ }
1236
+ else if (check.kind === "time") {
1237
+ const regex = timeRegex(check);
1238
+ if (!regex.test(input.data)) {
1239
+ ctx = this._getOrReturnCtx(input, ctx);
1240
+ addIssueToContext(ctx, {
1241
+ code: ZodIssueCode.invalid_string,
1242
+ validation: "time",
1243
+ message: check.message,
1244
+ });
1245
+ status.dirty();
1246
+ }
1247
+ }
1248
+ else if (check.kind === "duration") {
1249
+ if (!durationRegex.test(input.data)) {
1250
+ ctx = this._getOrReturnCtx(input, ctx);
1251
+ addIssueToContext(ctx, {
1252
+ validation: "duration",
1253
+ code: ZodIssueCode.invalid_string,
1254
+ message: check.message,
1255
+ });
1256
+ status.dirty();
1257
+ }
1258
+ }
1259
+ else if (check.kind === "ip") {
1260
+ if (!isValidIP(input.data, check.version)) {
1261
+ ctx = this._getOrReturnCtx(input, ctx);
1262
+ addIssueToContext(ctx, {
1263
+ validation: "ip",
1264
+ code: ZodIssueCode.invalid_string,
1265
+ message: check.message,
1266
+ });
1267
+ status.dirty();
1268
+ }
1269
+ }
1270
+ else if (check.kind === "jwt") {
1271
+ if (!isValidJWT(input.data, check.alg)) {
1272
+ ctx = this._getOrReturnCtx(input, ctx);
1273
+ addIssueToContext(ctx, {
1274
+ validation: "jwt",
1275
+ code: ZodIssueCode.invalid_string,
1276
+ message: check.message,
1277
+ });
1278
+ status.dirty();
1279
+ }
1280
+ }
1281
+ else if (check.kind === "cidr") {
1282
+ if (!isValidCidr(input.data, check.version)) {
1283
+ ctx = this._getOrReturnCtx(input, ctx);
1284
+ addIssueToContext(ctx, {
1285
+ validation: "cidr",
1286
+ code: ZodIssueCode.invalid_string,
1287
+ message: check.message,
1288
+ });
1289
+ status.dirty();
1290
+ }
1291
+ }
1292
+ else if (check.kind === "base64") {
1293
+ if (!base64Regex.test(input.data)) {
1294
+ ctx = this._getOrReturnCtx(input, ctx);
1295
+ addIssueToContext(ctx, {
1296
+ validation: "base64",
1297
+ code: ZodIssueCode.invalid_string,
1298
+ message: check.message,
1299
+ });
1300
+ status.dirty();
1301
+ }
1302
+ }
1303
+ else if (check.kind === "base64url") {
1304
+ if (!base64urlRegex.test(input.data)) {
1305
+ ctx = this._getOrReturnCtx(input, ctx);
1306
+ addIssueToContext(ctx, {
1307
+ validation: "base64url",
1308
+ code: ZodIssueCode.invalid_string,
1309
+ message: check.message,
1310
+ });
1311
+ status.dirty();
1312
+ }
1313
+ }
1314
+ else {
1315
+ util.assertNever(check);
1316
+ }
1317
+ }
1318
+ return { status: status.value, value: input.data };
1319
+ }
1320
+ _regex(regex, validation, message) {
1321
+ return this.refinement((data) => regex.test(data), {
1322
+ validation,
1323
+ code: ZodIssueCode.invalid_string,
1324
+ ...errorUtil.errToObj(message),
1325
+ });
1326
+ }
1327
+ _addCheck(check) {
1328
+ return new ZodString({
1329
+ ...this._def,
1330
+ checks: [...this._def.checks, check],
1331
+ });
1332
+ }
1333
+ email(message) {
1334
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1335
+ }
1336
+ url(message) {
1337
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1338
+ }
1339
+ emoji(message) {
1340
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1341
+ }
1342
+ uuid(message) {
1343
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1344
+ }
1345
+ nanoid(message) {
1346
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1347
+ }
1348
+ cuid(message) {
1349
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1350
+ }
1351
+ cuid2(message) {
1352
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1353
+ }
1354
+ ulid(message) {
1355
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1356
+ }
1357
+ base64(message) {
1358
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1359
+ }
1360
+ base64url(message) {
1361
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1362
+ return this._addCheck({
1363
+ kind: "base64url",
1364
+ ...errorUtil.errToObj(message),
1365
+ });
1366
+ }
1367
+ jwt(options) {
1368
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1369
+ }
1370
+ ip(options) {
1371
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1372
+ }
1373
+ cidr(options) {
1374
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1375
+ }
1376
+ datetime(options) {
1377
+ if (typeof options === "string") {
1378
+ return this._addCheck({
1379
+ kind: "datetime",
1380
+ precision: null,
1381
+ offset: false,
1382
+ local: false,
1383
+ message: options,
1384
+ });
1385
+ }
1386
+ return this._addCheck({
1387
+ kind: "datetime",
1388
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1389
+ offset: options?.offset ?? false,
1390
+ local: options?.local ?? false,
1391
+ ...errorUtil.errToObj(options?.message),
1392
+ });
1393
+ }
1394
+ date(message) {
1395
+ return this._addCheck({ kind: "date", message });
1396
+ }
1397
+ time(options) {
1398
+ if (typeof options === "string") {
1399
+ return this._addCheck({
1400
+ kind: "time",
1401
+ precision: null,
1402
+ message: options,
1403
+ });
1404
+ }
1405
+ return this._addCheck({
1406
+ kind: "time",
1407
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1408
+ ...errorUtil.errToObj(options?.message),
1409
+ });
1410
+ }
1411
+ duration(message) {
1412
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1413
+ }
1414
+ regex(regex, message) {
1415
+ return this._addCheck({
1416
+ kind: "regex",
1417
+ regex: regex,
1418
+ ...errorUtil.errToObj(message),
1419
+ });
1420
+ }
1421
+ includes(value, options) {
1422
+ return this._addCheck({
1423
+ kind: "includes",
1424
+ value: value,
1425
+ position: options?.position,
1426
+ ...errorUtil.errToObj(options?.message),
1427
+ });
1428
+ }
1429
+ startsWith(value, message) {
1430
+ return this._addCheck({
1431
+ kind: "startsWith",
1432
+ value: value,
1433
+ ...errorUtil.errToObj(message),
1434
+ });
1435
+ }
1436
+ endsWith(value, message) {
1437
+ return this._addCheck({
1438
+ kind: "endsWith",
1439
+ value: value,
1440
+ ...errorUtil.errToObj(message),
1441
+ });
1442
+ }
1443
+ min(minLength, message) {
1444
+ return this._addCheck({
1445
+ kind: "min",
1446
+ value: minLength,
1447
+ ...errorUtil.errToObj(message),
1448
+ });
1449
+ }
1450
+ max(maxLength, message) {
1451
+ return this._addCheck({
1452
+ kind: "max",
1453
+ value: maxLength,
1454
+ ...errorUtil.errToObj(message),
1455
+ });
1456
+ }
1457
+ length(len, message) {
1458
+ return this._addCheck({
1459
+ kind: "length",
1460
+ value: len,
1461
+ ...errorUtil.errToObj(message),
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Equivalent to `.min(1)`
1466
+ */
1467
+ nonempty(message) {
1468
+ return this.min(1, errorUtil.errToObj(message));
1469
+ }
1470
+ trim() {
1471
+ return new ZodString({
1472
+ ...this._def,
1473
+ checks: [...this._def.checks, { kind: "trim" }],
1474
+ });
1475
+ }
1476
+ toLowerCase() {
1477
+ return new ZodString({
1478
+ ...this._def,
1479
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
1480
+ });
1481
+ }
1482
+ toUpperCase() {
1483
+ return new ZodString({
1484
+ ...this._def,
1485
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
1486
+ });
1487
+ }
1488
+ get isDatetime() {
1489
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1490
+ }
1491
+ get isDate() {
1492
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1493
+ }
1494
+ get isTime() {
1495
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1496
+ }
1497
+ get isDuration() {
1498
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1499
+ }
1500
+ get isEmail() {
1501
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1502
+ }
1503
+ get isURL() {
1504
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1505
+ }
1506
+ get isEmoji() {
1507
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1508
+ }
1509
+ get isUUID() {
1510
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1511
+ }
1512
+ get isNANOID() {
1513
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1514
+ }
1515
+ get isCUID() {
1516
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1517
+ }
1518
+ get isCUID2() {
1519
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1520
+ }
1521
+ get isULID() {
1522
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1523
+ }
1524
+ get isIP() {
1525
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1526
+ }
1527
+ get isCIDR() {
1528
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1529
+ }
1530
+ get isBase64() {
1531
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1532
+ }
1533
+ get isBase64url() {
1534
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1535
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1536
+ }
1537
+ get minLength() {
1538
+ let min = null;
1539
+ for (const ch of this._def.checks) {
1540
+ if (ch.kind === "min") {
1541
+ if (min === null || ch.value > min)
1542
+ min = ch.value;
1543
+ }
1544
+ }
1545
+ return min;
1546
+ }
1547
+ get maxLength() {
1548
+ let max = null;
1549
+ for (const ch of this._def.checks) {
1550
+ if (ch.kind === "max") {
1551
+ if (max === null || ch.value < max)
1552
+ max = ch.value;
1553
+ }
1554
+ }
1555
+ return max;
1556
+ }
1557
+ }
1558
+ ZodString.create = (params) => {
1559
+ return new ZodString({
1560
+ checks: [],
1561
+ typeName: ZodFirstPartyTypeKind.ZodString,
1562
+ coerce: params?.coerce ?? false,
1563
+ ...processCreateParams(params),
1564
+ });
1565
+ };
1566
+ // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
1567
+ function floatSafeRemainder(val, step) {
1568
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1569
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1570
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1571
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1572
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1573
+ return (valInt % stepInt) / 10 ** decCount;
1574
+ }
1575
+ class ZodNumber extends ZodType {
1576
+ constructor() {
1577
+ super(...arguments);
1578
+ this.min = this.gte;
1579
+ this.max = this.lte;
1580
+ this.step = this.multipleOf;
1581
+ }
1582
+ _parse(input) {
1583
+ if (this._def.coerce) {
1584
+ input.data = Number(input.data);
1585
+ }
1586
+ const parsedType = this._getType(input);
1587
+ if (parsedType !== ZodParsedType.number) {
1588
+ const ctx = this._getOrReturnCtx(input);
1589
+ addIssueToContext(ctx, {
1590
+ code: ZodIssueCode.invalid_type,
1591
+ expected: ZodParsedType.number,
1592
+ received: ctx.parsedType,
1593
+ });
1594
+ return INVALID;
1595
+ }
1596
+ let ctx = undefined;
1597
+ const status = new ParseStatus();
1598
+ for (const check of this._def.checks) {
1599
+ if (check.kind === "int") {
1600
+ if (!util.isInteger(input.data)) {
1601
+ ctx = this._getOrReturnCtx(input, ctx);
1602
+ addIssueToContext(ctx, {
1603
+ code: ZodIssueCode.invalid_type,
1604
+ expected: "integer",
1605
+ received: "float",
1606
+ message: check.message,
1607
+ });
1608
+ status.dirty();
1609
+ }
1610
+ }
1611
+ else if (check.kind === "min") {
1612
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1613
+ if (tooSmall) {
1614
+ ctx = this._getOrReturnCtx(input, ctx);
1615
+ addIssueToContext(ctx, {
1616
+ code: ZodIssueCode.too_small,
1617
+ minimum: check.value,
1618
+ type: "number",
1619
+ inclusive: check.inclusive,
1620
+ exact: false,
1621
+ message: check.message,
1622
+ });
1623
+ status.dirty();
1624
+ }
1625
+ }
1626
+ else if (check.kind === "max") {
1627
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1628
+ if (tooBig) {
1629
+ ctx = this._getOrReturnCtx(input, ctx);
1630
+ addIssueToContext(ctx, {
1631
+ code: ZodIssueCode.too_big,
1632
+ maximum: check.value,
1633
+ type: "number",
1634
+ inclusive: check.inclusive,
1635
+ exact: false,
1636
+ message: check.message,
1637
+ });
1638
+ status.dirty();
1639
+ }
1640
+ }
1641
+ else if (check.kind === "multipleOf") {
1642
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1643
+ ctx = this._getOrReturnCtx(input, ctx);
1644
+ addIssueToContext(ctx, {
1645
+ code: ZodIssueCode.not_multiple_of,
1646
+ multipleOf: check.value,
1647
+ message: check.message,
1648
+ });
1649
+ status.dirty();
1650
+ }
1651
+ }
1652
+ else if (check.kind === "finite") {
1653
+ if (!Number.isFinite(input.data)) {
1654
+ ctx = this._getOrReturnCtx(input, ctx);
1655
+ addIssueToContext(ctx, {
1656
+ code: ZodIssueCode.not_finite,
1657
+ message: check.message,
1658
+ });
1659
+ status.dirty();
1660
+ }
1661
+ }
1662
+ else {
1663
+ util.assertNever(check);
1664
+ }
1665
+ }
1666
+ return { status: status.value, value: input.data };
1667
+ }
1668
+ gte(value, message) {
1669
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1670
+ }
1671
+ gt(value, message) {
1672
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1673
+ }
1674
+ lte(value, message) {
1675
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1676
+ }
1677
+ lt(value, message) {
1678
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1679
+ }
1680
+ setLimit(kind, value, inclusive, message) {
1681
+ return new ZodNumber({
1682
+ ...this._def,
1683
+ checks: [
1684
+ ...this._def.checks,
1685
+ {
1686
+ kind,
1687
+ value,
1688
+ inclusive,
1689
+ message: errorUtil.toString(message),
1690
+ },
1691
+ ],
1692
+ });
1693
+ }
1694
+ _addCheck(check) {
1695
+ return new ZodNumber({
1696
+ ...this._def,
1697
+ checks: [...this._def.checks, check],
1698
+ });
1699
+ }
1700
+ int(message) {
1701
+ return this._addCheck({
1702
+ kind: "int",
1703
+ message: errorUtil.toString(message),
1704
+ });
1705
+ }
1706
+ positive(message) {
1707
+ return this._addCheck({
1708
+ kind: "min",
1709
+ value: 0,
1710
+ inclusive: false,
1711
+ message: errorUtil.toString(message),
1712
+ });
1713
+ }
1714
+ negative(message) {
1715
+ return this._addCheck({
1716
+ kind: "max",
1717
+ value: 0,
1718
+ inclusive: false,
1719
+ message: errorUtil.toString(message),
1720
+ });
1721
+ }
1722
+ nonpositive(message) {
1723
+ return this._addCheck({
1724
+ kind: "max",
1725
+ value: 0,
1726
+ inclusive: true,
1727
+ message: errorUtil.toString(message),
1728
+ });
1729
+ }
1730
+ nonnegative(message) {
1731
+ return this._addCheck({
1732
+ kind: "min",
1733
+ value: 0,
1734
+ inclusive: true,
1735
+ message: errorUtil.toString(message),
1736
+ });
1737
+ }
1738
+ multipleOf(value, message) {
1739
+ return this._addCheck({
1740
+ kind: "multipleOf",
1741
+ value: value,
1742
+ message: errorUtil.toString(message),
1743
+ });
1744
+ }
1745
+ finite(message) {
1746
+ return this._addCheck({
1747
+ kind: "finite",
1748
+ message: errorUtil.toString(message),
1749
+ });
1750
+ }
1751
+ safe(message) {
1752
+ return this._addCheck({
1753
+ kind: "min",
1754
+ inclusive: true,
1755
+ value: Number.MIN_SAFE_INTEGER,
1756
+ message: errorUtil.toString(message),
1757
+ })._addCheck({
1758
+ kind: "max",
1759
+ inclusive: true,
1760
+ value: Number.MAX_SAFE_INTEGER,
1761
+ message: errorUtil.toString(message),
1762
+ });
1763
+ }
1764
+ get minValue() {
1765
+ let min = null;
1766
+ for (const ch of this._def.checks) {
1767
+ if (ch.kind === "min") {
1768
+ if (min === null || ch.value > min)
1769
+ min = ch.value;
1770
+ }
1771
+ }
1772
+ return min;
1773
+ }
1774
+ get maxValue() {
1775
+ let max = null;
1776
+ for (const ch of this._def.checks) {
1777
+ if (ch.kind === "max") {
1778
+ if (max === null || ch.value < max)
1779
+ max = ch.value;
1780
+ }
1781
+ }
1782
+ return max;
1783
+ }
1784
+ get isInt() {
1785
+ return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
1786
+ }
1787
+ get isFinite() {
1788
+ let max = null;
1789
+ let min = null;
1790
+ for (const ch of this._def.checks) {
1791
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1792
+ return true;
1793
+ }
1794
+ else if (ch.kind === "min") {
1795
+ if (min === null || ch.value > min)
1796
+ min = ch.value;
1797
+ }
1798
+ else if (ch.kind === "max") {
1799
+ if (max === null || ch.value < max)
1800
+ max = ch.value;
1801
+ }
1802
+ }
1803
+ return Number.isFinite(min) && Number.isFinite(max);
1804
+ }
1805
+ }
1806
+ ZodNumber.create = (params) => {
1807
+ return new ZodNumber({
1808
+ checks: [],
1809
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1810
+ coerce: params?.coerce || false,
1811
+ ...processCreateParams(params),
1812
+ });
1813
+ };
1814
+ class ZodBigInt extends ZodType {
1815
+ constructor() {
1816
+ super(...arguments);
1817
+ this.min = this.gte;
1818
+ this.max = this.lte;
1819
+ }
1820
+ _parse(input) {
1821
+ if (this._def.coerce) {
1822
+ try {
1823
+ input.data = BigInt(input.data);
1824
+ }
1825
+ catch {
1826
+ return this._getInvalidInput(input);
1827
+ }
1828
+ }
1829
+ const parsedType = this._getType(input);
1830
+ if (parsedType !== ZodParsedType.bigint) {
1831
+ return this._getInvalidInput(input);
1832
+ }
1833
+ let ctx = undefined;
1834
+ const status = new ParseStatus();
1835
+ for (const check of this._def.checks) {
1836
+ if (check.kind === "min") {
1837
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1838
+ if (tooSmall) {
1839
+ ctx = this._getOrReturnCtx(input, ctx);
1840
+ addIssueToContext(ctx, {
1841
+ code: ZodIssueCode.too_small,
1842
+ type: "bigint",
1843
+ minimum: check.value,
1844
+ inclusive: check.inclusive,
1845
+ message: check.message,
1846
+ });
1847
+ status.dirty();
1848
+ }
1849
+ }
1850
+ else if (check.kind === "max") {
1851
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1852
+ if (tooBig) {
1853
+ ctx = this._getOrReturnCtx(input, ctx);
1854
+ addIssueToContext(ctx, {
1855
+ code: ZodIssueCode.too_big,
1856
+ type: "bigint",
1857
+ maximum: check.value,
1858
+ inclusive: check.inclusive,
1859
+ message: check.message,
1860
+ });
1861
+ status.dirty();
1862
+ }
1863
+ }
1864
+ else if (check.kind === "multipleOf") {
1865
+ if (input.data % check.value !== BigInt(0)) {
1866
+ ctx = this._getOrReturnCtx(input, ctx);
1867
+ addIssueToContext(ctx, {
1868
+ code: ZodIssueCode.not_multiple_of,
1869
+ multipleOf: check.value,
1870
+ message: check.message,
1871
+ });
1872
+ status.dirty();
1873
+ }
1874
+ }
1875
+ else {
1876
+ util.assertNever(check);
1877
+ }
1878
+ }
1879
+ return { status: status.value, value: input.data };
1880
+ }
1881
+ _getInvalidInput(input) {
1882
+ const ctx = this._getOrReturnCtx(input);
1883
+ addIssueToContext(ctx, {
1884
+ code: ZodIssueCode.invalid_type,
1885
+ expected: ZodParsedType.bigint,
1886
+ received: ctx.parsedType,
1887
+ });
1888
+ return INVALID;
1889
+ }
1890
+ gte(value, message) {
1891
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1892
+ }
1893
+ gt(value, message) {
1894
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1895
+ }
1896
+ lte(value, message) {
1897
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1898
+ }
1899
+ lt(value, message) {
1900
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1901
+ }
1902
+ setLimit(kind, value, inclusive, message) {
1903
+ return new ZodBigInt({
1904
+ ...this._def,
1905
+ checks: [
1906
+ ...this._def.checks,
1907
+ {
1908
+ kind,
1909
+ value,
1910
+ inclusive,
1911
+ message: errorUtil.toString(message),
1912
+ },
1913
+ ],
1914
+ });
1915
+ }
1916
+ _addCheck(check) {
1917
+ return new ZodBigInt({
1918
+ ...this._def,
1919
+ checks: [...this._def.checks, check],
1920
+ });
1921
+ }
1922
+ positive(message) {
1923
+ return this._addCheck({
1924
+ kind: "min",
1925
+ value: BigInt(0),
1926
+ inclusive: false,
1927
+ message: errorUtil.toString(message),
1928
+ });
1929
+ }
1930
+ negative(message) {
1931
+ return this._addCheck({
1932
+ kind: "max",
1933
+ value: BigInt(0),
1934
+ inclusive: false,
1935
+ message: errorUtil.toString(message),
1936
+ });
1937
+ }
1938
+ nonpositive(message) {
1939
+ return this._addCheck({
1940
+ kind: "max",
1941
+ value: BigInt(0),
1942
+ inclusive: true,
1943
+ message: errorUtil.toString(message),
1944
+ });
1945
+ }
1946
+ nonnegative(message) {
1947
+ return this._addCheck({
1948
+ kind: "min",
1949
+ value: BigInt(0),
1950
+ inclusive: true,
1951
+ message: errorUtil.toString(message),
1952
+ });
1953
+ }
1954
+ multipleOf(value, message) {
1955
+ return this._addCheck({
1956
+ kind: "multipleOf",
1957
+ value,
1958
+ message: errorUtil.toString(message),
1959
+ });
1960
+ }
1961
+ get minValue() {
1962
+ let min = null;
1963
+ for (const ch of this._def.checks) {
1964
+ if (ch.kind === "min") {
1965
+ if (min === null || ch.value > min)
1966
+ min = ch.value;
1967
+ }
1968
+ }
1969
+ return min;
1970
+ }
1971
+ get maxValue() {
1972
+ let max = null;
1973
+ for (const ch of this._def.checks) {
1974
+ if (ch.kind === "max") {
1975
+ if (max === null || ch.value < max)
1976
+ max = ch.value;
1977
+ }
1978
+ }
1979
+ return max;
1980
+ }
1981
+ }
1982
+ ZodBigInt.create = (params) => {
1983
+ return new ZodBigInt({
1984
+ checks: [],
1985
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1986
+ coerce: params?.coerce ?? false,
1987
+ ...processCreateParams(params),
1988
+ });
1989
+ };
1990
+ class ZodBoolean extends ZodType {
1991
+ _parse(input) {
1992
+ if (this._def.coerce) {
1993
+ input.data = Boolean(input.data);
1994
+ }
1995
+ const parsedType = this._getType(input);
1996
+ if (parsedType !== ZodParsedType.boolean) {
1997
+ const ctx = this._getOrReturnCtx(input);
1998
+ addIssueToContext(ctx, {
1999
+ code: ZodIssueCode.invalid_type,
2000
+ expected: ZodParsedType.boolean,
2001
+ received: ctx.parsedType,
2002
+ });
2003
+ return INVALID;
2004
+ }
2005
+ return OK(input.data);
2006
+ }
2007
+ }
2008
+ ZodBoolean.create = (params) => {
2009
+ return new ZodBoolean({
2010
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2011
+ coerce: params?.coerce || false,
2012
+ ...processCreateParams(params),
2013
+ });
2014
+ };
2015
+ class ZodDate extends ZodType {
2016
+ _parse(input) {
2017
+ if (this._def.coerce) {
2018
+ input.data = new Date(input.data);
2019
+ }
2020
+ const parsedType = this._getType(input);
2021
+ if (parsedType !== ZodParsedType.date) {
2022
+ const ctx = this._getOrReturnCtx(input);
2023
+ addIssueToContext(ctx, {
2024
+ code: ZodIssueCode.invalid_type,
2025
+ expected: ZodParsedType.date,
2026
+ received: ctx.parsedType,
2027
+ });
2028
+ return INVALID;
2029
+ }
2030
+ if (Number.isNaN(input.data.getTime())) {
2031
+ const ctx = this._getOrReturnCtx(input);
2032
+ addIssueToContext(ctx, {
2033
+ code: ZodIssueCode.invalid_date,
2034
+ });
2035
+ return INVALID;
2036
+ }
2037
+ const status = new ParseStatus();
2038
+ let ctx = undefined;
2039
+ for (const check of this._def.checks) {
2040
+ if (check.kind === "min") {
2041
+ if (input.data.getTime() < check.value) {
2042
+ ctx = this._getOrReturnCtx(input, ctx);
2043
+ addIssueToContext(ctx, {
2044
+ code: ZodIssueCode.too_small,
2045
+ message: check.message,
2046
+ inclusive: true,
2047
+ exact: false,
2048
+ minimum: check.value,
2049
+ type: "date",
2050
+ });
2051
+ status.dirty();
2052
+ }
2053
+ }
2054
+ else if (check.kind === "max") {
2055
+ if (input.data.getTime() > check.value) {
2056
+ ctx = this._getOrReturnCtx(input, ctx);
2057
+ addIssueToContext(ctx, {
2058
+ code: ZodIssueCode.too_big,
2059
+ message: check.message,
2060
+ inclusive: true,
2061
+ exact: false,
2062
+ maximum: check.value,
2063
+ type: "date",
2064
+ });
2065
+ status.dirty();
2066
+ }
2067
+ }
2068
+ else {
2069
+ util.assertNever(check);
2070
+ }
2071
+ }
2072
+ return {
2073
+ status: status.value,
2074
+ value: new Date(input.data.getTime()),
2075
+ };
2076
+ }
2077
+ _addCheck(check) {
2078
+ return new ZodDate({
2079
+ ...this._def,
2080
+ checks: [...this._def.checks, check],
2081
+ });
2082
+ }
2083
+ min(minDate, message) {
2084
+ return this._addCheck({
2085
+ kind: "min",
2086
+ value: minDate.getTime(),
2087
+ message: errorUtil.toString(message),
2088
+ });
2089
+ }
2090
+ max(maxDate, message) {
2091
+ return this._addCheck({
2092
+ kind: "max",
2093
+ value: maxDate.getTime(),
2094
+ message: errorUtil.toString(message),
2095
+ });
2096
+ }
2097
+ get minDate() {
2098
+ let min = null;
2099
+ for (const ch of this._def.checks) {
2100
+ if (ch.kind === "min") {
2101
+ if (min === null || ch.value > min)
2102
+ min = ch.value;
2103
+ }
2104
+ }
2105
+ return min != null ? new Date(min) : null;
2106
+ }
2107
+ get maxDate() {
2108
+ let max = null;
2109
+ for (const ch of this._def.checks) {
2110
+ if (ch.kind === "max") {
2111
+ if (max === null || ch.value < max)
2112
+ max = ch.value;
2113
+ }
2114
+ }
2115
+ return max != null ? new Date(max) : null;
2116
+ }
2117
+ }
2118
+ ZodDate.create = (params) => {
2119
+ return new ZodDate({
2120
+ checks: [],
2121
+ coerce: params?.coerce || false,
2122
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2123
+ ...processCreateParams(params),
2124
+ });
2125
+ };
2126
+ class ZodSymbol extends ZodType {
2127
+ _parse(input) {
2128
+ const parsedType = this._getType(input);
2129
+ if (parsedType !== ZodParsedType.symbol) {
2130
+ const ctx = this._getOrReturnCtx(input);
2131
+ addIssueToContext(ctx, {
2132
+ code: ZodIssueCode.invalid_type,
2133
+ expected: ZodParsedType.symbol,
2134
+ received: ctx.parsedType,
2135
+ });
2136
+ return INVALID;
2137
+ }
2138
+ return OK(input.data);
2139
+ }
2140
+ }
2141
+ ZodSymbol.create = (params) => {
2142
+ return new ZodSymbol({
2143
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2144
+ ...processCreateParams(params),
2145
+ });
2146
+ };
2147
+ class ZodUndefined extends ZodType {
2148
+ _parse(input) {
2149
+ const parsedType = this._getType(input);
2150
+ if (parsedType !== ZodParsedType.undefined) {
2151
+ const ctx = this._getOrReturnCtx(input);
2152
+ addIssueToContext(ctx, {
2153
+ code: ZodIssueCode.invalid_type,
2154
+ expected: ZodParsedType.undefined,
2155
+ received: ctx.parsedType,
2156
+ });
2157
+ return INVALID;
2158
+ }
2159
+ return OK(input.data);
2160
+ }
2161
+ }
2162
+ ZodUndefined.create = (params) => {
2163
+ return new ZodUndefined({
2164
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2165
+ ...processCreateParams(params),
2166
+ });
2167
+ };
2168
+ class ZodNull extends ZodType {
2169
+ _parse(input) {
2170
+ const parsedType = this._getType(input);
2171
+ if (parsedType !== ZodParsedType.null) {
2172
+ const ctx = this._getOrReturnCtx(input);
2173
+ addIssueToContext(ctx, {
2174
+ code: ZodIssueCode.invalid_type,
2175
+ expected: ZodParsedType.null,
2176
+ received: ctx.parsedType,
2177
+ });
2178
+ return INVALID;
2179
+ }
2180
+ return OK(input.data);
2181
+ }
2182
+ }
2183
+ ZodNull.create = (params) => {
2184
+ return new ZodNull({
2185
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2186
+ ...processCreateParams(params),
2187
+ });
2188
+ };
2189
+ class ZodAny extends ZodType {
2190
+ constructor() {
2191
+ super(...arguments);
2192
+ // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
2193
+ this._any = true;
2194
+ }
2195
+ _parse(input) {
2196
+ return OK(input.data);
2197
+ }
2198
+ }
2199
+ ZodAny.create = (params) => {
2200
+ return new ZodAny({
2201
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2202
+ ...processCreateParams(params),
2203
+ });
2204
+ };
2205
+ class ZodUnknown extends ZodType {
2206
+ constructor() {
2207
+ super(...arguments);
2208
+ // required
2209
+ this._unknown = true;
2210
+ }
2211
+ _parse(input) {
2212
+ return OK(input.data);
2213
+ }
2214
+ }
2215
+ ZodUnknown.create = (params) => {
2216
+ return new ZodUnknown({
2217
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2218
+ ...processCreateParams(params),
2219
+ });
2220
+ };
2221
+ class ZodNever extends ZodType {
2222
+ _parse(input) {
2223
+ const ctx = this._getOrReturnCtx(input);
2224
+ addIssueToContext(ctx, {
2225
+ code: ZodIssueCode.invalid_type,
2226
+ expected: ZodParsedType.never,
2227
+ received: ctx.parsedType,
2228
+ });
2229
+ return INVALID;
2230
+ }
2231
+ }
2232
+ ZodNever.create = (params) => {
2233
+ return new ZodNever({
2234
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2235
+ ...processCreateParams(params),
2236
+ });
2237
+ };
2238
+ class ZodVoid extends ZodType {
2239
+ _parse(input) {
2240
+ const parsedType = this._getType(input);
2241
+ if (parsedType !== ZodParsedType.undefined) {
2242
+ const ctx = this._getOrReturnCtx(input);
2243
+ addIssueToContext(ctx, {
2244
+ code: ZodIssueCode.invalid_type,
2245
+ expected: ZodParsedType.void,
2246
+ received: ctx.parsedType,
2247
+ });
2248
+ return INVALID;
2249
+ }
2250
+ return OK(input.data);
2251
+ }
2252
+ }
2253
+ ZodVoid.create = (params) => {
2254
+ return new ZodVoid({
2255
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2256
+ ...processCreateParams(params),
2257
+ });
2258
+ };
2259
+ class ZodArray extends ZodType {
2260
+ _parse(input) {
2261
+ const { ctx, status } = this._processInputParams(input);
2262
+ const def = this._def;
2263
+ if (ctx.parsedType !== ZodParsedType.array) {
2264
+ addIssueToContext(ctx, {
2265
+ code: ZodIssueCode.invalid_type,
2266
+ expected: ZodParsedType.array,
2267
+ received: ctx.parsedType,
2268
+ });
2269
+ return INVALID;
2270
+ }
2271
+ if (def.exactLength !== null) {
2272
+ const tooBig = ctx.data.length > def.exactLength.value;
2273
+ const tooSmall = ctx.data.length < def.exactLength.value;
2274
+ if (tooBig || tooSmall) {
2275
+ addIssueToContext(ctx, {
2276
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2277
+ minimum: (tooSmall ? def.exactLength.value : undefined),
2278
+ maximum: (tooBig ? def.exactLength.value : undefined),
2279
+ type: "array",
2280
+ inclusive: true,
2281
+ exact: true,
2282
+ message: def.exactLength.message,
2283
+ });
2284
+ status.dirty();
2285
+ }
2286
+ }
2287
+ if (def.minLength !== null) {
2288
+ if (ctx.data.length < def.minLength.value) {
2289
+ addIssueToContext(ctx, {
2290
+ code: ZodIssueCode.too_small,
2291
+ minimum: def.minLength.value,
2292
+ type: "array",
2293
+ inclusive: true,
2294
+ exact: false,
2295
+ message: def.minLength.message,
2296
+ });
2297
+ status.dirty();
2298
+ }
2299
+ }
2300
+ if (def.maxLength !== null) {
2301
+ if (ctx.data.length > def.maxLength.value) {
2302
+ addIssueToContext(ctx, {
2303
+ code: ZodIssueCode.too_big,
2304
+ maximum: def.maxLength.value,
2305
+ type: "array",
2306
+ inclusive: true,
2307
+ exact: false,
2308
+ message: def.maxLength.message,
2309
+ });
2310
+ status.dirty();
2311
+ }
2312
+ }
2313
+ if (ctx.common.async) {
2314
+ return Promise.all([...ctx.data].map((item, i) => {
2315
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2316
+ })).then((result) => {
2317
+ return ParseStatus.mergeArray(status, result);
2318
+ });
2319
+ }
2320
+ const result = [...ctx.data].map((item, i) => {
2321
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2322
+ });
2323
+ return ParseStatus.mergeArray(status, result);
2324
+ }
2325
+ get element() {
2326
+ return this._def.type;
2327
+ }
2328
+ min(minLength, message) {
2329
+ return new ZodArray({
2330
+ ...this._def,
2331
+ minLength: { value: minLength, message: errorUtil.toString(message) },
2332
+ });
2333
+ }
2334
+ max(maxLength, message) {
2335
+ return new ZodArray({
2336
+ ...this._def,
2337
+ maxLength: { value: maxLength, message: errorUtil.toString(message) },
2338
+ });
2339
+ }
2340
+ length(len, message) {
2341
+ return new ZodArray({
2342
+ ...this._def,
2343
+ exactLength: { value: len, message: errorUtil.toString(message) },
2344
+ });
2345
+ }
2346
+ nonempty(message) {
2347
+ return this.min(1, message);
2348
+ }
2349
+ }
2350
+ ZodArray.create = (schema, params) => {
2351
+ return new ZodArray({
2352
+ type: schema,
2353
+ minLength: null,
2354
+ maxLength: null,
2355
+ exactLength: null,
2356
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2357
+ ...processCreateParams(params),
2358
+ });
2359
+ };
2360
+ function deepPartialify(schema) {
2361
+ if (schema instanceof ZodObject) {
2362
+ const newShape = {};
2363
+ for (const key in schema.shape) {
2364
+ const fieldSchema = schema.shape[key];
2365
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2366
+ }
2367
+ return new ZodObject({
2368
+ ...schema._def,
2369
+ shape: () => newShape,
2370
+ });
2371
+ }
2372
+ else if (schema instanceof ZodArray) {
2373
+ return new ZodArray({
2374
+ ...schema._def,
2375
+ type: deepPartialify(schema.element),
2376
+ });
2377
+ }
2378
+ else if (schema instanceof ZodOptional) {
2379
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2380
+ }
2381
+ else if (schema instanceof ZodNullable) {
2382
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2383
+ }
2384
+ else if (schema instanceof ZodTuple) {
2385
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2386
+ }
2387
+ else {
2388
+ return schema;
2389
+ }
2390
+ }
2391
+ class ZodObject extends ZodType {
2392
+ constructor() {
2393
+ super(...arguments);
2394
+ this._cached = null;
2395
+ /**
2396
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2397
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
2398
+ */
2399
+ this.nonstrict = this.passthrough;
2400
+ // extend<
2401
+ // Augmentation extends ZodRawShape,
2402
+ // NewOutput extends util.flatten<{
2403
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2404
+ // ? Augmentation[k]["_output"]
2405
+ // : k extends keyof Output
2406
+ // ? Output[k]
2407
+ // : never;
2408
+ // }>,
2409
+ // NewInput extends util.flatten<{
2410
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2411
+ // ? Augmentation[k]["_input"]
2412
+ // : k extends keyof Input
2413
+ // ? Input[k]
2414
+ // : never;
2415
+ // }>
2416
+ // >(
2417
+ // augmentation: Augmentation
2418
+ // ): ZodObject<
2419
+ // extendShape<T, Augmentation>,
2420
+ // UnknownKeys,
2421
+ // Catchall,
2422
+ // NewOutput,
2423
+ // NewInput
2424
+ // > {
2425
+ // return new ZodObject({
2426
+ // ...this._def,
2427
+ // shape: () => ({
2428
+ // ...this._def.shape(),
2429
+ // ...augmentation,
2430
+ // }),
2431
+ // }) as any;
2432
+ // }
2433
+ /**
2434
+ * @deprecated Use `.extend` instead
2435
+ * */
2436
+ this.augment = this.extend;
2437
+ }
2438
+ _getCached() {
2439
+ if (this._cached !== null)
2440
+ return this._cached;
2441
+ const shape = this._def.shape();
2442
+ const keys = util.objectKeys(shape);
2443
+ this._cached = { shape, keys };
2444
+ return this._cached;
2445
+ }
2446
+ _parse(input) {
2447
+ const parsedType = this._getType(input);
2448
+ if (parsedType !== ZodParsedType.object) {
2449
+ const ctx = this._getOrReturnCtx(input);
2450
+ addIssueToContext(ctx, {
2451
+ code: ZodIssueCode.invalid_type,
2452
+ expected: ZodParsedType.object,
2453
+ received: ctx.parsedType,
2454
+ });
2455
+ return INVALID;
2456
+ }
2457
+ const { status, ctx } = this._processInputParams(input);
2458
+ const { shape, keys: shapeKeys } = this._getCached();
2459
+ const extraKeys = [];
2460
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2461
+ for (const key in ctx.data) {
2462
+ if (!shapeKeys.includes(key)) {
2463
+ extraKeys.push(key);
2464
+ }
2465
+ }
2466
+ }
2467
+ const pairs = [];
2468
+ for (const key of shapeKeys) {
2469
+ const keyValidator = shape[key];
2470
+ const value = ctx.data[key];
2471
+ pairs.push({
2472
+ key: { status: "valid", value: key },
2473
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2474
+ alwaysSet: key in ctx.data,
2475
+ });
2476
+ }
2477
+ if (this._def.catchall instanceof ZodNever) {
2478
+ const unknownKeys = this._def.unknownKeys;
2479
+ if (unknownKeys === "passthrough") {
2480
+ for (const key of extraKeys) {
2481
+ pairs.push({
2482
+ key: { status: "valid", value: key },
2483
+ value: { status: "valid", value: ctx.data[key] },
2484
+ });
2485
+ }
2486
+ }
2487
+ else if (unknownKeys === "strict") {
2488
+ if (extraKeys.length > 0) {
2489
+ addIssueToContext(ctx, {
2490
+ code: ZodIssueCode.unrecognized_keys,
2491
+ keys: extraKeys,
2492
+ });
2493
+ status.dirty();
2494
+ }
2495
+ }
2496
+ else if (unknownKeys === "strip") ;
2497
+ else {
2498
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2499
+ }
2500
+ }
2501
+ else {
2502
+ // run catchall validation
2503
+ const catchall = this._def.catchall;
2504
+ for (const key of extraKeys) {
2505
+ const value = ctx.data[key];
2506
+ pairs.push({
2507
+ key: { status: "valid", value: key },
2508
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
2509
+ ),
2510
+ alwaysSet: key in ctx.data,
2511
+ });
2512
+ }
2513
+ }
2514
+ if (ctx.common.async) {
2515
+ return Promise.resolve()
2516
+ .then(async () => {
2517
+ const syncPairs = [];
2518
+ for (const pair of pairs) {
2519
+ const key = await pair.key;
2520
+ const value = await pair.value;
2521
+ syncPairs.push({
2522
+ key,
2523
+ value,
2524
+ alwaysSet: pair.alwaysSet,
2525
+ });
2526
+ }
2527
+ return syncPairs;
2528
+ })
2529
+ .then((syncPairs) => {
2530
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2531
+ });
2532
+ }
2533
+ else {
2534
+ return ParseStatus.mergeObjectSync(status, pairs);
2535
+ }
2536
+ }
2537
+ get shape() {
2538
+ return this._def.shape();
2539
+ }
2540
+ strict(message) {
2541
+ errorUtil.errToObj;
2542
+ return new ZodObject({
2543
+ ...this._def,
2544
+ unknownKeys: "strict",
2545
+ ...(message !== undefined
2546
+ ? {
2547
+ errorMap: (issue, ctx) => {
2548
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2549
+ if (issue.code === "unrecognized_keys")
2550
+ return {
2551
+ message: errorUtil.errToObj(message).message ?? defaultError,
2552
+ };
2553
+ return {
2554
+ message: defaultError,
2555
+ };
2556
+ },
2557
+ }
2558
+ : {}),
2559
+ });
2560
+ }
2561
+ strip() {
2562
+ return new ZodObject({
2563
+ ...this._def,
2564
+ unknownKeys: "strip",
2565
+ });
2566
+ }
2567
+ passthrough() {
2568
+ return new ZodObject({
2569
+ ...this._def,
2570
+ unknownKeys: "passthrough",
2571
+ });
2572
+ }
2573
+ // const AugmentFactory =
2574
+ // <Def extends ZodObjectDef>(def: Def) =>
2575
+ // <Augmentation extends ZodRawShape>(
2576
+ // augmentation: Augmentation
2577
+ // ): ZodObject<
2578
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2579
+ // Def["unknownKeys"],
2580
+ // Def["catchall"]
2581
+ // > => {
2582
+ // return new ZodObject({
2583
+ // ...def,
2584
+ // shape: () => ({
2585
+ // ...def.shape(),
2586
+ // ...augmentation,
2587
+ // }),
2588
+ // }) as any;
2589
+ // };
2590
+ extend(augmentation) {
2591
+ return new ZodObject({
2592
+ ...this._def,
2593
+ shape: () => ({
2594
+ ...this._def.shape(),
2595
+ ...augmentation,
2596
+ }),
2597
+ });
2598
+ }
2599
+ /**
2600
+ * Prior to zod@1.0.12 there was a bug in the
2601
+ * inferred type of merged objects. Please
2602
+ * upgrade if you are experiencing issues.
2603
+ */
2604
+ merge(merging) {
2605
+ const merged = new ZodObject({
2606
+ unknownKeys: merging._def.unknownKeys,
2607
+ catchall: merging._def.catchall,
2608
+ shape: () => ({
2609
+ ...this._def.shape(),
2610
+ ...merging._def.shape(),
2611
+ }),
2612
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2613
+ });
2614
+ return merged;
2615
+ }
2616
+ // merge<
2617
+ // Incoming extends AnyZodObject,
2618
+ // Augmentation extends Incoming["shape"],
2619
+ // NewOutput extends {
2620
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2621
+ // ? Augmentation[k]["_output"]
2622
+ // : k extends keyof Output
2623
+ // ? Output[k]
2624
+ // : never;
2625
+ // },
2626
+ // NewInput extends {
2627
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2628
+ // ? Augmentation[k]["_input"]
2629
+ // : k extends keyof Input
2630
+ // ? Input[k]
2631
+ // : never;
2632
+ // }
2633
+ // >(
2634
+ // merging: Incoming
2635
+ // ): ZodObject<
2636
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2637
+ // Incoming["_def"]["unknownKeys"],
2638
+ // Incoming["_def"]["catchall"],
2639
+ // NewOutput,
2640
+ // NewInput
2641
+ // > {
2642
+ // const merged: any = new ZodObject({
2643
+ // unknownKeys: merging._def.unknownKeys,
2644
+ // catchall: merging._def.catchall,
2645
+ // shape: () =>
2646
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2647
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2648
+ // }) as any;
2649
+ // return merged;
2650
+ // }
2651
+ setKey(key, schema) {
2652
+ return this.augment({ [key]: schema });
2653
+ }
2654
+ // merge<Incoming extends AnyZodObject>(
2655
+ // merging: Incoming
2656
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2657
+ // ZodObject<
2658
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2659
+ // Incoming["_def"]["unknownKeys"],
2660
+ // Incoming["_def"]["catchall"]
2661
+ // > {
2662
+ // // const mergedShape = objectUtil.mergeShapes(
2663
+ // // this._def.shape(),
2664
+ // // merging._def.shape()
2665
+ // // );
2666
+ // const merged: any = new ZodObject({
2667
+ // unknownKeys: merging._def.unknownKeys,
2668
+ // catchall: merging._def.catchall,
2669
+ // shape: () =>
2670
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2671
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2672
+ // }) as any;
2673
+ // return merged;
2674
+ // }
2675
+ catchall(index) {
2676
+ return new ZodObject({
2677
+ ...this._def,
2678
+ catchall: index,
2679
+ });
2680
+ }
2681
+ pick(mask) {
2682
+ const shape = {};
2683
+ for (const key of util.objectKeys(mask)) {
2684
+ if (mask[key] && this.shape[key]) {
2685
+ shape[key] = this.shape[key];
2686
+ }
2687
+ }
2688
+ return new ZodObject({
2689
+ ...this._def,
2690
+ shape: () => shape,
2691
+ });
2692
+ }
2693
+ omit(mask) {
2694
+ const shape = {};
2695
+ for (const key of util.objectKeys(this.shape)) {
2696
+ if (!mask[key]) {
2697
+ shape[key] = this.shape[key];
2698
+ }
2699
+ }
2700
+ return new ZodObject({
2701
+ ...this._def,
2702
+ shape: () => shape,
2703
+ });
2704
+ }
2705
+ /**
2706
+ * @deprecated
2707
+ */
2708
+ deepPartial() {
2709
+ return deepPartialify(this);
2710
+ }
2711
+ partial(mask) {
2712
+ const newShape = {};
2713
+ for (const key of util.objectKeys(this.shape)) {
2714
+ const fieldSchema = this.shape[key];
2715
+ if (mask && !mask[key]) {
2716
+ newShape[key] = fieldSchema;
2717
+ }
2718
+ else {
2719
+ newShape[key] = fieldSchema.optional();
2720
+ }
2721
+ }
2722
+ return new ZodObject({
2723
+ ...this._def,
2724
+ shape: () => newShape,
2725
+ });
2726
+ }
2727
+ required(mask) {
2728
+ const newShape = {};
2729
+ for (const key of util.objectKeys(this.shape)) {
2730
+ if (mask && !mask[key]) {
2731
+ newShape[key] = this.shape[key];
2732
+ }
2733
+ else {
2734
+ const fieldSchema = this.shape[key];
2735
+ let newField = fieldSchema;
2736
+ while (newField instanceof ZodOptional) {
2737
+ newField = newField._def.innerType;
2738
+ }
2739
+ newShape[key] = newField;
2740
+ }
2741
+ }
2742
+ return new ZodObject({
2743
+ ...this._def,
2744
+ shape: () => newShape,
2745
+ });
2746
+ }
2747
+ keyof() {
2748
+ return createZodEnum(util.objectKeys(this.shape));
2749
+ }
2750
+ }
2751
+ ZodObject.create = (shape, params) => {
2752
+ return new ZodObject({
2753
+ shape: () => shape,
2754
+ unknownKeys: "strip",
2755
+ catchall: ZodNever.create(),
2756
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2757
+ ...processCreateParams(params),
2758
+ });
2759
+ };
2760
+ ZodObject.strictCreate = (shape, params) => {
2761
+ return new ZodObject({
2762
+ shape: () => shape,
2763
+ unknownKeys: "strict",
2764
+ catchall: ZodNever.create(),
2765
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2766
+ ...processCreateParams(params),
2767
+ });
2768
+ };
2769
+ ZodObject.lazycreate = (shape, params) => {
2770
+ return new ZodObject({
2771
+ shape,
2772
+ unknownKeys: "strip",
2773
+ catchall: ZodNever.create(),
2774
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2775
+ ...processCreateParams(params),
2776
+ });
2777
+ };
2778
+ class ZodUnion extends ZodType {
2779
+ _parse(input) {
2780
+ const { ctx } = this._processInputParams(input);
2781
+ const options = this._def.options;
2782
+ function handleResults(results) {
2783
+ // return first issue-free validation if it exists
2784
+ for (const result of results) {
2785
+ if (result.result.status === "valid") {
2786
+ return result.result;
2787
+ }
2788
+ }
2789
+ for (const result of results) {
2790
+ if (result.result.status === "dirty") {
2791
+ // add issues from dirty option
2792
+ ctx.common.issues.push(...result.ctx.common.issues);
2793
+ return result.result;
2794
+ }
2795
+ }
2796
+ // return invalid
2797
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2798
+ addIssueToContext(ctx, {
2799
+ code: ZodIssueCode.invalid_union,
2800
+ unionErrors,
2801
+ });
2802
+ return INVALID;
2803
+ }
2804
+ if (ctx.common.async) {
2805
+ return Promise.all(options.map(async (option) => {
2806
+ const childCtx = {
2807
+ ...ctx,
2808
+ common: {
2809
+ ...ctx.common,
2810
+ issues: [],
2811
+ },
2812
+ parent: null,
2813
+ };
2814
+ return {
2815
+ result: await option._parseAsync({
2816
+ data: ctx.data,
2817
+ path: ctx.path,
2818
+ parent: childCtx,
2819
+ }),
2820
+ ctx: childCtx,
2821
+ };
2822
+ })).then(handleResults);
2823
+ }
2824
+ else {
2825
+ let dirty = undefined;
2826
+ const issues = [];
2827
+ for (const option of options) {
2828
+ const childCtx = {
2829
+ ...ctx,
2830
+ common: {
2831
+ ...ctx.common,
2832
+ issues: [],
2833
+ },
2834
+ parent: null,
2835
+ };
2836
+ const result = option._parseSync({
2837
+ data: ctx.data,
2838
+ path: ctx.path,
2839
+ parent: childCtx,
2840
+ });
2841
+ if (result.status === "valid") {
2842
+ return result;
2843
+ }
2844
+ else if (result.status === "dirty" && !dirty) {
2845
+ dirty = { result, ctx: childCtx };
2846
+ }
2847
+ if (childCtx.common.issues.length) {
2848
+ issues.push(childCtx.common.issues);
2849
+ }
2850
+ }
2851
+ if (dirty) {
2852
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2853
+ return dirty.result;
2854
+ }
2855
+ const unionErrors = issues.map((issues) => new ZodError(issues));
2856
+ addIssueToContext(ctx, {
2857
+ code: ZodIssueCode.invalid_union,
2858
+ unionErrors,
2859
+ });
2860
+ return INVALID;
2861
+ }
2862
+ }
2863
+ get options() {
2864
+ return this._def.options;
2865
+ }
2866
+ }
2867
+ ZodUnion.create = (types, params) => {
2868
+ return new ZodUnion({
2869
+ options: types,
2870
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2871
+ ...processCreateParams(params),
2872
+ });
2873
+ };
2874
+ function mergeValues(a, b) {
2875
+ const aType = getParsedType(a);
2876
+ const bType = getParsedType(b);
2877
+ if (a === b) {
2878
+ return { valid: true, data: a };
2879
+ }
2880
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2881
+ const bKeys = util.objectKeys(b);
2882
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2883
+ const newObj = { ...a, ...b };
2884
+ for (const key of sharedKeys) {
2885
+ const sharedValue = mergeValues(a[key], b[key]);
2886
+ if (!sharedValue.valid) {
2887
+ return { valid: false };
2888
+ }
2889
+ newObj[key] = sharedValue.data;
2890
+ }
2891
+ return { valid: true, data: newObj };
2892
+ }
2893
+ else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2894
+ if (a.length !== b.length) {
2895
+ return { valid: false };
2896
+ }
2897
+ const newArray = [];
2898
+ for (let index = 0; index < a.length; index++) {
2899
+ const itemA = a[index];
2900
+ const itemB = b[index];
2901
+ const sharedValue = mergeValues(itemA, itemB);
2902
+ if (!sharedValue.valid) {
2903
+ return { valid: false };
2904
+ }
2905
+ newArray.push(sharedValue.data);
2906
+ }
2907
+ return { valid: true, data: newArray };
2908
+ }
2909
+ else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2910
+ return { valid: true, data: a };
2911
+ }
2912
+ else {
2913
+ return { valid: false };
2914
+ }
2915
+ }
2916
+ class ZodIntersection extends ZodType {
2917
+ _parse(input) {
2918
+ const { status, ctx } = this._processInputParams(input);
2919
+ const handleParsed = (parsedLeft, parsedRight) => {
2920
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2921
+ return INVALID;
2922
+ }
2923
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2924
+ if (!merged.valid) {
2925
+ addIssueToContext(ctx, {
2926
+ code: ZodIssueCode.invalid_intersection_types,
2927
+ });
2928
+ return INVALID;
2929
+ }
2930
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2931
+ status.dirty();
2932
+ }
2933
+ return { status: status.value, value: merged.data };
2934
+ };
2935
+ if (ctx.common.async) {
2936
+ return Promise.all([
2937
+ this._def.left._parseAsync({
2938
+ data: ctx.data,
2939
+ path: ctx.path,
2940
+ parent: ctx,
2941
+ }),
2942
+ this._def.right._parseAsync({
2943
+ data: ctx.data,
2944
+ path: ctx.path,
2945
+ parent: ctx,
2946
+ }),
2947
+ ]).then(([left, right]) => handleParsed(left, right));
2948
+ }
2949
+ else {
2950
+ return handleParsed(this._def.left._parseSync({
2951
+ data: ctx.data,
2952
+ path: ctx.path,
2953
+ parent: ctx,
2954
+ }), this._def.right._parseSync({
2955
+ data: ctx.data,
2956
+ path: ctx.path,
2957
+ parent: ctx,
2958
+ }));
2959
+ }
2960
+ }
2961
+ }
2962
+ ZodIntersection.create = (left, right, params) => {
2963
+ return new ZodIntersection({
2964
+ left: left,
2965
+ right: right,
2966
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2967
+ ...processCreateParams(params),
2968
+ });
2969
+ };
2970
+ // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
2971
+ class ZodTuple extends ZodType {
2972
+ _parse(input) {
2973
+ const { status, ctx } = this._processInputParams(input);
2974
+ if (ctx.parsedType !== ZodParsedType.array) {
2975
+ addIssueToContext(ctx, {
2976
+ code: ZodIssueCode.invalid_type,
2977
+ expected: ZodParsedType.array,
2978
+ received: ctx.parsedType,
2979
+ });
2980
+ return INVALID;
2981
+ }
2982
+ if (ctx.data.length < this._def.items.length) {
2983
+ addIssueToContext(ctx, {
2984
+ code: ZodIssueCode.too_small,
2985
+ minimum: this._def.items.length,
2986
+ inclusive: true,
2987
+ exact: false,
2988
+ type: "array",
2989
+ });
2990
+ return INVALID;
2991
+ }
2992
+ const rest = this._def.rest;
2993
+ if (!rest && ctx.data.length > this._def.items.length) {
2994
+ addIssueToContext(ctx, {
2995
+ code: ZodIssueCode.too_big,
2996
+ maximum: this._def.items.length,
2997
+ inclusive: true,
2998
+ exact: false,
2999
+ type: "array",
3000
+ });
3001
+ status.dirty();
3002
+ }
3003
+ const items = [...ctx.data]
3004
+ .map((item, itemIndex) => {
3005
+ const schema = this._def.items[itemIndex] || this._def.rest;
3006
+ if (!schema)
3007
+ return null;
3008
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3009
+ })
3010
+ .filter((x) => !!x); // filter nulls
3011
+ if (ctx.common.async) {
3012
+ return Promise.all(items).then((results) => {
3013
+ return ParseStatus.mergeArray(status, results);
3014
+ });
3015
+ }
3016
+ else {
3017
+ return ParseStatus.mergeArray(status, items);
3018
+ }
3019
+ }
3020
+ get items() {
3021
+ return this._def.items;
3022
+ }
3023
+ rest(rest) {
3024
+ return new ZodTuple({
3025
+ ...this._def,
3026
+ rest,
3027
+ });
3028
+ }
3029
+ }
3030
+ ZodTuple.create = (schemas, params) => {
3031
+ if (!Array.isArray(schemas)) {
3032
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3033
+ }
3034
+ return new ZodTuple({
3035
+ items: schemas,
3036
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3037
+ rest: null,
3038
+ ...processCreateParams(params),
3039
+ });
3040
+ };
3041
+ class ZodRecord extends ZodType {
3042
+ get keySchema() {
3043
+ return this._def.keyType;
3044
+ }
3045
+ get valueSchema() {
3046
+ return this._def.valueType;
3047
+ }
3048
+ _parse(input) {
3049
+ const { status, ctx } = this._processInputParams(input);
3050
+ if (ctx.parsedType !== ZodParsedType.object) {
3051
+ addIssueToContext(ctx, {
3052
+ code: ZodIssueCode.invalid_type,
3053
+ expected: ZodParsedType.object,
3054
+ received: ctx.parsedType,
3055
+ });
3056
+ return INVALID;
3057
+ }
3058
+ const pairs = [];
3059
+ const keyType = this._def.keyType;
3060
+ const valueType = this._def.valueType;
3061
+ for (const key in ctx.data) {
3062
+ pairs.push({
3063
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3064
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3065
+ alwaysSet: key in ctx.data,
3066
+ });
3067
+ }
3068
+ if (ctx.common.async) {
3069
+ return ParseStatus.mergeObjectAsync(status, pairs);
3070
+ }
3071
+ else {
3072
+ return ParseStatus.mergeObjectSync(status, pairs);
3073
+ }
3074
+ }
3075
+ get element() {
3076
+ return this._def.valueType;
3077
+ }
3078
+ static create(first, second, third) {
3079
+ if (second instanceof ZodType) {
3080
+ return new ZodRecord({
3081
+ keyType: first,
3082
+ valueType: second,
3083
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3084
+ ...processCreateParams(third),
3085
+ });
3086
+ }
3087
+ return new ZodRecord({
3088
+ keyType: ZodString.create(),
3089
+ valueType: first,
3090
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3091
+ ...processCreateParams(second),
3092
+ });
3093
+ }
3094
+ }
3095
+ class ZodMap extends ZodType {
3096
+ get keySchema() {
3097
+ return this._def.keyType;
3098
+ }
3099
+ get valueSchema() {
3100
+ return this._def.valueType;
3101
+ }
3102
+ _parse(input) {
3103
+ const { status, ctx } = this._processInputParams(input);
3104
+ if (ctx.parsedType !== ZodParsedType.map) {
3105
+ addIssueToContext(ctx, {
3106
+ code: ZodIssueCode.invalid_type,
3107
+ expected: ZodParsedType.map,
3108
+ received: ctx.parsedType,
3109
+ });
3110
+ return INVALID;
3111
+ }
3112
+ const keyType = this._def.keyType;
3113
+ const valueType = this._def.valueType;
3114
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3115
+ return {
3116
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3117
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
3118
+ };
3119
+ });
3120
+ if (ctx.common.async) {
3121
+ const finalMap = new Map();
3122
+ return Promise.resolve().then(async () => {
3123
+ for (const pair of pairs) {
3124
+ const key = await pair.key;
3125
+ const value = await pair.value;
3126
+ if (key.status === "aborted" || value.status === "aborted") {
3127
+ return INVALID;
3128
+ }
3129
+ if (key.status === "dirty" || value.status === "dirty") {
3130
+ status.dirty();
3131
+ }
3132
+ finalMap.set(key.value, value.value);
3133
+ }
3134
+ return { status: status.value, value: finalMap };
3135
+ });
3136
+ }
3137
+ else {
3138
+ const finalMap = new Map();
3139
+ for (const pair of pairs) {
3140
+ const key = pair.key;
3141
+ const value = pair.value;
3142
+ if (key.status === "aborted" || value.status === "aborted") {
3143
+ return INVALID;
3144
+ }
3145
+ if (key.status === "dirty" || value.status === "dirty") {
3146
+ status.dirty();
3147
+ }
3148
+ finalMap.set(key.value, value.value);
3149
+ }
3150
+ return { status: status.value, value: finalMap };
3151
+ }
3152
+ }
3153
+ }
3154
+ ZodMap.create = (keyType, valueType, params) => {
3155
+ return new ZodMap({
3156
+ valueType,
3157
+ keyType,
3158
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3159
+ ...processCreateParams(params),
3160
+ });
3161
+ };
3162
+ class ZodSet extends ZodType {
3163
+ _parse(input) {
3164
+ const { status, ctx } = this._processInputParams(input);
3165
+ if (ctx.parsedType !== ZodParsedType.set) {
3166
+ addIssueToContext(ctx, {
3167
+ code: ZodIssueCode.invalid_type,
3168
+ expected: ZodParsedType.set,
3169
+ received: ctx.parsedType,
3170
+ });
3171
+ return INVALID;
3172
+ }
3173
+ const def = this._def;
3174
+ if (def.minSize !== null) {
3175
+ if (ctx.data.size < def.minSize.value) {
3176
+ addIssueToContext(ctx, {
3177
+ code: ZodIssueCode.too_small,
3178
+ minimum: def.minSize.value,
3179
+ type: "set",
3180
+ inclusive: true,
3181
+ exact: false,
3182
+ message: def.minSize.message,
3183
+ });
3184
+ status.dirty();
3185
+ }
3186
+ }
3187
+ if (def.maxSize !== null) {
3188
+ if (ctx.data.size > def.maxSize.value) {
3189
+ addIssueToContext(ctx, {
3190
+ code: ZodIssueCode.too_big,
3191
+ maximum: def.maxSize.value,
3192
+ type: "set",
3193
+ inclusive: true,
3194
+ exact: false,
3195
+ message: def.maxSize.message,
3196
+ });
3197
+ status.dirty();
3198
+ }
3199
+ }
3200
+ const valueType = this._def.valueType;
3201
+ function finalizeSet(elements) {
3202
+ const parsedSet = new Set();
3203
+ for (const element of elements) {
3204
+ if (element.status === "aborted")
3205
+ return INVALID;
3206
+ if (element.status === "dirty")
3207
+ status.dirty();
3208
+ parsedSet.add(element.value);
3209
+ }
3210
+ return { status: status.value, value: parsedSet };
3211
+ }
3212
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3213
+ if (ctx.common.async) {
3214
+ return Promise.all(elements).then((elements) => finalizeSet(elements));
3215
+ }
3216
+ else {
3217
+ return finalizeSet(elements);
3218
+ }
3219
+ }
3220
+ min(minSize, message) {
3221
+ return new ZodSet({
3222
+ ...this._def,
3223
+ minSize: { value: minSize, message: errorUtil.toString(message) },
3224
+ });
3225
+ }
3226
+ max(maxSize, message) {
3227
+ return new ZodSet({
3228
+ ...this._def,
3229
+ maxSize: { value: maxSize, message: errorUtil.toString(message) },
3230
+ });
3231
+ }
3232
+ size(size, message) {
3233
+ return this.min(size, message).max(size, message);
3234
+ }
3235
+ nonempty(message) {
3236
+ return this.min(1, message);
3237
+ }
3238
+ }
3239
+ ZodSet.create = (valueType, params) => {
3240
+ return new ZodSet({
3241
+ valueType,
3242
+ minSize: null,
3243
+ maxSize: null,
3244
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3245
+ ...processCreateParams(params),
3246
+ });
3247
+ };
3248
+ class ZodLazy extends ZodType {
3249
+ get schema() {
3250
+ return this._def.getter();
3251
+ }
3252
+ _parse(input) {
3253
+ const { ctx } = this._processInputParams(input);
3254
+ const lazySchema = this._def.getter();
3255
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3256
+ }
3257
+ }
3258
+ ZodLazy.create = (getter, params) => {
3259
+ return new ZodLazy({
3260
+ getter: getter,
3261
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3262
+ ...processCreateParams(params),
3263
+ });
3264
+ };
3265
+ class ZodLiteral extends ZodType {
3266
+ _parse(input) {
3267
+ if (input.data !== this._def.value) {
3268
+ const ctx = this._getOrReturnCtx(input);
3269
+ addIssueToContext(ctx, {
3270
+ received: ctx.data,
3271
+ code: ZodIssueCode.invalid_literal,
3272
+ expected: this._def.value,
3273
+ });
3274
+ return INVALID;
3275
+ }
3276
+ return { status: "valid", value: input.data };
3277
+ }
3278
+ get value() {
3279
+ return this._def.value;
3280
+ }
3281
+ }
3282
+ ZodLiteral.create = (value, params) => {
3283
+ return new ZodLiteral({
3284
+ value: value,
3285
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3286
+ ...processCreateParams(params),
3287
+ });
3288
+ };
3289
+ function createZodEnum(values, params) {
3290
+ return new ZodEnum({
3291
+ values,
3292
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3293
+ ...processCreateParams(params),
3294
+ });
3295
+ }
3296
+ class ZodEnum extends ZodType {
3297
+ _parse(input) {
3298
+ if (typeof input.data !== "string") {
3299
+ const ctx = this._getOrReturnCtx(input);
3300
+ const expectedValues = this._def.values;
3301
+ addIssueToContext(ctx, {
3302
+ expected: util.joinValues(expectedValues),
3303
+ received: ctx.parsedType,
3304
+ code: ZodIssueCode.invalid_type,
3305
+ });
3306
+ return INVALID;
3307
+ }
3308
+ if (!this._cache) {
3309
+ this._cache = new Set(this._def.values);
3310
+ }
3311
+ if (!this._cache.has(input.data)) {
3312
+ const ctx = this._getOrReturnCtx(input);
3313
+ const expectedValues = this._def.values;
3314
+ addIssueToContext(ctx, {
3315
+ received: ctx.data,
3316
+ code: ZodIssueCode.invalid_enum_value,
3317
+ options: expectedValues,
3318
+ });
3319
+ return INVALID;
3320
+ }
3321
+ return OK(input.data);
3322
+ }
3323
+ get options() {
3324
+ return this._def.values;
3325
+ }
3326
+ get enum() {
3327
+ const enumValues = {};
3328
+ for (const val of this._def.values) {
3329
+ enumValues[val] = val;
3330
+ }
3331
+ return enumValues;
3332
+ }
3333
+ get Values() {
3334
+ const enumValues = {};
3335
+ for (const val of this._def.values) {
3336
+ enumValues[val] = val;
3337
+ }
3338
+ return enumValues;
3339
+ }
3340
+ get Enum() {
3341
+ const enumValues = {};
3342
+ for (const val of this._def.values) {
3343
+ enumValues[val] = val;
3344
+ }
3345
+ return enumValues;
3346
+ }
3347
+ extract(values, newDef = this._def) {
3348
+ return ZodEnum.create(values, {
3349
+ ...this._def,
3350
+ ...newDef,
3351
+ });
3352
+ }
3353
+ exclude(values, newDef = this._def) {
3354
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3355
+ ...this._def,
3356
+ ...newDef,
3357
+ });
3358
+ }
3359
+ }
3360
+ ZodEnum.create = createZodEnum;
3361
+ class ZodNativeEnum extends ZodType {
3362
+ _parse(input) {
3363
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3364
+ const ctx = this._getOrReturnCtx(input);
3365
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3366
+ const expectedValues = util.objectValues(nativeEnumValues);
3367
+ addIssueToContext(ctx, {
3368
+ expected: util.joinValues(expectedValues),
3369
+ received: ctx.parsedType,
3370
+ code: ZodIssueCode.invalid_type,
3371
+ });
3372
+ return INVALID;
3373
+ }
3374
+ if (!this._cache) {
3375
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3376
+ }
3377
+ if (!this._cache.has(input.data)) {
3378
+ const expectedValues = util.objectValues(nativeEnumValues);
3379
+ addIssueToContext(ctx, {
3380
+ received: ctx.data,
3381
+ code: ZodIssueCode.invalid_enum_value,
3382
+ options: expectedValues,
3383
+ });
3384
+ return INVALID;
3385
+ }
3386
+ return OK(input.data);
3387
+ }
3388
+ get enum() {
3389
+ return this._def.values;
3390
+ }
3391
+ }
3392
+ ZodNativeEnum.create = (values, params) => {
3393
+ return new ZodNativeEnum({
3394
+ values: values,
3395
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3396
+ ...processCreateParams(params),
3397
+ });
3398
+ };
3399
+ class ZodPromise extends ZodType {
3400
+ unwrap() {
3401
+ return this._def.type;
3402
+ }
3403
+ _parse(input) {
3404
+ const { ctx } = this._processInputParams(input);
3405
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3406
+ addIssueToContext(ctx, {
3407
+ code: ZodIssueCode.invalid_type,
3408
+ expected: ZodParsedType.promise,
3409
+ received: ctx.parsedType,
3410
+ });
3411
+ return INVALID;
3412
+ }
3413
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3414
+ return OK(promisified.then((data) => {
3415
+ return this._def.type.parseAsync(data, {
3416
+ path: ctx.path,
3417
+ errorMap: ctx.common.contextualErrorMap,
3418
+ });
3419
+ }));
3420
+ }
3421
+ }
3422
+ ZodPromise.create = (schema, params) => {
3423
+ return new ZodPromise({
3424
+ type: schema,
3425
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3426
+ ...processCreateParams(params),
3427
+ });
3428
+ };
3429
+ class ZodEffects extends ZodType {
3430
+ innerType() {
3431
+ return this._def.schema;
3432
+ }
3433
+ sourceType() {
3434
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
3435
+ ? this._def.schema.sourceType()
3436
+ : this._def.schema;
3437
+ }
3438
+ _parse(input) {
3439
+ const { status, ctx } = this._processInputParams(input);
3440
+ const effect = this._def.effect || null;
3441
+ const checkCtx = {
3442
+ addIssue: (arg) => {
3443
+ addIssueToContext(ctx, arg);
3444
+ if (arg.fatal) {
3445
+ status.abort();
3446
+ }
3447
+ else {
3448
+ status.dirty();
3449
+ }
3450
+ },
3451
+ get path() {
3452
+ return ctx.path;
3453
+ },
3454
+ };
3455
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3456
+ if (effect.type === "preprocess") {
3457
+ const processed = effect.transform(ctx.data, checkCtx);
3458
+ if (ctx.common.async) {
3459
+ return Promise.resolve(processed).then(async (processed) => {
3460
+ if (status.value === "aborted")
3461
+ return INVALID;
3462
+ const result = await this._def.schema._parseAsync({
3463
+ data: processed,
3464
+ path: ctx.path,
3465
+ parent: ctx,
3466
+ });
3467
+ if (result.status === "aborted")
3468
+ return INVALID;
3469
+ if (result.status === "dirty")
3470
+ return DIRTY(result.value);
3471
+ if (status.value === "dirty")
3472
+ return DIRTY(result.value);
3473
+ return result;
3474
+ });
3475
+ }
3476
+ else {
3477
+ if (status.value === "aborted")
3478
+ return INVALID;
3479
+ const result = this._def.schema._parseSync({
3480
+ data: processed,
3481
+ path: ctx.path,
3482
+ parent: ctx,
3483
+ });
3484
+ if (result.status === "aborted")
3485
+ return INVALID;
3486
+ if (result.status === "dirty")
3487
+ return DIRTY(result.value);
3488
+ if (status.value === "dirty")
3489
+ return DIRTY(result.value);
3490
+ return result;
3491
+ }
3492
+ }
3493
+ if (effect.type === "refinement") {
3494
+ const executeRefinement = (acc) => {
3495
+ const result = effect.refinement(acc, checkCtx);
3496
+ if (ctx.common.async) {
3497
+ return Promise.resolve(result);
3498
+ }
3499
+ if (result instanceof Promise) {
3500
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3501
+ }
3502
+ return acc;
3503
+ };
3504
+ if (ctx.common.async === false) {
3505
+ const inner = this._def.schema._parseSync({
3506
+ data: ctx.data,
3507
+ path: ctx.path,
3508
+ parent: ctx,
3509
+ });
3510
+ if (inner.status === "aborted")
3511
+ return INVALID;
3512
+ if (inner.status === "dirty")
3513
+ status.dirty();
3514
+ // return value is ignored
3515
+ executeRefinement(inner.value);
3516
+ return { status: status.value, value: inner.value };
3517
+ }
3518
+ else {
3519
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3520
+ if (inner.status === "aborted")
3521
+ return INVALID;
3522
+ if (inner.status === "dirty")
3523
+ status.dirty();
3524
+ return executeRefinement(inner.value).then(() => {
3525
+ return { status: status.value, value: inner.value };
3526
+ });
3527
+ });
3528
+ }
3529
+ }
3530
+ if (effect.type === "transform") {
3531
+ if (ctx.common.async === false) {
3532
+ const base = this._def.schema._parseSync({
3533
+ data: ctx.data,
3534
+ path: ctx.path,
3535
+ parent: ctx,
3536
+ });
3537
+ if (!isValid(base))
3538
+ return INVALID;
3539
+ const result = effect.transform(base.value, checkCtx);
3540
+ if (result instanceof Promise) {
3541
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3542
+ }
3543
+ return { status: status.value, value: result };
3544
+ }
3545
+ else {
3546
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3547
+ if (!isValid(base))
3548
+ return INVALID;
3549
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3550
+ status: status.value,
3551
+ value: result,
3552
+ }));
3553
+ });
3554
+ }
3555
+ }
3556
+ util.assertNever(effect);
3557
+ }
3558
+ }
3559
+ ZodEffects.create = (schema, effect, params) => {
3560
+ return new ZodEffects({
3561
+ schema,
3562
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3563
+ effect,
3564
+ ...processCreateParams(params),
3565
+ });
3566
+ };
3567
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3568
+ return new ZodEffects({
3569
+ schema,
3570
+ effect: { type: "preprocess", transform: preprocess },
3571
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3572
+ ...processCreateParams(params),
3573
+ });
3574
+ };
3575
+ class ZodOptional extends ZodType {
3576
+ _parse(input) {
3577
+ const parsedType = this._getType(input);
3578
+ if (parsedType === ZodParsedType.undefined) {
3579
+ return OK(undefined);
3580
+ }
3581
+ return this._def.innerType._parse(input);
3582
+ }
3583
+ unwrap() {
3584
+ return this._def.innerType;
3585
+ }
3586
+ }
3587
+ ZodOptional.create = (type, params) => {
3588
+ return new ZodOptional({
3589
+ innerType: type,
3590
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3591
+ ...processCreateParams(params),
3592
+ });
3593
+ };
3594
+ class ZodNullable extends ZodType {
3595
+ _parse(input) {
3596
+ const parsedType = this._getType(input);
3597
+ if (parsedType === ZodParsedType.null) {
3598
+ return OK(null);
3599
+ }
3600
+ return this._def.innerType._parse(input);
3601
+ }
3602
+ unwrap() {
3603
+ return this._def.innerType;
3604
+ }
3605
+ }
3606
+ ZodNullable.create = (type, params) => {
3607
+ return new ZodNullable({
3608
+ innerType: type,
3609
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3610
+ ...processCreateParams(params),
3611
+ });
3612
+ };
3613
+ class ZodDefault extends ZodType {
3614
+ _parse(input) {
3615
+ const { ctx } = this._processInputParams(input);
3616
+ let data = ctx.data;
3617
+ if (ctx.parsedType === ZodParsedType.undefined) {
3618
+ data = this._def.defaultValue();
3619
+ }
3620
+ return this._def.innerType._parse({
3621
+ data,
3622
+ path: ctx.path,
3623
+ parent: ctx,
3624
+ });
3625
+ }
3626
+ removeDefault() {
3627
+ return this._def.innerType;
3628
+ }
3629
+ }
3630
+ ZodDefault.create = (type, params) => {
3631
+ return new ZodDefault({
3632
+ innerType: type,
3633
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3634
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3635
+ ...processCreateParams(params),
3636
+ });
3637
+ };
3638
+ class ZodCatch extends ZodType {
3639
+ _parse(input) {
3640
+ const { ctx } = this._processInputParams(input);
3641
+ // newCtx is used to not collect issues from inner types in ctx
3642
+ const newCtx = {
3643
+ ...ctx,
3644
+ common: {
3645
+ ...ctx.common,
3646
+ issues: [],
3647
+ },
3648
+ };
3649
+ const result = this._def.innerType._parse({
3650
+ data: newCtx.data,
3651
+ path: newCtx.path,
3652
+ parent: {
3653
+ ...newCtx,
3654
+ },
3655
+ });
3656
+ if (isAsync(result)) {
3657
+ return result.then((result) => {
3658
+ return {
3659
+ status: "valid",
3660
+ value: result.status === "valid"
3661
+ ? result.value
3662
+ : this._def.catchValue({
3663
+ get error() {
3664
+ return new ZodError(newCtx.common.issues);
3665
+ },
3666
+ input: newCtx.data,
3667
+ }),
3668
+ };
3669
+ });
3670
+ }
3671
+ else {
3672
+ return {
3673
+ status: "valid",
3674
+ value: result.status === "valid"
3675
+ ? result.value
3676
+ : this._def.catchValue({
3677
+ get error() {
3678
+ return new ZodError(newCtx.common.issues);
3679
+ },
3680
+ input: newCtx.data,
3681
+ }),
3682
+ };
3683
+ }
3684
+ }
3685
+ removeCatch() {
3686
+ return this._def.innerType;
3687
+ }
3688
+ }
3689
+ ZodCatch.create = (type, params) => {
3690
+ return new ZodCatch({
3691
+ innerType: type,
3692
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3693
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3694
+ ...processCreateParams(params),
3695
+ });
3696
+ };
3697
+ class ZodNaN extends ZodType {
3698
+ _parse(input) {
3699
+ const parsedType = this._getType(input);
3700
+ if (parsedType !== ZodParsedType.nan) {
3701
+ const ctx = this._getOrReturnCtx(input);
3702
+ addIssueToContext(ctx, {
3703
+ code: ZodIssueCode.invalid_type,
3704
+ expected: ZodParsedType.nan,
3705
+ received: ctx.parsedType,
3706
+ });
3707
+ return INVALID;
3708
+ }
3709
+ return { status: "valid", value: input.data };
3710
+ }
3711
+ }
3712
+ ZodNaN.create = (params) => {
3713
+ return new ZodNaN({
3714
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3715
+ ...processCreateParams(params),
3716
+ });
3717
+ };
3718
+ class ZodBranded extends ZodType {
3719
+ _parse(input) {
3720
+ const { ctx } = this._processInputParams(input);
3721
+ const data = ctx.data;
3722
+ return this._def.type._parse({
3723
+ data,
3724
+ path: ctx.path,
3725
+ parent: ctx,
3726
+ });
3727
+ }
3728
+ unwrap() {
3729
+ return this._def.type;
3730
+ }
3731
+ }
3732
+ class ZodPipeline extends ZodType {
3733
+ _parse(input) {
3734
+ const { status, ctx } = this._processInputParams(input);
3735
+ if (ctx.common.async) {
3736
+ const handleAsync = async () => {
3737
+ const inResult = await this._def.in._parseAsync({
3738
+ data: ctx.data,
3739
+ path: ctx.path,
3740
+ parent: ctx,
3741
+ });
3742
+ if (inResult.status === "aborted")
3743
+ return INVALID;
3744
+ if (inResult.status === "dirty") {
3745
+ status.dirty();
3746
+ return DIRTY(inResult.value);
3747
+ }
3748
+ else {
3749
+ return this._def.out._parseAsync({
3750
+ data: inResult.value,
3751
+ path: ctx.path,
3752
+ parent: ctx,
3753
+ });
3754
+ }
3755
+ };
3756
+ return handleAsync();
3757
+ }
3758
+ else {
3759
+ const inResult = this._def.in._parseSync({
3760
+ data: ctx.data,
3761
+ path: ctx.path,
3762
+ parent: ctx,
3763
+ });
3764
+ if (inResult.status === "aborted")
3765
+ return INVALID;
3766
+ if (inResult.status === "dirty") {
3767
+ status.dirty();
3768
+ return {
3769
+ status: "dirty",
3770
+ value: inResult.value,
3771
+ };
3772
+ }
3773
+ else {
3774
+ return this._def.out._parseSync({
3775
+ data: inResult.value,
3776
+ path: ctx.path,
3777
+ parent: ctx,
3778
+ });
3779
+ }
3780
+ }
3781
+ }
3782
+ static create(a, b) {
3783
+ return new ZodPipeline({
3784
+ in: a,
3785
+ out: b,
3786
+ typeName: ZodFirstPartyTypeKind.ZodPipeline,
3787
+ });
3788
+ }
3789
+ }
3790
+ class ZodReadonly extends ZodType {
3791
+ _parse(input) {
3792
+ const result = this._def.innerType._parse(input);
3793
+ const freeze = (data) => {
3794
+ if (isValid(data)) {
3795
+ data.value = Object.freeze(data.value);
3796
+ }
3797
+ return data;
3798
+ };
3799
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3800
+ }
3801
+ unwrap() {
3802
+ return this._def.innerType;
3803
+ }
3804
+ }
3805
+ ZodReadonly.create = (type, params) => {
3806
+ return new ZodReadonly({
3807
+ innerType: type,
3808
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
3809
+ ...processCreateParams(params),
3810
+ });
3811
+ };
3812
+ var ZodFirstPartyTypeKind;
3813
+ (function (ZodFirstPartyTypeKind) {
3814
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
3815
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
3816
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
3817
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
3818
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
3819
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
3820
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
3821
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
3822
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
3823
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
3824
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
3825
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
3826
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
3827
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
3828
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
3829
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
3830
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3831
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
3832
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
3833
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
3834
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
3835
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
3836
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
3837
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
3838
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
3839
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
3840
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
3841
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
3842
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
3843
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
3844
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
3845
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
3846
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
3847
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
3848
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
3849
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
3850
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3851
+ const stringType = ZodString.create;
3852
+ const numberType = ZodNumber.create;
3853
+ const booleanType = ZodBoolean.create;
3854
+ const unknownType = ZodUnknown.create;
3855
+ ZodNever.create;
3856
+ const arrayType = ZodArray.create;
3857
+ const objectType = ZodObject.create;
3858
+ ZodUnion.create;
3859
+ ZodIntersection.create;
3860
+ const tupleType = ZodTuple.create;
3861
+ const recordType = ZodRecord.create;
3862
+ const literalType = ZodLiteral.create;
3863
+ const enumType = ZodEnum.create;
3864
+ ZodPromise.create;
3865
+ ZodOptional.create;
3866
+ ZodNullable.create;
3867
+
3868
+ // src/schema.ts
3869
+ var shareOptionsSchema = objectType({
3870
+ showAiTranscript: booleanType().optional(),
3871
+ allowEditing: booleanType().optional()
3872
+ });
3873
+ var fileContentV10MetadataSchema = objectType({
3874
+ version: literalType("10"),
3875
+ shareOptions: shareOptionsSchema.optional()
3876
+ });
3877
+ var definitionV2Schema = objectType({
3878
+ kind: stringType(),
3879
+ id: stringType()
3880
+ }).passthrough();
3881
+ var slideV2Schema = objectType({
3882
+ definitions: arrayType(definitionV2Schema),
3883
+ uvarMap: arrayType(tupleType([stringType(), numberType()])),
3884
+ styleSheet: recordType(stringType(), unknownType()),
3885
+ doc: arrayType(unknownType())
3886
+ });
3887
+ var seedChatMessageSchema = objectType({
3888
+ id: stringType(),
3889
+ role: enumType(["user", "assistant", "system"]),
3890
+ timestamp: numberType()
3891
+ }).passthrough();
3892
+ objectType({
3893
+ slides: arrayType(slideV2Schema),
3894
+ messages: arrayType(seedChatMessageSchema),
3895
+ metadata: fileContentV10MetadataSchema
3896
+ });
3897
+
3
3898
  /**
4
3899
  * 大角几何内嵌画板 SDK
5
3900
  * 绑定 DOM 容器,自动创建 iframe 并封装 postMessage 通信
6
3901
  */
7
3902
  /** SDK 版本号,构建时由 rollup 注入 */
8
- const VERSION = '1.1.0';
3903
+ const VERSION = '1.2.1';
9
3904
  const DEFAULT_EMBED_BASE = 'https://dajiaoai.com';
10
3905
  let requestIdCounter = 0;
11
3906
  function generateRequestId() {
12
3907
  return `req-${Date.now()}-${++requestIdCounter}`;
13
3908
  }
14
- class AlgeoSdkError extends Error {
15
- constructor(message, code, details) {
16
- super(message);
17
- this.code = code;
18
- this.details = details;
19
- this.name = 'AlgeoSdkError';
20
- }
21
- }
22
3909
  function isResponseMessage(msg) {
23
3910
  return (typeof msg === 'object' &&
24
3911
  msg !== null &&
@@ -57,7 +3944,7 @@ class AlgeoSdk {
57
3944
  }
58
3945
  async init(options = {}) {
59
3946
  if (this.iframe) {
60
- throw new AlgeoSdkError('请勿多次调用init方法。', 'BAD_REQUEST');
3947
+ throw new AlgeoError('请勿多次调用init方法。', EMBED_ERROR_CODES.BAD_REQUEST);
61
3948
  }
62
3949
  return new Promise((resolve, reject) => {
63
3950
  const baseUrl = options.baseUrl ?? DEFAULT_EMBED_BASE;
@@ -94,7 +3981,7 @@ class AlgeoSdk {
94
3981
  }
95
3982
  else {
96
3983
  const err = data.error;
97
- pending.reject(new AlgeoSdkError(err.message, err.code, err.details));
3984
+ pending.reject(new AlgeoError(err?.message ?? '未知错误', err?.code ?? EMBED_ERROR_CODES.UNKNOWN_ERROR, err?.details));
98
3985
  }
99
3986
  }
100
3987
  }
@@ -107,7 +3994,7 @@ class AlgeoSdk {
107
3994
  const msg = { type, requestId, ...payload };
108
3995
  return new Promise((resolve, reject) => {
109
3996
  if (!this._ready) {
110
- reject(new AlgeoSdkError('iframe 未加载完成', 'IFRAME_NOT_READY'));
3997
+ reject(new AlgeoError('iframe 未加载完成', EMBED_ERROR_CODES.IFRAME_NOT_READY));
111
3998
  }
112
3999
  this.pending.set(requestId, {
113
4000
  resolve: resolve,
@@ -116,7 +4003,7 @@ class AlgeoSdk {
116
4003
  const target = this.iframe?.contentWindow;
117
4004
  if (!target) {
118
4005
  this.pending.delete(requestId);
119
- reject(new AlgeoSdkError('iframe 未加载完成', 'IFRAME_NOT_READY'));
4006
+ reject(new AlgeoError('iframe 未加载完成', EMBED_ERROR_CODES.IFRAME_NOT_READY));
120
4007
  return;
121
4008
  }
122
4009
  target.postMessage(msg, '*');
@@ -124,7 +4011,7 @@ class AlgeoSdk {
124
4011
  setTimeout(() => {
125
4012
  if (this.pending.has(requestId)) {
126
4013
  this.pending.delete(requestId);
127
- reject(new AlgeoSdkError('请求超时', 'TIMEOUT'));
4014
+ reject(new AlgeoError('请求超时', EMBED_ERROR_CODES.TIMEOUT));
128
4015
  }
129
4016
  }, 30000);
130
4017
  });
@@ -168,7 +4055,7 @@ class AlgeoSdk {
168
4055
  window.removeEventListener('message', this.messageHandler);
169
4056
  this.messageHandler = undefined;
170
4057
  }
171
- this.pending.forEach(({ reject }) => reject(new AlgeoSdkError('SDK 已销毁', 'DESTROYED')));
4058
+ this.pending.forEach(({ reject }) => reject(new AlgeoError('SDK 已销毁', EMBED_ERROR_CODES.DESTROYED)));
172
4059
  this.pending.clear();
173
4060
  if (this.iframe?.parentNode) {
174
4061
  this.iframe.parentNode.removeChild(this.iframe);
@@ -176,6 +4063,7 @@ class AlgeoSdk {
176
4063
  }
177
4064
  }
178
4065
 
4066
+ exports.AlgeoError = AlgeoError;
179
4067
  exports.AlgeoSdk = AlgeoSdk;
180
- exports.AlgeoSdkError = AlgeoSdkError;
4068
+ exports.EMBED_ERROR_CODES = EMBED_ERROR_CODES;
181
4069
  exports.VERSION = VERSION;