@mastra/deployer 1.80.0-alpha.7 → 1.81.0-alpha.0
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/@internal_core/dist/base/index.d.ts +28 -0
- package/dist/_types/@internal_core/dist/index-Diz1p9N7.d.ts +316 -0
- package/dist/_types/@internal_core/dist/logger/index.d.ts +2 -0
- package/dist/_types/@internal_core/package.json +1 -0
- package/dist/_types/@internal_deployer/dist/_types/@internal_core/dist/index-Diz1p9N7.d.ts +316 -0
- package/dist/_types/@internal_deployer/dist/_types/@internal_core/dist/logger/index.d.ts +2 -0
- package/dist/_types/@internal_deployer/dist/bundler.d.ts +79 -0
- package/dist/_types/@internal_deployer/dist/deployer.d.ts +11 -0
- package/dist/_types/@internal_deployer/dist/index.d.ts +4 -0
- package/dist/_types/@internal_deployer/package.json +1 -0
- package/dist/{analyze-CaR5az9N.js → analyze-BZGcfVSL.js} +5 -5
- package/dist/analyze-BZGcfVSL.js.map +1 -0
- package/dist/{analyze-CcZ2AWV3.cjs → analyze-CtWBhASF.cjs} +14 -14
- package/dist/analyze-CtWBhASF.cjs.map +1 -0
- package/dist/build/analyze/analyzeEntry.d.ts +1 -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 +4 -4
- package/dist/build/analyze.d.ts.map +1 -1
- package/dist/build/analyze.js +1 -1
- package/dist/build/babel/remove-all-options-except.d.ts +1 -1
- package/dist/build/babel/remove-all-options-except.d.ts.map +1 -1
- package/dist/build/bundler.cjs +1 -1
- package/dist/build/bundler.js +1 -1
- package/dist/build/bundlerOptions.d.ts +3 -3
- package/dist/build/bundlerOptions.d.ts.map +1 -1
- package/dist/build/deployer.d.ts +3 -3
- package/dist/build/deployer.d.ts.map +1 -1
- package/dist/build/index.cjs +5 -5
- package/dist/build/index.js +5 -5
- package/dist/build/plugins/esm-shim.d.ts.map +1 -1
- package/dist/build/plugins/remove-all-except.d.ts +1 -1
- package/dist/build/plugins/remove-all-except.d.ts.map +1 -1
- package/dist/build/serverOptions.d.ts +1 -1
- package/dist/build/serverOptions.d.ts.map +1 -1
- package/dist/build/shared/extract-mastra-option.d.ts +1 -1
- package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
- package/dist/{build-CwIzWB-q.js → build-CkZ0xUid.js} +7 -9
- package/dist/build-CkZ0xUid.js.map +1 -0
- package/dist/{build-BLhyMvzA.cjs → build-D0eiANsp.cjs} +8 -10
- package/dist/build-D0eiANsp.cjs.map +1 -0
- package/dist/bundler/index.cjs +6 -506
- package/dist/bundler/index.d.ts +14 -8
- package/dist/bundler/index.d.ts.map +1 -1
- package/dist/bundler/index.js +1 -498
- package/dist/bundler/workspaceDependencies.d.ts +1 -1
- package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
- package/dist/bundler-BBi45M7f.cjs +549 -0
- package/dist/bundler-BBi45M7f.cjs.map +1 -0
- package/dist/bundler-CNgW1Vui.js +516 -0
- package/dist/bundler-CNgW1Vui.js.map +1 -0
- package/dist/{bundler-D3Ky7WCf.js → bundler-C_LpvgiH.js} +2 -2
- package/dist/bundler-C_LpvgiH.js.map +1 -0
- package/dist/{bundler-D_3GyN0N.cjs → bundler-Cb7pRVvA.cjs} +5 -5
- package/dist/bundler-Cb7pRVvA.cjs.map +1 -0
- package/dist/{bundlerOptions-Dgt4ZEo1.cjs → bundlerOptions-BBvSNHFj.cjs} +2 -2
- package/dist/bundlerOptions-BBvSNHFj.cjs.map +1 -0
- package/dist/{bundlerOptions-BtDsaIgs.js → bundlerOptions-BlUHmPBE.js} +2 -2
- package/dist/bundlerOptions-BlUHmPBE.js.map +1 -0
- package/dist/deploy/base.d.ts +1 -1
- package/dist/deploy/base.d.ts.map +1 -1
- package/dist/deploy/log.d.ts +1 -1
- package/dist/deploy/log.d.ts.map +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-deployment-mastra-server.md +3 -1
- package/dist/error-BVvc5jcw.js +172 -0
- package/dist/error-BVvc5jcw.js.map +1 -0
- package/dist/error-CR4whExy.cjs +195 -0
- package/dist/error-CR4whExy.cjs.map +1 -0
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/server/handlers/a2a.d.ts +31 -31
- package/dist/server/handlers/a2a.d.ts.map +1 -1
- package/dist/server/handlers/client.d.ts.map +1 -1
- package/dist/server/index.cjs +9 -8
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +9 -8
- package/dist/server/index.js.map +1 -1
- package/dist/services/deps.d.ts +2 -2
- package/dist/services/deps.d.ts.map +1 -1
- package/dist/services/env.d.ts.map +1 -1
- package/dist/services/fs.d.ts.map +1 -1
- package/dist/services/index.cjs +1 -1
- package/dist/services/index.js +1 -1
- package/dist/{services-BJQJLQs9.js → services-CXZJN9er.js} +294 -5
- package/dist/services-CXZJN9er.js.map +1 -0
- package/dist/{services-Dqx1iouv.cjs → services-CtVt5CJq.cjs} +321 -20
- package/dist/services-CtVt5CJq.cjs.map +1 -0
- package/dist/validator/validate.d.ts.map +1 -1
- package/package.json +14 -12
- package/dist/analyze-CaR5az9N.js.map +0 -1
- package/dist/analyze-CcZ2AWV3.cjs.map +0 -1
- package/dist/build-BLhyMvzA.cjs.map +0 -1
- package/dist/build-CwIzWB-q.js.map +0 -1
- package/dist/bundler/index.cjs.map +0 -1
- package/dist/bundler/index.js.map +0 -1
- package/dist/bundler-D3Ky7WCf.js.map +0 -1
- package/dist/bundler-D_3GyN0N.cjs.map +0 -1
- package/dist/bundlerOptions-BtDsaIgs.js.map +0 -1
- package/dist/bundlerOptions-Dgt4ZEo1.cjs.map +0 -1
- package/dist/services-BJQJLQs9.js.map +0 -1
- package/dist/services-Dqx1iouv.cjs.map +0 -1
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-Bc0pwXKd.cjs");
|
|
2
|
+
const require_services = require("./services-CtVt5CJq.cjs");
|
|
3
|
+
const require_error = require("./error-CR4whExy.cjs");
|
|
4
|
+
const require_analyze = require("./analyze-CtWBhASF.cjs");
|
|
5
|
+
const require_utils = require("./utils-CDNA_ewa.cjs");
|
|
6
|
+
const require_bundler = require("./bundler-Cb7pRVvA.cjs");
|
|
7
|
+
const require_bundlerOptions = require("./bundlerOptions-BBvSNHFj.cjs");
|
|
8
|
+
let fs = require("fs");
|
|
9
|
+
let fs_promises = require("fs/promises");
|
|
10
|
+
let path = require("path");
|
|
11
|
+
let dotenv = require("dotenv");
|
|
12
|
+
let _rollup_plugin_virtual = require("@rollup/plugin-virtual");
|
|
13
|
+
_rollup_plugin_virtual = require_rolldown_runtime.__toESM(_rollup_plugin_virtual, 1);
|
|
14
|
+
let empathic_package = require("empathic/package");
|
|
15
|
+
empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
|
|
16
|
+
let fs_extra_esm = require("fs-extra/esm");
|
|
17
|
+
fs_extra_esm = require_rolldown_runtime.__toESM(fs_extra_esm, 1);
|
|
18
|
+
let tinyglobby = require("tinyglobby");
|
|
19
|
+
// ../_internals/deployer/dist/index.js
|
|
20
|
+
/**
|
|
21
|
+
* Reads dotenv files in order into one map; values from later files override earlier ones.
|
|
22
|
+
*/
|
|
23
|
+
async function loadEnvVars(files) {
|
|
24
|
+
const envVars = /* @__PURE__ */ new Map();
|
|
25
|
+
for (const file of files) {
|
|
26
|
+
const content = await (0, fs_promises.readFile)(file, "utf-8");
|
|
27
|
+
const config = (0, dotenv.parse)(content);
|
|
28
|
+
Object.entries(config).forEach(([key, value]) => {
|
|
29
|
+
envVars.set(key, value);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return envVars;
|
|
33
|
+
}
|
|
34
|
+
// src/bundler/index.ts
|
|
35
|
+
const IS_DEFAULT = Symbol("IS_DEFAULT");
|
|
36
|
+
const NPM_ALIAS_PREFIX = "npm:";
|
|
37
|
+
/** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */
|
|
38
|
+
const REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\s-]+$/;
|
|
39
|
+
const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/;
|
|
40
|
+
const TARBALL_SUFFIX_PATTERN = /\.(?:tgz|tar\.gz|tar)$/i;
|
|
41
|
+
/** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */
|
|
42
|
+
const FILE_SPEC_PREFIX_PATTERN = /^(?:\.|~[/\\]|[/\\]|[A-Za-z]:[/\\])/;
|
|
43
|
+
/** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */
|
|
44
|
+
const UNBOUNDED_RANGE_PATTERN = /(?:^|\|\||\s)\s*(?:[*xX]|>=?\s*0(?:\.0)*(?:\.0)*)\s*(?:$|\|\|)/;
|
|
45
|
+
const toStringRecord = (value) => {
|
|
46
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
47
|
+
return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* True when a specifier is something the isolated install in `.mastra/output` can resolve from the
|
|
51
|
+
* registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry
|
|
52
|
+
* package and range.
|
|
53
|
+
*
|
|
54
|
+
* This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is
|
|
55
|
+
* rejected without this code having to know it exists. The output directory is not a workspace, has
|
|
56
|
+
* no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,
|
|
57
|
+
* `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.
|
|
58
|
+
*/
|
|
59
|
+
const isRegistryVersionSpec = (spec) => {
|
|
60
|
+
if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) return false;
|
|
61
|
+
if (spec.startsWith(NPM_ALIAS_PREFIX)) {
|
|
62
|
+
const alias = spec.slice(4);
|
|
63
|
+
const rangeSeparator = alias.lastIndexOf("@");
|
|
64
|
+
const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;
|
|
65
|
+
const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "*";
|
|
66
|
+
return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);
|
|
67
|
+
}
|
|
68
|
+
return REGISTRY_SPEC_PATTERN.test(spec);
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* True when a specifier names a version the output install can be held to.
|
|
72
|
+
*
|
|
73
|
+
* A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the
|
|
74
|
+
* version already resolved, so writing it would let a later install pull something the bundle was
|
|
75
|
+
* never analyzed against.
|
|
76
|
+
*/
|
|
77
|
+
const isBoundedVersionSpec = (spec) => {
|
|
78
|
+
const range = spec.startsWith(NPM_ALIAS_PREFIX) ? (() => {
|
|
79
|
+
const alias = spec.slice(4);
|
|
80
|
+
const rangeSeparator = alias.lastIndexOf("@");
|
|
81
|
+
return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "";
|
|
82
|
+
})() : spec;
|
|
83
|
+
return /\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);
|
|
84
|
+
};
|
|
85
|
+
const readManifest = async (manifestPath) => {
|
|
86
|
+
if (!manifestPath) return;
|
|
87
|
+
try {
|
|
88
|
+
const manifest = await (0, fs_extra_esm.readJSON)(manifestPath);
|
|
89
|
+
return manifest && typeof manifest === "object" ? manifest : void 0;
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** Collect the package names a manifest's resolution fields pin, ignoring their values. */
|
|
95
|
+
const collectManifestPinnedNames = (manifest, pinned) => {
|
|
96
|
+
const pnpmSection = manifest?.pnpm;
|
|
97
|
+
const records = [
|
|
98
|
+
manifest?.overrides,
|
|
99
|
+
manifest?.resolutions,
|
|
100
|
+
pnpmSection && typeof pnpmSection === "object" ? pnpmSection.overrides : void 0
|
|
101
|
+
];
|
|
102
|
+
for (const record of records) if (record && typeof record === "object" && !Array.isArray(record)) for (const key of Object.keys(record)) pinned.add(key);
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.
|
|
106
|
+
*
|
|
107
|
+
* pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps
|
|
108
|
+
* them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff
|
|
109
|
+
* `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.
|
|
110
|
+
*/
|
|
111
|
+
const collectPnpmWorkspacePinnedNames = (source, pinned) => {
|
|
112
|
+
const lines = source.split(/\r?\n/);
|
|
113
|
+
let insideOverrides = false;
|
|
114
|
+
for (const line of lines) {
|
|
115
|
+
if (/^\S/.test(line)) {
|
|
116
|
+
insideOverrides = /^overrides:\s*$/.test(line);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (!insideOverrides) continue;
|
|
120
|
+
const key = /^\s+(?:'([^']+)'|"([^"]+)"|([^'"\s:][^:]*?))\s*:/.exec(line);
|
|
121
|
+
if (key) pinned.add((key[1] ?? key[2] ?? key[3] ?? "").trim());
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Read the constraints the source app declared.
|
|
126
|
+
*
|
|
127
|
+
* `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and
|
|
128
|
+
* whose directory receives the output, falling back to the manifest above the entry file. Anchoring
|
|
129
|
+
* on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed
|
|
130
|
+
* to the bundler is a generated wrapper rather than the app's own source file.
|
|
131
|
+
*
|
|
132
|
+
* Resolution-field names are collected from both that manifest and the workspace root, including the
|
|
133
|
+
* root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been
|
|
134
|
+
* chosen deliberately rather than hoisted by accident.
|
|
135
|
+
*/
|
|
136
|
+
const getSourceDependencyConstraints = async ({ projectRoot, mastraEntryFile, workspaceRoot }) => {
|
|
137
|
+
const manifestPaths = [empathic_package.up({ cwd: projectRoot }), empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) })].filter((entry, index, entries) => !!entry && entries.indexOf(entry) === index);
|
|
138
|
+
if (workspaceRoot) manifestPaths.push((0, path.join)(workspaceRoot, "package.json"));
|
|
139
|
+
const pinnedByResolutionField = /* @__PURE__ */ new Set();
|
|
140
|
+
let dependencies;
|
|
141
|
+
for (const manifestPath of manifestPaths) {
|
|
142
|
+
const manifest = await readManifest(manifestPath);
|
|
143
|
+
if (!manifest) continue;
|
|
144
|
+
dependencies ??= toStringRecord(manifest.dependencies);
|
|
145
|
+
collectManifestPinnedNames(manifest, pinnedByResolutionField);
|
|
146
|
+
}
|
|
147
|
+
if (workspaceRoot) try {
|
|
148
|
+
collectPnpmWorkspacePinnedNames(await (0, fs_promises.readFile)((0, path.join)(workspaceRoot, "pnpm-workspace.yaml"), "utf-8"), pinnedByResolutionField);
|
|
149
|
+
} catch {}
|
|
150
|
+
return {
|
|
151
|
+
dependencies: dependencies ?? {},
|
|
152
|
+
pinnedByResolutionField
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
const findDeclaredConstraint = (constraints, dependencyName) => {
|
|
156
|
+
const names = [dependencyName, require_utils.getPackageName(dependencyName)].filter((name, index, all) => !!name && all.indexOf(name) === index);
|
|
157
|
+
for (const name of names) if (constraints.pinnedByResolutionField.has(name)) return;
|
|
158
|
+
for (const name of names) {
|
|
159
|
+
const declared = (constraints.dependencies[name] ?? "").trim();
|
|
160
|
+
if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) return declared;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Prefer the constraint the app declared over the version resolved from `node_modules`.
|
|
165
|
+
*
|
|
166
|
+
* The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`
|
|
167
|
+
* next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the
|
|
168
|
+
* isolated install then locks it in.
|
|
169
|
+
*/
|
|
170
|
+
const applySourceDependencyRange = (dependencyName, dependencyInfo, constraints) => {
|
|
171
|
+
const declared = findDeclaredConstraint(constraints, dependencyName);
|
|
172
|
+
if (!declared) return dependencyInfo;
|
|
173
|
+
if (declared.startsWith(NPM_ALIAS_PREFIX)) return {
|
|
174
|
+
...dependencyInfo,
|
|
175
|
+
packageSpec: declared
|
|
176
|
+
};
|
|
177
|
+
if (dependencyInfo.packageSpec) return dependencyInfo;
|
|
178
|
+
return {
|
|
179
|
+
...dependencyInfo,
|
|
180
|
+
version: declared
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
async function toolIdForEntry(relativeEntryFile) {
|
|
184
|
+
const digest = Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(relativeEntryFile))).toString("hex");
|
|
185
|
+
return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;
|
|
186
|
+
}
|
|
187
|
+
var Bundler = class extends require_services.MastraBase {
|
|
188
|
+
analyzeOutputDir = ".build";
|
|
189
|
+
outputDir = "output";
|
|
190
|
+
platform = "node";
|
|
191
|
+
defaultExternalsPreset = false;
|
|
192
|
+
constructor(name, component = "BUNDLER") {
|
|
193
|
+
super({
|
|
194
|
+
name,
|
|
195
|
+
component
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
async loadEnvVars() {
|
|
199
|
+
return loadEnvVars(await this.getEnvFiles());
|
|
200
|
+
}
|
|
201
|
+
async prepare(outputDirectory) {
|
|
202
|
+
await (0, fs_extra_esm.emptyDir)(outputDirectory);
|
|
203
|
+
await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.analyzeOutputDir));
|
|
204
|
+
await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.outputDir));
|
|
205
|
+
}
|
|
206
|
+
async writePackageJson(outputDirectory, dependencies, resolutions) {
|
|
207
|
+
this.logger.debug("Writing project's package.json");
|
|
208
|
+
await (0, fs_extra_esm.ensureDir)(outputDirectory);
|
|
209
|
+
const pkgPath = (0, path.join)(outputDirectory, "package.json");
|
|
210
|
+
const dependenciesMap = /* @__PURE__ */ new Map();
|
|
211
|
+
for (const [key, value] of dependencies.entries()) {
|
|
212
|
+
const dependencyValue = typeof value === "string" ? value : value.packageSpec ?? value.version ?? "latest";
|
|
213
|
+
if (key.startsWith("@")) {
|
|
214
|
+
const pkgChunks = key.split("/");
|
|
215
|
+
dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);
|
|
216
|
+
} else {
|
|
217
|
+
const pkgName = key.split("/")[0] || key;
|
|
218
|
+
dependenciesMap.set(pkgName, dependencyValue);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
await (0, fs_promises.writeFile)(pkgPath, JSON.stringify({
|
|
222
|
+
name: "server",
|
|
223
|
+
version: "1.0.0",
|
|
224
|
+
private: true,
|
|
225
|
+
type: "module",
|
|
226
|
+
main: "index.mjs",
|
|
227
|
+
scripts: { start: "node ./index.mjs" },
|
|
228
|
+
dependencies: Object.fromEntries(dependenciesMap.entries()),
|
|
229
|
+
...Object.keys(resolutions ?? {}).length > 0 && { resolutions }
|
|
230
|
+
}, null, 2));
|
|
231
|
+
}
|
|
232
|
+
createBundler(inputOptions, outputOptions) {
|
|
233
|
+
return require_bundler.createBundler(inputOptions, outputOptions);
|
|
234
|
+
}
|
|
235
|
+
async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
|
|
236
|
+
const defaultBundlerOptions = {
|
|
237
|
+
externals: [],
|
|
238
|
+
sourcemap: false,
|
|
239
|
+
transpilePackages: [],
|
|
240
|
+
[IS_DEFAULT]: true
|
|
241
|
+
};
|
|
242
|
+
try {
|
|
243
|
+
return await require_bundlerOptions.getBundlerOptions(mastraEntryFile, outputDirectory) ?? defaultBundlerOptions;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.logger.debug("Failed to get bundler options, sourcemap will be disabled", { error });
|
|
246
|
+
}
|
|
247
|
+
return defaultBundlerOptions;
|
|
248
|
+
}
|
|
249
|
+
async analyze(entry, mastraFile, outputDirectory) {
|
|
250
|
+
return await require_analyze.analyzeBundle([].concat(entry), mastraFile, {
|
|
251
|
+
outputDir: (0, path.join)(outputDirectory, this.analyzeOutputDir),
|
|
252
|
+
projectRoot: outputDirectory,
|
|
253
|
+
platform: this.platform
|
|
254
|
+
}, this.logger);
|
|
255
|
+
}
|
|
256
|
+
pnpmNodeLinker;
|
|
257
|
+
getAdditionalEntries() {
|
|
258
|
+
return {};
|
|
259
|
+
}
|
|
260
|
+
async installDependencies(outputDirectory, rootDir = process.cwd(), pnpmOverrides, pnpmWorkspaceSettings) {
|
|
261
|
+
const deps = new require_services.DepsService(rootDir);
|
|
262
|
+
deps.__setLogger(this.logger);
|
|
263
|
+
const installOptions = {
|
|
264
|
+
dir: (0, path.join)(outputDirectory, this.outputDir),
|
|
265
|
+
pnpmOverrides,
|
|
266
|
+
pnpmNodeLinker: this.pnpmNodeLinker,
|
|
267
|
+
pnpmWorkspaceSettings
|
|
268
|
+
};
|
|
269
|
+
this.logger.info("Updating dependency lockfile and installing dependencies");
|
|
270
|
+
await deps.install(installOptions);
|
|
271
|
+
this.logger.info("Done updating dependency lockfile and installing dependencies");
|
|
272
|
+
}
|
|
273
|
+
async copyPublic(mastraDir, outputDirectory) {
|
|
274
|
+
const publicDir = (0, path.join)(mastraDir, "public");
|
|
275
|
+
try {
|
|
276
|
+
await (0, fs_promises.stat)(publicDir);
|
|
277
|
+
} catch {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
await (0, fs_extra_esm.copy)(publicDir, (0, path.join)(outputDirectory, this.outputDir));
|
|
281
|
+
}
|
|
282
|
+
async copyDOTNPMRC({ rootDir = process.cwd(), outputDirectory }) {
|
|
283
|
+
const sourceDotNpmRcPath = (0, path.join)(rootDir, ".npmrc");
|
|
284
|
+
const targetDotNpmRcPath = (0, path.join)(outputDirectory, this.outputDir, ".npmrc");
|
|
285
|
+
try {
|
|
286
|
+
await (0, fs_promises.stat)(sourceDotNpmRcPath);
|
|
287
|
+
await (0, fs_extra_esm.copy)(sourceDotNpmRcPath, targetDotNpmRcPath);
|
|
288
|
+
} catch {}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Writes the `mastra-project.json` deployment marker for Software Factory
|
|
292
|
+
* projects after public assets have been copied. Verifies that the Factory
|
|
293
|
+
* SPA (`factory/index.html`) exists in the output before emitting the marker.
|
|
294
|
+
*/
|
|
295
|
+
async writeFactoryMarker(outputDirectory) {
|
|
296
|
+
const outputDir = (0, path.join)(outputDirectory, this.outputDir);
|
|
297
|
+
const factoryIndex = (0, path.join)(outputDir, "factory", "index.html");
|
|
298
|
+
if (!(0, fs.existsSync)(factoryIndex)) throw new require_error.MastraError({
|
|
299
|
+
id: "DEPLOYER_BUNDLER_FACTORY_UI_MISSING",
|
|
300
|
+
text: "Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.",
|
|
301
|
+
domain: require_error.ErrorDomain.DEPLOYER,
|
|
302
|
+
category: require_error.ErrorCategory.SYSTEM
|
|
303
|
+
});
|
|
304
|
+
await (0, fs_promises.writeFile)((0, path.join)(outputDir, "mastra-project.json"), JSON.stringify({
|
|
305
|
+
schemaVersion: 1,
|
|
306
|
+
projectType: "factory",
|
|
307
|
+
assets: { ui: "factory" }
|
|
308
|
+
}, null, 2));
|
|
309
|
+
this.logger.info("Wrote mastra-project.json for Software Factory project");
|
|
310
|
+
}
|
|
311
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals, externalsPreset, alias }, additionalEntries, projectRoot) {
|
|
312
|
+
const { workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile });
|
|
313
|
+
const inputOptions = await require_bundler.getInputOptions(mastraEntryFile, analyzedBundleInfo, this.platform, { "process.env.NODE_ENV": JSON.stringify("production") }, {
|
|
314
|
+
sourcemap: enableSourcemap,
|
|
315
|
+
minify: enableMinify,
|
|
316
|
+
workspaceRoot,
|
|
317
|
+
projectRoot,
|
|
318
|
+
enableEsmShim,
|
|
319
|
+
externalsPreset: externals === true || !!externalsPreset,
|
|
320
|
+
explicitExternals: Array.isArray(externals) ? externals : [],
|
|
321
|
+
alias
|
|
322
|
+
});
|
|
323
|
+
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, projectRoot);
|
|
324
|
+
const entryInputs = {};
|
|
325
|
+
const virtualEntries = {};
|
|
326
|
+
const entries = {
|
|
327
|
+
index: serverFile,
|
|
328
|
+
...additionalEntries
|
|
329
|
+
};
|
|
330
|
+
for (const [name, entry] of Object.entries(entries)) if (entry.includes("\n") || !(0, fs.existsSync)(entry)) {
|
|
331
|
+
const virtualId = name === "index" ? "#entry" : `#entry-${name}`;
|
|
332
|
+
entryInputs[name] = virtualId;
|
|
333
|
+
virtualEntries[virtualId] = entry;
|
|
334
|
+
} else entryInputs[name] = entry;
|
|
335
|
+
inputOptions.input = {
|
|
336
|
+
...entryInputs,
|
|
337
|
+
...toolsInputOptions
|
|
338
|
+
};
|
|
339
|
+
if (Object.keys(virtualEntries).length > 0) {
|
|
340
|
+
if (Array.isArray(inputOptions.plugins)) inputOptions.plugins.unshift((0, _rollup_plugin_virtual.default)(virtualEntries));
|
|
341
|
+
else inputOptions.plugins = [(0, _rollup_plugin_virtual.default)(virtualEntries)];
|
|
342
|
+
}
|
|
343
|
+
return inputOptions;
|
|
344
|
+
}
|
|
345
|
+
getAllToolPaths(mastraDir, toolsPaths = []) {
|
|
346
|
+
const normalizedMastraDir = require_utils.slash(mastraDir);
|
|
347
|
+
const defaultPaths = [path.posix.join(normalizedMastraDir, "tools/**/*.{js,ts}"), ...[`!${path.posix.join(normalizedMastraDir, "tools/**/*.{test,spec}.{js,ts}")}`, `!${path.posix.join(normalizedMastraDir, "tools/**/__tests__/**")}`]];
|
|
348
|
+
if (toolsPaths.length === 0) return [defaultPaths];
|
|
349
|
+
return [...toolsPaths, defaultPaths];
|
|
350
|
+
}
|
|
351
|
+
async listToolsInputOptions(toolsPaths, projectRoot = process.cwd()) {
|
|
352
|
+
const entries = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const toolPath of toolsPaths) {
|
|
354
|
+
const expandedPaths = await (0, tinyglobby.glob)(toolPath, {
|
|
355
|
+
absolute: true,
|
|
356
|
+
expandDirectories: false
|
|
357
|
+
});
|
|
358
|
+
for (const path$1 of expandedPaths) if (await fs_extra_esm.default.pathExists(path$1)) {
|
|
359
|
+
const entryFile = new require_services.FileService().getFirstExistingFile([
|
|
360
|
+
(0, path.join)(path$1, "index.ts"),
|
|
361
|
+
(0, path.join)(path$1, "index.js"),
|
|
362
|
+
path$1
|
|
363
|
+
]);
|
|
364
|
+
if (!entryFile || (await (0, fs_promises.stat)(entryFile)).isDirectory()) {
|
|
365
|
+
this.logger.warn("No entry file found, skipping", { path: path$1 });
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
const normalizedEntryFile = entryFile.replaceAll("\\", "/");
|
|
369
|
+
const relativeEntryFile = (0, path.relative)(projectRoot, entryFile).replaceAll("\\", "/");
|
|
370
|
+
entries.set(relativeEntryFile, normalizedEntryFile);
|
|
371
|
+
} else this.logger.warn("Tool path does not exist, skipping", { path: path$1 });
|
|
372
|
+
}
|
|
373
|
+
return Object.fromEntries(await Promise.all([...entries.entries()].sort(([first], [second]) => first < second ? -1 : first > second ? 1 : 0).map(async ([relativeEntryFile, entryFile]) => [`tools/${await toolIdForEntry(relativeEntryFile)}`, entryFile])));
|
|
374
|
+
}
|
|
375
|
+
async _bundle(serverFile, mastraEntryFile, { projectRoot, outputDirectory, enableEsmShim = true, alias = {} }, toolsPaths = [], bundleLocation = (0, path.join)(outputDirectory, this.outputDir)) {
|
|
376
|
+
const analyzeDir = (0, path.join)(outputDirectory, this.analyzeOutputDir);
|
|
377
|
+
const additionalEntries = this.getAdditionalEntries();
|
|
378
|
+
const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
|
|
379
|
+
const entryProjectRoot = closestPkgJson ? (0, path.dirname)(closestPkgJson) : projectRoot;
|
|
380
|
+
const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);
|
|
381
|
+
const resolvedAlias = Object.fromEntries(Object.entries(alias).map(([specifier, target]) => [specifier, target.startsWith(".") ? (0, path.resolve)(projectRoot, target) : target]));
|
|
382
|
+
const internalBundlerOptions = {
|
|
383
|
+
enableSourcemap: !!bundlerOptions.sourcemap,
|
|
384
|
+
enableMinify: !!bundlerOptions.minify,
|
|
385
|
+
externals: bundlerOptions.externals ?? [],
|
|
386
|
+
externalsPreset: this.defaultExternalsPreset && bundlerOptions.externals !== false,
|
|
387
|
+
enableEsmShim,
|
|
388
|
+
alias: resolvedAlias,
|
|
389
|
+
dynamicPackages: bundlerOptions.dynamicPackages
|
|
390
|
+
};
|
|
391
|
+
let analyzedBundleInfo;
|
|
392
|
+
try {
|
|
393
|
+
const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths, entryProjectRoot);
|
|
394
|
+
analyzedBundleInfo = await require_analyze.analyzeBundle([
|
|
395
|
+
serverFile,
|
|
396
|
+
...Object.values(additionalEntries),
|
|
397
|
+
...Object.values(resolvedToolsPaths)
|
|
398
|
+
], mastraEntryFile, {
|
|
399
|
+
outputDir: analyzeDir,
|
|
400
|
+
projectRoot: entryProjectRoot,
|
|
401
|
+
platform: this.platform,
|
|
402
|
+
bundlerOptions: internalBundlerOptions
|
|
403
|
+
}, this.logger);
|
|
404
|
+
} catch (error) {
|
|
405
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
406
|
+
if (error instanceof require_error.MastraError) throw error;
|
|
407
|
+
throw new require_error.MastraError({
|
|
408
|
+
id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
|
|
409
|
+
text: `Failed to analyze Mastra application: ${message}`,
|
|
410
|
+
domain: require_error.ErrorDomain.DEPLOYER,
|
|
411
|
+
category: require_error.ErrorCategory.SYSTEM
|
|
412
|
+
}, error);
|
|
413
|
+
}
|
|
414
|
+
const { workspaceRoot } = await require_analyze.getWorkspaceInformation({
|
|
415
|
+
dir: projectRoot,
|
|
416
|
+
mastraEntryFile
|
|
417
|
+
});
|
|
418
|
+
const sourceDependencyConstraints = await getSourceDependencyConstraints({
|
|
419
|
+
projectRoot: entryProjectRoot,
|
|
420
|
+
mastraEntryFile,
|
|
421
|
+
workspaceRoot
|
|
422
|
+
});
|
|
423
|
+
const dependenciesToInstall = /* @__PURE__ */ new Map();
|
|
424
|
+
for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {
|
|
425
|
+
if (analyzedBundleInfo.workspaceMap.has(dep) || !require_utils.isBareModuleSpecifier(dep)) continue;
|
|
426
|
+
dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));
|
|
427
|
+
}
|
|
428
|
+
const initialWorkspaceDependencies = /* @__PURE__ */ new Set();
|
|
429
|
+
for (const dep of [...analyzedBundleInfo.dependencies.keys(), ...analyzedBundleInfo.externalDependencies.keys()]) {
|
|
430
|
+
const pkgName = require_utils.getPackageName(dep);
|
|
431
|
+
if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) initialWorkspaceDependencies.add(pkgName);
|
|
432
|
+
}
|
|
433
|
+
const transitiveWorkspaceDependencies = await require_analyze.collectTransitiveWorkspaceDependencies({
|
|
434
|
+
workspaceMap: analyzedBundleInfo.workspaceMap,
|
|
435
|
+
initialDependencies: initialWorkspaceDependencies,
|
|
436
|
+
logger: this.logger
|
|
437
|
+
});
|
|
438
|
+
for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) dependenciesToInstall.set(dep, {
|
|
439
|
+
version: analyzedBundleInfo.workspaceMap.get(dep)?.version,
|
|
440
|
+
packageSpec
|
|
441
|
+
});
|
|
442
|
+
try {
|
|
443
|
+
await this.writePackageJson((0, path.join)(outputDirectory, this.outputDir), dependenciesToInstall, transitiveWorkspaceDependencies.resolutions);
|
|
444
|
+
if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) await require_analyze.packWorkspaceDependencies({
|
|
445
|
+
workspaceMap: analyzedBundleInfo.workspaceMap,
|
|
446
|
+
usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,
|
|
447
|
+
bundleOutputDir: (0, path.join)(outputDirectory, this.outputDir),
|
|
448
|
+
logger: this.logger
|
|
449
|
+
});
|
|
450
|
+
this.logger.info("Bundling Mastra application");
|
|
451
|
+
const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions, additionalEntries, entryProjectRoot);
|
|
452
|
+
const unresolvedWorkspaceImports = [];
|
|
453
|
+
await (await this.createBundler({
|
|
454
|
+
...inputOptions,
|
|
455
|
+
logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
|
|
456
|
+
onwarn: (warning) => {
|
|
457
|
+
const unresolvedWorkspaceDep = require_bundler.getUnresolvedWorkspaceImport(warning, analyzedBundleInfo.workspaceMap);
|
|
458
|
+
if (unresolvedWorkspaceDep) unresolvedWorkspaceImports.push({ source: unresolvedWorkspaceDep });
|
|
459
|
+
if (warning.code === "CIRCULAR_DEPENDENCY") {
|
|
460
|
+
if (warning.ids?.[0]?.includes("node_modules")) return;
|
|
461
|
+
this.logger.warn("Circular dependency found", { dependency: warning.message.replace("Circular dependency: ", "") });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}, {
|
|
465
|
+
dir: bundleLocation,
|
|
466
|
+
manualChunks: { mastra: ["#mastra"] },
|
|
467
|
+
sourcemap: internalBundlerOptions.enableSourcemap
|
|
468
|
+
})).write();
|
|
469
|
+
if (unresolvedWorkspaceImports.length > 0) {
|
|
470
|
+
const importList = unresolvedWorkspaceImports.map((i) => ` - ${i.source}`).join("\n");
|
|
471
|
+
throw new require_error.MastraError({
|
|
472
|
+
id: "DEPLOYER_BUNDLER_UNRESOLVED_WORKSPACE_IMPORT",
|
|
473
|
+
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.`,
|
|
474
|
+
domain: require_error.ErrorDomain.DEPLOYER,
|
|
475
|
+
category: require_error.ErrorCategory.SYSTEM
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
const toolImports = [];
|
|
479
|
+
const toolsExports = [];
|
|
480
|
+
Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
|
|
481
|
+
const toolExport = `tool${index}`;
|
|
482
|
+
toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
|
|
483
|
+
toolsExports.push(toolExport);
|
|
484
|
+
});
|
|
485
|
+
await (0, fs_promises.writeFile)((0, path.join)(bundleLocation, "tools.mjs"), `${toolImports.join("\n")}
|
|
486
|
+
|
|
487
|
+
export const tools = [${toolsExports.join(", ")}]`);
|
|
488
|
+
this.logger.info("Bundling Mastra done");
|
|
489
|
+
this.logger.info("Copying public files");
|
|
490
|
+
await this.copyPublic((0, path.dirname)(mastraEntryFile), outputDirectory);
|
|
491
|
+
this.logger.info("Done copying public files");
|
|
492
|
+
if (analyzedBundleInfo.projectType === "factory") await this.writeFactoryMarker(outputDirectory);
|
|
493
|
+
this.logger.info("Copying .npmrc file");
|
|
494
|
+
await this.copyDOTNPMRC({
|
|
495
|
+
outputDirectory,
|
|
496
|
+
rootDir: projectRoot
|
|
497
|
+
});
|
|
498
|
+
this.logger.info("Done copying .npmrc file");
|
|
499
|
+
if (require_utils.shouldSkipInstall()) this.logger.info("Skipping dependency installation (MASTRA_BUILD_SKIP_INSTALL set)");
|
|
500
|
+
else await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions, bundlerOptions.pnpmWorkspaceSettings);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
if (error instanceof require_error.MastraError && (error.id === "DEPLOYER_BUNDLER_FACTORY_UI_MISSING" || error.id === "DEPLOYER_PNPM_IGNORED_BUILDS")) throw error;
|
|
503
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
504
|
+
throw new require_error.MastraError({
|
|
505
|
+
id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
|
|
506
|
+
text: `Failed during bundler bundle stage: ${message}`,
|
|
507
|
+
domain: require_error.ErrorDomain.DEPLOYER,
|
|
508
|
+
category: require_error.ErrorCategory.SYSTEM
|
|
509
|
+
}, error);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
async lint(_entryFile, outputDirectory, toolsPaths) {
|
|
513
|
+
const toolsInputOptions = await this.listToolsInputOptions(toolsPaths, (0, path.dirname)(outputDirectory));
|
|
514
|
+
const toolsLength = Object.keys(toolsInputOptions).length;
|
|
515
|
+
if (toolsLength > 0) this.logger.info("Found tools", { count: toolsLength });
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
Object.defineProperty(exports, "Bundler", {
|
|
519
|
+
enumerable: true,
|
|
520
|
+
get: function() {
|
|
521
|
+
return Bundler;
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
Object.defineProperty(exports, "IS_DEFAULT", {
|
|
525
|
+
enumerable: true,
|
|
526
|
+
get: function() {
|
|
527
|
+
return IS_DEFAULT;
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
Object.defineProperty(exports, "applySourceDependencyRange", {
|
|
531
|
+
enumerable: true,
|
|
532
|
+
get: function() {
|
|
533
|
+
return applySourceDependencyRange;
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
Object.defineProperty(exports, "getSourceDependencyConstraints", {
|
|
537
|
+
enumerable: true,
|
|
538
|
+
get: function() {
|
|
539
|
+
return getSourceDependencyConstraints;
|
|
540
|
+
}
|
|
541
|
+
});
|
|
542
|
+
Object.defineProperty(exports, "isRegistryVersionSpec", {
|
|
543
|
+
enumerable: true,
|
|
544
|
+
get: function() {
|
|
545
|
+
return isRegistryVersionSpec;
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
//# sourceMappingURL=bundler-BBi45M7f.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundler-BBi45M7f.cjs","names":["readFile","parse","readJSON","pkg","dirname","join","readFile","getPackageName","MastraBase","emptyDir","ensureDir","writeFile","createBundlerUtil","getBundlerOptions","analyzeBundle","DepsService","stat","copy","existsSync","MastraError","ErrorDomain","ErrorCategory","getWorkspaceInformation","getInputOptions","virtual","slash","posix","glob","path","fsExtra","FileService","relative","resolve","isBareModuleSpecifier","collectTransitiveWorkspaceDependencies","packWorkspaceDependencies","getUnresolvedWorkspaceImport","shouldSkipInstall"],"sources":["../../_internals/deployer/dist/index.js","../src/bundler/index.ts"],"sourcesContent":["import { readFile } from \"fs/promises\";\nimport { parse } from \"dotenv\";\n// src/bundler.ts\n/**\n* Reads dotenv files in order into one map; values from later files override earlier ones.\n*/\nasync function loadEnvVars(files) {\n\tconst envVars = /* @__PURE__ */ new Map();\n\tfor (const file of files) {\n\t\tconst content = await readFile(file, \"utf-8\");\n\t\tconst config = parse(content);\n\t\tObject.entries(config).forEach(([key, value]) => {\n\t\t\tenvVars.set(key, value);\n\t\t});\n\t}\n\treturn envVars;\n}\nexport { loadEnvVars };\n\n//# sourceMappingURL=index.js.map","import { existsSync } from 'node:fs';\nimport { readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix, relative, resolve } from 'node:path';\nimport { MastraBase } from '@internal/core/base';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@internal/core/error';\nimport { loadEnvVars } from '@internal/deployer';\nimport type { BundlerConfig, IBundler } from '@internal/deployer';\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 { ExternalDependencyInfo, InternalBundlerOptions } 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\nasync function toolIdForEntry(relativeEntryFile: string): Promise<string> {\n const digest = Buffer.from(\n await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(relativeEntryFile)),\n ).toString('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 MastraBase implements IBundler {\n protected analyzeOutputDir = '.build';\n protected outputDir = 'output';\n protected platform: BundlerPlatform = 'node';\n protected defaultExternalsPreset = false;\n\n constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n super({ name, component });\n }\n\n async loadEnvVars(): Promise<Map<string, string>> {\n return loadEnvVars(await this.getEnvFiles());\n }\n\n abstract getEnvFiles(): Promise<string[]>;\n abstract bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void>;\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(mastraEntryFile: string, outputDirectory: string): Promise<BundlerConfig> {\n const defaultBundlerOptions: BundlerConfig = {\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 pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'],\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 pnpmWorkspaceSettings,\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 }\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, externalsPreset, alias }: InternalBundlerOptions,\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 || !!externalsPreset,\n explicitExternals: Array.isArray(externals) ? externals : [],\n alias,\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 await Promise.all(\n [...entries.entries()]\n .sort(([first], [second]) => (first < second ? -1 : first > second ? 1 : 0))\n .map(\n async ([relativeEntryFile, entryFile]): Promise<[string, string]> => [\n `tools/${await toolIdForEntry(relativeEntryFile)}`,\n entryFile,\n ],\n ),\n ),\n );\n }\n\n protected async _bundle(\n serverFile: string,\n mastraEntryFile: string,\n {\n projectRoot,\n outputDirectory,\n enableEsmShim = true,\n alias = {},\n }: {\n projectRoot: string;\n outputDirectory: string;\n enableEsmShim?: boolean;\n alias?: Record<string, string>;\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 resolvedAlias = Object.fromEntries(\n Object.entries(alias).map(([specifier, target]) => [\n specifier,\n target.startsWith('.') ? resolve(projectRoot, target) : target,\n ]),\n );\n const internalBundlerOptions: InternalBundlerOptions = {\n enableSourcemap: !!bundlerOptions.sourcemap,\n enableMinify: !!bundlerOptions.minify,\n externals: bundlerOptions.externals ?? [],\n externalsPreset: this.defaultExternalsPreset && bundlerOptions.externals !== false,\n enableEsmShim,\n alias: resolvedAlias,\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(), ...analyzedBundleInfo.externalDependencies.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(\n outputDirectory,\n projectRoot,\n transitiveWorkspaceDependencies.resolutions,\n bundlerOptions.pnpmWorkspaceSettings,\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":";;;;;;;;;;;;;;;;;;;;;;AAMA,eAAe,YAAY,OAAO;CACjC,MA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