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

+12 -9
View File
@@ -14,6 +14,7 @@ import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
@@ -87,15 +88,17 @@ export function App() {
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
+2
View File
@@ -10,6 +10,7 @@ import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
@@ -36,6 +37,7 @@ export function AppRouter() {
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
+19 -1
View File
@@ -12,9 +12,11 @@ import {
MessageSquarePlus,
History,
Folder,
Rocket,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
interface ActionsMenuProps {
projectId: string;
@@ -29,7 +31,7 @@ interface ActionsMenuProps {
export function ActionsMenu({
projectId,
projectName: _projectName,
projectName,
onNewChat,
onProjectDetails,
isLoading = false,
@@ -39,6 +41,7 @@ export function ActionsMenu({
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
@@ -86,6 +89,15 @@ export function ActionsMenu({
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
@@ -112,6 +124,12 @@ export function ActionsMenu({
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
);
+301 -132
View File
@@ -1,182 +1,351 @@
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMutation } from '@tanstack/react-query';
import { deployProject } from '@/lib/deploy';
import { useFS } from '@/hooks/useFS';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
CloudUpload,
Loader2,
} from 'lucide-react';
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { ShakespeareDeployProvider, NetlifyDeployProvider, VercelDeployProvider } from '@/lib/deploy-providers';
import type { DeployProvider as DeployProviderType } from '@/contexts/DeploySettingsContext';
import { Link } from 'react-router-dom';
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onFirstInteraction?: () => void;
}
export function DeployDialog({
projectId,
projectName,
open,
onOpenChange,
onFirstInteraction
}: DeployDialogProps) {
const { config } = useAppContext();
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings, setProvider } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
const { user } = useCurrentUser();
const { fs } = useFS();
const { toast } = useToast();
const fs = useFS();
// State for the deploy URL input
const [deployUrl, setDeployUrl] = useState('');
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
// Initialize deploy URL when dialog opens
// Form fields for each provider
const [netlifyFields, setNetlifyFields] = useState({ siteId: '' });
const [vercelFields, setVercelFields] = useState({ teamId: '', projectId: '' });
// Load project settings when dialog opens
useEffect(() => {
if (open) {
setDeployUrl(`${projectId}.${config.deployServer}`);
if (open && projectSettings.providerId) {
setSelectedProviderId(projectSettings.providerId);
if (projectSettings.netlify?.siteId) {
setNetlifyFields({ siteId: projectSettings.netlify.siteId });
}
if (projectSettings.vercel) {
setVercelFields({
teamId: projectSettings.vercel.teamId || '',
projectId: projectSettings.vercel.projectId || '',
});
}
}
}, [open, projectId, config.deployServer]);
}, [open, projectSettings]);
const deployMutation = useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
const handleDeploy = async () => {
if (!selectedProvider) return;
setIsDeploying(true);
setError(null);
setDeployResult(null);
try {
const projectPath = `/projects/${projectId}`;
let provider;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
provider = new ShakespeareDeployProvider({
signer: user.signer,
});
} else if (selectedProvider.type === 'netlify') {
if (!selectedProvider.apiKey) {
throw new Error('Netlify API key is required');
}
// Update provider with site ID if provided
const updatedProvider: DeployProviderType = {
...selectedProvider,
siteId: netlifyFields.siteId || selectedProvider.siteId,
};
if (netlifyFields.siteId && netlifyFields.siteId !== selectedProvider.siteId) {
setProvider(updatedProvider);
}
provider = new NetlifyDeployProvider({
apiKey: selectedProvider.apiKey,
siteId: updatedProvider.siteId,
});
} else if (selectedProvider.type === 'vercel') {
if (!selectedProvider.apiKey) {
throw new Error('Vercel API key is required');
}
// Update provider with team/project ID if provided
const updatedProvider: DeployProviderType = {
...selectedProvider,
teamId: vercelFields.teamId || selectedProvider.teamId,
projectId: vercelFields.projectId || selectedProvider.projectId,
};
if (
(vercelFields.teamId && vercelFields.teamId !== selectedProvider.teamId) ||
(vercelFields.projectId && vercelFields.projectId !== selectedProvider.projectId)
) {
setProvider(updatedProvider);
}
provider = new VercelDeployProvider({
apiKey: selectedProvider.apiKey,
teamId: updatedProvider.teamId,
projectId: updatedProvider.projectId,
});
} else {
throw new Error('Unknown provider type');
}
// Parse the deploy URL to extract hostname and server
const hostname = deployUrl.trim();
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
}
// Extract the deploy server (everything after the first dot)
const deployServer = parts.slice(1).join('.');
return await deployProject({
const result = await provider.deploy({
projectId,
projectName,
fs,
projectId, // Keep the original projectId for file path
deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
customHostname: hostname, // Pass the custom hostname
});
},
onSuccess: (result) => {
toast({
title: "Deployment successful!",
description: `Your project is now live at ${result.hostname}`,
projectPath,
});
// Open the deployed site in a new tab
window.open(result.url, '_blank');
// Close the dialog
onOpenChange(false);
},
onError: (error) => {
toast({
title: "Deployment failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
// Save project-specific settings
await updateProjectSettings({
providerId: selectedProviderId,
netlify: selectedProvider.type === 'netlify' ? { siteId: netlifyFields.siteId } : undefined,
vercel: selectedProvider.type === 'vercel' ? {
teamId: vercelFields.teamId,
projectId: vercelFields.projectId,
} : undefined,
});
},
});
const handleDeploy = () => {
if (onFirstInteraction) {
onFirstInteraction();
setDeployResult(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
setIsDeploying(false);
}
deployMutation.mutate();
};
const handleUrlChange = (value: string) => {
// Remove protocol if user enters it
const cleanValue = value.replace(/^https?:\/\//, '');
setDeployUrl(cleanValue);
};
const isValidUrl = () => {
const trimmed = deployUrl.trim();
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setError(null);
setNetlifyFields({ siteId: '' });
setVercelFields({ teamId: '', projectId: '' });
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<CloudUpload className="h-5 w-5" />
Deploy "{projectName}"
<Rocket className="h-5 w-5" />
Deploy Project
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deploy-url">Deploy URL</Label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
https://
</span>
<Input
id="deploy-url"
value={deployUrl}
onChange={(e) => handleUrlChange(e.target.value)}
placeholder={`${projectId}.${config.deployServer}`}
className="pl-16"
disabled={deployMutation.isPending}
/>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
<p className="text-xs text-muted-foreground">
Your project will be deployed to this URL. You can customize the subdomain.
</p>
</div>
{!user && (
<div className="p-3 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
You must be logged into Nostr to deploy projects.
</p>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={deployMutation.isPending}
>
Cancel
</Button>
<Button
onClick={handleDeploy}
disabled={!user || !isValidUrl() || deployMutation.isPending}
className="gap-2"
>
{deployMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
) : (
<CloudUpload className="h-4 w-4" />
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
<SelectValue placeholder="Choose a deployment provider..." />
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
{provider.id === 'shakespeare' && 'Shakespeare Deploy'}
{provider.id === 'netlify' && 'Netlify'}
{provider.id === 'vercel' && 'Vercel'}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProvider?.type === 'netlify' && (
<div className="space-y-2">
<Label htmlFor="netlify-site-id">
Site ID (Optional)
</Label>
<Input
id="netlify-site-id"
placeholder="Leave empty to create new site"
value={netlifyFields.siteId}
onChange={(e) => setNetlifyFields({ ...netlifyFields, siteId: e.target.value })}
/>
</div>
)}
{selectedProvider?.type === 'vercel' && (
<>
<div className="space-y-2">
<Label htmlFor="vercel-team-id">
Team ID (Optional)
</Label>
<Input
id="vercel-team-id"
placeholder="Leave empty for personal account"
value={vercelFields.teamId}
onChange={(e) => setVercelFields({ ...vercelFields, teamId: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="vercel-project-id">
Project ID (Optional)
</Label>
<Input
id="vercel-project-id"
placeholder="Leave empty to create new project"
value={vercelFields.projectId}
onChange={(e) => setVercelFields({ ...vercelFields, projectId: e.target.value })}
/>
</div>
</>
)}
{selectedProvider?.type === 'shakespeare' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</>
)}
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
</Button>
</DialogFooter>
</div>
)}
</DialogContent>
</Dialog>
);
}
}
+82
View File
@@ -0,0 +1,82 @@
import { useState, useEffect, useMemo, type ReactNode } from 'react';
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
const STORAGE_KEY = 'shakespeare-deploy-settings';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
const [settings, setSettings] = useState<DeploySettings>(() => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
return JSON.parse(stored);
}
} catch (error) {
console.error('Failed to load deploy settings:', error);
}
return DEFAULT_SETTINGS;
});
useEffect(() => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
} catch (error) {
console.error('Failed to save deploy settings:', error);
}
}, [settings]);
const updateSettings = (updates: Partial<DeploySettings>) => {
setSettings(prev => ({ ...prev, ...updates }));
};
const setProvider = (provider: DeployProvider) => {
setSettings(prev => {
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
if (existingIndex >= 0) {
// Update existing provider
const newProviders = [...prev.providers];
newProviders[existingIndex] = provider;
return { ...prev, providers: newProviders };
} else {
// Add new provider
return { ...prev, providers: [...prev.providers, provider] };
}
});
};
const removeProvider = (id: string) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter(p => p.id !== id),
// Clear default if it was removed
defaultProviderId: prev.defaultProviderId === id ? undefined : prev.defaultProviderId,
}));
};
const setProviders = (providers: DeployProvider[]) => {
setSettings(prev => ({ ...prev, providers }));
};
const isConfigured = useMemo(() => {
return settings.providers.length > 0;
}, [settings.providers]);
const value = {
settings,
updateSettings,
setProvider,
removeProvider,
setProviders,
isConfigured,
};
return (
<DeploySettingsContext.Provider value={value}>
{children}
</DeploySettingsContext.Provider>
);
}
+1 -2
View File
@@ -71,7 +71,7 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
@@ -933,7 +933,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
onFirstInteraction={onFirstInteraction}
/>
)}
</div>
+26
View File
@@ -0,0 +1,26 @@
import { createContext } from 'react';
export interface DeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel';
apiKey?: string; // Not used for Shakespeare Deploy
siteId?: string; // For Netlify
projectId?: string; // For Vercel
teamId?: string; // For Vercel
}
export interface DeploySettings {
providers: DeployProvider[];
defaultProviderId?: string;
}
export interface DeploySettingsContextType {
settings: DeploySettings;
updateSettings: (settings: Partial<DeploySettings>) => void;
setProvider: (provider: DeployProvider) => void;
removeProvider: (id: string) => void;
setProviders: (providers: DeployProvider[]) => void;
isConfigured: boolean;
}
export const DeploySettingsContext = createContext<DeploySettingsContextType | undefined>(undefined);
+10
View File
@@ -0,0 +1,10 @@
import { useContext } from 'react';
import { DeploySettingsContext } from '@/contexts/DeploySettingsContext';
export function useDeploySettings() {
const context = useContext(DeploySettingsContext);
if (!context) {
throw new Error('useDeploySettings must be used within DeploySettingsProvider');
}
return context;
}
+73
View File
@@ -0,0 +1,73 @@
import { useState, useEffect, useCallback } from 'react';
import { useFS } from './useFS';
export interface ProjectDeploySettings {
providerId?: string;
netlify?: {
siteId?: string;
};
vercel?: {
teamId?: string;
projectId?: string;
};
}
/**
* Hook to manage project-specific deployment settings
* Stores settings in .git/shakespeare/deploy.json
*/
export function useProjectDeploySettings(projectId: string) {
const fs = useFS();
const [settings, setSettings] = useState<ProjectDeploySettings>({});
const [isLoading, setIsLoading] = useState(true);
const settingsPath = `/projects/${projectId}/.git/shakespeare/deploy.json`;
const loadSettings = useCallback(async () => {
try {
setIsLoading(true);
const content = await fs.fs.readFile(settingsPath, 'utf8');
setSettings(JSON.parse(content as string));
} catch {
// File doesn't exist or is invalid, use empty settings
setSettings({});
} finally {
setIsLoading(false);
}
}, [fs.fs, settingsPath]);
useEffect(() => {
loadSettings();
}, [loadSettings]);
const saveSettings = async (newSettings: ProjectDeploySettings) => {
try {
// Ensure .git/shakespeare directory exists
const shakespeareDir = `/projects/${projectId}/.git/shakespeare`;
try {
await fs.fs.stat(shakespeareDir);
} catch {
await fs.fs.mkdir(shakespeareDir, { recursive: true });
}
// Save settings
await fs.fs.writeFile(settingsPath, JSON.stringify(newSettings, null, 2), 'utf8');
setSettings(newSettings);
} catch (error) {
console.error('Failed to save deploy settings:', error);
throw error;
}
};
const updateSettings = async (updates: Partial<ProjectDeploySettings>) => {
const newSettings = { ...settings, ...updates };
await saveSettings(newSettings);
};
return {
settings,
isLoading,
updateSettings,
saveSettings,
};
}
@@ -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'),
+382
View File
@@ -0,0 +1,382 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ArrowLeft, Trash2, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate, Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel';
name: string;
description: string;
requiresNostr?: boolean;
apiKeyLabel?: string;
apiKeyURL?: string;
fields?: Array<{
key: string;
label: string;
placeholder: string;
type?: 'text' | 'password';
}>;
}
const PRESET_PROVIDERS: PresetProvider[] = [
{
id: 'shakespeare',
type: 'shakespeare',
name: 'Shakespeare Deploy',
description: 'Deploy to Shakespeare hosting with Nostr authentication',
requiresNostr: true,
},
{
id: 'netlify',
type: 'netlify',
name: 'Netlify',
description: 'Deploy to Netlify with personal access token',
apiKeyLabel: 'Personal Access Token',
apiKeyURL: 'https://app.netlify.com/user/applications#personal-access-tokens',
fields: [
{
key: 'siteId',
label: 'Site ID (Optional)',
placeholder: 'Leave empty to create new site',
type: 'text',
},
],
},
{
id: 'vercel',
type: 'vercel',
name: 'Vercel',
description: 'Deploy to Vercel with access token',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://vercel.com/account/tokens',
fields: [
{
key: 'teamId',
label: 'Team ID (Optional)',
placeholder: 'Leave empty for personal account',
type: 'text',
},
{
key: 'projectId',
label: 'Project ID (Optional)',
placeholder: 'Leave empty to create new project',
type: 'text',
},
],
},
];
export function DeploySettings() {
const { t } = useTranslation();
const { settings, setProvider, removeProvider } = useDeploySettings();
const { user } = useCurrentUser();
const isMobile = useIsMobile();
const navigate = useNavigate();
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [presetFields, setPresetFields] = useState<Record<string, Record<string, string>>>({});
const handleAddPresetProvider = (preset: PresetProvider) => {
// For Shakespeare, just check if user is logged in
if (preset.requiresNostr && !user) {
return;
}
const apiKey = presetApiKeys[preset.id];
// For non-Shakespeare providers, require API key
if (!preset.requiresNostr && !apiKey?.trim()) {
return;
}
const newProvider: DeployProvider = {
id: preset.id,
type: preset.type,
apiKey: preset.requiresNostr ? undefined : apiKey?.trim(),
};
// Add any additional fields
const fields = presetFields[preset.id] || {};
Object.entries(fields).forEach(([key, value]) => {
if (value.trim()) {
newProvider[key as keyof DeployProvider] = value.trim() as never;
}
});
setProvider(newProvider);
// Clear inputs
setPresetApiKeys(prev => ({ ...prev, [preset.id]: '' }));
setPresetFields(prev => ({ ...prev, [preset.id]: {} }));
};
const handleRemoveProvider = (id: string) => {
removeProvider(id);
};
const handleUpdateProvider = (provider: DeployProvider) => {
setProvider(provider);
};
const handleFieldChange = (presetId: string, fieldKey: string, value: string) => {
setPresetFields(prev => ({
...prev,
[presetId]: {
...(prev[presetId] || {}),
[fieldKey]: value,
},
}));
};
const configuredProviderIds = settings.providers.map(p => p.id);
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
return (
<div className="p-6 space-y-6">
{isMobile && (
<div className="space-y-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings')}
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Rocket className="h-6 w-6 text-primary" />
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
</p>
</div>
</div>
)}
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Rocket className="h-6 w-6 text-primary" />
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
</p>
</div>
)}
<div className="space-y-6">
{/* Configured Providers */}
{settings.providers.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">{t('configuredProviders')}</h4>
<Accordion type="multiple" className="w-full space-y-2">
{settings.providers.map((provider) => {
const preset = PRESET_PROVIDERS.find(p => p.id === provider.id);
return (
<AccordionItem key={provider.id} value={provider.id} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center justify-between w-full mr-3">
<div className="flex items-center gap-2">
<span className="font-medium">
{preset?.name || provider.id}
</span>
{provider.type === 'shakespeare' && (
<Badge variant="outline">Nostr</Badge>
)}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemoveProvider(provider.id);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
{provider.type === 'shakespeare' ? (
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
) : (
<>
<div className="grid gap-2">
<Label htmlFor={`${provider.id}-apiKey`}>
{preset?.apiKeyLabel || t('apiKey')}
</Label>
<PasswordInput
id={`${provider.id}-apiKey`}
placeholder={t('enterApiKey')}
value={provider.apiKey || ''}
onChange={(e) => handleUpdateProvider({ ...provider, apiKey: e.target.value })}
/>
</div>
{/* Additional fields based on provider type */}
{preset?.fields?.map((field) => (
<div key={field.key} className="grid gap-2">
<Label htmlFor={`${provider.id}-${field.key}`}>
{field.label}
</Label>
{field.type === 'password' ? (
<PasswordInput
id={`${provider.id}-${field.key}`}
placeholder={field.placeholder}
value={(provider[field.key as keyof DeployProvider] as string) || ''}
onChange={(e) => handleUpdateProvider({
...provider,
[field.key]: e.target.value,
})}
/>
) : (
<Input
id={`${provider.id}-${field.key}`}
placeholder={field.placeholder}
value={(provider[field.key as keyof DeployProvider] as string) || ''}
onChange={(e) => handleUpdateProvider({
...provider,
[field.key]: e.target.value,
})}
/>
)}
</div>
))}
</>
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</div>
)}
{/* Available Preset Providers */}
{availablePresets.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => {
const isNostrPreset = preset.requiresNostr;
const isLoggedIntoNostr = !!user;
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="space-y-1">
<h5 className="font-medium">{preset.name}</h5>
<p className="text-xs text-muted-foreground">{preset.description}</p>
</div>
{preset.apiKeyURL && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground whitespace-nowrap ml-2"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="space-y-3">
{!preset.requiresNostr && (
<div className="grid gap-2">
<Label htmlFor={`preset-${preset.id}-apiKey`}>
{preset.apiKeyLabel || t('apiKey')}
</Label>
<PasswordInput
id={`preset-${preset.id}-apiKey`}
placeholder={t('enterApiKey')}
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
/>
</div>
)}
{/* Additional fields */}
{preset.fields?.map((field) => (
<div key={field.key} className="grid gap-2">
<Label htmlFor={`preset-${preset.id}-${field.key}`}>
{field.label}
</Label>
{field.type === 'password' ? (
<PasswordInput
id={`preset-${preset.id}-${field.key}`}
placeholder={field.placeholder}
value={presetFields[preset.id]?.[field.key] || ''}
onChange={(e) => handleFieldChange(preset.id, field.key, e.target.value)}
/>
) : (
<Input
id={`preset-${preset.id}-${field.key}`}
placeholder={field.placeholder}
value={presetFields[preset.id]?.[field.key] || ''}
onChange={(e) => handleFieldChange(preset.id, field.key, e.target.value)}
/>
)}
</div>
))}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && !presetApiKeys[preset.id]?.trim())
}
className="w-full gap-2"
>
<Check className="h-4 w-4" />
{t('add')}
</Button>
</div>
)}
</div>
);
})}
</div>
</div>
)}
</div>
</div>
);
}
export default DeploySettings;