hono-ban 0.2.0 → 0.2.4

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