DeployProvider -> DeployAdapter, lib/deploy-providers -> lib/deploy

This commit is contained in:
Alex Gleason committed 2025-10-18 17:29:24 -05:00
1 parent 2bb07a2e5a
commit 52a9289c5b
11 files changed
+35 -257

No files matched your search

+9 -9
View File
@@ -23,8 +23,8 @@ import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { ShakespeareDeployProvider, NetlifyDeployProvider, VercelDeployProvider, DeployProvider } from '@/lib/deploy-providers';
import type { DeployProvider as DeployProviderType } from '@/contexts/DeploySettingsContext';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, DeployAdapter } from '@/lib/deploy';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import { Link } from 'react-router-dom';
interface DeployDialogProps {
@@ -80,13 +80,13 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
try {
const projectPath = `/projects/${projectId}`;
let provider: DeployProvider;
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
provider = new ShakespeareDeployProvider({
adapter = new ShakespeareAdapter({
signer: user.signer,
});
} else if (selectedProvider.type === 'netlify') {
@@ -95,7 +95,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
}
// Update provider with site ID if provided
const updatedProvider: DeployProviderType = {
const updatedProvider: DeployProvider = {
...selectedProvider,
siteId: netlifyFields.siteId || selectedProvider.siteId,
};
@@ -104,7 +104,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setProvider(updatedProvider);
}
provider = new NetlifyDeployProvider({
adapter = new NetlifyAdapter({
apiKey: selectedProvider.apiKey,
siteId: updatedProvider.siteId,
});
@@ -114,7 +114,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
}
// Update provider with team/project ID if provided
const updatedProvider: DeployProviderType = {
const updatedProvider: DeployProvider = {
...selectedProvider,
teamId: vercelFields.teamId || selectedProvider.teamId,
projectId: vercelFields.projectId || selectedProvider.projectId,
@@ -127,7 +127,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setProvider(updatedProvider);
}
provider = new VercelDeployProvider({
adapter = new VercelAdapter({
apiKey: selectedProvider.apiKey,
teamId: updatedProvider.teamId,
projectId: updatedProvider.projectId,
@@ -136,7 +136,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
throw new Error('Unknown provider type');
}
const result = await provider.deploy({
const result = await adapter.deploy({
projectId,
projectName,
fs,
-26
View File
@@ -1,26 +0,0 @@
import { useMutation } from "@tanstack/react-query";
import { deployProject } from "@/lib/deploy";
import { useFS } from "./useFS";
import { useAppContext } from "./useAppContext";
import { useCurrentUser } from "./useCurrentUser";
export function useDeployProject(projectId: string) {
const { fs } = useFS();
const { user } = useCurrentUser();
const { config } = useAppContext();
return useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
return await deployProject({
fs,
projectId: projectId,
deployServer: config.deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
});
},
});
}
-4
View File
@@ -1,4 +0,0 @@
export * from './types';
export * from './ShakespeareDeployProvider';
export * from './NetlifyDeployProvider';
export * from './VercelDeployProvider';
-92
View File
@@ -1,92 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { deployProject } from './deploy';
import type { JSRuntimeFS } from './JSRuntime';
import type { NostrSigner } from '@nostrify/nostrify';
// Mock JSZip
vi.mock('jszip', () => {
return {
default: vi.fn().mockImplementation(() => ({
folder: vi.fn().mockReturnValue({
file: vi.fn(),
}),
file: vi.fn(),
generateAsync: vi.fn().mockResolvedValue(new Blob()),
})),
};
});
// Mock NIP98Client
vi.mock('@nostrify/nostrify', () => ({
NIP98Client: vi.fn().mockImplementation(() => ({
fetch: vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
}),
})),
}));
describe('deployProject', () => {
let mockFS: JSRuntimeFS;
let mockSigner: NostrSigner;
beforeEach(() => {
mockFS = {
readFile: vi.fn().mockResolvedValue('mock file content'),
readdir: vi.fn().mockResolvedValue([]),
writeFile: vi.fn().mockResolvedValue(undefined),
mkdir: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
lstat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
readlink: vi.fn().mockResolvedValue(''),
symlink: vi.fn().mockResolvedValue(undefined),
} as JSRuntimeFS;
mockSigner = {} as NostrSigner;
});
it('should construct hostname from projectId and deployServer by default', async () => {
const result = await deployProject({
projectId: 'test-project',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/test-project',
signer: mockSigner,
});
expect(result.hostname).toBe('test-project.shakespeare.wtf');
expect(result.url).toBe('https://test-project.shakespeare.wtf');
});
it('should use customHostname when provided', async () => {
const result = await deployProject({
projectId: 'test-project',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/test-project',
signer: mockSigner,
customHostname: 'my-custom-domain.example.com',
});
expect(result.hostname).toBe('my-custom-domain.example.com');
expect(result.url).toBe('https://my-custom-domain.example.com');
});
it('should handle custom subdomain with same deploy server', async () => {
const result = await deployProject({
projectId: 'original-id',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/original-id',
signer: mockSigner,
customHostname: 'custom-name.shakespeare.wtf',
});
expect(result.hostname).toBe('custom-name.shakespeare.wtf');
expect(result.url).toBe('https://custom-name.shakespeare.wtf');
});
});
-107
View File
@@ -1,107 +0,0 @@
import JSZip from 'jszip';
import { NIP98Client } from '@nostrify/nostrify';
import type { NostrSigner } from '@nostrify/nostrify';
import type { JSRuntimeFS } from './JSRuntime';
export interface DeployOptions {
/** Project ID to use for hostname construction */
projectId: string;
/** Deploy server domain (e.g., "shakespeare.wtf") */
deployServer: string;
/** Filesystem instance containing the project */
fs: JSRuntimeFS;
/** Path to the project directory */
projectPath: string;
/** Nostr signer for NIP-98 authentication */
signer: NostrSigner;
/** Custom hostname to use instead of constructing from projectId.deployServer */
customHostname?: string;
}
export interface DeployResult {
/** The deployed URL */
url: string;
/** The hostname used */
hostname: string;
}
/**
* Deploy a project by creating a ZIP of the dist directory and uploading it
* to the deployment server using NIP-98 authentication.
*/
export async function deployProject(options: DeployOptions): Promise<DeployResult> {
const { projectId, deployServer, fs, projectPath, signer, customHostname } = options;
// 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 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,
hostname,
};
}
/**
* Recursively add all files in a directory to a JSZip instance
*/
async function addDirectoryToZip(fs: JSRuntimeFS, 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 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}`);
}
}
@@ -1,5 +1,5 @@
import JSZip from 'jszip';
import type { DeployProvider, DeployOptions, DeployResult, NetlifyDeployConfig } from './types';
import type { DeployAdapter, DeployOptions, DeployResult, NetlifyDeployConfig } from './types';
interface NetlifySite {
id: string;
@@ -17,10 +17,10 @@ interface NetlifyBuildResponse {
}
/**
* Netlify Deploy Provider
* Netlify Deploy Adapter
* Uses Netlify API with personal access token
*/
export class NetlifyDeployProvider implements DeployProvider {
export class NetlifyAdapter implements DeployAdapter {
private config: NetlifyDeployConfig;
constructor(config: NetlifyDeployConfig) {
@@ -1,12 +1,12 @@
import JSZip from 'jszip';
import { NIP98Client } from '@nostrify/nostrify';
import type { DeployProvider, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
/**
* Shakespeare Deploy Provider
* Shakespeare Deploy Adapter
* Uses NIP-98 authentication with Nostr signer
*/
export class ShakespeareDeployProvider implements DeployProvider {
export class ShakespeareAdapter implements DeployAdapter {
private config: ShakespeareDeployConfig;
constructor(config: ShakespeareDeployConfig) {
@@ -1,4 +1,4 @@
import type { DeployProvider, DeployOptions, DeployResult, VercelDeployConfig } from './types';
import type { DeployAdapter, DeployOptions, DeployResult, VercelDeployConfig } from './types';
interface VercelFile {
file: string;
@@ -13,10 +13,10 @@ interface VercelDeployment {
}
/**
* Vercel Deploy Provider
* Vercel Deploy Adapter
* Uses Vercel REST API with access token
*/
export class VercelDeployProvider implements DeployProvider {
export class VercelAdapter implements DeployAdapter {
private config: VercelDeployConfig;
constructor(config: VercelDeployConfig) {
@@ -102,7 +102,7 @@ export class VercelDeployProvider implements DeployProvider {
try {
// Read file content
const fileContent = await fs.readFile(fullPath);
// Convert to base64 for Vercel API
let base64Content: string;
if (typeof fileContent === 'string') {
+4
View File
@@ -0,0 +1,4 @@
export * from './types';
export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
@@ -19,7 +19,7 @@ export interface DeployResult {
metadata?: Record<string, unknown>;
}
export interface DeployProvider {
export interface DeployAdapter {
/** Deploy a project */
deploy(options: DeployOptions): Promise<DeployResult>;
}
+11 -8
View File
@@ -2,7 +2,7 @@ import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { deployProject } from "../deploy";
import { ShakespeareAdapter } from "../deploy";
import type { NostrSigner } from "@nostrify/nostrify";
interface DeployProjectParams {
@@ -47,16 +47,19 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
throw new Error(`❌ Could not find index.html in dist directory. Please build the project first using the build tool.`);
}
// Deploy the project
const result = await deployProject({
projectId: this.projectId,
deployServer,
fs: this.fs,
projectPath: this.cwd,
// Deploy the project using ShakespeareAdapter
const adapter = new ShakespeareAdapter({
signer: this.signer,
deployServer,
});
return `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n📡 Hostname: ${result.hostname}\n\n🚀 Your project is now live and accessible to anyone with the URL!`;
const result = await adapter.deploy({
projectId: this.projectId,
fs: this.fs,
projectPath: this.cwd,
});
return `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\n🚀 Your project is now live and accessible to anyone with the URL!`;
} catch (error) {
throw new Error(`❌ Deployment failed: ${String(error)}`);
}