@automattic/mcp-wordpress-remote 0.2.9 → 0.2.10

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