@paykit-sdk/monnify 1.0.0 → 1.2.0

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