@corsair-dev/mcp 0.1.27 → 0.1.29
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/adapters/mastra.d.ts +1 -1
- package/dist/bin.d.ts +7 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +126 -0
- package/dist/chunk-QFVNNGDE.js +4489 -0
- package/dist/index.js +13 -4399
- package/dist/langchain.d.ts +2 -0
- package/dist/langchain.d.ts.map +1 -0
- package/dist/langchain.js +2 -0
- package/dist/llamaindex.d.ts +2 -0
- package/dist/llamaindex.d.ts.map +1 -0
- package/dist/llamaindex.js +2 -0
- package/dist/mastra.d.ts +2 -0
- package/dist/mastra.d.ts.map +1 -0
- package/dist/mastra.js +2 -0
- package/package.json +47 -4
package/dist/index.js
CHANGED
|
@@ -1,4403 +1,17 @@
|
|
|
1
|
-
// src/adapters/anthropic-api.ts
|
|
2
|
-
import { z as z3 } from "zod";
|
|
3
|
-
|
|
4
|
-
// src/core/json-schema.ts
|
|
5
|
-
import { z } from "zod";
|
|
6
|
-
import * as z4mini from "zod/v4-mini";
|
|
7
|
-
function shapeToJsonSchema(shape) {
|
|
8
|
-
return z4mini.toJSONSchema(z.object(shape), {
|
|
9
|
-
target: "draft-7",
|
|
10
|
-
io: "input"
|
|
11
|
-
});
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// src/core/tools.ts
|
|
15
|
-
import { listOperations, runReadonly } from "corsair";
|
|
16
|
-
import { z as z2 } from "zod";
|
|
17
|
-
|
|
18
|
-
// src/core/schema-format.ts
|
|
19
|
-
import { formatDocSchemaShape, getSchema } from "corsair";
|
|
20
|
-
function formatGetSchemaResponse(corsair, path) {
|
|
21
|
-
return getSchema(corsair, path);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// src/core/tool-result.ts
|
|
25
|
-
import { AuthMissingError, PermissionRequiredError } from "corsair";
|
|
26
|
-
function isAgentFacingActionMessage(value) {
|
|
27
|
-
if (typeof value !== "string") {
|
|
28
|
-
return false;
|
|
29
|
-
}
|
|
30
|
-
return value.includes("[auth-missing:") || value.startsWith("Approval required. Visit") || value.includes(" requires user approval before it can run") || value.includes(" was denied by the user") || value.includes(" is blocked by the permission policy") || value.includes(" timed out waiting for approval") || value.includes("Could not create approval link");
|
|
31
|
-
}
|
|
32
|
-
function isActionToolError(err) {
|
|
33
|
-
return err instanceof AuthMissingError || err instanceof PermissionRequiredError || err instanceof Error && isAgentFacingActionMessage(err.message);
|
|
34
|
-
}
|
|
35
|
-
function toolErrorResult(message) {
|
|
36
|
-
return {
|
|
37
|
-
isError: true,
|
|
38
|
-
content: [{ type: "text", text: message }]
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
function formatRunScriptResult(result) {
|
|
42
|
-
if (isAgentFacingActionMessage(result)) {
|
|
43
|
-
return toolErrorResult(result);
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
content: [
|
|
47
|
-
{
|
|
48
|
-
type: "text",
|
|
49
|
-
text: JSON.stringify(result ?? null, null, 2)
|
|
50
|
-
}
|
|
51
|
-
]
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
function formatRunScriptError(err) {
|
|
55
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
56
|
-
if (isActionToolError(err)) {
|
|
57
|
-
return toolErrorResult(message);
|
|
58
|
-
}
|
|
59
|
-
const extra = err instanceof Error && err.cause ? `
|
|
60
|
-
Cause: ${String(err.cause)}` : "";
|
|
61
|
-
const full = JSON.stringify(err, Object.getOwnPropertyNames(err));
|
|
62
|
-
return toolErrorResult(`Error running snippet: ${message}${extra}
|
|
63
|
-
${full}`);
|
|
64
|
-
}
|
|
65
|
-
function callToolResultToText(result) {
|
|
66
|
-
const text = result.content.filter((c) => c.type === "text").map((c) => "text" in c ? c.text : "").join("\n");
|
|
67
|
-
if (result.isError) {
|
|
68
|
-
throw new Error(text);
|
|
69
|
-
}
|
|
70
|
-
return text;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// src/core/tools.ts
|
|
74
|
-
function buildCorsairToolDefs(options) {
|
|
75
|
-
const { corsair, runOptions } = options;
|
|
76
|
-
const defs = [
|
|
77
|
-
{
|
|
78
|
-
name: "list_operations",
|
|
79
|
-
description: "List available Corsair operations. Without options returns all API endpoints across every plugin. Filter by plugin (e.g. 'slack') and/or type ('api' | 'webhooks' | 'db').",
|
|
80
|
-
shape: {
|
|
81
|
-
plugin: z2.string().optional().describe("Plugin ID to filter by, e.g. 'slack' or 'github'"),
|
|
82
|
-
type: z2.enum(["api", "webhooks", "db"]).optional().describe("Operation type: 'api' (default), 'webhooks', or 'db'")
|
|
83
|
-
},
|
|
84
|
-
handler: async ({ plugin, type }) => {
|
|
85
|
-
const result = listOperations(corsair, {
|
|
86
|
-
plugin,
|
|
87
|
-
type
|
|
88
|
-
});
|
|
89
|
-
return {
|
|
90
|
-
content: [{ type: "text", text: result }]
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
{
|
|
95
|
-
name: "get_schema",
|
|
96
|
-
description: "Get the schema and metadata for a Corsair operation path. Accepts API paths ('slack.api.channels.list'), webhook paths ('slack.webhooks.messages.message'), or DB paths ('slack.db.messages.search').",
|
|
97
|
-
shape: {
|
|
98
|
-
path: z2.string().describe(
|
|
99
|
-
"Full dot-path from list_operations, e.g. 'slack.api.channels.list'"
|
|
100
|
-
)
|
|
101
|
-
},
|
|
102
|
-
handler: async ({ path }) => {
|
|
103
|
-
const result = formatGetSchemaResponse(
|
|
104
|
-
corsair,
|
|
105
|
-
path
|
|
106
|
-
);
|
|
107
|
-
return {
|
|
108
|
-
content: [{ type: "text", text: result }]
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
},
|
|
112
|
-
{
|
|
113
|
-
name: "run_script",
|
|
114
|
-
description: "Run a JavaScript script with `corsair` as the only variable in scope. Call Corsair operations, filter or transform the results inline, and return only what you need. The return value becomes the tool output.",
|
|
115
|
-
shape: {
|
|
116
|
-
code: z2.string().describe(
|
|
117
|
-
'Async JS script with `corsair` in scope. Return the value you want. Example:\nconst result = await corsair.slack.api.channels.list({});\nconst channel = result.channels?.find(c => c.name === "general");\nreturn channel?.id;'
|
|
118
|
-
)
|
|
119
|
-
},
|
|
120
|
-
handler: async ({ code }) => {
|
|
121
|
-
const readonly = runOptions?.readonly || false;
|
|
122
|
-
try {
|
|
123
|
-
const fn = new Function(
|
|
124
|
-
"corsair",
|
|
125
|
-
`return (async () => { ${code} })()`
|
|
126
|
-
);
|
|
127
|
-
const invoke = () => fn(corsair);
|
|
128
|
-
const result = readonly ? await runReadonly(invoke) : await invoke();
|
|
129
|
-
return formatRunScriptResult(result);
|
|
130
|
-
} catch (err) {
|
|
131
|
-
return formatRunScriptError(err);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
];
|
|
136
|
-
return defs;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// src/core/provider.ts
|
|
140
|
-
var BaseProvider = class {
|
|
141
|
-
build(options) {
|
|
142
|
-
return buildCorsairToolDefs(options).map((def) => this.wrapTool(def));
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
// src/adapters/anthropic-api.ts
|
|
147
|
-
var AnthropicProvider = class extends BaseProvider {
|
|
148
|
-
name = "anthropic";
|
|
149
|
-
wrapTool(def) {
|
|
150
|
-
const schema = shapeToJsonSchema(def.shape);
|
|
151
|
-
return {
|
|
152
|
-
type: "custom",
|
|
153
|
-
name: def.name,
|
|
154
|
-
description: def.description,
|
|
155
|
-
input_schema: schema,
|
|
156
|
-
run: async (args) => {
|
|
157
|
-
try {
|
|
158
|
-
const result = await def.handler(args);
|
|
159
|
-
return callToolResultToText(result);
|
|
160
|
-
} catch (err) {
|
|
161
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
162
|
-
return `Error: ${message}`;
|
|
163
|
-
}
|
|
164
|
-
},
|
|
165
|
-
parse: (content) => z3.object(def.shape).parse(content)
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
// src/adapters/claude.ts
|
|
171
|
-
var ClaudeProvider = class {
|
|
172
|
-
name = "claude";
|
|
173
|
-
async build(options) {
|
|
174
|
-
const { tool: tool2 } = await import(
|
|
175
|
-
/* webpackIgnore: true */
|
|
176
|
-
/* turbopackIgnore: true */
|
|
177
|
-
"@anthropic-ai/claude-agent-sdk"
|
|
178
|
-
);
|
|
179
|
-
return buildCorsairToolDefs(options).map(
|
|
180
|
-
(def) => tool2(def.name, def.description, def.shape, def.handler)
|
|
181
|
-
);
|
|
182
|
-
}
|
|
183
|
-
};
|
|
184
|
-
|
|
185
|
-
// src/adapters/mastra.ts
|
|
186
|
-
import { z as z4 } from "zod";
|
|
187
|
-
var MastraProvider = class {
|
|
188
|
-
name = "mastra";
|
|
189
|
-
async build(options) {
|
|
190
|
-
const { createTool } = await import(
|
|
191
|
-
/* webpackIgnore: true */
|
|
192
|
-
/* turbopackIgnore: true */
|
|
193
|
-
"@mastra/core/tools"
|
|
194
|
-
);
|
|
195
|
-
return buildCorsairToolDefs(options).map(
|
|
196
|
-
(def) => createTool({
|
|
197
|
-
id: def.name,
|
|
198
|
-
description: def.description,
|
|
199
|
-
inputSchema: z4.object(def.shape),
|
|
200
|
-
execute: async (inputData) => {
|
|
201
|
-
const result = await def.handler(
|
|
202
|
-
inputData
|
|
203
|
-
);
|
|
204
|
-
const text = callToolResultToText(result);
|
|
205
|
-
try {
|
|
206
|
-
return JSON.parse(text);
|
|
207
|
-
} catch {
|
|
208
|
-
return text;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
})
|
|
212
|
-
);
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
|
|
216
|
-
// src/adapters/ollama.ts
|
|
217
|
-
import { z as z5 } from "zod";
|
|
218
|
-
var OllamaProvider = class extends BaseProvider {
|
|
219
|
-
name = "ollama";
|
|
220
|
-
wrapTool(def) {
|
|
221
|
-
const schema = shapeToJsonSchema(def.shape);
|
|
222
|
-
return {
|
|
223
|
-
type: "function",
|
|
224
|
-
function: {
|
|
225
|
-
name: def.name,
|
|
226
|
-
description: def.description,
|
|
227
|
-
parameters: schema
|
|
228
|
-
},
|
|
229
|
-
/**
|
|
230
|
-
* The `execute` helper provides a simplified execution interface for runners.
|
|
231
|
-
* It handles:
|
|
232
|
-
* 1. Parsing arguments (handles both object and JSON string inputs).
|
|
233
|
-
* 2. Validation against the tool's Zod schema.
|
|
234
|
-
* 3. Execution of the underlying Corsair tool handler.
|
|
235
|
-
* 4. Extraction and concatenation of text results into a single string.
|
|
236
|
-
* 5. Graceful error handling for robust integration.
|
|
237
|
-
*/
|
|
238
|
-
execute: async (args) => {
|
|
239
|
-
try {
|
|
240
|
-
const raw = typeof args === "string" ? JSON.parse(args) : args;
|
|
241
|
-
const validated = z5.object(def.shape).parse(raw);
|
|
242
|
-
const result = await def.handler(validated);
|
|
243
|
-
return callToolResultToText(result);
|
|
244
|
-
} catch (err) {
|
|
245
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
246
|
-
return `Error: ${message}`;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
// src/adapters/openai.ts
|
|
254
|
-
function getOpenAIMcpConfig(baseUrl, headers) {
|
|
255
|
-
return {
|
|
256
|
-
serverLabel: "corsair",
|
|
257
|
-
serverUrl: baseUrl,
|
|
258
|
-
headers
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// src/adapters/openai-agents.ts
|
|
263
|
-
import { z as z6 } from "zod";
|
|
264
|
-
var OpenAIAgentsProvider = class {
|
|
265
|
-
name = "openai-agents";
|
|
266
|
-
build(options) {
|
|
267
|
-
const { tool: tool2, ...mcpOptions } = options;
|
|
268
|
-
return buildCorsairToolDefs(mcpOptions).map((def) => {
|
|
269
|
-
const jsonSchema2 = shapeToJsonSchema(def.shape);
|
|
270
|
-
const shapeKeys = new Set(Object.keys(def.shape));
|
|
271
|
-
return tool2({
|
|
272
|
-
name: def.name,
|
|
273
|
-
description: def.description,
|
|
274
|
-
parameters: jsonSchema2,
|
|
275
|
-
strict: false,
|
|
276
|
-
execute: async (input) => {
|
|
277
|
-
try {
|
|
278
|
-
const raw = typeof input === "string" ? JSON.parse(input) : input;
|
|
279
|
-
if (shapeKeys.has("args") && typeof raw.args !== "object") {
|
|
280
|
-
const extra = {};
|
|
281
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
282
|
-
if (!shapeKeys.has(k)) extra[k] = v;
|
|
283
|
-
}
|
|
284
|
-
if (Object.keys(extra).length > 0) raw.args = extra;
|
|
285
|
-
}
|
|
286
|
-
const args = z6.object(def.shape).parse(raw);
|
|
287
|
-
const result = await def.handler(args);
|
|
288
|
-
return callToolResultToText(result);
|
|
289
|
-
} catch (err) {
|
|
290
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
291
|
-
return `Error: ${message}`;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
});
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
};
|
|
298
|
-
|
|
299
|
-
// ../../node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs
|
|
300
|
-
var marker = "vercel.ai.error";
|
|
301
|
-
var symbol = Symbol.for(marker);
|
|
302
|
-
var _a;
|
|
303
|
-
var _b;
|
|
304
|
-
var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
|
|
305
|
-
/**
|
|
306
|
-
* Creates an AI SDK Error.
|
|
307
|
-
*
|
|
308
|
-
* @param {Object} params - The parameters for creating the error.
|
|
309
|
-
* @param {string} params.name - The name of the error.
|
|
310
|
-
* @param {string} params.message - The error message.
|
|
311
|
-
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
312
|
-
*/
|
|
313
|
-
constructor({
|
|
314
|
-
name: name142,
|
|
315
|
-
message,
|
|
316
|
-
cause
|
|
317
|
-
}) {
|
|
318
|
-
super(message);
|
|
319
|
-
this[_a] = true;
|
|
320
|
-
this.name = name142;
|
|
321
|
-
this.cause = cause;
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Checks if the given error is an AI SDK Error.
|
|
325
|
-
* @param {unknown} error - The error to check.
|
|
326
|
-
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
327
|
-
*/
|
|
328
|
-
static isInstance(error) {
|
|
329
|
-
return _AISDKError.hasMarker(error, marker);
|
|
330
|
-
}
|
|
331
|
-
static hasMarker(error, marker152) {
|
|
332
|
-
const markerSymbol = Symbol.for(marker152);
|
|
333
|
-
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
334
|
-
}
|
|
335
|
-
};
|
|
336
|
-
var name = "AI_APICallError";
|
|
337
|
-
var marker2 = `vercel.ai.error.${name}`;
|
|
338
|
-
var symbol2 = Symbol.for(marker2);
|
|
339
|
-
var _a2;
|
|
340
|
-
var _b2;
|
|
341
|
-
var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
|
|
342
|
-
constructor({
|
|
343
|
-
message,
|
|
344
|
-
url,
|
|
345
|
-
requestBodyValues,
|
|
346
|
-
statusCode,
|
|
347
|
-
responseHeaders,
|
|
348
|
-
responseBody,
|
|
349
|
-
cause,
|
|
350
|
-
isRetryable = statusCode != null && (statusCode === 408 || // request timeout
|
|
351
|
-
statusCode === 409 || // conflict
|
|
352
|
-
statusCode === 429 || // too many requests
|
|
353
|
-
statusCode >= 500),
|
|
354
|
-
// server error
|
|
355
|
-
data
|
|
356
|
-
}) {
|
|
357
|
-
super({ name, message, cause });
|
|
358
|
-
this[_a2] = true;
|
|
359
|
-
this.url = url;
|
|
360
|
-
this.requestBodyValues = requestBodyValues;
|
|
361
|
-
this.statusCode = statusCode;
|
|
362
|
-
this.responseHeaders = responseHeaders;
|
|
363
|
-
this.responseBody = responseBody;
|
|
364
|
-
this.isRetryable = isRetryable;
|
|
365
|
-
this.data = data;
|
|
366
|
-
}
|
|
367
|
-
static isInstance(error) {
|
|
368
|
-
return AISDKError.hasMarker(error, marker2);
|
|
369
|
-
}
|
|
370
|
-
};
|
|
371
|
-
var name2 = "AI_EmptyResponseBodyError";
|
|
372
|
-
var marker3 = `vercel.ai.error.${name2}`;
|
|
373
|
-
var symbol3 = Symbol.for(marker3);
|
|
374
|
-
var _a3;
|
|
375
|
-
var _b3;
|
|
376
|
-
var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
|
|
377
|
-
// used in isInstance
|
|
378
|
-
constructor({ message = "Empty response body" } = {}) {
|
|
379
|
-
super({ name: name2, message });
|
|
380
|
-
this[_a3] = true;
|
|
381
|
-
}
|
|
382
|
-
static isInstance(error) {
|
|
383
|
-
return AISDKError.hasMarker(error, marker3);
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
function getErrorMessage(error) {
|
|
387
|
-
if (error == null) {
|
|
388
|
-
return "unknown error";
|
|
389
|
-
}
|
|
390
|
-
if (typeof error === "string") {
|
|
391
|
-
return error;
|
|
392
|
-
}
|
|
393
|
-
if (error instanceof Error) {
|
|
394
|
-
return error.message;
|
|
395
|
-
}
|
|
396
|
-
return JSON.stringify(error);
|
|
397
|
-
}
|
|
398
|
-
var name3 = "AI_InvalidArgumentError";
|
|
399
|
-
var marker4 = `vercel.ai.error.${name3}`;
|
|
400
|
-
var symbol4 = Symbol.for(marker4);
|
|
401
|
-
var _a4;
|
|
402
|
-
var _b4;
|
|
403
|
-
var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
|
|
404
|
-
constructor({
|
|
405
|
-
message,
|
|
406
|
-
cause,
|
|
407
|
-
argument
|
|
408
|
-
}) {
|
|
409
|
-
super({ name: name3, message, cause });
|
|
410
|
-
this[_a4] = true;
|
|
411
|
-
this.argument = argument;
|
|
412
|
-
}
|
|
413
|
-
static isInstance(error) {
|
|
414
|
-
return AISDKError.hasMarker(error, marker4);
|
|
415
|
-
}
|
|
416
|
-
};
|
|
417
|
-
var name4 = "AI_InvalidPromptError";
|
|
418
|
-
var marker5 = `vercel.ai.error.${name4}`;
|
|
419
|
-
var symbol5 = Symbol.for(marker5);
|
|
420
|
-
var _a5;
|
|
421
|
-
var _b5;
|
|
422
|
-
var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
|
|
423
|
-
constructor({
|
|
424
|
-
prompt,
|
|
425
|
-
message,
|
|
426
|
-
cause
|
|
427
|
-
}) {
|
|
428
|
-
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
429
|
-
this[_a5] = true;
|
|
430
|
-
this.prompt = prompt;
|
|
431
|
-
}
|
|
432
|
-
static isInstance(error) {
|
|
433
|
-
return AISDKError.hasMarker(error, marker5);
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
var name5 = "AI_InvalidResponseDataError";
|
|
437
|
-
var marker6 = `vercel.ai.error.${name5}`;
|
|
438
|
-
var symbol6 = Symbol.for(marker6);
|
|
439
|
-
var _a6;
|
|
440
|
-
var _b6;
|
|
441
|
-
var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {
|
|
442
|
-
constructor({
|
|
443
|
-
data,
|
|
444
|
-
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
445
|
-
}) {
|
|
446
|
-
super({ name: name5, message });
|
|
447
|
-
this[_a6] = true;
|
|
448
|
-
this.data = data;
|
|
449
|
-
}
|
|
450
|
-
static isInstance(error) {
|
|
451
|
-
return AISDKError.hasMarker(error, marker6);
|
|
452
|
-
}
|
|
453
|
-
};
|
|
454
|
-
var name6 = "AI_JSONParseError";
|
|
455
|
-
var marker7 = `vercel.ai.error.${name6}`;
|
|
456
|
-
var symbol7 = Symbol.for(marker7);
|
|
457
|
-
var _a7;
|
|
458
|
-
var _b7;
|
|
459
|
-
var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
|
|
460
|
-
constructor({ text, cause }) {
|
|
461
|
-
super({
|
|
462
|
-
name: name6,
|
|
463
|
-
message: `JSON parsing failed: Text: ${text}.
|
|
464
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
465
|
-
cause
|
|
466
|
-
});
|
|
467
|
-
this[_a7] = true;
|
|
468
|
-
this.text = text;
|
|
469
|
-
}
|
|
470
|
-
static isInstance(error) {
|
|
471
|
-
return AISDKError.hasMarker(error, marker7);
|
|
472
|
-
}
|
|
473
|
-
};
|
|
474
|
-
var name7 = "AI_LoadAPIKeyError";
|
|
475
|
-
var marker8 = `vercel.ai.error.${name7}`;
|
|
476
|
-
var symbol8 = Symbol.for(marker8);
|
|
477
|
-
var _a8;
|
|
478
|
-
var _b8;
|
|
479
|
-
var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
|
|
480
|
-
// used in isInstance
|
|
481
|
-
constructor({ message }) {
|
|
482
|
-
super({ name: name7, message });
|
|
483
|
-
this[_a8] = true;
|
|
484
|
-
}
|
|
485
|
-
static isInstance(error) {
|
|
486
|
-
return AISDKError.hasMarker(error, marker8);
|
|
487
|
-
}
|
|
488
|
-
};
|
|
489
|
-
var name8 = "AI_LoadSettingError";
|
|
490
|
-
var marker9 = `vercel.ai.error.${name8}`;
|
|
491
|
-
var symbol9 = Symbol.for(marker9);
|
|
492
|
-
var _a9;
|
|
493
|
-
var _b9;
|
|
494
|
-
var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {
|
|
495
|
-
// used in isInstance
|
|
496
|
-
constructor({ message }) {
|
|
497
|
-
super({ name: name8, message });
|
|
498
|
-
this[_a9] = true;
|
|
499
|
-
}
|
|
500
|
-
static isInstance(error) {
|
|
501
|
-
return AISDKError.hasMarker(error, marker9);
|
|
502
|
-
}
|
|
503
|
-
};
|
|
504
|
-
var name9 = "AI_NoContentGeneratedError";
|
|
505
|
-
var marker10 = `vercel.ai.error.${name9}`;
|
|
506
|
-
var symbol10 = Symbol.for(marker10);
|
|
507
|
-
var _a10;
|
|
508
|
-
var _b10;
|
|
509
|
-
var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
|
|
510
|
-
// used in isInstance
|
|
511
|
-
constructor({
|
|
512
|
-
message = "No content generated."
|
|
513
|
-
} = {}) {
|
|
514
|
-
super({ name: name9, message });
|
|
515
|
-
this[_a10] = true;
|
|
516
|
-
}
|
|
517
|
-
static isInstance(error) {
|
|
518
|
-
return AISDKError.hasMarker(error, marker10);
|
|
519
|
-
}
|
|
520
|
-
};
|
|
521
|
-
var name10 = "AI_NoSuchModelError";
|
|
522
|
-
var marker11 = `vercel.ai.error.${name10}`;
|
|
523
|
-
var symbol11 = Symbol.for(marker11);
|
|
524
|
-
var _a11;
|
|
525
|
-
var _b11;
|
|
526
|
-
var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
|
|
527
|
-
constructor({
|
|
528
|
-
errorName = name10,
|
|
529
|
-
modelId,
|
|
530
|
-
modelType,
|
|
531
|
-
message = `No such ${modelType}: ${modelId}`
|
|
532
|
-
}) {
|
|
533
|
-
super({ name: errorName, message });
|
|
534
|
-
this[_a11] = true;
|
|
535
|
-
this.modelId = modelId;
|
|
536
|
-
this.modelType = modelType;
|
|
537
|
-
}
|
|
538
|
-
static isInstance(error) {
|
|
539
|
-
return AISDKError.hasMarker(error, marker11);
|
|
540
|
-
}
|
|
541
|
-
};
|
|
542
|
-
var name11 = "AI_TooManyEmbeddingValuesForCallError";
|
|
543
|
-
var marker12 = `vercel.ai.error.${name11}`;
|
|
544
|
-
var symbol12 = Symbol.for(marker12);
|
|
545
|
-
var _a12;
|
|
546
|
-
var _b12;
|
|
547
|
-
var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
|
|
548
|
-
constructor(options) {
|
|
549
|
-
super({
|
|
550
|
-
name: name11,
|
|
551
|
-
message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
|
|
552
|
-
});
|
|
553
|
-
this[_a12] = true;
|
|
554
|
-
this.provider = options.provider;
|
|
555
|
-
this.modelId = options.modelId;
|
|
556
|
-
this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
|
|
557
|
-
this.values = options.values;
|
|
558
|
-
}
|
|
559
|
-
static isInstance(error) {
|
|
560
|
-
return AISDKError.hasMarker(error, marker12);
|
|
561
|
-
}
|
|
562
|
-
};
|
|
563
|
-
var name12 = "AI_TypeValidationError";
|
|
564
|
-
var marker13 = `vercel.ai.error.${name12}`;
|
|
565
|
-
var symbol13 = Symbol.for(marker13);
|
|
566
|
-
var _a13;
|
|
567
|
-
var _b13;
|
|
568
|
-
var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
|
|
569
|
-
constructor({
|
|
570
|
-
value,
|
|
571
|
-
cause,
|
|
572
|
-
context
|
|
573
|
-
}) {
|
|
574
|
-
let contextPrefix = "Type validation failed";
|
|
575
|
-
if (context == null ? void 0 : context.field) {
|
|
576
|
-
contextPrefix += ` for ${context.field}`;
|
|
577
|
-
}
|
|
578
|
-
if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
|
|
579
|
-
contextPrefix += " (";
|
|
580
|
-
const parts = [];
|
|
581
|
-
if (context.entityName) {
|
|
582
|
-
parts.push(context.entityName);
|
|
583
|
-
}
|
|
584
|
-
if (context.entityId) {
|
|
585
|
-
parts.push(`id: "${context.entityId}"`);
|
|
586
|
-
}
|
|
587
|
-
contextPrefix += parts.join(", ");
|
|
588
|
-
contextPrefix += ")";
|
|
589
|
-
}
|
|
590
|
-
super({
|
|
591
|
-
name: name12,
|
|
592
|
-
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
|
|
593
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
594
|
-
cause
|
|
595
|
-
});
|
|
596
|
-
this[_a13] = true;
|
|
597
|
-
this.value = value;
|
|
598
|
-
this.context = context;
|
|
599
|
-
}
|
|
600
|
-
static isInstance(error) {
|
|
601
|
-
return AISDKError.hasMarker(error, marker13);
|
|
602
|
-
}
|
|
603
|
-
/**
|
|
604
|
-
* Wraps an error into a TypeValidationError.
|
|
605
|
-
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
|
|
606
|
-
* Otherwise, it creates a new TypeValidationError.
|
|
607
|
-
*
|
|
608
|
-
* @param {Object} params - The parameters for wrapping the error.
|
|
609
|
-
* @param {unknown} params.value - The value that failed validation.
|
|
610
|
-
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
611
|
-
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
|
|
612
|
-
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
613
|
-
*/
|
|
614
|
-
static wrap({
|
|
615
|
-
value,
|
|
616
|
-
cause,
|
|
617
|
-
context
|
|
618
|
-
}) {
|
|
619
|
-
var _a152, _b152, _c;
|
|
620
|
-
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a152 = cause.context) == null ? void 0 : _a152.field) === (context == null ? void 0 : context.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {
|
|
621
|
-
return cause;
|
|
622
|
-
}
|
|
623
|
-
return new _TypeValidationError({ value, cause, context });
|
|
624
|
-
}
|
|
625
|
-
};
|
|
626
|
-
var name13 = "AI_UnsupportedFunctionalityError";
|
|
627
|
-
var marker14 = `vercel.ai.error.${name13}`;
|
|
628
|
-
var symbol14 = Symbol.for(marker14);
|
|
629
|
-
var _a14;
|
|
630
|
-
var _b14;
|
|
631
|
-
var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
|
|
632
|
-
constructor({
|
|
633
|
-
functionality,
|
|
634
|
-
message = `'${functionality}' functionality not supported.`
|
|
635
|
-
}) {
|
|
636
|
-
super({ name: name13, message });
|
|
637
|
-
this[_a14] = true;
|
|
638
|
-
this.functionality = functionality;
|
|
639
|
-
}
|
|
640
|
-
static isInstance(error) {
|
|
641
|
-
return AISDKError.hasMarker(error, marker14);
|
|
642
|
-
}
|
|
643
|
-
};
|
|
644
|
-
|
|
645
|
-
// ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.19_zod@4.4.3/node_modules/@ai-sdk/provider-utils/dist/index.mjs
|
|
646
|
-
import * as z42 from "zod/v4";
|
|
647
|
-
import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
|
|
648
|
-
import { ZodFirstPartyTypeKind } from "zod/v3";
|
|
649
1
|
import {
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
throw new TypeError(
|
|
664
|
-
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
665
|
-
);
|
|
666
|
-
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
667
|
-
let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
|
|
668
|
-
function feed(newChunk) {
|
|
669
|
-
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
670
|
-
for (const line of complete)
|
|
671
|
-
parseLine(line);
|
|
672
|
-
incompleteLine = incomplete, isFirstChunk = false;
|
|
673
|
-
}
|
|
674
|
-
function parseLine(line) {
|
|
675
|
-
if (line === "") {
|
|
676
|
-
dispatchEvent();
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
if (line.startsWith(":")) {
|
|
680
|
-
onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
681
|
-
return;
|
|
682
|
-
}
|
|
683
|
-
const fieldSeparatorIndex = line.indexOf(":");
|
|
684
|
-
if (fieldSeparatorIndex !== -1) {
|
|
685
|
-
const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
|
|
686
|
-
processField(field, value, line);
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
processField(line, "", line);
|
|
690
|
-
}
|
|
691
|
-
function processField(field, value, line) {
|
|
692
|
-
switch (field) {
|
|
693
|
-
case "event":
|
|
694
|
-
eventType = value;
|
|
695
|
-
break;
|
|
696
|
-
case "data":
|
|
697
|
-
data = `${data}${value}
|
|
698
|
-
`;
|
|
699
|
-
break;
|
|
700
|
-
case "id":
|
|
701
|
-
id = value.includes("\0") ? void 0 : value;
|
|
702
|
-
break;
|
|
703
|
-
case "retry":
|
|
704
|
-
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
705
|
-
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
706
|
-
type: "invalid-retry",
|
|
707
|
-
value,
|
|
708
|
-
line
|
|
709
|
-
})
|
|
710
|
-
);
|
|
711
|
-
break;
|
|
712
|
-
default:
|
|
713
|
-
onError(
|
|
714
|
-
new ParseError(
|
|
715
|
-
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
716
|
-
{ type: "unknown-field", field, value, line }
|
|
717
|
-
)
|
|
718
|
-
);
|
|
719
|
-
break;
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
function dispatchEvent() {
|
|
723
|
-
data.length > 0 && onEvent({
|
|
724
|
-
id,
|
|
725
|
-
event: eventType || void 0,
|
|
726
|
-
// If the data buffer's last character is a U+000A LINE FEED (LF) character,
|
|
727
|
-
// then remove the last character from the data buffer.
|
|
728
|
-
data: data.endsWith(`
|
|
729
|
-
`) ? data.slice(0, -1) : data
|
|
730
|
-
}), id = void 0, data = "", eventType = "";
|
|
731
|
-
}
|
|
732
|
-
function reset(options = {}) {
|
|
733
|
-
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
|
|
734
|
-
}
|
|
735
|
-
return { feed, reset };
|
|
736
|
-
}
|
|
737
|
-
function splitLines(chunk) {
|
|
738
|
-
const lines = [];
|
|
739
|
-
let incompleteLine = "", searchIndex = 0;
|
|
740
|
-
for (; searchIndex < chunk.length; ) {
|
|
741
|
-
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
742
|
-
`, searchIndex);
|
|
743
|
-
let lineEnd = -1;
|
|
744
|
-
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
|
|
745
|
-
incompleteLine = chunk.slice(searchIndex);
|
|
746
|
-
break;
|
|
747
|
-
} else {
|
|
748
|
-
const line = chunk.slice(searchIndex, lineEnd);
|
|
749
|
-
lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
|
|
750
|
-
` && searchIndex++;
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
return [lines, incompleteLine];
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
// ../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
|
|
757
|
-
var EventSourceParserStream = class extends TransformStream {
|
|
758
|
-
constructor({ onError, onRetry, onComment } = {}) {
|
|
759
|
-
let parser;
|
|
760
|
-
super({
|
|
761
|
-
start(controller) {
|
|
762
|
-
parser = createParser({
|
|
763
|
-
onEvent: (event) => {
|
|
764
|
-
controller.enqueue(event);
|
|
765
|
-
},
|
|
766
|
-
onError(error) {
|
|
767
|
-
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
|
|
768
|
-
},
|
|
769
|
-
onRetry,
|
|
770
|
-
onComment
|
|
771
|
-
});
|
|
772
|
-
},
|
|
773
|
-
transform(chunk) {
|
|
774
|
-
parser.feed(chunk);
|
|
775
|
-
}
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
};
|
|
779
|
-
|
|
780
|
-
// ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.19_zod@4.4.3/node_modules/@ai-sdk/provider-utils/dist/index.mjs
|
|
781
|
-
var { btoa: btoa2, atob } = globalThis;
|
|
782
|
-
var name14 = "AI_DownloadError";
|
|
783
|
-
var marker15 = `vercel.ai.error.${name14}`;
|
|
784
|
-
var symbol15 = Symbol.for(marker15);
|
|
785
|
-
var _a15;
|
|
786
|
-
var _b15;
|
|
787
|
-
var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
|
|
788
|
-
constructor({
|
|
789
|
-
url,
|
|
790
|
-
statusCode,
|
|
791
|
-
statusText,
|
|
792
|
-
cause,
|
|
793
|
-
message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
|
|
794
|
-
}) {
|
|
795
|
-
super({ name: name14, message, cause });
|
|
796
|
-
this[_a15] = true;
|
|
797
|
-
this.url = url;
|
|
798
|
-
this.statusCode = statusCode;
|
|
799
|
-
this.statusText = statusText;
|
|
800
|
-
}
|
|
801
|
-
static isInstance(error) {
|
|
802
|
-
return AISDKError.hasMarker(error, marker15);
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
|
|
806
|
-
var createIdGenerator = ({
|
|
807
|
-
prefix,
|
|
808
|
-
size = 16,
|
|
809
|
-
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
810
|
-
separator = "-"
|
|
811
|
-
} = {}) => {
|
|
812
|
-
const generator = () => {
|
|
813
|
-
const alphabetLength = alphabet.length;
|
|
814
|
-
const chars = new Array(size);
|
|
815
|
-
for (let i = 0; i < size; i++) {
|
|
816
|
-
chars[i] = alphabet[Math.random() * alphabetLength | 0];
|
|
817
|
-
}
|
|
818
|
-
return chars.join("");
|
|
819
|
-
};
|
|
820
|
-
if (prefix == null) {
|
|
821
|
-
return generator;
|
|
822
|
-
}
|
|
823
|
-
if (alphabet.includes(separator)) {
|
|
824
|
-
throw new InvalidArgumentError({
|
|
825
|
-
argument: "separator",
|
|
826
|
-
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
return () => `${prefix}${separator}${generator()}`;
|
|
830
|
-
};
|
|
831
|
-
var generateId = createIdGenerator();
|
|
832
|
-
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
|
|
833
|
-
var _a23, _b23, _c;
|
|
834
|
-
if (globalThisAny.window) {
|
|
835
|
-
return `runtime/browser`;
|
|
836
|
-
}
|
|
837
|
-
if ((_a23 = globalThisAny.navigator) == null ? void 0 : _a23.userAgent) {
|
|
838
|
-
return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
|
|
839
|
-
}
|
|
840
|
-
if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.versions) == null ? void 0 : _c.node) {
|
|
841
|
-
return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
|
|
842
|
-
}
|
|
843
|
-
if (globalThisAny.EdgeRuntime) {
|
|
844
|
-
return `runtime/vercel-edge`;
|
|
845
|
-
}
|
|
846
|
-
return "runtime/unknown";
|
|
847
|
-
}
|
|
848
|
-
function normalizeHeaders(headers) {
|
|
849
|
-
if (headers == null) {
|
|
850
|
-
return {};
|
|
851
|
-
}
|
|
852
|
-
const normalized = {};
|
|
853
|
-
if (headers instanceof Headers) {
|
|
854
|
-
headers.forEach((value, key) => {
|
|
855
|
-
normalized[key.toLowerCase()] = value;
|
|
856
|
-
});
|
|
857
|
-
} else {
|
|
858
|
-
if (!Array.isArray(headers)) {
|
|
859
|
-
headers = Object.entries(headers);
|
|
860
|
-
}
|
|
861
|
-
for (const [key, value] of headers) {
|
|
862
|
-
if (value != null) {
|
|
863
|
-
normalized[key.toLowerCase()] = value;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
return normalized;
|
|
868
|
-
}
|
|
869
|
-
function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
|
|
870
|
-
const normalizedHeaders = new Headers(normalizeHeaders(headers));
|
|
871
|
-
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
|
|
872
|
-
normalizedHeaders.set(
|
|
873
|
-
"user-agent",
|
|
874
|
-
[currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
|
|
875
|
-
);
|
|
876
|
-
return Object.fromEntries(normalizedHeaders.entries());
|
|
877
|
-
}
|
|
878
|
-
var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
879
|
-
var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
880
|
-
function _parse(text) {
|
|
881
|
-
const obj = JSON.parse(text);
|
|
882
|
-
if (obj === null || typeof obj !== "object") {
|
|
883
|
-
return obj;
|
|
884
|
-
}
|
|
885
|
-
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
|
|
886
|
-
return obj;
|
|
887
|
-
}
|
|
888
|
-
return filter(obj);
|
|
889
|
-
}
|
|
890
|
-
function filter(obj) {
|
|
891
|
-
let next = [obj];
|
|
892
|
-
while (next.length) {
|
|
893
|
-
const nodes = next;
|
|
894
|
-
next = [];
|
|
895
|
-
for (const node of nodes) {
|
|
896
|
-
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
|
|
897
|
-
throw new SyntaxError("Object contains forbidden prototype property");
|
|
898
|
-
}
|
|
899
|
-
if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
|
|
900
|
-
throw new SyntaxError("Object contains forbidden prototype property");
|
|
901
|
-
}
|
|
902
|
-
for (const key in node) {
|
|
903
|
-
const value = node[key];
|
|
904
|
-
if (value && typeof value === "object") {
|
|
905
|
-
next.push(value);
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
return obj;
|
|
911
|
-
}
|
|
912
|
-
function secureJsonParse(text) {
|
|
913
|
-
const { stackTraceLimit } = Error;
|
|
914
|
-
try {
|
|
915
|
-
Error.stackTraceLimit = 0;
|
|
916
|
-
} catch (e) {
|
|
917
|
-
return _parse(text);
|
|
918
|
-
}
|
|
919
|
-
try {
|
|
920
|
-
return _parse(text);
|
|
921
|
-
} finally {
|
|
922
|
-
Error.stackTraceLimit = stackTraceLimit;
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
|
|
926
|
-
if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
|
|
927
|
-
jsonSchema2.additionalProperties = false;
|
|
928
|
-
const { properties } = jsonSchema2;
|
|
929
|
-
if (properties != null) {
|
|
930
|
-
for (const key of Object.keys(properties)) {
|
|
931
|
-
properties[key] = visit(properties[key]);
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
if (jsonSchema2.items != null) {
|
|
936
|
-
jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
|
|
937
|
-
}
|
|
938
|
-
if (jsonSchema2.anyOf != null) {
|
|
939
|
-
jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
|
|
940
|
-
}
|
|
941
|
-
if (jsonSchema2.allOf != null) {
|
|
942
|
-
jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
|
|
943
|
-
}
|
|
944
|
-
if (jsonSchema2.oneOf != null) {
|
|
945
|
-
jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
|
|
946
|
-
}
|
|
947
|
-
const { definitions } = jsonSchema2;
|
|
948
|
-
if (definitions != null) {
|
|
949
|
-
for (const key of Object.keys(definitions)) {
|
|
950
|
-
definitions[key] = visit(definitions[key]);
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
return jsonSchema2;
|
|
954
|
-
}
|
|
955
|
-
function visit(def) {
|
|
956
|
-
if (typeof def === "boolean") return def;
|
|
957
|
-
return addAdditionalPropertiesToJsonSchema(def);
|
|
958
|
-
}
|
|
959
|
-
var ignoreOverride = Symbol(
|
|
960
|
-
"Let zodToJsonSchema decide on which parser to use"
|
|
961
|
-
);
|
|
962
|
-
var defaultOptions = {
|
|
963
|
-
name: void 0,
|
|
964
|
-
$refStrategy: "root",
|
|
965
|
-
basePath: ["#"],
|
|
966
|
-
effectStrategy: "input",
|
|
967
|
-
pipeStrategy: "all",
|
|
968
|
-
dateStrategy: "format:date-time",
|
|
969
|
-
mapStrategy: "entries",
|
|
970
|
-
removeAdditionalStrategy: "passthrough",
|
|
971
|
-
allowedAdditionalProperties: true,
|
|
972
|
-
rejectedAdditionalProperties: false,
|
|
973
|
-
definitionPath: "definitions",
|
|
974
|
-
strictUnions: false,
|
|
975
|
-
definitions: {},
|
|
976
|
-
errorMessages: false,
|
|
977
|
-
patternStrategy: "escape",
|
|
978
|
-
applyRegexFlags: false,
|
|
979
|
-
emailStrategy: "format:email",
|
|
980
|
-
base64Strategy: "contentEncoding:base64",
|
|
981
|
-
nameStrategy: "ref"
|
|
982
|
-
};
|
|
983
|
-
var getDefaultOptions = (options) => typeof options === "string" ? {
|
|
984
|
-
...defaultOptions,
|
|
985
|
-
name: options
|
|
986
|
-
} : {
|
|
987
|
-
...defaultOptions,
|
|
988
|
-
...options
|
|
989
|
-
};
|
|
990
|
-
function parseAnyDef() {
|
|
991
|
-
return {};
|
|
992
|
-
}
|
|
993
|
-
function parseArrayDef(def, refs) {
|
|
994
|
-
var _a23, _b23, _c;
|
|
995
|
-
const res = {
|
|
996
|
-
type: "array"
|
|
997
|
-
};
|
|
998
|
-
if (((_a23 = def.type) == null ? void 0 : _a23._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
|
|
999
|
-
res.items = parseDef(def.type._def, {
|
|
1000
|
-
...refs,
|
|
1001
|
-
currentPath: [...refs.currentPath, "items"]
|
|
1002
|
-
});
|
|
1003
|
-
}
|
|
1004
|
-
if (def.minLength) {
|
|
1005
|
-
res.minItems = def.minLength.value;
|
|
1006
|
-
}
|
|
1007
|
-
if (def.maxLength) {
|
|
1008
|
-
res.maxItems = def.maxLength.value;
|
|
1009
|
-
}
|
|
1010
|
-
if (def.exactLength) {
|
|
1011
|
-
res.minItems = def.exactLength.value;
|
|
1012
|
-
res.maxItems = def.exactLength.value;
|
|
1013
|
-
}
|
|
1014
|
-
return res;
|
|
1015
|
-
}
|
|
1016
|
-
function parseBigintDef(def) {
|
|
1017
|
-
const res = {
|
|
1018
|
-
type: "integer",
|
|
1019
|
-
format: "int64"
|
|
1020
|
-
};
|
|
1021
|
-
if (!def.checks) return res;
|
|
1022
|
-
for (const check of def.checks) {
|
|
1023
|
-
switch (check.kind) {
|
|
1024
|
-
case "min":
|
|
1025
|
-
if (check.inclusive) {
|
|
1026
|
-
res.minimum = check.value;
|
|
1027
|
-
} else {
|
|
1028
|
-
res.exclusiveMinimum = check.value;
|
|
1029
|
-
}
|
|
1030
|
-
break;
|
|
1031
|
-
case "max":
|
|
1032
|
-
if (check.inclusive) {
|
|
1033
|
-
res.maximum = check.value;
|
|
1034
|
-
} else {
|
|
1035
|
-
res.exclusiveMaximum = check.value;
|
|
1036
|
-
}
|
|
1037
|
-
break;
|
|
1038
|
-
case "multipleOf":
|
|
1039
|
-
res.multipleOf = check.value;
|
|
1040
|
-
break;
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
return res;
|
|
1044
|
-
}
|
|
1045
|
-
function parseBooleanDef() {
|
|
1046
|
-
return { type: "boolean" };
|
|
1047
|
-
}
|
|
1048
|
-
function parseBrandedDef(_def, refs) {
|
|
1049
|
-
return parseDef(_def.type._def, refs);
|
|
1050
|
-
}
|
|
1051
|
-
var parseCatchDef = (def, refs) => {
|
|
1052
|
-
return parseDef(def.innerType._def, refs);
|
|
1053
|
-
};
|
|
1054
|
-
function parseDateDef(def, refs, overrideDateStrategy) {
|
|
1055
|
-
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
|
|
1056
|
-
if (Array.isArray(strategy)) {
|
|
1057
|
-
return {
|
|
1058
|
-
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
|
|
1059
|
-
};
|
|
1060
|
-
}
|
|
1061
|
-
switch (strategy) {
|
|
1062
|
-
case "string":
|
|
1063
|
-
case "format:date-time":
|
|
1064
|
-
return {
|
|
1065
|
-
type: "string",
|
|
1066
|
-
format: "date-time"
|
|
1067
|
-
};
|
|
1068
|
-
case "format:date":
|
|
1069
|
-
return {
|
|
1070
|
-
type: "string",
|
|
1071
|
-
format: "date"
|
|
1072
|
-
};
|
|
1073
|
-
case "integer":
|
|
1074
|
-
return integerDateParser(def);
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
var integerDateParser = (def) => {
|
|
1078
|
-
const res = {
|
|
1079
|
-
type: "integer",
|
|
1080
|
-
format: "unix-time"
|
|
1081
|
-
};
|
|
1082
|
-
for (const check of def.checks) {
|
|
1083
|
-
switch (check.kind) {
|
|
1084
|
-
case "min":
|
|
1085
|
-
res.minimum = check.value;
|
|
1086
|
-
break;
|
|
1087
|
-
case "max":
|
|
1088
|
-
res.maximum = check.value;
|
|
1089
|
-
break;
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
return res;
|
|
1093
|
-
};
|
|
1094
|
-
function parseDefaultDef(_def, refs) {
|
|
1095
|
-
return {
|
|
1096
|
-
...parseDef(_def.innerType._def, refs),
|
|
1097
|
-
default: _def.defaultValue()
|
|
1098
|
-
};
|
|
1099
|
-
}
|
|
1100
|
-
function parseEffectsDef(_def, refs) {
|
|
1101
|
-
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
|
|
1102
|
-
}
|
|
1103
|
-
function parseEnumDef(def) {
|
|
1104
|
-
return {
|
|
1105
|
-
type: "string",
|
|
1106
|
-
enum: Array.from(def.values)
|
|
1107
|
-
};
|
|
1108
|
-
}
|
|
1109
|
-
var isJsonSchema7AllOfType = (type) => {
|
|
1110
|
-
if ("type" in type && type.type === "string") return false;
|
|
1111
|
-
return "allOf" in type;
|
|
1112
|
-
};
|
|
1113
|
-
function parseIntersectionDef(def, refs) {
|
|
1114
|
-
const allOf = [
|
|
1115
|
-
parseDef(def.left._def, {
|
|
1116
|
-
...refs,
|
|
1117
|
-
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
1118
|
-
}),
|
|
1119
|
-
parseDef(def.right._def, {
|
|
1120
|
-
...refs,
|
|
1121
|
-
currentPath: [...refs.currentPath, "allOf", "1"]
|
|
1122
|
-
})
|
|
1123
|
-
].filter((x) => !!x);
|
|
1124
|
-
const mergedAllOf = [];
|
|
1125
|
-
allOf.forEach((schema) => {
|
|
1126
|
-
if (isJsonSchema7AllOfType(schema)) {
|
|
1127
|
-
mergedAllOf.push(...schema.allOf);
|
|
1128
|
-
} else {
|
|
1129
|
-
let nestedSchema = schema;
|
|
1130
|
-
if ("additionalProperties" in schema && schema.additionalProperties === false) {
|
|
1131
|
-
const { additionalProperties, ...rest } = schema;
|
|
1132
|
-
nestedSchema = rest;
|
|
1133
|
-
}
|
|
1134
|
-
mergedAllOf.push(nestedSchema);
|
|
1135
|
-
}
|
|
1136
|
-
});
|
|
1137
|
-
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
|
|
1138
|
-
}
|
|
1139
|
-
function parseLiteralDef(def) {
|
|
1140
|
-
const parsedType = typeof def.value;
|
|
1141
|
-
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
|
|
1142
|
-
return {
|
|
1143
|
-
type: Array.isArray(def.value) ? "array" : "object"
|
|
1144
|
-
};
|
|
1145
|
-
}
|
|
1146
|
-
return {
|
|
1147
|
-
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
1148
|
-
const: def.value
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
var emojiRegex = void 0;
|
|
1152
|
-
var zodPatterns = {
|
|
1153
|
-
/**
|
|
1154
|
-
* `c` was changed to `[cC]` to replicate /i flag
|
|
1155
|
-
*/
|
|
1156
|
-
cuid: /^[cC][^\s-]{8,}$/,
|
|
1157
|
-
cuid2: /^[0-9a-z]+$/,
|
|
1158
|
-
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
1159
|
-
/**
|
|
1160
|
-
* `a-z` was added to replicate /i flag
|
|
1161
|
-
*/
|
|
1162
|
-
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
1163
|
-
/**
|
|
1164
|
-
* Constructed a valid Unicode RegExp
|
|
1165
|
-
*
|
|
1166
|
-
* Lazily instantiate since this type of regex isn't supported
|
|
1167
|
-
* in all envs (e.g. React Native).
|
|
1168
|
-
*
|
|
1169
|
-
* See:
|
|
1170
|
-
* https://github.com/colinhacks/zod/issues/2433
|
|
1171
|
-
* Fix in Zod:
|
|
1172
|
-
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
|
|
1173
|
-
*/
|
|
1174
|
-
emoji: () => {
|
|
1175
|
-
if (emojiRegex === void 0) {
|
|
1176
|
-
emojiRegex = RegExp(
|
|
1177
|
-
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
|
|
1178
|
-
"u"
|
|
1179
|
-
);
|
|
1180
|
-
}
|
|
1181
|
-
return emojiRegex;
|
|
1182
|
-
},
|
|
1183
|
-
/**
|
|
1184
|
-
* Unused
|
|
1185
|
-
*/
|
|
1186
|
-
uuid: /^[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}$/,
|
|
1187
|
-
/**
|
|
1188
|
-
* Unused
|
|
1189
|
-
*/
|
|
1190
|
-
ipv4: /^(?:(?: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])$/,
|
|
1191
|
-
ipv4Cidr: /^(?:(?: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])$/,
|
|
1192
|
-
/**
|
|
1193
|
-
* Unused
|
|
1194
|
-
*/
|
|
1195
|
-
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
|
|
1196
|
-
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
|
|
1197
|
-
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
|
|
1198
|
-
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
|
|
1199
|
-
nanoid: /^[a-zA-Z0-9_-]{21}$/,
|
|
1200
|
-
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
|
|
1201
|
-
};
|
|
1202
|
-
function parseStringDef(def, refs) {
|
|
1203
|
-
const res = {
|
|
1204
|
-
type: "string"
|
|
1205
|
-
};
|
|
1206
|
-
if (def.checks) {
|
|
1207
|
-
for (const check of def.checks) {
|
|
1208
|
-
switch (check.kind) {
|
|
1209
|
-
case "min":
|
|
1210
|
-
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
1211
|
-
break;
|
|
1212
|
-
case "max":
|
|
1213
|
-
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
1214
|
-
break;
|
|
1215
|
-
case "email":
|
|
1216
|
-
switch (refs.emailStrategy) {
|
|
1217
|
-
case "format:email":
|
|
1218
|
-
addFormat(res, "email", check.message, refs);
|
|
1219
|
-
break;
|
|
1220
|
-
case "format:idn-email":
|
|
1221
|
-
addFormat(res, "idn-email", check.message, refs);
|
|
1222
|
-
break;
|
|
1223
|
-
case "pattern:zod":
|
|
1224
|
-
addPattern(res, zodPatterns.email, check.message, refs);
|
|
1225
|
-
break;
|
|
1226
|
-
}
|
|
1227
|
-
break;
|
|
1228
|
-
case "url":
|
|
1229
|
-
addFormat(res, "uri", check.message, refs);
|
|
1230
|
-
break;
|
|
1231
|
-
case "uuid":
|
|
1232
|
-
addFormat(res, "uuid", check.message, refs);
|
|
1233
|
-
break;
|
|
1234
|
-
case "regex":
|
|
1235
|
-
addPattern(res, check.regex, check.message, refs);
|
|
1236
|
-
break;
|
|
1237
|
-
case "cuid":
|
|
1238
|
-
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
1239
|
-
break;
|
|
1240
|
-
case "cuid2":
|
|
1241
|
-
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
1242
|
-
break;
|
|
1243
|
-
case "startsWith":
|
|
1244
|
-
addPattern(
|
|
1245
|
-
res,
|
|
1246
|
-
RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
|
|
1247
|
-
check.message,
|
|
1248
|
-
refs
|
|
1249
|
-
);
|
|
1250
|
-
break;
|
|
1251
|
-
case "endsWith":
|
|
1252
|
-
addPattern(
|
|
1253
|
-
res,
|
|
1254
|
-
RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
|
|
1255
|
-
check.message,
|
|
1256
|
-
refs
|
|
1257
|
-
);
|
|
1258
|
-
break;
|
|
1259
|
-
case "datetime":
|
|
1260
|
-
addFormat(res, "date-time", check.message, refs);
|
|
1261
|
-
break;
|
|
1262
|
-
case "date":
|
|
1263
|
-
addFormat(res, "date", check.message, refs);
|
|
1264
|
-
break;
|
|
1265
|
-
case "time":
|
|
1266
|
-
addFormat(res, "time", check.message, refs);
|
|
1267
|
-
break;
|
|
1268
|
-
case "duration":
|
|
1269
|
-
addFormat(res, "duration", check.message, refs);
|
|
1270
|
-
break;
|
|
1271
|
-
case "length":
|
|
1272
|
-
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
1273
|
-
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
1274
|
-
break;
|
|
1275
|
-
case "includes": {
|
|
1276
|
-
addPattern(
|
|
1277
|
-
res,
|
|
1278
|
-
RegExp(escapeLiteralCheckValue(check.value, refs)),
|
|
1279
|
-
check.message,
|
|
1280
|
-
refs
|
|
1281
|
-
);
|
|
1282
|
-
break;
|
|
1283
|
-
}
|
|
1284
|
-
case "ip": {
|
|
1285
|
-
if (check.version !== "v6") {
|
|
1286
|
-
addFormat(res, "ipv4", check.message, refs);
|
|
1287
|
-
}
|
|
1288
|
-
if (check.version !== "v4") {
|
|
1289
|
-
addFormat(res, "ipv6", check.message, refs);
|
|
1290
|
-
}
|
|
1291
|
-
break;
|
|
1292
|
-
}
|
|
1293
|
-
case "base64url":
|
|
1294
|
-
addPattern(res, zodPatterns.base64url, check.message, refs);
|
|
1295
|
-
break;
|
|
1296
|
-
case "jwt":
|
|
1297
|
-
addPattern(res, zodPatterns.jwt, check.message, refs);
|
|
1298
|
-
break;
|
|
1299
|
-
case "cidr": {
|
|
1300
|
-
if (check.version !== "v6") {
|
|
1301
|
-
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
|
|
1302
|
-
}
|
|
1303
|
-
if (check.version !== "v4") {
|
|
1304
|
-
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
|
|
1305
|
-
}
|
|
1306
|
-
break;
|
|
1307
|
-
}
|
|
1308
|
-
case "emoji":
|
|
1309
|
-
addPattern(res, zodPatterns.emoji(), check.message, refs);
|
|
1310
|
-
break;
|
|
1311
|
-
case "ulid": {
|
|
1312
|
-
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
1313
|
-
break;
|
|
1314
|
-
}
|
|
1315
|
-
case "base64": {
|
|
1316
|
-
switch (refs.base64Strategy) {
|
|
1317
|
-
case "format:binary": {
|
|
1318
|
-
addFormat(res, "binary", check.message, refs);
|
|
1319
|
-
break;
|
|
1320
|
-
}
|
|
1321
|
-
case "contentEncoding:base64": {
|
|
1322
|
-
res.contentEncoding = "base64";
|
|
1323
|
-
break;
|
|
1324
|
-
}
|
|
1325
|
-
case "pattern:zod": {
|
|
1326
|
-
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
1327
|
-
break;
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
break;
|
|
1331
|
-
}
|
|
1332
|
-
case "nanoid": {
|
|
1333
|
-
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
1334
|
-
}
|
|
1335
|
-
case "toLowerCase":
|
|
1336
|
-
case "toUpperCase":
|
|
1337
|
-
case "trim":
|
|
1338
|
-
break;
|
|
1339
|
-
default:
|
|
1340
|
-
/* @__PURE__ */ ((_) => {
|
|
1341
|
-
})(check);
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
return res;
|
|
1346
|
-
}
|
|
1347
|
-
function escapeLiteralCheckValue(literal, refs) {
|
|
1348
|
-
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
|
|
1349
|
-
}
|
|
1350
|
-
var ALPHA_NUMERIC = new Set(
|
|
1351
|
-
"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
|
|
1352
|
-
);
|
|
1353
|
-
function escapeNonAlphaNumeric(source) {
|
|
1354
|
-
let result = "";
|
|
1355
|
-
for (let i = 0; i < source.length; i++) {
|
|
1356
|
-
if (!ALPHA_NUMERIC.has(source[i])) {
|
|
1357
|
-
result += "\\";
|
|
1358
|
-
}
|
|
1359
|
-
result += source[i];
|
|
1360
|
-
}
|
|
1361
|
-
return result;
|
|
1362
|
-
}
|
|
1363
|
-
function addFormat(schema, value, message, refs) {
|
|
1364
|
-
var _a23;
|
|
1365
|
-
if (schema.format || ((_a23 = schema.anyOf) == null ? void 0 : _a23.some((x) => x.format))) {
|
|
1366
|
-
if (!schema.anyOf) {
|
|
1367
|
-
schema.anyOf = [];
|
|
1368
|
-
}
|
|
1369
|
-
if (schema.format) {
|
|
1370
|
-
schema.anyOf.push({
|
|
1371
|
-
format: schema.format
|
|
1372
|
-
});
|
|
1373
|
-
delete schema.format;
|
|
1374
|
-
}
|
|
1375
|
-
schema.anyOf.push({
|
|
1376
|
-
format: value,
|
|
1377
|
-
...message && refs.errorMessages && { errorMessage: { format: message } }
|
|
1378
|
-
});
|
|
1379
|
-
} else {
|
|
1380
|
-
schema.format = value;
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
function addPattern(schema, regex, message, refs) {
|
|
1384
|
-
var _a23;
|
|
1385
|
-
if (schema.pattern || ((_a23 = schema.allOf) == null ? void 0 : _a23.some((x) => x.pattern))) {
|
|
1386
|
-
if (!schema.allOf) {
|
|
1387
|
-
schema.allOf = [];
|
|
1388
|
-
}
|
|
1389
|
-
if (schema.pattern) {
|
|
1390
|
-
schema.allOf.push({
|
|
1391
|
-
pattern: schema.pattern
|
|
1392
|
-
});
|
|
1393
|
-
delete schema.pattern;
|
|
1394
|
-
}
|
|
1395
|
-
schema.allOf.push({
|
|
1396
|
-
pattern: stringifyRegExpWithFlags(regex, refs),
|
|
1397
|
-
...message && refs.errorMessages && { errorMessage: { pattern: message } }
|
|
1398
|
-
});
|
|
1399
|
-
} else {
|
|
1400
|
-
schema.pattern = stringifyRegExpWithFlags(regex, refs);
|
|
1401
|
-
}
|
|
1402
|
-
}
|
|
1403
|
-
function stringifyRegExpWithFlags(regex, refs) {
|
|
1404
|
-
var _a23;
|
|
1405
|
-
if (!refs.applyRegexFlags || !regex.flags) {
|
|
1406
|
-
return regex.source;
|
|
1407
|
-
}
|
|
1408
|
-
const flags = {
|
|
1409
|
-
i: regex.flags.includes("i"),
|
|
1410
|
-
// Case-insensitive
|
|
1411
|
-
m: regex.flags.includes("m"),
|
|
1412
|
-
// `^` and `$` matches adjacent to newline characters
|
|
1413
|
-
s: regex.flags.includes("s")
|
|
1414
|
-
// `.` matches newlines
|
|
1415
|
-
};
|
|
1416
|
-
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
1417
|
-
let pattern = "";
|
|
1418
|
-
let isEscaped = false;
|
|
1419
|
-
let inCharGroup = false;
|
|
1420
|
-
let inCharRange = false;
|
|
1421
|
-
for (let i = 0; i < source.length; i++) {
|
|
1422
|
-
if (isEscaped) {
|
|
1423
|
-
pattern += source[i];
|
|
1424
|
-
isEscaped = false;
|
|
1425
|
-
continue;
|
|
1426
|
-
}
|
|
1427
|
-
if (flags.i) {
|
|
1428
|
-
if (inCharGroup) {
|
|
1429
|
-
if (source[i].match(/[a-z]/)) {
|
|
1430
|
-
if (inCharRange) {
|
|
1431
|
-
pattern += source[i];
|
|
1432
|
-
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
1433
|
-
inCharRange = false;
|
|
1434
|
-
} else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? void 0 : _a23.match(/[a-z]/))) {
|
|
1435
|
-
pattern += source[i];
|
|
1436
|
-
inCharRange = true;
|
|
1437
|
-
} else {
|
|
1438
|
-
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
1439
|
-
}
|
|
1440
|
-
continue;
|
|
1441
|
-
}
|
|
1442
|
-
} else if (source[i].match(/[a-z]/)) {
|
|
1443
|
-
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
1444
|
-
continue;
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
if (flags.m) {
|
|
1448
|
-
if (source[i] === "^") {
|
|
1449
|
-
pattern += `(^|(?<=[\r
|
|
1450
|
-
]))`;
|
|
1451
|
-
continue;
|
|
1452
|
-
} else if (source[i] === "$") {
|
|
1453
|
-
pattern += `($|(?=[\r
|
|
1454
|
-
]))`;
|
|
1455
|
-
continue;
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
if (flags.s && source[i] === ".") {
|
|
1459
|
-
pattern += inCharGroup ? `${source[i]}\r
|
|
1460
|
-
` : `[${source[i]}\r
|
|
1461
|
-
]`;
|
|
1462
|
-
continue;
|
|
1463
|
-
}
|
|
1464
|
-
pattern += source[i];
|
|
1465
|
-
if (source[i] === "\\") {
|
|
1466
|
-
isEscaped = true;
|
|
1467
|
-
} else if (inCharGroup && source[i] === "]") {
|
|
1468
|
-
inCharGroup = false;
|
|
1469
|
-
} else if (!inCharGroup && source[i] === "[") {
|
|
1470
|
-
inCharGroup = true;
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
try {
|
|
1474
|
-
new RegExp(pattern);
|
|
1475
|
-
} catch (e) {
|
|
1476
|
-
console.warn(
|
|
1477
|
-
`Could not convert regex pattern at ${refs.currentPath.join(
|
|
1478
|
-
"/"
|
|
1479
|
-
)} to a flag-independent form! Falling back to the flag-ignorant source`
|
|
1480
|
-
);
|
|
1481
|
-
return regex.source;
|
|
1482
|
-
}
|
|
1483
|
-
return pattern;
|
|
1484
|
-
}
|
|
1485
|
-
function parseRecordDef(def, refs) {
|
|
1486
|
-
var _a23, _b23, _c, _d, _e, _f;
|
|
1487
|
-
const schema = {
|
|
1488
|
-
type: "object",
|
|
1489
|
-
additionalProperties: (_a23 = parseDef(def.valueType._def, {
|
|
1490
|
-
...refs,
|
|
1491
|
-
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
1492
|
-
})) != null ? _a23 : refs.allowedAdditionalProperties
|
|
1493
|
-
};
|
|
1494
|
-
if (((_b23 = def.keyType) == null ? void 0 : _b23._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
|
|
1495
|
-
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
1496
|
-
return {
|
|
1497
|
-
...schema,
|
|
1498
|
-
propertyNames: keyType
|
|
1499
|
-
};
|
|
1500
|
-
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
|
|
1501
|
-
return {
|
|
1502
|
-
...schema,
|
|
1503
|
-
propertyNames: {
|
|
1504
|
-
enum: def.keyType._def.values
|
|
1505
|
-
}
|
|
1506
|
-
};
|
|
1507
|
-
} else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
|
|
1508
|
-
const { type, ...keyType } = parseBrandedDef(
|
|
1509
|
-
def.keyType._def,
|
|
1510
|
-
refs
|
|
1511
|
-
);
|
|
1512
|
-
return {
|
|
1513
|
-
...schema,
|
|
1514
|
-
propertyNames: keyType
|
|
1515
|
-
};
|
|
1516
|
-
}
|
|
1517
|
-
return schema;
|
|
1518
|
-
}
|
|
1519
|
-
function parseMapDef(def, refs) {
|
|
1520
|
-
if (refs.mapStrategy === "record") {
|
|
1521
|
-
return parseRecordDef(def, refs);
|
|
1522
|
-
}
|
|
1523
|
-
const keys = parseDef(def.keyType._def, {
|
|
1524
|
-
...refs,
|
|
1525
|
-
currentPath: [...refs.currentPath, "items", "items", "0"]
|
|
1526
|
-
}) || parseAnyDef();
|
|
1527
|
-
const values = parseDef(def.valueType._def, {
|
|
1528
|
-
...refs,
|
|
1529
|
-
currentPath: [...refs.currentPath, "items", "items", "1"]
|
|
1530
|
-
}) || parseAnyDef();
|
|
1531
|
-
return {
|
|
1532
|
-
type: "array",
|
|
1533
|
-
maxItems: 125,
|
|
1534
|
-
items: {
|
|
1535
|
-
type: "array",
|
|
1536
|
-
items: [keys, values],
|
|
1537
|
-
minItems: 2,
|
|
1538
|
-
maxItems: 2
|
|
1539
|
-
}
|
|
1540
|
-
};
|
|
1541
|
-
}
|
|
1542
|
-
function parseNativeEnumDef(def) {
|
|
1543
|
-
const object = def.values;
|
|
1544
|
-
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
1545
|
-
return typeof object[object[key]] !== "number";
|
|
1546
|
-
});
|
|
1547
|
-
const actualValues = actualKeys.map((key) => object[key]);
|
|
1548
|
-
const parsedTypes = Array.from(
|
|
1549
|
-
new Set(actualValues.map((values) => typeof values))
|
|
1550
|
-
);
|
|
1551
|
-
return {
|
|
1552
|
-
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
|
|
1553
|
-
enum: actualValues
|
|
1554
|
-
};
|
|
1555
|
-
}
|
|
1556
|
-
function parseNeverDef() {
|
|
1557
|
-
return { not: parseAnyDef() };
|
|
1558
|
-
}
|
|
1559
|
-
function parseNullDef() {
|
|
1560
|
-
return {
|
|
1561
|
-
type: "null"
|
|
1562
|
-
};
|
|
1563
|
-
}
|
|
1564
|
-
var primitiveMappings = {
|
|
1565
|
-
ZodString: "string",
|
|
1566
|
-
ZodNumber: "number",
|
|
1567
|
-
ZodBigInt: "integer",
|
|
1568
|
-
ZodBoolean: "boolean",
|
|
1569
|
-
ZodNull: "null"
|
|
1570
|
-
};
|
|
1571
|
-
function parseUnionDef(def, refs) {
|
|
1572
|
-
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
|
|
1573
|
-
if (options.every(
|
|
1574
|
-
(x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
|
|
1575
|
-
)) {
|
|
1576
|
-
const types = options.reduce((types2, x) => {
|
|
1577
|
-
const type = primitiveMappings[x._def.typeName];
|
|
1578
|
-
return type && !types2.includes(type) ? [...types2, type] : types2;
|
|
1579
|
-
}, []);
|
|
1580
|
-
return {
|
|
1581
|
-
type: types.length > 1 ? types : types[0]
|
|
1582
|
-
};
|
|
1583
|
-
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
|
|
1584
|
-
const types = options.reduce(
|
|
1585
|
-
(acc, x) => {
|
|
1586
|
-
const type = typeof x._def.value;
|
|
1587
|
-
switch (type) {
|
|
1588
|
-
case "string":
|
|
1589
|
-
case "number":
|
|
1590
|
-
case "boolean":
|
|
1591
|
-
return [...acc, type];
|
|
1592
|
-
case "bigint":
|
|
1593
|
-
return [...acc, "integer"];
|
|
1594
|
-
case "object":
|
|
1595
|
-
if (x._def.value === null) return [...acc, "null"];
|
|
1596
|
-
case "symbol":
|
|
1597
|
-
case "undefined":
|
|
1598
|
-
case "function":
|
|
1599
|
-
default:
|
|
1600
|
-
return acc;
|
|
1601
|
-
}
|
|
1602
|
-
},
|
|
1603
|
-
[]
|
|
1604
|
-
);
|
|
1605
|
-
if (types.length === options.length) {
|
|
1606
|
-
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
|
|
1607
|
-
return {
|
|
1608
|
-
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
|
|
1609
|
-
enum: options.reduce(
|
|
1610
|
-
(acc, x) => {
|
|
1611
|
-
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
|
|
1612
|
-
},
|
|
1613
|
-
[]
|
|
1614
|
-
)
|
|
1615
|
-
};
|
|
1616
|
-
}
|
|
1617
|
-
} else if (options.every((x) => x._def.typeName === "ZodEnum")) {
|
|
1618
|
-
return {
|
|
1619
|
-
type: "string",
|
|
1620
|
-
enum: options.reduce(
|
|
1621
|
-
(acc, x) => [
|
|
1622
|
-
...acc,
|
|
1623
|
-
...x._def.values.filter((x2) => !acc.includes(x2))
|
|
1624
|
-
],
|
|
1625
|
-
[]
|
|
1626
|
-
)
|
|
1627
|
-
};
|
|
1628
|
-
}
|
|
1629
|
-
return asAnyOf(def, refs);
|
|
1630
|
-
}
|
|
1631
|
-
var asAnyOf = (def, refs) => {
|
|
1632
|
-
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
|
|
1633
|
-
(x, i) => parseDef(x._def, {
|
|
1634
|
-
...refs,
|
|
1635
|
-
currentPath: [...refs.currentPath, "anyOf", `${i}`]
|
|
1636
|
-
})
|
|
1637
|
-
).filter(
|
|
1638
|
-
(x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
|
|
1639
|
-
);
|
|
1640
|
-
return anyOf.length ? { anyOf } : void 0;
|
|
1641
|
-
};
|
|
1642
|
-
function parseNullableDef(def, refs) {
|
|
1643
|
-
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
|
|
1644
|
-
def.innerType._def.typeName
|
|
1645
|
-
) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
|
|
1646
|
-
return {
|
|
1647
|
-
type: [
|
|
1648
|
-
primitiveMappings[def.innerType._def.typeName],
|
|
1649
|
-
"null"
|
|
1650
|
-
]
|
|
1651
|
-
};
|
|
1652
|
-
}
|
|
1653
|
-
const base = parseDef(def.innerType._def, {
|
|
1654
|
-
...refs,
|
|
1655
|
-
currentPath: [...refs.currentPath, "anyOf", "0"]
|
|
1656
|
-
});
|
|
1657
|
-
return base && { anyOf: [base, { type: "null" }] };
|
|
1658
|
-
}
|
|
1659
|
-
function parseNumberDef(def) {
|
|
1660
|
-
const res = {
|
|
1661
|
-
type: "number"
|
|
1662
|
-
};
|
|
1663
|
-
if (!def.checks) return res;
|
|
1664
|
-
for (const check of def.checks) {
|
|
1665
|
-
switch (check.kind) {
|
|
1666
|
-
case "int":
|
|
1667
|
-
res.type = "integer";
|
|
1668
|
-
break;
|
|
1669
|
-
case "min":
|
|
1670
|
-
if (check.inclusive) {
|
|
1671
|
-
res.minimum = check.value;
|
|
1672
|
-
} else {
|
|
1673
|
-
res.exclusiveMinimum = check.value;
|
|
1674
|
-
}
|
|
1675
|
-
break;
|
|
1676
|
-
case "max":
|
|
1677
|
-
if (check.inclusive) {
|
|
1678
|
-
res.maximum = check.value;
|
|
1679
|
-
} else {
|
|
1680
|
-
res.exclusiveMaximum = check.value;
|
|
1681
|
-
}
|
|
1682
|
-
break;
|
|
1683
|
-
case "multipleOf":
|
|
1684
|
-
res.multipleOf = check.value;
|
|
1685
|
-
break;
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
return res;
|
|
1689
|
-
}
|
|
1690
|
-
function parseObjectDef(def, refs) {
|
|
1691
|
-
const result = {
|
|
1692
|
-
type: "object",
|
|
1693
|
-
properties: {}
|
|
1694
|
-
};
|
|
1695
|
-
const required = [];
|
|
1696
|
-
const shape = def.shape();
|
|
1697
|
-
for (const propName in shape) {
|
|
1698
|
-
let propDef = shape[propName];
|
|
1699
|
-
if (propDef === void 0 || propDef._def === void 0) {
|
|
1700
|
-
continue;
|
|
1701
|
-
}
|
|
1702
|
-
const propOptional = safeIsOptional(propDef);
|
|
1703
|
-
const parsedDef = parseDef(propDef._def, {
|
|
1704
|
-
...refs,
|
|
1705
|
-
currentPath: [...refs.currentPath, "properties", propName],
|
|
1706
|
-
propertyPath: [...refs.currentPath, "properties", propName]
|
|
1707
|
-
});
|
|
1708
|
-
if (parsedDef === void 0) {
|
|
1709
|
-
continue;
|
|
1710
|
-
}
|
|
1711
|
-
result.properties[propName] = parsedDef;
|
|
1712
|
-
if (!propOptional) {
|
|
1713
|
-
required.push(propName);
|
|
1714
|
-
}
|
|
1715
|
-
}
|
|
1716
|
-
if (required.length) {
|
|
1717
|
-
result.required = required;
|
|
1718
|
-
}
|
|
1719
|
-
const additionalProperties = decideAdditionalProperties(def, refs);
|
|
1720
|
-
if (additionalProperties !== void 0) {
|
|
1721
|
-
result.additionalProperties = additionalProperties;
|
|
1722
|
-
}
|
|
1723
|
-
return result;
|
|
1724
|
-
}
|
|
1725
|
-
function decideAdditionalProperties(def, refs) {
|
|
1726
|
-
if (def.catchall._def.typeName !== "ZodNever") {
|
|
1727
|
-
return parseDef(def.catchall._def, {
|
|
1728
|
-
...refs,
|
|
1729
|
-
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
1730
|
-
});
|
|
1731
|
-
}
|
|
1732
|
-
switch (def.unknownKeys) {
|
|
1733
|
-
case "passthrough":
|
|
1734
|
-
return refs.allowedAdditionalProperties;
|
|
1735
|
-
case "strict":
|
|
1736
|
-
return refs.rejectedAdditionalProperties;
|
|
1737
|
-
case "strip":
|
|
1738
|
-
return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
|
|
1739
|
-
}
|
|
1740
|
-
}
|
|
1741
|
-
function safeIsOptional(schema) {
|
|
1742
|
-
try {
|
|
1743
|
-
return schema.isOptional();
|
|
1744
|
-
} catch (e) {
|
|
1745
|
-
return true;
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
|
-
var parseOptionalDef = (def, refs) => {
|
|
1749
|
-
var _a23;
|
|
1750
|
-
if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? void 0 : _a23.toString())) {
|
|
1751
|
-
return parseDef(def.innerType._def, refs);
|
|
1752
|
-
}
|
|
1753
|
-
const innerSchema = parseDef(def.innerType._def, {
|
|
1754
|
-
...refs,
|
|
1755
|
-
currentPath: [...refs.currentPath, "anyOf", "1"]
|
|
1756
|
-
});
|
|
1757
|
-
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
|
|
1758
|
-
};
|
|
1759
|
-
var parsePipelineDef = (def, refs) => {
|
|
1760
|
-
if (refs.pipeStrategy === "input") {
|
|
1761
|
-
return parseDef(def.in._def, refs);
|
|
1762
|
-
} else if (refs.pipeStrategy === "output") {
|
|
1763
|
-
return parseDef(def.out._def, refs);
|
|
1764
|
-
}
|
|
1765
|
-
const a = parseDef(def.in._def, {
|
|
1766
|
-
...refs,
|
|
1767
|
-
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
1768
|
-
});
|
|
1769
|
-
const b = parseDef(def.out._def, {
|
|
1770
|
-
...refs,
|
|
1771
|
-
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
|
|
1772
|
-
});
|
|
1773
|
-
return {
|
|
1774
|
-
allOf: [a, b].filter((x) => x !== void 0)
|
|
1775
|
-
};
|
|
1776
|
-
};
|
|
1777
|
-
function parsePromiseDef(def, refs) {
|
|
1778
|
-
return parseDef(def.type._def, refs);
|
|
1779
|
-
}
|
|
1780
|
-
function parseSetDef(def, refs) {
|
|
1781
|
-
const items = parseDef(def.valueType._def, {
|
|
1782
|
-
...refs,
|
|
1783
|
-
currentPath: [...refs.currentPath, "items"]
|
|
1784
|
-
});
|
|
1785
|
-
const schema = {
|
|
1786
|
-
type: "array",
|
|
1787
|
-
uniqueItems: true,
|
|
1788
|
-
items
|
|
1789
|
-
};
|
|
1790
|
-
if (def.minSize) {
|
|
1791
|
-
schema.minItems = def.minSize.value;
|
|
1792
|
-
}
|
|
1793
|
-
if (def.maxSize) {
|
|
1794
|
-
schema.maxItems = def.maxSize.value;
|
|
1795
|
-
}
|
|
1796
|
-
return schema;
|
|
1797
|
-
}
|
|
1798
|
-
function parseTupleDef(def, refs) {
|
|
1799
|
-
if (def.rest) {
|
|
1800
|
-
return {
|
|
1801
|
-
type: "array",
|
|
1802
|
-
minItems: def.items.length,
|
|
1803
|
-
items: def.items.map(
|
|
1804
|
-
(x, i) => parseDef(x._def, {
|
|
1805
|
-
...refs,
|
|
1806
|
-
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1807
|
-
})
|
|
1808
|
-
).reduce(
|
|
1809
|
-
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1810
|
-
[]
|
|
1811
|
-
),
|
|
1812
|
-
additionalItems: parseDef(def.rest._def, {
|
|
1813
|
-
...refs,
|
|
1814
|
-
currentPath: [...refs.currentPath, "additionalItems"]
|
|
1815
|
-
})
|
|
1816
|
-
};
|
|
1817
|
-
} else {
|
|
1818
|
-
return {
|
|
1819
|
-
type: "array",
|
|
1820
|
-
minItems: def.items.length,
|
|
1821
|
-
maxItems: def.items.length,
|
|
1822
|
-
items: def.items.map(
|
|
1823
|
-
(x, i) => parseDef(x._def, {
|
|
1824
|
-
...refs,
|
|
1825
|
-
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1826
|
-
})
|
|
1827
|
-
).reduce(
|
|
1828
|
-
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1829
|
-
[]
|
|
1830
|
-
)
|
|
1831
|
-
};
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
function parseUndefinedDef() {
|
|
1835
|
-
return {
|
|
1836
|
-
not: parseAnyDef()
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
function parseUnknownDef() {
|
|
1840
|
-
return parseAnyDef();
|
|
1841
|
-
}
|
|
1842
|
-
var parseReadonlyDef = (def, refs) => {
|
|
1843
|
-
return parseDef(def.innerType._def, refs);
|
|
1844
|
-
};
|
|
1845
|
-
var selectParser = (def, typeName, refs) => {
|
|
1846
|
-
switch (typeName) {
|
|
1847
|
-
case ZodFirstPartyTypeKind3.ZodString:
|
|
1848
|
-
return parseStringDef(def, refs);
|
|
1849
|
-
case ZodFirstPartyTypeKind3.ZodNumber:
|
|
1850
|
-
return parseNumberDef(def);
|
|
1851
|
-
case ZodFirstPartyTypeKind3.ZodObject:
|
|
1852
|
-
return parseObjectDef(def, refs);
|
|
1853
|
-
case ZodFirstPartyTypeKind3.ZodBigInt:
|
|
1854
|
-
return parseBigintDef(def);
|
|
1855
|
-
case ZodFirstPartyTypeKind3.ZodBoolean:
|
|
1856
|
-
return parseBooleanDef();
|
|
1857
|
-
case ZodFirstPartyTypeKind3.ZodDate:
|
|
1858
|
-
return parseDateDef(def, refs);
|
|
1859
|
-
case ZodFirstPartyTypeKind3.ZodUndefined:
|
|
1860
|
-
return parseUndefinedDef();
|
|
1861
|
-
case ZodFirstPartyTypeKind3.ZodNull:
|
|
1862
|
-
return parseNullDef();
|
|
1863
|
-
case ZodFirstPartyTypeKind3.ZodArray:
|
|
1864
|
-
return parseArrayDef(def, refs);
|
|
1865
|
-
case ZodFirstPartyTypeKind3.ZodUnion:
|
|
1866
|
-
case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
|
|
1867
|
-
return parseUnionDef(def, refs);
|
|
1868
|
-
case ZodFirstPartyTypeKind3.ZodIntersection:
|
|
1869
|
-
return parseIntersectionDef(def, refs);
|
|
1870
|
-
case ZodFirstPartyTypeKind3.ZodTuple:
|
|
1871
|
-
return parseTupleDef(def, refs);
|
|
1872
|
-
case ZodFirstPartyTypeKind3.ZodRecord:
|
|
1873
|
-
return parseRecordDef(def, refs);
|
|
1874
|
-
case ZodFirstPartyTypeKind3.ZodLiteral:
|
|
1875
|
-
return parseLiteralDef(def);
|
|
1876
|
-
case ZodFirstPartyTypeKind3.ZodEnum:
|
|
1877
|
-
return parseEnumDef(def);
|
|
1878
|
-
case ZodFirstPartyTypeKind3.ZodNativeEnum:
|
|
1879
|
-
return parseNativeEnumDef(def);
|
|
1880
|
-
case ZodFirstPartyTypeKind3.ZodNullable:
|
|
1881
|
-
return parseNullableDef(def, refs);
|
|
1882
|
-
case ZodFirstPartyTypeKind3.ZodOptional:
|
|
1883
|
-
return parseOptionalDef(def, refs);
|
|
1884
|
-
case ZodFirstPartyTypeKind3.ZodMap:
|
|
1885
|
-
return parseMapDef(def, refs);
|
|
1886
|
-
case ZodFirstPartyTypeKind3.ZodSet:
|
|
1887
|
-
return parseSetDef(def, refs);
|
|
1888
|
-
case ZodFirstPartyTypeKind3.ZodLazy:
|
|
1889
|
-
return () => def.getter()._def;
|
|
1890
|
-
case ZodFirstPartyTypeKind3.ZodPromise:
|
|
1891
|
-
return parsePromiseDef(def, refs);
|
|
1892
|
-
case ZodFirstPartyTypeKind3.ZodNaN:
|
|
1893
|
-
case ZodFirstPartyTypeKind3.ZodNever:
|
|
1894
|
-
return parseNeverDef();
|
|
1895
|
-
case ZodFirstPartyTypeKind3.ZodEffects:
|
|
1896
|
-
return parseEffectsDef(def, refs);
|
|
1897
|
-
case ZodFirstPartyTypeKind3.ZodAny:
|
|
1898
|
-
return parseAnyDef();
|
|
1899
|
-
case ZodFirstPartyTypeKind3.ZodUnknown:
|
|
1900
|
-
return parseUnknownDef();
|
|
1901
|
-
case ZodFirstPartyTypeKind3.ZodDefault:
|
|
1902
|
-
return parseDefaultDef(def, refs);
|
|
1903
|
-
case ZodFirstPartyTypeKind3.ZodBranded:
|
|
1904
|
-
return parseBrandedDef(def, refs);
|
|
1905
|
-
case ZodFirstPartyTypeKind3.ZodReadonly:
|
|
1906
|
-
return parseReadonlyDef(def, refs);
|
|
1907
|
-
case ZodFirstPartyTypeKind3.ZodCatch:
|
|
1908
|
-
return parseCatchDef(def, refs);
|
|
1909
|
-
case ZodFirstPartyTypeKind3.ZodPipeline:
|
|
1910
|
-
return parsePipelineDef(def, refs);
|
|
1911
|
-
case ZodFirstPartyTypeKind3.ZodFunction:
|
|
1912
|
-
case ZodFirstPartyTypeKind3.ZodVoid:
|
|
1913
|
-
case ZodFirstPartyTypeKind3.ZodSymbol:
|
|
1914
|
-
return void 0;
|
|
1915
|
-
default:
|
|
1916
|
-
return /* @__PURE__ */ ((_) => void 0)(typeName);
|
|
1917
|
-
}
|
|
1918
|
-
};
|
|
1919
|
-
var getRelativePath = (pathA, pathB) => {
|
|
1920
|
-
let i = 0;
|
|
1921
|
-
for (; i < pathA.length && i < pathB.length; i++) {
|
|
1922
|
-
if (pathA[i] !== pathB[i]) break;
|
|
1923
|
-
}
|
|
1924
|
-
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
|
|
1925
|
-
};
|
|
1926
|
-
function parseDef(def, refs, forceResolution = false) {
|
|
1927
|
-
var _a23;
|
|
1928
|
-
const seenItem = refs.seen.get(def);
|
|
1929
|
-
if (refs.override) {
|
|
1930
|
-
const overrideResult = (_a23 = refs.override) == null ? void 0 : _a23.call(
|
|
1931
|
-
refs,
|
|
1932
|
-
def,
|
|
1933
|
-
refs,
|
|
1934
|
-
seenItem,
|
|
1935
|
-
forceResolution
|
|
1936
|
-
);
|
|
1937
|
-
if (overrideResult !== ignoreOverride) {
|
|
1938
|
-
return overrideResult;
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
1941
|
-
if (seenItem && !forceResolution) {
|
|
1942
|
-
const seenSchema = get$ref(seenItem, refs);
|
|
1943
|
-
if (seenSchema !== void 0) {
|
|
1944
|
-
return seenSchema;
|
|
1945
|
-
}
|
|
1946
|
-
}
|
|
1947
|
-
const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
|
|
1948
|
-
refs.seen.set(def, newItem);
|
|
1949
|
-
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
|
|
1950
|
-
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
|
|
1951
|
-
if (jsonSchema2) {
|
|
1952
|
-
addMeta(def, refs, jsonSchema2);
|
|
1953
|
-
}
|
|
1954
|
-
if (refs.postProcess) {
|
|
1955
|
-
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
|
|
1956
|
-
newItem.jsonSchema = jsonSchema2;
|
|
1957
|
-
return postProcessResult;
|
|
1958
|
-
}
|
|
1959
|
-
newItem.jsonSchema = jsonSchema2;
|
|
1960
|
-
return jsonSchema2;
|
|
1961
|
-
}
|
|
1962
|
-
var get$ref = (item, refs) => {
|
|
1963
|
-
switch (refs.$refStrategy) {
|
|
1964
|
-
case "root":
|
|
1965
|
-
return { $ref: item.path.join("/") };
|
|
1966
|
-
case "relative":
|
|
1967
|
-
return { $ref: getRelativePath(refs.currentPath, item.path) };
|
|
1968
|
-
case "none":
|
|
1969
|
-
case "seen": {
|
|
1970
|
-
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
|
|
1971
|
-
console.warn(
|
|
1972
|
-
`Recursive reference detected at ${refs.currentPath.join(
|
|
1973
|
-
"/"
|
|
1974
|
-
)}! Defaulting to any`
|
|
1975
|
-
);
|
|
1976
|
-
return parseAnyDef();
|
|
1977
|
-
}
|
|
1978
|
-
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
};
|
|
1982
|
-
var addMeta = (def, refs, jsonSchema2) => {
|
|
1983
|
-
if (def.description) {
|
|
1984
|
-
jsonSchema2.description = def.description;
|
|
1985
|
-
}
|
|
1986
|
-
return jsonSchema2;
|
|
1987
|
-
};
|
|
1988
|
-
var getRefs = (options) => {
|
|
1989
|
-
const _options = getDefaultOptions(options);
|
|
1990
|
-
const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
|
|
1991
|
-
return {
|
|
1992
|
-
..._options,
|
|
1993
|
-
currentPath,
|
|
1994
|
-
propertyPath: void 0,
|
|
1995
|
-
seen: new Map(
|
|
1996
|
-
Object.entries(_options.definitions).map(([name23, def]) => [
|
|
1997
|
-
def._def,
|
|
1998
|
-
{
|
|
1999
|
-
def: def._def,
|
|
2000
|
-
path: [..._options.basePath, _options.definitionPath, name23],
|
|
2001
|
-
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
|
|
2002
|
-
jsonSchema: void 0
|
|
2003
|
-
}
|
|
2004
|
-
])
|
|
2005
|
-
)
|
|
2006
|
-
};
|
|
2007
|
-
};
|
|
2008
|
-
var zod3ToJsonSchema = (schema, options) => {
|
|
2009
|
-
var _a23;
|
|
2010
|
-
const refs = getRefs(options);
|
|
2011
|
-
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
|
|
2012
|
-
(acc, [name32, schema2]) => {
|
|
2013
|
-
var _a32;
|
|
2014
|
-
return {
|
|
2015
|
-
...acc,
|
|
2016
|
-
[name32]: (_a32 = parseDef(
|
|
2017
|
-
schema2._def,
|
|
2018
|
-
{
|
|
2019
|
-
...refs,
|
|
2020
|
-
currentPath: [...refs.basePath, refs.definitionPath, name32]
|
|
2021
|
-
},
|
|
2022
|
-
true
|
|
2023
|
-
)) != null ? _a32 : parseAnyDef()
|
|
2024
|
-
};
|
|
2025
|
-
},
|
|
2026
|
-
{}
|
|
2027
|
-
) : void 0;
|
|
2028
|
-
const name23 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
|
|
2029
|
-
const main = (_a23 = parseDef(
|
|
2030
|
-
schema._def,
|
|
2031
|
-
name23 === void 0 ? refs : {
|
|
2032
|
-
...refs,
|
|
2033
|
-
currentPath: [...refs.basePath, refs.definitionPath, name23]
|
|
2034
|
-
},
|
|
2035
|
-
false
|
|
2036
|
-
)) != null ? _a23 : parseAnyDef();
|
|
2037
|
-
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
|
|
2038
|
-
if (title !== void 0) {
|
|
2039
|
-
main.title = title;
|
|
2040
|
-
}
|
|
2041
|
-
const combined = name23 === void 0 ? definitions ? {
|
|
2042
|
-
...main,
|
|
2043
|
-
[refs.definitionPath]: definitions
|
|
2044
|
-
} : main : {
|
|
2045
|
-
$ref: [
|
|
2046
|
-
...refs.$refStrategy === "relative" ? [] : refs.basePath,
|
|
2047
|
-
refs.definitionPath,
|
|
2048
|
-
name23
|
|
2049
|
-
].join("/"),
|
|
2050
|
-
[refs.definitionPath]: {
|
|
2051
|
-
...definitions,
|
|
2052
|
-
[name23]: main
|
|
2053
|
-
}
|
|
2054
|
-
};
|
|
2055
|
-
combined.$schema = "http://json-schema.org/draft-07/schema#";
|
|
2056
|
-
return combined;
|
|
2057
|
-
};
|
|
2058
|
-
var schemaSymbol = Symbol.for("vercel.ai.schema");
|
|
2059
|
-
function jsonSchema(jsonSchema2, {
|
|
2060
|
-
validate
|
|
2061
|
-
} = {}) {
|
|
2062
|
-
return {
|
|
2063
|
-
[schemaSymbol]: true,
|
|
2064
|
-
_type: void 0,
|
|
2065
|
-
// should never be used directly
|
|
2066
|
-
get jsonSchema() {
|
|
2067
|
-
if (typeof jsonSchema2 === "function") {
|
|
2068
|
-
jsonSchema2 = jsonSchema2();
|
|
2069
|
-
}
|
|
2070
|
-
return jsonSchema2;
|
|
2071
|
-
},
|
|
2072
|
-
validate
|
|
2073
|
-
};
|
|
2074
|
-
}
|
|
2075
|
-
function isSchema(value) {
|
|
2076
|
-
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
|
|
2077
|
-
}
|
|
2078
|
-
function asSchema(schema) {
|
|
2079
|
-
return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
|
|
2080
|
-
}
|
|
2081
|
-
function standardSchema(standardSchema2) {
|
|
2082
|
-
return jsonSchema(
|
|
2083
|
-
() => addAdditionalPropertiesToJsonSchema(
|
|
2084
|
-
standardSchema2["~standard"].jsonSchema.input({
|
|
2085
|
-
target: "draft-07"
|
|
2086
|
-
})
|
|
2087
|
-
),
|
|
2088
|
-
{
|
|
2089
|
-
validate: async (value) => {
|
|
2090
|
-
const result = await standardSchema2["~standard"].validate(value);
|
|
2091
|
-
return "value" in result ? { success: true, value: result.value } : {
|
|
2092
|
-
success: false,
|
|
2093
|
-
error: new TypeValidationError({
|
|
2094
|
-
value,
|
|
2095
|
-
cause: result.issues
|
|
2096
|
-
})
|
|
2097
|
-
};
|
|
2098
|
-
}
|
|
2099
|
-
}
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
function zod3Schema(zodSchema2, options) {
|
|
2103
|
-
var _a23;
|
|
2104
|
-
const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false;
|
|
2105
|
-
return jsonSchema(
|
|
2106
|
-
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
2107
|
-
() => zod3ToJsonSchema(zodSchema2, {
|
|
2108
|
-
$refStrategy: useReferences ? "root" : "none"
|
|
2109
|
-
}),
|
|
2110
|
-
{
|
|
2111
|
-
validate: async (value) => {
|
|
2112
|
-
const result = await zodSchema2.safeParseAsync(value);
|
|
2113
|
-
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
2114
|
-
}
|
|
2115
|
-
}
|
|
2116
|
-
);
|
|
2117
|
-
}
|
|
2118
|
-
function zod4Schema(zodSchema2, options) {
|
|
2119
|
-
var _a23;
|
|
2120
|
-
const useReferences = (_a23 = options == null ? void 0 : options.useReferences) != null ? _a23 : false;
|
|
2121
|
-
return jsonSchema(
|
|
2122
|
-
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
2123
|
-
() => addAdditionalPropertiesToJsonSchema(
|
|
2124
|
-
z42.toJSONSchema(zodSchema2, {
|
|
2125
|
-
target: "draft-7",
|
|
2126
|
-
io: "input",
|
|
2127
|
-
reused: useReferences ? "ref" : "inline"
|
|
2128
|
-
})
|
|
2129
|
-
),
|
|
2130
|
-
{
|
|
2131
|
-
validate: async (value) => {
|
|
2132
|
-
const result = await z42.safeParseAsync(zodSchema2, value);
|
|
2133
|
-
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
2134
|
-
}
|
|
2135
|
-
}
|
|
2136
|
-
);
|
|
2137
|
-
}
|
|
2138
|
-
function isZod4Schema(zodSchema2) {
|
|
2139
|
-
return "_zod" in zodSchema2;
|
|
2140
|
-
}
|
|
2141
|
-
function zodSchema(zodSchema2, options) {
|
|
2142
|
-
if (isZod4Schema(zodSchema2)) {
|
|
2143
|
-
return zod4Schema(zodSchema2, options);
|
|
2144
|
-
} else {
|
|
2145
|
-
return zod3Schema(zodSchema2, options);
|
|
2146
|
-
}
|
|
2147
|
-
}
|
|
2148
|
-
async function safeValidateTypes({
|
|
2149
|
-
value,
|
|
2150
|
-
schema,
|
|
2151
|
-
context
|
|
2152
|
-
}) {
|
|
2153
|
-
const actualSchema = asSchema(schema);
|
|
2154
|
-
try {
|
|
2155
|
-
if (actualSchema.validate == null) {
|
|
2156
|
-
return { success: true, value, rawValue: value };
|
|
2157
|
-
}
|
|
2158
|
-
const result = await actualSchema.validate(value);
|
|
2159
|
-
if (result.success) {
|
|
2160
|
-
return { success: true, value: result.value, rawValue: value };
|
|
2161
|
-
}
|
|
2162
|
-
return {
|
|
2163
|
-
success: false,
|
|
2164
|
-
error: TypeValidationError.wrap({ value, cause: result.error, context }),
|
|
2165
|
-
rawValue: value
|
|
2166
|
-
};
|
|
2167
|
-
} catch (error) {
|
|
2168
|
-
return {
|
|
2169
|
-
success: false,
|
|
2170
|
-
error: TypeValidationError.wrap({ value, cause: error, context }),
|
|
2171
|
-
rawValue: value
|
|
2172
|
-
};
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
async function safeParseJSON({
|
|
2176
|
-
text,
|
|
2177
|
-
schema
|
|
2178
|
-
}) {
|
|
2179
|
-
try {
|
|
2180
|
-
const value = secureJsonParse(text);
|
|
2181
|
-
if (schema == null) {
|
|
2182
|
-
return { success: true, value, rawValue: value };
|
|
2183
|
-
}
|
|
2184
|
-
return await safeValidateTypes({ value, schema });
|
|
2185
|
-
} catch (error) {
|
|
2186
|
-
return {
|
|
2187
|
-
success: false,
|
|
2188
|
-
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
|
|
2189
|
-
rawValue: void 0
|
|
2190
|
-
};
|
|
2191
|
-
}
|
|
2192
|
-
}
|
|
2193
|
-
function tool(tool2) {
|
|
2194
|
-
return tool2;
|
|
2195
|
-
}
|
|
2196
|
-
function dynamicTool(tool2) {
|
|
2197
|
-
return { ...tool2, type: "dynamic" };
|
|
2198
|
-
}
|
|
2199
|
-
|
|
2200
|
-
// ../../node_modules/.pnpm/@ai-sdk+mcp@1.0.25_zod@4.4.3/node_modules/@ai-sdk/mcp/dist/index.mjs
|
|
2201
|
-
import { z as z22 } from "zod/v4";
|
|
2202
|
-
import { z as z7 } from "zod/v4";
|
|
2203
|
-
|
|
2204
|
-
// ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
|
|
2205
|
-
var crypto;
|
|
2206
|
-
crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
|
|
2207
|
-
globalThis.crypto ?? // Node.js >18
|
|
2208
|
-
import("crypto").then((m) => m.webcrypto);
|
|
2209
|
-
async function getRandomValues(size) {
|
|
2210
|
-
return (await crypto).getRandomValues(new Uint8Array(size));
|
|
2211
|
-
}
|
|
2212
|
-
async function random(size) {
|
|
2213
|
-
const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
|
2214
|
-
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
|
|
2215
|
-
let result = "";
|
|
2216
|
-
while (result.length < size) {
|
|
2217
|
-
const randomBytes = await getRandomValues(size - result.length);
|
|
2218
|
-
for (const randomByte of randomBytes) {
|
|
2219
|
-
if (randomByte < evenDistCutoff) {
|
|
2220
|
-
result += mask[randomByte % mask.length];
|
|
2221
|
-
}
|
|
2222
|
-
}
|
|
2223
|
-
}
|
|
2224
|
-
return result;
|
|
2225
|
-
}
|
|
2226
|
-
async function generateVerifier(length) {
|
|
2227
|
-
return await random(length);
|
|
2228
|
-
}
|
|
2229
|
-
async function generateChallenge(code_verifier) {
|
|
2230
|
-
const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
|
|
2231
|
-
return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
|
|
2232
|
-
}
|
|
2233
|
-
async function pkceChallenge(length) {
|
|
2234
|
-
if (!length)
|
|
2235
|
-
length = 43;
|
|
2236
|
-
if (length < 43 || length > 128) {
|
|
2237
|
-
throw `Expected a length between 43 and 128. Received ${length}.`;
|
|
2238
|
-
}
|
|
2239
|
-
const verifier = await generateVerifier(length);
|
|
2240
|
-
const challenge = await generateChallenge(verifier);
|
|
2241
|
-
return {
|
|
2242
|
-
code_verifier: verifier,
|
|
2243
|
-
code_challenge: challenge
|
|
2244
|
-
};
|
|
2245
|
-
}
|
|
2246
|
-
|
|
2247
|
-
// ../../node_modules/.pnpm/@ai-sdk+mcp@1.0.25_zod@4.4.3/node_modules/@ai-sdk/mcp/dist/index.mjs
|
|
2248
|
-
import { z as z32 } from "zod/v4";
|
|
2249
|
-
var name15 = "AI_MCPClientError";
|
|
2250
|
-
var marker16 = `vercel.ai.error.${name15}`;
|
|
2251
|
-
var symbol16 = Symbol.for(marker16);
|
|
2252
|
-
var _a16;
|
|
2253
|
-
var _b16;
|
|
2254
|
-
var MCPClientError = class extends (_b16 = AISDKError, _a16 = symbol16, _b16) {
|
|
2255
|
-
constructor({
|
|
2256
|
-
name: name32 = "MCPClientError",
|
|
2257
|
-
message,
|
|
2258
|
-
cause,
|
|
2259
|
-
data,
|
|
2260
|
-
code
|
|
2261
|
-
}) {
|
|
2262
|
-
super({ name: name32, message, cause });
|
|
2263
|
-
this[_a16] = true;
|
|
2264
|
-
this.data = data;
|
|
2265
|
-
this.code = code;
|
|
2266
|
-
}
|
|
2267
|
-
static isInstance(error) {
|
|
2268
|
-
return AISDKError.hasMarker(error, marker16);
|
|
2269
|
-
}
|
|
2270
|
-
};
|
|
2271
|
-
var LATEST_PROTOCOL_VERSION = "2025-06-18";
|
|
2272
|
-
var SUPPORTED_PROTOCOL_VERSIONS = [
|
|
2273
|
-
LATEST_PROTOCOL_VERSION,
|
|
2274
|
-
"2025-03-26",
|
|
2275
|
-
"2024-11-05"
|
|
2276
|
-
];
|
|
2277
|
-
var ToolMetaSchema = z7.optional(z7.record(z7.string(), z7.unknown()));
|
|
2278
|
-
var ClientOrServerImplementationSchema = z7.looseObject({
|
|
2279
|
-
name: z7.string(),
|
|
2280
|
-
version: z7.string()
|
|
2281
|
-
});
|
|
2282
|
-
var BaseParamsSchema = z7.looseObject({
|
|
2283
|
-
_meta: z7.optional(z7.object({}).loose())
|
|
2284
|
-
});
|
|
2285
|
-
var ResultSchema = BaseParamsSchema;
|
|
2286
|
-
var RequestSchema = z7.object({
|
|
2287
|
-
method: z7.string(),
|
|
2288
|
-
params: z7.optional(BaseParamsSchema)
|
|
2289
|
-
});
|
|
2290
|
-
var ElicitationCapabilitySchema = z7.object({
|
|
2291
|
-
applyDefaults: z7.optional(z7.boolean())
|
|
2292
|
-
}).loose();
|
|
2293
|
-
var ServerCapabilitiesSchema = z7.looseObject({
|
|
2294
|
-
experimental: z7.optional(z7.object({}).loose()),
|
|
2295
|
-
logging: z7.optional(z7.object({}).loose()),
|
|
2296
|
-
prompts: z7.optional(
|
|
2297
|
-
z7.looseObject({
|
|
2298
|
-
listChanged: z7.optional(z7.boolean())
|
|
2299
|
-
})
|
|
2300
|
-
),
|
|
2301
|
-
resources: z7.optional(
|
|
2302
|
-
z7.looseObject({
|
|
2303
|
-
subscribe: z7.optional(z7.boolean()),
|
|
2304
|
-
listChanged: z7.optional(z7.boolean())
|
|
2305
|
-
})
|
|
2306
|
-
),
|
|
2307
|
-
tools: z7.optional(
|
|
2308
|
-
z7.looseObject({
|
|
2309
|
-
listChanged: z7.optional(z7.boolean())
|
|
2310
|
-
})
|
|
2311
|
-
),
|
|
2312
|
-
elicitation: z7.optional(ElicitationCapabilitySchema)
|
|
2313
|
-
});
|
|
2314
|
-
var ClientCapabilitiesSchema = z7.object({
|
|
2315
|
-
elicitation: z7.optional(ElicitationCapabilitySchema)
|
|
2316
|
-
}).loose();
|
|
2317
|
-
var InitializeResultSchema = ResultSchema.extend({
|
|
2318
|
-
protocolVersion: z7.string(),
|
|
2319
|
-
capabilities: ServerCapabilitiesSchema,
|
|
2320
|
-
serverInfo: ClientOrServerImplementationSchema,
|
|
2321
|
-
instructions: z7.optional(z7.string())
|
|
2322
|
-
});
|
|
2323
|
-
var PaginatedResultSchema = ResultSchema.extend({
|
|
2324
|
-
nextCursor: z7.optional(z7.string())
|
|
2325
|
-
});
|
|
2326
|
-
var ToolSchema = z7.object({
|
|
2327
|
-
name: z7.string(),
|
|
2328
|
-
/**
|
|
2329
|
-
* @see https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool
|
|
2330
|
-
*/
|
|
2331
|
-
title: z7.optional(z7.string()),
|
|
2332
|
-
description: z7.optional(z7.string()),
|
|
2333
|
-
inputSchema: z7.object({
|
|
2334
|
-
type: z7.literal("object"),
|
|
2335
|
-
properties: z7.optional(z7.object({}).loose())
|
|
2336
|
-
}).loose(),
|
|
2337
|
-
/**
|
|
2338
|
-
* @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema
|
|
2339
|
-
*/
|
|
2340
|
-
outputSchema: z7.optional(z7.object({}).loose()),
|
|
2341
|
-
annotations: z7.optional(
|
|
2342
|
-
z7.object({
|
|
2343
|
-
title: z7.optional(z7.string())
|
|
2344
|
-
}).loose()
|
|
2345
|
-
),
|
|
2346
|
-
_meta: ToolMetaSchema
|
|
2347
|
-
}).loose();
|
|
2348
|
-
var ListToolsResultSchema = PaginatedResultSchema.extend({
|
|
2349
|
-
tools: z7.array(ToolSchema)
|
|
2350
|
-
});
|
|
2351
|
-
var TextContentSchema = z7.object({
|
|
2352
|
-
type: z7.literal("text"),
|
|
2353
|
-
text: z7.string()
|
|
2354
|
-
}).loose();
|
|
2355
|
-
var ImageContentSchema = z7.object({
|
|
2356
|
-
type: z7.literal("image"),
|
|
2357
|
-
data: z7.base64(),
|
|
2358
|
-
mimeType: z7.string()
|
|
2359
|
-
}).loose();
|
|
2360
|
-
var ResourceSchema = z7.object({
|
|
2361
|
-
uri: z7.string(),
|
|
2362
|
-
name: z7.string(),
|
|
2363
|
-
title: z7.optional(z7.string()),
|
|
2364
|
-
description: z7.optional(z7.string()),
|
|
2365
|
-
mimeType: z7.optional(z7.string()),
|
|
2366
|
-
size: z7.optional(z7.number())
|
|
2367
|
-
}).loose();
|
|
2368
|
-
var ListResourcesResultSchema = PaginatedResultSchema.extend({
|
|
2369
|
-
resources: z7.array(ResourceSchema)
|
|
2370
|
-
});
|
|
2371
|
-
var ResourceContentsSchema = z7.object({
|
|
2372
|
-
/**
|
|
2373
|
-
* The URI of this resource.
|
|
2374
|
-
*/
|
|
2375
|
-
uri: z7.string(),
|
|
2376
|
-
/**
|
|
2377
|
-
* Optional display name of the resource content.
|
|
2378
|
-
*/
|
|
2379
|
-
name: z7.optional(z7.string()),
|
|
2380
|
-
/**
|
|
2381
|
-
* Optional human readable title.
|
|
2382
|
-
*/
|
|
2383
|
-
title: z7.optional(z7.string()),
|
|
2384
|
-
/**
|
|
2385
|
-
* The MIME type of this resource, if known.
|
|
2386
|
-
*/
|
|
2387
|
-
mimeType: z7.optional(z7.string())
|
|
2388
|
-
}).loose();
|
|
2389
|
-
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2390
|
-
text: z7.string()
|
|
2391
|
-
});
|
|
2392
|
-
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2393
|
-
blob: z7.base64()
|
|
2394
|
-
});
|
|
2395
|
-
var EmbeddedResourceSchema = z7.object({
|
|
2396
|
-
type: z7.literal("resource"),
|
|
2397
|
-
resource: z7.union([TextResourceContentsSchema, BlobResourceContentsSchema])
|
|
2398
|
-
}).loose();
|
|
2399
|
-
var CallToolResultSchema = ResultSchema.extend({
|
|
2400
|
-
content: z7.array(
|
|
2401
|
-
z7.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
|
|
2402
|
-
),
|
|
2403
|
-
/**
|
|
2404
|
-
* @see https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content
|
|
2405
|
-
*/
|
|
2406
|
-
structuredContent: z7.optional(z7.unknown()),
|
|
2407
|
-
isError: z7.boolean().default(false).optional()
|
|
2408
|
-
}).or(
|
|
2409
|
-
ResultSchema.extend({
|
|
2410
|
-
toolResult: z7.unknown()
|
|
2411
|
-
})
|
|
2412
|
-
);
|
|
2413
|
-
var ResourceTemplateSchema = z7.object({
|
|
2414
|
-
uriTemplate: z7.string(),
|
|
2415
|
-
name: z7.string(),
|
|
2416
|
-
title: z7.optional(z7.string()),
|
|
2417
|
-
description: z7.optional(z7.string()),
|
|
2418
|
-
mimeType: z7.optional(z7.string())
|
|
2419
|
-
}).loose();
|
|
2420
|
-
var ListResourceTemplatesResultSchema = ResultSchema.extend({
|
|
2421
|
-
resourceTemplates: z7.array(ResourceTemplateSchema)
|
|
2422
|
-
});
|
|
2423
|
-
var ReadResourceResultSchema = ResultSchema.extend({
|
|
2424
|
-
contents: z7.array(
|
|
2425
|
-
z7.union([TextResourceContentsSchema, BlobResourceContentsSchema])
|
|
2426
|
-
)
|
|
2427
|
-
});
|
|
2428
|
-
var PromptArgumentSchema = z7.object({
|
|
2429
|
-
name: z7.string(),
|
|
2430
|
-
description: z7.optional(z7.string()),
|
|
2431
|
-
required: z7.optional(z7.boolean())
|
|
2432
|
-
}).loose();
|
|
2433
|
-
var PromptSchema = z7.object({
|
|
2434
|
-
name: z7.string(),
|
|
2435
|
-
title: z7.optional(z7.string()),
|
|
2436
|
-
description: z7.optional(z7.string()),
|
|
2437
|
-
arguments: z7.optional(z7.array(PromptArgumentSchema))
|
|
2438
|
-
}).loose();
|
|
2439
|
-
var ListPromptsResultSchema = PaginatedResultSchema.extend({
|
|
2440
|
-
prompts: z7.array(PromptSchema)
|
|
2441
|
-
});
|
|
2442
|
-
var PromptMessageSchema = z7.object({
|
|
2443
|
-
role: z7.union([z7.literal("user"), z7.literal("assistant")]),
|
|
2444
|
-
content: z7.union([
|
|
2445
|
-
TextContentSchema,
|
|
2446
|
-
ImageContentSchema,
|
|
2447
|
-
EmbeddedResourceSchema
|
|
2448
|
-
])
|
|
2449
|
-
}).loose();
|
|
2450
|
-
var GetPromptResultSchema = ResultSchema.extend({
|
|
2451
|
-
description: z7.optional(z7.string()),
|
|
2452
|
-
messages: z7.array(PromptMessageSchema)
|
|
2453
|
-
});
|
|
2454
|
-
var ElicitationRequestParamsSchema = BaseParamsSchema.extend({
|
|
2455
|
-
message: z7.string(),
|
|
2456
|
-
requestedSchema: z7.unknown()
|
|
2457
|
-
});
|
|
2458
|
-
var ElicitationRequestSchema = RequestSchema.extend({
|
|
2459
|
-
method: z7.literal("elicitation/create"),
|
|
2460
|
-
params: ElicitationRequestParamsSchema
|
|
2461
|
-
});
|
|
2462
|
-
var ElicitResultSchema = ResultSchema.extend({
|
|
2463
|
-
action: z7.union([
|
|
2464
|
-
z7.literal("accept"),
|
|
2465
|
-
z7.literal("decline"),
|
|
2466
|
-
z7.literal("cancel")
|
|
2467
|
-
]),
|
|
2468
|
-
content: z7.optional(z7.record(z7.string(), z7.unknown()))
|
|
2469
|
-
});
|
|
2470
|
-
var JSONRPC_VERSION = "2.0";
|
|
2471
|
-
var JSONRPCRequestSchema = z22.object({
|
|
2472
|
-
jsonrpc: z22.literal(JSONRPC_VERSION),
|
|
2473
|
-
id: z22.union([z22.string(), z22.number().int()])
|
|
2474
|
-
}).merge(RequestSchema).strict();
|
|
2475
|
-
var JSONRPCResponseSchema = z22.object({
|
|
2476
|
-
jsonrpc: z22.literal(JSONRPC_VERSION),
|
|
2477
|
-
id: z22.union([z22.string(), z22.number().int()]),
|
|
2478
|
-
result: ResultSchema
|
|
2479
|
-
}).strict();
|
|
2480
|
-
var JSONRPCErrorSchema = z22.object({
|
|
2481
|
-
jsonrpc: z22.literal(JSONRPC_VERSION),
|
|
2482
|
-
id: z22.union([z22.string(), z22.number().int()]),
|
|
2483
|
-
error: z22.object({
|
|
2484
|
-
code: z22.number().int(),
|
|
2485
|
-
message: z22.string(),
|
|
2486
|
-
data: z22.optional(z22.unknown())
|
|
2487
|
-
})
|
|
2488
|
-
}).strict();
|
|
2489
|
-
var JSONRPCNotificationSchema = z22.object({
|
|
2490
|
-
jsonrpc: z22.literal(JSONRPC_VERSION)
|
|
2491
|
-
}).merge(
|
|
2492
|
-
z22.object({
|
|
2493
|
-
method: z22.string(),
|
|
2494
|
-
params: z22.optional(BaseParamsSchema)
|
|
2495
|
-
})
|
|
2496
|
-
).strict();
|
|
2497
|
-
var JSONRPCMessageSchema = z22.union([
|
|
2498
|
-
JSONRPCRequestSchema,
|
|
2499
|
-
JSONRPCNotificationSchema,
|
|
2500
|
-
JSONRPCResponseSchema,
|
|
2501
|
-
JSONRPCErrorSchema
|
|
2502
|
-
]);
|
|
2503
|
-
var VERSION = typeof __PACKAGE_VERSION__ !== "undefined" ? __PACKAGE_VERSION__ : "0.0.0-test";
|
|
2504
|
-
var OAuthTokensSchema = z32.object({
|
|
2505
|
-
access_token: z32.string(),
|
|
2506
|
-
id_token: z32.string().optional(),
|
|
2507
|
-
// Optional for OAuth 2.1, but necessary in OpenID Connect
|
|
2508
|
-
token_type: z32.string(),
|
|
2509
|
-
expires_in: z32.number().optional(),
|
|
2510
|
-
scope: z32.string().optional(),
|
|
2511
|
-
refresh_token: z32.string().optional()
|
|
2512
|
-
}).strip();
|
|
2513
|
-
var SafeUrlSchema = z32.string().url().superRefine((val, ctx) => {
|
|
2514
|
-
if (!URL.canParse(val)) {
|
|
2515
|
-
ctx.addIssue({
|
|
2516
|
-
code: z32.ZodIssueCode.custom,
|
|
2517
|
-
message: "URL must be parseable",
|
|
2518
|
-
fatal: true
|
|
2519
|
-
});
|
|
2520
|
-
return z32.NEVER;
|
|
2521
|
-
}
|
|
2522
|
-
}).refine(
|
|
2523
|
-
(url) => {
|
|
2524
|
-
const u = new URL(url);
|
|
2525
|
-
return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
|
|
2526
|
-
},
|
|
2527
|
-
{ message: "URL cannot use javascript:, data:, or vbscript: scheme" }
|
|
2528
|
-
);
|
|
2529
|
-
var OAuthProtectedResourceMetadataSchema = z32.object({
|
|
2530
|
-
resource: z32.string().url(),
|
|
2531
|
-
authorization_servers: z32.array(SafeUrlSchema).optional(),
|
|
2532
|
-
jwks_uri: z32.string().url().optional(),
|
|
2533
|
-
scopes_supported: z32.array(z32.string()).optional(),
|
|
2534
|
-
bearer_methods_supported: z32.array(z32.string()).optional(),
|
|
2535
|
-
resource_signing_alg_values_supported: z32.array(z32.string()).optional(),
|
|
2536
|
-
resource_name: z32.string().optional(),
|
|
2537
|
-
resource_documentation: z32.string().optional(),
|
|
2538
|
-
resource_policy_uri: z32.string().url().optional(),
|
|
2539
|
-
resource_tos_uri: z32.string().url().optional(),
|
|
2540
|
-
tls_client_certificate_bound_access_tokens: z32.boolean().optional(),
|
|
2541
|
-
authorization_details_types_supported: z32.array(z32.string()).optional(),
|
|
2542
|
-
dpop_signing_alg_values_supported: z32.array(z32.string()).optional(),
|
|
2543
|
-
dpop_bound_access_tokens_required: z32.boolean().optional()
|
|
2544
|
-
}).passthrough();
|
|
2545
|
-
var OAuthMetadataSchema = z32.object({
|
|
2546
|
-
issuer: z32.string(),
|
|
2547
|
-
authorization_endpoint: SafeUrlSchema,
|
|
2548
|
-
token_endpoint: SafeUrlSchema,
|
|
2549
|
-
registration_endpoint: SafeUrlSchema.optional(),
|
|
2550
|
-
scopes_supported: z32.array(z32.string()).optional(),
|
|
2551
|
-
response_types_supported: z32.array(z32.string()),
|
|
2552
|
-
grant_types_supported: z32.array(z32.string()).optional(),
|
|
2553
|
-
code_challenge_methods_supported: z32.array(z32.string()),
|
|
2554
|
-
token_endpoint_auth_methods_supported: z32.array(z32.string()).optional(),
|
|
2555
|
-
token_endpoint_auth_signing_alg_values_supported: z32.array(z32.string()).optional()
|
|
2556
|
-
}).passthrough();
|
|
2557
|
-
var OpenIdProviderMetadataSchema = z32.object({
|
|
2558
|
-
issuer: z32.string(),
|
|
2559
|
-
authorization_endpoint: SafeUrlSchema,
|
|
2560
|
-
token_endpoint: SafeUrlSchema,
|
|
2561
|
-
userinfo_endpoint: SafeUrlSchema.optional(),
|
|
2562
|
-
jwks_uri: SafeUrlSchema,
|
|
2563
|
-
registration_endpoint: SafeUrlSchema.optional(),
|
|
2564
|
-
scopes_supported: z32.array(z32.string()).optional(),
|
|
2565
|
-
response_types_supported: z32.array(z32.string()),
|
|
2566
|
-
grant_types_supported: z32.array(z32.string()).optional(),
|
|
2567
|
-
subject_types_supported: z32.array(z32.string()),
|
|
2568
|
-
id_token_signing_alg_values_supported: z32.array(z32.string()),
|
|
2569
|
-
claims_supported: z32.array(z32.string()).optional(),
|
|
2570
|
-
token_endpoint_auth_methods_supported: z32.array(z32.string()).optional()
|
|
2571
|
-
}).passthrough();
|
|
2572
|
-
var OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge(
|
|
2573
|
-
OAuthMetadataSchema.pick({
|
|
2574
|
-
code_challenge_methods_supported: true
|
|
2575
|
-
})
|
|
2576
|
-
);
|
|
2577
|
-
var OAuthClientInformationSchema = z32.object({
|
|
2578
|
-
client_id: z32.string(),
|
|
2579
|
-
client_secret: z32.string().optional(),
|
|
2580
|
-
client_id_issued_at: z32.number().optional(),
|
|
2581
|
-
client_secret_expires_at: z32.number().optional()
|
|
2582
|
-
}).strip();
|
|
2583
|
-
var OAuthClientMetadataSchema = z32.object({
|
|
2584
|
-
redirect_uris: z32.array(SafeUrlSchema),
|
|
2585
|
-
token_endpoint_auth_method: z32.string().optional(),
|
|
2586
|
-
grant_types: z32.array(z32.string()).optional(),
|
|
2587
|
-
response_types: z32.array(z32.string()).optional(),
|
|
2588
|
-
client_name: z32.string().optional(),
|
|
2589
|
-
client_uri: SafeUrlSchema.optional(),
|
|
2590
|
-
logo_uri: SafeUrlSchema.optional(),
|
|
2591
|
-
scope: z32.string().optional(),
|
|
2592
|
-
contacts: z32.array(z32.string()).optional(),
|
|
2593
|
-
tos_uri: SafeUrlSchema.optional(),
|
|
2594
|
-
policy_uri: z32.string().optional(),
|
|
2595
|
-
jwks_uri: SafeUrlSchema.optional(),
|
|
2596
|
-
jwks: z32.any().optional(),
|
|
2597
|
-
software_id: z32.string().optional(),
|
|
2598
|
-
software_version: z32.string().optional(),
|
|
2599
|
-
software_statement: z32.string().optional()
|
|
2600
|
-
}).strip();
|
|
2601
|
-
var OAuthErrorResponseSchema = z32.object({
|
|
2602
|
-
error: z32.string(),
|
|
2603
|
-
error_description: z32.string().optional(),
|
|
2604
|
-
error_uri: z32.string().optional()
|
|
2605
|
-
});
|
|
2606
|
-
var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(
|
|
2607
|
-
OAuthClientInformationSchema
|
|
2608
|
-
);
|
|
2609
|
-
var name22 = "AI_MCPClientOAuthError";
|
|
2610
|
-
var marker22 = `vercel.ai.error.${name22}`;
|
|
2611
|
-
var symbol22 = Symbol.for(marker22);
|
|
2612
|
-
var _a22;
|
|
2613
|
-
var _b22;
|
|
2614
|
-
var MCPClientOAuthError = class extends (_b22 = AISDKError, _a22 = symbol22, _b22) {
|
|
2615
|
-
constructor({
|
|
2616
|
-
name: name32 = "MCPClientOAuthError",
|
|
2617
|
-
message,
|
|
2618
|
-
cause
|
|
2619
|
-
}) {
|
|
2620
|
-
super({ name: name32, message, cause });
|
|
2621
|
-
this[_a22] = true;
|
|
2622
|
-
}
|
|
2623
|
-
static isInstance(error) {
|
|
2624
|
-
return AISDKError.hasMarker(error, marker22);
|
|
2625
|
-
}
|
|
2626
|
-
};
|
|
2627
|
-
var ServerError = class extends MCPClientOAuthError {
|
|
2628
|
-
};
|
|
2629
|
-
ServerError.errorCode = "server_error";
|
|
2630
|
-
var InvalidClientError = class extends MCPClientOAuthError {
|
|
2631
|
-
};
|
|
2632
|
-
InvalidClientError.errorCode = "invalid_client";
|
|
2633
|
-
var InvalidGrantError = class extends MCPClientOAuthError {
|
|
2634
|
-
};
|
|
2635
|
-
InvalidGrantError.errorCode = "invalid_grant";
|
|
2636
|
-
var UnauthorizedClientError = class extends MCPClientOAuthError {
|
|
2637
|
-
};
|
|
2638
|
-
UnauthorizedClientError.errorCode = "unauthorized_client";
|
|
2639
|
-
var OAUTH_ERRORS = {
|
|
2640
|
-
[ServerError.errorCode]: ServerError,
|
|
2641
|
-
[InvalidClientError.errorCode]: InvalidClientError,
|
|
2642
|
-
[InvalidGrantError.errorCode]: InvalidGrantError,
|
|
2643
|
-
[UnauthorizedClientError.errorCode]: UnauthorizedClientError
|
|
2644
|
-
};
|
|
2645
|
-
function resourceUrlFromServerUrl(url) {
|
|
2646
|
-
const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
|
|
2647
|
-
resourceURL.hash = "";
|
|
2648
|
-
return resourceURL;
|
|
2649
|
-
}
|
|
2650
|
-
function checkResourceAllowed({
|
|
2651
|
-
requestedResource,
|
|
2652
|
-
configuredResource
|
|
2653
|
-
}) {
|
|
2654
|
-
const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
|
|
2655
|
-
const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
|
|
2656
|
-
if (requested.origin !== configured.origin) {
|
|
2657
|
-
return false;
|
|
2658
|
-
}
|
|
2659
|
-
if (requested.pathname.length < configured.pathname.length) {
|
|
2660
|
-
return false;
|
|
2661
|
-
}
|
|
2662
|
-
const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
|
|
2663
|
-
const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
|
|
2664
|
-
return requestedPath.startsWith(configuredPath);
|
|
2665
|
-
}
|
|
2666
|
-
var UnauthorizedError = class extends Error {
|
|
2667
|
-
constructor(message = "Unauthorized") {
|
|
2668
|
-
super(message);
|
|
2669
|
-
this.name = "UnauthorizedError";
|
|
2670
|
-
}
|
|
2671
|
-
};
|
|
2672
|
-
function extractResourceMetadataUrl(response) {
|
|
2673
|
-
var _a32;
|
|
2674
|
-
const header = (_a32 = response.headers.get("www-authenticate")) != null ? _a32 : response.headers.get("WWW-Authenticate");
|
|
2675
|
-
if (!header) {
|
|
2676
|
-
return void 0;
|
|
2677
|
-
}
|
|
2678
|
-
const [type, scheme] = header.split(" ");
|
|
2679
|
-
if (type.toLowerCase() !== "bearer" || !scheme) {
|
|
2680
|
-
return void 0;
|
|
2681
|
-
}
|
|
2682
|
-
const regex = /resource_metadata="([^"]*)"/;
|
|
2683
|
-
const match = header.match(regex);
|
|
2684
|
-
if (!match) {
|
|
2685
|
-
return void 0;
|
|
2686
|
-
}
|
|
2687
|
-
try {
|
|
2688
|
-
return new URL(match[1]);
|
|
2689
|
-
} catch (e) {
|
|
2690
|
-
return void 0;
|
|
2691
|
-
}
|
|
2692
|
-
}
|
|
2693
|
-
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
|
|
2694
|
-
if (pathname.endsWith("/")) {
|
|
2695
|
-
pathname = pathname.slice(0, -1);
|
|
2696
|
-
}
|
|
2697
|
-
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
|
|
2698
|
-
}
|
|
2699
|
-
async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
|
|
2700
|
-
try {
|
|
2701
|
-
return await fetchFn(url, { headers });
|
|
2702
|
-
} catch (error) {
|
|
2703
|
-
if (error instanceof TypeError) {
|
|
2704
|
-
if (headers) {
|
|
2705
|
-
return fetchWithCorsRetry(url, void 0, fetchFn);
|
|
2706
|
-
} else {
|
|
2707
|
-
return void 0;
|
|
2708
|
-
}
|
|
2709
|
-
}
|
|
2710
|
-
throw error;
|
|
2711
|
-
}
|
|
2712
|
-
}
|
|
2713
|
-
async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
|
|
2714
|
-
const headers = {
|
|
2715
|
-
"MCP-Protocol-Version": protocolVersion
|
|
2716
|
-
};
|
|
2717
|
-
return await fetchWithCorsRetry(url, headers, fetchFn);
|
|
2718
|
-
}
|
|
2719
|
-
function shouldAttemptFallback(response, pathname) {
|
|
2720
|
-
return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
|
|
2721
|
-
}
|
|
2722
|
-
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
|
|
2723
|
-
var _a32, _b32;
|
|
2724
|
-
const issuer = new URL(serverUrl);
|
|
2725
|
-
const protocolVersion = (_a32 = opts == null ? void 0 : opts.protocolVersion) != null ? _a32 : LATEST_PROTOCOL_VERSION;
|
|
2726
|
-
let url;
|
|
2727
|
-
if (opts == null ? void 0 : opts.metadataUrl) {
|
|
2728
|
-
url = new URL(opts.metadataUrl);
|
|
2729
|
-
} else {
|
|
2730
|
-
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
|
|
2731
|
-
url = new URL(wellKnownPath, (_b32 = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b32 : issuer);
|
|
2732
|
-
url.search = issuer.search;
|
|
2733
|
-
}
|
|
2734
|
-
let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
|
|
2735
|
-
if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
|
|
2736
|
-
const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
|
|
2737
|
-
response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
|
|
2738
|
-
}
|
|
2739
|
-
return response;
|
|
2740
|
-
}
|
|
2741
|
-
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
|
|
2742
|
-
const response = await discoverMetadataWithFallback(
|
|
2743
|
-
serverUrl,
|
|
2744
|
-
"oauth-protected-resource",
|
|
2745
|
-
fetchFn,
|
|
2746
|
-
{
|
|
2747
|
-
protocolVersion: opts == null ? void 0 : opts.protocolVersion,
|
|
2748
|
-
metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl
|
|
2749
|
-
}
|
|
2750
|
-
);
|
|
2751
|
-
if (!response || response.status === 404) {
|
|
2752
|
-
throw new Error(
|
|
2753
|
-
`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`
|
|
2754
|
-
);
|
|
2755
|
-
}
|
|
2756
|
-
if (!response.ok) {
|
|
2757
|
-
throw new Error(
|
|
2758
|
-
`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`
|
|
2759
|
-
);
|
|
2760
|
-
}
|
|
2761
|
-
return OAuthProtectedResourceMetadataSchema.parse(await response.json());
|
|
2762
|
-
}
|
|
2763
|
-
function buildDiscoveryUrls(authorizationServerUrl) {
|
|
2764
|
-
const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
|
|
2765
|
-
const hasPath = url.pathname !== "/";
|
|
2766
|
-
const urlsToTry = [];
|
|
2767
|
-
if (!hasPath) {
|
|
2768
|
-
urlsToTry.push({
|
|
2769
|
-
url: new URL("/.well-known/oauth-authorization-server", url.origin),
|
|
2770
|
-
type: "oauth"
|
|
2771
|
-
});
|
|
2772
|
-
urlsToTry.push({
|
|
2773
|
-
url: new URL("/.well-known/openid-configuration", url.origin),
|
|
2774
|
-
type: "oidc"
|
|
2775
|
-
});
|
|
2776
|
-
return urlsToTry;
|
|
2777
|
-
}
|
|
2778
|
-
let pathname = url.pathname;
|
|
2779
|
-
if (pathname.endsWith("/")) {
|
|
2780
|
-
pathname = pathname.slice(0, -1);
|
|
2781
|
-
}
|
|
2782
|
-
urlsToTry.push({
|
|
2783
|
-
url: new URL(
|
|
2784
|
-
`/.well-known/oauth-authorization-server${pathname}`,
|
|
2785
|
-
url.origin
|
|
2786
|
-
),
|
|
2787
|
-
type: "oauth"
|
|
2788
|
-
});
|
|
2789
|
-
urlsToTry.push({
|
|
2790
|
-
url: new URL("/.well-known/oauth-authorization-server", url.origin),
|
|
2791
|
-
type: "oauth"
|
|
2792
|
-
});
|
|
2793
|
-
urlsToTry.push({
|
|
2794
|
-
url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
|
|
2795
|
-
type: "oidc"
|
|
2796
|
-
});
|
|
2797
|
-
urlsToTry.push({
|
|
2798
|
-
url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
|
|
2799
|
-
type: "oidc"
|
|
2800
|
-
});
|
|
2801
|
-
return urlsToTry;
|
|
2802
|
-
}
|
|
2803
|
-
async function discoverAuthorizationServerMetadata(authorizationServerUrl, {
|
|
2804
|
-
fetchFn = fetch,
|
|
2805
|
-
protocolVersion = LATEST_PROTOCOL_VERSION
|
|
2806
|
-
} = {}) {
|
|
2807
|
-
var _a32;
|
|
2808
|
-
const headers = { "MCP-Protocol-Version": protocolVersion };
|
|
2809
|
-
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
|
|
2810
|
-
for (const { url: endpointUrl, type } of urlsToTry) {
|
|
2811
|
-
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
|
|
2812
|
-
if (!response) {
|
|
2813
|
-
continue;
|
|
2814
|
-
}
|
|
2815
|
-
if (!response.ok) {
|
|
2816
|
-
if (response.status >= 400 && response.status < 500) {
|
|
2817
|
-
continue;
|
|
2818
|
-
}
|
|
2819
|
-
throw new Error(
|
|
2820
|
-
`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`
|
|
2821
|
-
);
|
|
2822
|
-
}
|
|
2823
|
-
if (type === "oauth") {
|
|
2824
|
-
return OAuthMetadataSchema.parse(await response.json());
|
|
2825
|
-
} else {
|
|
2826
|
-
const metadata = OpenIdProviderDiscoveryMetadataSchema.parse(
|
|
2827
|
-
await response.json()
|
|
2828
|
-
);
|
|
2829
|
-
if (!((_a32 = metadata.code_challenge_methods_supported) == null ? void 0 : _a32.includes("S256"))) {
|
|
2830
|
-
throw new Error(
|
|
2831
|
-
`Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`
|
|
2832
|
-
);
|
|
2833
|
-
}
|
|
2834
|
-
return metadata;
|
|
2835
|
-
}
|
|
2836
|
-
}
|
|
2837
|
-
return void 0;
|
|
2838
|
-
}
|
|
2839
|
-
async function startAuthorization(authorizationServerUrl, {
|
|
2840
|
-
metadata,
|
|
2841
|
-
clientInformation,
|
|
2842
|
-
redirectUrl,
|
|
2843
|
-
scope,
|
|
2844
|
-
state,
|
|
2845
|
-
resource
|
|
2846
|
-
}) {
|
|
2847
|
-
const responseType = "code";
|
|
2848
|
-
const codeChallengeMethod = "S256";
|
|
2849
|
-
let authorizationUrl;
|
|
2850
|
-
if (metadata) {
|
|
2851
|
-
authorizationUrl = new URL(metadata.authorization_endpoint);
|
|
2852
|
-
if (!metadata.response_types_supported.includes(responseType)) {
|
|
2853
|
-
throw new Error(
|
|
2854
|
-
`Incompatible auth server: does not support response type ${responseType}`
|
|
2855
|
-
);
|
|
2856
|
-
}
|
|
2857
|
-
if (!metadata.code_challenge_methods_supported || !metadata.code_challenge_methods_supported.includes(codeChallengeMethod)) {
|
|
2858
|
-
throw new Error(
|
|
2859
|
-
`Incompatible auth server: does not support code challenge method ${codeChallengeMethod}`
|
|
2860
|
-
);
|
|
2861
|
-
}
|
|
2862
|
-
} else {
|
|
2863
|
-
authorizationUrl = new URL("/authorize", authorizationServerUrl);
|
|
2864
|
-
}
|
|
2865
|
-
const challenge = await pkceChallenge();
|
|
2866
|
-
const codeVerifier = challenge.code_verifier;
|
|
2867
|
-
const codeChallenge = challenge.code_challenge;
|
|
2868
|
-
authorizationUrl.searchParams.set("response_type", responseType);
|
|
2869
|
-
authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
|
|
2870
|
-
authorizationUrl.searchParams.set("code_challenge", codeChallenge);
|
|
2871
|
-
authorizationUrl.searchParams.set(
|
|
2872
|
-
"code_challenge_method",
|
|
2873
|
-
codeChallengeMethod
|
|
2874
|
-
);
|
|
2875
|
-
authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
|
|
2876
|
-
if (state) {
|
|
2877
|
-
authorizationUrl.searchParams.set("state", state);
|
|
2878
|
-
}
|
|
2879
|
-
if (scope) {
|
|
2880
|
-
authorizationUrl.searchParams.set("scope", scope);
|
|
2881
|
-
}
|
|
2882
|
-
if (scope == null ? void 0 : scope.includes("offline_access")) {
|
|
2883
|
-
authorizationUrl.searchParams.append("prompt", "consent");
|
|
2884
|
-
}
|
|
2885
|
-
if (resource) {
|
|
2886
|
-
authorizationUrl.searchParams.set("resource", resource.href);
|
|
2887
|
-
}
|
|
2888
|
-
return { authorizationUrl, codeVerifier };
|
|
2889
|
-
}
|
|
2890
|
-
function selectClientAuthMethod(clientInformation, supportedMethods) {
|
|
2891
|
-
const hasClientSecret = clientInformation.client_secret !== void 0;
|
|
2892
|
-
if (supportedMethods.length === 0) {
|
|
2893
|
-
return hasClientSecret ? "client_secret_post" : "none";
|
|
2894
|
-
}
|
|
2895
|
-
if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
|
|
2896
|
-
return "client_secret_basic";
|
|
2897
|
-
}
|
|
2898
|
-
if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
|
|
2899
|
-
return "client_secret_post";
|
|
2900
|
-
}
|
|
2901
|
-
if (supportedMethods.includes("none")) {
|
|
2902
|
-
return "none";
|
|
2903
|
-
}
|
|
2904
|
-
return hasClientSecret ? "client_secret_post" : "none";
|
|
2905
|
-
}
|
|
2906
|
-
function applyClientAuthentication(method, clientInformation, headers, params) {
|
|
2907
|
-
const { client_id, client_secret } = clientInformation;
|
|
2908
|
-
switch (method) {
|
|
2909
|
-
case "client_secret_basic":
|
|
2910
|
-
applyBasicAuth(client_id, client_secret, headers);
|
|
2911
|
-
return;
|
|
2912
|
-
case "client_secret_post":
|
|
2913
|
-
applyPostAuth(client_id, client_secret, params);
|
|
2914
|
-
return;
|
|
2915
|
-
case "none":
|
|
2916
|
-
applyPublicAuth(client_id, params);
|
|
2917
|
-
return;
|
|
2918
|
-
default:
|
|
2919
|
-
throw new Error(`Unsupported client authentication method: ${method}`);
|
|
2920
|
-
}
|
|
2921
|
-
}
|
|
2922
|
-
function applyBasicAuth(clientId, clientSecret, headers) {
|
|
2923
|
-
if (!clientSecret) {
|
|
2924
|
-
throw new Error(
|
|
2925
|
-
"client_secret_basic authentication requires a client_secret"
|
|
2926
|
-
);
|
|
2927
|
-
}
|
|
2928
|
-
const credentials = btoa(`${clientId}:${clientSecret}`);
|
|
2929
|
-
headers.set("Authorization", `Basic ${credentials}`);
|
|
2930
|
-
}
|
|
2931
|
-
function applyPostAuth(clientId, clientSecret, params) {
|
|
2932
|
-
params.set("client_id", clientId);
|
|
2933
|
-
if (clientSecret) {
|
|
2934
|
-
params.set("client_secret", clientSecret);
|
|
2935
|
-
}
|
|
2936
|
-
}
|
|
2937
|
-
function applyPublicAuth(clientId, params) {
|
|
2938
|
-
params.set("client_id", clientId);
|
|
2939
|
-
}
|
|
2940
|
-
async function parseErrorResponse(input) {
|
|
2941
|
-
const statusCode = input instanceof Response ? input.status : void 0;
|
|
2942
|
-
const body = input instanceof Response ? await input.text() : input;
|
|
2943
|
-
try {
|
|
2944
|
-
const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
|
|
2945
|
-
const { error, error_description, error_uri } = result;
|
|
2946
|
-
const errorClass = OAUTH_ERRORS[error] || ServerError;
|
|
2947
|
-
return new errorClass({
|
|
2948
|
-
message: error_description || "",
|
|
2949
|
-
cause: error_uri
|
|
2950
|
-
});
|
|
2951
|
-
} catch (error) {
|
|
2952
|
-
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
|
|
2953
|
-
return new ServerError({ message: errorMessage });
|
|
2954
|
-
}
|
|
2955
|
-
}
|
|
2956
|
-
async function exchangeAuthorization(authorizationServerUrl, {
|
|
2957
|
-
metadata,
|
|
2958
|
-
clientInformation,
|
|
2959
|
-
authorizationCode,
|
|
2960
|
-
codeVerifier,
|
|
2961
|
-
redirectUri,
|
|
2962
|
-
resource,
|
|
2963
|
-
addClientAuthentication,
|
|
2964
|
-
fetchFn
|
|
2965
|
-
}) {
|
|
2966
|
-
var _a32;
|
|
2967
|
-
const grantType = "authorization_code";
|
|
2968
|
-
const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
|
|
2969
|
-
if ((metadata == null ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {
|
|
2970
|
-
throw new Error(
|
|
2971
|
-
`Incompatible auth server: does not support grant type ${grantType}`
|
|
2972
|
-
);
|
|
2973
|
-
}
|
|
2974
|
-
const headers = new Headers({
|
|
2975
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
2976
|
-
Accept: "application/json"
|
|
2977
|
-
});
|
|
2978
|
-
const params = new URLSearchParams({
|
|
2979
|
-
grant_type: grantType,
|
|
2980
|
-
code: authorizationCode,
|
|
2981
|
-
code_verifier: codeVerifier,
|
|
2982
|
-
redirect_uri: String(redirectUri)
|
|
2983
|
-
});
|
|
2984
|
-
if (addClientAuthentication) {
|
|
2985
|
-
addClientAuthentication(headers, params, authorizationServerUrl, metadata);
|
|
2986
|
-
} else {
|
|
2987
|
-
const supportedMethods = (_a32 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a32 : [];
|
|
2988
|
-
const authMethod = selectClientAuthMethod(
|
|
2989
|
-
clientInformation,
|
|
2990
|
-
supportedMethods
|
|
2991
|
-
);
|
|
2992
|
-
applyClientAuthentication(authMethod, clientInformation, headers, params);
|
|
2993
|
-
}
|
|
2994
|
-
if (resource) {
|
|
2995
|
-
params.set("resource", resource.href);
|
|
2996
|
-
}
|
|
2997
|
-
const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {
|
|
2998
|
-
method: "POST",
|
|
2999
|
-
headers,
|
|
3000
|
-
body: params
|
|
3001
|
-
});
|
|
3002
|
-
if (!response.ok) {
|
|
3003
|
-
throw await parseErrorResponse(response);
|
|
3004
|
-
}
|
|
3005
|
-
return OAuthTokensSchema.parse(await response.json());
|
|
3006
|
-
}
|
|
3007
|
-
async function refreshAuthorization(authorizationServerUrl, {
|
|
3008
|
-
metadata,
|
|
3009
|
-
clientInformation,
|
|
3010
|
-
refreshToken,
|
|
3011
|
-
resource,
|
|
3012
|
-
addClientAuthentication,
|
|
3013
|
-
fetchFn
|
|
3014
|
-
}) {
|
|
3015
|
-
var _a32;
|
|
3016
|
-
const grantType = "refresh_token";
|
|
3017
|
-
let tokenUrl;
|
|
3018
|
-
if (metadata) {
|
|
3019
|
-
tokenUrl = new URL(metadata.token_endpoint);
|
|
3020
|
-
if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {
|
|
3021
|
-
throw new Error(
|
|
3022
|
-
`Incompatible auth server: does not support grant type ${grantType}`
|
|
3023
|
-
);
|
|
3024
|
-
}
|
|
3025
|
-
} else {
|
|
3026
|
-
tokenUrl = new URL("/token", authorizationServerUrl);
|
|
3027
|
-
}
|
|
3028
|
-
const headers = new Headers({
|
|
3029
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
3030
|
-
Accept: "application/json"
|
|
3031
|
-
});
|
|
3032
|
-
const params = new URLSearchParams({
|
|
3033
|
-
grant_type: grantType,
|
|
3034
|
-
refresh_token: refreshToken
|
|
3035
|
-
});
|
|
3036
|
-
if (addClientAuthentication) {
|
|
3037
|
-
addClientAuthentication(headers, params, authorizationServerUrl, metadata);
|
|
3038
|
-
} else {
|
|
3039
|
-
const supportedMethods = (_a32 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a32 : [];
|
|
3040
|
-
const authMethod = selectClientAuthMethod(
|
|
3041
|
-
clientInformation,
|
|
3042
|
-
supportedMethods
|
|
3043
|
-
);
|
|
3044
|
-
applyClientAuthentication(authMethod, clientInformation, headers, params);
|
|
3045
|
-
}
|
|
3046
|
-
if (resource) {
|
|
3047
|
-
params.set("resource", resource.href);
|
|
3048
|
-
}
|
|
3049
|
-
const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {
|
|
3050
|
-
method: "POST",
|
|
3051
|
-
headers,
|
|
3052
|
-
body: params
|
|
3053
|
-
});
|
|
3054
|
-
if (!response.ok) {
|
|
3055
|
-
throw await parseErrorResponse(response);
|
|
3056
|
-
}
|
|
3057
|
-
return OAuthTokensSchema.parse({
|
|
3058
|
-
refresh_token: refreshToken,
|
|
3059
|
-
...await response.json()
|
|
3060
|
-
});
|
|
3061
|
-
}
|
|
3062
|
-
async function registerClient(authorizationServerUrl, {
|
|
3063
|
-
metadata,
|
|
3064
|
-
clientMetadata,
|
|
3065
|
-
fetchFn
|
|
3066
|
-
}) {
|
|
3067
|
-
let registrationUrl;
|
|
3068
|
-
if (metadata) {
|
|
3069
|
-
if (!metadata.registration_endpoint) {
|
|
3070
|
-
throw new Error(
|
|
3071
|
-
"Incompatible auth server: does not support dynamic client registration"
|
|
3072
|
-
);
|
|
3073
|
-
}
|
|
3074
|
-
registrationUrl = new URL(metadata.registration_endpoint);
|
|
3075
|
-
} else {
|
|
3076
|
-
registrationUrl = new URL("/register", authorizationServerUrl);
|
|
3077
|
-
}
|
|
3078
|
-
const response = await (fetchFn != null ? fetchFn : fetch)(registrationUrl, {
|
|
3079
|
-
method: "POST",
|
|
3080
|
-
headers: {
|
|
3081
|
-
"Content-Type": "application/json"
|
|
3082
|
-
},
|
|
3083
|
-
body: JSON.stringify(clientMetadata)
|
|
3084
|
-
});
|
|
3085
|
-
if (!response.ok) {
|
|
3086
|
-
throw await parseErrorResponse(response);
|
|
3087
|
-
}
|
|
3088
|
-
return OAuthClientInformationFullSchema.parse(await response.json());
|
|
3089
|
-
}
|
|
3090
|
-
async function auth(provider, options) {
|
|
3091
|
-
var _a32, _b32;
|
|
3092
|
-
try {
|
|
3093
|
-
return await authInternal(provider, options);
|
|
3094
|
-
} catch (error) {
|
|
3095
|
-
if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
|
|
3096
|
-
await ((_a32 = provider.invalidateCredentials) == null ? void 0 : _a32.call(provider, "all"));
|
|
3097
|
-
return await authInternal(provider, options);
|
|
3098
|
-
} else if (error instanceof InvalidGrantError) {
|
|
3099
|
-
await ((_b32 = provider.invalidateCredentials) == null ? void 0 : _b32.call(provider, "tokens"));
|
|
3100
|
-
return await authInternal(provider, options);
|
|
3101
|
-
}
|
|
3102
|
-
throw error;
|
|
3103
|
-
}
|
|
3104
|
-
}
|
|
3105
|
-
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
|
|
3106
|
-
const defaultResource = resourceUrlFromServerUrl(serverUrl);
|
|
3107
|
-
if (provider.validateResourceURL) {
|
|
3108
|
-
return await provider.validateResourceURL(
|
|
3109
|
-
defaultResource,
|
|
3110
|
-
resourceMetadata == null ? void 0 : resourceMetadata.resource
|
|
3111
|
-
);
|
|
3112
|
-
}
|
|
3113
|
-
if (!resourceMetadata) {
|
|
3114
|
-
return void 0;
|
|
3115
|
-
}
|
|
3116
|
-
if (!checkResourceAllowed({
|
|
3117
|
-
requestedResource: defaultResource,
|
|
3118
|
-
configuredResource: resourceMetadata.resource
|
|
3119
|
-
})) {
|
|
3120
|
-
throw new Error(
|
|
3121
|
-
`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`
|
|
3122
|
-
);
|
|
3123
|
-
}
|
|
3124
|
-
return new URL(resourceMetadata.resource);
|
|
3125
|
-
}
|
|
3126
|
-
async function authInternal(provider, {
|
|
3127
|
-
serverUrl,
|
|
3128
|
-
authorizationCode,
|
|
3129
|
-
scope,
|
|
3130
|
-
resourceMetadataUrl,
|
|
3131
|
-
fetchFn
|
|
3132
|
-
}) {
|
|
3133
|
-
let resourceMetadata;
|
|
3134
|
-
let authorizationServerUrl;
|
|
3135
|
-
try {
|
|
3136
|
-
resourceMetadata = await discoverOAuthProtectedResourceMetadata(
|
|
3137
|
-
serverUrl,
|
|
3138
|
-
{ resourceMetadataUrl },
|
|
3139
|
-
fetchFn
|
|
3140
|
-
);
|
|
3141
|
-
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
|
|
3142
|
-
authorizationServerUrl = resourceMetadata.authorization_servers[0];
|
|
3143
|
-
}
|
|
3144
|
-
} catch (e) {
|
|
3145
|
-
}
|
|
3146
|
-
if (!authorizationServerUrl) {
|
|
3147
|
-
authorizationServerUrl = serverUrl;
|
|
3148
|
-
}
|
|
3149
|
-
const resource = await selectResourceURL(
|
|
3150
|
-
serverUrl,
|
|
3151
|
-
provider,
|
|
3152
|
-
resourceMetadata
|
|
3153
|
-
);
|
|
3154
|
-
const metadata = await discoverAuthorizationServerMetadata(
|
|
3155
|
-
authorizationServerUrl,
|
|
3156
|
-
{
|
|
3157
|
-
fetchFn
|
|
3158
|
-
}
|
|
3159
|
-
);
|
|
3160
|
-
let clientInformation = await Promise.resolve(provider.clientInformation());
|
|
3161
|
-
if (!clientInformation) {
|
|
3162
|
-
if (authorizationCode !== void 0) {
|
|
3163
|
-
throw new Error(
|
|
3164
|
-
"Existing OAuth client information is required when exchanging an authorization code"
|
|
3165
|
-
);
|
|
3166
|
-
}
|
|
3167
|
-
if (!provider.saveClientInformation) {
|
|
3168
|
-
throw new Error(
|
|
3169
|
-
"OAuth client information must be saveable for dynamic registration"
|
|
3170
|
-
);
|
|
3171
|
-
}
|
|
3172
|
-
const fullInformation = await registerClient(authorizationServerUrl, {
|
|
3173
|
-
metadata,
|
|
3174
|
-
clientMetadata: provider.clientMetadata,
|
|
3175
|
-
fetchFn
|
|
3176
|
-
});
|
|
3177
|
-
await provider.saveClientInformation(fullInformation);
|
|
3178
|
-
clientInformation = fullInformation;
|
|
3179
|
-
}
|
|
3180
|
-
if (authorizationCode !== void 0) {
|
|
3181
|
-
const codeVerifier2 = await provider.codeVerifier();
|
|
3182
|
-
const tokens2 = await exchangeAuthorization(authorizationServerUrl, {
|
|
3183
|
-
metadata,
|
|
3184
|
-
clientInformation,
|
|
3185
|
-
authorizationCode,
|
|
3186
|
-
codeVerifier: codeVerifier2,
|
|
3187
|
-
redirectUri: provider.redirectUrl,
|
|
3188
|
-
resource,
|
|
3189
|
-
addClientAuthentication: provider.addClientAuthentication,
|
|
3190
|
-
fetchFn
|
|
3191
|
-
});
|
|
3192
|
-
await provider.saveTokens(tokens2);
|
|
3193
|
-
return "AUTHORIZED";
|
|
3194
|
-
}
|
|
3195
|
-
const tokens = await provider.tokens();
|
|
3196
|
-
if (tokens == null ? void 0 : tokens.refresh_token) {
|
|
3197
|
-
try {
|
|
3198
|
-
const newTokens = await refreshAuthorization(authorizationServerUrl, {
|
|
3199
|
-
metadata,
|
|
3200
|
-
clientInformation,
|
|
3201
|
-
refreshToken: tokens.refresh_token,
|
|
3202
|
-
resource,
|
|
3203
|
-
addClientAuthentication: provider.addClientAuthentication,
|
|
3204
|
-
fetchFn
|
|
3205
|
-
});
|
|
3206
|
-
await provider.saveTokens(newTokens);
|
|
3207
|
-
return "AUTHORIZED";
|
|
3208
|
-
} catch (error) {
|
|
3209
|
-
if (
|
|
3210
|
-
// If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
|
|
3211
|
-
!(error instanceof MCPClientOAuthError) || error instanceof ServerError
|
|
3212
|
-
) {
|
|
3213
|
-
} else {
|
|
3214
|
-
throw error;
|
|
3215
|
-
}
|
|
3216
|
-
}
|
|
3217
|
-
}
|
|
3218
|
-
const state = provider.state ? await provider.state() : void 0;
|
|
3219
|
-
const { authorizationUrl, codeVerifier } = await startAuthorization(
|
|
3220
|
-
authorizationServerUrl,
|
|
3221
|
-
{
|
|
3222
|
-
metadata,
|
|
3223
|
-
clientInformation,
|
|
3224
|
-
state,
|
|
3225
|
-
redirectUrl: provider.redirectUrl,
|
|
3226
|
-
scope: scope || provider.clientMetadata.scope,
|
|
3227
|
-
resource
|
|
3228
|
-
}
|
|
3229
|
-
);
|
|
3230
|
-
await provider.saveCodeVerifier(codeVerifier);
|
|
3231
|
-
await provider.redirectToAuthorization(authorizationUrl);
|
|
3232
|
-
return "REDIRECT";
|
|
3233
|
-
}
|
|
3234
|
-
var SseMCPTransport = class {
|
|
3235
|
-
constructor({
|
|
3236
|
-
url,
|
|
3237
|
-
headers,
|
|
3238
|
-
authProvider
|
|
3239
|
-
}) {
|
|
3240
|
-
this.connected = false;
|
|
3241
|
-
this.url = new URL(url);
|
|
3242
|
-
this.headers = headers;
|
|
3243
|
-
this.authProvider = authProvider;
|
|
3244
|
-
}
|
|
3245
|
-
async commonHeaders(base) {
|
|
3246
|
-
const headers = {
|
|
3247
|
-
...this.headers,
|
|
3248
|
-
...base,
|
|
3249
|
-
"mcp-protocol-version": LATEST_PROTOCOL_VERSION
|
|
3250
|
-
};
|
|
3251
|
-
if (this.authProvider) {
|
|
3252
|
-
const tokens = await this.authProvider.tokens();
|
|
3253
|
-
if (tokens == null ? void 0 : tokens.access_token) {
|
|
3254
|
-
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
3255
|
-
}
|
|
3256
|
-
}
|
|
3257
|
-
return withUserAgentSuffix(
|
|
3258
|
-
headers,
|
|
3259
|
-
`ai-sdk/${VERSION}`,
|
|
3260
|
-
getRuntimeEnvironmentUserAgent()
|
|
3261
|
-
);
|
|
3262
|
-
}
|
|
3263
|
-
async start() {
|
|
3264
|
-
return new Promise((resolve, reject) => {
|
|
3265
|
-
if (this.connected) {
|
|
3266
|
-
return resolve();
|
|
3267
|
-
}
|
|
3268
|
-
this.abortController = new AbortController();
|
|
3269
|
-
const establishConnection = async (triedAuth = false) => {
|
|
3270
|
-
var _a32, _b32, _c, _d, _e;
|
|
3271
|
-
try {
|
|
3272
|
-
const headers = await this.commonHeaders({
|
|
3273
|
-
Accept: "text/event-stream"
|
|
3274
|
-
});
|
|
3275
|
-
const response = await fetch(this.url.href, {
|
|
3276
|
-
headers,
|
|
3277
|
-
signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
|
|
3278
|
-
});
|
|
3279
|
-
if (response.status === 401 && this.authProvider && !triedAuth) {
|
|
3280
|
-
this.resourceMetadataUrl = extractResourceMetadataUrl(response);
|
|
3281
|
-
try {
|
|
3282
|
-
const result = await auth(this.authProvider, {
|
|
3283
|
-
serverUrl: this.url,
|
|
3284
|
-
resourceMetadataUrl: this.resourceMetadataUrl
|
|
3285
|
-
});
|
|
3286
|
-
if (result !== "AUTHORIZED") {
|
|
3287
|
-
const error = new UnauthorizedError();
|
|
3288
|
-
(_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
|
|
3289
|
-
return reject(error);
|
|
3290
|
-
}
|
|
3291
|
-
} catch (error) {
|
|
3292
|
-
(_c = this.onerror) == null ? void 0 : _c.call(this, error);
|
|
3293
|
-
return reject(error);
|
|
3294
|
-
}
|
|
3295
|
-
return establishConnection(true);
|
|
3296
|
-
}
|
|
3297
|
-
if (!response.ok || !response.body) {
|
|
3298
|
-
let errorMessage = `MCP SSE Transport Error: ${response.status} ${response.statusText}`;
|
|
3299
|
-
if (response.status === 405) {
|
|
3300
|
-
errorMessage += ". This server does not support SSE transport. Try using `http` transport instead";
|
|
3301
|
-
}
|
|
3302
|
-
const error = new MCPClientError({
|
|
3303
|
-
message: errorMessage
|
|
3304
|
-
});
|
|
3305
|
-
(_d = this.onerror) == null ? void 0 : _d.call(this, error);
|
|
3306
|
-
return reject(error);
|
|
3307
|
-
}
|
|
3308
|
-
const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
|
|
3309
|
-
const reader = stream.getReader();
|
|
3310
|
-
const processEvents = async () => {
|
|
3311
|
-
var _a42, _b42, _c2;
|
|
3312
|
-
try {
|
|
3313
|
-
while (true) {
|
|
3314
|
-
const { done, value } = await reader.read();
|
|
3315
|
-
if (done) {
|
|
3316
|
-
if (this.connected) {
|
|
3317
|
-
this.connected = false;
|
|
3318
|
-
throw new MCPClientError({
|
|
3319
|
-
message: "MCP SSE Transport Error: Connection closed unexpectedly"
|
|
3320
|
-
});
|
|
3321
|
-
}
|
|
3322
|
-
return;
|
|
3323
|
-
}
|
|
3324
|
-
const { event, data } = value;
|
|
3325
|
-
if (event === "endpoint") {
|
|
3326
|
-
this.endpoint = new URL(data, this.url);
|
|
3327
|
-
if (this.endpoint.origin !== this.url.origin) {
|
|
3328
|
-
throw new MCPClientError({
|
|
3329
|
-
message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`
|
|
3330
|
-
});
|
|
3331
|
-
}
|
|
3332
|
-
this.connected = true;
|
|
3333
|
-
resolve();
|
|
3334
|
-
} else if (event === "message") {
|
|
3335
|
-
try {
|
|
3336
|
-
const message = JSONRPCMessageSchema.parse(
|
|
3337
|
-
JSON.parse(data)
|
|
3338
|
-
);
|
|
3339
|
-
(_a42 = this.onmessage) == null ? void 0 : _a42.call(this, message);
|
|
3340
|
-
} catch (error) {
|
|
3341
|
-
const e = new MCPClientError({
|
|
3342
|
-
message: "MCP SSE Transport Error: Failed to parse message",
|
|
3343
|
-
cause: error
|
|
3344
|
-
});
|
|
3345
|
-
(_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
|
|
3346
|
-
}
|
|
3347
|
-
}
|
|
3348
|
-
}
|
|
3349
|
-
} catch (error) {
|
|
3350
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
3351
|
-
return;
|
|
3352
|
-
}
|
|
3353
|
-
(_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
|
|
3354
|
-
reject(error);
|
|
3355
|
-
}
|
|
3356
|
-
};
|
|
3357
|
-
this.sseConnection = {
|
|
3358
|
-
close: () => reader.cancel()
|
|
3359
|
-
};
|
|
3360
|
-
processEvents();
|
|
3361
|
-
} catch (error) {
|
|
3362
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
3363
|
-
return;
|
|
3364
|
-
}
|
|
3365
|
-
(_e = this.onerror) == null ? void 0 : _e.call(this, error);
|
|
3366
|
-
reject(error);
|
|
3367
|
-
}
|
|
3368
|
-
};
|
|
3369
|
-
void establishConnection();
|
|
3370
|
-
});
|
|
3371
|
-
}
|
|
3372
|
-
async close() {
|
|
3373
|
-
var _a32, _b32, _c;
|
|
3374
|
-
this.connected = false;
|
|
3375
|
-
(_a32 = this.sseConnection) == null ? void 0 : _a32.close();
|
|
3376
|
-
(_b32 = this.abortController) == null ? void 0 : _b32.abort();
|
|
3377
|
-
(_c = this.onclose) == null ? void 0 : _c.call(this);
|
|
3378
|
-
}
|
|
3379
|
-
async send(message) {
|
|
3380
|
-
if (!this.endpoint || !this.connected) {
|
|
3381
|
-
throw new MCPClientError({
|
|
3382
|
-
message: "MCP SSE Transport Error: Not connected"
|
|
3383
|
-
});
|
|
3384
|
-
}
|
|
3385
|
-
const endpoint = this.endpoint;
|
|
3386
|
-
const attempt = async (triedAuth = false) => {
|
|
3387
|
-
var _a32, _b32, _c, _d, _e;
|
|
3388
|
-
try {
|
|
3389
|
-
const headers = await this.commonHeaders({
|
|
3390
|
-
"Content-Type": "application/json"
|
|
3391
|
-
});
|
|
3392
|
-
const init = {
|
|
3393
|
-
method: "POST",
|
|
3394
|
-
headers,
|
|
3395
|
-
body: JSON.stringify(message),
|
|
3396
|
-
signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
|
|
3397
|
-
};
|
|
3398
|
-
const response = await fetch(endpoint, init);
|
|
3399
|
-
if (response.status === 401 && this.authProvider && !triedAuth) {
|
|
3400
|
-
this.resourceMetadataUrl = extractResourceMetadataUrl(response);
|
|
3401
|
-
try {
|
|
3402
|
-
const result = await auth(this.authProvider, {
|
|
3403
|
-
serverUrl: this.url,
|
|
3404
|
-
resourceMetadataUrl: this.resourceMetadataUrl
|
|
3405
|
-
});
|
|
3406
|
-
if (result !== "AUTHORIZED") {
|
|
3407
|
-
const error = new UnauthorizedError();
|
|
3408
|
-
(_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
|
|
3409
|
-
return;
|
|
3410
|
-
}
|
|
3411
|
-
} catch (error) {
|
|
3412
|
-
(_c = this.onerror) == null ? void 0 : _c.call(this, error);
|
|
3413
|
-
return;
|
|
3414
|
-
}
|
|
3415
|
-
return attempt(true);
|
|
3416
|
-
}
|
|
3417
|
-
if (!response.ok) {
|
|
3418
|
-
const text = await response.text().catch(() => null);
|
|
3419
|
-
const error = new MCPClientError({
|
|
3420
|
-
message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`
|
|
3421
|
-
});
|
|
3422
|
-
(_d = this.onerror) == null ? void 0 : _d.call(this, error);
|
|
3423
|
-
return;
|
|
3424
|
-
}
|
|
3425
|
-
} catch (error) {
|
|
3426
|
-
(_e = this.onerror) == null ? void 0 : _e.call(this, error);
|
|
3427
|
-
return;
|
|
3428
|
-
}
|
|
3429
|
-
};
|
|
3430
|
-
await attempt();
|
|
3431
|
-
}
|
|
3432
|
-
};
|
|
3433
|
-
var HttpMCPTransport = class {
|
|
3434
|
-
constructor({
|
|
3435
|
-
url,
|
|
3436
|
-
headers,
|
|
3437
|
-
authProvider
|
|
3438
|
-
}) {
|
|
3439
|
-
this.inboundReconnectAttempts = 0;
|
|
3440
|
-
this.reconnectionOptions = {
|
|
3441
|
-
initialReconnectionDelay: 1e3,
|
|
3442
|
-
maxReconnectionDelay: 3e4,
|
|
3443
|
-
reconnectionDelayGrowFactor: 1.5,
|
|
3444
|
-
maxRetries: 2
|
|
3445
|
-
};
|
|
3446
|
-
this.url = new URL(url);
|
|
3447
|
-
this.headers = headers;
|
|
3448
|
-
this.authProvider = authProvider;
|
|
3449
|
-
}
|
|
3450
|
-
async commonHeaders(base) {
|
|
3451
|
-
const headers = {
|
|
3452
|
-
...this.headers,
|
|
3453
|
-
...base,
|
|
3454
|
-
"mcp-protocol-version": LATEST_PROTOCOL_VERSION
|
|
3455
|
-
};
|
|
3456
|
-
if (this.sessionId) {
|
|
3457
|
-
headers["mcp-session-id"] = this.sessionId;
|
|
3458
|
-
}
|
|
3459
|
-
if (this.authProvider) {
|
|
3460
|
-
const tokens = await this.authProvider.tokens();
|
|
3461
|
-
if (tokens == null ? void 0 : tokens.access_token) {
|
|
3462
|
-
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
3463
|
-
}
|
|
3464
|
-
}
|
|
3465
|
-
return withUserAgentSuffix(
|
|
3466
|
-
headers,
|
|
3467
|
-
`ai-sdk/${VERSION}`,
|
|
3468
|
-
getRuntimeEnvironmentUserAgent()
|
|
3469
|
-
);
|
|
3470
|
-
}
|
|
3471
|
-
async start() {
|
|
3472
|
-
if (this.abortController) {
|
|
3473
|
-
throw new MCPClientError({
|
|
3474
|
-
message: "MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."
|
|
3475
|
-
});
|
|
3476
|
-
}
|
|
3477
|
-
this.abortController = new AbortController();
|
|
3478
|
-
void this.openInboundSse();
|
|
3479
|
-
}
|
|
3480
|
-
async close() {
|
|
3481
|
-
var _a32, _b32, _c;
|
|
3482
|
-
(_a32 = this.inboundSseConnection) == null ? void 0 : _a32.close();
|
|
3483
|
-
try {
|
|
3484
|
-
if (this.sessionId && this.abortController && !this.abortController.signal.aborted) {
|
|
3485
|
-
const headers = await this.commonHeaders({});
|
|
3486
|
-
await fetch(this.url, {
|
|
3487
|
-
method: "DELETE",
|
|
3488
|
-
headers,
|
|
3489
|
-
signal: this.abortController.signal
|
|
3490
|
-
}).catch(() => void 0);
|
|
3491
|
-
}
|
|
3492
|
-
} catch (e) {
|
|
3493
|
-
}
|
|
3494
|
-
(_b32 = this.abortController) == null ? void 0 : _b32.abort();
|
|
3495
|
-
(_c = this.onclose) == null ? void 0 : _c.call(this);
|
|
3496
|
-
}
|
|
3497
|
-
async send(message) {
|
|
3498
|
-
const attempt = async (triedAuth = false) => {
|
|
3499
|
-
var _a32, _b32, _c, _d, _e, _f, _g;
|
|
3500
|
-
try {
|
|
3501
|
-
const headers = await this.commonHeaders({
|
|
3502
|
-
"Content-Type": "application/json",
|
|
3503
|
-
Accept: "application/json, text/event-stream"
|
|
3504
|
-
});
|
|
3505
|
-
const init = {
|
|
3506
|
-
method: "POST",
|
|
3507
|
-
headers,
|
|
3508
|
-
body: JSON.stringify(message),
|
|
3509
|
-
signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
|
|
3510
|
-
};
|
|
3511
|
-
const response = await fetch(this.url, init);
|
|
3512
|
-
const sessionId = response.headers.get("mcp-session-id");
|
|
3513
|
-
if (sessionId) {
|
|
3514
|
-
this.sessionId = sessionId;
|
|
3515
|
-
}
|
|
3516
|
-
if (response.status === 401 && this.authProvider && !triedAuth) {
|
|
3517
|
-
this.resourceMetadataUrl = extractResourceMetadataUrl(response);
|
|
3518
|
-
try {
|
|
3519
|
-
const result = await auth(this.authProvider, {
|
|
3520
|
-
serverUrl: this.url,
|
|
3521
|
-
resourceMetadataUrl: this.resourceMetadataUrl
|
|
3522
|
-
});
|
|
3523
|
-
if (result !== "AUTHORIZED") {
|
|
3524
|
-
const error2 = new UnauthorizedError();
|
|
3525
|
-
throw error2;
|
|
3526
|
-
}
|
|
3527
|
-
} catch (error2) {
|
|
3528
|
-
(_b32 = this.onerror) == null ? void 0 : _b32.call(this, error2);
|
|
3529
|
-
throw error2;
|
|
3530
|
-
}
|
|
3531
|
-
return attempt(true);
|
|
3532
|
-
}
|
|
3533
|
-
if (response.status === 202) {
|
|
3534
|
-
if (!this.inboundSseConnection) {
|
|
3535
|
-
void this.openInboundSse();
|
|
3536
|
-
}
|
|
3537
|
-
return;
|
|
3538
|
-
}
|
|
3539
|
-
if (!response.ok) {
|
|
3540
|
-
const text = await response.text().catch(() => null);
|
|
3541
|
-
let errorMessage = `MCP HTTP Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`;
|
|
3542
|
-
if (response.status === 404) {
|
|
3543
|
-
errorMessage += ". This server does not support HTTP transport. Try using `sse` transport instead";
|
|
3544
|
-
}
|
|
3545
|
-
const error2 = new MCPClientError({
|
|
3546
|
-
message: errorMessage
|
|
3547
|
-
});
|
|
3548
|
-
(_c = this.onerror) == null ? void 0 : _c.call(this, error2);
|
|
3549
|
-
throw error2;
|
|
3550
|
-
}
|
|
3551
|
-
const isNotification = !("id" in message);
|
|
3552
|
-
if (isNotification) {
|
|
3553
|
-
return;
|
|
3554
|
-
}
|
|
3555
|
-
const contentType = response.headers.get("content-type") || "";
|
|
3556
|
-
if (contentType.includes("application/json")) {
|
|
3557
|
-
const data = await response.json();
|
|
3558
|
-
const messages = Array.isArray(data) ? data.map((m) => JSONRPCMessageSchema.parse(m)) : [JSONRPCMessageSchema.parse(data)];
|
|
3559
|
-
for (const m of messages) (_d = this.onmessage) == null ? void 0 : _d.call(this, m);
|
|
3560
|
-
return;
|
|
3561
|
-
}
|
|
3562
|
-
if (contentType.includes("text/event-stream")) {
|
|
3563
|
-
if (!response.body) {
|
|
3564
|
-
const error2 = new MCPClientError({
|
|
3565
|
-
message: "MCP HTTP Transport Error: text/event-stream response without body"
|
|
3566
|
-
});
|
|
3567
|
-
(_e = this.onerror) == null ? void 0 : _e.call(this, error2);
|
|
3568
|
-
throw error2;
|
|
3569
|
-
}
|
|
3570
|
-
const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
|
|
3571
|
-
const reader = stream.getReader();
|
|
3572
|
-
const processEvents = async () => {
|
|
3573
|
-
var _a42, _b42, _c2;
|
|
3574
|
-
try {
|
|
3575
|
-
while (true) {
|
|
3576
|
-
const { done, value } = await reader.read();
|
|
3577
|
-
if (done) return;
|
|
3578
|
-
const { event, data } = value;
|
|
3579
|
-
if (event === "message") {
|
|
3580
|
-
try {
|
|
3581
|
-
const msg = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
3582
|
-
(_a42 = this.onmessage) == null ? void 0 : _a42.call(this, msg);
|
|
3583
|
-
} catch (error2) {
|
|
3584
|
-
const e = new MCPClientError({
|
|
3585
|
-
message: "MCP HTTP Transport Error: Failed to parse message",
|
|
3586
|
-
cause: error2
|
|
3587
|
-
});
|
|
3588
|
-
(_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
|
|
3589
|
-
}
|
|
3590
|
-
}
|
|
3591
|
-
}
|
|
3592
|
-
} catch (error2) {
|
|
3593
|
-
if (error2 instanceof Error && error2.name === "AbortError") {
|
|
3594
|
-
return;
|
|
3595
|
-
}
|
|
3596
|
-
(_c2 = this.onerror) == null ? void 0 : _c2.call(this, error2);
|
|
3597
|
-
}
|
|
3598
|
-
};
|
|
3599
|
-
processEvents();
|
|
3600
|
-
return;
|
|
3601
|
-
}
|
|
3602
|
-
const error = new MCPClientError({
|
|
3603
|
-
message: `MCP HTTP Transport Error: Unexpected content type: ${contentType}`
|
|
3604
|
-
});
|
|
3605
|
-
(_f = this.onerror) == null ? void 0 : _f.call(this, error);
|
|
3606
|
-
throw error;
|
|
3607
|
-
} catch (error) {
|
|
3608
|
-
(_g = this.onerror) == null ? void 0 : _g.call(this, error);
|
|
3609
|
-
throw error;
|
|
3610
|
-
}
|
|
3611
|
-
};
|
|
3612
|
-
await attempt();
|
|
3613
|
-
}
|
|
3614
|
-
getNextReconnectionDelay(attempt) {
|
|
3615
|
-
const {
|
|
3616
|
-
initialReconnectionDelay,
|
|
3617
|
-
reconnectionDelayGrowFactor,
|
|
3618
|
-
maxReconnectionDelay
|
|
3619
|
-
} = this.reconnectionOptions;
|
|
3620
|
-
return Math.min(
|
|
3621
|
-
initialReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, attempt),
|
|
3622
|
-
maxReconnectionDelay
|
|
3623
|
-
);
|
|
3624
|
-
}
|
|
3625
|
-
scheduleInboundSseReconnection() {
|
|
3626
|
-
var _a32;
|
|
3627
|
-
const { maxRetries } = this.reconnectionOptions;
|
|
3628
|
-
if (maxRetries > 0 && this.inboundReconnectAttempts >= maxRetries) {
|
|
3629
|
-
(_a32 = this.onerror) == null ? void 0 : _a32.call(
|
|
3630
|
-
this,
|
|
3631
|
-
new MCPClientError({
|
|
3632
|
-
message: `MCP HTTP Transport Error: Maximum reconnection attempts (${maxRetries}) exceeded.`
|
|
3633
|
-
})
|
|
3634
|
-
);
|
|
3635
|
-
return;
|
|
3636
|
-
}
|
|
3637
|
-
const delay = this.getNextReconnectionDelay(this.inboundReconnectAttempts);
|
|
3638
|
-
this.inboundReconnectAttempts += 1;
|
|
3639
|
-
setTimeout(async () => {
|
|
3640
|
-
var _a42;
|
|
3641
|
-
if ((_a42 = this.abortController) == null ? void 0 : _a42.signal.aborted) return;
|
|
3642
|
-
await this.openInboundSse(false, this.lastInboundEventId);
|
|
3643
|
-
}, delay);
|
|
3644
|
-
}
|
|
3645
|
-
// Open optional inbound SSE stream; best-effort and resumable
|
|
3646
|
-
async openInboundSse(triedAuth = false, resumeToken) {
|
|
3647
|
-
var _a32, _b32, _c, _d, _e, _f;
|
|
3648
|
-
try {
|
|
3649
|
-
const headers = await this.commonHeaders({
|
|
3650
|
-
Accept: "text/event-stream"
|
|
3651
|
-
});
|
|
3652
|
-
if (resumeToken) {
|
|
3653
|
-
headers["last-event-id"] = resumeToken;
|
|
3654
|
-
}
|
|
3655
|
-
const response = await fetch(this.url.href, {
|
|
3656
|
-
method: "GET",
|
|
3657
|
-
headers,
|
|
3658
|
-
signal: (_a32 = this.abortController) == null ? void 0 : _a32.signal
|
|
3659
|
-
});
|
|
3660
|
-
const sessionId = response.headers.get("mcp-session-id");
|
|
3661
|
-
if (sessionId) {
|
|
3662
|
-
this.sessionId = sessionId;
|
|
3663
|
-
}
|
|
3664
|
-
if (response.status === 401 && this.authProvider && !triedAuth) {
|
|
3665
|
-
this.resourceMetadataUrl = extractResourceMetadataUrl(response);
|
|
3666
|
-
try {
|
|
3667
|
-
const result = await auth(this.authProvider, {
|
|
3668
|
-
serverUrl: this.url,
|
|
3669
|
-
resourceMetadataUrl: this.resourceMetadataUrl
|
|
3670
|
-
});
|
|
3671
|
-
if (result !== "AUTHORIZED") {
|
|
3672
|
-
const error = new UnauthorizedError();
|
|
3673
|
-
(_b32 = this.onerror) == null ? void 0 : _b32.call(this, error);
|
|
3674
|
-
return;
|
|
3675
|
-
}
|
|
3676
|
-
} catch (error) {
|
|
3677
|
-
(_c = this.onerror) == null ? void 0 : _c.call(this, error);
|
|
3678
|
-
return;
|
|
3679
|
-
}
|
|
3680
|
-
return this.openInboundSse(true, resumeToken);
|
|
3681
|
-
}
|
|
3682
|
-
if (response.status === 405) {
|
|
3683
|
-
return;
|
|
3684
|
-
}
|
|
3685
|
-
if (!response.ok || !response.body) {
|
|
3686
|
-
const error = new MCPClientError({
|
|
3687
|
-
message: `MCP HTTP Transport Error: GET SSE failed: ${response.status} ${response.statusText}`
|
|
3688
|
-
});
|
|
3689
|
-
(_d = this.onerror) == null ? void 0 : _d.call(this, error);
|
|
3690
|
-
return;
|
|
3691
|
-
}
|
|
3692
|
-
const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
|
|
3693
|
-
const reader = stream.getReader();
|
|
3694
|
-
const processEvents = async () => {
|
|
3695
|
-
var _a42, _b42, _c2, _d2;
|
|
3696
|
-
try {
|
|
3697
|
-
while (true) {
|
|
3698
|
-
const { done, value } = await reader.read();
|
|
3699
|
-
if (done) return;
|
|
3700
|
-
const { event, data, id } = value;
|
|
3701
|
-
if (id) {
|
|
3702
|
-
this.lastInboundEventId = id;
|
|
3703
|
-
}
|
|
3704
|
-
if (event === "message") {
|
|
3705
|
-
try {
|
|
3706
|
-
const msg = JSONRPCMessageSchema.parse(JSON.parse(data));
|
|
3707
|
-
(_a42 = this.onmessage) == null ? void 0 : _a42.call(this, msg);
|
|
3708
|
-
} catch (error) {
|
|
3709
|
-
const e = new MCPClientError({
|
|
3710
|
-
message: "MCP HTTP Transport Error: Failed to parse message",
|
|
3711
|
-
cause: error
|
|
3712
|
-
});
|
|
3713
|
-
(_b42 = this.onerror) == null ? void 0 : _b42.call(this, e);
|
|
3714
|
-
}
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
} catch (error) {
|
|
3718
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
3719
|
-
return;
|
|
3720
|
-
}
|
|
3721
|
-
(_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
|
|
3722
|
-
if (!((_d2 = this.abortController) == null ? void 0 : _d2.signal.aborted)) {
|
|
3723
|
-
this.scheduleInboundSseReconnection();
|
|
3724
|
-
}
|
|
3725
|
-
}
|
|
3726
|
-
};
|
|
3727
|
-
this.inboundSseConnection = {
|
|
3728
|
-
close: () => reader.cancel()
|
|
3729
|
-
};
|
|
3730
|
-
this.inboundReconnectAttempts = 0;
|
|
3731
|
-
processEvents();
|
|
3732
|
-
} catch (error) {
|
|
3733
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
3734
|
-
return;
|
|
3735
|
-
}
|
|
3736
|
-
(_e = this.onerror) == null ? void 0 : _e.call(this, error);
|
|
3737
|
-
if (!((_f = this.abortController) == null ? void 0 : _f.signal.aborted)) {
|
|
3738
|
-
this.scheduleInboundSseReconnection();
|
|
3739
|
-
}
|
|
3740
|
-
}
|
|
3741
|
-
}
|
|
3742
|
-
};
|
|
3743
|
-
function createMcpTransport(config) {
|
|
3744
|
-
switch (config.type) {
|
|
3745
|
-
case "sse":
|
|
3746
|
-
return new SseMCPTransport(config);
|
|
3747
|
-
case "http":
|
|
3748
|
-
return new HttpMCPTransport(config);
|
|
3749
|
-
default:
|
|
3750
|
-
throw new MCPClientError({
|
|
3751
|
-
message: "Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."
|
|
3752
|
-
});
|
|
3753
|
-
}
|
|
3754
|
-
}
|
|
3755
|
-
function isCustomMcpTransport(transport) {
|
|
3756
|
-
return "start" in transport && typeof transport.start === "function" && "send" in transport && typeof transport.send === "function" && "close" in transport && typeof transport.close === "function";
|
|
3757
|
-
}
|
|
3758
|
-
var CLIENT_VERSION = "1.0.0";
|
|
3759
|
-
function mcpToModelOutput({
|
|
3760
|
-
output
|
|
3761
|
-
}) {
|
|
3762
|
-
const result = output;
|
|
3763
|
-
if (!("content" in result) || !Array.isArray(result.content)) {
|
|
3764
|
-
return { type: "json", value: result };
|
|
3765
|
-
}
|
|
3766
|
-
const convertedContent = result.content.map(
|
|
3767
|
-
(part) => {
|
|
3768
|
-
if (part.type === "text" && "text" in part) {
|
|
3769
|
-
return { type: "text", text: part.text };
|
|
3770
|
-
}
|
|
3771
|
-
if (part.type === "image" && "data" in part && "mimeType" in part) {
|
|
3772
|
-
return {
|
|
3773
|
-
type: "image-data",
|
|
3774
|
-
data: part.data,
|
|
3775
|
-
mediaType: part.mimeType
|
|
3776
|
-
};
|
|
3777
|
-
}
|
|
3778
|
-
return { type: "text", text: JSON.stringify(part) };
|
|
3779
|
-
}
|
|
3780
|
-
);
|
|
3781
|
-
return { type: "content", value: convertedContent };
|
|
3782
|
-
}
|
|
3783
|
-
async function createMCPClient(config) {
|
|
3784
|
-
const client = new DefaultMCPClient(config);
|
|
3785
|
-
await client.init();
|
|
3786
|
-
return client;
|
|
3787
|
-
}
|
|
3788
|
-
var DefaultMCPClient = class {
|
|
3789
|
-
constructor({
|
|
3790
|
-
transport: transportConfig,
|
|
3791
|
-
name: name32 = "ai-sdk-mcp-client",
|
|
3792
|
-
version = CLIENT_VERSION,
|
|
3793
|
-
onUncaughtError,
|
|
3794
|
-
capabilities
|
|
3795
|
-
}) {
|
|
3796
|
-
this.requestMessageId = 0;
|
|
3797
|
-
this.responseHandlers = /* @__PURE__ */ new Map();
|
|
3798
|
-
this.serverCapabilities = {};
|
|
3799
|
-
this.isClosed = true;
|
|
3800
|
-
this.onUncaughtError = onUncaughtError;
|
|
3801
|
-
this.clientCapabilities = capabilities != null ? capabilities : {};
|
|
3802
|
-
if (isCustomMcpTransport(transportConfig)) {
|
|
3803
|
-
this.transport = transportConfig;
|
|
3804
|
-
} else {
|
|
3805
|
-
this.transport = createMcpTransport(transportConfig);
|
|
3806
|
-
}
|
|
3807
|
-
this.transport.onclose = () => this.onClose();
|
|
3808
|
-
this.transport.onerror = (error) => this.onError(error);
|
|
3809
|
-
this.transport.onmessage = (message) => {
|
|
3810
|
-
if ("method" in message) {
|
|
3811
|
-
if ("id" in message) {
|
|
3812
|
-
this.onRequestMessage(message);
|
|
3813
|
-
} else {
|
|
3814
|
-
this.onError(
|
|
3815
|
-
new MCPClientError({
|
|
3816
|
-
message: "Unsupported message type"
|
|
3817
|
-
})
|
|
3818
|
-
);
|
|
3819
|
-
}
|
|
3820
|
-
return;
|
|
3821
|
-
}
|
|
3822
|
-
this.onResponse(message);
|
|
3823
|
-
};
|
|
3824
|
-
this.clientInfo = {
|
|
3825
|
-
name: name32,
|
|
3826
|
-
version
|
|
3827
|
-
};
|
|
3828
|
-
}
|
|
3829
|
-
async init() {
|
|
3830
|
-
try {
|
|
3831
|
-
await this.transport.start();
|
|
3832
|
-
this.isClosed = false;
|
|
3833
|
-
const result = await this.request({
|
|
3834
|
-
request: {
|
|
3835
|
-
method: "initialize",
|
|
3836
|
-
params: {
|
|
3837
|
-
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
3838
|
-
capabilities: this.clientCapabilities,
|
|
3839
|
-
clientInfo: this.clientInfo
|
|
3840
|
-
}
|
|
3841
|
-
},
|
|
3842
|
-
resultSchema: InitializeResultSchema
|
|
3843
|
-
});
|
|
3844
|
-
if (result === void 0) {
|
|
3845
|
-
throw new MCPClientError({
|
|
3846
|
-
message: "Server sent invalid initialize result"
|
|
3847
|
-
});
|
|
3848
|
-
}
|
|
3849
|
-
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
|
|
3850
|
-
throw new MCPClientError({
|
|
3851
|
-
message: `Server's protocol version is not supported: ${result.protocolVersion}`
|
|
3852
|
-
});
|
|
3853
|
-
}
|
|
3854
|
-
this.serverCapabilities = result.capabilities;
|
|
3855
|
-
await this.notification({
|
|
3856
|
-
method: "notifications/initialized"
|
|
3857
|
-
});
|
|
3858
|
-
return this;
|
|
3859
|
-
} catch (error) {
|
|
3860
|
-
await this.close();
|
|
3861
|
-
throw error;
|
|
3862
|
-
}
|
|
3863
|
-
}
|
|
3864
|
-
async close() {
|
|
3865
|
-
var _a32;
|
|
3866
|
-
if (this.isClosed) return;
|
|
3867
|
-
await ((_a32 = this.transport) == null ? void 0 : _a32.close());
|
|
3868
|
-
this.onClose();
|
|
3869
|
-
}
|
|
3870
|
-
assertCapability(method) {
|
|
3871
|
-
switch (method) {
|
|
3872
|
-
case "initialize":
|
|
3873
|
-
break;
|
|
3874
|
-
case "tools/list":
|
|
3875
|
-
case "tools/call":
|
|
3876
|
-
if (!this.serverCapabilities.tools) {
|
|
3877
|
-
throw new MCPClientError({
|
|
3878
|
-
message: `Server does not support tools`
|
|
3879
|
-
});
|
|
3880
|
-
}
|
|
3881
|
-
break;
|
|
3882
|
-
case "resources/list":
|
|
3883
|
-
case "resources/read":
|
|
3884
|
-
case "resources/templates/list":
|
|
3885
|
-
if (!this.serverCapabilities.resources) {
|
|
3886
|
-
throw new MCPClientError({
|
|
3887
|
-
message: `Server does not support resources`
|
|
3888
|
-
});
|
|
3889
|
-
}
|
|
3890
|
-
break;
|
|
3891
|
-
case "prompts/list":
|
|
3892
|
-
case "prompts/get":
|
|
3893
|
-
if (!this.serverCapabilities.prompts) {
|
|
3894
|
-
throw new MCPClientError({
|
|
3895
|
-
message: `Server does not support prompts`
|
|
3896
|
-
});
|
|
3897
|
-
}
|
|
3898
|
-
break;
|
|
3899
|
-
default:
|
|
3900
|
-
throw new MCPClientError({
|
|
3901
|
-
message: `Unsupported method: ${method}`
|
|
3902
|
-
});
|
|
3903
|
-
}
|
|
3904
|
-
}
|
|
3905
|
-
async request({
|
|
3906
|
-
request,
|
|
3907
|
-
resultSchema,
|
|
3908
|
-
options
|
|
3909
|
-
}) {
|
|
3910
|
-
return new Promise((resolve, reject) => {
|
|
3911
|
-
if (this.isClosed) {
|
|
3912
|
-
return reject(
|
|
3913
|
-
new MCPClientError({
|
|
3914
|
-
message: "Attempted to send a request from a closed client"
|
|
3915
|
-
})
|
|
3916
|
-
);
|
|
3917
|
-
}
|
|
3918
|
-
this.assertCapability(request.method);
|
|
3919
|
-
const signal = options == null ? void 0 : options.signal;
|
|
3920
|
-
signal == null ? void 0 : signal.throwIfAborted();
|
|
3921
|
-
const messageId = this.requestMessageId++;
|
|
3922
|
-
const jsonrpcRequest = {
|
|
3923
|
-
...request,
|
|
3924
|
-
jsonrpc: "2.0",
|
|
3925
|
-
id: messageId
|
|
3926
|
-
};
|
|
3927
|
-
const cleanup2 = () => {
|
|
3928
|
-
this.responseHandlers.delete(messageId);
|
|
3929
|
-
};
|
|
3930
|
-
this.responseHandlers.set(messageId, (response) => {
|
|
3931
|
-
if (signal == null ? void 0 : signal.aborted) {
|
|
3932
|
-
return reject(
|
|
3933
|
-
new MCPClientError({
|
|
3934
|
-
message: "Request was aborted",
|
|
3935
|
-
cause: signal.reason
|
|
3936
|
-
})
|
|
3937
|
-
);
|
|
3938
|
-
}
|
|
3939
|
-
if (response instanceof Error) {
|
|
3940
|
-
return reject(response);
|
|
3941
|
-
}
|
|
3942
|
-
try {
|
|
3943
|
-
const result = resultSchema.parse(response.result);
|
|
3944
|
-
resolve(result);
|
|
3945
|
-
} catch (error) {
|
|
3946
|
-
const parseError = new MCPClientError({
|
|
3947
|
-
message: "Failed to parse server response",
|
|
3948
|
-
cause: error
|
|
3949
|
-
});
|
|
3950
|
-
reject(parseError);
|
|
3951
|
-
}
|
|
3952
|
-
});
|
|
3953
|
-
this.transport.send(jsonrpcRequest).catch((error) => {
|
|
3954
|
-
cleanup2();
|
|
3955
|
-
reject(error);
|
|
3956
|
-
});
|
|
3957
|
-
});
|
|
3958
|
-
}
|
|
3959
|
-
async listTools({
|
|
3960
|
-
params,
|
|
3961
|
-
options
|
|
3962
|
-
} = {}) {
|
|
3963
|
-
return this.request({
|
|
3964
|
-
request: { method: "tools/list", params },
|
|
3965
|
-
resultSchema: ListToolsResultSchema,
|
|
3966
|
-
options
|
|
3967
|
-
});
|
|
3968
|
-
}
|
|
3969
|
-
async callTool({
|
|
3970
|
-
name: name32,
|
|
3971
|
-
args,
|
|
3972
|
-
options
|
|
3973
|
-
}) {
|
|
3974
|
-
try {
|
|
3975
|
-
return this.request({
|
|
3976
|
-
request: { method: "tools/call", params: { name: name32, arguments: args } },
|
|
3977
|
-
resultSchema: CallToolResultSchema,
|
|
3978
|
-
options: {
|
|
3979
|
-
signal: options == null ? void 0 : options.abortSignal
|
|
3980
|
-
}
|
|
3981
|
-
});
|
|
3982
|
-
} catch (error) {
|
|
3983
|
-
throw error;
|
|
3984
|
-
}
|
|
3985
|
-
}
|
|
3986
|
-
async listResourcesInternal({
|
|
3987
|
-
params,
|
|
3988
|
-
options
|
|
3989
|
-
} = {}) {
|
|
3990
|
-
try {
|
|
3991
|
-
return this.request({
|
|
3992
|
-
request: { method: "resources/list", params },
|
|
3993
|
-
resultSchema: ListResourcesResultSchema,
|
|
3994
|
-
options
|
|
3995
|
-
});
|
|
3996
|
-
} catch (error) {
|
|
3997
|
-
throw error;
|
|
3998
|
-
}
|
|
3999
|
-
}
|
|
4000
|
-
async readResourceInternal({
|
|
4001
|
-
uri,
|
|
4002
|
-
options
|
|
4003
|
-
}) {
|
|
4004
|
-
try {
|
|
4005
|
-
return this.request({
|
|
4006
|
-
request: { method: "resources/read", params: { uri } },
|
|
4007
|
-
resultSchema: ReadResourceResultSchema,
|
|
4008
|
-
options
|
|
4009
|
-
});
|
|
4010
|
-
} catch (error) {
|
|
4011
|
-
throw error;
|
|
4012
|
-
}
|
|
4013
|
-
}
|
|
4014
|
-
async listResourceTemplatesInternal({
|
|
4015
|
-
options
|
|
4016
|
-
} = {}) {
|
|
4017
|
-
try {
|
|
4018
|
-
return this.request({
|
|
4019
|
-
request: { method: "resources/templates/list" },
|
|
4020
|
-
resultSchema: ListResourceTemplatesResultSchema,
|
|
4021
|
-
options
|
|
4022
|
-
});
|
|
4023
|
-
} catch (error) {
|
|
4024
|
-
throw error;
|
|
4025
|
-
}
|
|
4026
|
-
}
|
|
4027
|
-
async listPromptsInternal({
|
|
4028
|
-
params,
|
|
4029
|
-
options
|
|
4030
|
-
} = {}) {
|
|
4031
|
-
try {
|
|
4032
|
-
return this.request({
|
|
4033
|
-
request: { method: "prompts/list", params },
|
|
4034
|
-
resultSchema: ListPromptsResultSchema,
|
|
4035
|
-
options
|
|
4036
|
-
});
|
|
4037
|
-
} catch (error) {
|
|
4038
|
-
throw error;
|
|
4039
|
-
}
|
|
4040
|
-
}
|
|
4041
|
-
async getPromptInternal({
|
|
4042
|
-
name: name32,
|
|
4043
|
-
args,
|
|
4044
|
-
options
|
|
4045
|
-
}) {
|
|
4046
|
-
try {
|
|
4047
|
-
return this.request({
|
|
4048
|
-
request: { method: "prompts/get", params: { name: name32, arguments: args } },
|
|
4049
|
-
resultSchema: GetPromptResultSchema,
|
|
4050
|
-
options
|
|
4051
|
-
});
|
|
4052
|
-
} catch (error) {
|
|
4053
|
-
throw error;
|
|
4054
|
-
}
|
|
4055
|
-
}
|
|
4056
|
-
async notification(notification) {
|
|
4057
|
-
const jsonrpcNotification = {
|
|
4058
|
-
...notification,
|
|
4059
|
-
jsonrpc: "2.0"
|
|
4060
|
-
};
|
|
4061
|
-
await this.transport.send(jsonrpcNotification);
|
|
4062
|
-
}
|
|
4063
|
-
/**
|
|
4064
|
-
* Returns a set of AI SDK tools from the MCP server.
|
|
4065
|
-
* This fetches tool definitions and wraps them with execute functions.
|
|
4066
|
-
* @returns A record of tool names to their implementations
|
|
4067
|
-
*/
|
|
4068
|
-
async tools({
|
|
4069
|
-
schemas = "automatic"
|
|
4070
|
-
} = {}) {
|
|
4071
|
-
const definitions = await this.listTools();
|
|
4072
|
-
return this.toolsFromDefinitions(definitions, {
|
|
4073
|
-
schemas
|
|
4074
|
-
});
|
|
4075
|
-
}
|
|
4076
|
-
/**
|
|
4077
|
-
* Creates AI SDK tools from tool definitions without fetching from the server.
|
|
4078
|
-
*/
|
|
4079
|
-
toolsFromDefinitions(definitions, { schemas = "automatic" } = {}) {
|
|
4080
|
-
var _a32, _b32;
|
|
4081
|
-
const tools = {};
|
|
4082
|
-
for (const {
|
|
4083
|
-
name: name32,
|
|
4084
|
-
title,
|
|
4085
|
-
description,
|
|
4086
|
-
inputSchema,
|
|
4087
|
-
annotations,
|
|
4088
|
-
_meta
|
|
4089
|
-
} of definitions.tools) {
|
|
4090
|
-
const resolvedTitle = title != null ? title : annotations == null ? void 0 : annotations.title;
|
|
4091
|
-
if (schemas !== "automatic" && !(name32 in schemas)) {
|
|
4092
|
-
continue;
|
|
4093
|
-
}
|
|
4094
|
-
const self = this;
|
|
4095
|
-
const outputSchema = schemas !== "automatic" ? (_a32 = schemas[name32]) == null ? void 0 : _a32.outputSchema : void 0;
|
|
4096
|
-
const execute = async (args, options) => {
|
|
4097
|
-
var _a42;
|
|
4098
|
-
(_a42 = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a42.throwIfAborted();
|
|
4099
|
-
const result = await self.callTool({ name: name32, args, options });
|
|
4100
|
-
if (outputSchema != null) {
|
|
4101
|
-
return self.extractStructuredContent(result, outputSchema, name32);
|
|
4102
|
-
}
|
|
4103
|
-
return result;
|
|
4104
|
-
};
|
|
4105
|
-
const toolWithExecute = schemas === "automatic" ? dynamicTool({
|
|
4106
|
-
description,
|
|
4107
|
-
title: resolvedTitle,
|
|
4108
|
-
inputSchema: jsonSchema({
|
|
4109
|
-
...inputSchema,
|
|
4110
|
-
properties: (_b32 = inputSchema.properties) != null ? _b32 : {},
|
|
4111
|
-
additionalProperties: false
|
|
4112
|
-
}),
|
|
4113
|
-
execute,
|
|
4114
|
-
toModelOutput: mcpToModelOutput
|
|
4115
|
-
}) : tool({
|
|
4116
|
-
description,
|
|
4117
|
-
title: resolvedTitle,
|
|
4118
|
-
inputSchema: schemas[name32].inputSchema,
|
|
4119
|
-
...outputSchema != null ? { outputSchema } : {},
|
|
4120
|
-
execute,
|
|
4121
|
-
toModelOutput: mcpToModelOutput
|
|
4122
|
-
});
|
|
4123
|
-
tools[name32] = { ...toolWithExecute, _meta };
|
|
4124
|
-
}
|
|
4125
|
-
return tools;
|
|
4126
|
-
}
|
|
4127
|
-
/**
|
|
4128
|
-
* Extracts and validates structuredContent from a tool result.
|
|
4129
|
-
*/
|
|
4130
|
-
async extractStructuredContent(result, outputSchema, toolName) {
|
|
4131
|
-
if ("structuredContent" in result && result.structuredContent != null) {
|
|
4132
|
-
const validationResult = await safeValidateTypes({
|
|
4133
|
-
value: result.structuredContent,
|
|
4134
|
-
schema: asSchema(outputSchema)
|
|
4135
|
-
});
|
|
4136
|
-
if (!validationResult.success) {
|
|
4137
|
-
throw new MCPClientError({
|
|
4138
|
-
message: `Tool "${toolName}" returned structuredContent that does not match the expected outputSchema`,
|
|
4139
|
-
cause: validationResult.error
|
|
4140
|
-
});
|
|
4141
|
-
}
|
|
4142
|
-
return validationResult.value;
|
|
4143
|
-
}
|
|
4144
|
-
if ("content" in result && Array.isArray(result.content)) {
|
|
4145
|
-
const textContent = result.content.find((c) => c.type === "text");
|
|
4146
|
-
if (textContent && "text" in textContent) {
|
|
4147
|
-
const parseResult = await safeParseJSON({
|
|
4148
|
-
text: textContent.text,
|
|
4149
|
-
schema: outputSchema
|
|
4150
|
-
});
|
|
4151
|
-
if (!parseResult.success) {
|
|
4152
|
-
throw new MCPClientError({
|
|
4153
|
-
message: `Tool "${toolName}" returned content that does not match the expected outputSchema`,
|
|
4154
|
-
cause: parseResult.error
|
|
4155
|
-
});
|
|
4156
|
-
}
|
|
4157
|
-
return parseResult.value;
|
|
4158
|
-
}
|
|
4159
|
-
}
|
|
4160
|
-
throw new MCPClientError({
|
|
4161
|
-
message: `Tool "${toolName}" did not return structuredContent or parseable text content`
|
|
4162
|
-
});
|
|
4163
|
-
}
|
|
4164
|
-
listResources({
|
|
4165
|
-
params,
|
|
4166
|
-
options
|
|
4167
|
-
} = {}) {
|
|
4168
|
-
return this.listResourcesInternal({ params, options });
|
|
4169
|
-
}
|
|
4170
|
-
readResource({
|
|
4171
|
-
uri,
|
|
4172
|
-
options
|
|
4173
|
-
}) {
|
|
4174
|
-
return this.readResourceInternal({ uri, options });
|
|
4175
|
-
}
|
|
4176
|
-
listResourceTemplates({
|
|
4177
|
-
options
|
|
4178
|
-
} = {}) {
|
|
4179
|
-
return this.listResourceTemplatesInternal({ options });
|
|
4180
|
-
}
|
|
4181
|
-
experimental_listPrompts({
|
|
4182
|
-
params,
|
|
4183
|
-
options
|
|
4184
|
-
} = {}) {
|
|
4185
|
-
return this.listPromptsInternal({ params, options });
|
|
4186
|
-
}
|
|
4187
|
-
experimental_getPrompt({
|
|
4188
|
-
name: name32,
|
|
4189
|
-
arguments: args,
|
|
4190
|
-
options
|
|
4191
|
-
}) {
|
|
4192
|
-
return this.getPromptInternal({ name: name32, args, options });
|
|
4193
|
-
}
|
|
4194
|
-
onElicitationRequest(schema, handler) {
|
|
4195
|
-
if (schema !== ElicitationRequestSchema) {
|
|
4196
|
-
throw new MCPClientError({
|
|
4197
|
-
message: "Unsupported request schema. Only ElicitationRequestSchema is supported."
|
|
4198
|
-
});
|
|
4199
|
-
}
|
|
4200
|
-
this.elicitationRequestHandler = handler;
|
|
4201
|
-
}
|
|
4202
|
-
async onRequestMessage(request) {
|
|
4203
|
-
try {
|
|
4204
|
-
if (request.method !== "elicitation/create") {
|
|
4205
|
-
await this.transport.send({
|
|
4206
|
-
jsonrpc: "2.0",
|
|
4207
|
-
id: request.id,
|
|
4208
|
-
error: {
|
|
4209
|
-
code: -32601,
|
|
4210
|
-
message: `Unsupported request method: ${request.method}`
|
|
4211
|
-
}
|
|
4212
|
-
});
|
|
4213
|
-
return;
|
|
4214
|
-
}
|
|
4215
|
-
if (!this.elicitationRequestHandler) {
|
|
4216
|
-
await this.transport.send({
|
|
4217
|
-
jsonrpc: "2.0",
|
|
4218
|
-
id: request.id,
|
|
4219
|
-
error: {
|
|
4220
|
-
code: -32601,
|
|
4221
|
-
message: "No elicitation handler registered on client"
|
|
4222
|
-
}
|
|
4223
|
-
});
|
|
4224
|
-
return;
|
|
4225
|
-
}
|
|
4226
|
-
const parsedRequest = ElicitationRequestSchema.safeParse({
|
|
4227
|
-
method: request.method,
|
|
4228
|
-
params: request.params
|
|
4229
|
-
});
|
|
4230
|
-
if (!parsedRequest.success) {
|
|
4231
|
-
await this.transport.send({
|
|
4232
|
-
jsonrpc: "2.0",
|
|
4233
|
-
id: request.id,
|
|
4234
|
-
error: {
|
|
4235
|
-
code: -32602,
|
|
4236
|
-
message: `Invalid elicitation request: ${parsedRequest.error.message}`,
|
|
4237
|
-
data: parsedRequest.error.issues
|
|
4238
|
-
}
|
|
4239
|
-
});
|
|
4240
|
-
return;
|
|
4241
|
-
}
|
|
4242
|
-
try {
|
|
4243
|
-
const result = await this.elicitationRequestHandler(parsedRequest.data);
|
|
4244
|
-
const validatedResult = ElicitResultSchema.parse(result);
|
|
4245
|
-
await this.transport.send({
|
|
4246
|
-
jsonrpc: "2.0",
|
|
4247
|
-
id: request.id,
|
|
4248
|
-
result: validatedResult
|
|
4249
|
-
});
|
|
4250
|
-
} catch (error) {
|
|
4251
|
-
await this.transport.send({
|
|
4252
|
-
jsonrpc: "2.0",
|
|
4253
|
-
id: request.id,
|
|
4254
|
-
error: {
|
|
4255
|
-
code: -32603,
|
|
4256
|
-
message: error instanceof Error ? error.message : "Failed to handle elicitation request"
|
|
4257
|
-
}
|
|
4258
|
-
});
|
|
4259
|
-
this.onError(error);
|
|
4260
|
-
}
|
|
4261
|
-
} catch (error) {
|
|
4262
|
-
this.onError(error);
|
|
4263
|
-
}
|
|
4264
|
-
}
|
|
4265
|
-
onClose() {
|
|
4266
|
-
if (this.isClosed) return;
|
|
4267
|
-
this.isClosed = true;
|
|
4268
|
-
const error = new MCPClientError({
|
|
4269
|
-
message: "Connection closed"
|
|
4270
|
-
});
|
|
4271
|
-
for (const handler of this.responseHandlers.values()) {
|
|
4272
|
-
handler(error);
|
|
4273
|
-
}
|
|
4274
|
-
this.responseHandlers.clear();
|
|
4275
|
-
}
|
|
4276
|
-
onError(error) {
|
|
4277
|
-
if (this.onUncaughtError) {
|
|
4278
|
-
this.onUncaughtError(error);
|
|
4279
|
-
}
|
|
4280
|
-
}
|
|
4281
|
-
onResponse(response) {
|
|
4282
|
-
const messageId = Number(response.id);
|
|
4283
|
-
const handler = this.responseHandlers.get(messageId);
|
|
4284
|
-
if (handler === void 0) {
|
|
4285
|
-
throw new MCPClientError({
|
|
4286
|
-
message: `Protocol error: Received a response for an unknown message ID: ${JSON.stringify(
|
|
4287
|
-
response
|
|
4288
|
-
)}`
|
|
4289
|
-
});
|
|
4290
|
-
}
|
|
4291
|
-
this.responseHandlers.delete(messageId);
|
|
4292
|
-
handler(
|
|
4293
|
-
"result" in response ? response : new MCPClientError({
|
|
4294
|
-
message: response.error.message,
|
|
4295
|
-
code: response.error.code,
|
|
4296
|
-
data: response.error.data,
|
|
4297
|
-
cause: response.error
|
|
4298
|
-
})
|
|
4299
|
-
);
|
|
4300
|
-
}
|
|
4301
|
-
};
|
|
4302
|
-
|
|
4303
|
-
// src/adapters/vercel-ai.ts
|
|
4304
|
-
async function createVercelAiMcpClient(options) {
|
|
4305
|
-
const { url, headers } = options;
|
|
4306
|
-
const client = await createMCPClient({
|
|
4307
|
-
transport: {
|
|
4308
|
-
type: "http",
|
|
4309
|
-
url,
|
|
4310
|
-
headers
|
|
4311
|
-
}
|
|
4312
|
-
});
|
|
4313
|
-
return client;
|
|
4314
|
-
}
|
|
4315
|
-
|
|
4316
|
-
// src/core/base.ts
|
|
4317
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4318
|
-
import { z as z8 } from "zod";
|
|
4319
|
-
function createBaseMcpServer(options) {
|
|
4320
|
-
const server = new McpServer({
|
|
4321
|
-
name: "corsair",
|
|
4322
|
-
version: "1.0.0",
|
|
4323
|
-
description: "Use this to interact with the Corsair API. Corsair helps you integrate with dozens of tools and services."
|
|
4324
|
-
});
|
|
4325
|
-
for (const def of buildCorsairToolDefs(options)) {
|
|
4326
|
-
server.registerTool(
|
|
4327
|
-
def.name,
|
|
4328
|
-
{ description: def.description, inputSchema: z8.object(def.shape) },
|
|
4329
|
-
def.handler
|
|
4330
|
-
);
|
|
4331
|
-
}
|
|
4332
|
-
return server;
|
|
4333
|
-
}
|
|
4334
|
-
|
|
4335
|
-
// src/core/http.ts
|
|
4336
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4337
|
-
import { randomUUID } from "crypto";
|
|
4338
|
-
import { Router as createRouter } from "express";
|
|
4339
|
-
var sessions = /* @__PURE__ */ new Map();
|
|
4340
|
-
function cleanup(sessionId) {
|
|
4341
|
-
const session = sessions.get(sessionId);
|
|
4342
|
-
if (session) {
|
|
4343
|
-
session.transport.close();
|
|
4344
|
-
session.server.close();
|
|
4345
|
-
sessions.delete(sessionId);
|
|
4346
|
-
}
|
|
4347
|
-
}
|
|
4348
|
-
function createMcpRouter(createServer) {
|
|
4349
|
-
const router = createRouter();
|
|
4350
|
-
router.post("/", async (req, res) => {
|
|
4351
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
4352
|
-
if (sessionId) {
|
|
4353
|
-
const session = sessions.get(sessionId);
|
|
4354
|
-
if (!session) {
|
|
4355
|
-
res.status(404).json({ error: "Session not found" });
|
|
4356
|
-
return;
|
|
4357
|
-
}
|
|
4358
|
-
await session.transport.handleRequest(req, res, req.body);
|
|
4359
|
-
return;
|
|
4360
|
-
}
|
|
4361
|
-
const server = createServer();
|
|
4362
|
-
const transport = new StreamableHTTPServerTransport({
|
|
4363
|
-
sessionIdGenerator: () => randomUUID(),
|
|
4364
|
-
onsessioninitialized: (id) => {
|
|
4365
|
-
sessions.set(id, { server, transport });
|
|
4366
|
-
}
|
|
4367
|
-
});
|
|
4368
|
-
res.on("close", () => {
|
|
4369
|
-
const id = transport.sessionId;
|
|
4370
|
-
if (id) {
|
|
4371
|
-
setTimeout(() => cleanup(id), 6e4);
|
|
4372
|
-
}
|
|
4373
|
-
});
|
|
4374
|
-
await server.connect(transport);
|
|
4375
|
-
await transport.handleRequest(req, res, req.body);
|
|
4376
|
-
});
|
|
4377
|
-
router.get("/", async (req, res) => {
|
|
4378
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
4379
|
-
if (!sessionId || !sessions.has(sessionId)) {
|
|
4380
|
-
res.status(400).json({ error: "Missing or invalid mcp-session-id" });
|
|
4381
|
-
return;
|
|
4382
|
-
}
|
|
4383
|
-
const session = sessions.get(sessionId);
|
|
4384
|
-
await session.transport.handleRequest(req, res);
|
|
4385
|
-
});
|
|
4386
|
-
router.delete("/", async (req, res) => {
|
|
4387
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
4388
|
-
if (sessionId) cleanup(sessionId);
|
|
4389
|
-
res.status(200).end();
|
|
4390
|
-
});
|
|
4391
|
-
return router;
|
|
4392
|
-
}
|
|
4393
|
-
|
|
4394
|
-
// src/core/stdio.ts
|
|
4395
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4396
|
-
async function runStdioMcpServer(options) {
|
|
4397
|
-
const server = createBaseMcpServer(options);
|
|
4398
|
-
const transport = new StdioServerTransport();
|
|
4399
|
-
await server.connect(transport);
|
|
4400
|
-
}
|
|
2
|
+
AnthropicProvider,
|
|
3
|
+
BaseProvider,
|
|
4
|
+
ClaudeProvider,
|
|
5
|
+
MastraProvider,
|
|
6
|
+
OllamaProvider,
|
|
7
|
+
OpenAIAgentsProvider,
|
|
8
|
+
buildCorsairToolDefs,
|
|
9
|
+
createBaseMcpServer,
|
|
10
|
+
createMcpRouter,
|
|
11
|
+
createVercelAiMcpClient,
|
|
12
|
+
getOpenAIMcpConfig,
|
|
13
|
+
runStdioMcpServer
|
|
14
|
+
} from "./chunk-QFVNNGDE.js";
|
|
4401
15
|
export {
|
|
4402
16
|
AnthropicProvider,
|
|
4403
17
|
BaseProvider,
|