use super::types::JSONEvalWasm;
use crate::JSONEval;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen(js_name = getVersion)]
pub fn get_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[wasm_bindgen]
pub fn version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[wasm_bindgen(start)]
pub fn init() {
console_error_panic_hook::set_once();
}
#[wasm_bindgen]
impl JSONEvalWasm {
#[wasm_bindgen(constructor)]
pub fn new(
schema: &str,
context: Option<String>,
data: Option<String>,
) -> Result<JSONEvalWasm, JsValue> {
console_error_panic_hook::set_once();
let ctx = context.as_deref();
let dt = data.as_deref();
match JSONEval::new(schema, ctx, dt) {
Ok(eval) => Ok(JSONEvalWasm {
inner: eval,
current_token: None,
}),
Err(e) => {
let error_msg = format!("Failed to create JSONEval instance: {}", e);
log(&format!("[WASM ERROR] {}", error_msg));
Err(JsValue::from_str(&error_msg))
}
}
}
#[wasm_bindgen(js_name = newFromMsgpack)]
pub fn new_from_msgpack(
schema_msgpack: &[u8],
context: Option<String>,
data: Option<String>,
) -> Result<JSONEvalWasm, JsValue> {
console_error_panic_hook::set_once();
let ctx = context.as_deref();
let dt = data.as_deref();
match JSONEval::new_from_msgpack(schema_msgpack, ctx, dt) {
Ok(eval) => Ok(JSONEvalWasm {
inner: eval,
current_token: None,
}),
Err(e) => {
let error_msg =
format!("Failed to create JSONEval instance from MessagePack: {}", e);
log(&format!("[WASM ERROR] {}", error_msg));
Err(JsValue::from_str(&error_msg))
}
}
}
#[wasm_bindgen(js_name = newFromCache)]
pub fn new_from_cache(
cache_key: &str,
context: Option<String>,
data: Option<String>,
) -> Result<JSONEvalWasm, JsValue> {
console_error_panic_hook::set_once();
let ctx = context.as_deref();
let dt = data.as_deref();
let parsed = crate::PARSED_SCHEMA_CACHE.get(cache_key).ok_or_else(|| {
let error_msg = format!("Schema '{}' not found in cache", cache_key);
log(&format!("[WASM ERROR] {}", error_msg));
JsValue::from_str(&error_msg)
})?;
match JSONEval::with_parsed_schema(parsed, ctx, dt) {
Ok(eval) => Ok(JSONEvalWasm {
inner: eval,
current_token: None,
}),
Err(e) => {
let error_msg = format!("Failed to create JSONEval from cache: {}", e);
log(&format!("[WASM ERROR] {}", error_msg));
Err(JsValue::from_str(&error_msg))
}
}
}
#[wasm_bindgen(js_name = setTimezoneOffset)]
pub fn set_timezone_offset(&mut self, offset_minutes: Option<i32>) {
self.inner.set_timezone_offset(offset_minutes);
}
#[wasm_bindgen(js_name = cancel)]
pub fn cancel(&mut self) {
if let Some(token) = &self.current_token {
token.cancel();
}
}
}
pub(super) fn console_log(msg: &str) {
log(msg);
}