@mastra/deployer 0.16.4-alpha.1 → 0.17.0-alpha.3

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.
Files changed (87) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/build/analyze/analyzeEntry.d.ts +33 -0
  3. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -0
  4. package/dist/build/analyze/bundleExternals.d.ts +44 -0
  5. package/dist/build/analyze/bundleExternals.d.ts.map +1 -0
  6. package/dist/build/analyze/constants.d.ts +4 -0
  7. package/dist/build/analyze/constants.d.ts.map +1 -0
  8. package/dist/build/analyze.cjs +2 -6
  9. package/dist/build/analyze.d.ts +9 -24
  10. package/dist/build/analyze.d.ts.map +1 -1
  11. package/dist/build/analyze.js +1 -1
  12. package/dist/build/bundler.cjs +3 -3
  13. package/dist/build/bundler.d.ts +4 -3
  14. package/dist/build/bundler.d.ts.map +1 -1
  15. package/dist/build/bundler.js +1 -1
  16. package/dist/build/index.cjs +12 -12
  17. package/dist/build/index.d.ts +1 -1
  18. package/dist/build/index.js +4 -4
  19. package/dist/build/plugins/pino.d.ts.map +1 -1
  20. package/dist/build/watcher.d.ts +1 -2
  21. package/dist/build/watcher.d.ts.map +1 -1
  22. package/dist/bundler/index.cjs +2 -2
  23. package/dist/bundler/index.d.ts +9 -3
  24. package/dist/bundler/index.d.ts.map +1 -1
  25. package/dist/bundler/index.js +1 -1
  26. package/dist/bundler/workspaceDependencies.d.ts +21 -7
  27. package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
  28. package/dist/{chunk-OUS376P4.cjs → chunk-2JXD2KJI.cjs} +72 -31
  29. package/dist/chunk-2JXD2KJI.cjs.map +1 -0
  30. package/dist/{chunk-PX6ZHD5K.cjs → chunk-4SIOF7ZD.cjs} +5 -5
  31. package/dist/{chunk-PX6ZHD5K.cjs.map → chunk-4SIOF7ZD.cjs.map} +1 -1
  32. package/dist/{chunk-LL2SXZRQ.js → chunk-J3J7AMBG.js} +3 -3
  33. package/dist/{chunk-LL2SXZRQ.js.map → chunk-J3J7AMBG.js.map} +1 -1
  34. package/dist/{chunk-T4L3WY7M.cjs → chunk-M54YPGM4.cjs} +582 -408
  35. package/dist/chunk-M54YPGM4.cjs.map +1 -0
  36. package/dist/{chunk-4CAKOUIN.js → chunk-MIQJS7XN.js} +30 -42
  37. package/dist/chunk-MIQJS7XN.js.map +1 -0
  38. package/dist/{chunk-O7OB4KG5.js → chunk-RZAGSFAM.js} +43 -21
  39. package/dist/chunk-RZAGSFAM.js.map +1 -0
  40. package/dist/{chunk-LN4WTW4C.js → chunk-TWABWFKL.js} +11 -16
  41. package/dist/chunk-TWABWFKL.js.map +1 -0
  42. package/dist/{chunk-ZQJDMTCN.cjs → chunk-YHISSTZJ.cjs} +55 -47
  43. package/dist/chunk-YHISSTZJ.cjs.map +1 -0
  44. package/dist/{chunk-5ZHIZCMJ.js → chunk-YJOKHEUC.js} +575 -401
  45. package/dist/chunk-YJOKHEUC.js.map +1 -0
  46. package/dist/{chunk-JOCAZKZ5.cjs → chunk-YKVNJVGJ.cjs} +15 -20
  47. package/dist/chunk-YKVNJVGJ.cjs.map +1 -0
  48. package/dist/index.cjs +5 -5
  49. package/dist/index.js +2 -2
  50. package/dist/server/handlers/root.d.ts +1 -1
  51. package/dist/server/handlers/root.d.ts.map +1 -1
  52. package/dist/server/index.cjs +154 -8
  53. package/dist/server/index.cjs.map +1 -1
  54. package/dist/server/index.d.ts.map +1 -1
  55. package/dist/server/index.js +135 -8
  56. package/dist/server/index.js.map +1 -1
  57. package/package.json +12 -11
  58. package/dist/build/__fixtures__/no-bundler.d.ts +0 -5
  59. package/dist/build/__fixtures__/no-bundler.d.ts.map +0 -1
  60. package/dist/build/__fixtures__/no-server.d.ts +0 -5
  61. package/dist/build/__fixtures__/no-server.d.ts.map +0 -1
  62. package/dist/build/__fixtures__/no-telemetry.d.ts +0 -5
  63. package/dist/build/__fixtures__/no-telemetry.d.ts.map +0 -1
  64. package/dist/build/plugins/__fixtures__/basic-with-bundler.d.ts +0 -5
  65. package/dist/build/plugins/__fixtures__/basic-with-bundler.d.ts.map +0 -1
  66. package/dist/build/plugins/__fixtures__/basic-with-const.d.ts +0 -5
  67. package/dist/build/plugins/__fixtures__/basic-with-const.d.ts.map +0 -1
  68. package/dist/build/plugins/__fixtures__/basic-with-function.d.ts +0 -5
  69. package/dist/build/plugins/__fixtures__/basic-with-function.d.ts.map +0 -1
  70. package/dist/build/plugins/__fixtures__/basic-with-import.d.ts +0 -5
  71. package/dist/build/plugins/__fixtures__/basic-with-import.d.ts.map +0 -1
  72. package/dist/build/plugins/__fixtures__/basic-with-json.d.ts +0 -3
  73. package/dist/build/plugins/__fixtures__/basic-with-json.d.ts.map +0 -1
  74. package/dist/build/plugins/__fixtures__/basic.d.ts +0 -5
  75. package/dist/build/plugins/__fixtures__/basic.d.ts.map +0 -1
  76. package/dist/build/plugins/__fixtures__/empty-mastra.d.ts +0 -3
  77. package/dist/build/plugins/__fixtures__/empty-mastra.d.ts.map +0 -1
  78. package/dist/build/plugins/__fixtures__/mastra-with-extra-code.d.ts +0 -13
  79. package/dist/build/plugins/__fixtures__/mastra-with-extra-code.d.ts.map +0 -1
  80. package/dist/chunk-4CAKOUIN.js.map +0 -1
  81. package/dist/chunk-5ZHIZCMJ.js.map +0 -1
  82. package/dist/chunk-JOCAZKZ5.cjs.map +0 -1
  83. package/dist/chunk-LN4WTW4C.js.map +0 -1
  84. package/dist/chunk-O7OB4KG5.js.map +0 -1
  85. package/dist/chunk-OUS376P4.cjs.map +0 -1
  86. package/dist/chunk-T4L3WY7M.cjs.map +0 -1
  87. package/dist/chunk-ZQJDMTCN.cjs.map +0 -1
@@ -2,25 +2,29 @@
2
2
 
3
3
  var chunkHR2HOA5D_cjs = require('./chunk-HR2HOA5D.cjs');
4
4
  var babel = require('@babel/core');
5
- var commonjs2 = require('@rollup/plugin-commonjs');
6
- var json2 = require('@rollup/plugin-json');
7
- var nodeResolve = require('@rollup/plugin-node-resolve');
8
- var virtual = require('@rollup/plugin-virtual');
9
- var esmShim = require('@rollup/plugin-esm-shim');
10
5
  var fs = require('fs');
11
6
  var promises = require('fs/promises');
12
- var url = require('url');
7
+ var path2 = require('path');
8
+ var child_process = require('child_process');
13
9
  var rollup = require('rollup');
14
10
  var originalEsbuild = require('rollup-plugin-esbuild');
15
- var module$1 = require('module');
16
- var path = require('path');
17
- var child_process = require('child_process');
11
+ var commonjs = require('@rollup/plugin-commonjs');
12
+ var resolveFrom2 = require('resolve-from');
18
13
  var typescriptPaths = require('typescript-paths');
19
14
  var rollupPlugin = require('@optimize-lodash/rollup-plugin');
20
- var localPkg = require('local-pkg');
15
+ var json = require('@rollup/plugin-json');
21
16
  var slugify = require('@sindresorhus/slugify');
17
+ var pkg = require('empathic/package');
22
18
  var findWorkspaces = require('find-workspaces');
23
19
  var fsExtra = require('fs-extra');
20
+ var logger = require('@mastra/core/logger');
21
+ var virtual = require('@rollup/plugin-virtual');
22
+ var url = require('url');
23
+ var module$1 = require('module');
24
+ var localPkg = require('local-pkg');
25
+ var nodeResolve = require('@rollup/plugin-node-resolve');
26
+ var esmShim = require('@rollup/plugin-esm-shim');
27
+ var posix = require('path/posix');
24
28
 
25
29
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
26
30
 
@@ -43,113 +47,18 @@ function _interopNamespace(e) {
43
47
  }
44
48
 
45
49
  var babel__namespace = /*#__PURE__*/_interopNamespace(babel);
46
- var commonjs2__default = /*#__PURE__*/_interopDefault(commonjs2);
47
- var json2__default = /*#__PURE__*/_interopDefault(json2);
48
- var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);
49
- var virtual__default = /*#__PURE__*/_interopDefault(virtual);
50
- var esmShim__default = /*#__PURE__*/_interopDefault(esmShim);
51
50
  var fs__default = /*#__PURE__*/_interopDefault(fs);
51
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
52
52
  var originalEsbuild__default = /*#__PURE__*/_interopDefault(originalEsbuild);
53
- var path__default = /*#__PURE__*/_interopDefault(path);
53
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
54
+ var resolveFrom2__default = /*#__PURE__*/_interopDefault(resolveFrom2);
55
+ var json__default = /*#__PURE__*/_interopDefault(json);
54
56
  var slugify__default = /*#__PURE__*/_interopDefault(slugify);
57
+ var pkg__namespace = /*#__PURE__*/_interopNamespace(pkg);
58
+ var virtual__default = /*#__PURE__*/_interopDefault(virtual);
59
+ var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);
60
+ var esmShim__default = /*#__PURE__*/_interopDefault(esmShim);
55
61
 
56
- function esbuild(options = {}) {
57
- return originalEsbuild__default.default({
58
- target: "node20",
59
- platform: "node",
60
- minify: false,
61
- ...options
62
- });
63
- }
64
- function isNodeBuiltin(dep) {
65
- const [pkg] = dep.split("/");
66
- return dep.startsWith("node:") || module$1.builtinModules.includes(dep) || module$1.builtinModules.includes(pkg);
67
- }
68
- function aliasHono() {
69
- return {
70
- name: "hono-alias",
71
- resolveId(id) {
72
- if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
73
- return;
74
- }
75
- const path2 = undefined(id);
76
- return url.fileURLToPath(path2);
77
- }
78
- };
79
- }
80
- function removeDeployer() {
81
- const t = babel__namespace.default.types;
82
- return {
83
- name: "remove-deployer",
84
- visitor: {
85
- NewExpression(path2, state) {
86
- const varDeclaratorPath = path2.findParent((path3) => t.isVariableDeclarator(path3.node));
87
- if (!varDeclaratorPath) {
88
- return;
89
- }
90
- const parentNode = path2.parentPath.node;
91
- if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
92
- return;
93
- }
94
- if (!state.hasReplaced) {
95
- state.hasReplaced = true;
96
- const newMastraObj = t.cloneNode(path2.node);
97
- if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
98
- const deployer = newMastraObj.arguments[0].properties.find(
99
- (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
100
- );
101
- if (!deployer) {
102
- return;
103
- }
104
- newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
105
- (prop) => prop !== deployer
106
- );
107
- if (t.isObjectProperty(deployer) && t.isIdentifier(deployer.value)) {
108
- const deployerBinding = state.file.scope.getBinding(deployer.value.name);
109
- if (deployerBinding) {
110
- deployerBinding?.path?.parentPath?.remove();
111
- }
112
- }
113
- path2.replaceWith(newMastraObj);
114
- }
115
- }
116
- }
117
- }
118
- };
119
- }
120
-
121
- // src/build/plugins/remove-deployer.ts
122
- function removeDeployer2(mastraEntry, options) {
123
- return {
124
- name: "remove-deployer",
125
- transform(code, id) {
126
- if (id !== mastraEntry) {
127
- return;
128
- }
129
- return new Promise((resolve, reject) => {
130
- babel__namespace.transform(
131
- code,
132
- {
133
- babelrc: false,
134
- configFile: false,
135
- filename: id,
136
- plugins: [removeDeployer],
137
- sourceMaps: options?.sourcemap
138
- },
139
- (err, result) => {
140
- if (err) {
141
- return reject(err);
142
- }
143
- resolve({
144
- code: result.code,
145
- map: result.map
146
- });
147
- }
148
- );
149
- });
150
- }
151
- };
152
- }
153
62
  function spawn(command, args = [], options = {}) {
154
63
  return new Promise((resolve, reject) => {
155
64
  const childProcess = child_process.spawn(command, args, {
@@ -183,80 +92,10 @@ function validate(file) {
183
92
  `import('file://${file.replaceAll("\\", "/")}')`
184
93
  ],
185
94
  {
186
- cwd: path.dirname(file)
95
+ cwd: path2.dirname(file)
187
96
  }
188
97
  );
189
98
  }
190
- var PLUGIN_NAME = "tsconfig-paths";
191
- function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
192
- let handler;
193
- return {
194
- name: PLUGIN_NAME,
195
- buildStart() {
196
- handler = typescriptPaths.createHandler({
197
- log: () => {
198
- },
199
- tsConfigPath,
200
- respectCoreModule,
201
- falllback: (moduleName) => fs__default.default.existsSync(moduleName)
202
- });
203
- return;
204
- },
205
- async resolveId(request, importer, options) {
206
- if (!importer || request.startsWith("\0")) {
207
- return null;
208
- }
209
- const moduleName = handler?.(request, path.normalize(importer));
210
- if (!moduleName) {
211
- let importerMeta = {};
212
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
213
- if (!resolved) {
214
- return null;
215
- }
216
- if (localResolve) {
217
- const importerInfo = this.getModuleInfo(importer);
218
- importerMeta = importerInfo?.meta || {};
219
- if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
220
- return {
221
- ...resolved,
222
- external: !request.startsWith("hono/") && request !== "hono"
223
- };
224
- }
225
- }
226
- return {
227
- ...resolved,
228
- meta: {
229
- ...resolved.meta || {},
230
- ...importerMeta
231
- }
232
- };
233
- }
234
- if (!path__default.default.extname(moduleName)) {
235
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
236
- if (!resolved) {
237
- return null;
238
- }
239
- return {
240
- ...resolved,
241
- meta: {
242
- ...resolved.meta,
243
- [PLUGIN_NAME]: {
244
- resolved: true
245
- }
246
- }
247
- };
248
- }
249
- return {
250
- id: moduleName,
251
- meta: {
252
- [PLUGIN_NAME]: {
253
- resolved: true
254
- }
255
- }
256
- };
257
- }
258
- };
259
- }
260
99
  function removeAllOptionsFromMastraExcept(result, option, logger) {
261
100
  const t = babel__namespace.default.types;
262
101
  return {
@@ -264,29 +103,29 @@ function removeAllOptionsFromMastraExcept(result, option, logger) {
264
103
  visitor: {
265
104
  ExportNamedDeclaration: {
266
105
  // remove all exports
267
- exit(path2) {
268
- path2.remove();
106
+ exit(path3) {
107
+ path3.remove();
269
108
  }
270
109
  },
271
- NewExpression(path2, state) {
272
- const varDeclaratorPath = path2.findParent((path3) => t.isVariableDeclarator(path3.node));
110
+ NewExpression(path3, state) {
111
+ const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
273
112
  if (!varDeclaratorPath) {
274
113
  return;
275
114
  }
276
- const parentNode = path2.parentPath.node;
115
+ const parentNode = path3.parentPath.node;
277
116
  if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
278
117
  return;
279
118
  }
280
119
  let mastraArgs = t.objectExpression([]);
281
- if (t.isObjectExpression(path2.node.arguments[0])) {
282
- mastraArgs = path2.node.arguments[0];
120
+ if (t.isObjectExpression(path3.node.arguments[0])) {
121
+ mastraArgs = path3.node.arguments[0];
283
122
  }
284
123
  let telemetry = mastraArgs.properties.find(
285
124
  // @ts-ignore
286
125
  (prop) => prop.key.name === option
287
126
  );
288
127
  let telemetryValue = t.objectExpression([]);
289
- const programPath = path2.scope.getProgramParent().path;
128
+ const programPath = path3.scope.getProgramParent().path;
290
129
  if (!programPath) {
291
130
  return;
292
131
  }
@@ -296,7 +135,7 @@ function removeAllOptionsFromMastraExcept(result, option, logger) {
296
135
  if (t.isIdentifier(telemetry.value) && telemetry.value.name === option) {
297
136
  const telemetryBinding = state.file.scope.getBinding(option);
298
137
  if (telemetryBinding && t.isVariableDeclarator(telemetryBinding.path.node)) {
299
- const id = path2.scope.generateUidIdentifier(option);
138
+ const id = path3.scope.generateUidIdentifier(option);
300
139
  telemetryBinding.path.replaceWith(t.variableDeclarator(id, telemetryBinding.path.node.init));
301
140
  telemetryValue = id;
302
141
  }
@@ -309,8 +148,8 @@ function removeAllOptionsFromMastraExcept(result, option, logger) {
309
148
  programPath.node.body.push(exportDeclaration);
310
149
  },
311
150
  Program: {
312
- exit(path2) {
313
- const hasExport = path2.node.body.some(
151
+ exit(path3) {
152
+ const hasExport = path3.node.body.some(
314
153
  (node) => node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration"
315
154
  );
316
155
  if (!hasExport) {
@@ -326,7 +165,7 @@ export const mastra = new Mastra({
326
165
  t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), t.objectExpression([]))]),
327
166
  []
328
167
  );
329
- path2.node.body.push(fallbackExportDeclaration);
168
+ path3.node.body.push(fallbackExportDeclaration);
330
169
  }
331
170
  }
332
171
  }
@@ -338,14 +177,92 @@ export const mastra = new Mastra({
338
177
  function removeAllOptionsExceptBundler(result, logger) {
339
178
  return removeAllOptionsFromMastraExcept(result, "bundler", logger);
340
179
  }
180
+ function esbuild(options = {}) {
181
+ return originalEsbuild__default.default({
182
+ target: "node20",
183
+ platform: "node",
184
+ minify: false,
185
+ ...options
186
+ });
187
+ }
188
+ var PLUGIN_NAME = "tsconfig-paths";
189
+ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
190
+ let handler;
191
+ return {
192
+ name: PLUGIN_NAME,
193
+ buildStart() {
194
+ handler = typescriptPaths.createHandler({
195
+ log: () => {
196
+ },
197
+ tsConfigPath,
198
+ respectCoreModule,
199
+ falllback: (moduleName) => fs__default.default.existsSync(moduleName)
200
+ });
201
+ return;
202
+ },
203
+ async resolveId(request, importer, options) {
204
+ if (!importer || request.startsWith("\0")) {
205
+ return null;
206
+ }
207
+ const moduleName = handler?.(request, path2.normalize(importer));
208
+ if (!moduleName) {
209
+ let importerMeta = {};
210
+ const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
211
+ if (!resolved) {
212
+ return null;
213
+ }
214
+ if (localResolve) {
215
+ const importerInfo = this.getModuleInfo(importer);
216
+ importerMeta = importerInfo?.meta || {};
217
+ if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
218
+ return {
219
+ ...resolved,
220
+ external: !request.startsWith("hono/") && request !== "hono"
221
+ };
222
+ }
223
+ }
224
+ return {
225
+ ...resolved,
226
+ meta: {
227
+ ...resolved.meta || {},
228
+ ...importerMeta
229
+ }
230
+ };
231
+ }
232
+ if (!path2__namespace.default.extname(moduleName)) {
233
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
234
+ if (!resolved) {
235
+ return null;
236
+ }
237
+ return {
238
+ ...resolved,
239
+ meta: {
240
+ ...resolved.meta,
241
+ [PLUGIN_NAME]: {
242
+ resolved: true
243
+ }
244
+ }
245
+ };
246
+ }
247
+ return {
248
+ id: moduleName,
249
+ meta: {
250
+ [PLUGIN_NAME]: {
251
+ resolved: true
252
+ }
253
+ }
254
+ };
255
+ }
256
+ };
257
+ }
341
258
  function removeNonReferencedNodes() {
342
259
  const t = babel__namespace.default.types;
343
260
  return {
344
261
  name: "remove-non-referenced-nodes",
345
262
  visitor: {
346
- Program(path2) {
347
- const scope = path2.scope;
348
- const currentBody = path2.get("body");
263
+ Program(path3) {
264
+ const scope = path3.scope;
265
+ const currentBody = path3.get("body");
349
266
  const filteredBody = currentBody.filter((childPath) => {
350
267
  if (childPath.isExportDeclaration()) {
351
268
  return true;
@@ -377,7 +294,7 @@ function removeNonReferencedNodes() {
377
294
  }
378
295
  return false;
379
296
  });
380
- path2.set(
297
+ path3.set(
381
298
  "body",
382
299
  filteredBody.map((p) => p.node)
383
300
  );
@@ -423,13 +340,13 @@ function extractMastraOptionBundler(name, entryFile, transformer, result, logger
423
340
  // transpile typescript to something we understand
424
341
  esbuild(),
425
342
  rollupPlugin.optimizeLodashImports(),
426
- commonjs2__default.default({
343
+ commonjs__default.default({
427
344
  extensions: [".js", ".ts"],
428
345
  strictRequires: "strict",
429
346
  transformMixedEsModules: true,
430
347
  ignoreTryCatch: false
431
348
  }),
432
- json2__default.default(),
349
+ json__default.default(),
433
350
  {
434
351
  name: `extract-${name}-config`,
435
352
  transform(code, id) {
@@ -513,16 +430,16 @@ function checkConfigExport(result) {
513
430
  const mastraVars = /* @__PURE__ */ new Set();
514
431
  return {
515
432
  visitor: {
516
- ExportNamedDeclaration(path2) {
517
- const decl = path2.node.declaration;
433
+ ExportNamedDeclaration(path3) {
434
+ const decl = path3.node.declaration;
518
435
  if (t.isVariableDeclaration(decl)) {
519
436
  const varDecl = decl.declarations[0];
520
437
  if (t.isIdentifier(varDecl?.id, { name: "mastra" }) && t.isNewExpression(varDecl.init) && t.isIdentifier(varDecl.init.callee, { name: "Mastra" })) {
521
438
  result.hasValidConfig = true;
522
439
  }
523
440
  }
524
- if (Array.isArray(path2.node.specifiers)) {
525
- for (const spec of path2.node.specifiers) {
441
+ if (Array.isArray(path3.node.specifiers)) {
442
+ for (const spec of path3.node.specifiers) {
526
443
  if (t.isExportSpecifier(spec) && t.isIdentifier(spec.exported, { name: "mastra" }) && t.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) {
527
444
  result.hasValidConfig = true;
528
445
  }
@@ -530,8 +447,8 @@ function checkConfigExport(result) {
530
447
  }
531
448
  },
532
449
  // For cases 2-4 we need to track whether those variables are assigned to `new Mastra()`
533
- VariableDeclaration(path2) {
534
- for (const decl of path2.node.declarations) {
450
+ VariableDeclaration(path3) {
451
+ for (const decl of path3.node.declarations) {
535
452
  if (t.isIdentifier(decl.id) && t.isNewExpression(decl.init) && t.isIdentifier(decl.init.callee, { name: "Mastra" })) {
536
453
  mastraVars.add(decl.id.name);
537
454
  }
@@ -540,29 +457,15 @@ function checkConfigExport(result) {
540
457
  }
541
458
  };
542
459
  }
543
- function getPackageName(id) {
544
- const parts = id.split("/");
545
- if (id.startsWith("@")) {
546
- return parts.slice(0, 2).join("/");
547
- }
548
- return parts[0];
549
- }
550
- async function getPackageRootPath(packageName) {
551
- let rootPath;
552
- try {
553
- const pkg = await localPkg.getPackageInfo(packageName);
554
- rootPath = pkg?.rootPath ?? null;
555
- } catch (e) {
556
- rootPath = null;
557
- }
558
- return rootPath;
559
- }
560
- function getCompiledDepCachePath(rootPath, packageName) {
561
- return path.join(rootPath, "node_modules", ".cache", packageName);
562
- }
563
- var createWorkspacePackageMap = async () => {
564
- const workspaces = await findWorkspaces.findWorkspaces();
565
- const workspaceMap = new Map(
460
+ var workspacesCache = findWorkspaces.createWorkspacesCache();
461
+ async function getWorkspaceInformation({
462
+ dir = process.cwd(),
463
+ mastraEntryFile
464
+ }) {
465
+ const closestPkgJson = pkg__namespace.up({ cwd: path2.dirname(mastraEntryFile) });
466
+ const location = closestPkgJson ? path2.dirname(closestPkgJson) : process.cwd();
467
+ const workspaces = await findWorkspaces.findWorkspaces(dir, { cache: workspacesCache });
468
+ const _workspaceMap = new Map(
566
469
  workspaces?.map((workspace) => [
567
470
  workspace.package.name,
568
471
  {
@@ -572,8 +475,15 @@ var createWorkspacePackageMap = async () => {
572
475
  }
573
476
  ]) ?? []
574
477
  );
575
- return workspaceMap;
576
- };
478
+ const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location);
479
+ const workspaceRoot = isWorkspacePackage ? findWorkspaces.findWorkspacesRoot(dir, { cache: workspacesCache })?.location : void 0;
480
+ return {
481
+ // If the current package is not part of the workspace, the bundling down the line shouldn't look at any workspace packages
482
+ workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(),
483
+ workspaceRoot,
484
+ isWorkspacePackage
485
+ };
486
+ }
577
487
  var collectTransitiveWorkspaceDependencies = ({
578
488
  workspaceMap,
579
489
  initialDependencies,
@@ -626,7 +536,7 @@ var packWorkspaceDependencies = async ({
626
536
  const depsService = new chunkHR2HOA5D_cjs.DepsService(root.location);
627
537
  depsService.__setLogger(logger);
628
538
  if (usedWorkspacePackages.size > 0) {
629
- const workspaceDirPath = path.join(bundleOutputDir, "workspace-module");
539
+ const workspaceDirPath = path2.join(bundleOutputDir, "workspace-module");
630
540
  await fsExtra.ensureDir(workspaceDirPath);
631
541
  logger.info(`Packaging ${usedWorkspacePackages.size} workspace dependencies...`);
632
542
  const batchSize = 5;
@@ -648,44 +558,112 @@ var packWorkspaceDependencies = async ({
648
558
  logger.info(`Successfully packaged ${usedWorkspacePackages.size} workspace dependencies`);
649
559
  }
650
560
  };
651
-
652
- // src/build/analyze.ts
653
- var globalExternals = [
654
- "pino",
655
- "pino-pretty",
656
- "@libsql/client",
657
- "pg",
658
- "libsql",
659
- "jsdom",
660
- "sqlite3",
661
- "fastembed",
662
- "nodemailer",
663
- "#tools"
664
- ];
665
- function findExternalImporter(module, external, allOutputs) {
666
- const capturedFiles = /* @__PURE__ */ new Set();
667
- for (const id of module.imports) {
668
- if (id === external) {
669
- return module;
670
- } else {
671
- if (id.endsWith(".mjs")) {
672
- capturedFiles.add(id);
561
+ function isNodeBuiltin(dep) {
562
+ const [pkg2] = dep.split("/");
563
+ return dep.startsWith("node:") || module$1.builtinModules.includes(dep) || module$1.builtinModules.includes(pkg2);
564
+ }
565
+ function removeDeployer() {
566
+ const t = babel__namespace.default.types;
567
+ return {
568
+ name: "remove-deployer",
569
+ visitor: {
570
+ NewExpression(path3, state) {
571
+ const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
572
+ if (!varDeclaratorPath) {
573
+ return;
574
+ }
575
+ const parentNode = path3.parentPath.node;
576
+ if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
577
+ return;
578
+ }
579
+ if (!state.hasReplaced) {
580
+ state.hasReplaced = true;
581
+ const newMastraObj = t.cloneNode(path3.node);
582
+ if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
583
+ const deployer = newMastraObj.arguments[0].properties.find(
584
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
585
+ );
586
+ if (!deployer) {
587
+ return;
588
+ }
589
+ newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
590
+ (prop) => prop !== deployer
591
+ );
592
+ if (t.isObjectProperty(deployer) && t.isIdentifier(deployer.value)) {
593
+ const deployerBinding = state.file.scope.getBinding(deployer.value.name);
594
+ if (deployerBinding) {
595
+ deployerBinding?.path?.parentPath?.remove();
596
+ }
597
+ }
598
+ path3.replaceWith(newMastraObj);
599
+ }
600
+ }
673
601
  }
674
602
  }
675
- }
676
- for (const file of capturedFiles) {
677
- const nextModule = allOutputs.find((o) => o.fileName === file);
678
- if (nextModule) {
679
- const importer = findExternalImporter(nextModule, external, allOutputs);
680
- if (importer) {
681
- return importer;
603
+ };
604
+ }
605
+
606
+ // src/build/plugins/remove-deployer.ts
607
+ function removeDeployer2(mastraEntry, options) {
608
+ return {
609
+ name: "remove-deployer",
610
+ transform(code, id) {
611
+ if (id !== mastraEntry) {
612
+ return;
682
613
  }
614
+ return new Promise((resolve, reject) => {
615
+ babel__namespace.transform(
616
+ code,
617
+ {
618
+ babelrc: false,
619
+ configFile: false,
620
+ filename: id,
621
+ plugins: [removeDeployer],
622
+ sourceMaps: options?.sourcemap
623
+ },
624
+ (err, result) => {
625
+ if (err) {
626
+ return reject(err);
627
+ }
628
+ resolve({
629
+ code: result.code,
630
+ map: result.map
631
+ });
632
+ }
633
+ );
634
+ });
683
635
  }
636
+ };
637
+ }
638
+ function getPackageName(id) {
639
+ const parts = id.split("/");
640
+ if (id.startsWith("@")) {
641
+ return parts.slice(0, 2).join("/");
684
642
  }
685
- return null;
643
+ return parts[0];
686
644
  }
687
- async function analyze(entry, mastraEntry, isVirtualFile, platform, logger, sourcemapEnabled = false, workspaceMap) {
688
- logger.info("Analyzing dependencies...");
645
+ async function getPackageRootPath(packageName) {
646
+ let rootPath;
647
+ try {
648
+ const pkg2 = await localPkg.getPackageInfo(packageName);
649
+ rootPath = pkg2?.rootPath ?? null;
650
+ } catch (e) {
651
+ rootPath = null;
652
+ }
653
+ return rootPath;
654
+ }
655
+ function getCompiledDepCachePath(rootPath, packageName) {
656
+ return path2.join(rootPath, "node_modules", ".cache", packageName);
657
+ }
658
+
659
+ // src/build/analyze/constants.ts
660
+ var DEPS_TO_IGNORE = ["#tools"];
661
+ var GLOBAL_EXTERNALS = ["pino", "pino-pretty", "@libsql/client", "pg", "libsql", "#tools"];
662
+ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
663
+
664
+ // src/build/analyze/analyzeEntry.ts
665
+ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
666
+ const normalizedMastraEntry = mastraEntry.replaceAll("\\", "/");
689
667
  let virtualPlugin = null;
690
668
  if (isVirtualFile) {
691
669
  virtualPlugin = virtual__default.default({
@@ -693,14 +671,12 @@ async function analyze(entry, mastraEntry, isVirtualFile, platform, logger, sour
693
671
  });
694
672
  entry = "#entry";
695
673
  }
696
- const normalizedMastraEntry = mastraEntry.replaceAll("\\", "/");
697
- const optimizerBundler = await rollup.rollup({
698
- logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
699
- input: isVirtualFile ? "#entry" : entry,
700
- treeshake: "smallest",
701
- preserveSymlinks: true,
702
- plugins: [
703
- virtualPlugin,
674
+ const plugins = [];
675
+ if (virtualPlugin) {
676
+ plugins.push(virtualPlugin);
677
+ }
678
+ plugins.push(
679
+ ...[
704
680
  tsConfigPaths(),
705
681
  {
706
682
  name: "custom-alias-resolver",
@@ -714,52 +690,83 @@ async function analyze(entry, mastraEntry, isVirtualFile, platform, logger, sour
714
690
  if (id.startsWith("@mastra/server")) {
715
691
  return url.fileURLToPath(undefined(id));
716
692
  }
717
- if (id === "#tools") {
718
- return {
719
- id: "#tools",
720
- external: true
721
- };
722
- }
723
693
  }
724
694
  },
725
- json2__default.default(),
695
+ json__default.default(),
726
696
  esbuild(),
727
- commonjs2__default.default({
697
+ commonjs__default.default({
728
698
  strictRequires: "debug",
729
699
  ignoreTryCatch: false,
730
700
  transformMixedEsModules: true,
731
701
  extensions: [".js", ".ts"]
732
702
  }),
733
- removeDeployer2(normalizedMastraEntry, { sourcemap: sourcemapEnabled }),
703
+ removeDeployer2(mastraEntry, { sourcemap: sourcemapEnabled }),
734
704
  esbuild()
735
- ].filter(Boolean)
736
- });
737
- const { output } = await optimizerBundler.generate({
738
- format: "esm",
739
- inlineDynamicImports: true
740
- });
741
- await optimizerBundler.close();
705
+ ]
706
+ );
707
+ return plugins;
708
+ }
709
+ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, {
710
+ logger: logger$1
711
+ }) {
742
712
  const depsToOptimize = /* @__PURE__ */ new Map();
743
- for (const [dep, bindings] of Object.entries(output[0].importedBindings)) {
744
- if (isNodeBuiltin(dep)) {
713
+ for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
714
+ if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
745
715
  continue;
746
716
  }
747
- const isWorkspace = workspaceMap.has(dep);
748
- const pkgName = getPackageName(dep);
717
+ const pkgName = getPackageName(dependency);
749
718
  let rootPath = null;
750
- if (pkgName && pkgName !== "#tools") {
719
+ let isWorkspace = false;
720
+ if (pkgName) {
751
721
  rootPath = await getPackageRootPath(pkgName);
722
+ isWorkspace = workspaceMap.has(pkgName);
752
723
  }
753
- depsToOptimize.set(dep, { exports: bindings, rootPath, isWorkspace });
724
+ depsToOptimize.set(dependency, { exports: bindings, rootPath, isWorkspace });
754
725
  }
755
- for (const o of output) {
756
- if (o.type !== "chunk") {
757
- continue;
726
+ async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
727
+ if (currentDepth >= maxDepth) {
728
+ logger$1.warn("Maximum dependency depth reached while checking transitive dependencies.");
729
+ return;
758
730
  }
759
- const dynamicImports = o.dynamicImports.filter((d) => d !== "#tools");
760
- if (!dynamicImports.length) {
761
- continue;
731
+ const depsSnapshot = new Map(depsToOptimize);
732
+ let hasAddedDeps = false;
733
+ for (const [dep, meta] of depsSnapshot) {
734
+ if (!meta.isWorkspace || internalMap.has(dep)) {
735
+ continue;
736
+ }
737
+ try {
738
+ const resolvedPath = resolveFrom2__default.default(projectRoot, dep);
739
+ if (!resolvedPath) {
740
+ logger$1.warn(`Could not resolve path for workspace dependency ${dep}`);
741
+ continue;
742
+ }
743
+ const analysis = await analyzeEntry({ entry: resolvedPath, isVirtualFile: false }, "", {
744
+ workspaceMap,
745
+ projectRoot,
746
+ logger: logger.noopLogger,
747
+ sourcemapEnabled: false
748
+ });
749
+ if (!analysis?.dependencies) {
750
+ continue;
751
+ }
752
+ for (const [innerDep, innerMeta] of analysis.dependencies) {
753
+ if (innerMeta.isWorkspace && !internalMap.has(innerDep) && !depsToOptimize.has(innerDep)) {
754
+ depsToOptimize.set(innerDep, innerMeta);
755
+ internalMap.set(innerDep, innerMeta);
756
+ hasAddedDeps = true;
757
+ }
758
+ }
759
+ } catch (err) {
760
+ logger$1.error(`Failed to resolve or analyze dependency ${dep}: ${err.message}`);
761
+ }
762
+ }
763
+ if (hasAddedDeps) {
764
+ await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
762
765
  }
766
+ }
767
+ await checkTransitiveDependencies(/* @__PURE__ */ new Map());
768
+ const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
769
+ if (dynamicImports.length) {
763
770
  for (const dynamicImport of dynamicImports) {
764
771
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
765
772
  depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
@@ -768,49 +775,159 @@ async function analyze(entry, mastraEntry, isVirtualFile, platform, logger, sour
768
775
  }
769
776
  return depsToOptimize;
770
777
  }
771
- async function bundleExternals(depsToOptimize, outputDir, logger, bundlerOptions, meta) {
772
- logger.info("Optimizing dependencies...");
773
- logger.debug(
774
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
775
- );
776
- const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
777
- const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map() } = meta || {};
778
- const allExternals = [...globalExternals, ...customExternals];
779
- const reverseVirtualReferenceMap = /* @__PURE__ */ new Map();
780
- const virtualDependencies = /* @__PURE__ */ new Map();
781
- for (const [dep, { exports, isWorkspace, rootPath }] of depsToOptimize.entries()) {
782
- let name = dep.replaceAll("/", "-");
783
- if (isWorkspace && rootPath && isDev && workspaceRoot) {
784
- const absolutePath = getCompiledDepCachePath(rootPath, name);
785
- name = absolutePath.replace(workspaceRoot, "").replace(/^[/\\]+/, "");
786
- }
787
- reverseVirtualReferenceMap.set(name, dep);
778
+ async function analyzeEntry({
779
+ entry,
780
+ isVirtualFile
781
+ }, mastraEntry, {
782
+ logger,
783
+ sourcemapEnabled,
784
+ workspaceMap,
785
+ projectRoot
786
+ }) {
787
+ const optimizerBundler = await rollup.rollup({
788
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
789
+ input: isVirtualFile ? "#entry" : entry,
790
+ treeshake: "smallest",
791
+ preserveSymlinks: true,
792
+ plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
793
+ external: DEPS_TO_IGNORE
794
+ });
795
+ const { output } = await optimizerBundler.generate({
796
+ format: "esm",
797
+ inlineDynamicImports: true
798
+ });
799
+ await optimizerBundler.close();
800
+ const depsToOptimize = await captureDependenciesToOptimize(output[0], workspaceMap, projectRoot, {
801
+ logger
802
+ });
803
+ return {
804
+ dependencies: depsToOptimize,
805
+ output: {
806
+ code: output[0].code,
807
+ map: output[0].map
808
+ }
809
+ };
810
+ }
811
+ function aliasHono() {
812
+ return {
813
+ name: "hono-alias",
814
+ resolveId(id) {
815
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
816
+ return;
817
+ }
818
+ const path3 = undefined(id);
819
+ return url.fileURLToPath(path3);
820
+ }
821
+ };
822
+ }
823
+
824
+ // src/build/analyze/bundleExternals.ts
825
+ function prepareEntryFileName(name, rootDir) {
826
+ const relativePath = path2__namespace.relative(rootDir, name);
827
+ return relativePath.replaceAll(path2__namespace.sep, path2__namespace.posix.sep);
828
+ }
829
+ function createVirtualDependencies(depsToOptimize, { projectRoot, workspaceRoot, outputDir }) {
830
+ const fileNameToDependencyMap = /* @__PURE__ */ new Map();
831
+ const optimizedDependencyEntries = /* @__PURE__ */ new Map();
832
+ const rootDir = workspaceRoot || projectRoot;
833
+ for (const [dep, { exports }] of depsToOptimize.entries()) {
834
+ const fileName = dep.replaceAll("/", "-");
788
835
  const virtualFile = [];
789
- let exportStringBuilder = [];
836
+ const exportStringBuilder = [];
790
837
  for (const local of exports) {
791
838
  if (local === "*") {
792
839
  virtualFile.push(`export * from '${dep}';`);
840
+ continue;
793
841
  } else if (local === "default") {
794
- virtualFile.push(`export { default } from '${dep}';`);
842
+ exportStringBuilder.push("default");
795
843
  } else {
796
844
  exportStringBuilder.push(local);
797
845
  }
798
846
  }
799
- if (exportStringBuilder.length > 0) {
800
- virtualFile.push(`export { ${exportStringBuilder.join(", ")} } from '${dep}';`);
847
+ const chunks = [];
848
+ if (exportStringBuilder.length) {
849
+ chunks.push(`{ ${exportStringBuilder.join(", ")} }`);
850
+ }
851
+ if (chunks.length) {
852
+ virtualFile.push(`export ${chunks.join(", ")} from '${dep}';`);
801
853
  }
802
- virtualDependencies.set(dep, {
803
- name,
854
+ let entryName = prepareEntryFileName(path2__namespace.join(outputDir, fileName), rootDir);
855
+ fileNameToDependencyMap.set(entryName, dep);
856
+ optimizedDependencyEntries.set(dep, {
857
+ name: entryName,
804
858
  virtual: virtualFile.join("\n")
805
859
  });
806
860
  }
861
+ for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
862
+ if (!isWorkspace || !rootPath || !workspaceRoot) {
863
+ continue;
864
+ }
865
+ const currentDepPath = optimizedDependencyEntries.get(dep);
866
+ if (!currentDepPath) {
867
+ continue;
868
+ }
869
+ const fileName = posix.basename(currentDepPath.name);
870
+ const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);
871
+ fileNameToDependencyMap.set(entryName, dep);
872
+ optimizedDependencyEntries.set(dep, {
873
+ ...currentDepPath,
874
+ name: entryName
875
+ });
876
+ }
877
+ return { optimizedDependencyEntries, fileNameToDependencyMap };
878
+ }
879
+ async function getInputPlugins2(virtualDependencies, transpilePackages, workspaceMap, bundlerOptions) {
807
880
  const transpilePackagesMap = /* @__PURE__ */ new Map();
808
- for (const pkg of transpilePackages) {
809
- const dir = await getPackageRootPath(pkg);
881
+ for (const pkg2 of transpilePackages) {
882
+ const dir = await getPackageRootPath(pkg2);
810
883
  if (dir) {
811
- transpilePackagesMap.set(pkg, dir);
884
+ transpilePackagesMap.set(pkg2, dir);
812
885
  }
813
886
  }
887
+ return [
888
+ virtual__default.default(
889
+ Array.from(virtualDependencies.entries()).reduce(
890
+ (acc, [dep, virtualDep]) => {
891
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
892
+ return acc;
893
+ },
894
+ {}
895
+ )
896
+ ),
897
+ transpilePackagesMap.size ? esbuild({
898
+ format: "esm",
899
+ include: [...transpilePackagesMap.values()].map((p) => {
900
+ return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
901
+ })
902
+ }) : null,
903
+ commonjs__default.default({
904
+ strictRequires: "strict",
905
+ transformMixedEsModules: true,
906
+ ignoreTryCatch: false
907
+ }),
908
+ bundlerOptions.enableEsmShim ? esmShim__default.default() : void 0,
909
+ nodeResolve__default.default({
910
+ preferBuiltins: true,
911
+ exportConditions: ["node"],
912
+ // Do not embed external dependencies into files that we write to `node_modules/.cache` (for the mastra dev + workspace use case)
913
+ ...workspaceMap.size > 0 ? { resolveOnly: Array.from(workspaceMap.keys()) } : {}
914
+ }),
915
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
916
+ aliasHono(),
917
+ json__default.default()
918
+ ];
919
+ }
920
+ async function buildExternalDependencies(virtualDependencies, {
921
+ externals,
922
+ packagesToTranspile,
923
+ workspaceMap,
924
+ rootDir,
925
+ outputDir,
926
+ bundlerOptions
927
+ }) {
928
+ if (virtualDependencies.size === 0) {
929
+ return [];
930
+ }
814
931
  const bundler = await rollup.rollup({
815
932
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
816
933
  input: Array.from(virtualDependencies.entries()).reduce(
@@ -820,81 +937,115 @@ async function bundleExternals(depsToOptimize, outputDir, logger, bundlerOptions
820
937
  },
821
938
  {}
822
939
  ),
823
- external: allExternals,
940
+ external: externals,
824
941
  treeshake: "smallest",
825
- plugins: [
826
- virtual__default.default(
827
- Array.from(virtualDependencies.entries()).reduce(
828
- (acc, [dep, virtualDep]) => {
829
- acc[`#virtual-${dep}`] = virtualDep.virtual;
830
- return acc;
831
- },
832
- {}
833
- )
834
- ),
835
- transpilePackagesMap.size ? esbuild({
836
- format: "esm",
837
- include: [...transpilePackagesMap.values()].map((p) => {
838
- return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
839
- })
840
- }) : null,
841
- commonjs2__default.default({
842
- strictRequires: "strict",
843
- transformMixedEsModules: true,
844
- ignoreTryCatch: false
845
- }),
846
- isDev ? esmShim__default.default() : void 0,
847
- nodeResolve__default.default({
848
- preferBuiltins: true,
849
- exportConditions: ["node"],
850
- // Do not embed external dependencies into files that we write to `node_modules/.cache` (for the mastra dev + workspace use case)
851
- ...workspaceMap.size > 0 && isDev ? { resolveOnly: Array.from(workspaceMap.keys()) } : {}
852
- }),
853
- // hono is imported from deployer, so we need to resolve from here instead of the project root
854
- aliasHono(),
855
- json2__default.default()
856
- ].filter(Boolean)
942
+ plugins: getInputPlugins2(virtualDependencies, packagesToTranspile, workspaceMap, bundlerOptions)
857
943
  });
944
+ const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
858
945
  const { output } = await bundler.write({
859
946
  format: "esm",
947
+ dir: rootDir,
948
+ entryFileNames: "[name].mjs",
860
949
  /**
861
- * If Mastra is used inside a monorepo, we need to find the workspace root so that Rollup can use it as base for the output dir. This should only happen during `mastra dev`.
862
- *
863
- * Otherwise, use outputDir as normal.
950
+ * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
951
+ * So we want to write them to the `.mastra/output` folder as well.
864
952
  */
865
- dir: isDev ? workspaceRoot ? workspaceRoot : outputDir : outputDir,
866
- entryFileNames: "[name].mjs",
867
- chunkFileNames: "[name].mjs",
953
+ chunkFileNames: `${outputDirRelative}/[name].mjs`,
868
954
  hoistTransitiveImports: false
869
955
  });
870
- const moduleResolveMap = {};
956
+ await bundler.close();
957
+ return output;
958
+ }
959
+ function findExternalImporter(module, external, allOutputs) {
960
+ const capturedFiles = /* @__PURE__ */ new Set();
961
+ for (const id of module.imports) {
962
+ if (id === external) {
963
+ return module;
964
+ } else {
965
+ if (id.endsWith(".mjs")) {
966
+ capturedFiles.add(id);
967
+ }
968
+ }
969
+ }
970
+ for (const file of capturedFiles) {
971
+ const nextModule = allOutputs.find((o) => o.fileName === file);
972
+ if (nextModule) {
973
+ const importer = findExternalImporter(nextModule, external, allOutputs);
974
+ if (importer) {
975
+ return importer;
976
+ }
977
+ }
978
+ }
979
+ return null;
980
+ }
981
+ async function bundleExternals(depsToOptimize, outputDir, options) {
982
+ const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {} } = options;
983
+ const {
984
+ externals: customExternals = [],
985
+ transpilePackages = [],
986
+ isDev = false,
987
+ enableEsmShim = true
988
+ } = bundlerOptions || {};
989
+ const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...customExternals];
990
+ const workspacePackagesNames = Array.from(workspaceMap.keys());
991
+ const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
992
+ const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
993
+ workspaceRoot,
994
+ outputDir,
995
+ projectRoot
996
+ });
997
+ const output = await buildExternalDependencies(optimizedDependencyEntries, {
998
+ externals: allExternals,
999
+ packagesToTranspile,
1000
+ workspaceMap: isDev ? workspaceMap : /* @__PURE__ */ new Map(),
1001
+ rootDir: workspaceRoot || projectRoot,
1002
+ outputDir,
1003
+ bundlerOptions: {
1004
+ enableEsmShim
1005
+ }
1006
+ });
1007
+ const moduleResolveMap = /* @__PURE__ */ new Map();
871
1008
  const filteredChunks = output.filter((o) => o.type === "chunk");
872
1009
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
873
1010
  for (const external of allExternals) {
874
- if (external === "#tools") {
1011
+ if (DEPS_TO_IGNORE.includes(external)) {
875
1012
  continue;
876
1013
  }
877
1014
  const importer = findExternalImporter(o, external, filteredChunks);
878
1015
  if (importer) {
879
- const fullPath = path.join(outputDir, importer.fileName);
880
- moduleResolveMap[fullPath] = moduleResolveMap[fullPath] || {};
1016
+ const fullPath = path2__namespace.join(workspaceRoot || projectRoot, importer.fileName);
1017
+ let innerMap = moduleResolveMap.get(fullPath);
1018
+ if (!innerMap) {
1019
+ innerMap = /* @__PURE__ */ new Map();
1020
+ moduleResolveMap.set(fullPath, innerMap);
1021
+ }
881
1022
  if (importer.moduleIds.length) {
882
- moduleResolveMap[fullPath][external] = importer.moduleIds[importer.moduleIds.length - 1]?.startsWith(
883
- "\0virtual:#virtual"
884
- ) ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1];
1023
+ innerMap.set(
1024
+ external,
1025
+ importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1]
1026
+ );
885
1027
  }
886
1028
  }
887
1029
  }
888
1030
  }
889
- await promises.writeFile(path.join(outputDir, "module-resolve-map.json"), JSON.stringify(moduleResolveMap, null, 2));
890
- await bundler.close();
891
- return { output, reverseVirtualReferenceMap, usedExternals: moduleResolveMap };
1031
+ const usedExternals = /* @__PURE__ */ Object.create(null);
1032
+ for (const [fullPath, innerMap] of moduleResolveMap) {
1033
+ const innerObj = /* @__PURE__ */ Object.create(null);
1034
+ for (const [external, value] of innerMap) {
1035
+ innerObj[external] = value;
1036
+ }
1037
+ usedExternals[fullPath] = innerObj;
1038
+ }
1039
+ return { output, fileNameToDependencyMap, usedExternals };
892
1040
  }
1041
+
1042
+ // src/build/analyze.ts
893
1043
  async function validateOutput({
894
1044
  output,
895
1045
  reverseVirtualReferenceMap,
896
1046
  usedExternals,
897
1047
  outputDir,
1048
+ projectRoot,
898
1049
  workspaceMap
899
1050
  }, logger) {
900
1051
  const result = {
@@ -903,6 +1054,7 @@ async function validateOutput({
903
1054
  externalDependencies: /* @__PURE__ */ new Set(),
904
1055
  workspaceMap
905
1056
  };
1057
+ await promises.writeFile(path2.join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
906
1058
  for (const deps of Object.values(usedExternals)) {
907
1059
  for (const dep of Object.keys(deps)) {
908
1060
  result.externalDependencies.add(dep);
@@ -918,7 +1070,7 @@ async function validateOutput({
918
1070
  result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
919
1071
  }
920
1072
  if (!file.isDynamicEntry && file.isEntry) {
921
- await validate(path.join(outputDir, file.fileName));
1073
+ await validate(path2.join(projectRoot, file.fileName));
922
1074
  }
923
1075
  } catch (err) {
924
1076
  result.invalidChunks.add(file.fileName);
@@ -931,7 +1083,12 @@ async function validateOutput({
931
1083
  }
932
1084
  return result;
933
1085
  }
934
- async function analyzeBundle(entries, mastraEntry, outputDir, platform, logger, sourcemapEnabled = false) {
1086
+ async function analyzeBundle(entries, mastraEntry, {
1087
+ outputDir,
1088
+ projectRoot,
1089
+ isDev = false,
1090
+ bundlerOptions: _bundlerOptions
1091
+ }, logger) {
935
1092
  const mastraConfig = await promises.readFile(mastraEntry, "utf-8");
936
1093
  const mastraConfigResult = {
937
1094
  hasValidConfig: false
@@ -949,46 +1106,64 @@ export const mastra = new Mastra({
949
1106
 
950
1107
  If you think your configuration is valid, please open an issue.`);
951
1108
  }
952
- const workspaceMap = await createWorkspacePackageMap();
1109
+ const { enableEsmShim = true } = _bundlerOptions || {};
1110
+ const bundlerOptions = await getBundlerOptions(mastraEntry, outputDir);
1111
+ const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1112
+ let index = 0;
953
1113
  const depsToOptimize = /* @__PURE__ */ new Map();
1114
+ logger.info("Analyzing dependencies...");
954
1115
  for (const entry of entries) {
955
1116
  const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
956
- const analyzeResult = await analyze(
957
- entry,
958
- mastraEntry,
959
- isVirtualFile,
960
- platform,
1117
+ const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
961
1118
  logger,
962
- sourcemapEnabled,
963
- workspaceMap
964
- );
965
- for (const [dep, { exports }] of analyzeResult.entries()) {
1119
+ sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1120
+ workspaceMap,
1121
+ projectRoot
1122
+ });
1123
+ await promises.writeFile(path2.join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1124
+ for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
966
1125
  if (depsToOptimize.has(dep)) {
967
1126
  const existingEntry = depsToOptimize.get(dep);
968
1127
  depsToOptimize.set(dep, {
969
1128
  ...existingEntry,
970
- exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...exports])]
1129
+ exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])]
971
1130
  });
972
1131
  } else {
973
- const isWorkspace = workspaceMap.has(dep);
974
- const pkgName = getPackageName(dep);
975
- let rootPath = null;
976
- if (pkgName && pkgName !== "#tools") {
977
- rootPath = await getPackageRootPath(pkgName);
978
- }
979
- depsToOptimize.set(dep, { exports, rootPath, isWorkspace });
1132
+ depsToOptimize.set(dep, metadata);
980
1133
  }
981
1134
  }
982
1135
  }
983
- const bundlerOptions = await getBundlerOptions(mastraEntry, outputDir);
984
- const { output, reverseVirtualReferenceMap, usedExternals } = await bundleExternals(
985
- depsToOptimize,
986
- outputDir,
987
- logger,
988
- bundlerOptions ?? void 0
1136
+ if (isDev) {
1137
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1138
+ if (!metadata.isWorkspace) {
1139
+ depsToOptimize.delete(dep);
1140
+ }
1141
+ }
1142
+ }
1143
+ logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1144
+ logger.info("Optimizing dependencies...");
1145
+ logger.debug(
1146
+ `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
989
1147
  );
1148
+ const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1149
+ bundlerOptions: {
1150
+ ...bundlerOptions,
1151
+ enableEsmShim,
1152
+ isDev
1153
+ },
1154
+ projectRoot,
1155
+ workspaceRoot,
1156
+ workspaceMap
1157
+ });
990
1158
  const result = await validateOutput(
991
- { output, reverseVirtualReferenceMap, usedExternals, outputDir, workspaceMap },
1159
+ {
1160
+ output,
1161
+ reverseVirtualReferenceMap: fileNameToDependencyMap,
1162
+ usedExternals,
1163
+ outputDir,
1164
+ projectRoot: workspaceRoot || projectRoot,
1165
+ workspaceMap
1166
+ },
992
1167
  logger
993
1168
  );
994
1169
  return result;
@@ -996,17 +1171,16 @@ If you think your configuration is valid, please open an issue.`);
996
1171
 
997
1172
  exports.aliasHono = aliasHono;
998
1173
  exports.analyzeBundle = analyzeBundle;
999
- exports.bundleExternals = bundleExternals;
1000
1174
  exports.collectTransitiveWorkspaceDependencies = collectTransitiveWorkspaceDependencies;
1001
- exports.createWorkspacePackageMap = createWorkspacePackageMap;
1002
1175
  exports.esbuild = esbuild;
1003
1176
  exports.extractMastraOption = extractMastraOption;
1004
1177
  exports.getBundlerOptions = getBundlerOptions;
1005
1178
  exports.getPackageName = getPackageName;
1006
1179
  exports.getPackageRootPath = getPackageRootPath;
1180
+ exports.getWorkspaceInformation = getWorkspaceInformation;
1007
1181
  exports.packWorkspaceDependencies = packWorkspaceDependencies;
1008
1182
  exports.removeAllOptionsFromMastraExcept = removeAllOptionsFromMastraExcept;
1009
1183
  exports.removeDeployer = removeDeployer2;
1010
1184
  exports.tsConfigPaths = tsConfigPaths;
1011
- //# sourceMappingURL=chunk-T4L3WY7M.cjs.map
1012
- //# sourceMappingURL=chunk-T4L3WY7M.cjs.map
1185
+ //# sourceMappingURL=chunk-M54YPGM4.cjs.map
1186
+ //# sourceMappingURL=chunk-M54YPGM4.cjs.map