Skip to main content

bitwarden_ipc/wasm/
message.rs

1use std::str;
2
3use wasm_bindgen::prelude::*;
4
5use crate::{
6    endpoint::{Endpoint, Source},
7    message::{IncomingMessage, OutgoingMessage},
8};
9
10#[wasm_bindgen]
11impl OutgoingMessage {
12    #[wasm_bindgen(constructor)]
13    /// Create an outgoing IPC message from raw payload bytes.
14    pub fn new(payload: Vec<u8>, destination: Endpoint, topic: Option<String>) -> OutgoingMessage {
15        OutgoingMessage {
16            payload,
17            destination,
18            topic,
19        }
20    }
21
22    /// Create a new message and encode the payload as JSON.
23    pub fn new_json_payload(
24        payload: JsValue,
25        destination: Endpoint,
26        topic: Option<String>,
27    ) -> Result<OutgoingMessage, JsValue> {
28        let payload = js_sys::JSON::stringify(&payload)?;
29        let payload: String = payload
30            .as_string()
31            .ok_or_else(|| JsValue::from_str("Failed to convert JSON payload to string"))?;
32        let payload = payload.into_bytes();
33        Ok(OutgoingMessage {
34            payload,
35            destination,
36            topic,
37        })
38    }
39}
40
41#[wasm_bindgen]
42impl IncomingMessage {
43    #[wasm_bindgen(constructor)]
44    /// Create an incoming IPC message from raw payload bytes.
45    pub fn new(
46        payload: Vec<u8>,
47        destination: Endpoint,
48        source: Source,
49        topic: Option<String>,
50    ) -> IncomingMessage {
51        IncomingMessage {
52            payload,
53            destination,
54            source,
55            topic,
56        }
57    }
58
59    /// Try to parse the payload as JSON.
60    #[wasm_bindgen(
61        return_description = "The parsed JSON value, or undefined if the payload is not valid JSON."
62    )]
63    pub fn parse_payload_as_json(&self) -> JsValue {
64        str::from_utf8(&self.payload)
65            .ok()
66            .and_then(|payload| js_sys::JSON::parse(payload).ok())
67            .unwrap_or(JsValue::UNDEFINED)
68    }
69}