@mastra/elysia 0.1.23-alpha.1 → 0.1.23-alpha.10

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 CHANGED
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _mastra_server_auth = require("@mastra/server/auth");
3
2
  let _mastra_server_server_adapter = require("@mastra/server/server-adapter");
4
3
  let fetch_to_node = require("fetch-to-node");
5
4
  let _mastra_core_request_context = require("@mastra/core/request-context");
5
+ let _mastra_server_auth = require("@mastra/server/auth");
6
6
  let elysia_cookies = require("elysia/cookies");
7
7
  // src/auth-middleware.ts
8
8
  const pendingRefreshHeaders = /* @__PURE__ */ new WeakMap();
@@ -203,6 +203,13 @@ function clearMastraOpenAPICache(server) {
203
203
  }
204
204
  // src/index.ts
205
205
  const BODY_TOO_LARGE = Symbol("mastra.elysia.bodyTooLarge");
206
+ const EMPTY_JSON_BODY = Symbol("mastra.elysia.emptyJsonBody");
207
+ var InvalidJsonBody = class {
208
+ message;
209
+ constructor(message) {
210
+ this.message = message;
211
+ }
212
+ };
206
213
  async function readBodyWithLimit(body, maxSize) {
207
214
  const reader = body.getReader();
208
215
  const chunks = [];
@@ -226,18 +233,33 @@ async function readBodyWithLimit(body, maxSize) {
226
233
  return bytes;
227
234
  }
228
235
  /**
229
- * Route-level Elysia parse hook that enforces the body limit before Elysia's
230
- * default parsers buffer the request. Oversized bodies are marked with
231
- * BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.
236
+ * Route-level Elysia parse hook for body methods.
237
+ *
238
+ * Parses JSON bodies itself: under `@elysiajs/node` an empty request still has a body stream, so Elysia's default
239
+ * JSON parser throws on it and the request fails with 400 before the route runs. An empty JSON body comes back as
240
+ * EMPTY_JSON_BODY and malformed JSON as InvalidJsonBody, both resolved by the route handler.
241
+ *
242
+ * With a `maxSize`, also enforces the body limit before anything buffers the request. Oversized bodies are marked
243
+ * with BODY_TOO_LARGE (rejected with 413 by the route handler) without being read in full.
232
244
  */
233
- function createBodyLimitParser(maxSize) {
245
+ function createBodyParser(maxSize) {
234
246
  return async (ctx) => {
235
247
  const request = ctx.request;
236
248
  const contentLength = request.headers.get("content-length");
237
- if (contentLength !== null && parseInt(contentLength, 10) > maxSize) return BODY_TOO_LARGE;
238
- if (!request.body) return void 0;
239
- const bytes = await readBodyWithLimit(request.body, maxSize);
249
+ if (maxSize !== void 0 && contentLength !== null && parseInt(contentLength, 10) > maxSize) return BODY_TOO_LARGE;
250
+ const isJson = (request.headers.get("content-type") ?? "").includes("application/json");
251
+ if (!request.body || !isJson && maxSize === void 0) return void 0;
252
+ const bytes = maxSize === void 0 ? new Uint8Array(await request.arrayBuffer()) : await readBodyWithLimit(request.body, maxSize);
240
253
  if (!bytes) return BODY_TOO_LARGE;
254
+ if (isJson) {
255
+ const text = new TextDecoder().decode(bytes);
256
+ if (text.trim().length === 0) return EMPTY_JSON_BODY;
257
+ try {
258
+ return JSON.parse(text);
259
+ } catch (error) {
260
+ return new InvalidJsonBody(error instanceof Error ? error.message : "Invalid JSON in request body");
261
+ }
262
+ }
241
263
  ctx.request = new Request(request.url, {
242
264
  method: request.method,
243
265
  headers: request.headers,
@@ -313,6 +335,39 @@ async function createForwardRequest(ctx) {
313
335
  ...body ? { duplex: "half" } : {}
314
336
  });
315
337
  }
338
+ /**
339
+ * srvx, which runs `@elysiajs/node`, creates `request.signal` on first access and only then listens for the response
340
+ * 'close'. A client that left during an earlier hook therefore never aborts it, so check the Node response directly.
341
+ */
342
+ function getRequestAbortSignal(request) {
343
+ const signal = request.signal;
344
+ return (request.runtime?.node?.res)?.destroyed && !signal.aborted ? AbortSignal.abort() : signal;
345
+ }
346
+ function getRequestSignal(ctx) {
347
+ const context = ctx;
348
+ return context?.abortSignal ?? (context?.request ? getRequestAbortSignal(context.request) : void 0);
349
+ }
350
+ /**
351
+ * Cancels `reader` once, through `cancel()` or when the request signal aborts. A runtime that skips the response body
352
+ * of a request that closed while the route handler ran never cancels that body, so the signal is the only notice.
353
+ */
354
+ function cancelReaderOnRequestAbort(reader, signal) {
355
+ let canceled = false;
356
+ const onAbort = () => cancel("request aborted");
357
+ const dispose = () => signal?.removeEventListener("abort", onAbort);
358
+ const cancel = (reason) => {
359
+ if (canceled) return;
360
+ canceled = true;
361
+ dispose();
362
+ reader.cancel(reason).catch(() => {});
363
+ };
364
+ if (signal?.aborted) onAbort();
365
+ else signal?.addEventListener("abort", onAbort, { once: true });
366
+ return {
367
+ cancel,
368
+ dispose
369
+ };
370
+ }
316
371
  function createSafeReadableStream(body) {
317
372
  if (!body) return null;
318
373
  return new ReadableStream({ async start(controller) {
@@ -329,6 +384,37 @@ function createSafeReadableStream(body) {
329
384
  }
330
385
  } });
331
386
  }
387
+ /**
388
+ * Wraps a `datastream-response` body so a client disconnect cancels the upstream body. Unlike
389
+ * `createSafeReadableStream`, it reads one chunk per pull, so a slow client slows the upstream.
390
+ */
391
+ function createDatastreamBody(body, signal) {
392
+ if (!body) return null;
393
+ const reader = body.getReader();
394
+ const upstream = cancelReaderOnRequestAbort(reader, signal);
395
+ let finished = false;
396
+ return new ReadableStream({
397
+ async pull(controller) {
398
+ try {
399
+ const { done, value } = await reader.read();
400
+ if (finished) return;
401
+ if (!done) {
402
+ controller.enqueue(value);
403
+ return;
404
+ }
405
+ } catch {
406
+ if (finished) return;
407
+ }
408
+ finished = true;
409
+ upstream.dispose();
410
+ controller.close();
411
+ },
412
+ cancel(reason) {
413
+ finished = true;
414
+ upstream.cancel(reason);
415
+ }
416
+ });
417
+ }
332
418
  let _hasPermissionPromise;
333
419
  function loadHasPermission() {
334
420
  if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
@@ -371,12 +457,12 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
371
457
  mastra: this.mastra,
372
458
  registeredTools: this.tools || {},
373
459
  taskStore: this.taskStore,
374
- abortSignal: ctx.request.signal,
460
+ abortSignal: getRequestAbortSignal(ctx.request),
375
461
  customRouteAuthConfig: this.customRouteAuthConfig
376
462
  };
377
463
  };
378
464
  }
379
- async stream(route, _res, result) {
465
+ async stream(route, ctx, result) {
380
466
  const streamFormat = route.streamFormat || "stream";
381
467
  const encoder = new TextEncoder();
382
468
  const headers = streamFormat === "sse" ? {
@@ -386,50 +472,57 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
386
472
  "X-Accel-Buffering": "no"
387
473
  } : { "Content-Type": "text/plain" };
388
474
  const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
389
- let cancelled = false;
475
+ const upstream = cancelReaderOnRequestAbort(reader, getRequestSignal(ctx));
476
+ let finished = false;
390
477
  const stream = new ReadableStream({
391
- start: async (controller) => {
478
+ start: (controller) => {
479
+ if (streamFormat === "sse" && route.sseFlushOnConnect) controller.enqueue(encoder.encode(": connected\n\n"));
480
+ },
481
+ pull: async (controller) => {
392
482
  try {
393
- if (streamFormat === "sse" && route.sseFlushOnConnect) controller.enqueue(encoder.encode(": connected\n\n"));
394
483
  while (true) {
395
484
  const { done, value } = await reader.read();
396
- if (done || cancelled) break;
397
- if (value) {
398
- if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
399
- controller.enqueue(encoder.encode(value));
400
- continue;
401
- }
402
- const outputValue = this.streamOptions?.redact ?? true ? (0, _mastra_server_server_adapter.redactStreamChunk)(value) : value;
403
- const serialized = (0, _mastra_server_server_adapter.serializeStreamChunk)(outputValue);
404
- if (!serialized.ok) {
405
- this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
406
- path: route.path,
407
- chunkType: outputValue?.type,
408
- error: serialized.error.message
409
- });
410
- continue;
411
- }
412
- if (streamFormat === "sse") controller.enqueue(encoder.encode(`data: ${serialized.json}\n\n`));
413
- else controller.enqueue(encoder.encode(serialized.json + ""));
485
+ if (finished) return;
486
+ if (done) {
487
+ finished = true;
488
+ upstream.dispose();
489
+ if (streamFormat === "sse") controller.enqueue(encoder.encode("data: [DONE]\n\n"));
490
+ controller.close();
491
+ return;
492
+ }
493
+ if (!value) continue;
494
+ if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
495
+ controller.enqueue(encoder.encode(value));
496
+ return;
414
497
  }
498
+ const outputValue = this.streamOptions?.redact ?? true ? (0, _mastra_server_server_adapter.redactStreamChunk)(value) : value;
499
+ const serialized = (0, _mastra_server_server_adapter.serializeStreamChunk)(outputValue);
500
+ if (!serialized.ok) {
501
+ this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
502
+ path: route.path,
503
+ chunkType: outputValue?.type,
504
+ error: serialized.error.message
505
+ });
506
+ continue;
507
+ }
508
+ if (streamFormat === "sse") controller.enqueue(encoder.encode(`data: ${serialized.json}\n\n`));
509
+ else controller.enqueue(encoder.encode(serialized.json + ""));
510
+ return;
415
511
  }
416
- if (cancelled) return;
417
- if (streamFormat === "sse") controller.enqueue(encoder.encode("data: [DONE]\n\n"));
418
- controller.close();
419
512
  } catch (error) {
420
- if (cancelled) return;
513
+ if (finished) return;
514
+ finished = true;
515
+ upstream.dispose();
421
516
  this.mastra.getLogger()?.error("Error in stream processing", { error: error instanceof Error ? {
422
517
  message: error.message,
423
518
  stack: error.stack
424
519
  } : error });
425
- controller.error(error);
426
- } finally {
427
- await reader.cancel();
520
+ controller.close();
428
521
  }
429
522
  },
430
- cancel: async (reason) => {
431
- cancelled = true;
432
- await reader.cancel(reason);
523
+ cancel: (reason) => {
524
+ finished = true;
525
+ upstream.cancel(reason);
433
526
  }
434
527
  });
435
528
  return new Response(stream, { headers });
@@ -530,7 +623,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
530
623
  const fetchResponse = result;
531
624
  const headers = new Headers(fetchResponse.headers);
532
625
  headers.delete("Transfer-Encoding");
533
- return new Response(createSafeReadableStream(fetchResponse.body), {
626
+ return new Response(createDatastreamBody(fetchResponse.body, getRequestSignal(response)), {
534
627
  status: fetchResponse.status,
535
628
  statusText: fetchResponse.statusText,
536
629
  headers
@@ -665,19 +758,11 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
665
758
  bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
666
759
  }
667
760
  else if (contentType.includes("application/json")) {
668
- body = ctx.body;
669
- if (body === void 0 && contentType.includes("application/json")) {
670
- const bodyText = await ctx.request.clone().text();
671
- if (bodyText && bodyText.trim().length > 0) try {
672
- body = JSON.parse(bodyText);
673
- } catch (error) {
674
- this.mastra.getLogger()?.error("Failed to parse JSON body", { error: error instanceof Error ? {
675
- message: error.message,
676
- stack: error.stack
677
- } : error });
678
- bodyParseError = { message: error instanceof Error ? error.message : "Invalid JSON in request body" };
679
- }
680
- }
761
+ if (ctx.body instanceof InvalidJsonBody) {
762
+ this.mastra.getLogger()?.error("Failed to parse JSON body", { error: { message: ctx.body.message } });
763
+ bodyParseError = { message: ctx.body.message };
764
+ } else if (ctx.body !== EMPTY_JSON_BODY) body = ctx.body;
765
+ ctx.body = body;
681
766
  }
682
767
  }
683
768
  const params = {
@@ -827,7 +912,7 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
827
912
  "PUT",
828
913
  "PATCH",
829
914
  "DELETE"
830
- ].includes(route.method) && maxSize !== void 0) app[method](normalizedPath, handler, { parse: createBodyLimitParser(maxSize) });
915
+ ].includes(route.method)) app[method](normalizedPath, handler, { parse: createBodyParser(maxSize) });
831
916
  else app[method](normalizedPath, handler);
832
917
  }
833
918
  async registerCustomApiRoutes() {
@@ -839,19 +924,9 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
839
924
  this.app[method](customNormalizedPath, async (ctx) => {
840
925
  const path = new URL(ctx.request.url).pathname;
841
926
  const requestMethod = ctx.request.method;
842
- const matchedRoute = (0, _mastra_server_auth.findMatchingCustomRoute)(path, requestMethod, this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes);
843
- const shouldRunCustomRouteAuth = (0, _mastra_server_auth.isProtectedCustomRoute)(path, requestMethod, this.customRouteAuthConfig);
927
+ const { match: matchedRoute, requiresAuth: shouldRunCustomRouteAuth, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(ctx.request.url, requestMethod, path, route);
844
928
  const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
845
929
  if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
846
- const serverRoute = {
847
- method: matchedRoute?.route.method ?? requestMethod,
848
- path: matchedRoute?.route.path ?? path,
849
- responseType: "json",
850
- handler: async () => {},
851
- requiresAuth: matchedRoute?.route.requiresAuth,
852
- requiresPermission: matchedRoute?.route.requiresPermission,
853
- fga: matchedRoute?.route.fga
854
- };
855
930
  if (shouldRunCustomRouteAuth) {
856
931
  const authError = await this.checkRouteAuth(serverRoute, {
857
932
  path,
@@ -860,7 +935,8 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
860
935
  getQuery: (name) => ctx.query?.[name],
861
936
  requestContext: ctx.requestContext,
862
937
  request: ctx.request,
863
- buildAuthorizeContext: () => ctx
938
+ buildAuthorizeContext: () => ctx,
939
+ customRouteAuthConfig
864
940
  });
865
941
  if (authError) return new Response(JSON.stringify({ error: authError.error }), {
866
942
  status: authError.status,