From 91e75d8abe1e2c5dbaf8c34a4c3fe3dfc202c7d0 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 6 Aug 2025 20:39:59 -0500 Subject: [PATCH] esbuild almost works! --- package-lock.json | 22 +++++++ package.json | 3 + src/components/Shakespeare/ChatPane.tsx | 69 ++++++--------------- src/lib/build/esmShPlugin.ts | 40 ++++++++++++ src/lib/build/index.ts | 43 +++++++++++++ src/lib/build/lightningFsPlugin.ts | 82 +++++++++++++++++++++++++ 6 files changed, 210 insertions(+), 49 deletions(-) create mode 100644 src/lib/build/esmShPlugin.ts create mode 100644 src/lib/build/index.ts create mode 100644 src/lib/build/lightningFsPlugin.ts diff --git a/package-lock.json b/package-lock.json index aaae38e5..a26b96da 100644 --- a/package-lock.json +++ b/package-lock.json @@ -53,12 +53,14 @@ "cmdk": "^1.0.0", "date-fns": "^3.6.0", "embla-carousel-react": "^8.3.0", + "esbuild-wasm": "^0.25.8", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", "jszip": "^3.10.1", "lucide-react": "^0.525.0", "next-themes": "^0.3.0", "nostr-tools": "^2.15.2", + "path-browserify": "^1.0.1", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", @@ -84,6 +86,7 @@ "@testing-library/react": "^16.3.0", "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", + "@types/path-browserify": "^1.0.3", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/react-syntax-highlighter": "^15.5.13", @@ -3745,6 +3748,13 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/path-browserify": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.3.tgz", + "integrity": "sha512-ZmHivEbNCBtAfcrFeBCiTjdIc2dey0l7oCGNGpSuRTy8jP6UVND7oUowlvDujBy8r2Hoa8bfFUOCiPWfmtkfxw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/prop-types": { "version": "15.7.14", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz", @@ -5433,6 +5443,18 @@ "@esbuild/win32-x64": "0.25.5" } }, + "node_modules/esbuild-wasm": { + "version": "0.25.8", + "resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.25.8.tgz", + "integrity": "sha512-VFUDMoZdf/NsyCepv5heZqvNLYj9HL+xEKG5tktsFbx+shR8Dt9MchKBEdu/5the2RfTzgxkO6B/nUfzmsWN9Q==", + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", diff --git a/package.json b/package.json index eab449cd..0a2dcda2 100644 --- a/package.json +++ b/package.json @@ -55,12 +55,14 @@ "cmdk": "^1.0.0", "date-fns": "^3.6.0", "embla-carousel-react": "^8.3.0", + "esbuild-wasm": "^0.25.8", "input-otp": "^1.2.4", "isomorphic-git": "^1.32.1", "jszip": "^3.10.1", "lucide-react": "^0.525.0", "next-themes": "^0.3.0", "nostr-tools": "^2.15.2", + "path-browserify": "^1.0.1", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", @@ -86,6 +88,7 @@ "@testing-library/react": "^16.3.0", "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", + "@types/path-browserify": "^1.0.3", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/react-syntax-highlighter": "^15.5.13", diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index ff8907e9..63c0b0d3 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -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 () => { diff --git a/src/lib/build/esmShPlugin.ts b/src/lib/build/esmShPlugin.ts new file mode 100644 index 00000000..db5861e9 --- /dev/null +++ b/src/lib/build/esmShPlugin.ts @@ -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', + }; + }); + }, + }; +} diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts new file mode 100644 index 00000000..d63fe62a --- /dev/null +++ b/src/lib/build/index.ts @@ -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> { + 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 = {}; + + 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; +} \ No newline at end of file diff --git a/src/lib/build/lightningFsPlugin.ts b/src/lib/build/lightningFsPlugin.ts new file mode 100644 index 00000000..366ec1cd --- /dev/null +++ b/src/lib/build/lightningFsPlugin.ts @@ -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 { + 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'); +}