@mastra/hono 0.0.0-main-test-2-20251127211532 → 0.0.0-mastra-auto-detect-server-20260108233416

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.js CHANGED
@@ -1,17 +1,29 @@
1
- import { InMemoryTaskStore } from '@mastra/server/a2a/store';
2
- import { MastraServerAdapter } from '@mastra/server/server-adapter';
1
+ import { formatZodError } from '@mastra/server/handlers/error';
2
+ import { MastraServer as MastraServer$1, normalizeQueryParams, redactStreamChunk } from '@mastra/server/server-adapter';
3
+ import { toReqRes, toFetchResponse } from 'fetch-to-node';
4
+ import { isDevPlaygroundRequest, isProtectedPath, canAccessPublicly, checkRules, defaultAuthConfig } from '@mastra/server/auth';
3
5
 
4
6
  // src/index.ts
5
7
 
6
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/http-exception.js
8
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/http-exception.js
7
9
  var HTTPException = class extends Error {
8
10
  res;
9
11
  status;
12
+ /**
13
+ * Creates an instance of `HTTPException`.
14
+ * @param status - HTTP status code for the exception. Defaults to 500.
15
+ * @param options - Additional options for the exception.
16
+ */
10
17
  constructor(status = 500, options) {
11
18
  super(options?.message, { cause: options?.cause });
12
19
  this.res = options?.res;
13
20
  this.status = status;
14
21
  }
22
+ /**
23
+ * Returns the response object associated with the exception.
24
+ * If a response object is not provided, a new response is created with the error message and status code.
25
+ * @returns The response object.
26
+ */
15
27
  getResponse() {
16
28
  if (this.res) {
17
29
  const newResponse = new Response(this.res.body, {
@@ -26,7 +38,7 @@ var HTTPException = class extends Error {
26
38
  }
27
39
  };
28
40
 
29
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/middleware/body-limit/index.js
41
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/middleware/body-limit/index.js
30
42
  var ERROR_MESSAGE = "Payload Too Large";
31
43
  var BodyLimitError = class extends Error {
32
44
  constructor(message) {
@@ -83,14 +95,20 @@ var bodyLimit = (options) => {
83
95
  };
84
96
  };
85
97
 
86
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/utils/stream.js
98
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/stream.js
87
99
  var StreamingApi = class {
88
100
  writer;
89
101
  encoder;
90
102
  writable;
91
103
  abortSubscribers = [];
92
104
  responseReadable;
105
+ /**
106
+ * Whether the stream has been aborted.
107
+ */
93
108
  aborted = false;
109
+ /**
110
+ * Whether the stream has been closed normally.
111
+ */
94
112
  closed = false;
95
113
  constructor(writable, _readable) {
96
114
  this.writable = writable;
@@ -142,6 +160,10 @@ var StreamingApi = class {
142
160
  onAbort(listener) {
143
161
  this.abortSubscribers.push(listener);
144
162
  }
163
+ /**
164
+ * Abort the stream.
165
+ * You can call this method when stream is aborted by external event.
166
+ */
145
167
  abort() {
146
168
  if (!this.aborted) {
147
169
  this.aborted = true;
@@ -150,7 +172,7 @@ var StreamingApi = class {
150
172
  }
151
173
  };
152
174
 
153
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/helper/streaming/utils.js
175
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/helper/streaming/utils.js
154
176
  var isOldBunVersion = () => {
155
177
  const version = typeof Bun !== "undefined" ? Bun.version : void 0;
156
178
  if (version === void 0) {
@@ -161,7 +183,7 @@ var isOldBunVersion = () => {
161
183
  return result;
162
184
  };
163
185
 
164
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/helper/streaming/stream.js
186
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/helper/streaming/stream.js
165
187
  var contextStash = /* @__PURE__ */ new WeakMap();
166
188
  var stream = (c, cb, onError) => {
167
189
  const { readable, writable } = new TransformStream();
@@ -190,27 +212,318 @@ var stream = (c, cb, onError) => {
190
212
  return c.newResponse(stream2.responseReadable);
191
213
  };
192
214
 
193
- // src/index.ts
194
- var HonoServerAdapter = class extends MastraServerAdapter {
195
- taskStore;
196
- customRouteAuthConfig;
197
- playground;
198
- isDev;
199
- constructor({
200
- mastra,
201
- tools,
202
- taskStore,
203
- customRouteAuthConfig,
204
- playground,
205
- isDev,
206
- bodyLimitOptions
207
- }) {
208
- super({ mastra, bodyLimitOptions, tools });
209
- this.taskStore = taskStore || new InMemoryTaskStore();
210
- this.customRouteAuthConfig = customRouteAuthConfig;
211
- this.playground = playground;
212
- this.isDev = isDev;
215
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
216
+ var util;
217
+ (function(util2) {
218
+ util2.assertEqual = (_) => {
219
+ };
220
+ function assertIs(_arg) {
221
+ }
222
+ util2.assertIs = assertIs;
223
+ function assertNever(_x) {
224
+ throw new Error();
225
+ }
226
+ util2.assertNever = assertNever;
227
+ util2.arrayToEnum = (items) => {
228
+ const obj = {};
229
+ for (const item of items) {
230
+ obj[item] = item;
231
+ }
232
+ return obj;
233
+ };
234
+ util2.getValidEnumValues = (obj) => {
235
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
236
+ const filtered = {};
237
+ for (const k of validKeys) {
238
+ filtered[k] = obj[k];
239
+ }
240
+ return util2.objectValues(filtered);
241
+ };
242
+ util2.objectValues = (obj) => {
243
+ return util2.objectKeys(obj).map(function(e) {
244
+ return obj[e];
245
+ });
246
+ };
247
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
248
+ const keys = [];
249
+ for (const key in object) {
250
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
251
+ keys.push(key);
252
+ }
253
+ }
254
+ return keys;
255
+ };
256
+ util2.find = (arr, checker) => {
257
+ for (const item of arr) {
258
+ if (checker(item))
259
+ return item;
260
+ }
261
+ return void 0;
262
+ };
263
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
264
+ function joinValues(array, separator = " | ") {
265
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
266
+ }
267
+ util2.joinValues = joinValues;
268
+ util2.jsonStringifyReplacer = (_, value) => {
269
+ if (typeof value === "bigint") {
270
+ return value.toString();
271
+ }
272
+ return value;
273
+ };
274
+ })(util || (util = {}));
275
+ var objectUtil;
276
+ (function(objectUtil2) {
277
+ objectUtil2.mergeShapes = (first, second) => {
278
+ return {
279
+ ...first,
280
+ ...second
281
+ // second overwrites first
282
+ };
283
+ };
284
+ })(objectUtil || (objectUtil = {}));
285
+ util.arrayToEnum([
286
+ "string",
287
+ "nan",
288
+ "number",
289
+ "integer",
290
+ "float",
291
+ "boolean",
292
+ "date",
293
+ "bigint",
294
+ "symbol",
295
+ "function",
296
+ "undefined",
297
+ "null",
298
+ "array",
299
+ "object",
300
+ "unknown",
301
+ "promise",
302
+ "void",
303
+ "never",
304
+ "map",
305
+ "set"
306
+ ]);
307
+
308
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
309
+ util.arrayToEnum([
310
+ "invalid_type",
311
+ "invalid_literal",
312
+ "custom",
313
+ "invalid_union",
314
+ "invalid_union_discriminator",
315
+ "invalid_enum_value",
316
+ "unrecognized_keys",
317
+ "invalid_arguments",
318
+ "invalid_return_type",
319
+ "invalid_date",
320
+ "invalid_string",
321
+ "too_small",
322
+ "too_big",
323
+ "invalid_intersection_types",
324
+ "not_multiple_of",
325
+ "not_finite"
326
+ ]);
327
+ var ZodError = class _ZodError extends Error {
328
+ get errors() {
329
+ return this.issues;
330
+ }
331
+ constructor(issues) {
332
+ super();
333
+ this.issues = [];
334
+ this.addIssue = (sub) => {
335
+ this.issues = [...this.issues, sub];
336
+ };
337
+ this.addIssues = (subs = []) => {
338
+ this.issues = [...this.issues, ...subs];
339
+ };
340
+ const actualProto = new.target.prototype;
341
+ if (Object.setPrototypeOf) {
342
+ Object.setPrototypeOf(this, actualProto);
343
+ } else {
344
+ this.__proto__ = actualProto;
345
+ }
346
+ this.name = "ZodError";
347
+ this.issues = issues;
348
+ }
349
+ format(_mapper) {
350
+ const mapper = _mapper || function(issue) {
351
+ return issue.message;
352
+ };
353
+ const fieldErrors = { _errors: [] };
354
+ const processError = (error) => {
355
+ for (const issue of error.issues) {
356
+ if (issue.code === "invalid_union") {
357
+ issue.unionErrors.map(processError);
358
+ } else if (issue.code === "invalid_return_type") {
359
+ processError(issue.returnTypeError);
360
+ } else if (issue.code === "invalid_arguments") {
361
+ processError(issue.argumentsError);
362
+ } else if (issue.path.length === 0) {
363
+ fieldErrors._errors.push(mapper(issue));
364
+ } else {
365
+ let curr = fieldErrors;
366
+ let i = 0;
367
+ while (i < issue.path.length) {
368
+ const el = issue.path[i];
369
+ const terminal = i === issue.path.length - 1;
370
+ if (!terminal) {
371
+ curr[el] = curr[el] || { _errors: [] };
372
+ } else {
373
+ curr[el] = curr[el] || { _errors: [] };
374
+ curr[el]._errors.push(mapper(issue));
375
+ }
376
+ curr = curr[el];
377
+ i++;
378
+ }
379
+ }
380
+ }
381
+ };
382
+ processError(this);
383
+ return fieldErrors;
384
+ }
385
+ static assert(value) {
386
+ if (!(value instanceof _ZodError)) {
387
+ throw new Error(`Not a ZodError: ${value}`);
388
+ }
389
+ }
390
+ toString() {
391
+ return this.message;
392
+ }
393
+ get message() {
394
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
395
+ }
396
+ get isEmpty() {
397
+ return this.issues.length === 0;
398
+ }
399
+ flatten(mapper = (issue) => issue.message) {
400
+ const fieldErrors = {};
401
+ const formErrors = [];
402
+ for (const sub of this.issues) {
403
+ if (sub.path.length > 0) {
404
+ const firstEl = sub.path[0];
405
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
406
+ fieldErrors[firstEl].push(mapper(sub));
407
+ } else {
408
+ formErrors.push(mapper(sub));
409
+ }
410
+ }
411
+ return { formErrors, fieldErrors };
412
+ }
413
+ get formErrors() {
414
+ return this.flatten();
415
+ }
416
+ };
417
+ ZodError.create = (issues) => {
418
+ const error = new ZodError(issues);
419
+ return error;
420
+ };
421
+ var authenticationMiddleware = async (c, next) => {
422
+ const mastra = c.get("mastra");
423
+ const authConfig = mastra.getServer()?.auth;
424
+ const customRouteAuthConfig = c.get("customRouteAuthConfig");
425
+ if (!authConfig) {
426
+ return next();
427
+ }
428
+ const path = c.req.path;
429
+ const method = c.req.method;
430
+ const getHeader = (name) => c.req.header(name);
431
+ if (isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
432
+ return next();
433
+ }
434
+ if (!isProtectedPath(c.req.path, c.req.method, authConfig, customRouteAuthConfig)) {
435
+ return next();
436
+ }
437
+ if (canAccessPublicly(c.req.path, c.req.method, authConfig)) {
438
+ return next();
439
+ }
440
+ const authHeader = c.req.header("Authorization");
441
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
442
+ if (!token && c.req.query("apiKey")) {
443
+ token = c.req.query("apiKey") || null;
444
+ }
445
+ if (!token) {
446
+ return c.json({ error: "Authentication required" }, 401);
447
+ }
448
+ try {
449
+ let user;
450
+ if (typeof authConfig.authenticateToken === "function") {
451
+ user = await authConfig.authenticateToken(token, c.req);
452
+ } else {
453
+ throw new Error("No token verification method configured");
454
+ }
455
+ if (!user) {
456
+ return c.json({ error: "Invalid or expired token" }, 401);
457
+ }
458
+ c.get("requestContext").set("user", user);
459
+ return next();
460
+ } catch (err) {
461
+ console.error(err);
462
+ return c.json({ error: "Invalid or expired token" }, 401);
463
+ }
464
+ };
465
+ var authorizationMiddleware = async (c, next) => {
466
+ const mastra = c.get("mastra");
467
+ const authConfig = mastra.getServer()?.auth;
468
+ const customRouteAuthConfig = c.get("customRouteAuthConfig");
469
+ if (!authConfig) {
470
+ return next();
471
+ }
472
+ const path = c.req.path;
473
+ const method = c.req.method;
474
+ const getHeader = (name) => c.req.header(name);
475
+ if (isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
476
+ return next();
477
+ }
478
+ if (!isProtectedPath(c.req.path, c.req.method, authConfig, customRouteAuthConfig)) {
479
+ return next();
480
+ }
481
+ if (canAccessPublicly(path, method, authConfig)) {
482
+ return next();
483
+ }
484
+ const user = c.get("requestContext").get("user");
485
+ if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
486
+ try {
487
+ const isAuthorized = await authConfig.authorizeUser(user, c.req);
488
+ if (isAuthorized) {
489
+ return next();
490
+ }
491
+ return c.json({ error: "Access denied" }, 403);
492
+ } catch (err) {
493
+ console.error(err);
494
+ return c.json({ error: "Authorization error" }, 500);
495
+ }
496
+ }
497
+ if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
498
+ try {
499
+ const isAuthorized = await authConfig.authorize(path, method, user, c);
500
+ if (isAuthorized) {
501
+ return next();
502
+ }
503
+ return c.json({ error: "Access denied" }, 403);
504
+ } catch (err) {
505
+ console.error(err);
506
+ return c.json({ error: "Authorization error" }, 500);
507
+ }
213
508
  }
509
+ if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
510
+ const isAuthorized = await checkRules(authConfig.rules, path, method, user);
511
+ if (isAuthorized) {
512
+ return next();
513
+ }
514
+ return c.json({ error: "Access denied" }, 403);
515
+ }
516
+ if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
517
+ const isAuthorized = await checkRules(defaultAuthConfig.rules, path, method, user);
518
+ if (isAuthorized) {
519
+ return next();
520
+ }
521
+ }
522
+ return c.json({ error: "Access denied" }, 403);
523
+ };
524
+
525
+ // src/index.ts
526
+ var MastraServer = class extends MastraServer$1 {
214
527
  createContextMiddleware() {
215
528
  return async (c, next) => {
216
529
  let bodyRequestContext;
@@ -250,10 +563,8 @@ var HonoServerAdapter = class extends MastraServerAdapter {
250
563
  c.set("mastra", this.mastra);
251
564
  c.set("tools", this.tools || {});
252
565
  c.set("taskStore", this.taskStore);
253
- c.set("playground", this.playground === true);
254
- c.set("isDev", this.isDev === true);
255
- c.set("customRouteAuthConfig", this.customRouteAuthConfig);
256
566
  c.set("abortSignal", c.req.raw.signal);
567
+ c.set("customRouteAuthConfig", this.customRouteAuthConfig);
257
568
  return next();
258
569
  };
259
570
  }
@@ -274,12 +585,14 @@ var HonoServerAdapter = class extends MastraServerAdapter {
274
585
  const { done, value } = await reader.read();
275
586
  if (done) break;
276
587
  if (value) {
588
+ const shouldRedact = this.streamOptions?.redact ?? true;
589
+ const outputValue = shouldRedact ? redactStreamChunk(value) : value;
277
590
  if (streamFormat === "sse") {
278
- await stream2.write(`data: ${JSON.stringify(value)}
591
+ await stream2.write(`data: ${JSON.stringify(outputValue)}
279
592
 
280
593
  `);
281
594
  } else {
282
- await stream2.write(JSON.stringify(value) + "");
595
+ await stream2.write(JSON.stringify(outputValue) + "");
283
596
  }
284
597
  }
285
598
  }
@@ -297,16 +610,51 @@ var HonoServerAdapter = class extends MastraServerAdapter {
297
610
  }
298
611
  async getParams(route, request) {
299
612
  const urlParams = request.param();
300
- const queryParams = request.query();
613
+ const queryParams = normalizeQueryParams(request.queries());
301
614
  let body;
302
615
  if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH") {
303
- try {
304
- body = await request.json();
305
- } catch {
616
+ const contentType = request.header("content-type") || "";
617
+ if (contentType.includes("multipart/form-data")) {
618
+ try {
619
+ const formData = await request.formData();
620
+ body = await this.parseFormData(formData);
621
+ } catch (error) {
622
+ console.error("Failed to parse multipart form data:", error);
623
+ if (error instanceof Error && error.message.toLowerCase().includes("size")) {
624
+ throw error;
625
+ }
626
+ }
627
+ } else {
628
+ try {
629
+ body = await request.json();
630
+ } catch (error) {
631
+ console.error("Failed to parse JSON body:", error);
632
+ }
306
633
  }
307
634
  }
308
635
  return { urlParams, queryParams, body };
309
636
  }
637
+ /**
638
+ * Parse FormData into a plain object, converting File objects to Buffers.
639
+ */
640
+ async parseFormData(formData) {
641
+ const result = {};
642
+ for (const [key, value] of formData.entries()) {
643
+ if (value instanceof File) {
644
+ const arrayBuffer = await value.arrayBuffer();
645
+ result[key] = Buffer.from(arrayBuffer);
646
+ } else if (typeof value === "string") {
647
+ try {
648
+ result[key] = JSON.parse(value);
649
+ } catch {
650
+ result[key] = value;
651
+ }
652
+ } else {
653
+ result[key] = value;
654
+ }
655
+ }
656
+ return result;
657
+ }
310
658
  async sendResponse(route, response, result) {
311
659
  if (route.responseType === "json") {
312
660
  return response.json(result, 200);
@@ -315,6 +663,43 @@ var HonoServerAdapter = class extends MastraServerAdapter {
315
663
  } else if (route.responseType === "datastream-response") {
316
664
  const fetchResponse = result;
317
665
  return fetchResponse;
666
+ } else if (route.responseType === "mcp-http") {
667
+ const { server, httpPath } = result;
668
+ const { req, res } = toReqRes(response.req.raw);
669
+ try {
670
+ await server.startHTTP({
671
+ url: new URL(response.req.url),
672
+ httpPath,
673
+ req,
674
+ res
675
+ });
676
+ return await toFetchResponse(res);
677
+ } catch {
678
+ if (!res.headersSent) {
679
+ res.writeHead(500, { "Content-Type": "application/json" });
680
+ res.end(
681
+ JSON.stringify({
682
+ jsonrpc: "2.0",
683
+ error: { code: -32603, message: "Internal server error" },
684
+ id: null
685
+ })
686
+ );
687
+ return await toFetchResponse(res);
688
+ }
689
+ return await toFetchResponse(res);
690
+ }
691
+ } else if (route.responseType === "mcp-sse") {
692
+ const { server, ssePath, messagePath } = result;
693
+ try {
694
+ return await server.startHonoSSE({
695
+ url: new URL(response.req.url),
696
+ ssePath,
697
+ messagePath,
698
+ context: response
699
+ });
700
+ } catch {
701
+ return response.json({ error: "Error handling MCP SSE request" }, 500);
702
+ }
318
703
  } else {
319
704
  return response.status(500);
320
705
  }
@@ -341,10 +726,13 @@ var HonoServerAdapter = class extends MastraServerAdapter {
341
726
  params.queryParams = await this.parseQueryParams(route, params.queryParams);
342
727
  } catch (error) {
343
728
  console.error("Error parsing query params", error);
729
+ if (error instanceof ZodError) {
730
+ return c.json(formatZodError(error, "query parameters"), 400);
731
+ }
344
732
  return c.json(
345
733
  {
346
734
  error: "Invalid query parameters",
347
- details: error instanceof Error ? error.message : "Unknown error"
735
+ issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
348
736
  },
349
737
  400
350
738
  );
@@ -354,11 +742,14 @@ var HonoServerAdapter = class extends MastraServerAdapter {
354
742
  try {
355
743
  params.body = await this.parseBody(route, params.body);
356
744
  } catch (error) {
357
- console.error("Error parsing body", error);
745
+ console.error("Error parsing body:", error instanceof Error ? error.message : String(error));
746
+ if (error instanceof ZodError) {
747
+ return c.json(formatZodError(error, "request body"), 400);
748
+ }
358
749
  return c.json(
359
750
  {
360
751
  error: "Invalid request body",
361
- details: error instanceof Error ? error.message : "Unknown error"
752
+ issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
362
753
  },
363
754
  400
364
755
  );
@@ -394,14 +785,19 @@ var HonoServerAdapter = class extends MastraServerAdapter {
394
785
  }
395
786
  );
396
787
  }
397
- registerContextMiddleware(app) {
398
- app.use("*", this.createContextMiddleware());
788
+ registerContextMiddleware() {
789
+ this.app.use("*", this.createContextMiddleware());
399
790
  }
400
- async registerRoutes(app, { prefix, openapiPath }) {
401
- await super.registerRoutes(app, { prefix, openapiPath });
791
+ registerAuthMiddleware() {
792
+ const authConfig = this.mastra.getServer()?.auth;
793
+ if (!authConfig) {
794
+ return;
795
+ }
796
+ this.app.use("*", authenticationMiddleware);
797
+ this.app.use("*", authorizationMiddleware);
402
798
  }
403
799
  };
404
800
 
405
- export { HonoServerAdapter };
801
+ export { MastraServer };
406
802
  //# sourceMappingURL=index.js.map
407
803
  //# sourceMappingURL=index.js.map