File: generate-wasm-code.js

package info (click to toggle)
node-webpack 5.97.1%2Bdfsg1%2B~cs11.18.27-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 59,064 kB
  • sloc: javascript: 185,073; makefile: 16; sh: 6
file content (90 lines) | stat: -rw-r--r-- 2,161 bytes parent folder | download
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
const path = require("path");
const fs = require("fs");

// When --write is set, files will be written in place
// Otherwise it only prints outdated files
const doWrite = process.argv.includes("--write");

const files = ["lib/util/hash/xxhash64.js", "lib/util/hash/md4.js"];

(async () => {
	// TODO: fix me after update typescript to v5
	// eslint-disable-next-line no-warning-comments
	// @ts-ignore
	// eslint-disable-next-line n/no-unsupported-features/es-syntax
	const asc = (await import("assemblyscript/asc")).default;

	for (const file of files) {
		const filePath = path.resolve(__dirname, "..", file);
		const content = fs.readFileSync(filePath, "utf-8");

		const regexp =
			/\n\/\/[\s]*#region wasm code: (.+) \((.+)\)(.*)\n[\s\S]+?\/\/[\s+]*#endregion\n/g;

		const replaces = new Map();

		let match = regexp.exec(content);
		while (match) {
			const [fullMatch, identifier, name, flags] = match;

			const sourcePath = path.resolve(filePath, "..", name);
			const sourcePathBase = path.join(
				path.dirname(sourcePath),
				path.basename(sourcePath)
			);

			const { error } = await asc.main(
				[
					sourcePath,
					// cspell:word Ospeed
					"-Ospeed",
					"--noAssert",
					"--converge",
					"--textFile",
					`${sourcePathBase}.wat`,
					"--outFile",
					`${sourcePathBase}.wasm`,
					...flags.split(" ").filter(Boolean)
				],
				{
					stdout: process.stdout,
					stderr: process.stderr
				}
			);

			if (error) {
				throw error;
			}

			const wasm = fs.readFileSync(`${sourcePathBase}.wasm`);

			replaces.set(
				fullMatch,
				`
// #region wasm code: ${identifier} (${name})${flags}
const ${identifier} = new WebAssembly.Module(
	Buffer.from(
		// ${wasm.length} bytes
		${JSON.stringify(wasm.toString("base64"))},
		"base64"
	)
);
// #endregion
`
			);
			match = regexp.exec(content);
		}

		const newContent = content.replace(regexp, match => replaces.get(match));

		if (newContent !== content) {
			if (doWrite) {
				fs.writeFileSync(filePath, newContent, "utf-8");
				console.error(`${file} updated`);
			} else {
				console.error(`${file} need to be updated`);
				process.exitCode = 1;
			}
		}
	}
})();