use std::error::Error;
use std::process::Command;
use std::path::Path;
use tokio::task;
use crate::config::{WasmModule, AssetSource};
pub async fn compile_wasm_modules(
modules: &[WasmModule],
) -> Result<(), Box<dyn Error>> {
let mut compile_futures = Vec::new();
for module in modules {
if module.compile_wasm {
if let AssetSource::Local(path) = &module.source {
let module_dir = extract_module_dir(path)?;
println!("Queue compilation for {}: {}", module.id, module_dir);
let future = Box::pin(build_wasm(module_dir));
compile_futures.push((
module.id.clone(),
future
));
}
}
}
if compile_futures.is_empty() {
println!("No WASM modules need compilation");
return Ok(());
}
let (ids, futures): (Vec<_>, Vec<_>) = compile_futures.into_iter().unzip();
let results = futures::future::join_all(futures).await;
let mut failed = false;
for (id, result) in ids.iter().zip(results.iter()) {
match result {
Ok(_) => println!("✅ {} compiled successfully", id),
Err(err) => {
eprintln!("❌ {} build failed: {}", id, err);
failed = true;
}
}
}
if failed {
return Err("One or more WASM builds failed".into());
}
println!("All WASM builds compiled successfully!");
Ok(())
}
fn extract_module_dir(
wasm_path: &Path,
) -> Result<String, Box<dyn Error>> {
if let Some(parent) = wasm_path.parent() {
if parent.ends_with("pkg") {
if let Some(module_dir) = parent.parent() {
return Ok(module_dir.to_string_lossy().to_string());
}
}
}
Err(format!(
"cannot extract project directory from path: {:?}. \
Expected pattern like '../module/pkg/wasm_module_bg.wasm'",
wasm_path
).into())
}
async fn build_wasm(
dir: String,
) -> Result<(), Box<dyn Error + Send + Sync>> {
println!("Building WASM in {}", dir);
let dir_copy = dir.clone();
let status = task::spawn_blocking(move || {
Command::new("wasm-pack")
.current_dir(&dir)
.args(&[
"build",
"--target",
"no-modules",
])
.status()
})
.await?;
if !status?.success() {
return Err(format!("Failed to compiled WASM in {}", &dir_copy).into());
}
println!("WASM compiled in {}.", &dir_copy);
Ok(())
}