@mastra/deployer 0.24.7-alpha.1 → 0.24.7-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  3. package/dist/build/analyze.cjs +2 -2
  4. package/dist/build/analyze.d.ts +1 -1
  5. package/dist/build/analyze.d.ts.map +1 -1
  6. package/dist/build/analyze.js +1 -1
  7. package/dist/build/bundler.cjs +3 -3
  8. package/dist/build/bundler.d.ts.map +1 -1
  9. package/dist/build/bundler.js +1 -1
  10. package/dist/build/index.cjs +12 -12
  11. package/dist/build/index.js +4 -4
  12. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  13. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  14. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  15. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  16. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  17. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  18. package/dist/build/utils.d.ts +1 -0
  19. package/dist/build/utils.d.ts.map +1 -1
  20. package/dist/bundler/index.cjs +2 -2
  21. package/dist/bundler/index.d.ts +1 -1
  22. package/dist/bundler/index.js +1 -1
  23. package/dist/{chunk-K7JCMIZW.cjs → chunk-35IO74UA.cjs} +17 -16
  24. package/dist/chunk-35IO74UA.cjs.map +1 -0
  25. package/dist/chunk-3GJSIS6L.cjs +69 -0
  26. package/dist/chunk-3GJSIS6L.cjs.map +1 -0
  27. package/dist/{chunk-MYLM6HSI.js → chunk-4UJPXE65.js} +5 -4
  28. package/dist/chunk-4UJPXE65.js.map +1 -0
  29. package/dist/{chunk-UWCXK7X6.cjs → chunk-AG6GOBBO.cjs} +15 -14
  30. package/dist/chunk-AG6GOBBO.cjs.map +1 -0
  31. package/dist/{chunk-KEU3VV3H.js → chunk-DFJK4OKW.js} +3 -3
  32. package/dist/{chunk-KEU3VV3H.js.map → chunk-DFJK4OKW.js.map} +1 -1
  33. package/dist/{chunk-KLIBX4WB.js → chunk-G4OG2LG5.js} +6 -5
  34. package/dist/chunk-G4OG2LG5.js.map +1 -0
  35. package/dist/{chunk-7VIDVYTY.js → chunk-GWACJ2WL.js} +6 -14
  36. package/dist/chunk-GWACJ2WL.js.map +1 -0
  37. package/dist/{chunk-FHZKTDSF.cjs → chunk-M2JPS7OF.cjs} +5 -5
  38. package/dist/{chunk-FHZKTDSF.cjs.map → chunk-M2JPS7OF.cjs.map} +1 -1
  39. package/dist/chunk-NEGQTTJS.js +62 -0
  40. package/dist/chunk-NEGQTTJS.js.map +1 -0
  41. package/dist/{chunk-53B6GOCH.cjs → chunk-SKDU2LXD.cjs} +13 -21
  42. package/dist/chunk-SKDU2LXD.cjs.map +1 -0
  43. package/dist/{chunk-PHZK4P6J.js → chunk-TDUDRKXR.js} +417 -143
  44. package/dist/chunk-TDUDRKXR.js.map +1 -0
  45. package/dist/{chunk-6R73ZVZX.cjs → chunk-UB6E4QPC.cjs} +430 -158
  46. package/dist/chunk-UB6E4QPC.cjs.map +1 -0
  47. package/dist/index.cjs +5 -5
  48. package/dist/index.js +2 -2
  49. package/dist/server/handlers/routes/scores/handlers.d.ts +4 -0
  50. package/dist/server/handlers/routes/scores/handlers.d.ts.map +1 -1
  51. package/dist/validator/custom-resolver.cjs +20 -12
  52. package/dist/validator/custom-resolver.cjs.map +1 -1
  53. package/dist/validator/custom-resolver.d.ts.map +1 -1
  54. package/dist/validator/custom-resolver.js +18 -10
  55. package/dist/validator/custom-resolver.js.map +1 -1
  56. package/dist/validator/validate.d.ts +15 -1
  57. package/dist/validator/validate.d.ts.map +1 -1
  58. package/package.json +6 -7
  59. package/dist/chunk-53B6GOCH.cjs.map +0 -1
  60. package/dist/chunk-6R73ZVZX.cjs.map +0 -1
  61. package/dist/chunk-7VIDVYTY.js.map +0 -1
  62. package/dist/chunk-K7JCMIZW.cjs.map +0 -1
  63. package/dist/chunk-KLIBX4WB.js.map +0 -1
  64. package/dist/chunk-MYLM6HSI.js.map +0 -1
  65. package/dist/chunk-PHZK4P6J.js.map +0 -1
  66. package/dist/chunk-UWCXK7X6.cjs.map +0 -1
@@ -1,12 +1,11 @@
1
+ import { slash, isDependencyPartOfPackage, getPackageRootPath, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-NEGQTTJS.js';
1
2
  import * as babel from '@babel/core';
2
3
  import babel__default from '@babel/core';
3
4
  import fs, { existsSync } from 'fs';
4
5
  import { readFile, writeFile } from 'fs/promises';
5
6
  import * as path2 from 'path';
6
- import path2__default, { dirname, join, normalize, relative, basename as basename$1 } from 'path';
7
+ import path2__default, { dirname, join, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
- import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { rollup } from 'rollup';
11
10
  import originalEsbuild from 'rollup-plugin-esbuild';
12
11
  import commonjs from '@rollup/plugin-commonjs';
@@ -18,90 +17,27 @@ import * as pkg from 'empathic/package';
18
17
  import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
19
18
  import { noopLogger } from '@mastra/core/logger';
20
19
  import virtual from '@rollup/plugin-virtual';
20
+ import { fileURLToPath, pathToFileURL } from 'url';
21
21
  import { builtinModules } from 'module';
22
22
  import nodeResolve from '@rollup/plugin-node-resolve';
23
23
  import originalEsmShim from '@rollup/plugin-esm-shim';
24
24
  import { basename } from 'path/posix';
25
25
  import * as resolve from 'resolve.exports';
26
+ import { getPackageInfo } from 'local-pkg';
26
27
  import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
27
28
 
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("/");
29
+ var ValidationError = class extends Error {
30
+ type;
31
+ stack;
32
+ constructor(args) {
33
+ super(args.message);
34
+ this.type = args.type;
35
+ this.stack = args.stack;
33
36
  }
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
37
+ };
103
38
  function spawn(command, args = [], options = {}) {
104
39
  return new Promise((resolve2, reject) => {
40
+ let validationError = null;
105
41
  const childProcess = spawn$1(command, args, {
106
42
  // stdio: 'inherit',
107
43
  ...options
@@ -111,28 +47,63 @@ function spawn(command, args = [], options = {}) {
111
47
  });
112
48
  let stderr = "";
113
49
  childProcess.stderr?.on("data", (message) => {
114
- stderr += message;
50
+ try {
51
+ validationError = JSON.parse(message.toString());
52
+ } catch {
53
+ stderr += message;
54
+ }
115
55
  });
116
56
  childProcess.on("close", (code) => {
117
57
  if (code === 0) {
118
58
  resolve2();
119
59
  } else {
120
- reject(new Error(stderr));
60
+ if (validationError) {
61
+ reject(new ValidationError(validationError));
62
+ } else {
63
+ reject(new Error(stderr));
64
+ }
121
65
  }
122
66
  });
123
67
  });
124
68
  }
125
- function validate(file) {
69
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
70
+ let prefixCode = "";
71
+ if (injectESMShim) {
72
+ prefixCode = `import { fileURLToPath } from 'url';
73
+ import { dirname } from 'path';
74
+
75
+ globalThis.__filename = fileURLToPath(import.meta.url);
76
+ globalThis.__dirname = dirname(__filename);
77
+ `;
78
+ }
79
+ function errorHandler(err) {
80
+ console.error(
81
+ JSON.stringify({
82
+ type: err.name,
83
+ message: err.message,
84
+ stack: err.stack
85
+ })
86
+ );
87
+ process.exit(1);
88
+ }
126
89
  return spawn(
127
- "node",
90
+ process.execPath,
128
91
  [
129
92
  "--import",
130
93
  import.meta.resolve("@mastra/deployer/loader"),
131
94
  "--input-type=module",
95
+ "--enable-source-maps",
132
96
  "-e",
133
- `import('file://${slash(file)}')`
97
+ `${prefixCode};import('file://${slash(file)}').catch(err => {
98
+ ${errorHandler.toString()}
99
+ errorHandler(err);
100
+ })`.replaceAll(/\n/g, "")
134
101
  ],
135
102
  {
103
+ env: {
104
+ ...process.env,
105
+ MODULE_MAP: `${moduleResolveMapLocation}`
106
+ },
136
107
  cwd: dirname(file)
137
108
  }
138
109
  );
@@ -897,6 +868,114 @@ function aliasHono() {
897
868
  }
898
869
  };
899
870
  }
871
+
872
+ // src/build/plugins/subpath-externals-resolver.ts
873
+ function subpathExternalsResolver(externals) {
874
+ return {
875
+ name: "subpath-externals-resolver",
876
+ resolveId(id) {
877
+ if (id.startsWith(".") || id.startsWith("/")) {
878
+ return null;
879
+ }
880
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
881
+ if (isPartOfExternals) {
882
+ return {
883
+ id,
884
+ external: true
885
+ };
886
+ }
887
+ }
888
+ };
889
+ }
890
+ function nodeGypDetector() {
891
+ const modulesToTrack = /* @__PURE__ */ new Set();
892
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
893
+ return {
894
+ name: "node-gyp-build-detector",
895
+ moduleParsed(info) {
896
+ if (!info.meta?.commonjs?.requires?.length) {
897
+ return;
898
+ }
899
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
900
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
901
+ );
902
+ if (!hasNodeGypBuild) {
903
+ return;
904
+ }
905
+ modulesToTrack.add(info.id);
906
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
907
+ },
908
+ async generateBundle(options, bundle) {
909
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
910
+ for (const [fileName, chunk] of Object.entries(bundle)) {
911
+ if (chunk.type === "chunk") {
912
+ for (const moduleId of chunk.moduleIds) {
913
+ if (modulesToTrackPackageInfo.has(moduleId)) {
914
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
915
+ if (!binaryMapByChunk.has(fileName)) {
916
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
917
+ }
918
+ if (pkgInfo?.packageJson?.name) {
919
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
920
+ }
921
+ }
922
+ }
923
+ }
924
+ }
925
+ const binaryMapJson = Object.fromEntries(
926
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
927
+ );
928
+ this.emitFile({
929
+ type: "asset",
930
+ name: "binary-map.json",
931
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
932
+ });
933
+ }
934
+ };
935
+ }
936
+ function moduleResolveMap(externals, projectRoot) {
937
+ const importMap = /* @__PURE__ */ new Map();
938
+ return {
939
+ name: "module-resolve-map",
940
+ moduleParsed(info) {
941
+ if (info.importedIds.length === 0 || !info.id) {
942
+ return;
943
+ }
944
+ for (const importedId of info.importedIds) {
945
+ for (const external of externals) {
946
+ if (isDependencyPartOfPackage(importedId, external)) {
947
+ importMap.set(external, info.id);
948
+ }
949
+ }
950
+ }
951
+ },
952
+ async generateBundle(options, bundle) {
953
+ const resolveMap = /* @__PURE__ */ new Map();
954
+ for (const [fileName, chunk] of Object.entries(bundle)) {
955
+ if (chunk.type === "chunk") {
956
+ for (const [external, resolvedFrom] of importMap) {
957
+ if (chunk.moduleIds.includes(resolvedFrom)) {
958
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
959
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
960
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
961
+ resolveMap.set(fullPath, innerMap);
962
+ }
963
+ }
964
+ }
965
+ }
966
+ const resolveMapJson = Object.fromEntries(
967
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
968
+ );
969
+ this.emitFile({
970
+ type: "asset",
971
+ name: "module-resolve-map.json",
972
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
973
+ });
974
+ }
975
+ };
976
+ }
977
+
978
+ // src/build/analyze/bundleExternals.ts
900
979
  function prepareEntryFileName(name, rootDir) {
901
980
  return rollupSafeName(name, rootDir);
902
981
  }
@@ -962,7 +1041,8 @@ async function getInputPlugins2(virtualDependencies, {
962
1041
  transpilePackages,
963
1042
  workspaceMap,
964
1043
  bundlerOptions,
965
- rootDir
1044
+ rootDir,
1045
+ externals
966
1046
  }) {
967
1047
  const transpilePackagesMap = /* @__PURE__ */ new Map();
968
1048
  for (const pkg2 of transpilePackages) {
@@ -983,6 +1063,7 @@ async function getInputPlugins2(virtualDependencies, {
983
1063
  {}
984
1064
  )
985
1065
  ),
1066
+ subpathExternalsResolver(externals),
986
1067
  transpilePackagesMap.size ? esbuild({
987
1068
  format: "esm",
988
1069
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -1011,7 +1092,8 @@ async function getInputPlugins2(virtualDependencies, {
1011
1092
  if (!resolvedPath) {
1012
1093
  resolvedPath = pkgJson.main ?? "index.js";
1013
1094
  }
1014
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1095
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1096
+ return resolved;
1015
1097
  }
1016
1098
  } : null,
1017
1099
  optimizeLodashImports({
@@ -1030,6 +1112,8 @@ async function getInputPlugins2(virtualDependencies, {
1030
1112
  // hono is imported from deployer, so we need to resolve from here instead of the project root
1031
1113
  aliasHono(),
1032
1114
  json(),
1115
+ nodeGypDetector(),
1116
+ moduleResolveMap(externals, rootDir),
1033
1117
  {
1034
1118
  name: "not-found-resolver",
1035
1119
  resolveId: {
@@ -1087,12 +1171,13 @@ async function buildExternalDependencies(virtualDependencies, {
1087
1171
  {}
1088
1172
  ),
1089
1173
  external: externals,
1090
- treeshake: "safest",
1174
+ treeshake: bundlerOptions.isDev ? false : "safest",
1091
1175
  plugins: getInputPlugins2(virtualDependencies, {
1092
1176
  transpilePackages: packagesToTranspile,
1093
1177
  workspaceMap,
1094
1178
  bundlerOptions,
1095
- rootDir
1179
+ rootDir,
1180
+ externals
1096
1181
  })
1097
1182
  });
1098
1183
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1100,6 +1185,8 @@ async function buildExternalDependencies(virtualDependencies, {
1100
1185
  format: "esm",
1101
1186
  dir: rootDir,
1102
1187
  entryFileNames: "[name].mjs",
1188
+ // used to get the filename of the actual error
1189
+ sourcemap: true,
1103
1190
  /**
1104
1191
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1105
1192
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1137,6 +1224,7 @@ async function buildExternalDependencies(virtualDependencies, {
1137
1224
  }
1138
1225
  return `${outputDirRelative}/[name].mjs`;
1139
1226
  },
1227
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1140
1228
  hoistTransitiveImports: false
1141
1229
  });
1142
1230
  await bundler.close();
@@ -1145,7 +1233,7 @@ async function buildExternalDependencies(virtualDependencies, {
1145
1233
  function findExternalImporter(module, external, allOutputs) {
1146
1234
  const capturedFiles = /* @__PURE__ */ new Set();
1147
1235
  for (const id of module.imports) {
1148
- if (id === external) {
1236
+ if (isDependencyPartOfPackage(id, external)) {
1149
1237
  return module;
1150
1238
  } else {
1151
1239
  if (id.endsWith(".mjs")) {
@@ -1191,7 +1279,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1191
1279
  isDev
1192
1280
  }
1193
1281
  });
1194
- const moduleResolveMap = /* @__PURE__ */ new Map();
1282
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1195
1283
  const filteredChunks = output.filter((o) => o.type === "chunk");
1196
1284
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1197
1285
  for (const external of allExternals) {
@@ -1201,10 +1289,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1201
1289
  const importer = findExternalImporter(o, external, filteredChunks);
1202
1290
  if (importer) {
1203
1291
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1204
- let innerMap = moduleResolveMap.get(fullPath);
1292
+ let innerMap = moduleResolveMap2.get(fullPath);
1205
1293
  if (!innerMap) {
1206
1294
  innerMap = /* @__PURE__ */ new Map();
1207
- moduleResolveMap.set(fullPath, innerMap);
1295
+ moduleResolveMap2.set(fullPath, innerMap);
1208
1296
  }
1209
1297
  if (importer.moduleIds.length) {
1210
1298
  innerMap.set(
@@ -1216,7 +1304,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1216
1304
  }
1217
1305
  }
1218
1306
  const usedExternals = /* @__PURE__ */ Object.create(null);
1219
- for (const [fullPath, innerMap] of moduleResolveMap) {
1307
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1220
1308
  const innerObj = /* @__PURE__ */ Object.create(null);
1221
1309
  for (const [external, value] of innerMap) {
1222
1310
  innerObj[external] = value;
@@ -1225,6 +1313,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1225
1313
  }
1226
1314
  return { output, fileNameToDependencyMap, usedExternals };
1227
1315
  }
1316
+
1317
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1318
+ var UNKNOWN_FUNCTION = "<unknown>";
1319
+ function parse(stackString) {
1320
+ var lines = stackString.split("\n");
1321
+ return lines.reduce(function(stack, line) {
1322
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1323
+ if (parseResult) {
1324
+ stack.push(parseResult);
1325
+ }
1326
+ return stack;
1327
+ }, []);
1328
+ }
1329
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1330
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1331
+ function parseChrome(line) {
1332
+ var parts = chromeRe.exec(line);
1333
+ if (!parts) {
1334
+ return null;
1335
+ }
1336
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1337
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1338
+ var submatch = chromeEvalRe.exec(parts[2]);
1339
+ if (isEval && submatch != null) {
1340
+ parts[2] = submatch[1];
1341
+ parts[3] = submatch[2];
1342
+ parts[4] = submatch[3];
1343
+ }
1344
+ return {
1345
+ file: !isNative ? parts[2] : null,
1346
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1347
+ arguments: isNative ? [parts[2]] : [],
1348
+ lineNumber: parts[3] ? +parts[3] : null,
1349
+ column: parts[4] ? +parts[4] : null
1350
+ };
1351
+ }
1352
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1353
+ function parseWinjs(line) {
1354
+ var parts = winjsRe.exec(line);
1355
+ if (!parts) {
1356
+ return null;
1357
+ }
1358
+ return {
1359
+ file: parts[2],
1360
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1361
+ arguments: [],
1362
+ lineNumber: +parts[3],
1363
+ column: parts[4] ? +parts[4] : null
1364
+ };
1365
+ }
1366
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1367
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1368
+ function parseGecko(line) {
1369
+ var parts = geckoRe.exec(line);
1370
+ if (!parts) {
1371
+ return null;
1372
+ }
1373
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1374
+ var submatch = geckoEvalRe.exec(parts[3]);
1375
+ if (isEval && submatch != null) {
1376
+ parts[3] = submatch[1];
1377
+ parts[4] = submatch[2];
1378
+ parts[5] = null;
1379
+ }
1380
+ return {
1381
+ file: parts[3],
1382
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1383
+ arguments: parts[2] ? parts[2].split(",") : [],
1384
+ lineNumber: parts[4] ? +parts[4] : null,
1385
+ column: parts[5] ? +parts[5] : null
1386
+ };
1387
+ }
1388
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1389
+ function parseJSC(line) {
1390
+ var parts = javaScriptCoreRe.exec(line);
1391
+ if (!parts) {
1392
+ return null;
1393
+ }
1394
+ return {
1395
+ file: parts[3],
1396
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1397
+ arguments: [],
1398
+ lineNumber: +parts[4],
1399
+ column: parts[5] ? +parts[5] : null
1400
+ };
1401
+ }
1402
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1403
+ function parseNode(line) {
1404
+ var parts = nodeRe.exec(line);
1405
+ if (!parts) {
1406
+ return null;
1407
+ }
1408
+ return {
1409
+ file: parts[2],
1410
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1411
+ arguments: [],
1412
+ lineNumber: +parts[3],
1413
+ column: parts[4] ? +parts[4] : null
1414
+ };
1415
+ }
1416
+
1417
+ // src/build/analyze.ts
1228
1418
  function throwExternalDependencyError({
1229
1419
  errorId,
1230
1420
  moduleName,
@@ -1248,6 +1438,110 @@ export const mastra = new Mastra({
1248
1438
  })`
1249
1439
  });
1250
1440
  }
1441
+ function getPackageNameFromBundledModuleName(moduleName) {
1442
+ const chunks = moduleName.split("-");
1443
+ if (!chunks.length) {
1444
+ return moduleName;
1445
+ }
1446
+ if (chunks[0]?.startsWith("@")) {
1447
+ return chunks.slice(0, 2).join("/");
1448
+ }
1449
+ return chunks[0];
1450
+ }
1451
+ function validateError(err, file, {
1452
+ binaryMapData,
1453
+ workspaceMap
1454
+ }) {
1455
+ let moduleName = null;
1456
+ let errorConfig = null;
1457
+ if (err instanceof ValidationError) {
1458
+ const parsedStack = parse(err.stack);
1459
+ if (err.type === "TypeError") {
1460
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1461
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1462
+ if (stacktraceFrame) {
1463
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1464
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1465
+ } else {
1466
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1467
+ }
1468
+ errorConfig = {
1469
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1470
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1471
+ };
1472
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1473
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1474
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1475
+ errorConfig = {
1476
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1477
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1478
+ };
1479
+ if (moduleName === parentModuleName) {
1480
+ return;
1481
+ }
1482
+ }
1483
+ }
1484
+ if (err.message.includes("No native build was found")) {
1485
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1486
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1487
+ errorConfig = {
1488
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1489
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1490
+ };
1491
+ }
1492
+ if (moduleName && workspaceMap.has(moduleName)) {
1493
+ throw new MastraError({
1494
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1495
+ domain: ErrorDomain.DEPLOYER,
1496
+ category: ErrorCategory.USER,
1497
+ details: {
1498
+ // importFile: moduleName,
1499
+ packageName: moduleName
1500
+ },
1501
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1502
+ Error: ${err.stack}`
1503
+ });
1504
+ }
1505
+ if (errorConfig && moduleName) {
1506
+ throwExternalDependencyError({
1507
+ errorId: errorConfig.id,
1508
+ moduleName,
1509
+ packageName: moduleName,
1510
+ messagePrefix: errorConfig.messagePrefix
1511
+ });
1512
+ }
1513
+ }
1514
+ async function validateFile(root, file, {
1515
+ binaryMapData,
1516
+ moduleResolveMapLocation,
1517
+ logger,
1518
+ workspaceMap
1519
+ }) {
1520
+ try {
1521
+ if (!file.isDynamicEntry && file.isEntry) {
1522
+ await validate(join(root, file.fileName), {
1523
+ moduleResolveMapLocation,
1524
+ injectESMShim: false
1525
+ });
1526
+ }
1527
+ } catch (err) {
1528
+ let errorToHandle = err;
1529
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1530
+ try {
1531
+ await validate(join(root, file.fileName), {
1532
+ moduleResolveMapLocation,
1533
+ injectESMShim: true
1534
+ });
1535
+ errorToHandle = null;
1536
+ } catch (err2) {
1537
+ errorToHandle = err2;
1538
+ }
1539
+ }
1540
+ if (errorToHandle instanceof Error) {
1541
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1542
+ }
1543
+ }
1544
+ }
1251
1545
  async function validateOutput({
1252
1546
  output,
1253
1547
  reverseVirtualReferenceMap,
@@ -1261,60 +1555,30 @@ async function validateOutput({
1261
1555
  externalDependencies: /* @__PURE__ */ new Set(),
1262
1556
  workspaceMap
1263
1557
  };
1264
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1265
1558
  for (const deps of Object.values(usedExternals)) {
1266
1559
  for (const dep of Object.keys(deps)) {
1267
1560
  result.externalDependencies.add(dep);
1268
1561
  }
1269
1562
  }
1563
+ let binaryMapData = {};
1564
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1565
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1566
+ binaryMapData = JSON.parse(binaryMap);
1567
+ }
1270
1568
  for (const file of output) {
1271
1569
  if (file.type === "asset") {
1272
1570
  continue;
1273
1571
  }
1274
- try {
1275
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1276
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1277
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1278
- }
1279
- if (!file.isDynamicEntry && file.isEntry) {
1280
- await validate(join(projectRoot, file.fileName));
1281
- }
1282
- } catch (err) {
1283
- if (err instanceof Error) {
1284
- let moduleName = null;
1285
- let errorConfig = null;
1286
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1287
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1288
- const fallbackName = file.name.split("/").pop();
1289
- moduleName = moduleIdName ?? fallbackName;
1290
- errorConfig = {
1291
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1292
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1293
- };
1294
- } else if (err.message.includes("Error: No native build was found for ")) {
1295
- moduleName = findNativePackageModule(file.moduleIds);
1296
- errorConfig = {
1297
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1298
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1299
- };
1300
- }
1301
- if (moduleName && errorConfig) {
1302
- const pkgInfo = await getPackageInfo(moduleName);
1303
- const packageName = pkgInfo?.packageJson?.name;
1304
- if (packageName) {
1305
- throwExternalDependencyError({
1306
- errorId: errorConfig.id,
1307
- moduleName,
1308
- packageName,
1309
- messagePrefix: errorConfig.messagePrefix
1310
- });
1311
- } else {
1312
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1313
- }
1314
- }
1315
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1316
- }
1572
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1573
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1574
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1317
1575
  }
1576
+ await validateFile(projectRoot, file, {
1577
+ binaryMapData,
1578
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1579
+ logger,
1580
+ workspaceMap
1581
+ });
1318
1582
  }
1319
1583
  return result;
1320
1584
  }
@@ -1346,7 +1610,10 @@ If you think your configuration is valid, please open an issue.`);
1346
1610
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1347
1611
  let index = 0;
1348
1612
  const depsToOptimize = /* @__PURE__ */ new Map();
1613
+ const { externals: customExternals = [] } = bundlerOptions || {};
1614
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1349
1615
  logger.info("Analyzing dependencies...");
1616
+ const allUsedExternals = /* @__PURE__ */ new Set();
1350
1617
  for (const entry of entries) {
1351
1618
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1352
1619
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
@@ -1358,6 +1625,11 @@ If you think your configuration is valid, please open an issue.`);
1358
1625
  });
1359
1626
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1360
1627
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1628
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1629
+ if (isPartOfExternals) {
1630
+ allUsedExternals.add(dep);
1631
+ continue;
1632
+ }
1361
1633
  if (depsToOptimize.has(dep)) {
1362
1634
  const existingEntry = depsToOptimize.get(dep);
1363
1635
  depsToOptimize.set(dep, {
@@ -1376,14 +1648,13 @@ If you think your configuration is valid, please open an issue.`);
1376
1648
  }
1377
1649
  }
1378
1650
  }
1379
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1651
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1380
1652
  logger.info("Optimizing dependencies...");
1381
- logger.debug(
1382
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1383
- );
1653
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1384
1654
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1385
1655
  bundlerOptions: {
1386
1656
  ...bundlerOptions,
1657
+ externals: allExternals,
1387
1658
  enableEsmShim,
1388
1659
  isDev
1389
1660
  },
@@ -1402,9 +1673,12 @@ If you think your configuration is valid, please open an issue.`);
1402
1673
  },
1403
1674
  logger
1404
1675
  );
1405
- return result;
1676
+ return {
1677
+ ...result,
1678
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1679
+ };
1406
1680
  }
1407
1681
 
1408
- export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getPackageName, getPackageRootPath, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, slash, tsConfigPaths };
1409
- //# sourceMappingURL=chunk-PHZK4P6J.js.map
1410
- //# sourceMappingURL=chunk-PHZK4P6J.js.map
1682
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1683
+ //# sourceMappingURL=chunk-TDUDRKXR.js.map
1684
+ //# sourceMappingURL=chunk-TDUDRKXR.js.map