@mastra/deployer 1.0.0-beta.2 → 1.0.0-beta.20

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 (237) hide show
  1. package/CHANGELOG.md +357 -0
  2. package/dist/arktype-aI7TBD0R-CCZH3EYK.js +8 -0
  3. package/dist/arktype-aI7TBD0R-CCZH3EYK.js.map +1 -0
  4. package/dist/arktype-aI7TBD0R-XHBHUL3T.cjs +10 -0
  5. package/dist/arktype-aI7TBD0R-XHBHUL3T.cjs.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 +4 -5
  9. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  10. package/dist/build/analyze.cjs +2 -2
  11. package/dist/build/analyze.d.ts +6 -6
  12. package/dist/build/analyze.d.ts.map +1 -1
  13. package/dist/build/analyze.js +1 -1
  14. package/dist/build/babel/remove-deployer.d.ts.map +1 -1
  15. package/dist/build/bundler.cjs +3 -3
  16. package/dist/build/bundler.d.ts +3 -1
  17. package/dist/build/bundler.d.ts.map +1 -1
  18. package/dist/build/bundler.js +1 -1
  19. package/dist/build/bundlerOptions.d.ts.map +1 -1
  20. package/dist/build/deployer.d.ts.map +1 -1
  21. package/dist/build/index.cjs +22 -13
  22. package/dist/build/index.d.ts +2 -0
  23. package/dist/build/index.d.ts.map +1 -1
  24. package/dist/build/index.js +5 -4
  25. package/dist/build/package-info.d.ts +9 -0
  26. package/dist/build/package-info.d.ts.map +1 -0
  27. package/dist/build/plugins/esm-shim.d.ts +14 -0
  28. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  29. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  30. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  31. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  32. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  33. package/dist/build/plugins/node-modules-extension-resolver.d.ts +7 -0
  34. package/dist/build/plugins/node-modules-extension-resolver.d.ts.map +1 -1
  35. package/dist/build/plugins/remove-all-except.d.ts +10 -0
  36. package/dist/build/plugins/remove-all-except.d.ts.map +1 -0
  37. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  38. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  39. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  40. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  41. package/dist/build/serverOptions.d.ts.map +1 -1
  42. package/dist/build/shared/extract-mastra-option.d.ts +4 -8
  43. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  44. package/dist/build/types.d.ts +5 -0
  45. package/dist/build/types.d.ts.map +1 -1
  46. package/dist/build/utils.d.ts +36 -4
  47. package/dist/build/utils.d.ts.map +1 -1
  48. package/dist/build/watcher.d.ts +2 -1
  49. package/dist/build/watcher.d.ts.map +1 -1
  50. package/dist/bundler/index.cjs +6 -2
  51. package/dist/bundler/index.d.ts +11 -8
  52. package/dist/bundler/index.d.ts.map +1 -1
  53. package/dist/bundler/index.js +1 -1
  54. package/dist/chunk-2VG357HT.cjs +4 -0
  55. package/dist/chunk-2VG357HT.cjs.map +1 -0
  56. package/dist/{chunk-OFUWEVGF.js → chunk-2ZPRZMBN.js} +70 -24
  57. package/dist/chunk-2ZPRZMBN.js.map +1 -0
  58. package/dist/{chunk-H3LLQ2MW.js → chunk-4NPMVODD.js} +813 -349
  59. package/dist/chunk-4NPMVODD.js.map +1 -0
  60. package/dist/chunk-5TYVF4KJ.cjs +76 -0
  61. package/dist/chunk-5TYVF4KJ.cjs.map +1 -0
  62. package/dist/chunk-DBXWQ2CA.js +159 -0
  63. package/dist/chunk-DBXWQ2CA.js.map +1 -0
  64. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  65. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  66. package/dist/chunk-G6GFAPPU.js +6 -0
  67. package/dist/chunk-G6GFAPPU.js.map +1 -0
  68. package/dist/chunk-HPGDVJAZ.js +3 -0
  69. package/dist/chunk-HPGDVJAZ.js.map +1 -0
  70. package/dist/{chunk-IL2VLNIJ.cjs → chunk-HVKR4FT2.cjs} +77 -31
  71. package/dist/chunk-HVKR4FT2.cjs.map +1 -0
  72. package/dist/chunk-JBE6KM7R.cjs +95 -0
  73. package/dist/chunk-JBE6KM7R.cjs.map +1 -0
  74. package/dist/chunk-JRUJ546M.cjs +162 -0
  75. package/dist/chunk-JRUJ546M.cjs.map +1 -0
  76. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  77. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  78. package/dist/chunk-KE4NVPI4.cjs +8 -0
  79. package/dist/chunk-KE4NVPI4.cjs.map +1 -0
  80. package/dist/chunk-MCWU6IKS.js +14 -0
  81. package/dist/chunk-MCWU6IKS.js.map +1 -0
  82. package/dist/{chunk-WBAWUM7Z.js → chunk-NGWTN4SJ.js} +48 -28
  83. package/dist/chunk-NGWTN4SJ.js.map +1 -0
  84. package/dist/{chunk-C74EXQSL.cjs → chunk-NWQP6PZQ.cjs} +826 -362
  85. package/dist/chunk-NWQP6PZQ.cjs.map +1 -0
  86. package/dist/chunk-QAOUDKHK.js +67 -0
  87. package/dist/chunk-QAOUDKHK.js.map +1 -0
  88. package/dist/{chunk-AQAOWLJJ.cjs → chunk-SBGBJ7NB.cjs} +57 -36
  89. package/dist/chunk-SBGBJ7NB.cjs.map +1 -0
  90. package/dist/chunk-UKP4KHBS.js +88 -0
  91. package/dist/chunk-UKP4KHBS.js.map +1 -0
  92. package/dist/chunk-V4HCIN6G.js +93 -0
  93. package/dist/chunk-V4HCIN6G.js.map +1 -0
  94. package/dist/chunk-Z53UZLS3.cjs +112 -0
  95. package/dist/chunk-Z53UZLS3.cjs.map +1 -0
  96. package/dist/chunk-ZXQ7DOYU.cjs +16 -0
  97. package/dist/chunk-ZXQ7DOYU.cjs.map +1 -0
  98. package/dist/default-u_dwuiYb-JPNIZQKK.cjs +9 -0
  99. package/dist/default-u_dwuiYb-JPNIZQKK.cjs.map +1 -0
  100. package/dist/default-u_dwuiYb-RK5OD4MY.js +3 -0
  101. package/dist/default-u_dwuiYb-RK5OD4MY.js.map +1 -0
  102. package/dist/deploy/log.d.ts +1 -1
  103. package/dist/deploy/log.d.ts.map +1 -1
  104. package/dist/docs/README.md +32 -0
  105. package/dist/docs/SKILL.md +36 -0
  106. package/dist/docs/SOURCE_MAP.json +27 -0
  107. package/dist/docs/deployer/01-reference.md +93 -0
  108. package/dist/docs/deployment/01-overview.md +60 -0
  109. package/dist/docs/deployment/02-mastra-server.md +70 -0
  110. package/dist/docs/deployment/03-monorepo.md +70 -0
  111. package/dist/docs/deployment/04-cloud-providers.md +17 -0
  112. package/dist/docs/deployment/05-web-framework.md +55 -0
  113. package/dist/docs/deployment/06-workflow-runners.md +11 -0
  114. package/dist/effect-QlVUlMFu-HN3LWZSQ.cjs +17 -0
  115. package/dist/effect-QlVUlMFu-HN3LWZSQ.cjs.map +1 -0
  116. package/dist/effect-QlVUlMFu-XOJ2F4UA.js +15 -0
  117. package/dist/effect-QlVUlMFu-XOJ2F4UA.js.map +1 -0
  118. package/dist/esm-6TGK2CUM.js +1289 -0
  119. package/dist/esm-6TGK2CUM.js.map +1 -0
  120. package/dist/esm-SQKX5ABS.cjs +1336 -0
  121. package/dist/esm-SQKX5ABS.cjs.map +1 -0
  122. package/dist/index.cjs +11 -22
  123. package/dist/index.cjs.map +1 -1
  124. package/dist/index.js +5 -16
  125. package/dist/index.js.map +1 -1
  126. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  127. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  128. package/dist/server/index.cjs +2659 -10538
  129. package/dist/server/index.cjs.map +1 -1
  130. package/dist/server/index.d.ts +3 -12
  131. package/dist/server/index.d.ts.map +1 -1
  132. package/dist/server/index.js +2662 -10542
  133. package/dist/server/index.js.map +1 -1
  134. package/dist/services/index.cjs +4 -4
  135. package/dist/services/index.js +1 -1
  136. package/dist/sury-CWZTCd75-KEHKUXG7.cjs +17 -0
  137. package/dist/sury-CWZTCd75-KEHKUXG7.cjs.map +1 -0
  138. package/dist/sury-CWZTCd75-L2D76L25.js +15 -0
  139. package/dist/sury-CWZTCd75-L2D76L25.js.map +1 -0
  140. package/dist/typebox-Dei93FPO-LBLFC3RD.js +8 -0
  141. package/dist/typebox-Dei93FPO-LBLFC3RD.js.map +1 -0
  142. package/dist/typebox-Dei93FPO-RDSW6DFA.cjs +10 -0
  143. package/dist/typebox-Dei93FPO-RDSW6DFA.cjs.map +1 -0
  144. package/dist/valibot--1zFm7rT-NVADAEQI.cjs +17 -0
  145. package/dist/valibot--1zFm7rT-NVADAEQI.cjs.map +1 -0
  146. package/dist/valibot--1zFm7rT-R2UKWLZC.js +15 -0
  147. package/dist/valibot--1zFm7rT-R2UKWLZC.js.map +1 -0
  148. package/dist/valibot-D_HTw1Gn-DSFFOUBW.cjs +45 -0
  149. package/dist/valibot-D_HTw1Gn-DSFFOUBW.cjs.map +1 -0
  150. package/dist/valibot-D_HTw1Gn-KWXWP2TJ.js +43 -0
  151. package/dist/valibot-D_HTw1Gn-KWXWP2TJ.js.map +1 -0
  152. package/dist/validator/custom-resolver.cjs +20 -12
  153. package/dist/validator/custom-resolver.cjs.map +1 -1
  154. package/dist/validator/custom-resolver.d.ts.map +1 -1
  155. package/dist/validator/custom-resolver.js +18 -10
  156. package/dist/validator/custom-resolver.js.map +1 -1
  157. package/dist/validator/validate.d.ts +15 -1
  158. package/dist/validator/validate.d.ts.map +1 -1
  159. package/dist/zod-Bwrt9trS-GCUGPBJX.js +29 -0
  160. package/dist/zod-Bwrt9trS-GCUGPBJX.js.map +1 -0
  161. package/dist/zod-Bwrt9trS-ZZHFZ7YQ.cjs +31 -0
  162. package/dist/zod-Bwrt9trS-ZZHFZ7YQ.cjs.map +1 -0
  163. package/dist/zod-DSgpEGAE-3CMS4FSB.cjs +39 -0
  164. package/dist/zod-DSgpEGAE-3CMS4FSB.cjs.map +1 -0
  165. package/dist/zod-DSgpEGAE-IPE3O2NQ.js +37 -0
  166. package/dist/zod-DSgpEGAE-IPE3O2NQ.js.map +1 -0
  167. package/package.json +21 -24
  168. package/dist/build/babel/get-deployer.d.ts +0 -3
  169. package/dist/build/babel/get-deployer.d.ts.map +0 -1
  170. package/dist/build/babel/remove-all-options-bundler.d.ts +0 -5
  171. package/dist/build/babel/remove-all-options-bundler.d.ts.map +0 -1
  172. package/dist/build/babel/remove-all-options-deployer.d.ts +0 -5
  173. package/dist/build/babel/remove-all-options-deployer.d.ts.map +0 -1
  174. package/dist/build/babel/remove-all-options-server.d.ts +0 -5
  175. package/dist/build/babel/remove-all-options-server.d.ts.map +0 -1
  176. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  177. package/dist/chunk-5QFG6SCM.js.map +0 -1
  178. package/dist/chunk-AQAOWLJJ.cjs.map +0 -1
  179. package/dist/chunk-C74EXQSL.cjs.map +0 -1
  180. package/dist/chunk-H3LLQ2MW.js.map +0 -1
  181. package/dist/chunk-HQJR52M7.js +0 -168
  182. package/dist/chunk-HQJR52M7.js.map +0 -1
  183. package/dist/chunk-IL2VLNIJ.cjs.map +0 -1
  184. package/dist/chunk-OFUWEVGF.js.map +0 -1
  185. package/dist/chunk-TDWIGFVF.cjs +0 -195
  186. package/dist/chunk-TDWIGFVF.cjs.map +0 -1
  187. package/dist/chunk-WBAWUM7Z.js.map +0 -1
  188. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  189. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  190. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  191. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  192. package/dist/server/handlers/auth/index.d.ts +0 -11
  193. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  194. package/dist/server/handlers/prompt.d.ts +0 -3
  195. package/dist/server/handlers/prompt.d.ts.map +0 -1
  196. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -20
  197. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  198. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  199. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  200. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -232
  201. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  202. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  203. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  204. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  205. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  206. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  207. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  208. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  209. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  210. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  211. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  212. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  213. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  214. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -15
  215. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  216. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  217. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  218. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  219. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  220. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  221. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  222. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -302
  223. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  224. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  225. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  226. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  227. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  228. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  229. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  230. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  231. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  232. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  233. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  234. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  235. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  236. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  237. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
@@ -1,16 +1,17 @@
1
+ import { slash, isDependencyPartOfPackage, isBuiltinModule, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-QAOUDKHK.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, relative, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
9
  import { pathToFileURL, fileURLToPath } from 'url';
10
10
  import { rollup } from 'rollup';
11
11
  import originalEsbuild from 'rollup-plugin-esbuild';
12
12
  import commonjs from '@rollup/plugin-commonjs';
13
13
  import resolveFrom2 from 'resolve-from';
14
+ import stripJsonComments from 'strip-json-comments';
14
15
  import { createHandler } from 'typescript-paths';
15
16
  import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
16
17
  import json from '@rollup/plugin-json';
@@ -19,89 +20,25 @@ import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-
19
20
  import { noopLogger } from '@mastra/core/logger';
20
21
  import virtual from '@rollup/plugin-virtual';
21
22
  import { builtinModules } from 'module';
23
+ import { getPackageInfo } from 'local-pkg';
22
24
  import nodeResolve from '@rollup/plugin-node-resolve';
23
- import esmShim from '@rollup/plugin-esm-shim';
25
+ import originalEsmShim from '@rollup/plugin-esm-shim';
24
26
  import { basename } from 'path/posix';
25
27
  import * as resolve from 'resolve.exports';
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,113 +48,67 @@ 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('${pathToFileURL(file).href}').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
  );
139
111
  }
140
- function removeAllOptionsFromMastraExcept(result, option, logger) {
141
- const t = babel__default.types;
142
- return {
143
- name: "remove-all-except-" + option + "-config",
144
- visitor: {
145
- ExportNamedDeclaration: {
146
- // remove all exports
147
- exit(path3) {
148
- path3.remove();
149
- }
150
- },
151
- NewExpression(path3, state) {
152
- const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
153
- if (!varDeclaratorPath) {
154
- return;
155
- }
156
- const parentNode = path3.parentPath.node;
157
- if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
158
- return;
159
- }
160
- let mastraArgs = t.objectExpression([]);
161
- if (t.isObjectExpression(path3.node.arguments[0])) {
162
- mastraArgs = path3.node.arguments[0];
163
- }
164
- let configProperty = mastraArgs.properties.find(
165
- // @ts-ignore
166
- (prop) => prop.key.name === option
167
- );
168
- let configValue = t.objectExpression([]);
169
- const programPath = path3.scope.getProgramParent().path;
170
- if (!programPath) {
171
- return;
172
- }
173
- if (configProperty && t.isObjectProperty(configProperty) && t.isExpression(configProperty.value)) {
174
- result.hasCustomConfig = true;
175
- configValue = configProperty.value;
176
- if (t.isIdentifier(configProperty.value) && configProperty.value.name === option) {
177
- const configBinding = state.file.scope.getBinding(option);
178
- if (configBinding && t.isVariableDeclarator(configBinding.path.node)) {
179
- const id = path3.scope.generateUidIdentifier(option);
180
- configBinding.path.replaceWith(t.variableDeclarator(id, configBinding.path.node.init));
181
- configValue = id;
182
- }
183
- }
184
- }
185
- const exportDeclaration = t.exportNamedDeclaration(
186
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), configValue)]),
187
- []
188
- );
189
- programPath.node.body.push(exportDeclaration);
190
- },
191
- Program: {
192
- exit(path3) {
193
- const hasExport = path3.node.body.some(
194
- (node) => node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration"
195
- );
196
- if (!hasExport) {
197
- if (logger) {
198
- logger.warn(`Mastra ${option} config could not be extracted. Please make sure your entry file looks like this:
199
- export const mastra = new Mastra({
200
- ${option}: <value>
201
- })
202
-
203
- `);
204
- }
205
- const fallbackExportDeclaration = t.exportNamedDeclaration(
206
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), t.objectExpression([]))]),
207
- []
208
- );
209
- path3.node.body.push(fallbackExportDeclaration);
210
- }
211
- }
212
- }
213
- }
214
- };
215
- }
216
-
217
- // src/build/babel/remove-all-options-bundler.ts
218
- function removeAllOptionsExceptBundler(result, logger) {
219
- return removeAllOptionsFromMastraExcept(result, "bundler", logger);
220
- }
221
112
  function esbuild(options = {}) {
222
113
  return originalEsbuild({
223
114
  target: "node20",
@@ -227,29 +118,90 @@ function esbuild(options = {}) {
227
118
  });
228
119
  }
229
120
  var PLUGIN_NAME = "tsconfig-paths";
121
+ function hasPaths(tsConfigPath) {
122
+ try {
123
+ const content = fs.readFileSync(tsConfigPath, "utf8");
124
+ const config = JSON.parse(stripJsonComments(content));
125
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
126
+ } catch {
127
+ return false;
128
+ }
129
+ }
230
130
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
231
- let handler;
131
+ const handlerCache = /* @__PURE__ */ new Map();
132
+ function findTsConfigForFile(filePath) {
133
+ let currentDir = path2__default.dirname(filePath);
134
+ const root = path2__default.parse(currentDir).root;
135
+ while (currentDir !== root) {
136
+ const tsConfigPath2 = path2__default.join(currentDir, "tsconfig.json");
137
+ if (fs.existsSync(tsConfigPath2)) {
138
+ if (hasPaths(tsConfigPath2)) {
139
+ return tsConfigPath2;
140
+ }
141
+ }
142
+ const tsConfigBasePath = path2__default.join(currentDir, "tsconfig.base.json");
143
+ if (fs.existsSync(tsConfigBasePath)) {
144
+ if (hasPaths(tsConfigBasePath)) {
145
+ return tsConfigBasePath;
146
+ }
147
+ }
148
+ currentDir = path2__default.dirname(currentDir);
149
+ }
150
+ return null;
151
+ }
152
+ function getHandlerForFile(filePath) {
153
+ if (tsConfigPath && typeof tsConfigPath === "string") {
154
+ if (!handlerCache.has(tsConfigPath)) {
155
+ handlerCache.set(
156
+ tsConfigPath,
157
+ createHandler({
158
+ log: () => {
159
+ },
160
+ tsConfigPath,
161
+ respectCoreModule,
162
+ falllback: (moduleName) => fs.existsSync(moduleName)
163
+ })
164
+ );
165
+ }
166
+ return handlerCache.get(tsConfigPath);
167
+ }
168
+ const configPath = findTsConfigForFile(filePath);
169
+ if (!configPath) {
170
+ return null;
171
+ }
172
+ if (!handlerCache.has(configPath)) {
173
+ handlerCache.set(
174
+ configPath,
175
+ createHandler({
176
+ log: () => {
177
+ },
178
+ tsConfigPath: configPath,
179
+ respectCoreModule,
180
+ falllback: (moduleName) => fs.existsSync(moduleName)
181
+ })
182
+ );
183
+ }
184
+ return handlerCache.get(configPath);
185
+ }
186
+ function resolveAlias(request, importer) {
187
+ const dynamicHandler = getHandlerForFile(importer);
188
+ if (!dynamicHandler) {
189
+ return null;
190
+ }
191
+ const resolved = dynamicHandler(request, normalize(importer));
192
+ return resolved;
193
+ }
232
194
  return {
233
195
  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
196
  async resolveId(request, importer, options) {
245
- if (!importer || request.startsWith("\0")) {
197
+ if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) {
246
198
  return null;
247
199
  }
248
- const moduleName = handler?.(request, normalize(importer));
200
+ const moduleName = resolveAlias(request, importer);
249
201
  if (!moduleName) {
250
202
  let importerMeta = {};
251
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
252
- if (!resolved) {
203
+ const resolved2 = await this.resolve(request, importer, { skipSelf: true, ...options });
204
+ if (!resolved2) {
253
205
  return null;
254
206
  }
255
207
  if (localResolve) {
@@ -257,37 +209,42 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
257
209
  importerMeta = importerInfo?.meta || {};
258
210
  if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
259
211
  return {
260
- ...resolved,
212
+ ...resolved2,
261
213
  external: !request.startsWith("hono/") && request !== "hono"
262
214
  };
263
215
  }
264
216
  }
265
217
  return {
266
- ...resolved,
218
+ ...resolved2,
267
219
  meta: {
268
- ...resolved.meta || {},
220
+ ...resolved2.meta || {},
269
221
  ...importerMeta
270
222
  }
271
223
  };
272
224
  }
273
225
  if (!path2__default.extname(moduleName)) {
274
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
275
- if (!resolved) {
226
+ const resolved2 = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
227
+ if (!resolved2) {
276
228
  return null;
277
229
  }
278
230
  return {
279
- ...resolved,
231
+ ...resolved2,
280
232
  meta: {
281
- ...resolved.meta,
233
+ ...resolved2.meta,
282
234
  [PLUGIN_NAME]: {
283
235
  resolved: true
284
236
  }
285
237
  }
286
238
  };
287
239
  }
240
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
241
+ if (!resolved) {
242
+ return null;
243
+ }
288
244
  return {
289
- id: moduleName,
245
+ ...resolved,
290
246
  meta: {
247
+ ...resolved.meta,
291
248
  [PLUGIN_NAME]: {
292
249
  resolved: true
293
250
  }
@@ -369,7 +326,117 @@ function recursiveRemoveNonReferencedNodes(code) {
369
326
  );
370
327
  });
371
328
  }
372
- function extractMastraOptionBundler(name, entryFile, transformer, result, logger) {
329
+ function removeAllOptionsFromMastraExcept(result, option, logger) {
330
+ const t = babel__default.types;
331
+ return {
332
+ name: "remove-all-except-" + option + "-config",
333
+ visitor: {
334
+ ExportNamedDeclaration: {
335
+ // remove all exports
336
+ exit(path3) {
337
+ path3.remove();
338
+ }
339
+ },
340
+ NewExpression(path3, state) {
341
+ const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
342
+ if (!varDeclaratorPath) {
343
+ return;
344
+ }
345
+ const parentNode = path3.parentPath.node;
346
+ if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
347
+ return;
348
+ }
349
+ let mastraArgs = t.objectExpression([]);
350
+ if (t.isObjectExpression(path3.node.arguments[0])) {
351
+ mastraArgs = path3.node.arguments[0];
352
+ }
353
+ let configProperty = mastraArgs.properties.find(
354
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === option
355
+ );
356
+ let configValue = t.objectExpression([]);
357
+ const programPath = path3.scope.getProgramParent().path;
358
+ if (!programPath) {
359
+ return;
360
+ }
361
+ if (configProperty && t.isObjectProperty(configProperty) && t.isExpression(configProperty.value)) {
362
+ result.hasCustomConfig = true;
363
+ configValue = configProperty.value;
364
+ if (t.isIdentifier(configProperty.value) && configProperty.value.name === option) {
365
+ const configBinding = state.file.scope.getBinding(option);
366
+ if (configBinding && t.isVariableDeclarator(configBinding.path.node)) {
367
+ const id = path3.scope.generateUidIdentifier(option);
368
+ configBinding.path.replaceWith(t.variableDeclarator(id, configBinding.path.node.init));
369
+ configValue = id;
370
+ }
371
+ }
372
+ }
373
+ const exportDeclaration = t.exportNamedDeclaration(
374
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), configValue)]),
375
+ []
376
+ );
377
+ programPath.node.body.push(exportDeclaration);
378
+ },
379
+ Program: {
380
+ exit(path3) {
381
+ const hasExport = path3.node.body.some(
382
+ (node) => node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration"
383
+ );
384
+ if (!hasExport) {
385
+ if (logger) {
386
+ logger.warn(`Mastra ${option} config could not be extracted. Please make sure your entry file looks like this:
387
+ export const mastra = new Mastra({
388
+ ${option}: <value>
389
+ })
390
+
391
+ `);
392
+ }
393
+ const fallbackExportDeclaration = t.exportNamedDeclaration(
394
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), t.objectExpression([]))]),
395
+ []
396
+ );
397
+ path3.node.body.push(fallbackExportDeclaration);
398
+ }
399
+ }
400
+ }
401
+ }
402
+ };
403
+ }
404
+
405
+ // src/build/plugins/remove-all-except.ts
406
+ function removeAllOptionsFromMastraExceptPlugin(mastraEntry, name, result, options) {
407
+ return {
408
+ name: `remove-${name}`,
409
+ transform(code, id) {
410
+ if (id !== mastraEntry) {
411
+ return;
412
+ }
413
+ return new Promise((resolve2, reject) => {
414
+ babel.transform(
415
+ code,
416
+ {
417
+ babelrc: false,
418
+ configFile: false,
419
+ filename: id,
420
+ plugins: [removeAllOptionsFromMastraExcept(result, name, options?.logger)],
421
+ sourceMaps: options?.sourcemap
422
+ },
423
+ (err, result2) => {
424
+ if (err) {
425
+ return reject(err);
426
+ }
427
+ resolve2({
428
+ code: result2.code,
429
+ map: result2.map
430
+ });
431
+ }
432
+ );
433
+ });
434
+ }
435
+ };
436
+ }
437
+
438
+ // src/build/shared/extract-mastra-option.ts
439
+ function extractMastraOptionBundler(name, entryFile, result, logger) {
373
440
  return rollup({
374
441
  logLevel: "silent",
375
442
  input: {
@@ -390,34 +457,7 @@ function extractMastraOptionBundler(name, entryFile, transformer, result, logger
390
457
  ignoreTryCatch: false
391
458
  }),
392
459
  json(),
393
- {
394
- name: `extract-${name}-config`,
395
- transform(code, id) {
396
- if (id !== entryFile) {
397
- return;
398
- }
399
- return new Promise((resolve2, reject) => {
400
- babel.transform(
401
- code,
402
- {
403
- babelrc: false,
404
- configFile: false,
405
- filename: id,
406
- plugins: [transformer(result, logger)]
407
- },
408
- (err, result2) => {
409
- if (err) {
410
- return reject(err);
411
- }
412
- resolve2({
413
- code: result2.code,
414
- map: result2.map
415
- });
416
- }
417
- );
418
- });
419
- }
420
- },
460
+ removeAllOptionsFromMastraExceptPlugin(entryFile, name, result, { logger }),
421
461
  // let esbuild remove all unused imports
422
462
  esbuild(),
423
463
  {
@@ -434,11 +474,11 @@ function extractMastraOptionBundler(name, entryFile, transformer, result, logger
434
474
  ]
435
475
  });
436
476
  }
437
- async function extractMastraOption(name, entryFile, transformer, outputDir, logger) {
477
+ async function extractMastraOption(name, entryFile, outputDir, logger) {
438
478
  const result = {
439
479
  hasCustomConfig: false
440
480
  };
441
- const bundler = await extractMastraOptionBundler(name, entryFile, transformer, result, logger);
481
+ const bundler = await extractMastraOptionBundler(name, entryFile, result, logger);
442
482
  const output = await bundler.write({
443
483
  dir: outputDir,
444
484
  format: "es",
@@ -448,7 +488,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
448
488
  const configPath = `${outputDir}/${name}-config.mjs`;
449
489
  return {
450
490
  bundleOutput: output,
451
- getConfig: () => import(`file:${configPath}`).then((m) => m[name])
491
+ getConfig: () => import(pathToFileURL(configPath).href).then((m) => m[name])
452
492
  };
453
493
  }
454
494
  return null;
@@ -456,13 +496,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
456
496
 
457
497
  // src/build/bundlerOptions.ts
458
498
  async function getBundlerOptions(entryFile, outputDir, logger) {
459
- const result = await extractMastraOption(
460
- "bundler",
461
- entryFile,
462
- removeAllOptionsExceptBundler,
463
- outputDir,
464
- logger
465
- );
499
+ const result = await extractMastraOption("bundler", entryFile, outputDir, logger);
466
500
  if (!result) {
467
501
  return null;
468
502
  }
@@ -531,8 +565,57 @@ function isNodeBuiltin(dep) {
531
565
  const [pkg2] = dep.split("/");
532
566
  return dep.startsWith("node:") || builtinModules.includes(dep) || builtinModules.includes(pkg2);
533
567
  }
568
+ async function getPackageRootPath(packageName, parentPath) {
569
+ let rootPath;
570
+ try {
571
+ let options = void 0;
572
+ if (parentPath) {
573
+ if (!parentPath.startsWith("file://")) {
574
+ parentPath = pathToFileURL(parentPath).href;
575
+ }
576
+ options = {
577
+ paths: [parentPath]
578
+ };
579
+ }
580
+ const pkg2 = await getPackageInfo(packageName, options);
581
+ rootPath = pkg2?.rootPath ?? null;
582
+ } catch (e) {
583
+ rootPath = null;
584
+ }
585
+ return rootPath;
586
+ }
587
+
588
+ // src/build/analyze/constants.ts
589
+ var DEPS_TO_IGNORE = ["#tools"];
590
+ var GLOBAL_EXTERNALS = [
591
+ "pino",
592
+ "pino-pretty",
593
+ "@libsql/client",
594
+ "pg",
595
+ "libsql",
596
+ "#tools",
597
+ "typescript",
598
+ "undici",
599
+ "readable-stream"
600
+ ];
601
+ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
534
602
  function removeDeployer() {
535
603
  const t = babel__default.types;
604
+ function removeDeployerFromObject(objectExpr, scope) {
605
+ const deployerProp = objectExpr.properties.find(
606
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
607
+ );
608
+ if (deployerProp) {
609
+ objectExpr.properties = objectExpr.properties.filter((prop) => prop !== deployerProp);
610
+ if (t.isIdentifier(deployerProp.value)) {
611
+ const deployerBinding = scope.getBinding(deployerProp.value.name);
612
+ if (deployerBinding) {
613
+ deployerBinding.path?.parentPath?.remove();
614
+ }
615
+ }
616
+ }
617
+ return deployerProp;
618
+ }
536
619
  return {
537
620
  name: "remove-deployer",
538
621
  visitor: {
@@ -548,23 +631,30 @@ function removeDeployer() {
548
631
  if (!state.hasReplaced) {
549
632
  state.hasReplaced = true;
550
633
  const newMastraObj = t.cloneNode(path3.node);
551
- if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
552
- const deployer = newMastraObj.arguments[0].properties.find(
553
- (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
554
- );
555
- if (!deployer) {
556
- return;
634
+ if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.length) {
635
+ const objectArg = newMastraObj.arguments[0];
636
+ let foundDeployer = false;
637
+ const directDeployer = removeDeployerFromObject(objectArg, state.file.scope);
638
+ if (directDeployer) {
639
+ foundDeployer = true;
557
640
  }
558
- newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
559
- (prop) => prop !== deployer
560
- );
561
- if (t.isObjectProperty(deployer) && t.isIdentifier(deployer.value)) {
562
- const deployerBinding = state.file.scope.getBinding(deployer.value.name);
563
- if (deployerBinding) {
564
- deployerBinding?.path?.parentPath?.remove();
641
+ for (const prop of objectArg.properties) {
642
+ if (t.isSpreadElement(prop) && t.isIdentifier(prop.argument)) {
643
+ const spreadBinding = state.file.scope.getBinding(prop.argument.name);
644
+ if (spreadBinding?.path && t.isVariableDeclarator(spreadBinding.path.node)) {
645
+ const init = spreadBinding.path.node.init;
646
+ if (t.isObjectExpression(init)) {
647
+ const spreadDeployer = removeDeployerFromObject(init, state.file.scope);
648
+ if (spreadDeployer) {
649
+ foundDeployer = true;
650
+ }
651
+ }
652
+ }
565
653
  }
566
654
  }
567
- path3.replaceWith(newMastraObj);
655
+ if (foundDeployer) {
656
+ path3.replaceWith(newMastraObj);
657
+ }
568
658
  }
569
659
  }
570
660
  }
@@ -605,21 +695,6 @@ function removeDeployer2(mastraEntry, options) {
605
695
  };
606
696
  }
607
697
 
608
- // src/build/analyze/constants.ts
609
- var DEPS_TO_IGNORE = ["#tools"];
610
- var GLOBAL_EXTERNALS = [
611
- "pino",
612
- "pino-pretty",
613
- "@libsql/client",
614
- "pg",
615
- "libsql",
616
- "#tools",
617
- "typescript",
618
- "undici",
619
- "readable-stream"
620
- ];
621
- var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
622
-
623
698
  // src/build/analyze/analyzeEntry.ts
624
699
  function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
625
700
  const normalizedMastraEntry = slash(mastraEntry);
@@ -659,14 +734,17 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
659
734
  transformMixedEsModules: true,
660
735
  extensions: [".js", ".ts"]
661
736
  }),
662
- removeDeployer2(mastraEntry, { sourcemap: sourcemapEnabled }),
737
+ removeDeployer2(mastraEntry, {
738
+ sourcemap: sourcemapEnabled
739
+ }),
663
740
  esbuild()
664
741
  ]
665
742
  );
666
743
  return plugins;
667
744
  }
668
745
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
669
- logger
746
+ logger,
747
+ shouldCheckTransitiveDependencies
670
748
  }) {
671
749
  const depsToOptimize = /* @__PURE__ */ new Map();
672
750
  if (!output.facadeModuleId) {
@@ -679,7 +757,7 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
679
757
  entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
680
758
  }
681
759
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
682
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
760
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
683
761
  continue;
684
762
  }
685
763
  const pkgName = getPackageName(dependency);
@@ -690,7 +768,11 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
690
768
  isWorkspace = workspaceMap.has(pkgName);
691
769
  }
692
770
  const normalizedRootPath = rootPath ? slash(rootPath) : null;
693
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
771
+ depsToOptimize.set(dependency, {
772
+ exports: bindings,
773
+ rootPath: normalizedRootPath,
774
+ isWorkspace
775
+ });
694
776
  }
695
777
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
696
778
  if (currentDepth >= maxDepth) {
@@ -734,12 +816,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
734
816
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
735
817
  }
736
818
  }
737
- await checkTransitiveDependencies(initialDepsToOptimize);
819
+ if (shouldCheckTransitiveDependencies) {
820
+ await checkTransitiveDependencies(initialDepsToOptimize);
821
+ }
738
822
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
739
823
  if (dynamicImports.length) {
740
824
  for (const dynamicImport of dynamicImports) {
741
825
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
742
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
826
+ depsToOptimize.set(dynamicImport, {
827
+ exports: ["*"],
828
+ rootPath: null,
829
+ isWorkspace: false
830
+ });
743
831
  }
744
832
  }
745
833
  }
@@ -753,13 +841,14 @@ async function analyzeEntry({
753
841
  sourcemapEnabled,
754
842
  workspaceMap,
755
843
  projectRoot,
756
- initialDepsToOptimize = /* @__PURE__ */ new Map()
844
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
757
845
  // used to avoid infinite recursion
846
+ shouldCheckTransitiveDependencies = false
758
847
  }) {
759
848
  const optimizerBundler = await rollup({
760
849
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
761
850
  input: isVirtualFile ? "#entry" : entry,
762
- treeshake: "smallest",
851
+ treeshake: false,
763
852
  preserveSymlinks: true,
764
853
  plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
765
854
  external: DEPS_TO_IGNORE
@@ -775,7 +864,8 @@ async function analyzeEntry({
775
864
  projectRoot,
776
865
  initialDepsToOptimize,
777
866
  {
778
- logger
867
+ logger,
868
+ shouldCheckTransitiveDependencies
779
869
  }
780
870
  );
781
871
  return {
@@ -786,6 +876,27 @@ async function analyzeEntry({
786
876
  }
787
877
  };
788
878
  }
879
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
880
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
881
+ function esmShim() {
882
+ const original = originalEsmShim();
883
+ return {
884
+ name: "esm-shim",
885
+ renderChunk(code, chunk, opts, meta) {
886
+ const hasFilename = code.includes("__filename");
887
+ const hasDirname = code.includes("__dirname");
888
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
889
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
890
+ if (userDeclaredFilename || userDeclaredDirname) {
891
+ return null;
892
+ }
893
+ if (typeof original.renderChunk === "function") {
894
+ return original.renderChunk.call(this, code, chunk, opts, meta);
895
+ }
896
+ return null;
897
+ }
898
+ };
899
+ }
789
900
  function aliasHono() {
790
901
  return {
791
902
  name: "hono-alias",
@@ -798,6 +909,114 @@ function aliasHono() {
798
909
  }
799
910
  };
800
911
  }
912
+ function nodeGypDetector() {
913
+ const modulesToTrack = /* @__PURE__ */ new Set();
914
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
915
+ return {
916
+ name: "node-gyp-build-detector",
917
+ moduleParsed(info) {
918
+ if (!info.meta?.commonjs?.requires?.length) {
919
+ return;
920
+ }
921
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
922
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
923
+ );
924
+ if (!hasNodeGypBuild) {
925
+ return;
926
+ }
927
+ modulesToTrack.add(info.id);
928
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
929
+ },
930
+ async generateBundle(options, bundle) {
931
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
932
+ for (const [fileName, chunk] of Object.entries(bundle)) {
933
+ if (chunk.type === "chunk") {
934
+ for (const moduleId of chunk.moduleIds) {
935
+ if (modulesToTrackPackageInfo.has(moduleId)) {
936
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
937
+ if (!binaryMapByChunk.has(fileName)) {
938
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
939
+ }
940
+ if (pkgInfo?.packageJson?.name) {
941
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
942
+ }
943
+ }
944
+ }
945
+ }
946
+ }
947
+ const binaryMapJson = Object.fromEntries(
948
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
949
+ );
950
+ this.emitFile({
951
+ type: "asset",
952
+ name: "binary-map.json",
953
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
954
+ });
955
+ }
956
+ };
957
+ }
958
+
959
+ // src/build/plugins/subpath-externals-resolver.ts
960
+ function subpathExternalsResolver(externals) {
961
+ return {
962
+ name: "subpath-externals-resolver",
963
+ resolveId(id) {
964
+ if (id.startsWith(".") || id.startsWith("/")) {
965
+ return null;
966
+ }
967
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
968
+ if (isPartOfExternals) {
969
+ return {
970
+ id,
971
+ external: true
972
+ };
973
+ }
974
+ }
975
+ };
976
+ }
977
+ function moduleResolveMap(externals, projectRoot) {
978
+ const importMap = /* @__PURE__ */ new Map();
979
+ return {
980
+ name: "module-resolve-map",
981
+ moduleParsed(info) {
982
+ if (info.importedIds.length === 0 || !info.id) {
983
+ return;
984
+ }
985
+ for (const importedId of info.importedIds) {
986
+ for (const external of externals) {
987
+ if (isDependencyPartOfPackage(importedId, external)) {
988
+ importMap.set(external, info.id);
989
+ }
990
+ }
991
+ }
992
+ },
993
+ async generateBundle(options, bundle) {
994
+ const resolveMap = /* @__PURE__ */ new Map();
995
+ for (const [fileName, chunk] of Object.entries(bundle)) {
996
+ if (chunk.type === "chunk") {
997
+ for (const [external, resolvedFrom] of importMap) {
998
+ if (chunk.moduleIds.includes(resolvedFrom)) {
999
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
1000
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
1001
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
1002
+ resolveMap.set(fullPath, innerMap);
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ const resolveMapJson = Object.fromEntries(
1008
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
1009
+ );
1010
+ this.emitFile({
1011
+ type: "asset",
1012
+ name: "module-resolve-map.json",
1013
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
1014
+ });
1015
+ }
1016
+ };
1017
+ }
1018
+
1019
+ // src/build/analyze/bundleExternals.ts
801
1020
  function prepareEntryFileName(name, rootDir) {
802
1021
  return rollupSafeName(name, rootDir);
803
1022
  }
@@ -807,7 +1026,7 @@ function createVirtualDependencies(depsToOptimize, {
807
1026
  outputDir,
808
1027
  bundlerOptions
809
1028
  }) {
810
- const { isDev = false } = bundlerOptions || {};
1029
+ const { isDev = false, externalsPreset = false } = bundlerOptions || {};
811
1030
  const fileNameToDependencyMap = /* @__PURE__ */ new Map();
812
1031
  const optimizedDependencyEntries = /* @__PURE__ */ new Map();
813
1032
  const rootDir = workspaceRoot || projectRoot;
@@ -839,7 +1058,7 @@ function createVirtualDependencies(depsToOptimize, {
839
1058
  virtual: virtualFile.join("\n")
840
1059
  });
841
1060
  }
842
- if (isDev) {
1061
+ if (isDev || externalsPreset) {
843
1062
  for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
844
1063
  if (!isWorkspace || !rootPath || !workspaceRoot) {
845
1064
  continue;
@@ -863,7 +1082,8 @@ async function getInputPlugins2(virtualDependencies, {
863
1082
  transpilePackages,
864
1083
  workspaceMap,
865
1084
  bundlerOptions,
866
- rootDir
1085
+ rootDir,
1086
+ externals
867
1087
  }) {
868
1088
  const transpilePackagesMap = /* @__PURE__ */ new Map();
869
1089
  for (const pkg2 of transpilePackages) {
@@ -884,6 +1104,7 @@ async function getInputPlugins2(virtualDependencies, {
884
1104
  {}
885
1105
  )
886
1106
  ),
1107
+ subpathExternalsResolver(externals),
887
1108
  transpilePackagesMap.size ? esbuild({
888
1109
  format: "esm",
889
1110
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -894,7 +1115,7 @@ async function getInputPlugins2(virtualDependencies, {
894
1115
  }
895
1116
  })
896
1117
  }) : null,
897
- bundlerOptions.isDev ? {
1118
+ bundlerOptions.noBundling ? {
898
1119
  name: "alias-optimized-deps",
899
1120
  async resolveId(id, importer, options) {
900
1121
  if (!virtualDependencies.has(id)) {
@@ -912,7 +1133,8 @@ async function getInputPlugins2(virtualDependencies, {
912
1133
  if (!resolvedPath) {
913
1134
  resolvedPath = pkgJson.main ?? "index.js";
914
1135
  }
915
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1136
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1137
+ return resolved;
916
1138
  }
917
1139
  } : null,
918
1140
  optimizeLodashImports({
@@ -923,14 +1145,16 @@ async function getInputPlugins2(virtualDependencies, {
923
1145
  transformMixedEsModules: true,
924
1146
  ignoreTryCatch: false
925
1147
  }),
926
- bundlerOptions.isDev ? null : nodeResolve({
1148
+ bundlerOptions.noBundling ? null : nodeResolve({
927
1149
  preferBuiltins: true,
928
1150
  exportConditions: ["node"]
929
1151
  }),
930
- bundlerOptions.isDev ? esmShim() : null,
1152
+ bundlerOptions.noBundling ? esmShim() : null,
931
1153
  // hono is imported from deployer, so we need to resolve from here instead of the project root
932
1154
  aliasHono(),
933
1155
  json(),
1156
+ nodeGypDetector(),
1157
+ moduleResolveMap(externals, rootDir),
934
1158
  {
935
1159
  name: "not-found-resolver",
936
1160
  resolveId: {
@@ -978,6 +1202,16 @@ async function buildExternalDependencies(virtualDependencies, {
978
1202
  if (virtualDependencies.size === 0) {
979
1203
  return [];
980
1204
  }
1205
+ const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
1206
+ const plugins = await getInputPlugins2(virtualDependencies, {
1207
+ transpilePackages: packagesToTranspile,
1208
+ workspaceMap,
1209
+ bundlerOptions: {
1210
+ noBundling
1211
+ },
1212
+ rootDir,
1213
+ externals
1214
+ });
981
1215
  const bundler = await rollup({
982
1216
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
983
1217
  input: Array.from(virtualDependencies.entries()).reduce(
@@ -988,25 +1222,22 @@ async function buildExternalDependencies(virtualDependencies, {
988
1222
  {}
989
1223
  ),
990
1224
  external: externals,
991
- treeshake: "safest",
992
- plugins: getInputPlugins2(virtualDependencies, {
993
- transpilePackages: packagesToTranspile,
994
- workspaceMap,
995
- bundlerOptions,
996
- rootDir
997
- })
1225
+ treeshake: noBundling ? false : "safest",
1226
+ plugins
998
1227
  });
999
1228
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
1000
1229
  const { output } = await bundler.write({
1001
1230
  format: "esm",
1002
1231
  dir: rootDir,
1003
1232
  entryFileNames: "[name].mjs",
1233
+ // used to get the filename of the actual error
1234
+ sourcemap: true,
1004
1235
  /**
1005
1236
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1006
1237
  * So we want to write them to the `.mastra/output` folder as well.
1007
1238
  */
1008
1239
  chunkFileNames: (chunkInfo) => {
1009
- if (bundlerOptions.isDev) {
1240
+ if (noBundling) {
1010
1241
  const importedFromPackages = /* @__PURE__ */ new Set();
1011
1242
  for (const moduleId of chunkInfo.moduleIds) {
1012
1243
  const normalized = slash(moduleId);
@@ -1038,6 +1269,7 @@ async function buildExternalDependencies(virtualDependencies, {
1038
1269
  }
1039
1270
  return `${outputDirRelative}/[name].mjs`;
1040
1271
  },
1272
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1041
1273
  hoistTransitiveImports: false
1042
1274
  });
1043
1275
  await bundler.close();
@@ -1046,7 +1278,7 @@ async function buildExternalDependencies(virtualDependencies, {
1046
1278
  function findExternalImporter(module, external, allOutputs) {
1047
1279
  const capturedFiles = /* @__PURE__ */ new Set();
1048
1280
  for (const id of module.imports) {
1049
- if (id === external) {
1281
+ if (isDependencyPartOfPackage(id, external)) {
1050
1282
  return module;
1051
1283
  } else {
1052
1284
  if (id.endsWith(".mjs")) {
@@ -1067,19 +1299,31 @@ function findExternalImporter(module, external, allOutputs) {
1067
1299
  }
1068
1300
  async function bundleExternals(depsToOptimize, outputDir, options) {
1069
1301
  const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {} } = options;
1070
- const {
1071
- externals: customExternals = [],
1072
- transpilePackages = [],
1073
- isDev = false} = bundlerOptions || {};
1074
- const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...customExternals];
1302
+ const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
1303
+ let externalsPreset = false;
1304
+ if (customExternals === true) {
1305
+ externalsPreset = true;
1306
+ }
1307
+ const externalsList = Array.isArray(customExternals) ? customExternals : [];
1308
+ const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...externalsList];
1075
1309
  const workspacePackagesNames = Array.from(workspaceMap.keys());
1076
1310
  const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
1311
+ const extractedExternals = /* @__PURE__ */ new Map();
1312
+ if (externalsPreset) {
1313
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1314
+ if (!metadata.isWorkspace) {
1315
+ extractedExternals.set(dep, metadata.rootPath ?? dep);
1316
+ depsToOptimize.delete(dep);
1317
+ }
1318
+ }
1319
+ }
1077
1320
  const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
1078
1321
  workspaceRoot,
1079
1322
  outputDir,
1080
1323
  projectRoot,
1081
1324
  bundlerOptions: {
1082
- isDev
1325
+ isDev,
1326
+ externalsPreset
1083
1327
  }
1084
1328
  });
1085
1329
  const output = await buildExternalDependencies(optimizedDependencyEntries, {
@@ -1089,10 +1333,11 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1089
1333
  rootDir: workspaceRoot || projectRoot,
1090
1334
  outputDir,
1091
1335
  bundlerOptions: {
1092
- isDev
1336
+ isDev,
1337
+ externalsPreset
1093
1338
  }
1094
1339
  });
1095
- const moduleResolveMap = /* @__PURE__ */ new Map();
1340
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1096
1341
  const filteredChunks = output.filter((o) => o.type === "chunk");
1097
1342
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1098
1343
  for (const external of allExternals) {
@@ -1102,10 +1347,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1102
1347
  const importer = findExternalImporter(o, external, filteredChunks);
1103
1348
  if (importer) {
1104
1349
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1105
- let innerMap = moduleResolveMap.get(fullPath);
1350
+ let innerMap = moduleResolveMap2.get(fullPath);
1106
1351
  if (!innerMap) {
1107
1352
  innerMap = /* @__PURE__ */ new Map();
1108
- moduleResolveMap.set(fullPath, innerMap);
1353
+ moduleResolveMap2.set(fullPath, innerMap);
1109
1354
  }
1110
1355
  if (importer.moduleIds.length) {
1111
1356
  innerMap.set(
@@ -1117,15 +1362,125 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1117
1362
  }
1118
1363
  }
1119
1364
  const usedExternals = /* @__PURE__ */ Object.create(null);
1120
- for (const [fullPath, innerMap] of moduleResolveMap) {
1365
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1121
1366
  const innerObj = /* @__PURE__ */ Object.create(null);
1122
1367
  for (const [external, value] of innerMap) {
1123
1368
  innerObj[external] = value;
1124
1369
  }
1125
1370
  usedExternals[fullPath] = innerObj;
1126
1371
  }
1372
+ if (extractedExternals.size > 0) {
1373
+ const syntheticPath = path2.join(workspaceRoot || projectRoot, "__externals__");
1374
+ const externalsObj = /* @__PURE__ */ Object.create(null);
1375
+ for (const [dep, rootPath] of extractedExternals) {
1376
+ externalsObj[dep] = rootPath;
1377
+ }
1378
+ usedExternals[syntheticPath] = externalsObj;
1379
+ }
1127
1380
  return { output, fileNameToDependencyMap, usedExternals };
1128
1381
  }
1382
+
1383
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1384
+ var UNKNOWN_FUNCTION = "<unknown>";
1385
+ function parse(stackString) {
1386
+ var lines = stackString.split("\n");
1387
+ return lines.reduce(function(stack, line) {
1388
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1389
+ if (parseResult) {
1390
+ stack.push(parseResult);
1391
+ }
1392
+ return stack;
1393
+ }, []);
1394
+ }
1395
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1396
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1397
+ function parseChrome(line) {
1398
+ var parts = chromeRe.exec(line);
1399
+ if (!parts) {
1400
+ return null;
1401
+ }
1402
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1403
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1404
+ var submatch = chromeEvalRe.exec(parts[2]);
1405
+ if (isEval && submatch != null) {
1406
+ parts[2] = submatch[1];
1407
+ parts[3] = submatch[2];
1408
+ parts[4] = submatch[3];
1409
+ }
1410
+ return {
1411
+ file: !isNative ? parts[2] : null,
1412
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1413
+ arguments: isNative ? [parts[2]] : [],
1414
+ lineNumber: parts[3] ? +parts[3] : null,
1415
+ column: parts[4] ? +parts[4] : null
1416
+ };
1417
+ }
1418
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1419
+ function parseWinjs(line) {
1420
+ var parts = winjsRe.exec(line);
1421
+ if (!parts) {
1422
+ return null;
1423
+ }
1424
+ return {
1425
+ file: parts[2],
1426
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1427
+ arguments: [],
1428
+ lineNumber: +parts[3],
1429
+ column: parts[4] ? +parts[4] : null
1430
+ };
1431
+ }
1432
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1433
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1434
+ function parseGecko(line) {
1435
+ var parts = geckoRe.exec(line);
1436
+ if (!parts) {
1437
+ return null;
1438
+ }
1439
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1440
+ var submatch = geckoEvalRe.exec(parts[3]);
1441
+ if (isEval && submatch != null) {
1442
+ parts[3] = submatch[1];
1443
+ parts[4] = submatch[2];
1444
+ parts[5] = null;
1445
+ }
1446
+ return {
1447
+ file: parts[3],
1448
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1449
+ arguments: parts[2] ? parts[2].split(",") : [],
1450
+ lineNumber: parts[4] ? +parts[4] : null,
1451
+ column: parts[5] ? +parts[5] : null
1452
+ };
1453
+ }
1454
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1455
+ function parseJSC(line) {
1456
+ var parts = javaScriptCoreRe.exec(line);
1457
+ if (!parts) {
1458
+ return null;
1459
+ }
1460
+ return {
1461
+ file: parts[3],
1462
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1463
+ arguments: [],
1464
+ lineNumber: +parts[4],
1465
+ column: parts[5] ? +parts[5] : null
1466
+ };
1467
+ }
1468
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1469
+ function parseNode(line) {
1470
+ var parts = nodeRe.exec(line);
1471
+ if (!parts) {
1472
+ return null;
1473
+ }
1474
+ return {
1475
+ file: parts[2],
1476
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1477
+ arguments: [],
1478
+ lineNumber: +parts[3],
1479
+ column: parts[4] ? +parts[4] : null
1480
+ };
1481
+ }
1482
+
1483
+ // src/build/analyze.ts
1129
1484
  function throwExternalDependencyError({
1130
1485
  errorId,
1131
1486
  moduleName,
@@ -1149,6 +1504,110 @@ export const mastra = new Mastra({
1149
1504
  })`
1150
1505
  });
1151
1506
  }
1507
+ function getPackageNameFromBundledModuleName(moduleName) {
1508
+ const chunks = moduleName.split("-");
1509
+ if (!chunks.length) {
1510
+ return moduleName;
1511
+ }
1512
+ if (chunks[0]?.startsWith("@")) {
1513
+ return chunks.slice(0, 2).join("/");
1514
+ }
1515
+ return chunks[0];
1516
+ }
1517
+ function validateError(err, file, {
1518
+ binaryMapData,
1519
+ workspaceMap
1520
+ }) {
1521
+ let moduleName = null;
1522
+ let errorConfig = null;
1523
+ if (err instanceof ValidationError) {
1524
+ const parsedStack = parse(err.stack);
1525
+ if (err.type === "TypeError") {
1526
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1527
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1528
+ if (stacktraceFrame) {
1529
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1530
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1531
+ } else {
1532
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1533
+ }
1534
+ errorConfig = {
1535
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1536
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1537
+ };
1538
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1539
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1540
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1541
+ errorConfig = {
1542
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1543
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1544
+ };
1545
+ if (moduleName === parentModuleName) {
1546
+ return;
1547
+ }
1548
+ }
1549
+ }
1550
+ if (err.message.includes("No native build was found")) {
1551
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1552
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1553
+ errorConfig = {
1554
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1555
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1556
+ };
1557
+ }
1558
+ if (moduleName && workspaceMap.has(moduleName)) {
1559
+ throw new MastraError({
1560
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1561
+ domain: ErrorDomain.DEPLOYER,
1562
+ category: ErrorCategory.USER,
1563
+ details: {
1564
+ // importFile: moduleName,
1565
+ packageName: moduleName
1566
+ },
1567
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1568
+ Error: ${err.stack}`
1569
+ });
1570
+ }
1571
+ if (errorConfig && moduleName) {
1572
+ throwExternalDependencyError({
1573
+ errorId: errorConfig.id,
1574
+ moduleName,
1575
+ packageName: moduleName,
1576
+ messagePrefix: errorConfig.messagePrefix
1577
+ });
1578
+ }
1579
+ }
1580
+ async function validateFile(root, file, {
1581
+ binaryMapData,
1582
+ moduleResolveMapLocation,
1583
+ logger,
1584
+ workspaceMap
1585
+ }) {
1586
+ try {
1587
+ if (!file.isDynamicEntry && file.isEntry) {
1588
+ await validate(join(root, file.fileName), {
1589
+ moduleResolveMapLocation,
1590
+ injectESMShim: false
1591
+ });
1592
+ }
1593
+ } catch (err) {
1594
+ let errorToHandle = err;
1595
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1596
+ try {
1597
+ await validate(join(root, file.fileName), {
1598
+ moduleResolveMapLocation,
1599
+ injectESMShim: true
1600
+ });
1601
+ errorToHandle = null;
1602
+ } catch (err2) {
1603
+ errorToHandle = err2;
1604
+ }
1605
+ }
1606
+ if (errorToHandle instanceof Error) {
1607
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1608
+ }
1609
+ }
1610
+ }
1152
1611
  async function validateOutput({
1153
1612
  output,
1154
1613
  reverseVirtualReferenceMap,
@@ -1162,60 +1621,30 @@ async function validateOutput({
1162
1621
  externalDependencies: /* @__PURE__ */ new Set(),
1163
1622
  workspaceMap
1164
1623
  };
1165
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1166
1624
  for (const deps of Object.values(usedExternals)) {
1167
1625
  for (const dep of Object.keys(deps)) {
1168
1626
  result.externalDependencies.add(dep);
1169
1627
  }
1170
1628
  }
1629
+ let binaryMapData = {};
1630
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1631
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1632
+ binaryMapData = JSON.parse(binaryMap);
1633
+ }
1171
1634
  for (const file of output) {
1172
1635
  if (file.type === "asset") {
1173
1636
  continue;
1174
1637
  }
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
- }
1638
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1639
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1640
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1218
1641
  }
1642
+ await validateFile(projectRoot, file, {
1643
+ binaryMapData,
1644
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1645
+ logger,
1646
+ workspaceMap
1647
+ });
1219
1648
  }
1220
1649
  return result;
1221
1650
  }
@@ -1223,7 +1652,7 @@ async function analyzeBundle(entries, mastraEntry, {
1223
1652
  outputDir,
1224
1653
  projectRoot,
1225
1654
  isDev = false,
1226
- bundlerOptions: _bundlerOptions
1655
+ bundlerOptions
1227
1656
  }, logger) {
1228
1657
  const mastraConfig = await readFile(mastraEntry, "utf-8");
1229
1658
  const mastraConfigResult = {
@@ -1242,22 +1671,33 @@ export const mastra = new Mastra({
1242
1671
 
1243
1672
  If you think your configuration is valid, please open an issue.`);
1244
1673
  }
1245
- const { enableEsmShim = true } = _bundlerOptions || {};
1246
- const bundlerOptions = await getBundlerOptions(mastraEntry, outputDir);
1247
1674
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1675
+ let externalsPreset = false;
1676
+ const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1677
+ if (bundlerOptions?.externals === true) {
1678
+ externalsPreset = true;
1679
+ }
1248
1680
  let index = 0;
1249
1681
  const depsToOptimize = /* @__PURE__ */ new Map();
1682
+ const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1250
1683
  logger.info("Analyzing dependencies...");
1684
+ const allUsedExternals = /* @__PURE__ */ new Set();
1251
1685
  for (const entry of entries) {
1252
1686
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1253
1687
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1254
1688
  logger,
1255
- sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1689
+ sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1256
1690
  workspaceMap,
1257
- projectRoot
1691
+ projectRoot,
1692
+ shouldCheckTransitiveDependencies: isDev || externalsPreset
1258
1693
  });
1259
1694
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1260
1695
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1696
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1697
+ if (isPartOfExternals || externalsPreset && !metadata.isWorkspace) {
1698
+ allUsedExternals.add(dep);
1699
+ continue;
1700
+ }
1261
1701
  if (depsToOptimize.has(dep)) {
1262
1702
  const existingEntry = depsToOptimize.get(dep);
1263
1703
  depsToOptimize.set(dep, {
@@ -1269,28 +1709,49 @@ If you think your configuration is valid, please open an issue.`);
1269
1709
  }
1270
1710
  }
1271
1711
  }
1272
- if (isDev) {
1712
+ if (isDev || externalsPreset) {
1273
1713
  for (const [dep, metadata] of depsToOptimize.entries()) {
1274
1714
  if (!metadata.isWorkspace) {
1275
1715
  depsToOptimize.delete(dep);
1276
1716
  }
1277
1717
  }
1278
1718
  }
1279
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1719
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1280
1720
  logger.info("Optimizing dependencies...");
1281
- logger.debug(
1282
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1283
- );
1721
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1284
1722
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1285
1723
  bundlerOptions: {
1286
1724
  ...bundlerOptions,
1287
- enableEsmShim,
1725
+ externals: bundlerOptions?.externals ?? allExternals,
1288
1726
  isDev
1289
1727
  },
1290
1728
  projectRoot,
1291
1729
  workspaceRoot,
1292
1730
  workspaceMap
1293
1731
  });
1732
+ const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map(
1733
+ (pkgInfo) => relative(workspaceRoot || projectRoot, pkgInfo.location)
1734
+ );
1735
+ for (const o of output) {
1736
+ if (o.type === "asset") {
1737
+ continue;
1738
+ }
1739
+ for (const i of o.imports) {
1740
+ if (isBuiltinModule(i)) {
1741
+ continue;
1742
+ }
1743
+ if (i.startsWith(".") || i.startsWith("/")) {
1744
+ continue;
1745
+ }
1746
+ if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) {
1747
+ continue;
1748
+ }
1749
+ const pkgName = getPackageName(i);
1750
+ if (pkgName) {
1751
+ allUsedExternals.add(pkgName);
1752
+ }
1753
+ }
1754
+ }
1294
1755
  const result = await validateOutput(
1295
1756
  {
1296
1757
  output,
@@ -1302,9 +1763,12 @@ If you think your configuration is valid, please open an issue.`);
1302
1763
  },
1303
1764
  logger
1304
1765
  );
1305
- return result;
1766
+ return {
1767
+ ...result,
1768
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1769
+ };
1306
1770
  }
1307
1771
 
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
1772
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getPackageRootPath, getWorkspaceInformation, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1773
+ //# sourceMappingURL=chunk-4NPMVODD.js.map
1774
+ //# sourceMappingURL=chunk-4NPMVODD.js.map