From 6f94aaa45ec1c626e8f45b1d15bf9005386dbf0e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 16:36:22 -0600 Subject: [PATCH 01/28] Allow editing t-tags on Nostr repos --- .../git/AnnounceRepositoryDialog.tsx | 55 +++- src/components/ui/tag-input.test.tsx | 256 ++++++++++++++++++ src/components/ui/tag-input.tsx | 172 ++++++++++++ src/lib/announceRepository.ts | 10 + 4 files changed, 492 insertions(+), 1 deletion(-) create mode 100644 src/components/ui/tag-input.test.tsx create mode 100644 src/components/ui/tag-input.tsx diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx index 30d9ae16..dece235a 100644 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ b/src/components/git/AnnounceRepositoryDialog.tsx @@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; +import { TagInput } from '@/components/ui/tag-input'; import { Dialog, DialogContent, @@ -33,6 +34,8 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@/hooks/useNostr'; import { useToast } from '@/hooks/useToast'; import { useAppContext } from '@/hooks/useAppContext'; +import { useFS } from '@/hooks/useFS'; +import { DotAI } from '@/lib/DotAI'; import { nip19 } from 'nostr-tools'; import { createRepositoryAnnouncementEvent, @@ -75,6 +78,7 @@ export function AnnounceRepositoryDialog({ const [webUrls, setWebUrls] = useState([]); const [cloneUrls, setCloneUrls] = useState([]); const [relays, setRelays] = useState([]); + const [tTags, setTTags] = useState([]); const [earliestCommit, setEarliestCommit] = useState(''); const [isCreating, setIsCreating] = useState(false); const [error, setError] = useState(null); @@ -89,6 +93,7 @@ export function AnnounceRepositoryDialog({ const { nostr } = useNostr(); const { toast } = useToast(); const { config } = useAppContext(); + const { fs } = useFS(); const projectPath = `${projectsPath}/${projectId}`; @@ -169,9 +174,31 @@ export function AnnounceRepositoryDialog({ } } + // Prepopulate t-tags if empty + if (tTags.length === 0) { + const defaultTTags: string[] = ['shakespeare']; + + // Try to read template.json to get template name + try { + const dotAI = new DotAI(fs, projectPath); + const template = await dotAI.readTemplate(); + if (template?.name) { + // Convert template name to lowercase and add as t-tag + const templateTag = template.name.toLowerCase(); + if (!defaultTTags.includes(templateTag)) { + defaultTTags.push(templateTag); + } + } + } catch (error) { + console.warn('Failed to read template for t-tags:', error); + } + + setTTags(defaultTTags); + } + // Get earliest commit await getEarliestCommit(); - }, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]); + }, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length, tTags.length]); // Load existing repository data if editing useEffect(() => { @@ -221,6 +248,13 @@ export function AnnounceRepositoryDialog({ setRelays(parsed.relays); setEarliestCommit(parsed.earliestCommit || ''); + // Extract t-tags from the event + const extractedTTags = parsed.event.tags + .filter(([name]) => name === 't') + .map(([, value]) => value) + .filter((value): value is string => !!value); + setTTags(extractedTTags); + setIsPrepopulated(true); } catch (error) { console.error('Failed to load repository data:', error); @@ -313,6 +347,7 @@ export function AnnounceRepositoryDialog({ webUrls, cloneUrls, relays, + tTags, earliestCommit, }); @@ -385,6 +420,7 @@ export function AnnounceRepositoryDialog({ setWebUrls([]); setCloneUrls([]); setRelays(['wss://relay.nostr.band']); + setTTags([]); setEarliestCommit(''); setError(null); setNewWebUrl(''); @@ -636,6 +672,23 @@ export function AnnounceRepositoryDialog({

+ {/* Category Tags (t-tags) */} +
+ + tag.trim().toLowerCase()} + allowDuplicates={false} + /> +

+ Tags for categorizing your repository. Press space or comma to add a tag. +

+
+ {/* Earliest Commit */}
diff --git a/src/components/ui/tag-input.test.tsx b/src/components/ui/tag-input.test.tsx new file mode 100644 index 00000000..d651182d --- /dev/null +++ b/src/components/ui/tag-input.test.tsx @@ -0,0 +1,256 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { TagInput } from './tag-input'; + +describe('TagInput', () => { + it('renders with placeholder when no tags', () => { + const onChange = vi.fn(); + render( + + ); + + const input = screen.getByPlaceholderText('Add tags...'); + expect(input).toBeInTheDocument(); + }); + + it('displays existing tags', () => { + const onChange = vi.fn(); + render( + + ); + + expect(screen.getByText('tag1')).toBeInTheDocument(); + expect(screen.getByText('tag2')).toBeInTheDocument(); + expect(screen.getByText('tag3')).toBeInTheDocument(); + }); + + it('adds tag on space key', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByPlaceholderText('Add tags...'); + await user.type(input, 'newtag '); + + expect(onChange).toHaveBeenCalledWith(['newtag']); + }); + + it('adds tag on comma key', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByPlaceholderText('Add tags...'); + await user.type(input, 'newtag,'); + + expect(onChange).toHaveBeenCalledWith(['newtag']); + }); + + it('adds tag on Enter key', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByPlaceholderText('Add tags...'); + await user.type(input, 'newtag{Enter}'); + + expect(onChange).toHaveBeenCalledWith(['newtag']); + }); + + it('removes last tag on Backspace when input is empty', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByRole('textbox'); + await user.click(input); + await user.keyboard('{Backspace}'); + + expect(onChange).toHaveBeenCalledWith(['tag1']); + }); + + it('removes tag when clicking X button', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const removeButtons = screen.getAllByRole('button'); + await user.click(removeButtons[1]); // Remove tag2 + + expect(onChange).toHaveBeenCalledWith(['tag1', 'tag3']); + }); + + it('transforms tags using transformTag function', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + tag.toUpperCase()} + placeholder="Add tags..." + /> + ); + + const input = screen.getByPlaceholderText('Add tags...'); + await user.type(input, 'lowercase '); + + expect(onChange).toHaveBeenCalledWith(['LOWERCASE']); + }); + + it('prevents duplicate tags by default', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByRole('textbox'); + await user.type(input, 'existing '); + + expect(onChange).not.toHaveBeenCalled(); + }); + + it('allows duplicate tags when allowDuplicates is true', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByRole('textbox'); + await user.type(input, 'existing '); + + expect(onChange).toHaveBeenCalledWith(['existing', 'existing']); + }); + + it('validates tags using validateTag function', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + tag.length >= 3} + placeholder="Add tags..." + /> + ); + + const input = screen.getByPlaceholderText('Add tags...'); + + // Try adding tag that's too short + await user.type(input, 'ab '); + expect(onChange).not.toHaveBeenCalled(); + + // Add valid tag + await user.type(input, 'valid '); + expect(onChange).toHaveBeenCalledWith(['valid']); + }); + + it('does not add empty tags', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByPlaceholderText('Add tags...'); + await user.type(input, ' '); // Just spaces + + expect(onChange).not.toHaveBeenCalled(); + }); + + it('focuses input when container is clicked', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + const { container } = render( + + ); + + const inputContainer = container.querySelector('div'); + if (inputContainer) { + await user.click(inputContainer); + } + + const input = screen.getByRole('textbox'); + expect(input).toHaveFocus(); + }); + + it('is disabled when disabled prop is true', () => { + const onChange = vi.fn(); + + render( + + ); + + const input = screen.getByRole('textbox'); + expect(input).toBeDisabled(); + }); +}); diff --git a/src/components/ui/tag-input.tsx b/src/components/ui/tag-input.tsx new file mode 100644 index 00000000..71484c03 --- /dev/null +++ b/src/components/ui/tag-input.tsx @@ -0,0 +1,172 @@ +import * as React from 'react'; +import { X } from 'lucide-react'; +import { Badge } from '@/components/ui/badge'; +import { cn } from '@/lib/utils'; + +export interface TagInputProps + extends Omit, 'value' | 'onChange'> { + value: string[]; + onChange: (tags: string[]) => void; + /** Character(s) that trigger tag creation. Default: [' ', ','] */ + delimiters?: string[]; + /** Transform tag before adding (e.g., toLowerCase). Default: (tag) => tag.trim() */ + transformTag?: (tag: string) => string; + /** Validate tag before adding. Return false to reject. */ + validateTag?: (tag: string) => boolean; + /** Allow duplicate tags. Default: false */ + allowDuplicates?: boolean; +} + +export const TagInput = React.forwardRef( + ( + { + className, + value = [], + onChange, + delimiters = [' ', ','], + transformTag = (tag) => tag.trim(), + validateTag, + allowDuplicates = false, + disabled, + placeholder, + ...props + }, + ref + ) => { + const [inputValue, setInputValue] = React.useState(''); + const inputRef = React.useRef(null); + const containerRef = React.useRef(null); + + // Combine external ref with internal ref + React.useImperativeHandle(ref, () => inputRef.current!); + + const addTag = (tag: string) => { + const transformed = transformTag(tag); + + if (!transformed) return; + + // Check for duplicates if not allowed + if (!allowDuplicates && value.includes(transformed)) { + setInputValue(''); + return; + } + + // Validate if validator provided + if (validateTag && !validateTag(transformed)) { + setInputValue(''); + return; + } + + onChange([...value, transformed]); + setInputValue(''); + }; + + const removeTag = (index: number) => { + onChange(value.filter((_, i) => i !== index)); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + // Handle delimiters (space, comma, etc.) + if (delimiters.includes(e.key)) { + e.preventDefault(); + if (inputValue.trim()) { + addTag(inputValue); + } + return; + } + + // Handle Enter key + if (e.key === 'Enter') { + e.preventDefault(); + if (inputValue.trim()) { + addTag(inputValue); + } + return; + } + + // Handle Backspace - delete last tag if input is empty + if (e.key === 'Backspace' && !inputValue && value.length > 0) { + e.preventDefault(); + removeTag(value.length - 1); + return; + } + }; + + const handleInputChange = (e: React.ChangeEvent) => { + const newValue = e.target.value; + + // Check if any delimiter was typed + const hasDelimiter = delimiters.some(delimiter => newValue.includes(delimiter)); + + if (hasDelimiter) { + // Extract the part before the delimiter + const parts = newValue.split(new RegExp(`[${delimiters.map(d => d === ' ' ? '\\s' : d).join('')}]`)); + const tagToAdd = parts[0]; + + if (tagToAdd.trim()) { + addTag(tagToAdd); + } + } else { + setInputValue(newValue); + } + }; + + const handleContainerClick = () => { + inputRef.current?.focus(); + }; + + return ( +
+ {/* Render tags */} + {value.map((tag, index) => ( + + {tag} + + + ))} + + {/* Input field */} + +
+ ); + } +); + +TagInput.displayName = 'TagInput'; diff --git a/src/lib/announceRepository.ts b/src/lib/announceRepository.ts index 0d6ae314..fff9fa24 100644 --- a/src/lib/announceRepository.ts +++ b/src/lib/announceRepository.ts @@ -15,6 +15,8 @@ export interface RepositoryAnnouncementData { cloneUrls: string[]; /** Relays for patch submissions */ relays?: string[]; + /** Category tags for the repository */ + tTags?: string[]; /** Earliest unique commit (root commit) */ earliestCommit?: string; } @@ -95,6 +97,14 @@ export function createRepositoryAnnouncementEvent( } } + // Add t-tags for categorization (each as a separate tag for relay-level filtering) + if (data.tTags && data.tTags.length > 0) { + const trimmedTags = data.tTags.map(tag => tag.trim().toLowerCase()).filter(tag => tag); + for (const tag of trimmedTags) { + tags.push(['t', tag]); + } + } + // Add earliest unique commit (euc) for repository identification if (data.earliestCommit?.trim()) { tags.push(['r', data.earliestCommit.trim(), 'euc']); From f41d70442a2ae0fc58c691faa5b7d507596ec51d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 17:06:29 -0600 Subject: [PATCH 02/28] Prevent the Nostr settings dialog from refreshing --- .../git/AnnounceRepositoryDialog.tsx | 84 +++++++++---------- 1 file changed, 41 insertions(+), 43 deletions(-) diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx index dece235a..0dfaf8fc 100644 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ b/src/components/git/AnnounceRepositoryDialog.tsx @@ -151,59 +151,57 @@ export function AnnounceRepositoryDialog({ .join(' '); setName(defaultName); - // Only prepopulate if the arrays are empty (user hasn't made changes yet) - if (cloneUrls.length === 0 && relays.length === 0) { - // Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr) - if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) { - // Clone URLs: https://{server}/{npub}/{repo-id}.git - const npub = nip19.npubEncode(user.pubkey); - const cloneUrls = config.ngitServers.map(server => - `https://${server}/${npub}/${defaultRepoId}.git` - ); - setCloneUrls(cloneUrls); + // Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr) + if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) { + // Clone URLs: https://{server}/{npub}/{repo-id}.git + const npub = nip19.npubEncode(user.pubkey); + const cloneUrls = config.ngitServers.map(server => + `https://${server}/${npub}/${defaultRepoId}.git` + ); + setCloneUrls(cloneUrls); - // Relay URLs: wss://{server} - const relayUrls = config.ngitServers.map(server => `wss://${server}`); - setRelays(relayUrls); - } else { - // Fallback to write relays if no ngitServers configured - const writeRelays = config.relayMetadata.relays - .filter(r => r.write) - .map(r => r.url); - setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']); - } + // Relay URLs: wss://{server} + const relayUrls = config.ngitServers.map(server => `wss://${server}`); + setRelays(relayUrls); + } else { + // Fallback to write relays if no ngitServers configured + const writeRelays = config.relayMetadata.relays + .filter(r => r.write) + .map(r => r.url); + setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']); } - // Prepopulate t-tags if empty - if (tTags.length === 0) { - const defaultTTags: string[] = ['shakespeare']; + // Prepopulate t-tags + const defaultTTags: string[] = ['shakespeare']; - // Try to read template.json to get template name - try { - const dotAI = new DotAI(fs, projectPath); - const template = await dotAI.readTemplate(); - if (template?.name) { - // Convert template name to lowercase and add as t-tag - const templateTag = template.name.toLowerCase(); - if (!defaultTTags.includes(templateTag)) { - defaultTTags.push(templateTag); - } + // Try to read template.json to get template name + try { + const dotAI = new DotAI(fs, projectPath); + const template = await dotAI.readTemplate(); + if (template?.name) { + // Convert template name to lowercase and add as t-tag + const templateTag = template.name.toLowerCase(); + if (!defaultTTags.includes(templateTag)) { + defaultTTags.push(templateTag); } - } catch (error) { - console.warn('Failed to read template for t-tags:', error); } - - setTTags(defaultTTags); + } catch (error) { + console.warn('Failed to read template for t-tags:', error); } + setTTags(defaultTTags); + // Get earliest commit await getEarliestCommit(); - }, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length, tTags.length]); + }, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]); - // Load existing repository data if editing + // Load existing repository data if editing, or prepopulate fields for new repos useEffect(() => { + // Only run when dialog opens + if (!isOpen || isPrepopulated) return; + const loadExistingRepo = async () => { - if (!editNaddr || !isOpen) return; + if (!editNaddr) return; try { // Decode the naddr to get repository coordinates @@ -266,13 +264,13 @@ export function AnnounceRepositoryDialog({ } }; - if (isOpen && editNaddr) { + if (editNaddr) { loadExistingRepo(); - } else if (isOpen && !isPrepopulated) { + } else { prepopulateFields(); setIsPrepopulated(true); } - }, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]); + }, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]); const addWebUrl = () => { if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) { From 46db6542aaf136c60f41239c88a20cfc78bd74f7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 19:37:36 -0600 Subject: [PATCH 03/28] Add Cloudflare deployment provider --- src/components/DeployDialog.tsx | 69 +++++- .../deploy/CloudflareDeployForm.tsx | 195 ++++++++++++++++ src/components/deploy/index.ts | 1 + src/contexts/DeploySettingsContext.ts | 10 +- src/hooks/useProjectDeploySettings.ts | 9 +- src/lib/deploy/CloudflareAdapter.ts | 220 ++++++++++++++++++ src/lib/deploy/index.ts | 1 + src/lib/deploy/types.ts | 9 + src/pages/DeploySettings.tsx | 159 +++++++++++-- 9 files changed, 643 insertions(+), 30 deletions(-) create mode 100644 src/components/deploy/CloudflareDeployForm.tsx create mode 100644 src/lib/deploy/CloudflareAdapter.ts diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index 1f78788e..c56b44ea 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -27,13 +27,14 @@ import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useAppContext } from '@/hooks/useAppContext'; import { useNostr } from '@nostrify/react'; -import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy'; +import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DeployAdapter } from '@/lib/deploy'; import { Link } from 'react-router-dom'; -import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext'; +import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider } from '@/contexts/DeploySettingsContext'; import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm'; import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm'; import { VercelDeployForm } from '@/components/deploy/VercelDeployForm'; import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm'; +import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm'; /** * Helper function to get provider URL for favicon @@ -58,6 +59,12 @@ function getProviderUrl(provider: DeployProvider): string | null { } return 'https://vercel.com'; + case 'cloudflare': + if (provider.baseURL) { + return provider.baseURL; + } + return 'https://cloudflare.com'; + case 'nsite': return null; @@ -110,6 +117,10 @@ interface VercelFormData { teamId: string; } +interface CloudflareFormData { + projectName: string; +} + export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) { const { t } = useTranslation(); const { settings } = useDeploySettings(); @@ -141,6 +152,9 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectName: projectName || projectId, teamId: '', }); + const [cloudflareForm, setCloudflareForm] = useState({ + projectName: projectName || projectId, + }); // Load project settings when dialog opens useEffect(() => { @@ -230,6 +244,23 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectName: vercelForm.projectName || undefined, corsProxy: vercelProvider.proxy ? config.corsProxy : undefined, }); + } else if (selectedProvider.type === 'cloudflare') { + const cloudflareProvider = selectedProvider as CloudflareProvider; + if (!cloudflareProvider.apiKey) { + throw new Error('Cloudflare API key is required'); + } + if (!cloudflareProvider.accountId) { + throw new Error('Cloudflare account ID is required'); + } + + adapter = new CloudflareAdapter({ + fs, + apiKey: cloudflareProvider.apiKey, + accountId: cloudflareProvider.accountId, + baseURL: cloudflareProvider.baseURL, + projectName: cloudflareForm.projectName || undefined, + corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined, + }); } else { throw new Error('Unknown provider type'); } @@ -269,6 +300,13 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep projectId: vercelForm.projectName || undefined, }, }); + } else if (selectedProvider.type === 'cloudflare') { + await updateProjectSettings(selectedProviderId, { + type: 'cloudflare', + data: { + projectName: cloudflareForm.projectName || undefined, + }, + }); } setDeployResult(result); @@ -288,6 +326,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setNsiteForm({ nsec: '' }); setNetlifyForm({ siteId: '', siteName: '' }); setVercelForm({ projectName: projectName || projectId, teamId: '' }); + setCloudflareForm({ projectName: projectName || projectId }); onOpenChange(false); }; @@ -311,6 +350,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep setVercelForm({ projectName, teamId }); }, []); + const handleCloudflareProjectChange = useCallback((projectName: string) => { + setCloudflareForm({ projectName }); + }, []); + const renderProviderFields = () => { if (!selectedProvider) return null; @@ -373,6 +416,25 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep ); } + if (selectedProvider.type === 'cloudflare') { + const cloudflareProvider = selectedProvider as CloudflareProvider; + const savedConfig = projectSettings.providers[selectedProviderId]; + const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined; + + return ( + + ); + } + return null; }; @@ -503,7 +565,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep (selectedProvider.type === 'shakespeare' && !user) || (selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) || (selectedProvider.type === 'nsite' && !nsiteForm.nsec) || - (selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) + (selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) || + (selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) } > {isDeploying ? ( diff --git a/src/components/deploy/CloudflareDeployForm.tsx b/src/components/deploy/CloudflareDeployForm.tsx new file mode 100644 index 00000000..952b4c6a --- /dev/null +++ b/src/components/deploy/CloudflareDeployForm.tsx @@ -0,0 +1,195 @@ +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'; +import { proxyUrl } from '@/lib/proxyUrl'; + +interface CloudflareProject { + id: string; + name: string; + subdomain: string; + domains: string[]; + production_branch: string; + created_on: string; +} + +interface CloudflareDeployFormProps { + apiKey: string; + accountId: string; + baseURL?: string; + projectId: string; + projectName?: string; + savedProjectName?: string; + onProjectChange: (projectName: string) => void; + corsProxy?: string; +} + +export function CloudflareDeployForm({ + apiKey, + accountId, + baseURL = 'https://api.cloudflare.com/client/v4', + projectId, + projectName, + savedProjectName, + onProjectChange, + corsProxy, +}: CloudflareDeployFormProps) { + const [projects, setProjects] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedProjectName, setSelectedProjectName] = useState(''); + const [newProjectName, setNewProjectName] = useState(projectName || projectId); + + const fetchProjects = useCallback(async () => { + setIsLoading(true); + setError(null); + + try { + const url = `${baseURL}/accounts/${accountId}/pages/projects`; + const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url; + + const response = await fetch(targetUrl, { + headers: { + 'Authorization': `Bearer ${apiKey}`, + }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch projects: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + setProjects(data.result || []); + + // If there's a saved project name and it exists in the list, select it + // Otherwise leave it empty (showing placeholder) + if (savedProjectName && data.result?.some((p: CloudflareProject) => p.name === savedProjectName)) { + setSelectedProjectName(savedProjectName); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch projects'); + } finally { + setIsLoading(false); + } + }, [apiKey, accountId, baseURL, savedProjectName, corsProxy]); + + useEffect(() => { + fetchProjects(); + }, [fetchProjects]); + + // Update newProjectName when switching to "new" if it's empty + useEffect(() => { + if (selectedProjectName === 'new' && !newProjectName) { + setNewProjectName(projectName || projectId); + } + }, [selectedProjectName, newProjectName, projectName, projectId]); + + useEffect(() => { + if (selectedProjectName === '') { + // No selection yet - don't call onProjectChange + return; + } else if (selectedProjectName === 'new') { + onProjectChange(newProjectName); + } else { + onProjectChange(selectedProjectName); + } + }, [selectedProjectName, newProjectName, onProjectChange]); + + if (isLoading) { + return ( +
+
+ + +
+ +
+ ); + } + + const selectedProject = projects.find(p => p.name === selectedProjectName); + + return ( +
+ {error && ( + + {error} + + )} + +
+ + +
+ + {selectedProjectName === 'new' ? ( +
+ + setNewProjectName(e.target.value)} + placeholder={projectName || projectId} + /> +

+ Domain: {newProjectName || projectId}.pages.dev +

+

+ A new project will be created when you deploy +

+
+ ) : selectedProject ? ( +
+
+
+
+

{selectedProject.name}

+

+ https://{selectedProject.subdomain}.pages.dev +

+
+ +
+
+

+ Deployment will update this existing project +

+
+ ) : null} +
+ ); +} diff --git a/src/components/deploy/index.ts b/src/components/deploy/index.ts index 2333aa0c..98b40d1e 100644 --- a/src/components/deploy/index.ts +++ b/src/components/deploy/index.ts @@ -2,3 +2,4 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm'; export { NetlifyDeployForm } from './NetlifyDeployForm'; export { VercelDeployForm } from './VercelDeployForm'; export { NsiteDeployForm } from './NsiteDeployForm'; +export { CloudflareDeployForm } from './CloudflareDeployForm'; diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index d52a5e42..3699d70c 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -32,7 +32,15 @@ export interface NsiteProvider extends BaseDeployProvider { blossomServers: string[]; } -export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider; +export interface CloudflareProvider extends BaseDeployProvider { + type: 'cloudflare'; + apiKey: string; + accountId: string; + baseURL?: string; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index 47e049c7..cbadfd5c 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -31,7 +31,14 @@ export interface VercelProjectConfig { }; } -export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig; +export interface CloudflareProjectConfig { + type: 'cloudflare'; + data: { + projectName?: string; + }; +} + +export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig; export interface ProjectDeploySettings { providers: Record; diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts new file mode 100644 index 00000000..9a0aedfe --- /dev/null +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -0,0 +1,220 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface CloudflareProject { + id: string; + name: string; + subdomain: string; + domains: string[]; + production_branch: string; +} + +interface CloudflareDeployment { + id: string; + url: string; + environment: string; + deployment_trigger: { + type: string; + }; + latest_stage: { + name: string; + status: string; + }; +} + +/** + * Cloudflare Pages Deploy Adapter + * Uses Cloudflare API with API token + */ +export class CloudflareAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private accountId: string; + private baseURL: string; + private projectName?: string; + private corsProxy?: string; + + constructor(config: CloudflareDeployConfig) { + this.fs = config.fs; + this.apiKey = config.apiKey; + this.accountId = config.accountId; + this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4'; + this.projectName = config.projectName; + this.corsProxy = config.corsProxy; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, projectPath } = options; + + // Check if dist directory exists and contains index.html + const distPath = `${projectPath}/dist`; + try { + await this.fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No index.html found in dist directory. Please build the project first.'); + } + + const activeProjectName = this.projectName || projectId; + + // Get or create project + let project: CloudflareProject; + try { + project = await this.getProject(activeProjectName); + } catch { + // Project doesn't exist, create it + project = await this.createProject(activeProjectName); + } + + // Create FormData for deployment + const formData = new FormData(); + + // Collect all files from dist directory + await this.addFilesToFormData(distPath, '', formData); + + // Deploy to Cloudflare Pages + const deployment = await this.createDeployment(project.name, formData); + + // Construct the production URL + const productionUrl = `https://${project.subdomain}.pages.dev`; + + return { + url: productionUrl, + metadata: { + deploymentId: deployment.id, + projectId: project.id, + projectName: project.name, + provider: 'cloudflare', + environment: deployment.environment, + }, + }; + } + + private async getProject(projectName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'GET', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to get Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async createProject(projectName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + name: projectName, + production_branch: 'main', + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async createDeployment(projectName: string, formData: FormData): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}/deployments`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create Cloudflare deployment: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result; + } + + private async addFilesToFormData( + dirPath: string, + relativePath: string, + formData: FormData + ): Promise { + try { + const entries = await this.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 add files from subdirectories + await this.addFilesToFormData(fullPath, entryRelativePath, formData); + } else if (entry.isFile()) { + try { + // Read file content + const fileContent = await this.fs.readFile(fullPath); + + // Convert to Blob for FormData + let blob: Blob; + if (typeof fileContent === 'string') { + blob = new Blob([fileContent], { type: this.getMimeType(entry.name) }); + } else { + // Handle Uint8Array + blob = new Blob([fileContent], { type: this.getMimeType(entry.name) }); + } + + // Add to FormData with the relative path as the field name + formData.append(entryRelativePath, blob, entry.name); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private getMimeType(filename: string): string { + const ext = filename.split('.').pop()?.toLowerCase(); + const mimeTypes: Record = { + 'html': 'text/html', + 'css': 'text/css', + 'js': 'application/javascript', + 'json': 'application/json', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'svg': 'image/svg+xml', + 'ico': 'image/x-icon', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'ttf': 'font/ttf', + 'eot': 'application/vnd.ms-fontobject', + }; + return mimeTypes[ext || ''] || 'application/octet-stream'; + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 830bff96..5832fa94 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -3,3 +3,4 @@ export * from './ShakespeareAdapter'; export * from './NetlifyAdapter'; export * from './VercelAdapter'; export * from './NsiteAdapter'; +export * from './CloudflareAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 5adf4eeb..63a52fa5 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -54,3 +54,12 @@ export interface NsiteDeployConfig { relayUrls: string[]; blossomServers: string[]; } + +export interface CloudflareDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + accountId: string; + baseURL?: string; + projectName?: string; + corsProxy?: string; +} diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 9c88bff9..bd970c34 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -46,12 +46,14 @@ import { normalizeUrl } from '@/lib/faviconUrl'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare'; name: string; description: string; requiresNostr?: boolean; apiKeyLabel?: string; apiKeyURL?: string; + accountIdLabel?: string; + accountIdURL?: string; proxy?: boolean; } @@ -200,23 +202,45 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho onUpdate(index, { ...provider, apiKey: e.target.value }); } else if (provider.type === 'vercel') { onUpdate(index, { ...provider, apiKey: e.target.value }); + } else if (provider.type === 'cloudflare') { + onUpdate(index, { ...provider, apiKey: e.target.value }); } }} />
+ {provider.type === 'cloudflare' && ( +
+ + onUpdate(index, { ...provider, accountId: e.target.value })} + /> +
+ )}
{ if (provider.type === 'netlify') { onUpdate(index, { ...provider, baseURL: e.target.value }); } else if (provider.type === 'vercel') { onUpdate(index, { ...provider, baseURL: e.target.value }); + } else if (provider.type === 'cloudflare') { + onUpdate(index, { ...provider, baseURL: e.target.value }); } }} /> @@ -282,6 +306,17 @@ const PRESET_PROVIDERS: PresetProvider[] = [ apiKeyURL: 'https://vercel.com/account/tokens', proxy: true, }, + { + id: 'cloudflare', + type: 'cloudflare', + name: 'Cloudflare Pages', + description: 'Deploy to Cloudflare Pages', + apiKeyLabel: 'API Token', + apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens', + accountIdLabel: 'Account ID', + accountIdURL: 'https://dash.cloudflare.com/', + proxy: true, + }, ]; // Helper function to generate custom provider ID @@ -314,6 +349,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul } return 'https://vercel.com'; + case 'cloudflare': + // For Cloudflare providers, check for custom baseURL first, then use default + if ('baseURL' in provider && provider.baseURL) { + return provider.baseURL; + } + return 'https://cloudflare.com'; + case 'nsite': // nsite uses Rocket icon fallback return null; @@ -338,9 +380,10 @@ export function DeploySettings() { const [forceManualEntry, setForceManualEntry] = useState>({}); // Custom provider form state - const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>(''); + const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | ''>(''); const [customName, setCustomName] = useState(''); const [customApiKey, setCustomApiKey] = useState(''); + const [customAccountId, setCustomAccountId] = useState(''); const [customBaseURL, setCustomBaseURL] = useState(''); const [customHost, setCustomHost] = useState(''); const [customProxy, setCustomProxy] = useState(false); @@ -416,7 +459,7 @@ export function DeploySettings() { apiKey: apiKey.trim(), ...(preset.proxy && { proxy: true }), }; - } else { + } else if (preset.type === 'vercel') { newProvider = { id: preset.id, // Use preset ID for presets name: preset.name, @@ -424,6 +467,21 @@ export function DeploySettings() { apiKey: apiKey.trim(), ...(preset.proxy && { proxy: true }), }; + } else if (preset.type === 'cloudflare') { + const accountId = presetApiKeys[`${preset.id}-accountId`]; + if (!accountId?.trim()) { + return; + } + newProvider = { + id: preset.id, // Use preset ID for presets + name: preset.name, + type: 'cloudflare', + apiKey: apiKey.trim(), + accountId: accountId.trim(), + ...(preset.proxy && { proxy: true }), + }; + } else { + return; // Unknown type } setProviders([...settings.providers, newProvider]); @@ -472,7 +530,7 @@ export function DeploySettings() { ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), ...(customProxy && { proxy: true }), }; - } else { + } else if (customProviderType === 'vercel') { if (!customApiKey.trim()) return; newProvider = { id: generateCustomProviderId(customProviderType), // Generate custom ID @@ -482,6 +540,19 @@ export function DeploySettings() { ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), ...(customProxy && { proxy: true }), }; + } else if (customProviderType === 'cloudflare') { + if (!customApiKey.trim() || !customAccountId.trim()) return; + newProvider = { + id: generateCustomProviderId(customProviderType), // Generate custom ID + name: customName.trim(), + type: 'cloudflare', + apiKey: customApiKey.trim(), + accountId: customAccountId.trim(), + ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), + ...(customProxy && { proxy: true }), + }; + } else { + return; // Unknown type } setProviders([...settings.providers, newProvider]); @@ -490,6 +561,7 @@ export function DeploySettings() { setCustomProviderType(''); setCustomName(''); setCustomApiKey(''); + setCustomAccountId(''); setCustomBaseURL(''); setCustomHost(''); setCustomProxy(false); @@ -703,34 +775,51 @@ export function DeploySettings() { ) : ( // Show manual token input
-
- {!preset.requiresNostr && preset.type !== 'nsite' && ( + {!preset.requiresNostr && preset.type !== 'nsite' && ( + <> setPresetApiKeys(prev => ({ ...prev, [preset.id]: e.target.value, }))} onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { handleAddPresetProvider(preset); } }} /> - )} - -
+ {preset.type === 'cloudflare' && ( + setPresetApiKeys(prev => ({ + ...prev, + [`${preset.id}-accountId`]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + presetApiKeys[`${preset.id}-accountId`]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + )} + + )} +
)} @@ -759,10 +848,11 @@ export function DeploySettings() {
@@ -849,7 +940,9 @@ export function DeploySettings() { <>
setCustomApiKey(e.target.value)} />
+ {customProviderType === 'cloudflare' && ( +
+ + setCustomAccountId(e.target.value)} + /> +
+ )}
setCustomBaseURL(e.target.value)} @@ -890,7 +998,8 @@ export function DeploySettings() { disabled={ !customProviderType || !customName.trim() || - (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) + (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) || + (customProviderType === 'cloudflare' && !customAccountId.trim()) } className="gap-2 ml-auto" > From b345145ad31d5efaa43a68faa2ced5ce511e5a6b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 20:02:50 -0600 Subject: [PATCH 04/28] Improve design of "Get Key" inputs --- src/pages/DeploySettings.tsx | 105 ++++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 46 deletions(-) diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index bd970c34..c7e7c604 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus } from 'lucide-react'; +import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus, ExternalLink } from 'lucide-react'; import { Checkbox } from '@/components/ui/checkbox'; import { DropdownMenu, @@ -673,31 +673,20 @@ export function DeploySettings() { return ( -
-
- {(() => { - const url = getProviderUrl(preset); - return url ? ( - } - /> - ) : ( - - ); - })()} -
{preset.name}
-
- {preset.apiKeyURL && !isOAuthConfigured && ( - - )} +
+ {(() => { + const url = getProviderUrl(preset); + return url ? ( + } + /> + ) : ( + + ); + })()} +
{preset.name}

{preset.description}

@@ -777,35 +766,59 @@ export function DeploySettings() {
{!preset.requiresNostr && preset.type !== 'nsite' && ( <> - setPresetApiKeys(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && - (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { - handleAddPresetProvider(preset); - } - }} - /> - {preset.type === 'cloudflare' && ( - + setPresetApiKeys(prev => ({ ...prev, - [`${preset.id}-accountId`]: e.target.value, + [preset.id]: e.target.value, }))} onKeyDown={(e) => { if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && - presetApiKeys[`${preset.id}-accountId`]?.trim()) { + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { handleAddPresetProvider(preset); } }} /> + {preset.apiKeyURL && !presetApiKeys[preset.id] && ( + + )} +
+ {preset.type === 'cloudflare' && ( +
+ setPresetApiKeys(prev => ({ + ...prev, + [`${preset.id}-accountId`]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + presetApiKeys[`${preset.id}-accountId`]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.accountIdURL && !presetApiKeys[`${preset.id}-accountId`] && ( + + )} +
)} )} From fef40abcae40ddab1880469820808093f4693bef Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 20:09:47 -0600 Subject: [PATCH 05/28] Improve input external link hover style --- src/pages/DeploySettings.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index c7e7c604..a4bf53a2 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -784,7 +784,7 @@ export function DeploySettings() { {preset.apiKeyURL && !presetApiKeys[preset.id] && ( - )} -
{preset.type === 'cloudflare' && (
)} +
+ setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.apiKeyURL && !presetApiKeys[preset.id] && ( + + )} +
)}

- Deployment will update this existing project + Deployment will update this existing worker

) : null} diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts index aa16a6ef..944fa06f 100644 --- a/src/lib/deploy/CloudflareAdapter.ts +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -2,30 +2,44 @@ import type { JSRuntimeFS } from '../JSRuntime'; import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types'; import { proxyUrl } from '../proxyUrl'; -interface CloudflareProject { - id: string; - name: string; - subdomain: string; - domains: string[]; - production_branch: string; +interface AssetManifest { + [path: string]: { hash: string; size: number }; } -interface CloudflareDeployment { +interface InitializeAssetsResponse { + buckets: string[][]; + jwt: string; +} + +interface UploadResponse { + jwt?: string; +} + +interface WorkerScript { id: string; - url: string; - environment: string; - deployment_trigger: { - type: string; - }; - latest_stage: { - name: string; - status: string; - }; + etag: string; + handlers: string[]; + modified_on: string; + created_on: string; + has_assets: boolean; +} + +interface FileInfo { + hash: string; + content: Uint8Array; + size: number; + contentType: string; } /** - * Cloudflare Pages Deploy Adapter - * Uses Cloudflare API with API token + * Cloudflare Workers Deploy Adapter + * Uses Cloudflare Workers API with static assets support + * + * Implements the Workers Assets upload workflow: + * 1. Build asset manifest with file hashes + * 2. Initialize upload session to get buckets of files to upload + * 3. Upload files in buckets using FormData with base64 content + * 4. Deploy worker with assets JWT */ export class CloudflareAdapter implements DeployAdapter { private fs: JSRuntimeFS; @@ -55,47 +69,74 @@ export class CloudflareAdapter implements DeployAdapter { throw new Error('No index.html found in dist directory. Please build the project first.'); } - const activeProjectName = this.projectName || projectId; + const scriptName = this.projectName || projectId; - // Get or create project - let project: CloudflareProject; - try { - project = await this.getProject(activeProjectName); - } catch { - // Project doesn't exist, create it - project = await this.createProject(activeProjectName); + // Step 1: Collect all files and build manifest + const files = new Map(); + await this.collectFiles(distPath, '', files); + + const manifest: AssetManifest = {}; + for (const [filePath, fileInfo] of files) { + // Normalize path with leading slash + const normalizedPath = '/' + filePath.replace(/\\/g, '/'); + manifest[normalizedPath] = { + hash: fileInfo.hash, + size: fileInfo.size, + }; } - // Collect all files and create manifest - const files: Record = {}; - const fileContents: Record = {}; - await this.collectFiles(distPath, '', files, fileContents); + // Step 2: Initialize upload session + const initResponse = await this.initializeUploadSession(scriptName, manifest); - // Deploy to Cloudflare Pages using Direct Upload - const deployment = await this.createDeployment(project.name, files, fileContents); + // Step 3: Upload files in buckets + let completionJwt = initResponse.jwt; - // Construct the production URL - // The subdomain from the API response already includes the full domain - // e.g., "error-button.pages.dev" not just "error-button" - const productionUrl = project.subdomain.includes('.') - ? `https://${project.subdomain}` - : `https://${project.subdomain}.pages.dev`; + if (initResponse.buckets.flat().length > 0) { + // Create lookup from hash to file info + const hashToFile = new Map(); + for (const [filePath, fileInfo] of files) { + hashToFile.set(fileInfo.hash, { path: filePath, info: fileInfo }); + } + + // Upload each bucket + for (const bucket of initResponse.buckets) { + const uploadResult = await this.uploadBucket( + initResponse.jwt, + bucket, + hashToFile + ); + if (uploadResult.jwt) { + completionJwt = uploadResult.jwt; + } + } + } + + // Step 4: Deploy the worker with assets + const deployment = await this.deployWorker(scriptName, completionJwt); + + // Step 5: Enable the workers.dev subdomain for this script + await this.enableWorkersDevSubdomain(scriptName); + + // Step 6: Get the account's workers.dev subdomain + const subdomain = await this.getWorkersSubdomain(); + + // Construct the URL + const workerUrl = `https://${scriptName}.${subdomain}.workers.dev`; return { - url: deployment.url, + url: workerUrl, metadata: { - deploymentId: deployment.id, - projectId: project.id, - projectName: project.name, - productionUrl, - provider: 'cloudflare', - environment: deployment.environment, + scriptId: deployment.id, + scriptName: scriptName, + provider: 'cloudflare-workers', + hasAssets: deployment.has_assets, + modifiedOn: deployment.modified_on, }, }; } - private async getProject(projectName: string): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}`; + private async getWorkersSubdomain(): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`; const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; const response = await fetch(targetUrl, { @@ -107,19 +148,15 @@ export class CloudflareAdapter implements DeployAdapter { if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to get Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`); } const data = await response.json(); - - // Log the project response for debugging - console.log('Cloudflare project response:', data); - - return data.result; + return data.result.subdomain; } - private async createProject(projectName: string): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects`; + private async enableWorkersDevSubdomain(scriptName: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`; const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; const response = await fetch(targetUrl, { @@ -129,40 +166,125 @@ export class CloudflareAdapter implements DeployAdapter { 'Content-Type': 'application/json', }, body: JSON.stringify({ - name: projectName, - production_branch: 'main', + enabled: true, + previews_enabled: true, }), }); if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to create Cloudflare project: ${response.status} ${response.statusText}. ${errorText}`); + throw new Error(`Failed to enable workers.dev subdomain: ${response.status} ${response.statusText}. ${errorText}`); + } + } + + private async initializeUploadSession( + scriptName: string, + manifest: AssetManifest + ): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ manifest }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to initialize upload session: ${response.status} ${response.statusText}. ${errorText}`); } const data = await response.json(); return data.result; } - private async createDeployment( - projectName: string, - manifest: Record, - fileContents: Record - ): Promise { - const url = `${this.baseURL}/accounts/${this.accountId}/pages/projects/${projectName}/deployments`; + private async uploadBucket( + jwt: string, + bucket: string[], + hashToFile: Map + ): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`; const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; - // Create FormData with manifest const formData = new FormData(); - formData.append('manifest', JSON.stringify(manifest)); - // Add all files to FormData - for (const [path, content] of Object.entries(fileContents)) { - const blob = new Blob([content]); - formData.append(path, blob, path); + for (const fileHash of bucket) { + const fileData = hashToFile.get(fileHash); + if (!fileData) { + throw new Error(`File with hash ${fileHash} not found in manifest`); + } + + // Convert content to base64 + const base64Content = this.uint8ArrayToBase64(fileData.info.content); + + // Use content type or "application/null" to signal no content-type header + const contentType = fileData.info.contentType || 'application/null'; + + // Create a File/Blob with the base64 content + const blob = new Blob([base64Content], { type: contentType }); + formData.append(fileHash, blob, fileHash); } const response = await fetch(targetUrl, { method: 'POST', + headers: { + 'Authorization': `Bearer ${jwt}`, + }, + body: formData, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to upload assets: ${response.status} ${response.statusText}. ${errorText}`); + } + + const data = await response.json(); + return data.result || {}; + } + + private async deployWorker(scriptName: string, assetsJwt: string): Promise { + const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + // Create a minimal worker script that serves static assets + // This is an assets-only worker - Cloudflare will automatically serve the uploaded assets + const workerScript = ` +export default { + async fetch(request, env) { + // This worker only serves static assets + // The assets are automatically served by Cloudflare's asset handler + return new Response('Not Found', { status: 404 }); + } +}; +`; + + const formData = new FormData(); + + // Add the worker script as the main module + const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' }); + formData.append('worker.js', scriptBlob, 'worker.js'); + + // Add metadata with assets configuration + const metadata = { + main_module: 'worker.js', + compatibility_date: new Date().toISOString().split('T')[0], + assets: { + jwt: assetsJwt, + config: { + html_handling: 'auto-trailing-slash', + not_found_handling: 'single-page-application', + }, + }, + }; + + formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); + + const response = await fetch(targetUrl, { + method: 'PUT', headers: { 'Authorization': `Bearer ${this.apiKey}`, }, @@ -171,22 +293,17 @@ export class CloudflareAdapter implements DeployAdapter { if (!response.ok) { const errorText = await response.text().catch(() => 'Unknown error'); - throw new Error(`Failed to create Cloudflare deployment: ${response.status} ${response.statusText}. ${errorText}`); + throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`); } const data = await response.json(); - - // Log the response for debugging - console.log('Cloudflare deployment response:', data); - return data.result; } private async collectFiles( dirPath: string, relativePath: string, - manifest: Record, - fileContents: Record + files: Map ): Promise { try { const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); @@ -196,11 +313,9 @@ export class CloudflareAdapter implements DeployAdapter { const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name; if (entry.isDirectory()) { - // Recursively collect files from subdirectories - await this.collectFiles(fullPath, entryRelativePath, manifest, fileContents); + await this.collectFiles(fullPath, entryRelativePath, files); } else if (entry.isFile()) { try { - // Read file content const fileContent = await this.fs.readFile(fullPath); // Convert to Uint8Array @@ -211,15 +326,18 @@ export class CloudflareAdapter implements DeployAdapter { content = fileContent; } - // Calculate hash for manifest + // Calculate hash (same algorithm as Wrangler uses) const hash = await this.calculateHash(content); - // Add to manifest with leading slash - const manifestPath = `/${entryRelativePath}`; - manifest[manifestPath] = hash; + // Determine content type + const contentType = this.getContentType(entry.name); - // Store file content - fileContents[entryRelativePath] = content; + files.set(entryRelativePath, { + hash, + content, + size: content.length, + contentType, + }); } catch (error) { console.warn(`Failed to read file ${fullPath}:`, error); } @@ -231,10 +349,55 @@ export class CloudflareAdapter implements DeployAdapter { } private async calculateHash(content: Uint8Array): Promise { - // Use SHA-256 to calculate hash + // Use xxHash algorithm like Wrangler does, but fall back to SHA-256 for browser compatibility const hashBuffer = await crypto.subtle.digest('SHA-256', content); const hashArray = Array.from(new Uint8Array(hashBuffer)); - const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + // Take first 16 bytes (32 hex chars) to match Wrangler's hash length + const hashHex = hashArray.slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join(''); return hashHex; } + + private uint8ArrayToBase64(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } + + private getContentType(filename: string): string { + const ext = filename.split('.').pop()?.toLowerCase() || ''; + const mimeTypes: Record = { + 'html': 'text/html', + 'htm': 'text/html', + 'css': 'text/css', + 'js': 'application/javascript', + 'mjs': 'application/javascript', + 'json': 'application/json', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'svg': 'image/svg+xml', + 'ico': 'image/x-icon', + 'webp': 'image/webp', + 'avif': 'image/avif', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'ttf': 'font/ttf', + 'eot': 'application/vnd.ms-fontobject', + 'otf': 'font/otf', + 'txt': 'text/plain', + 'xml': 'application/xml', + 'pdf': 'application/pdf', + 'zip': 'application/zip', + 'mp4': 'video/mp4', + 'webm': 'video/webm', + 'mp3': 'audio/mpeg', + 'wav': 'audio/wav', + 'ogg': 'audio/ogg', + 'wasm': 'application/wasm', + }; + return mimeTypes[ext] || 'application/octet-stream'; + } } diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index b0aaef05..03401809 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -309,8 +309,8 @@ const PRESET_PROVIDERS: PresetProvider[] = [ { id: 'cloudflare', type: 'cloudflare', - name: 'Cloudflare Pages', - description: 'Deploy to Cloudflare Pages', + name: 'Cloudflare', + description: 'Deploy to Cloudflare Workers', apiKeyLabel: 'API Token', apiKeyURL: 'https://dash.cloudflare.com/profile/api-tokens', accountIdLabel: 'Account ID', @@ -882,7 +882,7 @@ export function DeploySettings() { nsite Netlify Vercel - Cloudflare Pages + Cloudflare From 74b5f60df83c490f2cf03123793b53dbb5df07e3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 23:02:50 -0600 Subject: [PATCH 12/28] Improve Get Key inputs --- src/components/ui/password-input.tsx | 40 +++++++++++++++++----------- src/pages/DeploySettings.tsx | 3 ++- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/components/ui/password-input.tsx b/src/components/ui/password-input.tsx index 1b19f661..a9f915fd 100644 --- a/src/components/ui/password-input.tsx +++ b/src/components/ui/password-input.tsx @@ -2,8 +2,13 @@ import * as React from "react" import { Eye, EyeOff } from "lucide-react" import { cn } from "@/lib/utils" -const PasswordInput = React.forwardRef>( - ({ className, ...props }, ref) => { +interface PasswordInputProps extends React.InputHTMLAttributes { + /** Whether to show the visibility toggle button. Defaults to true. */ + showToggle?: boolean; +} + +const PasswordInput = React.forwardRef( + ({ className, showToggle = true, ...props }, ref) => { const [showPassword, setShowPassword] = React.useState(false) const [isFocused, setIsFocused] = React.useState(false) @@ -12,7 +17,8 @@ const PasswordInput = React.forwardRef - + {showToggle && ( + + )} ) } diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 03401809..5329eaa1 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -808,11 +808,12 @@ export function DeploySettings() { handleAddPresetProvider(preset); } }} + showToggle={!!presetApiKeys[preset.id]} /> {preset.apiKeyURL && !presetApiKeys[preset.id] && ( - )} +
+ } + /> +
{preset.name}
{showNostrLoginRequired ? ( @@ -458,22 +447,34 @@ export function AISettings() {
{!preset.nostr && ( - setPresetApiKeys(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && - presetApiKeys[preset.id]?.trim() && - presetTermsAgreements[preset.id]) { - handleAddPresetProvider(preset); - } - }} - /> +
+ setPresetApiKeys(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && + presetApiKeys[preset.id]?.trim() && + presetTermsAgreements[preset.id]) { + handleAddPresetProvider(preset); + } + }} + showToggle={!!presetApiKeys[preset.id]} + /> + {preset.apiKeysURL && !presetApiKeys[preset.id] && ( + + )} +
)} - )} +
+ } + /> +
{preset.name}
{preset.id === 'github' ? ( @@ -308,20 +297,32 @@ export function GitSettings() {
) : (
- setPresetTokens(prev => ({ - ...prev, - [preset.id]: e.target.value, - }))} - onKeyDown={(e) => { - if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { - handleAddPresetProvider(preset); - } - }} - /> +
+ setPresetTokens(prev => ({ + ...prev, + [preset.id]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) { + handleAddPresetProvider(preset); + } + }} + showToggle={!!presetTokens[preset.id]} + /> + {preset.tokenURL && !presetTokens[preset.id] && ( + + )} +
+ )} +
+
+ +

+ Deployment will create a new version for this project +

+ + ) : null} + + ); +} diff --git a/src/components/deploy/index.ts b/src/components/deploy/index.ts index 98b40d1e..e0626373 100644 --- a/src/components/deploy/index.ts +++ b/src/components/deploy/index.ts @@ -3,3 +3,4 @@ export { NetlifyDeployForm } from './NetlifyDeployForm'; export { VercelDeployForm } from './VercelDeployForm'; export { NsiteDeployForm } from './NsiteDeployForm'; export { CloudflareDeployForm } from './CloudflareDeployForm'; +export { DenoDeployForm } from './DenoDeployForm'; diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 3699d70c..5fc0b0e5 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -40,7 +40,15 @@ export interface CloudflareProvider extends BaseDeployProvider { proxy?: boolean; } -export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider; +export interface DenoDeployProvider extends BaseDeployProvider { + type: 'deno'; + apiKey: string; + organizationId: string; + baseURL?: string; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index cbadfd5c..467bd3a9 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -38,7 +38,14 @@ export interface CloudflareProjectConfig { }; } -export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig; +export interface DenoDeployProjectConfig { + type: 'deno'; + data: { + projectName?: string; + }; +} + +export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig; export interface ProjectDeploySettings { providers: Record; diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts new file mode 100644 index 00000000..8fa61f5c --- /dev/null +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -0,0 +1,304 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, DenoDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface Project { + id: string; + name: string; + createdAt: string; + updatedAt: string; +} + +interface Deployment { + id: string; + projectId: string; + status: string; + domains: string[]; + createdAt: string; + updatedAt: string; +} + +/** + * Deno Deploy Adapter + * Uses Deno Deploy API to deploy static sites + * + * Implements the Deno Deploy workflow: + * 1. Create or find existing project + * 2. Build asset manifest with file contents + * 3. Create deployment with assets + * 4. Attach domain to deployment + */ +export class DenoDeployAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private organizationId: string; + private baseURL: string; + private projectName?: string; + private corsProxy?: string; + + constructor(config: DenoDeployConfig) { + this.fs = config.fs; + this.apiKey = config.apiKey; + this.organizationId = config.organizationId; + this.baseURL = config.baseURL || 'https://api.deno.com/v1'; + this.projectName = config.projectName; + this.corsProxy = config.corsProxy; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, projectPath } = options; + + // Check if dist directory exists and contains index.html + const distPath = `${projectPath}/dist`; + try { + await this.fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No index.html found in dist directory. Please build the project first.'); + } + + const projectName = this.projectName || projectId; + + // Step 1: Get or create project + const project = await this.getOrCreateProject(projectName); + + // Step 2: Collect all files and build assets + const assets: Record = {}; + await this.collectFiles(distPath, '', assets); + + // Step 3: Create deployment with assets + const deployment = await this.createDeployment(project.id, assets); + + // Step 4: Attach the deno.dev domain to the deployment + const domain = `${project.name}.deno.dev`; + await this.attachDomain(deployment.id, `{project.name}.deno.dev`); + + return { + url: `https://${domain}`, + metadata: { + deploymentId: deployment.id, + projectId: project.id, + projectName: project.name, + provider: 'deno-deploy', + status: deployment.status, + }, + }; + } + + private async getOrCreateProject(projectName: string): Promise { + // First, try to find existing project + const existingProject = await this.findProject(projectName); + if (existingProject) { + return existingProject; + } + + // Create new project + return this.createProject(projectName); + } + + private async findProject(projectName: string): Promise { + const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'GET', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + }, + }); + + if (!response.ok) { + // If we can't list projects, just return null and try to create + return null; + } + + const projects: Project[] = await response.json(); + return projects.find(p => p.name === projectName) || null; + } + + private async createProject(projectName: string): Promise { + const url = `${this.baseURL}/organizations/${this.organizationId}/projects`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + name: projectName, + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create project: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async createDeployment( + projectId: string, + assets: Record + ): Promise { + const url = `${this.baseURL}/projects/${projectId}/deployments`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + // Create a minimal server script that serves static files + // For static sites, we use a simple file server entry point + const entryPointUrl = 'file:///src/main.ts'; + + // Add the entry point script that serves static files + const serverScript = ` +import { serveDir } from "https://deno.land/std@0.208.0/http/file_server.ts"; + +Deno.serve((req) => { + return serveDir(req, { + fsRoot: ".", + showIndex: true, + enableCors: true, + }); +}); +`; + + // Add the server script to assets + assets['src/main.ts'] = { + kind: 'file', + content: serverScript, + encoding: 'utf-8', + }; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + entryPointUrl, + assets, + importMapUrl: null, + lockFileUrl: null, + compilerOptions: null, + envVars: {}, + }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to create deployment: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } + + private async attachDomain(deploymentId: string, domain: string): Promise { + const url = `${this.baseURL}/deployments/${deploymentId}/domains/${encodeURIComponent(domain)}`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'PUT', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + // Don't throw on domain attachment failure - deployment still succeeded + console.warn(`Failed to attach domain: ${response.status} ${response.statusText}. ${errorText}`); + } + } + + private async collectFiles( + dirPath: string, + relativePath: string, + assets: Record + ): Promise { + try { + const entries = await this.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()) { + await this.collectFiles(fullPath, entryRelativePath, assets); + } else if (entry.isFile()) { + try { + const fileContent = await this.fs.readFile(fullPath); + + // Determine if file is text or binary based on extension + const isText = this.isTextFile(entry.name); + + let content: string; + let encoding: 'utf-8' | 'base64'; + + if (isText) { + if (typeof fileContent === 'string') { + content = fileContent; + } else { + content = new TextDecoder().decode(fileContent); + } + encoding = 'utf-8'; + } else { + // Binary file - encode as base64 + let bytes: Uint8Array; + if (typeof fileContent === 'string') { + bytes = new TextEncoder().encode(fileContent); + } else { + bytes = fileContent; + } + content = this.uint8ArrayToBase64(bytes); + encoding = 'base64'; + } + + assets[entryRelativePath] = { + kind: 'file', + content, + encoding, + }; + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private isTextFile(filename: string): boolean { + const textExtensions = [ + 'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', + 'json', 'xml', 'svg', 'txt', 'md', 'yaml', 'yml', 'toml', + 'sh', 'bash', 'zsh', 'fish', 'bat', 'cmd', 'ps1', + 'py', 'rb', 'php', 'java', 'c', 'cpp', 'h', 'hpp', + 'rs', 'go', 'swift', 'kt', 'scala', 'clj', 'ex', 'exs', + 'vue', 'svelte', 'astro', 'njk', 'ejs', 'pug', 'hbs', + 'graphql', 'gql', 'sql', 'csv', 'tsv', 'log', 'ini', 'cfg', + 'env', 'gitignore', 'dockerignore', 'editorconfig', + 'prettierrc', 'eslintrc', 'babelrc', 'npmrc', + 'map', // source maps + ]; + + const ext = filename.split('.').pop()?.toLowerCase() || ''; + // Also check if filename itself is a known text file + const textFilenames = [ + 'dockerfile', 'makefile', 'gemfile', 'rakefile', 'procfile', + 'license', 'readme', 'changelog', 'authors', 'contributors', + ]; + + return textExtensions.includes(ext) || textFilenames.includes(filename.toLowerCase()); + } + + private uint8ArrayToBase64(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 5832fa94..24bf4795 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -4,3 +4,4 @@ export * from './NetlifyAdapter'; export * from './VercelAdapter'; export * from './NsiteAdapter'; export * from './CloudflareAdapter'; +export * from './DenoDeployAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 63a52fa5..f7f2d1ea 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -63,3 +63,12 @@ export interface CloudflareDeployConfig { projectName?: string; corsProxy?: string; } + +export interface DenoDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + organizationId: string; + baseURL?: string; + projectName?: string; + corsProxy?: string; +} diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 5329eaa1..15bbddf9 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -46,7 +46,7 @@ import { normalizeUrl } from '@/lib/faviconUrl'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; name: string; description: string; requiresNostr?: boolean; @@ -54,6 +54,8 @@ interface PresetProvider { apiKeyURL?: string; accountIdLabel?: string; accountIdURL?: string; + organizationIdLabel?: string; + organizationIdURL?: string; proxy?: boolean; } @@ -202,6 +204,19 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho /> )} + {provider.type === 'deno' && ( +
+ + onUpdate(index, { ...provider, organizationId: e.target.value })} + /> +
+ )}
)} + {preset.type === 'deno' && ( +
+ setPresetApiKeys(prev => ({ + ...prev, + [`${preset.id}-organizationId`]: e.target.value, + }))} + onKeyDown={(e) => { + if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && + presetApiKeys[`${preset.id}-organizationId`]?.trim()) { + handleAddPresetProvider(preset); + } + }} + /> + {preset.organizationIdURL && !presetApiKeys[`${preset.id}-organizationId`] && ( + + )} +
+ )}
{ if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim() && - (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim())) { + (preset.type !== 'cloudflare' || presetApiKeys[`${preset.id}-accountId`]?.trim()) && + (preset.type !== 'deno' || presetApiKeys[`${preset.id}-organizationId`]?.trim())) { handleAddPresetProvider(preset); } }} @@ -828,7 +921,8 @@ export function DeploySettings() { disabled={ (preset.requiresNostr && !isLoggedIntoNostr) || (!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim()) || - (preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) + (preset.type === 'cloudflare' && !presetApiKeys[`${preset.id}-accountId`]?.trim()) || + (preset.type === 'deno' && !presetApiKeys[`${preset.id}-organizationId`]?.trim()) } className="w-full" > @@ -862,11 +956,12 @@ export function DeploySettings() {
@@ -965,11 +1061,25 @@ export function DeploySettings() { /> )} + {customProviderType === 'deno' && ( +
+ + setCustomOrganizationId(e.target.value)} + /> +
+ )}
setCustomBaseURL(e.target.value)} @@ -1013,7 +1125,8 @@ export function DeploySettings() { !customProviderType || !customName.trim() || (customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim()) || - (customProviderType === 'cloudflare' && !customAccountId.trim()) + (customProviderType === 'cloudflare' && !customAccountId.trim()) || + (customProviderType === 'deno' && !customOrganizationId.trim()) } className="gap-2 ml-auto" > From 5685c6f52f3042aacd38b429dd5f49e133655ad0 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 3 Dec 2025 23:57:01 -0600 Subject: [PATCH 16/28] Fix Deno config in configUtils --- src/lib/configUtils.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 5b4975fc..62ab4799 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -113,12 +113,20 @@ const cloudflareProviderSchema = baseDeployProviderSchema.extend({ baseURL: z.string().optional(), }); +const denoDeployProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('deno'), + apiKey: z.string(), + organizationId: z.string(), + baseURL: z.string().optional(), +}); + const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ shakespeareDeployProviderSchema, netlifyProviderSchema, vercelProviderSchema, nsiteProviderSchema, cloudflareProviderSchema, + denoDeployProviderSchema, ]); const deploySettingsSchema = z.object({ From bbb4a2534bbde63ba5e22616a47a85170e76f7be Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 00:02:50 -0600 Subject: [PATCH 17/28] Fix Deno Deploy so it works --- src/lib/deploy/DenoDeployAdapter.ts | 37 +++++++---------------------- 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts index 8fa61f5c..57f7665c 100644 --- a/src/lib/deploy/DenoDeployAdapter.ts +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -65,12 +65,9 @@ export class DenoDeployAdapter implements DeployAdapter { const assets: Record = {}; await this.collectFiles(distPath, '', assets); - // Step 3: Create deployment with assets - const deployment = await this.createDeployment(project.id, assets); - - // Step 4: Attach the deno.dev domain to the deployment + // Step 3: Create deployment with assets and domain const domain = `${project.name}.deno.dev`; - await this.attachDomain(deployment.id, `{project.name}.deno.dev`); + const deployment = await this.createDeployment(project.id, assets, domain); return { url: `https://${domain}`, @@ -140,18 +137,19 @@ export class DenoDeployAdapter implements DeployAdapter { private async createDeployment( projectId: string, - assets: Record + assets: Record, + domain: string ): Promise { const url = `${this.baseURL}/projects/${projectId}/deployments`; const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; // Create a minimal server script that serves static files // For static sites, we use a simple file server entry point - const entryPointUrl = 'file:///src/main.ts'; + const entryPointUrl = 'main.ts'; // Add the entry point script that serves static files const serverScript = ` -import { serveDir } from "https://deno.land/std@0.208.0/http/file_server.ts"; +import { serveDir } from "jsr:@std/http/file-server"; Deno.serve((req) => { return serveDir(req, { @@ -163,7 +161,7 @@ Deno.serve((req) => { `; // Add the server script to assets - assets['src/main.ts'] = { + assets['main.ts'] = { kind: 'file', content: serverScript, encoding: 'utf-8', @@ -182,6 +180,8 @@ Deno.serve((req) => { lockFileUrl: null, compilerOptions: null, envVars: {}, + // Attach domain during deployment creation instead of separately + domains: [domain], }), }); @@ -193,25 +193,6 @@ Deno.serve((req) => { return response.json(); } - private async attachDomain(deploymentId: string, domain: string): Promise { - const url = `${this.baseURL}/deployments/${deploymentId}/domains/${encodeURIComponent(domain)}`; - const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; - - const response = await fetch(targetUrl, { - method: 'PUT', - headers: { - 'Authorization': `Bearer ${this.apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - const errorText = await response.text().catch(() => 'Unknown error'); - // Don't throw on domain attachment failure - deployment still succeeded - console.warn(`Failed to attach domain: ${response.status} ${response.statusText}. ${errorText}`); - } - } - private async collectFiles( dirPath: string, relativePath: string, From 2096c83b3cbc163e8b101a16ff0a8fa0c64b2ef3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 00:17:11 -0600 Subject: [PATCH 18/28] Let baseDomain be configured for Cloudflare and Deno Deploy --- src/components/DeployDialog.tsx | 4 ++ .../deploy/CloudflareDeployForm.tsx | 6 ++- src/components/deploy/DenoDeployForm.tsx | 4 +- src/contexts/DeploySettingsContext.ts | 2 + src/lib/configUtils.ts | 2 + src/lib/deploy/CloudflareAdapter.ts | 8 ++-- src/lib/deploy/DenoDeployAdapter.ts | 4 +- src/lib/deploy/types.ts | 2 + src/pages/DeploySettings.tsx | 39 +++++++++++++++++++ 9 files changed, 64 insertions(+), 7 deletions(-) diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx index e34d8399..8c8dbd88 100644 --- a/src/components/DeployDialog.tsx +++ b/src/components/DeployDialog.tsx @@ -272,6 +272,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey: cloudflareProvider.apiKey, accountId: cloudflareProvider.accountId, baseURL: cloudflareProvider.baseURL, + baseDomain: cloudflareProvider.baseDomain, projectName: cloudflareForm.projectName || undefined, corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined, }); @@ -288,6 +289,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep fs, apiKey: denoProvider.apiKey, organizationId: denoProvider.organizationId, + baseDomain: denoProvider.baseDomain, baseURL: denoProvider.baseURL, projectName: denoDeployForm.projectName || undefined, corsProxy: denoProvider.proxy ? config.corsProxy : undefined, @@ -469,6 +471,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey={cloudflareProvider.apiKey} accountId={cloudflareProvider.accountId} baseURL={cloudflareProvider.baseURL} + baseDomain={cloudflareProvider.baseDomain} projectId={projectId} projectName={projectName} savedProjectName={savedProjectName} @@ -488,6 +491,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep apiKey={denoProvider.apiKey} organizationId={denoProvider.organizationId} baseURL={denoProvider.baseURL} + baseDomain={denoProvider.baseDomain} projectId={projectId} projectName={projectName} savedProjectName={savedProjectName} diff --git a/src/components/deploy/CloudflareDeployForm.tsx b/src/components/deploy/CloudflareDeployForm.tsx index 99d0f8b3..0acb061b 100644 --- a/src/components/deploy/CloudflareDeployForm.tsx +++ b/src/components/deploy/CloudflareDeployForm.tsx @@ -27,6 +27,7 @@ interface CloudflareDeployFormProps { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; projectId: string; projectName?: string; savedProjectName?: string; @@ -38,6 +39,7 @@ export function CloudflareDeployForm({ apiKey, accountId, baseURL = 'https://api.cloudflare.com/client/v4', + baseDomain = 'workers.dev', projectId, projectName, savedProjectName, @@ -136,9 +138,9 @@ export function CloudflareDeployForm({ // Construct the URL preview const getWorkerUrl = (scriptName: string) => { if (workersSubdomain) { - return `https://${scriptName}.${workersSubdomain}.workers.dev`; + return `https://${scriptName}.${workersSubdomain}.${baseDomain}`; } - return `https://${scriptName}..workers.dev`; + return `https://${scriptName}..${baseDomain}`; }; return ( diff --git a/src/components/deploy/DenoDeployForm.tsx b/src/components/deploy/DenoDeployForm.tsx index 152dcd23..961d2726 100644 --- a/src/components/deploy/DenoDeployForm.tsx +++ b/src/components/deploy/DenoDeployForm.tsx @@ -25,6 +25,7 @@ interface DenoDeployFormProps { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; projectId: string; projectName?: string; savedProjectName?: string; @@ -36,6 +37,7 @@ export function DenoDeployForm({ apiKey, organizationId, baseURL = 'https://api.deno.com/v1', + baseDomain = 'deno.dev', projectId, projectName, savedProjectName, @@ -117,7 +119,7 @@ export function DenoDeployForm({ // Construct the URL preview const getProjectUrl = (name: string) => { - return `https://${name}.deno.dev`; + return `https://${name}.${baseDomain}`; }; return ( diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 5fc0b0e5..09abe69a 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -37,6 +37,7 @@ export interface CloudflareProvider extends BaseDeployProvider { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; proxy?: boolean; } @@ -45,6 +46,7 @@ export interface DenoDeployProvider extends BaseDeployProvider { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; proxy?: boolean; } diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 62ab4799..1a2a8f3b 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -111,6 +111,7 @@ const cloudflareProviderSchema = baseDeployProviderSchema.extend({ apiKey: z.string(), accountId: z.string(), baseURL: z.string().optional(), + baseDomain: z.string().optional(), }); const denoDeployProviderSchema = baseDeployProviderSchema.extend({ @@ -118,6 +119,7 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({ apiKey: z.string(), organizationId: z.string(), baseURL: z.string().optional(), + baseDomain: z.string().optional(), }); const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ diff --git a/src/lib/deploy/CloudflareAdapter.ts b/src/lib/deploy/CloudflareAdapter.ts index 8157ff17..5db367c2 100644 --- a/src/lib/deploy/CloudflareAdapter.ts +++ b/src/lib/deploy/CloudflareAdapter.ts @@ -46,6 +46,7 @@ export class CloudflareAdapter implements DeployAdapter { private apiKey: string; private accountId: string; private baseURL: string; + private baseDomain: string; private projectName?: string; private corsProxy?: string; @@ -54,6 +55,7 @@ export class CloudflareAdapter implements DeployAdapter { this.apiKey = config.apiKey; this.accountId = config.accountId; this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4'; + this.baseDomain = config.baseDomain || 'workers.dev'; this.projectName = config.projectName; this.corsProxy = config.corsProxy; } @@ -118,11 +120,11 @@ export class CloudflareAdapter implements DeployAdapter { // Step 5: Enable the workers.dev subdomain for this script await this.enableWorkersDevSubdomain(scriptName); - // Step 6: Get the account's workers.dev subdomain + // Step 6: Get the account's workers subdomain const subdomain = await this.getWorkersSubdomain(); - // Construct the URL - const workerUrl = `https://${scriptName}.${subdomain}.workers.dev`; + // Construct the URL using the configurable base domain + const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`; return { url: workerUrl, diff --git a/src/lib/deploy/DenoDeployAdapter.ts b/src/lib/deploy/DenoDeployAdapter.ts index 57f7665c..041b0aa6 100644 --- a/src/lib/deploy/DenoDeployAdapter.ts +++ b/src/lib/deploy/DenoDeployAdapter.ts @@ -33,6 +33,7 @@ export class DenoDeployAdapter implements DeployAdapter { private apiKey: string; private organizationId: string; private baseURL: string; + private baseDomain: string; private projectName?: string; private corsProxy?: string; @@ -41,6 +42,7 @@ export class DenoDeployAdapter implements DeployAdapter { this.apiKey = config.apiKey; this.organizationId = config.organizationId; this.baseURL = config.baseURL || 'https://api.deno.com/v1'; + this.baseDomain = config.baseDomain || 'deno.dev'; this.projectName = config.projectName; this.corsProxy = config.corsProxy; } @@ -66,7 +68,7 @@ export class DenoDeployAdapter implements DeployAdapter { await this.collectFiles(distPath, '', assets); // Step 3: Create deployment with assets and domain - const domain = `${project.name}.deno.dev`; + const domain = `${project.name}.${this.baseDomain}`; const deployment = await this.createDeployment(project.id, assets, domain); return { diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index f7f2d1ea..60222a5d 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -60,6 +60,7 @@ export interface CloudflareDeployConfig { apiKey: string; accountId: string; baseURL?: string; + baseDomain?: string; projectName?: string; corsProxy?: string; } @@ -69,6 +70,7 @@ export interface DenoDeployConfig { apiKey: string; organizationId: string; baseURL?: string; + baseDomain?: string; projectName?: string; corsProxy?: string; } diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index 15bbddf9..1caffd50 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -265,6 +265,24 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho }} />
+ {(provider.type === 'cloudflare' || provider.type === 'deno') && ( +
+ + onUpdate(index, { ...provider, baseDomain: e.target.value })} + /> +

+ {provider.type === 'cloudflare' + ? 'The domain suffix for deployed workers (e.g., workers.dev)' + : 'The domain suffix for deployed projects (e.g., deno.dev)'} +

+
+ )}
setCustomBaseURL(e.target.value)} />
+ {(customProviderType === 'cloudflare' || customProviderType === 'deno') && ( +
+ + setCustomBaseDomain(e.target.value)} + /> +

+ {customProviderType === 'cloudflare' + ? 'The domain suffix for deployed workers (e.g., workers.dev)' + : 'The domain suffix for deployed projects (e.g., deno.dev)'} +

+
+ )} )} From 2a39dcaf86cff5ca2d109013146040ab81f96654 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 16:13:03 -0600 Subject: [PATCH 19/28] Emphasize the textarea on the homepage; position the showcase to peek from the bottom --- src/pages/Index.tsx | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index ea6f731c..c61e83e1 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -287,20 +287,22 @@ export default function Index() { return ( <> -
-
-
- + {/* Main Chat Section - Takes up most of viewport with generous whitespace */} +
+
+
+
+ +
+

+ {t('buildNostrApps')} +

+

+ {t('whatToBuild')} +

-

- {t('buildNostrApps')} -

-

- {t('whatToBuild')} -

-
-
+
{/* Quilly Helper - shows when there are errors */} {quillyError && (
@@ -392,11 +394,14 @@ export default function Index() {
+
- {/* App Showcase */} - + {/* App Showcase - Positioned to peek from bottom */} +
+ +
{/* Version Display */} {import.meta.env.VERSION && ( From 7b84447f297acc0577ec508d2f79eaef53f295a8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 16:25:44 -0600 Subject: [PATCH 20/28] Simplify homepage textarea --- src/locales/en.json | 7 +++---- src/locales/ha.json | 7 +++---- src/locales/ig.json | 7 +++---- src/locales/pt.json | 7 +++---- src/locales/yo.json | 7 +++---- src/locales/zh.json | 7 +++---- src/pages/Index.tsx | 15 ++++++--------- 7 files changed, 24 insertions(+), 33 deletions(-) diff --git a/src/locales/en.json b/src/locales/en.json index 3de166bf..ac451aa5 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -93,11 +93,10 @@ "name": "Name", "id": "ID", "email": "Email", - "buildNostrApps": "Build apps with AI", - "whatToBuild": "What would you like to build?", + "buildApps": "Build apps with AI", "chooseModel": "Choose a model...", - "selectModelToDescribe": "Please select a model below, then describe what you'd like to build...", - "examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...", + "selectModelToDescribe": "Select a model below to get started...", + "examplePrompt": "Describe what you'd like to build...", "aiSettings": "AI", "aiSettingsDescription": "Configure AI providers and API keys", "gitSettings": "Git", diff --git a/src/locales/ha.json b/src/locales/ha.json index 0e1f8494..053cd390 100644 --- a/src/locales/ha.json +++ b/src/locales/ha.json @@ -89,11 +89,10 @@ "name": "Suna", "id": "ID", "email": "Imel", - "buildNostrApps": "Gina aikace-aikace da AI", - "whatToBuild": "Me kuke son ginawa?", + "buildApps": "Gina aikace-aikace da AI", "chooseModel": "Zaɓi samfuri...", - "selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...", - "examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...", + "selectModelToDescribe": "Zaɓi samfuri a ƙasa don farawa...", + "examplePrompt": "Bayyana abin da kuke son ginawa...", "settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.", "aiSettings": "AI", "aiSettingsDescription": "Saita masu samar da AI da maɓallan API", diff --git a/src/locales/ig.json b/src/locales/ig.json index bb561264..cbf2537b 100644 --- a/src/locales/ig.json +++ b/src/locales/ig.json @@ -89,11 +89,10 @@ "name": "Aha", "id": "ID", "email": "Ozi-eletrọniki", - "buildNostrApps": "Wuo ngwa na AI", - "whatToBuild": "Gịnị ka ị chọrọ iwu?", + "buildApps": "Wuo ngwa na AI", "chooseModel": "Họrọ ụdịdị...", - "selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...", - "examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...", + "selectModelToDescribe": "Họrọ ụdịdị n'okpuru iji malite...", + "examplePrompt": "Kọwaa ihe ị chọrọ iwu...", "settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.", "aiSettings": "AI", "aiSettingsDescription": "Hazie ndị na-enye AI na igodo API", diff --git a/src/locales/pt.json b/src/locales/pt.json index 0e178635..9947de79 100644 --- a/src/locales/pt.json +++ b/src/locales/pt.json @@ -89,11 +89,10 @@ "name": "Nome", "id": "ID", "email": "Email", - "buildNostrApps": "Construa aplicativos com IA", - "whatToBuild": "O que você gostaria de construir?", + "buildApps": "Construa aplicativos com IA", "chooseModel": "Escolha um modelo...", - "selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...", - "examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...", + "selectModelToDescribe": "Selecione um modelo abaixo para começar...", + "examplePrompt": "Descreva o que você gostaria de construir...", "settingsDescription": "Gerencie as configurações e preferências da aplicação.", "aiSettings": "IA", "aiSettingsDescription": "Configure provedores de IA e chaves de API", diff --git a/src/locales/yo.json b/src/locales/yo.json index 9941194d..62286d38 100644 --- a/src/locales/yo.json +++ b/src/locales/yo.json @@ -89,11 +89,10 @@ "name": "Orukọ", "id": "ID", "email": "Imeeli", - "buildNostrApps": "Kọ awọn ohun elo pẹlu AI", - "whatToBuild": "Kini o fẹ kọ?", + "buildApps": "Kọ awọn ohun elo pẹlu AI", "chooseModel": "Yan awoṣe...", - "selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...", - "examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...", + "selectModelToDescribe": "Yan awoṣe ni isalẹ lati bẹrẹ...", + "examplePrompt": "Ṣapejuwe ohun ti o fẹ kọ...", "settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.", "aiSettings": "AI", "aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API", diff --git a/src/locales/zh.json b/src/locales/zh.json index 6977a6ed..83b361ae 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -89,11 +89,10 @@ "name": "名称", "id": "ID", "email": "邮箱", - "buildNostrApps": "使用AI构建应用", - "whatToBuild": "您想构建什么?", + "buildApps": "使用AI构建应用", "chooseModel": "选择模型...", - "selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...", - "examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...", + "selectModelToDescribe": "请选择下方的模型以开始...", + "examplePrompt": "描述您想要构建的内容...", "settingsDescription": "管理您的应用程序设置和偏好。", "aiSettings": "AI", "aiSettingsDescription": "配置AI提供商和API密钥", diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index c61e83e1..5b85594e 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -289,17 +289,14 @@ export default function Index() { {/* Main Chat Section - Takes up most of viewport with generous whitespace */}
-
+

- {t('buildNostrApps')} + {t('buildApps')}

-

- {t('whatToBuild')} -

@@ -318,7 +315,7 @@ export default function Index() { {/* Chat Input Container - matching the ChatPane style */}
{ const target = e.target as HTMLTextAreaElement; From 96b908855140ebad55c125e8b2b56b9e22dc5e50 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 16:29:19 -0600 Subject: [PATCH 21/28] Fix text overflow issue with homepage textarea --- src/pages/Index.tsx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 5b85594e..57045c0b 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -315,7 +315,7 @@ export default function Index() { {/* Chat Input Container - matching the ChatPane style */}
{ const target = e.target as HTMLTextAreaElement; @@ -349,10 +350,9 @@ export default function Index() { /> {/* Bottom Controls Row */} -
+
{/* File Attachment */} {/* Model Selector - always show to allow configuration */} -
+
Date: Thu, 4 Dec 2025 17:56:35 -0600 Subject: [PATCH 22/28] Nostr plugin discovery --- src/components/DiscoverPluginsDialog.tsx | 229 +++++++++++++++++++++++ src/components/PluginsSection.tsx | 27 ++- src/hooks/useDiscoverPlugins.test.ts | 84 +++++++++ src/hooks/useDiscoverPlugins.ts | 69 +++++++ src/locales/en.json | 15 ++ src/locales/ha.json | 17 +- src/locales/ig.json | 17 +- src/locales/pt.json | 17 +- src/locales/yo.json | 17 +- src/locales/zh.json | 17 +- 10 files changed, 500 insertions(+), 9 deletions(-) create mode 100644 src/components/DiscoverPluginsDialog.tsx create mode 100644 src/hooks/useDiscoverPlugins.test.ts create mode 100644 src/hooks/useDiscoverPlugins.ts diff --git a/src/components/DiscoverPluginsDialog.tsx b/src/components/DiscoverPluginsDialog.tsx new file mode 100644 index 00000000..ec1c7722 --- /dev/null +++ b/src/components/DiscoverPluginsDialog.tsx @@ -0,0 +1,229 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Search, Download, ExternalLink, Loader2, Check, Globe, Package } from 'lucide-react'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Card, CardContent } from '@/components/ui/card'; +import { Skeleton } from '@/components/ui/skeleton'; +import { useDiscoverPlugins } from '@/hooks/useDiscoverPlugins'; +import { usePlugins } from '@/hooks/usePlugins'; +import { useAuthor } from '@/hooks/useAuthor'; +import { useToast } from '@/hooks/useToast'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { genUserName } from '@/lib/genUserName'; +import type { NostrMetadata } from '@nostrify/nostrify'; + +interface DiscoverPluginsDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDialogProps) { + const { t } = useTranslation(); + const { data: plugins, isLoading } = useDiscoverPlugins(); + const [searchQuery, setSearchQuery] = useState(''); + + // Filter plugins based on search query + const filteredPlugins = plugins?.filter((plugin) => { + const query = searchQuery.toLowerCase(); + return ( + plugin.name.toLowerCase().includes(query) || + plugin.description.toLowerCase().includes(query) || + plugin.id.toLowerCase().includes(query) + ); + }); + + return ( + + + + + + {t('discoverPlugins')} + + + {t('discoverPluginsDescription')} + + + +
+ {/* Search Input */} +
+ + setSearchQuery(e.target.value)} + className="pl-9" + /> +
+ + {/* Plugins List */} +
+ {isLoading && ( + <> + {[...Array(3)].map((_, i) => ( + + +
+ +
+ + + +
+
+
+
+ ))} + + )} + + {!isLoading && filteredPlugins?.length === 0 && ( +
+ {searchQuery ? t('noPluginsFound') : t('noPluginsAvailable')} +
+ )} + + {!isLoading && filteredPlugins?.map((plugin) => ( + + ))} +
+
+
+
+ ); +} + +interface PluginCardProps { + plugin: { + id: string; + name: string; + description: string; + cloneUrl?: string; + webUrl?: string; + author: string; + }; +} + +function PluginCard({ plugin }: PluginCardProps) { + const { t } = useTranslation(); + const { toast } = useToast(); + const author = useAuthor(plugin.author); + const { clonePlugin, plugins: installedPlugins } = usePlugins(); + const metadata: NostrMetadata | undefined = author.data?.metadata; + + const isInstalled = installedPlugins.includes(plugin.id); + const isInstalling = clonePlugin.isPending && clonePlugin.variables?.pluginName === plugin.id; + + const handleInstall = async () => { + if (!plugin.cloneUrl) { + toast({ + title: t('noCloneUrl'), + description: t('noCloneUrlDescription'), + variant: 'destructive', + }); + return; + } + + try { + await clonePlugin.mutateAsync({ + gitUrl: plugin.cloneUrl, + pluginName: plugin.id, + }); + toast({ + title: t('pluginInstalled'), + description: t('pluginInstalledDescription', { name: plugin.name }), + }); + } catch (error) { + toast({ + title: t('pluginInstallFailed'), + description: error instanceof Error ? error.message : String(error), + variant: 'destructive', + }); + } + }; + + const displayName = metadata?.name ?? genUserName(plugin.author); + const profileImage = metadata?.picture; + + return ( + + + {/* Plugin Header with Author Info */} +
+ + + {displayName.slice(0, 2).toUpperCase()} + +
+
+

{plugin.name}

+ {isInstalled && ( + + + {t('installed')} + + )} +
+

+ {t('by')} {displayName} +

+
+
+ + {/* Plugin Description */} + {plugin.description && ( +

+ {plugin.description} +

+ )} + + {/* Action Buttons */} +
+ + {plugin.webUrl && ( + + )} +
+
+
+ ); +} diff --git a/src/components/PluginsSection.tsx b/src/components/PluginsSection.tsx index 09e7492e..3818d662 100644 --- a/src/components/PluginsSection.tsx +++ b/src/components/PluginsSection.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react'; +import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check, Compass } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -8,12 +8,14 @@ import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/ import { usePlugins } from '@/hooks/usePlugins'; import { usePluginGitInfo } from '@/hooks/usePluginGitInfo'; import { useToast } from '@/hooks/useToast'; +import { DiscoverPluginsDialog } from '@/components/DiscoverPluginsDialog'; export function PluginsSection() { const { t } = useTranslation(); const { toast } = useToast(); const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins(); const [gitUrl, setGitUrl] = useState(''); + const [showDiscoverDialog, setShowDiscoverDialog] = useState(false); const handleAddPlugin = async () => { if (!gitUrl.trim()) return; @@ -79,9 +81,20 @@ export function PluginsSection() {
{/* Plugins Header */}
-
- -

{t('plugins')}

+
+
+ +

{t('plugins')}

+
+

{t('pluginsDescription')} @@ -160,6 +173,12 @@ export function PluginsSection() { + + {/* Discover Plugins Dialog */} +

); } diff --git a/src/hooks/useDiscoverPlugins.test.ts b/src/hooks/useDiscoverPlugins.test.ts new file mode 100644 index 00000000..d694d27f --- /dev/null +++ b/src/hooks/useDiscoverPlugins.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect } from 'vitest'; +import type { NostrEvent } from '@nostrify/nostrify'; + +describe('useDiscoverPlugins', () => { + it('should validate NIP-34 event structure', () => { + // Example of a valid NIP-34 repository announcement event + const validEvent: NostrEvent = { + id: 'test-event-id', + pubkey: 'test-pubkey', + created_at: Math.floor(Date.now() / 1000), + kind: 30617, + tags: [ + ['d', 'test-plugin'], + ['name', 'Test Plugin'], + ['description', 'A test Shakespeare plugin'], + ['clone', 'https://github.com/user/test-plugin.git'], + ['web', 'https://github.com/user/test-plugin'], + ['t', 'shakespeare-plugin'], + ], + content: '', + sig: 'test-signature', + }; + + // Verify the event has the correct kind + expect(validEvent.kind).toBe(30617); + + // Verify required tags exist + const dTag = validEvent.tags.find(([name]) => name === 'd')?.[1]; + const nameTag = validEvent.tags.find(([name]) => name === 'name')?.[1]; + const tTag = validEvent.tags.find(([name, value]) => name === 't' && value === 'shakespeare-plugin'); + + expect(dTag).toBe('test-plugin'); + expect(nameTag).toBe('Test Plugin'); + expect(tTag).toBeDefined(); + }); + + it('should identify required fields for plugin discovery', () => { + const event: NostrEvent = { + id: 'test-event-id', + pubkey: 'test-pubkey', + created_at: Math.floor(Date.now() / 1000), + kind: 30617, + tags: [ + ['d', 'minimal-plugin'], + ['name', 'Minimal Plugin'], + ['t', 'shakespeare-plugin'], + ], + content: '', + sig: 'test-signature', + }; + + const dTag = event.tags.find(([name]) => name === 'd')?.[1]; + const nameTag = event.tags.find(([name]) => name === 'name')?.[1]; + + // These are the minimum required fields + expect(dTag).toBeDefined(); + expect(nameTag).toBeDefined(); + }); + + it('should handle optional fields gracefully', () => { + const event: NostrEvent = { + id: 'test-event-id', + pubkey: 'test-pubkey', + created_at: Math.floor(Date.now() / 1000), + kind: 30617, + tags: [ + ['d', 'plugin-without-optional'], + ['name', 'Plugin Without Optional Fields'], + ['t', 'shakespeare-plugin'], + ], + content: '', + sig: 'test-signature', + }; + + const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1]; + const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1]; + const webTag = event.tags.find(([name]) => name === 'web')?.[1]; + + // Optional fields should be undefined + expect(descriptionTag).toBeUndefined(); + expect(cloneTag).toBeUndefined(); + expect(webTag).toBeUndefined(); + }); +}); diff --git a/src/hooks/useDiscoverPlugins.ts b/src/hooks/useDiscoverPlugins.ts new file mode 100644 index 00000000..43443099 --- /dev/null +++ b/src/hooks/useDiscoverPlugins.ts @@ -0,0 +1,69 @@ +import { useQuery } from '@tanstack/react-query'; +import { useNostr } from '@nostrify/react'; +import type { NostrEvent } from '@nostrify/nostrify'; + +export interface DiscoveredPlugin { + id: string; + event: NostrEvent; + name: string; + description: string; + cloneUrl?: string; + webUrl?: string; + author: string; +} + +/** + * Hook to discover Shakespeare plugins on Nostr + * Queries NIP-34 git repository announcements with t-tag "shakespeare-plugin" + */ +export function useDiscoverPlugins() { + const { nostr } = useNostr(); + + return useQuery({ + queryKey: ['discover-plugins'], + queryFn: async (c) => { + const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]); + + // Query NIP-34 repository announcements (kind 30617) with shakespeare-plugin tag + const events = await nostr.query( + [ + { + kinds: [30617], + '#t': ['shakespeare-plugin'], + limit: 100, + }, + ], + { signal } + ); + + // Transform events into DiscoveredPlugin objects + const plugins: DiscoveredPlugin[] = events + .map((event): DiscoveredPlugin | null => { + const dTag = event.tags.find(([name]) => name === 'd')?.[1]; + const nameTag = event.tags.find(([name]) => name === 'name')?.[1]; + const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1]; + const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1]; + const webTag = event.tags.find(([name]) => name === 'web')?.[1]; + + // Skip events without required fields + if (!dTag || !nameTag) { + return null; + } + + return { + id: dTag, + event, + name: nameTag, + description: descriptionTag || '', + cloneUrl: cloneTag, + webUrl: webTag, + author: event.pubkey, + }; + }) + .filter((plugin): plugin is DiscoveredPlugin => plugin !== null); + + return plugins; + }, + staleTime: 5 * 60 * 1000, // 5 minutes + }); +} diff --git a/src/locales/en.json b/src/locales/en.json index ac451aa5..4efb1a28 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -478,6 +478,21 @@ "noPluginsConfigured": "No plugins configured. Add a plugin to get started.", "pluginsDirectory": "Plugins Directory", "pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.", + "discoverPlugins": "Discover Plugins", + "discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.", + "searchPlugins": "Search plugins...", + "noPluginsFound": "No plugins found matching your search.", + "noPluginsAvailable": "No plugins available at this time.", + "pluginInstalled": "Plugin Installed", + "pluginInstalledDescription": "Plugin \"{{name}}\" has been installed successfully.", + "pluginInstallFailed": "Failed to Install Plugin", + "noCloneUrl": "No Clone URL", + "noCloneUrlDescription": "This plugin does not have a clone URL configured.", + "installed": "Installed", + "install": "Install", + "installing": "Installing...", + "by": "by", + "website": "Website", "mcpServers": "MCP Servers", "mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.", "addMcpServer": "Add MCP Server", diff --git a/src/locales/ha.json b/src/locales/ha.json index 053cd390..49073384 100644 --- a/src/locales/ha.json +++ b/src/locales/ha.json @@ -430,5 +430,20 @@ "modified": "An Canza", "restoreToDefault": "Mayar da asali", "restoredToDefault": "An Mayar da Asali", - "terminal": "Terminal" + "terminal": "Terminal", + "discoverPlugins": "Gano Plugins", + "discoverPluginsDescription": "Bincika kuma shigar da plugins na Shakespeare da aka raba akan hanyar sadarwa ta Nostr.", + "searchPlugins": "Bincika plugins...", + "noPluginsFound": "Ba a sami plugins da suka dace da bincikenka ba.", + "noPluginsAvailable": "Babu plugins a wannan lokaci.", + "pluginInstalled": "An Shigar da Plugin", + "pluginInstalledDescription": "An shigar da plugin \"{{name}}\" cikin nasara.", + "pluginInstallFailed": "An Kasa Shigar da Plugin", + "noCloneUrl": "Babu Clone URL", + "noCloneUrlDescription": "Wannan plugin ba shi da clone URL da aka saita.", + "installed": "An Shigar", + "install": "Shigar", + "installing": "Ana Shigarwa...", + "by": "ta", + "website": "Gidan Yanar Gizo" } diff --git a/src/locales/ig.json b/src/locales/ig.json index cbf2537b..68613793 100644 --- a/src/locales/ig.json +++ b/src/locales/ig.json @@ -427,5 +427,20 @@ "modified": "Gbanwere", "restoreToDefault": "Weghachi na nke mbụ", "restoredToDefault": "Weghachiri na Nke Mbụ", - "terminal": "Terminal" + "terminal": "Terminal", + "discoverPlugins": "Chọpụta Plugins", + "discoverPluginsDescription": "Chọgharịa ma wụnye plugins Shakespeare nke ekekọrịtara na netwọk Nostr.", + "searchPlugins": "Chọọ plugins...", + "noPluginsFound": "Achọtaghị plugins dabara na nchọgharị gị.", + "noPluginsAvailable": "Enweghị plugins dị ugbu a.", + "pluginInstalled": "Ewubatara Plugin", + "pluginInstalledDescription": "Ewubatara plugin \"{{name}}\" nke ọma.", + "pluginInstallFailed": "Ọ Dara Ada Ịwụnye Plugin", + "noCloneUrl": "Enweghị Clone URL", + "noCloneUrlDescription": "Plugin a enweghị clone URL edoziri.", + "installed": "Ewubatara", + "install": "Wụnye", + "installing": "Na-ewunye...", + "by": "site na", + "website": "Webụsaịtị" } diff --git a/src/locales/pt.json b/src/locales/pt.json index 9947de79..62b6bf47 100644 --- a/src/locales/pt.json +++ b/src/locales/pt.json @@ -439,5 +439,20 @@ "modified": "Modificado", "restoreToDefault": "Restaurar para padrão", "restoredToDefault": "Restaurado para Padrão", - "terminal": "Terminal" + "terminal": "Terminal", + "discoverPlugins": "Descobrir Plugins", + "discoverPluginsDescription": "Navegue e instale plugins do Shakespeare compartilhados na rede Nostr.", + "searchPlugins": "Buscar plugins...", + "noPluginsFound": "Nenhum plugin encontrado correspondente à sua busca.", + "noPluginsAvailable": "Nenhum plugin disponível no momento.", + "pluginInstalled": "Plugin Instalado", + "pluginInstalledDescription": "Plugin \"{{name}}\" foi instalado com sucesso.", + "pluginInstallFailed": "Falha ao Instalar Plugin", + "noCloneUrl": "Sem URL de Clone", + "noCloneUrlDescription": "Este plugin não tem uma URL de clone configurada.", + "installed": "Instalado", + "install": "Instalar", + "installing": "Instalando...", + "by": "por", + "website": "Site" } diff --git a/src/locales/yo.json b/src/locales/yo.json index 62286d38..f1e0967d 100644 --- a/src/locales/yo.json +++ b/src/locales/yo.json @@ -427,5 +427,20 @@ "modified": "Ti Yipada", "restoreToDefault": "Pada si atilẹwa", "restoredToDefault": "Ti Pada si Atilẹwa", - "terminal": "Terminal" + "terminal": "Terminal", + "discoverPlugins": "Ṣawari Awọn Plugins", + "discoverPluginsDescription": "Ṣayẹwo ati fi sori ẹrọ awọn plugins Shakespeare ti a pin lori nẹtiwọọki Nostr.", + "searchPlugins": "Wa awọn plugins...", + "noPluginsFound": "Ko si awọn plugins ti o baamu wiwa rẹ.", + "noPluginsAvailable": "Ko si awọn plugins ti o wa ni akoko yii.", + "pluginInstalled": "Plugin Ti Fi Sori Ẹrọ", + "pluginInstalledDescription": "A ti fi plugin \"{{name}}\" sori ẹrọ ni aṣeyọri.", + "pluginInstallFailed": "O Kuna Lati Fi Plugin Sori Ẹrọ", + "noCloneUrl": "Ko Si Clone URL", + "noCloneUrlDescription": "Plugin yii ko ni clone URL ti a ṣeto.", + "installed": "Ti Fi Sori Ẹrọ", + "install": "Fi Sori Ẹrọ", + "installing": "N Fi Sori Ẹrọ...", + "by": "nipasẹ", + "website": "Oju opo wẹẹbu" } diff --git a/src/locales/zh.json b/src/locales/zh.json index 83b361ae..7025324e 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -439,5 +439,20 @@ "modified": "已修改", "restoreToDefault": "恢复默认值", "restoredToDefault": "已恢复默认值", - "terminal": "终端" + "terminal": "终端", + "discoverPlugins": "发现插件", + "discoverPluginsDescription": "浏览并安装在 Nostr 网络上共享的 Shakespeare 插件。", + "searchPlugins": "搜索插件...", + "noPluginsFound": "未找到与您搜索匹配的插件。", + "noPluginsAvailable": "目前没有可用的插件。", + "pluginInstalled": "插件已安装", + "pluginInstalledDescription": "插件 \"{{name}}\" 已成功安装。", + "pluginInstallFailed": "安装插件失败", + "noCloneUrl": "无克隆 URL", + "noCloneUrlDescription": "此插件未配置克隆 URL。", + "installed": "已安装", + "install": "安装", + "installing": "安装中...", + "by": "作者", + "website": "网站" } From 9005a2c38e12e3fe4160c1543a4fbe5dfd7bb39b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 18:06:13 -0600 Subject: [PATCH 23/28] Display plugins from people you follow --- src/components/DiscoverPluginsDialog.tsx | 53 ++++++++++++++++++++---- src/hooks/useDiscoverPlugins.ts | 23 +++++++++- src/locales/en.json | 5 +++ src/locales/ha.json | 7 +++- src/locales/ig.json | 7 +++- src/locales/pt.json | 7 +++- src/locales/yo.json | 7 +++- src/locales/zh.json | 7 +++- 8 files changed, 103 insertions(+), 13 deletions(-) diff --git a/src/components/DiscoverPluginsDialog.tsx b/src/components/DiscoverPluginsDialog.tsx index ec1c7722..02f3b32e 100644 --- a/src/components/DiscoverPluginsDialog.tsx +++ b/src/components/DiscoverPluginsDialog.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Search, Download, ExternalLink, Loader2, Check, Globe, Package } from 'lucide-react'; +import { Search, Download, ExternalLink, Loader2, Check, Globe, Package, LogIn } from 'lucide-react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -10,8 +10,10 @@ import { useDiscoverPlugins } from '@/hooks/useDiscoverPlugins'; import { usePlugins } from '@/hooks/usePlugins'; import { useAuthor } from '@/hooks/useAuthor'; import { useToast } from '@/hooks/useToast'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { genUserName } from '@/lib/genUserName'; +import { Link } from 'react-router-dom'; import type { NostrMetadata } from '@nostrify/nostrify'; interface DiscoverPluginsDialogProps { @@ -21,6 +23,7 @@ interface DiscoverPluginsDialogProps { export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDialogProps) { const { t } = useTranslation(); + const { user } = useCurrentUser(); const { data: plugins, isLoading } = useDiscoverPlugins(); const [searchQuery, setSearchQuery] = useState(''); @@ -61,7 +64,28 @@ export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDia {/* Plugins List */}
- {isLoading && ( + {!user && ( + + +
+ +
+

{t('loginRequired')}

+

+ {t('loginToDiscoverPlugins')} +

+
+ +
+
+
+ )} + + {user && isLoading && ( <> {[...Array(3)].map((_, i) => ( @@ -80,13 +104,28 @@ export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDia )} - {!isLoading && filteredPlugins?.length === 0 && ( -
- {searchQuery ? t('noPluginsFound') : t('noPluginsAvailable')} -
+ {user && !isLoading && filteredPlugins?.length === 0 && ( + + +
+ +
+

+ {searchQuery ? t('noPluginsFound') : t('noPluginsFromNetwork')} +

+

+ {searchQuery + ? t('tryDifferentSearch') + : t('noPluginsFromNetworkDescription') + } +

+
+
+
+
)} - {!isLoading && filteredPlugins?.map((plugin) => ( + {user && !isLoading && filteredPlugins?.map((plugin) => ( ))}
diff --git a/src/hooks/useDiscoverPlugins.ts b/src/hooks/useDiscoverPlugins.ts index 43443099..4770322c 100644 --- a/src/hooks/useDiscoverPlugins.ts +++ b/src/hooks/useDiscoverPlugins.ts @@ -1,6 +1,8 @@ import { useQuery } from '@tanstack/react-query'; import { useNostr } from '@nostrify/react'; import type { NostrEvent } from '@nostrify/nostrify'; +import { useCurrentUser } from './useCurrentUser'; +import { useContacts } from './useContacts'; export interface DiscoveredPlugin { id: string; @@ -15,20 +17,39 @@ export interface DiscoveredPlugin { /** * Hook to discover Shakespeare plugins on Nostr * Queries NIP-34 git repository announcements with t-tag "shakespeare-plugin" + * Filters to only show plugins by the current user and people they follow */ export function useDiscoverPlugins() { const { nostr } = useNostr(); + const { user } = useCurrentUser(); + const { data: contacts } = useContacts(user?.pubkey); return useQuery({ - queryKey: ['discover-plugins'], + queryKey: ['discover-plugins', user?.pubkey, contacts], queryFn: async (c) => { const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]); + // Build authors list: current user + people they follow + const authors: string[] = []; + if (user?.pubkey) { + authors.push(user.pubkey); + } + if (contacts && contacts.length > 0) { + authors.push(...contacts); + } + + // If no authors (user not logged in or no follows), return empty array + if (authors.length === 0) { + return []; + } + // Query NIP-34 repository announcements (kind 30617) with shakespeare-plugin tag + // Filter by authors: current user + people they follow const events = await nostr.query( [ { kinds: [30617], + authors, '#t': ['shakespeare-plugin'], limit: 100, }, diff --git a/src/locales/en.json b/src/locales/en.json index 4efb1a28..4f194261 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -493,6 +493,11 @@ "installing": "Installing...", "by": "by", "website": "Website", + "loginRequired": "Login Required", + "loginToDiscoverPlugins": "Log in with Nostr to discover plugins from people you follow.", + "noPluginsFromNetwork": "No Plugins Found", + "noPluginsFromNetworkDescription": "No plugins found from people you follow. Follow plugin developers on Nostr to see their plugins here.", + "tryDifferentSearch": "Try a different search term.", "mcpServers": "MCP Servers", "mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.", "addMcpServer": "Add MCP Server", diff --git a/src/locales/ha.json b/src/locales/ha.json index 49073384..5db604c5 100644 --- a/src/locales/ha.json +++ b/src/locales/ha.json @@ -445,5 +445,10 @@ "install": "Shigar", "installing": "Ana Shigarwa...", "by": "ta", - "website": "Gidan Yanar Gizo" + "website": "Gidan Yanar Gizo", + "loginRequired": "Ana Buƙatar Shiga", + "loginToDiscoverPlugins": "Shiga tare da Nostr don gano plugins daga mutanen da kuke bi.", + "noPluginsFromNetwork": "Ba a Sami Plugin ba", + "noPluginsFromNetworkDescription": "Ba a sami plugins daga mutanen da kuke bi ba. Bi masu haɓaka plugins akan Nostr don ganin plugins nasu a nan.", + "tryDifferentSearch": "Gwada kalmar bincike daban." } diff --git a/src/locales/ig.json b/src/locales/ig.json index 68613793..b3a88edb 100644 --- a/src/locales/ig.json +++ b/src/locales/ig.json @@ -442,5 +442,10 @@ "install": "Wụnye", "installing": "Na-ewunye...", "by": "site na", - "website": "Webụsaịtị" + "website": "Webụsaịtị", + "loginRequired": "Achọrọ Nbanye", + "loginToDiscoverPlugins": "Banye na Nostr iji chọpụta plugins sitere na ndị ị na-eso.", + "noPluginsFromNetwork": "Achọtaghị Plugins", + "noPluginsFromNetworkDescription": "Achọtaghị plugins sitere na ndị ị na-eso. Soro ndị mmepe plugin na Nostr iji hụ plugins ha ebe a.", + "tryDifferentSearch": "Gbalịa okwu nchọgharị dị iche." } diff --git a/src/locales/pt.json b/src/locales/pt.json index 62b6bf47..b44d6db9 100644 --- a/src/locales/pt.json +++ b/src/locales/pt.json @@ -454,5 +454,10 @@ "install": "Instalar", "installing": "Instalando...", "by": "por", - "website": "Site" + "website": "Site", + "loginRequired": "Login Necessário", + "loginToDiscoverPlugins": "Faça login com Nostr para descobrir plugins de pessoas que você segue.", + "noPluginsFromNetwork": "Nenhum Plugin Encontrado", + "noPluginsFromNetworkDescription": "Nenhum plugin encontrado de pessoas que você segue. Siga desenvolvedores de plugins no Nostr para ver seus plugins aqui.", + "tryDifferentSearch": "Tente um termo de busca diferente." } diff --git a/src/locales/yo.json b/src/locales/yo.json index f1e0967d..4268077f 100644 --- a/src/locales/yo.json +++ b/src/locales/yo.json @@ -442,5 +442,10 @@ "install": "Fi Sori Ẹrọ", "installing": "N Fi Sori Ẹrọ...", "by": "nipasẹ", - "website": "Oju opo wẹẹbu" + "website": "Oju opo wẹẹbu", + "loginRequired": "Wiwọle Nilo", + "loginToDiscoverPlugins": "Wọle pẹlu Nostr lati ṣawari awọn plugins lati ọdọ awọn eniyan ti o ntẹle.", + "noPluginsFromNetwork": "Ko Ri Plugins", + "noPluginsFromNetworkDescription": "Ko ri awọn plugins lati ọdọ awọn eniyan ti o ntẹle. Tẹle awọn olupilẹṣẹ plugin lori Nostr lati rii awọn plugins wọn nibi.", + "tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran." } diff --git a/src/locales/zh.json b/src/locales/zh.json index 7025324e..6cd8419e 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -454,5 +454,10 @@ "install": "安装", "installing": "安装中...", "by": "作者", - "website": "网站" + "website": "网站", + "loginRequired": "需要登录", + "loginToDiscoverPlugins": "使用 Nostr 登录以发现您关注的人的插件。", + "noPluginsFromNetwork": "未找到插件", + "noPluginsFromNetworkDescription": "未找到您关注的人的插件。在 Nostr 上关注插件开发者以在此处查看他们的插件。", + "tryDifferentSearch": "尝试不同的搜索词。" } From acadf07a683de5f997df94809396abfcb41735c4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 18:09:49 -0600 Subject: [PATCH 24/28] Small plugins design tweaks --- src/components/DiscoverPluginsDialog.tsx | 75 +++++++++--------------- 1 file changed, 28 insertions(+), 47 deletions(-) diff --git a/src/components/DiscoverPluginsDialog.tsx b/src/components/DiscoverPluginsDialog.tsx index 02f3b32e..70f30b03 100644 --- a/src/components/DiscoverPluginsDialog.tsx +++ b/src/components/DiscoverPluginsDialog.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Search, Download, ExternalLink, Loader2, Check, Globe, Package, LogIn } from 'lucide-react'; +import { Search, Download, Loader2, Check, Package, LogIn } from 'lucide-react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -39,7 +39,7 @@ export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDia return ( - + @@ -50,9 +50,9 @@ export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDia -
+
{/* Search Input */} -
+
{/* Plugins List */} -
+
{!user && ( @@ -219,49 +219,30 @@ function PluginCard({ plugin }: PluginCardProps) {

)} - {/* Action Buttons */} -
- - {plugin.webUrl && ( - + {/* Action Button */} +
+
); From 9a288c38c7a04d4a53de32f2a97115563cf77ad4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 4 Dec 2025 19:41:29 -0600 Subject: [PATCH 25/28] Allow duplicating a project --- src/components/ActionsMenu.tsx | 21 +++ .../DuplicateProjectDialog.test.tsx | 137 ++++++++++++++++++ src/components/DuplicateProjectDialog.tsx | 119 +++++++++++++++ src/components/Shakespeare/PreviewPane.tsx | 1 + src/lib/ProjectsManager.ts | 59 +++++++- src/locales/en.json | 9 +- src/locales/ha.json | 9 +- src/locales/ig.json | 9 +- src/locales/pt.json | 9 +- src/locales/yo.json | 9 +- src/locales/zh.json | 9 +- 11 files changed, 381 insertions(+), 10 deletions(-) create mode 100644 src/components/DuplicateProjectDialog.test.tsx create mode 100644 src/components/DuplicateProjectDialog.tsx diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 040fcd4d..77015443 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -1,4 +1,5 @@ import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { DropdownMenu, @@ -13,10 +14,12 @@ import { History, Folder, Rocket, + Copy, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; import { DeployDialog } from '@/components/DeployDialog'; +import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog'; interface ActionsMenuProps { projectId: string; @@ -39,9 +42,11 @@ export function ActionsMenu({ disabled = false, onFirstInteraction: _onFirstInteraction, }: ActionsMenuProps) { + const { t } = useTranslation(); const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); const [deployDialogOpen, setDeployDialogOpen] = useState(false); + const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false); const isAnyLoading = isLoading || isBuildLoading; @@ -98,6 +103,15 @@ export function ActionsMenu({ Deploy + setDuplicateDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + {t('duplicateProject')} + + + + ); } \ No newline at end of file diff --git a/src/components/DuplicateProjectDialog.test.tsx b/src/components/DuplicateProjectDialog.test.tsx new file mode 100644 index 00000000..aaab0c9d --- /dev/null +++ b/src/components/DuplicateProjectDialog.test.tsx @@ -0,0 +1,137 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { DuplicateProjectDialog } from './DuplicateProjectDialog'; +import { TestApp } from '@/test/TestApp'; + +// Mock the navigate function +const mockNavigate = vi.fn(); +vi.mock('react-router-dom', async () => { + const actual = await vi.importActual('react-router-dom'); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe('DuplicateProjectDialog', () => { + beforeEach(() => { + mockNavigate.mockClear(); + }); + + it('renders dialog when open', () => { + render( + + {}} + /> + + ); + + expect(screen.getByRole('dialog')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Duplicate Project' })).toBeInTheDocument(); + expect(screen.getByText('Create a copy of this project with a new name')).toBeInTheDocument(); + }); + + it('does not render dialog when closed', () => { + render( + + {}} + /> + + ); + + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('shows default project name with -copy suffix', () => { + render( + + {}} + /> + + ); + + const input = screen.getByLabelText('New Project Name'); + expect(input).toHaveValue('Test Project-copy'); + }); + + it('allows changing the project name', async () => { + const user = userEvent.setup(); + + render( + + {}} + /> + + ); + + const input = screen.getByLabelText('New Project Name'); + await user.clear(input); + await user.type(input, 'My New Project'); + + expect(input).toHaveValue('My New Project'); + }); + + it('disables duplicate button when name is empty', async () => { + const user = userEvent.setup(); + + render( + + {}} + /> + + ); + + const input = screen.getByLabelText('New Project Name'); + const duplicateButton = screen.getByRole('button', { name: /Duplicate Project/i }); + + // Clear the input + await user.clear(input); + + // Button should be disabled when input is empty + expect(duplicateButton).toBeDisabled(); + }); + + it('closes dialog when cancel button is clicked', async () => { + const user = userEvent.setup(); + const onOpenChange = vi.fn(); + + render( + + + + ); + + const cancelButton = screen.getByRole('button', { name: /Cancel/i }); + await user.click(cancelButton); + + await waitFor(() => { + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + }); +}); diff --git a/src/components/DuplicateProjectDialog.tsx b/src/components/DuplicateProjectDialog.tsx new file mode 100644 index 00000000..1fb56331 --- /dev/null +++ b/src/components/DuplicateProjectDialog.tsx @@ -0,0 +1,119 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useNavigate } from 'react-router-dom'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useToast } from '@/hooks/useToast'; +import { useQueryClient } from '@tanstack/react-query'; + +interface DuplicateProjectDialogProps { + projectId: string; + projectName: string; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function DuplicateProjectDialog({ + projectId, + projectName, + open, + onOpenChange, +}: DuplicateProjectDialogProps) { + const { t } = useTranslation(); + const navigate = useNavigate(); + const { toast } = useToast(); + const projectsManager = useProjectsManager(); + const queryClient = useQueryClient(); + const [newName, setNewName] = useState(`${projectName}-copy`); + const [isLoading, setIsLoading] = useState(false); + + const handleDuplicate = async () => { + if (!newName.trim()) { + return; + } + + setIsLoading(true); + + try { + const duplicatedProject = await projectsManager.duplicateProject(projectId, newName); + + // Invalidate projects query to refresh the list + await queryClient.invalidateQueries({ queryKey: ['projects'] }); + + toast({ + title: t('projectDuplicated'), + description: t('projectDuplicatedDescription'), + }); + + // Close dialog + onOpenChange(false); + + // Navigate to the new project + navigate(`/project/${duplicatedProject.id}`); + } catch (error) { + console.error('Failed to duplicate project:', error); + toast({ + title: t('failedToDuplicateProject'), + description: error instanceof Error ? error.message : String(error), + variant: 'destructive', + }); + } finally { + setIsLoading(false); + } + }; + + return ( + + + + {t('duplicateProject')} + + {t('duplicateProjectDescription')} + + +
+
+ + setNewName(e.target.value)} + placeholder={`${projectName}-copy`} + disabled={isLoading} + onKeyDown={(e) => { + if (e.key === 'Enter' && newName.trim()) { + handleDuplicate(); + } + }} + /> +
+
+ + + + +
+
+ ); +} diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index a24e9115..8434a701 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -708,6 +708,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{hasBuiltProject ? (