@mastra/deployer 1.0.0-beta.0 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +200 -0
  2. package/dist/arktype-aI7TBD0R-4YXBEQBG.cjs +10 -0
  3. package/dist/arktype-aI7TBD0R-4YXBEQBG.cjs.map +1 -0
  4. package/dist/arktype-aI7TBD0R-OEPFT4G6.js +8 -0
  5. package/dist/arktype-aI7TBD0R-OEPFT4G6.js.map +1 -0
  6. package/dist/build/analyze/analyzeEntry.d.ts +4 -1
  7. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  8. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  9. package/dist/build/analyze.cjs +2 -2
  10. package/dist/build/analyze.d.ts +1 -1
  11. package/dist/build/analyze.d.ts.map +1 -1
  12. package/dist/build/analyze.js +1 -1
  13. package/dist/build/bundler.cjs +3 -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 +13 -13
  17. package/dist/build/index.js +4 -4
  18. package/dist/build/plugins/esm-shim.d.ts +14 -0
  19. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  20. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  21. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  22. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  23. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  24. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  25. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  26. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  27. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  28. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  29. package/dist/build/utils.d.ts +1 -0
  30. package/dist/build/utils.d.ts.map +1 -1
  31. package/dist/bundler/index.cjs +2 -2
  32. package/dist/bundler/index.d.ts +1 -1
  33. package/dist/bundler/index.js +1 -1
  34. package/dist/chunk-2OTEFUER.cjs +69 -0
  35. package/dist/chunk-2OTEFUER.cjs.map +1 -0
  36. package/dist/chunk-5CWPEG6R.js +62 -0
  37. package/dist/chunk-5CWPEG6R.js.map +1 -0
  38. package/dist/chunk-7PLNIFGZ.cjs +8 -0
  39. package/dist/chunk-7PLNIFGZ.cjs.map +1 -0
  40. package/dist/{chunk-IL2VLNIJ.cjs → chunk-BFQ2S5UD.cjs} +13 -23
  41. package/dist/chunk-BFQ2S5UD.cjs.map +1 -0
  42. package/dist/chunk-BTNPI4Z7.cjs +4 -0
  43. package/dist/chunk-BTNPI4Z7.cjs.map +1 -0
  44. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  45. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  46. package/dist/chunk-FBT6QP7J.js +3 -0
  47. package/dist/chunk-FBT6QP7J.js.map +1 -0
  48. package/dist/chunk-GD2TGMBP.cjs +95 -0
  49. package/dist/chunk-GD2TGMBP.cjs.map +1 -0
  50. package/dist/chunk-ID3HN3BH.cjs +16 -0
  51. package/dist/chunk-ID3HN3BH.cjs.map +1 -0
  52. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  53. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  54. package/dist/chunk-MMUE22EL.js +159 -0
  55. package/dist/chunk-MMUE22EL.js.map +1 -0
  56. package/dist/{chunk-C74EXQSL.cjs → chunk-MUWNMVNL.cjs} +570 -194
  57. package/dist/chunk-MUWNMVNL.cjs.map +1 -0
  58. package/dist/chunk-N5TMJUIR.js +14 -0
  59. package/dist/chunk-N5TMJUIR.js.map +1 -0
  60. package/dist/chunk-P4L6VIHY.js +93 -0
  61. package/dist/chunk-P4L6VIHY.js.map +1 -0
  62. package/dist/chunk-Q2YGWEXY.js +6 -0
  63. package/dist/chunk-Q2YGWEXY.js.map +1 -0
  64. package/dist/{chunk-WBAWUM7Z.js → chunk-RBPCXFN7.js} +6 -5
  65. package/dist/chunk-RBPCXFN7.js.map +1 -0
  66. package/dist/{chunk-AQAOWLJJ.cjs → chunk-SS22TD6R.cjs} +16 -15
  67. package/dist/chunk-SS22TD6R.cjs.map +1 -0
  68. package/dist/{chunk-H3LLQ2MW.js → chunk-TK2CCU7I.js} +553 -177
  69. package/dist/chunk-TK2CCU7I.js.map +1 -0
  70. package/dist/chunk-TXKETRIN.cjs +162 -0
  71. package/dist/chunk-TXKETRIN.cjs.map +1 -0
  72. package/dist/{chunk-OFUWEVGF.js → chunk-UQZGTSBF.js} +6 -15
  73. package/dist/chunk-UQZGTSBF.js.map +1 -0
  74. package/dist/{chunk-TDWIGFVF.cjs → chunk-X4TNUYQL.cjs} +15 -14
  75. package/dist/chunk-X4TNUYQL.cjs.map +1 -0
  76. package/dist/{chunk-HQJR52M7.js → chunk-X5QU7B2W.js} +5 -4
  77. package/dist/chunk-X5QU7B2W.js.map +1 -0
  78. package/dist/default-u_dwuiYb-65M4BHAA.js +3 -0
  79. package/dist/default-u_dwuiYb-65M4BHAA.js.map +1 -0
  80. package/dist/default-u_dwuiYb-PWN6FHC6.cjs +9 -0
  81. package/dist/default-u_dwuiYb-PWN6FHC6.cjs.map +1 -0
  82. package/dist/deploy/log.d.ts +1 -1
  83. package/dist/deploy/log.d.ts.map +1 -1
  84. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs +17 -0
  85. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs.map +1 -0
  86. package/dist/effect-QlVUlMFu-FD73M3OO.js +15 -0
  87. package/dist/effect-QlVUlMFu-FD73M3OO.js.map +1 -0
  88. package/dist/esm-BLVTLTJW.js +1289 -0
  89. package/dist/esm-BLVTLTJW.js.map +1 -0
  90. package/dist/esm-E3NUCNVN.cjs +1336 -0
  91. package/dist/esm-E3NUCNVN.cjs.map +1 -0
  92. package/dist/index.cjs +12 -12
  93. package/dist/index.js +4 -4
  94. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  95. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  96. package/dist/server/index.cjs +2336 -10512
  97. package/dist/server/index.cjs.map +1 -1
  98. package/dist/server/index.d.ts +3 -12
  99. package/dist/server/index.d.ts.map +1 -1
  100. package/dist/server/index.js +2327 -10503
  101. package/dist/server/index.js.map +1 -1
  102. package/dist/services/index.cjs +4 -4
  103. package/dist/services/index.js +1 -1
  104. package/dist/sury-CWZTCd75-K3FHMZF5.cjs +17 -0
  105. package/dist/sury-CWZTCd75-K3FHMZF5.cjs.map +1 -0
  106. package/dist/sury-CWZTCd75-Y2GURJ6K.js +15 -0
  107. package/dist/sury-CWZTCd75-Y2GURJ6K.js.map +1 -0
  108. package/dist/typebox-Dei93FPO-2WP4NOYD.js +8 -0
  109. package/dist/typebox-Dei93FPO-2WP4NOYD.js.map +1 -0
  110. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs +10 -0
  111. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs.map +1 -0
  112. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs +17 -0
  113. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs.map +1 -0
  114. package/dist/valibot--1zFm7rT-VGFBTDTW.js +15 -0
  115. package/dist/valibot--1zFm7rT-VGFBTDTW.js.map +1 -0
  116. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs +45 -0
  117. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs.map +1 -0
  118. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js +43 -0
  119. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js.map +1 -0
  120. package/dist/validator/custom-resolver.cjs +20 -12
  121. package/dist/validator/custom-resolver.cjs.map +1 -1
  122. package/dist/validator/custom-resolver.d.ts.map +1 -1
  123. package/dist/validator/custom-resolver.js +18 -10
  124. package/dist/validator/custom-resolver.js.map +1 -1
  125. package/dist/validator/validate.d.ts +15 -1
  126. package/dist/validator/validate.d.ts.map +1 -1
  127. package/dist/zod-Bwrt9trS-XCRGYQVE.js +29 -0
  128. package/dist/zod-Bwrt9trS-XCRGYQVE.js.map +1 -0
  129. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs +31 -0
  130. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs.map +1 -0
  131. package/dist/zod-DSgpEGAE-TKBHSSLS.js +37 -0
  132. package/dist/zod-DSgpEGAE-TKBHSSLS.js.map +1 -0
  133. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs +39 -0
  134. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs.map +1 -0
  135. package/package.json +18 -21
  136. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  137. package/dist/chunk-5QFG6SCM.js.map +0 -1
  138. package/dist/chunk-AQAOWLJJ.cjs.map +0 -1
  139. package/dist/chunk-C74EXQSL.cjs.map +0 -1
  140. package/dist/chunk-H3LLQ2MW.js.map +0 -1
  141. package/dist/chunk-HQJR52M7.js.map +0 -1
  142. package/dist/chunk-IL2VLNIJ.cjs.map +0 -1
  143. package/dist/chunk-OFUWEVGF.js.map +0 -1
  144. package/dist/chunk-TDWIGFVF.cjs.map +0 -1
  145. package/dist/chunk-WBAWUM7Z.js.map +0 -1
  146. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  147. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  148. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  149. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  150. package/dist/server/handlers/auth/index.d.ts +0 -11
  151. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  152. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -20
  153. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  154. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  155. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  156. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -232
  157. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  158. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  159. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  160. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  161. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  162. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  163. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  164. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  165. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  166. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  167. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  168. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  169. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  170. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -15
  171. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  172. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  173. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  174. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  175. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  176. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  177. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  178. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -302
  179. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  180. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  181. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  182. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  183. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  184. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  185. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  186. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  187. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  188. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  189. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  190. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  191. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  192. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  193. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
@@ -1,107 +1,44 @@
1
+ import { slash, isDependencyPartOfPackage, getPackageRootPath, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-5CWPEG6R.js';
1
2
  import * as babel from '@babel/core';
2
3
  import babel__default from '@babel/core';
3
4
  import fs, { existsSync } from 'fs';
4
5
  import { readFile, writeFile } from 'fs/promises';
5
6
  import * as path2 from 'path';
6
- import path2__default, { dirname, join, normalize, relative, basename as basename$1 } from 'path';
7
+ import path2__default, { dirname, join, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
- import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { rollup } from 'rollup';
11
10
  import originalEsbuild from 'rollup-plugin-esbuild';
12
11
  import commonjs from '@rollup/plugin-commonjs';
13
12
  import resolveFrom2 from 'resolve-from';
13
+ import stripJsonComments from 'strip-json-comments';
14
14
  import { createHandler } from 'typescript-paths';
15
15
  import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
16
16
  import json from '@rollup/plugin-json';
17
+ import { fileURLToPath, pathToFileURL } from 'url';
17
18
  import * as pkg from 'empathic/package';
18
19
  import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
19
20
  import { noopLogger } from '@mastra/core/logger';
20
21
  import virtual from '@rollup/plugin-virtual';
21
22
  import { builtinModules } from 'module';
22
23
  import nodeResolve from '@rollup/plugin-node-resolve';
23
- import esmShim from '@rollup/plugin-esm-shim';
24
+ import originalEsmShim from '@rollup/plugin-esm-shim';
24
25
  import { basename } from 'path/posix';
25
26
  import * as resolve from 'resolve.exports';
27
+ import { getPackageInfo } from 'local-pkg';
26
28
  import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
27
29
 
28
- // src/build/analyze.ts
29
- function getPackageName(id) {
30
- const parts = id.split("/");
31
- if (id.startsWith("@")) {
32
- return parts.slice(0, 2).join("/");
30
+ var ValidationError = class extends Error {
31
+ type;
32
+ stack;
33
+ constructor(args) {
34
+ super(args.message);
35
+ this.type = args.type;
36
+ this.stack = args.stack;
33
37
  }
34
- return parts[0];
35
- }
36
- async function getPackageRootPath(packageName, parentPath) {
37
- let rootPath;
38
- try {
39
- let options = void 0;
40
- if (parentPath) {
41
- if (!parentPath.startsWith("file://")) {
42
- parentPath = pathToFileURL(parentPath).href;
43
- }
44
- options = {
45
- paths: [parentPath]
46
- };
47
- }
48
- const pkg2 = await getPackageInfo(packageName, options);
49
- rootPath = pkg2?.rootPath ?? null;
50
- } catch (e) {
51
- rootPath = null;
52
- }
53
- return rootPath;
54
- }
55
- function getCompiledDepCachePath(rootPath, packageName) {
56
- return slash(join(rootPath, "node_modules", ".cache", packageName));
57
- }
58
- function slash(path3) {
59
- const isExtendedLengthPath = path3.startsWith("\\\\?\\");
60
- if (isExtendedLengthPath) {
61
- return path3;
62
- }
63
- return path3.replaceAll("\\", "/");
64
- }
65
- function rollupSafeName(name, rootDir) {
66
- const rel = relative(rootDir, name);
67
- let entry = slash(rel);
68
- entry = entry.replace(/^(\.\.\/)+/, "");
69
- entry = entry.replace(/^\/+/, "");
70
- entry = entry.replace(/^[A-Za-z]:\//, "");
71
- if (!entry) {
72
- entry = slash(basename$1(name));
73
- }
74
- return entry;
75
- }
76
- var NATIVE_BINDING_LOADERS = [
77
- "node-gyp-build",
78
- "prebuild-install",
79
- "bindings",
80
- "node-addon-api",
81
- "node-pre-gyp",
82
- "nan"
83
- // Native Abstractions for Node.js
84
- ];
85
- function findNativePackageModule(moduleIds) {
86
- return moduleIds.find((id) => {
87
- if (id.startsWith("\0")) {
88
- return false;
89
- }
90
- if (!id.includes("/node_modules/")) {
91
- return false;
92
- }
93
- for (const loader of NATIVE_BINDING_LOADERS) {
94
- if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {
95
- return false;
96
- }
97
- }
98
- return true;
99
- });
100
- }
101
-
102
- // src/validator/validate.ts
38
+ };
103
39
  function spawn(command, args = [], options = {}) {
104
40
  return new Promise((resolve2, reject) => {
41
+ let validationError = null;
105
42
  const childProcess = spawn$1(command, args, {
106
43
  // stdio: 'inherit',
107
44
  ...options
@@ -111,28 +48,63 @@ function spawn(command, args = [], options = {}) {
111
48
  });
112
49
  let stderr = "";
113
50
  childProcess.stderr?.on("data", (message) => {
114
- stderr += message;
51
+ try {
52
+ validationError = JSON.parse(message.toString());
53
+ } catch {
54
+ stderr += message;
55
+ }
115
56
  });
116
57
  childProcess.on("close", (code) => {
117
58
  if (code === 0) {
118
59
  resolve2();
119
60
  } else {
120
- reject(new Error(stderr));
61
+ if (validationError) {
62
+ reject(new ValidationError(validationError));
63
+ } else {
64
+ reject(new Error(stderr));
65
+ }
121
66
  }
122
67
  });
123
68
  });
124
69
  }
125
- function validate(file) {
70
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
71
+ let prefixCode = "";
72
+ if (injectESMShim) {
73
+ prefixCode = `import { fileURLToPath } from 'url';
74
+ import { dirname } from 'path';
75
+
76
+ globalThis.__filename = fileURLToPath(import.meta.url);
77
+ globalThis.__dirname = dirname(__filename);
78
+ `;
79
+ }
80
+ function errorHandler(err) {
81
+ console.error(
82
+ JSON.stringify({
83
+ type: err.name,
84
+ message: err.message,
85
+ stack: err.stack
86
+ })
87
+ );
88
+ process.exit(1);
89
+ }
126
90
  return spawn(
127
- "node",
91
+ process.execPath,
128
92
  [
129
93
  "--import",
130
94
  import.meta.resolve("@mastra/deployer/loader"),
131
95
  "--input-type=module",
96
+ "--enable-source-maps",
132
97
  "-e",
133
- `import('file://${slash(file)}')`
98
+ `${prefixCode};import('file://${slash(file)}').catch(err => {
99
+ ${errorHandler.toString()}
100
+ errorHandler(err);
101
+ })`.replaceAll(/\n/g, "")
134
102
  ],
135
103
  {
104
+ env: {
105
+ ...process.env,
106
+ MODULE_MAP: `${moduleResolveMapLocation}`
107
+ },
136
108
  cwd: dirname(file)
137
109
  }
138
110
  );
@@ -227,29 +199,90 @@ function esbuild(options = {}) {
227
199
  });
228
200
  }
229
201
  var PLUGIN_NAME = "tsconfig-paths";
202
+ function hasPaths(tsConfigPath) {
203
+ try {
204
+ const content = fs.readFileSync(tsConfigPath, "utf8");
205
+ const config = JSON.parse(stripJsonComments(content));
206
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
230
211
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
231
- let handler;
212
+ const handlerCache = /* @__PURE__ */ new Map();
213
+ function findTsConfigForFile(filePath) {
214
+ let currentDir = path2__default.dirname(filePath);
215
+ const root = path2__default.parse(currentDir).root;
216
+ while (currentDir !== root) {
217
+ const tsConfigPath2 = path2__default.join(currentDir, "tsconfig.json");
218
+ if (fs.existsSync(tsConfigPath2)) {
219
+ if (hasPaths(tsConfigPath2)) {
220
+ return tsConfigPath2;
221
+ }
222
+ }
223
+ const tsConfigBasePath = path2__default.join(currentDir, "tsconfig.base.json");
224
+ if (fs.existsSync(tsConfigBasePath)) {
225
+ if (hasPaths(tsConfigBasePath)) {
226
+ return tsConfigBasePath;
227
+ }
228
+ }
229
+ currentDir = path2__default.dirname(currentDir);
230
+ }
231
+ return null;
232
+ }
233
+ function getHandlerForFile(filePath) {
234
+ if (tsConfigPath && typeof tsConfigPath === "string") {
235
+ if (!handlerCache.has(tsConfigPath)) {
236
+ handlerCache.set(
237
+ tsConfigPath,
238
+ createHandler({
239
+ log: () => {
240
+ },
241
+ tsConfigPath,
242
+ respectCoreModule,
243
+ falllback: (moduleName) => fs.existsSync(moduleName)
244
+ })
245
+ );
246
+ }
247
+ return handlerCache.get(tsConfigPath);
248
+ }
249
+ const configPath = findTsConfigForFile(filePath);
250
+ if (!configPath) {
251
+ return null;
252
+ }
253
+ if (!handlerCache.has(configPath)) {
254
+ handlerCache.set(
255
+ configPath,
256
+ createHandler({
257
+ log: () => {
258
+ },
259
+ tsConfigPath: configPath,
260
+ respectCoreModule,
261
+ falllback: (moduleName) => fs.existsSync(moduleName)
262
+ })
263
+ );
264
+ }
265
+ return handlerCache.get(configPath);
266
+ }
267
+ function resolveAlias(request, importer) {
268
+ const dynamicHandler = getHandlerForFile(importer);
269
+ if (!dynamicHandler) {
270
+ return null;
271
+ }
272
+ const resolved = dynamicHandler(request, normalize(importer));
273
+ return resolved;
274
+ }
232
275
  return {
233
276
  name: PLUGIN_NAME,
234
- buildStart() {
235
- handler = createHandler({
236
- log: () => {
237
- },
238
- tsConfigPath,
239
- respectCoreModule,
240
- falllback: (moduleName) => fs.existsSync(moduleName)
241
- });
242
- return;
243
- },
244
277
  async resolveId(request, importer, options) {
245
- if (!importer || request.startsWith("\0")) {
278
+ if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) {
246
279
  return null;
247
280
  }
248
- const moduleName = handler?.(request, normalize(importer));
281
+ const moduleName = resolveAlias(request, importer);
249
282
  if (!moduleName) {
250
283
  let importerMeta = {};
251
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
252
- if (!resolved) {
284
+ const resolved2 = await this.resolve(request, importer, { skipSelf: true, ...options });
285
+ if (!resolved2) {
253
286
  return null;
254
287
  }
255
288
  if (localResolve) {
@@ -257,37 +290,42 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
257
290
  importerMeta = importerInfo?.meta || {};
258
291
  if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
259
292
  return {
260
- ...resolved,
293
+ ...resolved2,
261
294
  external: !request.startsWith("hono/") && request !== "hono"
262
295
  };
263
296
  }
264
297
  }
265
298
  return {
266
- ...resolved,
299
+ ...resolved2,
267
300
  meta: {
268
- ...resolved.meta || {},
301
+ ...resolved2.meta || {},
269
302
  ...importerMeta
270
303
  }
271
304
  };
272
305
  }
273
306
  if (!path2__default.extname(moduleName)) {
274
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
275
- if (!resolved) {
307
+ const resolved2 = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
308
+ if (!resolved2) {
276
309
  return null;
277
310
  }
278
311
  return {
279
- ...resolved,
312
+ ...resolved2,
280
313
  meta: {
281
- ...resolved.meta,
314
+ ...resolved2.meta,
282
315
  [PLUGIN_NAME]: {
283
316
  resolved: true
284
317
  }
285
318
  }
286
319
  };
287
320
  }
321
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
322
+ if (!resolved) {
323
+ return null;
324
+ }
288
325
  return {
289
- id: moduleName,
326
+ ...resolved,
290
327
  meta: {
328
+ ...resolved.meta,
291
329
  [PLUGIN_NAME]: {
292
330
  resolved: true
293
331
  }
@@ -448,7 +486,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
448
486
  const configPath = `${outputDir}/${name}-config.mjs`;
449
487
  return {
450
488
  bundleOutput: output,
451
- getConfig: () => import(`file:${configPath}`).then((m) => m[name])
489
+ getConfig: () => import(pathToFileURL(configPath).href).then((m) => m[name])
452
490
  };
453
491
  }
454
492
  return null;
@@ -666,7 +704,8 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
666
704
  return plugins;
667
705
  }
668
706
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
669
- logger
707
+ logger,
708
+ shouldCheckTransitiveDependencies
670
709
  }) {
671
710
  const depsToOptimize = /* @__PURE__ */ new Map();
672
711
  if (!output.facadeModuleId) {
@@ -679,7 +718,7 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
679
718
  entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
680
719
  }
681
720
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
682
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
721
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
683
722
  continue;
684
723
  }
685
724
  const pkgName = getPackageName(dependency);
@@ -690,7 +729,11 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
690
729
  isWorkspace = workspaceMap.has(pkgName);
691
730
  }
692
731
  const normalizedRootPath = rootPath ? slash(rootPath) : null;
693
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
732
+ depsToOptimize.set(dependency, {
733
+ exports: bindings,
734
+ rootPath: normalizedRootPath,
735
+ isWorkspace
736
+ });
694
737
  }
695
738
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
696
739
  if (currentDepth >= maxDepth) {
@@ -734,12 +777,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
734
777
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
735
778
  }
736
779
  }
737
- await checkTransitiveDependencies(initialDepsToOptimize);
780
+ if (shouldCheckTransitiveDependencies) {
781
+ await checkTransitiveDependencies(initialDepsToOptimize);
782
+ }
738
783
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
739
784
  if (dynamicImports.length) {
740
785
  for (const dynamicImport of dynamicImports) {
741
786
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
742
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
787
+ depsToOptimize.set(dynamicImport, {
788
+ exports: ["*"],
789
+ rootPath: null,
790
+ isWorkspace: false
791
+ });
743
792
  }
744
793
  }
745
794
  }
@@ -753,13 +802,14 @@ async function analyzeEntry({
753
802
  sourcemapEnabled,
754
803
  workspaceMap,
755
804
  projectRoot,
756
- initialDepsToOptimize = /* @__PURE__ */ new Map()
805
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
757
806
  // used to avoid infinite recursion
807
+ shouldCheckTransitiveDependencies = false
758
808
  }) {
759
809
  const optimizerBundler = await rollup({
760
810
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
761
811
  input: isVirtualFile ? "#entry" : entry,
762
- treeshake: "smallest",
812
+ treeshake: false,
763
813
  preserveSymlinks: true,
764
814
  plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
765
815
  external: DEPS_TO_IGNORE
@@ -775,7 +825,8 @@ async function analyzeEntry({
775
825
  projectRoot,
776
826
  initialDepsToOptimize,
777
827
  {
778
- logger
828
+ logger,
829
+ shouldCheckTransitiveDependencies
779
830
  }
780
831
  );
781
832
  return {
@@ -786,6 +837,27 @@ async function analyzeEntry({
786
837
  }
787
838
  };
788
839
  }
840
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
841
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
842
+ function esmShim() {
843
+ const original = originalEsmShim();
844
+ return {
845
+ name: "esm-shim",
846
+ renderChunk(code, chunk, opts, meta) {
847
+ const hasFilename = code.includes("__filename");
848
+ const hasDirname = code.includes("__dirname");
849
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
850
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
851
+ if (userDeclaredFilename || userDeclaredDirname) {
852
+ return null;
853
+ }
854
+ if (typeof original.renderChunk === "function") {
855
+ return original.renderChunk.call(this, code, chunk, opts, meta);
856
+ }
857
+ return null;
858
+ }
859
+ };
860
+ }
789
861
  function aliasHono() {
790
862
  return {
791
863
  name: "hono-alias",
@@ -798,6 +870,114 @@ function aliasHono() {
798
870
  }
799
871
  };
800
872
  }
873
+ function nodeGypDetector() {
874
+ const modulesToTrack = /* @__PURE__ */ new Set();
875
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
876
+ return {
877
+ name: "node-gyp-build-detector",
878
+ moduleParsed(info) {
879
+ if (!info.meta?.commonjs?.requires?.length) {
880
+ return;
881
+ }
882
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
883
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
884
+ );
885
+ if (!hasNodeGypBuild) {
886
+ return;
887
+ }
888
+ modulesToTrack.add(info.id);
889
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
890
+ },
891
+ async generateBundle(options, bundle) {
892
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
893
+ for (const [fileName, chunk] of Object.entries(bundle)) {
894
+ if (chunk.type === "chunk") {
895
+ for (const moduleId of chunk.moduleIds) {
896
+ if (modulesToTrackPackageInfo.has(moduleId)) {
897
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
898
+ if (!binaryMapByChunk.has(fileName)) {
899
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
900
+ }
901
+ if (pkgInfo?.packageJson?.name) {
902
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
903
+ }
904
+ }
905
+ }
906
+ }
907
+ }
908
+ const binaryMapJson = Object.fromEntries(
909
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
910
+ );
911
+ this.emitFile({
912
+ type: "asset",
913
+ name: "binary-map.json",
914
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
915
+ });
916
+ }
917
+ };
918
+ }
919
+
920
+ // src/build/plugins/subpath-externals-resolver.ts
921
+ function subpathExternalsResolver(externals) {
922
+ return {
923
+ name: "subpath-externals-resolver",
924
+ resolveId(id) {
925
+ if (id.startsWith(".") || id.startsWith("/")) {
926
+ return null;
927
+ }
928
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
929
+ if (isPartOfExternals) {
930
+ return {
931
+ id,
932
+ external: true
933
+ };
934
+ }
935
+ }
936
+ };
937
+ }
938
+ function moduleResolveMap(externals, projectRoot) {
939
+ const importMap = /* @__PURE__ */ new Map();
940
+ return {
941
+ name: "module-resolve-map",
942
+ moduleParsed(info) {
943
+ if (info.importedIds.length === 0 || !info.id) {
944
+ return;
945
+ }
946
+ for (const importedId of info.importedIds) {
947
+ for (const external of externals) {
948
+ if (isDependencyPartOfPackage(importedId, external)) {
949
+ importMap.set(external, info.id);
950
+ }
951
+ }
952
+ }
953
+ },
954
+ async generateBundle(options, bundle) {
955
+ const resolveMap = /* @__PURE__ */ new Map();
956
+ for (const [fileName, chunk] of Object.entries(bundle)) {
957
+ if (chunk.type === "chunk") {
958
+ for (const [external, resolvedFrom] of importMap) {
959
+ if (chunk.moduleIds.includes(resolvedFrom)) {
960
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
961
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
962
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
963
+ resolveMap.set(fullPath, innerMap);
964
+ }
965
+ }
966
+ }
967
+ }
968
+ const resolveMapJson = Object.fromEntries(
969
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
970
+ );
971
+ this.emitFile({
972
+ type: "asset",
973
+ name: "module-resolve-map.json",
974
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
975
+ });
976
+ }
977
+ };
978
+ }
979
+
980
+ // src/build/analyze/bundleExternals.ts
801
981
  function prepareEntryFileName(name, rootDir) {
802
982
  return rollupSafeName(name, rootDir);
803
983
  }
@@ -863,7 +1043,8 @@ async function getInputPlugins2(virtualDependencies, {
863
1043
  transpilePackages,
864
1044
  workspaceMap,
865
1045
  bundlerOptions,
866
- rootDir
1046
+ rootDir,
1047
+ externals
867
1048
  }) {
868
1049
  const transpilePackagesMap = /* @__PURE__ */ new Map();
869
1050
  for (const pkg2 of transpilePackages) {
@@ -884,6 +1065,7 @@ async function getInputPlugins2(virtualDependencies, {
884
1065
  {}
885
1066
  )
886
1067
  ),
1068
+ subpathExternalsResolver(externals),
887
1069
  transpilePackagesMap.size ? esbuild({
888
1070
  format: "esm",
889
1071
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -912,7 +1094,8 @@ async function getInputPlugins2(virtualDependencies, {
912
1094
  if (!resolvedPath) {
913
1095
  resolvedPath = pkgJson.main ?? "index.js";
914
1096
  }
915
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1097
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1098
+ return resolved;
916
1099
  }
917
1100
  } : null,
918
1101
  optimizeLodashImports({
@@ -931,6 +1114,8 @@ async function getInputPlugins2(virtualDependencies, {
931
1114
  // hono is imported from deployer, so we need to resolve from here instead of the project root
932
1115
  aliasHono(),
933
1116
  json(),
1117
+ nodeGypDetector(),
1118
+ moduleResolveMap(externals, rootDir),
934
1119
  {
935
1120
  name: "not-found-resolver",
936
1121
  resolveId: {
@@ -988,12 +1173,13 @@ async function buildExternalDependencies(virtualDependencies, {
988
1173
  {}
989
1174
  ),
990
1175
  external: externals,
991
- treeshake: "safest",
1176
+ treeshake: bundlerOptions.isDev ? false : "safest",
992
1177
  plugins: getInputPlugins2(virtualDependencies, {
993
1178
  transpilePackages: packagesToTranspile,
994
1179
  workspaceMap,
995
1180
  bundlerOptions,
996
- rootDir
1181
+ rootDir,
1182
+ externals
997
1183
  })
998
1184
  });
999
1185
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1001,6 +1187,8 @@ async function buildExternalDependencies(virtualDependencies, {
1001
1187
  format: "esm",
1002
1188
  dir: rootDir,
1003
1189
  entryFileNames: "[name].mjs",
1190
+ // used to get the filename of the actual error
1191
+ sourcemap: true,
1004
1192
  /**
1005
1193
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1006
1194
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1038,6 +1226,7 @@ async function buildExternalDependencies(virtualDependencies, {
1038
1226
  }
1039
1227
  return `${outputDirRelative}/[name].mjs`;
1040
1228
  },
1229
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1041
1230
  hoistTransitiveImports: false
1042
1231
  });
1043
1232
  await bundler.close();
@@ -1046,7 +1235,7 @@ async function buildExternalDependencies(virtualDependencies, {
1046
1235
  function findExternalImporter(module, external, allOutputs) {
1047
1236
  const capturedFiles = /* @__PURE__ */ new Set();
1048
1237
  for (const id of module.imports) {
1049
- if (id === external) {
1238
+ if (isDependencyPartOfPackage(id, external)) {
1050
1239
  return module;
1051
1240
  } else {
1052
1241
  if (id.endsWith(".mjs")) {
@@ -1092,7 +1281,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1092
1281
  isDev
1093
1282
  }
1094
1283
  });
1095
- const moduleResolveMap = /* @__PURE__ */ new Map();
1284
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1096
1285
  const filteredChunks = output.filter((o) => o.type === "chunk");
1097
1286
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1098
1287
  for (const external of allExternals) {
@@ -1102,10 +1291,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1102
1291
  const importer = findExternalImporter(o, external, filteredChunks);
1103
1292
  if (importer) {
1104
1293
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1105
- let innerMap = moduleResolveMap.get(fullPath);
1294
+ let innerMap = moduleResolveMap2.get(fullPath);
1106
1295
  if (!innerMap) {
1107
1296
  innerMap = /* @__PURE__ */ new Map();
1108
- moduleResolveMap.set(fullPath, innerMap);
1297
+ moduleResolveMap2.set(fullPath, innerMap);
1109
1298
  }
1110
1299
  if (importer.moduleIds.length) {
1111
1300
  innerMap.set(
@@ -1117,7 +1306,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1117
1306
  }
1118
1307
  }
1119
1308
  const usedExternals = /* @__PURE__ */ Object.create(null);
1120
- for (const [fullPath, innerMap] of moduleResolveMap) {
1309
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1121
1310
  const innerObj = /* @__PURE__ */ Object.create(null);
1122
1311
  for (const [external, value] of innerMap) {
1123
1312
  innerObj[external] = value;
@@ -1126,6 +1315,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1126
1315
  }
1127
1316
  return { output, fileNameToDependencyMap, usedExternals };
1128
1317
  }
1318
+
1319
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1320
+ var UNKNOWN_FUNCTION = "<unknown>";
1321
+ function parse(stackString) {
1322
+ var lines = stackString.split("\n");
1323
+ return lines.reduce(function(stack, line) {
1324
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1325
+ if (parseResult) {
1326
+ stack.push(parseResult);
1327
+ }
1328
+ return stack;
1329
+ }, []);
1330
+ }
1331
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1332
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1333
+ function parseChrome(line) {
1334
+ var parts = chromeRe.exec(line);
1335
+ if (!parts) {
1336
+ return null;
1337
+ }
1338
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1339
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1340
+ var submatch = chromeEvalRe.exec(parts[2]);
1341
+ if (isEval && submatch != null) {
1342
+ parts[2] = submatch[1];
1343
+ parts[3] = submatch[2];
1344
+ parts[4] = submatch[3];
1345
+ }
1346
+ return {
1347
+ file: !isNative ? parts[2] : null,
1348
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1349
+ arguments: isNative ? [parts[2]] : [],
1350
+ lineNumber: parts[3] ? +parts[3] : null,
1351
+ column: parts[4] ? +parts[4] : null
1352
+ };
1353
+ }
1354
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1355
+ function parseWinjs(line) {
1356
+ var parts = winjsRe.exec(line);
1357
+ if (!parts) {
1358
+ return null;
1359
+ }
1360
+ return {
1361
+ file: parts[2],
1362
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1363
+ arguments: [],
1364
+ lineNumber: +parts[3],
1365
+ column: parts[4] ? +parts[4] : null
1366
+ };
1367
+ }
1368
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1369
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1370
+ function parseGecko(line) {
1371
+ var parts = geckoRe.exec(line);
1372
+ if (!parts) {
1373
+ return null;
1374
+ }
1375
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1376
+ var submatch = geckoEvalRe.exec(parts[3]);
1377
+ if (isEval && submatch != null) {
1378
+ parts[3] = submatch[1];
1379
+ parts[4] = submatch[2];
1380
+ parts[5] = null;
1381
+ }
1382
+ return {
1383
+ file: parts[3],
1384
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1385
+ arguments: parts[2] ? parts[2].split(",") : [],
1386
+ lineNumber: parts[4] ? +parts[4] : null,
1387
+ column: parts[5] ? +parts[5] : null
1388
+ };
1389
+ }
1390
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1391
+ function parseJSC(line) {
1392
+ var parts = javaScriptCoreRe.exec(line);
1393
+ if (!parts) {
1394
+ return null;
1395
+ }
1396
+ return {
1397
+ file: parts[3],
1398
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1399
+ arguments: [],
1400
+ lineNumber: +parts[4],
1401
+ column: parts[5] ? +parts[5] : null
1402
+ };
1403
+ }
1404
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1405
+ function parseNode(line) {
1406
+ var parts = nodeRe.exec(line);
1407
+ if (!parts) {
1408
+ return null;
1409
+ }
1410
+ return {
1411
+ file: parts[2],
1412
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1413
+ arguments: [],
1414
+ lineNumber: +parts[3],
1415
+ column: parts[4] ? +parts[4] : null
1416
+ };
1417
+ }
1418
+
1419
+ // src/build/analyze.ts
1129
1420
  function throwExternalDependencyError({
1130
1421
  errorId,
1131
1422
  moduleName,
@@ -1149,6 +1440,110 @@ export const mastra = new Mastra({
1149
1440
  })`
1150
1441
  });
1151
1442
  }
1443
+ function getPackageNameFromBundledModuleName(moduleName) {
1444
+ const chunks = moduleName.split("-");
1445
+ if (!chunks.length) {
1446
+ return moduleName;
1447
+ }
1448
+ if (chunks[0]?.startsWith("@")) {
1449
+ return chunks.slice(0, 2).join("/");
1450
+ }
1451
+ return chunks[0];
1452
+ }
1453
+ function validateError(err, file, {
1454
+ binaryMapData,
1455
+ workspaceMap
1456
+ }) {
1457
+ let moduleName = null;
1458
+ let errorConfig = null;
1459
+ if (err instanceof ValidationError) {
1460
+ const parsedStack = parse(err.stack);
1461
+ if (err.type === "TypeError") {
1462
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1463
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1464
+ if (stacktraceFrame) {
1465
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1466
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1467
+ } else {
1468
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1469
+ }
1470
+ errorConfig = {
1471
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1472
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1473
+ };
1474
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1475
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1476
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1477
+ errorConfig = {
1478
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1479
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1480
+ };
1481
+ if (moduleName === parentModuleName) {
1482
+ return;
1483
+ }
1484
+ }
1485
+ }
1486
+ if (err.message.includes("No native build was found")) {
1487
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1488
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1489
+ errorConfig = {
1490
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1491
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1492
+ };
1493
+ }
1494
+ if (moduleName && workspaceMap.has(moduleName)) {
1495
+ throw new MastraError({
1496
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1497
+ domain: ErrorDomain.DEPLOYER,
1498
+ category: ErrorCategory.USER,
1499
+ details: {
1500
+ // importFile: moduleName,
1501
+ packageName: moduleName
1502
+ },
1503
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1504
+ Error: ${err.stack}`
1505
+ });
1506
+ }
1507
+ if (errorConfig && moduleName) {
1508
+ throwExternalDependencyError({
1509
+ errorId: errorConfig.id,
1510
+ moduleName,
1511
+ packageName: moduleName,
1512
+ messagePrefix: errorConfig.messagePrefix
1513
+ });
1514
+ }
1515
+ }
1516
+ async function validateFile(root, file, {
1517
+ binaryMapData,
1518
+ moduleResolveMapLocation,
1519
+ logger,
1520
+ workspaceMap
1521
+ }) {
1522
+ try {
1523
+ if (!file.isDynamicEntry && file.isEntry) {
1524
+ await validate(join(root, file.fileName), {
1525
+ moduleResolveMapLocation,
1526
+ injectESMShim: false
1527
+ });
1528
+ }
1529
+ } catch (err) {
1530
+ let errorToHandle = err;
1531
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1532
+ try {
1533
+ await validate(join(root, file.fileName), {
1534
+ moduleResolveMapLocation,
1535
+ injectESMShim: true
1536
+ });
1537
+ errorToHandle = null;
1538
+ } catch (err2) {
1539
+ errorToHandle = err2;
1540
+ }
1541
+ }
1542
+ if (errorToHandle instanceof Error) {
1543
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1544
+ }
1545
+ }
1546
+ }
1152
1547
  async function validateOutput({
1153
1548
  output,
1154
1549
  reverseVirtualReferenceMap,
@@ -1162,60 +1557,30 @@ async function validateOutput({
1162
1557
  externalDependencies: /* @__PURE__ */ new Set(),
1163
1558
  workspaceMap
1164
1559
  };
1165
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1166
1560
  for (const deps of Object.values(usedExternals)) {
1167
1561
  for (const dep of Object.keys(deps)) {
1168
1562
  result.externalDependencies.add(dep);
1169
1563
  }
1170
1564
  }
1565
+ let binaryMapData = {};
1566
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1567
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1568
+ binaryMapData = JSON.parse(binaryMap);
1569
+ }
1171
1570
  for (const file of output) {
1172
1571
  if (file.type === "asset") {
1173
1572
  continue;
1174
1573
  }
1175
- try {
1176
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1177
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1178
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1179
- }
1180
- if (!file.isDynamicEntry && file.isEntry) {
1181
- await validate(join(projectRoot, file.fileName));
1182
- }
1183
- } catch (err) {
1184
- if (err instanceof Error) {
1185
- let moduleName = null;
1186
- let errorConfig = null;
1187
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1188
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1189
- const fallbackName = file.name.split("/").pop();
1190
- moduleName = moduleIdName ?? fallbackName;
1191
- errorConfig = {
1192
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1193
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1194
- };
1195
- } else if (err.message.includes("Error: No native build was found for ")) {
1196
- moduleName = findNativePackageModule(file.moduleIds);
1197
- errorConfig = {
1198
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1199
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1200
- };
1201
- }
1202
- if (moduleName && errorConfig) {
1203
- const pkgInfo = await getPackageInfo(moduleName);
1204
- const packageName = pkgInfo?.packageJson?.name;
1205
- if (packageName) {
1206
- throwExternalDependencyError({
1207
- errorId: errorConfig.id,
1208
- moduleName,
1209
- packageName,
1210
- messagePrefix: errorConfig.messagePrefix
1211
- });
1212
- } else {
1213
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1214
- }
1215
- }
1216
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1217
- }
1574
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1575
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1576
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1218
1577
  }
1578
+ await validateFile(projectRoot, file, {
1579
+ binaryMapData,
1580
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1581
+ logger,
1582
+ workspaceMap
1583
+ });
1219
1584
  }
1220
1585
  return result;
1221
1586
  }
@@ -1247,17 +1612,26 @@ If you think your configuration is valid, please open an issue.`);
1247
1612
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1248
1613
  let index = 0;
1249
1614
  const depsToOptimize = /* @__PURE__ */ new Map();
1615
+ const { externals: customExternals = [] } = bundlerOptions || {};
1616
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1250
1617
  logger.info("Analyzing dependencies...");
1618
+ const allUsedExternals = /* @__PURE__ */ new Set();
1251
1619
  for (const entry of entries) {
1252
1620
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1253
1621
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1254
1622
  logger,
1255
1623
  sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1256
1624
  workspaceMap,
1257
- projectRoot
1625
+ projectRoot,
1626
+ shouldCheckTransitiveDependencies: isDev
1258
1627
  });
1259
1628
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1260
1629
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1630
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1631
+ if (isPartOfExternals) {
1632
+ allUsedExternals.add(dep);
1633
+ continue;
1634
+ }
1261
1635
  if (depsToOptimize.has(dep)) {
1262
1636
  const existingEntry = depsToOptimize.get(dep);
1263
1637
  depsToOptimize.set(dep, {
@@ -1276,14 +1650,13 @@ If you think your configuration is valid, please open an issue.`);
1276
1650
  }
1277
1651
  }
1278
1652
  }
1279
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1653
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1280
1654
  logger.info("Optimizing dependencies...");
1281
- logger.debug(
1282
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1283
- );
1655
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1284
1656
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1285
1657
  bundlerOptions: {
1286
1658
  ...bundlerOptions,
1659
+ externals: allExternals,
1287
1660
  enableEsmShim,
1288
1661
  isDev
1289
1662
  },
@@ -1302,9 +1675,12 @@ If you think your configuration is valid, please open an issue.`);
1302
1675
  },
1303
1676
  logger
1304
1677
  );
1305
- return result;
1678
+ return {
1679
+ ...result,
1680
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1681
+ };
1306
1682
  }
1307
1683
 
1308
- export { aliasHono, analyzeBundle, esbuild, extractMastraOption, getBundlerOptions, getPackageName, getPackageRootPath, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, slash, tsConfigPaths };
1309
- //# sourceMappingURL=chunk-H3LLQ2MW.js.map
1310
- //# sourceMappingURL=chunk-H3LLQ2MW.js.map
1684
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1685
+ //# sourceMappingURL=chunk-TK2CCU7I.js.map
1686
+ //# sourceMappingURL=chunk-TK2CCU7I.js.map