Netlify deploy improvements

This commit is contained in:
Alex Gleason committed 2025-10-18 19:42:04 -05:00
1 parent b39e52487c
commit 6eb6bde5bb
9 files changed
+482 -71

No files matched your search

+133 -12
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react'; import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { import {
@@ -25,6 +25,10 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS'; import { useFS } from '@/hooks/useFS';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, DeployAdapter } from '@/lib/deploy'; import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import type { ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
interface DeployDialogProps { interface DeployDialogProps {
projectId: string; projectId: string;
@@ -33,6 +37,20 @@ interface DeployDialogProps {
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
} }
interface ShakespeareFormData {
subdomain: string;
}
interface NetlifyFormData {
siteId: string;
siteName: string;
}
interface VercelFormData {
projectName: string;
teamId: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) { export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { settings } = useDeploySettings(); const { settings } = useDeploySettings();
@@ -45,6 +63,19 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null); const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
subdomain: projectId,
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
siteName: projectName || projectId,
});
const [vercelForm, setVercelForm] = useState<VercelFormData>({
projectName: projectName || projectId,
teamId: '',
});
// Load project settings when dialog opens // Load project settings when dialog opens
useEffect(() => { useEffect(() => {
if (open && projectSettings.providerId) { if (open && projectSettings.providerId) {
@@ -70,27 +101,41 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
if (!user) { if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy'); throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
} }
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
adapter = new ShakespeareAdapter({ adapter = new ShakespeareAdapter({
fs,
signer: user.signer, signer: user.signer,
host: selectedProvider.host, host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
}); });
} else if (selectedProvider.type === 'netlify') { } else if (selectedProvider.type === 'netlify') {
if (!selectedProvider.apiKey) { const netlifyProvider = selectedProvider as NetlifyProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required'); throw new Error('Netlify API key is required');
} }
// If siteId is empty, we're creating a new site, so only pass siteName
// If siteId is set, we're updating an existing site
adapter = new NetlifyAdapter({ adapter = new NetlifyAdapter({
apiKey: selectedProvider.apiKey, fs,
baseURL: selectedProvider.baseURL, apiKey: netlifyProvider.apiKey,
baseURL: netlifyProvider.baseURL,
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
siteId: netlifyForm.siteId || undefined,
}); });
} else if (selectedProvider.type === 'vercel') { } else if (selectedProvider.type === 'vercel') {
if (!selectedProvider.apiKey) { const vercelProvider = selectedProvider as VercelProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required'); throw new Error('Vercel API key is required');
} }
adapter = new VercelAdapter({ adapter = new VercelAdapter({
apiKey: selectedProvider.apiKey, fs,
baseURL: selectedProvider.baseURL, apiKey: vercelProvider.apiKey,
baseURL: vercelProvider.baseURL,
teamId: vercelForm.teamId || undefined,
projectName: vercelForm.projectName || undefined,
}); });
} else { } else {
throw new Error('Unknown provider type'); throw new Error('Unknown provider type');
@@ -98,15 +143,28 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
const result = await adapter.deploy({ const result = await adapter.deploy({
projectId, projectId,
projectName,
fs,
projectPath, projectPath,
}); });
// Save project-specific settings // Save project-specific settings
await updateProjectSettings({ const projectSettingsUpdate: typeof projectSettings = {
providerId: selectedProviderName, providerId: selectedProviderName,
}); };
if (selectedProvider.type === 'netlify' && result.metadata?.siteId) {
projectSettingsUpdate.netlify = {
siteId: result.metadata.siteId as string,
};
}
if (selectedProvider.type === 'vercel') {
projectSettingsUpdate.vercel = {
teamId: vercelForm.teamId || undefined,
projectId: vercelForm.projectName || undefined,
};
}
await updateProjectSettings(projectSettingsUpdate);
setDeployResult(result); setDeployResult(result);
} catch (err) { } catch (err) {
@@ -120,9 +178,70 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setSelectedProviderName(''); setSelectedProviderName('');
setDeployResult(null); setDeployResult(null);
setError(null); setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNetlifyForm({ siteId: '', siteName: projectName || projectId });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
onOpenChange(false); onOpenChange(false);
}; };
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
setVercelForm({ projectName, teamId });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
/>
);
}
if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
return (
<NetlifyDeployForm
apiKey={netlifyProvider.apiKey}
baseURL={netlifyProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedSiteId={projectSettings.netlify?.siteId}
onSiteChange={handleNetlifySiteChange}
/>
);
}
if (selectedProvider.type === 'vercel') {
return (
<VercelDeployForm
projectId={projectId}
projectName={projectName}
savedTeamId={projectSettings.vercel?.teamId}
savedProjectName={projectSettings.vercel?.projectId}
onConfigChange={handleVercelConfigChange}
/>
);
}
return null;
};
return ( return (
<Dialog open={open} onOpenChange={handleClose}> <Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]"> <DialogContent className="sm:max-w-[500px]">
@@ -203,6 +322,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
</Select> </Select>
</div> </div>
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && ( {selectedProvider?.type === 'shakespeare' && !user && (
<Alert> <Alert>
<AlertCircle className="h-4 w-4" /> <AlertCircle className="h-4 w-4" />
+179
View File
@@ -0,0 +1,179 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
interface NetlifySite {
id: string;
site_id: string;
name: string;
url: string;
admin_url: string;
}
interface NetlifyDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedSiteId?: string;
onSiteChange: (siteId: string, siteName: string) => void;
}
export function NetlifyDeployForm({
apiKey,
baseURL = 'https://api.netlify.com/api/v1',
projectId,
projectName,
savedSiteId,
onSiteChange,
}: NetlifyDeployFormProps) {
const [sites, setSites] = useState<NetlifySite[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedSiteId, setSelectedSiteId] = useState<string>('new');
const [newSiteName, setNewSiteName] = useState(projectName || projectId);
const fetchSites = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch(`${baseURL}/sites`, {
headers: {
'Authorization': `Bearer ${apiKey}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch sites: ${response.status} ${response.statusText}`);
}
const data: NetlifySite[] = await response.json();
setSites(data);
// If there's a saved site ID and it exists in the list, select it
// Otherwise keep "new" selected
if (savedSiteId && data.some(s => s.id === savedSiteId)) {
setSelectedSiteId(savedSiteId);
} else {
setSelectedSiteId('new');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch sites');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedSiteId]);
useEffect(() => {
fetchSites();
}, [fetchSites]);
useEffect(() => {
if (selectedSiteId === 'new') {
onSiteChange('', newSiteName);
} else {
const site = sites.find(s => s.id === selectedSiteId);
if (site) {
onSiteChange(site.id, site.name);
}
}
}, [selectedSiteId, newSiteName, sites, onSiteChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Site</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedSite = sites.find(s => s.id === selectedSiteId);
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="netlify-site">Select Site</Label>
<Select value={selectedSiteId} onValueChange={setSelectedSiteId}>
<SelectTrigger id="netlify-site">
<SelectValue placeholder="Choose a site..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new site
</div>
</SelectItem>
{sites.map((site) => (
<SelectItem key={site.id} value={site.id}>
{site.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedSiteId === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-site-name">New Site Name</Label>
<Input
id="new-site-name"
value={newSiteName}
onChange={(e) => setNewSiteName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
Domain: <span className="font-mono">{newSiteName || projectId}.netlify.app</span>
</p>
<p className="text-xs text-muted-foreground">
A new site will be created when you deploy
</p>
</div>
) : selectedSite ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedSite.name}</p>
<p className="text-xs text-muted-foreground font-mono">{selectedSite.url}</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(selectedSite.admin_url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will update this existing site
</p>
</div>
) : null}
</div>
);
}
@@ -0,0 +1,40 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
onSubdomainChange: (subdomain: string) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
onSubdomainChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(projectId);
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
<Input
id="shakespeare-subdomain"
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
/>
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
</div>
</div>
);
}
@@ -0,0 +1,55 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface VercelDeployFormProps {
projectId: string;
projectName?: string;
savedTeamId?: string;
savedProjectName?: string;
onConfigChange: (projectName: string, teamId: string) => void;
}
export function VercelDeployForm({
projectId,
projectName: initialProjectName,
savedTeamId,
savedProjectName,
onConfigChange,
}: VercelDeployFormProps) {
const [projectName, setProjectName] = useState(savedProjectName || initialProjectName || projectId);
const [teamId, setTeamId] = useState(savedTeamId || '');
useEffect(() => {
onConfigChange(projectName, teamId);
}, [projectName, teamId, onConfigChange]);
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="vercel-project-name">Project Name</Label>
<Input
id="vercel-project-name"
value={projectName}
onChange={(e) => setProjectName(e.target.value)}
placeholder={initialProjectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{projectName || projectId}.vercel.app</span>
</p>
</div>
<div className="space-y-2">
<Label htmlFor="vercel-team-id">Team ID (optional)</Label>
<Input
id="vercel-team-id"
value={teamId}
onChange={(e) => setTeamId(e.target.value)}
placeholder="Leave empty for personal account"
/>
<p className="text-xs text-muted-foreground">
Deploy to a team account instead of your personal account
</p>
</div>
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
+26 -20
View File
@@ -1,4 +1,5 @@
import JSZip from 'jszip'; import JSZip from 'jszip';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NetlifyDeployConfig } from './types'; import type { DeployAdapter, DeployOptions, DeployResult, NetlifyDeployConfig } from './types';
interface NetlifySite { interface NetlifySite {
@@ -21,50 +22,55 @@ interface NetlifyBuildResponse {
* Uses Netlify API with personal access token * Uses Netlify API with personal access token
*/ */
export class NetlifyAdapter implements DeployAdapter { export class NetlifyAdapter implements DeployAdapter {
private config: NetlifyDeployConfig; private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string; private baseURL: string;
private siteName?: string;
private siteId?: string;
constructor(config: NetlifyDeployConfig) { constructor(config: NetlifyDeployConfig) {
this.config = config; this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://api.netlify.com/api/v1'; this.baseURL = config.baseURL || 'https://api.netlify.com/api/v1';
this.siteName = config.siteName;
this.siteId = config.siteId;
} }
async deploy(options: DeployOptions): Promise<DeployResult> { async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectName, fs, projectPath } = options; const { projectId, projectPath } = options;
const { apiKey, siteId, siteName } = this.config;
// Check if dist directory exists and contains index.html // Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`; const distPath = `${projectPath}/dist`;
try { try {
await fs.readFile(`${distPath}/index.html`, 'utf8'); await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch { } catch {
throw new Error('No index.html found in dist directory. Please build the project first.'); throw new Error('No index.html found in dist directory. Please build the project first.');
} }
// Get or create site // Get or create site
let activeSiteId = siteId; let activeSiteId = this.siteId;
let siteUrl = ''; let siteUrl = '';
if (!activeSiteId) { if (!activeSiteId) {
// Create new site // Create new site
const site = await this.createSite(apiKey, siteName || projectName || projectId); const site = await this.createSite(this.siteName || projectId);
activeSiteId = site.id; activeSiteId = site.id;
siteUrl = site.url; siteUrl = site.url;
} else { } else {
// Get existing site URL // Get existing site URL
const site = await this.getSite(apiKey, activeSiteId); const site = await this.getSite(activeSiteId);
siteUrl = site.url; siteUrl = site.url;
} }
// Create ZIP of dist directory // Create ZIP of dist directory
const zip = new JSZip(); const zip = new JSZip();
await this.addDirectoryToZip(fs, distPath, zip); await this.addDirectoryToZip(distPath, zip);
// Generate ZIP blob // Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
// Deploy to Netlify // Deploy to Netlify
await this.triggerDeploy(apiKey, activeSiteId, zipBlob); await this.triggerDeploy(activeSiteId, zipBlob);
return { return {
url: siteUrl, url: siteUrl,
@@ -75,11 +81,11 @@ export class NetlifyAdapter implements DeployAdapter {
}; };
} }
private async createSite(apiKey: string, name: string): Promise<NetlifySite> { private async createSite(name: string): Promise<NetlifySite> {
const response = await fetch(`${this.baseURL}/sites`, { const response = await fetch(`${this.baseURL}/sites`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${apiKey}`, 'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
@@ -96,11 +102,11 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json(); return response.json();
} }
private async getSite(apiKey: string, siteId: string): Promise<NetlifySite> { private async getSite(siteId: string): Promise<NetlifySite> {
const response = await fetch(`${this.baseURL}/sites/${siteId}`, { const response = await fetch(`${this.baseURL}/sites/${siteId}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'Authorization': `Bearer ${apiKey}`, 'Authorization': `Bearer ${this.apiKey}`,
}, },
}); });
@@ -112,11 +118,11 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json(); return response.json();
} }
private async triggerDeploy(apiKey: string, siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> { private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
const response = await fetch(`${this.baseURL}/sites/${siteId}/deploys`, { const response = await fetch(`${this.baseURL}/sites/${siteId}/deploys`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${apiKey}`, 'Authorization': `Bearer ${this.apiKey}`,
}, },
body: zipBlob, body: zipBlob,
}); });
@@ -129,9 +135,9 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json(); return response.json();
} }
private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise<void> { private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try { try {
const entries = await fs.readdir(dirPath, { withFileTypes: true }); const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) { for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`; const fullPath = `${dirPath}/${entry.name}`;
@@ -140,12 +146,12 @@ export class NetlifyAdapter implements DeployAdapter {
// Create folder in zip and recursively add its contents // Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name); const folder = zip.folder(entry.name);
if (folder) { if (folder) {
await this.addDirectoryToZip(fs, fullPath, folder); await this.addDirectoryToZip(fullPath, folder);
} }
} else if (entry.isFile()) { } else if (entry.isFile()) {
// Add file to zip // Add file to zip
try { try {
const fileContent = await fs.readFile(fullPath); const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent); zip.file(entry.name, fileContent);
} catch { } catch {
console.warn(`Failed to read file ${fullPath}`); console.warn(`Failed to read file ${fullPath}`);
+20 -15
View File
@@ -1,5 +1,6 @@
import JSZip from 'jszip'; import JSZip from 'jszip';
import { NIP98Client } from '@nostrify/nostrify'; import { NIP98Client } from '@nostrify/nostrify';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types'; import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
/** /**
@@ -7,35 +8,39 @@ import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfi
* Uses NIP-98 authentication with Nostr signer * Uses NIP-98 authentication with Nostr signer
*/ */
export class ShakespeareAdapter implements DeployAdapter { export class ShakespeareAdapter implements DeployAdapter {
private config: ShakespeareDeployConfig; private fs: JSRuntimeFS;
private signer: ShakespeareDeployConfig['signer'];
private host: string; private host: string;
private subdomain?: string;
constructor(config: ShakespeareDeployConfig) { constructor(config: ShakespeareDeployConfig) {
this.config = config; this.fs = config.fs;
this.signer = config.signer;
this.host = config.host || 'shakespeare.wtf'; this.host = config.host || 'shakespeare.wtf';
this.subdomain = config.subdomain;
} }
async deploy(options: DeployOptions): Promise<DeployResult> { async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, fs, projectPath } = options; const { projectId, projectPath } = options;
const { signer, deployServer, customHostname } = this.config;
// Use custom hostname if provided, otherwise construct from projectId.host // Use custom subdomain if provided, otherwise construct from projectId
const effectiveHost = deployServer || this.host; const hostname = this.subdomain
const hostname = customHostname || `${projectId}.${effectiveHost}`; ? `${this.subdomain}.${this.host}`
const deployUrl = `https://${effectiveHost}/deploy`; : `${projectId}.${this.host}`;
const deployUrl = `https://${this.host}/deploy`;
const siteUrl = `https://${hostname}`; const siteUrl = `https://${hostname}`;
// Check if dist directory exists and contains index.html // Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`; const distPath = `${projectPath}/dist`;
try { try {
await fs.readFile(`${distPath}/index.html`, 'utf8'); await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch { } catch {
throw new Error('No index.html found in dist directory. Please build the project first.'); throw new Error('No index.html found in dist directory. Please build the project first.');
} }
// Create ZIP of dist directory // Create ZIP of dist directory
const zip = new JSZip(); const zip = new JSZip();
await this.addDirectoryToZip(fs, distPath, zip); await this.addDirectoryToZip(distPath, zip);
// Generate ZIP blob // Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' }); const zipBlob = await zip.generateAsync({ type: 'blob' });
@@ -46,7 +51,7 @@ export class ShakespeareAdapter implements DeployAdapter {
formData.append('file', zipBlob, `${projectId}.zip`); formData.append('file', zipBlob, `${projectId}.zip`);
// Create NIP-98 authenticated client and deploy // Create NIP-98 authenticated client and deploy
const nip98Client = new NIP98Client({ signer }); const nip98Client = new NIP98Client({ signer: this.signer });
const response = await nip98Client.fetch(deployUrl, { const response = await nip98Client.fetch(deployUrl, {
method: 'POST', method: 'POST',
body: formData, body: formData,
@@ -66,9 +71,9 @@ export class ShakespeareAdapter implements DeployAdapter {
}; };
} }
private async addDirectoryToZip(fs: DeployOptions['fs'], dirPath: string, zip: JSZip): Promise<void> { private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try { try {
const entries = await fs.readdir(dirPath, { withFileTypes: true }); const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) { for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`; const fullPath = `${dirPath}/${entry.name}`;
@@ -77,12 +82,12 @@ export class ShakespeareAdapter implements DeployAdapter {
// Create folder in zip and recursively add its contents // Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name); const folder = zip.folder(entry.name);
if (folder) { if (folder) {
await this.addDirectoryToZip(fs, fullPath, folder); await this.addDirectoryToZip(fullPath, folder);
} }
} else if (entry.isFile()) { } else if (entry.isFile()) {
// Add file to zip // Add file to zip
try { try {
const fileContent = await fs.readFile(fullPath); const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent); zip.file(entry.name, fileContent);
} catch { } catch {
console.warn(`Failed to read file ${fullPath}`); console.warn(`Failed to read file ${fullPath}`);
+19 -14
View File
@@ -1,3 +1,4 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, VercelDeployConfig } from './types'; import type { DeployAdapter, DeployOptions, DeployResult, VercelDeployConfig } from './types';
interface VercelFile { interface VercelFile {
@@ -17,33 +18,38 @@ interface VercelDeployment {
* Uses Vercel REST API with access token * Uses Vercel REST API with access token
*/ */
export class VercelAdapter implements DeployAdapter { export class VercelAdapter implements DeployAdapter {
private config: VercelDeployConfig; private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string; private baseURL: string;
private teamId?: string;
private projectName?: string;
constructor(config: VercelDeployConfig) { constructor(config: VercelDeployConfig) {
this.config = config; this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://api.vercel.com'; this.baseURL = config.baseURL || 'https://api.vercel.com';
this.teamId = config.teamId;
this.projectName = config.projectName;
} }
async deploy(options: DeployOptions): Promise<DeployResult> { async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectName, fs, projectPath } = options; const { projectId, projectPath } = options;
const { apiKey, teamId } = this.config;
// Check if dist directory exists and contains index.html // Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`; const distPath = `${projectPath}/dist`;
try { try {
await fs.readFile(`${distPath}/index.html`, 'utf8'); await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch { } catch {
throw new Error('No index.html found in dist directory. Please build the project first.'); throw new Error('No index.html found in dist directory. Please build the project first.');
} }
// Collect all files from dist directory // Collect all files from dist directory
const files: VercelFile[] = []; const files: VercelFile[] = [];
await this.collectFiles(fs, distPath, '', files); await this.collectFiles(distPath, '', files);
// Create deployment payload // Create deployment payload
const deploymentPayload = { const deploymentPayload = {
name: this.config.projectName || projectName || projectId, name: this.projectName || projectId,
files, files,
projectSettings: { projectSettings: {
framework: null, // Static deployment framework: null, // Static deployment
@@ -53,15 +59,15 @@ export class VercelAdapter implements DeployAdapter {
// Build API URL with optional team parameter // Build API URL with optional team parameter
let apiUrl = `${this.baseURL}/v13/deployments`; let apiUrl = `${this.baseURL}/v13/deployments`;
if (teamId) { if (this.teamId) {
apiUrl += `?teamId=${teamId}`; apiUrl += `?teamId=${this.teamId}`;
} }
// Deploy to Vercel // Deploy to Vercel
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${apiKey}`, 'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify(deploymentPayload), body: JSON.stringify(deploymentPayload),
@@ -85,13 +91,12 @@ export class VercelAdapter implements DeployAdapter {
} }
private async collectFiles( private async collectFiles(
fs: DeployOptions['fs'],
dirPath: string, dirPath: string,
relativePath: string, relativePath: string,
files: VercelFile[] files: VercelFile[]
): Promise<void> { ): Promise<void> {
try { try {
const entries = await fs.readdir(dirPath, { withFileTypes: true }); const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) { for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`; const fullPath = `${dirPath}/${entry.name}`;
@@ -99,11 +104,11 @@ export class VercelAdapter implements DeployAdapter {
if (entry.isDirectory()) { if (entry.isDirectory()) {
// Recursively collect files from subdirectories // Recursively collect files from subdirectories
await this.collectFiles(fs, fullPath, entryRelativePath, files); await this.collectFiles(fullPath, entryRelativePath, files);
} else if (entry.isFile()) { } else if (entry.isFile()) {
try { try {
// Read file content // Read file content
const fileContent = await fs.readFile(fullPath); const fileContent = await this.fs.readFile(fullPath);
// Convert to base64 for Vercel API // Convert to base64 for Vercel API
let base64Content: string; let base64Content: string;
+7 -10
View File
@@ -4,12 +4,8 @@ import type { NostrSigner } from '@nostrify/nostrify';
export interface DeployOptions { export interface DeployOptions {
/** Project ID */ /** Project ID */
projectId: string; projectId: string;
/** Filesystem instance containing the project */
fs: JSRuntimeFS;
/** Path to the project directory */ /** Path to the project directory */
projectPath: string; projectPath: string;
/** Project name */
projectName?: string;
} }
export interface DeployResult { export interface DeployResult {
@@ -25,23 +21,24 @@ export interface DeployAdapter {
} }
export interface ShakespeareDeployConfig { export interface ShakespeareDeployConfig {
fs: JSRuntimeFS;
signer: NostrSigner; signer: NostrSigner;
deployServer?: string;
customHostname?: string;
host?: string; host?: string;
subdomain?: string;
} }
export interface NetlifyDeployConfig { export interface NetlifyDeployConfig {
fs: JSRuntimeFS;
apiKey: string; apiKey: string;
siteId?: string;
siteName?: string;
baseURL?: string; baseURL?: string;
siteName?: string;
siteId?: string;
} }
export interface VercelDeployConfig { export interface VercelDeployConfig {
fs: JSRuntimeFS;
apiKey: string; apiKey: string;
projectId?: string; baseURL?: string;
teamId?: string; teamId?: string;
projectName?: string; projectName?: string;
baseURL?: string;
} }