hono-ban 0.2.0 → 0.2.4

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