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