forked from evanw/esbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.ts
65 lines (55 loc) · 1.73 KB
/
worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// This file is part of the web worker source code
declare const ESBUILD_VERSION: string;
declare function postMessage(message: any): void;
onmessage = ({ data: wasm }) => {
let decoder = new TextDecoder()
let fs = (global as any).fs
let stderr = ''
fs.writeSync = (fd: number, buffer: Uint8Array) => {
if (fd === 1) {
postMessage(buffer)
} else if (fd === 2) {
stderr += decoder.decode(buffer)
let parts = stderr.split('\n')
if (parts.length > 1) console.log(parts.slice(0, -1).join('\n'))
stderr = parts[parts.length - 1]
} else {
throw new Error('Bad write')
}
return buffer.length
}
let stdin: Uint8Array[] = []
let resumeStdin: () => void
let stdinPos = 0
onmessage = ({ data }) => {
if (data.length > 0) {
stdin.push(data)
if (resumeStdin) resumeStdin()
}
}
fs.read = (
fd: number, buffer: Uint8Array, offset: number, length: number,
position: null, callback: (err: Error | null, count?: number) => void,
) => {
if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
throw new Error('Bad read')
}
if (stdin.length === 0) {
resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback)
return
}
let first = stdin[0]
let count = Math.max(0, Math.min(length, first.length - stdinPos))
buffer.set(first.subarray(stdinPos, stdinPos + count), offset)
stdinPos += count
if (stdinPos === first.length) {
stdin.shift()
stdinPos = 0
}
callback(null, count)
}
let go = new (global as any).Go()
go.argv = ['', `--service=${ESBUILD_VERSION}`]
WebAssembly.instantiate(wasm, go.importObject)
.then(({ instance }) => go.run(instance))
}