diff --git a/src/components/FSProvider.tsx b/src/components/FSProvider.tsx index 1f3dbe41..2f91a58a 100644 --- a/src/components/FSProvider.tsx +++ b/src/components/FSProvider.tsx @@ -1,6 +1,7 @@ import { ReactNode } from 'react'; import type LightningFS from '@isomorphic-git/lightning-fs'; import { FSContext, type FSContextType } from '@/contexts/FSContext'; +import { LightningFSAdapter } from '@/lib/LightningFSAdapter'; interface FSProviderProps { children: ReactNode; @@ -8,7 +9,9 @@ interface FSProviderProps { } export function FSProvider({ children, fs }: FSProviderProps) { - const contextValue: FSContextType = { fs }; + const contextValue: FSContextType = { + fs: new LightningFSAdapter(fs) + }; return ( diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 21a4b60b..3fafc19c 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -11,7 +11,7 @@ import { useAISettings } from '@/hooks/useAISettings'; import { FsToolSet } from '@/lib/FsToolSet'; import { useFS } from '@/hooks/useFS'; import { useJSRuntime } from '@/hooks/useJSRuntime'; -import { copyDirectory, copyToRuntime } from '@/lib/copyFiles'; +import { copyDirectory } from '@/lib/copyFiles'; interface ChatPaneProps { projectId: string; @@ -48,7 +48,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { // Copy project files to runtime filesystem const projectPath = `/projects/${projectId}`; try { - await copyToRuntime(fs, runtime.fs, projectPath, '.'); + await copyDirectory(fs, runtime.fs, projectPath, '.'); console.log('Successfully copied project to runtime'); } catch (error) { console.error('Failed to copy project to runtime:', error); diff --git a/src/contexts/FSContext.ts b/src/contexts/FSContext.ts index 41073a67..31cc710e 100644 --- a/src/contexts/FSContext.ts +++ b/src/contexts/FSContext.ts @@ -1,8 +1,8 @@ import { createContext } from 'react'; -import type LightningFS from '@isomorphic-git/lightning-fs'; +import type { JSRuntimeFS } from '@/lib/JSRuntime'; export interface FSContextType { - fs: LightningFS.PromisifiedFS; + fs: JSRuntimeFS; } export const FSContext = createContext(undefined); \ No newline at end of file diff --git a/src/lib/FsToolSet.ts b/src/lib/FsToolSet.ts index 6174acf0..d9bd76da 100644 --- a/src/lib/FsToolSet.ts +++ b/src/lib/FsToolSet.ts @@ -1,4 +1,4 @@ -import type LightningFS from '@isomorphic-git/lightning-fs'; +import type { JSRuntimeFS } from '@/lib/JSRuntime'; import { join } from "@std/path/posix/join"; import { dirname } from "@std/path/posix/dirname"; import { relative } from "@std/path/posix/relative"; @@ -7,7 +7,7 @@ import { tool } from "ai"; import z from 'zod'; export class FsToolSet { - constructor(readonly fs: LightningFS.PromisifiedFS, private cwd?: string) {} + constructor(readonly fs: JSRuntimeFS, private cwd?: string) {} readonly readFile = tool({ description: 'Read the contents of a file in the project', @@ -32,7 +32,7 @@ export class FsToolSet { // Ensure directory exists const dir = dirname(filepath); await this.ensureDirectory(dir); - + await this.fs.writeFile(filepath, args.content, 'utf8'); return { success: true, message: `File ${args.filePath} written successfully` }; } catch (error) { @@ -120,7 +120,7 @@ export class FsToolSet { // Ensure destination directory exists const destDir = dirname(destPath); await this.ensureDirectory(destDir); - + await this.fs.rename(sourcePath, destPath); return { success: true, message: `Moved ${args.sourcePath} to ${args.destinationPath}` }; } catch (error) { @@ -139,7 +139,7 @@ export class FsToolSet { // Ensure destination directory exists const destDir = dirname(destPath); await this.ensureDirectory(destDir); - + const content = await this.fs.readFile(sourcePath); await this.fs.writeFile(destPath, content); return { success: true, message: `Copied ${args.sourcePath} to ${args.destinationPath}` }; diff --git a/src/lib/JSRuntime.ts b/src/lib/JSRuntime.ts index 5dd51b5d..f5cc2c80 100644 --- a/src/lib/JSRuntime.ts +++ b/src/lib/JSRuntime.ts @@ -11,13 +11,40 @@ export interface DirectoryEntry { /** * Filesystem interface compatible with both WebContainer and LightningFS + * This interface unifies the APIs of both filesystem implementations */ export interface JSRuntimeFS { + // Core file operations with proper overloads for type safety + readFile(path: string): Promise; + readFile(path: string, encoding: 'utf8'): Promise; + readFile(path: string, encoding: string): Promise; readFile(path: string, encoding?: string): Promise; - writeFile(path: string, data: string | Uint8Array): Promise; + + writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise; + + // readdir overloads for different return types + readdir(path: string): Promise; + readdir(path: string, options: { withFileTypes: true }): Promise; readdir(path: string, options?: { withFileTypes?: boolean }): Promise; + mkdir(path: string, options?: { recursive?: boolean }): Promise; - stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean }>; + stat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }>; + lstat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }>; + + // Additional operations that LightningFS supports + unlink(path: string): Promise; + rmdir(path: string): Promise; + rename(oldPath: string, newPath: string): Promise; } /** diff --git a/src/lib/LightningFSAdapter.ts b/src/lib/LightningFSAdapter.ts new file mode 100644 index 00000000..72419f65 --- /dev/null +++ b/src/lib/LightningFSAdapter.ts @@ -0,0 +1,105 @@ +import type LightningFS from '@isomorphic-git/lightning-fs'; +import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; + +/** + * LightningFS adapter that implements JSRuntimeFS interface + * This makes LightningFS compatible with the unified filesystem interface + */ +export class LightningFSAdapter implements JSRuntimeFS { + constructor(private lightningFS: LightningFS.PromisifiedFS) {} + + async readFile(path: string): Promise; + async readFile(path: string, encoding: 'utf8'): Promise; + async readFile(path: string, encoding: string): Promise; + async readFile(path: string, encoding?: string): Promise; + async readFile(path: string, encoding?: string): Promise { + return this.lightningFS.readFile(path, encoding); + } + + async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise { + return this.lightningFS.writeFile(path, data, encoding); + } + + async readdir(path: string): Promise; + async readdir(path: string, options: { withFileTypes: true }): Promise; + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise; + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { + if (options?.withFileTypes) { + // LightningFS doesn't support withFileTypes, so we need to simulate it + const items = await this.lightningFS.readdir(path); + const entries: DirectoryEntry[] = []; + + for (const item of items) { + const itemPath = `${path}/${item}`; + try { + const stat = await this.lightningFS.stat(itemPath); + entries.push({ + name: item, + isDirectory: stat.isDirectory.bind(stat), + isFile: stat.isFile.bind(stat), + }); + } catch { + // If stat fails, assume it's a file + entries.push({ + name: item, + isDirectory: () => false, + isFile: () => true, + }); + } + } + + return entries; + } else { + return this.lightningFS.readdir(path); + } + } + + async mkdir(path: string, options?: { recursive?: boolean }): Promise { + if (options?.recursive) { + // LightningFS doesn't support recursive option, so we need to create directories one by one + const parts = path.split('/').filter(Boolean); + let currentPath = path.startsWith('/') ? '/' : ''; + + for (const part of parts) { + currentPath = currentPath === '/' ? `/${part}` : `${currentPath}/${part}`; + try { + await this.lightningFS.mkdir(currentPath); + } catch { + // Directory might already exist, continue + } + } + } else { + return this.lightningFS.mkdir(path); + } + } + + async stat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }> { + return this.lightningFS.stat(path); + } + + async lstat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }> { + return this.lightningFS.lstat(path); + } + + async unlink(path: string): Promise { + return this.lightningFS.unlink(path); + } + + async rmdir(path: string): Promise { + return this.lightningFS.rmdir(path); + } + + async rename(oldPath: string, newPath: string): Promise { + return this.lightningFS.rename(oldPath, newPath); + } +} \ No newline at end of file diff --git a/src/lib/WebContainerAdapter.ts b/src/lib/WebContainerAdapter.ts index c396665d..9baaa888 100644 --- a/src/lib/WebContainerAdapter.ts +++ b/src/lib/WebContainerAdapter.ts @@ -52,6 +52,10 @@ export class WebContainerAdapter implements JSRuntime { class WebContainerFSAdapter implements JSRuntimeFS { constructor(private webcontainer: WebContainer) {} + async readFile(path: string): Promise; + async readFile(path: string, encoding: 'utf8'): Promise; + async readFile(path: string, encoding: string): Promise; + async readFile(path: string, encoding?: string): Promise; async readFile(path: string, encoding?: string): Promise { if (encoding) { return this.webcontainer.fs.readFile(path, encoding as 'utf8'); @@ -60,10 +64,17 @@ class WebContainerFSAdapter implements JSRuntimeFS { } } - async writeFile(path: string, data: string | Uint8Array): Promise { - return this.webcontainer.fs.writeFile(path, data); + async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise { + if (encoding) { + return this.webcontainer.fs.writeFile(path, data, encoding as 'utf8'); + } else { + return this.webcontainer.fs.writeFile(path, data); + } } + async readdir(path: string): Promise; + async readdir(path: string, options: { withFileTypes: true }): Promise; + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise; async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { if (options?.withFileTypes) { return this.webcontainer.fs.readdir(path, { withFileTypes: true }) as Promise; @@ -80,7 +91,12 @@ class WebContainerFSAdapter implements JSRuntimeFS { } } - async stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean }> { + async stat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }> { // WebContainer doesn't have a stat method, so we'll implement a workaround try { // Try to read as directory first @@ -88,13 +104,56 @@ class WebContainerFSAdapter implements JSRuntimeFS { return { isDirectory: () => true, isFile: () => false, + size: undefined, + mtimeMs: undefined, }; } catch { // If readdir fails, assume it's a file - return { - isDirectory: () => false, - isFile: () => true, - }; + try { + const content = await this.webcontainer.fs.readFile(path) as string | Uint8Array; + const size = typeof content === 'string' ? content.length : content.byteLength; + return { + isDirectory: () => false, + isFile: () => true, + size, + mtimeMs: Date.now(), // WebContainer doesn't provide modification time + }; + } catch { + return { + isDirectory: () => false, + isFile: () => true, + size: undefined, + mtimeMs: undefined, + }; + } } } + + async lstat(path: string): Promise<{ + isDirectory(): boolean; + isFile(): boolean; + size?: number; + mtimeMs?: number; + }> { + // WebContainer doesn't have a lstat method, so we can use stat directly + return this.stat(path); + } + + async unlink(_path: string): Promise { + // WebContainer doesn't expose unlink, so we'll throw an error for now + throw new Error('unlink operation not supported in WebContainer'); + } + + async rmdir(_path: string): Promise { + // WebContainer doesn't expose rmdir, so we'll throw an error for now + throw new Error('rmdir operation not supported in WebContainer'); + } + + async rename(oldPath: string, newPath: string): Promise { + // WebContainer doesn't expose rename, so we'll implement it by copying and deleting + const content = await this.webcontainer.fs.readFile(oldPath); + await this.webcontainer.fs.writeFile(newPath, content); + // Note: We can't delete the old file since WebContainer doesn't expose unlink + console.warn('WebContainer rename: copied file but could not delete original'); + } } \ No newline at end of file diff --git a/src/lib/copyFiles.ts b/src/lib/copyFiles.ts index c1f656ac..938710f9 100644 --- a/src/lib/copyFiles.ts +++ b/src/lib/copyFiles.ts @@ -1,16 +1,15 @@ -import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; -import type LightningFS from '@isomorphic-git/lightning-fs'; +import type { JSRuntimeFS } from './JSRuntime'; /** * Copy files and directories between two filesystem instances - * @param sourceFS Source filesystem (e.g., WebContainer fs) - * @param targetFS Target filesystem (e.g., LightningFS) + * @param sourceFS Source filesystem + * @param targetFS Target filesystem * @param sourcePath Source directory path * @param targetPath Target directory path */ export async function copyFiles( sourceFS: JSRuntimeFS, - targetFS: LightningFS.PromisifiedFS, + targetFS: JSRuntimeFS, sourcePath: string, targetPath: string ): Promise { @@ -18,12 +17,12 @@ export async function copyFiles( console.log(`Copying: ${sourcePath} -> ${targetPath}`); // Get source directory contents - const items = await sourceFS.readdir(sourcePath, { withFileTypes: true }) as DirectoryEntry[]; + const items = await sourceFS.readdir(sourcePath, { withFileTypes: true }); console.log(`Found ${items.length} items in ${sourcePath}`); // Ensure target directory exists try { - await targetFS.mkdir(targetPath); + await targetFS.mkdir(targetPath, { recursive: true }); } catch { // Directory might already exist, that's fine } @@ -37,7 +36,7 @@ export async function copyFiles( if (item.isDirectory()) { console.log(`Creating directory: ${targetItemPath}`); try { - await targetFS.mkdir(targetItemPath); + await targetFS.mkdir(targetItemPath, { recursive: true }); } catch { // Directory might already exist } @@ -61,12 +60,12 @@ export async function copyFiles( } /** - * Copy a directory from JSRuntime filesystem to LightningFS + * Copy a directory between JSRuntime filesystems * Convenience wrapper for copyFiles with better error handling */ export async function copyDirectory( sourceFS: JSRuntimeFS, - targetFS: LightningFS.PromisifiedFS, + targetFS: JSRuntimeFS, sourcePath: string, targetPath: string ): Promise { @@ -82,65 +81,4 @@ export async function copyDirectory( console.error(`Failed to copy directory ${sourcePath} to ${targetPath}:`, error); throw error; } -} - -/** - * Copy files from LightningFS to JSRuntime filesystem - * @param sourceFS Source filesystem (LightningFS) - * @param targetFS Target filesystem (JSRuntime) - * @param sourcePath Source directory path - * @param targetPath Target directory path - */ -export async function copyToRuntime( - sourceFS: LightningFS.PromisifiedFS, - targetFS: JSRuntimeFS, - sourcePath: string, - targetPath: string -): Promise { - try { - console.log(`Copying to runtime: ${sourcePath} -> ${targetPath}`); - - // Get source directory contents - const items = await sourceFS.readdir(sourcePath); - console.log(`Found ${items.length} items in ${sourcePath}`); - - // Ensure target directory exists - try { - await targetFS.mkdir(targetPath, { recursive: true }); - } catch { - // Directory might already exist, that's fine - } - - // Copy each item - for (const item of items) { - const sourceItemPath = `${sourcePath}/${item}`; - const targetItemPath = `${targetPath}/${item}`; - - try { - const stat = await sourceFS.stat(sourceItemPath); - - if (stat.isDirectory()) { - console.log(`Creating directory: ${targetItemPath}`); - try { - await targetFS.mkdir(targetItemPath); - } catch { - // Directory might already exist - } - // Recursively copy directory contents - await copyToRuntime(sourceFS, targetFS, sourceItemPath, targetItemPath); - } else { - console.log(`Copying file: ${sourceItemPath} -> ${targetItemPath}`); - const content = await sourceFS.readFile(sourceItemPath); - await targetFS.writeFile(targetItemPath, content); - } - } catch (itemError) { - console.warn(`Failed to copy item ${item}:`, itemError); - } - } - - console.log(`Successfully copied ${sourcePath} to runtime`); - } catch (error) { - console.error(`Failed to copy ${sourcePath} to runtime:`, error); - throw error; - } } \ No newline at end of file diff --git a/src/lib/fs.ts b/src/lib/fs.ts index d9ea12b6..e888ec12 100644 --- a/src/lib/fs.ts +++ b/src/lib/fs.ts @@ -1,7 +1,7 @@ -import LightningFS from '@isomorphic-git/lightning-fs'; import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; import { Buffer } from 'buffer'; +import type { JSRuntimeFS } from '@/lib/JSRuntime'; // Polyfill Buffer for browser if (typeof window !== 'undefined') { @@ -20,10 +20,10 @@ export interface Project { } export class ProjectsManager { - fs: LightningFS.PromisifiedFS; + fs: JSRuntimeFS; dir: string; - constructor(fs: LightningFS.PromisifiedFS) { + constructor(fs: JSRuntimeFS) { this.fs = fs; this.dir = '/projects'; } @@ -64,9 +64,8 @@ export class ProjectsManager { async cloneTemplate(projectPath: string) { // Create a LightningFS instance for git operations - const gitFS = new LightningFS('shakespeare-fs'); await git.clone({ - fs: gitFS, + fs: this.fs, http, dir: projectPath, url: GIT_TEMPLATE_URL,