Abstract WebContainer into "JSRuntime" type

This commit is contained in:
Alex Gleason committed 2025-07-20 16:21:49 -05:00
1 parent 0986dd4e9d
commit 78398bcd7d
8 files changed
+316 -102

No files matched your search

+22 -15
View File
@@ -15,6 +15,8 @@ import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { FSProvider } from '@/components/FSProvider';
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
import { WebContainerAdapter } from '@/lib/WebContainerAdapter';
import AppRouter from './AppRouter';
const head = createHead({
@@ -49,26 +51,31 @@ const presetRelays = [
const lightningFS = new LightningFS('shakespeare-fs');
const fs = lightningFS.promises;
// Initialize JSRuntime with WebContainer adapter
const jsRuntime = new WebContainerAdapter();
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
<JSRuntimeProvider runtime={jsRuntime}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</JSRuntimeProvider>
</FSProvider>
</AppProvider>
</UnheadProvider>
+18
View File
@@ -0,0 +1,18 @@
import { ReactNode } from 'react';
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
import type { JSRuntime } from '@/lib/JSRuntime';
interface JSRuntimeProviderProps {
children: ReactNode;
runtime: JSRuntime;
}
export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) {
const contextValue: JSRuntimeContextType = { runtime };
return (
<JSRuntimeContext.Provider value={contextValue}>
{children}
</JSRuntimeContext.Provider>
);
}
+20 -87
View File
@@ -1,4 +1,4 @@
import { FileSystemTree, WebContainer } from '@webcontainer/api';
import { FileSystemTree } from '@webcontainer/api';
import { useState, useRef, useEffect } from 'react';
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
import { Button } from '@/components/ui/button';
@@ -10,8 +10,9 @@ import { cn } from '@/lib/utils';
import { useAISettings } from '@/hooks/useAISettings';
import { FsToolSet } from '@/lib/FsToolSet';
import { useFS } from '@/hooks/useFS';
const webcontainerPromise = WebContainer.boot();
import { useJSRuntime } from '@/hooks/useJSRuntime';
import { copyDirectory } from '@/lib/copyFiles';
import type { WebContainerAdapter } from '@/lib/WebContainerAdapter';
interface ChatPaneProps {
projectId: string;
@@ -27,6 +28,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { settings, isConfigured } = useAISettings();
const { fs } = useFS();
const { runtime } = useJSRuntime();
const addMessage = (message: AIMessage) => {
setMessages((prev) => {
@@ -44,8 +46,6 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
};
const runBuild = async () => {
const webcontainer = await webcontainerPromise;
const buildFileTree = async (dirPath: string): Promise<FileSystemTree> => {
const tree: FileSystemTree = {};
const items = await fs.readdir(dirPath);
@@ -71,95 +71,28 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
return tree;
};
// Build file tree and mount to WebContainer
const fsTree = await buildFileTree(`/projects/${projectId}`);
await webcontainer.mount(fsTree);
// Mount the file tree (this will boot the container if needed)
const webcontainerAdapter = runtime as WebContainerAdapter;
await webcontainerAdapter.mount(fsTree);
// Install dependencies and build
const proc = await webcontainer.spawn('npm', ['i']);
const proc = await runtime.spawn('npm', ['i']);
await proc.exit;
const proc2 = await webcontainer.spawn('npm', ['run', 'build']);
const proc2 = await runtime.spawn('npm', ['run', 'build']);
await proc2.exit;
// Copy "dist" out of the webcontainer back to the project directory
const copyDist = async () => {
try {
// Read the dist directory from webcontainer
const distContents = await webcontainer.fs.readdir('dist', { withFileTypes: true });
// Create dist directory in project if it doesn't exist
const distPath = `/projects/${projectId}/dist`;
try {
await fs.mkdir(distPath);
} catch {
// Directory might already exist, that's fine
}
// Helper function to copy directory recursively
const copyDirectory = async (sourcePath: string, destPath: string) => {
try {
console.log(`Copying directory: ${sourcePath}`);
const items = await webcontainer.fs.readdir(sourcePath, { withFileTypes: true });
console.log(`Found ${items.length} items in ${sourcePath}`);
for (const item of items) {
const sourceItemPath = `${sourcePath}/${item.name}`;
const destItemPath = `${destPath}/${item.name}`;
try {
if (item.isDirectory()) {
console.log(`Creating directory: ${destItemPath}`);
try {
await fs.mkdir(destItemPath);
} catch {
// Directory might already exist
}
await copyDirectory(sourceItemPath, destItemPath);
} else {
console.log(`Copying file: ${sourceItemPath} -> ${destItemPath}`);
const content = await webcontainer.fs.readFile(sourceItemPath);
await fs.writeFile(destItemPath, content);
}
} catch (itemError) {
console.warn(`Failed to copy item ${item.name}:`, itemError);
}
}
} catch (error) {
console.warn(`Failed to copy ${sourcePath}:`, error);
}
};
// Copy each package in dist
for (const item of distContents) {
const sourcePath = `dist/${item.name}`;
const destPath = `${distPath}/${item.name}`;
try {
if (item.isDirectory()) {
console.log(`Processing directory: ${item.name}`);
try {
await fs.mkdir(destPath);
} catch {
// Directory might already exist
}
await copyDirectory(sourcePath, destPath);
} else {
console.log(`Processing file: ${item.name}`);
const content = await webcontainer.fs.readFile(sourcePath);
await fs.writeFile(destPath, content);
}
} catch (itemError) {
console.warn(`Failed to process ${item.name}:`, itemError);
}
}
console.log('Successfully copied node_modules from webcontainer');
} catch (error) {
console.error('Failed to copy node_modules:', error);
}
};
await copyDist();
// Copy "dist" directory from runtime back to project filesystem
const distPath = `/projects/${projectId}/dist`;
try {
await copyDirectory(runtime.fs, fs, 'dist', distPath);
console.log('Successfully copied dist from runtime');
} catch (error) {
console.error('Failed to copy dist:', error);
}
};
useEffect(() => {
+8
View File
@@ -0,0 +1,8 @@
import { createContext } from 'react';
import type { JSRuntime } from '@/lib/JSRuntime';
export interface JSRuntimeContextType {
runtime: JSRuntime;
}
export const JSRuntimeContext = createContext<JSRuntimeContextType | undefined>(undefined);
+14
View File
@@ -0,0 +1,14 @@
import { useContext } from 'react';
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
/**
* Hook to access the JavaScript runtime
* @returns JSRuntime context with runtime instance
*/
export function useJSRuntime(): JSRuntimeContextType {
const context = useContext(JSRuntimeContext);
if (context === undefined) {
throw new Error('useJSRuntime must be used within a JSRuntimeProvider');
}
return context;
}
+40
View File
@@ -0,0 +1,40 @@
import type { WebContainerProcess } from '@webcontainer/api';
/**
* Directory entry with file type information
*/
export interface DirectoryEntry {
name: string;
isDirectory(): boolean;
isFile(): boolean;
}
/**
* Filesystem interface compatible with both WebContainer and LightningFS
*/
export interface JSRuntimeFS {
readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
writeFile(path: string, data: string | Uint8Array): Promise<void>;
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 }>;
}
/**
* JavaScript runtime interface for executing code and managing files
*/
export interface JSRuntime {
/**
* Filesystem access
*/
readonly fs: JSRuntimeFS;
/**
* Spawn a process in the runtime environment
* @param command Command to execute
* @param args Command arguments
* @param options Spawn options
* @returns Process handle
*/
spawn(command: string, args?: string[], options?: Record<string, unknown>): Promise<WebContainerProcess>;
}
+109
View File
@@ -0,0 +1,109 @@
import { WebContainer, type WebContainerProcess, type FileSystemTree } from '@webcontainer/api';
import type { JSRuntime, JSRuntimeFS, DirectoryEntry } from './JSRuntime';
/**
* WebContainer adapter that implements the JSRuntime interface
*/
export class WebContainerAdapter implements JSRuntime {
private webcontainer: WebContainer | null = null;
private bootPromise: Promise<WebContainer> | null = null;
private _fs: JSRuntimeFS | null = null;
/**
* Get the filesystem interface
*/
get fs(): JSRuntimeFS {
if (!this._fs) {
throw new Error('WebContainer not initialized. Call spawn() first to initialize.');
}
return this._fs;
}
/**
* Ensure WebContainer is booted
*/
private async ensureBooted(): Promise<WebContainer> {
if (this.webcontainer) {
return this.webcontainer;
}
if (!this.bootPromise) {
this.bootPromise = WebContainer.boot();
}
this.webcontainer = await this.bootPromise;
this._fs = new WebContainerFSAdapter(this.webcontainer);
return this.webcontainer;
}
/**
* Spawn a process in the WebContainer
* Automatically boots the container on first call
*/
async spawn(command: string, args: string[] = [], options: Record<string, unknown> = {}): Promise<WebContainerProcess> {
const webcontainer = await this.ensureBooted();
return webcontainer.spawn(command, args, options);
}
/**
* Mount a file tree in the WebContainer
* This is a convenience method for setting up the container
*/
async mount(tree: FileSystemTree): Promise<void> {
const webcontainer = await this.ensureBooted();
return webcontainer.mount(tree);
}
}
/**
* WebContainer filesystem adapter that implements JSRuntimeFS
*/
class WebContainerFSAdapter implements JSRuntimeFS {
constructor(private webcontainer: WebContainer) {}
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
if (encoding) {
return this.webcontainer.fs.readFile(path, encoding as 'utf8');
} else {
return this.webcontainer.fs.readFile(path);
}
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
return this.webcontainer.fs.writeFile(path, data);
}
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
if (options?.withFileTypes) {
return this.webcontainer.fs.readdir(path, { withFileTypes: true }) as Promise<DirectoryEntry[]>;
} else {
return this.webcontainer.fs.readdir(path) as Promise<string[]>;
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
if (options?.recursive) {
await this.webcontainer.fs.mkdir(path, { recursive: true });
} else {
await this.webcontainer.fs.mkdir(path);
}
}
async stat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean }> {
// WebContainer doesn't have a stat method, so we'll implement a workaround
try {
// Try to read as directory first
await this.webcontainer.fs.readdir(path);
return {
isDirectory: () => true,
isFile: () => false,
};
} catch {
// If readdir fails, assume it's a file
return {
isDirectory: () => false,
isFile: () => true,
};
}
}
}
+85
View File
@@ -0,0 +1,85 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
import type LightningFS from '@isomorphic-git/lightning-fs';
/**
* Copy files and directories between two filesystem instances
* @param sourceFS Source filesystem (e.g., WebContainer fs)
* @param targetFS Target filesystem (e.g., LightningFS)
* @param sourcePath Source directory path
* @param targetPath Target directory path
*/
export async function copyFiles(
sourceFS: JSRuntimeFS,
targetFS: LightningFS.PromisifiedFS,
sourcePath: string,
targetPath: string
): Promise<void> {
try {
console.log(`Copying: ${sourcePath} -> ${targetPath}`);
// Get source directory contents
const items = await sourceFS.readdir(sourcePath, { withFileTypes: true }) as DirectoryEntry[];
console.log(`Found ${items.length} items in ${sourcePath}`);
// Ensure target directory exists
try {
await targetFS.mkdir(targetPath);
} catch {
// Directory might already exist, that's fine
}
// Copy each item
for (const item of items) {
const sourceItemPath = `${sourcePath}/${item.name}`;
const targetItemPath = `${targetPath}/${item.name}`;
try {
if (item.isDirectory()) {
console.log(`Creating directory: ${targetItemPath}`);
try {
await targetFS.mkdir(targetItemPath);
} catch {
// Directory might already exist
}
// Recursively copy directory contents
await copyFiles(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.name}:`, itemError);
}
}
console.log(`Successfully copied ${sourcePath} to ${targetPath}`);
} catch (error) {
console.error(`Failed to copy ${sourcePath}:`, error);
throw error;
}
}
/**
* Copy a directory from JSRuntime filesystem to LightningFS
* Convenience wrapper for copyFiles with better error handling
*/
export async function copyDirectory(
sourceFS: JSRuntimeFS,
targetFS: LightningFS.PromisifiedFS,
sourcePath: string,
targetPath: string
): Promise<void> {
try {
// Check if source exists and is a directory
const sourceStat = await sourceFS.stat(sourcePath);
if (!sourceStat.isDirectory()) {
throw new Error(`Source path ${sourcePath} is not a directory`);
}
await copyFiles(sourceFS, targetFS, sourcePath, targetPath);
} catch (error) {
console.error(`Failed to copy directory ${sourcePath} to ${targetPath}:`, error);
throw error;
}
}