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