forked from denoland/wasmbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_command.ts
More file actions
176 lines (155 loc) · 4.91 KB
/
build_command.ts
File metadata and controls
176 lines (155 loc) · 4.91 KB
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
// Copyright 2018-2025 the Deno authors. MIT license.
import * as colors from "@std/fmt/colors";
import * as base64 from "@std/encoding/base64";
import type { BuildCommand } from "../args.ts";
import {
generatedHeader,
getFormattedText,
type PreBuildOutput,
runPreBuild,
} from "../pre_build.ts";
import { runWasmOpt } from "../wasmopt.ts";
import type { Path } from "@david/path";
export async function runBuildCommand(args: BuildCommand) {
const output = await runPreBuild(args);
args.outDir.ensureDirSync();
writeSnippets();
const files = args.inline
? await inlinePreBuild(output, args)
: await handleWasmModuleOutput(output, args);
for (const file of files) {
console.log(` write ${colors.yellow(file.path.toString())}`);
if (typeof file.data === "string") {
file.path.writeTextSync(file.data);
} else {
file.path.writeSync(file.data);
}
}
console.log(
`${colors.bold(colors.green("Finished"))} WebAssembly output`,
);
function writeSnippets() {
const localModules = Array.from(output.bindgen.localModules);
const snippets = Array.from(output.bindgen.snippets);
if (localModules.length === 0 && !snippets.some((s) => s[1].length > 0)) {
return; // don't create the snippets directory
}
const snippetsDest = args.outDir.join("snippets");
// start with a fresh directory in order to clear out any previously
// created snippets which might have a different name
snippetsDest.emptyDirSync();
for (const [name, text] of localModules) {
const filePath = snippetsDest.join(name);
const dirPath = filePath.parentOrThrow();
dirPath.mkdirSync({ recursive: true });
filePath.writeTextSync(text);
}
for (const [identifier, list] of snippets) {
if (list.length === 0) {
continue;
}
const dirPath = snippetsDest.join(identifier);
dirPath.mkdirSync({ recursive: true });
for (const [i, text] of list.entries()) {
const name = `inline${i}.js`;
const filePath = dirPath.join(name);
filePath.writeTextSync(text);
}
}
}
}
interface FileEntry {
path: Path;
data: string | Uint8Array;
}
async function handleWasmModuleOutput(
output: PreBuildOutput,
args: BuildCommand,
): Promise<FileEntry[]> {
return [{
path: args.outDir.join(
`${output.crateName}.${args.bindingJsFileExt}`,
),
data: await getFormattedText(`${generatedHeader}
// @ts-self-types="./${output.bindingDts.path.basename()}"
// source-hash: ${output.sourceHash}
import * as wasm from "./${output.wasmFileName}";
export * from "./${output.bindingJsBg.path.basename()}";
import { __wbg_set_wasm } from "./${output.bindingJsBg.path.basename()}";
__wbg_set_wasm(wasm);
${output.hasStart ? "wasm.__wbindgen_start();" : ""}
`),
}, {
path: output.bindingJsBg.path,
data: output.bindingJsBg.text,
}, {
path: output.bindingDts.path,
data: output.bindingDts.text,
}, {
path: args.outDir.join(output.wasmFileName),
data: await getWasmBytes(output, args),
}];
}
async function inlinePreBuild(
output: PreBuildOutput,
args: BuildCommand,
): Promise<FileEntry[]> {
const wasmBytes = await getWasmBytes(output, args);
return [{
path: args.outDir.join(
`${output.crateName}.${args.bindingJsFileExt}`,
),
data: await getFormattedText(`${generatedHeader}
// @ts-self-types="./${output.bindingDts.path.basename()}"
// source-hash: ${output.sourceHash}
import * as imports from "./${output.bindingJsBg.path.basename()}";
const bytes = base64decode("\\\n${
base64.encodeBase64(wasmBytes).replace(/.{78}/g, "$&\\\n")
}\\\n");
const wasmModule = new WebAssembly.Module(bytes);
const wasm = new WebAssembly.Instance(wasmModule, {
"./${output.bindingJsBg.path.basename()}": imports,
});
export * from "./${output.bindingJsBg.path.basename()}";
import { __wbg_set_wasm } from "./${output.bindingJsBg.path.basename()}";
__wbg_set_wasm(wasm.exports);
function base64decode(b64) {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
`),
}, {
path: output.bindingJsBg.path,
data: output.bindingJsBg.text,
}, {
path: output.bindingDts.path,
data: output.bindingDts.text,
}];
}
async function getWasmBytes(output: PreBuildOutput, args: BuildCommand) {
const wasmBytes = new Uint8Array(output.bindgen.wasm.bytes);
if (args.isOpt) {
return await optimizeWasmFile(wasmBytes);
} else {
return wasmBytes;
}
}
async function optimizeWasmFile(fileBytes: Uint8Array) {
try {
console.log(
`${colors.bold(colors.green("Optimizing"))} .wasm file...`,
);
return await runWasmOpt(fileBytes);
} catch (err) {
console.error(
`${colors.bold(colors.red("Error"))} ` +
`running wasm-opt failed. Maybe skip with --skip-opt?\n\n${err}`,
);
Deno.exit(1);
}
}