@mastra/deployer-cloud 1.79.0-alpha.10 → 1.79.0-alpha.12
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.cjs +13 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/studio/assets/{index-BCFAaDwt.js → index-ByPzDdcI.js} +2 -2
- package/dist/studio/assets/{main-CTb6k7kh.js → main-DlUaMwI7.js} +232 -232
- package/dist/studio/index.html +1 -1
- package/package.json +4 -4
- package/versions.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -16,7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
@@ -144,7 +144,7 @@ var RedisTransport = class extends _mastra_core_logger.LoggerTransport {
|
|
|
144
144
|
_transform(chunk, _encoding, callback) {
|
|
145
145
|
chunk = chunk.toString();
|
|
146
146
|
const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
|
|
147
|
-
const ttl =
|
|
147
|
+
const ttl = 172800;
|
|
148
148
|
const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
|
|
149
149
|
process.nextTick(async () => {
|
|
150
150
|
try {
|
|
@@ -259,10 +259,10 @@ function findLockFile(dir) {
|
|
|
259
259
|
if (parentDir !== dir) return findLockFile(parentDir);
|
|
260
260
|
return null;
|
|
261
261
|
}
|
|
262
|
-
function detectPm({ path
|
|
263
|
-
const cached = MEMOIZED.get(path
|
|
262
|
+
function detectPm({ path }) {
|
|
263
|
+
const cached = MEMOIZED.get(path);
|
|
264
264
|
if (cached) return cached;
|
|
265
|
-
const lockFile = findLockFile(path
|
|
265
|
+
const lockFile = findLockFile(path);
|
|
266
266
|
let pm = "npm";
|
|
267
267
|
switch (lockFile) {
|
|
268
268
|
case "pnpm-lock.yaml":
|
|
@@ -279,14 +279,14 @@ function detectPm({ path: path$1 }) {
|
|
|
279
279
|
break;
|
|
280
280
|
default: pm = "npm";
|
|
281
281
|
}
|
|
282
|
-
MEMOIZED.set(path
|
|
282
|
+
MEMOIZED.set(path, pm);
|
|
283
283
|
return pm;
|
|
284
284
|
}
|
|
285
|
-
async function installDeps({ path
|
|
286
|
-
pm = pm ?? detectPm({ path
|
|
285
|
+
async function installDeps({ path, pm }) {
|
|
286
|
+
pm = pm ?? detectPm({ path });
|
|
287
287
|
logger.info("Installing dependencies", {
|
|
288
288
|
pm,
|
|
289
|
-
path
|
|
289
|
+
path
|
|
290
290
|
});
|
|
291
291
|
const { success, error } = await runWithExeca({
|
|
292
292
|
cmd: pm,
|
|
@@ -295,7 +295,7 @@ async function installDeps({ path: path$3, pm }) {
|
|
|
295
295
|
"--legacy-peer-deps=false",
|
|
296
296
|
"--force"
|
|
297
297
|
],
|
|
298
|
-
cwd: path
|
|
298
|
+
cwd: path
|
|
299
299
|
});
|
|
300
300
|
if (!success) throw new _mastra_core_error.MastraError({
|
|
301
301
|
id: "FAIL_INSTALL_DEPS",
|
|
@@ -360,9 +360,10 @@ var CloudDeployer = class extends _mastra_deployer.Deployer {
|
|
|
360
360
|
async prepare(outputDirectory) {
|
|
361
361
|
await super.prepare(outputDirectory);
|
|
362
362
|
if (this.studio) {
|
|
363
|
-
const
|
|
363
|
+
const __filename$1 = (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
|
|
364
|
+
const __dirname$1 = (0, path.dirname)(__filename$1);
|
|
364
365
|
const studioServePath = (0, path.join)(outputDirectory, this.outputDir, "studio");
|
|
365
|
-
await (0, fs_extra_esm.copy)((0, path.join)((0, path.dirname)(__dirname), (0, path.join)("dist", "studio")), studioServePath, { overwrite: true });
|
|
366
|
+
await (0, fs_extra_esm.copy)((0, path.join)((0, path.dirname)(__dirname$1), (0, path.join)("dist", "studio")), studioServePath, { overwrite: true });
|
|
366
367
|
}
|
|
367
368
|
}
|
|
368
369
|
async writePackageJson(outputDirectory, dependencies) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["LoggerTransport","PinoLogger","Writable","path","MastraError","FileService","MastraError","Deployer"],"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"sourcesContent":["export function getAuthEntrypoint() {\n const tokensObject: Record<string, { id: string; role: string }> = {};\n\n if (process.env.PLAYGROUND_JWT_TOKEN) {\n tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n if (process.env.BUSINESS_JWT_TOKEN) {\n tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n\n return `\n import { SimpleAuth, CompositeAuth } from '@mastra/core/server';\n import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';\n\n // Service token auth (for business-api, playground internal calls)\n class MastraCloudServiceAuth extends SimpleAuth {\n constructor() {\n super({\n tokens: ${JSON.stringify(tokensObject)}\n });\n }\n\n async authorizeUser(user, request) {\n // Allow access to /api path\n if (request && request.url && new URL(request.url).pathname === '/api') {\n return true;\n }\n // Allow access for business-api users\n if (user && user.id === 'business-api') {\n return true;\n }\n return false;\n }\n }\n\n const serviceAuth = new MastraCloudServiceAuth();\n\n // Cloud user auth (for end users via OAuth)\n // Only enabled if MASTRA_CLOUD_API_URL is set\n let cloudUserAuth = null;\n if (process.env.MASTRA_CLOUD_API_URL) {\n cloudUserAuth = new MastraCloudAuthProvider({\n projectId: process.env.PROJECT_ID,\n cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,\n callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \\`\\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\\`,\n });\n }\n\n const serverConfig = mastra.getServer();\n const userAuth = serverConfig?.auth;\n\n // Only enable auth if cloudUserAuth or userAuth are defined\n if (serverConfig && (cloudUserAuth || userAuth)) {\n // Build provider list: service auth first, then cloud user auth, then user's custom auth\n const providers = [serviceAuth];\n if (cloudUserAuth) {\n providers.push(cloudUserAuth);\n }\n if (userAuth) {\n providers.push(userAuth);\n }\n\n serverConfig.auth = new CompositeAuth(providers);\n\n // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC\n if (cloudUserAuth && !serverConfig.rbac) {\n serverConfig.rbac = new MastraRBACCloud({\n roleMapping: {\n owner: ['*'],\n admin: ['*:read', '*:write', '*:execute'],\n api: ['*:read', '*:write', '*:execute'],\n member: ['*:read', '*:execute'],\n viewer: ['*:read'],\n _default: [],\n },\n });\n }\n }\n `;\n}\n","import os from 'node:os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const PLAYGROUND_JWT_TOKEN: string = process.env.PLAYGROUND_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'node:stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n listLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n listLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { createRequire } from 'node:module';\nimport { Writable } from 'node:stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n stdin: 'ignore',\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n const { stdout, stderr, exitCode } = await subprocess;\n pinoStream.end();\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n pinoStream.end();\n logger.error('Process failed', { error });\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const __require = typeof require === 'function' ? require : createRequire(import.meta.url);\n const { stdout, stderr } = __require('node:child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info('Installing dependencies', { pm, path });\n // --force is needed to install peer deps for external packages in the mastra output directory\n // --legacy-peer-deps=false is needed to override other overrides by the repo package manager such as pnpm. Pnpm would set it to true\n const args = ['install', '--legacy-peer-deps=false', '--force'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info('Running install command', { command: installCommand, path });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info('Running script', { script: scriptName, pm });\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info('Running build command', { command });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'node:path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true') {\n await fetch('${process.env.REPORTER_API_URL}', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport { Deployer } from '@mastra/deployer';\nimport { copy, readJSON } from 'fs-extra/esm';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n private studio: boolean;\n\n constructor({ studio }: { studio?: boolean } = {}) {\n super({ name: 'cloud' });\n this.studio = studio ?? false;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Always force externals: true for cloud deployments.\n // The cloud deployer installs all dependencies from npm into node_modules,\n // so bundling them inline serves no purpose. Bundling inline can also cause\n // circular module evaluation deadlocks when dynamic imports (e.g. in\n // MemoryLibSQL.init()) reference chunks that depend back on the entry module,\n // resulting in \"Detected unsettled top-level await\" warnings.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n await copy(join(dirname(__dirname), join('dist', 'studio')), studioServePath, {\n overwrite: true,\n });\n }\n }\n async writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n const versions = (await readJSON(join(dirname(fileURLToPath(import.meta.url)), '../versions.json'))) as\n | Record<string, string>\n | undefined;\n for (const [pkgName, version] of Object.entries(versions || {})) {\n dependencies.set(pkgName, version);\n }\n\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);\n\n // Use the getAllToolPaths method to prepare tools paths\n const discoveredTools = this.getAllToolPaths(mastraAppDir);\n\n await this.prepare(outputDirectory);\n await this._bundle(\n this.getEntry(),\n mastraEntryFile,\n {\n outputDirectory,\n projectRoot: mastraDir,\n },\n discoveredTools,\n );\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n id: 'mastra-cloud-storage-libsql',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n id: 'mastra-cloud-storage-libsql-vector',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n} else {\n const userStorage = mastra?.getStorage();\n if (userStorage && !userStorage.disableInit) {\n userStorage.init();\n }\n}\n\nif (mastra?.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n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YAAY,CAAC,CAAC,GAC5D,aAAa,IAAI,SAAS,OAAO;EAGnC,OAAO,MAAM,iBAAiB,iBAAiB,YAAY;CAC7D;CAEA,MAAM,OAAO,CAAC;CAEd,MAAgB,oBAAoB,iBAAyB,WAAW,QAAQ,IAAI,GAAG;EACrF,MAAM,YAAY;GAAE,OAAA,GAAA,KAAA,KAAA,CAAW,iBAAiB,QAAQ;GAAG,IAAI;EAAM,CAAC;CACxE;CAEA,MAAM,OAAO,WAAmB,iBAAwC;EACtE,MAAM,aAAa,QAAQ,IAAI;EAC/B,QAAQ,MAAM,SAAS;EAEvB,MAAM,kBAAkB,mBAAmB,SAAS;EAEpD,MAAM,gBAAA,GAAA,KAAA,KAAA,CAAoB,WAAW,gBAAgB;EAGrD,MAAM,kBAAkB,KAAK,gBAAgB,YAAY;EAEzD,MAAM,KAAK,QAAQ,eAAe;EAClC,MAAM,KAAK,QACT,KAAK,SAAS,GACd,iBACA;GACE;GACA,aAAa;EACf,GACA,eACF;EACA,QAAQ,MAAM,UAAU;CAC1B;CAEA,oBAAoB;EAClB,OAAO,kBAAkB;CAC3B;CAEA,WAA2B;EACzB,OAAO;;;;;;;;;;;;;;;;;;;;eAoBI,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqDvB,kBAAkB,EAAE;;2CAEqB,KAAK,OAAO;;EAErD,kBAAkB,EAAE;;;;;;;;;;eAUP,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;;;;;;;;eAWV,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;CAIvB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createClient","LoggerTransport","PinoLogger","Writable","join","resolve","MastraError","FileService","join","MastraError","Deployer","__filename","fileURLToPath","__dirname","dirname","join","copy","readJSON"],"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"sourcesContent":["export function getAuthEntrypoint() {\n const tokensObject: Record<string, { id: string; role: string }> = {};\n\n if (process.env.PLAYGROUND_JWT_TOKEN) {\n tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n if (process.env.BUSINESS_JWT_TOKEN) {\n tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n\n return `\n import { SimpleAuth, CompositeAuth } from '@mastra/core/server';\n import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';\n\n // Service token auth (for business-api, playground internal calls)\n class MastraCloudServiceAuth extends SimpleAuth {\n constructor() {\n super({\n tokens: ${JSON.stringify(tokensObject)}\n });\n }\n\n async authorizeUser(user, request) {\n // Allow access to /api path\n if (request && request.url && new URL(request.url).pathname === '/api') {\n return true;\n }\n // Allow access for business-api users\n if (user && user.id === 'business-api') {\n return true;\n }\n return false;\n }\n }\n\n const serviceAuth = new MastraCloudServiceAuth();\n\n // Cloud user auth (for end users via OAuth)\n // Only enabled if MASTRA_CLOUD_API_URL is set\n let cloudUserAuth = null;\n if (process.env.MASTRA_CLOUD_API_URL) {\n cloudUserAuth = new MastraCloudAuthProvider({\n projectId: process.env.PROJECT_ID,\n cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,\n callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \\`\\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\\`,\n });\n }\n\n const serverConfig = mastra.getServer();\n const userAuth = serverConfig?.auth;\n\n // Only enable auth if cloudUserAuth or userAuth are defined\n if (serverConfig && (cloudUserAuth || userAuth)) {\n // Build provider list: service auth first, then cloud user auth, then user's custom auth\n const providers = [serviceAuth];\n if (cloudUserAuth) {\n providers.push(cloudUserAuth);\n }\n if (userAuth) {\n providers.push(userAuth);\n }\n\n serverConfig.auth = new CompositeAuth(providers);\n\n // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC\n if (cloudUserAuth && !serverConfig.rbac) {\n serverConfig.rbac = new MastraRBACCloud({\n roleMapping: {\n owner: ['*'],\n admin: ['*:read', '*:write', '*:execute'],\n api: ['*:read', '*:write', '*:execute'],\n member: ['*:read', '*:execute'],\n viewer: ['*:read'],\n _default: [],\n },\n });\n }\n }\n `;\n}\n","import os from 'node:os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const PLAYGROUND_JWT_TOKEN: string = process.env.PLAYGROUND_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'node:stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n listLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n listLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { createRequire } from 'node:module';\nimport { Writable } from 'node:stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n stdin: 'ignore',\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n const { stdout, stderr, exitCode } = await subprocess;\n pinoStream.end();\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n pinoStream.end();\n logger.error('Process failed', { error });\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const __require = typeof require === 'function' ? require : createRequire(import.meta.url);\n const { stdout, stderr } = __require('node:child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info('Installing dependencies', { pm, path });\n // --force is needed to install peer deps for external packages in the mastra output directory\n // --legacy-peer-deps=false is needed to override other overrides by the repo package manager such as pnpm. Pnpm would set it to true\n const args = ['install', '--legacy-peer-deps=false', '--force'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info('Running install command', { command: installCommand, path });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info('Running script', { script: scriptName, pm });\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info('Running build command', { command });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'node:path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true') {\n await fetch('${process.env.REPORTER_API_URL}', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport { Deployer } from '@mastra/deployer';\nimport { copy, readJSON } from 'fs-extra/esm';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n private studio: boolean;\n\n constructor({ studio }: { studio?: boolean } = {}) {\n super({ name: 'cloud' });\n this.studio = studio ?? false;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Always force externals: true for cloud deployments.\n // The cloud deployer installs all dependencies from npm into node_modules,\n // so bundling them inline serves no purpose. Bundling inline can also cause\n // circular module evaluation deadlocks when dynamic imports (e.g. in\n // MemoryLibSQL.init()) reference chunks that depend back on the entry module,\n // resulting in \"Detected unsettled top-level await\" warnings.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n await copy(join(dirname(__dirname), join('dist', 'studio')), studioServePath, {\n overwrite: true,\n });\n }\n }\n async writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n const versions = (await readJSON(join(dirname(fileURLToPath(import.meta.url)), '../versions.json'))) as\n | Record<string, string>\n | undefined;\n for (const [pkgName, version] of Object.entries(versions || {})) {\n dependencies.set(pkgName, version);\n }\n\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);\n\n // Use the getAllToolPaths method to prepare tools paths\n const discoveredTools = this.getAllToolPaths(mastraAppDir);\n\n await this.prepare(outputDirectory);\n await this._bundle(\n this.getEntry(),\n mastraEntryFile,\n {\n outputDirectory,\n projectRoot: mastraDir,\n },\n discoveredTools,\n );\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n id: 'mastra-cloud-storage-libsql',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n id: 'mastra-cloud-storage-libsql-vector',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n} else {\n const userStorage = mastra?.getStorage();\n if (userStorage && !userStorage.disableInit) {\n userStorage.init();\n }\n}\n\nif (mastra?.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAgB,oBAAoB;CAClC,MAAM,eAA6D,CAAC;CAEpE,IAAI,QAAQ,IAAI,sBACd,aAAa,QAAQ,IAAI,wBAAwB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAErF,IAAI,QAAQ,IAAI,oBACd,aAAa,QAAQ,IAAI,sBAAsB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAGnF,OAAO;;;;;;;;kBAQS,KAAK,UAAU,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6D/C;;;AC7EA,MAAa,QAAQ,QAAQ,IAAI,UAAU;AAC3C,MAAa,UAAkB,QAAQ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W,gBAAgB;EAGrD,MAAM,kBAAkB,KAAK,gBAAgB,YAAY;EAEzD,MAAM,KAAK,QAAQ,eAAe;EAClC,MAAM,KAAK,QACT,KAAK,SAAS,GACd,iBACA;GACE;GACA,aAAa;EACf,GACA,eACF;EACA,QAAQ,MAAM,UAAU;CAC1B;CAEA,oBAAoB;EAClB,OAAO,kBAAkB;CAC3B;CAEA,WAA2B;EACzB,OAAO;;;;;;;;;;;;;;;;;;;;eAoBI,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqDvB,kBAAkB,EAAE;;2CAEqB,KAAK,OAAO;;EAErD,kBAAkB,EAAE;;;;;;;;;;eAUP,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;;;;;;;;eAWV,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;CAIvB;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -119,7 +119,7 @@ var RedisTransport = class extends LoggerTransport {
|
|
|
119
119
|
_transform(chunk, _encoding, callback) {
|
|
120
120
|
chunk = chunk.toString();
|
|
121
121
|
const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;
|
|
122
|
-
const ttl =
|
|
122
|
+
const ttl = 172800;
|
|
123
123
|
const logData = typeof chunk === "string" ? chunk : JSON.stringify(chunk);
|
|
124
124
|
process.nextTick(async () => {
|
|
125
125
|
try {
|
|
@@ -335,7 +335,8 @@ var CloudDeployer = class extends Deployer {
|
|
|
335
335
|
async prepare(outputDirectory) {
|
|
336
336
|
await super.prepare(outputDirectory);
|
|
337
337
|
if (this.studio) {
|
|
338
|
-
const
|
|
338
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
339
|
+
const __dirname = dirname(__filename);
|
|
339
340
|
const studioServePath = join(outputDirectory, this.outputDir, "studio");
|
|
340
341
|
await copy(join(dirname(__dirname), join("dist", "studio")), studioServePath, { overwrite: true });
|
|
341
342
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"sourcesContent":["export function getAuthEntrypoint() {\n const tokensObject: Record<string, { id: string; role: string }> = {};\n\n if (process.env.PLAYGROUND_JWT_TOKEN) {\n tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n if (process.env.BUSINESS_JWT_TOKEN) {\n tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n\n return `\n import { SimpleAuth, CompositeAuth } from '@mastra/core/server';\n import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';\n\n // Service token auth (for business-api, playground internal calls)\n class MastraCloudServiceAuth extends SimpleAuth {\n constructor() {\n super({\n tokens: ${JSON.stringify(tokensObject)}\n });\n }\n\n async authorizeUser(user, request) {\n // Allow access to /api path\n if (request && request.url && new URL(request.url).pathname === '/api') {\n return true;\n }\n // Allow access for business-api users\n if (user && user.id === 'business-api') {\n return true;\n }\n return false;\n }\n }\n\n const serviceAuth = new MastraCloudServiceAuth();\n\n // Cloud user auth (for end users via OAuth)\n // Only enabled if MASTRA_CLOUD_API_URL is set\n let cloudUserAuth = null;\n if (process.env.MASTRA_CLOUD_API_URL) {\n cloudUserAuth = new MastraCloudAuthProvider({\n projectId: process.env.PROJECT_ID,\n cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,\n callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \\`\\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\\`,\n });\n }\n\n const serverConfig = mastra.getServer();\n const userAuth = serverConfig?.auth;\n\n // Only enable auth if cloudUserAuth or userAuth are defined\n if (serverConfig && (cloudUserAuth || userAuth)) {\n // Build provider list: service auth first, then cloud user auth, then user's custom auth\n const providers = [serviceAuth];\n if (cloudUserAuth) {\n providers.push(cloudUserAuth);\n }\n if (userAuth) {\n providers.push(userAuth);\n }\n\n serverConfig.auth = new CompositeAuth(providers);\n\n // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC\n if (cloudUserAuth && !serverConfig.rbac) {\n serverConfig.rbac = new MastraRBACCloud({\n roleMapping: {\n owner: ['*'],\n admin: ['*:read', '*:write', '*:execute'],\n api: ['*:read', '*:write', '*:execute'],\n member: ['*:read', '*:execute'],\n viewer: ['*:read'],\n _default: [],\n },\n });\n }\n }\n `;\n}\n","import os from 'node:os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const PLAYGROUND_JWT_TOKEN: string = process.env.PLAYGROUND_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'node:stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n listLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n listLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { createRequire } from 'node:module';\nimport { Writable } from 'node:stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n stdin: 'ignore',\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n const { stdout, stderr, exitCode } = await subprocess;\n pinoStream.end();\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n pinoStream.end();\n logger.error('Process failed', { error });\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const __require = typeof require === 'function' ? require : createRequire(import.meta.url);\n const { stdout, stderr } = __require('node:child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info('Installing dependencies', { pm, path });\n // --force is needed to install peer deps for external packages in the mastra output directory\n // --legacy-peer-deps=false is needed to override other overrides by the repo package manager such as pnpm. Pnpm would set it to true\n const args = ['install', '--legacy-peer-deps=false', '--force'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info('Running install command', { command: installCommand, path });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info('Running script', { script: scriptName, pm });\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info('Running build command', { command });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'node:path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true') {\n await fetch('${process.env.REPORTER_API_URL}', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport { Deployer } from '@mastra/deployer';\nimport { copy, readJSON } from 'fs-extra/esm';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n private studio: boolean;\n\n constructor({ studio }: { studio?: boolean } = {}) {\n super({ name: 'cloud' });\n this.studio = studio ?? false;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Always force externals: true for cloud deployments.\n // The cloud deployer installs all dependencies from npm into node_modules,\n // so bundling them inline serves no purpose. Bundling inline can also cause\n // circular module evaluation deadlocks when dynamic imports (e.g. in\n // MemoryLibSQL.init()) reference chunks that depend back on the entry module,\n // resulting in \"Detected unsettled top-level await\" warnings.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n await copy(join(dirname(__dirname), join('dist', 'studio')), studioServePath, {\n overwrite: true,\n });\n }\n }\n async writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n const versions = (await readJSON(join(dirname(fileURLToPath(import.meta.url)), '../versions.json'))) as\n | Record<string, string>\n | undefined;\n for (const [pkgName, version] of Object.entries(versions || {})) {\n dependencies.set(pkgName, version);\n }\n\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);\n\n // Use the getAllToolPaths method to prepare tools paths\n const discoveredTools = this.getAllToolPaths(mastraAppDir);\n\n await this.prepare(outputDirectory);\n await this._bundle(\n this.getEntry(),\n mastraEntryFile,\n {\n outputDirectory,\n projectRoot: mastraDir,\n },\n discoveredTools,\n );\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n id: 'mastra-cloud-storage-libsql',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n id: 'mastra-cloud-storage-libsql-vector',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n} else {\n const userStorage = mastra?.getStorage();\n if (userStorage && !userStorage.disableInit) {\n userStorage.init();\n }\n}\n\nif (mastra?.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAgB,oBAAoB;CAClC,MAAM,eAA6D,CAAC;CAEpE,IAAI,QAAQ,IAAI,sBACd,aAAa,QAAQ,IAAI,wBAAwB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAErF,IAAI,QAAQ,IAAI,oBACd,aAAa,QAAQ,IAAI,sBAAsB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAGnF,OAAO;;;;;;;;kBAQS,KAAK,UAAU,YAAY,EAAE;;;;;;;;;;;;;;;;;;;;;;;;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L,WAAW;gBACb,SAAS;;;;;;;;;;;eAWV,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;CAIvB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/utils/auth.ts","../src/utils/constants.ts","../src/utils/logger.ts","../src/utils/execa.ts","../src/utils/deps.ts","../src/utils/file.ts","../src/utils/report.ts","../src/index.ts"],"sourcesContent":["export function getAuthEntrypoint() {\n const tokensObject: Record<string, { id: string; role: string }> = {};\n\n if (process.env.PLAYGROUND_JWT_TOKEN) {\n tokensObject[process.env.PLAYGROUND_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n if (process.env.BUSINESS_JWT_TOKEN) {\n tokensObject[process.env.BUSINESS_JWT_TOKEN] = { id: 'business-api', role: 'api' };\n }\n\n return `\n import { SimpleAuth, CompositeAuth } from '@mastra/core/server';\n import { MastraCloudAuthProvider, MastraRBACCloud } from '@mastra/auth-cloud';\n\n // Service token auth (for business-api, playground internal calls)\n class MastraCloudServiceAuth extends SimpleAuth {\n constructor() {\n super({\n tokens: ${JSON.stringify(tokensObject)}\n });\n }\n\n async authorizeUser(user, request) {\n // Allow access to /api path\n if (request && request.url && new URL(request.url).pathname === '/api') {\n return true;\n }\n // Allow access for business-api users\n if (user && user.id === 'business-api') {\n return true;\n }\n return false;\n }\n }\n\n const serviceAuth = new MastraCloudServiceAuth();\n\n // Cloud user auth (for end users via OAuth)\n // Only enabled if MASTRA_CLOUD_API_URL is set\n let cloudUserAuth = null;\n if (process.env.MASTRA_CLOUD_API_URL) {\n cloudUserAuth = new MastraCloudAuthProvider({\n projectId: process.env.PROJECT_ID,\n cloudBaseUrl: process.env.MASTRA_CLOUD_API_URL,\n callbackUrl: process.env.MASTRA_CLOUD_CALLBACK_URL || \\`\\${process.env.MASTRA_CLOUD_API_URL}/auth/callback\\`,\n });\n }\n\n const serverConfig = mastra.getServer();\n const userAuth = serverConfig?.auth;\n\n // Only enable auth if cloudUserAuth or userAuth are defined\n if (serverConfig && (cloudUserAuth || userAuth)) {\n // Build provider list: service auth first, then cloud user auth, then user's custom auth\n const providers = [serviceAuth];\n if (cloudUserAuth) {\n providers.push(cloudUserAuth);\n }\n if (userAuth) {\n providers.push(userAuth);\n }\n\n serverConfig.auth = new CompositeAuth(providers);\n\n // If cloud auth is enabled but no RBAC is configured, add default cloud RBAC\n if (cloudUserAuth && !serverConfig.rbac) {\n serverConfig.rbac = new MastraRBACCloud({\n roleMapping: {\n owner: ['*'],\n admin: ['*:read', '*:write', '*:execute'],\n api: ['*:read', '*:write', '*:execute'],\n member: ['*:read', '*:execute'],\n viewer: ['*:read'],\n _default: [],\n },\n });\n }\n }\n `;\n}\n","import os from 'node:os';\n\nexport const LOCAL = process.env.LOCAL === 'true';\nexport const TEAM_ID: string = process.env.TEAM_ID ?? '';\nexport const PROJECT_ID: string = process.env.PROJECT_ID ?? '';\nexport const BUILD_ID: string = process.env.BUILD_ID ?? '';\nexport const BUILD_URL: string = process.env.BUILD_URL ?? '';\nexport const LOG_REDIS_URL: string = process.env.LOG_REDIS_URL ?? 'redis://localhost:6379';\nexport const BUSINESS_JWT_TOKEN: string = process.env.BUSINESS_JWT_TOKEN ?? '';\nexport const PLAYGROUND_JWT_TOKEN: string = process.env.PLAYGROUND_JWT_TOKEN ?? '';\nexport const USER_IP_ADDRESS: string = process.env.USER_IP_ADDRESS ?? '';\nexport const MASTRA_DIRECTORY: string = process.env.MASTRA_DIRECTORY ?? 'src/mastra';\nexport const PROJECT_ENV_VARS: Record<string, string> = safelyParseJson(process.env.PROJECT_ENV_VARS ?? '{}');\n\nexport const PROJECT_ROOT = LOCAL ? os.tmpdir() + '/project' : (process.env.PROJECT_ROOT ?? '/project');\n\nexport function safelyParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch {\n return {};\n }\n}\n","import type { TransformCallback } from 'node:stream';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { createClient } from 'redis';\nimport { BUILD_ID, LOG_REDIS_URL, PROJECT_ID, TEAM_ID } from './constants.js';\n\nconst redisClient = createClient({\n url: LOG_REDIS_URL,\n});\n\nclass RedisTransport extends LoggerTransport {\n _transform(chunk: any, _encoding: string, callback: TransformCallback): void {\n chunk = chunk.toString();\n const logKey = `builder:logs:${TEAM_ID}:${PROJECT_ID}:${BUILD_ID}`;\n const ttl = 2 * 24 * 60 * 60; // 2 days in seconds\n const logData = typeof chunk === 'string' ? chunk : JSON.stringify(chunk);\n\n // Don't block the event loop - process logs asynchronously\n process.nextTick(async () => {\n try {\n // Connect to Redis if not already connected\n if (!redisClient.isOpen) {\n await redisClient.connect().catch(err => {\n console.error('Redis connection error:', err);\n });\n }\n\n // Use pipeline to batch Redis operations\n const pipeline = redisClient.multi();\n pipeline.rPush(logKey, logData);\n pipeline.expire(logKey, ttl);\n await pipeline.exec();\n } catch (err) {\n console.error('Redis logging error:', err);\n }\n });\n\n // Immediately pass through the chunk without waiting\n callback(null, chunk);\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null | undefined) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n async _flush(): Promise<void> {\n // // Ensure the pipeline is closed and flushed\n // redisClient.quit().catch(err => {\n // console.error('Redis connection error:', err);\n // });\n // callback();\n await new Promise(resolve => setTimeout(resolve, 10));\n }\n\n async _destroy(err: Error, cb: Function) {\n await closeLogger();\n cb(err);\n }\n\n listLogs(_args: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{ logs: BaseLogMessage[]; total: number; page: number; perPage: number; hasMore: boolean }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n\n listLogsByRunId(_args?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n return Promise.resolve({\n logs: [],\n total: 0,\n page: _args?.page ?? 1,\n perPage: _args?.perPage ?? 100,\n hasMore: false,\n });\n }\n}\n\nexport const transport = new RedisTransport();\n\nexport const closeLogger = async () => {\n if (redisClient.isOpen) {\n setTimeout(async () => {\n await redisClient.quit();\n }, 10);\n }\n};\n\nexport const logger = new PinoLogger({\n level: 'info',\n transports: {\n redis: transport,\n },\n});\n","import { createRequire } from 'node:module';\nimport { Writable } from 'node:stream';\nimport { execa } from 'execa';\nimport { PROJECT_ENV_VARS, PROJECT_ROOT } from './constants.js';\nimport { logger } from './logger.js';\n\nexport const createPinoStream = () => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\nexport async function runWithExeca({\n cmd,\n args,\n cwd = process.cwd(),\n env = PROJECT_ENV_VARS,\n}: {\n cmd: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n}): Promise<{ stdout?: string; stderr?: string; success: boolean; error?: Error }> {\n const pinoStream = createPinoStream();\n\n try {\n const subprocess = execa(cmd, args, {\n cwd,\n stdin: 'ignore',\n env: {\n ...process.env,\n ...env,\n },\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n const { stdout, stderr, exitCode } = await subprocess;\n pinoStream.end();\n return { stdout, stderr, success: exitCode === 0 };\n } catch (error) {\n pinoStream.end();\n logger.error('Process failed', { error });\n return { success: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\nexport function runWithChildProcess(cmd: string, args: string[]): { stdout?: string; stderr?: string } {\n const pinoStream = createPinoStream();\n\n try {\n const __require = typeof require === 'function' ? require : createRequire(import.meta.url);\n const { stdout, stderr } = __require('node:child_process').spawnSync(cmd, args, {\n cwd: PROJECT_ROOT,\n encoding: 'utf8',\n shell: true,\n env: {\n ...process.env,\n ...PROJECT_ENV_VARS,\n },\n maxBuffer: 1024 * 1024 * 10, // 10MB buffer\n });\n\n if (stdout) {\n pinoStream.write(stdout);\n }\n if (stderr) {\n pinoStream.write(stderr);\n }\n\n pinoStream.end();\n return { stdout, stderr };\n } catch (error) {\n logger.error('Process failed' + error);\n pinoStream.end();\n return {};\n }\n}\n","import * as fs from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { MastraError } from '@mastra/core/error';\nimport { runWithExeca } from './execa.js';\nimport { logger } from './logger.js';\n\nconst MEMOIZED = new Map();\n\nfunction findLockFile(dir: string): string | null {\n const lockFiles = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];\n for (const file of lockFiles) {\n if (fs.existsSync(join(dir, file))) {\n return file;\n }\n }\n const parentDir = resolve(dir, '..');\n if (parentDir !== dir) {\n return findLockFile(parentDir);\n }\n return null;\n}\n\nexport function detectPm({ path }: { path: string }): string {\n const cached = MEMOIZED.get(path);\n if (cached) {\n return cached;\n }\n\n const lockFile = findLockFile(path);\n let pm: string = 'npm';\n switch (lockFile) {\n case 'pnpm-lock.yaml':\n pm = 'pnpm';\n break;\n case 'package-lock.json':\n pm = 'npm';\n break;\n case 'yarn.lock':\n pm = 'yarn';\n break;\n case 'bun.lock':\n pm = 'bun';\n break;\n default:\n pm = 'npm';\n }\n\n MEMOIZED.set(path, pm);\n return pm;\n}\n\nexport async function installNodeVersion({ path }: { path: string }) {\n let nvmrcExists = false;\n let nodeVersionExists = false;\n\n try {\n fs.accessSync(join(path, '.nvmrc'));\n nvmrcExists = true;\n } catch {\n // File does not exist\n }\n\n try {\n fs.accessSync(join(path, '.node-version'));\n nodeVersionExists = true;\n } catch {\n // File does not exist\n }\n\n if (nvmrcExists || nodeVersionExists) {\n logger.info('Node version file found, installing specified Node.js version...');\n const { success, error } = await runWithExeca({\n cmd: 'n',\n args: ['auto'],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'NODE_FAIL_INSTALL_SPECIFIED_VERSION',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n }\n}\n\nexport async function installDeps({ path, pm }: { path: string; pm?: string }) {\n pm = pm ?? detectPm({ path });\n logger.info('Installing dependencies', { pm, path });\n // --force is needed to install peer deps for external packages in the mastra output directory\n // --legacy-peer-deps=false is needed to override other overrides by the repo package manager such as pnpm. Pnpm would set it to true\n const args = ['install', '--legacy-peer-deps=false', '--force'];\n const { success, error } = await runWithExeca({ cmd: pm, args, cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_INSTALL_DEPS',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runInstallCommand({ path, installCommand }: { path: string; installCommand: string }) {\n logger.info('Running install command', { command: installCommand, path });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', installCommand], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_CUSTOM_INSTALL_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runScript({ scriptName, path, args }: { scriptName: string; path: string; args?: string[] }) {\n const pm = detectPm({ path });\n logger.info('Running script', { script: scriptName, pm });\n const { success, error } = await runWithExeca({\n cmd: pm,\n args: pm === 'npm' ? ['run', scriptName, ...(args ?? [])] : [scriptName, ...(args ?? [])],\n cwd: path,\n });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_SCRIPT',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n\nexport async function runBuildCommand({ command, path }: { command: string; path: string }) {\n logger.info('Running build command', { command });\n const { success, error } = await runWithExeca({ cmd: 'sh', args: ['-c', command], cwd: path });\n if (!success) {\n throw new MastraError(\n {\n id: 'FAIL_BUILD_COMMAND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { join } from 'node:path';\nimport { MastraError } from '@mastra/core/error';\nimport { FileService } from '@mastra/deployer';\n\nimport { MASTRA_DIRECTORY } from './constants.js';\n\nexport function getMastraEntryFile(mastraDir: string) {\n try {\n const fileService = new FileService();\n return fileService.getFirstExistingFile([\n join(mastraDir, MASTRA_DIRECTORY, 'index.ts'),\n join(mastraDir, MASTRA_DIRECTORY, 'index.js'),\n ]);\n } catch (error) {\n throw new MastraError(\n {\n id: 'MASTRA_ENTRY_FILE_NOT_FOUND',\n category: 'USER',\n domain: 'DEPLOYER',\n },\n error,\n );\n }\n}\n","import { PROJECT_ID, BUILD_ID, BUILD_URL, USER_IP_ADDRESS } from './constants.js';\n\nexport function successEntrypoint() {\n return `\n if (process.env.CI !== 'true') {\n await fetch('${process.env.REPORTER_API_URL}', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ${process.env.REPORTER_API_URL_AUTH_TOKEN}',\n },\n body: JSON.stringify(${JSON.stringify({\n projectId: PROJECT_ID,\n buildId: BUILD_ID,\n status: 'success',\n url: BUILD_URL,\n userIpAddress: USER_IP_ADDRESS,\n })}),\n }).catch(err => {\n console.error('Failed to report build status to monitoring service', {\n error: err,\n });\n })\n }\n `;\n}\n","import { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport { Deployer } from '@mastra/deployer';\nimport { copy, readJSON } from 'fs-extra/esm';\n\nimport { getAuthEntrypoint } from './utils/auth.js';\nimport { MASTRA_DIRECTORY, BUILD_ID, PROJECT_ID, TEAM_ID } from './utils/constants.js';\nimport { installDeps } from './utils/deps.js';\nimport { getMastraEntryFile } from './utils/file.js';\nimport { successEntrypoint } from './utils/report.js';\n\nexport class CloudDeployer extends Deployer {\n private studio: boolean;\n\n constructor({ studio }: { studio?: boolean } = {}) {\n super({ name: 'cloud' });\n this.studio = studio ?? false;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Always force externals: true for cloud deployments.\n // The cloud deployer installs all dependencies from npm into node_modules,\n // so bundling them inline serves no purpose. Bundling inline can also cause\n // circular module evaluation deadlocks when dynamic imports (e.g. in\n // MemoryLibSQL.init()) reference chunks that depend back on the entry module,\n // resulting in \"Detected unsettled top-level await\" warnings.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n async deploy(_outputDirectory: string): Promise<void> {}\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n await copy(join(dirname(__dirname), join('dist', 'studio')), studioServePath, {\n overwrite: true,\n });\n }\n }\n async writePackageJson(outputDirectory: string, dependencies: Map<string, string>) {\n const versions = (await readJSON(join(dirname(fileURLToPath(import.meta.url)), '../versions.json'))) as\n | Record<string, string>\n | undefined;\n for (const [pkgName, version] of Object.entries(versions || {})) {\n dependencies.set(pkgName, version);\n }\n\n return super.writePackageJson(outputDirectory, dependencies);\n }\n\n async lint() {}\n\n protected async installDependencies(outputDirectory: string, _rootDir = process.cwd()) {\n await installDeps({ path: join(outputDirectory, 'output'), pm: 'npm' });\n }\n\n async bundle(mastraDir: string, outputDirectory: string): Promise<void> {\n const currentCwd = process.cwd();\n process.chdir(mastraDir);\n\n const mastraEntryFile = getMastraEntryFile(mastraDir);\n\n const mastraAppDir = join(mastraDir, MASTRA_DIRECTORY);\n\n // Use the getAllToolPaths method to prepare tools paths\n const discoveredTools = this.getAllToolPaths(mastraAppDir);\n\n await this.prepare(outputDirectory);\n await this._bundle(\n this.getEntry(),\n mastraEntryFile,\n {\n outputDirectory,\n projectRoot: mastraDir,\n },\n discoveredTools,\n );\n process.chdir(currentCwd);\n }\n\n getAuthEntrypoint() {\n return getAuthEntrypoint();\n }\n\n private getEntry(): string {\n return `\nimport { createNodeServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { mastra } from '#mastra';\nimport { MultiLogger } from '@mastra/core/logger';\nimport { PinoLogger } from '@mastra/loggers';\nimport { HttpTransport } from '@mastra/loggers/http';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\nconst startTime = process.env.RUNNER_START_TIME ? new Date(process.env.RUNNER_START_TIME).getTime() : Date.now();\nconst createNodeServerStartTime = Date.now();\n\nconsole.log(JSON.stringify({\n message: \"Server starting\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\nconst transports = {}\nif (process.env.CI !== 'true') {\n if (process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT) {\n transports.default = new HttpTransport({\n url: process.env.BUSINESS_API_RUNNER_LOGS_ENDPOINT,\n headers: {\n Authorization: 'Bearer ' + process.env.BUSINESS_JWT_TOKEN,\n },\n });\n }\n}\n\nconst logger = new PinoLogger({\n name: 'MastraCloud',\n transports,\n level: 'debug',\n});\nconst existingLogger = mastra?.getLogger();\nconst combinedLogger = existingLogger ? new MultiLogger([logger, existingLogger]) : logger;\n\nmastra.setLogger({ logger: combinedLogger });\n\nif (process.env.MASTRA_STORAGE_URL && process.env.MASTRA_STORAGE_AUTH_TOKEN) {\n const { MastraStorage } = await import('@mastra/core/storage');\n logger.info('Using Mastra Cloud Storage: ' + process.env.MASTRA_STORAGE_URL)\n const storage = new LibSQLStore({\n id: 'mastra-cloud-storage-libsql',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n const vector = new LibSQLVector({\n id: 'mastra-cloud-storage-libsql-vector',\n url: process.env.MASTRA_STORAGE_URL,\n authToken: process.env.MASTRA_STORAGE_AUTH_TOKEN,\n })\n\n await storage.init()\n mastra?.setStorage(storage)\n} else {\n const userStorage = mastra?.getStorage();\n if (userStorage && !userStorage.disableInit) {\n userStorage.init();\n }\n}\n\nif (mastra?.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n}\n\n${getAuthEntrypoint()}\n\nawait createNodeServer(mastra, { studio: ${this.studio}, swaggerUI: false, tools: getToolExports(tools) });\n\n${successEntrypoint()}\n\nconsole.log(JSON.stringify({\n message: \"Server started\",\n operation: 'builder.createNodeServer',\n operation_startTime: createNodeServerStartTime,\n operation_durationMs: Date.now() - createNodeServerStartTime,\n type: \"READINESS\",\n startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n\n\nconsole.log(JSON.stringify({\n message: \"Runner Initialized\",\n type: \"READINESS\",\n startTime,\n durationMs: Date.now() - startTime,\n metadata: {\n teamId: \"${TEAM_ID}\",\n projectId: \"${PROJECT_ID}\",\n buildId: \"${BUILD_ID}\",\n },\n}));\n`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAgB,oBAAoB;CAClC,MAAM,eAA6D,CAAC;CAEpE,IAAI,QAAQ,IAAI,sBACd,aAAa,QAAQ,IAAI,wBAAwB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAErF,IAAI,QAAQ,IAAI,oBACd,aAAa,QAAQ,IAAI,sBAAsB;EAAE,IAAI;EAAgB,MAAM;CAAM;CAGnF,OAAO;;;;;;;;kBAQS,KAA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;EAErD,kBAAkB,EAAE;;;;;;;;;;eAUP,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;;;;;;;;eAWV,QAAQ;kBACL,WAAW;gBACb,SAAS;;;;CAIvB;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-
|
|
2
|
-
import{t as e}from"./preload-helper-CRzLMJPS.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=!1;function n(e){return e instanceof Error?e.stack||e.message:String(e)}function r(e,{showDetails:r=t}={}){let i=document.getElementById(`root`);if(!i||i.childElementCount>0)return;let a=document.createElement(`main`);a.setAttribute(`role`,`alert`),a.style.cssText=`min-height:100vh;background:#0b0d10;color:#f4f4f5;font-family:"Mona Sans",ui-sans-serif,system-ui,sans-serif;font-feature-settings:"ss06" on;padding:32px;box-sizing:border-box;`;let o=document.createElement(`h1`);o.textContent=`Mastra Studio failed to start`,o.style.cssText=`font-size:20px;line-height:1.4;margin:0 0 8px;`;let s=document.createElement(`p`);if(s.textContent=r?`The startup module failed before React could render. Check the Vite terminal and browser console for the original request details.`:`The startup module failed before React could render. Run Studio in development mode to view detailed diagnostics.`,s.style.cssText=`color:#a1a1aa;max-width:760px;margin:0 0 20px;line-height:1.6;`,a.append(o,s),r){let t=document.createElement(`pre`);t.textContent=n(e),t.style.cssText=`white-space:pre-wrap;overflow:auto;background:#18181b;border:1px solid #3f3f46;border-radius:8px;padding:16px;max-width:100%;line-height:1.5;`,a.append(t)}i.replaceChildren(a)}try{let{startStudio:t}=await e(async()=>{let{startStudio:e}=await import(`./main-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DlUaMwI7.js","./rolldown-runtime-BWaJ3C7D.js","./preload-helper-CRzLMJPS.js","./dist-CXMb7aeG.js","./dist-DIJvMGBR.js","./dist-BeXC2sV7.js","./dist-D73uoo3G.js","./dist-DOBwC-Vj.js","./cn-CQUhN5Jx-DGfaIrHO.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-CRzLMJPS.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=!1;function n(e){return e instanceof Error?e.stack||e.message:String(e)}function r(e,{showDetails:r=t}={}){let i=document.getElementById(`root`);if(!i||i.childElementCount>0)return;let a=document.createElement(`main`);a.setAttribute(`role`,`alert`),a.style.cssText=`min-height:100vh;background:#0b0d10;color:#f4f4f5;font-family:"Mona Sans",ui-sans-serif,system-ui,sans-serif;font-feature-settings:"ss06" on;padding:32px;box-sizing:border-box;`;let o=document.createElement(`h1`);o.textContent=`Mastra Studio failed to start`,o.style.cssText=`font-size:20px;line-height:1.4;margin:0 0 8px;`;let s=document.createElement(`p`);if(s.textContent=r?`The startup module failed before React could render. Check the Vite terminal and browser console for the original request details.`:`The startup module failed before React could render. Run Studio in development mode to view detailed diagnostics.`,s.style.cssText=`color:#a1a1aa;max-width:760px;margin:0 0 20px;line-height:1.6;`,a.append(o,s),r){let t=document.createElement(`pre`);t.textContent=n(e),t.style.cssText=`white-space:pre-wrap;overflow:auto;background:#18181b;border:1px solid #3f3f46;border-radius:8px;padding:16px;max-width:100%;line-height:1.5;`,a.append(t)}i.replaceChildren(a)}try{let{startStudio:t}=await e(async()=>{let{startStudio:e}=await import(`./main-DlUaMwI7.js`);return{startStudio:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url);t()}catch(e){console.error(`Mastra Studio failed to start`,e),r(e)}
|