-
Notifications
You must be signed in to change notification settings - Fork 76
/
build.js
executable file
·76 lines (64 loc) · 1.87 KB
/
build.js
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
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env node
const { build, sha1, file } = require("estrella")
const pkg = require("./package.json")
const fs = require("fs").promises
process.chdir(__dirname)
build({
entry: "gotalk/index.js",
outfile: "gotalk.js",
bundle: true,
sourcemap: true,
globalName: "gotalk",
target: "es5",
// format: "cjs",
define: { VERSION: pkg.version },
onEnd: postProcess,
})
async function postProcess(config, diagnostics) {
let jsbuf = await file.read(config.outfile)
// find sourceMappingURL
let sourceMappingURLBuf = Buffer.from("//# sourceMappingURL")
let i = jsbuf.indexOf(sourceMappingURLBuf)
if (i == -1) { throw new Error("could not find '//# sourceMappingURL' in gotalk.js") }
// js without sourcemap url
let jsbuf1 = jsbuf.subarray(0, i)
// js with nodejs compat code added
let jsbuf2 = Buffer.concat([
jsbuf.subarray(0, i),
Buffer.from(`if(typeof module!="undefined")module.exports=gotalk;\n`),
jsbuf.subarray(i),
])
// go source with embedded js
let goSource = `
package gotalk
const JSLibSHA1Base64 = "${sha1(jsbuf1, 'base64')}"
const JSLibString = ${bytesToGoString(jsbuf1)}
`.trim().replace(/\n +/g,"\n") + "\n"
await Promise.all([
file.write(config.outfile, jsbuf2),
file.write("../jslib.go", goSource, {log:true}),
])
}
function bytesToGoString(buf) {
const charmap = {
0x09: "\\t",
0x0a: "\\n",
0x0d: "\\r",
0x5c: "\\\\",
}
function strEscByte(c) {
let r = charmap[c]
return (
r !== undefined ? r : // special representation, e.g. "\n"
c == 0x22 ? '\\"' : // '"'
c >= 0x20 && c < 0x7f ? String.fromCharCode(c) : // verbatim
(c <= 0xf ? '\\x0' : '\\x') + c.toString(16) // "\xHH"
)
}
let s = '"';
for (let c, i = 0, L = buf.length; i !== L; ++i) {
c = buf[i];
s += strEscByte(c)
}
return s + '"';
}