include fetch arg for wasm2es6js

This commit is contained in:
Robert Masen 2018-04-20 21:13:28 -05:00 committed by robert masen
parent 65acc3b692
commit cbccd2028d
4 changed files with 86 additions and 24 deletions

View File

@ -39,6 +39,8 @@ matrix:
(cd examples/hello_world && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |
(cd examples/hello_world/chrome && ./build.sh)
- |
(cd examples/hello_world/chrome && ./build_fetch.sh)
- |
(cd examples/smorgasboard && sed -i 's/: "webpack-dev-server"/: "webpack"/' package.json && ./build.sh)
- |

View File

@ -1,6 +1,7 @@
extern crate base64;
use std::collections::HashSet;
use std::path::PathBuf;
use parity_wasm::elements::*;
@ -8,17 +9,23 @@ use super::Error;
pub struct Config {
base64: bool,
fetch: bool,
file_name: String,
}
pub struct Output {
module: Module,
base64: bool,
fetch: bool,
file_name: String,
}
impl Config {
pub fn new() -> Config {
Config {
base64: false,
fetch: false,
file_name: String::new(),
}
}
@ -26,15 +33,28 @@ impl Config {
self.base64 = base64;
self
}
pub fn fetch(&mut self, fetch: bool, in_path: &PathBuf) -> &mut Self {
self.fetch = fetch;
self.file_name = match in_path.file_name() {
Some(os_str) => os_str.to_str().unwrap_or("").to_string(),
None => String::new()
};
self
}
pub fn generate(&mut self, wasm: &[u8]) -> Result<Output, Error> {
assert!(self.base64);
if !self.base64 && !self.fetch {
panic!()
}
let module = deserialize_buffer(wasm).map_err(|e| {
::Error(format!("{:?}", e))
})?;
Ok(Output {
module,
base64: self.base64,
fetch: self.fetch,
file_name: self.file_name.clone(),
})
}
}
@ -180,35 +200,51 @@ impl Output {
));
}
}
let wasm = serialize(self.module)
.expect("failed to serialize");
format!("
{js_imports}
let wasm;
let bytes;
const base64 = \"{base64}\";
if (typeof Buffer === 'undefined') {{
bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
}} else {{
bytes = Buffer.from(base64, 'base64');
}}
{mem_export}
export const booted = WebAssembly.instantiate(bytes, {{ {imports} }})
let inst = format!("WebAssembly.instantiate(bytes,{{ {imports} }})
.then(obj => {{
wasm = obj.instance;
{memory}
}});
}})",
imports = imports,
memory = if export_mem { "memory = wasm.exports.memory;" } else { "" },
);
let (bytes, booted) = if self.base64 {
let wasm = serialize(self.module)
.expect("failed to serialize");
(
format!("
let bytes;
const base64 = \"{base64}\";
if (typeof Buffer === 'undefined') {{
bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
}} else {{
bytes = Buffer.from(base64, 'base64');
}}", base64 = base64::encode(&wasm)),
inst
)
} else if self.fetch {
(
String::new(),
format!("fetch('/{name}')
.then(res => res.arrayBuffer())
.then(bytes => {inst})", name = self.file_name, inst = inst)
)
} else {
panic!("the option --base64 or --fetch is required");
};
format!("
{js_imports}
let wasm;
{bytes}
{mem_export}
export const booted = {booted};
{exports}
",
base64 = base64::encode(&wasm),
bytes = bytes,
booted = booted,
js_imports = js_imports,
imports = imports,
exports = exports,
mem_export = if export_mem { "export let memory;" } else { "" },
memory = if export_mem { "memory = wasm.exports.memory;" } else { "" },
)
}
}

View File

@ -22,6 +22,7 @@ Options:
-o --output FILE File to place output in
--typescript Output a `*.d.ts` file next to the JS output
--base64 Inline the wasm module using base64 encoding
--fetch Load module via `fetch()` instead of default webpack implementation
Note that this is not intended to produce a production-ready output module
but rather is intended purely as a temporary \"hack\" until it's standard in
@ -33,6 +34,7 @@ struct Args {
flag_output: Option<PathBuf>,
flag_typescript: bool,
flag_base64: bool,
flag_fetch: bool,
arg_input: PathBuf,
}
@ -41,8 +43,8 @@ fn main() {
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if !args.flag_base64 {
panic!("unfortunately only works right now with base64");
if !args.flag_base64 && !args.flag_fetch {
panic!("unfortunately only works right now with base64 or fetch");
}
let mut wasm = Vec::new();
@ -51,6 +53,7 @@ fn main() {
let object = wasm_bindgen_cli_support::wasm2es6js::Config::new()
.base64(args.flag_base64)
.fetch(args.flag_fetch, &args.arg_input)
.generate(&wasm)
.expect("failed to parse wasm");

View File

@ -0,0 +1,21 @@
#!/bin/sh
set -ex
# This is the same as the directory above this.
cargo +nightly build --target wasm32-unknown-unknown
cargo +nightly run -p wasm-bindgen-cli --bin wasm-bindgen -- \
../../../target/wasm32-unknown-unknown/debug/hello_world.wasm --out-dir .
# To avoid a bug occurring when webpack, wasm, and Chrome are used together, we
# convert the .wasm module to a .js module that embeds the wasm bytecode. To
# enable this, use the "--resolve-enxensions .js" flag when starting
# webpack-dev-server
cargo +nightly run -p wasm-bindgen-cli --bin wasm2es6js -- \
--fetch -o hello_world_bg.js hello_world_bg.wasm
# wasm2es6js --base64 -o hello_world_bg.js hello_world_bg.wasm
# And like the directory above this, from here it's the same.
npm install
#force webpack-dev-server to ignore the .wasm file
npm run serve -- --resolve-extensions .js