diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts new file mode 100644 index 00000000..8934a324 --- /dev/null +++ b/src/lib/build/index.test.ts @@ -0,0 +1,260 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { buildProject } from './index'; +import { copyFiles } from '../copyFiles'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock esbuild +vi.mock('../esbuild', () => ({ + getEsbuild: vi.fn(() => ({ + build: vi.fn(() => ({ + outputFiles: [ + { + path: '/stdin.js', + contents: new Uint8Array([1, 2, 3]), + }, + { + path: '/stdin.css', + contents: new Uint8Array([4, 5, 6]), + }, + ], + })), + })), +})); + +// Mock copyFiles +vi.mock('../copyFiles', () => ({ + copyFiles: vi.fn(), +})); + +describe('buildProject', () => { + let mockFS: JSRuntimeFS; + let mockDOMParser: DOMParser; + + beforeEach(() => { + vi.clearAllMocks(); + + mockFS = { + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + stat: vi.fn(), + mkdir: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + lstat: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), + } as JSRuntimeFS; + + mockDOMParser = { + parseFromString: vi.fn(() => ({ + documentElement: { + outerHTML: '', + }, + querySelector: vi.fn(() => ({ + setAttribute: vi.fn(), + })), + head: { + appendChild: vi.fn(), + }, + createElement: vi.fn(() => ({ + setAttribute: vi.fn(), + })), + })), + } as unknown as DOMParser; + }); + + it('should include files from public directory in build output', async () => { + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + return '{"dependencies": {}}'; + } + if (path === '/test/project/public/favicon.ico') { + return new Uint8Array([10, 11, 12]); + } + if (path === '/test/project/public/images/logo.png') { + return new Uint8Array([20, 21, 22]); + } + throw new Error(`Unexpected file read: ${path}`); + }); + + // Mock public directory structure + vi.mocked(mockFS.stat) + .mockImplementation(async (path: string) => { + if (path === '/test/project/public') { + return { isDirectory: () => true, isFile: () => false }; + } + if (path === '/test/project/public/images') { + return { isDirectory: () => true, isFile: () => false }; + } + return { isDirectory: () => false, isFile: () => true }; + }); + + vi.mocked(mockFS.readdir) + .mockImplementation(async (path: string, _options?: { withFileTypes: true }) => { + if (path === '/test/project/public') { + return [ + { name: 'favicon.ico', isDirectory: () => false, isFile: () => true }, + { name: 'images', isDirectory: () => true, isFile: () => false }, + ]; + } + if (path === '/test/project/public/images') { + return [ + { name: 'logo.png', isDirectory: () => false, isFile: () => true }, + ]; + } + return []; + }); + + // Mock additional filesystem operations for buildProject + vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => { + // Handle regular readdir calls for dist cleanup + if (path === '/test/project/dist') { + return []; + } + return []; + }); + + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await buildProject({ + fs: mockFS, + projectPath: '/test/project', + domParser: mockDOMParser, + }); + + // Should include built files + expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + expect(result.files['index.html']).toBeDefined(); + + // Public files should be copied to filesystem, not included in files object + // Verify copyFiles was called for public directory + expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public'); + expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); + + // Should have correct metadata + expect(result.outputPath).toBe('/test/project/dist'); + expect(result.projectId).toBe('project'); + }); + + it('should handle missing public directory gracefully', async () => { + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + return '{"dependencies": {}}'; + } + throw new Error(`File not found: ${path}`); + }); + + // Mock missing public directory + vi.mocked(mockFS.stat) + .mockImplementation(async (path: string) => { + if (path === '/test/project/public') { + throw new Error('Directory not found'); + } + return { isDirectory: () => false, isFile: () => true }; + }); + + // Mock additional filesystem operations for buildProject + vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => { + if (path === '/test/project/dist') { + return []; + } + return []; + }); + + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await buildProject({ + fs: mockFS, + projectPath: '/test/project', + domParser: mockDOMParser, + }); + + // Should still include built files + expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + expect(result.files['index.html']).toBeDefined(); + + // Should not include any public files in bundle + expect(Object.keys(result.files)).not.toContain('favicon.ico'); + + // Should not try to copy public files if directory doesn't exist + expect(copyFiles).not.toHaveBeenCalled(); + }); + + it('should handle empty public directory', async () => { + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return '{"name": "test-project"}'; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + return '{"dependencies": {}}'; + } + throw new Error(`File not found: ${path}`); + }); + + // Mock empty public directory + vi.mocked(mockFS.stat) + .mockImplementation(async (path: string) => { + if (path === '/test/project/public') { + return { isDirectory: () => true, isFile: () => false }; + } + return { isDirectory: () => false, isFile: () => true }; + }); + + vi.mocked(mockFS.readdir) + .mockImplementation(async (path: string) => { + // Handle regular readdir calls for dist cleanup + if (path === '/test/project/dist') { + return []; + } + return []; + }); + + // Mock additional filesystem operations for buildProject + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await buildProject({ + fs: mockFS, + projectPath: '/test/project', + domParser: mockDOMParser, + }); + + // Should include built files + expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3])); + expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6])); + expect(result.files['index.html']).toBeDefined(); + + // Should have exactly 3 files (main.js, main.css, index.html) + expect(Object.keys(result.files)).toHaveLength(3); + + // Should try to copy public files but directory is empty + expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist'); + }); +}); \ No newline at end of file diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index d456dd24..fc9dbd1c 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,4 +1,5 @@ import { getEsbuild } from "@/lib/esbuild"; +import { copyFiles } from "@/lib/copyFiles"; import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; @@ -10,9 +11,10 @@ export interface BuildProjectOptions { projectPath: string; domParser: DOMParser; target?: string; + outputPath?: string; } -export async function buildProject( +async function bundle( options: BuildProjectOptions, ): Promise> { const esbuild = await getEsbuild(); @@ -77,6 +79,81 @@ export async function buildProject( return dist; } +/** + * Build project and write output files to the filesystem + */ +export async function buildProject(options: BuildProjectOptions): Promise<{ + files: Record; + outputPath: string; + projectId?: string; +}> { + const { fs, projectPath, outputPath = `${projectPath}/dist` } = options; + + // Check if we're in a valid project directory + try { + await fs.readFile(`${projectPath}/package.json`, "utf8"); + } catch { + throw new Error(`❌ Could not find package.json at ${projectPath}. Make sure you're in a valid project directory.`); + } + + // Check if index.html exists + try { + await fs.readFile(`${projectPath}/index.html`, "utf8"); + } catch { + throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`); + } + + // Run the build + const dist = await bundle(options); + + // Delete all existing files in output directory + try { + const distFiles = await fs.readdir(outputPath); + for (const file of distFiles) { + await fs.unlink(`${outputPath}/${file}`); + } + } catch { + // Ignore errors (e.g., directory doesn't exist) + } + + // Create output directory if it doesn't exist + await fs.mkdir(outputPath, { recursive: true }); + + // Write all built files to output directory + for (const [path, contents] of Object.entries(dist)) { + await fs.writeFile(`${outputPath}/${path}`, contents); + } + + // Copy files from public directory if it exists + try { + const publicPath = `${projectPath}/public`; + const stat = await fs.stat(publicPath); + if (stat.isDirectory()) { + await copyFiles(fs, fs, publicPath, outputPath); + } + } catch { + // Public directory doesn't exist, which is fine + } + + // Extract project ID from the project path + // Expected format: /projects/{projectId} + const projectId = projectPath.split('/').pop(); + + // Emit build completion event for PreviewPane to listen to + if (projectId && typeof window !== 'undefined') { + const buildCompleteEvent = new CustomEvent('buildComplete', { + detail: { projectId } + }); + window.dispatchEvent(buildCompleteEvent); + } + + return { + files: dist, + outputPath, + projectId, + }; +} + function updateIndexHtml(doc: Document): void { const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); diff --git a/src/lib/tools/BuildProjectTool.test.ts b/src/lib/tools/BuildProjectTool.test.ts index b6aad023..b668c694 100644 --- a/src/lib/tools/BuildProjectTool.test.ts +++ b/src/lib/tools/BuildProjectTool.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { BuildProjectTool } from './BuildProjectTool'; import type { JSRuntimeFS } from '../JSRuntime'; -// Mock the buildProject function +// Mock the build functions vi.mock('../build', () => ({ buildProject: vi.fn(), })); @@ -32,36 +32,39 @@ describe('BuildProjectTool', () => { }); it('should fail if package.json does not exist', async () => { - vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + vi.mocked(buildProject).mockRejectedValue( + new Error('❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.') + ); await expect(tool.execute()).rejects.toThrow( - '❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.' + '❌ Build failed: Error: ❌ Could not find package.json at /test/project. Make sure you\'re in a valid project directory.' ); }); it('should fail if index.html does not exist', async () => { - vi.mocked(mockFS.readFile) - .mockResolvedValueOnce('{"name": "test"}') // package.json exists - .mockRejectedValueOnce(new Error('File not found')); // index.html doesn't exist + vi.mocked(buildProject).mockRejectedValue( + new Error('❌ Could not find index.html at /test/project. This is required for building the project.') + ); await expect(tool.execute()).rejects.toThrow( - '❌ Could not find index.html at /test/project. This is required for building the project.' + '❌ Build failed: Error: ❌ Could not find index.html at /test/project. This is required for building the project.' ); }); it('should successfully build project', async () => { - const mockDist = { + const mockFiles = { 'index.html': new Uint8Array([1, 2, 3]), 'main.js': new Uint8Array([4, 5, 6]), 'main.css': new Uint8Array([7, 8, 9]), }; - vi.mocked(mockFS.readFile) - .mockResolvedValueOnce('{"name": "test"}') // package.json - .mockResolvedValueOnce(''); // index.html + const mockResult = { + files: mockFiles, + outputPath: '/test/project/dist', + projectId: 'project', + }; - vi.mocked(mockFS.readdir).mockRejectedValue(new Error('Directory not found')); - vi.mocked(buildProject).mockResolvedValue(mockDist); + vi.mocked(buildProject).mockResolvedValue(mockResult); const result = await tool.execute(); @@ -71,13 +74,8 @@ describe('BuildProjectTool', () => { domParser: expect.any(DOMParser), }); - expect(mockFS.mkdir).toHaveBeenCalledWith('/test/project/dist', { recursive: true }); - expect(mockFS.writeFile).toHaveBeenCalledTimes(3); - expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/index.html', mockDist['index.html']); - expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.js', mockDist['main.js']); - expect(mockFS.writeFile).toHaveBeenCalledWith('/test/project/dist/main.css', mockDist['main.css']); - expect(result).toContain('✅ Successfully built project!'); + expect(result).toContain('📁 Output: /test/project/dist'); expect(result).toContain('📦 Files generated: 3'); expect(result).toContain('📄 index.html'); expect(result).toContain('📄 main.js'); @@ -87,29 +85,28 @@ describe('BuildProjectTool', () => { it('should clean existing dist directory before building', async () => { - const mockDist = { + const mockFiles = { 'index.html': new Uint8Array([1, 2, 3]), }; - vi.mocked(mockFS.readFile) - .mockResolvedValueOnce('{"name": "test"}') // package.json - .mockResolvedValueOnce(''); // index.html + const mockResult = { + files: mockFiles, + outputPath: '/test/project/dist', + projectId: 'project', + }; - vi.mocked(mockFS.readdir).mockResolvedValue(['old-file.js', 'old-style.css']); - vi.mocked(buildProject).mockResolvedValue(mockDist); + vi.mocked(buildProject).mockResolvedValue(mockResult); await tool.execute(); - expect(mockFS.readdir).toHaveBeenCalledWith('/test/project/dist'); - expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-file.js'); - expect(mockFS.unlink).toHaveBeenCalledWith('/test/project/dist/old-style.css'); + expect(buildProject).toHaveBeenCalledWith({ + fs: mockFS, + projectPath: '/test/project', + domParser: expect.any(DOMParser), + }); }); it('should handle build errors gracefully', async () => { - vi.mocked(mockFS.readFile) - .mockResolvedValueOnce('{"name": "test"}') // package.json - .mockResolvedValueOnce(''); // index.html - vi.mocked(buildProject).mockRejectedValue(new Error('Build compilation failed')); await expect(tool.execute()).rejects.toThrow( diff --git a/src/lib/tools/BuildProjectTool.ts b/src/lib/tools/BuildProjectTool.ts index 9d43f776..979a3526 100644 --- a/src/lib/tools/BuildProjectTool.ts +++ b/src/lib/tools/BuildProjectTool.ts @@ -15,61 +15,17 @@ export class BuildProjectTool implements Tool { async execute(): Promise { try { - // Check if we're in a valid project directory - try { - await this.fs.readFile(`${this.cwd}/package.json`, "utf8"); - } catch { - throw new Error(`❌ Could not find package.json at ${this.cwd}. Make sure you're in a valid project directory.`); - } - - // Check if index.html exists - try { - await this.fs.readFile(`${this.cwd}/index.html`, "utf8"); - } catch { - throw new Error(`❌ Could not find index.html at ${this.cwd}. This is required for building the project.`); - } - - // Run the build - const dist = await buildProject({ + // Build and write the project files + const result = await buildProject({ fs: this.fs, projectPath: this.cwd, domParser: new DOMParser(), }); - // Delete all existing files in "dist" directory - try { - const distFiles = await this.fs.readdir(`${this.cwd}/dist`); - for (const file of distFiles) { - await this.fs.unlink(`${this.cwd}/dist/${file}`); - } - } catch { - // Ignore errors (e.g., directory doesn't exist) - } + const fileCount = Object.keys(result.files).length; + const fileList = Object.keys(result.files).map(file => ` 📄 ${file}`).join('\n'); - // Create dist directory if it doesn't exist - await this.fs.mkdir(`${this.cwd}/dist`, { recursive: true }); - - // Write all built files to dist directory - for (const [path, contents] of Object.entries(dist)) { - await this.fs.writeFile(`${this.cwd}/dist/${path}`, contents); - } - - const fileCount = Object.keys(dist).length; - const fileList = Object.keys(dist).map(file => ` 📄 ${file}`).join('\n'); - - // Extract project ID from the current working directory path - // Expected format: /projects/{projectId} - const projectId = this.cwd.split('/').pop(); - - // Emit build completion event for PreviewPane to listen to - if (projectId && typeof window !== 'undefined') { - const buildCompleteEvent = new CustomEvent('buildComplete', { - detail: { projectId } - }); - window.dispatchEvent(buildCompleteEvent); - } - - return `✅ Successfully built project!\n\n📁 Output: ${this.cwd}/dist\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`; + return `✅ Successfully built project!\n\n📁 Output: ${result.outputPath}\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`; } catch (error) { throw new Error(`❌ Build failed: ${String(error)}`); } diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index c23332a0..44810d8d 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -88,28 +88,13 @@ export function ProjectView() { updateMetadata('Shakespeare', `Building ${project.name}...`); try { - const dist = await buildProject({ + const result = await buildProject({ fs: browserFS, projectPath: `/projects/${project.id}`, domParser: new DOMParser(), }); - console.log(dist); - - // Delete all existing files in "dist" directory - try { - for (const file of await browserFS.readdir(`/projects/${project.id}/dist`)) { - await browserFS.unlink(`/projects/${project.id}/dist/${file}`); - } - } catch { - // Ignore errors (e.g., directory doesn't exist) - } - - await browserFS.mkdir(`/projects/${project.id}/dist`, { recursive: true }); - - for (const [path, contents] of Object.entries(dist)) { - await browserFS.writeFile(`/projects/${project.id}/dist/${path}`, contents); - } + console.log('Build completed:', result); } catch (error) { console.error('Build failed:', error); } finally {