use std::fs::{self, File};
use std::io::{self, Write};
use std::path::PathBuf;
use anyhow::{Result, anyhow};
use wasmtime::component::Component;
use wasmtime::{Config, Engine};
pub fn compile(wasm: &PathBuf, output: Option<PathBuf>) -> Result<()> {
let Some(file_name) = wasm.file_name() else {
return Err(anyhow!("invalid file name"));
};
let mut config = Config::new();
config.wasm_component_model_async(true);
let engine = Engine::new(&config)?;
let component = Component::from_file(&engine, wasm)?;
let serialized = component.serialize()?;
if let Some(mut out_path) = output {
if out_path.is_dir() {
let file_name = file_name.to_string_lossy().to_string();
let file_name = file_name.replace(".wasm", ".bin");
out_path.push(file_name);
}
if let Some(dir) = out_path.parent()
&& !dir.exists()
{
fs::create_dir_all(dir)?;
}
File::create(&out_path)?.write_all(&serialized)?;
} else {
let mut stdout = io::stdout().lock();
stdout.write_all(&serialized)?;
}
Ok(())
}