|
import * as base64 from "https://deno.land/[email protected]/encoding/base64.ts"; |
|
|
|
const decoder = new TextDecoder("utf-8"); |
|
const cargo_file = decoder.decode(await Deno.readFile("./Cargo.toml")); |
|
if (cargo_file === null) { |
|
throw new Error("Cargo.toml not found"); |
|
} |
|
const cargo_package = /\[package\]\nname = "(.*?)"/.exec(cargo_file); |
|
if (cargo_package === null) { |
|
throw new Error("Cargo.toml is invalid"); |
|
} |
|
const cargo_package_name = cargo_package[1]; |
|
const name = cargo_package_name.replace(/-/g, "_"); |
|
|
|
const bytes = await Deno.readFile(`./pkg/${name}_bg.wasm`); |
|
if (bytes === null) { |
|
throw new Error(`pkg/${name}_bg.wasm not found`); |
|
} |
|
const encoded = base64.encodeBase64(bytes); |
|
|
|
const js_file = decoder.decode(await Deno.readFile(`./pkg/${name}.js`)); |
|
if (js_file === null) { |
|
throw new Error(`pkg/${name}.js not found`); |
|
} |
|
|
|
const patched = |
|
"" + |
|
`import * as base64 from "https://deno.land/std/encoding/base64.ts"\n\n` + |
|
`const bytes = base64.decodeBase64(\n` + |
|
` // base64 encoded wasm module\n` + |
|
` ${JSON.stringify(encoded)}\n` + |
|
`);\n\n` + |
|
js_file |
|
.replace("let imports = {};", "let imports: any = {};") |
|
// use global TextDecoder TextEncoder |
|
.replace("require(`util`)", "globalThis") |
|
// attach to `imports` instead of module.exports |
|
.replace("= module.exports", "= imports") |
|
.replace(/\nmodule\.exports\.(.*?)\s+/g, "\nexport const $1 = imports.$1 ") |
|
.replace(/$/, "export default imports") |
|
// inline bytes Uint8Array |
|
.replace(/\nconst path.*\nconst bytes.*\n/, ""); |
|
|
|
const encoder = new TextEncoder(); |
|
await Deno.writeFile(`./val.ts`, encoder.encode(patched)); |