import execa from "execa"; import fs from "fs-extra"; import path from "path"; import { logger } from "./logger"; /** * Deployment configuration */ export interface DeploymentConfig { platform?: string; environment?: string; domain?: string; } /** * Deployment result */ export interface DeploymentResult { success: boolean; url?: string; deploymentId?: string; error?: string; } /** * Deployment status */ export interface DeploymentStatus { status: string; url: string; id: string; createdAt: string; } /** * Deployment history item */ export interface DeploymentHistoryItem { id: string; url: string; status: string; createdAt: string; } /** * Rollback result */ export interface RollbackResult { success: boolean; message: string; url?: string; } /** * Deployment manager for deploying applications to various platforms */ export class DeploymentManager { private config: DeploymentConfig; /** * Create a new deployment manager * @param config Deployment configuration */ constructor(config: DeploymentConfig) { this.config = { platform: "vercel", environment: "production", ...config, }; } /** * Deploy the application * @returns Deployment result */ async deploy(): Promise { try { // Check if the platform CLI is installed await this.ensurePlatformCLI(); // Load configuration const deploymentConfig = await this.loadConfig(); // Set environment variables this.setEnvironmentVariables(deploymentConfig); // Build the application await this.build(); // Deploy the application const deploymentResult = await this.deployToPlatform(); // Configure domain if specified if (this.config.domain) { await this.configureDomain(this.config.domain); } return deploymentResult; } catch (error) { return { success: false, error: (error as Error).message, }; } } /** * Get the status of the latest deployment * @returns Deployment status */ async getStatus(): Promise { try { // Check if the platform CLI is installed await this.ensurePlatformCLI(); // Get deployment status based on platform switch (this.config.platform) { case "vercel": return this.getVercelStatus(); case "netlify": return this.getNetlifyStatus(); case "aws": return this.getAWSStatus(); default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } catch (error) { throw new Error( `Failed to get deployment status: ${(error as Error).message}` ); } } /** * Get the deployment history * @returns Deployment history */ async getHistory(): Promise { try { // Check if the platform CLI is installed await this.ensurePlatformCLI(); // Get deployment history based on platform switch (this.config.platform) { case "vercel": return this.getVercelHistory(); case "netlify": return this.getNetlifyHistory(); case "aws": return this.getAWSHistory(); default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } catch (error) { throw new Error( `Failed to get deployment history: ${(error as Error).message}` ); } } /** * Roll back to a previous deployment * @param deploymentId Deployment ID to roll back to * @returns Rollback result */ async rollback(deploymentId: string): Promise { try { // Check if the platform CLI is installed await this.ensurePlatformCLI(); // Roll back based on platform switch (this.config.platform) { case "vercel": return this.rollbackVercel(deploymentId); case "netlify": return this.rollbackNetlify(deploymentId); case "aws": return this.rollbackAWS(deploymentId); default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } catch (error) { return { success: false, message: `Failed to roll back: ${(error as Error).message}`, }; } } /** * Ensure the platform CLI is installed */ private async ensurePlatformCLI(): Promise { try { switch (this.config.platform) { case "vercel": await execa("vercel", ["--version"]); break; case "netlify": await execa("netlify", ["--version"]); break; case "aws": await execa("aws", ["--version"]); break; default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } catch (error) { throw new Error( `${this.config.platform} CLI is not installed. Please install it first.` ); } } /** * Load deployment configuration * @returns Deployment configuration */ private async loadConfig(): Promise> { const configPath = path.join(process.cwd(), "rsdt.config.js"); if (fs.existsSync(configPath)) { try { const config = require(configPath); return config.deployment || {}; } catch (error) { logger.warn( `Failed to load configuration: ${(error as Error).message}` ); return {}; } } return {}; } /** * Set environment variables for deployment * @param config Deployment configuration */ private setEnvironmentVariables(config: Record): void { // Set NODE_ENV process.env.NODE_ENV = this.config.environment === "production" ? "production" : "development"; // Set platform-specific environment variables if (config.env) { for (const [key, value] of Object.entries(config.env)) { process.env[key] = value as string; } } } /** * Build the application */ private async build(): Promise { try { await execa("pnpm", ["build"]); } catch (error) { throw new Error( `Failed to build application: ${(error as Error).message}` ); } } /** * Deploy the application to the selected platform * @returns Deployment result */ private async deployToPlatform(): Promise { switch (this.config.platform) { case "vercel": return this.deployToVercel(); case "netlify": return this.deployToNetlify(); case "aws": return this.deployToAWS(); default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } /** * Deploy the application to Vercel * @returns Deployment result */ private async deployToVercel(): Promise { try { // Deploy to Vercel const args = ["--prod"]; if ( this.config.environment && this.config.environment !== "production" ) { args.push("--environment", this.config.environment); } const { stdout } = await execa("vercel", args); // Parse deployment URL and ID const url = this.parseVercelDeploymentUrl(stdout); const id = this.parseVercelDeploymentId(stdout); return { success: true, url, deploymentId: id, }; } catch (error) { return { success: false, error: `Failed to deploy to Vercel: ${(error as Error).message}`, }; } } /** * Deploy the application to Netlify * @returns Deployment result */ private async deployToNetlify(): Promise { try { // Deploy to Netlify const args = ["deploy"]; if (this.config.environment === "production") { args.push("--prod"); } const { stdout } = await execa("netlify", args); // Parse deployment URL and ID const url = this.parseNetlifyDeploymentUrl(stdout); const id = this.parseNetlifyDeploymentId(stdout); return { success: true, url, deploymentId: id, }; } catch (error) { return { success: false, error: `Failed to deploy to Netlify: ${(error as Error).message}`, }; } } /** * Deploy the application to AWS * @returns Deployment result */ private async deployToAWS(): Promise { // This is a simplified implementation // In a real-world scenario, this would be more complex try { // Deploy to AWS const { stdout } = await execa("aws", [ "s3", "sync", "out", `s3://my-bucket/${this.config.environment}`, ]); return { success: true, url: `https://my-bucket.s3.amazonaws.com/${this.config.environment}/index.html`, deploymentId: new Date().toISOString(), }; } catch (error) { return { success: false, error: `Failed to deploy to AWS: ${(error as Error).message}`, }; } } /** * Configure a custom domain * @param domain Custom domain */ private async configureDomain(domain: string): Promise { try { switch (this.config.platform) { case "vercel": await execa("vercel", ["domains", "add", domain]); break; case "netlify": await execa("netlify", ["domain:add", domain]); break; case "aws": // AWS domain configuration would be more complex break; default: throw new Error( `Unsupported platform: ${this.config.platform}` ); } } catch (error) { throw new Error( `Failed to configure domain: ${(error as Error).message}` ); } } /** * Get deployment status from Vercel * @returns Deployment status */ private async getVercelStatus(): Promise { try { const { stdout } = await execa("vercel", [ "list", "--limit", "1", "--json", ]); const deployments = JSON.parse(stdout); const deployment = deployments[0]; return { status: deployment.state, url: deployment.url, id: deployment.uid, createdAt: new Date(deployment.created).toLocaleString(), }; } catch (error) { throw new Error( `Failed to get Vercel status: ${(error as Error).message}` ); } } /** * Get deployment status from Netlify * @returns Deployment status */ private async getNetlifyStatus(): Promise { try { const { stdout } = await execa("netlify", [ "api", "listSites", "--json", ]); const sites = JSON.parse(stdout); const site = sites[0]; return { status: site.state, url: site.url, id: site.id, createdAt: new Date(site.created_at).toLocaleString(), }; } catch (error) { throw new Error( `Failed to get Netlify status: ${(error as Error).message}` ); } } /** * Get deployment status from AWS * @returns Deployment status */ private async getAWSStatus(): Promise { // This is a simplified implementation return { status: "ready", url: `https://my-bucket.s3.amazonaws.com/${this.config.environment}/index.html`, id: "aws-deployment", createdAt: new Date().toLocaleString(), }; } /** * Get deployment history from Vercel * @returns Deployment history */ private async getVercelHistory(): Promise { try { const { stdout } = await execa("vercel", ["list", "--json"]); const deployments = JSON.parse(stdout); return deployments.map((deployment: any) => ({ id: deployment.uid, url: deployment.url, status: deployment.state, createdAt: new Date(deployment.created).toLocaleString(), })); } catch (error) { throw new Error( `Failed to get Vercel history: ${(error as Error).message}` ); } } /** * Get deployment history from Netlify * @returns Deployment history */ private async getNetlifyHistory(): Promise { try { const { stdout } = await execa("netlify", [ "api", "listSites", "--json", ]); const sites = JSON.parse(stdout); return sites.map((site: any) => ({ id: site.id, url: site.url, status: site.state, createdAt: new Date(site.created_at).toLocaleString(), })); } catch (error) { throw new Error( `Failed to get Netlify history: ${(error as Error).message}` ); } } /** * Get deployment history from AWS * @returns Deployment history */ private async getAWSHistory(): Promise { // This is a simplified implementation return [ { id: "aws-deployment", url: `https://my-bucket.s3.amazonaws.com/${this.config.environment}/index.html`, status: "ready", createdAt: new Date().toLocaleString(), }, ]; } /** * Roll back to a previous Vercel deployment * @param deploymentId Deployment ID to roll back to * @returns Rollback result */ private async rollbackVercel( deploymentId: string ): Promise { try { const { stdout } = await execa("vercel", [ "rollback", deploymentId, ]); const success = stdout.includes("Success"); if (success) { const { stdout: statusStdout } = await execa("vercel", [ "inspect", deploymentId, "--json", ]); const deployment = JSON.parse(statusStdout); return { success: true, message: "Rollback successful", url: deployment.url, }; } else { return { success: false, message: "Rollback failed", }; } } catch (error) { return { success: false, message: `Failed to roll back Vercel deployment: ${(error as Error).message}`, }; } } /** * Roll back to a previous Netlify deployment * @param deploymentId Deployment ID to roll back to * @returns Rollback result */ private async rollbackNetlify( deploymentId: string ): Promise { try { const { stdout } = await execa("netlify", [ "api", "restoreSiteDeploy", "--data", `{"deploy_id":"${deploymentId}"}`, ]); const success = stdout.includes("restored"); if (success) { const { stdout: statusStdout } = await execa("netlify", [ "api", "getDeploy", "--data", `{"deploy_id":"${deploymentId}"}`, ]); const deployment = JSON.parse(statusStdout); return { success: true, message: "Rollback successful", url: deployment.deploy_url, }; } else { return { success: false, message: "Rollback failed", }; } } catch (error) { return { success: false, message: `Failed to roll back Netlify deployment: ${(error as Error).message}`, }; } } /** * Roll back to a previous AWS deployment * @param deploymentId Deployment ID to roll back to * @returns Rollback result */ private async rollbackAWS(deploymentId: string): Promise { // This is a simplified implementation return { success: true, message: "Rollback successful", url: `https://my-bucket.s3.amazonaws.com/${this.config.environment}/index.html`, }; } /** * Parse deployment URL from Vercel output * @param output Vercel output * @returns Deployment URL */ private parseVercelDeploymentUrl(output: string): string { const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.vercel\.app/); return match ? match[0] : ""; } /** * Parse deployment ID from Vercel output * @param output Vercel output * @returns Deployment ID */ private parseVercelDeploymentId(output: string): string { const match = output.match(/Deployment ID: ([a-zA-Z0-9]+)/); return match ? match[1] : ""; } /** * Parse deployment URL from Netlify output * @param output Netlify output * @returns Deployment URL */ private parseNetlifyDeploymentUrl(output: string): string { const match = output.match(/Website URL: +([^\s]+)/); return match ? match[1] : ""; } /** * Parse deployment ID from Netlify output * @param output Netlify output * @returns Deployment ID */ private parseNetlifyDeploymentId(output: string): string { const match = output.match(/Deploy ID: +([^\s]+)/); return match ? match[1] : ""; } }