import execa from "execa"; import fs from "fs-extra"; import path from "path"; import { PlatformAdapter, DeploymentConfig, DeploymentResult, DeploymentStatus, DeploymentHistoryItem, RollbackResult, } from "../platform-adapter"; import { logger } from "../../utils/logger"; /** * Netlify platform adapter */ export class NetlifyAdapter implements PlatformAdapter { /** * Deploy the application to Netlify * @param config Deployment configuration * @returns Deployment result */ async deploy(config: DeploymentConfig): Promise { try { // Ensure Netlify CLI is installed await this.ensureNetlifyCLI(); // Set environment variables await this.setEnvironmentVariables(config); // Build the application if needed if (config.buildCommand) { await execa("pnpm", ["run", config.buildCommand], { stdio: "inherit", }); } // Create netlify.toml if it doesn't exist await this.createNetlifyConfig(config); // Deploy to Netlify const args = ["deploy"]; // Add production flag if environment is production if (config.environment === "production") { args.push("--prod"); } // Add output directory if specified if (config.outputDir) { args.push("--dir", config.outputDir); } logger.info(`Deploying to Netlify with args: ${args.join(" ")}`); const { stdout } = await execa("netlify", args); // Parse deployment URL and ID const url = this.parseDeploymentUrl(stdout); const id = this.parseDeploymentId(stdout); // Configure domain if specified if (config.domain) { await this.configureDomain(config.domain); } return { success: true, url, deploymentId: id, }; } catch (error) { logger.error( `Netlify deployment error: ${(error as Error).message}` ); return { success: false, error: `Failed to deploy to Netlify: ${(error as Error).message}`, }; } } /** * Get deployment status * @param deploymentId Deployment ID * @returns Deployment status */ async getStatus(deploymentId?: string): Promise { try { // Ensure Netlify CLI is installed await this.ensureNetlifyCLI(); // Get deployment status const args = ["api", "getSite"]; if (deploymentId) { args.push("--data", `{"site_id":"${deploymentId}"}`); } const { stdout } = await execa("netlify", args); const site = JSON.parse(stdout); return { status: site.state, url: site.ssl_url || site.url, id: site.id, createdAt: new Date(site.created_at).toLocaleString(), }; } catch (error) { logger.error(`Netlify status error: ${(error as Error).message}`); throw new Error( `Failed to get Netlify deployment status: ${(error as Error).message}` ); } } /** * Get deployment history * @returns Deployment history */ async getHistory(): Promise { try { // Ensure Netlify CLI is installed await this.ensureNetlifyCLI(); // Get deployment history const { stdout } = await execa("netlify", ["api", "listSites"]); const sites = JSON.parse(stdout); return sites.map((site: any) => ({ id: site.id, url: site.ssl_url || site.url, status: site.state, createdAt: new Date(site.created_at).toLocaleString(), })); } catch (error) { logger.error(`Netlify history error: ${(error as Error).message}`); throw new Error( `Failed to get Netlify deployment history: ${(error as Error).message}` ); } } /** * Roll back to a previous deployment * @param deploymentId Deployment ID * @returns Rollback result */ async rollback(deploymentId: string): Promise { try { // Ensure Netlify CLI is installed await this.ensureNetlifyCLI(); // Roll back to previous deployment const { stdout } = await execa("netlify", [ "api", "restoreSiteDeploy", "--data", `{"deploy_id":"${deploymentId}"}`, ]); const success = stdout.includes("restored"); if (success) { // Get deployment status const status = await this.getStatus(deploymentId); return { success: true, message: "Rollback successful", url: status.url, }; } else { return { success: false, message: "Rollback failed", }; } } catch (error) { logger.error(`Netlify rollback error: ${(error as Error).message}`); return { success: false, message: `Failed to roll back Netlify deployment: ${(error as Error).message}`, }; } } /** * Configure a custom domain * @param domain Custom domain * @returns Success status */ async configureDomain(domain: string): Promise { try { // Ensure Netlify CLI is installed await this.ensureNetlifyCLI(); // Configure domain const { stdout } = await execa("netlify", ["domain:add", domain]); return stdout.includes("Success"); } catch (error) { logger.error( `Netlify domain configuration error: ${(error as Error).message}` ); return false; } } /** * Ensure Netlify CLI is installed */ private async ensureNetlifyCLI(): Promise { try { await execa("netlify", ["--version"]); } catch (error) { logger.info("Netlify CLI not found, installing..."); await execa("pnpm", ["install", "-g", "netlify-cli"]); } } /** * Set environment variables * @param config Deployment configuration */ private async setEnvironmentVariables( config: DeploymentConfig ): Promise { try { // Check if .env file exists const envPath = path.join(process.cwd(), ".env"); if (fs.existsSync(envPath)) { // Read .env file const envContent = await fs.readFile(envPath, "utf8"); const envVars = this.parseEnvFile(envContent); // Set environment variables for (const [key, value] of Object.entries(envVars)) { await execa("netlify", ["env:set", key, value]); } } // Check if .env.{environment} file exists const envEnvironmentPath = path.join( process.cwd(), `.env.${config.environment}` ); if (fs.existsSync(envEnvironmentPath)) { // Read .env.{environment} file const envContent = await fs.readFile( envEnvironmentPath, "utf8" ); const envVars = this.parseEnvFile(envContent); // Set environment variables for (const [key, value] of Object.entries(envVars)) { await execa("netlify", [ "env:set", key, value, "--scope", config.environment, ]); } } } catch (error) { logger.warn( `Failed to set environment variables: ${(error as Error).message}` ); } } /** * Create Netlify configuration file * @param config Deployment configuration */ private async createNetlifyConfig(config: DeploymentConfig): Promise { try { const netlifyConfigPath = path.join(process.cwd(), "netlify.toml"); // Skip if file already exists if (fs.existsSync(netlifyConfigPath)) { return; } // Create netlify.toml const netlifyConfig = `[build] command = "${config.buildCommand || "npm run build"}" publish = "${config.outputDir || "out"}" [build.environment] NODE_VERSION = "18" NODE_ENV = "${config.environment}" [dev] command = "npm run dev" port = 8888 targetPort = 3000 [[redirects]] from = "/*" to = "/index.html" status = 200 `; await fs.writeFile(netlifyConfigPath, netlifyConfig, "utf8"); logger.info("Created netlify.toml configuration file"); } catch (error) { logger.warn( `Failed to create Netlify configuration: ${(error as Error).message}` ); } } /** * Parse .env file * @param content .env file content * @returns Environment variables */ private parseEnvFile(content: string): Record { const envVars: Record = {}; const lines = content.split("\n"); for (const line of lines) { // Skip comments and empty lines if (line.startsWith("#") || line.trim() === "") { continue; } // Parse key-value pair const match = line.match(/^([^=]+)=(.*)$/); if (match) { const key = match[1].trim(); const value = match[2].trim(); envVars[key] = value; } } return envVars; } /** * Parse deployment URL from Netlify output * @param output Netlify output * @returns Deployment URL */ private parseDeploymentUrl(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 parseDeploymentId(output: string): string { const match = output.match(/Deploy ID: +([^\s]+)/); return match ? match[1] : ""; } }