pub mod rewrite; use std::{panic, str::FromStr}; use js_sys::{Function, Object, Reflect}; use rewrite::{rewrite, Config, EncodeFn}; use url::Url; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); } #[wasm_bindgen] pub fn init() { panic::set_hook(Box::new(console_error_panic_hook::hook)); } fn create_encode_function(encode: Function) -> EncodeFn { Box::new(move |str| { encode .call1(&JsValue::NULL, &str.into()) .unwrap() .as_string() .unwrap() .to_string() }) } #[wasm_bindgen] pub fn rewrite_js(js: &str, url: &str, config: Object) -> Vec { rewrite( js, Url::from_str(url).unwrap(), Config { prefix: Reflect::get(&config, &"prefix".into()) .unwrap() .as_string() .unwrap(), encode: create_encode_function(Reflect::get(&config, &"encode".into()).unwrap().into()), wrapfn: Reflect::get(&config, &"wrapfn".into()) .unwrap() .as_string() .unwrap(), importfn: Reflect::get(&config, &"importfn".into()) .unwrap() .as_string() .unwrap(), rewritefn: Reflect::get(&config, &"rewritefn".into()) .unwrap() .as_string() .unwrap(), }, ) } #[wasm_bindgen] pub fn rewrite_js_from_arraybuffer(js: &[u8], url: &str, config: Object) -> Vec { // we know that this is a valid utf-8 string let js = unsafe { std::str::from_utf8_unchecked(js) }; rewrite( js, Url::from_str(url).unwrap(), Config { prefix: Reflect::get(&config, &"prefix".into()) .unwrap() .as_string() .unwrap(), encode: create_encode_function(Reflect::get(&config, &"encode".into()).unwrap().into()), wrapfn: Reflect::get(&config, &"wrapfn".into()) .unwrap() .as_string() .unwrap(), importfn: Reflect::get(&config, &"importfn".into()) .unwrap() .as_string() .unwrap(), rewritefn: Reflect::get(&config, &"rewritefn".into()) .unwrap() .as_string() .unwrap(), }, ) }