audible-api-ts 0.1.0

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