web_message/lib.rs
1//! A crate for sending and receiving messages via `postMessage`.
2//!
3//! Any type that implements [Message] can be serialized and unserialized.
4//! Unlike using Serde for JSON encoding, this approach preserves [Transferable Objects](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) and can avoid expensive allocations and copying.
5//! Unlike using #[wasm-bindgen], this approach works outside of the `wasm-bindgen` ABI, supporting more types (ex. named enum variants).
6//!
7//! For example, the main thread can send a [js_sys::ArrayBuffer] or a Web Worker without copying the data.
8//! If the WASM worker only needs to process a few header bytes, it can use the [js_sys::ArrayBuffer] instead of copying into a [Vec<u8>].
9//! The resulting bytes can then be passed to [VideoDecoder](https://developer.mozilla.org/en-US/docs/Web/API/VideoDecoder) and the resulting [VideoFrame](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame) (transferable) can be posted back to the main thread.
10//! You can even pass around a [web_sys::MessagePort]!
11//!
12//! This crate is designed to be used in conjunction with the `web-message-derive` crate.
13//! We currently attempt parity with [ts-rs](https://docs.rs/ts-rs/latest/ts_rs/) so the resulting types can use `postMessage` directly from Typescript.
14//!
15//! ```rs
16//! // NOTE: This is not possible with `wasm-bindgen` or `wasm-bindgen-serde`
17//! #[derive(Message)]
18//! #[msg(tag = "command")]
19//! enum Command {
20//! Connect {
21//! url: String,
22//! },
23//! Frame {
24//! keyframe: bool,
25//! payload: js_sys::ArrayBuffer,
26//! },
27//! Close,
28//! }
29//! ```
30//!
31//! Some transferable types are gated behind feature flags:
32//!
33
34// Required for derive to work.
35extern crate self as web_message;
36
37#[cfg(feature = "derive")]
38mod derive;
39#[cfg(feature = "derive")]
40pub use derive::*;
41
42mod error;
43mod message;
44
45pub use error::*;
46pub use message::*;