Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: load wasm #1705

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/mako/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ tracing = "0.1.37"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
tungstenite = "0.19.0"
twox-hash = "1.6.3"
wasmparser = "0.207.0"

[dev-dependencies]
insta = { version = "1.30.0", features = ["yaml"] }
Expand Down
22 changes: 0 additions & 22 deletions crates/mako/src/build/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ const CSS_EXTENSIONS: [&str; 1] = ["css"];
const JSON_EXTENSIONS: [&str; 2] = ["json", "json5"];
const YAML_EXTENSIONS: [&str; 2] = ["yaml", "yml"];
const XML_EXTENSIONS: [&str; 1] = ["xml"];
const WASM_EXTENSIONS: [&str; 1] = ["wasm"];
const TOML_EXTENSIONS: [&str; 1] = ["toml"];
const SVG_EXTENSIONS: [&str; 1] = ["svg"];
const MD_EXTENSIONS: [&str; 2] = ["md", "mdx"];
Expand Down Expand Up @@ -180,27 +179,6 @@ export function moduleToDom(css) {
}));
}

// wasm
if WASM_EXTENSIONS.contains(&file.extname.as_str()) {
let final_file_name = format!(
"{}.{}.{}",
file.get_file_stem(),
file.get_content_hash()?,
file.extname
);
context.emit_assets(
file.pathname.to_string_lossy().to_string(),
final_file_name.clone(),
);
return Ok(Content::Js(JsContent {
content: format!(
"module.exports = require._interopreRequireWasm(exports, \"{}\")",
final_file_name
),
..Default::default()
}));
}

// xml
if XML_EXTENSIONS.contains(&file.extname.as_str()) {
let content = FileSystem::read_file(&file.pathname)?;
Expand Down
144 changes: 143 additions & 1 deletion crates/mako/src/plugins/wasm_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::sync::Arc;

use anyhow;
use wasmparser::{Import, Parser, Payload};

use crate::ast::file::{Content, JsContent};
use crate::compiler::Context;
use crate::plugin::Plugin;
use crate::plugin::{Plugin, PluginLoadParam};

pub struct WasmRuntimePlugin {}

const WASM_EXTENSIONS: [&str; 1] = ["wasm"];

impl Plugin for WasmRuntimePlugin {
fn name(&self) -> &str {
"wasm_runtime"
Expand All @@ -27,4 +34,139 @@ impl Plugin for WasmRuntimePlugin {
Ok(vec![])
}
}

fn load(
&self,
param: &PluginLoadParam,
_context: &Arc<Context>,
) -> anyhow::Result<Option<Content>> {
let file = param.file;

if WASM_EXTENSIONS.contains(&file.extname.as_str()) {
let final_file_name = format!(
"{}.{}.{}",
file.get_file_stem(),
file.get_content_hash()?,
file.extname
);
_context.emit_assets(
file.pathname.to_string_lossy().to_string(),
final_file_name.clone(),
);

let mut buffer = Vec::new();
File::open(&file.path)?.read_to_end(&mut buffer)?;
// Parse wasm file to get imports
let mut wasm_import_object_map: HashMap<&str, Vec<String>> = HashMap::new();
Parser::new(0).parse_all(&buffer).for_each(|payload| {
if let Ok(Payload::ImportSection(imports)) = payload {
imports.into_iter_with_offsets().for_each(|import| {
if let Ok((
_,
Import {
module,
name,
ty: _,
},
)) = import
{
if let Some(import_object) = wasm_import_object_map.get_mut(module) {
import_object.push(name.to_string());
} else {
wasm_import_object_map.insert(module, vec![name.to_string()]);
}
}
});
}
});

let mut module_import_code = String::new();
let mut wasm_import_object_code = String::new();

for (index, (key, value)) in wasm_import_object_map.iter().enumerate() {
module_import_code.push_str(&format!(
"import * as module{module_idx} from \"{module}\";\n",
module_idx = index,
module = key
));

wasm_import_object_code.push_str(&format!(
"\"{module}\": {{ {names} }}",
module = key,
names = value
.iter()
.map(|name| format!("\"{}\": module{}[\"{}\"]", name, index, name))
.collect::<Vec<String>>()
.join(", ")
));
}

let mut content = String::new();
content.push_str(&module_import_code);

if wasm_import_object_code.is_empty() {
content.push_str(&format!(
"module.exports = require._interopreRequireWasm(exports, \"{}\")",
final_file_name
));
} else {
content.push_str(&format!(
"module.exports = require._interopreRequireWasm(exports, \"{}\", {{{}}})",
xusd320 marked this conversation as resolved.
Show resolved Hide resolved
final_file_name, wasm_import_object_code
));
}

return Ok(Some(Content::Js(JsContent {
content,
..Default::default()
})));
}

Ok(None)
}
}

#[cfg(test)]
mod tests {
use std::sync::Arc;

use super::*;
use crate::ast::file::File;
use crate::compiler::Context;

#[test]
fn test_wasm_runtime_load_with_import_object() {
let plugin = WasmRuntimePlugin {};
let context = Arc::new(Context {
..Default::default()
});
let wasm_relative_path =
std::path::Path::new("../../examples/import-resources/minus-wasm-pack/index_bg.wasm");
let wasm_path = std::fs::canonicalize(wasm_relative_path).unwrap();
let file = File::new(wasm_path.to_string_lossy().to_string(), context.clone());
let param = PluginLoadParam { file: &file };
let result: Option<Content> = plugin.load(&param, &context).unwrap();

assert!(result.is_some());
if let Some(Content::Js(js_content)) = result {
assert!(js_content.content.contains("import * as module0 from"));
}
}

#[test]
fn test_wasm_runtime_load_without_import_object() {
let plugin = WasmRuntimePlugin {};
let context = Arc::new(Context {
..Default::default()
});
let wasm_relative_path = std::path::Path::new("../../examples/import-resources/add.wasm");
let wasm_path = std::fs::canonicalize(wasm_relative_path).unwrap();
let file = File::new(wasm_path.to_string_lossy().to_string(), context.clone());
let param = PluginLoadParam { file: &file };
let result = plugin.load(&param, &context).unwrap();
assert!(result.is_some());
if let Some(Content::Js(js_content)) = result {
assert!(!js_content.content.contains("import * as module0 from"))
}
}
}
3 changes: 3 additions & 0 deletions examples/import-resources/import-js-wasm/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* tslint:disable */
/* eslint-disable */
export function run(): void;
5 changes: 5 additions & 0 deletions examples/import-resources/import-js-wasm/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as wasm from './index_bg.wasm';
export * from './index_bg.js';
import { __wbg_set_wasm } from './index_bg.js';
__wbg_set_wasm(wasm);
wasm.__wbindgen_start();
Loading