use chrono::{DateTime, Utc}; use js_sys::{Array, Date, Function, Object, Promise, Reflect, JSON}; use serde::Serialize; use serde_json::Value; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; use crate::{market_contract_held, DidDoc, Error, HttpIo, Io, Options, StrongRef}; struct JsIo { io: JsValue, http: HttpIo, } fn js_err(v: JsValue) -> Error { format!("{v:?}").into() } fn to_js(v: &T) -> Result { JSON::parse(&serde_json::to_string(v).map_err(|e| e.to_string())?) } fn from_js(v: &JsValue) -> Result { let s = JSON::stringify(v)?.as_string().unwrap_or_default(); serde_json::from_str(&s).map_err(|e| e.to_string().into()) } impl JsIo { fn func(&self, name: &str) -> Option { Reflect::get(&self.io, &name.into()).ok()?.dyn_into().ok() } async fn call(&self, f: &Function, args: &[JsValue]) -> Result, Error> { let args: Array = args.iter().collect(); let v = JsFuture::from(Promise::resolve(&f.apply(&self.io, &args).map_err(js_err)?)).await.map_err(js_err)?; if v.is_null() || v.is_undefined() { return Ok(None); } Ok(JSON::stringify(&v).map_err(js_err)?.as_string()) } } impl Io for JsIo { async fn resolve_did(&self, did: &str) -> Result, Error> { let Some(f) = self.func("resolveDid") else { return self.http.resolve_did(did).await; }; Ok(match self.call(&f, &[did.into()]).await? { Some(s) => Some(serde_json::from_str(&s)?), None => None, }) } async fn get_record(&self, repo: &str, collection: &str, rkey: &str) -> Result, Error> { let Some(f) = self.func("getRecord") else { return self.http.get_record(repo, collection, rkey).await; }; Ok(match self.call(&f, &[repo.into(), collection.into(), rkey.into()]).await? { Some(s) => Some(serde_json::from_str(&s)?), None => None, }) } async fn contract_held(&self, contract: &StrongRef, authorities: &[String]) -> Result { let Some(f) = self.func("contractHeld") else { return market_contract_held(self, contract, authorities).await; }; let authorities: Array = authorities.iter().map(|a| JsValue::from_str(a)).collect(); let contract = to_js(contract).map_err(js_err)?; Ok(self.call(&f, &[contract, authorities.into()]).await?.as_deref() == Some("true")) } fn now(&self) -> DateTime { let ms = self .func("now") .and_then(|f| f.call0(&self.io).ok()) .map(|v| Date::new(&v).get_time()) .filter(|ms| ms.is_finite()) .unwrap_or_else(Date::now); DateTime::from_timestamp_millis(ms as i64).unwrap_or(DateTime::::MAX_UTC) } } #[wasm_bindgen(js_name = walk)] pub async fn walk_js(io: JsValue, agent: String, options: JsValue) -> Result { let options: Options = if options.is_object() { from_js(&options)? } else { Options::default() }; let io = js_io(io); to_js(&crate::walk(&io, &agent, options).await) } fn js_io(io: JsValue) -> JsIo { JsIo { io: if io.is_object() { io } else { Object::new().into() }, http: HttpIo::default() } } #[wasm_bindgen(js_name = marketContractHeld)] pub async fn market_contract_held_js(io: JsValue, contract: JsValue, authorities: Vec) -> Result { let contract: StrongRef = from_js(&contract)?; market_contract_held(&js_io(io), &contract, &authorities).await.map_err(|e| JsValue::from_str(&e.to_string())) } #[wasm_bindgen(js_name = recordCid)] pub fn record_cid_js(value: JsValue) -> Result { crate::record_cid(&from_js(&value)?).map_err(|e| JsValue::from_str(&e.to_string())) } #[wasm_bindgen(js_name = agentOf)] pub fn agent_of_js(also_known_as: Vec) -> Vec { crate::agent_of(&also_known_as) } #[wasm_bindgen(js_name = verifyRecord)] pub fn verify_record_js(car: &[u8], doc: JsValue, repo: &str, collection: &str, rkey: &str) -> Result { let doc: DidDoc = from_js(&doc)?; let value = crate::verify_record(car, &doc, repo, collection, rkey).map_err(|e| JsValue::from_str(&e.to_string()))?; to_js(&value) }