@mastra/deployer 0.10.12-alpha.1 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/package.json +6 -6
  2. package/dist/_tsup-dts-rollup.d.cts +0 -836
  3. package/dist/_tsup-dts-rollup.d.ts +0 -836
  4. package/dist/build/analyze.cjs +0 -10
  5. package/dist/build/analyze.d.cts +0 -1
  6. package/dist/build/analyze.d.ts +0 -1
  7. package/dist/build/analyze.js +0 -1
  8. package/dist/build/bundler.cjs +0 -14
  9. package/dist/build/bundler.d.cts +0 -2
  10. package/dist/build/bundler.d.ts +0 -2
  11. package/dist/build/bundler.js +0 -1
  12. package/dist/build/index.cjs +0 -50
  13. package/dist/build/index.d.cts +0 -10
  14. package/dist/build/index.d.ts +0 -10
  15. package/dist/build/index.js +0 -5
  16. package/dist/bundler/index.cjs +0 -10
  17. package/dist/bundler/index.d.cts +0 -1
  18. package/dist/bundler/index.d.ts +0 -1
  19. package/dist/bundler/index.js +0 -1
  20. package/dist/chunk-2C7ENC5E.js +0 -474
  21. package/dist/chunk-54KOF3NB.cjs +0 -137
  22. package/dist/chunk-6QMONK4A.cjs +0 -2
  23. package/dist/chunk-C4JT7CIH.js +0 -1
  24. package/dist/chunk-D2DCFCLH.cjs +0 -157
  25. package/dist/chunk-D6736SJL.js +0 -209
  26. package/dist/chunk-ENT5RDOI.js +0 -99
  27. package/dist/chunk-FK2WUSEN.cjs +0 -238
  28. package/dist/chunk-GPD54HBC.js +0 -380
  29. package/dist/chunk-KCP5ITLV.cjs +0 -412
  30. package/dist/chunk-M2VZQFTW.cjs +0 -125
  31. package/dist/chunk-MKB7NDY3.cjs +0 -486
  32. package/dist/chunk-TIC2KT3M.js +0 -146
  33. package/dist/chunk-UYQZMNZL.js +0 -572
  34. package/dist/chunk-XKH6F4NE.cjs +0 -604
  35. package/dist/chunk-Z544XXXK.js +0 -111
  36. package/dist/index.cjs +0 -194
  37. package/dist/index.d.cts +0 -8
  38. package/dist/index.d.ts +0 -8
  39. package/dist/index.js +0 -153
  40. package/dist/server/index.cjs +0 -8326
  41. package/dist/server/index.d.cts +0 -2
  42. package/dist/server/index.d.ts +0 -2
  43. package/dist/server/index.js +0 -8318
  44. package/dist/services/index.cjs +0 -18
  45. package/dist/services/index.d.cts +0 -3
  46. package/dist/services/index.d.ts +0 -3
  47. package/dist/services/index.js +0 -1
  48. package/dist/templates/instrumentation-template.js +0 -137
  49. package/dist/validator/custom-resolver.cjs +0 -52
  50. package/dist/validator/custom-resolver.d.cts +0 -1
  51. package/dist/validator/custom-resolver.d.ts +0 -1
  52. package/dist/validator/custom-resolver.js +0 -50
  53. package/dist/validator/loader.cjs +0 -7
  54. package/dist/validator/loader.d.cts +0 -1
  55. package/dist/validator/loader.d.ts +0 -1
  56. package/dist/validator/loader.js +0 -4
@@ -1,10 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkXKH6F4NE_cjs = require('../chunk-XKH6F4NE.cjs');
4
-
5
-
6
-
7
- Object.defineProperty(exports, "analyzeBundle", {
8
- enumerable: true,
9
- get: function () { return chunkXKH6F4NE_cjs.analyzeBundle; }
10
- });
@@ -1 +0,0 @@
1
- export { analyzeBundle } from '../_tsup-dts-rollup.cjs';
@@ -1 +0,0 @@
1
- export { analyzeBundle } from '../_tsup-dts-rollup.js';
@@ -1 +0,0 @@
1
- export { analyzeBundle } from '../chunk-UYQZMNZL.js';
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkD2DCFCLH_cjs = require('../chunk-D2DCFCLH.cjs');
4
-
5
-
6
-
7
- Object.defineProperty(exports, "createBundler", {
8
- enumerable: true,
9
- get: function () { return chunkD2DCFCLH_cjs.createBundler; }
10
- });
11
- Object.defineProperty(exports, "getInputOptions", {
12
- enumerable: true,
13
- get: function () { return chunkD2DCFCLH_cjs.getInputOptions; }
14
- });
@@ -1,2 +0,0 @@
1
- export { getInputOptions } from '../_tsup-dts-rollup.cjs';
2
- export { createBundler } from '../_tsup-dts-rollup.cjs';
@@ -1,2 +0,0 @@
1
- export { getInputOptions } from '../_tsup-dts-rollup.js';
2
- export { createBundler } from '../_tsup-dts-rollup.js';
@@ -1 +0,0 @@
1
- export { createBundler, getInputOptions } from '../chunk-TIC2KT3M.js';
@@ -1,50 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkFK2WUSEN_cjs = require('../chunk-FK2WUSEN.cjs');
4
- var chunkM2VZQFTW_cjs = require('../chunk-M2VZQFTW.cjs');
5
- var chunkXKH6F4NE_cjs = require('../chunk-XKH6F4NE.cjs');
6
- var chunkD2DCFCLH_cjs = require('../chunk-D2DCFCLH.cjs');
7
- var chunkKCP5ITLV_cjs = require('../chunk-KCP5ITLV.cjs');
8
-
9
-
10
-
11
- Object.defineProperty(exports, "createWatcher", {
12
- enumerable: true,
13
- get: function () { return chunkFK2WUSEN_cjs.createWatcher; }
14
- });
15
- Object.defineProperty(exports, "getServerOptions", {
16
- enumerable: true,
17
- get: function () { return chunkFK2WUSEN_cjs.getServerOptions; }
18
- });
19
- Object.defineProperty(exports, "getWatcherInputOptions", {
20
- enumerable: true,
21
- get: function () { return chunkFK2WUSEN_cjs.getInputOptions; }
22
- });
23
- Object.defineProperty(exports, "writeTelemetryConfig", {
24
- enumerable: true,
25
- get: function () { return chunkM2VZQFTW_cjs.writeTelemetryConfig; }
26
- });
27
- Object.defineProperty(exports, "analyzeBundle", {
28
- enumerable: true,
29
- get: function () { return chunkXKH6F4NE_cjs.analyzeBundle; }
30
- });
31
- Object.defineProperty(exports, "getBundlerOptions", {
32
- enumerable: true,
33
- get: function () { return chunkXKH6F4NE_cjs.getBundlerOptions; }
34
- });
35
- Object.defineProperty(exports, "createBundler", {
36
- enumerable: true,
37
- get: function () { return chunkD2DCFCLH_cjs.createBundler; }
38
- });
39
- Object.defineProperty(exports, "getBundlerInputOptions", {
40
- enumerable: true,
41
- get: function () { return chunkD2DCFCLH_cjs.getInputOptions; }
42
- });
43
- Object.defineProperty(exports, "Deps", {
44
- enumerable: true,
45
- get: function () { return chunkKCP5ITLV_cjs.Deps; }
46
- });
47
- Object.defineProperty(exports, "FileService", {
48
- enumerable: true,
49
- get: function () { return chunkKCP5ITLV_cjs.FileService; }
50
- });
@@ -1,10 +0,0 @@
1
- export { createBundler_alias_1 as createBundler } from '../_tsup-dts-rollup.cjs';
2
- export { getBundlerInputOptions } from '../_tsup-dts-rollup.cjs';
3
- export { createWatcher } from '../_tsup-dts-rollup.cjs';
4
- export { getWatcherInputOptions } from '../_tsup-dts-rollup.cjs';
5
- export { analyzeBundle_alias_1 as analyzeBundle } from '../_tsup-dts-rollup.cjs';
6
- export { FileService_alias_1 as FileService } from '../_tsup-dts-rollup.cjs';
7
- export { Deps_alias_1 as Deps } from '../_tsup-dts-rollup.cjs';
8
- export { writeTelemetryConfig } from '../_tsup-dts-rollup.cjs';
9
- export { getServerOptions } from '../_tsup-dts-rollup.cjs';
10
- export { getBundlerOptions_alias_1 as getBundlerOptions } from '../_tsup-dts-rollup.cjs';
@@ -1,10 +0,0 @@
1
- export { createBundler_alias_1 as createBundler } from '../_tsup-dts-rollup.js';
2
- export { getBundlerInputOptions } from '../_tsup-dts-rollup.js';
3
- export { createWatcher } from '../_tsup-dts-rollup.js';
4
- export { getWatcherInputOptions } from '../_tsup-dts-rollup.js';
5
- export { analyzeBundle_alias_1 as analyzeBundle } from '../_tsup-dts-rollup.js';
6
- export { FileService_alias_1 as FileService } from '../_tsup-dts-rollup.js';
7
- export { Deps_alias_1 as Deps } from '../_tsup-dts-rollup.js';
8
- export { writeTelemetryConfig } from '../_tsup-dts-rollup.js';
9
- export { getServerOptions } from '../_tsup-dts-rollup.js';
10
- export { getBundlerOptions_alias_1 as getBundlerOptions } from '../_tsup-dts-rollup.js';
@@ -1,5 +0,0 @@
1
- export { createWatcher, getServerOptions, getInputOptions as getWatcherInputOptions } from '../chunk-D6736SJL.js';
2
- export { writeTelemetryConfig } from '../chunk-ENT5RDOI.js';
3
- export { analyzeBundle, getBundlerOptions } from '../chunk-UYQZMNZL.js';
4
- export { createBundler, getInputOptions as getBundlerInputOptions } from '../chunk-TIC2KT3M.js';
5
- export { Deps, FileService } from '../chunk-GPD54HBC.js';
@@ -1,10 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkMKB7NDY3_cjs = require('../chunk-MKB7NDY3.cjs');
4
-
5
-
6
-
7
- Object.defineProperty(exports, "Bundler", {
8
- enumerable: true,
9
- get: function () { return chunkMKB7NDY3_cjs.Bundler; }
10
- });
@@ -1 +0,0 @@
1
- export { Bundler } from '../_tsup-dts-rollup.cjs';
@@ -1 +0,0 @@
1
- export { Bundler } from '../_tsup-dts-rollup.js';
@@ -1 +0,0 @@
1
- export { Bundler } from '../chunk-2C7ENC5E.js';
@@ -1,474 +0,0 @@
1
- import { writeTelemetryConfig } from './chunk-ENT5RDOI.js';
2
- import { analyzeBundle } from './chunk-UYQZMNZL.js';
3
- import { createBundler, getInputOptions } from './chunk-TIC2KT3M.js';
4
- import { DepsService, FileService } from './chunk-GPD54HBC.js';
5
- import { existsSync } from 'fs';
6
- import { writeFile, stat } from 'fs/promises';
7
- import { join, dirname } from 'path';
8
- import { fileURLToPath } from 'url';
9
- import { MastraBundler } from '@mastra/core/bundler';
10
- import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
11
- import virtual from '@rollup/plugin-virtual';
12
- import fsExtra, { emptyDir, ensureDir, copy, readJSON } from 'fs-extra/esm';
13
- import { globby } from 'globby';
14
- import resolveFrom from 'resolve-from';
15
- import { rollup } from 'rollup';
16
- import esbuild from 'rollup-plugin-esbuild';
17
- import commonjs from '@rollup/plugin-commonjs';
18
- import slugify from '@sindresorhus/slugify';
19
- import { findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
20
- import { ensureDir as ensureDir$1 } from 'fs-extra';
21
-
22
- function getCustomInstrumentationBundler(entryFile, result) {
23
- return rollup({
24
- logLevel: "silent",
25
- input: {
26
- instrumentation: entryFile
27
- },
28
- treeshake: false,
29
- plugins: [
30
- // transpile typescript to something we understand
31
- esbuild({
32
- target: "node20",
33
- platform: "node",
34
- minify: false
35
- }),
36
- commonjs({
37
- extensions: [".js", ".ts"],
38
- strictRequires: "strict",
39
- transformMixedEsModules: true,
40
- ignoreTryCatch: false
41
- })
42
- ]
43
- });
44
- }
45
- async function writeCustomInstrumentation(entryFile, outputDir) {
46
- const result = {
47
- hasCustomConfig: false
48
- };
49
- const bundle = await getCustomInstrumentationBundler(entryFile);
50
- const { output } = await bundle.write({
51
- dir: outputDir,
52
- format: "es",
53
- entryFileNames: "[name].mjs"
54
- });
55
- const externals = output[0].imports.filter((x) => !x.startsWith("./"));
56
- return { ...result, externalDependencies: externals };
57
- }
58
- var createWorkspacePackageMap = async () => {
59
- const workspaces = await findWorkspaces();
60
- const workspaceMap = new Map(
61
- workspaces?.map((workspace) => [
62
- workspace.package.name,
63
- {
64
- location: workspace.location,
65
- dependencies: workspace.package.dependencies,
66
- version: workspace.package.version
67
- }
68
- ]) ?? []
69
- );
70
- return workspaceMap;
71
- };
72
- var collectTransitiveWorkspaceDependencies = ({
73
- workspaceMap,
74
- initialDependencies,
75
- logger
76
- }) => {
77
- const usedWorkspacePackages = /* @__PURE__ */ new Set();
78
- const queue = Array.from(initialDependencies);
79
- const resolutions = {};
80
- while (queue.length > 0) {
81
- const len = queue.length;
82
- for (let i = 0; i < len; i += 1) {
83
- const pkgName = queue.shift();
84
- if (!pkgName || usedWorkspacePackages.has(pkgName)) {
85
- continue;
86
- }
87
- const dep = workspaceMap.get(pkgName);
88
- if (!dep) continue;
89
- const root = findWorkspacesRoot();
90
- if (!root) {
91
- throw new Error("Could not find workspace root");
92
- }
93
- const depsService = new DepsService(root.location);
94
- depsService.__setLogger(logger);
95
- const sanitizedName = slugify(pkgName);
96
- const tgzPath = depsService.getWorkspaceDependencyPath({
97
- pkgName: sanitizedName,
98
- version: dep.version
99
- });
100
- resolutions[pkgName] = tgzPath;
101
- usedWorkspacePackages.add(pkgName);
102
- for (const [depName, _depVersion] of Object.entries(dep?.dependencies ?? {})) {
103
- if (!usedWorkspacePackages.has(depName) && workspaceMap.has(depName)) {
104
- queue.push(depName);
105
- }
106
- }
107
- }
108
- }
109
- return { resolutions, usedWorkspacePackages };
110
- };
111
- var packWorkspaceDependencies = async ({
112
- workspaceMap,
113
- usedWorkspacePackages,
114
- bundleOutputDir,
115
- logger
116
- }) => {
117
- const root = findWorkspacesRoot();
118
- if (!root) {
119
- throw new Error("Could not find workspace root");
120
- }
121
- const depsService = new DepsService(root.location);
122
- depsService.__setLogger(logger);
123
- if (usedWorkspacePackages.size > 0) {
124
- const workspaceDirPath = join(bundleOutputDir, "workspace-module");
125
- await ensureDir$1(workspaceDirPath);
126
- logger.info(`Packaging ${usedWorkspacePackages.size} workspace dependencies...`);
127
- const batchSize = 5;
128
- const packages = Array.from(usedWorkspacePackages.values());
129
- for (let i = 0; i < packages.length; i += batchSize) {
130
- const batch = packages.slice(i, i + batchSize);
131
- logger.info(
132
- `Packaging batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(packages.length / batchSize)}: ${batch.join(", ")}`
133
- );
134
- await Promise.all(
135
- batch.map(async (pkgName) => {
136
- const dep = workspaceMap.get(pkgName);
137
- if (!dep) return;
138
- await depsService.pack({ dir: dep.location, destination: workspaceDirPath });
139
- })
140
- );
141
- }
142
- logger.info(`Successfully packaged ${usedWorkspacePackages.size} workspace dependencies`);
143
- }
144
- };
145
-
146
- // src/bundler/index.ts
147
- var Bundler = class extends MastraBundler {
148
- analyzeOutputDir = ".build";
149
- outputDir = "output";
150
- constructor(name, component = "BUNDLER") {
151
- super({ name, component });
152
- }
153
- async prepare(outputDirectory) {
154
- await emptyDir(outputDirectory);
155
- await ensureDir(join(outputDirectory, this.analyzeOutputDir));
156
- await ensureDir(join(outputDirectory, this.outputDir));
157
- }
158
- async writeInstrumentationFile(outputDirectory, customInstrumentationFile) {
159
- const instrumentationFile = join(outputDirectory, "instrumentation.mjs");
160
- const __dirname = dirname(fileURLToPath(import.meta.url));
161
- if (customInstrumentationFile) {
162
- await copy(customInstrumentationFile, instrumentationFile);
163
- } else {
164
- await copy(join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
165
- }
166
- }
167
- async writePackageJson(outputDirectory, dependencies, resolutions) {
168
- this.logger.debug(`Writing project's package.json`);
169
- await ensureDir(outputDirectory);
170
- const pkgPath = join(outputDirectory, "package.json");
171
- const dependenciesMap = /* @__PURE__ */ new Map();
172
- for (const [key, value] of dependencies.entries()) {
173
- if (key.startsWith("@")) {
174
- const pkgChunks = key.split("/");
175
- dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
176
- } else {
177
- const pkgName = key.split("/")[0] || key;
178
- dependenciesMap.set(pkgName, value);
179
- }
180
- }
181
- dependenciesMap.set("@opentelemetry/core", "^2.0.1");
182
- dependenciesMap.set("@opentelemetry/auto-instrumentations-node", "^0.59.0");
183
- dependenciesMap.set("@opentelemetry/exporter-trace-otlp-grpc", "^0.201.0");
184
- dependenciesMap.set("@opentelemetry/exporter-trace-otlp-http", "^0.201.0");
185
- dependenciesMap.set("@opentelemetry/resources", "^2.0.1");
186
- dependenciesMap.set("@opentelemetry/sdk-node", "^0.201.0");
187
- dependenciesMap.set("@opentelemetry/sdk-trace-base", "^2.0.1");
188
- dependenciesMap.set("@opentelemetry/semantic-conventions", "^1.33.0");
189
- dependenciesMap.set("@opentelemetry/instrumentation", "^0.202.0");
190
- await writeFile(
191
- pkgPath,
192
- JSON.stringify(
193
- {
194
- name: "server",
195
- version: "1.0.0",
196
- description: "",
197
- type: "module",
198
- main: "index.mjs",
199
- scripts: {
200
- start: "node --import=./instrumentation.mjs --import=@opentelemetry/instrumentation/hook.mjs ./index.mjs"
201
- },
202
- author: "Mastra",
203
- license: "ISC",
204
- dependencies: Object.fromEntries(dependenciesMap.entries()),
205
- ...Object.keys(resolutions ?? {}).length > 0 && { resolutions },
206
- pnpm: {
207
- neverBuiltDependencies: []
208
- }
209
- },
210
- null,
211
- 2
212
- )
213
- );
214
- }
215
- createBundler(inputOptions, outputOptions) {
216
- return createBundler(inputOptions, outputOptions);
217
- }
218
- async analyze(entry, mastraFile, outputDirectory) {
219
- return await analyzeBundle(
220
- [].concat(entry),
221
- mastraFile,
222
- join(outputDirectory, this.analyzeOutputDir),
223
- "node",
224
- this.logger
225
- );
226
- }
227
- async installDependencies(outputDirectory, rootDir = process.cwd()) {
228
- const deps = new DepsService(rootDir);
229
- deps.__setLogger(this.logger);
230
- await deps.install({ dir: join(outputDirectory, this.outputDir) });
231
- }
232
- async copyPublic(mastraDir, outputDirectory) {
233
- const publicDir = join(mastraDir, "public");
234
- try {
235
- await stat(publicDir);
236
- } catch {
237
- return;
238
- }
239
- await copy(publicDir, join(outputDirectory, this.outputDir));
240
- }
241
- async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths) {
242
- const inputOptions = await getInputOptions(mastraEntryFile, analyzedBundleInfo, "node", {
243
- "process.env.NODE_ENV": JSON.stringify("production")
244
- });
245
- const isVirtual = serverFile.includes("\n") || existsSync(serverFile);
246
- const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
247
- if (isVirtual) {
248
- inputOptions.input = { index: "#entry", ...toolsInputOptions };
249
- if (Array.isArray(inputOptions.plugins)) {
250
- inputOptions.plugins.unshift(virtual({ "#entry": serverFile }));
251
- } else {
252
- inputOptions.plugins = [virtual({ "#entry": serverFile })];
253
- }
254
- } else {
255
- inputOptions.input = { index: serverFile, ...toolsInputOptions };
256
- }
257
- return inputOptions;
258
- }
259
- async getToolsInputOptions(toolsPaths) {
260
- const inputs = {};
261
- for (const toolPath of toolsPaths) {
262
- const expandedPaths = await globby(toolPath, {});
263
- for (const path of expandedPaths) {
264
- if (await fsExtra.pathExists(path)) {
265
- const fileService = new FileService();
266
- const entryFile = fileService.getFirstExistingFile([
267
- join(path, "index.ts"),
268
- join(path, "index.js"),
269
- path
270
- // if path itself is a file
271
- ]);
272
- if (!entryFile || (await stat(entryFile)).isDirectory()) {
273
- this.logger.warn(`No entry file found in ${path}, skipping...`);
274
- continue;
275
- }
276
- const uniqueToolID = crypto.randomUUID();
277
- inputs[`tools/${uniqueToolID}`] = entryFile;
278
- } else {
279
- this.logger.warn(`Tool path ${path} does not exist, skipping...`);
280
- }
281
- }
282
- }
283
- return inputs;
284
- }
285
- async _bundle(serverFile, mastraEntryFile, outputDirectory, toolsPaths = [], bundleLocation = join(outputDirectory, this.outputDir)) {
286
- this.logger.info("Start bundling Mastra");
287
- let analyzedBundleInfo;
288
- try {
289
- const resolvedToolsPaths = await this.getToolsInputOptions(toolsPaths);
290
- analyzedBundleInfo = await analyzeBundle(
291
- [serverFile, ...Object.values(resolvedToolsPaths)],
292
- mastraEntryFile,
293
- join(outputDirectory, this.analyzeOutputDir),
294
- "node",
295
- this.logger
296
- );
297
- } catch (error) {
298
- const message = error instanceof Error ? error.message : String(error);
299
- throw new MastraError(
300
- {
301
- id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
302
- text: `Failed to analyze Mastra application: ${message}`,
303
- domain: ErrorDomain.DEPLOYER,
304
- category: ErrorCategory.SYSTEM
305
- },
306
- error
307
- );
308
- }
309
- let externalDependencies;
310
- try {
311
- const result = await writeTelemetryConfig(mastraEntryFile, join(outputDirectory, this.outputDir));
312
- externalDependencies = result.externalDependencies;
313
- } catch (error) {
314
- const message = error instanceof Error ? error.message : String(error);
315
- throw new MastraError(
316
- {
317
- id: "DEPLOYER_BUNDLER_TELEMETRY_FAILED",
318
- text: `Failed to write telemetry config: ${message}`,
319
- domain: ErrorDomain.DEPLOYER,
320
- category: ErrorCategory.SYSTEM
321
- },
322
- error
323
- );
324
- }
325
- const mastraFolder = dirname(mastraEntryFile);
326
- const fileService = new FileService();
327
- const customInstrumentation = fileService.getFirstExistingFileOrUndefined([
328
- join(mastraFolder, "instrumentation.js"),
329
- join(mastraFolder, "instrumentation.ts"),
330
- join(mastraFolder, "instrumentation.mjs")
331
- ]);
332
- try {
333
- if (customInstrumentation) {
334
- const result = await writeCustomInstrumentation(customInstrumentation, join(outputDirectory, this.outputDir));
335
- externalDependencies = [...externalDependencies, ...result.externalDependencies];
336
- await this.writeInstrumentationFile(join(outputDirectory, this.outputDir), customInstrumentation);
337
- } else {
338
- await this.writeInstrumentationFile(join(outputDirectory, this.outputDir));
339
- }
340
- } catch (error) {
341
- const message = error instanceof Error ? error.message : String(error);
342
- throw new MastraError(
343
- {
344
- id: "DEPLOYER_BUNDLER_INSTRUMENTATION_FILE_FAILED",
345
- text: `Failed to write instrumentation file: ${message}, ${customInstrumentation ? ` Found custom instrumentation file: ${customInstrumentation}` : ""}`,
346
- domain: ErrorDomain.DEPLOYER,
347
- category: ErrorCategory.SYSTEM
348
- },
349
- error
350
- );
351
- }
352
- const dependenciesToInstall = /* @__PURE__ */ new Map();
353
- for (const external of externalDependencies) {
354
- dependenciesToInstall.set(external, "latest");
355
- }
356
- const workspaceMap = await createWorkspacePackageMap();
357
- const workspaceDependencies = /* @__PURE__ */ new Set();
358
- for (const dep of analyzedBundleInfo.externalDependencies) {
359
- try {
360
- const pkgPath = resolveFrom(mastraEntryFile, `${dep}/package.json`);
361
- const pkg = await readJSON(pkgPath);
362
- if (workspaceMap.has(pkg.name)) {
363
- workspaceDependencies.add(pkg.name);
364
- continue;
365
- }
366
- dependenciesToInstall.set(dep, pkg.version);
367
- } catch {
368
- dependenciesToInstall.set(dep, "latest");
369
- }
370
- }
371
- let resolutions = {};
372
- if (workspaceDependencies.size > 0) {
373
- try {
374
- const result = collectTransitiveWorkspaceDependencies({
375
- workspaceMap,
376
- initialDependencies: workspaceDependencies,
377
- logger: this.logger
378
- });
379
- resolutions = result.resolutions;
380
- Object.entries(resolutions).forEach(([pkgName, tgzPath]) => {
381
- dependenciesToInstall.set(pkgName, tgzPath);
382
- });
383
- await packWorkspaceDependencies({
384
- workspaceMap,
385
- usedWorkspacePackages: result.usedWorkspacePackages,
386
- bundleOutputDir: join(outputDirectory, this.outputDir),
387
- logger: this.logger
388
- });
389
- } catch (error) {
390
- throw new MastraError(
391
- {
392
- id: "DEPLOYER_BUNDLER_WORKSPACE_DEPS_FAILED",
393
- text: `Failed to collect and pack workspace dependencies.`,
394
- domain: ErrorDomain.DEPLOYER,
395
- category: ErrorCategory.USER
396
- },
397
- error
398
- );
399
- }
400
- }
401
- try {
402
- await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall, resolutions);
403
- this.logger.info("Bundling Mastra application");
404
- const inputOptions = await this.getBundlerOptions(
405
- serverFile,
406
- mastraEntryFile,
407
- analyzedBundleInfo,
408
- toolsPaths
409
- );
410
- const bundler = await this.createBundler(
411
- {
412
- ...inputOptions,
413
- logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
414
- onwarn: (warning) => {
415
- if (warning.code === "CIRCULAR_DEPENDENCY") {
416
- if (warning.ids?.[0]?.includes("node_modules")) {
417
- return;
418
- }
419
- this.logger.warn(`Circular dependency found:
420
- ${warning.message.replace("Circular dependency: ", "")}`);
421
- }
422
- }
423
- },
424
- {
425
- dir: bundleLocation,
426
- manualChunks: {
427
- mastra: ["#mastra"]
428
- }
429
- }
430
- );
431
- await bundler.write();
432
- const toolImports = [];
433
- const toolsExports = [];
434
- Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
435
- const toolExport = `tool${index}`;
436
- toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
437
- toolsExports.push(toolExport);
438
- });
439
- await writeFile(
440
- join(bundleLocation, "tools.mjs"),
441
- `${toolImports.join("\n")}
442
-
443
- export const tools = [${toolsExports.join(", ")}]`
444
- );
445
- this.logger.info("Bundling Mastra done");
446
- this.logger.info("Copying public files");
447
- await this.copyPublic(dirname(mastraEntryFile), outputDirectory);
448
- this.logger.info("Done copying public files");
449
- this.logger.info("Installing dependencies");
450
- await this.installDependencies(outputDirectory);
451
- this.logger.info("Done installing dependencies");
452
- } catch (error) {
453
- const message = error instanceof Error ? error.message : String(error);
454
- throw new MastraError(
455
- {
456
- id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
457
- text: `Failed during bundler bundle stage: ${message}`,
458
- domain: ErrorDomain.DEPLOYER,
459
- category: ErrorCategory.SYSTEM
460
- },
461
- error
462
- );
463
- }
464
- }
465
- async lint(_entryFile, _outputDirectory, toolsPaths) {
466
- const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
467
- const toolsLength = Object.keys(toolsInputOptions).length;
468
- if (toolsLength > 0) {
469
- this.logger.info(`Found ${toolsLength} ${toolsLength === 1 ? "tool" : "tools"}`);
470
- }
471
- }
472
- };
473
-
474
- export { Bundler };