@mastra/elysia 0.1.23-alpha.8 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +22 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -37
- package/dist/index.js.map +1 -1
- package/package.json +11 -11
package/dist/index.cjs
CHANGED
|
@@ -415,13 +415,6 @@ function createDatastreamBody(body, signal) {
|
|
|
415
415
|
}
|
|
416
416
|
});
|
|
417
417
|
}
|
|
418
|
-
let _hasPermissionPromise;
|
|
419
|
-
function loadHasPermission() {
|
|
420
|
-
if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
|
|
421
|
-
console.error("[@mastra/elysia] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest");
|
|
422
|
-
});
|
|
423
|
-
return _hasPermissionPromise;
|
|
424
|
-
}
|
|
425
418
|
var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
426
419
|
createContextMiddleware() {
|
|
427
420
|
return async (ctx) => {
|
|
@@ -603,6 +596,10 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
|
603
596
|
}
|
|
604
597
|
return result;
|
|
605
598
|
}
|
|
599
|
+
/** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */
|
|
600
|
+
resolveMcpOptions() {
|
|
601
|
+
return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;
|
|
602
|
+
}
|
|
606
603
|
async sendResponse(route, response, result, prefix) {
|
|
607
604
|
const resolvedPrefix = prefix ?? this.prefix ?? "";
|
|
608
605
|
const refreshHeaders = {};
|
|
@@ -634,7 +631,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
|
634
631
|
const forwardRequest = await createForwardRequest(request);
|
|
635
632
|
const { req, res } = (0, fetch_to_node.toReqRes)(forwardRequest);
|
|
636
633
|
const { setRequestAuth, ...options } = {
|
|
637
|
-
...this.
|
|
634
|
+
...this.resolveMcpOptions(),
|
|
638
635
|
...routeMcpOptions
|
|
639
636
|
};
|
|
640
637
|
await (0, _mastra_server_server_adapter.applyMcpRequestAuth)({
|
|
@@ -671,7 +668,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
|
671
668
|
await (0, _mastra_server_server_adapter.applyMcpRequestAuth)({
|
|
672
669
|
req,
|
|
673
670
|
requestContext: request.requestContext,
|
|
674
|
-
setRequestAuth: this.
|
|
671
|
+
setRequestAuth: this.resolveMcpOptions()?.setRequestAuth
|
|
675
672
|
});
|
|
676
673
|
server.startSSE({
|
|
677
674
|
url: new URL(forwardRequest.url),
|
|
@@ -726,20 +723,14 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
|
726
723
|
...authError.headers
|
|
727
724
|
}
|
|
728
725
|
});
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
}), {
|
|
738
|
-
status: permissionError.status,
|
|
739
|
-
headers: { "Content-Type": "application/json" }
|
|
740
|
-
});
|
|
741
|
-
}
|
|
742
|
-
}
|
|
726
|
+
const permissionError = this.checkRouteRBAC(route, ctx.requestContext);
|
|
727
|
+
if (permissionError) return new Response(JSON.stringify({
|
|
728
|
+
error: permissionError.error,
|
|
729
|
+
message: permissionError.message
|
|
730
|
+
}), {
|
|
731
|
+
status: permissionError.status,
|
|
732
|
+
headers: { "Content-Type": "application/json" }
|
|
733
|
+
});
|
|
743
734
|
const rawParams = ctx.params || {};
|
|
744
735
|
const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;
|
|
745
736
|
const queryParams = (0, _mastra_server_server_adapter.normalizeQueryParams)(searchParamsToQuery(new URL(ctx.request.url).searchParams));
|
|
@@ -945,20 +936,14 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
|
|
|
945
936
|
...authError.headers
|
|
946
937
|
}
|
|
947
938
|
});
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
}), {
|
|
957
|
-
status: permissionError.status,
|
|
958
|
-
headers: { "Content-Type": "application/json" }
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
}
|
|
939
|
+
const permissionError = this.checkRouteRBAC(serverRoute, ctx.requestContext);
|
|
940
|
+
if (permissionError) return new Response(JSON.stringify({
|
|
941
|
+
error: permissionError.error,
|
|
942
|
+
message: permissionError.message
|
|
943
|
+
}), {
|
|
944
|
+
status: permissionError.status,
|
|
945
|
+
headers: { "Content-Type": "application/json" }
|
|
946
|
+
});
|
|
962
947
|
}
|
|
963
948
|
const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, serverRoute, ctx.requestContext, {
|
|
964
949
|
...ctx.query,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["RequestContext","isCustomRoutePublic","coreAuthMiddleware","serializeCookie","generateOpenAPIDocument","SERVER_ROUTES","convertCustomRoutesToOpenAPIPaths","MastraServerBase","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","isSafeObjectKey","toReqRes","applyMcpRequestAuth","toFetchResponse","isZodError","checkRouteFGA","getCustomHTTPExceptionResponse","getHTTPErrorResponse"],"sources":["../src/auth-middleware.ts","../src/helper.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport { serializeCookie } from 'elysia/cookies';\n\nexport interface ElysiaAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\n// Refreshed session headers from an allowed request, applied to the final response by applyAuthRefreshHeaders.\nconst pendingRefreshHeaders = new WeakMap<Request, Record<string, string>>();\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ElysiaAuthMiddlewareOptions): (ctx: any) => Promise<globalThis.Response | void> {\n return async (ctx: any) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n ctx.requestContext ??= new RequestContext();\n ctx.mastra ??= mastra;\n\n const url = new URL(ctx.request.url);\n const path = url.pathname;\n const method = ctx.request.method;\n const customRouteAuthConfig = new Map<string, boolean>(ctx.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = ctx.request.headers.get('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && ctx.query?.apiKey) {\n token = ctx.query.apiKey;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => ctx.request.headers.get(name) || undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: ctx.requestContext,\n rawRequest: ctx.request,\n token,\n buildAuthorizeContext: () => ctx,\n });\n\n if (result.action === 'error') {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n appendHeaders(headers, result.headers);\n return new Response(JSON.stringify(result.body), { status: result.status, headers });\n }\n\n if (result.headers && Object.keys(result.headers).length > 0) {\n pendingRefreshHeaders.set(ctx.request, result.headers);\n }\n };\n}\n\n/**\n * Elysia `onAfterHandle` and `onError` hook that forwards session headers refreshed by\n * `createAuthMiddleware` onto the final response, including responses for handlers that throw. `Set-Cookie` values are appended alongside any cookies the app set\n * (via `ctx.cookie`, `set.headers`, or a returned `Response`) so none of them are dropped.\n */\nexport function applyAuthRefreshHeaders(ctx: any): globalThis.Response | void {\n const refreshHeaders = pendingRefreshHeaders.get(ctx.request);\n if (!refreshHeaders) {\n return;\n }\n pendingRefreshHeaders.delete(ctx.request);\n\n const set = ctx.set;\n const appCookies = takeSetSideCookies(set);\n const response = ctx.response;\n\n if (response instanceof Response) {\n const headers = new Headers(response.headers);\n for (const cookie of appCookies) {\n headers.append('set-cookie', cookie);\n }\n appendHeaders(headers, refreshHeaders);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n\n const cookies = [...appCookies];\n for (const [key, value] of Object.entries(refreshHeaders)) {\n if (key.toLowerCase() === 'set-cookie') {\n cookies.push(value);\n } else if (set.headers instanceof Headers) {\n set.headers.set(key, value);\n } else {\n set.headers[key] = value;\n }\n }\n if (cookies.length === 0) {\n return;\n }\n if (set.headers instanceof Headers) {\n for (const cookie of cookies) {\n set.headers.append('set-cookie', cookie);\n }\n } else {\n set.headers['set-cookie'] = cookies;\n }\n}\n\nfunction appendHeaders(headers: Headers, extra: Record<string, string> | undefined): void {\n for (const [key, value] of Object.entries(extra ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n headers.append(key, value);\n } else {\n headers.set(key, value);\n }\n }\n}\n\n/**\n * Removes and returns cookies queued on Elysia's `set` (both `set.cookie` and raw `set-cookie` headers).\n * Elysia overwrites raw `set-cookie` headers with `set.cookie`, and drops set-side cookies when the\n * returned `Response` already has one, so they are collected here and re-emitted explicitly.\n */\nfunction takeSetSideCookies(set: any): string[] {\n const cookies: string[] = [];\n\n if (set.headers instanceof Headers) {\n cookies.push(...set.headers.getSetCookie());\n set.headers.delete('set-cookie');\n } else if (set.headers) {\n for (const key of Object.keys(set.headers)) {\n if (key.toLowerCase() !== 'set-cookie') continue;\n const value = set.headers[key];\n cookies.push(...(Array.isArray(value) ? value : [value]));\n delete set.headers[key];\n }\n }\n\n const serialized = serializeCookie(set.cookie);\n if (serialized) {\n cookies.push(...(Array.isArray(serialized) ? serialized : [serialized]));\n }\n for (const key of Object.keys(set.cookie ?? {})) {\n delete set.cookie[key];\n }\n\n return cookies;\n}\n","import {\n generateOpenAPIDocument,\n convertCustomRoutesToOpenAPIPaths,\n SERVER_ROUTES,\n} from '@mastra/server/server-adapter';\nimport type { MastraServer } from './index';\n\n/**\n * OpenAPI documentation cache to avoid regenerating on each call.\n * Uses WeakMap to prevent cache collisions between server instances.\n */\nconst openapiDocCache = new WeakMap<\n MastraServer,\n {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n }\n>();\n\n/**\n * Get OpenAPI documentation from a MastraServer instance, formatted for Elysia's openapi plugin.\n *\n * This function:\n * - Extracts all Mastra routes with their Zod schemas\n * - Converts them to OpenAPI 3.1.0 format\n * - Merges custom routes if registered\n * - Applies the configured route prefix to all paths\n * - Caches the result for performance\n *\n * @param server - The MastraServer instance (must be initialized with init())\n * @param options - Optional configuration for OpenAPI metadata\n * @returns OpenAPI documentation with paths, components, and info\n *\n * @example\n * ```typescript\n * import { getMastraOpenAPIDoc } from '@mastra/elysia';\n *\n * const srv = new MastraServer({ mastra, app, prefix: '/api' });\n * await srv.init();\n *\n * const openAPIDoc = getMastraOpenAPIDoc(srv, {\n * title: 'My Mastra API',\n * version: '1.0.0',\n * description: 'API with weather agent'\n * });\n *\n * app.use(openapi({\n * documentation: {\n * info: openAPIDoc.info,\n * paths: openAPIDoc.paths,\n * components: openAPIDoc.components\n * }\n * }));\n * ```\n */\nexport function getMastraOpenAPIDoc(\n server: MastraServer,\n options?: {\n title?: string;\n version?: string;\n description?: string;\n clearCache?: boolean;\n },\n): {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n} {\n // Clear cache if requested\n if (options?.clearCache) {\n openapiDocCache.delete(server);\n }\n\n // Return cached result if available\n const cached = openapiDocCache.get(server);\n if (cached) {\n // Merge custom info if provided\n if (options) {\n return {\n ...cached,\n info: {\n ...cached.info,\n ...(options.title && { title: options.title }),\n ...(options.version && { version: options.version }),\n ...(options.description && { description: options.description }),\n },\n };\n }\n return cached;\n }\n\n // Generate complete OpenAPI spec from Mastra's route definitions\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, {\n title: options?.title || 'Mastra API',\n version: options?.version || '1.0.0',\n description: options?.description || 'Mastra Server API',\n });\n\n // Merge custom API routes if present\n const customApiRoutes = (server as any).customApiRoutes;\n if (customApiRoutes && customApiRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n const customPaths = convertCustomRoutesToOpenAPIPaths(customApiRoutes, componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n let paths = openApiSpec.paths || {};\n\n // Apply prefix transformation if configured\n const prefix = (server as any).prefix;\n if (prefix && prefix !== '/') {\n const prefixedPaths: Record<string, any> = {};\n for (const [path, pathItem] of Object.entries(paths)) {\n // Combine prefix with path, ensuring no double slashes\n const prefixedPath = `${prefix}${path}`.replace(/\\/+/g, '/');\n prefixedPaths[prefixedPath] = pathItem;\n }\n paths = prefixedPaths;\n }\n\n const result = {\n paths,\n components: openApiSpec.components,\n info: openApiSpec.info,\n };\n\n // Cache the result\n openapiDocCache.set(server, result);\n\n return result;\n}\n\n/**\n * Clear the OpenAPI documentation cache.\n * Call this if routes are added dynamically after initialization.\n *\n * `@param` server - The MastraServer instance to clear cache for.\n * Note: WeakMap does not support clearing all entries. Pass the specific server instance whose cache should be invalidated.\n */\nexport function clearMastraOpenAPICache(server?: MastraServer): void {\n if (server) {\n openapiDocCache.delete(server);\n }\n // Cannot clear all entries in WeakMap - they will be garbage collected when servers are released\n}\n","import type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n propagateRequestAbort,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { AnyElysia, MaybePromise } from 'elysia';\nimport type Elysia from 'elysia';\nimport { toReqRes, toFetchResponse } from 'fetch-to-node';\nimport { applyAuthRefreshHeaders } from './auth-middleware';\nexport { applyAuthRefreshHeaders, createAuthMiddleware } from './auth-middleware';\nexport type { ElysiaAuthMiddlewareOptions } from './auth-middleware';\n\n// Export helper functions for OpenAPI integration\nexport { getMastraOpenAPIDoc, clearMastraOpenAPICache } from './helper';\n\nconst BODY_TOO_LARGE = Symbol('mastra.elysia.bodyTooLarge');\nconst EMPTY_JSON_BODY = Symbol('mastra.elysia.emptyJsonBody');\n\nclass InvalidJsonBody {\n constructor(readonly message: string) {}\n}\n\nasync function readBodyWithLimit(body: ReadableStream<Uint8Array>, maxSize: number): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxSize) {\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Route-level Elysia parse hook for body methods.\n *\n * Parses JSON bodies itself: under `@elysiajs/node` an empty request still has a body stream, so Elysia's default\n * JSON parser throws on it and the request fails with 400 before the route runs. An empty JSON body comes back as\n * EMPTY_JSON_BODY and malformed JSON as InvalidJsonBody, both resolved by the route handler.\n *\n * With a `maxSize`, also enforces the body limit before anything buffers the request. Oversized bodies are marked\n * with BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.\n */\nfunction createBodyParser(maxSize: number | undefined) {\n return async (ctx: any) => {\n const request: Request = ctx.request;\n const contentLength = request.headers.get('content-length');\n // Reject a declared oversized body without reading it. A declared size within\n // the limit is still read with the cap, since app.handle() accepts a Request\n // whose stream need not match its Content-Length header.\n if (maxSize !== undefined && contentLength !== null && parseInt(contentLength, 10) > maxSize) {\n return BODY_TOO_LARGE;\n }\n\n const isJson = (request.headers.get('content-type') ?? '').includes('application/json');\n if (!request.body || (!isJson && maxSize === undefined)) return undefined;\n\n const bytes =\n maxSize === undefined\n ? new Uint8Array(await request.arrayBuffer())\n : await readBodyWithLimit(request.body, maxSize);\n if (!bytes) return BODY_TOO_LARGE;\n\n if (isJson) {\n const text = new TextDecoder().decode(bytes);\n if (text.trim().length === 0) return EMPTY_JSON_BODY;\n try {\n return JSON.parse(text);\n } catch (error) {\n return new InvalidJsonBody(error instanceof Error ? error.message : 'Invalid JSON in request body');\n }\n }\n\n // Hand the bounded body back to Elysia's default parsers.\n ctx.request = new Request(request.url, {\n method: request.method,\n headers: request.headers,\n body: bytes,\n signal: request.signal,\n });\n return undefined;\n };\n}\n\n/**\n * Normalizes route path parameters to position-based names (:p0, :p1, ...)\n * to avoid Elysia router conflicts when different routes use different\n * parameter names at the same path segment position (e.g. :agentId vs\n * :storedAgentId under /stored/agents/...).\n * Returns the normalized path and the original parameter names in order.\n */\nfunction normalizeRouteParams(path: string): { normalizedPath: string; paramNames: string[] } {\n const paramNames: string[] = [];\n const normalizedPath = path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName: string) => {\n paramNames.push(paramName);\n return `:p${paramNames.length - 1}`;\n });\n return { normalizedPath, paramNames };\n}\n\n/**\n * Reads query params keeping every value of a repeated key (`?tag=a&tag=b` -> `{ tag: ['a', 'b'] }`), as the\n * other adapters do; Elysia's `ctx.query` and `Object.fromEntries` keep only one.\n */\nfunction searchParamsToQuery(searchParams: URLSearchParams): Record<string, string | string[]> {\n const query: Record<string, string | string[]> = {};\n for (const key of new Set(searchParams.keys())) {\n const values = searchParams.getAll(key);\n query[key] = values.length === 1 ? (values[0] as string) : values;\n }\n return query;\n}\n\n/**\n * Remaps Elysia's parsed params from position-based names (p0, p1, ...)\n * back to the original parameter names expected by the route handler.\n */\nfunction remapParams(rawParams: Record<string, string>, paramNames: string[]): Record<string, string> {\n if (paramNames.length === 0) return rawParams;\n const result: Record<string, string> = {};\n paramNames.forEach((paramName, i) => {\n const key = `p${i}`;\n if (key in rawParams) {\n result[paramName] = rawParams[key] as string;\n }\n });\n return result;\n}\n\nasync function createForwardRequest(ctx: any): Promise<Request> {\n const request = ctx.request as Request;\n const method = request.method;\n\n if (method === 'GET' || method === 'HEAD') {\n return request;\n }\n\n const headers = new Headers(request.headers);\n let body: any;\n\n if (ctx.body !== undefined) {\n if (typeof ctx.body === 'string' || ctx.body instanceof FormData || ctx.body instanceof Blob) {\n body = ctx.body;\n } else {\n body = JSON.stringify(ctx.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n } else if (!request.bodyUsed) {\n const bodyBuffer = await request.clone().arrayBuffer();\n if (bodyBuffer.byteLength > 0) {\n body = bodyBuffer;\n }\n }\n\n headers.delete('content-length');\n\n return new Request(request.url, {\n method,\n headers,\n body,\n signal: request.signal,\n ...(body ? { duplex: 'half' as const } : {}),\n } as RequestInit);\n}\n\n/**\n * srvx, which runs `@elysiajs/node`, creates `request.signal` on first access and only then listens for the response\n * 'close'. A client that left during an earlier hook therefore never aborts it, so check the Node response directly.\n */\nfunction getRequestAbortSignal(request: Request): AbortSignal {\n const signal = request.signal;\n const nodeRes = (request as { runtime?: { node?: { res?: { destroyed?: boolean } } } }).runtime?.node?.res;\n return nodeRes?.destroyed && !signal.aborted ? AbortSignal.abort() : signal;\n}\n\nfunction getRequestSignal(ctx: unknown): AbortSignal | undefined {\n const context = ctx as { abortSignal?: AbortSignal; request?: Request } | undefined;\n return context?.abortSignal ?? (context?.request ? getRequestAbortSignal(context.request) : undefined);\n}\n\n/**\n * Cancels `reader` once, through `cancel()` or when the request signal aborts. A runtime that skips the response body\n * of a request that closed while the route handler ran never cancels that body, so the signal is the only notice.\n */\nfunction cancelReaderOnRequestAbort(\n reader: ReadableStreamDefaultReader<unknown>,\n signal: AbortSignal | undefined,\n): { cancel: (reason?: unknown) => void; dispose: () => void } {\n let canceled = false;\n const onAbort = () => cancel('request aborted');\n const dispose = () => signal?.removeEventListener('abort', onAbort);\n const cancel = (reason?: unknown) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n dispose();\n void reader.cancel(reason).catch(() => {});\n };\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return { cancel, dispose };\n}\n\nfunction createSafeReadableStream(body: ReadableStream<Uint8Array> | null): ReadableStream<Uint8Array> | null {\n if (!body) return null;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const reader = body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n controller.enqueue(value);\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n } finally {\n controller.close();\n reader.releaseLock();\n }\n },\n });\n}\n\n/**\n * Wraps a `datastream-response` body so a client disconnect cancels the upstream body. Unlike\n * `createSafeReadableStream`, it reads one chunk per pull, so a slow client slows the upstream.\n */\nfunction createDatastreamBody(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal | undefined,\n): ReadableStream<Uint8Array> | null {\n if (!body) {\n return null;\n }\n\n const reader = body.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, signal);\n let finished = false;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (!done) {\n controller.enqueue(value);\n return;\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n if (finished) {\n return;\n }\n }\n\n finished = true;\n upstream.dispose();\n controller.close();\n },\n cancel(reason) {\n finished = true;\n upstream.cancel(reason);\n },\n });\n}\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/elysia] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n// Export type definitions for Elysia app configuration\nexport interface ElysiaContext {\n mastra: Mastra;\n requestContext: RequestContext;\n registeredTools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n}\n\n/**\n * Minimal interface representing what MastraServer needs from an Elysia app.\n * This allows any Elysia app instance to be passed without strict generic matching.\n */\nexport interface ElysiaApp {\n use(instance: MaybePromise<AnyElysia>): ElysiaApp;\n derive(callback: (context: any) => any | Promise<any>): ElysiaApp;\n get(path: string, handler: any, options?: any): ElysiaApp;\n post(path: string, handler: any, options?: any): ElysiaApp;\n put(path: string, handler: any, options?: any): ElysiaApp;\n delete(path: string, handler: any, options?: any): ElysiaApp;\n patch(path: string, handler: any, options?: any): ElysiaApp;\n all(path: string, handler: any, options?: any): ElysiaApp;\n onAfterHandle(handler: (context: any) => any): ElysiaApp;\n onError(handler: (context: any) => any): ElysiaApp;\n}\n\nexport class MastraServer extends MastraServerBase<Elysia, Request, Response> {\n createContextMiddleware() {\n return async (ctx: any) => {\n // Parse request context from request body and query params\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT/PATCH)\n if (ctx.request.method === 'POST' || ctx.request.method === 'PUT' || ctx.request.method === 'PATCH') {\n const contentType = ctx.request.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n try {\n const body = (ctx.body ?? (await ctx.request.clone().json())) as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n } catch {\n // Body parsing failed, continue without body\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (ctx.request.method === 'GET') {\n try {\n // Elysia pre-parses query params into ctx.query\n const encodedRequestContext = ctx.query?.requestContext;\n if (encodedRequestContext) {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n });\n\n // Add relevant contexts to Elysia context\n return {\n requestContext,\n mastra: this.mastra,\n registeredTools: this.tools || {},\n taskStore: this.taskStore,\n abortSignal: getRequestAbortSignal(ctx.request),\n customRouteAuthConfig: this.customRouteAuthConfig,\n };\n };\n }\n\n async stream(route: ServerRoute, ctx: Response, result: { fullStream: ReadableStream }): Promise<any> {\n const streamFormat = route.streamFormat || 'stream';\n const encoder = new TextEncoder();\n\n const headers: Record<string, string> =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, getRequestSignal(ctx));\n // Set once the controller is closed, errored or cancelled; nothing may be enqueued from then on.\n let finished = false;\n\n // Reads one upstream chunk per pull so a slow client slows the upstream instead of buffering it here.\n const stream = new ReadableStream({\n start: controller => {\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n controller.enqueue(encoder.encode(': connected\\n\\n'));\n }\n },\n pull: async controller => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (done) {\n finished = true;\n upstream.dispose();\n\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n }\n\n controller.close();\n return;\n }\n\n if (!value) {\n continue;\n }\n\n // SSE comment passthrough — strings starting with ':' are written as-is\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n controller.enqueue(encoder.encode(value));\n return;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode(`data: ${serialized.json}\\n\\n`));\n } else {\n controller.enqueue(encoder.encode(serialized.json + '\\x1E'));\n }\n return;\n }\n } catch (error) {\n if (finished) {\n return;\n }\n\n finished = true;\n upstream.dispose();\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Close instead of erroring: @elysiajs/node destroys the socket on an errored body, dropping the frames\n // already enqueued and, for an early error, the status line too.\n controller.close();\n }\n },\n cancel: reason => {\n finished = true;\n upstream.cancel(reason);\n },\n });\n\n return new Response(stream, { headers });\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const url = new URL(request.url);\n\n // URL params - extract from request context if available (Elysia stores params in ctx)\n // Params may be normalized (p0, p1, ...) — remap back to original names from route path\n const { paramNames } = normalizeRouteParams(route.path);\n const rawUrlParams: Record<string, string> = (request as any).params || (request as any).ctx?.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawUrlParams, paramNames) : rawUrlParams;\n\n // Query params - parse from URL\n const queryParams = normalizeQueryParams(searchParamsToQuery(url.searchParams));\n\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const formData = await request.formData();\n body = await this.parseFormData(formData);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n const clonedReq = request.clone();\n const bodyText = await clonedReq.text();\n\n if (bodyText && bodyText.trim().length > 0) {\n try {\n body = JSON.parse(bodyText);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Invalid JSON in request body',\n };\n }\n }\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse FormData into a plain object, converting File objects to Buffers.\n * Handles both native FormData and Elysia's pre-parsed object format.\n */\n private async parseFormData(data: FormData | Record<string, unknown>): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {};\n\n // Handle native FormData\n if (data instanceof FormData) {\n for (const [key, value] of data.entries()) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value instanceof File) {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n // Try to parse JSON strings (like 'options')\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n // Handle Elysia's pre-parsed object format\n for (const [key, value] of Object.entries(data)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value && typeof value === 'object' && 'arrayBuffer' in value && typeof value.arrayBuffer === 'function') {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n async sendResponse(route: ServerRoute, response: Response, result: unknown, prefix?: string): Promise<any> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n const refreshHeaders: Record<string, string> = {};\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const headers = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(headers)) {\n refreshHeaders[key] = value;\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json', ...refreshHeaders },\n });\n } else if (route.responseType === 'stream') {\n return this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n const fetchResponse = result as globalThis.Response;\n const headers = new Headers(fetchResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createDatastreamBody(fetchResponse.body, getRequestSignal(response)), {\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n const { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n // `toReqRes` builds a fresh IncomingMessage, so bridge the principal auth resolved.\n await applyMcpRequestAuth({ req, requestContext: request.requestContext, setRequestAuth });\n\n // Do NOT await startHTTP — let it run in the background so SSE\n // notifications stream to the client as they are written.\n // toFetchResponse resolves when headers are sent, not when the body finishes.\n server\n .startHTTP({\n url: new URL(forwardRequest.url),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req,\n res,\n options: Object.keys(options).length > 0 ? options : undefined,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP HTTP] Error in background startHTTP:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n // `createForwardRequest` rebuilds the Request without a signal, so listen on the\n // original one: a client disconnect must abort the in-flight MCP request.\n propagateRequestAbort((request.request as Request).signal, res);\n\n const mcpResponse = await toFetchResponse(res);\n const headers = new Headers(mcpResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(mcpResponse.body), {\n status: mcpResponse.status,\n statusText: mcpResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-sse') {\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n await applyMcpRequestAuth({\n req,\n requestContext: request.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\n server\n .startSSE({\n url: new URL(forwardRequest.url),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req,\n res,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP SSE] Error in background startSSE:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n const sseResponse = await toFetchResponse(res);\n const headers = new Headers(sseResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(sseResponse.body), {\n status: sseResponse.status,\n statusText: sseResponse.statusText,\n headers,\n });\n }\n return new Response(null, { status: 500 });\n }\n\n async registerRoute(\n app: ElysiaApp,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n const prefix = prefixParam ?? this.prefix ?? '';\n const fullPath = `${prefix}${route.path}`;\n const { normalizedPath, paramNames } = normalizeRouteParams(fullPath);\n\n const handler = async (ctx: any) => {\n // Reject oversized bodies before auth, matching adapters that enforce the limit in middleware.\n if (ctx.body === BODY_TOO_LARGE) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default error response.\n }\n }\n return new Response(JSON.stringify(errorResponse), {\n status: 413,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: ctx.request.url ? new URL(ctx.request.url).pathname : ctx.path,\n method: ctx.request.method,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = ctx.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n }\n\n // Extract params - remap from normalized param names back to original\n const rawParams = ctx.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;\n const queryParams = normalizeQueryParams(searchParamsToQuery(new URL(ctx.request.url).searchParams));\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = ctx.request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n // Elysia pre-parses multipart form data\n body = ctx.body ? await this.parseFormData(ctx.body) : undefined;\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n // Parsed by the route's parse hook (createBodyParser)\n if (ctx.body instanceof InvalidJsonBody) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', { error: { message: ctx.body.message } });\n bodyParseError = { message: ctx.body.message };\n } else if (ctx.body !== EMPTY_JSON_BODY) {\n body = ctx.body;\n }\n // createForwardRequest (MCP routes) reads ctx.body later and must not see the parse hook's markers.\n ctx.body = body;\n }\n }\n\n const params = { urlParams, queryParams, body, bodyParseError };\n\n // Return 400 Bad Request if body parsing failed\n if (params.bodyParseError) {\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n const fgaError = await checkRouteFGA(this.mastra, route, ctx.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: ctx.requestContext,\n mastra: ctx.mastra,\n registeredTools: ctx.registeredTools,\n taskStore: ctx.taskStore,\n abortSignal: ctx.abortSignal,\n routePrefix: prefix,\n request: ctx.request,\n };\n\n try {\n const result = await route.handler(handlerParams);\n return this.sendResponse(route, ctx as any, result, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n // Client errors (4xx) are returned as structured responses below, so they aren't logged as server faults.\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n return customResponse;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n\n // Register the route using Elysia's method chaining\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method);\n if (isBodyMethod) {\n app[method](normalizedPath, handler, { parse: createBodyParser(maxSize) });\n } else {\n app[method](normalizedPath, handler);\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const { normalizedPath: customNormalizedPath } = normalizeRouteParams(route.path);\n (this.app as ElysiaApp)[method](customNormalizedPath, async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n const requestMethod = ctx.request.method;\n // Check auth against the custom route the custom-route app will actually run for\n // this URL, which can differ from the route Elysia matched.\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(ctx.request.url, requestMethod, path, route);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method: requestMethod,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n customRouteAuthConfig,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = ctx.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n serverRoute,\n userPermissions,\n hasPermission,\n ctx.requestContext,\n );\n if (permissionError) {\n return new Response(\n JSON.stringify({ error: permissionError.error, message: permissionError.message }),\n {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n }\n }\n\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {\n ...(ctx.query as Record<string, string>),\n ...(typeof ctx.body === 'object' && ctx.body !== null ? ctx.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const headers: Record<string, string | string[] | undefined> = {};\n ctx.request.headers.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n\n const response = await this.handleCustomRouteRequest(\n ctx.request.url,\n ctx.request.method,\n headers,\n ctx.body,\n ctx.requestContext,\n ctx.request.signal,\n );\n\n if (!response) {\n return new Response(JSON.stringify({ error: 'Not Found' }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return response;\n });\n }\n }\n\n registerContextMiddleware(): void {\n this.app.derive(this.createContextMiddleware());\n this.app.onAfterHandle({ as: 'global' }, applyAuthRefreshHeaders);\n this.app.onError({ as: 'global' }, applyAuthRefreshHeaders);\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n\n // Register global error handler to catch Elysia body parsing errors\n // and return structured JSON responses instead of plain text \"Bad Request\"\n this.app.onError((ctx: any) => {\n const error = ctx.error;\n const status = error?.status ?? error?.code ?? 500;\n const message = error?.message ?? 'Internal server error';\n\n // Body parsing / validation errors from Elysia are 400s\n const httpStatus = typeof status === 'number' && status >= 400 && status < 500 ? status : 500;\n\n return new Response(\n JSON.stringify({\n error: httpStatus < 500 ? message : 'Internal server error',\n ...(httpStatus < 500 ? { issues: [] } : {}),\n }),\n {\n status: httpStatus,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n });\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.derive(async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return {};\n }\n\n return {\n httpLogStart: Date.now(),\n };\n });\n\n this.app.onAfterHandle((ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return;\n }\n\n const duration = Date.now() - (ctx.httpLogStart ?? Date.now());\n const method = ctx.request.method;\n const status = ctx.response?.status ?? ctx.set?.status ?? 200;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = ctx.query || {};\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = Object.fromEntries(ctx.request.headers.entries());\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n }\n}\n"],"mappings":";;;;;;;AAWA,MAAM,wCAAwB,IAAI,QAAyC;AAE3E,SAAgB,qBAAqB,EACnC,QACA,eAAe,QACkE;CACjF,OAAO,OAAO,QAAa;EACzB,IAAI,CAAC,cACH;EAGF,MAAM,aAAa,OAAO,UAAU,CAAC,EAAE;EACvC,IAAI,CAAC,YACH;EAGF,IAAI,mBAAmB,IAAIA,6BAAAA,eAAe;EAC1C,IAAI,WAAW;EAGf,MAAM,OAAO,IADG,IAAI,IAAI,QAAQ,GACjB,CAAC,CAAC;EACjB,MAAM,SAAS,IAAI,QAAQ;EAC3B,MAAM,wBAAwB,IAAI,IAAqB,IAAI,yBAAyB,CAAC,CAAC;EAEtF,IAAI,EAAA,GAACC,oBAAAA,oBAAAA,CAAoB,MAAM,QAAQ,qBAAqB,GAC1D,sBAAsB,IAAI,GAAG,OAAO,GAAG,QAAQ,IAAI;EAGrD,MAAM,aAAa,IAAI,QAAQ,QAAQ,IAAI,eAAe;EAC1D,IAAI,QAAuB,aAAa,WAAW,QAAQ,WAAW,EAAE,IAAI;EAC5E,IAAI,CAAC,SAAS,IAAI,OAAO,QACvB,QAAQ,IAAI,MAAM;EAGpB,MAAM,SAAS,OAAA,GAAMC,oBAAAA,mBAAAA,CAAmB;GACtC;GACA;GACA,YAAW,SAAQ,IAAI,QAAQ,QAAQ,IAAI,IAAI,KAAK,KAAA;GACpD;GACA;GACA;GACA,gBAAgB,IAAI;GACpB,YAAY,IAAI;GAChB;GACA,6BAA6B;EAC/B,CAAC;EAED,IAAI,OAAO,WAAW,SAAS;GAC7B,MAAM,UAAU,IAAI,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;GAClE,c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hE,CADsB,KAAK,kBAAkB,iBAAiB,CAAC,EAAA,CACjD,SAAQ,MAAK;KACzB,MAAM,MAAM,EAAE,YAAY;KAC1B,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,OAAO;IAEnB,CAAC;IACD,QAAQ,UAAU;GACpB;GAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;EACzE,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["RequestContext","isCustomRoutePublic","coreAuthMiddleware","serializeCookie","generateOpenAPIDocument","SERVER_ROUTES","convertCustomRoutesToOpenAPIPaths","MastraServerBase","redactStreamChunk","serializeStreamChunk","normalizeQueryParams","isSafeObjectKey","toReqRes","applyMcpRequestAuth","toFetchResponse","isZodError","checkRouteFGA","getCustomHTTPExceptionResponse","getHTTPErrorResponse"],"sources":["../src/auth-middleware.ts","../src/helper.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport { serializeCookie } from 'elysia/cookies';\n\nexport interface ElysiaAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\n// Refreshed session headers from an allowed request, applied to the final response by applyAuthRefreshHeaders.\nconst pendingRefreshHeaders = new WeakMap<Request, Record<string, string>>();\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ElysiaAuthMiddlewareOptions): (ctx: any) => Promise<globalThis.Response | void> {\n return async (ctx: any) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n ctx.requestContext ??= new RequestContext();\n ctx.mastra ??= mastra;\n\n const url = new URL(ctx.request.url);\n const path = url.pathname;\n const method = ctx.request.method;\n const customRouteAuthConfig = new Map<string, boolean>(ctx.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = ctx.request.headers.get('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && ctx.query?.apiKey) {\n token = ctx.query.apiKey;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => ctx.request.headers.get(name) || undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: ctx.requestContext,\n rawRequest: ctx.request,\n token,\n buildAuthorizeContext: () => ctx,\n });\n\n if (result.action === 'error') {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n appendHeaders(headers, result.headers);\n return new Response(JSON.stringify(result.body), { status: result.status, headers });\n }\n\n if (result.headers && Object.keys(result.headers).length > 0) {\n pendingRefreshHeaders.set(ctx.request, result.headers);\n }\n };\n}\n\n/**\n * Elysia `onAfterHandle` and `onError` hook that forwards session headers refreshed by\n * `createAuthMiddleware` onto the final response, including responses for handlers that throw. `Set-Cookie` values are appended alongside any cookies the app set\n * (via `ctx.cookie`, `set.headers`, or a returned `Response`) so none of them are dropped.\n */\nexport function applyAuthRefreshHeaders(ctx: any): globalThis.Response | void {\n const refreshHeaders = pendingRefreshHeaders.get(ctx.request);\n if (!refreshHeaders) {\n return;\n }\n pendingRefreshHeaders.delete(ctx.request);\n\n const set = ctx.set;\n const appCookies = takeSetSideCookies(set);\n const response = ctx.response;\n\n if (response instanceof Response) {\n const headers = new Headers(response.headers);\n for (const cookie of appCookies) {\n headers.append('set-cookie', cookie);\n }\n appendHeaders(headers, refreshHeaders);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n\n const cookies = [...appCookies];\n for (const [key, value] of Object.entries(refreshHeaders)) {\n if (key.toLowerCase() === 'set-cookie') {\n cookies.push(value);\n } else if (set.headers instanceof Headers) {\n set.headers.set(key, value);\n } else {\n set.headers[key] = value;\n }\n }\n if (cookies.length === 0) {\n return;\n }\n if (set.headers instanceof Headers) {\n for (const cookie of cookies) {\n set.headers.append('set-cookie', cookie);\n }\n } else {\n set.headers['set-cookie'] = cookies;\n }\n}\n\nfunction appendHeaders(headers: Headers, extra: Record<string, string> | undefined): void {\n for (const [key, value] of Object.entries(extra ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n headers.append(key, value);\n } else {\n headers.set(key, value);\n }\n }\n}\n\n/**\n * Removes and returns cookies queued on Elysia's `set` (both `set.cookie` and raw `set-cookie` headers).\n * Elysia overwrites raw `set-cookie` headers with `set.cookie`, and drops set-side cookies when the\n * returned `Response` already has one, so they are collected here and re-emitted explicitly.\n */\nfunction takeSetSideCookies(set: any): string[] {\n const cookies: string[] = [];\n\n if (set.headers instanceof Headers) {\n cookies.push(...set.headers.getSetCookie());\n set.headers.delete('set-cookie');\n } else if (set.headers) {\n for (const key of Object.keys(set.headers)) {\n if (key.toLowerCase() !== 'set-cookie') continue;\n const value = set.headers[key];\n cookies.push(...(Array.isArray(value) ? value : [value]));\n delete set.headers[key];\n }\n }\n\n const serialized = serializeCookie(set.cookie);\n if (serialized) {\n cookies.push(...(Array.isArray(serialized) ? serialized : [serialized]));\n }\n for (const key of Object.keys(set.cookie ?? {})) {\n delete set.cookie[key];\n }\n\n return cookies;\n}\n","import {\n generateOpenAPIDocument,\n convertCustomRoutesToOpenAPIPaths,\n SERVER_ROUTES,\n} from '@mastra/server/server-adapter';\nimport type { MastraServer } from './index';\n\n/**\n * OpenAPI documentation cache to avoid regenerating on each call.\n * Uses WeakMap to prevent cache collisions between server instances.\n */\nconst openapiDocCache = new WeakMap<\n MastraServer,\n {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n }\n>();\n\n/**\n * Get OpenAPI documentation from a MastraServer instance, formatted for Elysia's openapi plugin.\n *\n * This function:\n * - Extracts all Mastra routes with their Zod schemas\n * - Converts them to OpenAPI 3.1.0 format\n * - Merges custom routes if registered\n * - Applies the configured route prefix to all paths\n * - Caches the result for performance\n *\n * @param server - The MastraServer instance (must be initialized with init())\n * @param options - Optional configuration for OpenAPI metadata\n * @returns OpenAPI documentation with paths, components, and info\n *\n * @example\n * ```typescript\n * import { getMastraOpenAPIDoc } from '@mastra/elysia';\n *\n * const srv = new MastraServer({ mastra, app, prefix: '/api' });\n * await srv.init();\n *\n * const openAPIDoc = getMastraOpenAPIDoc(srv, {\n * title: 'My Mastra API',\n * version: '1.0.0',\n * description: 'API with weather agent'\n * });\n *\n * app.use(openapi({\n * documentation: {\n * info: openAPIDoc.info,\n * paths: openAPIDoc.paths,\n * components: openAPIDoc.components\n * }\n * }));\n * ```\n */\nexport function getMastraOpenAPIDoc(\n server: MastraServer,\n options?: {\n title?: string;\n version?: string;\n description?: string;\n clearCache?: boolean;\n },\n): {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n} {\n // Clear cache if requested\n if (options?.clearCache) {\n openapiDocCache.delete(server);\n }\n\n // Return cached result if available\n const cached = openapiDocCache.get(server);\n if (cached) {\n // Merge custom info if provided\n if (options) {\n return {\n ...cached,\n info: {\n ...cached.info,\n ...(options.title && { title: options.title }),\n ...(options.version && { version: options.version }),\n ...(options.description && { description: options.description }),\n },\n };\n }\n return cached;\n }\n\n // Generate complete OpenAPI spec from Mastra's route definitions\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, {\n title: options?.title || 'Mastra API',\n version: options?.version || '1.0.0',\n description: options?.description || 'Mastra Server API',\n });\n\n // Merge custom API routes if present\n const customApiRoutes = (server as any).customApiRoutes;\n if (customApiRoutes && customApiRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n const customPaths = convertCustomRoutesToOpenAPIPaths(customApiRoutes, componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n let paths = openApiSpec.paths || {};\n\n // Apply prefix transformation if configured\n const prefix = (server as any).prefix;\n if (prefix && prefix !== '/') {\n const prefixedPaths: Record<string, any> = {};\n for (const [path, pathItem] of Object.entries(paths)) {\n // Combine prefix with path, ensuring no double slashes\n const prefixedPath = `${prefix}${path}`.replace(/\\/+/g, '/');\n prefixedPaths[prefixedPath] = pathItem;\n }\n paths = prefixedPaths;\n }\n\n const result = {\n paths,\n components: openApiSpec.components,\n info: openApiSpec.info,\n };\n\n // Cache the result\n openapiDocCache.set(server, result);\n\n return result;\n}\n\n/**\n * Clear the OpenAPI documentation cache.\n * Call this if routes are added dynamically after initialization.\n *\n * `@param` server - The MastraServer instance to clear cache for.\n * Note: WeakMap does not support clearing all entries. Pass the specific server instance whose cache should be invalidated.\n */\nexport function clearMastraOpenAPICache(server?: MastraServer): void {\n if (server) {\n openapiDocCache.delete(server);\n }\n // Cannot clear all entries in WeakMap - they will be garbage collected when servers are released\n}\n","import type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n propagateRequestAbort,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { AnyElysia, MaybePromise } from 'elysia';\nimport type Elysia from 'elysia';\nimport { toReqRes, toFetchResponse } from 'fetch-to-node';\nimport { applyAuthRefreshHeaders } from './auth-middleware';\nexport { applyAuthRefreshHeaders, createAuthMiddleware } from './auth-middleware';\nexport type { ElysiaAuthMiddlewareOptions } from './auth-middleware';\n\n// Export helper functions for OpenAPI integration\nexport { getMastraOpenAPIDoc, clearMastraOpenAPICache } from './helper';\n\nconst BODY_TOO_LARGE = Symbol('mastra.elysia.bodyTooLarge');\nconst EMPTY_JSON_BODY = Symbol('mastra.elysia.emptyJsonBody');\n\nclass InvalidJsonBody {\n constructor(readonly message: string) {}\n}\n\nasync function readBodyWithLimit(body: ReadableStream<Uint8Array>, maxSize: number): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxSize) {\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Route-level Elysia parse hook for body methods.\n *\n * Parses JSON bodies itself: under `@elysiajs/node` an empty request still has a body stream, so Elysia's default\n * JSON parser throws on it and the request fails with 400 before the route runs. An empty JSON body comes back as\n * EMPTY_JSON_BODY and malformed JSON as InvalidJsonBody, both resolved by the route handler.\n *\n * With a `maxSize`, also enforces the body limit before anything buffers the request. Oversized bodies are marked\n * with BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.\n */\nfunction createBodyParser(maxSize: number | undefined) {\n return async (ctx: any) => {\n const request: Request = ctx.request;\n const contentLength = request.headers.get('content-length');\n // Reject a declared oversized body without reading it. A declared size within\n // the limit is still read with the cap, since app.handle() accepts a Request\n // whose stream need not match its Content-Length header.\n if (maxSize !== undefined && contentLength !== null && parseInt(contentLength, 10) > maxSize) {\n return BODY_TOO_LARGE;\n }\n\n const isJson = (request.headers.get('content-type') ?? '').includes('application/json');\n if (!request.body || (!isJson && maxSize === undefined)) return undefined;\n\n const bytes =\n maxSize === undefined\n ? new Uint8Array(await request.arrayBuffer())\n : await readBodyWithLimit(request.body, maxSize);\n if (!bytes) return BODY_TOO_LARGE;\n\n if (isJson) {\n const text = new TextDecoder().decode(bytes);\n if (text.trim().length === 0) return EMPTY_JSON_BODY;\n try {\n return JSON.parse(text);\n } catch (error) {\n return new InvalidJsonBody(error instanceof Error ? error.message : 'Invalid JSON in request body');\n }\n }\n\n // Hand the bounded body back to Elysia's default parsers.\n ctx.request = new Request(request.url, {\n method: request.method,\n headers: request.headers,\n body: bytes,\n signal: request.signal,\n });\n return undefined;\n };\n}\n\n/**\n * Normalizes route path parameters to position-based names (:p0, :p1, ...)\n * to avoid Elysia router conflicts when different routes use different\n * parameter names at the same path segment position (e.g. :agentId vs\n * :storedAgentId under /stored/agents/...).\n * Returns the normalized path and the original parameter names in order.\n */\nfunction normalizeRouteParams(path: string): { normalizedPath: string; paramNames: string[] } {\n const paramNames: string[] = [];\n const normalizedPath = path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName: string) => {\n paramNames.push(paramName);\n return `:p${paramNames.length - 1}`;\n });\n return { normalizedPath, paramNames };\n}\n\n/**\n * Reads query params keeping every value of a repeated key (`?tag=a&tag=b` -> `{ tag: ['a', 'b'] }`), as the\n * other adapters do; Elysia's `ctx.query` and `Object.fromEntries` keep only one.\n */\nfunction searchParamsToQuery(searchParams: URLSearchParams): Record<string, string | string[]> {\n const query: Record<string, string | string[]> = {};\n for (const key of new Set(searchParams.keys())) {\n const values = searchParams.getAll(key);\n query[key] = values.length === 1 ? (values[0] as string) : values;\n }\n return query;\n}\n\n/**\n * Remaps Elysia's parsed params from position-based names (p0, p1, ...)\n * back to the original parameter names expected by the route handler.\n */\nfunction remapParams(rawParams: Record<string, string>, paramNames: string[]): Record<string, string> {\n if (paramNames.length === 0) return rawParams;\n const result: Record<string, string> = {};\n paramNames.forEach((paramName, i) => {\n const key = `p${i}`;\n if (key in rawParams) {\n result[paramName] = rawParams[key] as string;\n }\n });\n return result;\n}\n\nasync function createForwardRequest(ctx: any): Promise<Request> {\n const request = ctx.request as Request;\n const method = request.method;\n\n if (method === 'GET' || method === 'HEAD') {\n return request;\n }\n\n const headers = new Headers(request.headers);\n let body: any;\n\n if (ctx.body !== undefined) {\n if (typeof ctx.body === 'string' || ctx.body instanceof FormData || ctx.body instanceof Blob) {\n body = ctx.body;\n } else {\n body = JSON.stringify(ctx.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n } else if (!request.bodyUsed) {\n const bodyBuffer = await request.clone().arrayBuffer();\n if (bodyBuffer.byteLength > 0) {\n body = bodyBuffer;\n }\n }\n\n headers.delete('content-length');\n\n return new Request(request.url, {\n method,\n headers,\n body,\n signal: request.signal,\n ...(body ? { duplex: 'half' as const } : {}),\n } as RequestInit);\n}\n\n/**\n * srvx, which runs `@elysiajs/node`, creates `request.signal` on first access and only then listens for the response\n * 'close'. A client that left during an earlier hook therefore never aborts it, so check the Node response directly.\n */\nfunction getRequestAbortSignal(request: Request): AbortSignal {\n const signal = request.signal;\n const nodeRes = (request as { runtime?: { node?: { res?: { destroyed?: boolean } } } }).runtime?.node?.res;\n return nodeRes?.destroyed && !signal.aborted ? AbortSignal.abort() : signal;\n}\n\nfunction getRequestSignal(ctx: unknown): AbortSignal | undefined {\n const context = ctx as { abortSignal?: AbortSignal; request?: Request } | undefined;\n return context?.abortSignal ?? (context?.request ? getRequestAbortSignal(context.request) : undefined);\n}\n\n/**\n * Cancels `reader` once, through `cancel()` or when the request signal aborts. A runtime that skips the response body\n * of a request that closed while the route handler ran never cancels that body, so the signal is the only notice.\n */\nfunction cancelReaderOnRequestAbort(\n reader: ReadableStreamDefaultReader<unknown>,\n signal: AbortSignal | undefined,\n): { cancel: (reason?: unknown) => void; dispose: () => void } {\n let canceled = false;\n const onAbort = () => cancel('request aborted');\n const dispose = () => signal?.removeEventListener('abort', onAbort);\n const cancel = (reason?: unknown) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n dispose();\n void reader.cancel(reason).catch(() => {});\n };\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return { cancel, dispose };\n}\n\nfunction createSafeReadableStream(body: ReadableStream<Uint8Array> | null): ReadableStream<Uint8Array> | null {\n if (!body) return null;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const reader = body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n controller.enqueue(value);\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n } finally {\n controller.close();\n reader.releaseLock();\n }\n },\n });\n}\n\n/**\n * Wraps a `datastream-response` body so a client disconnect cancels the upstream body. Unlike\n * `createSafeReadableStream`, it reads one chunk per pull, so a slow client slows the upstream.\n */\nfunction createDatastreamBody(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal | undefined,\n): ReadableStream<Uint8Array> | null {\n if (!body) {\n return null;\n }\n\n const reader = body.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, signal);\n let finished = false;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (!done) {\n controller.enqueue(value);\n return;\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n if (finished) {\n return;\n }\n }\n\n finished = true;\n upstream.dispose();\n controller.close();\n },\n cancel(reason) {\n finished = true;\n upstream.cancel(reason);\n },\n });\n}\n\n// Export type definitions for Elysia app configuration\nexport interface ElysiaContext {\n mastra: Mastra;\n requestContext: RequestContext;\n registeredTools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n}\n\n/**\n * Minimal interface representing what MastraServer needs from an Elysia app.\n * This allows any Elysia app instance to be passed without strict generic matching.\n */\nexport interface ElysiaApp {\n use(instance: MaybePromise<AnyElysia>): ElysiaApp;\n derive(callback: (context: any) => any | Promise<any>): ElysiaApp;\n get(path: string, handler: any, options?: any): ElysiaApp;\n post(path: string, handler: any, options?: any): ElysiaApp;\n put(path: string, handler: any, options?: any): ElysiaApp;\n delete(path: string, handler: any, options?: any): ElysiaApp;\n patch(path: string, handler: any, options?: any): ElysiaApp;\n all(path: string, handler: any, options?: any): ElysiaApp;\n onAfterHandle(handler: (context: any) => any): ElysiaApp;\n onError(handler: (context: any) => any): ElysiaApp;\n}\n\nexport class MastraServer extends MastraServerBase<Elysia, Request, Response> {\n createContextMiddleware() {\n return async (ctx: any) => {\n // Parse request context from request body and query params\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT/PATCH)\n if (ctx.request.method === 'POST' || ctx.request.method === 'PUT' || ctx.request.method === 'PATCH') {\n const contentType = ctx.request.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n try {\n const body = (ctx.body ?? (await ctx.request.clone().json())) as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n } catch {\n // Body parsing failed, continue without body\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (ctx.request.method === 'GET') {\n try {\n // Elysia pre-parses query params into ctx.query\n const encodedRequestContext = ctx.query?.requestContext;\n if (encodedRequestContext) {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n });\n\n // Add relevant contexts to Elysia context\n return {\n requestContext,\n mastra: this.mastra,\n registeredTools: this.tools || {},\n taskStore: this.taskStore,\n abortSignal: getRequestAbortSignal(ctx.request),\n customRouteAuthConfig: this.customRouteAuthConfig,\n };\n };\n }\n\n async stream(route: ServerRoute, ctx: Response, result: { fullStream: ReadableStream }): Promise<any> {\n const streamFormat = route.streamFormat || 'stream';\n const encoder = new TextEncoder();\n\n const headers: Record<string, string> =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, getRequestSignal(ctx));\n // Set once the controller is closed, errored or cancelled; nothing may be enqueued from then on.\n let finished = false;\n\n // Reads one upstream chunk per pull so a slow client slows the upstream instead of buffering it here.\n const stream = new ReadableStream({\n start: controller => {\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n controller.enqueue(encoder.encode(': connected\\n\\n'));\n }\n },\n pull: async controller => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (done) {\n finished = true;\n upstream.dispose();\n\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n }\n\n controller.close();\n return;\n }\n\n if (!value) {\n continue;\n }\n\n // SSE comment passthrough — strings starting with ':' are written as-is\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n controller.enqueue(encoder.encode(value));\n return;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode(`data: ${serialized.json}\\n\\n`));\n } else {\n controller.enqueue(encoder.encode(serialized.json + '\\x1E'));\n }\n return;\n }\n } catch (error) {\n if (finished) {\n return;\n }\n\n finished = true;\n upstream.dispose();\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Close instead of erroring: @elysiajs/node destroys the socket on an errored body, dropping the frames\n // already enqueued and, for an early error, the status line too.\n controller.close();\n }\n },\n cancel: reason => {\n finished = true;\n upstream.cancel(reason);\n },\n });\n\n return new Response(stream, { headers });\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const url = new URL(request.url);\n\n // URL params - extract from request context if available (Elysia stores params in ctx)\n // Params may be normalized (p0, p1, ...) — remap back to original names from route path\n const { paramNames } = normalizeRouteParams(route.path);\n const rawUrlParams: Record<string, string> = (request as any).params || (request as any).ctx?.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawUrlParams, paramNames) : rawUrlParams;\n\n // Query params - parse from URL\n const queryParams = normalizeQueryParams(searchParamsToQuery(url.searchParams));\n\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const formData = await request.formData();\n body = await this.parseFormData(formData);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n const clonedReq = request.clone();\n const bodyText = await clonedReq.text();\n\n if (bodyText && bodyText.trim().length > 0) {\n try {\n body = JSON.parse(bodyText);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Invalid JSON in request body',\n };\n }\n }\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse FormData into a plain object, converting File objects to Buffers.\n * Handles both native FormData and Elysia's pre-parsed object format.\n */\n private async parseFormData(data: FormData | Record<string, unknown>): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {};\n\n // Handle native FormData\n if (data instanceof FormData) {\n for (const [key, value] of data.entries()) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value instanceof File) {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n // Try to parse JSON strings (like 'options')\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n // Handle Elysia's pre-parsed object format\n for (const [key, value] of Object.entries(data)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value && typeof value === 'object' && 'arrayBuffer' in value && typeof value.arrayBuffer === 'function') {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n /** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */\n private resolveMcpOptions() {\n return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;\n }\n\n async sendResponse(route: ServerRoute, response: Response, result: unknown, prefix?: string): Promise<any> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n const refreshHeaders: Record<string, string> = {};\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const headers = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(headers)) {\n refreshHeaders[key] = value;\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json', ...refreshHeaders },\n });\n } else if (route.responseType === 'stream') {\n return this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n const fetchResponse = result as globalThis.Response;\n const headers = new Headers(fetchResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createDatastreamBody(fetchResponse.body, getRequestSignal(response)), {\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n const { setRequestAuth, ...options } = { ...this.resolveMcpOptions(), ...routeMcpOptions };\n\n // `toReqRes` builds a fresh IncomingMessage, so bridge the principal auth resolved.\n await applyMcpRequestAuth({ req, requestContext: request.requestContext, setRequestAuth });\n\n // Do NOT await startHTTP — let it run in the background so SSE\n // notifications stream to the client as they are written.\n // toFetchResponse resolves when headers are sent, not when the body finishes.\n server\n .startHTTP({\n url: new URL(forwardRequest.url),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req,\n res,\n options: Object.keys(options).length > 0 ? options : undefined,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP HTTP] Error in background startHTTP:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n // `createForwardRequest` rebuilds the Request without a signal, so listen on the\n // original one: a client disconnect must abort the in-flight MCP request.\n propagateRequestAbort((request.request as Request).signal, res);\n\n const mcpResponse = await toFetchResponse(res);\n const headers = new Headers(mcpResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(mcpResponse.body), {\n status: mcpResponse.status,\n statusText: mcpResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-sse') {\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n await applyMcpRequestAuth({\n req,\n requestContext: request.requestContext,\n setRequestAuth: this.resolveMcpOptions()?.setRequestAuth,\n });\n\n server\n .startSSE({\n url: new URL(forwardRequest.url),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req,\n res,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP SSE] Error in background startSSE:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n const sseResponse = await toFetchResponse(res);\n const headers = new Headers(sseResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(sseResponse.body), {\n status: sseResponse.status,\n statusText: sseResponse.statusText,\n headers,\n });\n }\n return new Response(null, { status: 500 });\n }\n\n async registerRoute(\n app: ElysiaApp,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n const prefix = prefixParam ?? this.prefix ?? '';\n const fullPath = `${prefix}${route.path}`;\n const { normalizedPath, paramNames } = normalizeRouteParams(fullPath);\n\n const handler = async (ctx: any) => {\n // Reject oversized bodies before auth, matching adapters that enforce the limit in middleware.\n if (ctx.body === BODY_TOO_LARGE) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default error response.\n }\n }\n return new Response(JSON.stringify(errorResponse), {\n status: 413,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: ctx.request.url ? new URL(ctx.request.url).pathname : ctx.path,\n method: ctx.request.method,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check route permission (RBAC). Elysia checks it before schema validation.\n const permissionError = this.checkRouteRBAC(route, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Extract params - remap from normalized param names back to original\n const rawParams = ctx.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;\n const queryParams = normalizeQueryParams(searchParamsToQuery(new URL(ctx.request.url).searchParams));\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = ctx.request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n // Elysia pre-parses multipart form data\n body = ctx.body ? await this.parseFormData(ctx.body) : undefined;\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n // Parsed by the route's parse hook (createBodyParser)\n if (ctx.body instanceof InvalidJsonBody) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', { error: { message: ctx.body.message } });\n bodyParseError = { message: ctx.body.message };\n } else if (ctx.body !== EMPTY_JSON_BODY) {\n body = ctx.body;\n }\n // createForwardRequest (MCP routes) reads ctx.body later and must not see the parse hook's markers.\n ctx.body = body;\n }\n }\n\n const params = { urlParams, queryParams, body, bodyParseError };\n\n // Return 400 Bad Request if body parsing failed\n if (params.bodyParseError) {\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n const fgaError = await checkRouteFGA(this.mastra, route, ctx.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: ctx.requestContext,\n mastra: ctx.mastra,\n registeredTools: ctx.registeredTools,\n taskStore: ctx.taskStore,\n abortSignal: ctx.abortSignal,\n routePrefix: prefix,\n request: ctx.request,\n };\n\n try {\n const result = await route.handler(handlerParams);\n return this.sendResponse(route, ctx as any, result, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n // Client errors (4xx) are returned as structured responses below, so they aren't logged as server faults.\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n return customResponse;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n\n // Register the route using Elysia's method chaining\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method);\n if (isBodyMethod) {\n app[method](normalizedPath, handler, { parse: createBodyParser(maxSize) });\n } else {\n app[method](normalizedPath, handler);\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const { normalizedPath: customNormalizedPath } = normalizeRouteParams(route.path);\n (this.app as ElysiaApp)[method](customNormalizedPath, async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n const requestMethod = ctx.request.method;\n // Check auth against the custom route the custom-route app will actually run for\n // this URL, which can differ from the route Elysia matched.\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(ctx.request.url, requestMethod, path, route);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method: requestMethod,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n customRouteAuthConfig,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n const permissionError = this.checkRouteRBAC(serverRoute, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {\n ...(ctx.query as Record<string, string>),\n ...(typeof ctx.body === 'object' && ctx.body !== null ? ctx.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const headers: Record<string, string | string[] | undefined> = {};\n ctx.request.headers.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n\n const response = await this.handleCustomRouteRequest(\n ctx.request.url,\n ctx.request.method,\n headers,\n ctx.body,\n ctx.requestContext,\n ctx.request.signal,\n );\n\n if (!response) {\n return new Response(JSON.stringify({ error: 'Not Found' }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return response;\n });\n }\n }\n\n registerContextMiddleware(): void {\n this.app.derive(this.createContextMiddleware());\n this.app.onAfterHandle({ as: 'global' }, applyAuthRefreshHeaders);\n this.app.onError({ as: 'global' }, applyAuthRefreshHeaders);\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n\n // Register global error handler to catch Elysia body parsing errors\n // and return structured JSON responses instead of plain text \"Bad Request\"\n this.app.onError((ctx: any) => {\n const error = ctx.error;\n const status = error?.status ?? error?.code ?? 500;\n const message = error?.message ?? 'Internal server error';\n\n // Body parsing / validation errors from Elysia are 400s\n const httpStatus = typeof status === 'number' && status >= 400 && status < 500 ? status : 500;\n\n return new Response(\n JSON.stringify({\n error: httpStatus < 500 ? message : 'Internal server error',\n ...(httpStatus < 500 ? { issues: [] } : {}),\n }),\n {\n status: httpStatus,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n });\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.derive(async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return {};\n }\n\n return {\n httpLogStart: Date.now(),\n };\n });\n\n this.app.onAfterHandle((ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return;\n }\n\n const duration = Date.now() - (ctx.httpLogStart ?? Date.now());\n const method = ctx.request.method;\n const status = ctx.response?.status ?? ctx.set?.status ?? 200;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = ctx.query || {};\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = Object.fromEntries(ctx.request.headers.entries());\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n }\n}\n"],"mappings":";;;;;;;AAWA,MAAM,wCAAwB,IAAI,QAAyC;AAE3E,SAAgB,qBAAqB,EACnC,QACA,eAAe,QACkE;CACjF,OAAO,OAAO,QAAa;EACzB,IAAI,CAAC,cACH;EAGF,MAAM,aAAa,OAAO,UAAU,CAAC,EAAE;EACvC,IAAI,CAAC,YACH;EAGF,IAAI,mBAAmB,IAAIA,6BAAAA,eAAe;EAC1C,IAAI,WAAW;EAGf,MAAM,OAAO,IADG,IAAI,IAAI,QAAQ,GACjB,CAAC,CAAC;EACjB,MAAM,SAAS,IAAI,QAAQ;EAC3B,MAAM,wBAAwB,IAAI,IAAqB,IAAI,yBAAyB,CAAC,CAAC;EAEtF,IAAI,EAAA,GAACC,oBAAAA,oBAAAA,CAAoB,MAAM,QAAQ,qBAAqB,GAC1D,sBAAsB,IAAI,GAAG,OAAO,GAAG,QAAQ,IAAI;EAGrD,MAAM,aAAa,IAAI,QAAQ,QAAQ,IAAI,eAAe;EAC1D,IAAI,QAAuB,aAAa,WAAW,QAAQ,WAAW,EAAE,IAAI;EAC5E,IAAI,CAAC,SAAS,IAAI,OAAO,QACvB,QAAQ,IAAI,MAAM;EAGpB,MAAM,SAAS,OAAA,GAAMC,oBAAAA,mB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AG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;EACzE,CAAC;CACH;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export declare class MastraServer extends MastraServerBase<Elysia, Request, Resp
|
|
|
51
51
|
* Handles both native FormData and Elysia's pre-parsed object format.
|
|
52
52
|
*/
|
|
53
53
|
private parseFormData;
|
|
54
|
+
/** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */
|
|
55
|
+
private resolveMcpOptions;
|
|
54
56
|
sendResponse(route: ServerRoute, response: Response, result: unknown, prefix?: string): Promise<any>;
|
|
55
57
|
registerRoute(app: ElysiaApp, route: ServerRoute, { prefix: prefixParam }?: {
|
|
56
58
|
prefix?: string;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EACL,YAAY,IAAI,gBAAgB,EAWjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAGjC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAClF,YAAY,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAGrE,OAAO,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAA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IA+C3B,0FAA0F;IAC1F,OAAO,CAAC,iBAAiB;IAInB,YAAY,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CA2GzG;IAEK,aAAa,CACjB,GAAG,EAAE,SAAS,EACd,KAAK,EAAE,WAAW,EAClB,EAAE,MAAM,EAAE,WAAW,EAAE,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO,GAChD,OAAO,CAAC,IAAI,CAAC,CA0Pf;IAEK,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC,CAwF7C;IAED,yBAAyB,IAAI,IAAI,CAIhC;IAED,sBAAsB,IAAI,IAAI,CAyB7B;IAED,6BAA6B,IAAI,IAAI,CAoDpC;CACF"}
|
package/dist/index.js
CHANGED
|
@@ -414,13 +414,6 @@ function createDatastreamBody(body, signal) {
|
|
|
414
414
|
}
|
|
415
415
|
});
|
|
416
416
|
}
|
|
417
|
-
let _hasPermissionPromise;
|
|
418
|
-
function loadHasPermission() {
|
|
419
|
-
if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
|
|
420
|
-
console.error("[@mastra/elysia] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest");
|
|
421
|
-
});
|
|
422
|
-
return _hasPermissionPromise;
|
|
423
|
-
}
|
|
424
417
|
var MastraServer = class extends MastraServer$1 {
|
|
425
418
|
createContextMiddleware() {
|
|
426
419
|
return async (ctx) => {
|
|
@@ -602,6 +595,10 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
602
595
|
}
|
|
603
596
|
return result;
|
|
604
597
|
}
|
|
598
|
+
/** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */
|
|
599
|
+
resolveMcpOptions() {
|
|
600
|
+
return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;
|
|
601
|
+
}
|
|
605
602
|
async sendResponse(route, response, result, prefix) {
|
|
606
603
|
const resolvedPrefix = prefix ?? this.prefix ?? "";
|
|
607
604
|
const refreshHeaders = {};
|
|
@@ -633,7 +630,7 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
633
630
|
const forwardRequest = await createForwardRequest(request);
|
|
634
631
|
const { req, res } = toReqRes(forwardRequest);
|
|
635
632
|
const { setRequestAuth, ...options } = {
|
|
636
|
-
...this.
|
|
633
|
+
...this.resolveMcpOptions(),
|
|
637
634
|
...routeMcpOptions
|
|
638
635
|
};
|
|
639
636
|
await applyMcpRequestAuth({
|
|
@@ -670,7 +667,7 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
670
667
|
await applyMcpRequestAuth({
|
|
671
668
|
req,
|
|
672
669
|
requestContext: request.requestContext,
|
|
673
|
-
setRequestAuth: this.
|
|
670
|
+
setRequestAuth: this.resolveMcpOptions()?.setRequestAuth
|
|
674
671
|
});
|
|
675
672
|
server.startSSE({
|
|
676
673
|
url: new URL(forwardRequest.url),
|
|
@@ -725,20 +722,14 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
725
722
|
...authError.headers
|
|
726
723
|
}
|
|
727
724
|
});
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
}), {
|
|
737
|
-
status: permissionError.status,
|
|
738
|
-
headers: { "Content-Type": "application/json" }
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
}
|
|
725
|
+
const permissionError = this.checkRouteRBAC(route, ctx.requestContext);
|
|
726
|
+
if (permissionError) return new Response(JSON.stringify({
|
|
727
|
+
error: permissionError.error,
|
|
728
|
+
message: permissionError.message
|
|
729
|
+
}), {
|
|
730
|
+
status: permissionError.status,
|
|
731
|
+
headers: { "Content-Type": "application/json" }
|
|
732
|
+
});
|
|
742
733
|
const rawParams = ctx.params || {};
|
|
743
734
|
const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;
|
|
744
735
|
const queryParams = normalizeQueryParams(searchParamsToQuery(new URL(ctx.request.url).searchParams));
|
|
@@ -944,20 +935,14 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
944
935
|
...authError.headers
|
|
945
936
|
}
|
|
946
937
|
});
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
}), {
|
|
956
|
-
status: permissionError.status,
|
|
957
|
-
headers: { "Content-Type": "application/json" }
|
|
958
|
-
});
|
|
959
|
-
}
|
|
960
|
-
}
|
|
938
|
+
const permissionError = this.checkRouteRBAC(serverRoute, ctx.requestContext);
|
|
939
|
+
if (permissionError) return new Response(JSON.stringify({
|
|
940
|
+
error: permissionError.error,
|
|
941
|
+
message: permissionError.message
|
|
942
|
+
}), {
|
|
943
|
+
status: permissionError.status,
|
|
944
|
+
headers: { "Content-Type": "application/json" }
|
|
945
|
+
});
|
|
961
946
|
}
|
|
962
947
|
const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {
|
|
963
948
|
...ctx.query,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["MastraServerBase"],"sources":["../src/auth-middleware.ts","../src/helper.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport { serializeCookie } from 'elysia/cookies';\n\nexport interface ElysiaAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\n// Refreshed session headers from an allowed request, applied to the final response by applyAuthRefreshHeaders.\nconst pendingRefreshHeaders = new WeakMap<Request, Record<string, string>>();\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ElysiaAuthMiddlewareOptions): (ctx: any) => Promise<globalThis.Response | void> {\n return async (ctx: any) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n ctx.requestContext ??= new RequestContext();\n ctx.mastra ??= mastra;\n\n const url = new URL(ctx.request.url);\n const path = url.pathname;\n const method = ctx.request.method;\n const customRouteAuthConfig = new Map<string, boolean>(ctx.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = ctx.request.headers.get('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && ctx.query?.apiKey) {\n token = ctx.query.apiKey;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => ctx.request.headers.get(name) || undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: ctx.requestContext,\n rawRequest: ctx.request,\n token,\n buildAuthorizeContext: () => ctx,\n });\n\n if (result.action === 'error') {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n appendHeaders(headers, result.headers);\n return new Response(JSON.stringify(result.body), { status: result.status, headers });\n }\n\n if (result.headers && Object.keys(result.headers).length > 0) {\n pendingRefreshHeaders.set(ctx.request, result.headers);\n }\n };\n}\n\n/**\n * Elysia `onAfterHandle` and `onError` hook that forwards session headers refreshed by\n * `createAuthMiddleware` onto the final response, including responses for handlers that throw. `Set-Cookie` values are appended alongside any cookies the app set\n * (via `ctx.cookie`, `set.headers`, or a returned `Response`) so none of them are dropped.\n */\nexport function applyAuthRefreshHeaders(ctx: any): globalThis.Response | void {\n const refreshHeaders = pendingRefreshHeaders.get(ctx.request);\n if (!refreshHeaders) {\n return;\n }\n pendingRefreshHeaders.delete(ctx.request);\n\n const set = ctx.set;\n const appCookies = takeSetSideCookies(set);\n const response = ctx.response;\n\n if (response instanceof Response) {\n const headers = new Headers(response.headers);\n for (const cookie of appCookies) {\n headers.append('set-cookie', cookie);\n }\n appendHeaders(headers, refreshHeaders);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n\n const cookies = [...appCookies];\n for (const [key, value] of Object.entries(refreshHeaders)) {\n if (key.toLowerCase() === 'set-cookie') {\n cookies.push(value);\n } else if (set.headers instanceof Headers) {\n set.headers.set(key, value);\n } else {\n set.headers[key] = value;\n }\n }\n if (cookies.length === 0) {\n return;\n }\n if (set.headers instanceof Headers) {\n for (const cookie of cookies) {\n set.headers.append('set-cookie', cookie);\n }\n } else {\n set.headers['set-cookie'] = cookies;\n }\n}\n\nfunction appendHeaders(headers: Headers, extra: Record<string, string> | undefined): void {\n for (const [key, value] of Object.entries(extra ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n headers.append(key, value);\n } else {\n headers.set(key, value);\n }\n }\n}\n\n/**\n * Removes and returns cookies queued on Elysia's `set` (both `set.cookie` and raw `set-cookie` headers).\n * Elysia overwrites raw `set-cookie` headers with `set.cookie`, and drops set-side cookies when the\n * returned `Response` already has one, so they are collected here and re-emitted explicitly.\n */\nfunction takeSetSideCookies(set: any): string[] {\n const cookies: string[] = [];\n\n if (set.headers instanceof Headers) {\n cookies.push(...set.headers.getSetCookie());\n set.headers.delete('set-cookie');\n } else if (set.headers) {\n for (const key of Object.keys(set.headers)) {\n if (key.toLowerCase() !== 'set-cookie') continue;\n const value = set.headers[key];\n cookies.push(...(Array.isArray(value) ? value : [value]));\n delete set.headers[key];\n }\n }\n\n const serialized = serializeCookie(set.cookie);\n if (serialized) {\n cookies.push(...(Array.isArray(serialized) ? serialized : [serialized]));\n }\n for (const key of Object.keys(set.cookie ?? {})) {\n delete set.cookie[key];\n }\n\n return cookies;\n}\n","import {\n generateOpenAPIDocument,\n convertCustomRoutesToOpenAPIPaths,\n SERVER_ROUTES,\n} from '@mastra/server/server-adapter';\nimport type { MastraServer } from './index';\n\n/**\n * OpenAPI documentation cache to avoid regenerating on each call.\n * Uses WeakMap to prevent cache collisions between server instances.\n */\nconst openapiDocCache = new WeakMap<\n MastraServer,\n {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n }\n>();\n\n/**\n * Get OpenAPI documentation from a MastraServer instance, formatted for Elysia's openapi plugin.\n *\n * This function:\n * - Extracts all Mastra routes with their Zod schemas\n * - Converts them to OpenAPI 3.1.0 format\n * - Merges custom routes if registered\n * - Applies the configured route prefix to all paths\n * - Caches the result for performance\n *\n * @param server - The MastraServer instance (must be initialized with init())\n * @param options - Optional configuration for OpenAPI metadata\n * @returns OpenAPI documentation with paths, components, and info\n *\n * @example\n * ```typescript\n * import { getMastraOpenAPIDoc } from '@mastra/elysia';\n *\n * const srv = new MastraServer({ mastra, app, prefix: '/api' });\n * await srv.init();\n *\n * const openAPIDoc = getMastraOpenAPIDoc(srv, {\n * title: 'My Mastra API',\n * version: '1.0.0',\n * description: 'API with weather agent'\n * });\n *\n * app.use(openapi({\n * documentation: {\n * info: openAPIDoc.info,\n * paths: openAPIDoc.paths,\n * components: openAPIDoc.components\n * }\n * }));\n * ```\n */\nexport function getMastraOpenAPIDoc(\n server: MastraServer,\n options?: {\n title?: string;\n version?: string;\n description?: string;\n clearCache?: boolean;\n },\n): {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n} {\n // Clear cache if requested\n if (options?.clearCache) {\n openapiDocCache.delete(server);\n }\n\n // Return cached result if available\n const cached = openapiDocCache.get(server);\n if (cached) {\n // Merge custom info if provided\n if (options) {\n return {\n ...cached,\n info: {\n ...cached.info,\n ...(options.title && { title: options.title }),\n ...(options.version && { version: options.version }),\n ...(options.description && { description: options.description }),\n },\n };\n }\n return cached;\n }\n\n // Generate complete OpenAPI spec from Mastra's route definitions\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, {\n title: options?.title || 'Mastra API',\n version: options?.version || '1.0.0',\n description: options?.description || 'Mastra Server API',\n });\n\n // Merge custom API routes if present\n const customApiRoutes = (server as any).customApiRoutes;\n if (customApiRoutes && customApiRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n const customPaths = convertCustomRoutesToOpenAPIPaths(customApiRoutes, componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n let paths = openApiSpec.paths || {};\n\n // Apply prefix transformation if configured\n const prefix = (server as any).prefix;\n if (prefix && prefix !== '/') {\n const prefixedPaths: Record<string, any> = {};\n for (const [path, pathItem] of Object.entries(paths)) {\n // Combine prefix with path, ensuring no double slashes\n const prefixedPath = `${prefix}${path}`.replace(/\\/+/g, '/');\n prefixedPaths[prefixedPath] = pathItem;\n }\n paths = prefixedPaths;\n }\n\n const result = {\n paths,\n components: openApiSpec.components,\n info: openApiSpec.info,\n };\n\n // Cache the result\n openapiDocCache.set(server, result);\n\n return result;\n}\n\n/**\n * Clear the OpenAPI documentation cache.\n * Call this if routes are added dynamically after initialization.\n *\n * `@param` server - The MastraServer instance to clear cache for.\n * Note: WeakMap does not support clearing all entries. Pass the specific server instance whose cache should be invalidated.\n */\nexport function clearMastraOpenAPICache(server?: MastraServer): void {\n if (server) {\n openapiDocCache.delete(server);\n }\n // Cannot clear all entries in WeakMap - they will be garbage collected when servers are released\n}\n","import type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n propagateRequestAbort,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { AnyElysia, MaybePromise } from 'elysia';\nimport type Elysia from 'elysia';\nimport { toReqRes, toFetchResponse } from 'fetch-to-node';\nimport { applyAuthRefreshHeaders } from './auth-middleware';\nexport { applyAuthRefreshHeaders, createAuthMiddleware } from './auth-middleware';\nexport type { ElysiaAuthMiddlewareOptions } from './auth-middleware';\n\n// Export helper functions for OpenAPI integration\nexport { getMastraOpenAPIDoc, clearMastraOpenAPICache } from './helper';\n\nconst BODY_TOO_LARGE = Symbol('mastra.elysia.bodyTooLarge');\nconst EMPTY_JSON_BODY = Symbol('mastra.elysia.emptyJsonBody');\n\nclass InvalidJsonBody {\n constructor(readonly message: string) {}\n}\n\nasync function readBodyWithLimit(body: ReadableStream<Uint8Array>, maxSize: number): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxSize) {\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Route-level Elysia parse hook for body methods.\n *\n * Parses JSON bodies itself: under `@elysiajs/node` an empty request still has a body stream, so Elysia's default\n * JSON parser throws on it and the request fails with 400 before the route runs. An empty JSON body comes back as\n * EMPTY_JSON_BODY and malformed JSON as InvalidJsonBody, both resolved by the route handler.\n *\n * With a `maxSize`, also enforces the body limit before anything buffers the request. Oversized bodies are marked\n * with BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.\n */\nfunction createBodyParser(maxSize: number | undefined) {\n return async (ctx: any) => {\n const request: Request = ctx.request;\n const contentLength = request.headers.get('content-length');\n // Reject a declared oversized body without reading it. A declared size within\n // the limit is still read with the cap, since app.handle() accepts a Request\n // whose stream need not match its Content-Length header.\n if (maxSize !== undefined && contentLength !== null && parseInt(contentLength, 10) > maxSize) {\n return BODY_TOO_LARGE;\n }\n\n const isJson = (request.headers.get('content-type') ?? '').includes('application/json');\n if (!request.body || (!isJson && maxSize === undefined)) return undefined;\n\n const bytes =\n maxSize === undefined\n ? new Uint8Array(await request.arrayBuffer())\n : await readBodyWithLimit(request.body, maxSize);\n if (!bytes) return BODY_TOO_LARGE;\n\n if (isJson) {\n const text = new TextDecoder().decode(bytes);\n if (text.trim().length === 0) return EMPTY_JSON_BODY;\n try {\n return JSON.parse(text);\n } catch (error) {\n return new InvalidJsonBody(error instanceof Error ? error.message : 'Invalid JSON in request body');\n }\n }\n\n // Hand the bounded body back to Elysia's default parsers.\n ctx.request = new Request(request.url, {\n method: request.method,\n headers: request.headers,\n body: bytes,\n signal: request.signal,\n });\n return undefined;\n };\n}\n\n/**\n * Normalizes route path parameters to position-based names (:p0, :p1, ...)\n * to avoid Elysia router conflicts when different routes use different\n * parameter names at the same path segment position (e.g. :agentId vs\n * :storedAgentId under /stored/agents/...).\n * Returns the normalized path and the original parameter names in order.\n */\nfunction normalizeRouteParams(path: string): { normalizedPath: string; paramNames: string[] } {\n const paramNames: string[] = [];\n const normalizedPath = path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName: string) => {\n paramNames.push(paramName);\n return `:p${paramNames.length - 1}`;\n });\n return { normalizedPath, paramNames };\n}\n\n/**\n * Reads query params keeping every value of a repeated key (`?tag=a&tag=b` -> `{ tag: ['a', 'b'] }`), as the\n * other adapters do; Elysia's `ctx.query` and `Object.fromEntries` keep only one.\n */\nfunction searchParamsToQuery(searchParams: URLSearchParams): Record<string, string | string[]> {\n const query: Record<string, string | string[]> = {};\n for (const key of new Set(searchParams.keys())) {\n const values = searchParams.getAll(key);\n query[key] = values.length === 1 ? (values[0] as string) : values;\n }\n return query;\n}\n\n/**\n * Remaps Elysia's parsed params from position-based names (p0, p1, ...)\n * back to the original parameter names expected by the route handler.\n */\nfunction remapParams(rawParams: Record<string, string>, paramNames: string[]): Record<string, string> {\n if (paramNames.length === 0) return rawParams;\n const result: Record<string, string> = {};\n paramNames.forEach((paramName, i) => {\n const key = `p${i}`;\n if (key in rawParams) {\n result[paramName] = rawParams[key] as string;\n }\n });\n return result;\n}\n\nasync function createForwardRequest(ctx: any): Promise<Request> {\n const request = ctx.request as Request;\n const method = request.method;\n\n if (method === 'GET' || method === 'HEAD') {\n return request;\n }\n\n const headers = new Headers(request.headers);\n let body: any;\n\n if (ctx.body !== undefined) {\n if (typeof ctx.body === 'string' || ctx.body instanceof FormData || ctx.body instanceof Blob) {\n body = ctx.body;\n } else {\n body = JSON.stringify(ctx.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n } else if (!request.bodyUsed) {\n const bodyBuffer = await request.clone().arrayBuffer();\n if (bodyBuffer.byteLength > 0) {\n body = bodyBuffer;\n }\n }\n\n headers.delete('content-length');\n\n return new Request(request.url, {\n method,\n headers,\n body,\n signal: request.signal,\n ...(body ? { duplex: 'half' as const } : {}),\n } as RequestInit);\n}\n\n/**\n * srvx, which runs `@elysiajs/node`, creates `request.signal` on first access and only then listens for the response\n * 'close'. A client that left during an earlier hook therefore never aborts it, so check the Node response directly.\n */\nfunction getRequestAbortSignal(request: Request): AbortSignal {\n const signal = request.signal;\n const nodeRes = (request as { runtime?: { node?: { res?: { destroyed?: boolean } } } }).runtime?.node?.res;\n return nodeRes?.destroyed && !signal.aborted ? AbortSignal.abort() : signal;\n}\n\nfunction getRequestSignal(ctx: unknown): AbortSignal | undefined {\n const context = ctx as { abortSignal?: AbortSignal; request?: Request } | undefined;\n return context?.abortSignal ?? (context?.request ? getRequestAbortSignal(context.request) : undefined);\n}\n\n/**\n * Cancels `reader` once, through `cancel()` or when the request signal aborts. A runtime that skips the response body\n * of a request that closed while the route handler ran never cancels that body, so the signal is the only notice.\n */\nfunction cancelReaderOnRequestAbort(\n reader: ReadableStreamDefaultReader<unknown>,\n signal: AbortSignal | undefined,\n): { cancel: (reason?: unknown) => void; dispose: () => void } {\n let canceled = false;\n const onAbort = () => cancel('request aborted');\n const dispose = () => signal?.removeEventListener('abort', onAbort);\n const cancel = (reason?: unknown) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n dispose();\n void reader.cancel(reason).catch(() => {});\n };\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return { cancel, dispose };\n}\n\nfunction createSafeReadableStream(body: ReadableStream<Uint8Array> | null): ReadableStream<Uint8Array> | null {\n if (!body) return null;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const reader = body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n controller.enqueue(value);\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n } finally {\n controller.close();\n reader.releaseLock();\n }\n },\n });\n}\n\n/**\n * Wraps a `datastream-response` body so a client disconnect cancels the upstream body. Unlike\n * `createSafeReadableStream`, it reads one chunk per pull, so a slow client slows the upstream.\n */\nfunction createDatastreamBody(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal | undefined,\n): ReadableStream<Uint8Array> | null {\n if (!body) {\n return null;\n }\n\n const reader = body.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, signal);\n let finished = false;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (!done) {\n controller.enqueue(value);\n return;\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n if (finished) {\n return;\n }\n }\n\n finished = true;\n upstream.dispose();\n controller.close();\n },\n cancel(reason) {\n finished = true;\n upstream.cancel(reason);\n },\n });\n}\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/elysia] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n// Export type definitions for Elysia app configuration\nexport interface ElysiaContext {\n mastra: Mastra;\n requestContext: RequestContext;\n registeredTools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n}\n\n/**\n * Minimal interface representing what MastraServer needs from an Elysia app.\n * This allows any Elysia app instance to be passed without strict generic matching.\n */\nexport interface ElysiaApp {\n use(instance: MaybePromise<AnyElysia>): ElysiaApp;\n derive(callback: (context: any) => any | Promise<any>): ElysiaApp;\n get(path: string, handler: any, options?: any): ElysiaApp;\n post(path: string, handler: any, options?: any): ElysiaApp;\n put(path: string, handler: any, options?: any): ElysiaApp;\n delete(path: string, handler: any, options?: any): ElysiaApp;\n patch(path: string, handler: any, options?: any): ElysiaApp;\n all(path: string, handler: any, options?: any): ElysiaApp;\n onAfterHandle(handler: (context: any) => any): ElysiaApp;\n onError(handler: (context: any) => any): ElysiaApp;\n}\n\nexport class MastraServer extends MastraServerBase<Elysia, Request, Response> {\n createContextMiddleware() {\n return async (ctx: any) => {\n // Parse request context from request body and query params\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT/PATCH)\n if (ctx.request.method === 'POST' || ctx.request.method === 'PUT' || ctx.request.method === 'PATCH') {\n const contentType = ctx.request.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n try {\n const body = (ctx.body ?? (await ctx.request.clone().json())) as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n } catch {\n // Body parsing failed, continue without body\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (ctx.request.method === 'GET') {\n try {\n // Elysia pre-parses query params into ctx.query\n const encodedRequestContext = ctx.query?.requestContext;\n if (encodedRequestContext) {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n });\n\n // Add relevant contexts to Elysia context\n return {\n requestContext,\n mastra: this.mastra,\n registeredTools: this.tools || {},\n taskStore: this.taskStore,\n abortSignal: getRequestAbortSignal(ctx.request),\n customRouteAuthConfig: this.customRouteAuthConfig,\n };\n };\n }\n\n async stream(route: ServerRoute, ctx: Response, result: { fullStream: ReadableStream }): Promise<any> {\n const streamFormat = route.streamFormat || 'stream';\n const encoder = new TextEncoder();\n\n const headers: Record<string, string> =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, getRequestSignal(ctx));\n // Set once the controller is closed, errored or cancelled; nothing may be enqueued from then on.\n let finished = false;\n\n // Reads one upstream chunk per pull so a slow client slows the upstream instead of buffering it here.\n const stream = new ReadableStream({\n start: controller => {\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n controller.enqueue(encoder.encode(': connected\\n\\n'));\n }\n },\n pull: async controller => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (done) {\n finished = true;\n upstream.dispose();\n\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n }\n\n controller.close();\n return;\n }\n\n if (!value) {\n continue;\n }\n\n // SSE comment passthrough — strings starting with ':' are written as-is\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n controller.enqueue(encoder.encode(value));\n return;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode(`data: ${serialized.json}\\n\\n`));\n } else {\n controller.enqueue(encoder.encode(serialized.json + '\\x1E'));\n }\n return;\n }\n } catch (error) {\n if (finished) {\n return;\n }\n\n finished = true;\n upstream.dispose();\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Close instead of erroring: @elysiajs/node destroys the socket on an errored body, dropping the frames\n // already enqueued and, for an early error, the status line too.\n controller.close();\n }\n },\n cancel: reason => {\n finished = true;\n upstream.cancel(reason);\n },\n });\n\n return new Response(stream, { headers });\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const url = new URL(request.url);\n\n // URL params - extract from request context if available (Elysia stores params in ctx)\n // Params may be normalized (p0, p1, ...) — remap back to original names from route path\n const { paramNames } = normalizeRouteParams(route.path);\n const rawUrlParams: Record<string, string> = (request as any).params || (request as any).ctx?.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawUrlParams, paramNames) : rawUrlParams;\n\n // Query params - parse from URL\n const queryParams = normalizeQueryParams(searchParamsToQuery(url.searchParams));\n\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const formData = await request.formData();\n body = await this.parseFormData(formData);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n const clonedReq = request.clone();\n const bodyText = await clonedReq.text();\n\n if (bodyText && bodyText.trim().length > 0) {\n try {\n body = JSON.parse(bodyText);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Invalid JSON in request body',\n };\n }\n }\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse FormData into a plain object, converting File objects to Buffers.\n * Handles both native FormData and Elysia's pre-parsed object format.\n */\n private async parseFormData(data: FormData | Record<string, unknown>): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {};\n\n // Handle native FormData\n if (data instanceof FormData) {\n for (const [key, value] of data.entries()) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value instanceof File) {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n // Try to parse JSON strings (like 'options')\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n // Handle Elysia's pre-parsed object format\n for (const [key, value] of Object.entries(data)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value && typeof value === 'object' && 'arrayBuffer' in value && typeof value.arrayBuffer === 'function') {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n async sendResponse(route: ServerRoute, response: Response, result: unknown, prefix?: string): Promise<any> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n const refreshHeaders: Record<string, string> = {};\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const headers = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(headers)) {\n refreshHeaders[key] = value;\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json', ...refreshHeaders },\n });\n } else if (route.responseType === 'stream') {\n return this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n const fetchResponse = result as globalThis.Response;\n const headers = new Headers(fetchResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createDatastreamBody(fetchResponse.body, getRequestSignal(response)), {\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n const { setRequestAuth, ...options } = { ...this.mcpOptions, ...routeMcpOptions };\n\n // `toReqRes` builds a fresh IncomingMessage, so bridge the principal auth resolved.\n await applyMcpRequestAuth({ req, requestContext: request.requestContext, setRequestAuth });\n\n // Do NOT await startHTTP — let it run in the background so SSE\n // notifications stream to the client as they are written.\n // toFetchResponse resolves when headers are sent, not when the body finishes.\n server\n .startHTTP({\n url: new URL(forwardRequest.url),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req,\n res,\n options: Object.keys(options).length > 0 ? options : undefined,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP HTTP] Error in background startHTTP:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n // `createForwardRequest` rebuilds the Request without a signal, so listen on the\n // original one: a client disconnect must abort the in-flight MCP request.\n propagateRequestAbort((request.request as Request).signal, res);\n\n const mcpResponse = await toFetchResponse(res);\n const headers = new Headers(mcpResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(mcpResponse.body), {\n status: mcpResponse.status,\n statusText: mcpResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-sse') {\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n await applyMcpRequestAuth({\n req,\n requestContext: request.requestContext,\n setRequestAuth: this.mcpOptions?.setRequestAuth,\n });\n\n server\n .startSSE({\n url: new URL(forwardRequest.url),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req,\n res,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP SSE] Error in background startSSE:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n const sseResponse = await toFetchResponse(res);\n const headers = new Headers(sseResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(sseResponse.body), {\n status: sseResponse.status,\n statusText: sseResponse.statusText,\n headers,\n });\n }\n return new Response(null, { status: 500 });\n }\n\n async registerRoute(\n app: ElysiaApp,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n const prefix = prefixParam ?? this.prefix ?? '';\n const fullPath = `${prefix}${route.path}`;\n const { normalizedPath, paramNames } = normalizeRouteParams(fullPath);\n\n const handler = async (ctx: any) => {\n // Reject oversized bodies before auth, matching adapters that enforce the limit in middleware.\n if (ctx.body === BODY_TOO_LARGE) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default error response.\n }\n }\n return new Response(JSON.stringify(errorResponse), {\n status: 413,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: ctx.request.url ? new URL(ctx.request.url).pathname : ctx.path,\n method: ctx.request.method,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = ctx.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n }\n\n // Extract params - remap from normalized param names back to original\n const rawParams = ctx.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;\n const queryParams = normalizeQueryParams(searchParamsToQuery(new URL(ctx.request.url).searchParams));\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = ctx.request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n // Elysia pre-parses multipart form data\n body = ctx.body ? await this.parseFormData(ctx.body) : undefined;\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n // Parsed by the route's parse hook (createBodyParser)\n if (ctx.body instanceof InvalidJsonBody) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', { error: { message: ctx.body.message } });\n bodyParseError = { message: ctx.body.message };\n } else if (ctx.body !== EMPTY_JSON_BODY) {\n body = ctx.body;\n }\n // createForwardRequest (MCP routes) reads ctx.body later and must not see the parse hook's markers.\n ctx.body = body;\n }\n }\n\n const params = { urlParams, queryParams, body, bodyParseError };\n\n // Return 400 Bad Request if body parsing failed\n if (params.bodyParseError) {\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n const fgaError = await checkRouteFGA(this.mastra, route, ctx.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: ctx.requestContext,\n mastra: ctx.mastra,\n registeredTools: ctx.registeredTools,\n taskStore: ctx.taskStore,\n abortSignal: ctx.abortSignal,\n routePrefix: prefix,\n request: ctx.request,\n };\n\n try {\n const result = await route.handler(handlerParams);\n return this.sendResponse(route, ctx as any, result, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n // Client errors (4xx) are returned as structured responses below, so they aren't logged as server faults.\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n return customResponse;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n\n // Register the route using Elysia's method chaining\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method);\n if (isBodyMethod) {\n app[method](normalizedPath, handler, { parse: createBodyParser(maxSize) });\n } else {\n app[method](normalizedPath, handler);\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const { normalizedPath: customNormalizedPath } = normalizeRouteParams(route.path);\n (this.app as ElysiaApp)[method](customNormalizedPath, async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n const requestMethod = ctx.request.method;\n // Check auth against the custom route the custom-route app will actually run for\n // this URL, which can differ from the route Elysia matched.\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(ctx.request.url, requestMethod, path, route);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method: requestMethod,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n customRouteAuthConfig,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check if any auth is configured (studio or server) for RBAC\n const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;\n if (hasAuth) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = ctx.requestContext.get('mastra__userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(\n serverRoute,\n userPermissions,\n hasPermission,\n ctx.requestContext,\n );\n if (permissionError) {\n return new Response(\n JSON.stringify({ error: permissionError.error, message: permissionError.message }),\n {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n }\n }\n\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {\n ...(ctx.query as Record<string, string>),\n ...(typeof ctx.body === 'object' && ctx.body !== null ? ctx.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const headers: Record<string, string | string[] | undefined> = {};\n ctx.request.headers.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n\n const response = await this.handleCustomRouteRequest(\n ctx.request.url,\n ctx.request.method,\n headers,\n ctx.body,\n ctx.requestContext,\n ctx.request.signal,\n );\n\n if (!response) {\n return new Response(JSON.stringify({ error: 'Not Found' }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return response;\n });\n }\n }\n\n registerContextMiddleware(): void {\n this.app.derive(this.createContextMiddleware());\n this.app.onAfterHandle({ as: 'global' }, applyAuthRefreshHeaders);\n this.app.onError({ as: 'global' }, applyAuthRefreshHeaders);\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n\n // Register global error handler to catch Elysia body parsing errors\n // and return structured JSON responses instead of plain text \"Bad Request\"\n this.app.onError((ctx: any) => {\n const error = ctx.error;\n const status = error?.status ?? error?.code ?? 500;\n const message = error?.message ?? 'Internal server error';\n\n // Body parsing / validation errors from Elysia are 400s\n const httpStatus = typeof status === 'number' && status >= 400 && status < 500 ? status : 500;\n\n return new Response(\n JSON.stringify({\n error: httpStatus < 500 ? message : 'Internal server error',\n ...(httpStatus < 500 ? { issues: [] } : {}),\n }),\n {\n status: httpStatus,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n });\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.derive(async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return {};\n }\n\n return {\n httpLogStart: Date.now(),\n };\n });\n\n this.app.onAfterHandle((ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return;\n }\n\n const duration = Date.now() - (ctx.httpLogStart ?? Date.now());\n const method = ctx.request.method;\n const status = ctx.response?.status ?? ctx.set?.status ?? 200;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = ctx.query || {};\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = Object.fromEntries(ctx.request.headers.entries());\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[RE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AM,OAAO,IAAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;GACtC,IAAI,CAAC,KAAK,iBAAiB,IAAI,GAC7B;GAGF,MAAM,WAAW,KAAK,IAAI,KAAK,IAAI,gBAAgB,KAAK,IAAI;GAC5D,MAAM,SAAS,IAAI,QAAQ;GAC3B,MAAM,SAAS,IAAI,UAAU,UAAU,IAAI,KAAK,UAAU;GAC1D,MAAM,QAAQ,KAAK,mBAAmB,SAAS;GAE/C,MAAM,UAA+B;IACnC;IACA;IACA;IACA,UAAU,GAAG,SAAS;GACxB;GAEA,IAAI,KAAK,mBAAmB,oBAC1B,QAAQ,QAAQ,IAAI,SAAS,CAAC;GAGhC,IAAI,KAAK,mBAAmB,gBAAgB;IAC1C,MAAM,UAAU,OAAO,YAAY,IAAI,QAAQ,QAAQ,QAAQ,CAAC;IAEhE,CADsB,KAAK,kBAAkB,iBAAiB,CAAC,EAAA,CACjD,SAAQ,MAAK;KACzB,MAAM,MAAM,EAAE,YAAY;KAC1B,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,OAAO;IAEnB,CAAC;IACD,QAAQ,UAAU;GACpB;GAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;EACzE,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["MastraServerBase"],"sources":["../src/auth-middleware.ts","../src/helper.ts","../src/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware, isCustomRoutePublic } from '@mastra/server/auth';\nimport { serializeCookie } from 'elysia/cookies';\n\nexport interface ElysiaAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\n// Refreshed session headers from an allowed request, applied to the final response by applyAuthRefreshHeaders.\nconst pendingRefreshHeaders = new WeakMap<Request, Record<string, string>>();\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: ElysiaAuthMiddlewareOptions): (ctx: any) => Promise<globalThis.Response | void> {\n return async (ctx: any) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n ctx.requestContext ??= new RequestContext();\n ctx.mastra ??= mastra;\n\n const url = new URL(ctx.request.url);\n const path = url.pathname;\n const method = ctx.request.method;\n const customRouteAuthConfig = new Map<string, boolean>(ctx.customRouteAuthConfig ?? []);\n // Don't reclassify a custom route the app declared public (requiresAuth: false).\n if (!isCustomRoutePublic(path, method, customRouteAuthConfig)) {\n customRouteAuthConfig.set(`${method}:${path}`, true);\n }\n\n const authHeader = ctx.request.headers.get('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token && ctx.query?.apiKey) {\n token = ctx.query.apiKey;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => ctx.request.headers.get(name) || undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: ctx.requestContext,\n rawRequest: ctx.request,\n token,\n buildAuthorizeContext: () => ctx,\n });\n\n if (result.action === 'error') {\n const headers = new Headers({ 'Content-Type': 'application/json' });\n appendHeaders(headers, result.headers);\n return new Response(JSON.stringify(result.body), { status: result.status, headers });\n }\n\n if (result.headers && Object.keys(result.headers).length > 0) {\n pendingRefreshHeaders.set(ctx.request, result.headers);\n }\n };\n}\n\n/**\n * Elysia `onAfterHandle` and `onError` hook that forwards session headers refreshed by\n * `createAuthMiddleware` onto the final response, including responses for handlers that throw. `Set-Cookie` values are appended alongside any cookies the app set\n * (via `ctx.cookie`, `set.headers`, or a returned `Response`) so none of them are dropped.\n */\nexport function applyAuthRefreshHeaders(ctx: any): globalThis.Response | void {\n const refreshHeaders = pendingRefreshHeaders.get(ctx.request);\n if (!refreshHeaders) {\n return;\n }\n pendingRefreshHeaders.delete(ctx.request);\n\n const set = ctx.set;\n const appCookies = takeSetSideCookies(set);\n const response = ctx.response;\n\n if (response instanceof Response) {\n const headers = new Headers(response.headers);\n for (const cookie of appCookies) {\n headers.append('set-cookie', cookie);\n }\n appendHeaders(headers, refreshHeaders);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers });\n }\n\n const cookies = [...appCookies];\n for (const [key, value] of Object.entries(refreshHeaders)) {\n if (key.toLowerCase() === 'set-cookie') {\n cookies.push(value);\n } else if (set.headers instanceof Headers) {\n set.headers.set(key, value);\n } else {\n set.headers[key] = value;\n }\n }\n if (cookies.length === 0) {\n return;\n }\n if (set.headers instanceof Headers) {\n for (const cookie of cookies) {\n set.headers.append('set-cookie', cookie);\n }\n } else {\n set.headers['set-cookie'] = cookies;\n }\n}\n\nfunction appendHeaders(headers: Headers, extra: Record<string, string> | undefined): void {\n for (const [key, value] of Object.entries(extra ?? {})) {\n if (key.toLowerCase() === 'set-cookie') {\n headers.append(key, value);\n } else {\n headers.set(key, value);\n }\n }\n}\n\n/**\n * Removes and returns cookies queued on Elysia's `set` (both `set.cookie` and raw `set-cookie` headers).\n * Elysia overwrites raw `set-cookie` headers with `set.cookie`, and drops set-side cookies when the\n * returned `Response` already has one, so they are collected here and re-emitted explicitly.\n */\nfunction takeSetSideCookies(set: any): string[] {\n const cookies: string[] = [];\n\n if (set.headers instanceof Headers) {\n cookies.push(...set.headers.getSetCookie());\n set.headers.delete('set-cookie');\n } else if (set.headers) {\n for (const key of Object.keys(set.headers)) {\n if (key.toLowerCase() !== 'set-cookie') continue;\n const value = set.headers[key];\n cookies.push(...(Array.isArray(value) ? value : [value]));\n delete set.headers[key];\n }\n }\n\n const serialized = serializeCookie(set.cookie);\n if (serialized) {\n cookies.push(...(Array.isArray(serialized) ? serialized : [serialized]));\n }\n for (const key of Object.keys(set.cookie ?? {})) {\n delete set.cookie[key];\n }\n\n return cookies;\n}\n","import {\n generateOpenAPIDocument,\n convertCustomRoutesToOpenAPIPaths,\n SERVER_ROUTES,\n} from '@mastra/server/server-adapter';\nimport type { MastraServer } from './index';\n\n/**\n * OpenAPI documentation cache to avoid regenerating on each call.\n * Uses WeakMap to prevent cache collisions between server instances.\n */\nconst openapiDocCache = new WeakMap<\n MastraServer,\n {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n }\n>();\n\n/**\n * Get OpenAPI documentation from a MastraServer instance, formatted for Elysia's openapi plugin.\n *\n * This function:\n * - Extracts all Mastra routes with their Zod schemas\n * - Converts them to OpenAPI 3.1.0 format\n * - Merges custom routes if registered\n * - Applies the configured route prefix to all paths\n * - Caches the result for performance\n *\n * @param server - The MastraServer instance (must be initialized with init())\n * @param options - Optional configuration for OpenAPI metadata\n * @returns OpenAPI documentation with paths, components, and info\n *\n * @example\n * ```typescript\n * import { getMastraOpenAPIDoc } from '@mastra/elysia';\n *\n * const srv = new MastraServer({ mastra, app, prefix: '/api' });\n * await srv.init();\n *\n * const openAPIDoc = getMastraOpenAPIDoc(srv, {\n * title: 'My Mastra API',\n * version: '1.0.0',\n * description: 'API with weather agent'\n * });\n *\n * app.use(openapi({\n * documentation: {\n * info: openAPIDoc.info,\n * paths: openAPIDoc.paths,\n * components: openAPIDoc.components\n * }\n * }));\n * ```\n */\nexport function getMastraOpenAPIDoc(\n server: MastraServer,\n options?: {\n title?: string;\n version?: string;\n description?: string;\n clearCache?: boolean;\n },\n): {\n paths: Record<string, any>;\n components?: Record<string, any>;\n info: { title: string; version: string; description?: string };\n} {\n // Clear cache if requested\n if (options?.clearCache) {\n openapiDocCache.delete(server);\n }\n\n // Return cached result if available\n const cached = openapiDocCache.get(server);\n if (cached) {\n // Merge custom info if provided\n if (options) {\n return {\n ...cached,\n info: {\n ...cached.info,\n ...(options.title && { title: options.title }),\n ...(options.version && { version: options.version }),\n ...(options.description && { description: options.description }),\n },\n };\n }\n return cached;\n }\n\n // Generate complete OpenAPI spec from Mastra's route definitions\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, {\n title: options?.title || 'Mastra API',\n version: options?.version || '1.0.0',\n description: options?.description || 'Mastra Server API',\n });\n\n // Merge custom API routes if present\n const customApiRoutes = (server as any).customApiRoutes;\n if (customApiRoutes && customApiRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n const customPaths = convertCustomRoutesToOpenAPIPaths(customApiRoutes, componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n let paths = openApiSpec.paths || {};\n\n // Apply prefix transformation if configured\n const prefix = (server as any).prefix;\n if (prefix && prefix !== '/') {\n const prefixedPaths: Record<string, any> = {};\n for (const [path, pathItem] of Object.entries(paths)) {\n // Combine prefix with path, ensuring no double slashes\n const prefixedPath = `${prefix}${path}`.replace(/\\/+/g, '/');\n prefixedPaths[prefixedPath] = pathItem;\n }\n paths = prefixedPaths;\n }\n\n const result = {\n paths,\n components: openApiSpec.components,\n info: openApiSpec.info,\n };\n\n // Cache the result\n openapiDocCache.set(server, result);\n\n return result;\n}\n\n/**\n * Clear the OpenAPI documentation cache.\n * Call this if routes are added dynamically after initialization.\n *\n * `@param` server - The MastraServer instance to clear cache for.\n * Note: WeakMap does not support clearing all entries. Pass the specific server instance whose cache should be invalidated.\n */\nexport function clearMastraOpenAPICache(server?: MastraServer): void {\n if (server) {\n openapiDocCache.delete(server);\n }\n // Cannot clear all entries in WeakMap - they will be garbage collected when servers are released\n}\n","import type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n applyMcpRequestAuth,\n checkRouteFGA,\n getCustomHTTPExceptionResponse,\n getHTTPErrorResponse,\n isSafeObjectKey,\n isZodError,\n normalizeQueryParams,\n propagateRequestAbort,\n redactStreamChunk,\n serializeStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { AnyElysia, MaybePromise } from 'elysia';\nimport type Elysia from 'elysia';\nimport { toReqRes, toFetchResponse } from 'fetch-to-node';\nimport { applyAuthRefreshHeaders } from './auth-middleware';\nexport { applyAuthRefreshHeaders, createAuthMiddleware } from './auth-middleware';\nexport type { ElysiaAuthMiddlewareOptions } from './auth-middleware';\n\n// Export helper functions for OpenAPI integration\nexport { getMastraOpenAPIDoc, clearMastraOpenAPICache } from './helper';\n\nconst BODY_TOO_LARGE = Symbol('mastra.elysia.bodyTooLarge');\nconst EMPTY_JSON_BODY = Symbol('mastra.elysia.emptyJsonBody');\n\nclass InvalidJsonBody {\n constructor(readonly message: string) {}\n}\n\nasync function readBodyWithLimit(body: ReadableStream<Uint8Array>, maxSize: number): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxSize) {\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Route-level Elysia parse hook for body methods.\n *\n * Parses JSON bodies itself: under `@elysiajs/node` an empty request still has a body stream, so Elysia's default\n * JSON parser throws on it and the request fails with 400 before the route runs. An empty JSON body comes back as\n * EMPTY_JSON_BODY and malformed JSON as InvalidJsonBody, both resolved by the route handler.\n *\n * With a `maxSize`, also enforces the body limit before anything buffers the request. Oversized bodies are marked\n * with BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.\n */\nfunction createBodyParser(maxSize: number | undefined) {\n return async (ctx: any) => {\n const request: Request = ctx.request;\n const contentLength = request.headers.get('content-length');\n // Reject a declared oversized body without reading it. A declared size within\n // the limit is still read with the cap, since app.handle() accepts a Request\n // whose stream need not match its Content-Length header.\n if (maxSize !== undefined && contentLength !== null && parseInt(contentLength, 10) > maxSize) {\n return BODY_TOO_LARGE;\n }\n\n const isJson = (request.headers.get('content-type') ?? '').includes('application/json');\n if (!request.body || (!isJson && maxSize === undefined)) return undefined;\n\n const bytes =\n maxSize === undefined\n ? new Uint8Array(await request.arrayBuffer())\n : await readBodyWithLimit(request.body, maxSize);\n if (!bytes) return BODY_TOO_LARGE;\n\n if (isJson) {\n const text = new TextDecoder().decode(bytes);\n if (text.trim().length === 0) return EMPTY_JSON_BODY;\n try {\n return JSON.parse(text);\n } catch (error) {\n return new InvalidJsonBody(error instanceof Error ? error.message : 'Invalid JSON in request body');\n }\n }\n\n // Hand the bounded body back to Elysia's default parsers.\n ctx.request = new Request(request.url, {\n method: request.method,\n headers: request.headers,\n body: bytes,\n signal: request.signal,\n });\n return undefined;\n };\n}\n\n/**\n * Normalizes route path parameters to position-based names (:p0, :p1, ...)\n * to avoid Elysia router conflicts when different routes use different\n * parameter names at the same path segment position (e.g. :agentId vs\n * :storedAgentId under /stored/agents/...).\n * Returns the normalized path and the original parameter names in order.\n */\nfunction normalizeRouteParams(path: string): { normalizedPath: string; paramNames: string[] } {\n const paramNames: string[] = [];\n const normalizedPath = path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName: string) => {\n paramNames.push(paramName);\n return `:p${paramNames.length - 1}`;\n });\n return { normalizedPath, paramNames };\n}\n\n/**\n * Reads query params keeping every value of a repeated key (`?tag=a&tag=b` -> `{ tag: ['a', 'b'] }`), as the\n * other adapters do; Elysia's `ctx.query` and `Object.fromEntries` keep only one.\n */\nfunction searchParamsToQuery(searchParams: URLSearchParams): Record<string, string | string[]> {\n const query: Record<string, string | string[]> = {};\n for (const key of new Set(searchParams.keys())) {\n const values = searchParams.getAll(key);\n query[key] = values.length === 1 ? (values[0] as string) : values;\n }\n return query;\n}\n\n/**\n * Remaps Elysia's parsed params from position-based names (p0, p1, ...)\n * back to the original parameter names expected by the route handler.\n */\nfunction remapParams(rawParams: Record<string, string>, paramNames: string[]): Record<string, string> {\n if (paramNames.length === 0) return rawParams;\n const result: Record<string, string> = {};\n paramNames.forEach((paramName, i) => {\n const key = `p${i}`;\n if (key in rawParams) {\n result[paramName] = rawParams[key] as string;\n }\n });\n return result;\n}\n\nasync function createForwardRequest(ctx: any): Promise<Request> {\n const request = ctx.request as Request;\n const method = request.method;\n\n if (method === 'GET' || method === 'HEAD') {\n return request;\n }\n\n const headers = new Headers(request.headers);\n let body: any;\n\n if (ctx.body !== undefined) {\n if (typeof ctx.body === 'string' || ctx.body instanceof FormData || ctx.body instanceof Blob) {\n body = ctx.body;\n } else {\n body = JSON.stringify(ctx.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n } else if (!request.bodyUsed) {\n const bodyBuffer = await request.clone().arrayBuffer();\n if (bodyBuffer.byteLength > 0) {\n body = bodyBuffer;\n }\n }\n\n headers.delete('content-length');\n\n return new Request(request.url, {\n method,\n headers,\n body,\n signal: request.signal,\n ...(body ? { duplex: 'half' as const } : {}),\n } as RequestInit);\n}\n\n/**\n * srvx, which runs `@elysiajs/node`, creates `request.signal` on first access and only then listens for the response\n * 'close'. A client that left during an earlier hook therefore never aborts it, so check the Node response directly.\n */\nfunction getRequestAbortSignal(request: Request): AbortSignal {\n const signal = request.signal;\n const nodeRes = (request as { runtime?: { node?: { res?: { destroyed?: boolean } } } }).runtime?.node?.res;\n return nodeRes?.destroyed && !signal.aborted ? AbortSignal.abort() : signal;\n}\n\nfunction getRequestSignal(ctx: unknown): AbortSignal | undefined {\n const context = ctx as { abortSignal?: AbortSignal; request?: Request } | undefined;\n return context?.abortSignal ?? (context?.request ? getRequestAbortSignal(context.request) : undefined);\n}\n\n/**\n * Cancels `reader` once, through `cancel()` or when the request signal aborts. A runtime that skips the response body\n * of a request that closed while the route handler ran never cancels that body, so the signal is the only notice.\n */\nfunction cancelReaderOnRequestAbort(\n reader: ReadableStreamDefaultReader<unknown>,\n signal: AbortSignal | undefined,\n): { cancel: (reason?: unknown) => void; dispose: () => void } {\n let canceled = false;\n const onAbort = () => cancel('request aborted');\n const dispose = () => signal?.removeEventListener('abort', onAbort);\n const cancel = (reason?: unknown) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n dispose();\n void reader.cancel(reason).catch(() => {});\n };\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return { cancel, dispose };\n}\n\nfunction createSafeReadableStream(body: ReadableStream<Uint8Array> | null): ReadableStream<Uint8Array> | null {\n if (!body) return null;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const reader = body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n controller.enqueue(value);\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n } finally {\n controller.close();\n reader.releaseLock();\n }\n },\n });\n}\n\n/**\n * Wraps a `datastream-response` body so a client disconnect cancels the upstream body. Unlike\n * `createSafeReadableStream`, it reads one chunk per pull, so a slow client slows the upstream.\n */\nfunction createDatastreamBody(\n body: ReadableStream<Uint8Array> | null,\n signal: AbortSignal | undefined,\n): ReadableStream<Uint8Array> | null {\n if (!body) {\n return null;\n }\n\n const reader = body.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, signal);\n let finished = false;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (!done) {\n controller.enqueue(value);\n return;\n }\n } catch {\n // Preserve chunks already sent before upstream stream errors.\n if (finished) {\n return;\n }\n }\n\n finished = true;\n upstream.dispose();\n controller.close();\n },\n cancel(reason) {\n finished = true;\n upstream.cancel(reason);\n },\n });\n}\n\n// Export type definitions for Elysia app configuration\nexport interface ElysiaContext {\n mastra: Mastra;\n requestContext: RequestContext;\n registeredTools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n}\n\n/**\n * Minimal interface representing what MastraServer needs from an Elysia app.\n * This allows any Elysia app instance to be passed without strict generic matching.\n */\nexport interface ElysiaApp {\n use(instance: MaybePromise<AnyElysia>): ElysiaApp;\n derive(callback: (context: any) => any | Promise<any>): ElysiaApp;\n get(path: string, handler: any, options?: any): ElysiaApp;\n post(path: string, handler: any, options?: any): ElysiaApp;\n put(path: string, handler: any, options?: any): ElysiaApp;\n delete(path: string, handler: any, options?: any): ElysiaApp;\n patch(path: string, handler: any, options?: any): ElysiaApp;\n all(path: string, handler: any, options?: any): ElysiaApp;\n onAfterHandle(handler: (context: any) => any): ElysiaApp;\n onError(handler: (context: any) => any): ElysiaApp;\n}\n\nexport class MastraServer extends MastraServerBase<Elysia, Request, Response> {\n createContextMiddleware() {\n return async (ctx: any) => {\n // Parse request context from request body and query params\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT/PATCH)\n if (ctx.request.method === 'POST' || ctx.request.method === 'PUT' || ctx.request.method === 'PATCH') {\n const contentType = ctx.request.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n try {\n const body = (ctx.body ?? (await ctx.request.clone().json())) as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n } catch {\n // Body parsing failed, continue without body\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (ctx.request.method === 'GET') {\n try {\n // Elysia pre-parses query params into ctx.query\n const encodedRequestContext = ctx.query?.requestContext;\n if (encodedRequestContext) {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n this.applyRequestMetadataToContext({\n requestContext,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n });\n\n // Add relevant contexts to Elysia context\n return {\n requestContext,\n mastra: this.mastra,\n registeredTools: this.tools || {},\n taskStore: this.taskStore,\n abortSignal: getRequestAbortSignal(ctx.request),\n customRouteAuthConfig: this.customRouteAuthConfig,\n };\n };\n }\n\n async stream(route: ServerRoute, ctx: Response, result: { fullStream: ReadableStream }): Promise<any> {\n const streamFormat = route.streamFormat || 'stream';\n const encoder = new TextEncoder();\n\n const headers: Record<string, string> =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n const upstream = cancelReaderOnRequestAbort(reader, getRequestSignal(ctx));\n // Set once the controller is closed, errored or cancelled; nothing may be enqueued from then on.\n let finished = false;\n\n // Reads one upstream chunk per pull so a slow client slows the upstream instead of buffering it here.\n const stream = new ReadableStream({\n start: controller => {\n if (streamFormat === 'sse' && route.sseFlushOnConnect) {\n controller.enqueue(encoder.encode(': connected\\n\\n'));\n }\n },\n pull: async controller => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (finished) {\n return;\n }\n\n if (done) {\n finished = true;\n upstream.dispose();\n\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n }\n\n controller.close();\n return;\n }\n\n if (!value) {\n continue;\n }\n\n // SSE comment passthrough — strings starting with ':' are written as-is\n if (streamFormat === 'sse' && typeof value === 'string' && value.startsWith(':')) {\n controller.enqueue(encoder.encode(value));\n return;\n }\n\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n // A chunk that can't be serialized must not kill the stream — skip it and keep streaming\n const serialized = serializeStreamChunk(outputValue);\n if (!serialized.ok) {\n this.mastra.getLogger()?.error('Failed to serialize stream chunk, skipping', {\n path: route.path,\n chunkType: (outputValue as { type?: string })?.type,\n error: serialized.error.message,\n });\n continue;\n }\n if (streamFormat === 'sse') {\n controller.enqueue(encoder.encode(`data: ${serialized.json}\\n\\n`));\n } else {\n controller.enqueue(encoder.encode(serialized.json + '\\x1E'));\n }\n return;\n }\n } catch (error) {\n if (finished) {\n return;\n }\n\n finished = true;\n upstream.dispose();\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Close instead of erroring: @elysiajs/node destroys the socket on an errored body, dropping the frames\n // already enqueued and, for an early error, the status line too.\n controller.close();\n }\n },\n cancel: reason => {\n finished = true;\n upstream.cancel(reason);\n },\n });\n\n return new Response(stream, { headers });\n }\n\n async getParams(route: ServerRoute, request: Request): Promise<ParsedRequestParams> {\n const url = new URL(request.url);\n\n // URL params - extract from request context if available (Elysia stores params in ctx)\n // Params may be normalized (p0, p1, ...) — remap back to original names from route path\n const { paramNames } = normalizeRouteParams(route.path);\n const rawUrlParams: Record<string, string> = (request as any).params || (request as any).ctx?.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawUrlParams, paramNames) : rawUrlParams;\n\n // Query params - parse from URL\n const queryParams = normalizeQueryParams(searchParamsToQuery(url.searchParams));\n\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const formData = await request.formData();\n body = await this.parseFormData(formData);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n const clonedReq = request.clone();\n const bodyText = await clonedReq.text();\n\n if (bodyText && bodyText.trim().length > 0) {\n try {\n body = JSON.parse(bodyText);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Invalid JSON in request body',\n };\n }\n }\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse FormData into a plain object, converting File objects to Buffers.\n * Handles both native FormData and Elysia's pre-parsed object format.\n */\n private async parseFormData(data: FormData | Record<string, unknown>): Promise<Record<string, unknown>> {\n const result: Record<string, unknown> = {};\n\n // Handle native FormData\n if (data instanceof FormData) {\n for (const [key, value] of data.entries()) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value instanceof File) {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n // Try to parse JSON strings (like 'options')\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n // Handle Elysia's pre-parsed object format\n for (const [key, value] of Object.entries(data)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n if (value && typeof value === 'object' && 'arrayBuffer' in value && typeof value.arrayBuffer === 'function') {\n const arrayBuffer = await value.arrayBuffer();\n result[key] = Buffer.from(arrayBuffer);\n } else if (typeof value === 'string') {\n try {\n result[key] = JSON.parse(value);\n } catch {\n result[key] = value;\n }\n } else {\n result[key] = value;\n }\n }\n return result;\n }\n\n /** Adapter `mcpOptions` win; otherwise use `server.mcpOptions` from the Mastra config. */\n private resolveMcpOptions() {\n return this.mcpOptions ?? this.mastra.getServer()?.mcpOptions;\n }\n\n async sendResponse(route: ServerRoute, response: Response, result: unknown, prefix?: string): Promise<any> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n // Apply refresh headers from transparent session refresh (e.g. Set-Cookie after token refresh)\n const refreshHeaders: Record<string, string> = {};\n if (result && typeof result === 'object' && '__refreshHeaders' in result) {\n const headers = (result as any).__refreshHeaders as Record<string, string>;\n for (const [key, value] of Object.entries(headers)) {\n refreshHeaders[key] = value;\n }\n delete (result as any).__refreshHeaders;\n }\n\n if (route.responseType === 'json') {\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { 'Content-Type': 'application/json', ...refreshHeaders },\n });\n } else if (route.responseType === 'stream') {\n return this.stream(route, response, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n const fetchResponse = result as globalThis.Response;\n const headers = new Headers(fetchResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createDatastreamBody(fetchResponse.body, getRequestSignal(response)), {\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n const { setRequestAuth, ...options } = { ...this.resolveMcpOptions(), ...routeMcpOptions };\n\n // `toReqRes` builds a fresh IncomingMessage, so bridge the principal auth resolved.\n await applyMcpRequestAuth({ req, requestContext: request.requestContext, setRequestAuth });\n\n // Do NOT await startHTTP — let it run in the background so SSE\n // notifications stream to the client as they are written.\n // toFetchResponse resolves when headers are sent, not when the body finishes.\n server\n .startHTTP({\n url: new URL(forwardRequest.url),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req,\n res,\n options: Object.keys(options).length > 0 ? options : undefined,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP HTTP] Error in background startHTTP:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n // `createForwardRequest` rebuilds the Request without a signal, so listen on the\n // original one: a client disconnect must abort the in-flight MCP request.\n propagateRequestAbort((request.request as Request).signal, res);\n\n const mcpResponse = await toFetchResponse(res);\n const headers = new Headers(mcpResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(mcpResponse.body), {\n status: mcpResponse.status,\n statusText: mcpResponse.statusText,\n headers,\n });\n } else if (route.responseType === 'mcp-sse') {\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n const request = response as any; // Elysia context\n const forwardRequest = await createForwardRequest(request);\n const { req, res } = toReqRes(forwardRequest);\n\n await applyMcpRequestAuth({\n req,\n requestContext: request.requestContext,\n setRequestAuth: this.resolveMcpOptions()?.setRequestAuth,\n });\n\n server\n .startSSE({\n url: new URL(forwardRequest.url),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req,\n res,\n })\n .catch((e: unknown) => {\n this.mastra.getLogger()?.error('[MCP SSE] Error in background startSSE:', {\n error: e instanceof Error ? { message: e.message, stack: e.stack } : e,\n });\n });\n\n const sseResponse = await toFetchResponse(res);\n const headers = new Headers(sseResponse.headers);\n headers.delete('Transfer-Encoding');\n return new Response(createSafeReadableStream(sseResponse.body), {\n status: sseResponse.status,\n statusText: sseResponse.statusText,\n headers,\n });\n }\n return new Response(null, { status: 500 });\n }\n\n async registerRoute(\n app: ElysiaApp,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n const prefix = prefixParam ?? this.prefix ?? '';\n const fullPath = `${prefix}${route.path}`;\n const { normalizedPath, paramNames } = normalizeRouteParams(fullPath);\n\n const handler = async (ctx: any) => {\n // Reject oversized bodies before auth, matching adapters that enforce the limit in middleware.\n if (ctx.body === BODY_TOO_LARGE) {\n let errorResponse: unknown = { error: 'Request body too large' };\n if (route.maxBodySize === undefined && this.bodyLimitOptions) {\n try {\n errorResponse = this.bodyLimitOptions.onError(errorResponse);\n } catch {\n // Fall back to the default error response.\n }\n }\n return new Response(JSON.stringify(errorResponse), {\n status: 413,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: ctx.request.url ? new URL(ctx.request.url).pathname : ctx.path,\n method: ctx.request.method,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n // Check route permission (RBAC). Elysia checks it before schema validation.\n const permissionError = this.checkRouteRBAC(route, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Extract params - remap from normalized param names back to original\n const rawParams = ctx.params || {};\n const urlParams = paramNames.length > 0 ? remapParams(rawParams, paramNames) : rawParams;\n const queryParams = normalizeQueryParams(searchParamsToQuery(new URL(ctx.request.url).searchParams));\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = ctx.request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n // Elysia pre-parses multipart form data\n body = ctx.body ? await this.parseFormData(ctx.body) : undefined;\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else if (contentType.includes('application/json')) {\n // Parsed by the route's parse hook (createBodyParser)\n if (ctx.body instanceof InvalidJsonBody) {\n this.mastra.getLogger()?.error('Failed to parse JSON body', { error: { message: ctx.body.message } });\n bodyParseError = { message: ctx.body.message };\n } else if (ctx.body !== EMPTY_JSON_BODY) {\n body = ctx.body;\n }\n // createForwardRequest (MCP routes) reads ctx.body later and must not see the parse hook's markers.\n ctx.body = body;\n }\n }\n\n const params = { urlParams, queryParams, body, bodyParseError };\n\n // Return 400 Bad Request if body parsing failed\n if (params.bodyParseError) {\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n if (params.body !== undefined || route.bodySchema) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (isZodError(error)) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n return new Response(\n JSON.stringify({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n }\n }\n\n const fgaError = await checkRouteFGA(this.mastra, route, ctx.requestContext, {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: ctx.requestContext,\n mastra: ctx.mastra,\n registeredTools: ctx.registeredTools,\n taskStore: ctx.taskStore,\n abortSignal: ctx.abortSignal,\n routePrefix: prefix,\n request: ctx.request,\n };\n\n try {\n const result = await route.handler(handlerParams);\n return this.sendResponse(route, ctx as any, result, prefix);\n } catch (error) {\n const httpStatus =\n error && typeof error === 'object' ? ((error as any).status ?? (error as any).details?.status) : undefined;\n // Client errors (4xx) are returned as structured responses below, so they aren't logged as server faults.\n const isClientError = typeof httpStatus === 'number' && httpStatus >= 400 && httpStatus < 500;\n if (!isClientError) {\n // 501 means an optional capability isn't provided by the configured storage or core: expected, not a server fault.\n const logLevel = httpStatus === 501 ? 'warn' : 'error';\n this.mastra.getLogger()?.[logLevel]('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n }\n\n const customResponse = getCustomHTTPExceptionResponse(error);\n if (customResponse) {\n return customResponse;\n }\n\n const { status, body } = getHTTPErrorResponse(error);\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n\n // Register the route using Elysia's method chaining\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n const isBodyMethod = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(route.method);\n if (isBodyMethod) {\n app[method](normalizedPath, handler, { parse: createBodyParser(maxSize) });\n } else {\n app[method](normalizedPath, handler);\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n const routes = await this.registerSchemaApiRoutes();\n if (!(await this.buildCustomRouteHandler(routes))) return;\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all';\n const { normalizedPath: customNormalizedPath } = normalizeRouteParams(route.path);\n (this.app as ElysiaApp)[method](customNormalizedPath, async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n const requestMethod = ctx.request.method;\n // Check auth against the custom route the custom-route app will actually run for\n // this URL, which can differ from the route Elysia matched.\n const {\n match: matchedRoute,\n requiresAuth: shouldRunCustomRouteAuth,\n serverRoute,\n customRouteAuthConfig,\n } = this.resolveCustomRouteAuth(ctx.request.url, requestMethod, path, route);\n const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;\n\n if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {\n if (shouldRunCustomRouteAuth) {\n const authError = await this.checkRouteAuth(serverRoute, {\n path,\n method: requestMethod,\n getHeader: (name: string) => ctx.request.headers.get(name) || undefined,\n getQuery: (name: string) => ctx.query?.[name],\n requestContext: ctx.requestContext,\n request: ctx.request,\n buildAuthorizeContext: () => ctx,\n customRouteAuthConfig,\n });\n\n if (authError) {\n return new Response(JSON.stringify({ error: authError.error }), {\n status: authError.status,\n headers: { 'Content-Type': 'application/json', ...authError.headers },\n });\n }\n\n const permissionError = this.checkRouteRBAC(serverRoute, ctx.requestContext);\n if (permissionError) {\n return new Response(JSON.stringify({ error: permissionError.error, message: permissionError.message }), {\n status: permissionError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n // Path params last: the custom handler reads them from the URL, so query/body\n // values must not be able to change which resource FGA checks.\n const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {\n ...(ctx.query as Record<string, string>),\n ...(typeof ctx.body === 'object' && ctx.body !== null ? ctx.body : {}),\n ...(matchedRoute?.params ?? {}),\n });\n if (fgaError) {\n return new Response(JSON.stringify({ error: fgaError.error, message: fgaError.message }), {\n status: fgaError.status,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const headers: Record<string, string | string[] | undefined> = {};\n ctx.request.headers.forEach((value: string, key: string) => {\n headers[key] = value;\n });\n\n const response = await this.handleCustomRouteRequest(\n ctx.request.url,\n ctx.request.method,\n headers,\n ctx.body,\n ctx.requestContext,\n ctx.request.signal,\n );\n\n if (!response) {\n return new Response(JSON.stringify({ error: 'Not Found' }), {\n status: 404,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return response;\n });\n }\n }\n\n registerContextMiddleware(): void {\n this.app.derive(this.createContextMiddleware());\n this.app.onAfterHandle({ as: 'global' }, applyAuthRefreshHeaders);\n this.app.onError({ as: 'global' }, applyAuthRefreshHeaders);\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n\n // Register global error handler to catch Elysia body parsing errors\n // and return structured JSON responses instead of plain text \"Bad Request\"\n this.app.onError((ctx: any) => {\n const error = ctx.error;\n const status = error?.status ?? error?.code ?? 500;\n const message = error?.message ?? 'Internal server error';\n\n // Body parsing / validation errors from Elysia are 400s\n const httpStatus = typeof status === 'number' && status >= 400 && status < 500 ? status : 500;\n\n return new Response(\n JSON.stringify({\n error: httpStatus < 500 ? message : 'Internal server error',\n ...(httpStatus < 500 ? { issues: [] } : {}),\n }),\n {\n status: httpStatus,\n headers: { 'Content-Type': 'application/json' },\n },\n );\n });\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.derive(async (ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return {};\n }\n\n return {\n httpLogStart: Date.now(),\n };\n });\n\n this.app.onAfterHandle((ctx: any) => {\n const path = new URL(ctx.request.url).pathname;\n if (!this.shouldLogRequest(path)) {\n return;\n }\n\n const duration = Date.now() - (ctx.httpLogStart ?? Date.now());\n const method = ctx.request.method;\n const status = ctx.response?.status ?? ctx.set?.status ?? 200;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = ctx.query || {};\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = Object.fromEntries(ctx.request.headers.entries());\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach(h => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n }\n}\n"],"mappings":";;;;;;AAWA,MAAM,wCAAwB,IAAI,QAAyC;AAE3E,SAAgB,qBAAqB,EACnC,QACA,eAAe,QACkE;CACjF,OAAO,OAAO,QAAa;EACzB,IAAI,CAAC,cACH;EAGF,MAAM,aAAa,OAAO,UAAU,CAAC,EAAE;EACvC,IAAI,CAAC,YACH;EAGF,IAAI,mBAAmB,IAAI,eAAe;EAC1C,IAAI,WAAW;EAGf,MAAM,OAAO,IADG,IAAI,IAAI,QAAQ,GACjB,CAAC,CAAC;EACjB,MAAM,SAAS,IAAI,QAAQ;EAC3B,MAAM,wBAAwB,IAAI,IAAqB,IAAI,yBAAyB,CAAC,CAAC;EAEtF,IAAI,CAAC,oBAAoB,MAAM,QAAQ,qBAAqB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AAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;GACtC,IAAI,CAAC,KAAK,iBAAiB,IAAI,GAC7B,OAAO,CAAC;GAGV,OAAO,EACL,cAAc,KAAK,IAAI,EACzB;EACF,CAAC;EAED,KAAK,IAAI,eAAe,QAAa;GACnC,MAAM,OAAO,IAAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;GACtC,IAAI,CAAC,KAAK,iBAAiB,IAAI,GAC7B;GAGF,MAAM,WAAW,KAAK,IAAI,KAAK,IAAI,gBAAgB,KAAK,IAAI;GAC5D,MAAM,SAAS,IAAI,QAAQ;GAC3B,MAAM,SAAS,IAAI,UAAU,UAAU,IAAI,KAAK,UAAU;GAC1D,MAAM,QAAQ,KAAK,mBAAmB,SAAS;GAE/C,MAAM,UAA+B;IACnC;IACA;IACA;IACA,UAAU,GAAG,SAAS;GACxB;GAEA,IAAI,KAAK,mBAAmB,oBAC1B,QAAQ,QAAQ,IAAI,SAAS,CAAC;GAGhC,IAAI,KAAK,mBAAmB,gBAAgB;IAC1C,MAAM,UAAU,OAAO,YAAY,IAAI,QAAQ,QAAQ,QAAQ,CAAC;IAEhE,CADsB,KAAK,kBAAkB,iBAAiB,CAAC,EAAA,CACjD,SAAQ,MAAK;KACzB,MAAM,MAAM,EAAE,YAAY;KAC1B,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,OAAO;IAEnB,CAAC;IACD,QAAQ,UAAU;GACpB;GAEA,KAAK,OAAO,MAAM,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,GAAG,SAAS,KAAK,OAAO;EACzE,CAAC;CACH;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/elysia",
|
|
3
|
-
"version": "0.1.23
|
|
3
|
+
"version": "0.1.23",
|
|
4
4
|
"description": "Mastra Elysia adapter for the server",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"license": "Apache-2.0",
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"fetch-to-node": "^2.1.0",
|
|
24
|
-
"@mastra/server": "1.83.0
|
|
24
|
+
"@mastra/server": "1.83.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@ai-sdk/openai": "^2.0.139",
|
|
@@ -38,17 +38,17 @@
|
|
|
38
38
|
"typescript": "^7.0.2",
|
|
39
39
|
"vitest": "5.1.0",
|
|
40
40
|
"zod": "^4.6.7",
|
|
41
|
-
"@internal/lint": "0.0.
|
|
42
|
-
"@internal/storage-test-utils": "0.0.
|
|
43
|
-
"@internal/types-builder": "0.0.
|
|
44
|
-
"@mastra/core": "1.83.0
|
|
45
|
-
"@mastra/libsql": "1.30.0
|
|
46
|
-
"@mastra/memory": "1.41.1
|
|
47
|
-
"@mastra/observability": "1.24.0
|
|
48
|
-
"@mastra/server-adapters-test-suite": "0.3.0
|
|
41
|
+
"@internal/lint": "0.0.149",
|
|
42
|
+
"@internal/storage-test-utils": "0.0.145",
|
|
43
|
+
"@internal/types-builder": "0.0.124",
|
|
44
|
+
"@mastra/core": "1.83.0",
|
|
45
|
+
"@mastra/libsql": "1.30.0",
|
|
46
|
+
"@mastra/memory": "1.41.1",
|
|
47
|
+
"@mastra/observability": "1.24.0",
|
|
48
|
+
"@mastra/server-adapters-test-suite": "0.3.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@mastra/core": ">=1.
|
|
51
|
+
"@mastra/core": ">=1.83.0-0 <2.0.0-0",
|
|
52
52
|
"elysia": "^1.4.25"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|