nym_wasm_utils/
lib.rs

1// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use wasm_bindgen::prelude::*;
5
6#[cfg(feature = "websocket")]
7pub mod websocket;
8
9#[cfg(feature = "crypto")]
10pub mod crypto;
11
12pub mod error;
13
14// will cause messages to be written as if console.log("...") was called
15#[macro_export]
16macro_rules! console_log {
17    ($($t:tt)*) => ($crate::log(&format_args!($($t)*).to_string()))
18}
19
20// will cause messages to be written as if console.debug("...") was called
21#[macro_export]
22macro_rules! console_debug {
23    ($($t:tt)*) => ($crate::debug(&format_args!($($t)*).to_string()))
24}
25
26// will cause messages to be written as if console.info("...") was called
27#[macro_export]
28macro_rules! console_info {
29    ($($t:tt)*) => ($crate::info(&format_args!($($t)*).to_string()))
30}
31
32// will cause messages to be written as if console.warn("...") was called
33#[macro_export]
34macro_rules! console_warn {
35    ($($t:tt)*) => ($crate::warn(&format_args!($($t)*).to_string()))
36}
37
38// will cause messages to be written as if console.error("...") was called
39#[macro_export]
40macro_rules! console_error {
41    ($($t:tt)*) => ($crate::error(&format_args!($($t)*).to_string()))
42}
43
44#[wasm_bindgen]
45pub fn set_panic_hook() {
46    // When the `console_error_panic_hook` feature is enabled, we can call the
47    // `set_panic_hook` function at least once during initialization, and then
48    // we will get better error messages if our code ever panics.
49    //
50    // For more details see
51    // https://github.com/rustwasm/console_error_panic_hook#readme
52    #[cfg(feature = "console_error_panic_hook")]
53    console_error_panic_hook::set_once();
54}
55
56#[wasm_bindgen]
57extern "C" {
58    #[wasm_bindgen(js_namespace = console)]
59    pub fn log(s: &str);
60
61    #[wasm_bindgen(js_namespace = console)]
62    pub fn debug(s: &str);
63
64    #[wasm_bindgen(js_namespace = console)]
65    pub fn info(s: &str);
66
67    #[wasm_bindgen(js_namespace = console)]
68    pub fn warn(s: &str);
69
70    #[wasm_bindgen(js_namespace = console)]
71    pub fn error(s: &str);
72}
73
74#[cfg(feature = "sleep")]
75pub async fn sleep(ms: i32) -> Result<(), wasm_bindgen::JsValue> {
76    let promise = js_sys::Promise::new(&mut |yes, _| {
77        let win = web_sys::window().expect("no window available!");
78        win.set_timeout_with_callback_and_timeout_and_arguments_0(&yes, ms)
79            .unwrap();
80    });
81    let js_fut = wasm_bindgen_futures::JsFuture::from(promise);
82    js_fut.await?;
83    Ok(())
84}