-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
build.js
223 lines (190 loc) · 5.99 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import fs from "fs";
import * as yenc from "simple-yenc";
import Zopfli from "node-zopfli";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import { rollup } from "rollup";
import { minify } from "terser";
const searchFileSize = async (
startIteration,
stopIteration,
sourcePath,
outputName,
rollupOutput,
terserOutput,
) => {
let bestLength = Infinity;
let bestIteration = Infinity;
const sizes = [];
for (
let iteration = startIteration;
iteration <= stopIteration;
iteration++
) {
await buildWasm(
sourcePath,
outputName,
iteration,
rollupOutput,
terserOutput,
)
.then((code) => {
sizes.push({
iteration,
size: code.length,
});
if (code.length <= bestLength) {
if (code.length < bestLength || bestIteration > iteration) {
bestIteration = iteration;
console.log(
"new best iteration",
iteration,
sourcePath,
code.length,
);
}
bestLength = code.length;
}
console.log(iteration, sourcePath, code.length);
})
.catch((e) => {
console.error("failed", iteration, sourcePath);
console.error(e);
});
}
sizes.sort((a, b) => a.size - b.size || a.iteration - b.iteration);
fs.writeFileSync(moduleMin + ".sizes.json", JSON.stringify(sizes, null, 2));
console.log(moduleMin, "best iteration", bestIteration);
};
const buildWasm = async (
sourcePath,
outputName,
compressionIterations,
rollupOutput,
terserOutput,
) => {
const emscriptenInputPath = sourcePath + `src/${outputName}.tmp.js`;
const emscriptenOutputPath = sourcePath + `src/${outputName}.js`;
const rollupConfigPath = sourcePath + "rollup.json";
const rollupInput = sourcePath + "index.js";
const terserConfigPath = sourcePath + "terser.json";
if (outputName !== "none") {
let decoder = fs.readFileSync(emscriptenInputPath, { encoding: "ascii" });
// only compile wasm once
const wasmInstantiateMatcher = /WebAssembly\.instantiate\(.*?exports;/s;
decoder = decoder.replace(
decoder.match(wasmInstantiateMatcher)[0],
`
this.setModule = (data) => {
WASMAudioDecoderCommon.setModule(EmscriptenWASM, data);
};
this.getModule = () =>
WASMAudioDecoderCommon.getModule(EmscriptenWASM);
this.instantiate = () => {
this.getModule().then((wasm) => WebAssembly.instantiate(wasm, imports)).then((instance) => {
const wasmExports = instance.exports;`,
);
const wasmBase64ContentMatcher =
/Module\["wasm"\] = base64Decode\("(?<wasm>(.+))"\)/;
const wasmBase64DeclarationMatcher = 'Module["wasm"] = base64Decode("';
// original wasm
const wasmContent = decoder.match(wasmBase64ContentMatcher).groups.wasm;
// compressed buffer
const wasmBuffer = Uint8Array.from(Buffer.from(wasmContent, "base64"));
let wasmBufferCompressed = wasmBuffer;
if (compressionIterations > 0) {
wasmBufferCompressed = Zopfli.deflateSync(wasmBuffer, {
numiterations: compressionIterations,
blocksplitting: true,
blocksplittingmax: 0,
});
}
const dynEncodedWasm = {
wasm: yenc.dynamicEncode(wasmBufferCompressed, "`"),
quote: "`",
};
// code before the wasm
const wasmStartIdx = decoder.indexOf(wasmBase64DeclarationMatcher);
// code after the wasm
const wasmEndIdx =
wasmStartIdx +
wasmBase64DeclarationMatcher.length +
wasmContent.length +
2;
decoder = Buffer.concat(
[
decoder.substring(0, wasmStartIdx),
'if (!EmscriptenWASM.wasm) Object.defineProperty(EmscriptenWASM, "wasm", {get: () => String.raw',
dynEncodedWasm.quote,
dynEncodedWasm.wasm,
dynEncodedWasm.quote,
"})",
decoder.substring(wasmEndIdx),
].map((string) => Buffer.from(string, { encoding: "binary" })),
);
const banner =
"/* **************************************************\n" +
" * This file is auto-generated during the build process.\n" +
" * Any edits to this file will be overwritten.\n" +
" ****************************************************/" +
"\n\n";
// Concatenate the strings as buffers to preserve extended ascii
const finalString = Buffer.concat(
[
banner,
"export default function EmscriptenWASM(WASMAudioDecoderCommon) {\n",
decoder,
"return this;\n",
"}}",
].map((string) => Buffer.from(string, { encoding: "binary" })),
);
fs.writeFileSync(emscriptenOutputPath, finalString, { encoding: "binary" });
}
if (module && moduleMin) {
// rollup
const rollupConfig = fs.readFileSync(rollupConfigPath).toString();
const rollupInputConfig = JSON.parse(rollupConfig);
rollupInputConfig.input = rollupInput;
rollupInputConfig.plugins = [nodeResolve()];
const rollupOutputConfig = JSON.parse(rollupConfig).output;
rollupOutputConfig.file = rollupOutput;
const bundle = await rollup(rollupInputConfig);
const output = (await bundle.generate(rollupOutputConfig)).output[0];
// terser
const terserConfig = JSON.parse(
fs.readFileSync(terserConfigPath).toString(),
);
const minified = await minify(
{ [output.fileName]: output.code },
terserConfig,
);
// write output files
await Promise.all([
bundle.write(rollupOutputConfig),
fs.promises.writeFile(terserOutput, minified.code),
fs.promises.writeFile(terserOutput + ".map", minified.map),
]);
return fs.readFileSync(terserOutput);
}
};
const sourcePath = process.argv[2];
const outputName = process.argv[3];
const compressionIterations = parseInt(process.argv[4]);
const module = process.argv[5];
const moduleMin = process.argv[6];
await buildWasm(
sourcePath,
outputName,
compressionIterations,
module,
moduleMin,
);
/*
await searchFileSize(
1, // start iteration
500, // stop iteration
sourcePath,
outputName,
module,
moduleMin
);
*/