Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

use-webcontainer-store.ts

434 lines13.7 KB

1import { WebContainer } from '@webcontainer/api'
2import { createStore } from 'zustand'
3​
4import shimALS from '../lib/als-shim'
5​
6import type { FileSystemTree, WebContainerProcess } from '@webcontainer/api'
7​
8export type SetupStep =
9 | 'mounting'
10 | 'installing'
11 | 'starting'
12 | 'ready'
13 | 'error'
14​
15type WebContainerStore = {
16 webContainer: Promise<WebContainer> | null
17 ready: boolean
18 setupStep: SetupStep
19 statusMessage: string
20 terminalOutput: Array<string>
21 previewUrl: string | null
22 error: string | null
23 devProcess: WebContainerProcess | null
24 projectFiles: Array<{ path: string; content: string }>
25 isInstalling: boolean
26​
27 teardown: () => void
28 updateProjectFiles: (
29 projectFiles: Array<{ path: string; content: string }>,
30 ) => Promise<void>
31​
32 startDevServer: () => Promise<void>
33 addTerminalOutput: (output: string) => void
34 installDependencies: () => Promise<void>
35 setTerminalOutput: (output: Array<string>) => void
37​
38const processTerminalLine = (data: string): string => {
39 // Clean up terminal output - remove ANSI codes and control characters
40 let cleaned = data
41​
42 // Remove all ANSI escape sequences (comprehensive)
43 cleaned = cleaned.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '') // Standard ANSI sequences
44 cleaned = cleaned.replace(/\u001b\][0-9;]*;[^\u0007]*\u0007/g, '') // OSC sequences
45 cleaned = cleaned.replace(/\u001b[=>]/g, '') // Other escape codes
46​
47 // Remove carriage returns and other control characters
48 cleaned = cleaned.replace(/\r/g, '')
49 cleaned = cleaned.replace(
50 /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g,
51 '',
52 )
53​
54 // Remove spinner characters and progress bar artifacts
55 cleaned = cleaned.replace(/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/g, '')
56 cleaned = cleaned.replace(/[▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏]/g, '')
57 cleaned = cleaned.replace(/[░▒▓]/g, '')
58​
59 // Trim excessive whitespace
60 cleaned = cleaned.trim()
61​
62 // Only return non-empty lines
63 return cleaned.length > 0 ? cleaned : ''
65​
66let webContainer: Promise<WebContainer> | null = null
67​
68export default function createWebContainerStore(shouldShimALS: boolean) {
69 if (!webContainer) {
70 webContainer = WebContainer.boot()
71 }
72​
73 const store = createStore<WebContainerStore>((set, get) => ({
74 webContainer,
75 ready: false,
76 setupStep: 'mounting',
77 statusMessage: '',
78 terminalOutput: [],
79 previewUrl: null,
80 error: null,
81 devProcess: null,
82 projectFiles: [],
83 isInstalling: false,
84​
85 teardown: () => {
86 set({ webContainer: null, ready: false })
87 },
88 addTerminalOutput: (output: string) => {
89 set(({ terminalOutput }) => ({
90 terminalOutput: [...terminalOutput, output],
91 }))
92 },
93 setTerminalOutput: (output: string[]) => {
94 set({ terminalOutput: output })
95 },
96 startDevServer: async () => {
97 const { devProcess, webContainer, addTerminalOutput } = get()
98 if (!webContainer) {
99 throw new Error('WebContainer not found')
100 }
101​
102 try {
103 const container = await webContainer
104 if (!container) {
105 throw new Error('WebContainer not found')
106 }
107 if (devProcess) {
108 console.log('Killing existing dev process...')
109 devProcess.kill()
110 set({ devProcess: null })
111 }
112​
113 set({
114 setupStep: 'starting',
115 statusMessage: 'Starting development server...',
116 })
117 addTerminalOutput('🚀 Starting dev server...')
118​
119 // Wait for server to be ready (set up listener first)
120 container.on('server-ready', (port, url) => {
121 console.log('Server ready on port', port, 'at', url)
122 const currentState = get()
123 set({
124 previewUrl: url,
125 setupStep: 'ready',
126 statusMessage: 'Development server running',
127 terminalOutput: [
128 ...currentState.terminalOutput,
129 `✅ Server ready at ${url}`,
130 ],
131 })
132 })
133​
134 // Start the dev server
135 const newDevProcess = await container.spawn('pnpm', ['dev'])
136 set({ devProcess: newDevProcess })
137​
138 newDevProcess.output.pipeTo(
139 new WritableStream({
140 write(data) {
141 const cleaned = processTerminalLine(data)
142 if (cleaned && cleaned.length > 3) {
143 console.log('[DEV]', cleaned)
144 const currentState = get()
145 set({
146 terminalOutput: [...currentState.terminalOutput, cleaned],
147 })
148 }
149 },
150 }),
151 )
152​
153 // Check exit code
154 const exitCode = await newDevProcess.exit
155 if (exitCode !== 0) {
156 addTerminalOutput(`❌ Dev server exited with code ${exitCode}`)
157 set({ error: `Dev server exited with code ${exitCode}` })
158 }
159 } catch (error) {
160 console.error('Dev server start error:', error)
161 addTerminalOutput(`❌ Dev server error: ${(error as Error).message}`)
162 set({ error: (error as Error).message, setupStep: 'error' })
163 }
164 },
165 updateProjectFiles: async (
166 projectFiles: Array<{ path: string; content: string }>,
167 ) => {
168 const {
169 projectFiles: originalProjectFiles,
170 addTerminalOutput,
171 installDependencies,
172 webContainer,
173 } = get()
174​
175 if (!webContainer) {
176 console.error('WebContainer not found in updateProjectFiles')
177 throw new Error('WebContainer not found')
178 }
179​
180 try {
181 const container = await webContainer
182 if (!container) {
183 console.error('WebContainer resolved to null')
184 throw new Error('WebContainer not found')
185 }
186 console.log('WebContainer booted successfully!', container)
187 } catch (error) {
188 console.error('WebContainer boot failed:', error)
189 set({
190 error: `WebContainer boot failed: ${(error as Error).message}`,
191 setupStep: 'error',
192 })
193 throw error
194 }
195​
196 const container = await webContainer
197​
198 let packageJSONChanged = false
199 const binaryFiles: Record<string, Uint8Array> = {}
200 if (originalProjectFiles.length === 0) {
201 const fileSystemTree: FileSystemTree = {}
202 let base64FileCount = 0
203​
204 for (const { path, content } of projectFiles) {
205 const cleanPath = path.replace(/^\.?\//, '')
206 const pathParts = cleanPath.split('/')
207​
208 let current: any = fileSystemTree
209 for (let i = 0; i < pathParts.length - 1; i++) {
210 const part = pathParts[i]
211 if (!current[part]) {
212 current[part] = { directory: {} }
213 }
214 current = current[part].directory
215 }
216​
217 const fileName = pathParts[pathParts.length - 1]
218​
219 const adjustedContent = shouldShimALS
220 ? shimALS(fileName, content)
221 : content
222​
223 if (adjustedContent.startsWith('base64::')) {
224 base64FileCount++
225 const base64Content = adjustedContent.replace('base64::', '')
226​
227 try {
228 const base64Cleaned = base64Content.replace(/\s/g, '')
229 const binaryString = atob(base64Cleaned)
230 const bytes = new Uint8Array(binaryString.length)
231 for (let i = 0; i < binaryString.length; i++) {
232 bytes[i] = binaryString.charCodeAt(i) & 0xff
233 }
234 binaryFiles[cleanPath] = bytes
235 } catch (error) {
236 console.error(
237 `[BINARY ERROR] Failed to convert ${cleanPath}:`,
238 error,
239 )
240 }
241 } else {
242 current[fileName] = {
243 file: {
244 contents: String(adjustedContent),
245 },
246 }
247 }
248 }
249​
250 // Write the binary files on their own since mount doesn't support binary files correctly
251 await container.mount(fileSystemTree)
252 for (const [path, bytes] of Object.entries(binaryFiles)) {
253 await container.fs.writeFile(path, bytes)
254 }
255 packageJSONChanged = true
256 } else {
257 const originalMap = new Map<string, string>()
258 for (const { path, content } of originalProjectFiles) {
259 originalMap.set(path, content)
260 }
261 const newMap = new Map<string, string>()
262 for (const { path, content } of projectFiles) {
263 newMap.set(path, content)
264 }
265​
266 const changedOrNewFiles: Array<{ path: string; content: string }> = []
267 for (const { path, content } of projectFiles) {
268 if (!originalMap.has(path)) {
269 changedOrNewFiles.push({ path, content })
270 } else if (originalMap.get(path) !== content) {
271 changedOrNewFiles.push({ path, content })
272 }
273 }
274​
275 const deletedFiles: string[] = []
276 for (const { path } of originalProjectFiles) {
277 if (!newMap.has(path)) {
278 deletedFiles.push(path)
279 }
280 }
281​
282 if (changedOrNewFiles.length > 0 || deletedFiles.length > 0) {
283 // Kill dev server before updating files to avoid HMR issues
284 const { devProcess } = get()
285 if (devProcess) {
286 console.log('Stopping dev server before file update...')
287 addTerminalOutput(
288 '⏸️ Stopping dev server before updating files...',
289 )
290 devProcess.kill()
291 set({ devProcess: null, previewUrl: null })
292 }
293​
294 for (const { path, content } of changedOrNewFiles) {
295 await container.fs.writeFile(path, content)
296 }
297​
298 for (const path of deletedFiles) {
299 await container.fs.rm(path)
300 }
301​
302 addTerminalOutput('📁 Files updated successfully')
303​
304 if (changedOrNewFiles.some(({ path }) => path === './package.json')) {
305 packageJSONChanged = true
306 }
307 }
308 }
309​
310 set({ projectFiles })
311​
312 if (packageJSONChanged) {
313 addTerminalOutput(
314 '📦 Package.json changed, reinstalling dependencies...',
315 )
316 await installDependencies()
317 }
318 },
319 installDependencies: async () => {
320 const { webContainer, addTerminalOutput, startDevServer, isInstalling } =
321 get()
322​
323 if (isInstalling) {
324 console.log('Install already in progress, skipping')
325 return
326 }
327​
328 if (!webContainer) {
329 throw new Error('WebContainer not found')
330 }
331​
332 set({ isInstalling: true })
333​
334 try {
335 const container = await webContainer
336 if (!container) {
337 set({ isInstalling: false })
338 throw new Error('WebContainer not found')
339 }
340​
341 set({
342 setupStep: 'installing',
343 statusMessage: 'Installing dependencies...',
344 })
345​
346 console.log('Starting pnpm install...')
347 addTerminalOutput('📦 Running pnpm install...')
348 addTerminalOutput('⏳ This may take a minute...')
349​
350 let installProcess
351 try {
352 installProcess = await container.spawn('pnpm', ['install'])
353 console.log('pnpm install process spawned successfully')
354 } catch (spawnError) {
355 console.error('Failed to spawn pnpm install:', spawnError)
356 throw spawnError
357 }
358​
359 let outputCount = 0
360 let lastProgressUpdate = Date.now()
361 let allOutput: string[] = []
362 let progressInterval = setInterval(() => {
363 const elapsed = Math.floor((Date.now() - lastProgressUpdate) / 1000)
364 console.log(
365 `[INSTALL] Still running... (${elapsed}s, ${outputCount} output chunks)`,
366 )
367 }, 5000)
368​
369 installProcess.output.pipeTo(
370 new WritableStream({
371 write(data) {
372 outputCount++
373 allOutput.push(data)
374​
375 const cleaned = processTerminalLine(data)
376​
377 // Show meaningful output immediately
378 if (cleaned && cleaned.length > 3) {
379 const isImportant =
380 cleaned.includes('added') ||
381 cleaned.includes('removed') ||
382 cleaned.includes('changed') ||
383 cleaned.includes('audited') ||
384 cleaned.includes('packages') ||
385 cleaned.includes('error') ||
386 cleaned.includes('warn') ||
387 cleaned.includes('ERR') ||
388 cleaned.includes('FAIL')
389​
390 if (isImportant) {
391 console.log('[INSTALL]', cleaned)
392 addTerminalOutput(cleaned)
393 if (isImportant && progressInterval) {
394 clearInterval(progressInterval)
395 progressInterval = undefined as any
396 }
397 }
398 }
399 },
400 }),
401 )
402​
403 console.log('Waiting for install to complete...')
404 const installExitCode = await installProcess.exit
405 if (progressInterval) clearInterval(progressInterval)
406 console.log('Install exit code:', installExitCode)
407 console.log('Total output lines:', outputCount)
408​
409 if (installExitCode !== 0) {
410 // Show all output for debugging
411 console.error('[INSTALL ERROR] All output:', allOutput.join('\n'))
412 const errorMsg = `pnpm install failed with exit code ${installExitCode}`
413 addTerminalOutput(`❌ ${errorMsg}`)
414 addTerminalOutput('💡 Check console for detailed error output')
415 set({ error: errorMsg, setupStep: 'error' })
416 throw new Error(errorMsg)
417 }
418​
419 addTerminalOutput('✅ Dependencies installed successfully')
420​
421 await startDevServer()
422 } catch (error) {
423 console.error('Install error:', error)
424 addTerminalOutput(`❌ Install error: ${(error as Error).message}`)
425 set({ error: (error as Error).message, setupStep: 'error' })
426 throw error
427 } finally {
428 set({ isInstalling: false })
429 }
430 },
431 }))
432​
433 return store