@mastra/deployer 1.60.0-alpha.1 → 1.60.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.
- package/CHANGELOG.md +12 -0
- package/dist/{analyze-BIrkd7zx.cjs → analyze-B7YwN5Vu.cjs} +32 -28
- package/dist/analyze-B7YwN5Vu.cjs.map +1 -0
- package/dist/{analyze-CNv6Qdaz.js → analyze-DuO_fzJD.js} +27 -29
- package/dist/analyze-DuO_fzJD.js.map +1 -0
- package/dist/build/analyze/bundleExternals.d.ts +4 -3
- package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
- package/dist/build/analyze/externals.d.ts +6 -0
- package/dist/build/analyze/externals.d.ts.map +1 -0
- package/dist/build/analyze.cjs +1 -1
- package/dist/build/analyze.d.ts.map +1 -1
- package/dist/build/analyze.js +1 -1
- package/dist/build/index.cjs +3 -3
- package/dist/build/index.js +3 -3
- package/dist/build/plugins/workspace-deps-watcher.d.ts.map +1 -1
- package/dist/{build-kZfvpuh9.js → build-DRxeLZsS.js} +8 -6
- package/dist/build-DRxeLZsS.js.map +1 -0
- package/dist/{build-BERX35Pi.cjs → build-Dw0ynO5J.cjs} +8 -6
- package/dist/build-Dw0ynO5J.cjs.map +1 -0
- package/dist/bundler/index.cjs +3 -3
- package/dist/bundler/index.cjs.map +1 -1
- package/dist/bundler/index.d.ts.map +1 -1
- package/dist/bundler/index.js +3 -3
- package/dist/bundler/index.js.map +1 -1
- package/dist/deploy/log.d.ts.map +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/dist/services/deps.d.ts +1 -0
- package/dist/services/deps.d.ts.map +1 -1
- package/dist/services/index.cjs +1 -1
- package/dist/services/index.js +1 -1
- package/dist/{services-BRF1RRXB.js → services-DWdPwTiP.js} +49 -8
- package/dist/services-DWdPwTiP.js.map +1 -0
- package/dist/{services-_ksvysL5.cjs → services-DrT0fgoG.cjs} +49 -8
- package/dist/services-DrT0fgoG.cjs.map +1 -0
- package/package.json +8 -8
- package/dist/analyze-BIrkd7zx.cjs.map +0 -1
- package/dist/analyze-CNv6Qdaz.js.map +0 -1
- package/dist/build-BERX35Pi.cjs.map +0 -1
- package/dist/build-kZfvpuh9.js.map +0 -1
- package/dist/services-BRF1RRXB.js.map +0 -1
- package/dist/services-_ksvysL5.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @mastra/deployer
|
|
2
2
|
|
|
3
|
+
## 1.60.0-alpha.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed deployer analysis to use one deterministic external dependency set across analysis, bundling, and validation. Deprecated externals such as `nodemailer`, `jsdom`, `sqlite3`, and `fastembed` are now declared and installed as runtime dependencies instead of bundled. This can cause a one-time experiment-worker digest and build-key change for affected projects. ([#21483](https://github.com/mastra-ai/mastra/pull/21483))
|
|
8
|
+
|
|
9
|
+
- Improved pnpm build failures to name blocked dependencies and report the required allowBuilds configuration as a user error. ([#21488](https://github.com/mastra-ai/mastra/pull/21488))
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`7e096f0`](https://github.com/mastra-ai/mastra/commit/7e096f02f0dddbf09b85d306458351245ed2f886), [`8f0a332`](https://github.com/mastra-ai/mastra/commit/8f0a3321bf180368d76fe7b36aa1a8f60f00b6de), [`b098de9`](https://github.com/mastra-ai/mastra/commit/b098de9d7cb9f672e0883a5c716465a3a689693d), [`ef6e295`](https://github.com/mastra-ai/mastra/commit/ef6e295b59bc25a5b61b633a89c97bcfce9fb465), [`208e1b3`](https://github.com/mastra-ai/mastra/commit/208e1b39f30f4b386e494394e9d71d96f0f90241), [`c938d34`](https://github.com/mastra-ai/mastra/commit/c938d34739936c8ecbabd67ad6a4a4396f41c4c6), [`1d9a0ea`](https://github.com/mastra-ai/mastra/commit/1d9a0ea4a9901baee6cd56737243bd6d1f631ac0), [`3667679`](https://github.com/mastra-ai/mastra/commit/3667679db057edfb086846d13369fdda4902ad65), [`49696e8`](https://github.com/mastra-ai/mastra/commit/49696e8e42f870674a0a58f5abcd22cc54dd2864), [`512100a`](https://github.com/mastra-ai/mastra/commit/512100a7d8b7e9c920f2590c6b3612f5de0d3cff), [`9ef432b`](https://github.com/mastra-ai/mastra/commit/9ef432b6faa534b57b0d182a610e13dd9a7123ff), [`b9cf308`](https://github.com/mastra-ai/mastra/commit/b9cf30846f97f99ac1906ee8a68f4f2d117b0378)]:
|
|
12
|
+
- @mastra/core@1.60.0-alpha.2
|
|
13
|
+
- @mastra/server@1.60.0-alpha.2
|
|
14
|
+
|
|
3
15
|
## 1.60.0-alpha.1
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
|
|
2
2
|
const require_utils = require("./utils-O98BGdnP.cjs");
|
|
3
|
-
const require_services = require("./services-
|
|
3
|
+
const require_services = require("./services-DrT0fgoG.cjs");
|
|
4
4
|
const require_bundler = require("./bundler-DCGtF4jP.cjs");
|
|
5
5
|
let child_process = require("child_process");
|
|
6
6
|
let fs = require("fs");
|
|
@@ -833,19 +833,8 @@ function findExternalImporter(module, external, allOutputs, visited = /* @__PURE
|
|
|
833
833
|
* @returns Object containing bundle output and reference map for validation
|
|
834
834
|
*/
|
|
835
835
|
async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
836
|
-
const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions
|
|
837
|
-
const {
|
|
838
|
-
/**
|
|
839
|
-
* 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.
|
|
840
|
-
*/
|
|
841
|
-
let externalsPreset = false;
|
|
842
|
-
if (customExternals === true) externalsPreset = true;
|
|
843
|
-
const externalsList = Array.isArray(customExternals) ? customExternals : [];
|
|
844
|
-
const allExternals = [
|
|
845
|
-
...GLOBAL_EXTERNALS,
|
|
846
|
-
...DEPRECATED_EXTERNALS,
|
|
847
|
-
...externalsList
|
|
848
|
-
];
|
|
836
|
+
const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions, platform = "node" } = options;
|
|
837
|
+
const { externalsPreset, mergedExternals, transpilePackages = [], isDev = false } = bundlerOptions;
|
|
849
838
|
const workspacePackagesNames = Array.from(workspaceMap.keys());
|
|
850
839
|
const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
|
|
851
840
|
/**
|
|
@@ -869,7 +858,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
869
858
|
}
|
|
870
859
|
});
|
|
871
860
|
const output = await buildExternalDependencies(optimizedDependencyEntries, {
|
|
872
|
-
externals:
|
|
861
|
+
externals: mergedExternals,
|
|
873
862
|
packagesToTranspile,
|
|
874
863
|
workspaceMap,
|
|
875
864
|
rootDir: workspaceRoot || projectRoot,
|
|
@@ -882,7 +871,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
882
871
|
});
|
|
883
872
|
const moduleResolveMap = /* @__PURE__ */ new Map();
|
|
884
873
|
const filteredChunks = output.filter((o) => o.type === "chunk");
|
|
885
|
-
for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of
|
|
874
|
+
for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of mergedExternals) {
|
|
886
875
|
if (DEPS_TO_IGNORE.includes(external)) continue;
|
|
887
876
|
const importer = findExternalImporter(o, external, filteredChunks);
|
|
888
877
|
if (importer) {
|
|
@@ -921,6 +910,19 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
921
910
|
};
|
|
922
911
|
}
|
|
923
912
|
//#endregion
|
|
913
|
+
//#region src/build/analyze/externals.ts
|
|
914
|
+
function normalizeExternals(externals) {
|
|
915
|
+
const userExternals = Array.isArray(externals) ? externals : [];
|
|
916
|
+
return {
|
|
917
|
+
externalsPreset: externals === true,
|
|
918
|
+
mergedExternals: [...new Set([
|
|
919
|
+
...GLOBAL_EXTERNALS,
|
|
920
|
+
...DEPRECATED_EXTERNALS,
|
|
921
|
+
...userExternals
|
|
922
|
+
].filter(Boolean))]
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
//#endregion
|
|
924
926
|
//#region src/build/babel/check-config-export.ts
|
|
925
927
|
function checkConfigExport(result) {
|
|
926
928
|
const mastraVars = /* @__PURE__ */ new Set();
|
|
@@ -1193,7 +1195,7 @@ async function validateFile(root, file, { binaryMapData, moduleResolveMapLocatio
|
|
|
1193
1195
|
* @param workspaceMap - Map of workspace packages that gets directly passed through for later consumption
|
|
1194
1196
|
* @returns Analysis result containing dependency mappings
|
|
1195
1197
|
*/
|
|
1196
|
-
async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals,
|
|
1198
|
+
async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals, mergedExternals, outputDir, projectRoot, workspaceMap, depsVersionInfo }, logger) {
|
|
1197
1199
|
const result = {
|
|
1198
1200
|
dependencies: /* @__PURE__ */ new Map(),
|
|
1199
1201
|
externalDependencies: /* @__PURE__ */ new Map(),
|
|
@@ -1214,9 +1216,8 @@ async function validateOutput({ output, reverseVirtualReferenceMap, usedExternal
|
|
|
1214
1216
|
binaryMapData = JSON.parse(binaryMap);
|
|
1215
1217
|
}
|
|
1216
1218
|
const stubbedExternals = [.../* @__PURE__ */ new Set([
|
|
1217
|
-
...
|
|
1219
|
+
...mergedExternals,
|
|
1218
1220
|
...DEPS_TO_IGNORE,
|
|
1219
|
-
...userExternals,
|
|
1220
1221
|
...result.externalDependencies.keys()
|
|
1221
1222
|
])];
|
|
1222
1223
|
for (const file of output) {
|
|
@@ -1251,13 +1252,10 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1251
1252
|
});
|
|
1252
1253
|
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." });
|
|
1253
1254
|
const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
|
|
1254
|
-
|
|
1255
|
-
const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
|
|
1255
|
+
const { externalsPreset, mergedExternals } = normalizeExternals(bundlerOptions?.externals);
|
|
1256
1256
|
const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];
|
|
1257
|
-
if (bundlerOptions?.externals === true) externalsPreset = true;
|
|
1258
1257
|
let index = 0;
|
|
1259
1258
|
const depsToOptimize = /* @__PURE__ */ new Map();
|
|
1260
|
-
const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
|
|
1261
1259
|
const detectedPinoTransports = /* @__PURE__ */ new Set();
|
|
1262
1260
|
logger.info("Analyzing dependencies...");
|
|
1263
1261
|
const allUsedExternals = /* @__PURE__ */ new Map();
|
|
@@ -1283,7 +1281,7 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1283
1281
|
});
|
|
1284
1282
|
await (0, fs_promises.writeFile)((0, path.join)(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
|
|
1285
1283
|
for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
|
|
1286
|
-
if (
|
|
1284
|
+
if (mergedExternals.some((external) => require_utils.isDependencyPartOfPackage(dep, external)) || externalsPreset && !metadata.isWorkspace) {
|
|
1287
1285
|
const pkgName = require_utils.getPackageName(dep);
|
|
1288
1286
|
if (pkgName) allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));
|
|
1289
1287
|
continue;
|
|
@@ -1316,8 +1314,8 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1316
1314
|
logger.debug("Sorted dependencies", { deps: sortedDeps });
|
|
1317
1315
|
const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
|
|
1318
1316
|
bundlerOptions: {
|
|
1319
|
-
|
|
1320
|
-
|
|
1317
|
+
externalsPreset,
|
|
1318
|
+
mergedExternals,
|
|
1321
1319
|
isDev
|
|
1322
1320
|
},
|
|
1323
1321
|
projectRoot,
|
|
@@ -1346,7 +1344,7 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1346
1344
|
output,
|
|
1347
1345
|
reverseVirtualReferenceMap: fileNameToDependencyMap,
|
|
1348
1346
|
usedExternals,
|
|
1349
|
-
|
|
1347
|
+
mergedExternals,
|
|
1350
1348
|
outputDir,
|
|
1351
1349
|
projectRoot: workspaceRoot || projectRoot,
|
|
1352
1350
|
workspaceMap,
|
|
@@ -1424,6 +1422,12 @@ Object.defineProperty(exports, "getWorkspaceInformation", {
|
|
|
1424
1422
|
return getWorkspaceInformation;
|
|
1425
1423
|
}
|
|
1426
1424
|
});
|
|
1425
|
+
Object.defineProperty(exports, "normalizeExternals", {
|
|
1426
|
+
enumerable: true,
|
|
1427
|
+
get: function() {
|
|
1428
|
+
return normalizeExternals;
|
|
1429
|
+
}
|
|
1430
|
+
});
|
|
1427
1431
|
Object.defineProperty(exports, "packWorkspaceDependencies", {
|
|
1428
1432
|
enumerable: true,
|
|
1429
1433
|
get: function() {
|
|
@@ -1431,4 +1435,4 @@ Object.defineProperty(exports, "packWorkspaceDependencies", {
|
|
|
1431
1435
|
}
|
|
1432
1436
|
});
|
|
1433
1437
|
|
|
1434
|
-
//# sourceMappingURL=analyze-
|
|
1438
|
+
//# sourceMappingURL=analyze-B7YwN5Vu.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analyze-B7YwN5Vu.cjs","names":["pkg","slash","DepsService","getInputPlugins","protocolExternalResolver","mastraInternalAliasPlugin","mastraToolsAliasPlugin","tsConfigPaths","esbuild","removeDeployer","getPackageRootPath","isBareModuleSpecifier","getPackageName","getPackageMetadata","slash","isDependencyPartOfPackage","slash","rollupSafeName","getCompiledDepCachePath","getPackageRootPath","slash","tsConfigPaths","protocolExternalResolver","subpathExternalsResolver","esbuild","resolve","getNodeResolveOptions","esmShim","MastraBaseError","ErrorDomain","ErrorCategory","isDependencyPartOfPackage","t","t","getPackageName","getPackageMetadata","MastraError","ErrorDomain","ErrorCategory","isExternalProtocolImport","isDependencyPartOfPackage","slash","isBuiltinModule","isBareModuleSpecifier"],"sources":["../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/stacktrace-parser/0.1.11/63406bc765474556691ebd1b24eaa0c5b032f058a26bbaff13797a2780d98220/node_modules/stacktrace-parser/dist/stack-trace-parser.cjs.js","../src/bundler/workspaceDependencies.ts","../src/validator/validate.ts","../src/build/analyze/constants.ts","../src/build/analyze/analyzeEntry.ts","../src/build/plugins/hono-alias.ts","../src/build/plugins/module-resolve-map.ts","../src/build/plugins/node-gyp-detector.ts","../src/build/analyze/bundleExternals.ts","../src/build/analyze/externals.ts","../src/build/babel/check-config-export.ts","../src/build/babel/detect-pino-transports.ts","../src/build/analyze.ts"],"sourcesContent":["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar UNKNOWN_FUNCTION = '<unknown>';\n/**\n * This parses the different stack traces and puts them into one format\n * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)\n */\n\nfunction parse(stackString) {\n var lines = stackString.split('\\n');\n return lines.reduce(function (stack, line) {\n var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);\n\n if (parseResult) {\n stack.push(parseResult);\n }\n\n return stack;\n }, []);\n}\nvar chromeRe = /^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nvar chromeEvalRe = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nfunction parseChrome(line) {\n var parts = chromeRe.exec(line);\n\n if (!parts) {\n return null;\n }\n\n var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n var submatch = chromeEvalRe.exec(parts[2]);\n\n if (isEval && submatch != null) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = submatch[1]; // url\n\n parts[3] = submatch[2]; // line\n\n parts[4] = submatch[3]; // column\n }\n\n return {\n file: !isNative ? parts[2] : null,\n methodName: parts[1] || UNKNOWN_FUNCTION,\n arguments: isNative ? [parts[2]] : [],\n lineNumber: parts[3] ? +parts[3] : null,\n column: parts[4] ? +parts[4] : null\n };\n}\n\nvar winjsRe = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseWinjs(line) {\n var parts = winjsRe.exec(line);\n\n if (!parts) {\n return null;\n }\n\n return {\n file: parts[2],\n methodName: parts[1] || UNKNOWN_FUNCTION,\n arguments: [],\n lineNumber: +parts[3],\n column: parts[4] ? +parts[4] : null\n };\n}\n\nvar geckoRe = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar geckoEvalRe = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nfunction parseGecko(line) {\n var parts = geckoRe.exec(line);\n\n if (!parts) {\n return null;\n }\n\n var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n var submatch = geckoEvalRe.exec(parts[3]);\n\n if (isEval && submatch != null) {\n // throw out eval line/column and use top-most line number\n parts[3] = submatch[1];\n parts[4] = submatch[2];\n parts[5] = null; // no column when eval\n }\n\n return {\n file: parts[3],\n methodName: parts[1] || UNKNOWN_FUNCTION,\n arguments: parts[2] ? parts[2].split(',') : [],\n lineNumber: parts[4] ? +parts[4] : null,\n column: parts[5] ? +parts[5] : null\n };\n}\n\nvar javaScriptCoreRe = /^\\s*(?:([^@]*)(?:\\((.*?)\\))?@)?(\\S.*?):(\\d+)(?::(\\d+))?\\s*$/i;\n\nfunction parseJSC(line) {\n var parts = javaScriptCoreRe.exec(line);\n\n if (!parts) {\n return null;\n }\n\n return {\n file: parts[3],\n methodName: parts[1] || UNKNOWN_FUNCTION,\n arguments: [],\n lineNumber: +parts[4],\n column: parts[5] ? +parts[5] : null\n };\n}\n\nvar nodeRe = /^\\s*at (?:((?:\\[object object\\])?[^\\\\/]+(?: \\[as \\S+\\])?) )?\\(?(.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseNode(line) {\n var parts = nodeRe.exec(line);\n\n if (!parts) {\n return null;\n }\n\n return {\n file: parts[2],\n methodName: parts[1] || UNKNOWN_FUNCTION,\n arguments: [],\n lineNumber: +parts[3],\n column: parts[4] ? +parts[4] : null\n };\n}\n\nexports.parse = parse;\n","import { join, dirname } from 'node:path';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport slugify from '@sindresorhus/slugify';\nimport * as pkg from 'empathic/package';\nimport { findWorkspaces, findWorkspacesRoot, createWorkspacesCache } from 'find-workspaces';\nimport { ensureDir } from 'fs-extra';\nimport { slash } from '../build/utils';\nimport { DepsService } from '../services';\n\nexport type WorkspacePackageInfo = {\n location: string;\n dependencies: Record<string, string> | undefined;\n version: string | undefined;\n exports?: unknown;\n};\n\nconst isExportTargetImportable = (target: unknown): boolean => {\n if (!target) return false;\n if (typeof target === 'string') return true;\n if (Array.isArray(target)) return target.some(isExportTargetImportable);\n if (typeof target !== 'object') return false;\n\n return Object.values(target).some(isExportTargetImportable);\n};\n\nexport const hasRootExport = (exportsField: unknown): boolean => {\n if (exportsField === undefined) return true;\n if (typeof exportsField === 'string' || Array.isArray(exportsField)) return isExportTargetImportable(exportsField);\n if (!exportsField || typeof exportsField !== 'object') return false;\n\n const exportMap = exportsField as Record<string, unknown>;\n const exportKeys = Object.keys(exportMap);\n if (exportKeys.length === 0) return false;\n if (Object.prototype.hasOwnProperty.call(exportMap, '.')) return isExportTargetImportable(exportMap['.']);\n if (exportKeys.some(key => key.startsWith('./'))) return false;\n\n return isExportTargetImportable(exportMap);\n};\n\ntype TransitiveDependencyResult = {\n resolutions: Record<string, string>;\n usedWorkspacePackages: Set<string>;\n};\n\n/**\n * Create a shared cache for find-workspaces\n */\nconst workspacesCache = createWorkspacesCache();\n\n/**\n * A utility function around find-workspaces to get information about:\n * - Which workspace packages are available in the project\n * - What is the workspace root location\n * - Is the current package a workspace package\n *\n * 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.\n *\n * @params dir - The directory to start searching from (default: `process.cwd()`)\n * @params location - The location of the current package (usually the directory containing the package.json)\n */\nexport async function getWorkspaceInformation({\n dir = process.cwd(),\n mastraEntryFile,\n}: {\n dir?: string;\n mastraEntryFile: string;\n}) {\n // 1) Get the location of the current package and its package.json\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const location = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());\n\n // 2) Get all workspaces\n const workspaces = await findWorkspaces(dir, { cache: workspacesCache });\n const _workspaceMap = new Map(\n workspaces?.map(workspace => [\n workspace.package.name,\n {\n location: workspace.location,\n dependencies: workspace.package.dependencies,\n version: workspace.package.version,\n exports: workspace.package.exports,\n },\n ]) ?? [],\n );\n\n // 3) Check if the current package is part of the workspace\n const isWorkspacePackage = (workspaces ?? []).some(ws => ws.location === location);\n\n // 4) Get the workspace root only if the current package is part of the workspace\n const workspaceRoot = isWorkspacePackage ? findWorkspacesRoot(dir, { cache: workspacesCache })?.location : undefined;\n\n return {\n // If the current package is not part of the workspace, the bundling down the line shouldn't look at any workspace packages\n workspaceMap: isWorkspacePackage ? _workspaceMap : new Map<string, WorkspacePackageInfo>(),\n workspaceRoot,\n isWorkspacePackage,\n };\n}\n\n/**\n * Collects all transitive workspace dependencies and their TGZ paths\n */\nexport const collectTransitiveWorkspaceDependencies = ({\n workspaceMap,\n initialDependencies,\n logger,\n}: {\n workspaceMap: Map<string, WorkspacePackageInfo>;\n initialDependencies: Set<string>;\n logger: IMastraLogger;\n}): TransitiveDependencyResult => {\n const usedWorkspacePackages = new Set<string>();\n const queue: string[] = Array.from(initialDependencies);\n const resolutions: Record<string, string> = {};\n\n while (queue.length > 0) {\n const len = queue.length;\n for (let i = 0; i < len; i += 1) {\n const pkgName = queue.shift();\n if (!pkgName || usedWorkspacePackages.has(pkgName)) {\n continue;\n }\n\n const dep = workspaceMap.get(pkgName);\n if (!dep) continue;\n\n const root = findWorkspacesRoot();\n if (!root) {\n throw new Error('Could not find workspace root');\n }\n\n const depsService = new DepsService(root.location);\n depsService.__setLogger(logger);\n const sanitizedName = slugify(pkgName);\n\n const tgzPath = depsService.getWorkspaceDependencyPath({\n pkgName: sanitizedName,\n version: dep.version!,\n });\n resolutions[pkgName] = tgzPath;\n usedWorkspacePackages.add(pkgName);\n\n for (const [depName, _depVersion] of Object.entries(dep?.dependencies ?? {})) {\n if (!usedWorkspacePackages.has(depName) && workspaceMap.has(depName)) {\n queue.push(depName);\n }\n }\n }\n }\n\n return { resolutions, usedWorkspacePackages };\n};\n\n/**\n * Creates TGZ packages for workspace dependencies in the workspace-module directory\n */\nexport const packWorkspaceDependencies = async ({\n workspaceMap,\n usedWorkspacePackages,\n bundleOutputDir,\n logger,\n}: {\n workspaceMap: Map<string, WorkspacePackageInfo>;\n bundleOutputDir: string;\n logger: IMastraLogger;\n usedWorkspacePackages: Set<string>;\n}): Promise<void> => {\n const root = findWorkspacesRoot();\n if (!root) {\n throw new Error('Could not find workspace root');\n }\n\n const depsService = new DepsService(root.location);\n depsService.__setLogger(logger);\n\n // package all workspace dependencies\n if (usedWorkspacePackages.size > 0) {\n const workspaceDirPath = join(bundleOutputDir, 'workspace-module');\n await ensureDir(workspaceDirPath);\n\n logger.info('Packaging workspace dependencies', { count: usedWorkspacePackages.size });\n\n const batchSize = 5;\n const packages = Array.from(usedWorkspacePackages.values());\n\n for (let i = 0; i < packages.length; i += batchSize) {\n const batch = packages.slice(i, i + batchSize);\n logger.info(\n `Packaging batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(packages.length / batchSize)}: ${batch.join(', ')}`,\n );\n await Promise.all(\n batch.map(async pkgName => {\n const dep = workspaceMap.get(pkgName);\n const sanitizedName = slugify(pkgName);\n if (!dep) return;\n\n await depsService.pack({ dir: dep.location, destination: workspaceDirPath, sanitizedName: sanitizedName });\n }),\n );\n }\n\n logger.info('Successfully packaged workspace dependencies', { count: usedWorkspacePackages.size });\n }\n};\n","import { spawn as nodeSpawn } from 'node:child_process';\nimport type { SpawnOptions } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\ntype ValidationArgs = {\n message: string;\n type: string;\n stack: string;\n};\n\nexport class ValidationError extends Error {\n public readonly type: string;\n public readonly stack: string;\n constructor(args: ValidationArgs) {\n super(args.message);\n this.type = args.type;\n this.stack = args.stack;\n }\n}\n\n/**\n * Promisified version of Node.js spawn function\n *\n * @param command - The command to run\n * @param args - List of string arguments\n * @param options - Spawn options\n * @returns Promise that resolves with the exit code when the process completes\n */\nfunction spawn(command: string, args: string[] = [], options: SpawnOptions = {}): Promise<void> {\n return new Promise((resolve, reject) => {\n let validationError: ValidationArgs | null = null;\n const childProcess = nodeSpawn(command, args, {\n stdio: ['ignore', 'ignore', 'pipe'],\n ...options,\n });\n\n childProcess.on('error', error => {\n reject(error);\n });\n\n let stderr = '';\n childProcess.stderr?.on('data', message => {\n try {\n validationError = JSON.parse(message.toString());\n } catch {\n stderr += message;\n }\n });\n\n childProcess.on('close', code => {\n if (code === 0) {\n resolve();\n } else {\n if (validationError) {\n reject(new ValidationError(validationError));\n } else {\n reject(new Error(stderr));\n }\n }\n });\n });\n}\n\nexport function validate(\n file: string,\n {\n injectESMShim = false,\n moduleResolveMapLocation,\n stubbedExternals = [],\n }: { injectESMShim?: boolean; moduleResolveMapLocation: string; stubbedExternals?: string[] },\n) {\n let prefixCode = '';\n if (injectESMShim) {\n prefixCode = `import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nglobalThis.__filename = fileURLToPath(import.meta.url);\nglobalThis.__dirname = dirname(__filename);\n `;\n }\n\n // Used to log a proper error we can parse instead of trying to do some fancy string grepping\n function errorHandler(err: Error) {\n console.error(\n JSON.stringify({\n type: err.name,\n message: err.message,\n stack: err.stack,\n }),\n );\n process.exit(1);\n }\n\n return spawn(\n process.execPath,\n [\n '--import',\n import.meta.resolve('@mastra/deployer/loader'),\n '--input-type=module',\n '--enable-source-maps',\n '-e',\n `${prefixCode};import('${pathToFileURL(file).href}').catch(err => {\n ${errorHandler.toString()}\n errorHandler(err);\n })`.replaceAll(/\\n/g, ''),\n ],\n {\n env: {\n ...process.env,\n MODULE_MAP: `${moduleResolveMapLocation}`,\n STUBBED_EXTERNALS: JSON.stringify(stubbedExternals),\n },\n cwd: dirname(file),\n },\n );\n}\n","export const DEPS_TO_IGNORE = ['#tools', 'execa', 'effect', 'sury', '@ast-grep/napi', '@hono/node-ws'];\n\nexport const GLOBAL_EXTERNALS = [\n 'pino',\n 'pino-pretty',\n '@libsql/client',\n 'pg',\n 'libsql',\n '#tools',\n 'typescript',\n 'undici',\n 'readable-stream',\n 'bufferutil',\n 'utf-8-validate',\n 'execa',\n '@ast-grep/napi',\n '@hono/node-ws',\n];\nexport const DEPRECATED_EXTERNALS = ['fastembed', 'nodemailer', 'jsdom', 'sqlite3'];\n","import type { IMastraLogger } from '@mastra/core/logger';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport virtual from '@rollup/plugin-virtual';\nimport { rollup } from 'rollup';\nimport type { OutputChunk, Plugin, SourceMap } from 'rollup';\nimport type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies';\nimport { hasRootExport } from '../../bundler/workspaceDependencies';\nimport { mastraInternalAliasPlugin, mastraToolsAliasPlugin } from '../bundler';\nimport { getPackageMetadata, getPackageRootPath } from '../package-info';\nimport { esbuild } from '../plugins/esbuild';\nimport { protocolExternalResolver } from '../plugins/protocol-external-resolver';\nimport { removeDeployer } from '../plugins/remove-deployer';\nimport { tsConfigPaths } from '../plugins/tsconfig-paths';\nimport type { DependencyMetadata } from '../types';\nimport { getPackageName, isBareModuleSpecifier, slash } from '../utils';\nimport { DEPS_TO_IGNORE } from './constants';\n\n/**\n * Configures and returns the Rollup plugins needed for analyzing entry files.\n * Sets up module resolution, transpilation, and custom alias handling for Mastra-specific imports.\n */\nfunction getInputPlugins(\n { entry, isVirtualFile }: { entry: string; isVirtualFile: boolean },\n mastraEntry: string,\n { sourcemapEnabled }: { sourcemapEnabled: boolean },\n): Plugin[] {\n let virtualPlugin = null;\n if (isVirtualFile) {\n virtualPlugin = virtual({\n '#entry': entry,\n });\n entry = '#entry';\n }\n\n const plugins = [];\n if (virtualPlugin) {\n plugins.push(virtualPlugin);\n }\n\n plugins.push(\n ...[\n protocolExternalResolver(),\n mastraInternalAliasPlugin(mastraEntry),\n mastraToolsAliasPlugin(),\n tsConfigPaths(),\n json(),\n esbuild(),\n commonjs({\n strictRequires: 'debug',\n ignoreTryCatch: false,\n transformMixedEsModules: true,\n extensions: ['.js', '.ts'],\n }),\n removeDeployer(mastraEntry, {\n sourcemap: sourcemapEnabled,\n }),\n esbuild(),\n ],\n );\n\n return plugins;\n}\n\n/**\n * Extracts and categorizes dependencies from Rollup output to determine which ones need optimization.\n * Analyzes both static imports and dynamic imports while filtering out Node.js built-ins and ignored dependencies.\n * Identifies workspace packages and resolves package root paths for proper bundling optimization.\n */\nasync function captureDependenciesToOptimize(\n output: OutputChunk,\n workspaceMap: Map<string, WorkspacePackageInfo>,\n projectRoot: string,\n {\n logger,\n shouldCheckTransitiveDependencies,\n }: {\n logger: IMastraLogger;\n shouldCheckTransitiveDependencies: boolean;\n },\n): Promise<Map<string, DependencyMetadata>> {\n const depsToOptimize = new Map<string, DependencyMetadata>();\n\n if (!output.facadeModuleId) {\n throw new Error(\n 'Something went wrong, we could not find the package name of the entry file. Please open an issue.',\n );\n }\n\n let entryRootPath = projectRoot;\n if (!output.facadeModuleId.startsWith('\\x00virtual:')) {\n entryRootPath = (await getPackageRootPath(output.facadeModuleId)) || projectRoot;\n }\n\n for (const [dependency, bindings] of Object.entries(output.importedBindings)) {\n if (!isBareModuleSpecifier(dependency)) {\n continue;\n }\n\n // The `getPackageName` helper also handles subpaths so we only get the proper package name\n const pkgName = getPackageName(dependency);\n let rootPath: string | null = null;\n let isWorkspace = false;\n let version: string | undefined;\n let packageSpec: string | undefined;\n\n if (pkgName) {\n const metadata = await getPackageMetadata(dependency, entryRootPath);\n rootPath = metadata.rootPath;\n version = metadata.version;\n packageSpec = metadata.packageSpec;\n isWorkspace = workspaceMap.has(pkgName);\n }\n\n const normalizedRootPath = rootPath ? slash(rootPath) : null;\n\n depsToOptimize.set(dependency, {\n exports: bindings,\n rootPath: normalizedRootPath,\n isWorkspace,\n version,\n packageSpec,\n });\n }\n\n const processedWorkspaceDeps = new Set<string>();\n\n /**\n * Recursively discovers transitive workspace dependencies from package manifests.\n */\n function checkTransitiveDependencies(maxDepth = 10, currentDepth = 0) {\n // Could be a circular dependency...\n if (currentDepth >= maxDepth) {\n logger.warn('Maximum dependency depth reached while checking transitive dependencies.');\n return;\n }\n\n // Make a copy so that we can safely iterate over it\n const depsSnapshot = new Map(depsToOptimize);\n let hasAddedDeps = false;\n\n for (const [dep, meta] of depsSnapshot) {\n const pkgName = getPackageName(dep);\n // We only care about workspace deps that we haven't already processed\n if (!pkgName || !meta.isWorkspace || processedWorkspaceDeps.has(pkgName)) {\n continue;\n }\n\n processedWorkspaceDeps.add(pkgName);\n\n const workspaceInfo = workspaceMap.get(pkgName);\n if (!workspaceInfo?.dependencies) {\n continue;\n }\n\n for (const [innerDep, _innerDepVersion] of Object.entries(workspaceInfo.dependencies)) {\n const innerWorkspaceInfo = workspaceMap.get(innerDep);\n if (!innerWorkspaceInfo) {\n continue;\n }\n\n if (!hasRootExport(innerWorkspaceInfo.exports)) {\n continue;\n }\n\n const existingMeta = depsToOptimize.get(innerDep);\n if (existingMeta) {\n depsToOptimize.set(innerDep, {\n ...existingMeta,\n exports: existingMeta.exports.includes('*') ? existingMeta.exports : [...existingMeta.exports, '*'],\n });\n continue;\n }\n\n depsToOptimize.set(innerDep, {\n exports: ['*'],\n rootPath: slash(innerWorkspaceInfo.location),\n isWorkspace: true,\n version: innerWorkspaceInfo.version,\n });\n hasAddedDeps = true;\n }\n }\n\n // Continue until no new deps are found\n if (hasAddedDeps) {\n checkTransitiveDependencies(maxDepth, currentDepth + 1);\n }\n }\n\n if (shouldCheckTransitiveDependencies) {\n checkTransitiveDependencies();\n }\n\n // #tools is a generated dependency, we don't want our analyzer to handle it\n const dynamicImports = output.dynamicImports.filter(d => !DEPS_TO_IGNORE.includes(d));\n if (dynamicImports.length) {\n for (const dynamicImport of dynamicImports) {\n if (!depsToOptimize.has(dynamicImport) && isBareModuleSpecifier(dynamicImport)) {\n // Try to resolve version for dynamic imports as well\n const pkgName = getPackageName(dynamicImport);\n let version: string | undefined;\n let packageSpec: string | undefined;\n let rootPath: string | null = null;\n\n if (pkgName) {\n const metadata = await getPackageMetadata(dynamicImport, entryRootPath);\n rootPath = metadata.rootPath;\n version = metadata.version;\n packageSpec = metadata.packageSpec;\n }\n\n depsToOptimize.set(dynamicImport, {\n exports: ['*'],\n rootPath: rootPath ? slash(rootPath) : null,\n isWorkspace: false,\n version,\n packageSpec,\n });\n }\n }\n }\n\n return depsToOptimize;\n}\n\n/**\n * Analyzes the entry file to identify external dependencies and their imports. This allows us to treeshake all code that is not used.\n *\n * @param entryConfig - Configuration object for the entry file\n * @param entryConfig.entry - The entry file path or content\n * @param entryConfig.isVirtualFile - Whether the entry is a virtual file (content string) or a file path\n * @param mastraEntry - The mastra entry point\n * @param options - Configuration options for the analysis\n * @param options.logger - Logger instance for debugging\n * @param options.sourcemapEnabled - Whether sourcemaps are enabled\n * @param options.workspaceMap - Map of workspace packages\n * @param options.shouldCheckTransitiveDependencies - Whether to recursively analyze transitive workspace dependencies (default: false)\n * @returns A promise that resolves to an object containing the analyzed dependencies and generated output\n */\n/** Return type of {@link analyzeEntry} */\nexport type AnalyzeEntryResult = {\n dependencies: Map<string, DependencyMetadata>;\n output: {\n code: string;\n map: SourceMap | null;\n };\n};\n\nexport async function analyzeEntry(\n {\n entry,\n isVirtualFile,\n }: {\n entry: string;\n isVirtualFile: boolean;\n },\n mastraEntry: string,\n {\n logger,\n sourcemapEnabled,\n workspaceMap,\n projectRoot,\n shouldCheckTransitiveDependencies = false,\n analyzeCache,\n }: {\n logger: IMastraLogger;\n sourcemapEnabled: boolean;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n projectRoot: string;\n shouldCheckTransitiveDependencies?: boolean;\n /** Shared cache to avoid re-analyzing the same entry across recursive calls */\n analyzeCache?: Map<string, AnalyzeEntryResult>;\n },\n): Promise<AnalyzeEntryResult> {\n // Deduplicate: if this entry was already analyzed, return cached result\n const cacheKey = isVirtualFile ? undefined : slash(entry);\n if (cacheKey && analyzeCache?.has(cacheKey)) {\n return analyzeCache.get(cacheKey)!;\n }\n\n const optimizerBundler = await rollup({\n logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',\n input: isVirtualFile ? '#entry' : entry,\n treeshake: false,\n preserveSymlinks: true,\n plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),\n external: DEPS_TO_IGNORE,\n });\n\n const { output } = await optimizerBundler.generate({\n format: 'esm',\n inlineDynamicImports: true,\n });\n\n await optimizerBundler.close();\n\n const depsToOptimize = await captureDependenciesToOptimize(output[0] as OutputChunk, workspaceMap, projectRoot, {\n logger,\n shouldCheckTransitiveDependencies,\n });\n\n const result: AnalyzeEntryResult = {\n dependencies: depsToOptimize,\n output: {\n code: output[0].code,\n map: output[0].map as SourceMap,\n },\n };\n\n // Cache the result so recursive calls for the same entry are instant\n if (cacheKey && analyzeCache) {\n analyzeCache.set(cacheKey, result);\n }\n\n return result;\n}\n","import { fileURLToPath } from 'node:url';\nimport type { Plugin } from 'rollup';\n\n// hono is imported from deployer, so we need to resolve from here instead of the project root\nexport function aliasHono(): Plugin {\n return {\n name: 'hono-alias',\n resolveId(id: string) {\n if (!id.startsWith('@hono/') && !id.startsWith('hono/') && id !== 'hono' && id !== 'hono-openapi') {\n return;\n }\n\n const path = import.meta.resolve(id);\n return fileURLToPath(path);\n },\n } satisfies Plugin;\n}\n","import { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { Plugin } from 'rollup';\nimport { isDependencyPartOfPackage, slash } from '../utils';\n\nexport function moduleResolveMap(externals: string[], projectRoot: string): Plugin {\n const importMap = new Map<string, string>();\n return {\n name: 'module-resolve-map',\n moduleParsed(info) {\n if (info.importedIds.length === 0 || !info.id) {\n return;\n }\n\n for (const importedId of info.importedIds) {\n for (const external of externals) {\n if (isDependencyPartOfPackage(importedId, external)) {\n // TODO add multi version support\n importMap.set(external, info.id);\n }\n }\n }\n },\n\n async generateBundle(options, bundle) {\n const resolveMap = new Map<string, Map<string, string>>();\n\n // Iterate through all output chunks\n for (const [fileName, chunk] of Object.entries(bundle)) {\n // Only chunks have modules, assets don't\n if (chunk.type === 'chunk') {\n for (const [external, resolvedFrom] of importMap) {\n if (chunk.moduleIds.includes(resolvedFrom)) {\n const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();\n const innerMap = resolveMap.get(fullPath) || new Map<string, string>();\n innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());\n resolveMap.set(fullPath, innerMap);\n }\n }\n }\n }\n\n // store all binaries used by a module to show in the error message\n const resolveMapJson = Object.fromEntries(\n Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())]),\n );\n\n this.emitFile({\n type: 'asset',\n name: 'module-resolve-map.json',\n source: `${JSON.stringify(resolveMapJson, null, 2)}`,\n });\n },\n } satisfies Plugin;\n}\n","import { getPackageInfo } from 'local-pkg';\nimport type { Plugin } from 'rollup';\n\nexport function nodeGypDetector(): Plugin {\n const modulesToTrack = new Set<string>();\n const modulesToTrackPackageInfo = new Map<string, ReturnType<typeof getPackageInfo>>();\n\n return {\n name: 'node-gyp-build-detector',\n moduleParsed(info) {\n if (!info.meta?.commonjs?.requires?.length) {\n return;\n }\n\n const hasNodeGypBuild = info.meta.commonjs.requires.some((m: { resolved?: { id: string } }) =>\n m?.resolved?.id.endsWith('node-gyp-build/index.js'),\n );\n if (!hasNodeGypBuild) {\n return;\n }\n\n modulesToTrack.add(info.id);\n modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));\n },\n\n async generateBundle(options, bundle) {\n const binaryMapByChunk = new Map<string, Set<string>>();\n // Iterate through all output chunks\n for (const [fileName, chunk] of Object.entries(bundle)) {\n // Only chunks have modules, assets don't\n if (chunk.type === 'chunk') {\n for (const moduleId of chunk.moduleIds) {\n if (modulesToTrackPackageInfo.has(moduleId)) {\n const pkgInfo = await modulesToTrackPackageInfo.get(moduleId)!;\n\n if (!binaryMapByChunk.has(fileName)) {\n binaryMapByChunk.set(fileName, new Set());\n }\n\n if (pkgInfo?.packageJson?.name) {\n binaryMapByChunk.get(fileName)!.add(pkgInfo.packageJson.name);\n }\n }\n }\n }\n }\n\n const binaryMapJson = Object.fromEntries(\n Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)]),\n );\n\n // store all binaries used by a module to show in the error message\n this.emitFile({\n type: 'asset',\n name: 'binary-map.json',\n source: `${JSON.stringify(binaryMapJson, null, 2)}`,\n });\n },\n } satisfies Plugin;\n}\n","import { readFile } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { basename } from 'node:path/posix';\nimport { ErrorCategory, ErrorDomain, MastraBaseError } from '@mastra/core/error';\nimport { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport virtual from '@rollup/plugin-virtual';\nimport { getPackageInfo } from 'local-pkg';\nimport * as resolve from 'resolve.exports';\nimport { rollup } from 'rollup';\nimport type { OutputChunk, OutputAsset, Plugin } from 'rollup';\nimport type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies';\nimport { getPackageRootPath } from '../package-info';\nimport { esbuild } from '../plugins/esbuild';\nimport { esmShim } from '../plugins/esm-shim';\nimport { aliasHono } from '../plugins/hono-alias';\nimport { moduleResolveMap } from '../plugins/module-resolve-map';\nimport { nodeGypDetector } from '../plugins/node-gyp-detector';\nimport { protocolExternalResolver } from '../plugins/protocol-external-resolver';\nimport { subpathExternalsResolver } from '../plugins/subpath-externals-resolver';\nimport { tsConfigPaths } from '../plugins/tsconfig-paths';\nimport type { DependencyMetadata } from '../types';\nimport {\n getCompiledDepCachePath,\n getNodeResolveOptions,\n isDependencyPartOfPackage,\n rollupSafeName,\n slash,\n} from '../utils';\nimport type { BundlerPlatform } from '../utils';\nimport { DEPS_TO_IGNORE } from './constants';\nimport type { NormalizedExternals } from './externals';\n\ntype VirtualDependency = {\n name: string;\n virtual: string;\n};\n\nfunction prepareEntryFileName(name: string, rootDir: string) {\n return rollupSafeName(name, rootDir);\n}\n\n/**\n * 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.\n */\nexport function createVirtualDependencies(\n depsToOptimize: Map<string, DependencyMetadata>,\n {\n projectRoot,\n workspaceRoot,\n outputDir,\n bundlerOptions,\n }: {\n workspaceRoot: string | null;\n projectRoot: string;\n outputDir: string;\n bundlerOptions?: { isDev?: boolean; externalsPreset?: boolean };\n },\n): {\n optimizedDependencyEntries: Map<string, VirtualDependency>;\n fileNameToDependencyMap: Map<string, string>;\n} {\n const { isDev = false, externalsPreset = false } = bundlerOptions || {};\n const fileNameToDependencyMap = new Map<string, string>();\n const optimizedDependencyEntries = new Map<string, VirtualDependency>();\n const rootDir = workspaceRoot || projectRoot;\n\n for (const [dep, { exports }] of depsToOptimize.entries()) {\n // Use __ as separator to avoid conflicts with hyphens in package names\n // e.g., @inner/inner-tools -> @inner__inner-tools (preserves the hyphen)\n const fileName = dep.replaceAll('/', '__');\n const virtualFile: string[] = [];\n const exportStringBuilder = [];\n\n for (const local of exports) {\n if (local === '*') {\n virtualFile.push(`export * from '${dep}';`);\n continue;\n } else if (local === 'default') {\n exportStringBuilder.push('default');\n } else {\n exportStringBuilder.push(local);\n }\n }\n\n const chunks = [];\n if (exportStringBuilder.length) {\n chunks.push(`{ ${exportStringBuilder.join(', ')} }`);\n }\n if (chunks.length) {\n virtualFile.push(`export ${chunks.join(', ')} from '${dep}';`);\n }\n\n // Determine the entry name based on the complexity of exports\n let entryName = prepareEntryFileName(path.join(outputDir, fileName), rootDir);\n\n fileNameToDependencyMap.set(entryName, dep);\n optimizedDependencyEntries.set(dep, {\n name: entryName,\n virtual: virtualFile.join('\\n'),\n });\n }\n\n // For workspace packages, we still want the dependencies to be imported from the original path\n // We rewrite the path to the original folder inside node_modules/.cache\n if (isDev || externalsPreset) {\n for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {\n if (!isWorkspace || !rootPath || !workspaceRoot) {\n continue;\n }\n\n const currentDepPath = optimizedDependencyEntries.get(dep);\n if (!currentDepPath) {\n continue;\n }\n\n const fileName = basename(currentDepPath.name);\n const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);\n\n fileNameToDependencyMap.set(entryName, dep);\n optimizedDependencyEntries.set(dep, {\n ...currentDepPath,\n name: entryName,\n });\n }\n }\n\n return { optimizedDependencyEntries, fileNameToDependencyMap };\n}\n\n/**\n * Configures and returns Rollup plugins for bundling external dependencies.\n * Sets up virtual modules, TypeScript compilation, CommonJS transformation, and workspace resolution.\n */\nasync function getInputPlugins(\n virtualDependencies: Map<string, { name: string; virtual: string }>,\n {\n transpilePackages,\n workspaceMap,\n bundlerOptions,\n rootDir,\n externals,\n platform,\n }: {\n transpilePackages: Set<string>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n bundlerOptions: { noBundling: boolean };\n rootDir: string;\n externals: string[];\n platform: BundlerPlatform;\n },\n) {\n const transpilePackagesMap = new Map<string, string>();\n for (const pkg of transpilePackages) {\n const dir = await getPackageRootPath(pkg);\n\n if (dir) {\n transpilePackagesMap.set(pkg, slash(dir));\n } else {\n transpilePackagesMap.set(pkg, workspaceMap.get(pkg)?.location ?? pkg);\n }\n }\n\n return [\n virtual(\n Array.from(virtualDependencies.entries()).reduce(\n (acc, [dep, virtualDep]) => {\n acc[`#virtual-${dep}`] = virtualDep.virtual;\n return acc;\n },\n {} as Record<string, string>,\n ),\n ),\n tsConfigPaths(),\n protocolExternalResolver(),\n subpathExternalsResolver(externals),\n transpilePackagesMap.size\n ? esbuild({\n format: 'esm',\n include: [\n // Match files from transpilePackages by their actual directory paths\n // but exclude any nested node_modules\n ...[...transpilePackagesMap.values()].map(p => {\n if (path.isAbsolute(p)) {\n return new RegExp(`^${p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}/(?!.*node_modules).*$`);\n } else {\n return new RegExp(`\\/${p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}/(?!.*node_modules).*$`);\n }\n }),\n // Also match workspace packages resolved through node_modules symlinks\n // (common in pnpm workspaces). Match by package name in node_modules path.\n ...[...transpilePackagesMap.keys()].map(pkgName => {\n const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`);\n }),\n ],\n // Disable the default /node_modules/ exclusion from rollup-plugin-esbuild.\n // In pnpm workspaces, nodeResolve resolves workspace packages through node_modules\n // symlinks, so the resolved paths contain \"node_modules\". Without this, workspace\n // package .ts files won't be transpiled even if they match the include patterns.\n exclude: [],\n })\n : null,\n bundlerOptions.noBundling\n ? ({\n name: 'alias-optimized-deps',\n async resolveId(id, importer, options) {\n if (!virtualDependencies.has(id)) {\n return null;\n }\n\n const info = virtualDependencies.get(id)!;\n // go from ./node_modules/.cache/index.js to ./pkg\n const packageRootPath = path.join(rootDir, path.dirname(path.dirname(path.dirname(info.name))));\n const pkgJsonBuffer = await readFile(path.join(packageRootPath, 'package.json'), 'utf-8');\n const pkgJson = JSON.parse(pkgJsonBuffer);\n if (!pkgJson) {\n return null;\n }\n\n const pkgName = pkgJson.name || '';\n let resolvedPath: string | undefined = resolve.exports(pkgJson, id.replace(pkgName, '.'))?.[0];\n if (!resolvedPath) {\n resolvedPath = pkgJson!.main ?? 'index.js';\n }\n\n const resolved = await this.resolve(path.posix.join(packageRootPath, resolvedPath!), importer, options);\n return resolved;\n },\n } satisfies Plugin)\n : null,\n optimizeLodashImports({\n include: '**/*.{js,ts,mjs,cjs}',\n }),\n commonjs({\n strictRequires: 'strict',\n transformMixedEsModules: true,\n ignoreTryCatch: false,\n }),\n bundlerOptions.noBundling ? null : nodeResolve(getNodeResolveOptions(platform)),\n bundlerOptions.noBundling ? esmShim() : null,\n // hono is imported from deployer, so we need to resolve from here instead of the project root\n aliasHono(),\n json(),\n nodeGypDetector(),\n moduleResolveMap(externals, rootDir),\n {\n name: 'not-found-resolver',\n resolveId: {\n order: 'post',\n async handler(id, importer) {\n if (!importer) {\n return null;\n }\n\n if (!id.endsWith('.node')) {\n return null;\n }\n\n const pkgInfo = await getPackageInfo(importer);\n const packageName = pkgInfo?.packageJson?.name || id;\n throw new MastraBaseError({\n id: 'DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: {\n importFile: importer,\n packageName,\n },\n text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}.\n\nPlease consider adding \\`${packageName}\\` to your externals, or updating this import to not end with \".node\".\n\nexport const mastra = new Mastra({\n bundler: {\n externals: [\"${packageName}\"],\n }\n})`,\n });\n },\n },\n } satisfies Plugin,\n ].filter(Boolean);\n}\n\n/**\n * Executes the Rollup build process for virtual dependencies using configured plugins.\n * Bundles all virtual dependency modules into optimized ESM files with proper external handling.\n */\nasync function buildExternalDependencies(\n virtualDependencies: Map<string, VirtualDependency>,\n {\n externals,\n packagesToTranspile,\n workspaceMap,\n rootDir,\n outputDir,\n bundlerOptions,\n platform,\n }: {\n externals: string[];\n packagesToTranspile: Set<string>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n rootDir: string;\n outputDir: string;\n bundlerOptions: {\n isDev: boolean;\n externalsPreset: boolean;\n };\n platform: BundlerPlatform;\n },\n) {\n /**\n * If there are no virtual dependencies to bundle, return an empty array to avoid Rollup errors.\n */\n if (virtualDependencies.size === 0) {\n return [] as unknown as [OutputChunk, ...(OutputAsset | OutputChunk)[]];\n }\n\n const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;\n\n const plugins = await getInputPlugins(virtualDependencies, {\n transpilePackages: packagesToTranspile,\n workspaceMap,\n bundlerOptions: {\n noBundling,\n },\n rootDir,\n externals,\n platform,\n });\n\n const bundler = await rollup({\n logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',\n input: Array.from(virtualDependencies.entries()).reduce(\n (acc, [dep, virtualDep]) => {\n acc[virtualDep.name] = `#virtual-${dep}`;\n return acc;\n },\n {} as Record<string, string>,\n ),\n external: externals,\n treeshake: noBundling ? false : 'safest',\n plugins,\n });\n\n const outputDirRelative = prepareEntryFileName(outputDir, rootDir);\n\n const { output } = await bundler.write({\n format: 'esm',\n dir: rootDir,\n entryFileNames: '[name].mjs',\n // used to get the filename of the actual error\n sourcemap: true,\n /**\n * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.\n * So we want to write them to the `.mastra/output` folder as well.\n */\n chunkFileNames: chunkInfo => {\n /**\n * 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.\n * We only care about this for the \"noBundling\" case!\n */\n if (noBundling) {\n const importedFromPackages = new Set<string>();\n\n for (const moduleId of chunkInfo.moduleIds) {\n const normalized = slash(moduleId);\n for (const [pkgName, pkgInfo] of workspaceMap.entries()) {\n const location = slash(pkgInfo.location);\n if (normalized.startsWith(location)) {\n importedFromPackages.add(pkgName);\n break;\n }\n }\n }\n\n if (importedFromPackages.size > 1) {\n throw new MastraBaseError({\n id: 'DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: {\n chunkName: chunkInfo.name,\n packages: JSON.stringify(Array.from(importedFromPackages)),\n },\n text: `Please open an issue. We found a shared chunk \"${\n chunkInfo.name\n }\" used by multiple workspace packages: ${Array.from(importedFromPackages).join(', ')}.`,\n });\n }\n\n if (importedFromPackages.size === 1) {\n const [pkgName] = importedFromPackages;\n const workspaceLocation = workspaceMap.get(pkgName!)!.location;\n return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, '[name].mjs'), rootDir);\n }\n }\n\n return `${outputDirRelative}/[name].mjs`;\n },\n assetFileNames: `${outputDirRelative}/[name][extname]`,\n hoistTransitiveImports: false,\n });\n\n await bundler.close();\n\n return output;\n}\n\n/**\n * Recursively searches through Rollup output chunks to find which module imports a specific external dependency.\n * Used to build the module resolution map for proper external dependency tracking.\n */\nfunction findExternalImporter(\n module: OutputChunk,\n external: string,\n allOutputs: OutputChunk[],\n visited = new Set<string>(),\n): OutputChunk | null {\n if (visited.has(module.fileName)) {\n return null;\n }\n\n visited.add(module.fileName);\n const capturedFiles = new Set<string>();\n\n for (const id of [...module.imports, ...module.dynamicImports]) {\n if (isDependencyPartOfPackage(id, external)) {\n return module;\n } else {\n if (id.endsWith('.mjs')) {\n capturedFiles.add(id);\n }\n }\n }\n\n for (const file of capturedFiles) {\n const nextModule = allOutputs.find(o => o.fileName === file);\n if (nextModule) {\n const importer = findExternalImporter(nextModule, external, allOutputs, visited);\n\n if (importer) {\n return importer;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Bundles vendor dependencies identified in the analysis step.\n * Creates virtual modules for each dependency and bundles them using rollup.\n *\n * @param depsToOptimize - Map of dependencies to optimize with their metadata (exported bindings, rootPath, isWorkspace)\n * @param outputDir - Directory where bundled files will be written\n * @param logger - Logger instance for debugging\n * @returns Object containing bundle output and reference map for validation\n */\nexport async function bundleExternals(\n depsToOptimize: Map<string, DependencyMetadata>,\n outputDir: string,\n options: {\n bundlerOptions: NormalizedExternals & {\n isDev?: boolean;\n transpilePackages?: string[];\n };\n projectRoot?: string;\n workspaceRoot?: string;\n workspaceMap?: Map<string, WorkspacePackageInfo>;\n platform?: BundlerPlatform;\n },\n) {\n const {\n workspaceRoot = null,\n workspaceMap = new Map(),\n projectRoot = outputDir,\n bundlerOptions,\n platform = 'node',\n } = options;\n const { externalsPreset, mergedExternals, transpilePackages = [], isDev = false } = bundlerOptions;\n\n const workspacePackagesNames = Array.from(workspaceMap.keys());\n const packagesToTranspile = new Set([...transpilePackages, ...workspacePackagesNames]);\n\n /**\n * When externals: true, we need to extract non-workspace deps from depsToOptimize\n * and add them directly to usedExternals instead of bundling them.\n */\n const extractedExternals = new Map<string, string>();\n if (externalsPreset) {\n for (const [dep, metadata] of depsToOptimize.entries()) {\n if (!metadata.isWorkspace) {\n // Add to extracted externals - use rootPath or fallback to package name\n extractedExternals.set(dep, metadata.rootPath ?? dep);\n // Remove from depsToOptimize so it won't be bundled\n depsToOptimize.delete(dep);\n }\n }\n }\n\n const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {\n workspaceRoot,\n outputDir,\n projectRoot,\n bundlerOptions: {\n isDev,\n externalsPreset,\n },\n });\n\n const output = await buildExternalDependencies(optimizedDependencyEntries, {\n externals: mergedExternals,\n packagesToTranspile,\n workspaceMap,\n rootDir: workspaceRoot || projectRoot,\n outputDir,\n bundlerOptions: {\n isDev,\n externalsPreset,\n },\n platform,\n });\n\n const moduleResolveMap = new Map<string, Map<string, string>>();\n const filteredChunks = output.filter(o => o.type === 'chunk');\n\n for (const o of filteredChunks.filter(o => o.isEntry || o.isDynamicEntry)) {\n for (const external of mergedExternals) {\n if (DEPS_TO_IGNORE.includes(external)) {\n continue;\n }\n\n const importer = findExternalImporter(o, external, filteredChunks);\n\n if (importer) {\n const fullPath = path.join(workspaceRoot || projectRoot, importer.fileName);\n let innerMap = moduleResolveMap.get(fullPath);\n\n if (!innerMap) {\n innerMap = new Map<string, string>();\n moduleResolveMap.set(fullPath, innerMap);\n }\n\n if (importer.moduleIds.length) {\n innerMap.set(\n external,\n importer.moduleIds[importer.moduleIds.length - 1]?.startsWith('\\x00virtual:#virtual')\n ? importer.moduleIds[importer.moduleIds.length - 2]!\n : importer.moduleIds[importer.moduleIds.length - 1]!,\n );\n }\n }\n }\n }\n\n /**\n * Convert moduleResolveMap to a plain object with prototype-less objects\n */\n const usedExternals = Object.create(null) as Record<string, Record<string, string>>;\n for (const [fullPath, innerMap] of moduleResolveMap) {\n const innerObj = Object.create(null) as Record<string, string>;\n for (const [external, value] of innerMap) {\n innerObj[external] = value;\n }\n usedExternals[fullPath] = innerObj;\n }\n\n /**\n * When externals: true, add the extracted non-workspace deps to usedExternals\n * using a synthetic entry path to track them.\n */\n if (extractedExternals.size > 0) {\n const syntheticPath = path.join(workspaceRoot || projectRoot, '__externals__');\n const externalsObj = Object.create(null) as Record<string, string>;\n for (const [dep, rootPath] of extractedExternals) {\n externalsObj[dep] = rootPath;\n }\n usedExternals[syntheticPath] = externalsObj;\n }\n\n return { output, fileNameToDependencyMap, usedExternals };\n}\n","import { DEPRECATED_EXTERNALS, GLOBAL_EXTERNALS } from './constants';\n\nexport interface NormalizedExternals {\n externalsPreset: boolean;\n mergedExternals: string[];\n}\n\nexport function normalizeExternals(externals?: boolean | string[] | null): NormalizedExternals {\n const userExternals = Array.isArray(externals) ? externals : [];\n\n return {\n externalsPreset: externals === true,\n mergedExternals: [...new Set([...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...userExternals].filter(Boolean))],\n };\n}\n","import { types as t } from '@babel/core';\nimport type { PluginObject } from '@babel/core';\n\nexport function checkConfigExport(result: { hasValidConfig: boolean; projectType?: string }): PluginObject {\n // Track which local variable names are assigned to `new Mastra()`\n const mastraVars = new Set<string>();\n\n return {\n visitor: {\n NewExpression(path) {\n if (!t.isIdentifier(path.node.callee)) {\n return;\n }\n\n const binding = path.scope.getBinding(path.node.callee.name);\n if (\n binding?.path.isImportSpecifier() &&\n t.isIdentifier(binding.path.node.imported, { name: 'MastraFactory' })\n ) {\n result.projectType = 'factory';\n }\n },\n ExportNamedDeclaration(path) {\n const decl = path.node.declaration;\n // 1) export const mastra = new Mastra(...)\n if (t.isVariableDeclaration(decl)) {\n const varDecl = decl.declarations[0];\n if (\n t.isIdentifier(varDecl?.id, { name: 'mastra' }) &&\n t.isNewExpression(varDecl.init) &&\n t.isIdentifier(varDecl.init.callee, { name: 'Mastra' })\n ) {\n result.hasValidConfig = true;\n }\n }\n /**\n * 2) export { foo as mastra }\n * 3) export { mastra }\n * 4) export { mastra, foo }\n */\n if (Array.isArray(path.node.specifiers)) {\n for (const spec of path.node.specifiers) {\n if (\n t.isExportSpecifier(spec) &&\n t.isIdentifier(spec.exported, { name: 'mastra' }) &&\n t.isIdentifier(spec.local) &&\n mastraVars.has(spec.local.name)\n ) {\n result.hasValidConfig = true;\n }\n }\n }\n },\n // For cases 2-4 we need to track whether those variables are assigned to `new Mastra()`\n VariableDeclaration(path) {\n for (const decl of path.node.declarations) {\n if (\n t.isIdentifier(decl.id) &&\n t.isNewExpression(decl.init) &&\n t.isIdentifier(decl.init.callee, { name: 'Mastra' })\n ) {\n mastraVars.add(decl.id.name);\n }\n }\n },\n },\n };\n}\n","import type { PluginObject, NodePath } from '@babel/core';\nimport { types as t } from '@babel/core';\n\n/**\n * Extract string value from a node (supports StringLiteral and TemplateLiteral without expressions)\n */\nfunction getStringValue(node: t.Node | null | undefined): string | null {\n if (!node) return null;\n\n if (t.isStringLiteral(node)) {\n return node.value;\n }\n\n // Handle template literals without expressions: `my-transport`\n if (t.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) {\n return node.quasis[0]?.value.cooked ?? null;\n }\n\n return null;\n}\n\n/**\n * Extract target value from an object property\n */\nfunction extractTargetFromProperty(prop: t.ObjectProperty | t.ObjectMethod | t.SpreadElement): string | null {\n if (!t.isObjectProperty(prop)) return null;\n\n const key = prop.key;\n if (t.isIdentifier(key, { name: 'target' }) || (t.isStringLiteral(key) && key.value === 'target')) {\n return getStringValue(prop.value);\n }\n\n return null;\n}\n\n/**\n * Check if a binding came from a pino import/require\n */\nfunction isBindingFromPino(path: NodePath<t.CallExpression>, identifierName: string): boolean {\n const binding = path.scope.getBinding(identifierName);\n if (!binding) {\n // No binding found - could be global `pino` (unlikely but accept literal name)\n return identifierName === 'pino';\n }\n\n const bindingPath = binding.path;\n\n // Import default: import pino from 'pino'\n if (bindingPath.isImportDefaultSpecifier()) {\n const importDecl = bindingPath.parentPath;\n if (importDecl?.isImportDeclaration()) {\n return importDecl.node.source.value === 'pino';\n }\n }\n\n // Import namespace: import * as p from 'pino'\n if (bindingPath.isImportNamespaceSpecifier()) {\n const importDecl = bindingPath.parentPath;\n if (importDecl?.isImportDeclaration()) {\n return importDecl.node.source.value === 'pino';\n }\n }\n\n // Import specifier: import { default as logger } from 'pino'\n if (bindingPath.isImportSpecifier()) {\n const importDecl = bindingPath.parentPath;\n if (importDecl?.isImportDeclaration() && importDecl.node.source.value === 'pino') {\n const imported = bindingPath.node.imported;\n if (t.isIdentifier(imported) && imported.name === 'default') return true;\n if (t.isStringLiteral(imported) && imported.value === 'default') return true;\n }\n return false;\n }\n\n // Require: const pino = require('pino')\n if (bindingPath.isVariableDeclarator()) {\n const init = bindingPath.node.init;\n if (\n t.isCallExpression(init) &&\n t.isIdentifier(init.callee, { name: 'require' }) &&\n init.arguments.length === 1 &&\n t.isStringLiteral(init.arguments[0]) &&\n init.arguments[0].value === 'pino'\n ) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Check if a call expression is a pino.transport() call using scope analysis\n */\nfunction isPinoTransportCall(path: NodePath<t.CallExpression>): boolean {\n const callee = path.node.callee;\n\n // Must be member expression like `something.transport`\n if (!t.isMemberExpression(callee)) return false;\n if (!t.isIdentifier(callee.property, { name: 'transport' })) return false;\n\n // Handle `pino.transport()` or `logger.transport()` where logger is bound to pino\n if (t.isIdentifier(callee.object)) {\n return isBindingFromPino(path, callee.object.name);\n }\n\n // Handle `pino.default.transport()` pattern (namespace import interop)\n if (\n t.isMemberExpression(callee.object) &&\n t.isIdentifier(callee.object.object) &&\n t.isIdentifier(callee.object.property, { name: 'default' })\n ) {\n return isBindingFromPino(path, callee.object.object.name);\n }\n\n return false;\n}\n\n/**\n * Extract transport targets from a pino.transport() argument\n */\nfunction extractTransportsFromArg(arg: t.Node): string[] {\n const targets: string[] = [];\n\n if (!t.isObjectExpression(arg)) return targets;\n\n for (const prop of arg.properties) {\n if (!t.isObjectProperty(prop)) continue;\n\n const key = prop.key;\n const keyName = t.isIdentifier(key) ? key.name : t.isStringLiteral(key) ? key.value : null;\n\n if (keyName === 'target') {\n // Single target: { target: \"package-name\" }\n const value = getStringValue(prop.value);\n if (value) {\n targets.push(value);\n }\n } else if (keyName === 'targets') {\n // Multiple targets: { targets: [{ target: \"pkg1\" }, { target: \"pkg2\" }] }\n if (t.isArrayExpression(prop.value)) {\n for (const element of prop.value.elements) {\n if (t.isObjectExpression(element)) {\n for (const innerProp of element.properties) {\n const targetValue = extractTargetFromProperty(innerProp);\n if (targetValue) {\n targets.push(targetValue);\n }\n }\n }\n }\n }\n }\n }\n\n return targets;\n}\n\n/**\n * Babel plugin to detect pino transport targets in code.\n * Matches patterns like:\n * - pino.transport({ target: \"package-name\" })\n * - pino.transport({ targets: [{ target: \"package-name\" }] })\n * - variable.transport({ target: \"...\" }) where variable is assigned from pino import\n *\n * @param transports - Set to collect detected transport package names\n * @returns Babel plugin object\n */\nexport function detectPinoTransports(transports: Set<string>): PluginObject {\n return {\n name: 'detect-pino-transports',\n visitor: {\n CallExpression(path) {\n if (!isPinoTransportCall(path)) return;\n\n // Process first argument which should be the transport config object\n const firstArg = path.node.arguments[0];\n if (firstArg && !t.isSpreadElement(firstArg)) {\n for (const target of extractTransportsFromArg(firstArg)) {\n transports.add(target);\n }\n }\n },\n },\n };\n}\n","import { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { basename, isAbsolute, join, relative } from 'node:path';\nimport { transformAsync, transformSync } from '@babel/core';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { IMastraLogger } from '@mastra/core/logger';\nimport type { OutputAsset, OutputChunk } from 'rollup';\nimport * as stackTraceParser from 'stacktrace-parser';\nimport { getWorkspaceInformation } from '../bundler/workspaceDependencies';\nimport type { WorkspacePackageInfo } from '../bundler/workspaceDependencies';\nimport { validate, ValidationError } from '../validator/validate';\nimport { analyzeEntry } from './analyze/analyzeEntry';\nimport { bundleExternals } from './analyze/bundleExternals';\nimport { DEPS_TO_IGNORE } from './analyze/constants';\nimport { normalizeExternals } from './analyze/externals';\nimport { checkConfigExport } from './babel/check-config-export';\nimport { detectPinoTransports } from './babel/detect-pino-transports';\nimport { getPackageMetadata } from './package-info';\nimport type { BundlerOptions, DependencyMetadata, ExternalDependencyInfo } from './types';\nimport {\n getPackageName,\n isBareModuleSpecifier,\n isBuiltinModule,\n isDependencyPartOfPackage,\n isExternalProtocolImport,\n slash,\n} from './utils';\nimport type { BundlerPlatform } from './utils';\n\ntype ErrorId =\n | 'DEPLOYER_ANALYZE_MODULE_NOT_FOUND'\n | 'DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD'\n | 'DEPLOYER_ANALYZE_TYPE_ERROR';\n\nfunction preferDependencyInfo(\n existing: ExternalDependencyInfo | undefined,\n incoming: ExternalDependencyInfo,\n): ExternalDependencyInfo {\n return {\n version: incoming.version ?? existing?.version,\n packageSpec: incoming.packageSpec ?? existing?.packageSpec,\n };\n}\n\nasync function resolveDependencyInfo(\n dep: string,\n existing: ExternalDependencyInfo | undefined,\n parentPaths: string[],\n): Promise<ExternalDependencyInfo> {\n if (existing?.version || existing?.packageSpec) {\n return existing;\n }\n\n const packageName = getPackageName(dep);\n const packageNames = [...new Set([dep, packageName].filter(Boolean) as string[])];\n\n for (const parentPath of parentPaths) {\n for (const name of packageNames) {\n const metadata = await getPackageMetadata(name, parentPath);\n if (metadata.version || metadata.packageSpec) {\n return preferDependencyInfo(existing, metadata);\n }\n }\n }\n\n for (const name of packageNames) {\n const metadata = await getPackageMetadata(name);\n if (metadata.version || metadata.packageSpec) {\n return preferDependencyInfo(existing, metadata);\n }\n }\n\n return existing ?? {};\n}\n\nfunction importerParentPaths(importerId: string | undefined, base: string[]): string[] {\n if (!importerId || importerId.startsWith('\\x00') || !isAbsolute(importerId)) {\n return base;\n }\n\n return [...new Set([importerId, ...base])];\n}\n\nfunction getLastConcreteModuleId(moduleIds: string[]): string | undefined {\n return moduleIds.findLast(id => !id.startsWith('\\x00') && isAbsolute(id));\n}\n\nfunction throwExternalDependencyError({\n errorId,\n moduleName,\n packageName,\n messagePrefix,\n}: {\n errorId: ErrorId;\n moduleName: string;\n packageName: string;\n messagePrefix: string;\n}): never {\n throw new MastraError({\n id: errorId,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: {\n importFile: moduleName,\n packageName: packageName,\n },\n text: `${messagePrefix} \\`${packageName}\\` to your externals.\n\nexport const mastra = new Mastra({\n bundler: {\n externals: [\"${packageName}\"],\n }\n})`,\n });\n}\n\nfunction getPackageNameFromBundledModuleName(moduleName: string) {\n // New encoding uses __ to separate path segments (e.g., @inner__inner-tools -> @inner/inner-tools)\n if (moduleName.includes('__')) {\n return moduleName.replaceAll('__', '/');\n }\n\n // Legacy fallback for old format using - as separator\n const chunks = moduleName.split('-');\n\n if (!chunks.length) {\n return moduleName;\n }\n\n if (chunks[0]?.startsWith('@')) {\n return chunks.slice(0, 2).join('/');\n }\n\n return chunks[0];\n}\n\nfunction validateError(\n err: ValidationError | Error,\n file: OutputChunk,\n {\n binaryMapData,\n workspaceMap,\n }: {\n binaryMapData: Record<string, string[]>;\n logger: IMastraLogger;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n },\n) {\n let moduleName: string | undefined | null = null;\n let errorConfig: {\n id: ErrorId;\n messagePrefix: string;\n } | null = null;\n\n if (err instanceof ValidationError) {\n const parsedStack = stackTraceParser.parse(err.stack);\n if (err.type === 'TypeError') {\n const pkgNameRegex = /.*node_modules\\/([^\\/]+)\\//;\n const stacktraceFrame = parsedStack.find(frame => frame.file && pkgNameRegex.test(frame.file));\n if (stacktraceFrame) {\n const match = stacktraceFrame.file!.match(pkgNameRegex);\n moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename(file.name));\n } else {\n moduleName = getPackageNameFromBundledModuleName(basename(file.name));\n }\n\n errorConfig = {\n id: 'DEPLOYER_ANALYZE_TYPE_ERROR',\n messagePrefix: `Mastra wasn't able to bundle \"${moduleName}\", might be an older commonJS module. Please add`,\n };\n } else if (err.stack?.includes?.('[ERR_MODULE_NOT_FOUND]')) {\n moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];\n\n const parentModuleName = getPackageNameFromBundledModuleName(basename(file.name));\n\n errorConfig = {\n id: 'DEPLOYER_ANALYZE_MODULE_NOT_FOUND',\n messagePrefix: `Mastra wasn't able to build your project, We couldn't load \"${moduleName}\" from \"${parentModuleName}\". Make sure \"${moduleName}\" is installed or add`,\n };\n\n // if they are the same, the feedback we give to our user is not really useful and probably something else went wrong\n if (moduleName === parentModuleName) {\n return;\n }\n }\n }\n\n if (err.message.includes('No native build was found')) {\n const pkgName = getPackageNameFromBundledModuleName(basename(file.name));\n moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;\n errorConfig = {\n id: 'DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD',\n messagePrefix: 'We found a binary dependency in your bundle but we cannot bundle it yet. Please add',\n };\n }\n\n if (moduleName && workspaceMap.has(moduleName)) {\n throw new MastraError({\n id: 'DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: {\n // importFile: moduleName,\n packageName: moduleName,\n },\n text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.\n Error: ${err.stack}`,\n });\n }\n\n if (errorConfig && moduleName) {\n throwExternalDependencyError({\n errorId: errorConfig.id,\n moduleName: moduleName!,\n packageName: moduleName!,\n messagePrefix: errorConfig.messagePrefix,\n });\n }\n}\n\nasync function validateFile(\n root: string,\n file: OutputChunk,\n {\n binaryMapData,\n moduleResolveMapLocation,\n logger,\n workspaceMap,\n stubbedExternals,\n }: {\n binaryMapData: Record<string, string[]>;\n moduleResolveMapLocation: string;\n logger: IMastraLogger;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n stubbedExternals: string[];\n },\n) {\n try {\n if (!file.isDynamicEntry && file.isEntry) {\n // validate if the chunk is actually valid, a failsafe to make sure bundling didn't make any mistakes\n await validate(join(root, file.fileName), {\n moduleResolveMapLocation,\n injectESMShim: false,\n stubbedExternals,\n });\n }\n } catch (err) {\n let errorToHandle = err;\n if (\n err instanceof ValidationError &&\n err.type === 'ReferenceError' &&\n (err.message.startsWith('__dirname') || err.message.startsWith('__filename'))\n ) {\n try {\n await validate(join(root, file.fileName), {\n moduleResolveMapLocation,\n injectESMShim: true,\n stubbedExternals,\n });\n errorToHandle = null;\n } catch (err) {\n errorToHandle = err;\n }\n }\n\n if (errorToHandle instanceof Error) {\n validateError(errorToHandle, file, { binaryMapData, logger, workspaceMap });\n }\n }\n}\n\n/**\n * Validates the bundled output by attempting to import each generated module.\n * Tracks external dependencies that couldn't be bundled.\n *\n * @param output - Bundle output from rollup\n * @param reverseVirtualReferenceMap - Map to resolve virtual module names back to original deps\n * @param outputDir - Directory containing the bundled files\n * @param logger - Logger instance for debugging\n * @param workspaceMap - Map of workspace packages that gets directly passed through for later consumption\n * @returns Analysis result containing dependency mappings\n */\nasync function validateOutput(\n {\n output,\n reverseVirtualReferenceMap,\n usedExternals,\n mergedExternals,\n outputDir,\n projectRoot,\n workspaceMap,\n depsVersionInfo,\n }: {\n output: (OutputChunk | OutputAsset)[];\n reverseVirtualReferenceMap: Map<string, string>;\n usedExternals: Record<string, Record<string, string>>;\n mergedExternals: string[];\n outputDir: string;\n projectRoot: string;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n depsVersionInfo: Map<string, ExternalDependencyInfo>;\n },\n logger: IMastraLogger,\n) {\n const result = {\n dependencies: new Map<string, string>(),\n externalDependencies: new Map<string, ExternalDependencyInfo>(),\n workspaceMap,\n };\n\n const externalMetadataParentPaths = [\n projectRoot,\n ...Array.from(workspaceMap.values()).map(pkgInfo => pkgInfo.location),\n ];\n\n // store resolve map for validation\n // we should resolve the version of the deps\n for (const deps of Object.values(usedExternals)) {\n for (const [dep, importerId] of Object.entries(deps)) {\n if (isExternalProtocolImport(dep)) {\n continue;\n }\n\n const pkgName = getPackageName(dep);\n if (pkgName) {\n // Use version info from analysis if available, then resolve from the module that imported the external.\n const versionInfo = depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName);\n const dependencyInfo = await resolveDependencyInfo(\n dep,\n versionInfo,\n importerParentPaths(importerId, externalMetadataParentPaths),\n );\n result.externalDependencies.set(\n pkgName,\n preferDependencyInfo(result.externalDependencies.get(pkgName), dependencyInfo),\n );\n }\n }\n }\n let binaryMapData: Record<string, string[]> = {};\n\n if (existsSync(join(outputDir, 'binary-map.json'))) {\n const binaryMap = await readFile(join(outputDir, 'binary-map.json'), 'utf-8');\n binaryMapData = JSON.parse(binaryMap);\n }\n\n const stubbedExternals = [...new Set([...mergedExternals, ...DEPS_TO_IGNORE, ...result.externalDependencies.keys()])];\n\n for (const file of output) {\n if (file.type === 'asset') {\n continue;\n }\n\n logger.debug('Validating module', { fileName: file.fileName });\n if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {\n result.dependencies.set(reverseVirtualReferenceMap.get(file.name)!, file.fileName);\n }\n\n // validate if the chunk is actually valid, a failsafe to make sure bundling didn't make any mistakes\n await validateFile(projectRoot, file, {\n binaryMapData,\n moduleResolveMapLocation: join(outputDir, 'module-resolve-map.json'),\n logger,\n workspaceMap,\n stubbedExternals,\n });\n }\n\n return result;\n}\n\n/**\n * Main bundle analysis function that orchestrates the three-step process:\n * 1. Analyze dependencies\n * 2. Bundle dependencies modules\n * 3. Validate generated bundles\n *\n * This helps identify which dependencies need to be externalized vs bundled.\n */\nexport async function analyzeBundle(\n entries: string[],\n mastraEntry: string,\n {\n outputDir,\n projectRoot,\n platform,\n isDev = false,\n bundlerOptions,\n }: {\n outputDir: string;\n projectRoot: string;\n platform: BundlerPlatform;\n isDev?: boolean;\n bundlerOptions?: Pick<BundlerOptions, 'externals' | 'enableSourcemap' | 'dynamicPackages'> | null;\n },\n logger: IMastraLogger,\n) {\n const mastraConfig = await readFile(mastraEntry, 'utf-8');\n const mastraConfigResult: { hasValidConfig: boolean; projectType?: string } = { hasValidConfig: false };\n\n await transformAsync(mastraConfig, {\n filename: mastraEntry,\n presets: [import.meta.resolve('@babel/preset-typescript')],\n plugins: [() => checkConfigExport(mastraConfigResult)],\n });\n\n if (!mastraConfigResult.hasValidConfig) {\n logger.warn('Invalid Mastra config', {\n details:\n '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.',\n });\n }\n\n const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });\n\n const { externalsPreset, mergedExternals } = normalizeExternals(bundlerOptions?.externals);\n const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];\n\n let index = 0;\n const depsToOptimize = new Map<string, DependencyMetadata>();\n\n // Collect pino transports detected across all entries\n const detectedPinoTransports = new Set<string>();\n\n logger.info('Analyzing dependencies...');\n\n // Track external dependencies with their version info\n const allUsedExternals = new Map<string, ExternalDependencyInfo>();\n // Shared cache prevents re-analyzing the same workspace package across entries and recursive calls.\n const analyzeCache = new Map<string, Awaited<ReturnType<typeof analyzeEntry>>>();\n for (const entry of entries) {\n const isVirtualFile = entry.includes('\\n') || !existsSync(entry);\n const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {\n logger,\n sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,\n workspaceMap,\n projectRoot,\n shouldCheckTransitiveDependencies: true,\n analyzeCache,\n });\n\n // Detect pino transports in the bundled output\n transformSync(analyzeResult.output.code, {\n filename: 'pino-detection.js',\n plugins: [() => detectPinoTransports(detectedPinoTransports)],\n configFile: false,\n babelrc: false,\n code: false,\n });\n\n // Write the entry file to the output dir so that we can use it for workspace resolution stuff\n await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);\n\n // Merge dependencies from each entry (main, tools, etc.)\n for (const [dep, metadata] of analyzeResult.dependencies.entries()) {\n const isPartOfExternals = mergedExternals.some(external => isDependencyPartOfPackage(dep, external));\n if (isPartOfExternals || (externalsPreset && !metadata.isWorkspace)) {\n // Add all packages coming from src/mastra with their version info\n const pkgName = getPackageName(dep);\n if (pkgName) {\n allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));\n }\n continue;\n }\n\n if (depsToOptimize.has(dep)) {\n // Merge with existing exports if dependency already exists\n const existingEntry = depsToOptimize.get(dep)!;\n depsToOptimize.set(dep, {\n ...existingEntry,\n version: metadata.version ?? existingEntry.version,\n packageSpec: metadata.packageSpec ?? existingEntry.packageSpec,\n exports: [...new Set([...existingEntry.exports, ...metadata.exports])],\n });\n } else {\n depsToOptimize.set(dep, metadata);\n }\n }\n }\n\n // Build a map of dependency versions from the full analysis result before dev/externalsPreset pruning.\n // Non-workspace deps are removed from optimization below, but their resolved version/packageSpec metadata\n // is still needed when they become externals.\n const depsVersionInfo = new Map<string, ExternalDependencyInfo>();\n for (const [dep, metadata] of depsToOptimize.entries()) {\n const pkgName = getPackageName(dep);\n if (pkgName && (metadata.version || metadata.packageSpec)) {\n depsVersionInfo.set(pkgName, preferDependencyInfo(depsVersionInfo.get(pkgName), metadata));\n }\n // Also store by full import path for subpath imports\n if (metadata.version || metadata.packageSpec) {\n depsVersionInfo.set(dep, preferDependencyInfo(depsVersionInfo.get(dep), metadata));\n }\n }\n\n /**\n * 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.\n */\n if (isDev || externalsPreset) {\n for (const [dep, metadata] of depsToOptimize.entries()) {\n if (!metadata.isWorkspace) {\n depsToOptimize.delete(dep);\n }\n }\n }\n\n const sortedDeps = Array.from(depsToOptimize.keys()).sort();\n logger.info('Optimizing dependencies...');\n logger.debug('Sorted dependencies', { deps: sortedDeps });\n\n const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {\n bundlerOptions: {\n externalsPreset,\n mergedExternals,\n isDev,\n },\n projectRoot,\n workspaceRoot,\n workspaceMap,\n platform,\n });\n\n // Filesystem-relative workspace paths for filtering workspace imports from rollup output.\n // Normalize to forward slashes so the startsWith check works on Windows where\n // path.relative() produces backslashes but rollup uses forward slashes.\n const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map(pkgInfo =>\n slash(relative(workspaceRoot || projectRoot, pkgInfo.location)),\n );\n\n for (const o of output) {\n if (o.type === 'asset') {\n continue;\n }\n\n const importerId = getLastConcreteModuleId(o.moduleIds);\n\n for (const i of o.imports) {\n if (isBuiltinModule(i)) {\n continue;\n }\n\n // Skip relative imports - they're local chunks, not external packages\n if (i.startsWith('.') || i.startsWith('/')) {\n continue;\n }\n\n if (!isBareModuleSpecifier(i) || isExternalProtocolImport(i)) {\n continue;\n }\n\n // Do not include workspace packages\n if (relativeWorkspaceFolderPaths.some(workspacePath => i.startsWith(workspacePath))) {\n continue;\n }\n\n const pkgName = getPackageName(i);\n\n if (pkgName && workspaceMap.has(pkgName)) {\n continue;\n }\n\n if (pkgName) {\n // Try to get version info from our tracked dependencies, then resolve from the chunk's source module.\n const versionInfo = depsVersionInfo.get(i) || depsVersionInfo.get(pkgName);\n const dependencyInfo = await resolveDependencyInfo(\n i,\n versionInfo,\n importerParentPaths(importerId, [\n projectRoot,\n ...Array.from(workspaceMap.values()).map(pkgInfo => pkgInfo.location),\n ]),\n );\n allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), dependencyInfo));\n }\n }\n }\n\n const result = await validateOutput(\n {\n output,\n reverseVirtualReferenceMap: fileNameToDependencyMap,\n usedExternals,\n mergedExternals,\n outputDir,\n projectRoot: workspaceRoot || projectRoot,\n workspaceMap,\n depsVersionInfo,\n },\n logger,\n );\n\n /**\n * Build the final set of external dependencies from four sources:\n * 1. result.externalDependencies - externals discovered during bundle validation\n * 2. allUsedExternals - packages detected via static analysis that matched the externals config\n * 3. detectedPinoTransports - pino transports detected by the plugin during bundling\n * 4. userDynamicPackages - user-specified packages loaded dynamically at runtime\n *\n * Prefer entries with version info over entries without\n */\n const mergedExternalDeps = new Map<string, ExternalDependencyInfo>(result.externalDependencies);\n for (const [dep, info] of allUsedExternals) {\n if (isExternalProtocolImport(dep)) {\n continue;\n }\n\n mergedExternalDeps.set(dep, preferDependencyInfo(mergedExternalDeps.get(dep), info));\n }\n\n const externalMetadataParentPaths = [\n projectRoot,\n ...Array.from(workspaceMap.values()).map(pkgInfo => pkgInfo.location),\n // Last resort: resolve from the deployer's own installed location. Some externals are\n // discovered inside externalized packages (e.g. optional dynamic imports like\n // `import('typescript')` in @mastra/core) without being installed in the user's project.\n import.meta.dirname,\n ];\n\n // Retry externals that were discovered without install metadata (e.g. from entry analysis\n // where the package isn't resolvable from the entry's own location).\n for (const [dep, info] of mergedExternalDeps) {\n if (!info.version && !info.packageSpec) {\n mergedExternalDeps.set(dep, await resolveDependencyInfo(dep, info, externalMetadataParentPaths));\n }\n }\n\n // Add pino transports and user dynamic packages\n for (const transport of detectedPinoTransports) {\n if (!mergedExternalDeps.has(transport)) {\n mergedExternalDeps.set(transport, await resolveDependencyInfo(transport, undefined, externalMetadataParentPaths));\n }\n }\n for (const pkg of userDynamicPackages) {\n if (!mergedExternalDeps.has(pkg)) {\n mergedExternalDeps.set(pkg, await resolveDependencyInfo(pkg, undefined, externalMetadataParentPaths));\n }\n }\n\n return {\n ...result,\n externalDependencies: mergedExternalDeps,\n /**\n * Workspace deps that were optimized (after isDev/externalsPreset pruning).\n * Used by the watcher to re-run optimization when workspace sources change.\n */\n depsToOptimize,\n workspaceRoot,\n outputDir,\n ...(mastraConfigResult.projectType ? { projectType: mastraConfigResult.projectType } : {}),\n };\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAEA,OAAO,eAAe,SAAS,cAAc,EAAE,OAAO,KAAK,CAAC;CAE5D,IAAI,mBAAmB;;;;;CAMvB,SAAS,MAAM,aAAa;EAE1B,OADY,YAAY,MAAM,IACnB,CAAC,CAAC,OAAO,SAAU,OAAO,MAAM;GACzC,IAAI,cAAc,YAAY,IAAI,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI,KAAK,UAAU,IAAI,KAAK,SAAS,IAAI;GAE/G,IAAI,aACF,MAAM,KAAK,WAAW;GAGxB,OAAO;EACT,GAAG,CAAC,CAAC;CACP;CACA,IAAI,WAAW;CACf,IAAI,eAAe;CAEnB,SAAS,YAAY,MAAM;EACzB,IAAI,QAAQ,SAAS,KAAK,IAAI;EAE9B,IAAI,CAAC,OACH,OAAO;EAGT,IAAI,WAAW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,CAAC;CAGpH,KAAK,MAAM,OAAO,qBAChB,IAAI,CAAC,mBAAmB,IAAI,GAAG,GAC7B,mBAAmB,IAAI,KAAK,MAAM,sBAAsB,KAAK,KAAA,GAAW,2BAA2B,CAAC;CAIxG,OAAO;EACL,GAAG;EACH,sBAAsB;;;;;EAKtB;EACA;EACA;EACA,GAAI,mBAAmB,cAAc,EAAE,aAAa,mBAAmB,YAAY,IAAI,CAAC;CAC1F;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as getPackageName, c as isBuiltinModule, f as rollupSafeName, i as getNodeResolveOptions, l as isDependencyPartOfPackage, p as slash, r as getCompiledDepCachePath, s as isBareModuleSpecifier, u as isExternalProtocolImport } from "./utils-FVOUvj-I.js";
|
|
2
|
-
import { i as DepsService } from "./services-
|
|
2
|
+
import { i as DepsService } from "./services-DWdPwTiP.js";
|
|
3
3
|
import { a as tsConfigPaths, c as protocolExternalResolver, d as getPackageRootPath, f as esmShim, i as mastraToolsAliasPlugin, o as subpathExternalsResolver, p as esbuild, r as mastraInternalAliasPlugin, s as removeDeployer, u as getPackageMetadata } from "./bundler-gff4vn1T.js";
|
|
4
4
|
import { spawn } from "child_process";
|
|
5
5
|
import { existsSync } from "fs";
|
|
@@ -845,19 +845,8 @@ function findExternalImporter(module, external, allOutputs, visited = /* @__PURE
|
|
|
845
845
|
* @returns Object containing bundle output and reference map for validation
|
|
846
846
|
*/
|
|
847
847
|
async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
848
|
-
const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions
|
|
849
|
-
const {
|
|
850
|
-
/**
|
|
851
|
-
* 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.
|
|
852
|
-
*/
|
|
853
|
-
let externalsPreset = false;
|
|
854
|
-
if (customExternals === true) externalsPreset = true;
|
|
855
|
-
const externalsList = Array.isArray(customExternals) ? customExternals : [];
|
|
856
|
-
const allExternals = [
|
|
857
|
-
...GLOBAL_EXTERNALS,
|
|
858
|
-
...DEPRECATED_EXTERNALS,
|
|
859
|
-
...externalsList
|
|
860
|
-
];
|
|
848
|
+
const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions, platform = "node" } = options;
|
|
849
|
+
const { externalsPreset, mergedExternals, transpilePackages = [], isDev = false } = bundlerOptions;
|
|
861
850
|
const workspacePackagesNames = Array.from(workspaceMap.keys());
|
|
862
851
|
const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
|
|
863
852
|
/**
|
|
@@ -881,7 +870,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
881
870
|
}
|
|
882
871
|
});
|
|
883
872
|
const output = await buildExternalDependencies(optimizedDependencyEntries, {
|
|
884
|
-
externals:
|
|
873
|
+
externals: mergedExternals,
|
|
885
874
|
packagesToTranspile,
|
|
886
875
|
workspaceMap,
|
|
887
876
|
rootDir: workspaceRoot || projectRoot,
|
|
@@ -894,7 +883,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
894
883
|
});
|
|
895
884
|
const moduleResolveMap = /* @__PURE__ */ new Map();
|
|
896
885
|
const filteredChunks = output.filter((o) => o.type === "chunk");
|
|
897
|
-
for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of
|
|
886
|
+
for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of mergedExternals) {
|
|
898
887
|
if (DEPS_TO_IGNORE.includes(external)) continue;
|
|
899
888
|
const importer = findExternalImporter(o, external, filteredChunks);
|
|
900
889
|
if (importer) {
|
|
@@ -933,6 +922,19 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
|
|
|
933
922
|
};
|
|
934
923
|
}
|
|
935
924
|
//#endregion
|
|
925
|
+
//#region src/build/analyze/externals.ts
|
|
926
|
+
function normalizeExternals(externals) {
|
|
927
|
+
const userExternals = Array.isArray(externals) ? externals : [];
|
|
928
|
+
return {
|
|
929
|
+
externalsPreset: externals === true,
|
|
930
|
+
mergedExternals: [...new Set([
|
|
931
|
+
...GLOBAL_EXTERNALS,
|
|
932
|
+
...DEPRECATED_EXTERNALS,
|
|
933
|
+
...userExternals
|
|
934
|
+
].filter(Boolean))]
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
//#endregion
|
|
936
938
|
//#region src/build/babel/check-config-export.ts
|
|
937
939
|
function checkConfigExport(result) {
|
|
938
940
|
const mastraVars = /* @__PURE__ */ new Set();
|
|
@@ -1205,7 +1207,7 @@ async function validateFile(root, file, { binaryMapData, moduleResolveMapLocatio
|
|
|
1205
1207
|
* @param workspaceMap - Map of workspace packages that gets directly passed through for later consumption
|
|
1206
1208
|
* @returns Analysis result containing dependency mappings
|
|
1207
1209
|
*/
|
|
1208
|
-
async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals,
|
|
1210
|
+
async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals, mergedExternals, outputDir, projectRoot, workspaceMap, depsVersionInfo }, logger) {
|
|
1209
1211
|
const result = {
|
|
1210
1212
|
dependencies: /* @__PURE__ */ new Map(),
|
|
1211
1213
|
externalDependencies: /* @__PURE__ */ new Map(),
|
|
@@ -1226,9 +1228,8 @@ async function validateOutput({ output, reverseVirtualReferenceMap, usedExternal
|
|
|
1226
1228
|
binaryMapData = JSON.parse(binaryMap);
|
|
1227
1229
|
}
|
|
1228
1230
|
const stubbedExternals = [.../* @__PURE__ */ new Set([
|
|
1229
|
-
...
|
|
1231
|
+
...mergedExternals,
|
|
1230
1232
|
...DEPS_TO_IGNORE,
|
|
1231
|
-
...userExternals,
|
|
1232
1233
|
...result.externalDependencies.keys()
|
|
1233
1234
|
])];
|
|
1234
1235
|
for (const file of output) {
|
|
@@ -1263,13 +1264,10 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1263
1264
|
});
|
|
1264
1265
|
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." });
|
|
1265
1266
|
const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
|
|
1266
|
-
|
|
1267
|
-
const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
|
|
1267
|
+
const { externalsPreset, mergedExternals } = normalizeExternals(bundlerOptions?.externals);
|
|
1268
1268
|
const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];
|
|
1269
|
-
if (bundlerOptions?.externals === true) externalsPreset = true;
|
|
1270
1269
|
let index = 0;
|
|
1271
1270
|
const depsToOptimize = /* @__PURE__ */ new Map();
|
|
1272
|
-
const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
|
|
1273
1271
|
const detectedPinoTransports = /* @__PURE__ */ new Set();
|
|
1274
1272
|
logger.info("Analyzing dependencies...");
|
|
1275
1273
|
const allUsedExternals = /* @__PURE__ */ new Map();
|
|
@@ -1295,7 +1293,7 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1295
1293
|
});
|
|
1296
1294
|
await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
|
|
1297
1295
|
for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
|
|
1298
|
-
if (
|
|
1296
|
+
if (mergedExternals.some((external) => isDependencyPartOfPackage(dep, external)) || externalsPreset && !metadata.isWorkspace) {
|
|
1299
1297
|
const pkgName = getPackageName(dep);
|
|
1300
1298
|
if (pkgName) allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));
|
|
1301
1299
|
continue;
|
|
@@ -1328,8 +1326,8 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1328
1326
|
logger.debug("Sorted dependencies", { deps: sortedDeps });
|
|
1329
1327
|
const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
|
|
1330
1328
|
bundlerOptions: {
|
|
1331
|
-
|
|
1332
|
-
|
|
1329
|
+
externalsPreset,
|
|
1330
|
+
mergedExternals,
|
|
1333
1331
|
isDev
|
|
1334
1332
|
},
|
|
1335
1333
|
projectRoot,
|
|
@@ -1358,7 +1356,7 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1358
1356
|
output,
|
|
1359
1357
|
reverseVirtualReferenceMap: fileNameToDependencyMap,
|
|
1360
1358
|
usedExternals,
|
|
1361
|
-
|
|
1359
|
+
mergedExternals,
|
|
1362
1360
|
outputDir,
|
|
1363
1361
|
projectRoot: workspaceRoot || projectRoot,
|
|
1364
1362
|
workspaceMap,
|
|
@@ -1400,6 +1398,6 @@ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, pla
|
|
|
1400
1398
|
};
|
|
1401
1399
|
}
|
|
1402
1400
|
//#endregion
|
|
1403
|
-
export {
|
|
1401
|
+
export { aliasHono as a, packWorkspaceDependencies as c, bundleExternals as i, checkConfigExport as n, collectTransitiveWorkspaceDependencies as o, normalizeExternals as r, getWorkspaceInformation as s, analyzeBundle as t };
|
|
1404
1402
|
|
|
1405
|
-
//# sourceMappingURL=analyze-
|
|
1403
|
+
//# sourceMappingURL=analyze-DuO_fzJD.js.map
|