Open History to see the last commit
1/// <reference lib="webworker" />
2
3import type {
4 HostToRuntimeMessage,
5 RuntimeHost,
6 RuntimeToHostMessage,
7} from './protocol'
8
9const scope = self as unknown as DedicatedWorkerGlobalScope
10// This legacy native-JS backend has no controllable microtask checkpoint.
11Object.defineProperty(globalThis,Symbol.for('web-container:task-queue'),{value:{
12 mode:'approximate-microtask',
13 nextTick(callback:(...args:unknown[])=>unknown,...args:unknown[]){if(typeof callback!=='function')throw new TypeError('Expected callback');queueMicrotask(()=>callback(...args))},
14 task:(callback:(...args:unknown[])=>unknown,receiver:unknown,args:unknown[]=[])=>Reflect.apply(callback,receiver,args),
15}})
16const encoder = new TextEncoder()
17const decoder = new TextDecoder()
18let handler: ((request: Request) => Response | Promise<Response>) | undefined
19let activeModuleUrl: string | undefined
20let operationQueue = Promise.resolve()
21
22function normalizePath(input: string | URL): string {
23 const value = input instanceof URL ? input.pathname : input
24 const parts: string[] = []
25 for (const part of (value.startsWith('/') ? value : `/${value}`).split('/')) {
26 if (!part || part === '.') continue
27 if (part === '..') parts.pop()
28 else parts.push(part)
29 }
30 return `/${parts.join('/')}`
31}
32
33function errorMessage(id: number, error: unknown): RuntimeToHostMessage {
34 const normalized = error instanceof Error ? error : new Error(String(error))
35 return { type: 'error', id, message: normalized.message, stack: normalized.stack }
36}
37
38async function loadRuntime(message: Extract<HostToRuntimeMessage, { type: 'load' }>) {
39 handler = undefined
40 const files = new Map(Object.entries(message.files))
41 const retainedStores = new Map<{ _store: unknown }, unknown>()
42 let requestActive = false
43 const stat=async(path:string|URL)=>{
44 const normalized=normalizePath(path),contents=files.get(normalized)
45 const directory=normalized==='/'||[...files.keys()].some(file=>file.startsWith(`${normalized}/`))
46 if(contents===undefined&&!directory)throw new Error(`ENOENT: no such file or directory, stat '${normalized}'`)
47 return {
48 kind:contents===undefined?'directory' as const:'file' as const,
49 isDirectory:()=>directory&&contents===undefined,
50 isFile:()=>contents!==undefined,
51 size:contents===undefined?0:encoder.encode(contents).byteLength,
52 }
53 }
54 const host: RuntimeHost = {
55 asyncContext: {
56 beginRequest() {
57 requestActive = true
58 },
59 endRequest() {
60 for (const [storage, previous] of retainedStores) storage._store = previous
61 retainedStores.clear()
62 requestActive = false
63 },
64 retain(storage, previous) {
65 if (!requestActive || retainedStores.has(storage)) return false
66 retainedStores.set(storage, previous)
67 return true
68 },
69 },
70 env: { ...message.env },
71 fs: {
72 async readFile(path, options) {
73 const normalized = normalizePath(path)
74 const contents = files.get(normalized)
75 if (contents === undefined) throw new Error(`ENOENT: no such file, open '${normalized}'`)
76 const encoding = typeof options === 'string' ? options : options?.encoding
77 return encoding ? contents : encoder.encode(contents)
78 },
79 async readdir(path) {
80 const normalized = normalizePath(path)
81 const prefix = normalized === '/' ? '/' : `${normalized}/`
82 return [...new Set(
83 [...files.keys()]
84 .filter((file) => file.startsWith(prefix))
85 .map((file) => file.slice(prefix.length).split('/')[0])
86 .filter(Boolean),
87 )].sort()
88 },
89 stat,
90 lstat:stat,
91 async writeFile(path, contents) {
92 files.set(normalizePath(path), typeof contents === 'string' ? contents : decoder.decode(contents))
93 },
94 },
95 }
96
97 globalThis.__webContainerHost = host
98
99 if (activeModuleUrl) URL.revokeObjectURL(activeModuleUrl)
100 activeModuleUrl = URL.createObjectURL(new Blob([message.code], { type: 'text/javascript' }))
101 const runtimeModule = await import(/* @vite-ignore */ activeModuleUrl)
102 const exportedHandler = runtimeModule.default?.fetch ?? runtimeModule.fetch ?? runtimeModule.default
103 if (typeof exportedHandler !== 'function') {
104 throw new Error('The entry module must export a fetch function or a default object with fetch(request)')
105 }
106 handler = exportedHandler.bind(runtimeModule.default)
107}
108
109async function runRequest(message: Extract<HostToRuntimeMessage, { type: 'request' }>) {
110 if (!handler) throw new Error('Runtime has not loaded an entry module')
111 const asyncContext = globalThis.__webContainerHost.asyncContext
112 asyncContext.beginRequest()
113 try {
114 const { body, headers, method, url } = message.request
115 const request = new Request(url, {
116 method,
117 headers,
118 body: method === 'GET' || method === 'HEAD' ? undefined : body,
119 })
120 const response = await handler(request)
121 if (!(response instanceof Response)) throw new Error('The request handler must return a Response')
122
123 scope.postMessage({
124 type: 'response-start',
125 id: message.id,
126 status: response.status,
127 statusText: response.statusText,
128 headers: [...response.headers.entries()],
129 } satisfies RuntimeToHostMessage)
130
131 if (response.body) {
132 const reader = response.body.getReader()
133 while (true) {
134 const { done, value } = await reader.read()
135 if (done) break
136 const chunk = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength)
137 scope.postMessage(
138 { type: 'response-chunk', id: message.id, chunk } satisfies RuntimeToHostMessage,
139 [chunk],
140 )
141 }
142 }
143 scope.postMessage({ type: 'response-end', id: message.id } satisfies RuntimeToHostMessage)
144 } finally {
145 asyncContext.endRequest()
146 }
147}
148
149async function handleMessage(message: HostToRuntimeMessage) {
150 try {
151 if (message.type === 'load') {
152 await loadRuntime(message)
153 scope.postMessage({ type: 'loaded', id: message.id } satisfies RuntimeToHostMessage)
154 } else {
155 await runRequest(message)
156 }
157 } catch (error) {
158 scope.postMessage(errorMessage(message.id, error))
159 }
160}
161
162scope.onmessage = (event: MessageEvent<HostToRuntimeMessage>) => {
163 const message = event.data
164 operationQueue = operationQueue.then(() => handleMessage(message))
165}