bitwarden_wasm_internal/
client.rs

1extern crate console_error_panic_hook;
2use std::{fmt::Display, sync::Arc};
3
4use bitwarden_core::ClientSettings;
5use bitwarden_error::bitwarden_error;
6use bitwarden_pm::{PasswordManagerClient, clients::*};
7use wasm_bindgen::prelude::*;
8
9use crate::platform::{
10    PlatformClient,
11    token_provider::{JsTokenProvider, WasmClientManagedTokens},
12};
13
14/// The main entry point for the Bitwarden SDK in WebAssembly environments
15#[wasm_bindgen]
16pub struct BitwardenClient(pub(crate) PasswordManagerClient);
17
18#[wasm_bindgen]
19impl BitwardenClient {
20    /// Initialize a new instance of the SDK client
21    #[wasm_bindgen(constructor)]
22    pub fn new(token_provider: JsTokenProvider, settings: Option<ClientSettings>) -> Self {
23        let tokens = Arc::new(WasmClientManagedTokens::new(token_provider));
24        Self(PasswordManagerClient::new_with_client_tokens(
25            settings, tokens,
26        ))
27    }
28
29    /// Test method, echoes back the input
30    pub fn echo(&self, msg: String) -> String {
31        msg
32    }
33
34    /// Returns the current SDK version
35    pub fn version(&self) -> String {
36        env!("SDK_VERSION").to_owned()
37    }
38
39    /// Test method, always throws an error
40    pub fn throw(&self, msg: String) -> Result<(), TestError> {
41        Err(TestError(msg))
42    }
43
44    /// Test method, calls http endpoint
45    pub async fn http_get(&self, url: String) -> Result<String, String> {
46        let client = self.0.0.internal.get_http_client();
47        let res = client.get(&url).send().await.map_err(|e| e.to_string())?;
48
49        res.text().await.map_err(|e| e.to_string())
50    }
51
52    /// Auth related operations.
53    pub fn auth(&self) -> AuthClient {
54        self.0.auth()
55    }
56
57    /// Crypto related operations.
58    pub fn crypto(&self) -> CryptoClient {
59        self.0.0.crypto()
60    }
61
62    /// Vault item related operations.
63    pub fn vault(&self) -> VaultClient {
64        self.0.vault()
65    }
66
67    /// Constructs a specific client for platform-specific functionality
68    pub fn platform(&self) -> PlatformClient {
69        PlatformClient::new(self.0.0.clone())
70    }
71
72    /// Constructs a specific client for generating passwords and passphrases
73    pub fn generator(&self) -> GeneratorClient {
74        self.0.generator()
75    }
76
77    /// Exporter related operations.
78    pub fn exporters(&self) -> ExporterClient {
79        self.0.exporters()
80    }
81}
82
83#[bitwarden_error(basic)]
84pub struct TestError(String);
85
86impl Display for TestError {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{}", self.0)
89    }
90}