@mastra/deployer 1.68.0-alpha.0 → 1.68.0-alpha.6
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/dist/_types/@hono_node-server/package.json +1 -0
- package/dist/_types/@mastra_hono/package.json +1 -0
- package/dist/{analyze-hp4aHpms.cjs → analyze-BC22OIkc.cjs} +109 -94
- package/dist/analyze-BC22OIkc.cjs.map +1 -0
- package/dist/{analyze-B5HY26Tt.js → analyze-D3eRdXC9.js} +107 -91
- package/dist/analyze-D3eRdXC9.js.map +1 -0
- package/dist/{arktype-aI7TBD0R-S0daSmHG.js → arktype-aI7TBD0R-BGjyzmsj.js} +2 -2
- package/dist/{arktype-aI7TBD0R-S0daSmHG.js.map → arktype-aI7TBD0R-BGjyzmsj.js.map} +1 -1
- package/dist/{arktype-aI7TBD0R-BuTX_Phx.cjs → arktype-aI7TBD0R-DCxjN6oF.cjs} +2 -2
- package/dist/{arktype-aI7TBD0R-BuTX_Phx.cjs.map → arktype-aI7TBD0R-DCxjN6oF.cjs.map} +1 -1
- package/dist/build/analyze/analyzeEntry.d.ts +3 -1
- package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
- package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
- 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/bundler.cjs +2 -1
- package/dist/build/bundler.d.ts +10 -0
- package/dist/build/bundler.d.ts.map +1 -1
- package/dist/build/bundler.js +2 -2
- package/dist/build/index.cjs +6 -6
- package/dist/build/index.js +6 -6
- package/dist/build/package-info.d.ts +4 -0
- package/dist/build/package-info.d.ts.map +1 -1
- package/dist/build/plugins/tsconfig-paths.d.ts +2 -1
- package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
- package/dist/{build-Boe3fe3L.js → build-C5eBQq1A.js} +6 -6
- package/dist/{build-Boe3fe3L.js.map → build-C5eBQq1A.js.map} +1 -1
- package/dist/{build-Dit9VFE2.cjs → build-D-GPvP7A.cjs} +6 -6
- package/dist/{build-Dit9VFE2.cjs.map → build-D-GPvP7A.cjs.map} +1 -1
- package/dist/bundler/index.cjs +29 -62
- package/dist/bundler/index.cjs.map +1 -1
- package/dist/bundler/index.d.ts +1 -11
- package/dist/bundler/index.d.ts.map +1 -1
- package/dist/bundler/index.js +30 -63
- package/dist/bundler/index.js.map +1 -1
- package/dist/bundler/workspaceDependencies.d.ts +1 -1
- package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
- package/dist/{bundler-CzQiVHzN.js → bundler-CNFQP4Qm.js} +45 -10
- package/dist/bundler-CNFQP4Qm.js.map +1 -0
- package/dist/{bundler-BKf2S2r_.cjs → bundler-I4HUeik1.cjs} +55 -8
- package/dist/bundler-I4HUeik1.cjs.map +1 -0
- package/dist/{bundlerOptions-I2E5y2Wp.cjs → bundlerOptions-CkFbsVoE.cjs} +2 -2
- package/dist/{bundlerOptions-I2E5y2Wp.cjs.map → bundlerOptions-CkFbsVoE.cjs.map} +1 -1
- package/dist/{bundlerOptions-BSySFLb3.js → bundlerOptions-Dg4pdJsM.js} +2 -2
- package/dist/{bundlerOptions-BSySFLb3.js.map → bundlerOptions-Dg4pdJsM.js.map} +1 -1
- package/dist/core-D3wM1JKp.js +1159 -0
- package/dist/core-D3wM1JKp.js.map +1 -0
- package/dist/core-QL_X0T4Y.cjs +1159 -0
- package/dist/core-QL_X0T4Y.cjs.map +1 -0
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-deployment-monorepo.md +2 -2
- package/dist/{effect-QlVUlMFu-tf02PTZR.cjs → effect-QlVUlMFu-B2nZ842E.cjs} +3 -3
- package/dist/{effect-QlVUlMFu-tf02PTZR.cjs.map → effect-QlVUlMFu-B2nZ842E.cjs.map} +1 -1
- package/dist/{effect-QlVUlMFu-BN-VJnMF.js → effect-QlVUlMFu-DbWuPaWV.js} +3 -3
- package/dist/{effect-QlVUlMFu-BN-VJnMF.js.map → effect-QlVUlMFu-DbWuPaWV.js.map} +1 -1
- package/dist/{esm-DZ1Siz1C.cjs → esm-Ai6osZ1a.cjs} +61 -50
- package/dist/esm-Ai6osZ1a.cjs.map +1 -0
- package/dist/{esm-B51vJPGv.js → esm-D-wYOO-S.js} +61 -50
- package/dist/esm-D-wYOO-S.js.map +1 -0
- package/dist/{index-CLddUTqr-eO-ae7Sx.js → index-CLddUTqr-BXqo9et4.js} +8 -8
- package/dist/{index-CLddUTqr-eO-ae7Sx.js.map → index-CLddUTqr-BXqo9et4.js.map} +1 -1
- package/dist/{index-CLddUTqr-DS5tJ3WV.cjs → index-CLddUTqr-DsGkVS-W.cjs} +8 -8
- package/dist/{index-CLddUTqr-DS5tJ3WV.cjs.map → index-CLddUTqr-DsGkVS-W.cjs.map} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.js +3 -3
- package/dist/server/index.cjs +8 -8
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +8 -8
- package/dist/server/index.js.map +1 -1
- package/dist/services/deps.d.ts +1 -1
- 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-BLvNG7v7.cjs → services-Beob47UW.cjs} +42 -23
- package/dist/services-Beob47UW.cjs.map +1 -0
- package/dist/{services-B9KRKBT-.js → services-Lm6PRS4D.js} +42 -23
- package/dist/services-Lm6PRS4D.js.map +1 -0
- package/dist/{sury-CWZTCd75-YUPbTtKO.cjs → sury-CWZTCd75-ChXu4j-p.cjs} +3 -3
- package/dist/{sury-CWZTCd75-YUPbTtKO.cjs.map → sury-CWZTCd75-ChXu4j-p.cjs.map} +1 -1
- package/dist/{sury-CWZTCd75-ClSNrMWF.js → sury-CWZTCd75-OKz7uWLi.js} +3 -3
- package/dist/{sury-CWZTCd75-ClSNrMWF.js.map → sury-CWZTCd75-OKz7uWLi.js.map} +1 -1
- package/dist/{typebox-Dei93FPO-CVSJ3SAf.js → typebox-Dei93FPO-C5ACKU09.js} +2 -2
- package/dist/{typebox-Dei93FPO-CVSJ3SAf.js.map → typebox-Dei93FPO-C5ACKU09.js.map} +1 -1
- package/dist/{typebox-Dei93FPO-BTBshlGz.cjs → typebox-Dei93FPO-KTtPU745.cjs} +2 -2
- package/dist/{typebox-Dei93FPO-BTBshlGz.cjs.map → typebox-Dei93FPO-KTtPU745.cjs.map} +1 -1
- package/dist/{utils-DYi43Kp4.js → utils-Bl3Lm7SI.js} +1 -2
- package/dist/{utils-DYi43Kp4.js.map → utils-Bl3Lm7SI.js.map} +1 -1
- package/dist/{utils-7WDNT3Ca.cjs → utils-Bsr_sEcH.cjs} +2 -2
- package/dist/{utils-7WDNT3Ca.cjs.map → utils-Bsr_sEcH.cjs.map} +1 -1
- package/dist/{valibot--1zFm7rT-Dn5WqdyK.cjs → valibot--1zFm7rT-BeX3W1HK.cjs} +3 -3
- package/dist/{valibot--1zFm7rT-Dn5WqdyK.cjs.map → valibot--1zFm7rT-BeX3W1HK.cjs.map} +1 -1
- package/dist/{valibot--1zFm7rT-BxcEC3Pu.js → valibot--1zFm7rT-BuVb-6oJ.js} +3 -3
- package/dist/{valibot--1zFm7rT-BxcEC3Pu.js.map → valibot--1zFm7rT-BuVb-6oJ.js.map} +1 -1
- package/dist/validator/custom-resolver.cjs +1 -1
- package/dist/validator/custom-resolver.js +1 -1
- package/dist/{zod-Bwrt9trS-Bd40XYOT.js → zod-Bwrt9trS-D5b1oyiT.js} +5 -5
- package/dist/{zod-Bwrt9trS-Bd40XYOT.js.map → zod-Bwrt9trS-D5b1oyiT.js.map} +1 -1
- package/dist/{zod-Bwrt9trS-Bi11nE9Q.cjs → zod-Bwrt9trS-DGQs9DWc.cjs} +5 -5
- package/dist/{zod-Bwrt9trS-Bi11nE9Q.cjs.map → zod-Bwrt9trS-DGQs9DWc.cjs.map} +1 -1
- package/package.json +15 -14
- package/dist/analyze-B5HY26Tt.js.map +0 -1
- package/dist/analyze-hp4aHpms.cjs.map +0 -1
- package/dist/bundler-BKf2S2r_.cjs.map +0 -1
- package/dist/bundler-CzQiVHzN.js.map +0 -1
- package/dist/core-D0wEgdn3.cjs +0 -790
- package/dist/core-D0wEgdn3.cjs.map +0 -1
- package/dist/core-DF65PJXc.js +0 -790
- package/dist/core-DF65PJXc.js.map +0 -1
- package/dist/esm-B51vJPGv.js.map +0 -1
- package/dist/esm-DZ1Siz1C.cjs.map +0 -1
- package/dist/services-B9KRKBT-.js.map +0 -1
- package/dist/services-BLvNG7v7.cjs.map +0 -1
package/dist/bundler/index.cjs
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_rolldown_runtime = require("../rolldown-runtime-emK7D4bc.cjs");
|
|
3
|
-
const require_analyze = require("../analyze-
|
|
4
|
-
const require_utils = require("../utils-
|
|
5
|
-
const require_services = require("../services-
|
|
6
|
-
const require_bundler = require("../bundler-
|
|
7
|
-
const require_bundlerOptions = require("../bundlerOptions-
|
|
8
|
-
let child_process = require("child_process");
|
|
3
|
+
const require_analyze = require("../analyze-BC22OIkc.cjs");
|
|
4
|
+
const require_utils = require("../utils-Bsr_sEcH.cjs");
|
|
5
|
+
const require_services = require("../services-Beob47UW.cjs");
|
|
6
|
+
const require_bundler = require("../bundler-I4HUeik1.cjs");
|
|
7
|
+
const require_bundlerOptions = require("../bundlerOptions-CkFbsVoE.cjs");
|
|
9
8
|
let crypto = require("crypto");
|
|
10
9
|
let fs = require("fs");
|
|
11
10
|
let fs_promises = require("fs/promises");
|
|
@@ -244,46 +243,14 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
244
243
|
async installDependencies(outputDirectory, rootDir = process.cwd(), pnpmOverrides) {
|
|
245
244
|
const deps = new require_services.DepsService(rootDir);
|
|
246
245
|
deps.__setLogger(this.logger);
|
|
247
|
-
|
|
246
|
+
const installOptions = {
|
|
248
247
|
dir: (0, path.join)(outputDirectory, this.outputDir),
|
|
249
248
|
pnpmOverrides,
|
|
250
249
|
pnpmNodeLinker: this.pnpmNodeLinker
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
* can use `npm ci` instead of `npm install`, skipping version resolution entirely.
|
|
256
|
-
* This is a lockfile-only operation — no packages are downloaded.
|
|
257
|
-
*
|
|
258
|
-
* Temporarily moves node_modules out of the way because pnpm's symlink-based
|
|
259
|
-
* layout confuses npm's arborist, then restores it afterwards so that
|
|
260
|
-
* `mastra start` (or wrangler) can still resolve dependencies at runtime.
|
|
261
|
-
*/
|
|
262
|
-
async generateNpmLockfile(outputDir) {
|
|
263
|
-
const nodeModules = (0, path.join)(outputDir, "node_modules");
|
|
264
|
-
const nodeModulesTmp = (0, path.join)(outputDir, "node_modules.__tmp");
|
|
265
|
-
let movedNodeModules = false;
|
|
266
|
-
try {
|
|
267
|
-
if (await fs_extra_esm.default.pathExists(nodeModules)) {
|
|
268
|
-
await fs_extra_esm.default.move(nodeModules, nodeModulesTmp, { overwrite: true });
|
|
269
|
-
movedNodeModules = true;
|
|
270
|
-
}
|
|
271
|
-
(0, child_process.execSync)("npm install --package-lock-only --force", {
|
|
272
|
-
cwd: outputDir,
|
|
273
|
-
stdio: "pipe",
|
|
274
|
-
timeout: 6e4
|
|
275
|
-
});
|
|
276
|
-
} catch {
|
|
277
|
-
this.logger.warn("Failed to generate package-lock.json — deploy will fall back to npm install");
|
|
278
|
-
} finally {
|
|
279
|
-
if (movedNodeModules) {
|
|
280
|
-
await (0, fs_promises.rm)(nodeModules, {
|
|
281
|
-
recursive: true,
|
|
282
|
-
force: true
|
|
283
|
-
});
|
|
284
|
-
await fs_extra_esm.default.move(nodeModulesTmp, nodeModules, { overwrite: true });
|
|
285
|
-
}
|
|
286
|
-
}
|
|
250
|
+
};
|
|
251
|
+
this.logger.info("Updating dependency lockfile and installing dependencies");
|
|
252
|
+
await deps.install(installOptions);
|
|
253
|
+
this.logger.info("Done updating dependency lockfile and installing dependencies");
|
|
287
254
|
}
|
|
288
255
|
async copyPublic(mastraDir, outputDirectory) {
|
|
289
256
|
const publicDir = (0, path.join)(mastraDir, "public");
|
|
@@ -324,10 +291,8 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
324
291
|
}, null, 2));
|
|
325
292
|
this.logger.info("Wrote mastra-project.json for Software Factory project");
|
|
326
293
|
}
|
|
327
|
-
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals }, additionalEntries,
|
|
294
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals }, additionalEntries, projectRoot) {
|
|
328
295
|
const { workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile });
|
|
329
|
-
const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
|
|
330
|
-
const projectRoot = closestPkgJson ? (0, path.dirname)(closestPkgJson) : process.cwd();
|
|
331
296
|
const inputOptions = await require_bundler.getInputOptions(mastraEntryFile, analyzedBundleInfo, this.platform, { "process.env.NODE_ENV": JSON.stringify("production") }, {
|
|
332
297
|
sourcemap: enableSourcemap,
|
|
333
298
|
minify: enableMinify,
|
|
@@ -336,7 +301,7 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
336
301
|
enableEsmShim,
|
|
337
302
|
externalsPreset: externals === true
|
|
338
303
|
});
|
|
339
|
-
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths,
|
|
304
|
+
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, projectRoot);
|
|
340
305
|
const entryInputs = {};
|
|
341
306
|
const virtualEntries = {};
|
|
342
307
|
const entries = {
|
|
@@ -389,6 +354,8 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
389
354
|
async _bundle(serverFile, mastraEntryFile, { projectRoot, outputDirectory, enableEsmShim = true }, toolsPaths = [], bundleLocation = (0, path.join)(outputDirectory, this.outputDir)) {
|
|
390
355
|
const analyzeDir = (0, path.join)(outputDirectory, this.analyzeOutputDir);
|
|
391
356
|
const additionalEntries = this.getAdditionalEntries();
|
|
357
|
+
const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
|
|
358
|
+
const entryProjectRoot = closestPkgJson ? (0, path.dirname)(closestPkgJson) : projectRoot;
|
|
392
359
|
const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);
|
|
393
360
|
const internalBundlerOptions = {
|
|
394
361
|
enableSourcemap: !!bundlerOptions.sourcemap,
|
|
@@ -399,14 +366,14 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
399
366
|
};
|
|
400
367
|
let analyzedBundleInfo;
|
|
401
368
|
try {
|
|
402
|
-
const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths,
|
|
369
|
+
const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, entryProjectRoot);
|
|
403
370
|
analyzedBundleInfo = await require_analyze.analyzeBundle([
|
|
404
371
|
serverFile,
|
|
405
372
|
...Object.values(additionalEntries),
|
|
406
373
|
...Object.values(resolvedToolsPaths)
|
|
407
374
|
], mastraEntryFile, {
|
|
408
375
|
outputDir: analyzeDir,
|
|
409
|
-
projectRoot,
|
|
376
|
+
projectRoot: entryProjectRoot,
|
|
410
377
|
platform: this.platform,
|
|
411
378
|
bundlerOptions: internalBundlerOptions
|
|
412
379
|
}, this.logger);
|
|
@@ -425,7 +392,7 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
425
392
|
mastraEntryFile
|
|
426
393
|
});
|
|
427
394
|
const sourceDependencyConstraints = await getSourceDependencyConstraints({
|
|
428
|
-
projectRoot,
|
|
395
|
+
projectRoot: entryProjectRoot,
|
|
429
396
|
mastraEntryFile,
|
|
430
397
|
workspaceRoot
|
|
431
398
|
});
|
|
@@ -439,7 +406,7 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
439
406
|
const pkgName = require_utils.getPackageName(dep);
|
|
440
407
|
if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) initialWorkspaceDependencies.add(pkgName);
|
|
441
408
|
}
|
|
442
|
-
const transitiveWorkspaceDependencies = require_analyze.collectTransitiveWorkspaceDependencies({
|
|
409
|
+
const transitiveWorkspaceDependencies = await require_analyze.collectTransitiveWorkspaceDependencies({
|
|
443
410
|
workspaceMap: analyzedBundleInfo.workspaceMap,
|
|
444
411
|
initialDependencies: initialWorkspaceDependencies,
|
|
445
412
|
logger: this.logger
|
|
@@ -457,11 +424,14 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
457
424
|
logger: this.logger
|
|
458
425
|
});
|
|
459
426
|
this.logger.info("Bundling Mastra application");
|
|
460
|
-
const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions, additionalEntries,
|
|
427
|
+
const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions, additionalEntries, entryProjectRoot);
|
|
428
|
+
const unresolvedWorkspaceImports = [];
|
|
461
429
|
await (await this.createBundler({
|
|
462
430
|
...inputOptions,
|
|
463
431
|
logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
|
|
464
432
|
onwarn: (warning) => {
|
|
433
|
+
const unresolvedWorkspaceDep = require_bundler.getUnresolvedWorkspaceImport(warning, analyzedBundleInfo.workspaceMap);
|
|
434
|
+
if (unresolvedWorkspaceDep) unresolvedWorkspaceImports.push({ source: unresolvedWorkspaceDep });
|
|
465
435
|
if (warning.code === "CIRCULAR_DEPENDENCY") {
|
|
466
436
|
if (warning.ids?.[0]?.includes("node_modules")) return;
|
|
467
437
|
this.logger.warn("Circular dependency found", { dependency: warning.message.replace("Circular dependency: ", "") });
|
|
@@ -472,6 +442,12 @@ var Bundler = class extends _mastra_core_bundler.MastraBundler {
|
|
|
472
442
|
manualChunks: { mastra: ["#mastra"] },
|
|
473
443
|
sourcemap: internalBundlerOptions.enableSourcemap
|
|
474
444
|
})).write();
|
|
445
|
+
if (unresolvedWorkspaceImports.length > 0) throw new _mastra_core_error.MastraError({
|
|
446
|
+
id: "DEPLOYER_BUNDLER_UNRESOLVED_WORKSPACE_IMPORT",
|
|
447
|
+
text: `Workspace imports could not be resolved during bundling:\n${unresolvedWorkspaceImports.map((i) => ` - ${i.source}`).join("\n")}\n\nThis means the analyzer did not capture these workspace subpath imports during the analysis phase. Try adding the package as a direct dependency of the app, or check the workspace configuration.`,
|
|
448
|
+
domain: _mastra_core_error.ErrorDomain.DEPLOYER,
|
|
449
|
+
category: _mastra_core_error.ErrorCategory.SYSTEM
|
|
450
|
+
});
|
|
475
451
|
const toolImports = [];
|
|
476
452
|
const toolsExports = [];
|
|
477
453
|
Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
|
|
@@ -494,16 +470,7 @@ export const tools = [${toolsExports.join(", ")}]`);
|
|
|
494
470
|
});
|
|
495
471
|
this.logger.info("Done copying .npmrc file");
|
|
496
472
|
if (require_utils.shouldSkipInstall()) this.logger.info("Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)");
|
|
497
|
-
else
|
|
498
|
-
this.logger.info("Installing dependencies");
|
|
499
|
-
await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
|
|
500
|
-
this.logger.info("Done installing dependencies");
|
|
501
|
-
if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {
|
|
502
|
-
this.logger.info("Generating package-lock.json for deploy");
|
|
503
|
-
await this.generateNpmLockfile((0, path.join)(outputDirectory, this.outputDir));
|
|
504
|
-
this.logger.info("Done generating package-lock.json");
|
|
505
|
-
} else this.logger.warn("Skipping package-lock.json generation because the output contains packed workspace dependencies");
|
|
506
|
-
}
|
|
473
|
+
else await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
|
|
507
474
|
} catch (error) {
|
|
508
475
|
if (error instanceof _mastra_core_error.MastraError && (error.id === "DEPLOYER_BUNDLER_FACTORY_UI_MISSING" || error.id === "DEPLOYER_PNPM_IGNORED_BUILDS")) throw error;
|
|
509
476
|
throw new _mastra_core_error.MastraError({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["pkg","getPackageName","MastraBundler","createBundlerUtil","getBundlerOptions","analyzeBundle","DepsService","fsExtra","MastraError","ErrorDomain","ErrorCategory","getWorkspaceInformation","getInputOptions","slash","posix","path","FileService","isBareModuleSpecifier","collectTransitiveWorkspaceDependencies","packWorkspaceDependencies","shouldSkipInstall"],"sources":["../../src/bundler/index.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, emptyDir, readJSON } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { getPackageName, isBareModuleSpecifier, shouldSkipInstall, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport {\n collectTransitiveWorkspaceDependencies,\n getWorkspaceInformation,\n packWorkspaceDependencies,\n} from './workspaceDependencies';\n\nexport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nconst NPM_ALIAS_PREFIX = 'npm:';\n/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */\nconst REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\\s-]+$/;\nconst PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\\/)?[A-Za-z0-9._-]+$/;\nconst TARBALL_SUFFIX_PATTERN = /\\.(?:tgz|tar\\.gz|tar)$/i;\n/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */\nconst FILE_SPEC_PREFIX_PATTERN = /^(?:\\.|~[/\\\\]|[/\\\\]|[A-Za-z]:[/\\\\])/;\n/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */\nconst UNBOUNDED_RANGE_PATTERN = /(?:^|\\|\\||\\s)\\s*(?:[*xX]|>=?\\s*0(?:\\.0)*(?:\\.0)*)\\s*(?:$|\\|\\|)/;\n\n/**\n * Constraints declared by the source app, plus the packages some resolution field pins.\n *\n * Only `dependencies` values are read. Override fields contribute names, never values: which of\n * `overrides`, `resolutions`, `pnpm.overrides` or `pnpm-workspace.yaml` a given install honoured\n * depends on the package manager and its version, so reproducing that precedence would mean\n * emulating three package managers. A name appearing in any of them is enough to know the resolved\n * version was chosen deliberately, which is all this needs.\n */\nexport type SourceDependencyConstraints = {\n dependencies: Record<string, string>;\n pinnedByResolutionField: Set<string>;\n};\n\nconst toStringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n};\n\n/**\n * True when a specifier is something the isolated install in `.mastra/output` can resolve from the\n * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry\n * package and range.\n *\n * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is\n * rejected without this code having to know it exists. The output directory is not a workspace, has\n * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,\n * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.\n */\nexport const isRegistryVersionSpec = (spec: string): boolean => {\n if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) {\n return false;\n }\n\n if (spec.startsWith(NPM_ALIAS_PREFIX)) {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n // Skip index 0 so `npm:@scope/pkg` reads as an alias with no range rather than an empty name.\n const rangeSeparator = alias.lastIndexOf('@');\n const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;\n const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '*';\n\n return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);\n }\n\n return REGISTRY_SPEC_PATTERN.test(spec);\n};\n\n/**\n * True when a specifier names a version the output install can be held to.\n *\n * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the\n * version already resolved, so writing it would let a later install pull something the bundle was\n * never analyzed against.\n */\nconst isBoundedVersionSpec = (spec: string): boolean => {\n const range = spec.startsWith(NPM_ALIAS_PREFIX)\n ? (() => {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n const rangeSeparator = alias.lastIndexOf('@');\n return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '';\n })()\n : spec;\n\n return /\\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);\n};\n\nconst readManifest = async (manifestPath: string | undefined): Promise<Record<string, unknown> | undefined> => {\n if (!manifestPath) {\n return undefined;\n }\n\n try {\n const manifest = await readJSON(manifestPath);\n return manifest && typeof manifest === 'object' ? manifest : undefined;\n } catch {\n // A manifest that cannot be read tells us nothing about intent.\n return undefined;\n }\n};\n\n/** Collect the package names a manifest's resolution fields pin, ignoring their values. */\nconst collectManifestPinnedNames = (manifest: Record<string, unknown> | undefined, pinned: Set<string>) => {\n const pnpmSection = manifest?.pnpm;\n const records = [\n manifest?.overrides,\n manifest?.resolutions,\n pnpmSection && typeof pnpmSection === 'object' ? (pnpmSection as { overrides?: unknown }).overrides : undefined,\n ];\n\n for (const record of records) {\n if (record && typeof record === 'object' && !Array.isArray(record)) {\n for (const key of Object.keys(record)) {\n pinned.add(key);\n }\n }\n }\n};\n\n/**\n * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.\n *\n * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps\n * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff\n * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.\n */\nconst collectPnpmWorkspacePinnedNames = (source: string, pinned: Set<string>) => {\n const lines = source.split(/\\r?\\n/);\n let insideOverrides = false;\n\n for (const line of lines) {\n if (/^\\S/.test(line)) {\n insideOverrides = /^overrides:\\s*$/.test(line);\n continue;\n }\n\n if (!insideOverrides) {\n continue;\n }\n\n const key = /^\\s+(?:'([^']+)'|\"([^\"]+)\"|([^'\"\\s:][^:]*?))\\s*:/.exec(line);\n if (key) {\n pinned.add((key[1] ?? key[2] ?? key[3] ?? '').trim());\n }\n }\n};\n\n/**\n * Read the constraints the source app declared.\n *\n * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and\n * whose directory receives the output, falling back to the manifest above the entry file. Anchoring\n * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed\n * to the bundler is a generated wrapper rather than the app's own source file.\n *\n * Resolution-field names are collected from both that manifest and the workspace root, including the\n * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been\n * chosen deliberately rather than hoisted by accident.\n */\nexport const getSourceDependencyConstraints = async ({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n}: {\n projectRoot: string;\n mastraEntryFile: string;\n workspaceRoot?: string;\n}): Promise<SourceDependencyConstraints> => {\n const manifestPaths = [pkg.up({ cwd: projectRoot }), pkg.up({ cwd: dirname(mastraEntryFile) })].filter(\n (entry, index, entries): entry is string => !!entry && entries.indexOf(entry) === index,\n );\n\n if (workspaceRoot) {\n manifestPaths.push(join(workspaceRoot, 'package.json'));\n }\n\n const pinnedByResolutionField = new Set<string>();\n let dependencies: Record<string, string> | undefined;\n\n for (const manifestPath of manifestPaths) {\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n continue;\n }\n\n // Nearest manifest wins, and an empty `dependencies` record is still that package's answer.\n dependencies ??= toStringRecord(manifest.dependencies);\n collectManifestPinnedNames(manifest, pinnedByResolutionField);\n }\n\n if (workspaceRoot) {\n try {\n collectPnpmWorkspacePinnedNames(\n await readFile(join(workspaceRoot, 'pnpm-workspace.yaml'), 'utf-8'),\n pinnedByResolutionField,\n );\n } catch {\n // No pnpm workspace config, or unreadable: nothing to learn from it.\n }\n }\n\n return { dependencies: dependencies ?? {}, pinnedByResolutionField };\n};\n\nconst findDeclaredConstraint = (\n constraints: SourceDependencyConstraints,\n dependencyName: string,\n): string | undefined => {\n const names = [dependencyName, getPackageName(dependencyName)].filter(\n (name, index, all): name is string => !!name && all.indexOf(name) === index,\n );\n\n for (const name of names) {\n // A pinned package's resolved version is the deliberate answer, so leave it as `main` wrote it.\n if (constraints.pinnedByResolutionField.has(name)) {\n return undefined;\n }\n }\n\n for (const name of names) {\n const declared = (constraints.dependencies[name] ?? '').trim();\n if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) {\n return declared;\n }\n }\n\n return undefined;\n};\n\n/**\n * Prefer the constraint the app declared over the version resolved from `node_modules`.\n *\n * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`\n * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the\n * isolated install then locks it in.\n */\nexport const applySourceDependencyRange = (\n dependencyName: string,\n dependencyInfo: ExternalDependencyInfo,\n constraints: SourceDependencyConstraints,\n): ExternalDependencyInfo => {\n const declared = findDeclaredConstraint(constraints, dependencyName);\n if (!declared) {\n return dependencyInfo;\n }\n\n if (declared.startsWith(NPM_ALIAS_PREFIX)) {\n return { ...dependencyInfo, packageSpec: declared };\n }\n\n // `packageSpec` is set only when the resolved package's own name differs from the requested one, so\n // a bare range under this key describes a different package and the resolved alias is the answer.\n if (dependencyInfo.packageSpec) {\n return dependencyInfo;\n }\n\n return { ...dependencyInfo, version: declared };\n};\n\nfunction toolIdForEntry(relativeEntryFile: string): string {\n const digest = createHash('sha256').update(relativeEntryFile).digest('hex');\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;\n}\n\nexport abstract class Bundler extends MastraBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n // Clean up the output directory first\n await emptyDir(outputDirectory);\n\n await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n await ensureDir(join(outputDirectory, this.outputDir));\n }\n\n async writePackageJson(\n outputDirectory: string,\n dependencies: Map<string, string | ExternalDependencyInfo>,\n resolutions?: Record<string, string>,\n ) {\n this.logger.debug(\"Writing project's package.json\");\n\n await ensureDir(outputDirectory);\n const pkgPath = join(outputDirectory, 'package.json');\n\n const dependenciesMap = new Map();\n for (const [key, value] of dependencies.entries()) {\n const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\n } else {\n // For non-scoped packages, take only the first part before any slash\n const pkgName = key.split('/')[0] || key;\n dependenciesMap.set(pkgName, dependencyValue);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n }\n\n protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n return createBundlerUtil(inputOptions, outputOptions);\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const defaultBundlerOptions: Config['bundler'] = {\n externals: [],\n sourcemap: false,\n transpilePackages: [],\n [IS_DEFAULT]: true,\n } as const;\n\n try {\n const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n return bundlerOptions ?? defaultBundlerOptions;\n } catch (error) {\n this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n }\n\n return defaultBundlerOptions;\n }\n\n protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n return await analyzeBundle(\n ([] as string[]).concat(entry),\n mastraFile,\n {\n outputDir: join(outputDirectory, this.analyzeOutputDir),\n projectRoot: outputDirectory,\n platform: this.platform,\n },\n this.logger,\n );\n }\n\n protected pnpmNodeLinker?: 'hoisted';\n\n protected getAdditionalEntries(): Record<string, string> {\n return {};\n }\n\n protected async installDependencies(\n outputDirectory: string,\n rootDir = process.cwd(),\n pnpmOverrides?: Record<string, string>,\n ) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n\n await deps.install({\n dir: join(outputDirectory, this.outputDir),\n pnpmOverrides,\n pnpmNodeLinker: this.pnpmNodeLinker,\n });\n }\n\n /**\n * Generate a package-lock.json for the output directory so that deploy targets\n * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n * This is a lockfile-only operation — no packages are downloaded.\n *\n * Temporarily moves node_modules out of the way because pnpm's symlink-based\n * layout confuses npm's arborist, then restores it afterwards so that\n * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n */\n private async generateNpmLockfile(outputDir: string): Promise<void> {\n const nodeModules = join(outputDir, 'node_modules');\n const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n let movedNodeModules = false;\n try {\n // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n if (await fsExtra.pathExists(nodeModules)) {\n await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n movedNodeModules = true;\n }\n execSync('npm install --package-lock-only --force', {\n cwd: outputDir,\n stdio: 'pipe',\n timeout: 60_000,\n });\n } catch {\n this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n } finally {\n // Restore node_modules so runtime resolution works\n if (movedNodeModules) {\n await rm(nodeModules, { recursive: true, force: true });\n await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n }\n }\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n /**\n * Writes the `mastra-project.json` deployment marker for Software Factory\n * projects after public assets have been copied. Verifies that the Factory\n * SPA (`factory/index.html`) exists in the output before emitting the marker.\n */\n protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n const outputDir = join(outputDirectory, this.outputDir);\n const factoryIndex = join(outputDir, 'factory', 'index.html');\n if (!existsSync(factoryIndex)) {\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n await writeFile(\n join(outputDir, 'mastra-project.json'),\n JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n );\n this.logger.info('Wrote mastra-project.json for Software Factory project');\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions,\n additionalEntries: Record<string, string>,\n toolProjectRoot: string,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();\n\n const inputOptions: InputOptions = await getInputOptions(\n mastraEntryFile,\n analyzedBundleInfo,\n this.platform,\n {\n 'process.env.NODE_ENV': JSON.stringify('production'),\n },\n {\n sourcemap: enableSourcemap,\n minify: enableMinify,\n workspaceRoot,\n projectRoot,\n enableEsmShim,\n externalsPreset: externals === true,\n },\n );\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, toolProjectRoot);\n const entryInputs: Record<string, string> = {};\n const virtualEntries: Record<string, string> = {};\n const entries = { index: serverFile, ...additionalEntries };\n\n for (const [name, entry] of Object.entries(entries)) {\n if (entry.includes('\\n') || !existsSync(entry)) {\n const virtualId = name === 'index' ? '#entry' : `#entry-${name}`;\n entryInputs[name] = virtualId;\n virtualEntries[virtualId] = entry;\n } else {\n entryInputs[name] = entry;\n }\n }\n\n inputOptions.input = { ...entryInputs, ...toolsInputOptions };\n\n if (Object.keys(virtualEntries).length > 0) {\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual(virtualEntries));\n } else {\n inputOptions.plugins = [virtual(virtualEntries)];\n }\n }\n\n return inputOptions;\n }\n\n getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedMastraDir = slash(mastraDir);\n\n // Prepare default tools paths with glob patterns\n const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n const defaultToolsIgnorePaths = [\n `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n ];\n\n // Combine default path with ignore patterns\n const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n // If no tools paths provided, use only the default paths\n if (toolsPaths.length === 0) {\n return [defaultPaths];\n }\n\n // If tools paths are provided, add the default paths to ensure standard tools are always included\n return [...toolsPaths, defaultPaths];\n }\n\n async listToolsInputOptions(toolsPaths: (string | string[])[], projectRoot: string = process.cwd()) {\n const entries = new Map<string, string>();\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n const relativeEntryFile = relative(projectRoot, entryFile).replaceAll('\\\\', '/');\n entries.set(relativeEntryFile, normalizedEntryFile);\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return Object.fromEntries(\n [...entries.entries()]\n .sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0))\n .map(([relativeEntryFile, entryFile]) => [`tools/${toolIdForEntry(relativeEntryFile)}`, entryFile]),\n );\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n },\n toolsPaths: (string | string[])[] = [],\n bundleLocation: string = join(outputDirectory, this.outputDir),\n ): Promise<void> {\n const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n const additionalEntries = this.getAdditionalEntries();\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n enableMinify: !!bundlerOptions.minify,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, projectRoot);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(additionalEntries), ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot,\n platform: this.platform,\n bundlerOptions: internalBundlerOptions,\n },\n this.logger,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof MastraError) {\n throw error;\n }\n\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n text: `Failed to analyze Mastra application: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n\n const { workspaceRoot } = await getWorkspaceInformation({ dir: projectRoot, mastraEntryFile });\n const sourceDependencyConstraints = await getSourceDependencyConstraints({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n });\n const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));\n }\n\n const initialWorkspaceDependencies = new Set<string>();\n for (const dep of analyzedBundleInfo.dependencies.keys()) {\n const pkgName = getPackageName(dep);\n if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) {\n initialWorkspaceDependencies.add(pkgName);\n }\n }\n\n const transitiveWorkspaceDependencies = collectTransitiveWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n initialDependencies: initialWorkspaceDependencies,\n logger: this.logger,\n });\n\n for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) {\n dependenciesToInstall.set(dep, {\n version: analyzedBundleInfo.workspaceMap.get(dep)?.version,\n packageSpec,\n });\n }\n\n try {\n await this.writePackageJson(\n join(outputDirectory, this.outputDir),\n dependenciesToInstall,\n transitiveWorkspaceDependencies.resolutions,\n );\n if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) {\n await packWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,\n bundleOutputDir: join(outputDirectory, this.outputDir),\n logger: this.logger,\n });\n }\n\n this.logger.info('Bundling Mastra application');\n\n const inputOptions: InputOptions = await this.getBundlerOptions(\n serverFile,\n mastraEntryFile,\n analyzedBundleInfo,\n toolsPaths,\n internalBundlerOptions,\n additionalEntries,\n projectRoot,\n );\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n // For Software Factory projects, write a deterministic deployment marker\n // after public assets (including the SPA) have been copied.\n if (analyzedBundleInfo.projectType === 'factory') {\n await this.writeFactoryMarker(outputDirectory);\n }\n\n this.logger.info('Copying .npmrc file');\n await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n this.logger.info('Done copying .npmrc file');\n\n if (shouldSkipInstall()) {\n this.logger.info('Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)');\n } else {\n this.logger.info('Installing dependencies');\n await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);\n this.logger.info('Done installing dependencies');\n\n if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {\n this.logger.info('Generating package-lock.json for deploy');\n await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n this.logger.info('Done generating package-lock.json');\n } else {\n this.logger.warn(\n 'Skipping package-lock.json generation because the output contains packed workspace dependencies',\n );\n }\n }\n } catch (error) {\n if (\n error instanceof MastraError &&\n (error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING' || error.id === 'DEPLOYER_PNPM_IGNORED_BUILDS')\n ) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n text: `Failed during bundler bundle stage: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n }\n\n async lint(_entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, dirname(outputDirectory));\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,aAAa,OAAO,YAAY;AAE7C,MAAM,mBAAmB;;AAEzB,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAC7B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAEjC,MAAM,0BAA0B;AAgBhC,MAAM,kBAAkB,UAA2C;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;CAGV,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,UAAqC,OAAO,MAAM,OAAO,QAAQ,CACjG;AACF;;;;;;;;;;;AAYA,MAAa,yBAAyB,SAA0B;CAC9D,IAAI,yBAAyB,KAAK,IAAI,KAAK,uBAAuB,KAAK,IAAI,GACzE,OAAO;CAGT,IAAI,KAAK,WAAW,gBAAgB,GAAG;EACrC,MAAM,QAAQ,KAAK,MAAM,CAAuB;EAEhD,MAAM,iBAAiB,MAAM,YAAY,GAAG;EAC5C,MAAM,OAAO,iBAAiB,IAAI,MAAM,MAAM,GAAG,cAAc,IAAI;EACnE,MAAM,QAAQ,iBAAiB,IAAI,MAAM,MAAM,iBAAiB,CAAC,IAAI;EAErE,OAAO,qBAAqB,KAAK,IAAI,KAAK,sBAAsB,KAAK;CACvE;CAEA,OAAO,sBAAsB,KAAK,IAAI;AACxC;;;;;;;;AASA,MAAM,wBAAwB,SAA0B;CACtD,MAAM,QAAQ,KAAK,WAAW,gBAAgB,WACnC;EACL,MAAM,QAAQ,KAAK,MAAM,CAAuB;EAChD,MAAM,iBAAiB,MAA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YAAY;IACpB,UAAUC,mBAAAA,cAAc;GAC1B,GACA,KACF;EACF;CACF;CAEA,MAAM,KAAK,YAAoB,iBAAyB,YAAkD;EACxG,MAAM,oBAAoB,MAAM,KAAK,sBAAsB,aAAA,GAAA,KAAA,QAAA,CAAoB,eAAe,CAAC;EAC/F,MAAM,cAAc,OAAO,KAAK,iBAAiB,CAAC,CAAC;EACnD,IAAI,cAAc,GAChB,KAAK,OAAO,KAAK,eAAe,EAAE,OAAO,YAAY,CAAC;CAE1D;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["pkg","getPackageName","MastraBundler","createBundlerUtil","getBundlerOptions","analyzeBundle","DepsService","MastraError","ErrorDomain","ErrorCategory","getWorkspaceInformation","getInputOptions","slash","posix","path","fsExtra","FileService","isBareModuleSpecifier","collectTransitiveWorkspaceDependencies","packWorkspaceDependencies","getUnresolvedWorkspaceImport","shouldSkipInstall"],"sources":["../../src/bundler/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, emptyDir, readJSON } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions, getUnresolvedWorkspaceImport } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { getPackageName, isBareModuleSpecifier, shouldSkipInstall, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport {\n collectTransitiveWorkspaceDependencies,\n getWorkspaceInformation,\n packWorkspaceDependencies,\n} from './workspaceDependencies';\n\nexport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nconst NPM_ALIAS_PREFIX = 'npm:';\n/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */\nconst REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\\s-]+$/;\nconst PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\\/)?[A-Za-z0-9._-]+$/;\nconst TARBALL_SUFFIX_PATTERN = /\\.(?:tgz|tar\\.gz|tar)$/i;\n/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */\nconst FILE_SPEC_PREFIX_PATTERN = /^(?:\\.|~[/\\\\]|[/\\\\]|[A-Za-z]:[/\\\\])/;\n/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */\nconst UNBOUNDED_RANGE_PATTERN = /(?:^|\\|\\||\\s)\\s*(?:[*xX]|>=?\\s*0(?:\\.0)*(?:\\.0)*)\\s*(?:$|\\|\\|)/;\n\n/**\n * Constraints declared by the source app, plus the packages some resolution field pins.\n *\n * Only `dependencies` values are read. Override fields contribute names, never values: which of\n * `overrides`, `resolutions`, `pnpm.overrides` or `pnpm-workspace.yaml` a given install honoured\n * depends on the package manager and its version, so reproducing that precedence would mean\n * emulating three package managers. A name appearing in any of them is enough to know the resolved\n * version was chosen deliberately, which is all this needs.\n */\nexport type SourceDependencyConstraints = {\n dependencies: Record<string, string>;\n pinnedByResolutionField: Set<string>;\n};\n\nconst toStringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n );\n};\n\n/**\n * True when a specifier is something the isolated install in `.mastra/output` can resolve from the\n * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry\n * package and range.\n *\n * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is\n * rejected without this code having to know it exists. The output directory is not a workspace, has\n * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,\n * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.\n */\nexport const isRegistryVersionSpec = (spec: string): boolean => {\n if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) {\n return false;\n }\n\n if (spec.startsWith(NPM_ALIAS_PREFIX)) {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n // Skip index 0 so `npm:@scope/pkg` reads as an alias with no range rather than an empty name.\n const rangeSeparator = alias.lastIndexOf('@');\n const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;\n const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '*';\n\n return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);\n }\n\n return REGISTRY_SPEC_PATTERN.test(spec);\n};\n\n/**\n * True when a specifier names a version the output install can be held to.\n *\n * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the\n * version already resolved, so writing it would let a later install pull something the bundle was\n * never analyzed against.\n */\nconst isBoundedVersionSpec = (spec: string): boolean => {\n const range = spec.startsWith(NPM_ALIAS_PREFIX)\n ? (() => {\n const alias = spec.slice(NPM_ALIAS_PREFIX.length);\n const rangeSeparator = alias.lastIndexOf('@');\n return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : '';\n })()\n : spec;\n\n return /\\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);\n};\n\nconst readManifest = async (manifestPath: string | undefined): Promise<Record<string, unknown> | undefined> => {\n if (!manifestPath) {\n return undefined;\n }\n\n try {\n const manifest = await readJSON(manifestPath);\n return manifest && typeof manifest === 'object' ? manifest : undefined;\n } catch {\n // A manifest that cannot be read tells us nothing about intent.\n return undefined;\n }\n};\n\n/** Collect the package names a manifest's resolution fields pin, ignoring their values. */\nconst collectManifestPinnedNames = (manifest: Record<string, unknown> | undefined, pinned: Set<string>) => {\n const pnpmSection = manifest?.pnpm;\n const records = [\n manifest?.overrides,\n manifest?.resolutions,\n pnpmSection && typeof pnpmSection === 'object' ? (pnpmSection as { overrides?: unknown }).overrides : undefined,\n ];\n\n for (const record of records) {\n if (record && typeof record === 'object' && !Array.isArray(record)) {\n for (const key of Object.keys(record)) {\n pinned.add(key);\n }\n }\n }\n};\n\n/**\n * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.\n *\n * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps\n * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff\n * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.\n */\nconst collectPnpmWorkspacePinnedNames = (source: string, pinned: Set<string>) => {\n const lines = source.split(/\\r?\\n/);\n let insideOverrides = false;\n\n for (const line of lines) {\n if (/^\\S/.test(line)) {\n insideOverrides = /^overrides:\\s*$/.test(line);\n continue;\n }\n\n if (!insideOverrides) {\n continue;\n }\n\n const key = /^\\s+(?:'([^']+)'|\"([^\"]+)\"|([^'\"\\s:][^:]*?))\\s*:/.exec(line);\n if (key) {\n pinned.add((key[1] ?? key[2] ?? key[3] ?? '').trim());\n }\n }\n};\n\n/**\n * Read the constraints the source app declared.\n *\n * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and\n * whose directory receives the output, falling back to the manifest above the entry file. Anchoring\n * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed\n * to the bundler is a generated wrapper rather than the app's own source file.\n *\n * Resolution-field names are collected from both that manifest and the workspace root, including the\n * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been\n * chosen deliberately rather than hoisted by accident.\n */\nexport const getSourceDependencyConstraints = async ({\n projectRoot,\n mastraEntryFile,\n workspaceRoot,\n}: {\n projectRoot: string;\n mastraEntryFile: string;\n workspaceRoot?: string;\n}): Promise<SourceDependencyConstraints> => {\n const manifestPaths = [pkg.up({ cwd: projectRoot }), pkg.up({ cwd: dirname(mastraEntryFile) })].filter(\n (entry, index, entries): entry is string => !!entry && entries.indexOf(entry) === index,\n );\n\n if (workspaceRoot) {\n manifestPaths.push(join(workspaceRoot, 'package.json'));\n }\n\n const pinnedByResolutionField = new Set<string>();\n let dependencies: Record<string, string> | undefined;\n\n for (const manifestPath of manifestPaths) {\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n continue;\n }\n\n // Nearest manifest wins, and an empty `dependencies` record is still that package's answer.\n dependencies ??= toStringRecord(manifest.dependencies);\n collectManifestPinnedNames(manifest, pinnedByResolutionField);\n }\n\n if (workspaceRoot) {\n try {\n collectPnpmWorkspacePinnedNames(\n await readFile(join(workspaceRoot, 'pnpm-workspace.yaml'), 'utf-8'),\n pinnedByResolutionField,\n );\n } catch {\n // No pnpm workspace config, or unreadable: nothing to learn from it.\n }\n }\n\n return { dependencies: dependencies ?? {}, pinnedByResolutionField };\n};\n\nconst findDeclaredConstraint = (\n constraints: SourceDependencyConstraints,\n dependencyName: string,\n): string | undefined => {\n const names = [dependencyName, getPackageName(dependencyName)].filter(\n (name, index, all): name is string => !!name && all.indexOf(name) === index,\n );\n\n for (const name of names) {\n // A pinned package's resolved version is the deliberate answer, so leave it as `main` wrote it.\n if (constraints.pinnedByResolutionField.has(name)) {\n return undefined;\n }\n }\n\n for (const name of names) {\n const declared = (constraints.dependencies[name] ?? '').trim();\n if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) {\n return declared;\n }\n }\n\n return undefined;\n};\n\n/**\n * Prefer the constraint the app declared over the version resolved from `node_modules`.\n *\n * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`\n * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the\n * isolated install then locks it in.\n */\nexport const applySourceDependencyRange = (\n dependencyName: string,\n dependencyInfo: ExternalDependencyInfo,\n constraints: SourceDependencyConstraints,\n): ExternalDependencyInfo => {\n const declared = findDeclaredConstraint(constraints, dependencyName);\n if (!declared) {\n return dependencyInfo;\n }\n\n if (declared.startsWith(NPM_ALIAS_PREFIX)) {\n return { ...dependencyInfo, packageSpec: declared };\n }\n\n // `packageSpec` is set only when the resolved package's own name differs from the requested one, so\n // a bare range under this key describes a different package and the resolved alias is the answer.\n if (dependencyInfo.packageSpec) {\n return dependencyInfo;\n }\n\n return { ...dependencyInfo, version: declared };\n};\n\nfunction toolIdForEntry(relativeEntryFile: string): string {\n const digest = createHash('sha256').update(relativeEntryFile).digest('hex');\n return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;\n}\n\nexport abstract class Bundler extends MastraBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n // Clean up the output directory first\n await emptyDir(outputDirectory);\n\n await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n await ensureDir(join(outputDirectory, this.outputDir));\n }\n\n async writePackageJson(\n outputDirectory: string,\n dependencies: Map<string, string | ExternalDependencyInfo>,\n resolutions?: Record<string, string>,\n ) {\n this.logger.debug(\"Writing project's package.json\");\n\n await ensureDir(outputDirectory);\n const pkgPath = join(outputDirectory, 'package.json');\n\n const dependenciesMap = new Map();\n for (const [key, value] of dependencies.entries()) {\n const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n if (key.startsWith('@')) {\n // Handle scoped packages (e.g. @org/package)\n const pkgChunks = key.split('/');\n dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\n } else {\n // For non-scoped packages, take only the first part before any slash\n const pkgName = key.split('/')[0] || key;\n dependenciesMap.set(pkgName, dependencyValue);\n }\n }\n\n await writeFile(\n pkgPath,\n JSON.stringify(\n {\n name: 'server',\n version: '1.0.0',\n private: true,\n type: 'module',\n main: 'index.mjs',\n scripts: {\n start: 'node ./index.mjs',\n },\n dependencies: Object.fromEntries(dependenciesMap.entries()),\n ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n },\n null,\n 2,\n ),\n );\n }\n\n protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n return createBundlerUtil(inputOptions, outputOptions);\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const defaultBundlerOptions: Config['bundler'] = {\n externals: [],\n sourcemap: false,\n transpilePackages: [],\n [IS_DEFAULT]: true,\n } as const;\n\n try {\n const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n return bundlerOptions ?? defaultBundlerOptions;\n } catch (error) {\n this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n }\n\n return defaultBundlerOptions;\n }\n\n protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n return await analyzeBundle(\n ([] as string[]).concat(entry),\n mastraFile,\n {\n outputDir: join(outputDirectory, this.analyzeOutputDir),\n projectRoot: outputDirectory,\n platform: this.platform,\n },\n this.logger,\n );\n }\n\n protected pnpmNodeLinker?: 'hoisted';\n\n protected getAdditionalEntries(): Record<string, string> {\n return {};\n }\n\n protected async installDependencies(\n outputDirectory: string,\n rootDir = process.cwd(),\n pnpmOverrides?: Record<string, string>,\n ) {\n const deps = new DepsService(rootDir);\n deps.__setLogger(this.logger);\n const installOptions = {\n dir: join(outputDirectory, this.outputDir),\n pnpmOverrides,\n pnpmNodeLinker: this.pnpmNodeLinker,\n };\n\n this.logger.info('Updating dependency lockfile and installing dependencies');\n await deps.install(installOptions);\n this.logger.info('Done updating dependency lockfile and installing dependencies');\n }\n\n protected async copyPublic(mastraDir: string, outputDirectory: string) {\n const publicDir = join(mastraDir, 'public');\n\n try {\n await stat(publicDir);\n } catch {\n return;\n }\n\n await copy(publicDir, join(outputDirectory, this.outputDir));\n }\n\n protected async copyDOTNPMRC({\n rootDir = process.cwd(),\n outputDirectory,\n }: {\n rootDir?: string;\n outputDirectory: string;\n }) {\n const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n try {\n await stat(sourceDotNpmRcPath);\n await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n } catch {\n return;\n }\n }\n\n /**\n * Writes the `mastra-project.json` deployment marker for Software Factory\n * projects after public assets have been copied. Verifies that the Factory\n * SPA (`factory/index.html`) exists in the output before emitting the marker.\n */\n protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n const outputDir = join(outputDirectory, this.outputDir);\n const factoryIndex = join(outputDir, 'factory', 'index.html');\n if (!existsSync(factoryIndex)) {\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n await writeFile(\n join(outputDir, 'mastra-project.json'),\n JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n );\n this.logger.info('Wrote mastra-project.json for Software Factory project');\n }\n\n protected async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions,\n additionalEntries: Record<string, string>,\n projectRoot: string,\n ) {\n const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n\n const inputOptions: InputOptions = await getInputOptions(\n mastraEntryFile,\n analyzedBundleInfo,\n this.platform,\n {\n 'process.env.NODE_ENV': JSON.stringify('production'),\n },\n {\n sourcemap: enableSourcemap,\n minify: enableMinify,\n workspaceRoot,\n projectRoot,\n enableEsmShim,\n externalsPreset: externals === true,\n },\n );\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, projectRoot);\n const entryInputs: Record<string, string> = {};\n const virtualEntries: Record<string, string> = {};\n const entries = { index: serverFile, ...additionalEntries };\n\n for (const [name, entry] of Object.entries(entries)) {\n if (entry.includes('\\n') || !existsSync(entry)) {\n const virtualId = name === 'index' ? '#entry' : `#entry-${name}`;\n entryInputs[name] = virtualId;\n virtualEntries[virtualId] = entry;\n } else {\n entryInputs[name] = entry;\n }\n }\n\n inputOptions.input = { ...entryInputs, ...toolsInputOptions };\n\n if (Object.keys(virtualEntries).length > 0) {\n if (Array.isArray(inputOptions.plugins)) {\n inputOptions.plugins.unshift(virtual(virtualEntries));\n } else {\n inputOptions.plugins = [virtual(virtualEntries)];\n }\n }\n\n return inputOptions;\n }\n\n getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n // Normalize Windows paths to forward slashes for consistent handling\n const normalizedMastraDir = slash(mastraDir);\n\n // Prepare default tools paths with glob patterns\n const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n const defaultToolsIgnorePaths = [\n `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n ];\n\n // Combine default path with ignore patterns\n const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n // If no tools paths provided, use only the default paths\n if (toolsPaths.length === 0) {\n return [defaultPaths];\n }\n\n // If tools paths are provided, add the default paths to ensure standard tools are always included\n return [...toolsPaths, defaultPaths];\n }\n\n async listToolsInputOptions(toolsPaths: (string | string[])[], projectRoot: string = process.cwd()) {\n const entries = new Map<string, string>();\n\n for (const toolPath of toolsPaths) {\n const expandedPaths = await glob(toolPath, {\n absolute: true,\n expandDirectories: false,\n });\n\n for (const path of expandedPaths) {\n if (await fsExtra.pathExists(path)) {\n const fileService = new FileService();\n const entryFile = fileService.getFirstExistingFile([\n join(path, 'index.ts'),\n join(path, 'index.js'),\n path, // if path itself is a file\n ]);\n\n // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n if (!entryFile || (await stat(entryFile)).isDirectory()) {\n this.logger.warn('No entry file found, skipping', { path });\n continue;\n }\n\n const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n const relativeEntryFile = relative(projectRoot, entryFile).replaceAll('\\\\', '/');\n entries.set(relativeEntryFile, normalizedEntryFile);\n } else {\n this.logger.warn('Tool path does not exist, skipping', { path });\n }\n }\n }\n\n return Object.fromEntries(\n [...entries.entries()]\n .sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0))\n .map(([relativeEntryFile, entryFile]) => [`tools/${toolIdForEntry(relativeEntryFile)}`, entryFile]),\n );\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n },\n toolsPaths: (string | string[])[] = [],\n bundleLocation: string = join(outputDirectory, this.outputDir),\n ): Promise<void> {\n const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n const additionalEntries = this.getAdditionalEntries();\n const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n const entryProjectRoot = closestPkgJson ? dirname(closestPkgJson) : projectRoot;\n\n const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n const internalBundlerOptions: BundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n enableMinify: !!bundlerOptions.minify,\n externals: bundlerOptions.externals ?? [],\n enableEsmShim,\n dynamicPackages: bundlerOptions.dynamicPackages,\n };\n\n let analyzedBundleInfo;\n try {\n const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, entryProjectRoot);\n analyzedBundleInfo = await analyzeBundle(\n [serverFile, ...Object.values(additionalEntries), ...Object.values(resolvedToolsPaths)],\n mastraEntryFile,\n {\n outputDir: analyzeDir,\n projectRoot: entryProjectRoot,\n platform: this.platform,\n bundlerOptions: internalBundlerOptions,\n },\n this.logger,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n\n if (error instanceof MastraError) {\n throw error;\n }\n\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n text: `Failed to analyze Mastra application: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n\n const { workspaceRoot } = await getWorkspaceInformation({ dir: projectRoot, mastraEntryFile });\n const sourceDependencyConstraints = await getSourceDependencyConstraints({\n projectRoot: entryProjectRoot,\n mastraEntryFile,\n workspaceRoot,\n });\n const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n continue;\n }\n\n dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));\n }\n\n const initialWorkspaceDependencies = new Set<string>();\n for (const dep of analyzedBundleInfo.dependencies.keys()) {\n const pkgName = getPackageName(dep);\n if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) {\n initialWorkspaceDependencies.add(pkgName);\n }\n }\n\n const transitiveWorkspaceDependencies = await collectTransitiveWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n initialDependencies: initialWorkspaceDependencies,\n logger: this.logger,\n });\n\n for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) {\n dependenciesToInstall.set(dep, {\n version: analyzedBundleInfo.workspaceMap.get(dep)?.version,\n packageSpec,\n });\n }\n\n try {\n await this.writePackageJson(\n join(outputDirectory, this.outputDir),\n dependenciesToInstall,\n transitiveWorkspaceDependencies.resolutions,\n );\n if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) {\n await packWorkspaceDependencies({\n workspaceMap: analyzedBundleInfo.workspaceMap,\n usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,\n bundleOutputDir: join(outputDirectory, this.outputDir),\n logger: this.logger,\n });\n }\n\n this.logger.info('Bundling Mastra application');\n\n const inputOptions: InputOptions = await this.getBundlerOptions(\n serverFile,\n mastraEntryFile,\n analyzedBundleInfo,\n toolsPaths,\n internalBundlerOptions,\n additionalEntries,\n entryProjectRoot,\n );\n\n const unresolvedWorkspaceImports: Array<{ source: string }> = [];\n\n const bundler = await this.createBundler(\n {\n ...inputOptions,\n logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n onwarn: warning => {\n const unresolvedWorkspaceDep = getUnresolvedWorkspaceImport(\n warning as { code: string; source?: string; id?: string },\n analyzedBundleInfo.workspaceMap,\n );\n if (unresolvedWorkspaceDep) {\n unresolvedWorkspaceImports.push({ source: unresolvedWorkspaceDep });\n }\n\n if (warning.code === 'CIRCULAR_DEPENDENCY') {\n if (warning.ids?.[0]?.includes('node_modules')) {\n return;\n }\n\n this.logger.warn('Circular dependency found', {\n dependency: warning.message.replace('Circular dependency: ', ''),\n });\n }\n },\n },\n {\n dir: bundleLocation,\n manualChunks: {\n mastra: ['#mastra'],\n },\n sourcemap: internalBundlerOptions.enableSourcemap,\n },\n );\n\n await bundler.write();\n\n if (unresolvedWorkspaceImports.length > 0) {\n const importList = unresolvedWorkspaceImports.map(i => ` - ${i.source}`).join('\\n');\n throw new MastraError({\n id: 'DEPLOYER_BUNDLER_UNRESOLVED_WORKSPACE_IMPORT',\n text: `Workspace imports could not be resolved during bundling:\\n${importList}\\n\\nThis means the analyzer did not capture these workspace subpath imports during the analysis phase. Try adding the package as a direct dependency of the app, or check the workspace configuration.`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n });\n }\n const toolImports: string[] = [];\n const toolsExports: string[] = [];\n Array.from(Object.keys(inputOptions.input || {}))\n .filter(key => key.startsWith('tools/'))\n .forEach((key, index) => {\n const toolExport = `tool${index}`;\n toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n toolsExports.push(toolExport);\n });\n\n await writeFile(\n join(bundleLocation, 'tools.mjs'),\n `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n );\n this.logger.info('Bundling Mastra done');\n\n this.logger.info('Copying public files');\n await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n this.logger.info('Done copying public files');\n\n // For Software Factory projects, write a deterministic deployment marker\n // after public assets (including the SPA) have been copied.\n if (analyzedBundleInfo.projectType === 'factory') {\n await this.writeFactoryMarker(outputDirectory);\n }\n\n this.logger.info('Copying .npmrc file');\n await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n this.logger.info('Done copying .npmrc file');\n\n if (shouldSkipInstall()) {\n this.logger.info('Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)');\n } else {\n await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);\n }\n } catch (error) {\n if (\n error instanceof MastraError &&\n (error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING' || error.id === 'DEPLOYER_PNPM_IGNORED_BUILDS')\n ) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n throw new MastraError(\n {\n id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n text: `Failed during bundler bundle stage: ${message}`,\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.SYSTEM,\n },\n error,\n );\n }\n }\n\n async lint(_entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, dirname(outputDirectory));\n const toolsLength = Object.keys(toolsInputOptions).length;\n if (toolsLength > 0) {\n this.logger.info('Found tools', { count: toolsLength });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,a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AAK,OAAO,KAAK,qBAAqB;GACtC,MAAM,KAAK,aAAa;IAAE;IAAiB,SAAS;GAAY,CAAC;GAEjE,KAAK,OAAO,KAAK,0BAA0B;GAE3C,IAAIY,cAAAA,kBAAkB,GACpB,KAAK,OAAO,KAAK,kEAAkE;QAEnF,MAAM,KAAK,oBAAoB,iBAAiB,aAAa,gCAAgC,WAAW;EAE5G,SAAS,OAAO;GACd,IACE,iBAAiBd,mBAAAA,gBAChB,MAAM,OAAO,yCAAyC,MAAM,OAAO,iCAEpE,MAAM;GAIR,MAAM,IAAIA,mBAAAA,YACR;IACE,IAAI;IACJ,MAAM,uCAJM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAKjE,QAAQC,mBAAAA,YAAY;IACpB,UAAUC,mBAAAA,cAAc;GAC1B,GACA,KACF;EACF;CACF;CAEA,MAAM,KAAK,YAAoB,iBAAyB,YAAkD;EACxG,MAAM,oBAAoB,MAAM,KAAK,sBAAsB,aAAA,GAAA,KAAA,QAAA,CAAoB,eAAe,CAAC;EAC/F,MAAM,cAAc,OAAO,KAAK,iBAAiB,CAAC,CAAC;EACnD,IAAI,cAAc,GAChB,KAAK,OAAO,KAAK,eAAe,EAAE,OAAO,YAAY,CAAC;CAE1D;AACF"}
|
package/dist/bundler/index.d.ts
CHANGED
|
@@ -82,16 +82,6 @@ export declare abstract class Bundler extends MastraBundler {
|
|
|
82
82
|
protected pnpmNodeLinker?: 'hoisted';
|
|
83
83
|
protected getAdditionalEntries(): Record<string, string>;
|
|
84
84
|
protected installDependencies(outputDirectory: string, rootDir?: string, pnpmOverrides?: Record<string, string>): Promise<void>;
|
|
85
|
-
/**
|
|
86
|
-
* Generate a package-lock.json for the output directory so that deploy targets
|
|
87
|
-
* can use `npm ci` instead of `npm install`, skipping version resolution entirely.
|
|
88
|
-
* This is a lockfile-only operation — no packages are downloaded.
|
|
89
|
-
*
|
|
90
|
-
* Temporarily moves node_modules out of the way because pnpm's symlink-based
|
|
91
|
-
* layout confuses npm's arborist, then restores it afterwards so that
|
|
92
|
-
* `mastra start` (or wrangler) can still resolve dependencies at runtime.
|
|
93
|
-
*/
|
|
94
|
-
private generateNpmLockfile;
|
|
95
85
|
protected copyPublic(mastraDir: string, outputDirectory: string): Promise<void>;
|
|
96
86
|
protected copyDOTNPMRC({ rootDir, outputDirectory, }: {
|
|
97
87
|
rootDir?: string;
|
|
@@ -103,7 +93,7 @@ export declare abstract class Bundler extends MastraBundler {
|
|
|
103
93
|
* SPA (`factory/index.html`) exists in the output before emitting the marker.
|
|
104
94
|
*/
|
|
105
95
|
protected writeFactoryMarker(outputDirectory: string): Promise<void>;
|
|
106
|
-
protected getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[], { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions, additionalEntries: Record<string, string>,
|
|
96
|
+
protected getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[], { enableSourcemap, enableMinify, enableEsmShim, externals }: BundlerOptions, additionalEntries: Record<string, string>, projectRoot: string): Promise<InputOptions>;
|
|
107
97
|
getAllToolPaths(mastraDir: string, toolsPaths?: (string | string[])[]): (string | string[])[];
|
|
108
98
|
listToolsInputOptions(toolsPaths: (string | string[])[], projectRoot?: string): Promise<{
|
|
109
99
|
[k: string]: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bundler/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bundler/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAIlD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa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AG,MAAM,EAAE,CAAC,EAAE,EACjC,EAAE,eAAe,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,cAAc,EAC3E,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACzC,WAAW,EAAE,MAAM;IAgDrB,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,GAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAO,GAAG,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE;IAuB3F,qBAAqB,CAAC,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE,WAAW,GAAE,MAAsB;;;cAwClF,OAAO,CACrB,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,MAAM,EACvB,EACE,WAAW,EACX,eAAe,EACf,aAAoB,GACrB,EAAE;QACD,WAAW,EAAE,MAAM,CAAC;QACpB,eAAe,EAAE,MAAM,CAAC;QACxB,aAAa,CAAC,EAAE,OAAO,CAAC;KACzB,EACD,UAAU,GAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAO,EACtC,cAAc,GAAE,MAA8C,GAC7D,OAAO,CAAC,IAAI,CAAC;IAuNV,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAO1G"}
|
package/dist/bundler/index.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import { c as packWorkspaceDependencies, o as collectTransitiveWorkspaceDependencies, s as getWorkspaceInformation, t as analyzeBundle } from "../analyze-
|
|
2
|
-
import { a as getPackageName, m as slash, p as shouldSkipInstall, s as isBareModuleSpecifier } from "../utils-
|
|
3
|
-
import { i as DepsService, t as FileService } from "../services-
|
|
4
|
-
import { n as getInputOptions, t as createBundler } from "../bundler-
|
|
5
|
-
import { t as getBundlerOptions } from "../bundlerOptions-
|
|
6
|
-
import { execSync } from "child_process";
|
|
1
|
+
import { c as packWorkspaceDependencies, o as collectTransitiveWorkspaceDependencies, s as getWorkspaceInformation, t as analyzeBundle } from "../analyze-D3eRdXC9.js";
|
|
2
|
+
import { a as getPackageName, m as slash, p as shouldSkipInstall, s as isBareModuleSpecifier } from "../utils-Bl3Lm7SI.js";
|
|
3
|
+
import { i as DepsService, t as FileService } from "../services-Lm6PRS4D.js";
|
|
4
|
+
import { n as getInputOptions, r as getUnresolvedWorkspaceImport, t as createBundler } from "../bundler-CNFQP4Qm.js";
|
|
5
|
+
import { t as getBundlerOptions } from "../bundlerOptions-Dg4pdJsM.js";
|
|
7
6
|
import { createHash } from "crypto";
|
|
8
7
|
import { existsSync } from "fs";
|
|
9
|
-
import { readFile,
|
|
8
|
+
import { readFile, stat, writeFile } from "fs/promises";
|
|
10
9
|
import { dirname, join, posix, relative } from "path";
|
|
11
10
|
import { MastraBundler } from "@mastra/core/bundler";
|
|
12
11
|
import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
|
|
@@ -239,46 +238,14 @@ var Bundler = class extends MastraBundler {
|
|
|
239
238
|
async installDependencies(outputDirectory, rootDir = process.cwd(), pnpmOverrides) {
|
|
240
239
|
const deps = new DepsService(rootDir);
|
|
241
240
|
deps.__setLogger(this.logger);
|
|
242
|
-
|
|
241
|
+
const installOptions = {
|
|
243
242
|
dir: join(outputDirectory, this.outputDir),
|
|
244
243
|
pnpmOverrides,
|
|
245
244
|
pnpmNodeLinker: this.pnpmNodeLinker
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
* can use `npm ci` instead of `npm install`, skipping version resolution entirely.
|
|
251
|
-
* This is a lockfile-only operation — no packages are downloaded.
|
|
252
|
-
*
|
|
253
|
-
* Temporarily moves node_modules out of the way because pnpm's symlink-based
|
|
254
|
-
* layout confuses npm's arborist, then restores it afterwards so that
|
|
255
|
-
* `mastra start` (or wrangler) can still resolve dependencies at runtime.
|
|
256
|
-
*/
|
|
257
|
-
async generateNpmLockfile(outputDir) {
|
|
258
|
-
const nodeModules = join(outputDir, "node_modules");
|
|
259
|
-
const nodeModulesTmp = join(outputDir, "node_modules.__tmp");
|
|
260
|
-
let movedNodeModules = false;
|
|
261
|
-
try {
|
|
262
|
-
if (await fsExtra.pathExists(nodeModules)) {
|
|
263
|
-
await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });
|
|
264
|
-
movedNodeModules = true;
|
|
265
|
-
}
|
|
266
|
-
execSync("npm install --package-lock-only --force", {
|
|
267
|
-
cwd: outputDir,
|
|
268
|
-
stdio: "pipe",
|
|
269
|
-
timeout: 6e4
|
|
270
|
-
});
|
|
271
|
-
} catch {
|
|
272
|
-
this.logger.warn("Failed to generate package-lock.json — deploy will fall back to npm install");
|
|
273
|
-
} finally {
|
|
274
|
-
if (movedNodeModules) {
|
|
275
|
-
await rm(nodeModules, {
|
|
276
|
-
recursive: true,
|
|
277
|
-
force: true
|
|
278
|
-
});
|
|
279
|
-
await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });
|
|
280
|
-
}
|
|
281
|
-
}
|
|
245
|
+
};
|
|
246
|
+
this.logger.info("Updating dependency lockfile and installing dependencies");
|
|
247
|
+
await deps.install(installOptions);
|
|
248
|
+
this.logger.info("Done updating dependency lockfile and installing dependencies");
|
|
282
249
|
}
|
|
283
250
|
async copyPublic(mastraDir, outputDirectory) {
|
|
284
251
|
const publicDir = join(mastraDir, "public");
|
|
@@ -319,10 +286,8 @@ var Bundler = class extends MastraBundler {
|
|
|
319
286
|
}, null, 2));
|
|
320
287
|
this.logger.info("Wrote mastra-project.json for Software Factory project");
|
|
321
288
|
}
|
|
322
|
-
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals }, additionalEntries,
|
|
289
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals }, additionalEntries, projectRoot) {
|
|
323
290
|
const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });
|
|
324
|
-
const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });
|
|
325
|
-
const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();
|
|
326
291
|
const inputOptions = await getInputOptions(mastraEntryFile, analyzedBundleInfo, this.platform, { "process.env.NODE_ENV": JSON.stringify("production") }, {
|
|
327
292
|
sourcemap: enableSourcemap,
|
|
328
293
|
minify: enableMinify,
|
|
@@ -331,7 +296,7 @@ var Bundler = class extends MastraBundler {
|
|
|
331
296
|
enableEsmShim,
|
|
332
297
|
externalsPreset: externals === true
|
|
333
298
|
});
|
|
334
|
-
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths,
|
|
299
|
+
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, projectRoot);
|
|
335
300
|
const entryInputs = {};
|
|
336
301
|
const virtualEntries = {};
|
|
337
302
|
const entries = {
|
|
@@ -384,6 +349,8 @@ var Bundler = class extends MastraBundler {
|
|
|
384
349
|
async _bundle(serverFile, mastraEntryFile, { projectRoot, outputDirectory, enableEsmShim = true }, toolsPaths = [], bundleLocation = join(outputDirectory, this.outputDir)) {
|
|
385
350
|
const analyzeDir = join(outputDirectory, this.analyzeOutputDir);
|
|
386
351
|
const additionalEntries = this.getAdditionalEntries();
|
|
352
|
+
const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });
|
|
353
|
+
const entryProjectRoot = closestPkgJson ? dirname(closestPkgJson) : projectRoot;
|
|
387
354
|
const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);
|
|
388
355
|
const internalBundlerOptions = {
|
|
389
356
|
enableSourcemap: !!bundlerOptions.sourcemap,
|
|
@@ -394,14 +361,14 @@ var Bundler = class extends MastraBundler {
|
|
|
394
361
|
};
|
|
395
362
|
let analyzedBundleInfo;
|
|
396
363
|
try {
|
|
397
|
-
const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths,
|
|
364
|
+
const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, entryProjectRoot);
|
|
398
365
|
analyzedBundleInfo = await analyzeBundle([
|
|
399
366
|
serverFile,
|
|
400
367
|
...Object.values(additionalEntries),
|
|
401
368
|
...Object.values(resolvedToolsPaths)
|
|
402
369
|
], mastraEntryFile, {
|
|
403
370
|
outputDir: analyzeDir,
|
|
404
|
-
projectRoot,
|
|
371
|
+
projectRoot: entryProjectRoot,
|
|
405
372
|
platform: this.platform,
|
|
406
373
|
bundlerOptions: internalBundlerOptions
|
|
407
374
|
}, this.logger);
|
|
@@ -420,7 +387,7 @@ var Bundler = class extends MastraBundler {
|
|
|
420
387
|
mastraEntryFile
|
|
421
388
|
});
|
|
422
389
|
const sourceDependencyConstraints = await getSourceDependencyConstraints({
|
|
423
|
-
projectRoot,
|
|
390
|
+
projectRoot: entryProjectRoot,
|
|
424
391
|
mastraEntryFile,
|
|
425
392
|
workspaceRoot
|
|
426
393
|
});
|
|
@@ -434,7 +401,7 @@ var Bundler = class extends MastraBundler {
|
|
|
434
401
|
const pkgName = getPackageName(dep);
|
|
435
402
|
if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) initialWorkspaceDependencies.add(pkgName);
|
|
436
403
|
}
|
|
437
|
-
const transitiveWorkspaceDependencies = collectTransitiveWorkspaceDependencies({
|
|
404
|
+
const transitiveWorkspaceDependencies = await collectTransitiveWorkspaceDependencies({
|
|
438
405
|
workspaceMap: analyzedBundleInfo.workspaceMap,
|
|
439
406
|
initialDependencies: initialWorkspaceDependencies,
|
|
440
407
|
logger: this.logger
|
|
@@ -452,11 +419,14 @@ var Bundler = class extends MastraBundler {
|
|
|
452
419
|
logger: this.logger
|
|
453
420
|
});
|
|
454
421
|
this.logger.info("Bundling Mastra application");
|
|
455
|
-
const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions, additionalEntries,
|
|
422
|
+
const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions, additionalEntries, entryProjectRoot);
|
|
423
|
+
const unresolvedWorkspaceImports = [];
|
|
456
424
|
await (await this.createBundler({
|
|
457
425
|
...inputOptions,
|
|
458
426
|
logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
|
|
459
427
|
onwarn: (warning) => {
|
|
428
|
+
const unresolvedWorkspaceDep = getUnresolvedWorkspaceImport(warning, analyzedBundleInfo.workspaceMap);
|
|
429
|
+
if (unresolvedWorkspaceDep) unresolvedWorkspaceImports.push({ source: unresolvedWorkspaceDep });
|
|
460
430
|
if (warning.code === "CIRCULAR_DEPENDENCY") {
|
|
461
431
|
if (warning.ids?.[0]?.includes("node_modules")) return;
|
|
462
432
|
this.logger.warn("Circular dependency found", { dependency: warning.message.replace("Circular dependency: ", "") });
|
|
@@ -467,6 +437,12 @@ var Bundler = class extends MastraBundler {
|
|
|
467
437
|
manualChunks: { mastra: ["#mastra"] },
|
|
468
438
|
sourcemap: internalBundlerOptions.enableSourcemap
|
|
469
439
|
})).write();
|
|
440
|
+
if (unresolvedWorkspaceImports.length > 0) throw new MastraError({
|
|
441
|
+
id: "DEPLOYER_BUNDLER_UNRESOLVED_WORKSPACE_IMPORT",
|
|
442
|
+
text: `Workspace imports could not be resolved during bundling:\n${unresolvedWorkspaceImports.map((i) => ` - ${i.source}`).join("\n")}\n\nThis means the analyzer did not capture these workspace subpath imports during the analysis phase. Try adding the package as a direct dependency of the app, or check the workspace configuration.`,
|
|
443
|
+
domain: ErrorDomain.DEPLOYER,
|
|
444
|
+
category: ErrorCategory.SYSTEM
|
|
445
|
+
});
|
|
470
446
|
const toolImports = [];
|
|
471
447
|
const toolsExports = [];
|
|
472
448
|
Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
|
|
@@ -489,16 +465,7 @@ export const tools = [${toolsExports.join(", ")}]`);
|
|
|
489
465
|
});
|
|
490
466
|
this.logger.info("Done copying .npmrc file");
|
|
491
467
|
if (shouldSkipInstall()) this.logger.info("Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)");
|
|
492
|
-
else
|
|
493
|
-
this.logger.info("Installing dependencies");
|
|
494
|
-
await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
|
|
495
|
-
this.logger.info("Done installing dependencies");
|
|
496
|
-
if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {
|
|
497
|
-
this.logger.info("Generating package-lock.json for deploy");
|
|
498
|
-
await this.generateNpmLockfile(join(outputDirectory, this.outputDir));
|
|
499
|
-
this.logger.info("Done generating package-lock.json");
|
|
500
|
-
} else this.logger.warn("Skipping package-lock.json generation because the output contains packed workspace dependencies");
|
|
501
|
-
}
|
|
468
|
+
else await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
|
|
502
469
|
} catch (error) {
|
|
503
470
|
if (error instanceof MastraError && (error.id === "DEPLOYER_BUNDLER_FACTORY_UI_MISSING" || error.id === "DEPLOYER_PNPM_IGNORED_BUILDS")) throw error;
|
|
504
471
|
throw new MastraError({
|