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