@mastra/koa 0.1.0-beta.15 → 0.1.0-beta.16

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 ADDED
@@ -0,0 +1,699 @@
1
+ 'use strict';
2
+
3
+ var busboy = require('@fastify/busboy');
4
+ var error = require('@mastra/server/handlers/error');
5
+ var serverAdapter = require('@mastra/server/server-adapter');
6
+ var auth = require('@mastra/server/auth');
7
+
8
+ // src/index.ts
9
+
10
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
11
+ var util;
12
+ (function(util2) {
13
+ util2.assertEqual = (_) => {
14
+ };
15
+ function assertIs(_arg) {
16
+ }
17
+ util2.assertIs = assertIs;
18
+ function assertNever(_x) {
19
+ throw new Error();
20
+ }
21
+ util2.assertNever = assertNever;
22
+ util2.arrayToEnum = (items) => {
23
+ const obj = {};
24
+ for (const item of items) {
25
+ obj[item] = item;
26
+ }
27
+ return obj;
28
+ };
29
+ util2.getValidEnumValues = (obj) => {
30
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
31
+ const filtered = {};
32
+ for (const k of validKeys) {
33
+ filtered[k] = obj[k];
34
+ }
35
+ return util2.objectValues(filtered);
36
+ };
37
+ util2.objectValues = (obj) => {
38
+ return util2.objectKeys(obj).map(function(e) {
39
+ return obj[e];
40
+ });
41
+ };
42
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
43
+ const keys = [];
44
+ for (const key in object) {
45
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
46
+ keys.push(key);
47
+ }
48
+ }
49
+ return keys;
50
+ };
51
+ util2.find = (arr, checker) => {
52
+ for (const item of arr) {
53
+ if (checker(item))
54
+ return item;
55
+ }
56
+ return void 0;
57
+ };
58
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
59
+ function joinValues(array, separator = " | ") {
60
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
61
+ }
62
+ util2.joinValues = joinValues;
63
+ util2.jsonStringifyReplacer = (_, value) => {
64
+ if (typeof value === "bigint") {
65
+ return value.toString();
66
+ }
67
+ return value;
68
+ };
69
+ })(util || (util = {}));
70
+ var objectUtil;
71
+ (function(objectUtil2) {
72
+ objectUtil2.mergeShapes = (first, second) => {
73
+ return {
74
+ ...first,
75
+ ...second
76
+ // second overwrites first
77
+ };
78
+ };
79
+ })(objectUtil || (objectUtil = {}));
80
+ util.arrayToEnum([
81
+ "string",
82
+ "nan",
83
+ "number",
84
+ "integer",
85
+ "float",
86
+ "boolean",
87
+ "date",
88
+ "bigint",
89
+ "symbol",
90
+ "function",
91
+ "undefined",
92
+ "null",
93
+ "array",
94
+ "object",
95
+ "unknown",
96
+ "promise",
97
+ "void",
98
+ "never",
99
+ "map",
100
+ "set"
101
+ ]);
102
+
103
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
104
+ util.arrayToEnum([
105
+ "invalid_type",
106
+ "invalid_literal",
107
+ "custom",
108
+ "invalid_union",
109
+ "invalid_union_discriminator",
110
+ "invalid_enum_value",
111
+ "unrecognized_keys",
112
+ "invalid_arguments",
113
+ "invalid_return_type",
114
+ "invalid_date",
115
+ "invalid_string",
116
+ "too_small",
117
+ "too_big",
118
+ "invalid_intersection_types",
119
+ "not_multiple_of",
120
+ "not_finite"
121
+ ]);
122
+ var ZodError = class _ZodError extends Error {
123
+ get errors() {
124
+ return this.issues;
125
+ }
126
+ constructor(issues) {
127
+ super();
128
+ this.issues = [];
129
+ this.addIssue = (sub) => {
130
+ this.issues = [...this.issues, sub];
131
+ };
132
+ this.addIssues = (subs = []) => {
133
+ this.issues = [...this.issues, ...subs];
134
+ };
135
+ const actualProto = new.target.prototype;
136
+ if (Object.setPrototypeOf) {
137
+ Object.setPrototypeOf(this, actualProto);
138
+ } else {
139
+ this.__proto__ = actualProto;
140
+ }
141
+ this.name = "ZodError";
142
+ this.issues = issues;
143
+ }
144
+ format(_mapper) {
145
+ const mapper = _mapper || function(issue) {
146
+ return issue.message;
147
+ };
148
+ const fieldErrors = { _errors: [] };
149
+ const processError = (error) => {
150
+ for (const issue of error.issues) {
151
+ if (issue.code === "invalid_union") {
152
+ issue.unionErrors.map(processError);
153
+ } else if (issue.code === "invalid_return_type") {
154
+ processError(issue.returnTypeError);
155
+ } else if (issue.code === "invalid_arguments") {
156
+ processError(issue.argumentsError);
157
+ } else if (issue.path.length === 0) {
158
+ fieldErrors._errors.push(mapper(issue));
159
+ } else {
160
+ let curr = fieldErrors;
161
+ let i = 0;
162
+ while (i < issue.path.length) {
163
+ const el = issue.path[i];
164
+ const terminal = i === issue.path.length - 1;
165
+ if (!terminal) {
166
+ curr[el] = curr[el] || { _errors: [] };
167
+ } else {
168
+ curr[el] = curr[el] || { _errors: [] };
169
+ curr[el]._errors.push(mapper(issue));
170
+ }
171
+ curr = curr[el];
172
+ i++;
173
+ }
174
+ }
175
+ }
176
+ };
177
+ processError(this);
178
+ return fieldErrors;
179
+ }
180
+ static assert(value) {
181
+ if (!(value instanceof _ZodError)) {
182
+ throw new Error(`Not a ZodError: ${value}`);
183
+ }
184
+ }
185
+ toString() {
186
+ return this.message;
187
+ }
188
+ get message() {
189
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
190
+ }
191
+ get isEmpty() {
192
+ return this.issues.length === 0;
193
+ }
194
+ flatten(mapper = (issue) => issue.message) {
195
+ const fieldErrors = {};
196
+ const formErrors = [];
197
+ for (const sub of this.issues) {
198
+ if (sub.path.length > 0) {
199
+ const firstEl = sub.path[0];
200
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
201
+ fieldErrors[firstEl].push(mapper(sub));
202
+ } else {
203
+ formErrors.push(mapper(sub));
204
+ }
205
+ }
206
+ return { formErrors, fieldErrors };
207
+ }
208
+ get formErrors() {
209
+ return this.flatten();
210
+ }
211
+ };
212
+ ZodError.create = (issues) => {
213
+ const error = new ZodError(issues);
214
+ return error;
215
+ };
216
+ var authenticationMiddleware = async (ctx, next) => {
217
+ const mastra = ctx.state.mastra;
218
+ const authConfig = mastra.getServer()?.auth;
219
+ const customRouteAuthConfig = ctx.state.customRouteAuthConfig;
220
+ if (!authConfig) {
221
+ return next();
222
+ }
223
+ const path = String(ctx.path || "/");
224
+ const method = String(ctx.method || "GET");
225
+ const getHeader = (name) => ctx.headers[name.toLowerCase()];
226
+ if (auth.isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
227
+ return next();
228
+ }
229
+ if (!auth.isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {
230
+ return next();
231
+ }
232
+ if (auth.canAccessPublicly(path, method, authConfig)) {
233
+ return next();
234
+ }
235
+ const authHeader = ctx.headers.authorization;
236
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
237
+ const query = ctx.query;
238
+ if (!token && query.apiKey) {
239
+ token = query.apiKey || null;
240
+ }
241
+ if (!token) {
242
+ ctx.status = 401;
243
+ ctx.body = { error: "Authentication required" };
244
+ return;
245
+ }
246
+ try {
247
+ let user;
248
+ if (typeof authConfig.authenticateToken === "function") {
249
+ user = await authConfig.authenticateToken(token, ctx.request);
250
+ } else {
251
+ throw new Error("No token verification method configured");
252
+ }
253
+ if (!user) {
254
+ ctx.status = 401;
255
+ ctx.body = { error: "Invalid or expired token" };
256
+ return;
257
+ }
258
+ ctx.state.requestContext.set("user", user);
259
+ return next();
260
+ } catch (err) {
261
+ console.error(err);
262
+ ctx.status = 401;
263
+ ctx.body = { error: "Invalid or expired token" };
264
+ return;
265
+ }
266
+ };
267
+ var authorizationMiddleware = async (ctx, next) => {
268
+ const mastra = ctx.state.mastra;
269
+ const authConfig = mastra.getServer()?.auth;
270
+ const customRouteAuthConfig = ctx.state.customRouteAuthConfig;
271
+ if (!authConfig) {
272
+ return next();
273
+ }
274
+ const path = String(ctx.path || "/");
275
+ const method = String(ctx.method || "GET");
276
+ const getHeader = (name) => ctx.headers[name.toLowerCase()];
277
+ if (auth.isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
278
+ return next();
279
+ }
280
+ if (!auth.isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {
281
+ return next();
282
+ }
283
+ if (auth.canAccessPublicly(path, method, authConfig)) {
284
+ return next();
285
+ }
286
+ const user = ctx.state.requestContext.get("user");
287
+ if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
288
+ try {
289
+ const isAuthorized = await authConfig.authorizeUser(user, ctx.request);
290
+ if (isAuthorized) {
291
+ return next();
292
+ }
293
+ ctx.status = 403;
294
+ ctx.body = { error: "Access denied" };
295
+ return;
296
+ } catch (err) {
297
+ console.error(err);
298
+ ctx.status = 500;
299
+ ctx.body = { error: "Authorization error" };
300
+ return;
301
+ }
302
+ }
303
+ if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
304
+ try {
305
+ const context = {
306
+ get: (key) => {
307
+ if (key === "mastra") return ctx.state.mastra;
308
+ if (key === "requestContext") return ctx.state.requestContext;
309
+ if (key === "tools") return ctx.state.tools;
310
+ if (key === "taskStore") return ctx.state.taskStore;
311
+ if (key === "customRouteAuthConfig") return ctx.state.customRouteAuthConfig;
312
+ return void 0;
313
+ },
314
+ req: ctx.request
315
+ };
316
+ const isAuthorized = await authConfig.authorize(path, method, user, context);
317
+ if (isAuthorized) {
318
+ return next();
319
+ }
320
+ ctx.status = 403;
321
+ ctx.body = { error: "Access denied" };
322
+ return;
323
+ } catch (err) {
324
+ console.error(err);
325
+ ctx.status = 500;
326
+ ctx.body = { error: "Authorization error" };
327
+ return;
328
+ }
329
+ }
330
+ if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
331
+ const isAuthorized = await auth.checkRules(authConfig.rules, path, method, user);
332
+ if (isAuthorized) {
333
+ return next();
334
+ }
335
+ ctx.status = 403;
336
+ ctx.body = { error: "Access denied" };
337
+ return;
338
+ }
339
+ if (auth.defaultAuthConfig.rules && auth.defaultAuthConfig.rules.length > 0) {
340
+ const isAuthorized = await auth.checkRules(auth.defaultAuthConfig.rules, path, method, user);
341
+ if (isAuthorized) {
342
+ return next();
343
+ }
344
+ }
345
+ ctx.status = 403;
346
+ ctx.body = { error: "Access denied" };
347
+ };
348
+
349
+ // src/index.ts
350
+ var MastraServer = class extends serverAdapter.MastraServer {
351
+ createContextMiddleware() {
352
+ return async (ctx, next) => {
353
+ let bodyRequestContext;
354
+ let paramsRequestContext;
355
+ if (ctx.method === "POST" || ctx.method === "PUT") {
356
+ const contentType = ctx.headers["content-type"];
357
+ if (contentType?.includes("application/json") && ctx.request.body) {
358
+ const body = ctx.request.body;
359
+ if (body.requestContext) {
360
+ bodyRequestContext = body.requestContext;
361
+ }
362
+ }
363
+ }
364
+ if (ctx.method === "GET") {
365
+ try {
366
+ const query = ctx.query;
367
+ const encodedRequestContext = query.requestContext;
368
+ if (typeof encodedRequestContext === "string") {
369
+ try {
370
+ paramsRequestContext = JSON.parse(encodedRequestContext);
371
+ } catch {
372
+ try {
373
+ const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
374
+ paramsRequestContext = JSON.parse(json);
375
+ } catch {
376
+ }
377
+ }
378
+ }
379
+ } catch {
380
+ }
381
+ }
382
+ const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });
383
+ ctx.state.requestContext = requestContext;
384
+ ctx.state.mastra = this.mastra;
385
+ ctx.state.tools = this.tools || {};
386
+ if (this.taskStore) {
387
+ ctx.state.taskStore = this.taskStore;
388
+ }
389
+ ctx.state.customRouteAuthConfig = this.customRouteAuthConfig;
390
+ const controller = new AbortController();
391
+ ctx.req.on("close", () => {
392
+ if (!ctx.res.writableEnded) {
393
+ controller.abort();
394
+ }
395
+ });
396
+ ctx.state.abortSignal = controller.signal;
397
+ await next();
398
+ };
399
+ }
400
+ async stream(route, ctx, result) {
401
+ ctx.respond = false;
402
+ ctx.res.writeHead(200, {
403
+ "Content-Type": "text/plain",
404
+ "Transfer-Encoding": "chunked"
405
+ });
406
+ const streamFormat = route.streamFormat || "stream";
407
+ const readableStream = result instanceof ReadableStream ? result : result.fullStream;
408
+ const reader = readableStream.getReader();
409
+ ctx.res.on("close", () => {
410
+ void reader.cancel("request aborted");
411
+ });
412
+ try {
413
+ while (true) {
414
+ const { done, value } = await reader.read();
415
+ if (done) break;
416
+ if (value) {
417
+ const shouldRedact = this.streamOptions?.redact ?? true;
418
+ const outputValue = shouldRedact ? serverAdapter.redactStreamChunk(value) : value;
419
+ if (streamFormat === "sse") {
420
+ ctx.res.write(`data: ${JSON.stringify(outputValue)}
421
+
422
+ `);
423
+ } else {
424
+ ctx.res.write(JSON.stringify(outputValue) + "");
425
+ }
426
+ }
427
+ }
428
+ } catch (error) {
429
+ console.error(error);
430
+ } finally {
431
+ ctx.res.end();
432
+ }
433
+ }
434
+ async getParams(route, ctx) {
435
+ const urlParams = ctx.params || {};
436
+ const queryParams = serverAdapter.normalizeQueryParams(ctx.query || {});
437
+ let body;
438
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH") {
439
+ const contentType = ctx.headers["content-type"] || "";
440
+ if (contentType.includes("multipart/form-data")) {
441
+ try {
442
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
443
+ body = await this.parseMultipartFormData(ctx, maxFileSize);
444
+ } catch (error) {
445
+ console.error("Failed to parse multipart form data:", error);
446
+ if (error instanceof Error && error.message.toLowerCase().includes("size")) {
447
+ throw error;
448
+ }
449
+ }
450
+ } else {
451
+ body = ctx.request.body;
452
+ }
453
+ }
454
+ return { urlParams, queryParams, body };
455
+ }
456
+ /**
457
+ * Parse multipart/form-data using @fastify/busboy.
458
+ * Converts file uploads to Buffers and parses JSON field values.
459
+ *
460
+ * @param ctx - The Koa context object
461
+ * @param maxFileSize - Optional maximum file size in bytes
462
+ */
463
+ parseMultipartFormData(ctx, maxFileSize) {
464
+ return new Promise((resolve, reject) => {
465
+ const result = {};
466
+ const busboy$1 = new busboy.Busboy({
467
+ headers: {
468
+ "content-type": ctx.headers["content-type"]
469
+ },
470
+ limits: maxFileSize ? { fileSize: maxFileSize } : void 0
471
+ });
472
+ busboy$1.on("file", (fieldname, file) => {
473
+ const chunks = [];
474
+ let limitExceeded = false;
475
+ file.on("data", (chunk) => {
476
+ chunks.push(chunk);
477
+ });
478
+ file.on("limit", () => {
479
+ limitExceeded = true;
480
+ reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
481
+ });
482
+ file.on("end", () => {
483
+ if (!limitExceeded) {
484
+ result[fieldname] = Buffer.concat(chunks);
485
+ }
486
+ });
487
+ });
488
+ busboy$1.on("field", (fieldname, value) => {
489
+ try {
490
+ result[fieldname] = JSON.parse(value);
491
+ } catch {
492
+ result[fieldname] = value;
493
+ }
494
+ });
495
+ busboy$1.on("finish", () => {
496
+ resolve(result);
497
+ });
498
+ busboy$1.on("error", (error) => {
499
+ reject(error);
500
+ });
501
+ ctx.req.pipe(busboy$1);
502
+ });
503
+ }
504
+ async sendResponse(route, ctx, result) {
505
+ if (route.responseType === "json") {
506
+ ctx.body = result;
507
+ } else if (route.responseType === "stream") {
508
+ await this.stream(route, ctx, result);
509
+ } else if (route.responseType === "datastream-response") {
510
+ ctx.respond = false;
511
+ const fetchResponse = result;
512
+ const headers = {};
513
+ fetchResponse.headers.forEach((value, key) => {
514
+ headers[key] = value;
515
+ });
516
+ ctx.res.writeHead(fetchResponse.status, headers);
517
+ if (fetchResponse.body) {
518
+ const reader = fetchResponse.body.getReader();
519
+ try {
520
+ while (true) {
521
+ const { done, value } = await reader.read();
522
+ if (done) break;
523
+ ctx.res.write(value);
524
+ }
525
+ } finally {
526
+ ctx.res.end();
527
+ }
528
+ } else {
529
+ ctx.res.end();
530
+ }
531
+ } else if (route.responseType === "mcp-http") {
532
+ ctx.respond = false;
533
+ const { server, httpPath } = result;
534
+ try {
535
+ const rawReq = ctx.req;
536
+ if (ctx.request.body !== void 0) {
537
+ rawReq.body = ctx.request.body;
538
+ }
539
+ await server.startHTTP({
540
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
541
+ httpPath,
542
+ req: rawReq,
543
+ res: ctx.res
544
+ });
545
+ } catch {
546
+ if (!ctx.res.headersSent) {
547
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
548
+ ctx.res.end(
549
+ JSON.stringify({
550
+ jsonrpc: "2.0",
551
+ error: { code: -32603, message: "Internal server error" },
552
+ id: null
553
+ })
554
+ );
555
+ }
556
+ }
557
+ } else if (route.responseType === "mcp-sse") {
558
+ ctx.respond = false;
559
+ const { server, ssePath, messagePath } = result;
560
+ try {
561
+ const rawReq = ctx.req;
562
+ if (ctx.request.body !== void 0) {
563
+ rawReq.body = ctx.request.body;
564
+ }
565
+ await server.startSSE({
566
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
567
+ ssePath,
568
+ messagePath,
569
+ req: rawReq,
570
+ res: ctx.res
571
+ });
572
+ } catch {
573
+ if (!ctx.res.headersSent) {
574
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
575
+ ctx.res.end(JSON.stringify({ error: "Error handling MCP SSE request" }));
576
+ }
577
+ }
578
+ } else {
579
+ ctx.status = 500;
580
+ }
581
+ }
582
+ async registerRoute(app, route, { prefix }) {
583
+ const fullPath = `${prefix}${route.path}`;
584
+ const koaPath = fullPath;
585
+ const handler = async (ctx, next) => {
586
+ const pathRegex = this.pathToRegex(koaPath);
587
+ const match = pathRegex.exec(ctx.path);
588
+ if (!match) {
589
+ await next();
590
+ return;
591
+ }
592
+ if (route.method.toUpperCase() !== "ALL" && ctx.method.toUpperCase() !== route.method.toUpperCase()) {
593
+ await next();
594
+ return;
595
+ }
596
+ const paramNames = this.extractParamNames(koaPath);
597
+ ctx.params = {};
598
+ paramNames.forEach((name, index) => {
599
+ ctx.params[name] = match[index + 1];
600
+ });
601
+ const params = await this.getParams(route, ctx);
602
+ if (params.queryParams) {
603
+ try {
604
+ params.queryParams = await this.parseQueryParams(route, params.queryParams);
605
+ } catch (error$1) {
606
+ console.error("Error parsing query params", error$1);
607
+ if (error$1 instanceof ZodError) {
608
+ ctx.status = 400;
609
+ ctx.body = error.formatZodError(error$1, "query parameters");
610
+ return;
611
+ }
612
+ ctx.status = 400;
613
+ ctx.body = {
614
+ error: "Invalid query parameters",
615
+ issues: [{ field: "unknown", message: error$1 instanceof Error ? error$1.message : "Unknown error" }]
616
+ };
617
+ return;
618
+ }
619
+ }
620
+ if (params.body) {
621
+ try {
622
+ params.body = await this.parseBody(route, params.body);
623
+ } catch (error$1) {
624
+ console.error("Error parsing body:", error$1 instanceof Error ? error$1.message : String(error$1));
625
+ if (error$1 instanceof ZodError) {
626
+ ctx.status = 400;
627
+ ctx.body = error.formatZodError(error$1, "request body");
628
+ return;
629
+ }
630
+ ctx.status = 400;
631
+ ctx.body = {
632
+ error: "Invalid request body",
633
+ issues: [{ field: "unknown", message: error$1 instanceof Error ? error$1.message : "Unknown error" }]
634
+ };
635
+ return;
636
+ }
637
+ }
638
+ const handlerParams = {
639
+ ...params.urlParams,
640
+ ...params.queryParams,
641
+ ...typeof params.body === "object" ? params.body : {},
642
+ requestContext: ctx.state.requestContext,
643
+ mastra: this.mastra,
644
+ tools: ctx.state.tools,
645
+ taskStore: ctx.state.taskStore,
646
+ abortSignal: ctx.state.abortSignal
647
+ };
648
+ try {
649
+ const result = await route.handler(handlerParams);
650
+ await this.sendResponse(route, ctx, result);
651
+ } catch (error) {
652
+ console.error("Error calling handler", error);
653
+ let status = 500;
654
+ if (error && typeof error === "object") {
655
+ if ("status" in error) {
656
+ status = error.status;
657
+ } else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
658
+ status = error.details.status;
659
+ }
660
+ }
661
+ ctx.status = status;
662
+ ctx.body = { error: error instanceof Error ? error.message : "Unknown error" };
663
+ }
664
+ };
665
+ app.use(handler);
666
+ }
667
+ /**
668
+ * Convert Express-style path to regex for matching
669
+ */
670
+ pathToRegex(path) {
671
+ const PARAM_PLACEHOLDER = "\0PARAM\0";
672
+ const pathWithPlaceholders = path.replace(/:[^/]+/g, PARAM_PLACEHOLDER);
673
+ const escapedPath = pathWithPlaceholders.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
674
+ const regexPath = escapedPath.replace(new RegExp(PARAM_PLACEHOLDER, "g"), "([^/]+)").replace(/\//g, "\\/");
675
+ return new RegExp(`^${regexPath}$`);
676
+ }
677
+ /**
678
+ * Extract parameter names from path
679
+ */
680
+ extractParamNames(path) {
681
+ const matches = path.match(/:[^/]+/g) || [];
682
+ return matches.map((m) => m.slice(1));
683
+ }
684
+ registerContextMiddleware() {
685
+ this.app.use(this.createContextMiddleware());
686
+ }
687
+ registerAuthMiddleware() {
688
+ const authConfig = this.mastra.getServer()?.auth;
689
+ if (!authConfig) {
690
+ return;
691
+ }
692
+ this.app.use(authenticationMiddleware);
693
+ this.app.use(authorizationMiddleware);
694
+ }
695
+ };
696
+
697
+ exports.MastraServer = MastraServer;
698
+ //# sourceMappingURL=index.cjs.map
699
+ //# sourceMappingURL=index.cjs.map