@mastra/deployer 1.58.0-alpha.8 → 1.58.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.
@@ -1,598 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
2
- const require_analyze = require("./analyze-BIrkd7zx.cjs");
3
- const require_utils = require("./utils-O98BGdnP.cjs");
4
- const require_services = require("./services-_ksvysL5.cjs");
5
- const require_bundler = require("./bundler-DCGtF4jP.cjs");
6
- const require_bundlerOptions = require("./bundlerOptions-CjjAPZYp.cjs");
7
- let child_process = require("child_process");
8
- let fs = require("fs");
9
- let fs_promises = require("fs/promises");
10
- let path = require("path");
11
- let _mastra_core_bundler = require("@mastra/core/bundler");
12
- let _mastra_core_error = require("@mastra/core/error");
13
- let _rollup_plugin_virtual = require("@rollup/plugin-virtual");
14
- _rollup_plugin_virtual = require_rolldown_runtime.__toESM(_rollup_plugin_virtual, 1);
15
- let empathic_package = require("empathic/package");
16
- empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
17
- let fs_extra_esm = require("fs-extra/esm");
18
- fs_extra_esm = require_rolldown_runtime.__toESM(fs_extra_esm, 1);
19
- let tinyglobby = require("tinyglobby");
20
- //#region src/bundler/entries.ts
21
- /** Reserved by the server bundle (`index.mjs`). */
22
- const SERVER_ENTRY_NAME = "index";
23
- /**
24
- * Reserved by the tool aggregator, which `_bundle` writes to `tools.mjs` with `writeFile`
25
- * *after* rollup finishes. Rollup deduplicates colliding chunk names, but that write
26
- * happens outside its control, so an entry named `tools` is silently overwritten.
27
- */
28
- const TOOLS_ENTRY_NAME = "tools";
29
- /** Reserved by tool bundles (`tools/<uuid>.mjs`), which the aggregator collects by prefix. */
30
- const TOOLS_ENTRY_PREFIX = "tools/";
31
- function invalidEntries(text) {
32
- return new _mastra_core_error.MastraError({
33
- id: "DEPLOYER_BUNDLER_INVALID_ENTRIES",
34
- text,
35
- domain: _mastra_core_error.ErrorDomain.DEPLOYER,
36
- category: _mastra_core_error.ErrorCategory.USER
37
- });
38
- }
39
- /**
40
- * Resolves the user's `bundler.entries` config into the absolute source paths the
41
- * bundler emits beside the server bundle.
42
- *
43
- * Names become output filenames (`<name>.mjs` via rollup's `entryFileNames`), so they
44
- * are rejected when they would collide with the server or tool bundles, or when they
45
- * would escape the output directory. Paths resolve relative to the Mastra directory —
46
- * the directory holding the entry file — so they read the same way as the imports
47
- * already in that file.
48
- */
49
- function resolveExtraEntries(entries, mastraEntryFile) {
50
- if (!entries) return {};
51
- const mastraDir = (0, path.dirname)(mastraEntryFile);
52
- const resolved = /* @__PURE__ */ new Map();
53
- for (const [name, entryPath] of Object.entries(entries)) {
54
- if (!name || name !== name.trim()) throw invalidEntries(`bundler.entries has an empty or untrimmed entry name: ${JSON.stringify(name)}`);
55
- const normalizedName = require_utils.slash(name);
56
- if (normalizedName === SERVER_ENTRY_NAME) throw invalidEntries(`bundler.entries cannot use the name "${SERVER_ENTRY_NAME}" — it is reserved for the Mastra server bundle.`);
57
- if (normalizedName === TOOLS_ENTRY_NAME || normalizedName.startsWith(TOOLS_ENTRY_PREFIX)) throw invalidEntries(`bundler.entries cannot use the name "${name}" — "${TOOLS_ENTRY_NAME}" and names starting with "${TOOLS_ENTRY_PREFIX}" are reserved for tool bundles.`);
58
- if ((0, path.isAbsolute)(name) || normalizedName.startsWith("/") || normalizedName.split("/").includes("..")) throw invalidEntries(`bundler.entries name "${name}" must be a relative name without ".." segments — it becomes a file inside the build output.`);
59
- if (resolved.has(normalizedName)) throw invalidEntries(`bundler.entries has two entries that resolve to the output name "${normalizedName}" (the second is "${name}"). Entry names must be unique once path separators are normalized.`);
60
- if (!entryPath) throw invalidEntries(`bundler.entries entry "${name}" has an empty path.`);
61
- const absolutePath = (0, path.isAbsolute)(entryPath) ? entryPath : (0, path.resolve)(mastraDir, entryPath);
62
- let entryStats;
63
- try {
64
- entryStats = (0, fs.statSync)(absolutePath);
65
- } catch (error) {
66
- if (error.code === "ENOENT" || error.code === "ENOTDIR") throw invalidEntries(`bundler.entries entry "${name}" points at "${entryPath}", which does not exist (resolved to ${absolutePath}). Paths are resolved relative to your Mastra directory (${mastraDir}).`);
67
- throw error;
68
- }
69
- if (!entryStats.isFile()) throw invalidEntries(`bundler.entries entry "${name}" points at "${entryPath}", which is not a file (resolved to ${absolutePath}). Point it at the source file to bundle.`);
70
- resolved.set(normalizedName, require_utils.slash(absolutePath));
71
- }
72
- return Object.fromEntries(resolved);
73
- }
74
- //#endregion
75
- //#region src/bundler/index.ts
76
- const IS_DEFAULT = Symbol("IS_DEFAULT");
77
- const NPM_ALIAS_PREFIX = "npm:";
78
- /** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */
79
- const REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\s-]+$/;
80
- const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/;
81
- const TARBALL_SUFFIX_PATTERN = /\.(?:tgz|tar\.gz|tar)$/i;
82
- /** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */
83
- const FILE_SPEC_PREFIX_PATTERN = /^(?:\.|~[/\\]|[/\\]|[A-Za-z]:[/\\])/;
84
- /** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */
85
- const UNBOUNDED_RANGE_PATTERN = /(?:^|\|\||\s)\s*(?:[*xX]|>=?\s*0(?:\.0)*(?:\.0)*)\s*(?:$|\|\|)/;
86
- const toStringRecord = (value) => {
87
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
88
- return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
89
- };
90
- /**
91
- * True when a specifier is something the isolated install in `.mastra/output` can resolve from the
92
- * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry
93
- * package and range.
94
- *
95
- * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is
96
- * rejected without this code having to know it exists. The output directory is not a workspace, has
97
- * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,
98
- * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.
99
- */
100
- const isRegistryVersionSpec = (spec) => {
101
- if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) return false;
102
- if (spec.startsWith(NPM_ALIAS_PREFIX)) {
103
- const alias = spec.slice(4);
104
- const rangeSeparator = alias.lastIndexOf("@");
105
- const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;
106
- const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "*";
107
- return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);
108
- }
109
- return REGISTRY_SPEC_PATTERN.test(spec);
110
- };
111
- /**
112
- * True when a specifier names a version the output install can be held to.
113
- *
114
- * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the
115
- * version already resolved, so writing it would let a later install pull something the bundle was
116
- * never analyzed against.
117
- */
118
- const isBoundedVersionSpec = (spec) => {
119
- const range = spec.startsWith(NPM_ALIAS_PREFIX) ? (() => {
120
- const alias = spec.slice(4);
121
- const rangeSeparator = alias.lastIndexOf("@");
122
- return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "";
123
- })() : spec;
124
- return /\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);
125
- };
126
- const readManifest = async (manifestPath) => {
127
- if (!manifestPath) return;
128
- try {
129
- const manifest = await (0, fs_extra_esm.readJSON)(manifestPath);
130
- return manifest && typeof manifest === "object" ? manifest : void 0;
131
- } catch {
132
- return;
133
- }
134
- };
135
- /** Collect the package names a manifest's resolution fields pin, ignoring their values. */
136
- const collectManifestPinnedNames = (manifest, pinned) => {
137
- const pnpmSection = manifest?.pnpm;
138
- const records = [
139
- manifest?.overrides,
140
- manifest?.resolutions,
141
- pnpmSection && typeof pnpmSection === "object" ? pnpmSection.overrides : void 0
142
- ];
143
- for (const record of records) if (record && typeof record === "object" && !Array.isArray(record)) for (const key of Object.keys(record)) pinned.add(key);
144
- };
145
- /**
146
- * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.
147
- *
148
- * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps
149
- * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff
150
- * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.
151
- */
152
- const collectPnpmWorkspacePinnedNames = (source, pinned) => {
153
- const lines = source.split(/\r?\n/);
154
- let insideOverrides = false;
155
- for (const line of lines) {
156
- if (/^\S/.test(line)) {
157
- insideOverrides = /^overrides:\s*$/.test(line);
158
- continue;
159
- }
160
- if (!insideOverrides) continue;
161
- const key = /^\s+(?:'([^']+)'|"([^"]+)"|([^'"\s:][^:]*?))\s*:/.exec(line);
162
- if (key) pinned.add((key[1] ?? key[2] ?? key[3] ?? "").trim());
163
- }
164
- };
165
- /**
166
- * Read the constraints the source app declared.
167
- *
168
- * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and
169
- * whose directory receives the output, falling back to the manifest above the entry file. Anchoring
170
- * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed
171
- * to the bundler is a generated wrapper rather than the app's own source file.
172
- *
173
- * Resolution-field names are collected from both that manifest and the workspace root, including the
174
- * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been
175
- * chosen deliberately rather than hoisted by accident.
176
- */
177
- const getSourceDependencyConstraints = async ({ projectRoot, mastraEntryFile, workspaceRoot }) => {
178
- const manifestPaths = [empathic_package.up({ cwd: projectRoot }), empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) })].filter((entry, index, entries) => !!entry && entries.indexOf(entry) === index);
179
- if (workspaceRoot) manifestPaths.push((0, path.join)(workspaceRoot, "package.json"));
180
- const pinnedByResolutionField = /* @__PURE__ */ new Set();
181
- let dependencies;
182
- for (const manifestPath of manifestPaths) {
183
- const manifest = await readManifest(manifestPath);
184
- if (!manifest) continue;
185
- dependencies ??= toStringRecord(manifest.dependencies);
186
- collectManifestPinnedNames(manifest, pinnedByResolutionField);
187
- }
188
- if (workspaceRoot) try {
189
- collectPnpmWorkspacePinnedNames(await (0, fs_promises.readFile)((0, path.join)(workspaceRoot, "pnpm-workspace.yaml"), "utf-8"), pinnedByResolutionField);
190
- } catch {}
191
- return {
192
- dependencies: dependencies ?? {},
193
- pinnedByResolutionField
194
- };
195
- };
196
- const findDeclaredConstraint = (constraints, dependencyName) => {
197
- const names = [dependencyName, require_utils.getPackageName(dependencyName)].filter((name, index, all) => !!name && all.indexOf(name) === index);
198
- for (const name of names) if (constraints.pinnedByResolutionField.has(name)) return;
199
- for (const name of names) {
200
- const declared = (constraints.dependencies[name] ?? "").trim();
201
- if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) return declared;
202
- }
203
- };
204
- /**
205
- * Prefer the constraint the app declared over the version resolved from `node_modules`.
206
- *
207
- * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`
208
- * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the
209
- * isolated install then locks it in.
210
- */
211
- const applySourceDependencyRange = (dependencyName, dependencyInfo, constraints) => {
212
- const declared = findDeclaredConstraint(constraints, dependencyName);
213
- if (!declared) return dependencyInfo;
214
- if (declared.startsWith(NPM_ALIAS_PREFIX)) return {
215
- ...dependencyInfo,
216
- packageSpec: declared
217
- };
218
- if (dependencyInfo.packageSpec) return dependencyInfo;
219
- return {
220
- ...dependencyInfo,
221
- version: declared
222
- };
223
- };
224
- var Bundler = class extends _mastra_core_bundler.MastraBundler {
225
- analyzeOutputDir = ".build";
226
- outputDir = "output";
227
- platform = "node";
228
- constructor(name, component = "BUNDLER") {
229
- super({
230
- name,
231
- component
232
- });
233
- }
234
- async prepare(outputDirectory) {
235
- await (0, fs_extra_esm.emptyDir)(outputDirectory);
236
- await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.analyzeOutputDir));
237
- await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.outputDir));
238
- }
239
- async writePackageJson(outputDirectory, dependencies, resolutions) {
240
- this.logger.debug("Writing project's package.json");
241
- await (0, fs_extra_esm.ensureDir)(outputDirectory);
242
- const pkgPath = (0, path.join)(outputDirectory, "package.json");
243
- const dependenciesMap = /* @__PURE__ */ new Map();
244
- for (const [key, value] of dependencies.entries()) {
245
- const dependencyValue = typeof value === "string" ? value : value.packageSpec ?? value.version ?? "latest";
246
- if (key.startsWith("@")) {
247
- const pkgChunks = key.split("/");
248
- dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);
249
- } else {
250
- const pkgName = key.split("/")[0] || key;
251
- dependenciesMap.set(pkgName, dependencyValue);
252
- }
253
- }
254
- await (0, fs_promises.writeFile)(pkgPath, JSON.stringify({
255
- name: "server",
256
- version: "1.0.0",
257
- private: true,
258
- type: "module",
259
- main: "index.mjs",
260
- scripts: { start: "node ./index.mjs" },
261
- dependencies: Object.fromEntries(dependenciesMap.entries()),
262
- ...Object.keys(resolutions ?? {}).length > 0 && { resolutions }
263
- }, null, 2));
264
- }
265
- createBundler(inputOptions, outputOptions) {
266
- return require_bundler.createBundler(inputOptions, outputOptions);
267
- }
268
- async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
269
- const defaultBundlerOptions = {
270
- externals: [],
271
- sourcemap: false,
272
- transpilePackages: [],
273
- [IS_DEFAULT]: true
274
- };
275
- try {
276
- return await require_bundlerOptions.getBundlerOptions(mastraEntryFile, outputDirectory) ?? defaultBundlerOptions;
277
- } catch (error) {
278
- this.logger.debug("Failed to get bundler options, sourcemap will be disabled", { error });
279
- }
280
- return defaultBundlerOptions;
281
- }
282
- async analyze(entry, mastraFile, outputDirectory) {
283
- return await require_analyze.analyzeBundle([].concat(entry), mastraFile, {
284
- outputDir: (0, path.join)(outputDirectory, this.analyzeOutputDir),
285
- projectRoot: outputDirectory,
286
- platform: this.platform
287
- }, this.logger);
288
- }
289
- pnpmNodeLinker;
290
- async installDependencies(outputDirectory, rootDir = process.cwd(), pnpmOverrides) {
291
- const deps = new require_services.DepsService(rootDir);
292
- deps.__setLogger(this.logger);
293
- await deps.install({
294
- dir: (0, path.join)(outputDirectory, this.outputDir),
295
- pnpmOverrides,
296
- pnpmNodeLinker: this.pnpmNodeLinker
297
- });
298
- }
299
- /**
300
- * Generate a package-lock.json for the output directory so that deploy targets
301
- * can use `npm ci` instead of `npm install`, skipping version resolution entirely.
302
- * This is a lockfile-only operation — no packages are downloaded.
303
- *
304
- * Temporarily moves node_modules out of the way because pnpm's symlink-based
305
- * layout confuses npm's arborist, then restores it afterwards so that
306
- * `mastra start` (or wrangler) can still resolve dependencies at runtime.
307
- */
308
- async generateNpmLockfile(outputDir) {
309
- const nodeModules = (0, path.join)(outputDir, "node_modules");
310
- const nodeModulesTmp = (0, path.join)(outputDir, "node_modules.__tmp");
311
- let movedNodeModules = false;
312
- try {
313
- if (await fs_extra_esm.default.pathExists(nodeModules)) {
314
- await fs_extra_esm.default.move(nodeModules, nodeModulesTmp, { overwrite: true });
315
- movedNodeModules = true;
316
- }
317
- (0, child_process.execSync)("npm install --package-lock-only --force", {
318
- cwd: outputDir,
319
- stdio: "pipe",
320
- timeout: 6e4
321
- });
322
- } catch {
323
- this.logger.warn("Failed to generate package-lock.json — deploy will fall back to npm install");
324
- } finally {
325
- if (movedNodeModules) {
326
- await (0, fs_promises.rm)(nodeModules, {
327
- recursive: true,
328
- force: true
329
- });
330
- await fs_extra_esm.default.move(nodeModulesTmp, nodeModules, { overwrite: true });
331
- }
332
- }
333
- }
334
- async copyPublic(mastraDir, outputDirectory) {
335
- const publicDir = (0, path.join)(mastraDir, "public");
336
- try {
337
- await (0, fs_promises.stat)(publicDir);
338
- } catch {
339
- return;
340
- }
341
- await (0, fs_extra_esm.copy)(publicDir, (0, path.join)(outputDirectory, this.outputDir));
342
- }
343
- async copyDOTNPMRC({ rootDir = process.cwd(), outputDirectory }) {
344
- const sourceDotNpmRcPath = (0, path.join)(rootDir, ".npmrc");
345
- const targetDotNpmRcPath = (0, path.join)(outputDirectory, this.outputDir, ".npmrc");
346
- try {
347
- await (0, fs_promises.stat)(sourceDotNpmRcPath);
348
- await (0, fs_extra_esm.copy)(sourceDotNpmRcPath, targetDotNpmRcPath);
349
- } catch {
350
- return;
351
- }
352
- }
353
- /**
354
- * Writes the `mastra-project.json` deployment marker for Software Factory
355
- * projects after public assets have been copied. Verifies that the Factory
356
- * SPA (`factory/index.html`) exists in the output before emitting the marker.
357
- */
358
- async writeFactoryMarker(outputDirectory) {
359
- const outputDir = (0, path.join)(outputDirectory, this.outputDir);
360
- if (!(0, fs.existsSync)((0, path.join)(outputDir, "factory", "index.html"))) throw new _mastra_core_error.MastraError({
361
- id: "DEPLOYER_BUNDLER_FACTORY_UI_MISSING",
362
- text: "Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.",
363
- domain: _mastra_core_error.ErrorDomain.DEPLOYER,
364
- category: _mastra_core_error.ErrorCategory.SYSTEM
365
- });
366
- await (0, fs_promises.writeFile)((0, path.join)(outputDir, "mastra-project.json"), JSON.stringify({
367
- schemaVersion: 1,
368
- projectType: "factory",
369
- assets: { ui: "factory" }
370
- }, null, 2));
371
- this.logger.info("Wrote mastra-project.json for Software Factory project");
372
- }
373
- async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals, entries }) {
374
- const { workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile });
375
- const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
376
- const projectRoot = closestPkgJson ? (0, path.dirname)(closestPkgJson) : process.cwd();
377
- const inputOptions = await require_bundler.getInputOptions(mastraEntryFile, analyzedBundleInfo, this.platform, { "process.env.NODE_ENV": JSON.stringify("production") }, {
378
- sourcemap: enableSourcemap,
379
- minify: enableMinify,
380
- workspaceRoot,
381
- projectRoot,
382
- enableEsmShim,
383
- externalsPreset: externals === true
384
- });
385
- const isVirtual = serverFile.includes("\n") || !(0, fs.existsSync)(serverFile);
386
- const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);
387
- const extraEntries = entries ?? {};
388
- if (isVirtual) {
389
- inputOptions.input = {
390
- index: "#entry",
391
- ...extraEntries,
392
- ...toolsInputOptions
393
- };
394
- if (Array.isArray(inputOptions.plugins)) inputOptions.plugins.unshift((0, _rollup_plugin_virtual.default)({ "#entry": serverFile }));
395
- else inputOptions.plugins = [(0, _rollup_plugin_virtual.default)({ "#entry": serverFile })];
396
- } else inputOptions.input = {
397
- index: serverFile,
398
- ...extraEntries,
399
- ...toolsInputOptions
400
- };
401
- return inputOptions;
402
- }
403
- getAllToolPaths(mastraDir, toolsPaths = []) {
404
- const normalizedMastraDir = require_utils.slash(mastraDir);
405
- const defaultPaths = [path.posix.join(normalizedMastraDir, "tools/**/*.{js,ts}"), ...[`!${path.posix.join(normalizedMastraDir, "tools/**/*.{test,spec}.{js,ts}")}`, `!${path.posix.join(normalizedMastraDir, "tools/**/__tests__/**")}`]];
406
- if (toolsPaths.length === 0) return [defaultPaths];
407
- return [...toolsPaths, defaultPaths];
408
- }
409
- async listToolsInputOptions(toolsPaths) {
410
- const inputs = {};
411
- for (const toolPath of toolsPaths) {
412
- const expandedPaths = await (0, tinyglobby.glob)(toolPath, {
413
- absolute: true,
414
- expandDirectories: false
415
- });
416
- for (const path$1 of expandedPaths) if (await fs_extra_esm.default.pathExists(path$1)) {
417
- const entryFile = new require_services.FileService().getFirstExistingFile([
418
- (0, path.join)(path$1, "index.ts"),
419
- (0, path.join)(path$1, "index.js"),
420
- path$1
421
- ]);
422
- if (!entryFile || (await (0, fs_promises.stat)(entryFile)).isDirectory()) {
423
- this.logger.warn("No entry file found, skipping", { path: path$1 });
424
- continue;
425
- }
426
- const uniqueToolID = crypto.randomUUID();
427
- const normalizedEntryFile = entryFile.replaceAll("\\", "/");
428
- inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;
429
- } else this.logger.warn("Tool path does not exist, skipping", { path: path$1 });
430
- }
431
- return inputs;
432
- }
433
- async _bundle(serverFile, mastraEntryFile, { projectRoot, outputDirectory, enableEsmShim = true }, toolsPaths = [], bundleLocation = (0, path.join)(outputDirectory, this.outputDir)) {
434
- const analyzeDir = (0, path.join)(outputDirectory, this.analyzeOutputDir);
435
- const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);
436
- const extraEntries = resolveExtraEntries(bundlerOptions.entries, mastraEntryFile);
437
- const internalBundlerOptions = {
438
- enableSourcemap: !!bundlerOptions.sourcemap,
439
- enableMinify: !!bundlerOptions.minify,
440
- externals: bundlerOptions.externals ?? [],
441
- enableEsmShim,
442
- dynamicPackages: bundlerOptions.dynamicPackages,
443
- entries: extraEntries
444
- };
445
- if (Object.keys(extraEntries).length > 0) this.logger.info("Found additional entries", { entries: Object.keys(extraEntries) });
446
- let analyzedBundleInfo;
447
- try {
448
- const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);
449
- analyzedBundleInfo = await require_analyze.analyzeBundle([
450
- serverFile,
451
- ...Object.values(extraEntries),
452
- ...Object.values(resolvedToolsPaths)
453
- ], mastraEntryFile, {
454
- outputDir: analyzeDir,
455
- projectRoot,
456
- platform: this.platform,
457
- bundlerOptions: internalBundlerOptions
458
- }, this.logger);
459
- } catch (error) {
460
- const message = error instanceof Error ? error.message : String(error);
461
- if (error instanceof _mastra_core_error.MastraError) throw error;
462
- throw new _mastra_core_error.MastraError({
463
- id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
464
- text: `Failed to analyze Mastra application: ${message}`,
465
- domain: _mastra_core_error.ErrorDomain.DEPLOYER,
466
- category: _mastra_core_error.ErrorCategory.SYSTEM
467
- }, error);
468
- }
469
- const { workspaceRoot } = await require_analyze.getWorkspaceInformation({
470
- dir: projectRoot,
471
- mastraEntryFile
472
- });
473
- const sourceDependencyConstraints = await getSourceDependencyConstraints({
474
- projectRoot,
475
- mastraEntryFile,
476
- workspaceRoot
477
- });
478
- const dependenciesToInstall = /* @__PURE__ */ new Map();
479
- for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {
480
- if (analyzedBundleInfo.workspaceMap.has(dep) || !require_utils.isBareModuleSpecifier(dep)) continue;
481
- dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));
482
- }
483
- const initialWorkspaceDependencies = /* @__PURE__ */ new Set();
484
- for (const dep of analyzedBundleInfo.dependencies.keys()) {
485
- const pkgName = require_utils.getPackageName(dep);
486
- if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) initialWorkspaceDependencies.add(pkgName);
487
- }
488
- const transitiveWorkspaceDependencies = require_analyze.collectTransitiveWorkspaceDependencies({
489
- workspaceMap: analyzedBundleInfo.workspaceMap,
490
- initialDependencies: initialWorkspaceDependencies,
491
- logger: this.logger
492
- });
493
- for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) dependenciesToInstall.set(dep, {
494
- version: analyzedBundleInfo.workspaceMap.get(dep)?.version,
495
- packageSpec
496
- });
497
- try {
498
- await this.writePackageJson((0, path.join)(outputDirectory, this.outputDir), dependenciesToInstall, transitiveWorkspaceDependencies.resolutions);
499
- if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) await require_analyze.packWorkspaceDependencies({
500
- workspaceMap: analyzedBundleInfo.workspaceMap,
501
- usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,
502
- bundleOutputDir: (0, path.join)(outputDirectory, this.outputDir),
503
- logger: this.logger
504
- });
505
- this.logger.info("Bundling Mastra application");
506
- const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions);
507
- await (await this.createBundler({
508
- ...inputOptions,
509
- logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
510
- onwarn: (warning) => {
511
- if (warning.code === "CIRCULAR_DEPENDENCY") {
512
- if (warning.ids?.[0]?.includes("node_modules")) return;
513
- this.logger.warn("Circular dependency found", { dependency: warning.message.replace("Circular dependency: ", "") });
514
- }
515
- }
516
- }, {
517
- dir: bundleLocation,
518
- manualChunks: { mastra: ["#mastra"] },
519
- sourcemap: internalBundlerOptions.enableSourcemap
520
- })).write();
521
- const toolImports = [];
522
- const toolsExports = [];
523
- Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
524
- const toolExport = `tool${index}`;
525
- toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
526
- toolsExports.push(toolExport);
527
- });
528
- await (0, fs_promises.writeFile)((0, path.join)(bundleLocation, "tools.mjs"), `${toolImports.join("\n")}
529
-
530
- export const tools = [${toolsExports.join(", ")}]`);
531
- this.logger.info("Bundling Mastra done");
532
- this.logger.info("Copying public files");
533
- await this.copyPublic((0, path.dirname)(mastraEntryFile), outputDirectory);
534
- this.logger.info("Done copying public files");
535
- if (analyzedBundleInfo.projectType === "factory") await this.writeFactoryMarker(outputDirectory);
536
- this.logger.info("Copying .npmrc file");
537
- await this.copyDOTNPMRC({
538
- outputDirectory,
539
- rootDir: projectRoot
540
- });
541
- this.logger.info("Done copying .npmrc file");
542
- this.logger.info("Installing dependencies");
543
- await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
544
- this.logger.info("Done installing dependencies");
545
- if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {
546
- this.logger.info("Generating package-lock.json for deploy");
547
- await this.generateNpmLockfile((0, path.join)(outputDirectory, this.outputDir));
548
- this.logger.info("Done generating package-lock.json");
549
- } else this.logger.warn("Skipping package-lock.json generation because the output contains packed workspace dependencies");
550
- } catch (error) {
551
- if (error instanceof _mastra_core_error.MastraError && error.id === "DEPLOYER_BUNDLER_FACTORY_UI_MISSING") throw error;
552
- throw new _mastra_core_error.MastraError({
553
- id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
554
- text: `Failed during bundler bundle stage: ${error instanceof Error ? error.message : String(error)}`,
555
- domain: _mastra_core_error.ErrorDomain.DEPLOYER,
556
- category: _mastra_core_error.ErrorCategory.SYSTEM
557
- }, error);
558
- }
559
- }
560
- async lint(_entryFile, _outputDirectory, toolsPaths) {
561
- const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);
562
- const toolsLength = Object.keys(toolsInputOptions).length;
563
- if (toolsLength > 0) this.logger.info("Found tools", { count: toolsLength });
564
- }
565
- };
566
- //#endregion
567
- Object.defineProperty(exports, "Bundler", {
568
- enumerable: true,
569
- get: function() {
570
- return Bundler;
571
- }
572
- });
573
- Object.defineProperty(exports, "IS_DEFAULT", {
574
- enumerable: true,
575
- get: function() {
576
- return IS_DEFAULT;
577
- }
578
- });
579
- Object.defineProperty(exports, "applySourceDependencyRange", {
580
- enumerable: true,
581
- get: function() {
582
- return applySourceDependencyRange;
583
- }
584
- });
585
- Object.defineProperty(exports, "getSourceDependencyConstraints", {
586
- enumerable: true,
587
- get: function() {
588
- return getSourceDependencyConstraints;
589
- }
590
- });
591
- Object.defineProperty(exports, "isRegistryVersionSpec", {
592
- enumerable: true,
593
- get: function() {
594
- return isRegistryVersionSpec;
595
- }
596
- });
597
-
598
- //# sourceMappingURL=bundler-DLXwkS7b.cjs.map