@mastra/elysia 0.1.19 → 0.1.20-alpha.1
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/__tests__/helpers.d.ts.map +1 -1
- package/dist/index.cjs +118 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +119 -75
- package/dist/index.js.map +1 -1
- package/package.json +12 -10
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { coreAuthMiddleware, findMatchingCustomRoute, isCustomRoutePublic, isProtectedCustomRoute } from "@mastra/server/auth";
|
|
2
|
-
import { MastraServer as MastraServer$1, SERVER_ROUTES, checkRouteFGA, convertCustomRoutesToOpenAPIPaths, generateOpenAPIDocument, getCustomHTTPExceptionResponse, isSafeObjectKey, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
|
|
2
|
+
import { MastraServer as MastraServer$1, SERVER_ROUTES, checkRouteFGA, convertCustomRoutesToOpenAPIPaths, generateOpenAPIDocument, getCustomHTTPExceptionResponse, getHTTPErrorResponse, isSafeObjectKey, isZodError, normalizeQueryParams, propagateRequestAbort, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
|
|
3
3
|
import { toFetchResponse, toReqRes } from "fetch-to-node";
|
|
4
4
|
import { RequestContext } from "@mastra/core/request-context";
|
|
5
5
|
import { serializeCookie } from "elysia/cookies";
|
|
@@ -203,6 +203,50 @@ function clearMastraOpenAPICache(server) {
|
|
|
203
203
|
}
|
|
204
204
|
//#endregion
|
|
205
205
|
//#region src/index.ts
|
|
206
|
+
const BODY_TOO_LARGE = Symbol("mastra.elysia.bodyTooLarge");
|
|
207
|
+
async function readBodyWithLimit(body, maxSize) {
|
|
208
|
+
const reader = body.getReader();
|
|
209
|
+
const chunks = [];
|
|
210
|
+
let size = 0;
|
|
211
|
+
while (true) {
|
|
212
|
+
const { done, value } = await reader.read();
|
|
213
|
+
if (done) break;
|
|
214
|
+
size += value.byteLength;
|
|
215
|
+
if (size > maxSize) {
|
|
216
|
+
await reader.cancel().catch(() => {});
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
chunks.push(value);
|
|
220
|
+
}
|
|
221
|
+
const bytes = new Uint8Array(size);
|
|
222
|
+
let offset = 0;
|
|
223
|
+
for (const chunk of chunks) {
|
|
224
|
+
bytes.set(chunk, offset);
|
|
225
|
+
offset += chunk.byteLength;
|
|
226
|
+
}
|
|
227
|
+
return bytes;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Route-level Elysia parse hook that enforces the body limit before Elysia's
|
|
231
|
+
* default parsers buffer the request. Oversized bodies are marked with
|
|
232
|
+
* BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.
|
|
233
|
+
*/
|
|
234
|
+
function createBodyLimitParser(maxSize) {
|
|
235
|
+
return async (ctx) => {
|
|
236
|
+
const request = ctx.request;
|
|
237
|
+
const contentLength = request.headers.get("content-length");
|
|
238
|
+
if (contentLength !== null && parseInt(contentLength, 10) > maxSize) return BODY_TOO_LARGE;
|
|
239
|
+
if (!request.body) return void 0;
|
|
240
|
+
const bytes = await readBodyWithLimit(request.body, maxSize);
|
|
241
|
+
if (!bytes) return BODY_TOO_LARGE;
|
|
242
|
+
ctx.request = new Request(request.url, {
|
|
243
|
+
method: request.method,
|
|
244
|
+
headers: request.headers,
|
|
245
|
+
body: bytes,
|
|
246
|
+
signal: request.signal
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
}
|
|
206
250
|
/**
|
|
207
251
|
* Normalizes route path parameters to position-based names (:p0, :p1, ...)
|
|
208
252
|
* to avoid Elysia router conflicts when different routes use different
|
|
@@ -330,44 +374,53 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
330
374
|
Connection: "keep-alive",
|
|
331
375
|
"X-Accel-Buffering": "no"
|
|
332
376
|
} : { "Content-Type": "text/plain" };
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
if (
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
377
|
+
const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
|
|
378
|
+
let cancelled = false;
|
|
379
|
+
const stream = new ReadableStream({
|
|
380
|
+
start: async (controller) => {
|
|
381
|
+
try {
|
|
382
|
+
if (streamFormat === "sse" && route.sseFlushOnConnect) controller.enqueue(encoder.encode(": connected\n\n"));
|
|
383
|
+
while (true) {
|
|
384
|
+
const { done, value } = await reader.read();
|
|
385
|
+
if (done || cancelled) break;
|
|
386
|
+
if (value) {
|
|
387
|
+
if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
|
|
388
|
+
controller.enqueue(encoder.encode(value));
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const outputValue = this.streamOptions?.redact ?? true ? redactStreamChunk(value) : value;
|
|
392
|
+
const serialized = serializeStreamChunk(outputValue);
|
|
393
|
+
if (!serialized.ok) {
|
|
394
|
+
this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
|
|
395
|
+
path: route.path,
|
|
396
|
+
chunkType: outputValue?.type,
|
|
397
|
+
error: serialized.error.message
|
|
398
|
+
});
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
if (streamFormat === "sse") controller.enqueue(encoder.encode(`data: ${serialized.json}\n\n`));
|
|
402
|
+
else controller.enqueue(encoder.encode(serialized.json + ""));
|
|
354
403
|
}
|
|
355
|
-
if (streamFormat === "sse") controller.enqueue(encoder.encode(`data: ${serialized.json}\n\n`));
|
|
356
|
-
else controller.enqueue(encoder.encode(serialized.json + ""));
|
|
357
404
|
}
|
|
405
|
+
if (cancelled) return;
|
|
406
|
+
if (streamFormat === "sse") controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
407
|
+
controller.close();
|
|
408
|
+
} catch (error) {
|
|
409
|
+
if (cancelled) return;
|
|
410
|
+
this.mastra.getLogger()?.error("Error in stream processing", { error: error instanceof Error ? {
|
|
411
|
+
message: error.message,
|
|
412
|
+
stack: error.stack
|
|
413
|
+
} : error });
|
|
414
|
+
controller.error(error);
|
|
415
|
+
} finally {
|
|
416
|
+
await reader.cancel();
|
|
358
417
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
message: error.message,
|
|
364
|
-
stack: error.stack
|
|
365
|
-
} : error });
|
|
366
|
-
controller.error(error);
|
|
367
|
-
} finally {
|
|
368
|
-
await reader.cancel();
|
|
418
|
+
},
|
|
419
|
+
cancel: async (reason) => {
|
|
420
|
+
cancelled = true;
|
|
421
|
+
await reader.cancel(reason);
|
|
369
422
|
}
|
|
370
|
-
}
|
|
423
|
+
});
|
|
371
424
|
return new Response(stream, { headers });
|
|
372
425
|
}
|
|
373
426
|
async getParams(route, request) {
|
|
@@ -473,7 +526,8 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
473
526
|
});
|
|
474
527
|
} else if (route.responseType === "mcp-http") {
|
|
475
528
|
const { server, httpPath, mcpOptions: routeMcpOptions } = result;
|
|
476
|
-
const
|
|
529
|
+
const request = response;
|
|
530
|
+
const forwardRequest = await createForwardRequest(request);
|
|
477
531
|
const { req, res } = toReqRes(forwardRequest);
|
|
478
532
|
const options = {
|
|
479
533
|
...this.mcpOptions,
|
|
@@ -491,6 +545,7 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
491
545
|
stack: e.stack
|
|
492
546
|
} : e });
|
|
493
547
|
});
|
|
548
|
+
propagateRequestAbort(request.request.signal, res);
|
|
494
549
|
const mcpResponse = await toFetchResponse(res);
|
|
495
550
|
const headers = new Headers(mcpResponse.headers);
|
|
496
551
|
headers.delete("Transfer-Encoding");
|
|
@@ -529,6 +584,16 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
529
584
|
const prefix = prefixParam ?? this.prefix ?? "";
|
|
530
585
|
const { normalizedPath, paramNames } = normalizeRouteParams(`${prefix}${route.path}`);
|
|
531
586
|
const handler = async (ctx) => {
|
|
587
|
+
if (ctx.body === BODY_TOO_LARGE) {
|
|
588
|
+
let errorResponse = { error: "Request body too large" };
|
|
589
|
+
if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
|
|
590
|
+
errorResponse = this.bodyLimitOptions.onError(errorResponse);
|
|
591
|
+
} catch {}
|
|
592
|
+
return new Response(JSON.stringify(errorResponse), {
|
|
593
|
+
status: 413,
|
|
594
|
+
headers: { "Content-Type": "application/json" }
|
|
595
|
+
});
|
|
596
|
+
}
|
|
532
597
|
const authError = await this.checkRouteAuth(route, {
|
|
533
598
|
path: ctx.request.url ? new URL(ctx.request.url).pathname : ctx.path,
|
|
534
599
|
method: ctx.request.method,
|
|
@@ -545,11 +610,11 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
545
610
|
...authError.headers
|
|
546
611
|
}
|
|
547
612
|
});
|
|
548
|
-
if (this.mastra.getServer()?.auth) {
|
|
613
|
+
if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
|
|
549
614
|
const hasPermission = await loadHasPermission();
|
|
550
615
|
if (hasPermission) {
|
|
551
616
|
const userPermissions = ctx.requestContext.get("userPermissions");
|
|
552
|
-
const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
|
|
617
|
+
const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, ctx.requestContext);
|
|
553
618
|
if (permissionError) return new Response(JSON.stringify({
|
|
554
619
|
error: permissionError.error,
|
|
555
620
|
message: permissionError.message
|
|
@@ -565,21 +630,7 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
565
630
|
let body;
|
|
566
631
|
let bodyParseError;
|
|
567
632
|
if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
|
|
568
|
-
const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
|
|
569
|
-
const contentLength = ctx.request.headers.get("content-length");
|
|
570
633
|
const contentType = ctx.request.headers.get("content-type") || "";
|
|
571
|
-
const exceedsDeclaredLimit = maxSize !== void 0 && contentLength !== null && parseInt(contentLength, 10) > maxSize;
|
|
572
|
-
const exceedsStreamedJsonLimit = maxSize !== void 0 && contentLength === null && contentType.includes("application/json") && ctx.body !== void 0 && new TextEncoder().encode(JSON.stringify(ctx.body)).byteLength > maxSize;
|
|
573
|
-
if (exceedsDeclaredLimit || exceedsStreamedJsonLimit) {
|
|
574
|
-
let errorResponse = { error: "Request body too large" };
|
|
575
|
-
if (route.maxBodySize === void 0 && this.bodyLimitOptions) try {
|
|
576
|
-
errorResponse = this.bodyLimitOptions.onError(errorResponse);
|
|
577
|
-
} catch {}
|
|
578
|
-
return new Response(JSON.stringify(errorResponse), {
|
|
579
|
-
status: 413,
|
|
580
|
-
headers: { "Content-Type": "application/json" }
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
634
|
if (contentType.includes("multipart/form-data")) try {
|
|
584
635
|
body = ctx.body ? await this.parseFormData(ctx.body) : void 0;
|
|
585
636
|
} catch (error) {
|
|
@@ -736,29 +787,22 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
736
787
|
});
|
|
737
788
|
const customResponse = getCustomHTTPExceptionResponse(error);
|
|
738
789
|
if (customResponse) return customResponse;
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
return new Response(JSON.stringify({ error: error instanceof Error ? error.message : "Unknown error" }), {
|
|
743
|
-
status,
|
|
744
|
-
headers: { "Content-Type": "application/json" }
|
|
745
|
-
});
|
|
746
|
-
}
|
|
747
|
-
if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
|
|
748
|
-
const status = error.details.status;
|
|
749
|
-
return new Response(JSON.stringify({ error: error instanceof Error ? error.message : "Unknown error" }), {
|
|
750
|
-
status,
|
|
751
|
-
headers: { "Content-Type": "application/json" }
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
return new Response(JSON.stringify({ error: error instanceof Error ? error.message : "Unknown error" }), {
|
|
756
|
-
status: 500,
|
|
790
|
+
const { status, body } = getHTTPErrorResponse(error);
|
|
791
|
+
return new Response(JSON.stringify(body), {
|
|
792
|
+
status,
|
|
757
793
|
headers: { "Content-Type": "application/json" }
|
|
758
794
|
});
|
|
759
795
|
}
|
|
760
796
|
};
|
|
761
|
-
|
|
797
|
+
const method = route.method.toLowerCase();
|
|
798
|
+
const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
|
|
799
|
+
if ([
|
|
800
|
+
"POST",
|
|
801
|
+
"PUT",
|
|
802
|
+
"PATCH",
|
|
803
|
+
"DELETE"
|
|
804
|
+
].includes(route.method) && maxSize !== void 0) app[method](normalizedPath, handler, { parse: createBodyLimitParser(maxSize) });
|
|
805
|
+
else app[method](normalizedPath, handler);
|
|
762
806
|
}
|
|
763
807
|
async registerCustomApiRoutes() {
|
|
764
808
|
const routes = await this.registerSchemaApiRoutes();
|
|
@@ -799,11 +843,11 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
799
843
|
...authError.headers
|
|
800
844
|
}
|
|
801
845
|
});
|
|
802
|
-
if (this.mastra.getServer()?.auth) {
|
|
846
|
+
if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
|
|
803
847
|
const hasPermission = await loadHasPermission();
|
|
804
848
|
if (hasPermission) {
|
|
805
849
|
const userPermissions = ctx.requestContext.get("userPermissions");
|
|
806
|
-
const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
|
|
850
|
+
const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission, ctx.requestContext);
|
|
807
851
|
if (permissionError) return new Response(JSON.stringify({
|
|
808
852
|
error: permissionError.error,
|
|
809
853
|
message: permissionError.message
|
|
@@ -815,9 +859,9 @@ var MastraServer = class extends MastraServer$1 {
|
|
|
815
859
|
}
|
|
816
860
|
}
|
|
817
861
|
const fgaError = await checkRouteFGA(this.mastra, serverRoute, ctx.requestContext, {
|
|
818
|
-
...matchedRoute?.params ?? {},
|
|
819
862
|
...ctx.query,
|
|
820
|
-
...typeof ctx.body === "object" && ctx.body !== null ? ctx.body : {}
|
|
863
|
+
...typeof ctx.body === "object" && ctx.body !== null ? ctx.body : {},
|
|
864
|
+
...matchedRoute?.params ?? {}
|
|
821
865
|
});
|
|
822
866
|
if (fgaError) return new Response(JSON.stringify({
|
|
823
867
|
error: fgaError.error,
|