@mastra/deployer 1.54.0-alpha.0 → 1.54.0-alpha.2

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 (211) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/analyze-C2q7jxbN.js +1308 -0
  3. package/dist/analyze-C2q7jxbN.js.map +1 -0
  4. package/dist/analyze-DhDZW9TS.cjs +1318 -0
  5. package/dist/analyze-DhDZW9TS.cjs.map +1 -0
  6. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs +8 -0
  7. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs.map +1 -0
  8. package/dist/arktype-aI7TBD0R-_UZl-wsH.js +8 -0
  9. package/dist/arktype-aI7TBD0R-_UZl-wsH.js.map +1 -0
  10. package/dist/build/analyze/constants.d.ts.map +1 -1
  11. package/dist/build/analyze.cjs +3 -12
  12. package/dist/build/analyze.js +2 -3
  13. package/dist/build/bundler.cjs +6 -24
  14. package/dist/build/bundler.js +2 -3
  15. package/dist/build/index.cjs +29 -101
  16. package/dist/build/index.js +7 -8
  17. package/dist/build-De4AZhfJ.cjs +908 -0
  18. package/dist/build-De4AZhfJ.cjs.map +1 -0
  19. package/dist/build-KCOeHd4N.js +834 -0
  20. package/dist/build-KCOeHd4N.js.map +1 -0
  21. package/dist/bundler/index.cjs +318 -13
  22. package/dist/bundler/index.cjs.map +1 -1
  23. package/dist/bundler/index.js +314 -2
  24. package/dist/bundler/index.js.map +1 -1
  25. package/dist/bundler-BqrDXofn.cjs +792 -0
  26. package/dist/bundler-BqrDXofn.cjs.map +1 -0
  27. package/dist/bundler-D86rFu2J.js +705 -0
  28. package/dist/bundler-D86rFu2J.js.map +1 -0
  29. package/dist/bundlerOptions-aFsEi86t.js +180 -0
  30. package/dist/bundlerOptions-aFsEi86t.js.map +1 -0
  31. package/dist/bundlerOptions-rBmtSyGe.cjs +194 -0
  32. package/dist/bundlerOptions-rBmtSyGe.cjs.map +1 -0
  33. package/dist/core-D0wEgdn3.cjs +790 -0
  34. package/dist/core-D0wEgdn3.cjs.map +1 -0
  35. package/dist/core-DF65PJXc.js +790 -0
  36. package/dist/core-DF65PJXc.js.map +1 -0
  37. package/dist/dist-BauTimif.js +532 -0
  38. package/dist/dist-BauTimif.js.map +1 -0
  39. package/dist/dist-Cv-mAEtr.cjs +532 -0
  40. package/dist/dist-Cv-mAEtr.cjs.map +1 -0
  41. package/dist/docs/SKILL.md +1 -1
  42. package/dist/docs/assets/SOURCE_MAP.json +2 -23
  43. package/dist/docs/references/docs-deployment-cloud-providers.md +1 -0
  44. package/dist/docs/references/docs-deployment-overview.md +1 -0
  45. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs +14 -0
  46. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs.map +1 -0
  47. package/dist/effect-QlVUlMFu-gyLQRCtQ.js +14 -0
  48. package/dist/effect-QlVUlMFu-gyLQRCtQ.js.map +1 -0
  49. package/dist/esm-BX-weMyC.js +4634 -0
  50. package/dist/esm-BX-weMyC.js.map +1 -0
  51. package/dist/esm-D81PZ_wJ.cjs +4634 -0
  52. package/dist/esm-D81PZ_wJ.cjs.map +1 -0
  53. package/dist/index-CLddUTqr-B5mOP6DC.cjs +145 -0
  54. package/dist/index-CLddUTqr-B5mOP6DC.cjs.map +1 -0
  55. package/dist/index-CLddUTqr-CkS6Y_hA.js +140 -0
  56. package/dist/index-CLddUTqr-CkS6Y_hA.js.map +1 -0
  57. package/dist/index.cjs +35 -48
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.js +29 -30
  60. package/dist/index.js.map +1 -1
  61. package/dist/rolldown-runtime-emK7D4bc.cjs +35 -0
  62. package/dist/server/index.cjs +3141 -3874
  63. package/dist/server/index.cjs.map +1 -1
  64. package/dist/server/index.d.ts.map +1 -1
  65. package/dist/server/index.js +3131 -3842
  66. package/dist/server/index.js.map +1 -1
  67. package/dist/server/types.d.ts +1 -0
  68. package/dist/server/types.d.ts.map +1 -1
  69. package/dist/services/index.cjs +5 -20
  70. package/dist/services/index.js +2 -3
  71. package/dist/services-BxYMLS9-.cjs +430 -0
  72. package/dist/services-BxYMLS9-.cjs.map +1 -0
  73. package/dist/services-CLi56qqe.js +391 -0
  74. package/dist/services-CLi56qqe.js.map +1 -0
  75. package/dist/sury-CWZTCd75-B85M6878.js +14 -0
  76. package/dist/sury-CWZTCd75-B85M6878.js.map +1 -0
  77. package/dist/sury-CWZTCd75-DTj5HlK_.cjs +14 -0
  78. package/dist/sury-CWZTCd75-DTj5HlK_.cjs.map +1 -0
  79. package/dist/typebox-Dei93FPO-BeuT13_G.cjs +8 -0
  80. package/dist/typebox-Dei93FPO-BeuT13_G.cjs.map +1 -0
  81. package/dist/typebox-Dei93FPO-DovwMlVl.js +8 -0
  82. package/dist/typebox-Dei93FPO-DovwMlVl.js.map +1 -0
  83. package/dist/utils-FVOUvj-I.js +190 -0
  84. package/dist/utils-FVOUvj-I.js.map +1 -0
  85. package/dist/utils-O98BGdnP.cjs +267 -0
  86. package/dist/utils-O98BGdnP.cjs.map +1 -0
  87. package/dist/valibot--1zFm7rT-BqJHja5B.cjs +14 -0
  88. package/dist/valibot--1zFm7rT-BqJHja5B.cjs.map +1 -0
  89. package/dist/valibot--1zFm7rT-Y4Fhea0w.js +14 -0
  90. package/dist/valibot--1zFm7rT-Y4Fhea0w.js.map +1 -0
  91. package/dist/validator/custom-resolver.cjs +71 -73
  92. package/dist/validator/custom-resolver.cjs.map +1 -1
  93. package/dist/validator/custom-resolver.js +70 -71
  94. package/dist/validator/custom-resolver.js.map +1 -1
  95. package/dist/validator/loader.cjs +6 -7
  96. package/dist/validator/loader.cjs.map +1 -1
  97. package/dist/validator/loader.js +8 -4
  98. package/dist/validator/loader.js.map +1 -1
  99. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs +23 -0
  100. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs.map +1 -0
  101. package/dist/zod-Bwrt9trS-rVHICsmp.js +23 -0
  102. package/dist/zod-Bwrt9trS-rVHICsmp.js.map +1 -0
  103. package/package.json +7 -7
  104. package/dist/arktype-aI7TBD0R-K3QZAVE2.js +0 -8
  105. package/dist/arktype-aI7TBD0R-K3QZAVE2.js.map +0 -1
  106. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs +0 -10
  107. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs.map +0 -1
  108. package/dist/build/analyze.cjs.map +0 -1
  109. package/dist/build/analyze.js.map +0 -1
  110. package/dist/build/bundler.cjs.map +0 -1
  111. package/dist/build/bundler.js.map +0 -1
  112. package/dist/build/index.cjs.map +0 -1
  113. package/dist/build/index.js.map +0 -1
  114. package/dist/chunk-36AWZH7Z.cjs +0 -252
  115. package/dist/chunk-36AWZH7Z.cjs.map +0 -1
  116. package/dist/chunk-3XIMK24X.cjs +0 -765
  117. package/dist/chunk-3XIMK24X.cjs.map +0 -1
  118. package/dist/chunk-46M65MQG.cjs +0 -95
  119. package/dist/chunk-46M65MQG.cjs.map +0 -1
  120. package/dist/chunk-4ZNTNJ6T.js +0 -6
  121. package/dist/chunk-4ZNTNJ6T.js.map +0 -1
  122. package/dist/chunk-5PORNUPF.js +0 -739
  123. package/dist/chunk-5PORNUPF.js.map +0 -1
  124. package/dist/chunk-743HRNWT.cjs +0 -1546
  125. package/dist/chunk-743HRNWT.cjs.map +0 -1
  126. package/dist/chunk-AEQ7JHDB.cjs +0 -412
  127. package/dist/chunk-AEQ7JHDB.cjs.map +0 -1
  128. package/dist/chunk-E5SBYHQK.js +0 -244
  129. package/dist/chunk-E5SBYHQK.js.map +0 -1
  130. package/dist/chunk-FKKJQUGR.cjs +0 -497
  131. package/dist/chunk-FKKJQUGR.cjs.map +0 -1
  132. package/dist/chunk-FQHUOYYL.js +0 -1514
  133. package/dist/chunk-FQHUOYYL.js.map +0 -1
  134. package/dist/chunk-G7MIMGMX.js +0 -14
  135. package/dist/chunk-G7MIMGMX.js.map +0 -1
  136. package/dist/chunk-HZC3PTK2.cjs +0 -16
  137. package/dist/chunk-HZC3PTK2.cjs.map +0 -1
  138. package/dist/chunk-JZRFRUGM.cjs +0 -158
  139. package/dist/chunk-JZRFRUGM.cjs.map +0 -1
  140. package/dist/chunk-L45X3DJX.js +0 -385
  141. package/dist/chunk-L45X3DJX.js.map +0 -1
  142. package/dist/chunk-PC25XSK7.cjs +0 -8
  143. package/dist/chunk-PC25XSK7.cjs.map +0 -1
  144. package/dist/chunk-PZ5AY32C.js +0 -9
  145. package/dist/chunk-PZ5AY32C.js.map +0 -1
  146. package/dist/chunk-Q7SFCCGT.cjs +0 -11
  147. package/dist/chunk-Q7SFCCGT.cjs.map +0 -1
  148. package/dist/chunk-T4UT2QX7.js +0 -3
  149. package/dist/chunk-T4UT2QX7.js.map +0 -1
  150. package/dist/chunk-UBIDJOJA.js +0 -93
  151. package/dist/chunk-UBIDJOJA.js.map +0 -1
  152. package/dist/chunk-V3EKV6QB.cjs +0 -162
  153. package/dist/chunk-V3EKV6QB.cjs.map +0 -1
  154. package/dist/chunk-WHD2QQ3N.js +0 -783
  155. package/dist/chunk-WHD2QQ3N.js.map +0 -1
  156. package/dist/chunk-WP65JQAT.js +0 -144
  157. package/dist/chunk-WP65JQAT.js.map +0 -1
  158. package/dist/chunk-YO5OFXPN.cjs +0 -819
  159. package/dist/chunk-YO5OFXPN.cjs.map +0 -1
  160. package/dist/chunk-YUBKHO52.js +0 -465
  161. package/dist/chunk-YUBKHO52.js.map +0 -1
  162. package/dist/chunk-YWMYXUHX.cjs +0 -4
  163. package/dist/chunk-YWMYXUHX.cjs.map +0 -1
  164. package/dist/chunk-ZKZOVNT4.js +0 -159
  165. package/dist/chunk-ZKZOVNT4.js.map +0 -1
  166. package/dist/core-XIDAXLRB.js +0 -11866
  167. package/dist/core-XIDAXLRB.js.map +0 -1
  168. package/dist/core-XJNQ4AY6.cjs +0 -12141
  169. package/dist/core-XJNQ4AY6.cjs.map +0 -1
  170. package/dist/default-u_dwuiYb-HGUAHA6N.cjs +0 -9
  171. package/dist/default-u_dwuiYb-HGUAHA6N.cjs.map +0 -1
  172. package/dist/default-u_dwuiYb-MVPTVDCE.js +0 -3
  173. package/dist/default-u_dwuiYb-MVPTVDCE.js.map +0 -1
  174. package/dist/dist-UEE5OLII.cjs +0 -521
  175. package/dist/dist-UEE5OLII.cjs.map +0 -1
  176. package/dist/dist-X75F2Q36.js +0 -515
  177. package/dist/dist-X75F2Q36.js.map +0 -1
  178. package/dist/effect-QlVUlMFu-QNLZLGWO.js +0 -15
  179. package/dist/effect-QlVUlMFu-QNLZLGWO.js.map +0 -1
  180. package/dist/effect-QlVUlMFu-XUD6EH23.cjs +0 -17
  181. package/dist/effect-QlVUlMFu-XUD6EH23.cjs.map +0 -1
  182. package/dist/esm-DFCHSIJZ.cjs +0 -1589
  183. package/dist/esm-DFCHSIJZ.cjs.map +0 -1
  184. package/dist/esm-PXGQ5WB4.js +0 -1542
  185. package/dist/esm-PXGQ5WB4.js.map +0 -1
  186. package/dist/services/index.cjs.map +0 -1
  187. package/dist/services/index.js.map +0 -1
  188. package/dist/sury-CWZTCd75-3KQQJ22C.cjs +0 -17
  189. package/dist/sury-CWZTCd75-3KQQJ22C.cjs.map +0 -1
  190. package/dist/sury-CWZTCd75-DZQHKAZF.js +0 -15
  191. package/dist/sury-CWZTCd75-DZQHKAZF.js.map +0 -1
  192. package/dist/typebox-Dei93FPO-GOYJ5OUT.js +0 -8
  193. package/dist/typebox-Dei93FPO-GOYJ5OUT.js.map +0 -1
  194. package/dist/typebox-Dei93FPO-M7J7E57W.cjs +0 -10
  195. package/dist/typebox-Dei93FPO-M7J7E57W.cjs.map +0 -1
  196. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs +0 -17
  197. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs.map +0 -1
  198. package/dist/valibot--1zFm7rT-ZVGQI7WV.js +0 -15
  199. package/dist/valibot--1zFm7rT-ZVGQI7WV.js.map +0 -1
  200. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs +0 -45
  201. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs.map +0 -1
  202. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js +0 -43
  203. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js.map +0 -1
  204. package/dist/zod-Bwrt9trS-GN7ZXBMN.js +0 -29
  205. package/dist/zod-Bwrt9trS-GN7ZXBMN.js.map +0 -1
  206. package/dist/zod-Bwrt9trS-OVKARV6W.cjs +0 -31
  207. package/dist/zod-Bwrt9trS-OVKARV6W.cjs.map +0 -1
  208. package/dist/zod-DSgpEGAE-E7YZZ7VC.js +0 -37
  209. package/dist/zod-DSgpEGAE-E7YZZ7VC.js.map +0 -1
  210. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs +0 -39
  211. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs.map +0 -1
@@ -0,0 +1,1318 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
2
+ const require_utils = require("./utils-O98BGdnP.cjs");
3
+ require("./services-BxYMLS9-.cjs");
4
+ const require_bundler = require("./bundler-BqrDXofn.cjs");
5
+ let child_process = require("child_process");
6
+ let fs = require("fs");
7
+ let fs_promises = require("fs/promises");
8
+ let path = require("path");
9
+ path = require_rolldown_runtime.__toESM(path, 1);
10
+ let _mastra_core_error = require("@mastra/core/error");
11
+ let _rollup_plugin_virtual = require("@rollup/plugin-virtual");
12
+ _rollup_plugin_virtual = require_rolldown_runtime.__toESM(_rollup_plugin_virtual, 1);
13
+ let empathic_package = require("empathic/package");
14
+ empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
15
+ let _babel_core = require("@babel/core");
16
+ require("@sindresorhus/slugify");
17
+ let find_workspaces = require("find-workspaces");
18
+ require("fs-extra");
19
+ let url = require("url");
20
+ let _rollup_plugin_commonjs = require("@rollup/plugin-commonjs");
21
+ _rollup_plugin_commonjs = require_rolldown_runtime.__toESM(_rollup_plugin_commonjs, 1);
22
+ let _rollup_plugin_json = require("@rollup/plugin-json");
23
+ _rollup_plugin_json = require_rolldown_runtime.__toESM(_rollup_plugin_json, 1);
24
+ let rollup = require("rollup");
25
+ let _optimize_lodash_rollup_plugin = require("@optimize-lodash/rollup-plugin");
26
+ let _rollup_plugin_node_resolve = require("@rollup/plugin-node-resolve");
27
+ _rollup_plugin_node_resolve = require_rolldown_runtime.__toESM(_rollup_plugin_node_resolve, 1);
28
+ let local_pkg = require("local-pkg");
29
+ let path_posix = require("path/posix");
30
+ let resolve_exports = require("resolve.exports");
31
+ resolve_exports = require_rolldown_runtime.__toESM(resolve_exports, 1);
32
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/stacktrace-parser/0.1.11/63406bc765474556691ebd1b24eaa0c5b032f058a26bbaff13797a2780d98220/node_modules/stacktrace-parser/dist/stack-trace-parser.cjs.js
33
+ var require_stack_trace_parser_cjs = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((exports) => {
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ var UNKNOWN_FUNCTION = "<unknown>";
36
+ /**
37
+ * This parses the different stack traces and puts them into one format
38
+ * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)
39
+ */
40
+ function parse(stackString) {
41
+ return stackString.split("\n").reduce(function(stack, line) {
42
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
43
+ if (parseResult) stack.push(parseResult);
44
+ return stack;
45
+ }, []);
46
+ }
47
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
48
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
49
+ function parseChrome(line) {
50
+ var parts = chromeRe.exec(line);
51
+ if (!parts) return null;
52
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
53
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
54
+ var submatch = chromeEvalRe.exec(parts[2]);
55
+ if (isEval && submatch != null) {
56
+ parts[2] = submatch[1];
57
+ parts[3] = submatch[2];
58
+ parts[4] = submatch[3];
59
+ }
60
+ return {
61
+ file: !isNative ? parts[2] : null,
62
+ methodName: parts[1] || UNKNOWN_FUNCTION,
63
+ arguments: isNative ? [parts[2]] : [],
64
+ lineNumber: parts[3] ? +parts[3] : null,
65
+ column: parts[4] ? +parts[4] : null
66
+ };
67
+ }
68
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
69
+ function parseWinjs(line) {
70
+ var parts = winjsRe.exec(line);
71
+ if (!parts) return null;
72
+ return {
73
+ file: parts[2],
74
+ methodName: parts[1] || UNKNOWN_FUNCTION,
75
+ arguments: [],
76
+ lineNumber: +parts[3],
77
+ column: parts[4] ? +parts[4] : null
78
+ };
79
+ }
80
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
81
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
82
+ function parseGecko(line) {
83
+ var parts = geckoRe.exec(line);
84
+ if (!parts) return null;
85
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
86
+ var submatch = geckoEvalRe.exec(parts[3]);
87
+ if (isEval && submatch != null) {
88
+ parts[3] = submatch[1];
89
+ parts[4] = submatch[2];
90
+ parts[5] = null;
91
+ }
92
+ return {
93
+ file: parts[3],
94
+ methodName: parts[1] || UNKNOWN_FUNCTION,
95
+ arguments: parts[2] ? parts[2].split(",") : [],
96
+ lineNumber: parts[4] ? +parts[4] : null,
97
+ column: parts[5] ? +parts[5] : null
98
+ };
99
+ }
100
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
101
+ function parseJSC(line) {
102
+ var parts = javaScriptCoreRe.exec(line);
103
+ if (!parts) return null;
104
+ return {
105
+ file: parts[3],
106
+ methodName: parts[1] || UNKNOWN_FUNCTION,
107
+ arguments: [],
108
+ lineNumber: +parts[4],
109
+ column: parts[5] ? +parts[5] : null
110
+ };
111
+ }
112
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
113
+ function parseNode(line) {
114
+ var parts = nodeRe.exec(line);
115
+ if (!parts) return null;
116
+ return {
117
+ file: parts[2],
118
+ methodName: parts[1] || UNKNOWN_FUNCTION,
119
+ arguments: [],
120
+ lineNumber: +parts[3],
121
+ column: parts[4] ? +parts[4] : null
122
+ };
123
+ }
124
+ exports.parse = parse;
125
+ }));
126
+ //#endregion
127
+ //#region src/bundler/workspaceDependencies.ts
128
+ var import_stack_trace_parser_cjs = /* @__PURE__ */ require_rolldown_runtime.__toESM(require_stack_trace_parser_cjs(), 1);
129
+ /**
130
+ * Create a shared cache for find-workspaces
131
+ */
132
+ const workspacesCache = (0, find_workspaces.createWorkspacesCache)();
133
+ /**
134
+ * A utility function around find-workspaces to get information about:
135
+ * - Which workspace packages are available in the project
136
+ * - What is the workspace root location
137
+ * - Is the current package a workspace package
138
+ *
139
+ * Because `findWorkspacesRoot` only traverses up until it finds workspace information, but doesn't check if the current package is even part of the workspace. We rather want to return `null` for these cases because in other code paths we use `workspaceRoot || projectRoot` to determine the root of the project.
140
+ *
141
+ * @params dir - The directory to start searching from (default: `process.cwd()`)
142
+ * @params location - The location of the current package (usually the directory containing the package.json)
143
+ */
144
+ async function getWorkspaceInformation({ dir = process.cwd(), mastraEntryFile }) {
145
+ const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
146
+ const location = closestPkgJson ? (0, path.dirname)(require_utils.slash(closestPkgJson)) : require_utils.slash(process.cwd());
147
+ const workspaces = await (0, find_workspaces.findWorkspaces)(dir, { cache: workspacesCache });
148
+ const _workspaceMap = new Map(workspaces?.map((workspace) => [workspace.package.name, {
149
+ location: workspace.location,
150
+ dependencies: workspace.package.dependencies,
151
+ version: workspace.package.version
152
+ }]) ?? []);
153
+ const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location);
154
+ const workspaceRoot = isWorkspacePackage ? (0, find_workspaces.findWorkspacesRoot)(dir, { cache: workspacesCache })?.location : void 0;
155
+ return {
156
+ workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(),
157
+ workspaceRoot,
158
+ isWorkspacePackage
159
+ };
160
+ }
161
+ //#endregion
162
+ //#region src/validator/validate.ts
163
+ var ValidationError = class extends Error {
164
+ type;
165
+ stack;
166
+ constructor(args) {
167
+ super(args.message);
168
+ this.type = args.type;
169
+ this.stack = args.stack;
170
+ }
171
+ };
172
+ /**
173
+ * Promisified version of Node.js spawn function
174
+ *
175
+ * @param command - The command to run
176
+ * @param args - List of string arguments
177
+ * @param options - Spawn options
178
+ * @returns Promise that resolves with the exit code when the process completes
179
+ */
180
+ function spawn(command, args = [], options = {}) {
181
+ return new Promise((resolve, reject) => {
182
+ let validationError = null;
183
+ const childProcess = (0, child_process.spawn)(command, args, {
184
+ stdio: [
185
+ "ignore",
186
+ "ignore",
187
+ "pipe"
188
+ ],
189
+ ...options
190
+ });
191
+ childProcess.on("error", (error) => {
192
+ reject(error);
193
+ });
194
+ let stderr = "";
195
+ childProcess.stderr?.on("data", (message) => {
196
+ try {
197
+ validationError = JSON.parse(message.toString());
198
+ } catch {
199
+ stderr += message;
200
+ }
201
+ });
202
+ childProcess.on("close", (code) => {
203
+ if (code === 0) resolve();
204
+ else if (validationError) reject(new ValidationError(validationError));
205
+ else reject(new Error(stderr));
206
+ });
207
+ });
208
+ }
209
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation, stubbedExternals = [] }) {
210
+ let prefixCode = "";
211
+ if (injectESMShim) prefixCode = `import { fileURLToPath } from 'url';
212
+ import { dirname } from 'path';
213
+
214
+ globalThis.__filename = fileURLToPath(import.meta.url);
215
+ globalThis.__dirname = dirname(__filename);
216
+ `;
217
+ function errorHandler(err) {
218
+ console.error(JSON.stringify({
219
+ type: err.name,
220
+ message: err.message,
221
+ stack: err.stack
222
+ }));
223
+ process.exit(1);
224
+ }
225
+ return spawn(process.execPath, [
226
+ "--import",
227
+ {}.resolve("@mastra/deployer/loader"),
228
+ "--input-type=module",
229
+ "--enable-source-maps",
230
+ "-e",
231
+ `${prefixCode};import('${(0, url.pathToFileURL)(file).href}').catch(err => {
232
+ ${errorHandler.toString()}
233
+ errorHandler(err);
234
+ })`.replaceAll(/\n/g, "")
235
+ ], {
236
+ env: {
237
+ ...process.env,
238
+ MODULE_MAP: `${moduleResolveMapLocation}`,
239
+ STUBBED_EXTERNALS: JSON.stringify(stubbedExternals)
240
+ },
241
+ cwd: (0, path.dirname)(file)
242
+ });
243
+ }
244
+ //#endregion
245
+ //#region src/build/analyze/constants.ts
246
+ const DEPS_TO_IGNORE = [
247
+ "#tools",
248
+ "execa",
249
+ "effect",
250
+ "sury",
251
+ "@ast-grep/napi",
252
+ "@hono/node-ws"
253
+ ];
254
+ const GLOBAL_EXTERNALS = [
255
+ "pino",
256
+ "pino-pretty",
257
+ "@libsql/client",
258
+ "pg",
259
+ "libsql",
260
+ "#tools",
261
+ "typescript",
262
+ "undici",
263
+ "readable-stream",
264
+ "bufferutil",
265
+ "utf-8-validate",
266
+ "execa",
267
+ "@ast-grep/napi",
268
+ "@hono/node-ws"
269
+ ];
270
+ const DEPRECATED_EXTERNALS = [
271
+ "fastembed",
272
+ "nodemailer",
273
+ "jsdom",
274
+ "sqlite3"
275
+ ];
276
+ //#endregion
277
+ //#region src/build/analyze/analyzeEntry.ts
278
+ /**
279
+ * Configures and returns the Rollup plugins needed for analyzing entry files.
280
+ * Sets up module resolution, transpilation, and custom alias handling for Mastra-specific imports.
281
+ */
282
+ function getInputPlugins$1({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
283
+ let virtualPlugin = null;
284
+ if (isVirtualFile) {
285
+ virtualPlugin = (0, _rollup_plugin_virtual.default)({ "#entry": entry });
286
+ entry = "#entry";
287
+ }
288
+ const plugins = [];
289
+ if (virtualPlugin) plugins.push(virtualPlugin);
290
+ plugins.push(...[
291
+ require_bundler.protocolExternalResolver(),
292
+ require_bundler.mastraInternalAliasPlugin(mastraEntry),
293
+ require_bundler.mastraToolsAliasPlugin(),
294
+ require_bundler.tsConfigPaths(),
295
+ (0, _rollup_plugin_json.default)(),
296
+ require_bundler.esbuild(),
297
+ (0, _rollup_plugin_commonjs.default)({
298
+ strictRequires: "debug",
299
+ ignoreTryCatch: false,
300
+ transformMixedEsModules: true,
301
+ extensions: [".js", ".ts"]
302
+ }),
303
+ require_bundler.removeDeployer(mastraEntry, { sourcemap: sourcemapEnabled }),
304
+ require_bundler.esbuild()
305
+ ]);
306
+ return plugins;
307
+ }
308
+ /**
309
+ * Extracts and categorizes dependencies from Rollup output to determine which ones need optimization.
310
+ * Analyzes both static imports and dynamic imports while filtering out Node.js built-ins and ignored dependencies.
311
+ * Identifies workspace packages and resolves package root paths for proper bundling optimization.
312
+ */
313
+ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, { logger, shouldCheckTransitiveDependencies }) {
314
+ const depsToOptimize = /* @__PURE__ */ new Map();
315
+ if (!output.facadeModuleId) throw new Error("Something went wrong, we could not find the package name of the entry file. Please open an issue.");
316
+ let entryRootPath = projectRoot;
317
+ if (!output.facadeModuleId.startsWith("\0virtual:")) entryRootPath = await require_bundler.getPackageRootPath(output.facadeModuleId) || projectRoot;
318
+ for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
319
+ if (!require_utils.isBareModuleSpecifier(dependency)) continue;
320
+ const pkgName = require_utils.getPackageName(dependency);
321
+ let rootPath = null;
322
+ let isWorkspace = false;
323
+ let version;
324
+ let packageSpec;
325
+ if (pkgName) {
326
+ const metadata = await require_bundler.getPackageMetadata(dependency, entryRootPath);
327
+ rootPath = metadata.rootPath;
328
+ version = metadata.version;
329
+ packageSpec = metadata.packageSpec;
330
+ isWorkspace = workspaceMap.has(pkgName);
331
+ }
332
+ const normalizedRootPath = rootPath ? require_utils.slash(rootPath) : null;
333
+ depsToOptimize.set(dependency, {
334
+ exports: bindings,
335
+ rootPath: normalizedRootPath,
336
+ isWorkspace,
337
+ version,
338
+ packageSpec
339
+ });
340
+ }
341
+ const processedWorkspaceDeps = /* @__PURE__ */ new Set();
342
+ /**
343
+ * Recursively discovers transitive workspace dependencies from package manifests.
344
+ */
345
+ function checkTransitiveDependencies(maxDepth = 10, currentDepth = 0) {
346
+ if (currentDepth >= maxDepth) {
347
+ logger.warn("Maximum dependency depth reached while checking transitive dependencies.");
348
+ return;
349
+ }
350
+ const depsSnapshot = new Map(depsToOptimize);
351
+ let hasAddedDeps = false;
352
+ for (const [dep, meta] of depsSnapshot) {
353
+ const pkgName = require_utils.getPackageName(dep);
354
+ if (!pkgName || !meta.isWorkspace || processedWorkspaceDeps.has(pkgName)) continue;
355
+ processedWorkspaceDeps.add(pkgName);
356
+ const workspaceInfo = workspaceMap.get(pkgName);
357
+ if (!workspaceInfo?.dependencies) continue;
358
+ for (const [innerDep, _innerDepVersion] of Object.entries(workspaceInfo.dependencies)) {
359
+ const innerWorkspaceInfo = workspaceMap.get(innerDep);
360
+ if (!innerWorkspaceInfo) continue;
361
+ const existingMeta = depsToOptimize.get(innerDep);
362
+ if (existingMeta) {
363
+ depsToOptimize.set(innerDep, {
364
+ ...existingMeta,
365
+ exports: existingMeta.exports.includes("*") ? existingMeta.exports : [...existingMeta.exports, "*"]
366
+ });
367
+ continue;
368
+ }
369
+ depsToOptimize.set(innerDep, {
370
+ exports: ["*"],
371
+ rootPath: require_utils.slash(innerWorkspaceInfo.location),
372
+ isWorkspace: true,
373
+ version: innerWorkspaceInfo.version
374
+ });
375
+ hasAddedDeps = true;
376
+ }
377
+ }
378
+ if (hasAddedDeps) checkTransitiveDependencies(maxDepth, currentDepth + 1);
379
+ }
380
+ if (shouldCheckTransitiveDependencies) checkTransitiveDependencies();
381
+ const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
382
+ if (dynamicImports.length) {
383
+ for (const dynamicImport of dynamicImports) if (!depsToOptimize.has(dynamicImport) && require_utils.isBareModuleSpecifier(dynamicImport)) {
384
+ const pkgName = require_utils.getPackageName(dynamicImport);
385
+ let version;
386
+ let packageSpec;
387
+ let rootPath = null;
388
+ if (pkgName) {
389
+ const metadata = await require_bundler.getPackageMetadata(dynamicImport, entryRootPath);
390
+ rootPath = metadata.rootPath;
391
+ version = metadata.version;
392
+ packageSpec = metadata.packageSpec;
393
+ }
394
+ depsToOptimize.set(dynamicImport, {
395
+ exports: ["*"],
396
+ rootPath: rootPath ? require_utils.slash(rootPath) : null,
397
+ isWorkspace: false,
398
+ version,
399
+ packageSpec
400
+ });
401
+ }
402
+ }
403
+ return depsToOptimize;
404
+ }
405
+ async function analyzeEntry({ entry, isVirtualFile }, mastraEntry, { logger, sourcemapEnabled, workspaceMap, projectRoot, shouldCheckTransitiveDependencies = false, analyzeCache }) {
406
+ const cacheKey = isVirtualFile ? void 0 : require_utils.slash(entry);
407
+ if (cacheKey && analyzeCache?.has(cacheKey)) return analyzeCache.get(cacheKey);
408
+ const optimizerBundler = await (0, rollup.rollup)({
409
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
410
+ input: isVirtualFile ? "#entry" : entry,
411
+ treeshake: false,
412
+ preserveSymlinks: true,
413
+ plugins: getInputPlugins$1({
414
+ entry,
415
+ isVirtualFile
416
+ }, mastraEntry, { sourcemapEnabled }),
417
+ external: DEPS_TO_IGNORE
418
+ });
419
+ const { output } = await optimizerBundler.generate({
420
+ format: "esm",
421
+ inlineDynamicImports: true
422
+ });
423
+ await optimizerBundler.close();
424
+ const result = {
425
+ dependencies: await captureDependenciesToOptimize(output[0], workspaceMap, projectRoot, {
426
+ logger,
427
+ shouldCheckTransitiveDependencies
428
+ }),
429
+ output: {
430
+ code: output[0].code,
431
+ map: output[0].map
432
+ }
433
+ };
434
+ if (cacheKey && analyzeCache) analyzeCache.set(cacheKey, result);
435
+ return result;
436
+ }
437
+ //#endregion
438
+ //#region src/build/plugins/hono-alias.ts
439
+ function aliasHono() {
440
+ return {
441
+ name: "hono-alias",
442
+ resolveId(id) {
443
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") return;
444
+ return (0, url.fileURLToPath)({}.resolve(id));
445
+ }
446
+ };
447
+ }
448
+ //#endregion
449
+ //#region src/build/plugins/module-resolve-map.ts
450
+ function moduleResolveMap(externals, projectRoot) {
451
+ const importMap = /* @__PURE__ */ new Map();
452
+ return {
453
+ name: "module-resolve-map",
454
+ moduleParsed(info) {
455
+ if (info.importedIds.length === 0 || !info.id) return;
456
+ for (const importedId of info.importedIds) for (const external of externals) if (require_utils.isDependencyPartOfPackage(importedId, external)) importMap.set(external, info.id);
457
+ },
458
+ async generateBundle(options, bundle) {
459
+ const resolveMap = /* @__PURE__ */ new Map();
460
+ for (const [fileName, chunk] of Object.entries(bundle)) if (chunk.type === "chunk") {
461
+ for (const [external, resolvedFrom] of importMap) if (chunk.moduleIds.includes(resolvedFrom)) {
462
+ const fullPath = (0, url.pathToFileURL)(require_utils.slash((0, path.join)(projectRoot, fileName))).toString();
463
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
464
+ innerMap.set(external, (0, url.pathToFileURL)(require_utils.slash(resolvedFrom)).toString());
465
+ resolveMap.set(fullPath, innerMap);
466
+ }
467
+ }
468
+ const resolveMapJson = Object.fromEntries(Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())]));
469
+ this.emitFile({
470
+ type: "asset",
471
+ name: "module-resolve-map.json",
472
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
473
+ });
474
+ }
475
+ };
476
+ }
477
+ //#endregion
478
+ //#region src/build/plugins/node-gyp-detector.ts
479
+ function nodeGypDetector() {
480
+ const modulesToTrack = /* @__PURE__ */ new Set();
481
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
482
+ return {
483
+ name: "node-gyp-build-detector",
484
+ moduleParsed(info) {
485
+ if (!info.meta?.commonjs?.requires?.length) return;
486
+ if (!info.meta.commonjs.requires.some((m) => m?.resolved?.id.endsWith("node-gyp-build/index.js"))) return;
487
+ modulesToTrack.add(info.id);
488
+ modulesToTrackPackageInfo.set(info.id, (0, local_pkg.getPackageInfo)(info.id));
489
+ },
490
+ async generateBundle(options, bundle) {
491
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
492
+ for (const [fileName, chunk] of Object.entries(bundle)) if (chunk.type === "chunk") {
493
+ for (const moduleId of chunk.moduleIds) if (modulesToTrackPackageInfo.has(moduleId)) {
494
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
495
+ if (!binaryMapByChunk.has(fileName)) binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
496
+ if (pkgInfo?.packageJson?.name) binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
497
+ }
498
+ }
499
+ const binaryMapJson = Object.fromEntries(Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)]));
500
+ this.emitFile({
501
+ type: "asset",
502
+ name: "binary-map.json",
503
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
504
+ });
505
+ }
506
+ };
507
+ }
508
+ //#endregion
509
+ //#region src/build/analyze/bundleExternals.ts
510
+ function prepareEntryFileName(name, rootDir) {
511
+ return require_utils.rollupSafeName(name, rootDir);
512
+ }
513
+ /**
514
+ * Creates virtual dependency modules for optimized bundling by generating virtual entry points for each dependency with their specific exports and handling workspace package path resolution.
515
+ */
516
+ function createVirtualDependencies(depsToOptimize, { projectRoot, workspaceRoot, outputDir, bundlerOptions }) {
517
+ const { isDev = false, externalsPreset = false } = bundlerOptions || {};
518
+ const fileNameToDependencyMap = /* @__PURE__ */ new Map();
519
+ const optimizedDependencyEntries = /* @__PURE__ */ new Map();
520
+ const rootDir = workspaceRoot || projectRoot;
521
+ for (const [dep, { exports }] of depsToOptimize.entries()) {
522
+ const fileName = dep.replaceAll("/", "__");
523
+ const virtualFile = [];
524
+ const exportStringBuilder = [];
525
+ for (const local of exports) if (local === "*") {
526
+ virtualFile.push(`export * from '${dep}';`);
527
+ continue;
528
+ } else if (local === "default") exportStringBuilder.push("default");
529
+ else exportStringBuilder.push(local);
530
+ const chunks = [];
531
+ if (exportStringBuilder.length) chunks.push(`{ ${exportStringBuilder.join(", ")} }`);
532
+ if (chunks.length) virtualFile.push(`export ${chunks.join(", ")} from '${dep}';`);
533
+ let entryName = prepareEntryFileName(path.join(outputDir, fileName), rootDir);
534
+ fileNameToDependencyMap.set(entryName, dep);
535
+ optimizedDependencyEntries.set(dep, {
536
+ name: entryName,
537
+ virtual: virtualFile.join("\n")
538
+ });
539
+ }
540
+ if (isDev || externalsPreset) for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
541
+ if (!isWorkspace || !rootPath || !workspaceRoot) continue;
542
+ const currentDepPath = optimizedDependencyEntries.get(dep);
543
+ if (!currentDepPath) continue;
544
+ const entryName = prepareEntryFileName(require_utils.getCompiledDepCachePath(rootPath, (0, path_posix.basename)(currentDepPath.name)), rootDir);
545
+ fileNameToDependencyMap.set(entryName, dep);
546
+ optimizedDependencyEntries.set(dep, {
547
+ ...currentDepPath,
548
+ name: entryName
549
+ });
550
+ }
551
+ return {
552
+ optimizedDependencyEntries,
553
+ fileNameToDependencyMap
554
+ };
555
+ }
556
+ /**
557
+ * Configures and returns Rollup plugins for bundling external dependencies.
558
+ * Sets up virtual modules, TypeScript compilation, CommonJS transformation, and workspace resolution.
559
+ */
560
+ async function getInputPlugins(virtualDependencies, { transpilePackages, workspaceMap, bundlerOptions, rootDir, externals, platform }) {
561
+ const transpilePackagesMap = /* @__PURE__ */ new Map();
562
+ for (const pkg of transpilePackages) {
563
+ const dir = await require_bundler.getPackageRootPath(pkg);
564
+ if (dir) transpilePackagesMap.set(pkg, require_utils.slash(dir));
565
+ else transpilePackagesMap.set(pkg, workspaceMap.get(pkg)?.location ?? pkg);
566
+ }
567
+ return [
568
+ (0, _rollup_plugin_virtual.default)(Array.from(virtualDependencies.entries()).reduce((acc, [dep, virtualDep]) => {
569
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
570
+ return acc;
571
+ }, {})),
572
+ require_bundler.tsConfigPaths(),
573
+ require_bundler.protocolExternalResolver(),
574
+ require_bundler.subpathExternalsResolver(externals),
575
+ transpilePackagesMap.size ? require_bundler.esbuild({
576
+ format: "esm",
577
+ include: [...[...transpilePackagesMap.values()].map((p) => {
578
+ if (path.isAbsolute(p)) return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
579
+ else return new RegExp(`\/${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
580
+ }), ...[...transpilePackagesMap.keys()].map((pkgName) => {
581
+ const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
582
+ return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`);
583
+ })],
584
+ exclude: []
585
+ }) : null,
586
+ bundlerOptions.noBundling ? {
587
+ name: "alias-optimized-deps",
588
+ async resolveId(id, importer, options) {
589
+ if (!virtualDependencies.has(id)) return null;
590
+ const info = virtualDependencies.get(id);
591
+ const packageRootPath = path.join(rootDir, path.dirname(path.dirname(path.dirname(info.name))));
592
+ const pkgJsonBuffer = await (0, fs_promises.readFile)(path.join(packageRootPath, "package.json"), "utf-8");
593
+ const pkgJson = JSON.parse(pkgJsonBuffer);
594
+ if (!pkgJson) return null;
595
+ const pkgName = pkgJson.name || "";
596
+ let resolvedPath = resolve_exports.exports(pkgJson, id.replace(pkgName, "."))?.[0];
597
+ if (!resolvedPath) resolvedPath = pkgJson.main ?? "index.js";
598
+ return await this.resolve(path.posix.join(packageRootPath, resolvedPath), importer, options);
599
+ }
600
+ } : null,
601
+ (0, _optimize_lodash_rollup_plugin.optimizeLodashImports)({ include: "**/*.{js,ts,mjs,cjs}" }),
602
+ (0, _rollup_plugin_commonjs.default)({
603
+ strictRequires: "strict",
604
+ transformMixedEsModules: true,
605
+ ignoreTryCatch: false
606
+ }),
607
+ bundlerOptions.noBundling ? null : (0, _rollup_plugin_node_resolve.default)(require_utils.getNodeResolveOptions(platform)),
608
+ bundlerOptions.noBundling ? require_bundler.esmShim() : null,
609
+ aliasHono(),
610
+ (0, _rollup_plugin_json.default)(),
611
+ nodeGypDetector(),
612
+ moduleResolveMap(externals, rootDir),
613
+ {
614
+ name: "not-found-resolver",
615
+ resolveId: {
616
+ order: "post",
617
+ async handler(id, importer) {
618
+ if (!importer) return null;
619
+ if (!id.endsWith(".node")) return null;
620
+ const packageName = (await (0, local_pkg.getPackageInfo)(importer))?.packageJson?.name || id;
621
+ throw new _mastra_core_error.MastraBaseError({
622
+ id: "DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD",
623
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
624
+ category: _mastra_core_error.ErrorCategory.USER,
625
+ details: {
626
+ importFile: importer,
627
+ packageName
628
+ },
629
+ text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}.
630
+
631
+ Please consider adding \`${packageName}\` to your externals, or updating this import to not end with ".node".
632
+
633
+ export const mastra = new Mastra({
634
+ bundler: {
635
+ externals: ["${packageName}"],
636
+ }
637
+ })`
638
+ });
639
+ }
640
+ }
641
+ }
642
+ ].filter(Boolean);
643
+ }
644
+ /**
645
+ * Executes the Rollup build process for virtual dependencies using configured plugins.
646
+ * Bundles all virtual dependency modules into optimized ESM files with proper external handling.
647
+ */
648
+ async function buildExternalDependencies(virtualDependencies, { externals, packagesToTranspile, workspaceMap, rootDir, outputDir, bundlerOptions, platform }) {
649
+ /**
650
+ * If there are no virtual dependencies to bundle, return an empty array to avoid Rollup errors.
651
+ */
652
+ if (virtualDependencies.size === 0) return [];
653
+ const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
654
+ const plugins = await getInputPlugins(virtualDependencies, {
655
+ transpilePackages: packagesToTranspile,
656
+ workspaceMap,
657
+ bundlerOptions: { noBundling },
658
+ rootDir,
659
+ externals,
660
+ platform
661
+ });
662
+ const bundler = await (0, rollup.rollup)({
663
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
664
+ input: Array.from(virtualDependencies.entries()).reduce((acc, [dep, virtualDep]) => {
665
+ acc[virtualDep.name] = `#virtual-${dep}`;
666
+ return acc;
667
+ }, {}),
668
+ external: externals,
669
+ treeshake: noBundling ? false : "safest",
670
+ plugins
671
+ });
672
+ const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
673
+ const { output } = await bundler.write({
674
+ format: "esm",
675
+ dir: rootDir,
676
+ entryFileNames: "[name].mjs",
677
+ sourcemap: true,
678
+ /**
679
+ * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
680
+ * So we want to write them to the `.mastra/output` folder as well.
681
+ */
682
+ chunkFileNames: (chunkInfo) => {
683
+ /**
684
+ * This whole bunch of logic directly below is for the edge case shown in the e2e-tests/monorepo with "tinyrainbow" package. It's used in multiple places in the package and as such Rollup creates a shared chunk for it. During 'mastra dev' / with externals: true, we don't want that chunk to show up in the '.mastra/output' folder (outputDirRelative) but inside <pkg>/node_modules/.cache instead.
685
+ * We only care about this for the "noBundling" case!
686
+ */
687
+ if (noBundling) {
688
+ const importedFromPackages = /* @__PURE__ */ new Set();
689
+ for (const moduleId of chunkInfo.moduleIds) {
690
+ const normalized = require_utils.slash(moduleId);
691
+ for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
692
+ const location = require_utils.slash(pkgInfo.location);
693
+ if (normalized.startsWith(location)) {
694
+ importedFromPackages.add(pkgName);
695
+ break;
696
+ }
697
+ }
698
+ }
699
+ if (importedFromPackages.size > 1) throw new _mastra_core_error.MastraBaseError({
700
+ id: "DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK",
701
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
702
+ category: _mastra_core_error.ErrorCategory.USER,
703
+ details: {
704
+ chunkName: chunkInfo.name,
705
+ packages: JSON.stringify(Array.from(importedFromPackages))
706
+ },
707
+ text: `Please open an issue. We found a shared chunk "${chunkInfo.name}" used by multiple workspace packages: ${Array.from(importedFromPackages).join(", ")}.`
708
+ });
709
+ if (importedFromPackages.size === 1) {
710
+ const [pkgName] = importedFromPackages;
711
+ const workspaceLocation = workspaceMap.get(pkgName).location;
712
+ return prepareEntryFileName(require_utils.getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
713
+ }
714
+ }
715
+ return `${outputDirRelative}/[name].mjs`;
716
+ },
717
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
718
+ hoistTransitiveImports: false
719
+ });
720
+ await bundler.close();
721
+ return output;
722
+ }
723
+ /**
724
+ * Recursively searches through Rollup output chunks to find which module imports a specific external dependency.
725
+ * Used to build the module resolution map for proper external dependency tracking.
726
+ */
727
+ function findExternalImporter(module, external, allOutputs, visited = /* @__PURE__ */ new Set()) {
728
+ if (visited.has(module.fileName)) return null;
729
+ visited.add(module.fileName);
730
+ const capturedFiles = /* @__PURE__ */ new Set();
731
+ for (const id of [...module.imports, ...module.dynamicImports]) if (require_utils.isDependencyPartOfPackage(id, external)) return module;
732
+ else if (id.endsWith(".mjs")) capturedFiles.add(id);
733
+ for (const file of capturedFiles) {
734
+ const nextModule = allOutputs.find((o) => o.fileName === file);
735
+ if (nextModule) {
736
+ const importer = findExternalImporter(nextModule, external, allOutputs, visited);
737
+ if (importer) return importer;
738
+ }
739
+ }
740
+ return null;
741
+ }
742
+ /**
743
+ * Bundles vendor dependencies identified in the analysis step.
744
+ * Creates virtual modules for each dependency and bundles them using rollup.
745
+ *
746
+ * @param depsToOptimize - Map of dependencies to optimize with their metadata (exported bindings, rootPath, isWorkspace)
747
+ * @param outputDir - Directory where bundled files will be written
748
+ * @param logger - Logger instance for debugging
749
+ * @returns Object containing bundle output and reference map for validation
750
+ */
751
+ async function bundleExternals(depsToOptimize, outputDir, options) {
752
+ const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {}, platform = "node" } = options;
753
+ const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
754
+ /**
755
+ * A user can set `externals: true` to indicate they want to externalize all dependencies. In this case, we set `externalsPreset` to true to skip bundling any externals.
756
+ */
757
+ let externalsPreset = false;
758
+ if (customExternals === true) externalsPreset = true;
759
+ const externalsList = Array.isArray(customExternals) ? customExternals : [];
760
+ const allExternals = [
761
+ ...GLOBAL_EXTERNALS,
762
+ ...DEPRECATED_EXTERNALS,
763
+ ...externalsList
764
+ ];
765
+ const workspacePackagesNames = Array.from(workspaceMap.keys());
766
+ const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
767
+ /**
768
+ * When externals: true, we need to extract non-workspace deps from depsToOptimize
769
+ * and add them directly to usedExternals instead of bundling them.
770
+ */
771
+ const extractedExternals = /* @__PURE__ */ new Map();
772
+ if (externalsPreset) {
773
+ for (const [dep, metadata] of depsToOptimize.entries()) if (!metadata.isWorkspace) {
774
+ extractedExternals.set(dep, metadata.rootPath ?? dep);
775
+ depsToOptimize.delete(dep);
776
+ }
777
+ }
778
+ const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
779
+ workspaceRoot,
780
+ outputDir,
781
+ projectRoot,
782
+ bundlerOptions: {
783
+ isDev,
784
+ externalsPreset
785
+ }
786
+ });
787
+ const output = await buildExternalDependencies(optimizedDependencyEntries, {
788
+ externals: allExternals,
789
+ packagesToTranspile,
790
+ workspaceMap,
791
+ rootDir: workspaceRoot || projectRoot,
792
+ outputDir,
793
+ bundlerOptions: {
794
+ isDev,
795
+ externalsPreset
796
+ },
797
+ platform
798
+ });
799
+ const moduleResolveMap = /* @__PURE__ */ new Map();
800
+ const filteredChunks = output.filter((o) => o.type === "chunk");
801
+ for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of allExternals) {
802
+ if (DEPS_TO_IGNORE.includes(external)) continue;
803
+ const importer = findExternalImporter(o, external, filteredChunks);
804
+ if (importer) {
805
+ const fullPath = path.join(workspaceRoot || projectRoot, importer.fileName);
806
+ let innerMap = moduleResolveMap.get(fullPath);
807
+ if (!innerMap) {
808
+ innerMap = /* @__PURE__ */ new Map();
809
+ moduleResolveMap.set(fullPath, innerMap);
810
+ }
811
+ if (importer.moduleIds.length) innerMap.set(external, importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1]);
812
+ }
813
+ }
814
+ /**
815
+ * Convert moduleResolveMap to a plain object with prototype-less objects
816
+ */
817
+ const usedExternals = Object.create(null);
818
+ for (const [fullPath, innerMap] of moduleResolveMap) {
819
+ const innerObj = Object.create(null);
820
+ for (const [external, value] of innerMap) innerObj[external] = value;
821
+ usedExternals[fullPath] = innerObj;
822
+ }
823
+ /**
824
+ * When externals: true, add the extracted non-workspace deps to usedExternals
825
+ * using a synthetic entry path to track them.
826
+ */
827
+ if (extractedExternals.size > 0) {
828
+ const syntheticPath = path.join(workspaceRoot || projectRoot, "__externals__");
829
+ const externalsObj = Object.create(null);
830
+ for (const [dep, rootPath] of extractedExternals) externalsObj[dep] = rootPath;
831
+ usedExternals[syntheticPath] = externalsObj;
832
+ }
833
+ return {
834
+ output,
835
+ fileNameToDependencyMap,
836
+ usedExternals
837
+ };
838
+ }
839
+ //#endregion
840
+ //#region src/build/babel/check-config-export.ts
841
+ function checkConfigExport(result) {
842
+ const mastraVars = /* @__PURE__ */ new Set();
843
+ return { visitor: {
844
+ NewExpression(path) {
845
+ if (!_babel_core.types.isIdentifier(path.node.callee)) return;
846
+ const binding = path.scope.getBinding(path.node.callee.name);
847
+ if (binding?.path.isImportSpecifier() && _babel_core.types.isIdentifier(binding.path.node.imported, { name: "MastraFactory" })) result.projectType = "factory";
848
+ },
849
+ ExportNamedDeclaration(path) {
850
+ const decl = path.node.declaration;
851
+ if (_babel_core.types.isVariableDeclaration(decl)) {
852
+ const varDecl = decl.declarations[0];
853
+ if (_babel_core.types.isIdentifier(varDecl?.id, { name: "mastra" }) && _babel_core.types.isNewExpression(varDecl.init) && _babel_core.types.isIdentifier(varDecl.init.callee, { name: "Mastra" })) result.hasValidConfig = true;
854
+ }
855
+ /**
856
+ * 2) export { foo as mastra }
857
+ * 3) export { mastra }
858
+ * 4) export { mastra, foo }
859
+ */
860
+ if (Array.isArray(path.node.specifiers)) {
861
+ for (const spec of path.node.specifiers) if (_babel_core.types.isExportSpecifier(spec) && _babel_core.types.isIdentifier(spec.exported, { name: "mastra" }) && _babel_core.types.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) result.hasValidConfig = true;
862
+ }
863
+ },
864
+ VariableDeclaration(path) {
865
+ for (const decl of path.node.declarations) if (_babel_core.types.isIdentifier(decl.id) && _babel_core.types.isNewExpression(decl.init) && _babel_core.types.isIdentifier(decl.init.callee, { name: "Mastra" })) mastraVars.add(decl.id.name);
866
+ }
867
+ } };
868
+ }
869
+ //#endregion
870
+ //#region src/build/babel/detect-pino-transports.ts
871
+ /**
872
+ * Extract string value from a node (supports StringLiteral and TemplateLiteral without expressions)
873
+ */
874
+ function getStringValue(node) {
875
+ if (!node) return null;
876
+ if (_babel_core.types.isStringLiteral(node)) return node.value;
877
+ if (_babel_core.types.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) return node.quasis[0]?.value.cooked ?? null;
878
+ return null;
879
+ }
880
+ /**
881
+ * Extract target value from an object property
882
+ */
883
+ function extractTargetFromProperty(prop) {
884
+ if (!_babel_core.types.isObjectProperty(prop)) return null;
885
+ const key = prop.key;
886
+ if (_babel_core.types.isIdentifier(key, { name: "target" }) || _babel_core.types.isStringLiteral(key) && key.value === "target") return getStringValue(prop.value);
887
+ return null;
888
+ }
889
+ /**
890
+ * Check if a binding came from a pino import/require
891
+ */
892
+ function isBindingFromPino(path, identifierName) {
893
+ const binding = path.scope.getBinding(identifierName);
894
+ if (!binding) return identifierName === "pino";
895
+ const bindingPath = binding.path;
896
+ if (bindingPath.isImportDefaultSpecifier()) {
897
+ const importDecl = bindingPath.parentPath;
898
+ if (importDecl?.isImportDeclaration()) return importDecl.node.source.value === "pino";
899
+ }
900
+ if (bindingPath.isImportNamespaceSpecifier()) {
901
+ const importDecl = bindingPath.parentPath;
902
+ if (importDecl?.isImportDeclaration()) return importDecl.node.source.value === "pino";
903
+ }
904
+ if (bindingPath.isImportSpecifier()) {
905
+ const importDecl = bindingPath.parentPath;
906
+ if (importDecl?.isImportDeclaration() && importDecl.node.source.value === "pino") {
907
+ const imported = bindingPath.node.imported;
908
+ if (_babel_core.types.isIdentifier(imported) && imported.name === "default") return true;
909
+ if (_babel_core.types.isStringLiteral(imported) && imported.value === "default") return true;
910
+ }
911
+ return false;
912
+ }
913
+ if (bindingPath.isVariableDeclarator()) {
914
+ const init = bindingPath.node.init;
915
+ if (_babel_core.types.isCallExpression(init) && _babel_core.types.isIdentifier(init.callee, { name: "require" }) && init.arguments.length === 1 && _babel_core.types.isStringLiteral(init.arguments[0]) && init.arguments[0].value === "pino") return true;
916
+ }
917
+ return false;
918
+ }
919
+ /**
920
+ * Check if a call expression is a pino.transport() call using scope analysis
921
+ */
922
+ function isPinoTransportCall(path) {
923
+ const callee = path.node.callee;
924
+ if (!_babel_core.types.isMemberExpression(callee)) return false;
925
+ if (!_babel_core.types.isIdentifier(callee.property, { name: "transport" })) return false;
926
+ if (_babel_core.types.isIdentifier(callee.object)) return isBindingFromPino(path, callee.object.name);
927
+ if (_babel_core.types.isMemberExpression(callee.object) && _babel_core.types.isIdentifier(callee.object.object) && _babel_core.types.isIdentifier(callee.object.property, { name: "default" })) return isBindingFromPino(path, callee.object.object.name);
928
+ return false;
929
+ }
930
+ /**
931
+ * Extract transport targets from a pino.transport() argument
932
+ */
933
+ function extractTransportsFromArg(arg) {
934
+ const targets = [];
935
+ if (!_babel_core.types.isObjectExpression(arg)) return targets;
936
+ for (const prop of arg.properties) {
937
+ if (!_babel_core.types.isObjectProperty(prop)) continue;
938
+ const key = prop.key;
939
+ const keyName = _babel_core.types.isIdentifier(key) ? key.name : _babel_core.types.isStringLiteral(key) ? key.value : null;
940
+ if (keyName === "target") {
941
+ const value = getStringValue(prop.value);
942
+ if (value) targets.push(value);
943
+ } else if (keyName === "targets") {
944
+ if (_babel_core.types.isArrayExpression(prop.value)) {
945
+ for (const element of prop.value.elements) if (_babel_core.types.isObjectExpression(element)) for (const innerProp of element.properties) {
946
+ const targetValue = extractTargetFromProperty(innerProp);
947
+ if (targetValue) targets.push(targetValue);
948
+ }
949
+ }
950
+ }
951
+ }
952
+ return targets;
953
+ }
954
+ /**
955
+ * Babel plugin to detect pino transport targets in code.
956
+ * Matches patterns like:
957
+ * - pino.transport({ target: "package-name" })
958
+ * - pino.transport({ targets: [{ target: "package-name" }] })
959
+ * - variable.transport({ target: "..." }) where variable is assigned from pino import
960
+ *
961
+ * @param transports - Set to collect detected transport package names
962
+ * @returns Babel plugin object
963
+ */
964
+ function detectPinoTransports(transports) {
965
+ return {
966
+ name: "detect-pino-transports",
967
+ visitor: { CallExpression(path) {
968
+ if (!isPinoTransportCall(path)) return;
969
+ const firstArg = path.node.arguments[0];
970
+ if (firstArg && !_babel_core.types.isSpreadElement(firstArg)) for (const target of extractTransportsFromArg(firstArg)) transports.add(target);
971
+ } }
972
+ };
973
+ }
974
+ //#endregion
975
+ //#region src/build/analyze.ts
976
+ function preferDependencyInfo(existing, incoming) {
977
+ return {
978
+ version: incoming.version ?? existing?.version,
979
+ packageSpec: incoming.packageSpec ?? existing?.packageSpec
980
+ };
981
+ }
982
+ async function resolveDependencyInfo(dep, existing, parentPaths) {
983
+ if (existing?.version || existing?.packageSpec) return existing;
984
+ const packageName = require_utils.getPackageName(dep);
985
+ const packageNames = [...new Set([dep, packageName].filter(Boolean))];
986
+ for (const parentPath of parentPaths) for (const name of packageNames) {
987
+ const metadata = await require_bundler.getPackageMetadata(name, parentPath);
988
+ if (metadata.version || metadata.packageSpec) return preferDependencyInfo(existing, metadata);
989
+ }
990
+ for (const name of packageNames) {
991
+ const metadata = await require_bundler.getPackageMetadata(name);
992
+ if (metadata.version || metadata.packageSpec) return preferDependencyInfo(existing, metadata);
993
+ }
994
+ return existing ?? {};
995
+ }
996
+ function importerParentPaths(importerId, base) {
997
+ if (!importerId || importerId.startsWith("\0") || !(0, path.isAbsolute)(importerId)) return base;
998
+ return [.../* @__PURE__ */ new Set([importerId, ...base])];
999
+ }
1000
+ function getLastConcreteModuleId(moduleIds) {
1001
+ return moduleIds.findLast((id) => !id.startsWith("\0") && (0, path.isAbsolute)(id));
1002
+ }
1003
+ function throwExternalDependencyError({ errorId, moduleName, packageName, messagePrefix }) {
1004
+ throw new _mastra_core_error.MastraError({
1005
+ id: errorId,
1006
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
1007
+ category: _mastra_core_error.ErrorCategory.USER,
1008
+ details: {
1009
+ importFile: moduleName,
1010
+ packageName
1011
+ },
1012
+ text: `${messagePrefix} \`${packageName}\` to your externals.
1013
+
1014
+ export const mastra = new Mastra({
1015
+ bundler: {
1016
+ externals: ["${packageName}"],
1017
+ }
1018
+ })`
1019
+ });
1020
+ }
1021
+ function getPackageNameFromBundledModuleName(moduleName) {
1022
+ if (moduleName.includes("__")) return moduleName.replaceAll("__", "/");
1023
+ const chunks = moduleName.split("-");
1024
+ if (!chunks.length) return moduleName;
1025
+ if (chunks[0]?.startsWith("@")) return chunks.slice(0, 2).join("/");
1026
+ return chunks[0];
1027
+ }
1028
+ function validateError(err, file, { binaryMapData, workspaceMap }) {
1029
+ let moduleName = null;
1030
+ let errorConfig = null;
1031
+ if (err instanceof ValidationError) {
1032
+ const parsedStack = import_stack_trace_parser_cjs.parse(err.stack);
1033
+ if (err.type === "TypeError") {
1034
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1035
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1036
+ if (stacktraceFrame) moduleName = stacktraceFrame.file.match(pkgNameRegex)?.[1] ?? getPackageNameFromBundledModuleName((0, path.basename)(file.name));
1037
+ else moduleName = getPackageNameFromBundledModuleName((0, path.basename)(file.name));
1038
+ errorConfig = {
1039
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1040
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1041
+ };
1042
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1043
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1044
+ const parentModuleName = getPackageNameFromBundledModuleName((0, path.basename)(file.name));
1045
+ errorConfig = {
1046
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1047
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1048
+ };
1049
+ if (moduleName === parentModuleName) return;
1050
+ }
1051
+ }
1052
+ if (err.message.includes("No native build was found")) {
1053
+ const pkgName = getPackageNameFromBundledModuleName((0, path.basename)(file.name));
1054
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1055
+ errorConfig = {
1056
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1057
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1058
+ };
1059
+ }
1060
+ if (moduleName && workspaceMap.has(moduleName)) throw new _mastra_core_error.MastraError({
1061
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1062
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
1063
+ category: _mastra_core_error.ErrorCategory.USER,
1064
+ details: { packageName: moduleName },
1065
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1066
+ Error: ${err.stack}`
1067
+ });
1068
+ if (errorConfig && moduleName) throwExternalDependencyError({
1069
+ errorId: errorConfig.id,
1070
+ moduleName,
1071
+ packageName: moduleName,
1072
+ messagePrefix: errorConfig.messagePrefix
1073
+ });
1074
+ }
1075
+ async function validateFile(root, file, { binaryMapData, moduleResolveMapLocation, logger, workspaceMap, stubbedExternals }) {
1076
+ try {
1077
+ if (!file.isDynamicEntry && file.isEntry) await validate((0, path.join)(root, file.fileName), {
1078
+ moduleResolveMapLocation,
1079
+ injectESMShim: false,
1080
+ stubbedExternals
1081
+ });
1082
+ } catch (err) {
1083
+ let errorToHandle = err;
1084
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) try {
1085
+ await validate((0, path.join)(root, file.fileName), {
1086
+ moduleResolveMapLocation,
1087
+ injectESMShim: true,
1088
+ stubbedExternals
1089
+ });
1090
+ errorToHandle = null;
1091
+ } catch (err) {
1092
+ errorToHandle = err;
1093
+ }
1094
+ if (errorToHandle instanceof Error) validateError(errorToHandle, file, {
1095
+ binaryMapData,
1096
+ logger,
1097
+ workspaceMap
1098
+ });
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Validates the bundled output by attempting to import each generated module.
1103
+ * Tracks external dependencies that couldn't be bundled.
1104
+ *
1105
+ * @param output - Bundle output from rollup
1106
+ * @param reverseVirtualReferenceMap - Map to resolve virtual module names back to original deps
1107
+ * @param outputDir - Directory containing the bundled files
1108
+ * @param logger - Logger instance for debugging
1109
+ * @param workspaceMap - Map of workspace packages that gets directly passed through for later consumption
1110
+ * @returns Analysis result containing dependency mappings
1111
+ */
1112
+ async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals, outputDir, projectRoot, workspaceMap, depsVersionInfo }, logger) {
1113
+ const result = {
1114
+ dependencies: /* @__PURE__ */ new Map(),
1115
+ externalDependencies: /* @__PURE__ */ new Map(),
1116
+ workspaceMap
1117
+ };
1118
+ const externalMetadataParentPaths = [projectRoot, ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)];
1119
+ for (const deps of Object.values(usedExternals)) for (const [dep, importerId] of Object.entries(deps)) {
1120
+ if (require_utils.isExternalProtocolImport(dep)) continue;
1121
+ const pkgName = require_utils.getPackageName(dep);
1122
+ if (pkgName) {
1123
+ const dependencyInfo = await resolveDependencyInfo(dep, depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName), importerParentPaths(importerId, externalMetadataParentPaths));
1124
+ result.externalDependencies.set(pkgName, preferDependencyInfo(result.externalDependencies.get(pkgName), dependencyInfo));
1125
+ }
1126
+ }
1127
+ let binaryMapData = {};
1128
+ if ((0, fs.existsSync)((0, path.join)(outputDir, "binary-map.json"))) {
1129
+ const binaryMap = await (0, fs_promises.readFile)((0, path.join)(outputDir, "binary-map.json"), "utf-8");
1130
+ binaryMapData = JSON.parse(binaryMap);
1131
+ }
1132
+ for (const file of output) {
1133
+ if (file.type === "asset") continue;
1134
+ logger.debug("Validating module", { fileName: file.fileName });
1135
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1136
+ await validateFile(projectRoot, file, {
1137
+ binaryMapData,
1138
+ moduleResolveMapLocation: (0, path.join)(outputDir, "module-resolve-map.json"),
1139
+ logger,
1140
+ workspaceMap,
1141
+ stubbedExternals: [...GLOBAL_EXTERNALS, ...DEPS_TO_IGNORE]
1142
+ });
1143
+ }
1144
+ return result;
1145
+ }
1146
+ /**
1147
+ * Main bundle analysis function that orchestrates the three-step process:
1148
+ * 1. Analyze dependencies
1149
+ * 2. Bundle dependencies modules
1150
+ * 3. Validate generated bundles
1151
+ *
1152
+ * This helps identify which dependencies need to be externalized vs bundled.
1153
+ */
1154
+ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, platform, isDev = false, bundlerOptions }, logger) {
1155
+ const mastraConfig = await (0, fs_promises.readFile)(mastraEntry, "utf-8");
1156
+ const mastraConfigResult = { hasValidConfig: false };
1157
+ await (0, _babel_core.transformAsync)(mastraConfig, {
1158
+ filename: mastraEntry,
1159
+ presets: [{}.resolve("@babel/preset-typescript")],
1160
+ plugins: [() => checkConfigExport(mastraConfigResult)]
1161
+ });
1162
+ if (!mastraConfigResult.hasValidConfig) logger.warn("Invalid Mastra config", { details: "Please make sure that your entry file looks like this:\nexport const mastra = new Mastra({\n // your options\n})\n\nIf you think your configuration is valid, please open an issue." });
1163
+ const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1164
+ let externalsPreset = false;
1165
+ const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1166
+ const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];
1167
+ if (bundlerOptions?.externals === true) externalsPreset = true;
1168
+ let index = 0;
1169
+ const depsToOptimize = /* @__PURE__ */ new Map();
1170
+ const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1171
+ const detectedPinoTransports = /* @__PURE__ */ new Set();
1172
+ logger.info("Analyzing dependencies...");
1173
+ const allUsedExternals = /* @__PURE__ */ new Map();
1174
+ const analyzeCache = /* @__PURE__ */ new Map();
1175
+ for (const entry of entries) {
1176
+ const analyzeResult = await analyzeEntry({
1177
+ entry,
1178
+ isVirtualFile: entry.includes("\n") || !(0, fs.existsSync)(entry)
1179
+ }, mastraEntry, {
1180
+ logger,
1181
+ sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1182
+ workspaceMap,
1183
+ projectRoot,
1184
+ shouldCheckTransitiveDependencies: true,
1185
+ analyzeCache
1186
+ });
1187
+ (0, _babel_core.transformSync)(analyzeResult.output.code, {
1188
+ filename: "pino-detection.js",
1189
+ plugins: [() => detectPinoTransports(detectedPinoTransports)],
1190
+ configFile: false,
1191
+ babelrc: false,
1192
+ code: false
1193
+ });
1194
+ await (0, fs_promises.writeFile)((0, path.join)(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1195
+ for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1196
+ if (allExternals.some((external) => require_utils.isDependencyPartOfPackage(dep, external)) || externalsPreset && !metadata.isWorkspace) {
1197
+ const pkgName = require_utils.getPackageName(dep);
1198
+ if (pkgName) allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));
1199
+ continue;
1200
+ }
1201
+ if (depsToOptimize.has(dep)) {
1202
+ const existingEntry = depsToOptimize.get(dep);
1203
+ depsToOptimize.set(dep, {
1204
+ ...existingEntry,
1205
+ version: metadata.version ?? existingEntry.version,
1206
+ packageSpec: metadata.packageSpec ?? existingEntry.packageSpec,
1207
+ exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])]
1208
+ });
1209
+ } else depsToOptimize.set(dep, metadata);
1210
+ }
1211
+ }
1212
+ const depsVersionInfo = /* @__PURE__ */ new Map();
1213
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1214
+ const pkgName = require_utils.getPackageName(dep);
1215
+ if (pkgName && (metadata.version || metadata.packageSpec)) depsVersionInfo.set(pkgName, preferDependencyInfo(depsVersionInfo.get(pkgName), metadata));
1216
+ if (metadata.version || metadata.packageSpec) depsVersionInfo.set(dep, preferDependencyInfo(depsVersionInfo.get(dep), metadata));
1217
+ }
1218
+ /**
1219
+ * Only during `mastra dev` we want to optimize workspace packages. In previous steps we might have added dependencies that are not workspace packages, so we gotta remove them again.
1220
+ */
1221
+ if (isDev || externalsPreset) {
1222
+ for (const [dep, metadata] of depsToOptimize.entries()) if (!metadata.isWorkspace) depsToOptimize.delete(dep);
1223
+ }
1224
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1225
+ logger.info("Optimizing dependencies...");
1226
+ logger.debug("Sorted dependencies", { deps: sortedDeps });
1227
+ const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1228
+ bundlerOptions: {
1229
+ ...bundlerOptions,
1230
+ externals: bundlerOptions?.externals ?? allExternals,
1231
+ isDev
1232
+ },
1233
+ projectRoot,
1234
+ workspaceRoot,
1235
+ workspaceMap,
1236
+ platform
1237
+ });
1238
+ const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map((pkgInfo) => require_utils.slash((0, path.relative)(workspaceRoot || projectRoot, pkgInfo.location)));
1239
+ for (const o of output) {
1240
+ if (o.type === "asset") continue;
1241
+ const importerId = getLastConcreteModuleId(o.moduleIds);
1242
+ for (const i of o.imports) {
1243
+ if (require_utils.isBuiltinModule(i)) continue;
1244
+ if (i.startsWith(".") || i.startsWith("/")) continue;
1245
+ if (!require_utils.isBareModuleSpecifier(i) || require_utils.isExternalProtocolImport(i)) continue;
1246
+ if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) continue;
1247
+ const pkgName = require_utils.getPackageName(i);
1248
+ if (pkgName && workspaceMap.has(pkgName)) continue;
1249
+ if (pkgName) {
1250
+ const dependencyInfo = await resolveDependencyInfo(i, depsVersionInfo.get(i) || depsVersionInfo.get(pkgName), importerParentPaths(importerId, [projectRoot, ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)]));
1251
+ allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), dependencyInfo));
1252
+ }
1253
+ }
1254
+ }
1255
+ const result = await validateOutput({
1256
+ output,
1257
+ reverseVirtualReferenceMap: fileNameToDependencyMap,
1258
+ usedExternals,
1259
+ outputDir,
1260
+ projectRoot: workspaceRoot || projectRoot,
1261
+ workspaceMap,
1262
+ depsVersionInfo
1263
+ }, logger);
1264
+ /**
1265
+ * Build the final set of external dependencies from four sources:
1266
+ * 1. result.externalDependencies - externals discovered during bundle validation
1267
+ * 2. allUsedExternals - packages detected via static analysis that matched the externals config
1268
+ * 3. detectedPinoTransports - pino transports detected by the plugin during bundling
1269
+ * 4. userDynamicPackages - user-specified packages loaded dynamically at runtime
1270
+ *
1271
+ * Prefer entries with version info over entries without
1272
+ */
1273
+ const mergedExternalDeps = new Map(result.externalDependencies);
1274
+ for (const [dep, info] of allUsedExternals) {
1275
+ if (require_utils.isExternalProtocolImport(dep)) continue;
1276
+ mergedExternalDeps.set(dep, preferDependencyInfo(mergedExternalDeps.get(dep), info));
1277
+ }
1278
+ const externalMetadataParentPaths = [
1279
+ projectRoot,
1280
+ ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location),
1281
+ __dirname
1282
+ ];
1283
+ for (const [dep, info] of mergedExternalDeps) if (!info.version && !info.packageSpec) mergedExternalDeps.set(dep, await resolveDependencyInfo(dep, info, externalMetadataParentPaths));
1284
+ for (const transport of detectedPinoTransports) if (!mergedExternalDeps.has(transport)) mergedExternalDeps.set(transport, await resolveDependencyInfo(transport, void 0, externalMetadataParentPaths));
1285
+ for (const pkg of userDynamicPackages) if (!mergedExternalDeps.has(pkg)) mergedExternalDeps.set(pkg, await resolveDependencyInfo(pkg, void 0, externalMetadataParentPaths));
1286
+ return {
1287
+ ...result,
1288
+ externalDependencies: mergedExternalDeps,
1289
+ ...mastraConfigResult.projectType ? { projectType: mastraConfigResult.projectType } : {}
1290
+ };
1291
+ }
1292
+ //#endregion
1293
+ Object.defineProperty(exports, "aliasHono", {
1294
+ enumerable: true,
1295
+ get: function() {
1296
+ return aliasHono;
1297
+ }
1298
+ });
1299
+ Object.defineProperty(exports, "analyzeBundle", {
1300
+ enumerable: true,
1301
+ get: function() {
1302
+ return analyzeBundle;
1303
+ }
1304
+ });
1305
+ Object.defineProperty(exports, "checkConfigExport", {
1306
+ enumerable: true,
1307
+ get: function() {
1308
+ return checkConfigExport;
1309
+ }
1310
+ });
1311
+ Object.defineProperty(exports, "getWorkspaceInformation", {
1312
+ enumerable: true,
1313
+ get: function() {
1314
+ return getWorkspaceInformation;
1315
+ }
1316
+ });
1317
+
1318
+ //# sourceMappingURL=analyze-DhDZW9TS.cjs.map