esbuild almost works!

This commit is contained in:
Alex Gleason committed 2025-08-06 20:57:33 -05:00
1 parent 6009ee7360
commit 28ec6f98cf
6 files changed
+210 -49

No files matched your search

+20 -49
View File
@@ -1,4 +1,3 @@
import { useState, useRef, useEffect } from 'react';
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage, generateId } from 'ai';
import { Button } from '@/components/ui/button';
@@ -8,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useJSRuntime } from '@/hooks/useJSRuntime';
import { useKeepAlive } from '@/hooks/useKeepAlive';
import { copyDirectory, copyFile } from '@/lib/copyFiles';
import { copyDirectory } from '@/lib/copyFiles';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { bytesToHex } from 'nostr-tools/utils';
import { MessageItem } from '@/components/ai/MessageItem';
@@ -19,6 +18,7 @@ import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
import { buildProject } from "@/lib/build";
interface ChatPaneProps {
projectId: string;
@@ -72,56 +72,27 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
setIsBuildLoading(true);
updateMetadata('Shakespeare', `Building ${projectName}...`);
const dist = await buildProject(browserFS, projectId);
console.log(dist);
// Delete all existing files in "dist" directory
try {
console.log('Running build for project:', projectId);
const runtimeFS = await runtime.fs();
// Copy project files to runtime filesystem
const projectPath = `/projects/${projectId}`;
try {
await copyDirectory(browserFS, runtimeFS, projectPath, '.');
console.log('Successfully copied project to runtime');
} catch (error) {
console.error('Failed to copy project to runtime:', error);
return;
for (const file of await browserFS.readdir(`/projects/${projectId}/dist`)) {
await browserFS.unlink(`/projects/${projectId}/dist/${file}`);
}
// Install dependencies and build
const proc = await runtime.spawn('npm', ['i']);
await proc.exit;
const proc2 = await runtime.spawn('npm', ['run', 'build']);
await proc2.exit;
// Copy "dist" directory from runtime back to project filesystem
const distPath = `/projects/${projectId}/dist`;
try {
await copyDirectory(runtimeFS, browserFS, 'dist', distPath);
console.log('Successfully copied dist from runtime');
} catch (error) {
console.error('Failed to copy dist:', error);
}
// Copy package-lock.json from runtime back to project filesystem
const packageLockPath = `/projects/${projectId}/package-lock.json`;
try {
await copyFile(runtimeFS, browserFS, 'package-lock.json', packageLockPath);
console.log('Successfully copied package-lock.json from runtime');
} catch (error) {
console.error('Failed to copy package-lock.json:', error);
}
// Dispatch build complete event to refresh the preview iframe
const buildCompleteEvent = new CustomEvent('buildComplete', {
detail: { projectId }
});
window.dispatchEvent(buildCompleteEvent);
console.log('Build completed successfully, dispatched refresh event');
} catch (error) {
console.error('Build failed:', error);
} finally {
setIsBuildLoading(false);
} catch {
// Ignore errors (e.g., directory doesn't exist)
}
await browserFS.mkdir(`/projects/${projectId}/dist`, { recursive: true });
for (const [path, contents] of Object.entries(dist)) {
await browserFS.writeFile(`/projects/${projectId}/dist/${path}`, contents);
}
setIsBuildLoading(false);
};
const runDeploy = async () => {
+40
View File
@@ -0,0 +1,40 @@
import type { Plugin } from 'esbuild-wasm';
export function esmShPlugin(): Plugin {
return {
name: 'esm-sh',
setup(build) {
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => ({
path: `https://esm.sh/${args.path}`,
namespace: 'http',
}));
// Handle relative or absolute imports inside esm.sh modules
build.onResolve({ filter: /.*/, namespace: 'http' }, (args) => {
const baseURL = new URL(args.importer); // e.g., https://esm.sh/react-dom/client
const fullURL = new URL(args.path, baseURL).toString(); // resolve "/x" → full URL
return {
path: fullURL,
namespace: 'http',
};
});
// Load HTTP modules
build.onLoad({ filter: /.*/, namespace: 'http' }, async (args) => {
const res = await fetch(args.path);
if (!res.ok) {
throw new Error(`Failed to fetch ${args.path}`);
}
const contents = await res.text();
return {
contents,
loader: 'js',
};
});
},
};
}
+43
View File
@@ -0,0 +1,43 @@
import * as esbuild from 'esbuild-wasm';
import { esmShPlugin } from './esmShPlugin';
import { lightningFsPlugin } from './lightningFsPlugin';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
await esbuild.initialize({
worker: false,
wasmURL: 'https://unpkg.com/esbuild-wasm/esbuild.wasm',
});
export async function buildProject(fs: JSRuntimeFS, projectId: string): Promise<Record<string, Uint8Array>> {
const indexHtml = await fs.readFile(`/projects/${projectId}/index.html`, 'utf8');
// TODO: parse indexHtml to find entryPoints
// The file will have an absolute path like `/src/main.tsx` which must be converted to a relative path like `main.tsx`
const results = await esbuild.build({
entryPoints: ['main.tsx'],
bundle: true,
write: false,
format: 'esm',
target: 'esnext',
outdir: 'dist',
plugins: [
lightningFsPlugin(fs, `/projects/${projectId}/src`),
esmShPlugin(),
],
});
const dist: Record<string, Uint8Array> = {};
for (const file of results.outputFiles) {
const relativePath = file.path.replace(/^\/dist\//, '');
dist[relativePath] = file.contents;
}
// FIXME: We need to ensure that dist files are imported inside the index.html. If a file was processed from an existing tag, its path might need to be updated, otherwise it might need to be imported (eg a css output file due to css import in js)
dist['index.html'] = new TextEncoder().encode(indexHtml);
return dist;
}
+82
View File
@@ -0,0 +1,82 @@
import path from 'path-browserify';
import type { Loader, Plugin } from 'esbuild-wasm';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
export function lightningFsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
return {
name: 'lightning-fs',
setup(build) {
build.onResolve({ filter: /.*/ }, async (args) => {
let resolved: string;
if (args.path.startsWith('@/')) {
resolved = path.join(cwd, args.path.slice(2));
} else if (args.path.startsWith('/')) {
resolved = args.path;
} else {
resolved = path.join(cwd, args.resolveDir, args.path);
}
try {
resolved = await tryFileVariants(fs, resolved);
} catch {
return; // Let other plugins handle this
}
return {
path: resolved,
namespace: 'lightning-fs',
};
});
build.onLoad({ filter: /.*/, namespace: 'lightning-fs' }, async (args) => {
const ext = path.extname(args.path).slice(1);
if (!['ts', 'tsx', 'js', 'jsx', 'css'].includes(ext)) {
return;
}
return {
contents: await fs.readFile(args.path, 'utf8'),
loader: ext as Loader,
};
});
},
};
}
async function tryFileVariants(fs: JSRuntimeFS, basePath: string): Promise<string> {
const extensions = ['.ts', '.tsx', '.js', '.jsx', '.css'];
try {
await fs.stat(basePath);
return basePath;
} catch {
// Ignore
}
// Try direct file with extensions
for (const ext of extensions) {
const full = basePath + ext;
try {
await fs.stat(full);
return full;
} catch {
// Ignore
}
}
// Try directory index files
for (const ext of extensions) {
const indexFile = path.join(basePath, 'index' + ext);
try {
await fs.stat(indexFile);
return indexFile;
} catch {
// Ignore
}
}
throw new Error('File not found');
}