@mastra/mcp 0.4.2-alpha.1 → 0.4.2-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MastraBase } from '@mastra/core/base';
2
2
  import { createTool } from '@mastra/core/tools';
3
- import { jsonSchemaToModel } from '@mastra/core/utils';
3
+ import { resolveSerializedZodOutput as resolveSerializedZodOutput$1, isZodType as isZodType$1 } from '@mastra/core/utils';
4
4
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
5
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
6
6
  import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js';
@@ -20,924 +20,1561 @@ import * as path from 'path';
20
20
 
21
21
  // src/client.ts
22
22
 
23
- // ../../node_modules/.pnpm/zod@3.24.3/node_modules/zod/lib/index.mjs
24
- var util;
25
- (function(util2) {
26
- util2.assertEqual = (val) => val;
27
- function assertIs(_arg) {
23
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseAnyOf.js
24
+ var parseAnyOf = (schema, refs) => {
25
+ return schema.anyOf.length ? schema.anyOf.length === 1 ? parseSchema(schema.anyOf[0], {
26
+ ...refs,
27
+ path: [...refs.path, "anyOf", 0]
28
+ }) : `z.union([${schema.anyOf.map((schema2, i) => parseSchema(schema2, { ...refs, path: [...refs.path, "anyOf", i] })).join(", ")}])` : `z.any()`;
29
+ };
30
+
31
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseBoolean.js
32
+ var parseBoolean = (_schema) => {
33
+ return "z.boolean()";
34
+ };
35
+
36
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseDefault.js
37
+ var parseDefault = (_schema) => {
38
+ return "z.any()";
39
+ };
40
+
41
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseMultipleType.js
42
+ var parseMultipleType = (schema, refs) => {
43
+ return `z.union([${schema.type.map((type) => parseSchema({ ...schema, type }, refs)).join(", ")}])`;
44
+ };
45
+
46
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNot.js
47
+ var parseNot = (schema, refs) => {
48
+ return `z.any().refine((value) => !${parseSchema(schema.not, {
49
+ ...refs,
50
+ path: [...refs.path, "not"]
51
+ })}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
52
+ };
53
+
54
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNull.js
55
+ var parseNull = (_schema) => {
56
+ return "z.null()";
57
+ };
58
+
59
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/half.js
60
+ var half = (arr) => {
61
+ return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
62
+ };
63
+
64
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseAllOf.js
65
+ var originalIndex = Symbol("Original index");
66
+ var ensureOriginalIndex = (arr) => {
67
+ let newArr = [];
68
+ for (let i = 0; i < arr.length; i++) {
69
+ const item = arr[i];
70
+ if (typeof item === "boolean") {
71
+ newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
72
+ } else if (originalIndex in item) {
73
+ return arr;
74
+ } else {
75
+ newArr.push({ ...item, [originalIndex]: i });
76
+ }
28
77
  }
29
- util2.assertIs = assertIs;
30
- function assertNever(_x) {
31
- throw new Error();
78
+ return newArr;
79
+ };
80
+ function parseAllOf(schema, refs) {
81
+ if (schema.allOf.length === 0) {
82
+ return "z.never()";
83
+ } else if (schema.allOf.length === 1) {
84
+ const item = schema.allOf[0];
85
+ return parseSchema(item, {
86
+ ...refs,
87
+ path: [...refs.path, "allOf", item[originalIndex]]
88
+ });
89
+ } else {
90
+ const [left, right] = half(ensureOriginalIndex(schema.allOf));
91
+ return `z.intersection(${parseAllOf({ allOf: left }, refs)}, ${parseAllOf({
92
+ allOf: right
93
+ }, refs)})`;
32
94
  }
33
- util2.assertNever = assertNever;
34
- util2.arrayToEnum = (items) => {
35
- const obj = {};
36
- for (const item of items) {
37
- obj[item] = item;
38
- }
39
- return obj;
40
- };
41
- util2.getValidEnumValues = (obj) => {
42
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
43
- const filtered = {};
44
- for (const k of validKeys) {
45
- filtered[k] = obj[k];
95
+ }
96
+
97
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/withMessage.js
98
+ function withMessage(schema, key, get) {
99
+ const value = schema[key];
100
+ let r = "";
101
+ if (value !== void 0) {
102
+ const got = get({ value, json: JSON.stringify(value) });
103
+ if (got) {
104
+ const opener = got[0];
105
+ const prefix = got.length === 3 ? got[1] : "";
106
+ const closer = got.length === 3 ? got[2] : got[1];
107
+ r += opener;
108
+ if (schema.errorMessage?.[key] !== void 0) {
109
+ r += prefix + JSON.stringify(schema.errorMessage[key]);
110
+ }
111
+ r += closer;
46
112
  }
47
- return util2.objectValues(filtered);
48
- };
49
- util2.objectValues = (obj) => {
50
- return util2.objectKeys(obj).map(function(e) {
51
- return obj[e];
113
+ }
114
+ return r;
115
+ }
116
+
117
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseArray.js
118
+ var parseArray = (schema, refs) => {
119
+ if (Array.isArray(schema.items)) {
120
+ return `z.tuple([${schema.items.map((v, i) => parseSchema(v, { ...refs, path: [...refs.path, "items", i] }))}])`;
121
+ }
122
+ let r = !schema.items ? "z.array(z.any())" : `z.array(${parseSchema(schema.items, {
123
+ ...refs,
124
+ path: [...refs.path, "items"]
125
+ })})`;
126
+ r += withMessage(schema, "minItems", ({ json }) => [
127
+ `.min(${json}`,
128
+ ", ",
129
+ ")"
130
+ ]);
131
+ r += withMessage(schema, "maxItems", ({ json }) => [
132
+ `.max(${json}`,
133
+ ", ",
134
+ ")"
135
+ ]);
136
+ return r;
137
+ };
138
+
139
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseConst.js
140
+ var parseConst = (schema) => {
141
+ return `z.literal(${JSON.stringify(schema.const)})`;
142
+ };
143
+
144
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseEnum.js
145
+ var parseEnum = (schema) => {
146
+ if (schema.enum.length === 0) {
147
+ return "z.never()";
148
+ } else if (schema.enum.length === 1) {
149
+ return `z.literal(${JSON.stringify(schema.enum[0])})`;
150
+ } else if (schema.enum.every((x) => typeof x === "string")) {
151
+ return `z.enum([${schema.enum.map((x) => JSON.stringify(x))}])`;
152
+ } else {
153
+ return `z.union([${schema.enum.map((x) => `z.literal(${JSON.stringify(x)})`).join(", ")}])`;
154
+ }
155
+ };
156
+
157
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseIfThenElse.js
158
+ var parseIfThenElse = (schema, refs) => {
159
+ const $if = parseSchema(schema.if, { ...refs, path: [...refs.path, "if"] });
160
+ const $then = parseSchema(schema.then, {
161
+ ...refs,
162
+ path: [...refs.path, "then"]
163
+ });
164
+ const $else = parseSchema(schema.else, {
165
+ ...refs,
166
+ path: [...refs.path, "else"]
167
+ });
168
+ return `z.union([${$then}, ${$else}]).superRefine((value,ctx) => {
169
+ const result = ${$if}.safeParse(value).success
170
+ ? ${$then}.safeParse(value)
171
+ : ${$else}.safeParse(value);
172
+ if (!result.success) {
173
+ result.error.errors.forEach((error) => ctx.addIssue(error))
174
+ }
175
+ })`;
176
+ };
177
+
178
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNumber.js
179
+ var parseNumber = (schema) => {
180
+ let r = "z.number()";
181
+ if (schema.type === "integer") {
182
+ r += withMessage(schema, "type", () => [".int(", ")"]);
183
+ } else {
184
+ r += withMessage(schema, "format", ({ value }) => {
185
+ if (value === "int64") {
186
+ return [".int(", ")"];
187
+ }
52
188
  });
53
- };
54
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
55
- const keys = [];
56
- for (const key in object) {
57
- if (Object.prototype.hasOwnProperty.call(object, key)) {
58
- keys.push(key);
189
+ }
190
+ r += withMessage(schema, "multipleOf", ({ value, json }) => {
191
+ if (value === 1) {
192
+ if (r.startsWith("z.number().int(")) {
193
+ return;
59
194
  }
195
+ return [".int(", ")"];
60
196
  }
61
- return keys;
62
- };
63
- util2.find = (arr, checker) => {
64
- for (const item of arr) {
65
- if (checker(item))
66
- return item;
197
+ return [`.multipleOf(${json}`, ", ", ")"];
198
+ });
199
+ if (typeof schema.minimum === "number") {
200
+ if (schema.exclusiveMinimum === true) {
201
+ r += withMessage(schema, "minimum", ({ json }) => [
202
+ `.gt(${json}`,
203
+ ", ",
204
+ ")"
205
+ ]);
206
+ } else {
207
+ r += withMessage(schema, "minimum", ({ json }) => [
208
+ `.gte(${json}`,
209
+ ", ",
210
+ ")"
211
+ ]);
67
212
  }
68
- return void 0;
69
- };
70
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
71
- function joinValues(array, separator = " | ") {
72
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
213
+ } else if (typeof schema.exclusiveMinimum === "number") {
214
+ r += withMessage(schema, "exclusiveMinimum", ({ json }) => [
215
+ `.gt(${json}`,
216
+ ", ",
217
+ ")"
218
+ ]);
73
219
  }
74
- util2.joinValues = joinValues;
75
- util2.jsonStringifyReplacer = (_, value) => {
76
- if (typeof value === "bigint") {
77
- return value.toString();
220
+ if (typeof schema.maximum === "number") {
221
+ if (schema.exclusiveMaximum === true) {
222
+ r += withMessage(schema, "maximum", ({ json }) => [
223
+ `.lt(${json}`,
224
+ ", ",
225
+ ")"
226
+ ]);
227
+ } else {
228
+ r += withMessage(schema, "maximum", ({ json }) => [
229
+ `.lte(${json}`,
230
+ ", ",
231
+ ")"
232
+ ]);
78
233
  }
79
- return value;
80
- };
81
- })(util || (util = {}));
82
- var objectUtil;
83
- (function(objectUtil2) {
84
- objectUtil2.mergeShapes = (first, second) => {
85
- return {
86
- ...first,
87
- ...second
88
- // second overwrites first
89
- };
90
- };
91
- })(objectUtil || (objectUtil = {}));
92
- var ZodParsedType = util.arrayToEnum([
93
- "string",
94
- "nan",
95
- "number",
96
- "integer",
97
- "float",
98
- "boolean",
99
- "date",
100
- "bigint",
101
- "symbol",
102
- "function",
103
- "undefined",
104
- "null",
105
- "array",
106
- "object",
107
- "unknown",
108
- "promise",
109
- "void",
110
- "never",
111
- "map",
112
- "set"
113
- ]);
114
- var getParsedType = (data) => {
115
- const t = typeof data;
116
- switch (t) {
117
- case "undefined":
118
- return ZodParsedType.undefined;
119
- case "string":
120
- return ZodParsedType.string;
121
- case "number":
122
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
123
- case "boolean":
124
- return ZodParsedType.boolean;
125
- case "function":
126
- return ZodParsedType.function;
127
- case "bigint":
128
- return ZodParsedType.bigint;
129
- case "symbol":
130
- return ZodParsedType.symbol;
131
- case "object":
132
- if (Array.isArray(data)) {
133
- return ZodParsedType.array;
134
- }
135
- if (data === null) {
136
- return ZodParsedType.null;
137
- }
138
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
139
- return ZodParsedType.promise;
140
- }
141
- if (typeof Map !== "undefined" && data instanceof Map) {
142
- return ZodParsedType.map;
143
- }
144
- if (typeof Set !== "undefined" && data instanceof Set) {
145
- return ZodParsedType.set;
146
- }
147
- if (typeof Date !== "undefined" && data instanceof Date) {
148
- return ZodParsedType.date;
149
- }
150
- return ZodParsedType.object;
151
- default:
152
- return ZodParsedType.unknown;
234
+ } else if (typeof schema.exclusiveMaximum === "number") {
235
+ r += withMessage(schema, "exclusiveMaximum", ({ json }) => [
236
+ `.lt(${json}`,
237
+ ", ",
238
+ ")"
239
+ ]);
153
240
  }
241
+ return r;
154
242
  };
155
- var ZodIssueCode = util.arrayToEnum([
156
- "invalid_type",
157
- "invalid_literal",
158
- "custom",
159
- "invalid_union",
160
- "invalid_union_discriminator",
161
- "invalid_enum_value",
162
- "unrecognized_keys",
163
- "invalid_arguments",
164
- "invalid_return_type",
165
- "invalid_date",
166
- "invalid_string",
167
- "too_small",
168
- "too_big",
169
- "invalid_intersection_types",
170
- "not_multiple_of",
171
- "not_finite"
172
- ]);
173
- var quotelessJson = (obj) => {
174
- const json = JSON.stringify(obj, null, 2);
175
- return json.replace(/"([^"]+)":/g, "$1:");
243
+
244
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseOneOf.js
245
+ var parseOneOf = (schema, refs) => {
246
+ return schema.oneOf.length ? schema.oneOf.length === 1 ? parseSchema(schema.oneOf[0], {
247
+ ...refs,
248
+ path: [...refs.path, "oneOf", 0]
249
+ }) : `z.any().superRefine((x, ctx) => {
250
+ const schemas = [${schema.oneOf.map((schema2, i) => parseSchema(schema2, {
251
+ ...refs,
252
+ path: [...refs.path, "oneOf", i]
253
+ })).join(", ")}];
254
+ const errors = schemas.reduce<z.ZodError[]>(
255
+ (errors, schema) =>
256
+ ((result) =>
257
+ result.error ? [...errors, result.error] : errors)(
258
+ schema.safeParse(x),
259
+ ),
260
+ [],
261
+ );
262
+ if (schemas.length - errors.length !== 1) {
263
+ ctx.addIssue({
264
+ path: ctx.path,
265
+ code: "invalid_union",
266
+ unionErrors: errors,
267
+ message: "Invalid input: Should pass single schema",
268
+ });
269
+ }
270
+ })` : "z.any()";
176
271
  };
177
- var ZodError = class _ZodError extends Error {
178
- get errors() {
179
- return this.issues;
272
+
273
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/jsdocs.js
274
+ var expandJsdocs = (jsdocs) => {
275
+ const lines = jsdocs.split("\n");
276
+ const result = lines.length === 1 ? lines[0] : `
277
+ ${lines.map((x) => `* ${x}`).join("\n")}
278
+ `;
279
+ return `/**${result}*/
280
+ `;
281
+ };
282
+ var addJsdocs = (schema, parsed) => {
283
+ const description = schema.description;
284
+ if (!description) {
285
+ return parsed;
180
286
  }
181
- constructor(issues) {
182
- super();
183
- this.issues = [];
184
- this.addIssue = (sub) => {
185
- this.issues = [...this.issues, sub];
186
- };
187
- this.addIssues = (subs = []) => {
188
- this.issues = [...this.issues, ...subs];
189
- };
190
- const actualProto = new.target.prototype;
191
- if (Object.setPrototypeOf) {
192
- Object.setPrototypeOf(this, actualProto);
287
+ return `
288
+ ${expandJsdocs(description)}${parsed}`;
289
+ };
290
+
291
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseObject.js
292
+ function parseObject(objectSchema, refs) {
293
+ let properties = void 0;
294
+ if (objectSchema.properties) {
295
+ if (!Object.keys(objectSchema.properties).length) {
296
+ properties = "z.object({})";
193
297
  } else {
194
- this.__proto__ = actualProto;
298
+ properties = "z.object({ ";
299
+ properties += Object.keys(objectSchema.properties).map((key) => {
300
+ const propSchema = objectSchema.properties[key];
301
+ let result = `${JSON.stringify(key)}: ${parseSchema(propSchema, {
302
+ ...refs,
303
+ path: [...refs.path, "properties", key]
304
+ })}`;
305
+ if (refs.withJsdocs && typeof propSchema === "object") {
306
+ result = addJsdocs(propSchema, result);
307
+ }
308
+ const hasDefault = typeof propSchema === "object" && propSchema.default !== void 0;
309
+ const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : typeof propSchema === "object" && propSchema.required === true;
310
+ const optional = !hasDefault && !required;
311
+ return optional ? `${result}.optional()` : result;
312
+ }).join(", ");
313
+ properties += " })";
195
314
  }
196
- this.name = "ZodError";
197
- this.issues = issues;
198
315
  }
199
- format(_mapper) {
200
- const mapper = _mapper || function(issue) {
201
- return issue.message;
202
- };
203
- const fieldErrors = { _errors: [] };
204
- const processError = (error) => {
205
- for (const issue of error.issues) {
206
- if (issue.code === "invalid_union") {
207
- issue.unionErrors.map(processError);
208
- } else if (issue.code === "invalid_return_type") {
209
- processError(issue.returnTypeError);
210
- } else if (issue.code === "invalid_arguments") {
211
- processError(issue.argumentsError);
212
- } else if (issue.path.length === 0) {
213
- fieldErrors._errors.push(mapper(issue));
214
- } else {
215
- let curr = fieldErrors;
216
- let i = 0;
217
- while (i < issue.path.length) {
218
- const el = issue.path[i];
219
- const terminal = i === issue.path.length - 1;
220
- if (!terminal) {
221
- curr[el] = curr[el] || { _errors: [] };
222
- } else {
223
- curr[el] = curr[el] || { _errors: [] };
224
- curr[el]._errors.push(mapper(issue));
225
- }
226
- curr = curr[el];
227
- i++;
228
- }
229
- }
316
+ const additionalProperties = objectSchema.additionalProperties !== void 0 ? parseSchema(objectSchema.additionalProperties, {
317
+ ...refs,
318
+ path: [...refs.path, "additionalProperties"]
319
+ }) : void 0;
320
+ let patternProperties = void 0;
321
+ if (objectSchema.patternProperties) {
322
+ const parsedPatternProperties = Object.fromEntries(Object.entries(objectSchema.patternProperties).map(([key, value]) => {
323
+ return [
324
+ key,
325
+ parseSchema(value, {
326
+ ...refs,
327
+ path: [...refs.path, "patternProperties", key]
328
+ })
329
+ ];
330
+ }, {}));
331
+ patternProperties = "";
332
+ if (properties) {
333
+ if (additionalProperties) {
334
+ patternProperties += `.catchall(z.union([${[
335
+ ...Object.values(parsedPatternProperties),
336
+ additionalProperties
337
+ ].join(", ")}]))`;
338
+ } else if (Object.keys(parsedPatternProperties).length > 1) {
339
+ patternProperties += `.catchall(z.union([${Object.values(parsedPatternProperties).join(", ")}]))`;
340
+ } else {
341
+ patternProperties += `.catchall(${Object.values(parsedPatternProperties)})`;
342
+ }
343
+ } else {
344
+ if (additionalProperties) {
345
+ patternProperties += `z.record(z.union([${[
346
+ ...Object.values(parsedPatternProperties),
347
+ additionalProperties
348
+ ].join(", ")}]))`;
349
+ } else if (Object.keys(parsedPatternProperties).length > 1) {
350
+ patternProperties += `z.record(z.union([${Object.values(parsedPatternProperties).join(", ")}]))`;
351
+ } else {
352
+ patternProperties += `z.record(${Object.values(parsedPatternProperties)})`;
230
353
  }
231
- };
232
- processError(this);
233
- return fieldErrors;
234
- }
235
- static assert(value) {
236
- if (!(value instanceof _ZodError)) {
237
- throw new Error(`Not a ZodError: ${value}`);
238
354
  }
355
+ patternProperties += ".superRefine((value, ctx) => {\n";
356
+ patternProperties += "for (const key in value) {\n";
357
+ if (additionalProperties) {
358
+ if (objectSchema.properties) {
359
+ patternProperties += `let evaluated = [${Object.keys(objectSchema.properties).map((key) => JSON.stringify(key)).join(", ")}].includes(key)
360
+ `;
361
+ } else {
362
+ patternProperties += `let evaluated = false
363
+ `;
364
+ }
365
+ }
366
+ for (const key in objectSchema.patternProperties) {
367
+ patternProperties += "if (key.match(new RegExp(" + JSON.stringify(key) + "))) {\n";
368
+ if (additionalProperties) {
369
+ patternProperties += "evaluated = true\n";
370
+ }
371
+ patternProperties += "const result = " + parsedPatternProperties[key] + ".safeParse(value[key])\n";
372
+ patternProperties += "if (!result.success) {\n";
373
+ patternProperties += `ctx.addIssue({
374
+ path: [...ctx.path, key],
375
+ code: 'custom',
376
+ message: \`Invalid input: Key matching regex /\${key}/ must match schema\`,
377
+ params: {
378
+ issues: result.error.issues
379
+ }
380
+ })
381
+ `;
382
+ patternProperties += "}\n";
383
+ patternProperties += "}\n";
384
+ }
385
+ if (additionalProperties) {
386
+ patternProperties += "if (!evaluated) {\n";
387
+ patternProperties += "const result = " + additionalProperties + ".safeParse(value[key])\n";
388
+ patternProperties += "if (!result.success) {\n";
389
+ patternProperties += `ctx.addIssue({
390
+ path: [...ctx.path, key],
391
+ code: 'custom',
392
+ message: \`Invalid input: must match catchall schema\`,
393
+ params: {
394
+ issues: result.error.issues
395
+ }
396
+ })
397
+ `;
398
+ patternProperties += "}\n";
399
+ patternProperties += "}\n";
400
+ }
401
+ patternProperties += "}\n";
402
+ patternProperties += "})";
239
403
  }
240
- toString() {
241
- return this.message;
404
+ let output = properties ? patternProperties ? properties + patternProperties : additionalProperties ? additionalProperties === "z.never()" ? properties + ".strict()" : properties + `.catchall(${additionalProperties})` : properties : patternProperties ? patternProperties : additionalProperties ? `z.record(${additionalProperties})` : "z.record(z.any())";
405
+ if (its.an.anyOf(objectSchema)) {
406
+ output += `.and(${parseAnyOf({
407
+ anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
408
+ }, refs)})`;
242
409
  }
243
- get message() {
244
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
410
+ if (its.a.oneOf(objectSchema)) {
411
+ output += `.and(${parseOneOf({
412
+ oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
413
+ }, refs)})`;
245
414
  }
246
- get isEmpty() {
247
- return this.issues.length === 0;
415
+ if (its.an.allOf(objectSchema)) {
416
+ output += `.and(${parseAllOf({
417
+ allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
418
+ }, refs)})`;
248
419
  }
249
- flatten(mapper = (issue) => issue.message) {
250
- const fieldErrors = {};
251
- const formErrors = [];
252
- for (const sub of this.issues) {
253
- if (sub.path.length > 0) {
254
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
255
- fieldErrors[sub.path[0]].push(mapper(sub));
256
- } else {
257
- formErrors.push(mapper(sub));
420
+ return output;
421
+ }
422
+
423
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseString.js
424
+ var parseString = (schema) => {
425
+ let r = "z.string()";
426
+ r += withMessage(schema, "format", ({ value }) => {
427
+ switch (value) {
428
+ case "email":
429
+ return [".email(", ")"];
430
+ case "ip":
431
+ return [".ip(", ")"];
432
+ case "ipv4":
433
+ return ['.ip({ version: "v4"', ", message: ", " })"];
434
+ case "ipv6":
435
+ return ['.ip({ version: "v6"', ", message: ", " })"];
436
+ case "uri":
437
+ return [".url(", ")"];
438
+ case "uuid":
439
+ return [".uuid(", ")"];
440
+ case "date-time":
441
+ return [".datetime({ offset: true", ", message: ", " })"];
442
+ case "time":
443
+ return [".time(", ")"];
444
+ case "date":
445
+ return [".date(", ")"];
446
+ case "binary":
447
+ return [".base64(", ")"];
448
+ case "duration":
449
+ return [".duration(", ")"];
450
+ }
451
+ });
452
+ r += withMessage(schema, "pattern", ({ json }) => [
453
+ `.regex(new RegExp(${json})`,
454
+ ", ",
455
+ ")"
456
+ ]);
457
+ r += withMessage(schema, "minLength", ({ json }) => [
458
+ `.min(${json}`,
459
+ ", ",
460
+ ")"
461
+ ]);
462
+ r += withMessage(schema, "maxLength", ({ json }) => [
463
+ `.max(${json}`,
464
+ ", ",
465
+ ")"
466
+ ]);
467
+ r += withMessage(schema, "contentEncoding", ({ value }) => {
468
+ if (value === "base64") {
469
+ return [".base64(", ")"];
470
+ }
471
+ });
472
+ const contentMediaType = withMessage(schema, "contentMediaType", ({ value }) => {
473
+ if (value === "application/json") {
474
+ return [
475
+ '.transform((str, ctx) => { try { return JSON.parse(str); } catch (err) { ctx.addIssue({ code: "custom", message: "Invalid JSON" }); }}',
476
+ ", ",
477
+ ")"
478
+ ];
479
+ }
480
+ });
481
+ if (contentMediaType != "") {
482
+ r += contentMediaType;
483
+ r += withMessage(schema, "contentSchema", ({ value }) => {
484
+ if (value && value instanceof Object) {
485
+ return [
486
+ `.pipe(${parseSchema(value)}`,
487
+ ", ",
488
+ ")"
489
+ ];
258
490
  }
491
+ });
492
+ }
493
+ return r;
494
+ };
495
+
496
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/omit.js
497
+ var omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
498
+ if (!keys.includes(key)) {
499
+ acc[key] = obj[key];
500
+ }
501
+ return acc;
502
+ }, {});
503
+
504
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNullable.js
505
+ var parseNullable = (schema, refs) => {
506
+ return `${parseSchema(omit(schema, "nullable"), refs, true)}.nullable()`;
507
+ };
508
+
509
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseSchema.js
510
+ var parseSchema = (schema, refs = { seen: /* @__PURE__ */ new Map(), path: [] }, blockMeta) => {
511
+ if (typeof schema !== "object")
512
+ return schema ? "z.any()" : "z.never()";
513
+ if (refs.parserOverride) {
514
+ const custom2 = refs.parserOverride(schema, refs);
515
+ if (typeof custom2 === "string") {
516
+ return custom2;
259
517
  }
260
- return { formErrors, fieldErrors };
261
518
  }
262
- get formErrors() {
263
- return this.flatten();
519
+ let seen = refs.seen.get(schema);
520
+ if (seen) {
521
+ if (seen.r !== void 0) {
522
+ return seen.r;
523
+ }
524
+ if (refs.depth === void 0 || seen.n >= refs.depth) {
525
+ return "z.any()";
526
+ }
527
+ seen.n += 1;
528
+ } else {
529
+ seen = { r: void 0, n: 0 };
530
+ refs.seen.set(schema, seen);
531
+ }
532
+ let parsed = selectParser(schema, refs);
533
+ if (!blockMeta) {
534
+ if (!refs.withoutDescribes) {
535
+ parsed = addDescribes(schema, parsed);
536
+ }
537
+ if (!refs.withoutDefaults) {
538
+ parsed = addDefaults(schema, parsed);
539
+ }
540
+ parsed = addAnnotations(schema, parsed);
264
541
  }
542
+ seen.r = parsed;
543
+ return parsed;
265
544
  };
266
- ZodError.create = (issues) => {
267
- const error = new ZodError(issues);
268
- return error;
545
+ var addDescribes = (schema, parsed) => {
546
+ if (schema.description) {
547
+ parsed += `.describe(${JSON.stringify(schema.description)})`;
548
+ }
549
+ return parsed;
269
550
  };
270
- var errorMap = (issue, _ctx) => {
271
- let message;
272
- switch (issue.code) {
273
- case ZodIssueCode.invalid_type:
274
- if (issue.received === ZodParsedType.undefined) {
275
- message = "Required";
276
- } else {
277
- message = `Expected ${issue.expected}, received ${issue.received}`;
278
- }
279
- break;
280
- case ZodIssueCode.invalid_literal:
281
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
282
- break;
283
- case ZodIssueCode.unrecognized_keys:
284
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
285
- break;
286
- case ZodIssueCode.invalid_union:
287
- message = `Invalid input`;
288
- break;
289
- case ZodIssueCode.invalid_union_discriminator:
290
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
291
- break;
292
- case ZodIssueCode.invalid_enum_value:
293
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
294
- break;
295
- case ZodIssueCode.invalid_arguments:
296
- message = `Invalid function arguments`;
297
- break;
298
- case ZodIssueCode.invalid_return_type:
299
- message = `Invalid function return type`;
300
- break;
301
- case ZodIssueCode.invalid_date:
302
- message = `Invalid date`;
303
- break;
304
- case ZodIssueCode.invalid_string:
305
- if (typeof issue.validation === "object") {
306
- if ("includes" in issue.validation) {
307
- message = `Invalid input: must include "${issue.validation.includes}"`;
308
- if (typeof issue.validation.position === "number") {
309
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
310
- }
311
- } else if ("startsWith" in issue.validation) {
312
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
313
- } else if ("endsWith" in issue.validation) {
314
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
315
- } else {
316
- util.assertNever(issue.validation);
317
- }
318
- } else if (issue.validation !== "regex") {
319
- message = `Invalid ${issue.validation}`;
320
- } else {
321
- message = "Invalid";
322
- }
323
- break;
324
- case ZodIssueCode.too_small:
325
- if (issue.type === "array")
326
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
327
- else if (issue.type === "string")
328
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
329
- else if (issue.type === "number")
330
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
331
- else if (issue.type === "date")
332
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
333
- else
334
- message = "Invalid input";
335
- break;
336
- case ZodIssueCode.too_big:
337
- if (issue.type === "array")
338
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
339
- else if (issue.type === "string")
340
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
341
- else if (issue.type === "number")
342
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
343
- else if (issue.type === "bigint")
344
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
345
- else if (issue.type === "date")
346
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
347
- else
348
- message = "Invalid input";
349
- break;
350
- case ZodIssueCode.custom:
351
- message = `Invalid input`;
352
- break;
353
- case ZodIssueCode.invalid_intersection_types:
354
- message = `Intersection results could not be merged`;
355
- break;
356
- case ZodIssueCode.not_multiple_of:
357
- message = `Number must be a multiple of ${issue.multipleOf}`;
358
- break;
359
- case ZodIssueCode.not_finite:
360
- message = "Number must be finite";
361
- break;
362
- default:
363
- message = _ctx.defaultError;
364
- util.assertNever(issue);
551
+ var addDefaults = (schema, parsed) => {
552
+ if (schema.default !== void 0) {
553
+ parsed += `.default(${JSON.stringify(schema.default)})`;
365
554
  }
366
- return { message };
555
+ return parsed;
367
556
  };
368
- var overrideErrorMap = errorMap;
369
- function setErrorMap(map) {
370
- overrideErrorMap = map;
371
- }
372
- function getErrorMap() {
373
- return overrideErrorMap;
374
- }
375
- var makeIssue = (params) => {
376
- const { data, path: path2, errorMaps, issueData } = params;
377
- const fullPath = [...path2, ...issueData.path || []];
378
- const fullIssue = {
379
- ...issueData,
380
- path: fullPath
381
- };
382
- if (issueData.message !== void 0) {
383
- return {
384
- ...issueData,
385
- path: fullPath,
386
- message: issueData.message
387
- };
388
- }
389
- let errorMessage = "";
390
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
391
- for (const map of maps) {
392
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
557
+ var addAnnotations = (schema, parsed) => {
558
+ if (schema.readOnly) {
559
+ parsed += ".readonly()";
393
560
  }
394
- return {
395
- ...issueData,
396
- path: fullPath,
397
- message: errorMessage
398
- };
561
+ return parsed;
399
562
  };
400
- var EMPTY_PATH = [];
401
- function addIssueToContext(ctx, issueData) {
402
- const overrideMap = getErrorMap();
403
- const issue = makeIssue({
404
- issueData,
405
- data: ctx.data,
406
- path: ctx.path,
407
- errorMaps: [
408
- ctx.common.contextualErrorMap,
409
- // contextual error map is first priority
410
- ctx.schemaErrorMap,
411
- // then schema-bound map if available
412
- overrideMap,
413
- // then global override map
414
- overrideMap === errorMap ? void 0 : errorMap
415
- // then global default map
416
- ].filter((x) => !!x)
417
- });
418
- ctx.common.issues.push(issue);
419
- }
420
- var ParseStatus = class _ParseStatus {
421
- constructor() {
422
- this.value = "valid";
563
+ var selectParser = (schema, refs) => {
564
+ if (its.a.nullable(schema)) {
565
+ return parseNullable(schema, refs);
566
+ } else if (its.an.object(schema)) {
567
+ return parseObject(schema, refs);
568
+ } else if (its.an.array(schema)) {
569
+ return parseArray(schema, refs);
570
+ } else if (its.an.anyOf(schema)) {
571
+ return parseAnyOf(schema, refs);
572
+ } else if (its.an.allOf(schema)) {
573
+ return parseAllOf(schema, refs);
574
+ } else if (its.a.oneOf(schema)) {
575
+ return parseOneOf(schema, refs);
576
+ } else if (its.a.not(schema)) {
577
+ return parseNot(schema, refs);
578
+ } else if (its.an.enum(schema)) {
579
+ return parseEnum(schema);
580
+ } else if (its.a.const(schema)) {
581
+ return parseConst(schema);
582
+ } else if (its.a.multipleType(schema)) {
583
+ return parseMultipleType(schema, refs);
584
+ } else if (its.a.primitive(schema, "string")) {
585
+ return parseString(schema);
586
+ } else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) {
587
+ return parseNumber(schema);
588
+ } else if (its.a.primitive(schema, "boolean")) {
589
+ return parseBoolean();
590
+ } else if (its.a.primitive(schema, "null")) {
591
+ return parseNull();
592
+ } else if (its.a.conditional(schema)) {
593
+ return parseIfThenElse(schema, refs);
594
+ } else {
595
+ return parseDefault();
423
596
  }
424
- dirty() {
425
- if (this.value === "valid")
426
- this.value = "dirty";
597
+ };
598
+ var its = {
599
+ an: {
600
+ object: (x) => x.type === "object",
601
+ array: (x) => x.type === "array",
602
+ anyOf: (x) => x.anyOf !== void 0,
603
+ allOf: (x) => x.allOf !== void 0,
604
+ enum: (x) => x.enum !== void 0
605
+ },
606
+ a: {
607
+ nullable: (x) => x.nullable === true,
608
+ multipleType: (x) => Array.isArray(x.type),
609
+ not: (x) => x.not !== void 0,
610
+ const: (x) => x.const !== void 0,
611
+ primitive: (x, p) => x.type === p,
612
+ conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
613
+ oneOf: (x) => x.oneOf !== void 0
427
614
  }
428
- abort() {
429
- if (this.value !== "aborted")
430
- this.value = "aborted";
615
+ };
616
+
617
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/jsonSchemaToZod.js
618
+ var jsonSchemaToZod = (schema, { module, name, type, noImport, ...rest } = {}) => {
619
+ if (type && (!name || module !== "esm")) {
620
+ throw new Error("Option `type` requires `name` to be set and `module` to be `esm`");
431
621
  }
432
- static mergeArray(status, results) {
433
- const arrayValue = [];
434
- for (const s of results) {
435
- if (s.status === "aborted")
436
- return INVALID;
437
- if (s.status === "dirty")
438
- status.dirty();
439
- arrayValue.push(s.value);
622
+ let result = parseSchema(schema, {
623
+ module,
624
+ name,
625
+ path: [],
626
+ seen: /* @__PURE__ */ new Map(),
627
+ ...rest
628
+ });
629
+ const jsdocs = rest.withJsdocs && typeof schema !== "boolean" && schema.description ? expandJsdocs(schema.description) : "";
630
+ if (module === "cjs") {
631
+ result = `${jsdocs}module.exports = ${name ? `{ ${JSON.stringify(name)}: ${result} }` : result}
632
+ `;
633
+ if (!noImport) {
634
+ result = `${jsdocs}const { z } = require("zod")
635
+
636
+ ${result}`;
440
637
  }
441
- return { status: status.value, value: arrayValue };
442
- }
443
- static async mergeObjectAsync(status, pairs) {
444
- const syncPairs = [];
445
- for (const pair of pairs) {
446
- const key = await pair.key;
447
- const value = await pair.value;
448
- syncPairs.push({
449
- key,
450
- value
451
- });
638
+ } else if (module === "esm") {
639
+ result = `${jsdocs}export ${name ? `const ${name} =` : `default`} ${result}
640
+ `;
641
+ if (!noImport) {
642
+ result = `import { z } from "zod"
643
+
644
+ ${result}`;
452
645
  }
453
- return _ParseStatus.mergeObjectSync(status, syncPairs);
646
+ } else if (name) {
647
+ result = `${jsdocs}const ${name} = ${result}`;
454
648
  }
455
- static mergeObjectSync(status, pairs) {
456
- const finalObject = {};
457
- for (const pair of pairs) {
458
- const { key, value } = pair;
459
- if (key.status === "aborted")
460
- return INVALID;
461
- if (value.status === "aborted")
462
- return INVALID;
463
- if (key.status === "dirty")
464
- status.dirty();
465
- if (value.status === "dirty")
466
- status.dirty();
467
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
468
- finalObject[key.value] = value.value;
469
- }
470
- }
471
- return { status: status.value, value: finalObject };
649
+ if (type && name) {
650
+ let typeName = typeof type === "string" ? type : `${name[0].toUpperCase()}${name.substring(1)}`;
651
+ result += `export type ${typeName} = z.infer<typeof ${name}>
652
+ `;
472
653
  }
654
+ return result;
473
655
  };
474
- var INVALID = Object.freeze({
475
- status: "aborted"
476
- });
477
- var DIRTY = (value) => ({ status: "dirty", value });
478
- var OK = (value) => ({ status: "valid", value });
479
- var isAborted = (x) => x.status === "aborted";
480
- var isDirty = (x) => x.status === "dirty";
481
- var isValid = (x) => x.status === "valid";
482
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
483
- function __classPrivateFieldGet(receiver, state, kind, f) {
484
- if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
485
- return state.get(receiver);
486
- }
487
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
488
- if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
489
- return state.set(receiver, value), value;
490
- }
491
- var errorUtil;
492
- (function(errorUtil2) {
493
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
494
- errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
495
- })(errorUtil || (errorUtil = {}));
496
- var _ZodEnum_cache;
497
- var _ZodNativeEnum_cache;
498
- var ParseInputLazyPath = class {
499
- constructor(parent, value, path2, key) {
500
- this._cachedPath = [];
501
- this.parent = parent;
502
- this.data = value;
503
- this._path = path2;
504
- this._key = key;
656
+
657
+ // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/index.js
658
+ var esm_default = jsonSchemaToZod;
659
+
660
+ // ../../node_modules/.pnpm/zod@3.24.3/node_modules/zod/lib/index.mjs
661
+ var util;
662
+ (function(util2) {
663
+ util2.assertEqual = (val) => val;
664
+ function assertIs(_arg) {
505
665
  }
506
- get path() {
507
- if (!this._cachedPath.length) {
508
- if (this._key instanceof Array) {
509
- this._cachedPath.push(...this._path, ...this._key);
510
- } else {
511
- this._cachedPath.push(...this._path, this._key);
666
+ util2.assertIs = assertIs;
667
+ function assertNever(_x) {
668
+ throw new Error();
669
+ }
670
+ util2.assertNever = assertNever;
671
+ util2.arrayToEnum = (items) => {
672
+ const obj = {};
673
+ for (const item of items) {
674
+ obj[item] = item;
675
+ }
676
+ return obj;
677
+ };
678
+ util2.getValidEnumValues = (obj) => {
679
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
680
+ const filtered = {};
681
+ for (const k of validKeys) {
682
+ filtered[k] = obj[k];
683
+ }
684
+ return util2.objectValues(filtered);
685
+ };
686
+ util2.objectValues = (obj) => {
687
+ return util2.objectKeys(obj).map(function(e) {
688
+ return obj[e];
689
+ });
690
+ };
691
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
692
+ const keys = [];
693
+ for (const key in object) {
694
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
695
+ keys.push(key);
512
696
  }
513
697
  }
514
- return this._cachedPath;
698
+ return keys;
699
+ };
700
+ util2.find = (arr, checker) => {
701
+ for (const item of arr) {
702
+ if (checker(item))
703
+ return item;
704
+ }
705
+ return void 0;
706
+ };
707
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
708
+ function joinValues(array, separator = " | ") {
709
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
515
710
  }
516
- };
517
- var handleResult = (ctx, result) => {
518
- if (isValid(result)) {
519
- return { success: true, data: result.value };
520
- } else {
521
- if (!ctx.common.issues.length) {
522
- throw new Error("Validation failed but no issues detected.");
711
+ util2.joinValues = joinValues;
712
+ util2.jsonStringifyReplacer = (_, value) => {
713
+ if (typeof value === "bigint") {
714
+ return value.toString();
523
715
  }
716
+ return value;
717
+ };
718
+ })(util || (util = {}));
719
+ var objectUtil;
720
+ (function(objectUtil2) {
721
+ objectUtil2.mergeShapes = (first, second) => {
524
722
  return {
525
- success: false,
526
- get error() {
527
- if (this._error)
528
- return this._error;
529
- const error = new ZodError(ctx.common.issues);
530
- this._error = error;
531
- return this._error;
532
- }
723
+ ...first,
724
+ ...second
725
+ // second overwrites first
533
726
  };
534
- }
535
- };
536
- function processCreateParams(params) {
537
- if (!params)
538
- return {};
539
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
540
- if (errorMap2 && (invalid_type_error || required_error)) {
541
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
542
- }
543
- if (errorMap2)
544
- return { errorMap: errorMap2, description };
545
- const customMap = (iss, ctx) => {
546
- var _a, _b;
547
- const { message } = params;
548
- if (iss.code === "invalid_enum_value") {
549
- return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
550
- }
551
- if (typeof ctx.data === "undefined") {
552
- return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
553
- }
554
- if (iss.code !== "invalid_type")
555
- return { message: ctx.defaultError };
556
- return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
557
727
  };
558
- return { errorMap: customMap, description };
559
- }
560
- var ZodType = class {
561
- get description() {
562
- return this._def.description;
728
+ })(objectUtil || (objectUtil = {}));
729
+ var ZodParsedType = util.arrayToEnum([
730
+ "string",
731
+ "nan",
732
+ "number",
733
+ "integer",
734
+ "float",
735
+ "boolean",
736
+ "date",
737
+ "bigint",
738
+ "symbol",
739
+ "function",
740
+ "undefined",
741
+ "null",
742
+ "array",
743
+ "object",
744
+ "unknown",
745
+ "promise",
746
+ "void",
747
+ "never",
748
+ "map",
749
+ "set"
750
+ ]);
751
+ var getParsedType = (data) => {
752
+ const t = typeof data;
753
+ switch (t) {
754
+ case "undefined":
755
+ return ZodParsedType.undefined;
756
+ case "string":
757
+ return ZodParsedType.string;
758
+ case "number":
759
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
760
+ case "boolean":
761
+ return ZodParsedType.boolean;
762
+ case "function":
763
+ return ZodParsedType.function;
764
+ case "bigint":
765
+ return ZodParsedType.bigint;
766
+ case "symbol":
767
+ return ZodParsedType.symbol;
768
+ case "object":
769
+ if (Array.isArray(data)) {
770
+ return ZodParsedType.array;
771
+ }
772
+ if (data === null) {
773
+ return ZodParsedType.null;
774
+ }
775
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
776
+ return ZodParsedType.promise;
777
+ }
778
+ if (typeof Map !== "undefined" && data instanceof Map) {
779
+ return ZodParsedType.map;
780
+ }
781
+ if (typeof Set !== "undefined" && data instanceof Set) {
782
+ return ZodParsedType.set;
783
+ }
784
+ if (typeof Date !== "undefined" && data instanceof Date) {
785
+ return ZodParsedType.date;
786
+ }
787
+ return ZodParsedType.object;
788
+ default:
789
+ return ZodParsedType.unknown;
563
790
  }
564
- _getType(input) {
565
- return getParsedType(input.data);
791
+ };
792
+ var ZodIssueCode = util.arrayToEnum([
793
+ "invalid_type",
794
+ "invalid_literal",
795
+ "custom",
796
+ "invalid_union",
797
+ "invalid_union_discriminator",
798
+ "invalid_enum_value",
799
+ "unrecognized_keys",
800
+ "invalid_arguments",
801
+ "invalid_return_type",
802
+ "invalid_date",
803
+ "invalid_string",
804
+ "too_small",
805
+ "too_big",
806
+ "invalid_intersection_types",
807
+ "not_multiple_of",
808
+ "not_finite"
809
+ ]);
810
+ var quotelessJson = (obj) => {
811
+ const json = JSON.stringify(obj, null, 2);
812
+ return json.replace(/"([^"]+)":/g, "$1:");
813
+ };
814
+ var ZodError = class _ZodError extends Error {
815
+ get errors() {
816
+ return this.issues;
566
817
  }
567
- _getOrReturnCtx(input, ctx) {
568
- return ctx || {
569
- common: input.parent.common,
570
- data: input.data,
571
- parsedType: getParsedType(input.data),
572
- schemaErrorMap: this._def.errorMap,
573
- path: input.path,
574
- parent: input.parent
818
+ constructor(issues) {
819
+ super();
820
+ this.issues = [];
821
+ this.addIssue = (sub) => {
822
+ this.issues = [...this.issues, sub];
575
823
  };
576
- }
577
- _processInputParams(input) {
578
- return {
579
- status: new ParseStatus(),
580
- ctx: {
581
- common: input.parent.common,
582
- data: input.data,
583
- parsedType: getParsedType(input.data),
584
- schemaErrorMap: this._def.errorMap,
585
- path: input.path,
586
- parent: input.parent
587
- }
824
+ this.addIssues = (subs = []) => {
825
+ this.issues = [...this.issues, ...subs];
588
826
  };
589
- }
590
- _parseSync(input) {
591
- const result = this._parse(input);
592
- if (isAsync(result)) {
593
- throw new Error("Synchronous parse encountered promise.");
827
+ const actualProto = new.target.prototype;
828
+ if (Object.setPrototypeOf) {
829
+ Object.setPrototypeOf(this, actualProto);
830
+ } else {
831
+ this.__proto__ = actualProto;
594
832
  }
595
- return result;
833
+ this.name = "ZodError";
834
+ this.issues = issues;
596
835
  }
597
- _parseAsync(input) {
598
- const result = this._parse(input);
599
- return Promise.resolve(result);
600
- }
601
- parse(data, params) {
602
- const result = this.safeParse(data, params);
603
- if (result.success)
604
- return result.data;
605
- throw result.error;
606
- }
607
- safeParse(data, params) {
608
- var _a;
609
- const ctx = {
610
- common: {
611
- issues: [],
612
- async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
613
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
614
- },
615
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
616
- schemaErrorMap: this._def.errorMap,
617
- parent: null,
618
- data,
619
- parsedType: getParsedType(data)
620
- };
621
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
622
- return handleResult(ctx, result);
623
- }
624
- "~validate"(data) {
625
- var _a, _b;
626
- const ctx = {
627
- common: {
628
- issues: [],
629
- async: !!this["~standard"].async
630
- },
631
- path: [],
632
- schemaErrorMap: this._def.errorMap,
633
- parent: null,
634
- data,
635
- parsedType: getParsedType(data)
836
+ format(_mapper) {
837
+ const mapper = _mapper || function(issue) {
838
+ return issue.message;
636
839
  };
637
- if (!this["~standard"].async) {
638
- try {
639
- const result = this._parseSync({ data, path: [], parent: ctx });
640
- return isValid(result) ? {
641
- value: result.value
642
- } : {
643
- issues: ctx.common.issues
644
- };
645
- } catch (err) {
646
- 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")) {
647
- this["~standard"].async = true;
840
+ const fieldErrors = { _errors: [] };
841
+ const processError = (error) => {
842
+ for (const issue of error.issues) {
843
+ if (issue.code === "invalid_union") {
844
+ issue.unionErrors.map(processError);
845
+ } else if (issue.code === "invalid_return_type") {
846
+ processError(issue.returnTypeError);
847
+ } else if (issue.code === "invalid_arguments") {
848
+ processError(issue.argumentsError);
849
+ } else if (issue.path.length === 0) {
850
+ fieldErrors._errors.push(mapper(issue));
851
+ } else {
852
+ let curr = fieldErrors;
853
+ let i = 0;
854
+ while (i < issue.path.length) {
855
+ const el = issue.path[i];
856
+ const terminal = i === issue.path.length - 1;
857
+ if (!terminal) {
858
+ curr[el] = curr[el] || { _errors: [] };
859
+ } else {
860
+ curr[el] = curr[el] || { _errors: [] };
861
+ curr[el]._errors.push(mapper(issue));
862
+ }
863
+ curr = curr[el];
864
+ i++;
865
+ }
648
866
  }
649
- ctx.common = {
650
- issues: [],
651
- async: true
652
- };
653
867
  }
868
+ };
869
+ processError(this);
870
+ return fieldErrors;
871
+ }
872
+ static assert(value) {
873
+ if (!(value instanceof _ZodError)) {
874
+ throw new Error(`Not a ZodError: ${value}`);
654
875
  }
655
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
656
- value: result.value
657
- } : {
658
- issues: ctx.common.issues
659
- });
660
876
  }
661
- async parseAsync(data, params) {
662
- const result = await this.safeParseAsync(data, params);
663
- if (result.success)
664
- return result.data;
665
- throw result.error;
877
+ toString() {
878
+ return this.message;
666
879
  }
667
- async safeParseAsync(data, params) {
668
- const ctx = {
669
- common: {
670
- issues: [],
671
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
672
- async: true
673
- },
674
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
675
- schemaErrorMap: this._def.errorMap,
676
- parent: null,
677
- data,
678
- parsedType: getParsedType(data)
679
- };
680
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
681
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
682
- return handleResult(ctx, result);
880
+ get message() {
881
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
683
882
  }
684
- refine(check, message) {
685
- const getIssueProperties = (val) => {
686
- if (typeof message === "string" || typeof message === "undefined") {
687
- return { message };
688
- } else if (typeof message === "function") {
689
- return message(val);
883
+ get isEmpty() {
884
+ return this.issues.length === 0;
885
+ }
886
+ flatten(mapper = (issue) => issue.message) {
887
+ const fieldErrors = {};
888
+ const formErrors = [];
889
+ for (const sub of this.issues) {
890
+ if (sub.path.length > 0) {
891
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
892
+ fieldErrors[sub.path[0]].push(mapper(sub));
690
893
  } else {
691
- return message;
692
- }
693
- };
694
- return this._refinement((val, ctx) => {
695
- const result = check(val);
696
- const setError = () => ctx.addIssue({
697
- code: ZodIssueCode.custom,
698
- ...getIssueProperties(val)
699
- });
700
- if (typeof Promise !== "undefined" && result instanceof Promise) {
701
- return result.then((data) => {
702
- if (!data) {
703
- setError();
704
- return false;
705
- } else {
706
- return true;
707
- }
708
- });
894
+ formErrors.push(mapper(sub));
709
895
  }
710
- if (!result) {
711
- setError();
712
- return false;
896
+ }
897
+ return { formErrors, fieldErrors };
898
+ }
899
+ get formErrors() {
900
+ return this.flatten();
901
+ }
902
+ };
903
+ ZodError.create = (issues) => {
904
+ const error = new ZodError(issues);
905
+ return error;
906
+ };
907
+ var errorMap = (issue, _ctx) => {
908
+ let message;
909
+ switch (issue.code) {
910
+ case ZodIssueCode.invalid_type:
911
+ if (issue.received === ZodParsedType.undefined) {
912
+ message = "Required";
713
913
  } else {
714
- return true;
914
+ message = `Expected ${issue.expected}, received ${issue.received}`;
715
915
  }
716
- });
717
- }
718
- refinement(check, refinementData) {
719
- return this._refinement((val, ctx) => {
720
- if (!check(val)) {
721
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
722
- return false;
916
+ break;
917
+ case ZodIssueCode.invalid_literal:
918
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
919
+ break;
920
+ case ZodIssueCode.unrecognized_keys:
921
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
922
+ break;
923
+ case ZodIssueCode.invalid_union:
924
+ message = `Invalid input`;
925
+ break;
926
+ case ZodIssueCode.invalid_union_discriminator:
927
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
928
+ break;
929
+ case ZodIssueCode.invalid_enum_value:
930
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
931
+ break;
932
+ case ZodIssueCode.invalid_arguments:
933
+ message = `Invalid function arguments`;
934
+ break;
935
+ case ZodIssueCode.invalid_return_type:
936
+ message = `Invalid function return type`;
937
+ break;
938
+ case ZodIssueCode.invalid_date:
939
+ message = `Invalid date`;
940
+ break;
941
+ case ZodIssueCode.invalid_string:
942
+ if (typeof issue.validation === "object") {
943
+ if ("includes" in issue.validation) {
944
+ message = `Invalid input: must include "${issue.validation.includes}"`;
945
+ if (typeof issue.validation.position === "number") {
946
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
947
+ }
948
+ } else if ("startsWith" in issue.validation) {
949
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
950
+ } else if ("endsWith" in issue.validation) {
951
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
952
+ } else {
953
+ util.assertNever(issue.validation);
954
+ }
955
+ } else if (issue.validation !== "regex") {
956
+ message = `Invalid ${issue.validation}`;
723
957
  } else {
724
- return true;
958
+ message = "Invalid";
725
959
  }
726
- });
727
- }
728
- _refinement(refinement) {
729
- return new ZodEffects({
730
- schema: this,
731
- typeName: ZodFirstPartyTypeKind.ZodEffects,
732
- effect: { type: "refinement", refinement }
733
- });
734
- }
735
- superRefine(refinement) {
736
- return this._refinement(refinement);
737
- }
738
- constructor(def) {
739
- this.spa = this.safeParseAsync;
740
- this._def = def;
741
- this.parse = this.parse.bind(this);
742
- this.safeParse = this.safeParse.bind(this);
743
- this.parseAsync = this.parseAsync.bind(this);
744
- this.safeParseAsync = this.safeParseAsync.bind(this);
745
- this.spa = this.spa.bind(this);
746
- this.refine = this.refine.bind(this);
747
- this.refinement = this.refinement.bind(this);
748
- this.superRefine = this.superRefine.bind(this);
749
- this.optional = this.optional.bind(this);
750
- this.nullable = this.nullable.bind(this);
751
- this.nullish = this.nullish.bind(this);
752
- this.array = this.array.bind(this);
753
- this.promise = this.promise.bind(this);
754
- this.or = this.or.bind(this);
755
- this.and = this.and.bind(this);
756
- this.transform = this.transform.bind(this);
757
- this.brand = this.brand.bind(this);
758
- this.default = this.default.bind(this);
759
- this.catch = this.catch.bind(this);
760
- this.describe = this.describe.bind(this);
761
- this.pipe = this.pipe.bind(this);
762
- this.readonly = this.readonly.bind(this);
763
- this.isNullable = this.isNullable.bind(this);
764
- this.isOptional = this.isOptional.bind(this);
765
- this["~standard"] = {
766
- version: 1,
767
- vendor: "zod",
768
- validate: (data) => this["~validate"](data)
960
+ break;
961
+ case ZodIssueCode.too_small:
962
+ if (issue.type === "array")
963
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
964
+ else if (issue.type === "string")
965
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
966
+ else if (issue.type === "number")
967
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
968
+ else if (issue.type === "date")
969
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
970
+ else
971
+ message = "Invalid input";
972
+ break;
973
+ case ZodIssueCode.too_big:
974
+ if (issue.type === "array")
975
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
976
+ else if (issue.type === "string")
977
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
978
+ else if (issue.type === "number")
979
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
980
+ else if (issue.type === "bigint")
981
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
982
+ else if (issue.type === "date")
983
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
984
+ else
985
+ message = "Invalid input";
986
+ break;
987
+ case ZodIssueCode.custom:
988
+ message = `Invalid input`;
989
+ break;
990
+ case ZodIssueCode.invalid_intersection_types:
991
+ message = `Intersection results could not be merged`;
992
+ break;
993
+ case ZodIssueCode.not_multiple_of:
994
+ message = `Number must be a multiple of ${issue.multipleOf}`;
995
+ break;
996
+ case ZodIssueCode.not_finite:
997
+ message = "Number must be finite";
998
+ break;
999
+ default:
1000
+ message = _ctx.defaultError;
1001
+ util.assertNever(issue);
1002
+ }
1003
+ return { message };
1004
+ };
1005
+ var overrideErrorMap = errorMap;
1006
+ function setErrorMap(map) {
1007
+ overrideErrorMap = map;
1008
+ }
1009
+ function getErrorMap() {
1010
+ return overrideErrorMap;
1011
+ }
1012
+ var makeIssue = (params) => {
1013
+ const { data, path: path2, errorMaps, issueData } = params;
1014
+ const fullPath = [...path2, ...issueData.path || []];
1015
+ const fullIssue = {
1016
+ ...issueData,
1017
+ path: fullPath
1018
+ };
1019
+ if (issueData.message !== void 0) {
1020
+ return {
1021
+ ...issueData,
1022
+ path: fullPath,
1023
+ message: issueData.message
769
1024
  };
770
1025
  }
771
- optional() {
772
- return ZodOptional.create(this, this._def);
1026
+ let errorMessage = "";
1027
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
1028
+ for (const map of maps) {
1029
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
773
1030
  }
774
- nullable() {
775
- return ZodNullable.create(this, this._def);
1031
+ return {
1032
+ ...issueData,
1033
+ path: fullPath,
1034
+ message: errorMessage
1035
+ };
1036
+ };
1037
+ var EMPTY_PATH = [];
1038
+ function addIssueToContext(ctx, issueData) {
1039
+ const overrideMap = getErrorMap();
1040
+ const issue = makeIssue({
1041
+ issueData,
1042
+ data: ctx.data,
1043
+ path: ctx.path,
1044
+ errorMaps: [
1045
+ ctx.common.contextualErrorMap,
1046
+ // contextual error map is first priority
1047
+ ctx.schemaErrorMap,
1048
+ // then schema-bound map if available
1049
+ overrideMap,
1050
+ // then global override map
1051
+ overrideMap === errorMap ? void 0 : errorMap
1052
+ // then global default map
1053
+ ].filter((x) => !!x)
1054
+ });
1055
+ ctx.common.issues.push(issue);
1056
+ }
1057
+ var ParseStatus = class _ParseStatus {
1058
+ constructor() {
1059
+ this.value = "valid";
776
1060
  }
777
- nullish() {
778
- return this.nullable().optional();
1061
+ dirty() {
1062
+ if (this.value === "valid")
1063
+ this.value = "dirty";
779
1064
  }
780
- array() {
781
- return ZodArray.create(this);
1065
+ abort() {
1066
+ if (this.value !== "aborted")
1067
+ this.value = "aborted";
782
1068
  }
783
- promise() {
784
- return ZodPromise.create(this, this._def);
1069
+ static mergeArray(status, results) {
1070
+ const arrayValue = [];
1071
+ for (const s of results) {
1072
+ if (s.status === "aborted")
1073
+ return INVALID;
1074
+ if (s.status === "dirty")
1075
+ status.dirty();
1076
+ arrayValue.push(s.value);
1077
+ }
1078
+ return { status: status.value, value: arrayValue };
785
1079
  }
786
- or(option) {
787
- return ZodUnion.create([this, option], this._def);
1080
+ static async mergeObjectAsync(status, pairs) {
1081
+ const syncPairs = [];
1082
+ for (const pair of pairs) {
1083
+ const key = await pair.key;
1084
+ const value = await pair.value;
1085
+ syncPairs.push({
1086
+ key,
1087
+ value
1088
+ });
1089
+ }
1090
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
788
1091
  }
789
- and(incoming) {
790
- return ZodIntersection.create(this, incoming, this._def);
1092
+ static mergeObjectSync(status, pairs) {
1093
+ const finalObject = {};
1094
+ for (const pair of pairs) {
1095
+ const { key, value } = pair;
1096
+ if (key.status === "aborted")
1097
+ return INVALID;
1098
+ if (value.status === "aborted")
1099
+ return INVALID;
1100
+ if (key.status === "dirty")
1101
+ status.dirty();
1102
+ if (value.status === "dirty")
1103
+ status.dirty();
1104
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1105
+ finalObject[key.value] = value.value;
1106
+ }
1107
+ }
1108
+ return { status: status.value, value: finalObject };
791
1109
  }
792
- transform(transform) {
793
- return new ZodEffects({
794
- ...processCreateParams(this._def),
795
- schema: this,
796
- typeName: ZodFirstPartyTypeKind.ZodEffects,
797
- effect: { type: "transform", transform }
798
- });
1110
+ };
1111
+ var INVALID = Object.freeze({
1112
+ status: "aborted"
1113
+ });
1114
+ var DIRTY = (value) => ({ status: "dirty", value });
1115
+ var OK = (value) => ({ status: "valid", value });
1116
+ var isAborted = (x) => x.status === "aborted";
1117
+ var isDirty = (x) => x.status === "dirty";
1118
+ var isValid = (x) => x.status === "valid";
1119
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1120
+ function __classPrivateFieldGet(receiver, state, kind, f) {
1121
+ if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1122
+ return state.get(receiver);
1123
+ }
1124
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
1125
+ if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1126
+ return state.set(receiver, value), value;
1127
+ }
1128
+ var errorUtil;
1129
+ (function(errorUtil2) {
1130
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1131
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
1132
+ })(errorUtil || (errorUtil = {}));
1133
+ var _ZodEnum_cache;
1134
+ var _ZodNativeEnum_cache;
1135
+ var ParseInputLazyPath = class {
1136
+ constructor(parent, value, path2, key) {
1137
+ this._cachedPath = [];
1138
+ this.parent = parent;
1139
+ this.data = value;
1140
+ this._path = path2;
1141
+ this._key = key;
799
1142
  }
800
- default(def) {
801
- const defaultValueFunc = typeof def === "function" ? def : () => def;
802
- return new ZodDefault({
803
- ...processCreateParams(this._def),
804
- innerType: this,
805
- defaultValue: defaultValueFunc,
806
- typeName: ZodFirstPartyTypeKind.ZodDefault
807
- });
1143
+ get path() {
1144
+ if (!this._cachedPath.length) {
1145
+ if (this._key instanceof Array) {
1146
+ this._cachedPath.push(...this._path, ...this._key);
1147
+ } else {
1148
+ this._cachedPath.push(...this._path, this._key);
1149
+ }
1150
+ }
1151
+ return this._cachedPath;
808
1152
  }
809
- brand() {
810
- return new ZodBranded({
811
- typeName: ZodFirstPartyTypeKind.ZodBranded,
812
- type: this,
813
- ...processCreateParams(this._def)
814
- });
1153
+ };
1154
+ var handleResult = (ctx, result) => {
1155
+ if (isValid(result)) {
1156
+ return { success: true, data: result.value };
1157
+ } else {
1158
+ if (!ctx.common.issues.length) {
1159
+ throw new Error("Validation failed but no issues detected.");
1160
+ }
1161
+ return {
1162
+ success: false,
1163
+ get error() {
1164
+ if (this._error)
1165
+ return this._error;
1166
+ const error = new ZodError(ctx.common.issues);
1167
+ this._error = error;
1168
+ return this._error;
1169
+ }
1170
+ };
815
1171
  }
816
- catch(def) {
817
- const catchValueFunc = typeof def === "function" ? def : () => def;
818
- return new ZodCatch({
819
- ...processCreateParams(this._def),
820
- innerType: this,
821
- catchValue: catchValueFunc,
822
- typeName: ZodFirstPartyTypeKind.ZodCatch
823
- });
1172
+ };
1173
+ function processCreateParams(params) {
1174
+ if (!params)
1175
+ return {};
1176
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1177
+ if (errorMap2 && (invalid_type_error || required_error)) {
1178
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
824
1179
  }
825
- describe(description) {
826
- const This = this.constructor;
827
- return new This({
828
- ...this._def,
829
- description
830
- });
1180
+ if (errorMap2)
1181
+ return { errorMap: errorMap2, description };
1182
+ const customMap = (iss, ctx) => {
1183
+ var _a, _b;
1184
+ const { message } = params;
1185
+ if (iss.code === "invalid_enum_value") {
1186
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
1187
+ }
1188
+ if (typeof ctx.data === "undefined") {
1189
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
1190
+ }
1191
+ if (iss.code !== "invalid_type")
1192
+ return { message: ctx.defaultError };
1193
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
1194
+ };
1195
+ return { errorMap: customMap, description };
1196
+ }
1197
+ var ZodType = class {
1198
+ get description() {
1199
+ return this._def.description;
831
1200
  }
832
- pipe(target) {
833
- return ZodPipeline.create(this, target);
1201
+ _getType(input) {
1202
+ return getParsedType(input.data);
834
1203
  }
835
- readonly() {
836
- return ZodReadonly.create(this);
1204
+ _getOrReturnCtx(input, ctx) {
1205
+ return ctx || {
1206
+ common: input.parent.common,
1207
+ data: input.data,
1208
+ parsedType: getParsedType(input.data),
1209
+ schemaErrorMap: this._def.errorMap,
1210
+ path: input.path,
1211
+ parent: input.parent
1212
+ };
837
1213
  }
838
- isOptional() {
839
- return this.safeParse(void 0).success;
1214
+ _processInputParams(input) {
1215
+ return {
1216
+ status: new ParseStatus(),
1217
+ ctx: {
1218
+ common: input.parent.common,
1219
+ data: input.data,
1220
+ parsedType: getParsedType(input.data),
1221
+ schemaErrorMap: this._def.errorMap,
1222
+ path: input.path,
1223
+ parent: input.parent
1224
+ }
1225
+ };
840
1226
  }
841
- isNullable() {
842
- return this.safeParse(null).success;
1227
+ _parseSync(input) {
1228
+ const result = this._parse(input);
1229
+ if (isAsync(result)) {
1230
+ throw new Error("Synchronous parse encountered promise.");
1231
+ }
1232
+ return result;
843
1233
  }
844
- };
845
- var cuidRegex = /^c[^\s-]{8,}$/i;
846
- var cuid2Regex = /^[0-9a-z]+$/;
847
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
848
- 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;
849
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
850
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
851
- 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)?)??$/;
852
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
853
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
854
- var emojiRegex;
855
- 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])$/;
856
- 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])$/;
857
- 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]))$/;
858
- 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])$/;
859
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
860
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
861
- 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])))`;
862
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
863
- function timeRegexSource(args) {
864
- let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
865
- if (args.precision) {
866
- regex = `${regex}\\.\\d{${args.precision}}`;
867
- } else if (args.precision == null) {
868
- regex = `${regex}(\\.\\d+)?`;
1234
+ _parseAsync(input) {
1235
+ const result = this._parse(input);
1236
+ return Promise.resolve(result);
869
1237
  }
870
- return regex;
871
- }
872
- function timeRegex(args) {
873
- return new RegExp(`^${timeRegexSource(args)}$`);
874
- }
875
- function datetimeRegex(args) {
876
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
877
- const opts = [];
878
- opts.push(args.local ? `Z?` : `Z`);
879
- if (args.offset)
880
- opts.push(`([+-]\\d{2}:?\\d{2})`);
881
- regex = `${regex}(${opts.join("|")})`;
882
- return new RegExp(`^${regex}$`);
883
- }
884
- function isValidIP(ip, version) {
885
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
886
- return true;
1238
+ parse(data, params) {
1239
+ const result = this.safeParse(data, params);
1240
+ if (result.success)
1241
+ return result.data;
1242
+ throw result.error;
887
1243
  }
888
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
889
- return true;
1244
+ safeParse(data, params) {
1245
+ var _a;
1246
+ const ctx = {
1247
+ common: {
1248
+ issues: [],
1249
+ async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
1250
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
1251
+ },
1252
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
1253
+ schemaErrorMap: this._def.errorMap,
1254
+ parent: null,
1255
+ data,
1256
+ parsedType: getParsedType(data)
1257
+ };
1258
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1259
+ return handleResult(ctx, result);
890
1260
  }
891
- return false;
892
- }
893
- function isValidJWT(jwt, alg) {
894
- if (!jwtRegex.test(jwt))
895
- return false;
896
- try {
897
- const [header] = jwt.split(".");
898
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
899
- const decoded = JSON.parse(atob(base64));
900
- if (typeof decoded !== "object" || decoded === null)
901
- return false;
902
- if (!decoded.typ || !decoded.alg)
903
- return false;
904
- if (alg && decoded.alg !== alg)
905
- return false;
906
- return true;
907
- } catch (_a) {
908
- return false;
1261
+ "~validate"(data) {
1262
+ var _a, _b;
1263
+ const ctx = {
1264
+ common: {
1265
+ issues: [],
1266
+ async: !!this["~standard"].async
1267
+ },
1268
+ path: [],
1269
+ schemaErrorMap: this._def.errorMap,
1270
+ parent: null,
1271
+ data,
1272
+ parsedType: getParsedType(data)
1273
+ };
1274
+ if (!this["~standard"].async) {
1275
+ try {
1276
+ const result = this._parseSync({ data, path: [], parent: ctx });
1277
+ return isValid(result) ? {
1278
+ value: result.value
1279
+ } : {
1280
+ issues: ctx.common.issues
1281
+ };
1282
+ } catch (err) {
1283
+ 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")) {
1284
+ this["~standard"].async = true;
1285
+ }
1286
+ ctx.common = {
1287
+ issues: [],
1288
+ async: true
1289
+ };
1290
+ }
1291
+ }
1292
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1293
+ value: result.value
1294
+ } : {
1295
+ issues: ctx.common.issues
1296
+ });
909
1297
  }
910
- }
911
- function isValidCidr(ip, version) {
912
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
913
- return true;
1298
+ async parseAsync(data, params) {
1299
+ const result = await this.safeParseAsync(data, params);
1300
+ if (result.success)
1301
+ return result.data;
1302
+ throw result.error;
914
1303
  }
915
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
916
- return true;
1304
+ async safeParseAsync(data, params) {
1305
+ const ctx = {
1306
+ common: {
1307
+ issues: [],
1308
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
1309
+ async: true
1310
+ },
1311
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
1312
+ schemaErrorMap: this._def.errorMap,
1313
+ parent: null,
1314
+ data,
1315
+ parsedType: getParsedType(data)
1316
+ };
1317
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1318
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1319
+ return handleResult(ctx, result);
917
1320
  }
918
- return false;
919
- }
920
- var ZodString = class _ZodString extends ZodType {
921
- _parse(input) {
922
- if (this._def.coerce) {
923
- input.data = String(input.data);
924
- }
925
- const parsedType = this._getType(input);
926
- if (parsedType !== ZodParsedType.string) {
927
- const ctx2 = this._getOrReturnCtx(input);
928
- addIssueToContext(ctx2, {
929
- code: ZodIssueCode.invalid_type,
930
- expected: ZodParsedType.string,
931
- received: ctx2.parsedType
1321
+ refine(check, message) {
1322
+ const getIssueProperties = (val) => {
1323
+ if (typeof message === "string" || typeof message === "undefined") {
1324
+ return { message };
1325
+ } else if (typeof message === "function") {
1326
+ return message(val);
1327
+ } else {
1328
+ return message;
1329
+ }
1330
+ };
1331
+ return this._refinement((val, ctx) => {
1332
+ const result = check(val);
1333
+ const setError = () => ctx.addIssue({
1334
+ code: ZodIssueCode.custom,
1335
+ ...getIssueProperties(val)
932
1336
  });
933
- return INVALID;
934
- }
935
- const status = new ParseStatus();
936
- let ctx = void 0;
937
- for (const check of this._def.checks) {
938
- if (check.kind === "min") {
939
- if (input.data.length < check.value) {
940
- ctx = this._getOrReturnCtx(input, ctx);
1337
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1338
+ return result.then((data) => {
1339
+ if (!data) {
1340
+ setError();
1341
+ return false;
1342
+ } else {
1343
+ return true;
1344
+ }
1345
+ });
1346
+ }
1347
+ if (!result) {
1348
+ setError();
1349
+ return false;
1350
+ } else {
1351
+ return true;
1352
+ }
1353
+ });
1354
+ }
1355
+ refinement(check, refinementData) {
1356
+ return this._refinement((val, ctx) => {
1357
+ if (!check(val)) {
1358
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1359
+ return false;
1360
+ } else {
1361
+ return true;
1362
+ }
1363
+ });
1364
+ }
1365
+ _refinement(refinement) {
1366
+ return new ZodEffects({
1367
+ schema: this,
1368
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1369
+ effect: { type: "refinement", refinement }
1370
+ });
1371
+ }
1372
+ superRefine(refinement) {
1373
+ return this._refinement(refinement);
1374
+ }
1375
+ constructor(def) {
1376
+ this.spa = this.safeParseAsync;
1377
+ this._def = def;
1378
+ this.parse = this.parse.bind(this);
1379
+ this.safeParse = this.safeParse.bind(this);
1380
+ this.parseAsync = this.parseAsync.bind(this);
1381
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1382
+ this.spa = this.spa.bind(this);
1383
+ this.refine = this.refine.bind(this);
1384
+ this.refinement = this.refinement.bind(this);
1385
+ this.superRefine = this.superRefine.bind(this);
1386
+ this.optional = this.optional.bind(this);
1387
+ this.nullable = this.nullable.bind(this);
1388
+ this.nullish = this.nullish.bind(this);
1389
+ this.array = this.array.bind(this);
1390
+ this.promise = this.promise.bind(this);
1391
+ this.or = this.or.bind(this);
1392
+ this.and = this.and.bind(this);
1393
+ this.transform = this.transform.bind(this);
1394
+ this.brand = this.brand.bind(this);
1395
+ this.default = this.default.bind(this);
1396
+ this.catch = this.catch.bind(this);
1397
+ this.describe = this.describe.bind(this);
1398
+ this.pipe = this.pipe.bind(this);
1399
+ this.readonly = this.readonly.bind(this);
1400
+ this.isNullable = this.isNullable.bind(this);
1401
+ this.isOptional = this.isOptional.bind(this);
1402
+ this["~standard"] = {
1403
+ version: 1,
1404
+ vendor: "zod",
1405
+ validate: (data) => this["~validate"](data)
1406
+ };
1407
+ }
1408
+ optional() {
1409
+ return ZodOptional.create(this, this._def);
1410
+ }
1411
+ nullable() {
1412
+ return ZodNullable.create(this, this._def);
1413
+ }
1414
+ nullish() {
1415
+ return this.nullable().optional();
1416
+ }
1417
+ array() {
1418
+ return ZodArray.create(this);
1419
+ }
1420
+ promise() {
1421
+ return ZodPromise.create(this, this._def);
1422
+ }
1423
+ or(option) {
1424
+ return ZodUnion.create([this, option], this._def);
1425
+ }
1426
+ and(incoming) {
1427
+ return ZodIntersection.create(this, incoming, this._def);
1428
+ }
1429
+ transform(transform) {
1430
+ return new ZodEffects({
1431
+ ...processCreateParams(this._def),
1432
+ schema: this,
1433
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1434
+ effect: { type: "transform", transform }
1435
+ });
1436
+ }
1437
+ default(def) {
1438
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1439
+ return new ZodDefault({
1440
+ ...processCreateParams(this._def),
1441
+ innerType: this,
1442
+ defaultValue: defaultValueFunc,
1443
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1444
+ });
1445
+ }
1446
+ brand() {
1447
+ return new ZodBranded({
1448
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1449
+ type: this,
1450
+ ...processCreateParams(this._def)
1451
+ });
1452
+ }
1453
+ catch(def) {
1454
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1455
+ return new ZodCatch({
1456
+ ...processCreateParams(this._def),
1457
+ innerType: this,
1458
+ catchValue: catchValueFunc,
1459
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1460
+ });
1461
+ }
1462
+ describe(description) {
1463
+ const This = this.constructor;
1464
+ return new This({
1465
+ ...this._def,
1466
+ description
1467
+ });
1468
+ }
1469
+ pipe(target) {
1470
+ return ZodPipeline.create(this, target);
1471
+ }
1472
+ readonly() {
1473
+ return ZodReadonly.create(this);
1474
+ }
1475
+ isOptional() {
1476
+ return this.safeParse(void 0).success;
1477
+ }
1478
+ isNullable() {
1479
+ return this.safeParse(null).success;
1480
+ }
1481
+ };
1482
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1483
+ var cuid2Regex = /^[0-9a-z]+$/;
1484
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1485
+ 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;
1486
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1487
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1488
+ 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)?)??$/;
1489
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1490
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1491
+ var emojiRegex;
1492
+ 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])$/;
1493
+ 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])$/;
1494
+ 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]))$/;
1495
+ 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])$/;
1496
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1497
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1498
+ 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])))`;
1499
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1500
+ function timeRegexSource(args) {
1501
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
1502
+ if (args.precision) {
1503
+ regex = `${regex}\\.\\d{${args.precision}}`;
1504
+ } else if (args.precision == null) {
1505
+ regex = `${regex}(\\.\\d+)?`;
1506
+ }
1507
+ return regex;
1508
+ }
1509
+ function timeRegex(args) {
1510
+ return new RegExp(`^${timeRegexSource(args)}$`);
1511
+ }
1512
+ function datetimeRegex(args) {
1513
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1514
+ const opts = [];
1515
+ opts.push(args.local ? `Z?` : `Z`);
1516
+ if (args.offset)
1517
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1518
+ regex = `${regex}(${opts.join("|")})`;
1519
+ return new RegExp(`^${regex}$`);
1520
+ }
1521
+ function isValidIP(ip, version) {
1522
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1523
+ return true;
1524
+ }
1525
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1526
+ return true;
1527
+ }
1528
+ return false;
1529
+ }
1530
+ function isValidJWT(jwt, alg) {
1531
+ if (!jwtRegex.test(jwt))
1532
+ return false;
1533
+ try {
1534
+ const [header] = jwt.split(".");
1535
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1536
+ const decoded = JSON.parse(atob(base64));
1537
+ if (typeof decoded !== "object" || decoded === null)
1538
+ return false;
1539
+ if (!decoded.typ || !decoded.alg)
1540
+ return false;
1541
+ if (alg && decoded.alg !== alg)
1542
+ return false;
1543
+ return true;
1544
+ } catch (_a) {
1545
+ return false;
1546
+ }
1547
+ }
1548
+ function isValidCidr(ip, version) {
1549
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1550
+ return true;
1551
+ }
1552
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1553
+ return true;
1554
+ }
1555
+ return false;
1556
+ }
1557
+ var ZodString = class _ZodString extends ZodType {
1558
+ _parse(input) {
1559
+ if (this._def.coerce) {
1560
+ input.data = String(input.data);
1561
+ }
1562
+ const parsedType = this._getType(input);
1563
+ if (parsedType !== ZodParsedType.string) {
1564
+ const ctx2 = this._getOrReturnCtx(input);
1565
+ addIssueToContext(ctx2, {
1566
+ code: ZodIssueCode.invalid_type,
1567
+ expected: ZodParsedType.string,
1568
+ received: ctx2.parsedType
1569
+ });
1570
+ return INVALID;
1571
+ }
1572
+ const status = new ParseStatus();
1573
+ let ctx = void 0;
1574
+ for (const check of this._def.checks) {
1575
+ if (check.kind === "min") {
1576
+ if (input.data.length < check.value) {
1577
+ ctx = this._getOrReturnCtx(input, ctx);
941
1578
  addIssueToContext(ctx, {
942
1579
  code: ZodIssueCode.too_small,
943
1580
  minimum: check.value,
@@ -4111,1020 +4748,385 @@ var InternalMastraMCPClient = class extends MastraBase {
4111
4748
  timeout = DEFAULT_REQUEST_TIMEOUT_MSEC
4112
4749
  }) {
4113
4750
  super({ name: "MastraMCPClient" });
4114
- this.name = name;
4115
- this.timeout = timeout;
4116
- this.logHandler = server.logger;
4117
- this.enableServerLogs = server.enableServerLogs ?? true;
4118
- this.serverConfig = server;
4119
- this.client = new Client(
4120
- {
4121
- name,
4122
- version
4123
- },
4124
- {
4125
- capabilities
4126
- }
4127
- );
4128
- this.setupLogging();
4129
- }
4130
- /**
4131
- * Log a message at the specified level
4132
- * @param level Log level
4133
- * @param message Log message
4134
- * @param details Optional additional details
4135
- */
4136
- log(level, message, details) {
4137
- const loggerMethod = convertLogLevelToLoggerMethod(level);
4138
- const msg = `[${this.name}] ${message}`;
4139
- this.logger[loggerMethod](msg, details);
4140
- if (this.logHandler) {
4141
- this.logHandler({
4142
- level,
4143
- message: msg,
4144
- timestamp: /* @__PURE__ */ new Date(),
4145
- serverName: this.name,
4146
- details
4147
- });
4148
- }
4149
- }
4150
- setupLogging() {
4151
- if (this.enableServerLogs) {
4152
- this.client.setNotificationHandler(
4153
- z.object({
4154
- method: z.literal("notifications/message"),
4155
- params: z.object({
4156
- level: z.string()
4157
- }).passthrough()
4158
- }),
4159
- (notification) => {
4160
- const { level, ...params } = notification.params;
4161
- this.log(level, "[MCP SERVER LOG]", params);
4162
- }
4163
- );
4164
- }
4165
- }
4166
- async connectStdio(command) {
4167
- this.log("debug", `Using Stdio transport for command: ${command}`);
4168
- try {
4169
- this.transport = new StdioClientTransport({
4170
- command,
4171
- args: this.serverConfig.args,
4172
- env: { ...getDefaultEnvironment(), ...this.serverConfig.env || {} }
4173
- });
4174
- await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout });
4175
- this.log("debug", `Successfully connected to MCP server via Stdio`);
4176
- } catch (e) {
4177
- this.log("error", e instanceof Error ? e.stack || e.message : JSON.stringify(e));
4178
- throw e;
4179
- }
4180
- }
4181
- async connectHttp(url) {
4182
- const { requestInit, eventSourceInit } = this.serverConfig;
4183
- this.log("debug", `Attempting to connect to URL: ${url}`);
4184
- let shouldTrySSE = url.pathname.endsWith(`/sse`);
4185
- if (!shouldTrySSE) {
4186
- try {
4187
- this.log("debug", "Trying Streamable HTTP transport...");
4188
- const streamableTransport = new StreamableHTTPClientTransport(url, {
4189
- requestInit,
4190
- reconnectionOptions: this.serverConfig.reconnectionOptions,
4191
- sessionId: this.serverConfig.sessionId
4192
- });
4193
- await this.client.connect(streamableTransport, {
4194
- timeout: (
4195
- // this is hardcoded to 3s because the long default timeout would be extremely slow for sse backwards compat (60s)
4196
- 3e3
4197
- )
4198
- });
4199
- this.transport = streamableTransport;
4200
- this.log("debug", "Successfully connected using Streamable HTTP transport.");
4201
- } catch (error) {
4202
- this.log("debug", `Streamable HTTP transport failed: ${error}`);
4203
- shouldTrySSE = true;
4204
- }
4205
- }
4206
- if (shouldTrySSE) {
4207
- this.log("debug", "Falling back to deprecated HTTP+SSE transport...");
4208
- try {
4209
- const sseTransport = new SSEClientTransport(url, { requestInit, eventSourceInit });
4210
- await this.client.connect(sseTransport, { timeout: this.serverConfig.timeout ?? this.timeout });
4211
- this.transport = sseTransport;
4212
- this.log("debug", "Successfully connected using deprecated HTTP+SSE transport.");
4213
- } catch (sseError) {
4214
- this.log(
4215
- "error",
4216
- `Failed to connect with SSE transport after failing to connect to Streamable HTTP transport first. SSE error: ${sseError}`
4217
- );
4218
- throw new Error("Could not connect to server with any available HTTP transport");
4219
- }
4220
- }
4221
- }
4222
- isConnected = false;
4223
- async connect() {
4224
- if (this.isConnected) return;
4225
- const { command, url } = this.serverConfig;
4226
- if (command) {
4227
- await this.connectStdio(command);
4228
- } else if (url) {
4229
- await this.connectHttp(url);
4230
- } else {
4231
- throw new Error("Server configuration must include either a command or a url.");
4232
- }
4233
- this.isConnected = true;
4234
- const originalOnClose = this.client.onclose;
4235
- this.client.onclose = () => {
4236
- this.log("debug", `MCP server connection closed`);
4237
- this.isConnected = false;
4238
- if (typeof originalOnClose === `function`) {
4239
- originalOnClose();
4240
- }
4241
- };
4242
- asyncExitHook(
4243
- async () => {
4244
- this.log("debug", `Disconnecting MCP server during exit`);
4245
- await this.disconnect();
4246
- },
4247
- { wait: 5e3 }
4248
- );
4249
- process.on("SIGTERM", () => gracefulExit());
4250
- this.log("debug", `Successfully connected to MCP server`);
4251
- }
4252
- /**
4253
- * Get the current session ID if using the Streamable HTTP transport.
4254
- * Returns undefined if not connected or not using Streamable HTTP.
4255
- */
4256
- get sessionId() {
4257
- if (this.transport instanceof StreamableHTTPClientTransport) {
4258
- return this.transport.sessionId;
4259
- }
4260
- return void 0;
4261
- }
4262
- async disconnect() {
4263
- if (!this.transport) {
4264
- this.log("debug", "Disconnect called but no transport was connected.");
4265
- return;
4266
- }
4267
- this.log("debug", `Disconnecting from MCP server`);
4268
- try {
4269
- await this.transport.close();
4270
- this.log("debug", "Successfully disconnected from MCP server");
4271
- } catch (e) {
4272
- this.log("error", "Error during MCP server disconnect", {
4273
- error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2)
4274
- });
4275
- throw e;
4276
- } finally {
4277
- this.transport = void 0;
4278
- this.isConnected = false;
4279
- }
4280
- }
4281
- // TODO: do the type magic to return the right method type. Right now we get infinitely deep infered type errors from Zod without using "any"
4282
- async resources() {
4283
- this.log("debug", `Requesting resources from MCP server`);
4284
- return await this.client.request({ method: "resources/list" }, ListResourcesResultSchema, {
4285
- timeout: this.timeout
4286
- });
4287
- }
4288
- async tools() {
4289
- this.log("debug", `Requesting tools from MCP server`);
4290
- const { tools } = await this.client.listTools({ timeout: this.timeout });
4291
- const toolsRes = {};
4292
- tools.forEach((tool) => {
4293
- this.log("debug", `Processing tool: ${tool.name}`);
4294
- const s = jsonSchemaToModel(tool.inputSchema);
4295
- const mastraTool = createTool({
4296
- id: `${this.name}_${tool.name}`,
4297
- description: tool.description || "",
4298
- inputSchema: s,
4299
- execute: async ({ context }) => {
4300
- try {
4301
- this.log("debug", `Executing tool: ${tool.name}`, { toolArgs: context });
4302
- const res = await this.client.callTool(
4303
- {
4304
- name: tool.name,
4305
- arguments: context
4306
- },
4307
- CallToolResultSchema,
4308
- {
4309
- timeout: this.timeout
4310
- }
4311
- );
4312
- this.log("debug", `Tool executed successfully: ${tool.name}`);
4313
- return res;
4314
- } catch (e) {
4315
- this.log("error", `Error calling tool: ${tool.name}`, {
4316
- error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),
4317
- toolArgs: context
4318
- });
4319
- throw e;
4320
- }
4321
- }
4322
- });
4323
- if (tool.name) {
4324
- toolsRes[tool.name] = mastraTool;
4325
- }
4326
- });
4327
- return toolsRes;
4328
- }
4329
- };
4330
- var MastraMCPClient = class extends InternalMastraMCPClient {
4331
- constructor(args) {
4332
- super(args);
4333
- this.logger.warn(
4334
- "[DEPRECATION] MastraMCPClient is deprecated and will be removed in a future release. Please use MCPClient instead."
4335
- );
4336
- }
4337
- };
4338
- var mcpClientInstances = /* @__PURE__ */ new Map();
4339
- var MCPClient = class extends MastraBase {
4340
- serverConfigs = {};
4341
- id;
4342
- defaultTimeout;
4343
- mcpClientsById = /* @__PURE__ */ new Map();
4344
- disconnectPromise = null;
4345
- constructor(args) {
4346
- super({ name: "MCPClient" });
4347
- this.defaultTimeout = args.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
4348
- this.serverConfigs = args.servers;
4349
- this.id = args.id ?? this.makeId();
4350
- if (args.id) {
4351
- this.id = args.id;
4352
- const cached = mcpClientInstances.get(this.id);
4353
- if (cached && !equal(cached.serverConfigs, args.servers)) {
4354
- const existingInstance2 = mcpClientInstances.get(this.id);
4355
- if (existingInstance2) {
4356
- void existingInstance2.disconnect();
4357
- }
4358
- }
4359
- } else {
4360
- this.id = this.makeId();
4361
- }
4362
- const existingInstance = mcpClientInstances.get(this.id);
4363
- if (existingInstance) {
4364
- if (!args.id) {
4365
- throw new Error(`MCPClient was initialized multiple times with the same configuration options.
4366
-
4367
- This error is intended to prevent memory leaks.
4368
-
4369
- To fix this you have three different options:
4370
- 1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: "my-unique-id" })
4371
- 2. Call "await client.disconnect()" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time of re-creating it, you will not see this error.
4372
- 3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)
4373
- `);
4374
- }
4375
- return existingInstance;
4376
- }
4377
- mcpClientInstances.set(this.id, this);
4378
- this.addToInstanceCache();
4379
- return this;
4380
- }
4381
- addToInstanceCache() {
4382
- if (!mcpClientInstances.has(this.id)) {
4383
- mcpClientInstances.set(this.id, this);
4384
- }
4385
- }
4386
- makeId() {
4387
- const text = JSON.stringify(this.serverConfigs).normalize("NFKC");
4388
- const idNamespace = v5(`MCPClient`, v5.DNS);
4389
- return v5(text, idNamespace);
4390
- }
4391
- async disconnect() {
4392
- if (this.disconnectPromise) {
4393
- return this.disconnectPromise;
4394
- }
4395
- this.disconnectPromise = (async () => {
4396
- try {
4397
- mcpClientInstances.delete(this.id);
4398
- await Promise.all(Array.from(this.mcpClientsById.values()).map((client) => client.disconnect()));
4399
- this.mcpClientsById.clear();
4400
- } finally {
4401
- this.disconnectPromise = null;
4402
- }
4403
- })();
4404
- return this.disconnectPromise;
4405
- }
4406
- async getTools() {
4407
- this.addToInstanceCache();
4408
- const connectedTools = {};
4409
- await this.eachClientTools(async ({ serverName, tools }) => {
4410
- for (const [toolName, toolConfig] of Object.entries(tools)) {
4411
- connectedTools[`${serverName}_${toolName}`] = toolConfig;
4412
- }
4413
- });
4414
- return connectedTools;
4415
- }
4416
- async getToolsets() {
4417
- this.addToInstanceCache();
4418
- const connectedToolsets = {};
4419
- await this.eachClientTools(async ({ serverName, tools }) => {
4420
- if (tools) {
4421
- connectedToolsets[serverName] = tools;
4422
- }
4423
- });
4424
- return connectedToolsets;
4425
- }
4426
- /**
4427
- * Get the current session IDs for all connected MCP clients using the Streamable HTTP transport.
4428
- * Returns an object mapping server names to their session IDs.
4429
- */
4430
- get sessionIds() {
4431
- const sessionIds = {};
4432
- for (const [serverName, client] of this.mcpClientsById.entries()) {
4433
- if (client.sessionId) {
4434
- sessionIds[serverName] = client.sessionId;
4435
- }
4436
- }
4437
- return sessionIds;
4438
- }
4439
- async getConnectedClient(name, config) {
4440
- if (this.disconnectPromise) {
4441
- await this.disconnectPromise;
4442
- }
4443
- const exists = this.mcpClientsById.has(name);
4444
- const existingClient = this.mcpClientsById.get(name);
4445
- if (exists) {
4446
- if (!existingClient) {
4447
- throw new Error(`Client ${name} exists but is undefined`);
4448
- }
4449
- await existingClient.connect();
4450
- return existingClient;
4451
- }
4452
- this.logger.debug(`Connecting to ${name} MCP server`);
4453
- const mcpClient = new InternalMastraMCPClient({
4454
- name,
4455
- server: config,
4456
- timeout: config.timeout ?? this.defaultTimeout
4457
- });
4458
- this.mcpClientsById.set(name, mcpClient);
4459
- try {
4460
- await mcpClient.connect();
4461
- } catch (e) {
4462
- this.mcpClientsById.delete(name);
4463
- this.logger.error(`MCPClient errored connecting to MCP server ${name}`, {
4464
- error: e instanceof Error ? e.message : String(e)
4465
- });
4466
- throw new Error(
4467
- `Failed to connect to MCP server ${name}: ${e instanceof Error ? e.stack || e.message : String(e)}`
4468
- );
4469
- }
4470
- this.logger.debug(`Connected to ${name} MCP server`);
4471
- return mcpClient;
4472
- }
4473
- async eachClientTools(cb) {
4474
- await Promise.all(
4475
- Object.entries(this.serverConfigs).map(async ([serverName, serverConfig]) => {
4476
- const client = await this.getConnectedClient(serverName, serverConfig);
4477
- const tools = await client.tools();
4478
- await cb({ serverName, tools, client });
4479
- })
4480
- );
4481
- }
4482
- };
4483
- var MCPConfiguration = class extends MCPClient {
4484
- constructor(args) {
4485
- super(args);
4486
- this.logger.warn(
4487
- `MCPConfiguration has been renamed to MCPClient and MCPConfiguration is deprecated. The API is identical but the MCPConfiguration export will be removed in the future. Update your imports now to prevent future errors.`
4488
- );
4489
- }
4490
- };
4491
-
4492
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseAnyOf.js
4493
- var parseAnyOf = (schema, refs) => {
4494
- return schema.anyOf.length ? schema.anyOf.length === 1 ? parseSchema(schema.anyOf[0], {
4495
- ...refs,
4496
- path: [...refs.path, "anyOf", 0]
4497
- }) : `z.union([${schema.anyOf.map((schema2, i) => parseSchema(schema2, { ...refs, path: [...refs.path, "anyOf", i] })).join(", ")}])` : `z.any()`;
4498
- };
4499
-
4500
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseBoolean.js
4501
- var parseBoolean = (_schema) => {
4502
- return "z.boolean()";
4503
- };
4504
-
4505
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseDefault.js
4506
- var parseDefault = (_schema) => {
4507
- return "z.any()";
4508
- };
4509
-
4510
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseMultipleType.js
4511
- var parseMultipleType = (schema, refs) => {
4512
- return `z.union([${schema.type.map((type) => parseSchema({ ...schema, type }, refs)).join(", ")}])`;
4513
- };
4514
-
4515
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNot.js
4516
- var parseNot = (schema, refs) => {
4517
- return `z.any().refine((value) => !${parseSchema(schema.not, {
4518
- ...refs,
4519
- path: [...refs.path, "not"]
4520
- })}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
4521
- };
4522
-
4523
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNull.js
4524
- var parseNull = (_schema) => {
4525
- return "z.null()";
4526
- };
4527
-
4528
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/half.js
4529
- var half = (arr) => {
4530
- return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
4531
- };
4532
-
4533
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseAllOf.js
4534
- var originalIndex = Symbol("Original index");
4535
- var ensureOriginalIndex = (arr) => {
4536
- let newArr = [];
4537
- for (let i = 0; i < arr.length; i++) {
4538
- const item = arr[i];
4539
- if (typeof item === "boolean") {
4540
- newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
4541
- } else if (originalIndex in item) {
4542
- return arr;
4543
- } else {
4544
- newArr.push({ ...item, [originalIndex]: i });
4545
- }
4546
- }
4547
- return newArr;
4548
- };
4549
- function parseAllOf(schema, refs) {
4550
- if (schema.allOf.length === 0) {
4551
- return "z.never()";
4552
- } else if (schema.allOf.length === 1) {
4553
- const item = schema.allOf[0];
4554
- return parseSchema(item, {
4555
- ...refs,
4556
- path: [...refs.path, "allOf", item[originalIndex]]
4557
- });
4558
- } else {
4559
- const [left, right] = half(ensureOriginalIndex(schema.allOf));
4560
- return `z.intersection(${parseAllOf({ allOf: left }, refs)}, ${parseAllOf({
4561
- allOf: right
4562
- }, refs)})`;
4563
- }
4564
- }
4565
-
4566
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/withMessage.js
4567
- function withMessage(schema, key, get) {
4568
- const value = schema[key];
4569
- let r = "";
4570
- if (value !== void 0) {
4571
- const got = get({ value, json: JSON.stringify(value) });
4572
- if (got) {
4573
- const opener = got[0];
4574
- const prefix = got.length === 3 ? got[1] : "";
4575
- const closer = got.length === 3 ? got[2] : got[1];
4576
- r += opener;
4577
- if (schema.errorMessage?.[key] !== void 0) {
4578
- r += prefix + JSON.stringify(schema.errorMessage[key]);
4579
- }
4580
- r += closer;
4581
- }
4582
- }
4583
- return r;
4584
- }
4585
-
4586
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseArray.js
4587
- var parseArray = (schema, refs) => {
4588
- if (Array.isArray(schema.items)) {
4589
- return `z.tuple([${schema.items.map((v, i) => parseSchema(v, { ...refs, path: [...refs.path, "items", i] }))}])`;
4590
- }
4591
- let r = !schema.items ? "z.array(z.any())" : `z.array(${parseSchema(schema.items, {
4592
- ...refs,
4593
- path: [...refs.path, "items"]
4594
- })})`;
4595
- r += withMessage(schema, "minItems", ({ json }) => [
4596
- `.min(${json}`,
4597
- ", ",
4598
- ")"
4599
- ]);
4600
- r += withMessage(schema, "maxItems", ({ json }) => [
4601
- `.max(${json}`,
4602
- ", ",
4603
- ")"
4604
- ]);
4605
- return r;
4606
- };
4607
-
4608
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseConst.js
4609
- var parseConst = (schema) => {
4610
- return `z.literal(${JSON.stringify(schema.const)})`;
4611
- };
4612
-
4613
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseEnum.js
4614
- var parseEnum = (schema) => {
4615
- if (schema.enum.length === 0) {
4616
- return "z.never()";
4617
- } else if (schema.enum.length === 1) {
4618
- return `z.literal(${JSON.stringify(schema.enum[0])})`;
4619
- } else if (schema.enum.every((x) => typeof x === "string")) {
4620
- return `z.enum([${schema.enum.map((x) => JSON.stringify(x))}])`;
4621
- } else {
4622
- return `z.union([${schema.enum.map((x) => `z.literal(${JSON.stringify(x)})`).join(", ")}])`;
4623
- }
4624
- };
4625
-
4626
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseIfThenElse.js
4627
- var parseIfThenElse = (schema, refs) => {
4628
- const $if = parseSchema(schema.if, { ...refs, path: [...refs.path, "if"] });
4629
- const $then = parseSchema(schema.then, {
4630
- ...refs,
4631
- path: [...refs.path, "then"]
4632
- });
4633
- const $else = parseSchema(schema.else, {
4634
- ...refs,
4635
- path: [...refs.path, "else"]
4636
- });
4637
- return `z.union([${$then}, ${$else}]).superRefine((value,ctx) => {
4638
- const result = ${$if}.safeParse(value).success
4639
- ? ${$then}.safeParse(value)
4640
- : ${$else}.safeParse(value);
4641
- if (!result.success) {
4642
- result.error.errors.forEach((error) => ctx.addIssue(error))
4643
- }
4644
- })`;
4645
- };
4646
-
4647
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNumber.js
4648
- var parseNumber = (schema) => {
4649
- let r = "z.number()";
4650
- if (schema.type === "integer") {
4651
- r += withMessage(schema, "type", () => [".int(", ")"]);
4652
- } else {
4653
- r += withMessage(schema, "format", ({ value }) => {
4654
- if (value === "int64") {
4655
- return [".int(", ")"];
4751
+ this.name = name;
4752
+ this.timeout = timeout;
4753
+ this.logHandler = server.logger;
4754
+ this.enableServerLogs = server.enableServerLogs ?? true;
4755
+ this.serverConfig = server;
4756
+ this.client = new Client(
4757
+ {
4758
+ name,
4759
+ version
4760
+ },
4761
+ {
4762
+ capabilities
4656
4763
  }
4657
- });
4764
+ );
4765
+ this.setupLogging();
4658
4766
  }
4659
- r += withMessage(schema, "multipleOf", ({ value, json }) => {
4660
- if (value === 1) {
4661
- if (r.startsWith("z.number().int(")) {
4662
- return;
4663
- }
4664
- return [".int(", ")"];
4665
- }
4666
- return [`.multipleOf(${json}`, ", ", ")"];
4667
- });
4668
- if (typeof schema.minimum === "number") {
4669
- if (schema.exclusiveMinimum === true) {
4670
- r += withMessage(schema, "minimum", ({ json }) => [
4671
- `.gt(${json}`,
4672
- ", ",
4673
- ")"
4674
- ]);
4675
- } else {
4676
- r += withMessage(schema, "minimum", ({ json }) => [
4677
- `.gte(${json}`,
4678
- ", ",
4679
- ")"
4680
- ]);
4767
+ /**
4768
+ * Log a message at the specified level
4769
+ * @param level Log level
4770
+ * @param message Log message
4771
+ * @param details Optional additional details
4772
+ */
4773
+ log(level, message, details) {
4774
+ const loggerMethod = convertLogLevelToLoggerMethod(level);
4775
+ const msg = `[${this.name}] ${message}`;
4776
+ this.logger[loggerMethod](msg, details);
4777
+ if (this.logHandler) {
4778
+ this.logHandler({
4779
+ level,
4780
+ message: msg,
4781
+ timestamp: /* @__PURE__ */ new Date(),
4782
+ serverName: this.name,
4783
+ details
4784
+ });
4681
4785
  }
4682
- } else if (typeof schema.exclusiveMinimum === "number") {
4683
- r += withMessage(schema, "exclusiveMinimum", ({ json }) => [
4684
- `.gt(${json}`,
4685
- ", ",
4686
- ")"
4687
- ]);
4688
4786
  }
4689
- if (typeof schema.maximum === "number") {
4690
- if (schema.exclusiveMaximum === true) {
4691
- r += withMessage(schema, "maximum", ({ json }) => [
4692
- `.lt(${json}`,
4693
- ", ",
4694
- ")"
4695
- ]);
4696
- } else {
4697
- r += withMessage(schema, "maximum", ({ json }) => [
4698
- `.lte(${json}`,
4699
- ", ",
4700
- ")"
4701
- ]);
4787
+ setupLogging() {
4788
+ if (this.enableServerLogs) {
4789
+ this.client.setNotificationHandler(
4790
+ z.object({
4791
+ method: z.literal("notifications/message"),
4792
+ params: z.object({
4793
+ level: z.string()
4794
+ }).passthrough()
4795
+ }),
4796
+ (notification) => {
4797
+ const { level, ...params } = notification.params;
4798
+ this.log(level, "[MCP SERVER LOG]", params);
4799
+ }
4800
+ );
4702
4801
  }
4703
- } else if (typeof schema.exclusiveMaximum === "number") {
4704
- r += withMessage(schema, "exclusiveMaximum", ({ json }) => [
4705
- `.lt(${json}`,
4706
- ", ",
4707
- ")"
4708
- ]);
4709
4802
  }
4710
- return r;
4711
- };
4712
-
4713
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseOneOf.js
4714
- var parseOneOf = (schema, refs) => {
4715
- return schema.oneOf.length ? schema.oneOf.length === 1 ? parseSchema(schema.oneOf[0], {
4716
- ...refs,
4717
- path: [...refs.path, "oneOf", 0]
4718
- }) : `z.any().superRefine((x, ctx) => {
4719
- const schemas = [${schema.oneOf.map((schema2, i) => parseSchema(schema2, {
4720
- ...refs,
4721
- path: [...refs.path, "oneOf", i]
4722
- })).join(", ")}];
4723
- const errors = schemas.reduce<z.ZodError[]>(
4724
- (errors, schema) =>
4725
- ((result) =>
4726
- result.error ? [...errors, result.error] : errors)(
4727
- schema.safeParse(x),
4728
- ),
4729
- [],
4730
- );
4731
- if (schemas.length - errors.length !== 1) {
4732
- ctx.addIssue({
4733
- path: ctx.path,
4734
- code: "invalid_union",
4735
- unionErrors: errors,
4736
- message: "Invalid input: Should pass single schema",
4803
+ async connectStdio(command) {
4804
+ this.log("debug", `Using Stdio transport for command: ${command}`);
4805
+ try {
4806
+ this.transport = new StdioClientTransport({
4807
+ command,
4808
+ args: this.serverConfig.args,
4809
+ env: { ...getDefaultEnvironment(), ...this.serverConfig.env || {} }
4737
4810
  });
4738
- }
4739
- })` : "z.any()";
4740
- };
4741
-
4742
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/jsdocs.js
4743
- var expandJsdocs = (jsdocs) => {
4744
- const lines = jsdocs.split("\n");
4745
- const result = lines.length === 1 ? lines[0] : `
4746
- ${lines.map((x) => `* ${x}`).join("\n")}
4747
- `;
4748
- return `/**${result}*/
4749
- `;
4750
- };
4751
- var addJsdocs = (schema, parsed) => {
4752
- const description = schema.description;
4753
- if (!description) {
4754
- return parsed;
4755
- }
4756
- return `
4757
- ${expandJsdocs(description)}${parsed}`;
4758
- };
4759
-
4760
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseObject.js
4761
- function parseObject(objectSchema, refs) {
4762
- let properties = void 0;
4763
- if (objectSchema.properties) {
4764
- if (!Object.keys(objectSchema.properties).length) {
4765
- properties = "z.object({})";
4766
- } else {
4767
- properties = "z.object({ ";
4768
- properties += Object.keys(objectSchema.properties).map((key) => {
4769
- const propSchema = objectSchema.properties[key];
4770
- let result = `${JSON.stringify(key)}: ${parseSchema(propSchema, {
4771
- ...refs,
4772
- path: [...refs.path, "properties", key]
4773
- })}`;
4774
- if (refs.withJsdocs && typeof propSchema === "object") {
4775
- result = addJsdocs(propSchema, result);
4776
- }
4777
- const hasDefault = typeof propSchema === "object" && propSchema.default !== void 0;
4778
- const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : typeof propSchema === "object" && propSchema.required === true;
4779
- const optional = !hasDefault && !required;
4780
- return optional ? `${result}.optional()` : result;
4781
- }).join(", ");
4782
- properties += " })";
4811
+ await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout });
4812
+ this.log("debug", `Successfully connected to MCP server via Stdio`);
4813
+ } catch (e) {
4814
+ this.log("error", e instanceof Error ? e.stack || e.message : JSON.stringify(e));
4815
+ throw e;
4783
4816
  }
4784
4817
  }
4785
- const additionalProperties = objectSchema.additionalProperties !== void 0 ? parseSchema(objectSchema.additionalProperties, {
4786
- ...refs,
4787
- path: [...refs.path, "additionalProperties"]
4788
- }) : void 0;
4789
- let patternProperties = void 0;
4790
- if (objectSchema.patternProperties) {
4791
- const parsedPatternProperties = Object.fromEntries(Object.entries(objectSchema.patternProperties).map(([key, value]) => {
4792
- return [
4793
- key,
4794
- parseSchema(value, {
4795
- ...refs,
4796
- path: [...refs.path, "patternProperties", key]
4797
- })
4798
- ];
4799
- }, {}));
4800
- patternProperties = "";
4801
- if (properties) {
4802
- if (additionalProperties) {
4803
- patternProperties += `.catchall(z.union([${[
4804
- ...Object.values(parsedPatternProperties),
4805
- additionalProperties
4806
- ].join(", ")}]))`;
4807
- } else if (Object.keys(parsedPatternProperties).length > 1) {
4808
- patternProperties += `.catchall(z.union([${Object.values(parsedPatternProperties).join(", ")}]))`;
4809
- } else {
4810
- patternProperties += `.catchall(${Object.values(parsedPatternProperties)})`;
4811
- }
4812
- } else {
4813
- if (additionalProperties) {
4814
- patternProperties += `z.record(z.union([${[
4815
- ...Object.values(parsedPatternProperties),
4816
- additionalProperties
4817
- ].join(", ")}]))`;
4818
- } else if (Object.keys(parsedPatternProperties).length > 1) {
4819
- patternProperties += `z.record(z.union([${Object.values(parsedPatternProperties).join(", ")}]))`;
4820
- } else {
4821
- patternProperties += `z.record(${Object.values(parsedPatternProperties)})`;
4818
+ async connectHttp(url) {
4819
+ const { requestInit, eventSourceInit } = this.serverConfig;
4820
+ this.log("debug", `Attempting to connect to URL: ${url}`);
4821
+ let shouldTrySSE = url.pathname.endsWith(`/sse`);
4822
+ if (!shouldTrySSE) {
4823
+ try {
4824
+ this.log("debug", "Trying Streamable HTTP transport...");
4825
+ const streamableTransport = new StreamableHTTPClientTransport(url, {
4826
+ requestInit,
4827
+ reconnectionOptions: this.serverConfig.reconnectionOptions,
4828
+ sessionId: this.serverConfig.sessionId
4829
+ });
4830
+ await this.client.connect(streamableTransport, {
4831
+ timeout: (
4832
+ // this is hardcoded to 3s because the long default timeout would be extremely slow for sse backwards compat (60s)
4833
+ 3e3
4834
+ )
4835
+ });
4836
+ this.transport = streamableTransport;
4837
+ this.log("debug", "Successfully connected using Streamable HTTP transport.");
4838
+ } catch (error) {
4839
+ this.log("debug", `Streamable HTTP transport failed: ${error}`);
4840
+ shouldTrySSE = true;
4822
4841
  }
4823
4842
  }
4824
- patternProperties += ".superRefine((value, ctx) => {\n";
4825
- patternProperties += "for (const key in value) {\n";
4826
- if (additionalProperties) {
4827
- if (objectSchema.properties) {
4828
- patternProperties += `let evaluated = [${Object.keys(objectSchema.properties).map((key) => JSON.stringify(key)).join(", ")}].includes(key)
4829
- `;
4830
- } else {
4831
- patternProperties += `let evaluated = false
4832
- `;
4843
+ if (shouldTrySSE) {
4844
+ this.log("debug", "Falling back to deprecated HTTP+SSE transport...");
4845
+ try {
4846
+ const sseTransport = new SSEClientTransport(url, { requestInit, eventSourceInit });
4847
+ await this.client.connect(sseTransport, { timeout: this.serverConfig.timeout ?? this.timeout });
4848
+ this.transport = sseTransport;
4849
+ this.log("debug", "Successfully connected using deprecated HTTP+SSE transport.");
4850
+ } catch (sseError) {
4851
+ this.log(
4852
+ "error",
4853
+ `Failed to connect with SSE transport after failing to connect to Streamable HTTP transport first. SSE error: ${sseError}`
4854
+ );
4855
+ throw new Error("Could not connect to server with any available HTTP transport");
4833
4856
  }
4834
4857
  }
4835
- for (const key in objectSchema.patternProperties) {
4836
- patternProperties += "if (key.match(new RegExp(" + JSON.stringify(key) + "))) {\n";
4837
- if (additionalProperties) {
4838
- patternProperties += "evaluated = true\n";
4839
- }
4840
- patternProperties += "const result = " + parsedPatternProperties[key] + ".safeParse(value[key])\n";
4841
- patternProperties += "if (!result.success) {\n";
4842
- patternProperties += `ctx.addIssue({
4843
- path: [...ctx.path, key],
4844
- code: 'custom',
4845
- message: \`Invalid input: Key matching regex /\${key}/ must match schema\`,
4846
- params: {
4847
- issues: result.error.issues
4848
- }
4849
- })
4850
- `;
4851
- patternProperties += "}\n";
4852
- patternProperties += "}\n";
4858
+ }
4859
+ isConnected = false;
4860
+ async connect() {
4861
+ if (this.isConnected) return;
4862
+ const { command, url } = this.serverConfig;
4863
+ if (command) {
4864
+ await this.connectStdio(command);
4865
+ } else if (url) {
4866
+ await this.connectHttp(url);
4867
+ } else {
4868
+ throw new Error("Server configuration must include either a command or a url.");
4853
4869
  }
4854
- if (additionalProperties) {
4855
- patternProperties += "if (!evaluated) {\n";
4856
- patternProperties += "const result = " + additionalProperties + ".safeParse(value[key])\n";
4857
- patternProperties += "if (!result.success) {\n";
4858
- patternProperties += `ctx.addIssue({
4859
- path: [...ctx.path, key],
4860
- code: 'custom',
4861
- message: \`Invalid input: must match catchall schema\`,
4862
- params: {
4863
- issues: result.error.issues
4864
- }
4865
- })
4866
- `;
4867
- patternProperties += "}\n";
4868
- patternProperties += "}\n";
4870
+ this.isConnected = true;
4871
+ const originalOnClose = this.client.onclose;
4872
+ this.client.onclose = () => {
4873
+ this.log("debug", `MCP server connection closed`);
4874
+ this.isConnected = false;
4875
+ if (typeof originalOnClose === `function`) {
4876
+ originalOnClose();
4877
+ }
4878
+ };
4879
+ asyncExitHook(
4880
+ async () => {
4881
+ this.log("debug", `Disconnecting MCP server during exit`);
4882
+ await this.disconnect();
4883
+ },
4884
+ { wait: 5e3 }
4885
+ );
4886
+ process.on("SIGTERM", () => gracefulExit());
4887
+ this.log("debug", `Successfully connected to MCP server`);
4888
+ }
4889
+ /**
4890
+ * Get the current session ID if using the Streamable HTTP transport.
4891
+ * Returns undefined if not connected or not using Streamable HTTP.
4892
+ */
4893
+ get sessionId() {
4894
+ if (this.transport instanceof StreamableHTTPClientTransport) {
4895
+ return this.transport.sessionId;
4869
4896
  }
4870
- patternProperties += "}\n";
4871
- patternProperties += "})";
4897
+ return void 0;
4872
4898
  }
4873
- let output = properties ? patternProperties ? properties + patternProperties : additionalProperties ? additionalProperties === "z.never()" ? properties + ".strict()" : properties + `.catchall(${additionalProperties})` : properties : patternProperties ? patternProperties : additionalProperties ? `z.record(${additionalProperties})` : "z.record(z.any())";
4874
- if (its.an.anyOf(objectSchema)) {
4875
- output += `.and(${parseAnyOf({
4876
- anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
4877
- }, refs)})`;
4899
+ async disconnect() {
4900
+ if (!this.transport) {
4901
+ this.log("debug", "Disconnect called but no transport was connected.");
4902
+ return;
4903
+ }
4904
+ this.log("debug", `Disconnecting from MCP server`);
4905
+ try {
4906
+ await this.transport.close();
4907
+ this.log("debug", "Successfully disconnected from MCP server");
4908
+ } catch (e) {
4909
+ this.log("error", "Error during MCP server disconnect", {
4910
+ error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2)
4911
+ });
4912
+ throw e;
4913
+ } finally {
4914
+ this.transport = void 0;
4915
+ this.isConnected = false;
4916
+ }
4878
4917
  }
4879
- if (its.a.oneOf(objectSchema)) {
4880
- output += `.and(${parseOneOf({
4881
- oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
4882
- }, refs)})`;
4918
+ // TODO: do the type magic to return the right method type. Right now we get infinitely deep infered type errors from Zod without using "any"
4919
+ async resources() {
4920
+ this.log("debug", `Requesting resources from MCP server`);
4921
+ return await this.client.request({ method: "resources/list" }, ListResourcesResultSchema, {
4922
+ timeout: this.timeout
4923
+ });
4883
4924
  }
4884
- if (its.an.allOf(objectSchema)) {
4885
- output += `.and(${parseAllOf({
4886
- allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties || x.additionalProperties || x.patternProperties) ? { ...x, type: "object" } : x)
4887
- }, refs)})`;
4925
+ convertInputSchema(inputSchema) {
4926
+ return isZodType$1(inputSchema) ? inputSchema : resolveSerializedZodOutput$1(esm_default(inputSchema));
4888
4927
  }
4889
- return output;
4890
- }
4891
-
4892
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseString.js
4893
- var parseString = (schema) => {
4894
- let r = "z.string()";
4895
- r += withMessage(schema, "format", ({ value }) => {
4896
- switch (value) {
4897
- case "email":
4898
- return [".email(", ")"];
4899
- case "ip":
4900
- return [".ip(", ")"];
4901
- case "ipv4":
4902
- return ['.ip({ version: "v4"', ", message: ", " })"];
4903
- case "ipv6":
4904
- return ['.ip({ version: "v6"', ", message: ", " })"];
4905
- case "uri":
4906
- return [".url(", ")"];
4907
- case "uuid":
4908
- return [".uuid(", ")"];
4909
- case "date-time":
4910
- return [".datetime({ offset: true", ", message: ", " })"];
4911
- case "time":
4912
- return [".time(", ")"];
4913
- case "date":
4914
- return [".date(", ")"];
4915
- case "binary":
4916
- return [".base64(", ")"];
4917
- case "duration":
4918
- return [".duration(", ")"];
4919
- }
4920
- });
4921
- r += withMessage(schema, "pattern", ({ json }) => [
4922
- `.regex(new RegExp(${json})`,
4923
- ", ",
4924
- ")"
4925
- ]);
4926
- r += withMessage(schema, "minLength", ({ json }) => [
4927
- `.min(${json}`,
4928
- ", ",
4929
- ")"
4930
- ]);
4931
- r += withMessage(schema, "maxLength", ({ json }) => [
4932
- `.max(${json}`,
4933
- ", ",
4934
- ")"
4935
- ]);
4936
- r += withMessage(schema, "contentEncoding", ({ value }) => {
4937
- if (value === "base64") {
4938
- return [".base64(", ")"];
4939
- }
4940
- });
4941
- const contentMediaType = withMessage(schema, "contentMediaType", ({ value }) => {
4942
- if (value === "application/json") {
4943
- return [
4944
- '.transform((str, ctx) => { try { return JSON.parse(str); } catch (err) { ctx.addIssue({ code: "custom", message: "Invalid JSON" }); }}',
4945
- ", ",
4946
- ")"
4947
- ];
4948
- }
4949
- });
4950
- if (contentMediaType != "") {
4951
- r += contentMediaType;
4952
- r += withMessage(schema, "contentSchema", ({ value }) => {
4953
- if (value && value instanceof Object) {
4954
- return [
4955
- `.pipe(${parseSchema(value)}`,
4956
- ", ",
4957
- ")"
4958
- ];
4928
+ async tools() {
4929
+ this.log("debug", `Requesting tools from MCP server`);
4930
+ const { tools } = await this.client.listTools({ timeout: this.timeout });
4931
+ const toolsRes = {};
4932
+ tools.forEach((tool) => {
4933
+ this.log("debug", `Processing tool: ${tool.name}`);
4934
+ const mastraTool = createTool({
4935
+ id: `${this.name}_${tool.name}`,
4936
+ description: tool.description || "",
4937
+ inputSchema: this.convertInputSchema(tool.inputSchema),
4938
+ execute: async ({ context }) => {
4939
+ try {
4940
+ this.log("debug", `Executing tool: ${tool.name}`, { toolArgs: context });
4941
+ const res = await this.client.callTool(
4942
+ {
4943
+ name: tool.name,
4944
+ arguments: context
4945
+ },
4946
+ CallToolResultSchema,
4947
+ {
4948
+ timeout: this.timeout
4949
+ }
4950
+ );
4951
+ this.log("debug", `Tool executed successfully: ${tool.name}`);
4952
+ return res;
4953
+ } catch (e) {
4954
+ this.log("error", `Error calling tool: ${tool.name}`, {
4955
+ error: e instanceof Error ? e.stack : JSON.stringify(e, null, 2),
4956
+ toolArgs: context
4957
+ });
4958
+ throw e;
4959
+ }
4960
+ }
4961
+ });
4962
+ if (tool.name) {
4963
+ toolsRes[tool.name] = mastraTool;
4959
4964
  }
4960
4965
  });
4966
+ return toolsRes;
4961
4967
  }
4962
- return r;
4963
4968
  };
4964
-
4965
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/utils/omit.js
4966
- var omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
4967
- if (!keys.includes(key)) {
4968
- acc[key] = obj[key];
4969
+ var MastraMCPClient = class extends InternalMastraMCPClient {
4970
+ constructor(args) {
4971
+ super(args);
4972
+ this.logger.warn(
4973
+ "[DEPRECATION] MastraMCPClient is deprecated and will be removed in a future release. Please use MCPClient instead."
4974
+ );
4969
4975
  }
4970
- return acc;
4971
- }, {});
4976
+ };
4977
+ var mcpClientInstances = /* @__PURE__ */ new Map();
4978
+ var MCPClient = class extends MastraBase {
4979
+ serverConfigs = {};
4980
+ id;
4981
+ defaultTimeout;
4982
+ mcpClientsById = /* @__PURE__ */ new Map();
4983
+ disconnectPromise = null;
4984
+ constructor(args) {
4985
+ super({ name: "MCPClient" });
4986
+ this.defaultTimeout = args.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
4987
+ this.serverConfigs = args.servers;
4988
+ this.id = args.id ?? this.makeId();
4989
+ if (args.id) {
4990
+ this.id = args.id;
4991
+ const cached = mcpClientInstances.get(this.id);
4992
+ if (cached && !equal(cached.serverConfigs, args.servers)) {
4993
+ const existingInstance2 = mcpClientInstances.get(this.id);
4994
+ if (existingInstance2) {
4995
+ void existingInstance2.disconnect();
4996
+ }
4997
+ }
4998
+ } else {
4999
+ this.id = this.makeId();
5000
+ }
5001
+ const existingInstance = mcpClientInstances.get(this.id);
5002
+ if (existingInstance) {
5003
+ if (!args.id) {
5004
+ throw new Error(`MCPClient was initialized multiple times with the same configuration options.
4972
5005
 
4973
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseNullable.js
4974
- var parseNullable = (schema, refs) => {
4975
- return `${parseSchema(omit(schema, "nullable"), refs, true)}.nullable()`;
4976
- };
5006
+ This error is intended to prevent memory leaks.
4977
5007
 
4978
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/parsers/parseSchema.js
4979
- var parseSchema = (schema, refs = { seen: /* @__PURE__ */ new Map(), path: [] }, blockMeta) => {
4980
- if (typeof schema !== "object")
4981
- return schema ? "z.any()" : "z.never()";
4982
- if (refs.parserOverride) {
4983
- const custom2 = refs.parserOverride(schema, refs);
4984
- if (typeof custom2 === "string") {
4985
- return custom2;
4986
- }
4987
- }
4988
- let seen = refs.seen.get(schema);
4989
- if (seen) {
4990
- if (seen.r !== void 0) {
4991
- return seen.r;
4992
- }
4993
- if (refs.depth === void 0 || seen.n >= refs.depth) {
4994
- return "z.any()";
5008
+ To fix this you have three different options:
5009
+ 1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: "my-unique-id" })
5010
+ 2. Call "await client.disconnect()" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time of re-creating it, you will not see this error.
5011
+ 3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)
5012
+ `);
5013
+ }
5014
+ return existingInstance;
4995
5015
  }
4996
- seen.n += 1;
4997
- } else {
4998
- seen = { r: void 0, n: 0 };
4999
- refs.seen.set(schema, seen);
5016
+ mcpClientInstances.set(this.id, this);
5017
+ this.addToInstanceCache();
5018
+ return this;
5000
5019
  }
5001
- let parsed = selectParser(schema, refs);
5002
- if (!blockMeta) {
5003
- if (!refs.withoutDescribes) {
5004
- parsed = addDescribes(schema, parsed);
5005
- }
5006
- if (!refs.withoutDefaults) {
5007
- parsed = addDefaults(schema, parsed);
5020
+ addToInstanceCache() {
5021
+ if (!mcpClientInstances.has(this.id)) {
5022
+ mcpClientInstances.set(this.id, this);
5008
5023
  }
5009
- parsed = addAnnotations(schema, parsed);
5010
- }
5011
- seen.r = parsed;
5012
- return parsed;
5013
- };
5014
- var addDescribes = (schema, parsed) => {
5015
- if (schema.description) {
5016
- parsed += `.describe(${JSON.stringify(schema.description)})`;
5017
5024
  }
5018
- return parsed;
5019
- };
5020
- var addDefaults = (schema, parsed) => {
5021
- if (schema.default !== void 0) {
5022
- parsed += `.default(${JSON.stringify(schema.default)})`;
5025
+ makeId() {
5026
+ const text = JSON.stringify(this.serverConfigs).normalize("NFKC");
5027
+ const idNamespace = v5(`MCPClient`, v5.DNS);
5028
+ return v5(text, idNamespace);
5023
5029
  }
5024
- return parsed;
5025
- };
5026
- var addAnnotations = (schema, parsed) => {
5027
- if (schema.readOnly) {
5028
- parsed += ".readonly()";
5030
+ async disconnect() {
5031
+ if (this.disconnectPromise) {
5032
+ return this.disconnectPromise;
5033
+ }
5034
+ this.disconnectPromise = (async () => {
5035
+ try {
5036
+ mcpClientInstances.delete(this.id);
5037
+ await Promise.all(Array.from(this.mcpClientsById.values()).map((client) => client.disconnect()));
5038
+ this.mcpClientsById.clear();
5039
+ } finally {
5040
+ this.disconnectPromise = null;
5041
+ }
5042
+ })();
5043
+ return this.disconnectPromise;
5029
5044
  }
5030
- return parsed;
5031
- };
5032
- var selectParser = (schema, refs) => {
5033
- if (its.a.nullable(schema)) {
5034
- return parseNullable(schema, refs);
5035
- } else if (its.an.object(schema)) {
5036
- return parseObject(schema, refs);
5037
- } else if (its.an.array(schema)) {
5038
- return parseArray(schema, refs);
5039
- } else if (its.an.anyOf(schema)) {
5040
- return parseAnyOf(schema, refs);
5041
- } else if (its.an.allOf(schema)) {
5042
- return parseAllOf(schema, refs);
5043
- } else if (its.a.oneOf(schema)) {
5044
- return parseOneOf(schema, refs);
5045
- } else if (its.a.not(schema)) {
5046
- return parseNot(schema, refs);
5047
- } else if (its.an.enum(schema)) {
5048
- return parseEnum(schema);
5049
- } else if (its.a.const(schema)) {
5050
- return parseConst(schema);
5051
- } else if (its.a.multipleType(schema)) {
5052
- return parseMultipleType(schema, refs);
5053
- } else if (its.a.primitive(schema, "string")) {
5054
- return parseString(schema);
5055
- } else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) {
5056
- return parseNumber(schema);
5057
- } else if (its.a.primitive(schema, "boolean")) {
5058
- return parseBoolean();
5059
- } else if (its.a.primitive(schema, "null")) {
5060
- return parseNull();
5061
- } else if (its.a.conditional(schema)) {
5062
- return parseIfThenElse(schema, refs);
5063
- } else {
5064
- return parseDefault();
5045
+ async getTools() {
5046
+ this.addToInstanceCache();
5047
+ const connectedTools = {};
5048
+ await this.eachClientTools(async ({ serverName, tools }) => {
5049
+ for (const [toolName, toolConfig] of Object.entries(tools)) {
5050
+ connectedTools[`${serverName}_${toolName}`] = toolConfig;
5051
+ }
5052
+ });
5053
+ return connectedTools;
5065
5054
  }
5066
- };
5067
- var its = {
5068
- an: {
5069
- object: (x) => x.type === "object",
5070
- array: (x) => x.type === "array",
5071
- anyOf: (x) => x.anyOf !== void 0,
5072
- allOf: (x) => x.allOf !== void 0,
5073
- enum: (x) => x.enum !== void 0
5074
- },
5075
- a: {
5076
- nullable: (x) => x.nullable === true,
5077
- multipleType: (x) => Array.isArray(x.type),
5078
- not: (x) => x.not !== void 0,
5079
- const: (x) => x.const !== void 0,
5080
- primitive: (x, p) => x.type === p,
5081
- conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
5082
- oneOf: (x) => x.oneOf !== void 0
5055
+ async getToolsets() {
5056
+ this.addToInstanceCache();
5057
+ const connectedToolsets = {};
5058
+ await this.eachClientTools(async ({ serverName, tools }) => {
5059
+ if (tools) {
5060
+ connectedToolsets[serverName] = tools;
5061
+ }
5062
+ });
5063
+ return connectedToolsets;
5083
5064
  }
5084
- };
5085
-
5086
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/jsonSchemaToZod.js
5087
- var jsonSchemaToZod = (schema, { module, name, type, noImport, ...rest } = {}) => {
5088
- if (type && (!name || module !== "esm")) {
5089
- throw new Error("Option `type` requires `name` to be set and `module` to be `esm`");
5065
+ /**
5066
+ * Get the current session IDs for all connected MCP clients using the Streamable HTTP transport.
5067
+ * Returns an object mapping server names to their session IDs.
5068
+ */
5069
+ get sessionIds() {
5070
+ const sessionIds = {};
5071
+ for (const [serverName, client] of this.mcpClientsById.entries()) {
5072
+ if (client.sessionId) {
5073
+ sessionIds[serverName] = client.sessionId;
5074
+ }
5075
+ }
5076
+ return sessionIds;
5090
5077
  }
5091
- let result = parseSchema(schema, {
5092
- module,
5093
- name,
5094
- path: [],
5095
- seen: /* @__PURE__ */ new Map(),
5096
- ...rest
5097
- });
5098
- const jsdocs = rest.withJsdocs && typeof schema !== "boolean" && schema.description ? expandJsdocs(schema.description) : "";
5099
- if (module === "cjs") {
5100
- result = `${jsdocs}module.exports = ${name ? `{ ${JSON.stringify(name)}: ${result} }` : result}
5101
- `;
5102
- if (!noImport) {
5103
- result = `${jsdocs}const { z } = require("zod")
5104
-
5105
- ${result}`;
5078
+ async getConnectedClient(name, config) {
5079
+ if (this.disconnectPromise) {
5080
+ await this.disconnectPromise;
5106
5081
  }
5107
- } else if (module === "esm") {
5108
- result = `${jsdocs}export ${name ? `const ${name} =` : `default`} ${result}
5109
- `;
5110
- if (!noImport) {
5111
- result = `import { z } from "zod"
5112
-
5113
- ${result}`;
5082
+ const exists = this.mcpClientsById.has(name);
5083
+ const existingClient = this.mcpClientsById.get(name);
5084
+ if (exists) {
5085
+ if (!existingClient) {
5086
+ throw new Error(`Client ${name} exists but is undefined`);
5087
+ }
5088
+ await existingClient.connect();
5089
+ return existingClient;
5114
5090
  }
5115
- } else if (name) {
5116
- result = `${jsdocs}const ${name} = ${result}`;
5091
+ this.logger.debug(`Connecting to ${name} MCP server`);
5092
+ const mcpClient = new InternalMastraMCPClient({
5093
+ name,
5094
+ server: config,
5095
+ timeout: config.timeout ?? this.defaultTimeout
5096
+ });
5097
+ this.mcpClientsById.set(name, mcpClient);
5098
+ try {
5099
+ await mcpClient.connect();
5100
+ } catch (e) {
5101
+ this.mcpClientsById.delete(name);
5102
+ this.logger.error(`MCPClient errored connecting to MCP server ${name}`, {
5103
+ error: e instanceof Error ? e.message : String(e)
5104
+ });
5105
+ throw new Error(
5106
+ `Failed to connect to MCP server ${name}: ${e instanceof Error ? e.stack || e.message : String(e)}`
5107
+ );
5108
+ }
5109
+ this.logger.debug(`Connected to ${name} MCP server`);
5110
+ return mcpClient;
5117
5111
  }
5118
- if (type && name) {
5119
- let typeName = typeof type === "string" ? type : `${name[0].toUpperCase()}${name.substring(1)}`;
5120
- result += `export type ${typeName} = z.infer<typeof ${name}>
5121
- `;
5112
+ async eachClientTools(cb) {
5113
+ await Promise.all(
5114
+ Object.entries(this.serverConfigs).map(async ([serverName, serverConfig]) => {
5115
+ const client = await this.getConnectedClient(serverName, serverConfig);
5116
+ const tools = await client.tools();
5117
+ await cb({ serverName, tools, client });
5118
+ })
5119
+ );
5120
+ }
5121
+ };
5122
+ var MCPConfiguration = class extends MCPClient {
5123
+ constructor(args) {
5124
+ super(args);
5125
+ this.logger.warn(
5126
+ `MCPConfiguration has been renamed to MCPClient and MCPConfiguration is deprecated. The API is identical but the MCPConfiguration export will be removed in the future. Update your imports now to prevent future errors.`
5127
+ );
5122
5128
  }
5123
- return result;
5124
5129
  };
5125
-
5126
- // ../../node_modules/.pnpm/json-schema-to-zod@2.6.0/node_modules/json-schema-to-zod/dist/esm/index.js
5127
- var esm_default = jsonSchemaToZod;
5128
5130
 
5129
5131
  // ../../node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.24.3/node_modules/zod-to-json-schema/dist/esm/Options.js
5130
5132
  var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");