mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad5902cdc6 | ||
|
|
ce4a602270 | ||
|
|
5e352e60e9 | ||
|
|
adeb3bf53f | ||
|
|
588e32a43d | ||
|
|
57e12261af | ||
|
|
797984c5d3 | ||
|
|
6d49648580 | ||
|
|
4d6bc91650 | ||
|
|
2fdf8a3740 | ||
|
|
f4ccc2d924 | ||
|
|
6f4aa264eb |
No files matched your search
@@ -168,6 +168,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
||||||
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
||||||
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
||||||
|
- `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options
|
||||||
|
- `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files
|
||||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||||
- `/src/hooks/`: Custom hooks including:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `useNostr`: Core Nostr protocol integration
|
||||||
@@ -182,7 +184,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useSessionManager`: Access session management for AI chat sessions
|
- `useSessionManager`: Access session management for AI chat sessions
|
||||||
- `useGitStatus`: Real-time Git repository status monitoring
|
- `useGitStatus`: Real-time Git repository status monitoring
|
||||||
- `useProjects`: Project management and CRUD operations
|
- `useProjects`: Project management and CRUD operations
|
||||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
|
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||||
- `useTheme`: Theme management
|
- `useTheme`: Theme management
|
||||||
- `useToast`: Toast notifications
|
- `useToast`: Toast notifications
|
||||||
- `useLocalStorage`: Persistent local storage
|
- `useLocalStorage`: Persistent local storage
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
|
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||||
@@ -9,6 +9,9 @@ import { useProjects } from '@/hooks/useProjects';
|
|||||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
|
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||||
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
import type { Project } from '@/lib/ProjectsManager';
|
import type { Project } from '@/lib/ProjectsManager';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
@@ -92,6 +95,9 @@ export function ProjectSidebar({
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { data: projects = [], isLoading, error } = useProjects();
|
const { data: projects = [], isLoading, error } = useProjects();
|
||||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||||
|
const projectsManager = useProjectsManager();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||||
|
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -117,6 +123,25 @@ export function ProjectSidebar({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||||
|
try {
|
||||||
|
// Import project from zip file
|
||||||
|
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||||
|
|
||||||
|
// Show success toast
|
||||||
|
toast({
|
||||||
|
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||||
|
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Navigate to the imported project
|
||||||
|
navigate(`/project/${project.id}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to import project:', error);
|
||||||
|
throw error; // Re-throw to let the dialog handle the error display
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||||
}, [favorites, queryClient]);
|
}, [favorites, queryClient]);
|
||||||
@@ -186,6 +211,13 @@ export function ProjectSidebar({
|
|||||||
<GitBranch className="h-4 w-4" />
|
<GitBranch className="h-4 w-4" />
|
||||||
{t('importRepository')}
|
{t('importRepository')}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => setIsZipDialogOpen(true)}
|
||||||
|
className="flex items-center gap-2 w-full"
|
||||||
|
>
|
||||||
|
<FileArchive className="h-4 w-4" />
|
||||||
|
Import ZIP File
|
||||||
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
@@ -248,6 +280,13 @@ export function ProjectSidebar({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* ZIP Import Dialog */}
|
||||||
|
<ZipImportDialog
|
||||||
|
onImport={handleImportZip}
|
||||||
|
open={isZipDialogOpen}
|
||||||
|
onOpenChange={setIsZipDialogOpen}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import { ZipImportDialog } from './ZipImportDialog';
|
||||||
|
import { TestApp } from '@/test/TestApp';
|
||||||
|
|
||||||
|
// Mock the useProjects hook
|
||||||
|
const mockProjects = [
|
||||||
|
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
|
||||||
|
];
|
||||||
|
|
||||||
|
vi.mock('@/hooks/useProjects', () => ({
|
||||||
|
useProjects: () => ({
|
||||||
|
data: mockProjects,
|
||||||
|
isLoading: false,
|
||||||
|
error: null
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('ZipImportDialog', () => {
|
||||||
|
const mockOnImport = vi.fn();
|
||||||
|
const defaultProps = {
|
||||||
|
onImport: mockOnImport,
|
||||||
|
disabled: false
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockOnImport.mockClear();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders dialog trigger button', () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens dialog when trigger is clicked', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('processes file selection without displaying project ID', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open dialog
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
// Create a mock file
|
||||||
|
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Find the hidden file input by ref
|
||||||
|
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||||
|
|
||||||
|
if (fileInput) {
|
||||||
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||||
|
}
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
// Verify that the file name is displayed (from the file selection area)
|
||||||
|
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
|
||||||
|
// Verify that Project ID label is not displayed
|
||||||
|
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows overwrite warning when project ID already exists', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open dialog
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
// Create a mock file that will generate an existing project ID
|
||||||
|
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Find the hidden file input by ref
|
||||||
|
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||||
|
|
||||||
|
if (fileInput) {
|
||||||
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||||
|
}
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls onImport with correct parameters when import button is clicked', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open dialog
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
// Create a mock file
|
||||||
|
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Find the hidden file input by ref
|
||||||
|
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||||
|
|
||||||
|
if (fileInput) {
|
||||||
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for file to be processed
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Click import button
|
||||||
|
const importButton = screen.getByText('Import Project');
|
||||||
|
fireEvent.click(importButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open dialog
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
// Create a mock file that will generate an existing project ID
|
||||||
|
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Find the hidden file input by ref
|
||||||
|
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||||
|
|
||||||
|
if (fileInput) {
|
||||||
|
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for overwrite button to appear
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Click overwrite button
|
||||||
|
const overwriteButton = screen.getByText('Overwrite Project');
|
||||||
|
fireEvent.click(overwriteButton);
|
||||||
|
|
||||||
|
// Check for overwrite confirmation dialog
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
|
||||||
|
// Use a more flexible matcher for the text that might be split across elements
|
||||||
|
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
|
||||||
|
if (dialogContent) {
|
||||||
|
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
|
||||||
|
}
|
||||||
|
}, { timeout: 2000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not show project ID input field (simplified interface)', async () => {
|
||||||
|
render(
|
||||||
|
<TestApp>
|
||||||
|
<ZipImportDialog {...defaultProps} />
|
||||||
|
</TestApp>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open dialog
|
||||||
|
const triggerButton = screen.getByText('Import ZIP');
|
||||||
|
fireEvent.click(triggerButton);
|
||||||
|
|
||||||
|
// Check that there's no input field for project ID
|
||||||
|
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||||
|
import { Progress } from '@/components/ui/progress';
|
||||||
|
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||||
|
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
|
||||||
|
import { useProjects } from '@/hooks/useProjects';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface ZipImportDialogProps {
|
||||||
|
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||||
|
disabled?: boolean;
|
||||||
|
className?: string;
|
||||||
|
open?: boolean;
|
||||||
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
|
||||||
|
// Use controlled state if props are provided, otherwise use internal state
|
||||||
|
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||||
|
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||||
|
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||||
|
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||||
|
const [generatedId, setGeneratedId] = useState('');
|
||||||
|
const [isImporting, setIsImporting] = useState(false);
|
||||||
|
const [importProgress, setImportProgress] = useState(0);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
|
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
||||||
|
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const { data: projects = [] } = useProjects();
|
||||||
|
|
||||||
|
const handleFileSelect = (file: File) => {
|
||||||
|
// Only accept zip files
|
||||||
|
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||||
|
setError('Please select a ZIP file');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelectedFile(file);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
// Auto-generate ID from file name
|
||||||
|
const baseName = file.name.replace(/\.zip$/i, '');
|
||||||
|
const id = baseName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
setGeneratedId(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check for existing project when generated ID changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (generatedId && projects.length > 0) {
|
||||||
|
const existing = projects.find(project => project.id === generatedId);
|
||||||
|
setExistingProject(existing || null);
|
||||||
|
} else {
|
||||||
|
setExistingProject(null);
|
||||||
|
}
|
||||||
|
}, [generatedId, projects]);
|
||||||
|
|
||||||
|
// Drag and drop handlers
|
||||||
|
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragOver(false);
|
||||||
|
|
||||||
|
const files = Array.from(e.dataTransfer.files);
|
||||||
|
if (files.length > 0) {
|
||||||
|
handleFileSelect(files[0]);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
setIsDragOver(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
setIsDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDropDialog = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
setIsDragOver(false);
|
||||||
|
|
||||||
|
const files = Array.from(e.dataTransfer.files);
|
||||||
|
if (files.length > 0) {
|
||||||
|
handleFileSelect(files[0]);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleClickUpload = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileRemove = () => {
|
||||||
|
setSelectedFile(null);
|
||||||
|
setGeneratedId('');
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImport = async (overwrite = false) => {
|
||||||
|
if (!selectedFile) return;
|
||||||
|
|
||||||
|
setIsImporting(true);
|
||||||
|
setImportProgress(0);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Simulate progress for better UX
|
||||||
|
const progressInterval = setInterval(() => {
|
||||||
|
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||||
|
}, 200);
|
||||||
|
|
||||||
|
await onImport(selectedFile, overwrite, generatedId);
|
||||||
|
|
||||||
|
clearInterval(progressInterval);
|
||||||
|
setImportProgress(100);
|
||||||
|
|
||||||
|
// Close dialog after a short delay
|
||||||
|
setTimeout(() => {
|
||||||
|
setIsOpen(false);
|
||||||
|
setSelectedFile(null);
|
||||||
|
setGeneratedId('');
|
||||||
|
setImportProgress(0);
|
||||||
|
setExistingProject(null);
|
||||||
|
}, 1000);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to import project');
|
||||||
|
setImportProgress(0);
|
||||||
|
} finally {
|
||||||
|
setIsImporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportWithOverwriteCheck = async () => {
|
||||||
|
if (!selectedFile || !generatedId) return;
|
||||||
|
|
||||||
|
// Check if project with this ID already exists
|
||||||
|
try {
|
||||||
|
// This would ideally be passed as a prop or through context
|
||||||
|
// For now, we'll assume the parent will handle the check and pass existing project info
|
||||||
|
if (existingProject) {
|
||||||
|
setShowOverwriteDialog(true);
|
||||||
|
} else {
|
||||||
|
await handleImport(false);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking existing project:', error);
|
||||||
|
await handleImport(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmOverwrite = async () => {
|
||||||
|
setShowOverwriteDialog(false);
|
||||||
|
await handleImport(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
if (!isImporting) {
|
||||||
|
setIsOpen(false);
|
||||||
|
setSelectedFile(null);
|
||||||
|
setGeneratedId('');
|
||||||
|
setError(null);
|
||||||
|
setImportProgress(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||||
|
// (no open/onOpenChange props provided)
|
||||||
|
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||||
|
{!isControlled && (
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={disabled}
|
||||||
|
className={cn("gap-2", className)}
|
||||||
|
>
|
||||||
|
<FileArchive className="h-4 w-4" />
|
||||||
|
Import ZIP
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DialogContent
|
||||||
|
className="sm:max-w-md"
|
||||||
|
onDragOver={handleDragOverDialog}
|
||||||
|
onDragLeave={handleDragLeaveDialog}
|
||||||
|
onDrop={handleDropDialog}
|
||||||
|
>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<Upload className="h-5 w-5" />
|
||||||
|
Import Project from ZIP
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{!isImporting && (
|
||||||
|
<>
|
||||||
|
{/* Drag and Drop Area */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
||||||
|
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||||
|
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||||
|
)}
|
||||||
|
onClick={handleClickUpload}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
onChange={(e) => {
|
||||||
|
const files = e.target.files;
|
||||||
|
if (files && files.length > 0) {
|
||||||
|
handleFileSelect(files[0]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
accept=".zip"
|
||||||
|
className="hidden"
|
||||||
|
disabled={isImporting}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
{selectedFile ? (
|
||||||
|
<FileText className="h-8 w-8 text-green-600" />
|
||||||
|
) : (
|
||||||
|
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{selectedFile ? (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-medium text-green-600">
|
||||||
|
{selectedFile.name}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleFileRemove();
|
||||||
|
}}
|
||||||
|
className="text-xs text-destructive hover:underline"
|
||||||
|
>
|
||||||
|
Remove file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
Drop your ZIP file here or click to browse
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Supports ZIP files up to 50MB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error Display */}
|
||||||
|
{error && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Overwrite Warning */}
|
||||||
|
{existingProject && (
|
||||||
|
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
||||||
|
<AlertCircle className="h-3 w-3" />
|
||||||
|
A project with this ID already exists. You can choose to overwrite it.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Import Button */}
|
||||||
|
<div className="flex justify-end gap-2 pt-4">
|
||||||
|
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleImportWithOverwriteCheck}
|
||||||
|
disabled={!selectedFile || !generatedId || isImporting}
|
||||||
|
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||||
|
>
|
||||||
|
{existingProject ? (
|
||||||
|
<>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Overwrite Project
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload className="mr-2 h-4 w-4" />
|
||||||
|
Import Project
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Import Progress */}
|
||||||
|
{isImporting && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||||
|
Importing project...
|
||||||
|
</div>
|
||||||
|
<Progress value={importProgress} className="w-full" />
|
||||||
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
|
Extracting files and setting up project...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Success State */}
|
||||||
|
{!isImporting && importProgress === 100 && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||||
|
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||||
|
</svg>
|
||||||
|
Project imported successfully!
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Overwrite Confirmation Dialog */}
|
||||||
|
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle className="flex items-center gap-2">
|
||||||
|
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||||
|
Overwrite Existing Project
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription className="space-y-2">
|
||||||
|
<p>
|
||||||
|
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
||||||
|
Overwriting it will:
|
||||||
|
</p>
|
||||||
|
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||||
|
<li><strong>Delete all existing files</strong> in the project</li>
|
||||||
|
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||||
|
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||||
|
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||||
|
</ul>
|
||||||
|
<p className="text-amber-600 font-medium">
|
||||||
|
This action cannot be undone. Are you sure you want to continue?
|
||||||
|
</p>
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={confirmOverwrite}
|
||||||
|
className="bg-amber-600 hover:bg-amber-700"
|
||||||
|
>
|
||||||
|
Yes, Overwrite Project
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,27 @@ const createMockNostr = (): NPool => ({
|
|||||||
close: vi.fn(),
|
close: vi.fn(),
|
||||||
}) as unknown as NPool;
|
}) as unknown as NPool;
|
||||||
|
|
||||||
|
// Mock JSZip
|
||||||
|
vi.mock('jszip', () => ({
|
||||||
|
default: class MockJSZip {
|
||||||
|
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
|
||||||
|
|
||||||
|
static async loadAsync(buffer: ArrayBuffer) {
|
||||||
|
const instance = new MockJSZip();
|
||||||
|
// Add a mock file entry
|
||||||
|
instance.files['package.json'] = {
|
||||||
|
dir: false,
|
||||||
|
async: () => new Uint8Array(buffer)
|
||||||
|
};
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
async file(name: string) {
|
||||||
|
return this.files[name];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
// Mock filesystem for testing
|
// Mock filesystem for testing
|
||||||
class MockFS implements JSRuntimeFS {
|
class MockFS implements JSRuntimeFS {
|
||||||
private files: Map<string, string | Uint8Array> = new Map();
|
private files: Map<string, string | Uint8Array> = new Map();
|
||||||
@@ -269,6 +290,156 @@ describe('ProjectsManager', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('importProjectFromZip', () => {
|
||||||
|
it('should preserve original project name when overwriting', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Create an existing project with a specific name
|
||||||
|
await fs.mkdir('/projects/my-project');
|
||||||
|
await fs.mkdir('/projects/my-project/.git');
|
||||||
|
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
|
||||||
|
|
||||||
|
// Mock the git methods to simulate existing project
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file with different name
|
||||||
|
const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import with overwrite
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
|
||||||
|
|
||||||
|
// Should preserve original project name
|
||||||
|
expect(project.name).toBe('my-project');
|
||||||
|
expect(project.id).toBe('my-project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should use new project name when not overwriting', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Mock the git methods
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file
|
||||||
|
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import without overwrite
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||||
|
|
||||||
|
// Should use formatted name from ID
|
||||||
|
expect(project.name).toBe('new-project');
|
||||||
|
expect(project.id).toBe('new-project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should prevent zip slip attacks during import', async () => {
|
||||||
|
await projectsManager.init();
|
||||||
|
|
||||||
|
// Mock the git methods
|
||||||
|
const mockGit = {
|
||||||
|
init: vi.fn(),
|
||||||
|
clone: vi.fn(),
|
||||||
|
add: vi.fn(),
|
||||||
|
commit: vi.fn(),
|
||||||
|
getConfig: vi.fn(),
|
||||||
|
getAllFiles: vi.fn().mockResolvedValue([]),
|
||||||
|
} as Partial<import('./git').Git>;
|
||||||
|
|
||||||
|
// Replace git instance
|
||||||
|
Object.assign(projectsManager, { git: mockGit });
|
||||||
|
|
||||||
|
// Create a mock ZIP file that would try to escape the project directory
|
||||||
|
const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' });
|
||||||
|
|
||||||
|
// Mock JSZip to simulate a malicious ZIP with path traversal
|
||||||
|
const JSZip = await import('jszip');
|
||||||
|
|
||||||
|
const mockLoadAsync = vi.fn().mockResolvedValue({
|
||||||
|
files: {
|
||||||
|
'../../../etc/passwd': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||||
|
},
|
||||||
|
'../../outside.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||||
|
},
|
||||||
|
'safe-file.txt': {
|
||||||
|
dir: false,
|
||||||
|
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync);
|
||||||
|
|
||||||
|
// Mock arrayBuffer method
|
||||||
|
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||||
|
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||||
|
writable: false
|
||||||
|
});
|
||||||
|
|
||||||
|
// Spy on console.warn to check for security warnings
|
||||||
|
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Import the malicious ZIP
|
||||||
|
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||||
|
|
||||||
|
// Should have completed successfully (safe files extracted)
|
||||||
|
expect(project).toBeDefined();
|
||||||
|
|
||||||
|
// Should have logged a security warning about skipped files
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'),
|
||||||
|
['../../../etc/passwd', '../../outside.txt']
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify that only safe files would be written (check writeFile calls)
|
||||||
|
const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || [];
|
||||||
|
const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) =>
|
||||||
|
call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt')
|
||||||
|
);
|
||||||
|
expect(maliciousPaths).toHaveLength(0);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// Restore mocks
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('renameProject', () => {
|
describe('renameProject', () => {
|
||||||
it('should rename a project directory', async () => {
|
it('should rename a project directory', async () => {
|
||||||
await projectsManager.init();
|
await projectsManager.init();
|
||||||
|
|||||||
+241
-1
@@ -1,5 +1,6 @@
|
|||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
import type { Git } from '@/lib/git';
|
import JSZip from 'jszip';
|
||||||
|
import { Git } from '@/lib/git';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
|
|
||||||
// Polyfill Buffer for browser
|
// Polyfill Buffer for browser
|
||||||
@@ -95,6 +96,192 @@ export class ProjectsManager {
|
|||||||
return project;
|
return project;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||||
|
// Generate a project ID based on the zip file name or use custom ID
|
||||||
|
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||||
|
const generatedId = baseName
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
|
||||||
|
// Determine the project ID to use
|
||||||
|
let id: string;
|
||||||
|
if (customId) {
|
||||||
|
// Use the provided custom ID (for overwrite scenarios)
|
||||||
|
id = customId;
|
||||||
|
} else {
|
||||||
|
// If no custom ID, generate a unique ID (for new projects)
|
||||||
|
id = await this.generateUniqueProjectId(generatedId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectPath = `${this.dir}/${id}`;
|
||||||
|
const projectExists = await this.projectExists(id);
|
||||||
|
|
||||||
|
// Check if project with this ID already exists when not overwriting
|
||||||
|
if (projectExists && !overwrite) {
|
||||||
|
throw new Error(`Project with ID "${id}" already exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get original project name if overwriting, otherwise use formatted name
|
||||||
|
let projectName: string;
|
||||||
|
if (overwrite && projectExists) {
|
||||||
|
const existingProject = await this.getProject(id);
|
||||||
|
projectName = existingProject?.name || this.formatProjectName(id);
|
||||||
|
} else {
|
||||||
|
projectName = this.formatProjectName(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create project directory (or ensure it exists for overwrite)
|
||||||
|
await this.fs.mkdir(projectPath, { recursive: true });
|
||||||
|
|
||||||
|
// If overwriting, delete existing files except .ai directory and .git directory
|
||||||
|
if (projectExists && overwrite) {
|
||||||
|
const existingFiles = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of existingFiles) {
|
||||||
|
// Preserve .ai directory and .git directory
|
||||||
|
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||||
|
try {
|
||||||
|
await this.fs.unlink(`${projectPath}/${file}`);
|
||||||
|
} catch {
|
||||||
|
// Ignore deletion errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the zip file
|
||||||
|
const arrayBuffer = await zipFile.arrayBuffer();
|
||||||
|
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||||
|
|
||||||
|
// Extract all files from the zip with security validation
|
||||||
|
const extractedFiles: string[] = [];
|
||||||
|
const skippedFiles: string[] = [];
|
||||||
|
|
||||||
|
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||||
|
// Validate the extraction path is within the project directory
|
||||||
|
const extractPath = this.join(projectPath, relativePath);
|
||||||
|
|
||||||
|
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||||
|
skippedFiles.push(relativePath);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (zipEntry.dir) {
|
||||||
|
// Create the directory structure
|
||||||
|
await this.fs.mkdir(extractPath, { recursive: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract file content
|
||||||
|
const content = await zipEntry.async('uint8array');
|
||||||
|
|
||||||
|
// Ensure parent directory exists
|
||||||
|
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||||
|
if (dirPath) {
|
||||||
|
await this.fs.mkdir(dirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the file (this will overwrite existing files)
|
||||||
|
await this.fs.writeFile(extractPath, content);
|
||||||
|
extractedFiles.push(relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFiles.length > 0) {
|
||||||
|
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get filesystem stats for timestamps
|
||||||
|
const stats = await this.fs.stat(projectPath);
|
||||||
|
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||||
|
|
||||||
|
// Initialize git repository if there's no .git directory
|
||||||
|
try {
|
||||||
|
await this.fs.stat(`${projectPath}/.git`);
|
||||||
|
|
||||||
|
// If git exists and we're overwriting, stage the new files
|
||||||
|
if (overwrite) {
|
||||||
|
const projectFiles = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of projectFiles) {
|
||||||
|
// Skip .git directory and .ai directory
|
||||||
|
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||||
|
try {
|
||||||
|
await this.git.add({
|
||||||
|
dir: projectPath,
|
||||||
|
filepath: file,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Ignore git add errors for files that might be gitignored
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make commit for the overwrite
|
||||||
|
await this.git.commit({
|
||||||
|
dir: projectPath,
|
||||||
|
message: `Overwrite project from ${zipFile.name}`,
|
||||||
|
author: {
|
||||||
|
name: 'shakespeare.diy',
|
||||||
|
email: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// No .git directory found, initialize new repository
|
||||||
|
await this.git.init({
|
||||||
|
dir: projectPath,
|
||||||
|
defaultBranch: 'main',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add all files to git (excluding .ai directory)
|
||||||
|
const projectFiles = await this.getAllFiles(projectPath);
|
||||||
|
for (const file of projectFiles) {
|
||||||
|
// Skip .git directory and .ai directory
|
||||||
|
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||||
|
await this.git.add({
|
||||||
|
dir: projectPath,
|
||||||
|
filepath: file,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make initial commit
|
||||||
|
await this.git.commit({
|
||||||
|
dir: projectPath,
|
||||||
|
message: `Import project from ${zipFile.name}`,
|
||||||
|
author: {
|
||||||
|
name: 'shakespeare.diy',
|
||||||
|
email: '[email protected]',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create .ai/history directory
|
||||||
|
try {
|
||||||
|
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||||
|
} catch {
|
||||||
|
// Directory might already exist
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: projectName,
|
||||||
|
path: projectPath,
|
||||||
|
lastModified: timestamp,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// Clean up on error (only if this was a new project creation)
|
||||||
|
if (!projectExists) {
|
||||||
|
try {
|
||||||
|
await this.deleteDirectory(projectPath);
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||||
const id = customId || await this.generateUniqueProjectId(name);
|
const id = customId || await this.generateUniqueProjectId(name);
|
||||||
|
|
||||||
@@ -402,4 +589,57 @@ export class ProjectsManager {
|
|||||||
|
|
||||||
return files;
|
return files;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe path join that normalizes the result to prevent directory traversal
|
||||||
|
*/
|
||||||
|
private join(...paths: string[]): string {
|
||||||
|
// Simple path joining with normalization
|
||||||
|
const joined = paths.join('/').replace(/\/+/g, '/');
|
||||||
|
|
||||||
|
// Normalize path separators and resolve .. and . components
|
||||||
|
const parts = joined.split('/').filter(part => part !== '');
|
||||||
|
const normalized: string[] = [];
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part === '..') {
|
||||||
|
normalized.pop();
|
||||||
|
} else if (part !== '.') {
|
||||||
|
normalized.push(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/' + normalized.join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a path is within the project directory
|
||||||
|
*/
|
||||||
|
private isPathWithinProject(extractPath: string, projectPath: string): boolean {
|
||||||
|
// Normalize both paths
|
||||||
|
const normalizedExtractPath = this.normalize(extractPath);
|
||||||
|
const normalizedProjectPath = this.normalize(projectPath);
|
||||||
|
|
||||||
|
// Check if the extract path starts with the project path
|
||||||
|
return normalizedExtractPath.startsWith(normalizedProjectPath + '/') ||
|
||||||
|
normalizedExtractPath === normalizedProjectPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a path by resolving . and .. components
|
||||||
|
*/
|
||||||
|
private normalize(path: string): string {
|
||||||
|
const parts = path.split('/').filter(part => part !== '');
|
||||||
|
const normalized: string[] = [];
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part === '..') {
|
||||||
|
normalized.pop();
|
||||||
|
} else if (part !== '.') {
|
||||||
|
normalized.push(part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/' + normalized.join('/');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+7
-2
@@ -15,7 +15,6 @@ import { parseProviderModel } from '@/lib/parseProviderModel';
|
|||||||
import type { AIMessage } from '@/lib/SessionManager';
|
import type { AIMessage } from '@/lib/SessionManager';
|
||||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||||
import type OpenAI from 'openai';
|
import type OpenAI from 'openai';
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { ModelSelector } from '@/components/ModelSelector';
|
import { ModelSelector } from '@/components/ModelSelector';
|
||||||
@@ -262,7 +261,13 @@ export default function Index() {
|
|||||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create project:', error);
|
console.error('Failed to create project:', error);
|
||||||
checkForKeyFailure(error);
|
if (!checkForKeyFailure(error)) {
|
||||||
|
toast({
|
||||||
|
title: "Project Creation Failed",
|
||||||
|
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setIsCreating(false);
|
setIsCreating(false);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user