shipflow 0.1.1 → 0.3.0

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