@mastra/deployer-cloud 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

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 (47) hide show
  1. package/CHANGELOG.md +3488 -5
  2. package/LICENSE.md +15 -0
  3. package/README.md +2 -3
  4. package/dist/index.cjs +366 -363
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +7 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +340 -336
  9. package/dist/index.js.map +1 -1
  10. package/dist/studio/assets/CommitMono-400-Regular-DzkyLZ26.woff2 +0 -0
  11. package/dist/studio/assets/CommitMono-700-Regular-DmOSN4kd.woff2 +0 -0
  12. package/dist/studio/assets/MonaSans-VariableFont_wdth-wght-CX-7s9jm.ttf +0 -0
  13. package/dist/studio/assets/babel-lWBcy2sH.js +16 -0
  14. package/dist/studio/assets/bash-atvbtKCR.js +1 -0
  15. package/dist/studio/assets/core-uJnW0DDG.js +12 -0
  16. package/dist/studio/assets/engine-compile-BkERmzkH.js +137 -0
  17. package/dist/studio/assets/engine-javascript-CSIo_1eZ.js +1 -0
  18. package/dist/studio/assets/estree-Dd9JfUIE.js +44 -0
  19. package/dist/studio/assets/github-dark-DHJKELXO.js +1 -0
  20. package/dist/studio/assets/github-light-DAi9KRSo.js +1 -0
  21. package/dist/studio/assets/index-BWC9t29j.js +2 -0
  22. package/dist/studio/assets/index-yUiD89B4.js +1 -0
  23. package/dist/studio/assets/javascript-ySlJ1b_l.js +1 -0
  24. package/dist/studio/assets/json-BQoSv7ci.js +1 -0
  25. package/dist/studio/assets/jsx-BAng5TT0.js +1 -0
  26. package/dist/studio/assets/livekit-client.esm-CKIgC2IJ.js +39 -0
  27. package/dist/studio/assets/main-D0m4O3FR.js +768 -0
  28. package/dist/studio/assets/markdown-UIAJJxZW.js +1 -0
  29. package/dist/studio/assets/preload-helper-PPVm8Dsz.js +1 -0
  30. package/dist/studio/assets/python-DhUJRlN_.js +1 -0
  31. package/dist/studio/assets/shell-CjFT_Tl9.js +1 -0
  32. package/dist/studio/assets/standalone-Dfz2oS5J.js +29 -0
  33. package/dist/studio/assets/style-B7CpWlks.css +1 -0
  34. package/dist/studio/assets/tsx-B6W0miNI.js +1 -0
  35. package/dist/studio/assets/typescript-Dj6nwHGl.js +1 -0
  36. package/dist/studio/index.html +100 -0
  37. package/dist/studio/mastra.svg +17 -0
  38. package/dist/studio/routes-manifest.json +27 -0
  39. package/dist/utils/auth.d.ts.map +1 -1
  40. package/dist/utils/deps.d.ts.map +1 -1
  41. package/dist/utils/execa.d.ts +2 -2
  42. package/dist/utils/execa.d.ts.map +1 -1
  43. package/dist/utils/logger.d.ts +4 -4
  44. package/dist/utils/logger.d.ts.map +1 -1
  45. package/package.json +26 -19
  46. package/versions.json +1 -1
  47. package/templates/instrumentation-template.js +0 -69
package/dist/index.js CHANGED
@@ -1,271 +1,300 @@
1
- import { fileURLToPath } from 'url';
2
- import { join, dirname, resolve } from 'path';
3
- import { Deployer, FileService } from '@mastra/deployer';
4
- import { copy, readJSON } from 'fs-extra/esm';
5
- import os from 'os';
6
- import * as fs from 'fs';
7
- import { MastraError } from '@mastra/core/error';
8
- import { Transform } from 'stream';
9
- import { execa } from 'execa';
10
- import { LoggerTransport } from '@mastra/core/logger';
11
- import { PinoLogger } from '@mastra/loggers';
12
- import { createClient } from 'redis';
13
-
14
- // src/index.ts
15
-
16
- // src/utils/auth.ts
1
+ import { dirname, join, resolve } from "path";
2
+ import { fileURLToPath } from "url";
3
+ import { Deployer, FileService } from "@mastra/deployer";
4
+ import { copy, readJSON } from "fs-extra/esm";
5
+ import os from "os";
6
+ import * as fs from "fs";
7
+ import { MastraError } from "@mastra/core/error";
8
+ import { Writable } from "stream";
9
+ import { execa } from "execa";
10
+ import { LoggerTransport } from "@mastra/core/logger";
11
+ import { PinoLogger } from "@mastra/loggers";
12
+ import { createClient } from "redis";
13
+ //#region src/utils/auth.ts
17
14
  function getAuthEntrypoint() {
18
- return `
19
- import { MastraAuthProvider } from '@mastra/core/server';
20
-
21
- class MastraCloudAuth extends MastraAuthProvider {
22
- constructor (auth) {
23
- super()
24
- this.auth = auth
25
- }
15
+ const tokensObject = {};
16
+ if (process.env.PLAYGROUND_JWT_TOKEN) tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = {
17
+ id: "business-api",
18
+ role: "api"
19
+ };
20
+ if (process.env.BUSINESS_JWT_TOKEN) tokensObject[process.env.BUSINESS_JWT_TOKEN] = {
21
+ id: "business-api",
22
+ role: "api"
23
+ };
24
+ return `
25
+ import { SimpleAuth, CompositeAuth } from '@mastra/core/server';
26
+ import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';
26
27
 
27
- async authenticateToken (...args) {
28
- if (typeof args[0] === 'string') {
29
- const token = args[0].replace('Bearer ', '');
30
- const validTokens = [];
31
- ${process.env.PLAYGROUND_JWT_TOKEN ? `validTokens.push('${process.env.PLAYGROUND_JWT_TOKEN}');` : ""}
32
- ${process.env.BUSINESS_JWT_TOKEN ? `validTokens.push('${process.env.BUSINESS_JWT_TOKEN}');` : ""}
33
-
34
- if (validTokens.includes(token)) {
35
- return { id: 'business-api' }
36
- }
37
- }
38
- return this.auth.authenticateToken(...args)
28
+ // Service token auth (for business-api, playground internal calls)
29
+ class MastraCloudServiceAuth extends SimpleAuth {
30
+ constructor() {
31
+ super({
32
+ tokens: ${JSON.stringify(tokensObject)}
33
+ });
39
34
  }
40
35
 
41
- async authorizeUser (...args) {
42
- if (args[1] && args[1].path === '/api') {
43
- return true
36
+ async authorizeUser(user, request) {
37
+ // Allow access to /api path
38
+ if (request && request.url && new URL(request.url).pathname === '/api') {
39
+ return true;
44
40
  }
45
- if (args[0] && args[0].id === 'business-api') {
46
- return true
41
+ // Allow access for business-api users
42
+ if (user && user.id === 'business-api') {
43
+ return true;
47
44
  }
48
- return this.auth.authorizeUser(...args)
45
+ return false;
49
46
  }
50
47
  }
51
48
 
52
- const serverConfig = mastra.getServer()
53
- if (serverConfig && serverConfig.experimental_auth) {
54
- const auth = serverConfig.experimental_auth
55
- serverConfig.experimental_auth = new MastraCloudAuth(auth)
49
+ const serviceAuth = new MastraCloudServiceAuth();
50
+
51
+ // Cloud user auth (for end users via OAuth)
52
+ // Only enabled if MASTRA_CLOUD_API_URL is set
53
+ let cloudUserAuth = null;
54
+ if (process.env.MASTRA_CLOUD_API_URL) {
55
+ cloudUserAuth = new MastraCloudAuthProvider({
56
+ projectId: process.env.PROJECT_ID,
57
+ cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,
58
+ callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \`\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\`,
59
+ });
60
+ }
61
+
62
+ const serverConfig = mastra.getServer();
63
+ const userAuth = serverConfig?.auth;
64
+
65
+ // Only enable auth if cloudUserAuth or userAuth are defined
66
+ if (serverConfig && (cloudUserAuth || userAuth)) {
67
+ // Build provider list: service auth first, then cloud user auth, then user's custom auth
68
+ const providers = [serviceAuth];
69
+ if (cloudUserAuth) {
70
+ providers.push(cloudUserAuth);
71
+ }
72
+ if (userAuth) {
73
+ providers.push(userAuth);
74
+ }
75
+
76
+ serverConfig.auth = new CompositeAuth(providers);
77
+
78
+ // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC
79
+ if (cloudUserAuth && !serverConfig.rbac) {
80
+ serverConfig.rbac = new MastraRBACCloud({
81
+ roleMapping: {
82
+ owner: ['*'],
83
+ admin: ['*:read', '*:write', '*:execute'],
84
+ api: ['*:read', '*:write', '*:execute'],
85
+ member: ['*:read', '*:execute'],
86
+ viewer: ['*:read'],
87
+ _default: [],
88
+ },
89
+ });
90
+ }
56
91
  }
57
92
  `;
58
93
  }
59
- var LOCAL = process.env.LOCAL === "true";
60
- var TEAM_ID = process.env.TEAM_ID ?? "";
61
- var PROJECT_ID = process.env.PROJECT_ID ?? "";
62
- var BUILD_ID = process.env.BUILD_ID ?? "";
63
- var BUILD_URL = process.env.BUILD_URL ?? "";
64
- var LOG_REDIS_URL = process.env.LOG_REDIS_URL ?? "redis://localhost:6379";
65
- var USER_IP_ADDRESS = process.env.USER_IP_ADDRESS ?? "";
66
- var MASTRA_DIRECTORY = process.env.MASTRA_DIRECTORY ?? "src/mastra";
67
- var PROJECT_ENV_VARS = safelyParseJson(process.env.PROJECT_ENV_VARS ?? "{}");
68
- LOCAL ? os.tmpdir() + "/project" : process.env.PROJECT_ROOT ?? "/project";
94
+ //#endregion
95
+ //#region src/utils/constants.ts
96
+ const LOCAL = process.env.LOCAL === "true";
97
+ const TEAM_ID = process.env.TEAM_ID ?? "";
98
+ const PROJECT_ID = process.env.PROJECT_ID ?? "";
99
+ const BUILD_ID = process.env.BUILD_ID ?? "";
100
+ const BUILD_URL = process.env.BUILD_URL ?? "";
101
+ const LOG_REDIS_URL = process.env.LOG_REDIS_URL ?? "redis://localhost:6379";
102
+ process.env.BUSINESS_JWT_TOKEN;
103
+ process.env.PLAYGROUND_JWT_TOKEN;
104
+ const USER_IP_ADDRESS = process.env.USER_IP_ADDRESS ?? "";
105
+ const MASTRA_DIRECTORY = process.env.MASTRA_DIRECTORY ?? "src/mastra";
106
+ const PROJECT_ENV_VARS = safelyParseJson(process.env.PROJECT_ENV_VARS ?? "{}");
107
+ LOCAL ? os.tmpdir() + "" : process.env.PROJECT_ROOT;
69
108
  function safelyParseJson(json) {
70
- try {
71
- return JSON.parse(json);
72
- } catch {
73
- return {};
74
- }
109
+ try {
110
+ return JSON.parse(json);
111
+ } catch {
112
+ return {};
113
+ }
75
114
  }
76
- var redisClient = createClient({
77
- url: LOG_REDIS_URL
78
- });
115
+ //#endregion
116
+ //#region src/utils/logger.ts
117
+ const redisClient = createClient({ url: LOG_REDIS_URL });
79
118
  var RedisTransport = class extends LoggerTransport {
80
- _transform(chunk, _encoding, callback) {
81
- chunk = chunk.toString();
82
- const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
83
- const ttl = 2 * 24 * 60 * 60;
84
- const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
85
- process.nextTick(async () => {
86
- try {
87
- if (!redisClient.isOpen) {
88
- await redisClient.connect().catch((err) => {
89
- console.error("Redis connection error:", err);
90
- });
91
- }
92
- const pipeline = redisClient.multi();
93
- pipeline.rPush(logKey, logData);
94
- pipeline.expire(logKey, ttl);
95
- await pipeline.exec();
96
- } catch (err) {
97
- console.error("Redis logging error:", err);
98
- }
99
- });
100
- callback(null, chunk);
101
- }
102
- _write(chunk, encoding, callback) {
103
- if (typeof callback === "function") {
104
- this._transform(chunk, encoding || "utf8", callback);
105
- return true;
106
- }
107
- this._transform(chunk, encoding || "utf8", (error) => {
108
- if (error) console.error("Transform error in write:", error);
109
- });
110
- return true;
111
- }
112
- async _flush() {
113
- await new Promise((resolve2) => setTimeout(resolve2, 10));
114
- }
115
- async _destroy(err, cb) {
116
- await closeLogger();
117
- cb(err);
118
- }
119
- getLogs(_args) {
120
- return Promise.resolve({
121
- logs: [],
122
- total: 0,
123
- page: _args?.page ?? 1,
124
- perPage: _args?.perPage ?? 100,
125
- hasMore: false
126
- });
127
- }
128
- getLogsByRunId(_args) {
129
- return Promise.resolve({
130
- logs: [],
131
- total: 0,
132
- page: _args?.page ?? 1,
133
- perPage: _args?.perPage ?? 100,
134
- hasMore: false
135
- });
136
- }
119
+ _transform(chunk, _encoding, callback) {
120
+ chunk = chunk.toString();
121
+ const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
122
+ const ttl = 2880 * 60;
123
+ const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
124
+ process.nextTick(async () => {
125
+ try {
126
+ if (!redisClient.isOpen) await redisClient.connect().catch((err) => {
127
+ console.error("Redis connection error:", err);
128
+ });
129
+ const pipeline = redisClient.multi();
130
+ pipeline.rPush(logKey, logData);
131
+ pipeline.expire(logKey, ttl);
132
+ await pipeline.exec();
133
+ } catch (err) {
134
+ console.error("Redis logging error:", err);
135
+ }
136
+ });
137
+ callback(null, chunk);
138
+ }
139
+ _write(chunk, encoding, callback) {
140
+ if (typeof callback === "function") {
141
+ this._transform(chunk, encoding || "utf8", callback);
142
+ return true;
143
+ }
144
+ this._transform(chunk, encoding || "utf8", (error) => {
145
+ if (error) console.error("Transform error in write:", error);
146
+ });
147
+ return true;
148
+ }
149
+ async _flush() {
150
+ await new Promise((resolve) => setTimeout(resolve, 10));
151
+ }
152
+ async _destroy(err, cb) {
153
+ await closeLogger();
154
+ cb(err);
155
+ }
156
+ listLogs(_args) {
157
+ return Promise.resolve({
158
+ logs: [],
159
+ total: 0,
160
+ page: _args?.page ?? 1,
161
+ perPage: _args?.perPage ?? 100,
162
+ hasMore: false
163
+ });
164
+ }
165
+ listLogsByRunId(_args) {
166
+ return Promise.resolve({
167
+ logs: [],
168
+ total: 0,
169
+ page: _args?.page ?? 1,
170
+ perPage: _args?.perPage ?? 100,
171
+ hasMore: false
172
+ });
173
+ }
137
174
  };
138
- var transport = new RedisTransport();
139
- var closeLogger = async () => {
140
- if (redisClient.isOpen) {
141
- setTimeout(async () => {
142
- await redisClient.quit();
143
- }, 10);
144
- }
175
+ const transport = new RedisTransport();
176
+ const closeLogger = async () => {
177
+ if (redisClient.isOpen) setTimeout(async () => {
178
+ await redisClient.quit();
179
+ }, 10);
145
180
  };
146
- var logger = new PinoLogger({
147
- level: "info",
148
- transports: {
149
- redis: transport
150
- }
181
+ const logger = new PinoLogger({
182
+ level: "info",
183
+ transports: { redis: transport }
151
184
  });
152
-
153
- // src/utils/execa.ts
154
- var createPinoStream = () => {
155
- return new Transform({
156
- transform(chunk, encoding, callback) {
157
- const line = chunk.toString().trim();
158
- if (line) {
159
- logger.info(line);
160
- }
161
- callback(null, chunk);
162
- }
163
- });
185
+ //#endregion
186
+ //#region src/utils/execa.ts
187
+ const createPinoStream = () => {
188
+ return new Writable({ write(chunk, _encoding, callback) {
189
+ const line = chunk.toString().trim();
190
+ if (line) logger.info(line);
191
+ callback();
192
+ } });
164
193
  };
165
- async function runWithExeca({
166
- cmd,
167
- args,
168
- cwd = process.cwd(),
169
- env = PROJECT_ENV_VARS
170
- }) {
171
- const pinoStream = createPinoStream();
172
- try {
173
- const subprocess = execa(cmd, args, {
174
- cwd,
175
- env: {
176
- ...process.env,
177
- ...env
178
- }
179
- });
180
- subprocess.stdout?.pipe(pinoStream);
181
- subprocess.stderr?.pipe(pinoStream);
182
- const { stdout, stderr, exitCode } = await subprocess;
183
- return { stdout, stderr, success: exitCode === 0 };
184
- } catch (error) {
185
- logger.error(`Process failed: ${error}`);
186
- return { success: false, error: error instanceof Error ? error : new Error(String(error)) };
187
- }
194
+ async function runWithExeca({ cmd, args, cwd = process.cwd(), env = PROJECT_ENV_VARS }) {
195
+ const pinoStream = createPinoStream();
196
+ try {
197
+ const subprocess = execa(cmd, args, {
198
+ cwd,
199
+ stdin: "ignore",
200
+ env: {
201
+ ...process.env,
202
+ ...env
203
+ }
204
+ });
205
+ subprocess.stdout?.pipe(pinoStream, { end: false });
206
+ subprocess.stderr?.pipe(pinoStream, { end: false });
207
+ const { stdout, stderr, exitCode } = await subprocess;
208
+ pinoStream.end();
209
+ return {
210
+ stdout,
211
+ stderr,
212
+ success: exitCode === 0
213
+ };
214
+ } catch (error) {
215
+ pinoStream.end();
216
+ logger.error("Process failed", { error });
217
+ return {
218
+ success: false,
219
+ error: error instanceof Error ? error : new Error(String(error))
220
+ };
221
+ }
188
222
  }
189
-
190
- // src/utils/deps.ts
191
- var MEMOIZED = /* @__PURE__ */ new Map();
223
+ //#endregion
224
+ //#region src/utils/deps.ts
225
+ const MEMOIZED = /* @__PURE__ */ new Map();
192
226
  function findLockFile(dir) {
193
- const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
194
- for (const file of lockFiles) {
195
- if (fs.existsSync(join(dir, file))) {
196
- return file;
197
- }
198
- }
199
- const parentDir = resolve(dir, "..");
200
- if (parentDir !== dir) {
201
- return findLockFile(parentDir);
202
- }
203
- return null;
227
+ for (const file of [
228
+ "pnpm-lock.yaml",
229
+ "package-lock.json",
230
+ "yarn.lock",
231
+ "bun.lock"
232
+ ]) if (fs.existsSync(join(dir, file))) return file;
233
+ const parentDir = resolve(dir, "..");
234
+ if (parentDir !== dir) return findLockFile(parentDir);
235
+ return null;
204
236
  }
205
237
  function detectPm({ path }) {
206
- const cached = MEMOIZED.get(path);
207
- if (cached) {
208
- return cached;
209
- }
210
- const lockFile = findLockFile(path);
211
- let pm = "npm";
212
- switch (lockFile) {
213
- case "pnpm-lock.yaml":
214
- pm = "pnpm";
215
- break;
216
- case "package-lock.json":
217
- pm = "npm";
218
- break;
219
- case "yarn.lock":
220
- pm = "yarn";
221
- break;
222
- case "bun.lock":
223
- pm = "bun";
224
- break;
225
- default:
226
- pm = "npm";
227
- }
228
- MEMOIZED.set(path, pm);
229
- return pm;
238
+ const cached = MEMOIZED.get(path);
239
+ if (cached) return cached;
240
+ const lockFile = findLockFile(path);
241
+ let pm = "npm";
242
+ switch (lockFile) {
243
+ case "pnpm-lock.yaml":
244
+ pm = "pnpm";
245
+ break;
246
+ case "package-lock.json":
247
+ pm = "npm";
248
+ break;
249
+ case "yarn.lock":
250
+ pm = "yarn";
251
+ break;
252
+ case "bun.lock":
253
+ pm = "bun";
254
+ break;
255
+ default: pm = "npm";
256
+ }
257
+ MEMOIZED.set(path, pm);
258
+ return pm;
230
259
  }
231
260
  async function installDeps({ path, pm }) {
232
- pm = pm ?? detectPm({ path });
233
- logger.info(`Installing dependencies with ${pm} in ${path}`);
234
- const args = ["install"];
235
- const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });
236
- if (!success) {
237
- throw new MastraError(
238
- {
239
- id: "FAIL_INSTALL_DEPS",
240
- category: "USER",
241
- domain: "DEPLOYER"
242
- },
243
- error
244
- );
245
- }
261
+ pm = pm ?? detectPm({ path });
262
+ logger.info("Installing dependencies", {
263
+ pm,
264
+ path
265
+ });
266
+ const { success, error } = await runWithExeca({
267
+ cmd: pm,
268
+ args: [
269
+ "install",
270
+ "--legacy-peer-deps=false",
271
+ "--force"
272
+ ],
273
+ cwd: path
274
+ });
275
+ if (!success) throw new MastraError({
276
+ id: "FAIL_INSTALL_DEPS",
277
+ category: "USER",
278
+ domain: "DEPLOYER"
279
+ }, error);
246
280
  }
281
+ //#endregion
282
+ //#region src/utils/file.ts
247
283
  function getMastraEntryFile(mastraDir) {
248
- try {
249
- const fileService = new FileService();
250
- return fileService.getFirstExistingFile([
251
- join(mastraDir, MASTRA_DIRECTORY, "index.ts"),
252
- join(mastraDir, MASTRA_DIRECTORY, "index.js")
253
- ]);
254
- } catch (error) {
255
- throw new MastraError(
256
- {
257
- id: "MASTRA_ENTRY_FILE_NOT_FOUND",
258
- category: "USER",
259
- domain: "DEPLOYER"
260
- },
261
- error
262
- );
263
- }
284
+ try {
285
+ return new FileService().getFirstExistingFile([join(mastraDir, MASTRA_DIRECTORY, "index.ts"), join(mastraDir, MASTRA_DIRECTORY, "index.js")]);
286
+ } catch (error) {
287
+ throw new MastraError({
288
+ id: "MASTRA_ENTRY_FILE_NOT_FOUND",
289
+ category: "USER",
290
+ domain: "DEPLOYER"
291
+ }, error);
292
+ }
264
293
  }
265
-
266
- // src/utils/report.ts
294
+ //#endregion
295
+ //#region src/utils/report.ts
267
296
  function successEntrypoint() {
268
- return `
297
+ return `
269
298
  if (process.env.CI !== 'true') {
270
299
  await fetch('${process.env.REPORTER_API_URL}', {
271
300
  method: 'POST',
@@ -274,12 +303,12 @@ function successEntrypoint() {
274
303
  Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',
275
304
  },
276
305
  body: JSON.stringify(${JSON.stringify({
277
- projectId: PROJECT_ID,
278
- buildId: BUILD_ID,
279
- status: "success",
280
- url: BUILD_URL,
281
- userIpAddress: USER_IP_ADDRESS
282
- })}),
306
+ projectId: PROJECT_ID,
307
+ buildId: BUILD_ID,
308
+ status: "success",
309
+ url: BUILD_URL,
310
+ userIpAddress: USER_IP_ADDRESS
311
+ })}),
283
312
  }).catch(err => {
284
313
  console.error('Failed to report build status to monitoring service', {
285
314
  error: err,
@@ -288,62 +317,68 @@ function successEntrypoint() {
288
317
  }
289
318
  `;
290
319
  }
291
-
292
- // src/index.ts
320
+ //#endregion
321
+ //#region src/index.ts
293
322
  var CloudDeployer = class extends Deployer {
294
- constructor() {
295
- super({ name: "cloud" });
296
- }
297
- async deploy(_outputDirectory) {
298
- }
299
- async writeInstrumentationFile(outputDirectory) {
300
- const instrumentationFile = join(outputDirectory, "instrumentation.mjs");
301
- const __dirname = dirname(fileURLToPath(import.meta.url));
302
- await copy(join(__dirname, "../templates", "instrumentation-template.js"), instrumentationFile);
303
- }
304
- async writePackageJson(outputDirectory, dependencies) {
305
- const versions = await readJSON(join(dirname(fileURLToPath(import.meta.url)), "../versions.json"));
306
- for (const [pkgName, version] of Object.entries(versions || {})) {
307
- dependencies.set(pkgName, version);
308
- }
309
- return super.writePackageJson(outputDirectory, dependencies);
310
- }
311
- async lint() {
312
- }
313
- async installDependencies(outputDirectory, _rootDir = process.cwd()) {
314
- await installDeps({ path: join(outputDirectory, "output"), pm: "npm" });
315
- }
316
- async bundle(mastraDir, outputDirectory) {
317
- const currentCwd = process.cwd();
318
- process.chdir(mastraDir);
319
- const mastraEntryFile = getMastraEntryFile(mastraDir);
320
- const defaultToolsPath = join(mastraDir, MASTRA_DIRECTORY, "tools");
321
- await this._bundle(
322
- this.getEntry(),
323
- mastraEntryFile,
324
- {
325
- outputDirectory,
326
- projectRoot: mastraDir
327
- },
328
- [defaultToolsPath]
329
- );
330
- process.chdir(currentCwd);
331
- }
332
- getAuthEntrypoint() {
333
- return getAuthEntrypoint();
334
- }
335
- getEntry() {
336
- return `
323
+ studio;
324
+ constructor({ studio } = {}) {
325
+ super({ name: "cloud" });
326
+ this.studio = studio ?? false;
327
+ }
328
+ async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
329
+ return {
330
+ ...await super.getUserBundlerOptions(mastraEntryFile, outputDirectory),
331
+ externals: true
332
+ };
333
+ }
334
+ async deploy(_outputDirectory) {}
335
+ async prepare(outputDirectory) {
336
+ await super.prepare(outputDirectory);
337
+ if (this.studio) {
338
+ const __dirname = dirname(fileURLToPath(import.meta.url));
339
+ const studioServePath = join(outputDirectory, this.outputDir, "studio");
340
+ await copy(join(dirname(__dirname), join("dist", "studio")), studioServePath, { overwrite: true });
341
+ }
342
+ }
343
+ async writePackageJson(outputDirectory, dependencies) {
344
+ const versions = await readJSON(join(dirname(fileURLToPath(import.meta.url)), "../versions.json"));
345
+ for (const [pkgName, version] of Object.entries(versions || {})) dependencies.set(pkgName, version);
346
+ return super.writePackageJson(outputDirectory, dependencies);
347
+ }
348
+ async lint() {}
349
+ async installDependencies(outputDirectory, _rootDir = process.cwd()) {
350
+ await installDeps({
351
+ path: join(outputDirectory, "output"),
352
+ pm: "npm"
353
+ });
354
+ }
355
+ async bundle(mastraDir, outputDirectory) {
356
+ const currentCwd = process.cwd();
357
+ process.chdir(mastraDir);
358
+ const mastraEntryFile = getMastraEntryFile(mastraDir);
359
+ const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);
360
+ const discoveredTools = this.getAllToolPaths(mastraAppDir);
361
+ await this.prepare(outputDirectory);
362
+ await this._bundle(this.getEntry(), mastraEntryFile, {
363
+ outputDirectory,
364
+ projectRoot: mastraDir
365
+ }, discoveredTools);
366
+ process.chdir(currentCwd);
367
+ }
368
+ getAuthEntrypoint() {
369
+ return getAuthEntrypoint();
370
+ }
371
+ getEntry() {
372
+ return `
337
373
  import { createNodeServer, getToolExports } from '#server';
338
374
  import { tools } from '#tools';
339
375
  import { mastra } from '#mastra';
340
376
  import { MultiLogger } from '@mastra/core/logger';
341
377
  import { PinoLogger } from '@mastra/loggers';
342
378
  import { HttpTransport } from '@mastra/loggers/http';
343
- import { evaluate } from '@mastra/core/eval';
344
- import { AvailableHooks, registerHook } from '@mastra/core/hooks';
345
379
  import { LibSQLStore, LibSQLVector } from '@mastra/libsql';
346
- import { scoreTracesWorkflow } from '@mastra/core/scores/scoreTraces';
380
+ import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';
381
+
347
382
  const startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();
348
383
  const createNodeServerStartTime = Date.now();
349
384
 
@@ -382,58 +417,27 @@ const combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]
382
417
 
383
418
  mastra.setLogger({ logger: combinedLogger });
384
419
 
385
- if (mastra?.storage) {
386
- mastra.storage.init()
387
- }
388
-
389
420
  if (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {
390
421
  const { MastraStorage } = await import('@mastra/core/storage');
391
422
  logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)
392
423
  const storage = new LibSQLStore({
424
+ id: 'mastra-cloud-storage-libsql',
393
425
  url: process.env.MASTRA_STORAGE_URL,
394
426
  authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
395
427
  })
396
428
  const vector = new LibSQLVector({
397
- connectionUrl: process.env.MASTRA_STORAGE_URL,
429
+ id: 'mastra-cloud-storage-libsql-vector',
430
+ url: process.env.MASTRA_STORAGE_URL,
398
431
  authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,
399
432
  })
400
433
 
401
434
  await storage.init()
402
435
  mastra?.setStorage(storage)
403
-
404
- mastra?.memory?.setStorage(storage)
405
- mastra?.memory?.setVector(vector)
406
-
407
- registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
408
- evaluate({
409
- agentName,
410
- input,
411
- metric,
412
- output,
413
- runId,
414
- globalRunId: runId,
415
- instructions,
416
- });
417
- });
418
- registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
419
- if (mastra?.storage) {
420
- await mastra.storage.insert({
421
- tableName: MastraStorage.TABLE_EVALS,
422
- record: {
423
- input: traceObject.input,
424
- output: traceObject.output,
425
- result: JSON.stringify(traceObject.result),
426
- agent_name: traceObject.agentName,
427
- metric_name: traceObject.metricName,
428
- instructions: traceObject.instructions,
429
- test_info: null,
430
- global_run_id: traceObject.globalRunId,
431
- run_id: traceObject.runId,
432
- created_at: new Date().toISOString(),
433
- },
434
- });
435
- }
436
- });
436
+ } else {
437
+ const userStorage = mastra?.getStorage();
438
+ if (userStorage && !userStorage.disableInit) {
439
+ userStorage.init();
440
+ }
437
441
  }
438
442
 
439
443
  if (mastra?.getStorage()) {
@@ -442,7 +446,7 @@ if (mastra?.getStorage()) {
442
446
 
443
447
  ${getAuthEntrypoint()}
444
448
 
445
- await createNodeServer(mastra, { playground: false, swaggerUI: false, tools: getToolExports(tools) });
449
+ await createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });
446
450
 
447
451
  ${successEntrypoint()}
448
452
 
@@ -473,9 +477,9 @@ console.log(JSON.stringify({
473
477
  },
474
478
  }));
475
479
  `;
476
- }
480
+ }
477
481
  };
478
-
482
+ //#endregion
479
483
  export { CloudDeployer };
480
- //# sourceMappingURL=index.js.map
484
+
481
485
  //# sourceMappingURL=index.js.map