Force FS types into a shared RuntimeFS type

This commit is contained in:
Alex Gleason committed 2025-07-20 16:45:04 -05:00
1 parent 93a57b2560
commit 9dc856d46e
9 files changed
+226 -95

No files matched your search

+4 -1
View File
@@ -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 (
<FSContext.Provider value={contextValue}>
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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<FSContextType | undefined>(undefined);
+5 -5
View File
@@ -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}` };
+29 -2
View File
@@ -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<Uint8Array>;
readFile(path: string, encoding: 'utf8'): Promise<string>;
readFile(path: string, encoding: string): Promise<string>;
readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
writeFile(path: string, data: string | Uint8Array): Promise<void>;
writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void>;
// readdir overloads for different return types
readdir(path: string): Promise<string[]>;
readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;
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<void>;
rmdir(path: string): Promise<void>;
rename(oldPath: string, newPath: string): Promise<void>;
}
/**
+105
View File
@@ -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<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
return this.lightningFS.readFile(path, encoding);
}
async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void> {
return this.lightningFS.writeFile(path, data, encoding);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
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<void> {
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<void> {
return this.lightningFS.unlink(path);
}
async rmdir(path: string): Promise<void> {
return this.lightningFS.rmdir(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
return this.lightningFS.rename(oldPath, newPath);
}
}
+66 -7
View File
@@ -52,6 +52,10 @@ export class WebContainerAdapter implements JSRuntime {
class WebContainerFSAdapter implements JSRuntimeFS {
constructor(private webcontainer: WebContainer) {}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
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<void> {
return this.webcontainer.fs.writeFile(path, data);
async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void> {
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<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
if (options?.withFileTypes) {
return this.webcontainer.fs.readdir(path, { withFileTypes: true }) as Promise<DirectoryEntry[]>;
@@ -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<void> {
// 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<void> {
// 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<void> {
// 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');
}
}
+9 -71
View File
@@ -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<void> {
@@ -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<void> {
@@ -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<void> {
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;
}
}
+4 -5
View File
@@ -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,