@mastra/deployer 0.0.0-commonjs-20250227130920

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 (86) hide show
  1. package/.turbo/turbo-build.log +41 -0
  2. package/CHANGELOG.md +897 -0
  3. package/LICENSE +44 -0
  4. package/README.md +159 -0
  5. package/dist/_tsup-dts-rollup.d.cts +360 -0
  6. package/dist/_tsup-dts-rollup.d.ts +360 -0
  7. package/dist/build/analyze.cjs +367 -0
  8. package/dist/build/analyze.d.cts +1 -0
  9. package/dist/build/analyze.d.ts +1 -0
  10. package/dist/build/analyze.js +2 -0
  11. package/dist/build/bundler.cjs +353 -0
  12. package/dist/build/bundler.d.cts +2 -0
  13. package/dist/build/bundler.d.ts +2 -0
  14. package/dist/build/bundler.js +2 -0
  15. package/dist/build/index.cjs +1146 -0
  16. package/dist/build/index.d.cts +10 -0
  17. package/dist/build/index.d.ts +10 -0
  18. package/dist/build/index.js +5 -0
  19. package/dist/bundler/index.cjs +999 -0
  20. package/dist/bundler/index.d.cts +1 -0
  21. package/dist/bundler/index.d.ts +1 -0
  22. package/dist/bundler/index.js +5 -0
  23. package/dist/chunk-3ONBKVC4.js +113 -0
  24. package/dist/chunk-AXS5WSIK.js +290 -0
  25. package/dist/chunk-DTSFVNIF.js +260 -0
  26. package/dist/chunk-JMH7HCD6.js +274 -0
  27. package/dist/chunk-SGK37ZWD.js +254 -0
  28. package/dist/chunk-YNXJO2XU.js +69 -0
  29. package/dist/index.cjs +1229 -0
  30. package/dist/index.d.cts +6 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +131 -0
  33. package/dist/server/index.cjs +4930 -0
  34. package/dist/server/index.d.cts +2 -0
  35. package/dist/server/index.d.ts +2 -0
  36. package/dist/server/index.js +4923 -0
  37. package/dist/templates/instrumentation-template.js +86 -0
  38. package/eslint.config.js +6 -0
  39. package/global.d.ts +0 -0
  40. package/package.json +112 -0
  41. package/public/templates/instrumentation-template.js +86 -0
  42. package/src/build/analyze.ts +279 -0
  43. package/src/build/babel/fix-libsql.ts +41 -0
  44. package/src/build/babel/get-deployer.ts +54 -0
  45. package/src/build/babel/get-telemetry-config.ts +62 -0
  46. package/src/build/babel/remove-deployer.ts +43 -0
  47. package/src/build/bundle.ts +139 -0
  48. package/src/build/bundler.ts +135 -0
  49. package/src/build/deployer.ts +67 -0
  50. package/src/build/deps.ts +149 -0
  51. package/src/build/env.ts +76 -0
  52. package/src/build/fs.ts +66 -0
  53. package/src/build/index.ts +7 -0
  54. package/src/build/isNodeBuiltin.ts +7 -0
  55. package/src/build/plugins/fix-libsql.ts +69 -0
  56. package/src/build/plugins/hono-alias.ts +17 -0
  57. package/src/build/plugins/pino.ts +93 -0
  58. package/src/build/plugins/remove-deployer.ts +37 -0
  59. package/src/build/plugins/telemetry-fix.ts +54 -0
  60. package/src/build/telemetry.ts +76 -0
  61. package/src/build/utils.ts +12 -0
  62. package/src/build/watcher.ts +43 -0
  63. package/src/bundler/index.ts +144 -0
  64. package/src/deploy/base.ts +30 -0
  65. package/src/deploy/index.ts +2 -0
  66. package/src/deploy/log.ts +61 -0
  67. package/src/index.ts +3 -0
  68. package/src/server/handlers/agents.ts +209 -0
  69. package/src/server/handlers/client.ts +36 -0
  70. package/src/server/handlers/error.ts +29 -0
  71. package/src/server/handlers/logs.ts +53 -0
  72. package/src/server/handlers/memory.ts +196 -0
  73. package/src/server/handlers/prompt.ts +128 -0
  74. package/src/server/handlers/root.ts +6 -0
  75. package/src/server/handlers/telemetry.ts +48 -0
  76. package/src/server/handlers/tools.ts +114 -0
  77. package/src/server/handlers/utils.ts +15 -0
  78. package/src/server/handlers/vector.ts +149 -0
  79. package/src/server/handlers/workflows.ts +119 -0
  80. package/src/server/index.ts +1355 -0
  81. package/src/server/openapi.json +434 -0
  82. package/src/server/openapi.script.js +22 -0
  83. package/src/server/types.ts +4 -0
  84. package/src/server/welcome.ts +105 -0
  85. package/tsconfig.json +5 -0
  86. package/vitest.config.ts +8 -0
@@ -0,0 +1,999 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var fsPromises = require('fs/promises');
5
+ var path = require('path');
6
+ var url = require('url');
7
+ var bundler = require('@mastra/core/bundler');
8
+ var virtual = require('@rollup/plugin-virtual');
9
+ var fsExtra$1 = require('fs-extra');
10
+ var fsExtra = require('fs-extra/esm');
11
+ var commonjs = require('@rollup/plugin-commonjs');
12
+ var json = require('@rollup/plugin-json');
13
+ var nodeResolve2 = require('@rollup/plugin-node-resolve');
14
+ var rollup = require('rollup');
15
+ var esbuild = require('rollup-plugin-esbuild');
16
+ var module$1 = require('module');
17
+ var babel = require('@babel/core');
18
+ var alias = require('@rollup/plugin-alias');
19
+ var load = require('@neon-rs/load');
20
+ var detectLibc = require('detect-libc');
21
+ var helperModuleImports = require('@babel/helper-module-imports');
22
+ var process$1 = require('process');
23
+ var base = require('@mastra/core/base');
24
+ var child_process = require('child_process');
25
+ var stream = require('stream');
26
+
27
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
28
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
29
+
30
+ function _interopNamespace(e) {
31
+ if (e && e.__esModule) return e;
32
+ var n = Object.create(null);
33
+ if (e) {
34
+ Object.keys(e).forEach(function (k) {
35
+ if (k !== 'default') {
36
+ var d = Object.getOwnPropertyDescriptor(e, k);
37
+ Object.defineProperty(n, k, d.get ? d : {
38
+ enumerable: true,
39
+ get: function () { return e[k]; }
40
+ });
41
+ }
42
+ });
43
+ }
44
+ n.default = e;
45
+ return Object.freeze(n);
46
+ }
47
+
48
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
49
+ var fsPromises__default = /*#__PURE__*/_interopDefault(fsPromises);
50
+ var path__default = /*#__PURE__*/_interopDefault(path);
51
+ var virtual__default = /*#__PURE__*/_interopDefault(virtual);
52
+ var fsExtra__default = /*#__PURE__*/_interopDefault(fsExtra);
53
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
54
+ var json__default = /*#__PURE__*/_interopDefault(json);
55
+ var nodeResolve2__default = /*#__PURE__*/_interopDefault(nodeResolve2);
56
+ var esbuild__default = /*#__PURE__*/_interopDefault(esbuild);
57
+ var babel__namespace = /*#__PURE__*/_interopNamespace(babel);
58
+ var alias__default = /*#__PURE__*/_interopDefault(alias);
59
+
60
+ // src/bundler/index.ts
61
+ function isNodeBuiltin(dep) {
62
+ const [pkg] = dep.split("/");
63
+ return dep.startsWith("node:") || module$1.builtinModules.includes(dep) || module$1.builtinModules.includes(pkg);
64
+ }
65
+ function aliasHono() {
66
+ return {
67
+ name: "hono-alias",
68
+ resolveId(id) {
69
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
70
+ return;
71
+ }
72
+ const path2 = undefined(id);
73
+ return url.fileURLToPath(path2);
74
+ }
75
+ };
76
+ }
77
+
78
+ // src/build/plugins/pino.ts
79
+ function pino() {
80
+ const workerFiles = [
81
+ {
82
+ id: "thread-stream-worker",
83
+ file: "pino-thread-stream-worker"
84
+ },
85
+ {
86
+ id: "pino-worker",
87
+ file: "pino-worker"
88
+ },
89
+ {
90
+ id: "pino/file",
91
+ file: "pino-file"
92
+ },
93
+ {
94
+ id: "pino-pretty",
95
+ file: "pino-pretty"
96
+ }
97
+ ];
98
+ const fileReferences = /* @__PURE__ */ new Map();
99
+ return {
100
+ name: "rollup-plugin-pino",
101
+ async resolveId(id, importee) {
102
+ if (id === "pino") {
103
+ const resolvedPino = await this.resolve(id, importee);
104
+ if (resolvedPino) {
105
+ await Promise.all(
106
+ workerFiles.map(async (file) => {
107
+ const resolvedEntry = await this.resolve(file.id, resolvedPino.id);
108
+ if (!resolvedEntry) {
109
+ return null;
110
+ }
111
+ const reference = this.emitFile({
112
+ type: "chunk",
113
+ id: resolvedEntry.id,
114
+ name: `${file.file}`
115
+ });
116
+ fileReferences.set(file.id, reference);
117
+ })
118
+ );
119
+ }
120
+ }
121
+ },
122
+ renderChunk(code, chunk) {
123
+ if (chunk.type === "chunk" && chunk.isEntry && fileReferences.size && chunk.name === "index") {
124
+ const importRegex = /^(?:import(?:["'\s]*[\w*${}\n\r\t, ]+from\s*)?["'\s].+[;"'\s]*)$/gm;
125
+ const codeToInject = `globalThis.__bundlerPathsOverrides = {
126
+ ${Array.from(fileReferences.entries()).map(([key, file]) => {
127
+ return '"' + key + '": import.meta.ROLLUP_FILE_URL_' + file;
128
+ }).join(",\n")}
129
+ };`;
130
+ const matches = Array.from(code.matchAll(importRegex));
131
+ if (matches.length > 0) {
132
+ const lastImport = matches[matches.length - 1];
133
+ const lastImportEnd = lastImport.index + lastImport[0].length;
134
+ const newCode = code.slice(0, lastImportEnd) + "\n\n" + codeToInject + "\n\n" + code.slice(lastImportEnd);
135
+ return {
136
+ code: newCode,
137
+ map: null
138
+ };
139
+ }
140
+ return {
141
+ code: `${codeToInject}
142
+
143
+ ${code}`,
144
+ map: null
145
+ };
146
+ }
147
+ }
148
+ };
149
+ }
150
+ function removeDeployer() {
151
+ const t = babel__namespace.default.types;
152
+ let mastraClass = null;
153
+ return {
154
+ name: "remove-deployer",
155
+ visitor: {
156
+ ImportDeclaration(path2) {
157
+ if ((path2.node.source.value === "@mastra/core" || path2.node.source.value === "@mastra/core/mastra") && path2.node.specifiers) {
158
+ const mastraObj = path2.node.specifiers.find(
159
+ (p) => t.isImportSpecifier(p) && t.isIdentifier(p.imported) && p.imported.name === "Mastra"
160
+ );
161
+ if (mastraObj?.local?.name) {
162
+ mastraClass = mastraObj.local.name;
163
+ }
164
+ }
165
+ },
166
+ NewExpression(path2, state) {
167
+ if (mastraClass && t.isIdentifier(path2.node.callee) && path2.node.callee.name === mastraClass && !state.hasReplaced) {
168
+ state.hasReplaced = true;
169
+ const newMastraObj = t.cloneNode(path2.node);
170
+ if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
171
+ newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
172
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name !== "deployer"
173
+ );
174
+ path2.replaceWith(newMastraObj);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ };
180
+ }
181
+
182
+ // src/build/plugins/remove-deployer.ts
183
+ function removeDeployer2(mastraEntry) {
184
+ return {
185
+ name: "remove-deployer",
186
+ transform(code, id) {
187
+ if (id !== mastraEntry) {
188
+ return;
189
+ }
190
+ return new Promise((resolve2, reject) => {
191
+ babel__namespace.transform(
192
+ code,
193
+ {
194
+ babelrc: false,
195
+ configFile: false,
196
+ filename: id,
197
+ plugins: [removeDeployer]
198
+ },
199
+ (err, result) => {
200
+ if (err) {
201
+ return reject(err);
202
+ }
203
+ resolve2({
204
+ code: result.code,
205
+ map: result.map
206
+ });
207
+ }
208
+ );
209
+ });
210
+ }
211
+ };
212
+ }
213
+
214
+ // src/build/analyze.ts
215
+ async function analyze(entry, mastraEntry, isVirtualFile, platform2, logger) {
216
+ logger.info("Analyzing dependencies...");
217
+ let virtualPlugin = null;
218
+ if (isVirtualFile) {
219
+ virtualPlugin = virtual__default.default({
220
+ "#entry": entry
221
+ });
222
+ entry = "#entry";
223
+ }
224
+ const optimizerBundler = await rollup.rollup({
225
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
226
+ input: isVirtualFile ? "#entry" : entry,
227
+ treeshake: true,
228
+ preserveSymlinks: true,
229
+ plugins: [
230
+ virtualPlugin,
231
+ {
232
+ name: "custom-alias-resolver",
233
+ resolveId(id) {
234
+ if (id === "#server") {
235
+ return url.fileURLToPath(undefined("@mastra/deployer/server")).replaceAll("\\", "/");
236
+ }
237
+ if (id === "#mastra") {
238
+ return mastraEntry.replaceAll("\\", "/");
239
+ }
240
+ }
241
+ },
242
+ json__default.default(),
243
+ commonjs__default.default({
244
+ strictRequires: "debug",
245
+ ignoreTryCatch: false,
246
+ transformMixedEsModules: true,
247
+ extensions: [".js", ".ts"]
248
+ }),
249
+ esbuild__default.default({
250
+ target: "node20",
251
+ platform: platform2,
252
+ minify: false
253
+ }),
254
+ removeDeployer2(mastraEntry),
255
+ esbuild__default.default({
256
+ target: "node20",
257
+ platform: platform2,
258
+ minify: false
259
+ })
260
+ ].filter(Boolean)
261
+ });
262
+ const { output } = await optimizerBundler.generate({
263
+ format: "esm",
264
+ inlineDynamicImports: true
265
+ });
266
+ await optimizerBundler.close();
267
+ const depsToOptimize = new Map(Object.entries(output[0].importedBindings));
268
+ for (const dep of depsToOptimize.keys()) {
269
+ if (isNodeBuiltin(dep)) {
270
+ depsToOptimize.delete(dep);
271
+ }
272
+ }
273
+ return depsToOptimize;
274
+ }
275
+ async function bundleExternals(depsToOptimize, outputDir, logger) {
276
+ logger.info("Optimizing dependencies...");
277
+ logger.debug(
278
+ `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
279
+ );
280
+ const reverseVirtualReferenceMap = /* @__PURE__ */ new Map();
281
+ const virtualDependencies = /* @__PURE__ */ new Map();
282
+ for (const [dep, exports] of depsToOptimize.entries()) {
283
+ const name = dep.replaceAll("/", "-");
284
+ reverseVirtualReferenceMap.set(name, dep);
285
+ const virtualFile = [];
286
+ let exportStringBuilder = [];
287
+ for (const local of exports) {
288
+ if (local === "*") {
289
+ virtualFile.push(`export * from '${dep}';`);
290
+ } else if (local === "default") {
291
+ virtualFile.push(`export * from '${dep}';`);
292
+ } else {
293
+ exportStringBuilder.push(local);
294
+ }
295
+ }
296
+ if (exportStringBuilder.length > 0) {
297
+ virtualFile.push(`export { ${exportStringBuilder.join(", ")} } from '${dep}';`);
298
+ }
299
+ virtualDependencies.set(dep, {
300
+ name,
301
+ virtual: virtualFile.join("\n")
302
+ });
303
+ }
304
+ const bundler = await rollup.rollup({
305
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
306
+ input: Array.from(virtualDependencies.entries()).reduce(
307
+ (acc, [dep, virtualDep]) => {
308
+ acc[virtualDep.name] = `#virtual-${dep}`;
309
+ return acc;
310
+ },
311
+ {}
312
+ ),
313
+ // this dependency breaks the build, so we need to exclude it
314
+ // TODO actually fix this so we don't need to exclude it
315
+ external: ["jsdom"],
316
+ treeshake: "smallest",
317
+ preserveSymlinks: true,
318
+ plugins: [
319
+ virtual__default.default(
320
+ Array.from(virtualDependencies.entries()).reduce(
321
+ (acc, [dep, virtualDep]) => {
322
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
323
+ return acc;
324
+ },
325
+ {}
326
+ )
327
+ ),
328
+ pino(),
329
+ commonjs__default.default({
330
+ strictRequires: "strict",
331
+ transformMixedEsModules: true,
332
+ ignoreTryCatch: false
333
+ }),
334
+ nodeResolve2__default.default({
335
+ preferBuiltins: true,
336
+ exportConditions: ["node", "import", "require"],
337
+ mainFields: ["module", "main"]
338
+ }),
339
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
340
+ aliasHono(),
341
+ json__default.default()
342
+ ].filter(Boolean)
343
+ });
344
+ const { output } = await bundler.write({
345
+ format: "esm",
346
+ dir: outputDir,
347
+ entryFileNames: "[name].mjs",
348
+ chunkFileNames: "[name].mjs"
349
+ });
350
+ await bundler.close();
351
+ return { output, reverseVirtualReferenceMap };
352
+ }
353
+ async function validateOutput(output, reverseVirtualReferenceMap, outputDir, logger) {
354
+ const result = {
355
+ invalidChunks: /* @__PURE__ */ new Set(),
356
+ dependencies: /* @__PURE__ */ new Map(),
357
+ externalDependencies: /* @__PURE__ */ new Set()
358
+ };
359
+ for (const file of output) {
360
+ if (file.type === "asset") {
361
+ continue;
362
+ }
363
+ try {
364
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
365
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
366
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
367
+ }
368
+ await import(`file:${outputDir}/${file.fileName}`);
369
+ } catch (err) {
370
+ result.invalidChunks.add(file.fileName);
371
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
372
+ result.externalDependencies.add(reverseVirtualReferenceMap.get(file.name));
373
+ }
374
+ }
375
+ }
376
+ return result;
377
+ }
378
+ async function analyzeBundle(entry, mastraEntry, outputDir, platform2, logger) {
379
+ const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
380
+ const depsToOptimize = await analyze(entry, mastraEntry, isVirtualFile, platform2, logger);
381
+ const { output, reverseVirtualReferenceMap } = await bundleExternals(depsToOptimize, outputDir, logger);
382
+ const result = await validateOutput(output, reverseVirtualReferenceMap, outputDir, logger);
383
+ return result;
384
+ }
385
+ function rewriteLibsqlImport() {
386
+ const t = babel__namespace.default.types;
387
+ let hasReplaced = false;
388
+ return {
389
+ name: "rewrite-libsql-import",
390
+ visitor: {
391
+ FunctionDeclaration(path2) {
392
+ if (path2.node.id?.name === "requireNative" && !hasReplaced) {
393
+ hasReplaced = true;
394
+ const createRequire = helperModuleImports.addNamed(path2, "createRequire", "module");
395
+ const requireIdentifier = t.identifier("require");
396
+ path2.replaceWith(
397
+ t.functionDeclaration(
398
+ t.identifier("requireNative"),
399
+ [],
400
+ t.blockStatement([
401
+ t.variableDeclaration("const", [
402
+ t.variableDeclarator(
403
+ requireIdentifier,
404
+ t.callExpression(createRequire, [
405
+ t.memberExpression(
406
+ t.metaProperty(t.identifier("import"), t.identifier("meta")),
407
+ t.identifier("url")
408
+ )
409
+ ])
410
+ )
411
+ ]),
412
+ t.returnStatement(t.callExpression(requireIdentifier, [t.stringLiteral("./libsql.node")]))
413
+ ])
414
+ )
415
+ );
416
+ }
417
+ }
418
+ }
419
+ };
420
+ }
421
+
422
+ // src/build/plugins/fix-libsql.ts
423
+ function libSqlFix() {
424
+ return {
425
+ name: "libSqlFix",
426
+ transform(code, id) {
427
+ if (!id.includes("\\libsql\\index.js") && !id.includes("/libsql/index.js")) {
428
+ return null;
429
+ }
430
+ return new Promise((resolve2, reject) => {
431
+ babel__namespace.transform(
432
+ code,
433
+ {
434
+ babelrc: false,
435
+ configFile: false,
436
+ filename: id,
437
+ plugins: [rewriteLibsqlImport]
438
+ },
439
+ (err, result) => {
440
+ if (err) {
441
+ return reject(err);
442
+ }
443
+ resolve2({
444
+ code: result.code,
445
+ map: result.map
446
+ });
447
+ }
448
+ );
449
+ });
450
+ },
451
+ async generateBundle({ file, dir }) {
452
+ if (!file && !dir) {
453
+ throw new Error("No output options were given.");
454
+ }
455
+ const outputDirectory = dir || path.dirname(file);
456
+ let target = load.currentTarget();
457
+ if (detectLibc.familySync() == detectLibc.GLIBC) {
458
+ switch (target) {
459
+ case "linux-x64-musl":
460
+ target = "linux-x64-gnu";
461
+ break;
462
+ case "linux-arm64-musl":
463
+ target = "linux-arm64-gnu";
464
+ break;
465
+ }
466
+ }
467
+ const fileToCopy = await this.resolve(`@libsql/${target}/index.node`);
468
+ if (fileToCopy) {
469
+ await fsExtra__default.default.copy(fileToCopy.id, path.join(outputDirectory, "libsql.node"));
470
+ }
471
+ }
472
+ };
473
+ }
474
+ function getTelemetryMachineFile() {
475
+ switch (process$1.platform) {
476
+ case "darwin":
477
+ return "getMachineId-darwin";
478
+ case "linux":
479
+ return "getMachineId-linux";
480
+ case "freebsd":
481
+ return "getMachineId-bsd";
482
+ case "win32":
483
+ return "getMachineId-win";
484
+ default:
485
+ return "getMachineId-unsupported";
486
+ }
487
+ }
488
+ function telemetryFix() {
489
+ return {
490
+ name: "telemetry-fix",
491
+ transform(code, id) {
492
+ if (id.includes("require-in-the-middle")) {
493
+ return code.replace(
494
+ `const path = require('path')`,
495
+ `const path = require('path');
496
+ const { createRequire } = require('module');
497
+ const realRequire = createRequire(import.meta.url)`
498
+ ).replaceAll(`require.resolve`, `realRequire.resolve`);
499
+ }
500
+ },
501
+ resolveId(id, importer) {
502
+ if (id === "./machine-id/getMachineId" && importer) {
503
+ return { id: path.resolve(path.dirname(importer), `./machine-id/${getTelemetryMachineFile()}.js`) };
504
+ }
505
+ if (id === "formdata-node") {
506
+ return { id: "formdata-node", external: false };
507
+ }
508
+ },
509
+ load(id) {
510
+ if (id.startsWith("formdata-node")) {
511
+ return "export default {};";
512
+ }
513
+ return null;
514
+ }
515
+ };
516
+ }
517
+
518
+ // src/build/bundler.ts
519
+ async function getInputOptions(entryFile, analyzedBundleInfo, platform2) {
520
+ let nodeResolvePlugin = nodeResolve2__default.default({
521
+ preferBuiltins: true,
522
+ exportConditions: ["node", "import", "require"],
523
+ mainFields: ["module", "main"]
524
+ }) ;
525
+ const externals = Array.from(analyzedBundleInfo.externalDependencies).concat(["@mastra/core/hooks"]);
526
+ return {
527
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
528
+ treeshake: true,
529
+ preserveSymlinks: true,
530
+ external: externals,
531
+ plugins: [
532
+ telemetryFix(),
533
+ libSqlFix(),
534
+ {
535
+ name: "alias-optimized-deps",
536
+ // @ts-ignore
537
+ resolveId(id) {
538
+ if (!analyzedBundleInfo.dependencies.has(id)) {
539
+ return null;
540
+ }
541
+ const isInvalidChunk = analyzedBundleInfo.invalidChunks.has(analyzedBundleInfo.dependencies.get(id));
542
+ if (isInvalidChunk) {
543
+ return {
544
+ id,
545
+ external: true
546
+ };
547
+ }
548
+ return {
549
+ id: ".mastra/.build/" + analyzedBundleInfo.dependencies.get(id),
550
+ external: false
551
+ };
552
+ }
553
+ },
554
+ alias__default.default({
555
+ entries: [
556
+ {
557
+ find: /^\#server$/,
558
+ replacement: url.fileURLToPath(undefined("@mastra/deployer/server")).replaceAll("\\", "/")
559
+ },
560
+ { find: /^\#mastra$/, replacement: entryFile.replaceAll("\\", "/") }
561
+ ]
562
+ }),
563
+ esbuild__default.default({
564
+ target: "node20",
565
+ platform: platform2,
566
+ minify: false,
567
+ define: {
568
+ "process.env.NODE_ENV": JSON.stringify("production")
569
+ }
570
+ }),
571
+ commonjs__default.default({
572
+ extensions: [".js", ".ts"],
573
+ transformMixedEsModules: true,
574
+ esmExternals(id) {
575
+ return externals.includes(id);
576
+ }
577
+ }),
578
+ nodeResolvePlugin,
579
+ // for debugging
580
+ // {
581
+ // name: 'logger',
582
+ // //@ts-ignore
583
+ // resolveId(id, ...args) {
584
+ // console.log({ id, args });
585
+ // },
586
+ // // @ts-ignore
587
+ // transform(code, id) {
588
+ // if (code.includes('class Duplexify ')) {
589
+ // console.log({ duplex: id });
590
+ // }
591
+ // },
592
+ // },
593
+ json__default.default(),
594
+ removeDeployer2(entryFile),
595
+ // treeshake unused imports
596
+ esbuild__default.default({
597
+ include: entryFile,
598
+ target: "node20",
599
+ platform: platform2,
600
+ minify: false
601
+ })
602
+ ].filter(Boolean)
603
+ };
604
+ }
605
+ async function createBundler(inputOptions, outputOptions) {
606
+ const bundler = await rollup.rollup(inputOptions);
607
+ return {
608
+ write: () => {
609
+ return bundler.write({
610
+ ...outputOptions,
611
+ format: "esm",
612
+ entryFileNames: "[name].mjs",
613
+ chunkFileNames: "[name].mjs"
614
+ });
615
+ },
616
+ close: () => {
617
+ return bundler.close();
618
+ }
619
+ };
620
+ }
621
+ var createPinoStream = (logger) => {
622
+ return new stream.Transform({
623
+ transform(chunk, _encoding, callback) {
624
+ const line = chunk.toString().trim();
625
+ if (line) {
626
+ console.log(line);
627
+ logger.info(line);
628
+ }
629
+ callback(null, chunk);
630
+ }
631
+ });
632
+ };
633
+ function createChildProcessLogger({ logger, root }) {
634
+ const pinoStream = createPinoStream(logger);
635
+ return async ({ cmd, args, env }) => {
636
+ try {
637
+ const subprocess = child_process.spawn(cmd, args, {
638
+ cwd: root,
639
+ shell: true,
640
+ env
641
+ });
642
+ subprocess.stdout?.pipe(pinoStream);
643
+ subprocess.stderr?.pipe(pinoStream);
644
+ return new Promise((resolve2, reject) => {
645
+ subprocess.on("close", (code) => {
646
+ pinoStream.end();
647
+ if (code === 0) {
648
+ resolve2({ success: true });
649
+ } else {
650
+ reject(new Error(`Process exited with code ${code}`));
651
+ }
652
+ });
653
+ subprocess.on("error", (error) => {
654
+ pinoStream.end();
655
+ logger.error("Process failed", { error });
656
+ reject(error);
657
+ });
658
+ });
659
+ } catch (error) {
660
+ console.log(error);
661
+ logger.error("Process failed", { error });
662
+ pinoStream.end();
663
+ return { success: false, error };
664
+ }
665
+ };
666
+ }
667
+
668
+ // src/build/deps.ts
669
+ var Deps = class extends base.MastraBase {
670
+ packageManager;
671
+ rootDir;
672
+ constructor(rootDir = process.cwd()) {
673
+ super({ component: "DEPLOYER", name: "DEPS" });
674
+ this.rootDir = rootDir;
675
+ this.packageManager = this.getPackageManager();
676
+ }
677
+ findLockFile(dir) {
678
+ const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
679
+ for (const file of lockFiles) {
680
+ if (fs__default.default.existsSync(path__default.default.join(dir, file))) {
681
+ return file;
682
+ }
683
+ }
684
+ const parentDir = path__default.default.resolve(dir, "..");
685
+ if (parentDir !== dir) {
686
+ return this.findLockFile(parentDir);
687
+ }
688
+ return null;
689
+ }
690
+ getPackageManager() {
691
+ const lockFile = this.findLockFile(this.rootDir);
692
+ switch (lockFile) {
693
+ case "pnpm-lock.yaml":
694
+ return "pnpm";
695
+ case "package-lock.json":
696
+ return "npm";
697
+ case "yarn.lock":
698
+ return "yarn";
699
+ case "bun.lock":
700
+ return "bun";
701
+ default:
702
+ return "npm";
703
+ }
704
+ }
705
+ async install({ dir = this.rootDir, packages = [] }) {
706
+ let runCommand = this.packageManager;
707
+ if (this.packageManager === "npm") {
708
+ runCommand = `${this.packageManager} i`;
709
+ } else {
710
+ runCommand = `${this.packageManager} ${packages?.length > 0 ? `add` : `install`}`;
711
+ }
712
+ const cpLogger = createChildProcessLogger({
713
+ logger: this.logger,
714
+ root: dir
715
+ });
716
+ return cpLogger({
717
+ cmd: runCommand,
718
+ args: packages,
719
+ env: {
720
+ PATH: process.env.PATH
721
+ }
722
+ });
723
+ }
724
+ async installPackages(packages) {
725
+ let runCommand = this.packageManager;
726
+ if (this.packageManager === "npm") {
727
+ runCommand = `${this.packageManager} i`;
728
+ } else {
729
+ runCommand = `${this.packageManager} add`;
730
+ }
731
+ const cpLogger = createChildProcessLogger({
732
+ logger: this.logger,
733
+ root: ""
734
+ });
735
+ return cpLogger({
736
+ cmd: `${runCommand}`,
737
+ args: packages,
738
+ env: {
739
+ PATH: process.env.PATH
740
+ }
741
+ });
742
+ }
743
+ async checkDependencies(dependencies) {
744
+ try {
745
+ const packageJsonPath = path__default.default.join(this.rootDir, "package.json");
746
+ try {
747
+ await fsPromises__default.default.access(packageJsonPath);
748
+ } catch {
749
+ return "No package.json file found in the current directory";
750
+ }
751
+ const packageJson = JSON.parse(await fsPromises__default.default.readFile(packageJsonPath, "utf-8"));
752
+ for (const dependency of dependencies) {
753
+ if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {
754
+ return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;
755
+ }
756
+ }
757
+ return "ok";
758
+ } catch (err) {
759
+ console.error(err);
760
+ return "Could not check dependencies";
761
+ }
762
+ }
763
+ async getProjectName() {
764
+ try {
765
+ const packageJsonPath = path__default.default.join(this.rootDir, "package.json");
766
+ const packageJson = await fsPromises__default.default.readFile(packageJsonPath, "utf-8");
767
+ const pkg = JSON.parse(packageJson);
768
+ return pkg.name;
769
+ } catch (err) {
770
+ throw err;
771
+ }
772
+ }
773
+ async getPackageVersion() {
774
+ const __filename = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
775
+ const __dirname = path.dirname(__filename);
776
+ const pkgJsonPath = path__default.default.join(__dirname, "..", "..", "package.json");
777
+ const content = await fsExtra__default.default.readJSON(pkgJsonPath);
778
+ return content.version;
779
+ }
780
+ async addScriptsToPackageJson(scripts) {
781
+ const packageJson = JSON.parse(await fsPromises__default.default.readFile("package.json", "utf-8"));
782
+ packageJson.scripts = {
783
+ ...packageJson.scripts,
784
+ ...scripts
785
+ };
786
+ await fsPromises__default.default.writeFile("package.json", JSON.stringify(packageJson, null, 2));
787
+ }
788
+ };
789
+ function removeAllExceptTelemetryConfig(result) {
790
+ let mastraClass = null;
791
+ const t = babel__namespace.default.types;
792
+ return {
793
+ name: "remove-all-except-telemetry-config",
794
+ visitor: {
795
+ ExportNamedDeclaration: {
796
+ // remove all exports
797
+ exit(path2) {
798
+ path2.remove();
799
+ }
800
+ },
801
+ ImportDeclaration(path2) {
802
+ if ((path2.node.source.value === "@mastra/core" || path2.node.source.value === "@mastra/core/mastra") && path2.node.specifiers) {
803
+ mastraClass = path2.node.specifiers.find(
804
+ // @ts-ignore - no need to type
805
+ (p) => p.imported?.name === "Mastra"
806
+ )?.local?.name ?? null;
807
+ }
808
+ },
809
+ NewExpression(path2) {
810
+ if (mastraClass && path2.node.callee.name === mastraClass) {
811
+ let telemetry = path2.node.arguments[0]?.properties?.find(
812
+ // @ts-ignore
813
+ (prop) => prop.key.name === "telemetry"
814
+ );
815
+ const programPath = path2.scope.getProgramParent().path;
816
+ if (!programPath) {
817
+ return;
818
+ }
819
+ if (telemetry) {
820
+ result.hasCustomConfig = true;
821
+ } else {
822
+ telemetry = {
823
+ value: t.objectExpression([])
824
+ };
825
+ }
826
+ const exportDeclaration = t.exportNamedDeclaration(
827
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("telemetry"), telemetry.value)]),
828
+ []
829
+ );
830
+ programPath.node.body.push(exportDeclaration);
831
+ }
832
+ }
833
+ }
834
+ };
835
+ }
836
+
837
+ // src/build/telemetry.ts
838
+ async function writeTelemetryConfig(entryFile, outputDir) {
839
+ const result = {
840
+ hasCustomConfig: false
841
+ };
842
+ const bundle = await rollup.rollup({
843
+ input: {
844
+ "telemetry-config": entryFile
845
+ },
846
+ treeshake: true,
847
+ plugins: [
848
+ // transpile typescript to something we understand
849
+ esbuild__default.default({
850
+ target: "node20",
851
+ platform: "node",
852
+ minify: false
853
+ }),
854
+ {
855
+ name: "get-telemetry-config",
856
+ transform(code, id) {
857
+ if (!this.getModuleInfo(id)?.isEntry) {
858
+ return;
859
+ }
860
+ return new Promise((resolve2, reject) => {
861
+ babel__namespace.transform(
862
+ code,
863
+ {
864
+ babelrc: false,
865
+ configFile: false,
866
+ filename: id,
867
+ plugins: [removeAllExceptTelemetryConfig(result)]
868
+ },
869
+ (err, result2) => {
870
+ if (err) {
871
+ return reject(err);
872
+ }
873
+ resolve2({
874
+ code: result2.code,
875
+ map: result2.map
876
+ });
877
+ }
878
+ );
879
+ });
880
+ }
881
+ },
882
+ // let esbuild remove all unused imports
883
+ esbuild__default.default({
884
+ target: "node20",
885
+ platform: "node",
886
+ minify: false
887
+ })
888
+ ]
889
+ });
890
+ await bundle.write({
891
+ dir: outputDir,
892
+ format: "es",
893
+ entryFileNames: "[name].mjs"
894
+ });
895
+ return result;
896
+ }
897
+
898
+ // src/bundler/index.ts
899
+ var Bundler = class extends bundler.MastraBundler {
900
+ analyzeOutputDir = ".build";
901
+ outputDir = "output";
902
+ constructor(name, component = "BUNDLER") {
903
+ super({ name, component });
904
+ }
905
+ async prepare(outputDirectory) {
906
+ await fsExtra__default.default.emptyDir(outputDirectory);
907
+ await fsExtra$1.ensureDir(path.join(outputDirectory, this.analyzeOutputDir));
908
+ await fsExtra$1.ensureDir(path.join(outputDirectory, this.outputDir));
909
+ }
910
+ async writeInstrumentationFile(outputDirectory) {
911
+ const instrumentationFile = path.join(outputDirectory, "instrumentation.mjs");
912
+ const __dirname = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
913
+ await fsExtra$1.copy(path.join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
914
+ }
915
+ async writePackageJson(outputDirectory, dependencies) {
916
+ this.logger.debug(`Writing project's package.json`);
917
+ await fsExtra$1.ensureDir(outputDirectory);
918
+ const pkgPath = path.join(outputDirectory, "package.json");
919
+ const dependenciesMap = /* @__PURE__ */ new Map();
920
+ for (const [key, value] of dependencies.entries()) {
921
+ if (key.startsWith("@")) {
922
+ const pkgChunks = key.split("/");
923
+ dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
924
+ continue;
925
+ }
926
+ dependenciesMap.set(key, value);
927
+ }
928
+ dependenciesMap.set("@opentelemetry/instrumentation", "latest");
929
+ await fsPromises.writeFile(
930
+ pkgPath,
931
+ JSON.stringify(
932
+ {
933
+ name: "server",
934
+ version: "1.0.0",
935
+ description: "",
936
+ type: "module",
937
+ main: "index.mjs",
938
+ scripts: {
939
+ start: "node ./index.mjs"
940
+ },
941
+ author: "Mastra",
942
+ license: "ISC",
943
+ dependencies: Object.fromEntries(dependenciesMap.entries())
944
+ },
945
+ null,
946
+ 2
947
+ )
948
+ );
949
+ }
950
+ createBundler(inputOptions, outputOptions) {
951
+ return createBundler(inputOptions, outputOptions);
952
+ }
953
+ async analyze(entry, mastraFile, outputDirectory) {
954
+ return await analyzeBundle(entry, mastraFile, path.join(outputDirectory, this.analyzeOutputDir), "node", this.logger);
955
+ }
956
+ async installDependencies(outputDirectory, rootDir = process.cwd()) {
957
+ const deps = new Deps(rootDir);
958
+ deps.__setLogger(this.logger);
959
+ await deps.install({ dir: path.join(outputDirectory, this.outputDir) });
960
+ }
961
+ async _bundle(serverFile, mastraEntryFile, outputDirectory, bundleLocation = path.join(outputDirectory, this.outputDir)) {
962
+ this.logger.info("Start bundling Mastra");
963
+ const isVirtual = serverFile.includes("\n") || fs.existsSync(serverFile);
964
+ const analyzedBundleInfo = await analyzeBundle(
965
+ serverFile,
966
+ mastraEntryFile,
967
+ path.join(outputDirectory, this.analyzeOutputDir),
968
+ "node",
969
+ this.logger
970
+ );
971
+ await writeTelemetryConfig(mastraEntryFile, path.join(outputDirectory, this.outputDir));
972
+ const dependenciesToInstall = Array.from(analyzedBundleInfo.externalDependencies).reduce((acc, dep) => {
973
+ acc.set(dep, "latest");
974
+ return acc;
975
+ }, /* @__PURE__ */ new Map());
976
+ await this.writePackageJson(path.join(outputDirectory, this.outputDir), dependenciesToInstall);
977
+ await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir));
978
+ this.logger.info("Bundling Mastra application");
979
+ const inputOptions = await getInputOptions(mastraEntryFile, analyzedBundleInfo, "node");
980
+ if (isVirtual) {
981
+ inputOptions.input = { index: "#entry" };
982
+ if (Array.isArray(inputOptions.plugins)) {
983
+ inputOptions.plugins.unshift(virtual__default.default({ "#entry": serverFile }));
984
+ } else {
985
+ inputOptions.plugins = [virtual__default.default({ "#entry": serverFile })];
986
+ }
987
+ } else {
988
+ inputOptions.input = { index: serverFile };
989
+ }
990
+ const bundler = await this.createBundler(inputOptions, { dir: bundleLocation });
991
+ await bundler.write();
992
+ this.logger.info("Bundling Mastra done");
993
+ this.logger.info("Installing dependencies");
994
+ await this.installDependencies(outputDirectory);
995
+ this.logger.info("Done installing dependencies");
996
+ }
997
+ };
998
+
999
+ exports.Bundler = Bundler;