Add support for multiple deployment providers

This commit is contained in:
Alex Gleason committed 2025-10-17 12:04:39 -05:00
1 parent bfb36c9633
commit a379de544a
17 files changed
+1367 -145

No files matched your search

@@ -0,0 +1,161 @@
import JSZip from 'jszip';
import type { DeployProvider, DeployOptions, DeployResult, NetlifyDeployConfig } from './types';
interface NetlifySite {
id: string;
site_id: string;
name: string;
url: string;
admin_url: string;
}
interface NetlifyBuildResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
}
/**
* Netlify Deploy Provider
* Uses Netlify API with personal access token
*/
export class NetlifyDeployProvider implements DeployProvider {
private config: NetlifyDeployConfig;
constructor(config: NetlifyDeployConfig) {
this.config = config;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectName, fs, projectPath } = options;
const { apiKey, siteId, siteName } = this.config;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Get or create site
let activeSiteId = siteId;
let siteUrl = '';
if (!activeSiteId) {
// Create new site
const site = await this.createSite(apiKey, siteName || projectName || projectId);
activeSiteId = site.id;
siteUrl = site.url;
} else {
// Get existing site URL
const site = await this.getSite(apiKey, activeSiteId);
siteUrl = site.url;
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(fs, distPath, zip);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Deploy to Netlify
await this.triggerBuild(apiKey, activeSiteId, zipBlob, `Deploy from Shakespeare - ${new Date().toISOString()}`);
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
provider: 'netlify',
},
};
}
private async createSite(apiKey: string, name: string): Promise<NetlifySite> {
const response = await fetch('https://api.netlify.com/api/v1/sites', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
created_via: 'shakespeare',
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create Netlify site: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async getSite(apiKey: string, siteId: string): Promise<NetlifySite> {
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
},
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to get Netlify site: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async triggerBuild(apiKey: string, siteId: string, zipBlob: Blob, title: string): Promise<NetlifyBuildResponse> {
const formData = new FormData();
formData.append('title', title);
formData.append('zip', zipBlob, 'deploy.zip');
const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/builds`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fs, fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
@@ -0,0 +1,93 @@
import JSZip from 'jszip';
import { NIP98Client } from '@nostrify/nostrify';
import type { DeployProvider, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
/**
* Shakespeare Deploy Provider
* Uses NIP-98 authentication with Nostr signer
*/
export class ShakespeareDeployProvider implements DeployProvider {
private config: ShakespeareDeployConfig;
constructor(config: ShakespeareDeployConfig) {
this.config = config;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, fs, projectPath } = options;
const { signer, deployServer = 'shakespeare.wtf', customHostname } = this.config;
// Use custom hostname if provided, otherwise construct from projectId.deployServer
const hostname = customHostname || `${projectId}.${deployServer}`;
const deployUrl = `https://${deployServer}/deploy`;
const siteUrl = `https://${hostname}`;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(fs, distPath, zip);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Create FormData
const formData = new FormData();
formData.append('hostname', hostname);
formData.append('file', zipBlob, `${projectId}.zip`);
// Create NIP-98 authenticated client and deploy
const nip98Client = new NIP98Client({ signer });
const response = await nip98Client.fetch(deployUrl, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Deployment failed: ${response.status} ${response.statusText}. ${errorText}`);
}
return {
url: siteUrl,
metadata: {
hostname,
provider: 'shakespeare',
},
};
}
private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fs, fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
@@ -0,0 +1,131 @@
import type { DeployProvider, DeployOptions, DeployResult, VercelDeployConfig } from './types';
interface VercelFile {
file: string;
data: string;
}
interface VercelDeployment {
id: string;
url: string;
name: string;
readyState: string;
}
/**
* Vercel Deploy Provider
* Uses Vercel REST API with access token
*/
export class VercelDeployProvider implements DeployProvider {
private config: VercelDeployConfig;
constructor(config: VercelDeployConfig) {
this.config = config;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectName, fs, projectPath } = options;
const { apiKey, teamId } = this.config;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Collect all files from dist directory
const files: VercelFile[] = [];
await this.collectFiles(fs, distPath, '', files);
// Create deployment payload
const deploymentPayload = {
name: this.config.projectName || projectName || projectId,
files,
projectSettings: {
framework: null, // Static deployment
},
target: 'production' as const,
};
// Build API URL with optional team parameter
let apiUrl = 'https://api.vercel.com/v13/deployments';
if (teamId) {
apiUrl += `?teamId=${teamId}`;
}
// Deploy to Vercel
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(deploymentPayload),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to deploy to Vercel: ${response.status} ${response.statusText}. ${errorText}`);
}
const deployment: VercelDeployment = await response.json();
return {
url: `https://${deployment.url}`,
metadata: {
deploymentId: deployment.id,
provider: 'vercel',
readyState: deployment.readyState,
},
};
}
private async collectFiles(
fs: DeployOptions['fs'],
dirPath: string,
relativePath: string,
files: VercelFile[]
): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Recursively collect files from subdirectories
await this.collectFiles(fs, fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
// Read file content
const fileContent = await fs.readFile(fullPath);
// Convert to base64 for Vercel API
let base64Content: string;
if (typeof fileContent === 'string') {
base64Content = btoa(fileContent);
} else {
// Handle Uint8Array
const binary = Array.from(fileContent)
.map(byte => String.fromCharCode(byte))
.join('');
base64Content = btoa(binary);
}
files.push({
file: entryRelativePath,
data: base64Content,
});
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
}
+4
View File
@@ -0,0 +1,4 @@
export * from './types';
export * from './ShakespeareDeployProvider';
export * from './NetlifyDeployProvider';
export * from './VercelDeployProvider';
+44
View File
@@ -0,0 +1,44 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { NostrSigner } from '@nostrify/nostrify';
export interface DeployOptions {
/** Project ID */
projectId: string;
/** Filesystem instance containing the project */
fs: JSRuntimeFS;
/** Path to the project directory */
projectPath: string;
/** Project name */
projectName?: string;
}
export interface DeployResult {
/** The deployed URL */
url: string;
/** Additional metadata */
metadata?: Record<string, unknown>;
}
export interface DeployProvider {
/** Deploy a project */
deploy(options: DeployOptions): Promise<DeployResult>;
}
export interface ShakespeareDeployConfig {
signer: NostrSigner;
deployServer?: string;
customHostname?: string;
}
export interface NetlifyDeployConfig {
apiKey: string;
siteId?: string;
siteName?: string;
}
export interface VercelDeployConfig {
apiKey: string;
projectId?: string;
teamId?: string;
projectName?: string;
}
+18
View File
@@ -88,6 +88,9 @@ const resources = {
aiSettingsDescription: 'Configure AI providers and API keys',
gitSettings: 'Git Settings',
gitSettingsDescription: 'Configure Git credentials for HTTP authentication',
deploySettings: 'Deployment',
deploySettingsDescription: 'Configure deployment providers',
deploySettingsDescriptionLong: 'Configure deployment providers to deploy your projects to various hosting platforms.',
nostrSettings: 'Nostr Settings',
nostrSettingsDescription: 'Configure relay connections and Nostr preferences',
storageSettings: 'Storage',
@@ -205,6 +208,9 @@ const resources = {
loginToNostrRequired: 'Log in to Nostr to use this provider',
goToNostrSettings: 'Go to Nostr Settings',
// Deploy Settings
shakespeareDeployNostrAuth: 'This provider uses Nostr authentication. Make sure you are logged in to deploy.',
// Git Settings
gitSettingsDescriptionLong: 'Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.',
configuredCredentials: 'Configured Credentials',
@@ -412,6 +418,9 @@ const resources = {
aiSettingsDescription: 'Configure provedores de IA e chaves de API',
gitSettings: 'Configurações do Git',
gitSettingsDescription: 'Configure credenciais do Git para autenticação HTTP',
deploySettings: 'Implantação',
deploySettingsDescription: 'Configure provedores de implantação',
deploySettingsDescriptionLong: 'Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.',
nostrSettings: 'Configurações do Nostr',
nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr',
storageSettings: 'Armazenamento',
@@ -529,6 +538,9 @@ const resources = {
loginToNostrRequired: 'Faça login no Nostr para usar este provedor',
goToNostrSettings: 'Ir para Configurações do Nostr',
// Deploy Settings
shakespeareDeployNostrAuth: 'Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.',
// Git Settings
gitSettingsDescriptionLong: 'Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.',
configuredCredentials: 'Credenciais Configuradas',
@@ -742,6 +754,9 @@ const resources = {
aiSettingsDescription: '配置AI提供商和API密钥',
gitSettings: 'Git设置',
gitSettingsDescription: '配置HTTP身份验证的Git凭据',
deploySettings: '部署',
deploySettingsDescription: '配置部署提供商',
deploySettingsDescriptionLong: '配置部署提供商以将您的项目部署到各种托管平台。',
nostrSettings: 'Nostr设置',
nostrSettingsDescription: '配置中继连接和Nostr偏好',
storageSettings: '存储',
@@ -859,6 +874,9 @@ const resources = {
loginToNostrRequired: '登录Nostr以使用此提供商',
goToNostrSettings: '前往Nostr设置',
// Deploy Settings
shakespeareDeployNostrAuth: '此提供商使用Nostr身份验证。请确保您已登录以进行部署。',
// Git Settings
gitSettingsDescriptionLong: '配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。',
configuredCredentials: '已配置的凭据',
+8 -1
View File
@@ -1,4 +1,4 @@
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings } from 'lucide-react';
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
export interface SettingsItem {
id: string;
@@ -35,6 +35,13 @@ export const getSettingsItems = (t: (key: string) => string): SettingsItem[] =>
icon: GitBranch,
href: '/settings/git',
},
{
id: 'deploy',
title: t('deploySettings'),
description: t('deploySettingsDescription'),
icon: Rocket,
href: '/settings/deploy',
},
{
id: 'nostr',
title: t('nostrSettings'),