@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,86 @@
1
+ import { createLogger } from '@mastra/core/logger'
2
+ import { LibSQLStore } from '@mastra/core/storage/libsql'
3
+ import { OTLPStorageExporter } from '@mastra/core/telemetry'
4
+ import {
5
+ NodeSDK, getNodeAutoInstrumentations, ATTR_SERVICE_NAME, Resource,
6
+ ParentBasedSampler,
7
+ TraceIdRatioBasedSampler,
8
+ AlwaysOnSampler,
9
+ AlwaysOffSampler,
10
+ OTLPHttpExporter,
11
+ } from '@mastra/core/telemetry/otel-vendor';
12
+ import { telemetry } from './telemetry-config.mjs'
13
+
14
+
15
+ function getSampler(config) {
16
+ if (!config.sampling) {
17
+ return new AlwaysOnSampler();
18
+ }
19
+
20
+ if (!config.enabled) {
21
+ return new AlwaysOffSampler();
22
+ }
23
+
24
+ switch (config.sampling.type) {
25
+ case 'ratio':
26
+ return new TraceIdRatioBasedSampler(config.sampling.probability);
27
+ case 'always_on':
28
+ return new AlwaysOnSampler();
29
+ case 'always_off':
30
+ return new AlwaysOffSampler();
31
+ case 'parent_based':
32
+ const rootSampler = new TraceIdRatioBasedSampler(config.sampling.root?.probability || 1.0);
33
+ return new ParentBasedSampler({ root: rootSampler });
34
+ default:
35
+ return new AlwaysOnSampler();
36
+ }
37
+
38
+ }
39
+
40
+ async function getExporter(config) {
41
+ if (config.export?.type === 'otlp') {
42
+ return new OTLPHttpExporter({
43
+ url: config.export.endpoint,
44
+ headers: config.export.headers,
45
+ })
46
+ } else if (config.export?.type === 'custom') {
47
+ return config.export.exporter
48
+ } else {
49
+ const storage = new LibSQLStore({
50
+ config: {
51
+ // file lives in ./.mastra/output, and we need to write to ./.mastra/mastra.db
52
+ url: "file:../mastra.db",
53
+ },
54
+ })
55
+ await storage.init()
56
+
57
+ return new OTLPStorageExporter({
58
+ logger: createLogger({
59
+ name: 'telemetry',
60
+ level: 'silent',
61
+ }),
62
+ storage,
63
+ })
64
+ }
65
+ }
66
+
67
+ const sampler = getSampler(telemetry);
68
+ const exporter = await getExporter(telemetry);
69
+
70
+ const sdk = new NodeSDK({
71
+ resource: new Resource({
72
+ [ATTR_SERVICE_NAME]: telemetry.serviceName || 'default-service',
73
+ }),
74
+ sampler,
75
+ traceExporter: exporter,
76
+ instrumentations: [getNodeAutoInstrumentations()],
77
+ });
78
+
79
+ sdk.start();
80
+
81
+ // gracefully shut down the SDK on process exit
82
+ process.on('SIGTERM', () => {
83
+ sdk.shutdown().catch(() => {
84
+ // do nothing
85
+ })
86
+ });
@@ -0,0 +1,6 @@
1
+ import { createConfig } from '@internal/lint/eslint';
2
+
3
+ const config = await createConfig();
4
+
5
+ /** @type {import("eslint").Linter.Config[]} */
6
+ export default [...config];
package/global.d.ts ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,112 @@
1
+ {
2
+ "name": "@mastra/deployer",
3
+ "version": "0.0.0-commonjs-20250227130920",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.cts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "./server": {
20
+ "import": {
21
+ "types": "./dist/server/index.d.ts",
22
+ "default": "./dist/server/index.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/server/index.d.cts",
26
+ "default": "./dist/server/index.cjs"
27
+ }
28
+ },
29
+ "./build": {
30
+ "import": {
31
+ "types": "./dist/build/index.d.ts",
32
+ "default": "./dist/build/index.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/build/index.d.cts",
36
+ "default": "./dist/build/index.cjs"
37
+ }
38
+ },
39
+ "./bundler": {
40
+ "import": {
41
+ "types": "./dist/bundler/index.d.ts",
42
+ "default": "./dist/bundler/index.js"
43
+ },
44
+ "require": {
45
+ "types": "./dist/bundler/index.d.cts",
46
+ "default": "./dist/bundler/index.cjs"
47
+ }
48
+ },
49
+ "./analyze": {
50
+ "import": {
51
+ "types": "./dist/build/analyze.d.ts",
52
+ "default": "./dist/build/analyze.js"
53
+ },
54
+ "require": {
55
+ "types": "./dist/build/analyze.d.cts",
56
+ "default": "./dist/build/analyze.cjs"
57
+ }
58
+ },
59
+ "./package.json": "./package.json"
60
+ },
61
+ "keywords": [],
62
+ "author": "",
63
+ "license": "ISC",
64
+ "dependencies": {
65
+ "@babel/core": "^7.26.7",
66
+ "@babel/helper-module-imports": "^7.25.9",
67
+ "@neon-rs/load": "^0.1.82",
68
+ "@rollup/plugin-alias": "^5.1.1",
69
+ "@rollup/plugin-commonjs": "^28.0.2",
70
+ "@rollup/plugin-json": "^6.1.0",
71
+ "@rollup/plugin-node-resolve": "^16.0.0",
72
+ "@rollup/plugin-virtual": "^3.0.2",
73
+ "builtins": "^5.1.0",
74
+ "detect-libc": "^2.0.3",
75
+ "dotenv": "^16.4.7",
76
+ "esbuild": "^0.24.2",
77
+ "fs-extra": "^11.2.0",
78
+ "hono": "^4.6.17",
79
+ "rollup": "^4.30.1",
80
+ "rollup-plugin-esbuild": "^6.1.1",
81
+ "rollup-plugin-node-externals": "^8.0.0",
82
+ "zod": "^3.24.1",
83
+ "@mastra/core": "^0.0.0-commonjs-20250227130920"
84
+ },
85
+ "devDependencies": {
86
+ "@hono/node-server": "^1.13.7",
87
+ "@hono/swagger-ui": "^0.5.0",
88
+ "@microsoft/api-extractor": "^7.49.2",
89
+ "@types/babel__core": "^7.20.5",
90
+ "@types/babel__helper-module-imports": "^7.18.3",
91
+ "@types/fs-extra": "^11.0.4",
92
+ "@types/node": "^22.13.1",
93
+ "concurrently": "^9.1.0",
94
+ "hono-openapi": "^0.4.3",
95
+ "rollup-plugin-visualizer": "^5.14.0",
96
+ "superjson": "^2.2.2",
97
+ "tsup": "^8.3.6",
98
+ "type-fest": "^4.30.0",
99
+ "typescript": "^5.7.3",
100
+ "vitest": "^2.1.8",
101
+ "zod-to-json-schema": "^3.24.1",
102
+ "eslint": "^9.20.1",
103
+ "@internal/lint": "0.0.0"
104
+ },
105
+ "scripts": {
106
+ "build": "tsup src/index.ts src/build/index.ts src/server/index.ts src/build/bundler.ts src/build/analyze.ts src/bundler/index.ts --format esm,cjs --clean --experimental-dts --treeshake --publicDir",
107
+ "build:watch": "pnpm build --watch",
108
+ "pull:openapispec": "node src/server/openapi.script.js",
109
+ "test": "vitest run",
110
+ "lint": "eslint ."
111
+ }
112
+ }
@@ -0,0 +1,86 @@
1
+ import { createLogger } from '@mastra/core/logger'
2
+ import { LibSQLStore } from '@mastra/core/storage/libsql'
3
+ import { OTLPStorageExporter } from '@mastra/core/telemetry'
4
+ import {
5
+ NodeSDK, getNodeAutoInstrumentations, ATTR_SERVICE_NAME, Resource,
6
+ ParentBasedSampler,
7
+ TraceIdRatioBasedSampler,
8
+ AlwaysOnSampler,
9
+ AlwaysOffSampler,
10
+ OTLPHttpExporter,
11
+ } from '@mastra/core/telemetry/otel-vendor';
12
+ import { telemetry } from './telemetry-config.mjs'
13
+
14
+
15
+ function getSampler(config) {
16
+ if (!config.sampling) {
17
+ return new AlwaysOnSampler();
18
+ }
19
+
20
+ if (!config.enabled) {
21
+ return new AlwaysOffSampler();
22
+ }
23
+
24
+ switch (config.sampling.type) {
25
+ case 'ratio':
26
+ return new TraceIdRatioBasedSampler(config.sampling.probability);
27
+ case 'always_on':
28
+ return new AlwaysOnSampler();
29
+ case 'always_off':
30
+ return new AlwaysOffSampler();
31
+ case 'parent_based':
32
+ const rootSampler = new TraceIdRatioBasedSampler(config.sampling.root?.probability || 1.0);
33
+ return new ParentBasedSampler({ root: rootSampler });
34
+ default:
35
+ return new AlwaysOnSampler();
36
+ }
37
+
38
+ }
39
+
40
+ async function getExporter(config) {
41
+ if (config.export?.type === 'otlp') {
42
+ return new OTLPHttpExporter({
43
+ url: config.export.endpoint,
44
+ headers: config.export.headers,
45
+ })
46
+ } else if (config.export?.type === 'custom') {
47
+ return config.export.exporter
48
+ } else {
49
+ const storage = new LibSQLStore({
50
+ config: {
51
+ // file lives in ./.mastra/output, and we need to write to ./.mastra/mastra.db
52
+ url: "file:../mastra.db",
53
+ },
54
+ })
55
+ await storage.init()
56
+
57
+ return new OTLPStorageExporter({
58
+ logger: createLogger({
59
+ name: 'telemetry',
60
+ level: 'silent',
61
+ }),
62
+ storage,
63
+ })
64
+ }
65
+ }
66
+
67
+ const sampler = getSampler(telemetry);
68
+ const exporter = await getExporter(telemetry);
69
+
70
+ const sdk = new NodeSDK({
71
+ resource: new Resource({
72
+ [ATTR_SERVICE_NAME]: telemetry.serviceName || 'default-service',
73
+ }),
74
+ sampler,
75
+ traceExporter: exporter,
76
+ instrumentations: [getNodeAutoInstrumentations()],
77
+ });
78
+
79
+ sdk.start();
80
+
81
+ // gracefully shut down the SDK on process exit
82
+ process.on('SIGTERM', () => {
83
+ sdk.shutdown().catch(() => {
84
+ // do nothing
85
+ })
86
+ });
@@ -0,0 +1,279 @@
1
+ import type { Logger } from '@mastra/core';
2
+ import commonjs from '@rollup/plugin-commonjs';
3
+ import json from '@rollup/plugin-json';
4
+ import nodeResolve from '@rollup/plugin-node-resolve';
5
+ import virtual from '@rollup/plugin-virtual';
6
+ import { existsSync } from 'node:fs';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { rollup, type Plugin } from 'rollup';
9
+ import esbuild from 'rollup-plugin-esbuild';
10
+
11
+ import { isNodeBuiltin } from './isNodeBuiltin';
12
+ import { aliasHono } from './plugins/hono-alias';
13
+ import { pino } from './plugins/pino';
14
+ import { removeDeployer } from './plugins/remove-deployer';
15
+
16
+ /**
17
+ * Analyzes the entry file to identify dependencies that need optimization.
18
+ * This is the first step of the bundle analysis process.
19
+ *
20
+ * @param entry - The entry file path or content
21
+ * @param mastraEntry - The mastra entry point
22
+ * @param isVirtualFile - Whether the entry is a virtual file (content string) or a file path
23
+ * @param platform - Target platform (node or browser)
24
+ * @param logger - Logger instance for debugging
25
+ * @returns Map of dependencies to optimize with their exported bindings
26
+ */
27
+ async function analyze(
28
+ entry: string,
29
+ mastraEntry: string,
30
+ isVirtualFile: boolean,
31
+ platform: 'node' | 'browser',
32
+ logger: Logger,
33
+ ) {
34
+ logger.info('Analyzing dependencies...');
35
+ let virtualPlugin = null;
36
+ if (isVirtualFile) {
37
+ virtualPlugin = virtual({
38
+ '#entry': entry,
39
+ });
40
+ entry = '#entry';
41
+ }
42
+
43
+ const optimizerBundler = await rollup({
44
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',
45
+ input: isVirtualFile ? '#entry' : entry,
46
+ treeshake: true,
47
+ preserveSymlinks: true,
48
+ plugins: [
49
+ virtualPlugin,
50
+ {
51
+ name: 'custom-alias-resolver',
52
+ resolveId(id: string) {
53
+ if (id === '#server') {
54
+ return fileURLToPath(import.meta.resolve('@mastra/deployer/server')).replaceAll('\\', '/');
55
+ }
56
+ if (id === '#mastra') {
57
+ return mastraEntry.replaceAll('\\', '/');
58
+ }
59
+ },
60
+ } satisfies Plugin,
61
+ json(),
62
+ commonjs({
63
+ strictRequires: 'debug',
64
+ ignoreTryCatch: false,
65
+ transformMixedEsModules: true,
66
+ extensions: ['.js', '.ts'],
67
+ }),
68
+ esbuild({
69
+ target: 'node20',
70
+ platform,
71
+ minify: false,
72
+ }),
73
+ removeDeployer(mastraEntry),
74
+ esbuild({
75
+ target: 'node20',
76
+ platform,
77
+ minify: false,
78
+ }),
79
+ ].filter(Boolean),
80
+ });
81
+
82
+ const { output } = await optimizerBundler.generate({
83
+ format: 'esm',
84
+ inlineDynamicImports: true,
85
+ });
86
+
87
+ await optimizerBundler.close();
88
+
89
+ const depsToOptimize = new Map(Object.entries(output[0].importedBindings));
90
+ for (const dep of depsToOptimize.keys()) {
91
+ if (isNodeBuiltin(dep)) {
92
+ depsToOptimize.delete(dep);
93
+ }
94
+ }
95
+
96
+ return depsToOptimize;
97
+ }
98
+
99
+ /**
100
+ * Bundles vendor dependencies identified in the analysis step.
101
+ * Creates virtual modules for each dependency and bundles them using rollup.
102
+ *
103
+ * @param depsToOptimize - Map of dependencies with their exports from analyze step
104
+ * @param outputDir - Directory where bundled files will be written
105
+ * @param logger - Logger instance for debugging
106
+ * @returns Object containing bundle output and reference map for validation
107
+ */
108
+ async function bundleExternals(depsToOptimize: Map<string, string[]>, outputDir: string, logger: Logger) {
109
+ logger.info('Optimizing dependencies...');
110
+ logger.debug(
111
+ `${Array.from(depsToOptimize.keys())
112
+ .map(key => `- ${key}`)
113
+ .join('\n')}`,
114
+ );
115
+
116
+ const reverseVirtualReferenceMap = new Map<string, string>();
117
+ const virtualDependencies = new Map();
118
+ for (const [dep, exports] of depsToOptimize.entries()) {
119
+ const name = dep.replaceAll('/', '-');
120
+ reverseVirtualReferenceMap.set(name, dep);
121
+
122
+ const virtualFile: string[] = [];
123
+ let exportStringBuilder = [];
124
+ for (const local of exports) {
125
+ if (local === '*') {
126
+ virtualFile.push(`export * from '${dep}';`);
127
+ } else if (local === 'default') {
128
+ virtualFile.push(`export * from '${dep}';`);
129
+ } else {
130
+ exportStringBuilder.push(local);
131
+ }
132
+ }
133
+
134
+ if (exportStringBuilder.length > 0) {
135
+ virtualFile.push(`export { ${exportStringBuilder.join(', ')} } from '${dep}';`);
136
+ }
137
+
138
+ virtualDependencies.set(dep, {
139
+ name,
140
+ virtual: virtualFile.join('\n'),
141
+ });
142
+ }
143
+
144
+ const bundler = await rollup({
145
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',
146
+ input: Array.from(virtualDependencies.entries()).reduce(
147
+ (acc, [dep, virtualDep]) => {
148
+ acc[virtualDep.name] = `#virtual-${dep}`;
149
+ return acc;
150
+ },
151
+ {} as Record<string, string>,
152
+ ),
153
+ // this dependency breaks the build, so we need to exclude it
154
+ // TODO actually fix this so we don't need to exclude it
155
+ external: ['jsdom'],
156
+ treeshake: 'smallest',
157
+ preserveSymlinks: true,
158
+ plugins: [
159
+ virtual(
160
+ Array.from(virtualDependencies.entries()).reduce(
161
+ (acc, [dep, virtualDep]) => {
162
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
163
+ return acc;
164
+ },
165
+ {} as Record<string, string>,
166
+ ),
167
+ ),
168
+ pino(),
169
+ commonjs({
170
+ strictRequires: 'strict',
171
+ transformMixedEsModules: true,
172
+ ignoreTryCatch: false,
173
+ }),
174
+ nodeResolve({
175
+ preferBuiltins: true,
176
+ exportConditions: ['node', 'import', 'require'],
177
+ mainFields: ['module', 'main'],
178
+ }),
179
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
180
+ aliasHono(),
181
+ json(),
182
+ ].filter(Boolean),
183
+ });
184
+
185
+ const { output } = await bundler.write({
186
+ format: 'esm',
187
+ dir: outputDir,
188
+ entryFileNames: '[name].mjs',
189
+ chunkFileNames: '[name].mjs',
190
+ });
191
+
192
+ await bundler.close();
193
+
194
+ return { output, reverseVirtualReferenceMap };
195
+ }
196
+
197
+ /**
198
+ * Validates the bundled output by attempting to import each generated module.
199
+ * Tracks invalid chunks and external dependencies that couldn't be bundled.
200
+ *
201
+ * @param output - Bundle output from rollup
202
+ * @param reverseVirtualReferenceMap - Map to resolve virtual module names back to original deps
203
+ * @param outputDir - Directory containing the bundled files
204
+ * @param logger - Logger instance for debugging
205
+ * @returns Analysis result containing invalid chunks and dependency mappings
206
+ */
207
+ async function validateOutput(
208
+ output: any[],
209
+ reverseVirtualReferenceMap: Map<string, string>,
210
+ outputDir: string,
211
+ logger: Logger,
212
+ ) {
213
+ const result = {
214
+ invalidChunks: new Set<string>(),
215
+ dependencies: new Map<string, string>(),
216
+ externalDependencies: new Set<string>(),
217
+ };
218
+
219
+ //const internalFiles = new Set<string>(output.map(file => file.fileName));
220
+
221
+ for (const file of output) {
222
+ if (file.type === 'asset') {
223
+ continue;
224
+ }
225
+
226
+ try {
227
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
228
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
229
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name)!, file.fileName);
230
+ }
231
+
232
+ await import(`file:${outputDir}/${file.fileName}`);
233
+ } catch (err) {
234
+ result.invalidChunks.add(file.fileName);
235
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
236
+ result.externalDependencies.add(reverseVirtualReferenceMap.get(file.name)!);
237
+ }
238
+
239
+ // we might need this on other projects but not sure so let's keep it commented out for now
240
+ // console.log(file.fileName, file.isEntry, file.isDynamicEntry, err);
241
+ // result.invalidChunks.add(file.fileName);
242
+ // const externalImports = excludeInternalDeps(file.imports.filter(file => !internalFiles.has(file)));
243
+ // externalImports.push(...excludeInternalDeps(file.dynamicImports.filter(file => !internalFiles.has(file))));
244
+ // for (const externalImport of externalImports) {
245
+ // result.externalDependencies.add(externalImport);
246
+ // }
247
+
248
+ // if (reverseVirtualReferenceMap.has(file.name)) {
249
+ // result.externalDependencies.add(reverseVirtualReferenceMap.get(file.name)!);
250
+ // }
251
+ }
252
+ }
253
+
254
+ return result;
255
+ }
256
+
257
+ /**
258
+ * Main bundle analysis function that orchestrates the three-step process:
259
+ * 1. Analyze dependencies
260
+ * 2. Bundle dependencies modules
261
+ * 3. Validate generated bundles
262
+ *
263
+ * This helps identify which dependencies need to be externalized vs bundled.
264
+ */
265
+ export async function analyzeBundle(
266
+ entry: string,
267
+ mastraEntry: string,
268
+ outputDir: string,
269
+ platform: 'node' | 'browser',
270
+ logger: Logger,
271
+ ) {
272
+ const isVirtualFile = entry.includes('\n') || !existsSync(entry);
273
+
274
+ const depsToOptimize = await analyze(entry, mastraEntry, isVirtualFile, platform, logger);
275
+ const { output, reverseVirtualReferenceMap } = await bundleExternals(depsToOptimize, outputDir, logger);
276
+ const result = await validateOutput(output, reverseVirtualReferenceMap, outputDir, logger);
277
+
278
+ return result;
279
+ }
@@ -0,0 +1,41 @@
1
+ import babel from '@babel/core';
2
+ import { addNamed } from '@babel/helper-module-imports';
3
+
4
+ export function rewriteLibsqlImport() {
5
+ const t = babel.types;
6
+ let hasReplaced = false;
7
+
8
+ return {
9
+ name: 'rewrite-libsql-import',
10
+ visitor: {
11
+ FunctionDeclaration(path) {
12
+ if (path.node.id?.name === 'requireNative' && !hasReplaced) {
13
+ hasReplaced = true;
14
+ const createRequire = addNamed(path, 'createRequire', 'module');
15
+
16
+ const requireIdentifier = t.identifier('require');
17
+ path.replaceWith(
18
+ t.functionDeclaration(
19
+ t.identifier('requireNative'),
20
+ [],
21
+ t.blockStatement([
22
+ t.variableDeclaration('const', [
23
+ t.variableDeclarator(
24
+ requireIdentifier,
25
+ t.callExpression(createRequire, [
26
+ t.memberExpression(
27
+ t.metaProperty(t.identifier('import'), t.identifier('meta')),
28
+ t.identifier('url'),
29
+ ),
30
+ ]),
31
+ ),
32
+ ]),
33
+ t.returnStatement(t.callExpression(requireIdentifier, [t.stringLiteral('./libsql.node')])),
34
+ ]),
35
+ ),
36
+ );
37
+ }
38
+ },
39
+ },
40
+ } as babel.PluginObj;
41
+ }
@@ -0,0 +1,54 @@
1
+ import babel from '@babel/core';
2
+
3
+ export function removeAllExceptDeployer() {
4
+ let mastraClass: string | null = null;
5
+
6
+ const t = babel.types;
7
+
8
+ return {
9
+ name: 'remove-all-except-deployer',
10
+ visitor: {
11
+ ExportNamedDeclaration: {
12
+ // remove all exports
13
+ exit(path) {
14
+ path.remove();
15
+ },
16
+ },
17
+ ImportDeclaration(path) {
18
+ if (
19
+ (path.node.source.value === '@mastra/core' || path.node.source.value === '@mastra/core/mastra') &&
20
+ path.node.specifiers
21
+ ) {
22
+ mastraClass =
23
+ path.node.specifiers.find(
24
+ // @ts-ignore - no need to type
25
+ p => p.imported?.name === 'Mastra',
26
+ )?.local?.name ?? null;
27
+ }
28
+ },
29
+ NewExpression(path) {
30
+ if (mastraClass && (path.node.callee as babel.types.Identifier).name === mastraClass) {
31
+ // @ts-ignore
32
+ const deployer = path.node.arguments[0]?.properties?.find(
33
+ // @ts-ignore
34
+ prop => prop.key.name === 'deployer',
35
+ );
36
+
37
+ const programPath = path.scope.getProgramParent().path;
38
+ if (!deployer || !programPath) {
39
+ return;
40
+ }
41
+
42
+ // add the deployer export
43
+ const exportDeclaration = t.exportNamedDeclaration(
44
+ t.variableDeclaration('const', [t.variableDeclarator(t.identifier('deployer'), deployer.value)]),
45
+ [],
46
+ );
47
+
48
+ // @ts-ignore
49
+ programPath.node.body.push(exportDeclaration);
50
+ }
51
+ },
52
+ },
53
+ } as babel.PluginObj;
54
+ }