bitwarden_ipc/wasm/
message.rs1use std::str;
2
3use wasm_bindgen::prelude::*;
4
5use crate::{
6 endpoint::{Endpoint, Source},
7 message::{IncomingMessage, OutgoingMessage},
8};
9
10#[bitwarden_ffi::wasm_export]
11impl OutgoingMessage {
12 #[wasm_bindgen(constructor)]
13 pub fn new(payload: Vec<u8>, destination: Endpoint, topic: Option<String>) -> OutgoingMessage {
15 OutgoingMessage {
16 payload,
17 destination,
18 topic,
19 }
20 }
21
22 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 #[wasm_only(note = "Read the `destination` field.")]
41 #[wasm_bindgen(getter)]
42 pub fn destination(&self) -> Endpoint {
44 self.destination.clone()
45 }
46
47 #[wasm_only(note = "Write the `destination` field.")]
48 #[wasm_bindgen(setter = destination)]
49 pub fn set_destination(&mut self, destination: Endpoint) {
51 self.destination = destination;
52 }
53}
54
55#[bitwarden_ffi::wasm_export]
56impl IncomingMessage {
57 #[wasm_bindgen(constructor)]
58 pub fn new(
60 payload: Vec<u8>,
61 destination: Endpoint,
62 source: Source,
63 topic: Option<String>,
64 ) -> IncomingMessage {
65 IncomingMessage {
66 payload,
67 destination,
68 source,
69 topic,
70 }
71 }
72
73 #[wasm_bindgen(
75 return_description = "The parsed JSON value, or undefined if the payload is not valid JSON."
76 )]
77 pub fn parse_payload_as_json(&self) -> JsValue {
78 str::from_utf8(&self.payload)
79 .ok()
80 .and_then(|payload| js_sys::JSON::parse(payload).ok())
81 .unwrap_or(JsValue::UNDEFINED)
82 }
83
84 #[wasm_only(note = "Read the `destination` field.")]
85 #[wasm_bindgen(getter)]
86 pub fn destination(&self) -> Endpoint {
88 self.destination.clone()
89 }
90
91 #[wasm_only(note = "Write the `destination` field.")]
92 #[wasm_bindgen(setter = destination)]
93 pub fn set_destination(&mut self, destination: Endpoint) {
95 self.destination = destination;
96 }
97
98 #[wasm_only(note = "Read the `source` field.")]
99 #[wasm_bindgen(getter)]
100 pub fn source(&self) -> Source {
102 self.source.clone()
103 }
104
105 #[wasm_only(note = "Write the `source` field.")]
106 #[wasm_bindgen(setter = source)]
107 pub fn set_source(&mut self, source: Source) {
109 self.source = source;
110 }
111}