@mastra/deployer-cloud 1.54.0-alpha.1 → 1.54.0-alpha.3

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.
package/dist/index.js CHANGED
@@ -1,28 +1,27 @@
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
-
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
- const tokensObject = {};
19
- if (process.env.PLAYGROUND_JWT_TOKEN) {
20
- tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: "business-api", role: "api" };
21
- }
22
- if (process.env.BUSINESS_JWT_TOKEN) {
23
- tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: "business-api", role: "api" };
24
- }
25
- return `
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 `
26
25
  import { SimpleAuth, CompositeAuth } from '@mastra/core/server';
27
26
  import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';
28
27
 
@@ -92,219 +91,210 @@ function getAuthEntrypoint() {
92
91
  }
93
92
  `;
94
93
  }
95
- var LOCAL = process.env.LOCAL === "true";
96
- var TEAM_ID = process.env.TEAM_ID ?? "";
97
- var PROJECT_ID = process.env.PROJECT_ID ?? "";
98
- var BUILD_ID = process.env.BUILD_ID ?? "";
99
- var BUILD_URL = process.env.BUILD_URL ?? "";
100
- var LOG_REDIS_URL = process.env.LOG_REDIS_URL ?? "redis://localhost:6379";
101
- var USER_IP_ADDRESS = process.env.USER_IP_ADDRESS ?? "";
102
- var MASTRA_DIRECTORY = process.env.MASTRA_DIRECTORY ?? "src/mastra";
103
- var PROJECT_ENV_VARS = safelyParseJson(process.env.PROJECT_ENV_VARS ?? "{}");
104
- 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;
105
108
  function safelyParseJson(json) {
106
- try {
107
- return JSON.parse(json);
108
- } catch {
109
- return {};
110
- }
109
+ try {
110
+ return JSON.parse(json);
111
+ } catch {
112
+ return {};
113
+ }
111
114
  }
112
- var redisClient = createClient({
113
- url: LOG_REDIS_URL
114
- });
115
+ //#endregion
116
+ //#region src/utils/logger.ts
117
+ const redisClient = createClient({ url: LOG_REDIS_URL });
115
118
  var RedisTransport = class extends LoggerTransport {
116
- _transform(chunk, _encoding, callback) {
117
- chunk = chunk.toString();
118
- const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
119
- const ttl = 2 * 24 * 60 * 60;
120
- const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
121
- process.nextTick(async () => {
122
- try {
123
- if (!redisClient.isOpen) {
124
- await redisClient.connect().catch((err) => {
125
- console.error("Redis connection error:", err);
126
- });
127
- }
128
- const pipeline = redisClient.multi();
129
- pipeline.rPush(logKey, logData);
130
- pipeline.expire(logKey, ttl);
131
- await pipeline.exec();
132
- } catch (err) {
133
- console.error("Redis logging error:", err);
134
- }
135
- });
136
- callback(null, chunk);
137
- }
138
- _write(chunk, encoding, callback) {
139
- if (typeof callback === "function") {
140
- this._transform(chunk, encoding || "utf8", callback);
141
- return true;
142
- }
143
- this._transform(chunk, encoding || "utf8", (error) => {
144
- if (error) console.error("Transform error in write:", error);
145
- });
146
- return true;
147
- }
148
- async _flush() {
149
- await new Promise((resolve2) => setTimeout(resolve2, 10));
150
- }
151
- async _destroy(err, cb) {
152
- await closeLogger();
153
- cb(err);
154
- }
155
- listLogs(_args) {
156
- return Promise.resolve({
157
- logs: [],
158
- total: 0,
159
- page: _args?.page ?? 1,
160
- perPage: _args?.perPage ?? 100,
161
- hasMore: false
162
- });
163
- }
164
- listLogsByRunId(_args) {
165
- return Promise.resolve({
166
- logs: [],
167
- total: 0,
168
- page: _args?.page ?? 1,
169
- perPage: _args?.perPage ?? 100,
170
- hasMore: false
171
- });
172
- }
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
+ }
173
174
  };
174
- var transport = new RedisTransport();
175
- var closeLogger = async () => {
176
- if (redisClient.isOpen) {
177
- setTimeout(async () => {
178
- await redisClient.quit();
179
- }, 10);
180
- }
175
+ const transport = new RedisTransport();
176
+ const closeLogger = async () => {
177
+ if (redisClient.isOpen) setTimeout(async () => {
178
+ await redisClient.quit();
179
+ }, 10);
181
180
  };
182
- var logger = new PinoLogger({
183
- level: "info",
184
- transports: {
185
- redis: transport
186
- }
181
+ const logger = new PinoLogger({
182
+ level: "info",
183
+ transports: { redis: transport }
187
184
  });
188
-
189
- // src/utils/execa.ts
190
- var createPinoStream = () => {
191
- return new Writable({
192
- write(chunk, _encoding, callback) {
193
- const line = chunk.toString().trim();
194
- if (line) {
195
- logger.info(line);
196
- }
197
- callback();
198
- }
199
- });
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
+ } });
200
193
  };
201
- async function runWithExeca({
202
- cmd,
203
- args,
204
- cwd = process.cwd(),
205
- env = PROJECT_ENV_VARS
206
- }) {
207
- const pinoStream = createPinoStream();
208
- try {
209
- const subprocess = execa(cmd, args, {
210
- cwd,
211
- stdin: "ignore",
212
- env: {
213
- ...process.env,
214
- ...env
215
- }
216
- });
217
- subprocess.stdout?.pipe(pinoStream, { end: false });
218
- subprocess.stderr?.pipe(pinoStream, { end: false });
219
- const { stdout, stderr, exitCode } = await subprocess;
220
- pinoStream.end();
221
- return { stdout, stderr, success: exitCode === 0 };
222
- } catch (error) {
223
- pinoStream.end();
224
- logger.error("Process failed", { error });
225
- return { success: false, error: error instanceof Error ? error : new Error(String(error)) };
226
- }
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
+ }
227
222
  }
228
-
229
- // src/utils/deps.ts
230
- var MEMOIZED = /* @__PURE__ */ new Map();
223
+ //#endregion
224
+ //#region src/utils/deps.ts
225
+ const MEMOIZED = /* @__PURE__ */ new Map();
231
226
  function findLockFile(dir) {
232
- const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
233
- for (const file of lockFiles) {
234
- if (fs.existsSync(join(dir, file))) {
235
- return file;
236
- }
237
- }
238
- const parentDir = resolve(dir, "..");
239
- if (parentDir !== dir) {
240
- return findLockFile(parentDir);
241
- }
242
- 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;
243
236
  }
244
237
  function detectPm({ path }) {
245
- const cached = MEMOIZED.get(path);
246
- if (cached) {
247
- return cached;
248
- }
249
- const lockFile = findLockFile(path);
250
- let pm = "npm";
251
- switch (lockFile) {
252
- case "pnpm-lock.yaml":
253
- pm = "pnpm";
254
- break;
255
- case "package-lock.json":
256
- pm = "npm";
257
- break;
258
- case "yarn.lock":
259
- pm = "yarn";
260
- break;
261
- case "bun.lock":
262
- pm = "bun";
263
- break;
264
- default:
265
- pm = "npm";
266
- }
267
- MEMOIZED.set(path, pm);
268
- 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;
269
259
  }
270
260
  async function installDeps({ path, pm }) {
271
- pm = pm ?? detectPm({ path });
272
- logger.info("Installing dependencies", { pm, path });
273
- const args = ["install", "--legacy-peer-deps=false", "--force"];
274
- const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });
275
- if (!success) {
276
- throw new MastraError(
277
- {
278
- id: "FAIL_INSTALL_DEPS",
279
- category: "USER",
280
- domain: "DEPLOYER"
281
- },
282
- error
283
- );
284
- }
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);
285
280
  }
281
+ //#endregion
282
+ //#region src/utils/file.ts
286
283
  function getMastraEntryFile(mastraDir) {
287
- try {
288
- const fileService = new FileService();
289
- return fileService.getFirstExistingFile([
290
- join(mastraDir, MASTRA_DIRECTORY, "index.ts"),
291
- join(mastraDir, MASTRA_DIRECTORY, "index.js")
292
- ]);
293
- } catch (error) {
294
- throw new MastraError(
295
- {
296
- id: "MASTRA_ENTRY_FILE_NOT_FOUND",
297
- category: "USER",
298
- domain: "DEPLOYER"
299
- },
300
- error
301
- );
302
- }
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
+ }
303
293
  }
304
-
305
- // src/utils/report.ts
294
+ //#endregion
295
+ //#region src/utils/report.ts
306
296
  function successEntrypoint() {
307
- return `
297
+ return `
308
298
  if (process.env.CI !== 'true') {
309
299
  await fetch('${process.env.REPORTER_API_URL}', {
310
300
  method: 'POST',
@@ -313,12 +303,12 @@ function successEntrypoint() {
313
303
  Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',
314
304
  },
315
305
  body: JSON.stringify(${JSON.stringify({
316
- projectId: PROJECT_ID,
317
- buildId: BUILD_ID,
318
- status: "success",
319
- url: BUILD_URL,
320
- userIpAddress: USER_IP_ADDRESS
321
- })}),
306
+ projectId: PROJECT_ID,
307
+ buildId: BUILD_ID,
308
+ status: "success",
309
+ url: BUILD_URL,
310
+ userIpAddress: USER_IP_ADDRESS
311
+ })}),
322
312
  }).catch(err => {
323
313
  console.error('Failed to report build status to monitoring service', {
324
314
  error: err,
@@ -327,69 +317,59 @@ function successEntrypoint() {
327
317
  }
328
318
  `;
329
319
  }
330
-
331
- // src/index.ts
320
+ //#endregion
321
+ //#region src/index.ts
332
322
  var CloudDeployer = class extends Deployer {
333
- studio;
334
- constructor({ studio } = {}) {
335
- super({ name: "cloud" });
336
- this.studio = studio ?? false;
337
- }
338
- async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
339
- const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);
340
- return {
341
- ...bundlerOptions,
342
- externals: true
343
- };
344
- }
345
- async deploy(_outputDirectory) {
346
- }
347
- async prepare(outputDirectory) {
348
- await super.prepare(outputDirectory);
349
- if (this.studio) {
350
- const __filename = fileURLToPath(import.meta.url);
351
- const __dirname = dirname(__filename);
352
- const studioServePath = join(outputDirectory, this.outputDir, "studio");
353
- await copy(join(dirname(__dirname), join("dist", "studio")), studioServePath, {
354
- overwrite: true
355
- });
356
- }
357
- }
358
- async writePackageJson(outputDirectory, dependencies) {
359
- const versions = await readJSON(join(dirname(fileURLToPath(import.meta.url)), "../versions.json"));
360
- for (const [pkgName, version] of Object.entries(versions || {})) {
361
- dependencies.set(pkgName, version);
362
- }
363
- return super.writePackageJson(outputDirectory, dependencies);
364
- }
365
- async lint() {
366
- }
367
- async installDependencies(outputDirectory, _rootDir = process.cwd()) {
368
- await installDeps({ path: join(outputDirectory, "output"), pm: "npm" });
369
- }
370
- async bundle(mastraDir, outputDirectory) {
371
- const currentCwd = process.cwd();
372
- process.chdir(mastraDir);
373
- const mastraEntryFile = getMastraEntryFile(mastraDir);
374
- const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);
375
- const discoveredTools = this.getAllToolPaths(mastraAppDir);
376
- await this.prepare(outputDirectory);
377
- await this._bundle(
378
- this.getEntry(),
379
- mastraEntryFile,
380
- {
381
- outputDirectory,
382
- projectRoot: mastraDir
383
- },
384
- discoveredTools
385
- );
386
- process.chdir(currentCwd);
387
- }
388
- getAuthEntrypoint() {
389
- return getAuthEntrypoint();
390
- }
391
- getEntry() {
392
- 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 `
393
373
  import { createNodeServer, getToolExports } from '#server';
394
374
  import { tools } from '#tools';
395
375
  import { mastra } from '#mastra';
@@ -497,9 +477,9 @@ console.log(JSON.stringify({
497
477
  },
498
478
  }));
499
479
  `;
500
- }
480
+ }
501
481
  };
502
-
482
+ //#endregion
503
483
  export { CloudDeployer };
504
- //# sourceMappingURL=index.js.map
484
+
505
485
  //# sourceMappingURL=index.js.map