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