From 26635a4b6a4d1ab5f013de14e5268e2e6f592dfa Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 7 Sep 2025 17:58:19 -0500 Subject: [PATCH] Deploy with picohost --- src/App.tsx | 1 + src/components/ActionsMenu.tsx | 13 +++ src/components/AppProvider.tsx | 5 +- src/components/AppSettingsDialog.tsx | 108 ++++++++++++++++++++++++ src/components/Shakespeare/ChatPane.tsx | 47 +++++++---- src/contexts/AppContext.ts | 2 + src/lib/deploy.ts | 105 +++++++++++++++++++++++ src/lib/tools/DeployProjectTool.ts | 64 ++++++++++++++ src/pages/ProjectView.tsx | 80 +++++++++--------- src/test/TestApp.tsx | 1 + 10 files changed, 367 insertions(+), 59 deletions(-) create mode 100644 src/components/AppSettingsDialog.tsx create mode 100644 src/lib/deploy.ts create mode 100644 src/lib/tools/DeployProjectTool.ts diff --git a/src/App.tsx b/src/App.tsx index c8cb5169..37c079d0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -40,6 +40,7 @@ const queryClient = new QueryClient({ const defaultConfig: AppConfig = { theme: "light", relayUrl: "wss://relay.primal.net", + deployServer: "shakespeare.wtf", }; const presetRelays = [ diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index ff65fa57..7ae9e73a 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -27,8 +27,10 @@ import { GitBranch, Download, Trash2, + Settings, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; +import { AppSettingsDialog } from '@/components/AppSettingsDialog'; import { useNavigate } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; @@ -220,6 +222,17 @@ export function ActionsMenu({ Git History + + e.preventDefault()} + > + + Settings + + + = z.object({ theme: z.enum(['dark', 'light', 'system']), relayUrl: z.string().url(), + deployServer: z.string().min(1), }); export function AppProvider(props: AppProviderProps) { @@ -88,11 +89,11 @@ function useApplyTheme(theme: Theme) { if (theme !== 'system') return; const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); - + const handleChange = () => { const root = window.document.documentElement; root.classList.remove('light', 'dark'); - + const systemTheme = mediaQuery.matches ? 'dark' : 'light'; root.classList.add(systemTheme); }; diff --git a/src/components/AppSettingsDialog.tsx b/src/components/AppSettingsDialog.tsx new file mode 100644 index 00000000..3960d34f --- /dev/null +++ b/src/components/AppSettingsDialog.tsx @@ -0,0 +1,108 @@ +import { useState } from 'react'; +import { Settings, Save } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { useAppContext } from '@/hooks/useAppContext'; +import { useToast } from '@/hooks/useToast'; + +interface AppSettingsDialogProps { + children?: React.ReactNode; +} + +export function AppSettingsDialog({ children }: AppSettingsDialogProps) { + const { config, updateConfig } = useAppContext(); + const { toast } = useToast(); + const [open, setOpen] = useState(false); + const [deployServer, setDeployServer] = useState(config.deployServer); + + const handleSave = () => { + // Validate deploy server + if (!deployServer.trim()) { + toast({ + title: "Invalid deploy server", + description: "Deploy server cannot be empty.", + variant: "destructive", + }); + return; + } + + // Remove protocol if present + const cleanDeployServer = deployServer.replace(/^https?:\/\//, ''); + + updateConfig((current) => ({ + ...current, + deployServer: cleanDeployServer, + })); + + toast({ + title: "Settings saved", + description: "Your deployment settings have been updated.", + }); + + setOpen(false); + }; + + const handleCancel = () => { + // Reset to current config + setDeployServer(config.deployServer); + setOpen(false); + }; + + return ( + + + {children || ( + + )} + + + + App Settings + + Configure your application preferences and deployment settings. + + + +
+ + + Deployment + + +
+ + setDeployServer(e.target.value)} + placeholder="shakespeare.wtf" + className="font-mono" + /> +

+ Your projects will be deployed to subdomains of this server. + Example: yourproject.{deployServer || 'shakespeare.wtf'} +

+
+
+
+
+ +
+ + +
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 8e63b9c2..6ba81fbb 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -6,6 +6,7 @@ import { Skeleton } from '@/components/ui/skeleton'; import { Send, Square, Loader2 } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { useAIChat } from '@/hooks/useAIChat'; @@ -22,6 +23,7 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; import { GitCommitTool } from '@/lib/tools/GitCommitTool'; import { BuildProjectTool } from '@/lib/tools/BuildProjectTool'; +import { DeployProjectTool } from '@/lib/tools/DeployProjectTool'; import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool'; import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool'; import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool'; @@ -79,25 +81,38 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs: browserFS } = useFS(); + const { user } = useCurrentUser(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; - const customTools = useMemo(() => ({ - git_commit: new GitCommitTool(browserFS, cwd), - text_editor_view: new TextEditorViewTool(browserFS, cwd), - text_editor_write: new TextEditorWriteTool(browserFS, cwd), - text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), - npm_add_package: new NpmAddPackageTool(browserFS, cwd), - npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), - build_project: new BuildProjectTool(browserFS, cwd), - nostr_read_nip: new NostrReadNipTool(), - nostr_fetch_event: new NostrFetchEventTool(), - nostr_read_kind: new NostrReadKindTool(), - nostr_read_tag: new NostrReadTagTool(), - nostr_read_protocol: new NostrReadProtocolTool(), - nostr_read_nips_index: new NostrReadNipsIndexTool(), - nostr_generate_kind: new NostrGenerateKindTool(), - }), [browserFS, cwd]); + const customTools = useMemo(() => { + const baseTools = { + git_commit: new GitCommitTool(browserFS, cwd), + text_editor_view: new TextEditorViewTool(browserFS, cwd), + text_editor_write: new TextEditorWriteTool(browserFS, cwd), + text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), + npm_add_package: new NpmAddPackageTool(browserFS, cwd), + npm_remove_package: new NpmRemovePackageTool(browserFS, cwd), + build_project: new BuildProjectTool(browserFS, cwd), + nostr_read_nip: new NostrReadNipTool(), + nostr_fetch_event: new NostrFetchEventTool(), + nostr_read_kind: new NostrReadKindTool(), + nostr_read_tag: new NostrReadTagTool(), + nostr_read_protocol: new NostrReadProtocolTool(), + nostr_read_nips_index: new NostrReadNipsIndexTool(), + nostr_generate_kind: new NostrGenerateKindTool(), + }; + + // Add deploy tool only if user is logged in + if (user && user.signer) { + return { + ...baseTools, + deploy_project: new DeployProjectTool(browserFS, cwd, user.signer, projectId), + }; + } + + return baseTools; + }, [browserFS, cwd, user, projectId]); // Convert tools to OpenAI format const tools = useMemo(() => { diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index e6cfa261..60a71e4e 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -7,6 +7,8 @@ export interface AppConfig { theme: Theme; /** Selected relay URL */ relayUrl: string; + /** Deploy server domain (e.g., "shakespeare.wtf") */ + deployServer: string; } export interface AppContextType { diff --git a/src/lib/deploy.ts b/src/lib/deploy.ts new file mode 100644 index 00000000..584d9c84 --- /dev/null +++ b/src/lib/deploy.ts @@ -0,0 +1,105 @@ +import JSZip from 'jszip'; +import { NIP98Client } from './NIP98Client'; +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; +} + +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 { + const { projectId, deployServer, fs, projectPath, signer } = options; + + // Construct hostname and URL + const hostname = `${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 { + 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}`); + } +} \ No newline at end of file diff --git a/src/lib/tools/DeployProjectTool.ts b/src/lib/tools/DeployProjectTool.ts new file mode 100644 index 00000000..fe7eff95 --- /dev/null +++ b/src/lib/tools/DeployProjectTool.ts @@ -0,0 +1,64 @@ +import { z } from "zod"; + +import type { Tool } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; +import { deployProject } from "../deploy"; +import type { NostrSigner } from "@nostrify/nostrify"; + +interface DeployProjectParams { + deployServer?: string; +} + +export class DeployProjectTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + private signer: NostrSigner; + private projectId: string; + + readonly description = "Deploy the project to a hosting server using NIP-98 authentication. Creates a ZIP of the dist directory and uploads it to the deployment server. Requires the user to be logged in with Nostr."; + + readonly inputSchema = z.object({ + deployServer: z.string().optional().describe("Deploy server domain (e.g., 'shakespeare.wtf'). If not provided, uses the default configured server."), + }); + + constructor(fs: JSRuntimeFS, cwd: string, signer: NostrSigner, projectId: string) { + this.fs = fs; + this.cwd = cwd; + this.signer = signer; + this.projectId = projectId; + } + + async execute(args: DeployProjectParams): Promise { + try { + // Use provided deployServer or default to shakespeare.wtf + const deployServer = args.deployServer || "shakespeare.wtf"; + + // Check if we're in a valid project directory + try { + await this.fs.readFile(`${this.cwd}/package.json`, "utf8"); + } catch { + throw new Error(`āŒ Could not find package.json at ${this.cwd}. Make sure you're in a valid project directory.`); + } + + // Check if dist directory exists and contains index.html + try { + await this.fs.readFile(`${this.cwd}/dist/index.html`, "utf8"); + } catch { + 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, + signer: this.signer, + }); + + 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!`; + } catch (error) { + throw new Error(`āŒ Deployment failed: ${String(error)}`); + } + } +} \ No newline at end of file diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index e5018b84..2e38a5af 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -19,10 +19,11 @@ import { useKeepAlive } from '@/hooks/useKeepAlive'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; -import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; -import { bytesToHex } from 'nostr-tools/utils'; import { buildProject } from "@/lib/build"; -import { copyDirectory } from '@/lib/copyFiles'; +import { deployProject } from "@/lib/deploy"; +import { useCurrentUser } from "@/hooks/useCurrentUser"; +import { useAppContext } from "@/hooks/useAppContext"; +import { useToast } from "@/hooks/useToast"; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -39,7 +40,10 @@ export function ProjectView() { const navigate = useNavigate(); const isMobile = useIsMobile(); const { fs: browserFS } = useFS(); - const { runtime } = useJSRuntime(); + const { runtime: _runtime } = useJSRuntime(); + const { user } = useCurrentUser(); + const { config } = useAppContext(); + const { toast } = useToast(); const [isSidebarVisible, setIsSidebarVisible] = useState(() => { // Check if we're on mobile immediately to set correct initial state if (typeof window !== 'undefined') { @@ -117,53 +121,47 @@ export function ProjectView() { }; const runDeploy = async () => { - if (isDeployLoading || !project || !browserFS || !runtime) return; + if (isDeployLoading || !project || !browserFS) return; + + // Check if user is logged in + if (!user || !user.signer) { + toast({ + title: "Authentication required", + description: "Please log in to deploy your project.", + variant: "destructive", + }); + return; + } setIsDeployLoading(true); updateMetadata('Shakespeare', `Deploying ${project.name}...`); try { - const runtimeFS = await runtime.fs(); + const result = await deployProject({ + projectId: project.id, + deployServer: config.deployServer, + fs: browserFS, + projectPath: `/projects/${project.id}`, + signer: user.signer, + }); - const sk = generateSecretKey(); - const pubkey = getPublicKey(sk); - const npub = nip19.npubEncode(pubkey); + console.log('Project deployed:', result.url); - const projectUrl = `https://${npub}.nostrdeploy.com`; - console.log('Running deploy for project:', project.id, 'at', projectUrl); + toast({ + title: "Deployment successful!", + description: `Your project is now live at ${result.hostname}`, + }); - await runtimeFS.mkdir('dist', { recursive: true }); - - await runtimeFS.writeFile('.env.nostr-deploy.local', `# Nostr Deploy CLI Configuration -# This file contains sensitive information - do not commit to version control - -# Nostr Authentication -NOSTR_PRIVATE_KEY=${bytesToHex(sk)} -NOSTR_PUBLIC_KEY=${pubkey} -NOSTR_RELAYS=wss://relay.nostr.band,wss://nostrue.com,wss://purplerelay.com,wss://relay.primal.net,wss://ditto.pub/relay - -# Blossom File Storage -BLOSSOM_SERVERS=https://cdn.hzrd149.com,https://blossom.primal.net,https://blossom.band,https://blossom.f7z.io - -# Deployment Settings -BASE_DOMAIN=nostrdeploy.com`); - - // Copy "dist" files to runtime filesystem - const distPath = `/projects/${project.id}/dist`; - try { - await copyDirectory(browserFS, runtimeFS, distPath, 'dist'); - console.log('Successfully copied dist to runtime'); - } catch (error) { - console.error('Failed to copy dist to runtime:', error); - return; - } - - const proc = await runtime.spawn('npx', ["-y", "nostr-deploy-cli", "deploy"]); - await proc.exit; - - console.log('Project deployed:', projectUrl); + // Open the deployed site in a new tab + window.open(result.url, '_blank'); } catch (error) { console.error('Deploy failed:', error); + + toast({ + title: "Deployment failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); } finally { setIsDeployLoading(false); } diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index cd699aa4..655acfcd 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -28,6 +28,7 @@ export function TestApp({ children }: TestAppProps) { const defaultConfig: AppConfig = { theme: 'light', relayUrl: 'wss://relay.nostr.band', + deployServer: 'shakespeare.wtf', }; // Initialize LightningFS for testing