integrate-sdk 0.7.23 → 0.7.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/adapters/auto-routes.d.ts +51 -0
  2. package/dist/adapters/auto-routes.d.ts.map +1 -0
  3. package/dist/adapters/auto-routes.js +2 -2
  4. package/dist/adapters/base-handler.d.ts +182 -0
  5. package/dist/adapters/base-handler.d.ts.map +1 -0
  6. package/dist/adapters/base-handler.js +1 -1
  7. package/dist/adapters/index.d.ts +13 -0
  8. package/dist/adapters/index.d.ts.map +1 -0
  9. package/dist/adapters/index.js +2173 -0
  10. package/dist/adapters/nextjs-oauth-redirect.d.ts +41 -0
  11. package/dist/adapters/nextjs-oauth-redirect.d.ts.map +1 -0
  12. package/dist/adapters/nextjs-oauth-redirect.js +2 -2
  13. package/dist/adapters/nextjs.d.ts +358 -0
  14. package/dist/adapters/nextjs.d.ts.map +1 -0
  15. package/dist/adapters/nextjs.js +3 -3
  16. package/dist/adapters/node.d.ts +48 -0
  17. package/dist/adapters/node.d.ts.map +1 -0
  18. package/dist/adapters/node.js +2 -2
  19. package/dist/adapters/solid-start.d.ts +8 -0
  20. package/dist/adapters/solid-start.d.ts.map +1 -0
  21. package/dist/adapters/solid-start.js +12 -12
  22. package/dist/adapters/svelte-kit.d.ts +83 -0
  23. package/dist/adapters/svelte-kit.d.ts.map +1 -0
  24. package/dist/adapters/svelte-kit.js +13 -13
  25. package/dist/adapters/tanstack-start.d.ts +53 -0
  26. package/dist/adapters/tanstack-start.d.ts.map +1 -0
  27. package/dist/adapters/tanstack-start.js +1 -1
  28. package/dist/ai/anthropic.d.ts +182 -0
  29. package/dist/ai/anthropic.d.ts.map +1 -0
  30. package/dist/ai/anthropic.js +4265 -0
  31. package/dist/ai/cloudflare.d.ts +158 -0
  32. package/dist/ai/cloudflare.d.ts.map +1 -0
  33. package/dist/ai/cloudflare.js +4249 -0
  34. package/dist/ai/google.d.ts +159 -0
  35. package/dist/ai/google.d.ts.map +1 -0
  36. package/dist/ai/google.js +4242 -0
  37. package/dist/ai/index.d.ts +79 -0
  38. package/dist/ai/index.d.ts.map +1 -0
  39. package/dist/ai/index.js +4580 -0
  40. package/dist/ai/langchain.d.ts +139 -0
  41. package/dist/ai/langchain.d.ts.map +1 -0
  42. package/dist/ai/langchain.js +4237 -0
  43. package/dist/ai/llamaindex.d.ts +125 -0
  44. package/dist/ai/llamaindex.d.ts.map +1 -0
  45. package/dist/ai/llamaindex.js +4236 -0
  46. package/dist/ai/mastra.d.ts +138 -0
  47. package/dist/ai/mastra.d.ts.map +1 -0
  48. package/dist/ai/mastra.js +4240 -0
  49. package/dist/ai/openai-agents.d.ts +99 -0
  50. package/dist/ai/openai-agents.d.ts.map +1 -0
  51. package/dist/ai/openai-agents.js +4235 -0
  52. package/dist/ai/openai.d.ts +130 -0
  53. package/dist/ai/openai.d.ts.map +1 -0
  54. package/dist/ai/openai.js +4245 -0
  55. package/dist/ai/utils.d.ts +75 -0
  56. package/dist/ai/utils.d.ts.map +1 -0
  57. package/dist/ai/utils.js +4212 -0
  58. package/dist/ai/vercel-ai.d.ts +141 -0
  59. package/dist/ai/vercel-ai.d.ts.map +1 -0
  60. package/dist/ai/vercel-ai.js +4238 -0
  61. package/dist/src/adapters/index.d.ts +13 -0
  62. package/dist/src/adapters/index.d.ts.map +1 -0
  63. package/package.json +8 -62
@@ -0,0 +1,2173 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
12
+
13
+ // base-handler.ts
14
+ class OAuthHandler {
15
+ config;
16
+ serverUrl;
17
+ apiKey;
18
+ constructor(config) {
19
+ this.config = config;
20
+ if (!config || !config.providers) {
21
+ throw new Error("OAuthHandler requires a valid config with providers");
22
+ }
23
+ this.serverUrl = config.serverUrl || MCP_SERVER_URL;
24
+ this.apiKey = config.apiKey;
25
+ }
26
+ getHeaders(additionalHeaders) {
27
+ const headers = {
28
+ ...additionalHeaders
29
+ };
30
+ if (this.apiKey) {
31
+ headers["X-API-KEY"] = this.apiKey;
32
+ }
33
+ return headers;
34
+ }
35
+ async handleAuthorize(request) {
36
+ const providerConfig = this.config.providers[request.provider];
37
+ if (!providerConfig) {
38
+ throw new Error(`Provider ${request.provider} not configured. Add OAuth credentials to your API route configuration.`);
39
+ }
40
+ if (!providerConfig.clientId || !providerConfig.clientSecret) {
41
+ throw new Error(`Missing OAuth credentials for ${request.provider}. Check your environment variables.`);
42
+ }
43
+ const url = new URL("/oauth/authorize", this.serverUrl);
44
+ url.searchParams.set("provider", request.provider);
45
+ url.searchParams.set("client_id", providerConfig.clientId);
46
+ url.searchParams.set("client_secret", providerConfig.clientSecret);
47
+ url.searchParams.set("scope", request.scopes.join(","));
48
+ url.searchParams.set("state", request.state);
49
+ url.searchParams.set("code_challenge", request.codeChallenge);
50
+ url.searchParams.set("code_challenge_method", request.codeChallengeMethod);
51
+ const redirectUri = request.redirectUri || providerConfig.redirectUri;
52
+ if (redirectUri) {
53
+ url.searchParams.set("redirect_uri", redirectUri);
54
+ }
55
+ const response = await fetch(url.toString(), {
56
+ method: "GET",
57
+ headers: this.getHeaders()
58
+ });
59
+ if (!response.ok) {
60
+ const error = await response.text();
61
+ throw new Error(`MCP server failed to generate authorization URL: ${error}`);
62
+ }
63
+ const data = await response.json();
64
+ return data;
65
+ }
66
+ async handleCallback(request) {
67
+ const providerConfig = this.config.providers[request.provider];
68
+ if (!providerConfig) {
69
+ throw new Error(`Provider ${request.provider} not configured. Add OAuth credentials to your API route configuration.`);
70
+ }
71
+ if (!providerConfig.clientId || !providerConfig.clientSecret) {
72
+ throw new Error(`Missing OAuth credentials for ${request.provider}. Check your environment variables.`);
73
+ }
74
+ const url = new URL("/oauth/callback", this.serverUrl);
75
+ const response = await fetch(url.toString(), {
76
+ method: "POST",
77
+ headers: this.getHeaders({
78
+ "Content-Type": "application/json"
79
+ }),
80
+ body: JSON.stringify({
81
+ provider: request.provider,
82
+ code: request.code,
83
+ code_verifier: request.codeVerifier,
84
+ state: request.state,
85
+ client_id: providerConfig.clientId,
86
+ client_secret: providerConfig.clientSecret,
87
+ redirect_uri: providerConfig.redirectUri
88
+ })
89
+ });
90
+ if (!response.ok) {
91
+ const error = await response.text();
92
+ throw new Error(`MCP server failed to exchange authorization code: ${error}`);
93
+ }
94
+ const data = await response.json();
95
+ return data;
96
+ }
97
+ async handleStatus(provider, accessToken) {
98
+ const url = new URL("/oauth/status", this.serverUrl);
99
+ url.searchParams.set("provider", provider);
100
+ const response = await fetch(url.toString(), {
101
+ method: "GET",
102
+ headers: this.getHeaders({
103
+ Authorization: `Bearer ${accessToken}`
104
+ })
105
+ });
106
+ if (!response.ok) {
107
+ if (response.status === 401) {
108
+ return {
109
+ authorized: false
110
+ };
111
+ }
112
+ const error = await response.text();
113
+ throw new Error(`MCP server failed to check authorization status: ${error}`);
114
+ }
115
+ const data = await response.json();
116
+ return data;
117
+ }
118
+ async handleDisconnect(request, accessToken) {
119
+ if (!accessToken) {
120
+ throw new Error("No access token provided. Cannot disconnect provider.");
121
+ }
122
+ const url = new URL("/oauth/disconnect", this.serverUrl);
123
+ const response = await fetch(url.toString(), {
124
+ method: "POST",
125
+ headers: this.getHeaders({
126
+ "Content-Type": "application/json",
127
+ Authorization: `Bearer ${accessToken}`
128
+ }),
129
+ body: JSON.stringify({
130
+ provider: request.provider
131
+ })
132
+ });
133
+ if (!response.ok) {
134
+ const error = await response.text();
135
+ throw new Error(`MCP server failed to disconnect provider: ${error}`);
136
+ }
137
+ const data = await response.json();
138
+ return data;
139
+ }
140
+ async handleToolCall(request, authHeader) {
141
+ const url = this.serverUrl;
142
+ const headers = this.getHeaders({
143
+ "Content-Type": "application/json"
144
+ });
145
+ if (authHeader && authHeader.startsWith("Bearer ")) {
146
+ headers["Authorization"] = authHeader;
147
+ }
148
+ const jsonRpcRequest = {
149
+ jsonrpc: "2.0",
150
+ id: Date.now() + Math.random(),
151
+ method: "tools/call",
152
+ params: {
153
+ name: request.name,
154
+ arguments: request.arguments || {}
155
+ }
156
+ };
157
+ const response = await fetch(url, {
158
+ method: "POST",
159
+ headers,
160
+ body: JSON.stringify(jsonRpcRequest)
161
+ });
162
+ if (!response.ok) {
163
+ const error = await response.text();
164
+ throw new Error(`MCP server failed to execute tool call: ${error}`);
165
+ }
166
+ const jsonRpcResponse = await response.json();
167
+ if (jsonRpcResponse.error) {
168
+ const error = new Error(jsonRpcResponse.error.message || "Tool call failed");
169
+ error.code = jsonRpcResponse.error.code;
170
+ error.data = jsonRpcResponse.error.data;
171
+ throw error;
172
+ }
173
+ return jsonRpcResponse.result;
174
+ }
175
+ }
176
+ var MCP_SERVER_URL = "https://mcp.integrate.dev/api/v1/mcp";
177
+
178
+ // ../oauth/pkce.ts
179
+ var exports_pkce = {};
180
+ __export(exports_pkce, {
181
+ parseState: () => parseState,
182
+ generateStateWithReturnUrl: () => generateStateWithReturnUrl,
183
+ generateState: () => generateState,
184
+ generateCodeVerifier: () => generateCodeVerifier,
185
+ generateCodeChallenge: () => generateCodeChallenge
186
+ });
187
+ function generateCodeVerifier() {
188
+ const array = new Uint8Array(32);
189
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
190
+ crypto.getRandomValues(array);
191
+ } else if (typeof globalThis !== "undefined" && globalThis.crypto) {
192
+ globalThis.crypto.getRandomValues(array);
193
+ } else {
194
+ throw new Error("crypto.getRandomValues is not available. Please use Node.js 19+ or a modern browser.");
195
+ }
196
+ return base64UrlEncode(array);
197
+ }
198
+ async function generateCodeChallenge(verifier) {
199
+ const encoder = new TextEncoder;
200
+ const data = encoder.encode(verifier);
201
+ let hashBuffer;
202
+ if (typeof crypto !== "undefined" && crypto.subtle) {
203
+ hashBuffer = await crypto.subtle.digest("SHA-256", data);
204
+ } else if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle) {
205
+ hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", data);
206
+ } else {
207
+ throw new Error("crypto.subtle.digest is not available. Please use Node.js 19+ or a modern browser.");
208
+ }
209
+ return base64UrlEncode(new Uint8Array(hashBuffer));
210
+ }
211
+ function generateState() {
212
+ const array = new Uint8Array(16);
213
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
214
+ crypto.getRandomValues(array);
215
+ } else if (typeof globalThis !== "undefined" && globalThis.crypto) {
216
+ globalThis.crypto.getRandomValues(array);
217
+ } else {
218
+ throw new Error("crypto.getRandomValues is not available. Please use Node.js 19+ or a modern browser.");
219
+ }
220
+ return base64UrlEncode(array);
221
+ }
222
+ function generateStateWithReturnUrl(returnUrl) {
223
+ const csrf = generateState();
224
+ const stateData = returnUrl ? { csrf, returnUrl } : { csrf };
225
+ const encoder = new TextEncoder;
226
+ const jsonBytes = encoder.encode(JSON.stringify(stateData));
227
+ return base64UrlEncode(jsonBytes);
228
+ }
229
+ function parseState(state) {
230
+ try {
231
+ const decoded = base64UrlDecode(state);
232
+ const parsed = JSON.parse(decoded);
233
+ if (typeof parsed === "string") {
234
+ return { csrf: parsed };
235
+ } else if (parsed && typeof parsed === "object") {
236
+ return {
237
+ csrf: parsed.csrf || state,
238
+ returnUrl: parsed.returnUrl
239
+ };
240
+ }
241
+ return { csrf: state };
242
+ } catch {
243
+ return { csrf: state };
244
+ }
245
+ }
246
+ function base64UrlEncode(array) {
247
+ let base64 = "";
248
+ if (typeof Buffer !== "undefined") {
249
+ base64 = Buffer.from(array).toString("base64");
250
+ } else {
251
+ const binary = String.fromCharCode(...array);
252
+ base64 = btoa(binary);
253
+ }
254
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
255
+ }
256
+ function base64UrlDecode(str) {
257
+ let base64 = str.replace(/-/g, "+").replace(/_/g, "/");
258
+ while (base64.length % 4 !== 0) {
259
+ base64 += "=";
260
+ }
261
+ if (typeof Buffer !== "undefined") {
262
+ return Buffer.from(base64, "base64").toString("utf-8");
263
+ } else {
264
+ const binary = atob(base64);
265
+ const bytes = new Uint8Array(binary.length);
266
+ for (let i = 0;i < binary.length; i++) {
267
+ bytes[i] = binary.charCodeAt(i);
268
+ }
269
+ const decoder = new TextDecoder;
270
+ return decoder.decode(bytes);
271
+ }
272
+ }
273
+
274
+ // ../errors.ts
275
+ var exports_errors = {};
276
+ __export(exports_errors, {
277
+ parseServerError: () => parseServerError,
278
+ isTokenExpiredError: () => isTokenExpiredError,
279
+ isAuthorizationError: () => isAuthorizationError,
280
+ isAuthError: () => isAuthError,
281
+ ToolCallError: () => ToolCallError,
282
+ TokenExpiredError: () => TokenExpiredError,
283
+ IntegrateSDKError: () => IntegrateSDKError,
284
+ ConnectionError: () => ConnectionError,
285
+ AuthorizationError: () => AuthorizationError,
286
+ AuthenticationError: () => AuthenticationError
287
+ });
288
+ function isAuthError(error) {
289
+ return error instanceof AuthenticationError;
290
+ }
291
+ function isTokenExpiredError(error) {
292
+ return error instanceof TokenExpiredError;
293
+ }
294
+ function isAuthorizationError(error) {
295
+ return error instanceof AuthorizationError;
296
+ }
297
+ function parseServerError(error, context) {
298
+ if (error && typeof error === "object" && "jsonrpcError" in error) {
299
+ const jsonrpcError = error.jsonrpcError;
300
+ if (jsonrpcError && typeof jsonrpcError === "object") {
301
+ return parseServerError(jsonrpcError, context);
302
+ }
303
+ }
304
+ if (error && typeof error === "object" && "code" in error && "message" in error) {
305
+ const code = error.code;
306
+ const message = error.message || "Unknown error";
307
+ if (code === -32600) {
308
+ return new IntegrateSDKError(`Invalid request: ${message}`);
309
+ }
310
+ if (code === -32601) {
311
+ return new IntegrateSDKError(`Method not found: ${message}`);
312
+ }
313
+ if (code === -32602) {
314
+ return new IntegrateSDKError(`Invalid params: ${message}`);
315
+ }
316
+ if (code === 401 || code === -32001) {
317
+ if (message.toLowerCase().includes("expired") || message.toLowerCase().includes("token")) {
318
+ return new TokenExpiredError(message, context?.provider);
319
+ }
320
+ return new AuthenticationError(message, 401, context?.provider);
321
+ }
322
+ if (code === 403 || code === -32002) {
323
+ return new AuthorizationError(message, 403);
324
+ }
325
+ if (context?.toolName) {
326
+ return new ToolCallError(message, context.toolName, error);
327
+ }
328
+ return new IntegrateSDKError(message);
329
+ }
330
+ if (error instanceof Error) {
331
+ const message = error.message;
332
+ const statusCode = error.statusCode;
333
+ if (statusCode === 401) {
334
+ if (message.toLowerCase().includes("expired") || message.toLowerCase().includes("token")) {
335
+ return new TokenExpiredError(message, context?.provider);
336
+ }
337
+ return new AuthenticationError(message, 401, context?.provider);
338
+ }
339
+ if (statusCode === 403) {
340
+ return new AuthorizationError(message, 403);
341
+ }
342
+ if (message.includes("401") || message.includes("Unauthorized") || message.includes("unauthenticated")) {
343
+ if (message.toLowerCase().includes("expired") || message.toLowerCase().includes("token")) {
344
+ return new TokenExpiredError(message, context?.provider);
345
+ }
346
+ return new AuthenticationError(message, 401, context?.provider);
347
+ }
348
+ if (message.includes("403") || message.includes("Forbidden") || message.includes("unauthorized")) {
349
+ return new AuthorizationError(message, 403);
350
+ }
351
+ if (context?.toolName) {
352
+ return new ToolCallError(message, context.toolName, error);
353
+ }
354
+ return new IntegrateSDKError(message);
355
+ }
356
+ return new IntegrateSDKError(String(error));
357
+ }
358
+ var IntegrateSDKError, AuthenticationError, AuthorizationError, TokenExpiredError, ConnectionError, ToolCallError;
359
+ var init_errors = __esm(() => {
360
+ IntegrateSDKError = class IntegrateSDKError extends Error {
361
+ constructor(message) {
362
+ super(message);
363
+ this.name = "IntegrateSDKError";
364
+ }
365
+ };
366
+ AuthenticationError = class AuthenticationError extends IntegrateSDKError {
367
+ statusCode;
368
+ provider;
369
+ constructor(message, statusCode, provider) {
370
+ super(message);
371
+ this.name = "AuthenticationError";
372
+ this.statusCode = statusCode;
373
+ this.provider = provider;
374
+ }
375
+ };
376
+ AuthorizationError = class AuthorizationError extends IntegrateSDKError {
377
+ statusCode;
378
+ requiredScopes;
379
+ constructor(message, statusCode, requiredScopes) {
380
+ super(message);
381
+ this.name = "AuthorizationError";
382
+ this.statusCode = statusCode;
383
+ this.requiredScopes = requiredScopes;
384
+ }
385
+ };
386
+ TokenExpiredError = class TokenExpiredError extends AuthenticationError {
387
+ constructor(message, provider) {
388
+ super(message, 401, provider);
389
+ this.name = "TokenExpiredError";
390
+ }
391
+ };
392
+ ConnectionError = class ConnectionError extends IntegrateSDKError {
393
+ statusCode;
394
+ constructor(message, statusCode) {
395
+ super(message);
396
+ this.name = "ConnectionError";
397
+ this.statusCode = statusCode;
398
+ }
399
+ };
400
+ ToolCallError = class ToolCallError extends IntegrateSDKError {
401
+ toolName;
402
+ originalError;
403
+ constructor(message, toolName, originalError) {
404
+ super(message);
405
+ this.name = "ToolCallError";
406
+ this.toolName = toolName;
407
+ this.originalError = originalError;
408
+ }
409
+ };
410
+ });
411
+
412
+ // auto-routes.ts
413
+ var globalOAuthConfig = null;
414
+ function setGlobalOAuthConfig(config) {
415
+ globalOAuthConfig = config;
416
+ }
417
+ function getGlobalOAuthConfig() {
418
+ return globalOAuthConfig;
419
+ }
420
+ async function POST(req, context) {
421
+ if (!globalOAuthConfig) {
422
+ throw new Error("OAuth configuration not found. Did you configure oauthProviders in createMCPClient?");
423
+ }
424
+ const handler = new OAuthHandler(globalOAuthConfig);
425
+ const action = context?.params?.action;
426
+ if (!action) {
427
+ return createErrorResponse("Missing action parameter", 400);
428
+ }
429
+ try {
430
+ if (action === "authorize") {
431
+ const body = await parseRequestBody(req);
432
+ const result = await handler.handleAuthorize(body);
433
+ return createSuccessResponse(result);
434
+ }
435
+ if (action === "callback") {
436
+ const body = await parseRequestBody(req);
437
+ const result = await handler.handleCallback(body);
438
+ return createSuccessResponse(result);
439
+ }
440
+ if (action === "disconnect") {
441
+ const body = await parseRequestBody(req);
442
+ const accessToken = extractAccessToken(req);
443
+ if (!accessToken) {
444
+ return createErrorResponse("Missing or invalid Authorization header", 400);
445
+ }
446
+ if (!body.provider) {
447
+ return createErrorResponse("Missing provider in request body", 400);
448
+ }
449
+ const result = await handler.handleDisconnect({ provider: body.provider }, accessToken);
450
+ return createSuccessResponse(result);
451
+ }
452
+ return createErrorResponse(`Unknown action: ${action}`, 404);
453
+ } catch (error) {
454
+ console.error(`[OAuth ${action}] Error:`, error);
455
+ return createErrorResponse(error.message, 500);
456
+ }
457
+ }
458
+ async function GET(req, context) {
459
+ if (!globalOAuthConfig) {
460
+ throw new Error("OAuth configuration not found. Did you configure oauthProviders in createMCPClient?");
461
+ }
462
+ const handler = new OAuthHandler(globalOAuthConfig);
463
+ const action = context?.params?.action;
464
+ if (!action) {
465
+ return createErrorResponse("Missing action parameter", 400);
466
+ }
467
+ try {
468
+ if (action === "status") {
469
+ const provider = extractProvider(req);
470
+ const accessToken = extractAccessToken(req);
471
+ if (!provider) {
472
+ return createErrorResponse("Missing provider parameter", 400);
473
+ }
474
+ if (!accessToken) {
475
+ return createErrorResponse("Missing or invalid Authorization header", 400);
476
+ }
477
+ const result = await handler.handleStatus(provider, accessToken);
478
+ return createSuccessResponse(result);
479
+ }
480
+ return createErrorResponse(`Unknown action: ${action}`, 404);
481
+ } catch (error) {
482
+ console.error(`[OAuth ${action}] Error:`, error);
483
+ return createErrorResponse(error.message, 500);
484
+ }
485
+ }
486
+ async function parseRequestBody(req) {
487
+ if (typeof req.json === "function") {
488
+ return await req.json();
489
+ }
490
+ throw new Error("Unable to parse request body");
491
+ }
492
+ function extractAccessToken(req) {
493
+ if (req.headers?.get) {
494
+ const authHeader = req.headers.get("authorization");
495
+ if (authHeader && authHeader.startsWith("Bearer ")) {
496
+ return authHeader.substring(7);
497
+ }
498
+ }
499
+ return;
500
+ }
501
+ function extractProvider(req) {
502
+ let url;
503
+ if (req.nextUrl) {
504
+ url = new URL(req.nextUrl);
505
+ } else if (req.url) {
506
+ url = new URL(req.url);
507
+ } else {
508
+ return;
509
+ }
510
+ return url.searchParams.get("provider") || undefined;
511
+ }
512
+ function createSuccessResponse(data) {
513
+ if (typeof globalThis.NextResponse !== "undefined") {
514
+ const NextResponse = globalThis.NextResponse;
515
+ return NextResponse.json(data);
516
+ }
517
+ return new Response(JSON.stringify(data), {
518
+ status: 200,
519
+ headers: { "Content-Type": "application/json" }
520
+ });
521
+ }
522
+ function createErrorResponse(message, status) {
523
+ if (typeof globalThis.NextResponse !== "undefined") {
524
+ const NextResponse = globalThis.NextResponse;
525
+ return NextResponse.json({ error: message }, { status });
526
+ }
527
+ return new Response(JSON.stringify({ error: message }), {
528
+ status,
529
+ headers: { "Content-Type": "application/json" }
530
+ });
531
+ }
532
+
533
+ // nextjs.ts
534
+ function createNextOAuthHandler(config) {
535
+ const handler = new OAuthHandler(config);
536
+ const handlers = {
537
+ async authorize(req) {
538
+ try {
539
+ const body = await req.json();
540
+ const result = await handler.handleAuthorize(body);
541
+ return Response.json(result);
542
+ } catch (error) {
543
+ console.error("[OAuth Authorize] Error:", error);
544
+ return Response.json({ error: error.message || "Failed to get authorization URL" }, { status: 500 });
545
+ }
546
+ },
547
+ async callback(req) {
548
+ try {
549
+ const body = await req.json();
550
+ const result = await handler.handleCallback(body);
551
+ return Response.json(result);
552
+ } catch (error) {
553
+ console.error("[OAuth Callback] Error:", error);
554
+ return Response.json({ error: error.message || "Failed to exchange authorization code" }, { status: 500 });
555
+ }
556
+ },
557
+ async status(req) {
558
+ try {
559
+ const provider = req.nextUrl.searchParams.get("provider");
560
+ const authHeader = req.headers.get("authorization");
561
+ if (!provider) {
562
+ return Response.json({ error: "Missing provider query parameter" }, { status: 400 });
563
+ }
564
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
565
+ return Response.json({ error: "Missing or invalid Authorization header" }, { status: 400 });
566
+ }
567
+ const accessToken = authHeader.substring(7);
568
+ const result = await handler.handleStatus(provider, accessToken);
569
+ return Response.json(result);
570
+ } catch (error) {
571
+ console.error("[OAuth Status] Error:", error);
572
+ return Response.json({ error: error.message || "Failed to check authorization status" }, { status: 500 });
573
+ }
574
+ },
575
+ async disconnect(req) {
576
+ try {
577
+ const authHeader = req.headers.get("authorization");
578
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
579
+ return Response.json({ error: "Missing or invalid Authorization header" }, { status: 400 });
580
+ }
581
+ const accessToken = authHeader.substring(7);
582
+ const body = await req.json();
583
+ const { provider } = body;
584
+ if (!provider) {
585
+ return Response.json({ error: "Missing provider in request body" }, { status: 400 });
586
+ }
587
+ const result = await handler.handleDisconnect({ provider }, accessToken);
588
+ return Response.json(result);
589
+ } catch (error) {
590
+ console.error("[OAuth Disconnect] Error:", error);
591
+ return Response.json({ error: error.message || "Failed to disconnect provider" }, { status: 500 });
592
+ }
593
+ },
594
+ createRoutes() {
595
+ return {
596
+ async POST(req, context) {
597
+ const params = context.params instanceof Promise ? await context.params : context.params;
598
+ const action = params.action;
599
+ if (action === "authorize") {
600
+ return handlers.authorize(req);
601
+ }
602
+ if (action === "callback") {
603
+ return handlers.callback(req);
604
+ }
605
+ if (action === "disconnect") {
606
+ return handlers.disconnect(req);
607
+ }
608
+ if (action === "mcp") {
609
+ return handlers.mcp(req);
610
+ }
611
+ return Response.json({ error: `Unknown action: ${action}` }, { status: 404 });
612
+ },
613
+ async GET(req, context) {
614
+ const params = context.params instanceof Promise ? await context.params : context.params;
615
+ const action = params.action;
616
+ if (action === "status") {
617
+ return handlers.status(req);
618
+ }
619
+ return Response.json({ error: `Unknown action: ${action}` }, { status: 404 });
620
+ }
621
+ };
622
+ },
623
+ async mcp(req) {
624
+ try {
625
+ const body = await req.json();
626
+ const authHeader = req.headers.get("authorization");
627
+ const result = await handler.handleToolCall(body, authHeader);
628
+ return Response.json(result);
629
+ } catch (error) {
630
+ console.error("[MCP Tool Call] Error:", error);
631
+ return Response.json({ error: error.message || "Failed to execute tool call" }, { status: error.statusCode || 500 });
632
+ }
633
+ },
634
+ toNextJsHandler(redirectConfig) {
635
+ const defaultRedirectUrl = redirectConfig?.redirectUrl || "/";
636
+ const errorRedirectUrl = redirectConfig?.errorRedirectUrl || "/auth-error";
637
+ return {
638
+ async POST(req, context) {
639
+ const params = context.params instanceof Promise ? await context.params : context.params;
640
+ const segments = params.all || [];
641
+ if (segments.length === 2 && segments[0] === "oauth") {
642
+ const action = segments[1];
643
+ if (action === "authorize") {
644
+ return handlers.authorize(req);
645
+ }
646
+ if (action === "callback") {
647
+ return handlers.callback(req);
648
+ }
649
+ if (action === "disconnect") {
650
+ return handlers.disconnect(req);
651
+ }
652
+ return Response.json({ error: `Unknown action: ${action}` }, { status: 404 });
653
+ }
654
+ if (segments.length === 1 && segments[0] === "mcp") {
655
+ return handlers.mcp(req);
656
+ }
657
+ return Response.json({ error: `Invalid route: /${segments.join("/")}` }, { status: 404 });
658
+ },
659
+ async GET(req, context) {
660
+ const params = context.params instanceof Promise ? await context.params : context.params;
661
+ const segments = params.all || [];
662
+ if (segments.length === 2 && segments[0] === "oauth") {
663
+ const action = segments[1];
664
+ if (action === "status") {
665
+ return handlers.status(req);
666
+ }
667
+ if (action === "callback") {
668
+ const { searchParams } = new URL(req.url);
669
+ const code = searchParams.get("code");
670
+ const state = searchParams.get("state");
671
+ const error = searchParams.get("error");
672
+ const errorDescription = searchParams.get("error_description");
673
+ if (error) {
674
+ const errorMsg = errorDescription || error;
675
+ console.error("[OAuth Redirect] Error:", errorMsg);
676
+ return Response.redirect(new URL(`${errorRedirectUrl}?error=${encodeURIComponent(errorMsg)}`, req.url));
677
+ }
678
+ if (!code || !state) {
679
+ console.error("[OAuth Redirect] Missing code or state parameter");
680
+ return Response.redirect(new URL(`${errorRedirectUrl}?error=${encodeURIComponent("Invalid OAuth callback")}`, req.url));
681
+ }
682
+ let returnUrl = defaultRedirectUrl;
683
+ try {
684
+ const { parseState: parseState2 } = await Promise.resolve().then(() => exports_pkce);
685
+ const stateData = parseState2(state);
686
+ if (stateData.returnUrl) {
687
+ returnUrl = stateData.returnUrl;
688
+ }
689
+ } catch (e) {
690
+ try {
691
+ const referrer = req.headers?.get?.("referer") || req.headers?.get?.("referrer");
692
+ if (referrer) {
693
+ const referrerUrl = new URL(referrer);
694
+ const currentUrl = new URL(req.url);
695
+ if (referrerUrl.origin === currentUrl.origin) {
696
+ returnUrl = referrerUrl.pathname + referrerUrl.search;
697
+ }
698
+ }
699
+ } catch {}
700
+ }
701
+ const targetUrl = new URL(returnUrl, req.url);
702
+ targetUrl.hash = `oauth_callback=${encodeURIComponent(JSON.stringify({ code, state }))}`;
703
+ return Response.redirect(targetUrl);
704
+ }
705
+ return Response.json({ error: `Unknown action: ${action}` }, { status: 404 });
706
+ }
707
+ return Response.json({ error: `Invalid route: /${segments.join("/")}` }, { status: 404 });
708
+ }
709
+ };
710
+ }
711
+ };
712
+ return handlers;
713
+ }
714
+
715
+ // node.ts
716
+ function fromNodeHeaders(nodeHeaders) {
717
+ const webHeaders = new Headers;
718
+ for (const [key, value] of Object.entries(nodeHeaders)) {
719
+ if (value !== undefined) {
720
+ if (Array.isArray(value)) {
721
+ value.forEach((v) => webHeaders.append(key, v));
722
+ } else {
723
+ webHeaders.set(key, value);
724
+ }
725
+ }
726
+ }
727
+ return webHeaders;
728
+ }
729
+ async function toWebRequest(req) {
730
+ const protocol = req.socket.encrypted ? "https" : "http";
731
+ const host = req.headers.host || "localhost";
732
+ const url = `${protocol}://${host}${req.url}`;
733
+ const headers = fromNodeHeaders(req.headers);
734
+ let body;
735
+ if (req.method && ["POST", "PUT", "PATCH"].includes(req.method)) {
736
+ body = await new Promise((resolve, reject) => {
737
+ let data = "";
738
+ req.on("data", (chunk) => data += chunk);
739
+ req.on("end", () => resolve(data));
740
+ req.on("error", reject);
741
+ });
742
+ }
743
+ return new Request(url, {
744
+ method: req.method,
745
+ headers,
746
+ body: body || undefined
747
+ });
748
+ }
749
+ async function sendWebResponse(webRes, nodeRes) {
750
+ nodeRes.statusCode = webRes.status;
751
+ webRes.headers.forEach((value, key) => {
752
+ nodeRes.setHeader(key, value);
753
+ });
754
+ const body = await webRes.text();
755
+ nodeRes.end(body);
756
+ }
757
+ function toNodeHandler(config) {
758
+ const oauthHandler = new OAuthHandler(config);
759
+ return async (req, res) => {
760
+ try {
761
+ const webReq = await toWebRequest(req);
762
+ const url = new URL(webReq.url);
763
+ const segments = url.pathname.split("/").filter(Boolean);
764
+ const action = segments[segments.length - 1];
765
+ let webRes;
766
+ if (req.method === "POST") {
767
+ if (action === "authorize") {
768
+ const body = await webReq.json();
769
+ const result = await oauthHandler.handleAuthorize(body);
770
+ webRes = new Response(JSON.stringify(result), {
771
+ status: 200,
772
+ headers: { "Content-Type": "application/json" }
773
+ });
774
+ } else if (action === "callback") {
775
+ const body = await webReq.json();
776
+ const result = await oauthHandler.handleCallback(body);
777
+ webRes = new Response(JSON.stringify(result), {
778
+ status: 200,
779
+ headers: { "Content-Type": "application/json" }
780
+ });
781
+ } else if (action === "disconnect") {
782
+ const authHeader = webReq.headers.get("authorization");
783
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
784
+ webRes = new Response(JSON.stringify({ error: "Missing or invalid Authorization header" }), {
785
+ status: 400,
786
+ headers: { "Content-Type": "application/json" }
787
+ });
788
+ } else {
789
+ const accessToken = authHeader.substring(7);
790
+ const body = await webReq.json();
791
+ const { provider } = body;
792
+ if (!provider) {
793
+ webRes = new Response(JSON.stringify({ error: "Missing provider in request body" }), {
794
+ status: 400,
795
+ headers: { "Content-Type": "application/json" }
796
+ });
797
+ } else {
798
+ const result = await oauthHandler.handleDisconnect({ provider }, accessToken);
799
+ webRes = new Response(JSON.stringify(result), {
800
+ status: 200,
801
+ headers: { "Content-Type": "application/json" }
802
+ });
803
+ }
804
+ }
805
+ } else {
806
+ webRes = new Response(JSON.stringify({ error: `Unknown action: ${action}` }), {
807
+ status: 404,
808
+ headers: { "Content-Type": "application/json" }
809
+ });
810
+ }
811
+ } else if (req.method === "GET" && action === "status") {
812
+ const provider = url.searchParams.get("provider");
813
+ const authHeader = webReq.headers.get("authorization");
814
+ if (!provider) {
815
+ webRes = new Response(JSON.stringify({ error: "Missing provider query parameter" }), {
816
+ status: 400,
817
+ headers: { "Content-Type": "application/json" }
818
+ });
819
+ } else if (!authHeader || !authHeader.startsWith("Bearer ")) {
820
+ webRes = new Response(JSON.stringify({ error: "Missing or invalid Authorization header" }), {
821
+ status: 400,
822
+ headers: { "Content-Type": "application/json" }
823
+ });
824
+ } else {
825
+ const accessToken = authHeader.substring(7);
826
+ const result = await oauthHandler.handleStatus(provider, accessToken);
827
+ webRes = new Response(JSON.stringify(result), {
828
+ status: 200,
829
+ headers: { "Content-Type": "application/json" }
830
+ });
831
+ }
832
+ } else {
833
+ webRes = new Response(JSON.stringify({ error: `Unknown action: ${action}` }), {
834
+ status: 404,
835
+ headers: { "Content-Type": "application/json" }
836
+ });
837
+ }
838
+ await sendWebResponse(webRes, res);
839
+ } catch (error) {
840
+ console.error("[OAuth Handler] Error:", error);
841
+ const errorRes = new Response(JSON.stringify({ error: error.message || "Internal server error" }), {
842
+ status: 500,
843
+ headers: { "Content-Type": "application/json" }
844
+ });
845
+ await sendWebResponse(errorRes, res);
846
+ }
847
+ };
848
+ }
849
+
850
+ // ../protocol/jsonrpc.ts
851
+ function parseMessage(message) {
852
+ try {
853
+ return JSON.parse(message);
854
+ } catch (error) {
855
+ throw new Error(`Failed to parse JSON-RPC message: ${error}`);
856
+ }
857
+ }
858
+
859
+ // ../transport/http-session.ts
860
+ class HttpSessionTransport {
861
+ url;
862
+ headers;
863
+ timeout;
864
+ messageHandlers = new Set;
865
+ sessionId;
866
+ sseController;
867
+ connected = false;
868
+ constructor(options) {
869
+ this.url = options.url;
870
+ this.headers = options.headers || {};
871
+ this.timeout = options.timeout || 30000;
872
+ }
873
+ async connect() {
874
+ if (this.connected) {
875
+ return;
876
+ }
877
+ this.connected = true;
878
+ }
879
+ async sendRequest(method, params) {
880
+ if (!this.connected) {
881
+ throw new Error("Not connected to server");
882
+ }
883
+ const request = {
884
+ jsonrpc: "2.0",
885
+ id: Date.now() + Math.random(),
886
+ method,
887
+ params
888
+ };
889
+ const headers = {
890
+ ...this.headers,
891
+ "Content-Type": "application/json"
892
+ };
893
+ if (this.sessionId) {
894
+ headers["mcp-session-id"] = this.sessionId;
895
+ }
896
+ try {
897
+ const controller = new AbortController;
898
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
899
+ const response = await fetch(this.url, {
900
+ method: "POST",
901
+ headers,
902
+ body: JSON.stringify(request),
903
+ signal: controller.signal
904
+ });
905
+ clearTimeout(timeoutId);
906
+ if (!response.ok) {
907
+ const error = new Error(`Request failed: ${response.statusText}`);
908
+ error.statusCode = response.status;
909
+ throw error;
910
+ }
911
+ if (!this.sessionId) {
912
+ const sid = response.headers.get("mcp-session-id");
913
+ if (sid) {
914
+ this.sessionId = sid;
915
+ console.log("Session established:", sid);
916
+ this.startSSEListener();
917
+ }
918
+ }
919
+ const jsonResponse = await response.json();
920
+ if ("error" in jsonResponse) {
921
+ const error = new Error(`JSON-RPC Error ${jsonResponse.error.code}: ${jsonResponse.error.message}`);
922
+ error.code = jsonResponse.error.code;
923
+ if (jsonResponse.error.data) {
924
+ error.data = jsonResponse.error.data;
925
+ }
926
+ error.jsonrpcError = jsonResponse.error;
927
+ throw error;
928
+ }
929
+ return jsonResponse.result;
930
+ } catch (error) {
931
+ if (error instanceof Error) {
932
+ if (error.name === "AbortError") {
933
+ const timeoutError = new Error("Request timeout");
934
+ timeoutError.code = -32000;
935
+ throw timeoutError;
936
+ }
937
+ throw error;
938
+ }
939
+ throw new Error(String(error));
940
+ }
941
+ }
942
+ async startSSEListener() {
943
+ if (!this.sessionId || this.sseController) {
944
+ return;
945
+ }
946
+ this.sseController = new AbortController;
947
+ try {
948
+ const response = await fetch(this.url, {
949
+ method: "GET",
950
+ headers: {
951
+ ...this.headers,
952
+ Accept: "text/event-stream",
953
+ "mcp-session-id": this.sessionId
954
+ },
955
+ signal: this.sseController.signal
956
+ });
957
+ if (!response.ok || !response.body) {
958
+ return;
959
+ }
960
+ this.processSSEStream(response.body);
961
+ } catch (error) {
962
+ if (error instanceof Error && error.name === "AbortError") {
963
+ return;
964
+ }
965
+ console.error("SSE connection error:", error);
966
+ }
967
+ }
968
+ async processSSEStream(body) {
969
+ const reader = body.getReader();
970
+ const decoder = new TextDecoder;
971
+ let buffer = "";
972
+ try {
973
+ while (true) {
974
+ const { done, value } = await reader.read();
975
+ if (done)
976
+ break;
977
+ buffer += decoder.decode(value, { stream: true });
978
+ const lines = buffer.split(`
979
+ `);
980
+ buffer = lines.pop() || "";
981
+ for (const line of lines) {
982
+ if (line.startsWith("data: ")) {
983
+ const data = line.slice(6).trim();
984
+ if (data) {
985
+ this.handleNotification(data);
986
+ }
987
+ }
988
+ }
989
+ }
990
+ } catch (error) {
991
+ if (error instanceof Error && error.name === "AbortError") {
992
+ return;
993
+ }
994
+ console.error("SSE stream error:", error);
995
+ } finally {
996
+ reader.releaseLock();
997
+ }
998
+ }
999
+ handleNotification(data) {
1000
+ try {
1001
+ const message = parseMessage(data);
1002
+ this.messageHandlers.forEach((handler) => {
1003
+ try {
1004
+ handler(message);
1005
+ } catch (error) {
1006
+ console.error("Error in message handler:", error);
1007
+ }
1008
+ });
1009
+ } catch (error) {
1010
+ console.error("Failed to parse notification:", error);
1011
+ }
1012
+ }
1013
+ onMessage(handler) {
1014
+ this.messageHandlers.add(handler);
1015
+ return () => {
1016
+ this.messageHandlers.delete(handler);
1017
+ };
1018
+ }
1019
+ async disconnect() {
1020
+ if (!this.connected) {
1021
+ return;
1022
+ }
1023
+ if (this.sseController) {
1024
+ this.sseController.abort();
1025
+ this.sseController = undefined;
1026
+ }
1027
+ this.messageHandlers.clear();
1028
+ this.sessionId = undefined;
1029
+ this.connected = false;
1030
+ }
1031
+ isConnected() {
1032
+ return this.connected;
1033
+ }
1034
+ getSessionId() {
1035
+ return this.sessionId;
1036
+ }
1037
+ setHeader(key, value) {
1038
+ this.headers[key] = value;
1039
+ }
1040
+ removeHeader(key) {
1041
+ delete this.headers[key];
1042
+ }
1043
+ getHeaders() {
1044
+ return { ...this.headers };
1045
+ }
1046
+ }
1047
+
1048
+ // ../client.ts
1049
+ init_errors();
1050
+
1051
+ // ../utils/naming.ts
1052
+ function camelToSnake(str) {
1053
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
1054
+ }
1055
+ function methodToToolName(methodName, integrationId) {
1056
+ const snakeCaseMethod = camelToSnake(methodName);
1057
+ return `${integrationId}_${snakeCaseMethod}`;
1058
+ }
1059
+ // ../oauth/window-manager.ts
1060
+ function isBrowser() {
1061
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
1062
+ }
1063
+
1064
+ class OAuthWindowManager {
1065
+ popupWindow = null;
1066
+ popupCheckInterval = null;
1067
+ popupCheckTimeout = null;
1068
+ openPopup(url, options) {
1069
+ if (!isBrowser()) {
1070
+ throw new Error("OAuthWindowManager.openPopup() can only be used in browser environments");
1071
+ }
1072
+ const width = options?.width || 600;
1073
+ const height = options?.height || 700;
1074
+ const left = window.screenX + (window.outerWidth - width) / 2;
1075
+ const top = window.screenY + (window.outerHeight - height) / 2;
1076
+ const features = [
1077
+ `popup=yes`,
1078
+ `width=${width}`,
1079
+ `height=${height}`,
1080
+ `left=${left}`,
1081
+ `top=${top}`,
1082
+ "toolbar=no",
1083
+ "location=no",
1084
+ "directories=no",
1085
+ "status=no",
1086
+ "menubar=no",
1087
+ "scrollbars=yes",
1088
+ "resizable=yes",
1089
+ "copyhistory=no",
1090
+ "noopener=no"
1091
+ ].join(",");
1092
+ const windowName = `oauth_popup_${Date.now()}`;
1093
+ this.popupWindow = window.open(url, windowName, features);
1094
+ if (!this.popupWindow) {
1095
+ console.warn("Popup was blocked by the browser. Please allow popups for this site.");
1096
+ return null;
1097
+ }
1098
+ this.popupWindow.focus();
1099
+ return this.popupWindow;
1100
+ }
1101
+ openRedirect(url) {
1102
+ if (!isBrowser()) {
1103
+ throw new Error("OAuthWindowManager.openRedirect() can only be used in browser environments");
1104
+ }
1105
+ window.location.href = url;
1106
+ }
1107
+ listenForCallback(mode, timeoutMs = 5 * 60 * 1000) {
1108
+ if (mode === "popup") {
1109
+ return this.listenForPopupCallback(timeoutMs);
1110
+ } else {
1111
+ return this.listenForRedirectCallback();
1112
+ }
1113
+ }
1114
+ listenForPopupCallback(timeoutMs) {
1115
+ if (!isBrowser()) {
1116
+ return Promise.reject(new Error("OAuth popup callback can only be used in browser environments"));
1117
+ }
1118
+ return new Promise((resolve, reject) => {
1119
+ const timeout = setTimeout(() => {
1120
+ this.cleanup();
1121
+ reject(new Error("OAuth authorization timed out"));
1122
+ }, timeoutMs);
1123
+ const messageHandler = (event) => {
1124
+ if (event.data && event.data.type === "oauth_callback") {
1125
+ clearTimeout(timeout);
1126
+ if (this.popupCheckTimeout) {
1127
+ clearTimeout(this.popupCheckTimeout);
1128
+ this.popupCheckTimeout = null;
1129
+ }
1130
+ window.removeEventListener("message", messageHandler);
1131
+ const { code, state, error } = event.data;
1132
+ if (error) {
1133
+ this.cleanup();
1134
+ reject(new Error(`OAuth error: ${error}`));
1135
+ return;
1136
+ }
1137
+ if (!code || !state) {
1138
+ this.cleanup();
1139
+ reject(new Error("Invalid OAuth callback: missing code or state"));
1140
+ return;
1141
+ }
1142
+ this.cleanup();
1143
+ resolve({ code, state });
1144
+ }
1145
+ };
1146
+ window.addEventListener("message", messageHandler);
1147
+ this.popupCheckTimeout = setTimeout(() => {
1148
+ this.popupCheckTimeout = null;
1149
+ this.popupCheckInterval = setInterval(() => {
1150
+ if (this.popupWindow?.closed) {
1151
+ clearTimeout(timeout);
1152
+ clearInterval(this.popupCheckInterval);
1153
+ window.removeEventListener("message", messageHandler);
1154
+ this.cleanup();
1155
+ reject(new Error("OAuth popup was closed by user"));
1156
+ }
1157
+ }, 500);
1158
+ }, 2000);
1159
+ });
1160
+ }
1161
+ listenForRedirectCallback() {
1162
+ if (!isBrowser()) {
1163
+ return Promise.reject(new Error("OAuth redirect callback can only be used in browser environments"));
1164
+ }
1165
+ return new Promise((resolve, reject) => {
1166
+ const params = new URLSearchParams(window.location.search);
1167
+ let code = params.get("code");
1168
+ let state = params.get("state");
1169
+ let error = params.get("error");
1170
+ let errorDescription = params.get("error_description");
1171
+ if (!code && !error && window.location.hash) {
1172
+ try {
1173
+ const hash = window.location.hash.substring(1);
1174
+ const hashParams = new URLSearchParams(hash);
1175
+ const oauthCallback = hashParams.get("oauth_callback");
1176
+ if (oauthCallback) {
1177
+ const parsed = JSON.parse(decodeURIComponent(oauthCallback));
1178
+ code = parsed.code;
1179
+ state = parsed.state;
1180
+ window.history.replaceState(null, "", window.location.pathname + window.location.search);
1181
+ }
1182
+ } catch (e) {
1183
+ console.error("Failed to parse OAuth callback params from hash:", e);
1184
+ }
1185
+ }
1186
+ if (!code && !error) {
1187
+ try {
1188
+ const stored = sessionStorage.getItem("oauth_callback_params");
1189
+ if (stored) {
1190
+ const parsed = JSON.parse(stored);
1191
+ code = parsed.code;
1192
+ state = parsed.state;
1193
+ sessionStorage.removeItem("oauth_callback_params");
1194
+ }
1195
+ } catch (e) {
1196
+ console.error("Failed to parse OAuth callback params from sessionStorage:", e);
1197
+ }
1198
+ }
1199
+ if (error) {
1200
+ const errorMsg = errorDescription || error;
1201
+ reject(new Error(`OAuth error: ${errorMsg}`));
1202
+ return;
1203
+ }
1204
+ if (!code || !state) {
1205
+ reject(new Error("Invalid OAuth callback: missing code or state in URL"));
1206
+ return;
1207
+ }
1208
+ resolve({ code, state });
1209
+ });
1210
+ }
1211
+ cleanup() {
1212
+ if (this.popupWindow && !this.popupWindow.closed) {
1213
+ this.popupWindow.close();
1214
+ }
1215
+ this.popupWindow = null;
1216
+ if (this.popupCheckInterval) {
1217
+ clearInterval(this.popupCheckInterval);
1218
+ this.popupCheckInterval = null;
1219
+ }
1220
+ if (this.popupCheckTimeout) {
1221
+ clearTimeout(this.popupCheckTimeout);
1222
+ this.popupCheckTimeout = null;
1223
+ }
1224
+ }
1225
+ close() {
1226
+ this.cleanup();
1227
+ }
1228
+ }
1229
+
1230
+ // ../oauth/manager.ts
1231
+ class OAuthManager {
1232
+ pendingAuths = new Map;
1233
+ providerTokens = new Map;
1234
+ windowManager;
1235
+ flowConfig;
1236
+ oauthApiBase;
1237
+ constructor(oauthApiBase, flowConfig) {
1238
+ this.oauthApiBase = oauthApiBase;
1239
+ this.windowManager = new OAuthWindowManager;
1240
+ this.flowConfig = {
1241
+ mode: flowConfig?.mode || "redirect",
1242
+ popupOptions: flowConfig?.popupOptions,
1243
+ onAuthCallback: flowConfig?.onAuthCallback
1244
+ };
1245
+ this.cleanupExpiredPendingAuths();
1246
+ }
1247
+ async initiateFlow(provider, config, returnUrl) {
1248
+ const codeVerifier = generateCodeVerifier();
1249
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
1250
+ const state = generateStateWithReturnUrl(returnUrl);
1251
+ const pendingAuth = {
1252
+ provider,
1253
+ state,
1254
+ codeVerifier,
1255
+ codeChallenge,
1256
+ scopes: config.scopes,
1257
+ redirectUri: config.redirectUri,
1258
+ returnUrl,
1259
+ initiatedAt: Date.now()
1260
+ };
1261
+ this.pendingAuths.set(state, pendingAuth);
1262
+ this.savePendingAuthToStorage(state, pendingAuth);
1263
+ const authUrl = await this.getAuthorizationUrl(provider, config.scopes, state, codeChallenge, config.redirectUri);
1264
+ if (this.flowConfig.mode === "popup") {
1265
+ this.windowManager.openPopup(authUrl, this.flowConfig.popupOptions);
1266
+ try {
1267
+ const callbackParams = await this.windowManager.listenForCallback("popup");
1268
+ await this.handleCallback(callbackParams.code, callbackParams.state);
1269
+ } catch (error) {
1270
+ this.pendingAuths.delete(state);
1271
+ throw error;
1272
+ }
1273
+ } else {
1274
+ this.windowManager.openRedirect(authUrl);
1275
+ }
1276
+ }
1277
+ async handleCallback(code, state) {
1278
+ let pendingAuth = this.pendingAuths.get(state);
1279
+ if (!pendingAuth) {
1280
+ pendingAuth = this.loadPendingAuthFromStorage(state);
1281
+ }
1282
+ if (!pendingAuth) {
1283
+ throw new Error("Invalid state parameter: no matching OAuth flow found");
1284
+ }
1285
+ const fiveMinutes = 5 * 60 * 1000;
1286
+ if (Date.now() - pendingAuth.initiatedAt > fiveMinutes) {
1287
+ this.pendingAuths.delete(state);
1288
+ this.removePendingAuthFromStorage(state);
1289
+ throw new Error("OAuth flow expired: please try again");
1290
+ }
1291
+ if (this.flowConfig.onAuthCallback) {
1292
+ try {
1293
+ await this.flowConfig.onAuthCallback(pendingAuth.provider, code, state);
1294
+ } catch (error) {
1295
+ console.error("Custom OAuth callback handler failed:", error);
1296
+ }
1297
+ }
1298
+ try {
1299
+ const response = await this.exchangeCodeForToken(pendingAuth.provider, code, pendingAuth.codeVerifier, state);
1300
+ const tokenData = {
1301
+ accessToken: response.accessToken,
1302
+ refreshToken: response.refreshToken,
1303
+ tokenType: response.tokenType,
1304
+ expiresIn: response.expiresIn,
1305
+ expiresAt: response.expiresAt,
1306
+ scopes: response.scopes
1307
+ };
1308
+ this.providerTokens.set(pendingAuth.provider, tokenData);
1309
+ this.saveProviderToken(pendingAuth.provider, tokenData);
1310
+ this.pendingAuths.delete(state);
1311
+ this.removePendingAuthFromStorage(state);
1312
+ return { ...tokenData, provider: pendingAuth.provider };
1313
+ } catch (error) {
1314
+ this.pendingAuths.delete(state);
1315
+ this.removePendingAuthFromStorage(state);
1316
+ throw error;
1317
+ }
1318
+ }
1319
+ async checkAuthStatus(provider) {
1320
+ const tokenData = this.providerTokens.get(provider);
1321
+ if (!tokenData) {
1322
+ return {
1323
+ authorized: false,
1324
+ provider
1325
+ };
1326
+ }
1327
+ return {
1328
+ authorized: true,
1329
+ provider,
1330
+ scopes: tokenData.scopes,
1331
+ expiresAt: tokenData.expiresAt
1332
+ };
1333
+ }
1334
+ async disconnectProvider(provider) {
1335
+ const tokenData = this.providerTokens.get(provider);
1336
+ if (!tokenData) {
1337
+ throw new Error(`No access token available for provider "${provider}". Cannot disconnect provider.`);
1338
+ }
1339
+ this.providerTokens.delete(provider);
1340
+ this.clearProviderToken(provider);
1341
+ }
1342
+ getProviderToken(provider) {
1343
+ return this.providerTokens.get(provider);
1344
+ }
1345
+ getAllProviderTokens() {
1346
+ return new Map(this.providerTokens);
1347
+ }
1348
+ setProviderToken(provider, tokenData) {
1349
+ this.providerTokens.set(provider, tokenData);
1350
+ this.saveProviderToken(provider, tokenData);
1351
+ }
1352
+ clearProviderToken(provider) {
1353
+ this.providerTokens.delete(provider);
1354
+ if (typeof window !== "undefined" && window.localStorage) {
1355
+ try {
1356
+ window.localStorage.removeItem(`integrate_token_${provider}`);
1357
+ } catch (error) {
1358
+ console.error(`Failed to clear token for ${provider} from localStorage:`, error);
1359
+ }
1360
+ }
1361
+ }
1362
+ clearAllProviderTokens() {
1363
+ const providers = Array.from(this.providerTokens.keys());
1364
+ this.providerTokens.clear();
1365
+ if (typeof window !== "undefined" && window.localStorage) {
1366
+ for (const provider of providers) {
1367
+ try {
1368
+ window.localStorage.removeItem(`integrate_token_${provider}`);
1369
+ } catch (error) {
1370
+ console.error(`Failed to clear token for ${provider} from localStorage:`, error);
1371
+ }
1372
+ }
1373
+ }
1374
+ }
1375
+ clearAllPendingAuths() {
1376
+ this.pendingAuths.clear();
1377
+ if (typeof window !== "undefined" && window.localStorage) {
1378
+ try {
1379
+ const prefix = "integrate_oauth_pending_";
1380
+ const keysToRemove = [];
1381
+ for (let i = 0;i < window.localStorage.length; i++) {
1382
+ const key = window.localStorage.key(i);
1383
+ if (key && key.startsWith(prefix)) {
1384
+ keysToRemove.push(key);
1385
+ }
1386
+ }
1387
+ keysToRemove.forEach((key) => window.localStorage.removeItem(key));
1388
+ } catch (error) {
1389
+ console.error("Failed to clear pending auths from localStorage:", error);
1390
+ }
1391
+ }
1392
+ }
1393
+ saveProviderToken(provider, tokenData) {
1394
+ if (typeof window !== "undefined" && window.localStorage) {
1395
+ try {
1396
+ const key = `integrate_token_${provider}`;
1397
+ window.localStorage.setItem(key, JSON.stringify(tokenData));
1398
+ } catch (error) {
1399
+ console.error(`Failed to save token for ${provider} to localStorage:`, error);
1400
+ }
1401
+ }
1402
+ }
1403
+ loadProviderToken(provider) {
1404
+ if (typeof window !== "undefined" && window.localStorage) {
1405
+ try {
1406
+ const key = `integrate_token_${provider}`;
1407
+ const stored = window.localStorage.getItem(key);
1408
+ if (stored) {
1409
+ return JSON.parse(stored);
1410
+ }
1411
+ } catch (error) {
1412
+ console.error(`Failed to load token for ${provider} from localStorage:`, error);
1413
+ }
1414
+ }
1415
+ return;
1416
+ }
1417
+ loadAllProviderTokens(providers) {
1418
+ for (const provider of providers) {
1419
+ const tokenData = this.loadProviderToken(provider);
1420
+ if (tokenData) {
1421
+ this.providerTokens.set(provider, tokenData);
1422
+ }
1423
+ }
1424
+ }
1425
+ savePendingAuthToStorage(state, pendingAuth) {
1426
+ if (typeof window !== "undefined" && window.localStorage) {
1427
+ try {
1428
+ const key = `integrate_oauth_pending_${state}`;
1429
+ window.localStorage.setItem(key, JSON.stringify(pendingAuth));
1430
+ } catch (error) {
1431
+ console.error("Failed to save pending auth to localStorage:", error);
1432
+ }
1433
+ }
1434
+ }
1435
+ loadPendingAuthFromStorage(state) {
1436
+ if (typeof window !== "undefined" && window.localStorage) {
1437
+ try {
1438
+ const key = `integrate_oauth_pending_${state}`;
1439
+ const stored = window.localStorage.getItem(key);
1440
+ if (stored) {
1441
+ return JSON.parse(stored);
1442
+ }
1443
+ } catch (error) {
1444
+ console.error("Failed to load pending auth from localStorage:", error);
1445
+ }
1446
+ }
1447
+ return;
1448
+ }
1449
+ removePendingAuthFromStorage(state) {
1450
+ if (typeof window !== "undefined" && window.localStorage) {
1451
+ try {
1452
+ const key = `integrate_oauth_pending_${state}`;
1453
+ window.localStorage.removeItem(key);
1454
+ } catch (error) {
1455
+ console.error("Failed to remove pending auth from localStorage:", error);
1456
+ }
1457
+ }
1458
+ }
1459
+ cleanupExpiredPendingAuths() {
1460
+ if (typeof window !== "undefined" && window.localStorage) {
1461
+ try {
1462
+ const prefix = "integrate_oauth_pending_";
1463
+ const fiveMinutes = 5 * 60 * 1000;
1464
+ const now = Date.now();
1465
+ const keysToRemove = [];
1466
+ for (let i = 0;i < window.localStorage.length; i++) {
1467
+ const key = window.localStorage.key(i);
1468
+ if (key && key.startsWith(prefix)) {
1469
+ try {
1470
+ const stored = window.localStorage.getItem(key);
1471
+ if (stored) {
1472
+ const pendingAuth = JSON.parse(stored);
1473
+ if (now - pendingAuth.initiatedAt > fiveMinutes) {
1474
+ keysToRemove.push(key);
1475
+ }
1476
+ }
1477
+ } catch (error) {
1478
+ keysToRemove.push(key);
1479
+ }
1480
+ }
1481
+ }
1482
+ keysToRemove.forEach((key) => window.localStorage.removeItem(key));
1483
+ } catch (error) {
1484
+ console.error("Failed to cleanup expired pending auths:", error);
1485
+ }
1486
+ }
1487
+ }
1488
+ async getAuthorizationUrl(provider, scopes, state, codeChallenge, redirectUri) {
1489
+ const url = `${this.oauthApiBase}/authorize`;
1490
+ const response = await fetch(url, {
1491
+ method: "POST",
1492
+ headers: {
1493
+ "Content-Type": "application/json"
1494
+ },
1495
+ body: JSON.stringify({
1496
+ provider,
1497
+ scopes,
1498
+ state,
1499
+ codeChallenge,
1500
+ codeChallengeMethod: "S256",
1501
+ redirectUri
1502
+ })
1503
+ });
1504
+ if (!response.ok) {
1505
+ const error = await response.text();
1506
+ throw new Error(`Failed to get authorization URL: ${error}`);
1507
+ }
1508
+ const data = await response.json();
1509
+ return data.authorizationUrl;
1510
+ }
1511
+ async exchangeCodeForToken(provider, code, codeVerifier, state) {
1512
+ const url = `${this.oauthApiBase}/callback`;
1513
+ const response = await fetch(url, {
1514
+ method: "POST",
1515
+ headers: {
1516
+ "Content-Type": "application/json"
1517
+ },
1518
+ body: JSON.stringify({
1519
+ provider,
1520
+ code,
1521
+ codeVerifier,
1522
+ state
1523
+ })
1524
+ });
1525
+ if (!response.ok) {
1526
+ const error = await response.text();
1527
+ throw new Error(`Failed to exchange code for token: ${error}`);
1528
+ }
1529
+ const data = await response.json();
1530
+ return data;
1531
+ }
1532
+ close() {
1533
+ this.windowManager.close();
1534
+ }
1535
+ }
1536
+
1537
+ // ../client.ts
1538
+ class SimpleEventEmitter {
1539
+ handlers = new Map;
1540
+ on(event, handler) {
1541
+ if (!this.handlers.has(event)) {
1542
+ this.handlers.set(event, new Set);
1543
+ }
1544
+ this.handlers.get(event).add(handler);
1545
+ }
1546
+ off(event, handler) {
1547
+ const handlers = this.handlers.get(event);
1548
+ if (handlers) {
1549
+ handlers.delete(handler);
1550
+ }
1551
+ }
1552
+ emit(event, payload) {
1553
+ const handlers = this.handlers.get(event);
1554
+ if (handlers) {
1555
+ handlers.forEach((handler) => {
1556
+ try {
1557
+ handler(payload);
1558
+ } catch (error) {
1559
+ console.error(`Error in event handler for ${event}:`, error);
1560
+ }
1561
+ });
1562
+ }
1563
+ }
1564
+ removeAllListeners(event) {
1565
+ if (event) {
1566
+ this.handlers.delete(event);
1567
+ } else {
1568
+ this.handlers.clear();
1569
+ }
1570
+ }
1571
+ }
1572
+ var MCP_SERVER_URL2 = "https://mcp.integrate.dev/api/v1/mcp";
1573
+ var clientCache = new Map;
1574
+ var cleanupClients = new Set;
1575
+ class MCPClient {
1576
+ transport;
1577
+ integrations;
1578
+ availableTools = new Map;
1579
+ enabledToolNames = new Set;
1580
+ initialized = false;
1581
+ clientInfo;
1582
+ onReauthRequired;
1583
+ maxReauthRetries;
1584
+ authState = new Map;
1585
+ oauthManager;
1586
+ eventEmitter = new SimpleEventEmitter;
1587
+ apiRouteBase;
1588
+ github;
1589
+ gmail;
1590
+ server;
1591
+ constructor(config) {
1592
+ this.transport = new HttpSessionTransport({
1593
+ url: config.serverUrl || MCP_SERVER_URL2,
1594
+ headers: config.headers,
1595
+ timeout: config.timeout
1596
+ });
1597
+ const oauthApiBase = config.oauthApiBase || "/api/integrate/oauth";
1598
+ const defaultRedirectUri = this.getDefaultRedirectUri(oauthApiBase);
1599
+ this.apiRouteBase = config.apiRouteBase || "/api/integrate";
1600
+ this.integrations = config.integrations.map((integration) => {
1601
+ if (integration.oauth && !integration.oauth.redirectUri) {
1602
+ return {
1603
+ ...integration,
1604
+ oauth: {
1605
+ ...integration.oauth,
1606
+ redirectUri: defaultRedirectUri
1607
+ }
1608
+ };
1609
+ }
1610
+ return integration;
1611
+ });
1612
+ this.clientInfo = config.clientInfo || {
1613
+ name: "integrate-sdk",
1614
+ version: "0.1.0"
1615
+ };
1616
+ this.onReauthRequired = config.onReauthRequired;
1617
+ this.maxReauthRetries = config.maxReauthRetries ?? 1;
1618
+ this.oauthManager = new OAuthManager(oauthApiBase, config.oauthFlow);
1619
+ const providers = this.integrations.filter((p) => p.oauth).map((p) => p.oauth.provider);
1620
+ this.oauthManager.loadAllProviderTokens(providers);
1621
+ for (const integration of this.integrations) {
1622
+ for (const toolName of integration.tools) {
1623
+ this.enabledToolNames.add(toolName);
1624
+ }
1625
+ if (integration.oauth) {
1626
+ const hasToken = this.oauthManager.getProviderToken(integration.oauth.provider) !== undefined;
1627
+ this.authState.set(integration.oauth.provider, { authenticated: hasToken });
1628
+ }
1629
+ }
1630
+ this.github = this.createIntegrationProxy("github");
1631
+ this.gmail = this.createIntegrationProxy("gmail");
1632
+ this.server = this.createServerProxy();
1633
+ this.initializeIntegrations();
1634
+ }
1635
+ getDefaultRedirectUri(oauthApiBase) {
1636
+ if (typeof window === "undefined" || !window.location) {
1637
+ return "http://localhost:3000/api/integrate/oauth/callback";
1638
+ }
1639
+ const origin = window.location.origin;
1640
+ const normalizedPath = oauthApiBase.replace(/\/$/, "");
1641
+ return `${origin}${normalizedPath}/callback`;
1642
+ }
1643
+ createIntegrationProxy(integrationId) {
1644
+ return new Proxy({}, {
1645
+ get: (_target, methodName) => {
1646
+ return async (args) => {
1647
+ const toolName = methodToToolName(methodName, integrationId);
1648
+ return await this.callToolWithRetry(toolName, args, 0);
1649
+ };
1650
+ }
1651
+ });
1652
+ }
1653
+ createServerProxy() {
1654
+ return new Proxy({}, {
1655
+ get: (_target, methodName) => {
1656
+ return async (args) => {
1657
+ const toolName = methodToToolName(methodName, "");
1658
+ const finalToolName = toolName.startsWith("_") ? toolName.substring(1) : toolName;
1659
+ return await this.callServerToolInternal(finalToolName, args);
1660
+ };
1661
+ }
1662
+ });
1663
+ }
1664
+ async callServerToolInternal(name, args) {
1665
+ try {
1666
+ const response = await this.callToolThroughHandler(name, args);
1667
+ return response;
1668
+ } catch (error) {
1669
+ const parsedError = parseServerError(error, { toolName: name });
1670
+ throw parsedError;
1671
+ }
1672
+ }
1673
+ async initializeIntegrations() {
1674
+ for (const integration of this.integrations) {
1675
+ if (integration.onInit) {
1676
+ await integration.onInit(this);
1677
+ }
1678
+ }
1679
+ }
1680
+ async connect() {
1681
+ for (const integration of this.integrations) {
1682
+ if (integration.onBeforeConnect) {
1683
+ await integration.onBeforeConnect(this);
1684
+ }
1685
+ }
1686
+ await this.transport.connect();
1687
+ await this.initialize();
1688
+ await this.discoverTools();
1689
+ for (const integration of this.integrations) {
1690
+ if (integration.onAfterConnect) {
1691
+ await integration.onAfterConnect(this);
1692
+ }
1693
+ }
1694
+ }
1695
+ async initialize() {
1696
+ const params = {
1697
+ protocolVersion: "2024-11-05",
1698
+ capabilities: {
1699
+ tools: {}
1700
+ },
1701
+ clientInfo: this.clientInfo
1702
+ };
1703
+ const response = await this.transport.sendRequest("initialize" /* INITIALIZE */, params);
1704
+ this.initialized = true;
1705
+ return response;
1706
+ }
1707
+ async discoverTools() {
1708
+ const response = await this.transport.sendRequest("tools/list" /* TOOLS_LIST */);
1709
+ for (const tool of response.tools) {
1710
+ this.availableTools.set(tool.name, tool);
1711
+ }
1712
+ const enabledTools = response.tools.filter((tool) => this.enabledToolNames.has(tool.name));
1713
+ console.log(`Discovered ${response.tools.length} tools, ${enabledTools.length} enabled by integrations`);
1714
+ }
1715
+ async _callToolByName(name, args) {
1716
+ return await this.callToolWithRetry(name, args, 0);
1717
+ }
1718
+ async callServerTool(name, args) {
1719
+ try {
1720
+ const response = await this.callToolThroughHandler(name, args);
1721
+ return response;
1722
+ } catch (error) {
1723
+ const parsedError = parseServerError(error, { toolName: name });
1724
+ throw parsedError;
1725
+ }
1726
+ }
1727
+ async callToolThroughHandler(name, args, provider) {
1728
+ const transportHeaders = this.transport.headers || {};
1729
+ const hasApiKey = !!transportHeaders["X-API-KEY"];
1730
+ if (hasApiKey) {
1731
+ if (provider) {
1732
+ const tokenData = this.oauthManager.getProviderToken(provider);
1733
+ if (tokenData && this.transport.setHeader) {
1734
+ const previousAuthHeader = transportHeaders["Authorization"];
1735
+ try {
1736
+ this.transport.setHeader("Authorization", `Bearer ${tokenData.accessToken}`);
1737
+ const result3 = await this.transport.sendRequest("tools/call", {
1738
+ name,
1739
+ arguments: args || {}
1740
+ });
1741
+ return result3;
1742
+ } finally {
1743
+ if (previousAuthHeader && this.transport.setHeader) {
1744
+ this.transport.setHeader("Authorization", previousAuthHeader);
1745
+ } else if (this.transport.removeHeader) {
1746
+ this.transport.removeHeader("Authorization");
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ const result2 = await this.transport.sendRequest("tools/call", {
1752
+ name,
1753
+ arguments: args || {}
1754
+ });
1755
+ return result2;
1756
+ }
1757
+ const url = `${this.apiRouteBase}/mcp`;
1758
+ const headers = {
1759
+ "Content-Type": "application/json"
1760
+ };
1761
+ if (provider) {
1762
+ const tokenData = this.oauthManager.getProviderToken(provider);
1763
+ if (tokenData) {
1764
+ headers["Authorization"] = `Bearer ${tokenData.accessToken}`;
1765
+ }
1766
+ }
1767
+ const response = await fetch(url, {
1768
+ method: "POST",
1769
+ headers,
1770
+ body: JSON.stringify({
1771
+ name,
1772
+ arguments: args
1773
+ })
1774
+ });
1775
+ if (!response.ok) {
1776
+ let errorMessage = `Request failed: ${response.statusText}`;
1777
+ const error = new Error(errorMessage);
1778
+ error.statusCode = response.status;
1779
+ try {
1780
+ const errorData = await response.json();
1781
+ if (errorData.error) {
1782
+ errorMessage = typeof errorData.error === "string" ? errorData.error : errorData.error.message || errorMessage;
1783
+ error.message = errorMessage;
1784
+ }
1785
+ if (errorData.code) {
1786
+ error.code = errorData.code;
1787
+ }
1788
+ if (errorData.data) {
1789
+ error.data = errorData.data;
1790
+ }
1791
+ if (errorData.error && typeof errorData.error === "object") {
1792
+ error.jsonrpcError = errorData.error;
1793
+ }
1794
+ } catch {}
1795
+ throw error;
1796
+ }
1797
+ const result = await response.json();
1798
+ return result;
1799
+ }
1800
+ async callToolWithRetry(name, args, retryCount = 0) {
1801
+ if (!this.enabledToolNames.has(name)) {
1802
+ throw new Error(`Tool "${name}" is not enabled. Enable it by adding the appropriate integration.`);
1803
+ }
1804
+ const provider = this.getProviderForTool(name);
1805
+ try {
1806
+ const response = await this.callToolThroughHandler(name, args, provider);
1807
+ if (provider) {
1808
+ this.authState.set(provider, { authenticated: true });
1809
+ }
1810
+ return response;
1811
+ } catch (error) {
1812
+ const parsedError = parseServerError(error, { toolName: name, provider });
1813
+ if (isAuthError(parsedError) && retryCount < this.maxReauthRetries) {
1814
+ if (provider) {
1815
+ this.authState.set(provider, {
1816
+ authenticated: false,
1817
+ lastError: parsedError
1818
+ });
1819
+ }
1820
+ if (this.onReauthRequired && provider) {
1821
+ const reauthSuccess = await this.onReauthRequired({
1822
+ provider,
1823
+ error: parsedError,
1824
+ toolName: name
1825
+ });
1826
+ if (reauthSuccess) {
1827
+ return await this.callToolWithRetry(name, args, retryCount + 1);
1828
+ }
1829
+ }
1830
+ }
1831
+ throw parsedError;
1832
+ }
1833
+ }
1834
+ getProviderForTool(toolName) {
1835
+ for (const integration of this.integrations) {
1836
+ if (integration.tools.includes(toolName) && integration.oauth) {
1837
+ return integration.oauth.provider;
1838
+ }
1839
+ }
1840
+ return;
1841
+ }
1842
+ getTool(name) {
1843
+ return this.availableTools.get(name);
1844
+ }
1845
+ getAvailableTools() {
1846
+ return Array.from(this.availableTools.values());
1847
+ }
1848
+ setRequestHeader(key, value) {
1849
+ this.transport.setHeader(key, value);
1850
+ }
1851
+ getEnabledTools() {
1852
+ return Array.from(this.availableTools.values()).filter((tool) => this.enabledToolNames.has(tool.name));
1853
+ }
1854
+ getOAuthConfig(integrationId) {
1855
+ const integration = this.integrations.find((p) => p.id === integrationId);
1856
+ return integration?.oauth;
1857
+ }
1858
+ getAllOAuthConfigs() {
1859
+ const configs = new Map;
1860
+ for (const integration of this.integrations) {
1861
+ if (integration.oauth) {
1862
+ configs.set(integration.id, integration.oauth);
1863
+ }
1864
+ }
1865
+ return configs;
1866
+ }
1867
+ onMessage(handler) {
1868
+ return this.transport.onMessage(handler);
1869
+ }
1870
+ on(event, handler) {
1871
+ this.eventEmitter.on(event, handler);
1872
+ }
1873
+ off(event, handler) {
1874
+ this.eventEmitter.off(event, handler);
1875
+ }
1876
+ clearSessionToken() {
1877
+ this.oauthManager.clearAllProviderTokens();
1878
+ }
1879
+ async disconnectProvider(provider) {
1880
+ const integration = this.integrations.find((p) => p.oauth?.provider === provider);
1881
+ if (!integration?.oauth) {
1882
+ throw new Error(`No OAuth configuration found for provider: ${provider}`);
1883
+ }
1884
+ try {
1885
+ await this.oauthManager.disconnectProvider(provider);
1886
+ this.authState.set(provider, { authenticated: false });
1887
+ this.eventEmitter.emit("auth:disconnect", { provider });
1888
+ } catch (error) {
1889
+ this.eventEmitter.emit("auth:error", {
1890
+ provider,
1891
+ error
1892
+ });
1893
+ throw error;
1894
+ }
1895
+ }
1896
+ async logout() {
1897
+ this.clearSessionToken();
1898
+ this.oauthManager.clearAllPendingAuths();
1899
+ this.authState.clear();
1900
+ for (const integration of this.integrations) {
1901
+ if (integration.oauth) {
1902
+ this.authState.set(integration.oauth.provider, { authenticated: false });
1903
+ }
1904
+ }
1905
+ this.eventEmitter.emit("auth:logout", {});
1906
+ }
1907
+ async disconnect() {
1908
+ for (const integration of this.integrations) {
1909
+ if (integration.onDisconnect) {
1910
+ await integration.onDisconnect(this);
1911
+ }
1912
+ }
1913
+ await this.transport.disconnect();
1914
+ this.initialized = false;
1915
+ }
1916
+ isConnected() {
1917
+ return this.transport.isConnected();
1918
+ }
1919
+ isInitialized() {
1920
+ return this.initialized;
1921
+ }
1922
+ getAuthState(provider) {
1923
+ return this.authState.get(provider);
1924
+ }
1925
+ isProviderAuthenticated(provider) {
1926
+ return this.authState.get(provider)?.authenticated ?? false;
1927
+ }
1928
+ async isAuthorized(provider) {
1929
+ const status = await this.oauthManager.checkAuthStatus(provider);
1930
+ return status.authorized;
1931
+ }
1932
+ async authorizedProviders() {
1933
+ const authorized = [];
1934
+ for (const integration of this.integrations) {
1935
+ if (integration.oauth) {
1936
+ const status = await this.oauthManager.checkAuthStatus(integration.oauth.provider);
1937
+ if (status.authorized) {
1938
+ authorized.push(integration.oauth.provider);
1939
+ }
1940
+ }
1941
+ }
1942
+ return authorized;
1943
+ }
1944
+ async getAuthorizationStatus(provider) {
1945
+ return await this.oauthManager.checkAuthStatus(provider);
1946
+ }
1947
+ async authorize(provider, options) {
1948
+ const integration = this.integrations.find((p) => p.oauth?.provider === provider);
1949
+ if (!integration?.oauth) {
1950
+ const error = new Error(`No OAuth configuration found for provider: ${provider}`);
1951
+ this.eventEmitter.emit("auth:error", { provider, error });
1952
+ throw error;
1953
+ }
1954
+ this.eventEmitter.emit("auth:started", { provider });
1955
+ try {
1956
+ await this.oauthManager.initiateFlow(provider, integration.oauth, options?.returnUrl);
1957
+ const tokenData = this.oauthManager.getProviderToken(provider);
1958
+ if (tokenData) {
1959
+ this.eventEmitter.emit("auth:complete", {
1960
+ provider,
1961
+ accessToken: tokenData.accessToken,
1962
+ expiresAt: tokenData.expiresAt
1963
+ });
1964
+ }
1965
+ this.authState.set(provider, { authenticated: true });
1966
+ } catch (error) {
1967
+ this.eventEmitter.emit("auth:error", { provider, error });
1968
+ throw error;
1969
+ }
1970
+ }
1971
+ async handleOAuthCallback(params) {
1972
+ try {
1973
+ const result = await this.oauthManager.handleCallback(params.code, params.state);
1974
+ this.authState.set(result.provider, { authenticated: true });
1975
+ this.eventEmitter.emit("auth:complete", {
1976
+ provider: result.provider,
1977
+ accessToken: result.accessToken,
1978
+ expiresAt: result.expiresAt
1979
+ });
1980
+ } catch (error) {
1981
+ this.eventEmitter.emit("auth:error", {
1982
+ provider: "unknown",
1983
+ error
1984
+ });
1985
+ throw error;
1986
+ }
1987
+ }
1988
+ getProviderToken(provider) {
1989
+ return this.oauthManager.getProviderToken(provider);
1990
+ }
1991
+ setProviderToken(provider, tokenData) {
1992
+ this.oauthManager.setProviderToken(provider, tokenData);
1993
+ this.authState.set(provider, { authenticated: true });
1994
+ }
1995
+ getAllProviderTokens() {
1996
+ const tokens = {};
1997
+ const allTokens = this.oauthManager.getAllProviderTokens();
1998
+ for (const [provider, tokenData] of allTokens.entries()) {
1999
+ tokens[provider] = tokenData.accessToken;
2000
+ }
2001
+ return tokens;
2002
+ }
2003
+ async reauthenticate(provider) {
2004
+ const state = this.authState.get(provider);
2005
+ if (!state) {
2006
+ throw new Error(`Provider "${provider}" not found in configured integrations`);
2007
+ }
2008
+ if (!this.onReauthRequired) {
2009
+ throw new Error("No re-authentication handler configured. Set onReauthRequired in client config.");
2010
+ }
2011
+ const lastError = state.lastError || new (await Promise.resolve().then(() => (init_errors(), exports_errors))).AuthenticationError("Manual re-authentication requested", undefined, provider);
2012
+ const success = await this.onReauthRequired({
2013
+ provider,
2014
+ error: lastError
2015
+ });
2016
+ if (success) {
2017
+ this.authState.set(provider, { authenticated: true });
2018
+ }
2019
+ return success;
2020
+ }
2021
+ }
2022
+ // ../server.ts
2023
+ function toSolidStartHandler(clientOrHandlerOrOptions, _redirectOptions) {
2024
+ if (clientOrHandlerOrOptions && clientOrHandlerOrOptions.handler && typeof clientOrHandlerOrOptions.handler === "function") {
2025
+ const baseHandler = clientOrHandlerOrOptions.handler;
2026
+ const handler2 = async (event) => {
2027
+ return baseHandler(event.request);
2028
+ };
2029
+ return {
2030
+ GET: handler2,
2031
+ POST: handler2,
2032
+ PATCH: handler2,
2033
+ PUT: handler2,
2034
+ DELETE: handler2
2035
+ };
2036
+ }
2037
+ if (typeof clientOrHandlerOrOptions === "function") {
2038
+ const baseHandler = clientOrHandlerOrOptions;
2039
+ const handler2 = async (event) => {
2040
+ return baseHandler(event.request);
2041
+ };
2042
+ return {
2043
+ GET: handler2,
2044
+ POST: handler2,
2045
+ PATCH: handler2,
2046
+ PUT: handler2,
2047
+ DELETE: handler2
2048
+ };
2049
+ }
2050
+ const options = clientOrHandlerOrOptions;
2051
+ if (!options.providers || Object.keys(options.providers).length === 0) {
2052
+ throw new Error("toSolidStartHandler requires either a handler function or a providers config object");
2053
+ }
2054
+ const { providers, serverUrl, apiKey, redirectUrl, errorRedirectUrl } = options;
2055
+ const nextHandler = createNextOAuthHandler({
2056
+ providers,
2057
+ serverUrl,
2058
+ apiKey
2059
+ });
2060
+ const routes = nextHandler.toNextJsHandler({
2061
+ redirectUrl: redirectUrl || "/",
2062
+ errorRedirectUrl: errorRedirectUrl || "/auth-error"
2063
+ });
2064
+ const handler = async (event) => {
2065
+ const method = event.request.method.toUpperCase();
2066
+ const url = new URL(event.request.url);
2067
+ const pathParts = url.pathname.split("/").filter(Boolean);
2068
+ const integrateIndex = pathParts.indexOf("integrate");
2069
+ const segments = integrateIndex >= 0 ? pathParts.slice(integrateIndex + 1) : [];
2070
+ const context = {
2071
+ params: segments
2072
+ };
2073
+ if (method === "POST") {
2074
+ return routes.POST(event.request, { params: { all: context.params } });
2075
+ } else if (method === "GET") {
2076
+ return routes.GET(event.request, { params: { all: context.params } });
2077
+ } else {
2078
+ return Response.json({ error: `Method ${method} not allowed` }, { status: 405 });
2079
+ }
2080
+ };
2081
+ return {
2082
+ GET: handler,
2083
+ POST: handler,
2084
+ PATCH: handler,
2085
+ PUT: handler,
2086
+ DELETE: handler
2087
+ };
2088
+ }
2089
+ function toSvelteKitHandler(clientOrHandlerOrOptions, _redirectOptions) {
2090
+ if (clientOrHandlerOrOptions && clientOrHandlerOrOptions.handler && typeof clientOrHandlerOrOptions.handler === "function") {
2091
+ const baseHandler = clientOrHandlerOrOptions.handler;
2092
+ return async (event) => {
2093
+ const all = event.params?.all;
2094
+ return baseHandler(event.request, { params: { all } });
2095
+ };
2096
+ }
2097
+ if (typeof clientOrHandlerOrOptions === "function") {
2098
+ const baseHandler = clientOrHandlerOrOptions;
2099
+ return async (event) => {
2100
+ const all = event.params?.all;
2101
+ return baseHandler(event.request, { params: { all } });
2102
+ };
2103
+ }
2104
+ const options = clientOrHandlerOrOptions;
2105
+ if (!options.providers || Object.keys(options.providers).length === 0) {
2106
+ throw new Error("toSvelteKitHandler requires either a handler function or a providers config object");
2107
+ }
2108
+ const { providers, serverUrl, apiKey, redirectUrl, errorRedirectUrl } = options;
2109
+ const nextHandler = createNextOAuthHandler({
2110
+ providers,
2111
+ serverUrl,
2112
+ apiKey
2113
+ });
2114
+ const routes = nextHandler.toNextJsHandler({
2115
+ redirectUrl: redirectUrl || "/",
2116
+ errorRedirectUrl: errorRedirectUrl || "/auth-error"
2117
+ });
2118
+ return async (event) => {
2119
+ const method = event.request.method.toUpperCase();
2120
+ const all = event.params?.all;
2121
+ const context = {
2122
+ params: Array.isArray(all) ? all : all ? all.split("/").filter(Boolean) : []
2123
+ };
2124
+ if (method === "POST") {
2125
+ return routes.POST(event.request, { params: { all: context.params } });
2126
+ } else if (method === "GET") {
2127
+ return routes.GET(event.request, { params: { all: context.params } });
2128
+ } else {
2129
+ return Response.json({ error: `Method ${method} not allowed` }, { status: 405 });
2130
+ }
2131
+ };
2132
+ }
2133
+ // svelte-kit.ts
2134
+ async function svelteKitHandler({
2135
+ authConfig,
2136
+ event,
2137
+ resolve,
2138
+ basePath = "/api/integrate"
2139
+ }) {
2140
+ const { url } = event;
2141
+ const baseUrl = new URL(basePath, url.origin);
2142
+ if (!url.pathname.startsWith(baseUrl.pathname)) {
2143
+ return resolve(event);
2144
+ }
2145
+ return authConfig(event.request);
2146
+ }
2147
+
2148
+ // tanstack-start.ts
2149
+ function toTanStackStartHandler(handler) {
2150
+ const baseHandler = async ({ request }) => {
2151
+ return handler(request);
2152
+ };
2153
+ return {
2154
+ GET: baseHandler,
2155
+ POST: baseHandler
2156
+ };
2157
+ }
2158
+ var createTanStackOAuthHandler = toTanStackStartHandler;
2159
+ export {
2160
+ toTanStackStartHandler,
2161
+ toSvelteKitHandler,
2162
+ toSolidStartHandler,
2163
+ toNodeHandler,
2164
+ svelteKitHandler,
2165
+ setGlobalOAuthConfig,
2166
+ getGlobalOAuthConfig,
2167
+ fromNodeHeaders,
2168
+ createTanStackOAuthHandler,
2169
+ createNextOAuthHandler,
2170
+ POST,
2171
+ OAuthHandler,
2172
+ GET
2173
+ };