Skip to content

Commit

Permalink
fix js callback obj
Browse files Browse the repository at this point in the history
  • Loading branch information
insipx committed Jan 31, 2025
1 parent 394966d commit 403e9e9
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 40 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,3 @@ diesel = { git = "https://github.com/diesel-rs/diesel", branch = "master" }
diesel_derives = { git = "https://github.com/diesel-rs/diesel", branch = "master" }
diesel_migrations = { git = "https://github.com/diesel-rs/diesel", branch = "master" }
sqlite-web = { git = "https://github.com/xmtp/sqlite-web-rs", branch = "main" }

4 changes: 4 additions & 0 deletions bindings_wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ futures.workspace = true

[dev-dependencies]
wasm-bindgen-test.workspace = true
xmtp_common = { workspace = true, features = ["test-utils"] }

[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
split-linked-modules = true
4 changes: 2 additions & 2 deletions bindings_wasm/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub async fn create_client(
) -> Result<Client, JsError> {
init_logging(log_options.unwrap_or_default())?;
xmtp_mls::storage::init_sqlite().await;
let api_client = XmtpHttpApiClient::new(host.clone()).unwrap();
let api_client = XmtpHttpApiClient::new(host.clone())?;

let storage_option = match db_path {
Some(path) => StorageOption::Persistent(path),
Expand Down Expand Up @@ -216,7 +216,7 @@ impl Client {
.await
.map_err(|e| JsError::new(format!("{}", e).as_str()))?;

Ok(serde_wasm_bindgen::to_value(&results)?)
Ok(crate::to_value(&results)?)
}

#[wasm_bindgen(js_name = registerIdentity)]
Expand Down
52 changes: 40 additions & 12 deletions bindings_wasm/src/conversation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::sync::Arc;
use wasm_bindgen::JsValue;
use wasm_bindgen::UnwrapThrowExt;
use wasm_bindgen::{prelude::wasm_bindgen, JsError};
use xmtp_mls::storage::group::ConversationType;

Expand Down Expand Up @@ -259,7 +258,7 @@ impl Conversation {
})
.collect();

Ok(serde_wasm_bindgen::to_value(&members)?)
Ok(crate::to_value(&members)?)
}

#[wasm_bindgen(js_name = adminList)]
Expand Down Expand Up @@ -529,17 +528,16 @@ impl Conversation {
self.inner_client.clone(),
self.group_id.clone(),
move |message| match message {
Ok(item) => {
let f = callback.on_item();
let _ = f
.call0(&serde_wasm_bindgen::to_value(&item).unwrap_throw())
.unwrap_throw();
Ok(item) => {
let serialized = crate::to_value(&item);
if let Err(e) = serialized {
callback.on_error(JsError::from(e));
} else {
callback.on_item(serialized.expect("checked for err"))
}
},
Err(e) => callback.on_error(JsError::from(e)),
}
Err(e) => {
let f = callback.on_error();
let _ = f.call0(&JsValue::from(JsError::from(e))).unwrap_throw();
}
},
);

Ok(StreamCloser::new(stream_closer))
Expand Down Expand Up @@ -614,3 +612,33 @@ impl Conversation {
.map_err(Into::into)
}
}

#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::wasm_bindgen_test;
use xmtp_mls::storage::group_message::{
ContentType, DeliveryStatus, GroupMessageKind, StoredGroupMessage,
};
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_dedicated_worker);

#[wasm_bindgen_test]
fn test_group_message_to_object() {
let stored_message = StoredGroupMessage {
id: xmtp_common::rand_vec::<32>(),
group_id: xmtp_common::rand_vec::<32>(),
decrypted_message_bytes: xmtp_common::rand_vec::<32>(),
sent_at_ns: 1738354508964432000,
kind: GroupMessageKind::Application,
sender_installation_id: xmtp_common::rand_vec::<32>(),
sender_inbox_id: String::from("test"),
delivery_status: DeliveryStatus::Published,
content_type: ContentType::Text,
version_major: 4,
version_minor: 123,
authority_id: String::from("test"),
reference_id: None,
};
let value = crate::to_value(&stored_message).unwrap();
}
}
26 changes: 10 additions & 16 deletions bindings_wasm/src/conversations.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::HashMap;
use std::sync::Arc;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::UnwrapThrowExt;
use wasm_bindgen::{JsError, JsValue};
use xmtp_mls::groups::{GroupMetadataOptions, HmacKey as XmtpHmacKey, PreconfiguredPolicies};
use xmtp_mls::storage::group::ConversationType as XmtpConversationType;
Expand Down Expand Up @@ -413,7 +412,7 @@ impl Conversations {
hmac_map.insert(id, keys);
}

Ok(serde_wasm_bindgen::to_value(&hmac_map)?)
Ok(crate::to_value(&hmac_map)?)
}

#[wasm_bindgen(js_name = stream)]
Expand All @@ -427,14 +426,10 @@ impl Conversations {
conversation_type.map(Into::into),
move |message| match message {
Ok(item) => {
let f = callback.on_item();
let conversation = Conversation::from(item);
let _ = f.call0(&JsValue::from(conversation)).unwrap_throw();
}
Err(e) => {
let f = callback.on_error();
let _ = f.call0(&JsValue::from(JsError::from(e))).unwrap_throw();
callback.on_item(JsValue::from(conversation))
}
Err(e) => callback.on_error(JsError::from(e)),
},
);

Expand Down Expand Up @@ -462,15 +457,14 @@ impl Conversations {
conversation_type.map(Into::into),
move |message| match message {
Ok(m) => {
let f = callback.on_item();
let _ = f
.call0(&serde_wasm_bindgen::to_value(&m).unwrap_throw())
.unwrap_throw();
}
Err(e) => {
let f = callback.on_error();
let _ = f.call0(&JsValue::from(JsError::from(e))).unwrap_throw();
let serialized = crate::to_value(&m);
if let Err(e) = serialized {
callback.on_error(JsError::from(e));
} else {
callback.on_item(serialized.expect("checked for err"))
}
}
Err(e) => callback.on_error(JsError::from(e)),
},
);
Ok(StreamCloser::new(stream_closer))
Expand Down
5 changes: 3 additions & 2 deletions bindings_wasm/src/encoded_content.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use js_sys::Uint8Array;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use wasm_bindgen::UnwrapThrowExt;
use xmtp_proto::xmtp::mls::message_contents::{
ContentTypeId as XmtpContentTypeId, EncodedContent as XmtpEncodedContent,
};
Expand Down Expand Up @@ -94,7 +95,7 @@ impl From<XmtpEncodedContent> for EncodedContent {

EncodedContent {
r#type,
parameters: serde_wasm_bindgen::to_value(&content.parameters).unwrap(),
parameters: crate::to_value(&content.parameters).unwrap_throw(),
fallback: content.fallback,
compression: content.compression,
content: content.content.as_slice().into(),
Expand All @@ -108,7 +109,7 @@ impl From<EncodedContent> for XmtpEncodedContent {

XmtpEncodedContent {
r#type,
parameters: serde_wasm_bindgen::from_value(content.parameters).unwrap(),
parameters: serde_wasm_bindgen::from_value(content.parameters).unwrap_throw(),
fallback: content.fallback,
compression: content.compression,
content: content.content.to_vec(),
Expand Down
2 changes: 1 addition & 1 deletion bindings_wasm/src/inbox_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub async fn get_inbox_id_for_address(
) -> Result<Option<String>, JsError> {
let account_address = account_address.to_lowercase();
let api_client = ApiClientWrapper::new(
XmtpHttpApiClient::new(host.clone()).unwrap().into(),
XmtpHttpApiClient::new(host.clone())?.into(),
Retry::default(),
);

Expand Down
13 changes: 11 additions & 2 deletions bindings_wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ pub mod permissions;
pub mod signatures;
pub mod streams;

fn error(e: impl std::error::Error) -> wasm_bindgen::JsError {
wasm_bindgen::JsError::new(&format!("{}", e))
fn error(e: impl std::error::Error) -> JsError {
JsError::new(&format!("{}", e))
}
use serde_wasm_bindgen::Serializer;
use wasm_bindgen::{JsError, JsValue};

/// Converts a Rust value into a [`JsValue`].
pub(crate) fn to_value<T: serde::ser::Serialize + ?Sized>(
value: &T,
) -> Result<JsValue, serde_wasm_bindgen::Error> {
value.serialize(&Serializer::new().serialize_large_number_types_as_bigints(true))
}
4 changes: 2 additions & 2 deletions bindings_wasm/src/streams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ extern "C" {

/// Js Fn to call on an item
#[wasm_bindgen(structural, method)]
pub fn on_item(this: &StreamCallback) -> js_sys::Function;
pub fn on_item(this: &StreamCallback, item: JsValue);

/// Js Fn to call on error
#[wasm_bindgen(structural, method)]
pub fn on_error(this: &StreamCallback) -> js_sys::Function;
pub fn on_error(this: &StreamCallback, error: JsError);
}

#[wasm_bindgen]
Expand Down
6 changes: 4 additions & 2 deletions bindings_wasm/tests/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use xmtp_id::associations::generate_inbox_id;
use xmtp_id::InboxOwner;

// Only run these tests in a browser.
wasm_bindgen_test_configure!(run_in_browser);
wasm_bindgen_test_configure!(run_in_dedicated_worker);

#[wasm_bindgen]
extern "C" {
Expand Down Expand Up @@ -36,6 +36,8 @@ pub async fn test_create_client() {
}),
)
.await;

if let Err(ref e) = client {
tracing::info!("{:?}", e);
}
assert!(client.is_ok());
}
3 changes: 3 additions & 0 deletions xmtp_mls/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,6 @@ required-features = ["bench"]
#harness = false
#name = "sync"
#required-features = ["bench"]

[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
split-linked-modules = true

0 comments on commit 403e9e9

Please sign in to comment.