@mastra/elysia 0.1.19 → 0.1.20-alpha.0

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