bevy_remote_wasm 0.1.0

Wasm transport for the Bevy Remote Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! A plugin for the [Bevy Remote Protocol](https://docs.rs/bevy/latest/bevy/remote/) that exposes remote methods to
//! Wasm/JavaScript.
//!
//! ## Setup
//!
//! 1. Add `bevy_remote` to your dependencies, and `bevy_remote_wasm` only for `wasm` targets.
//!
//!    ```toml
//!    [dependencies]
//!    bevy = "0.18"
//!    bevy_remote = { version = "0.18", default-features = false }
//!
//!    [target.'cfg(target_family = "wasm")'.dependencies]
//!    bevy_remote_wasm = "0.1"
//!    ```
//!
//!    Don't depend on `bevy/bevy_remote` (`bevy = { version = "0.18", features = ["bevy_remote"] }`) because it
//!    enables the default `http` transport, which does not compile on Wasm target (until
//!    [this fix](https://github.com/bevyengine/bevy/pull/23367/) is merged and released).
//!
//!    This is why it is recommended to depend on the separate crate `bevy_remote` with no default features (so
//!    `bevy_remote/http` is not enabled).
//!
//! 2. Add [`RemotePlugin`](bevy_remote::RemotePlugin) to your [`App`], and add [`RemoteWasmPlugin`] only when compiling
//!    for Wasm.
//!
//!    ```rust
//!    use bevy::prelude::*;
//!    use bevy_remote::RemotePlugin;
//!
//!    let mut app = App::new();
//!    app.add_plugins((DefaultPlugins, RemotePlugin::default()));
//!    #[cfg(target_family = "wasm")]
//!    app.add_plugins(bevy_remote_wasm::RemoteWasmPlugin);
//!    app.run();
//!    ```
//!
//! 3. Build for the `wasm32-unknown-unknown` target, then generate the JS bindings with
//!    [`wasm-bindgen`](https://wasm-bindgen.github.io/wasm-bindgen/)
//!    directly (`wasm-bindgen --target web --out-dir <output_dir> target/wasm32-unknown-unknown/debug/<crate_name>.wasm`)
//!    or through a tool such as [`wasm-pack`](https://wasm-bindgen.github.io/wasm-pack/) or [Trunk](https://trunkrs.dev/).
//!
//! 4. In JavaScript, load the generated JS module, call `init()`, then await `getBridge()`:
//!
//!    ```js
//!    import init, { getBridge } from "/example.js";
//!
//!    await init();
//!    const bridge = await getBridge();
//!    const response = await bridge.main["rpc.discover"]();
//!    console.log(response.info.version);
//!    ```
//!
//!    The generated module path and `init` function depend on your build tool, but the initialization order does not:
//!    initialize the Wasm module first, then await the bridge.
//!
//!    `getBridge()` may be called as soon as the JS module loads, but it resolves only after Bevy publishes the bridge
//!    during app startup, which, depending on your setup, may take some time.
//!
//!    The `wasm-bindgen` output also includes TypeScript declarations for the root bridge (`BrpBridge`) and the default
//!    remote methods (`BuiltInBrpBridge`):
//!
//!    ```ts
//!    import type { BuiltInBrpBridge } from "./example.js";
//!
//!    const bridge = await getBridge() as BuiltInBrpBridge;
//!    const response = await bridge.main['world.query']({ data: { option: 'all' } });
//!    // Enjoy docs and autocompletion for built-in methods!
//!    ```
//!
//! 5. Serve the generated HTML, JS, and `.wasm` files together from a web server or bundler that supports Wasm imports.
//!
//! ## Wasm API
//!
//! The plugin builds a bridge object with app-scoped method maps based on the methods registered with
//! [`RemotePlugin`](bevy_remote::RemotePlugin), more specifically through the [`RemoteMethods`]
//! resource. Each time this resource is updated, the bridge is re-published with the new methods. The `getBridge()`
//! function must be called again to get the updated bridge.
//!
//! For Bevy `0.18`, the bridge exposes only the `main` app. Method keys inside that namespace use the BRP method names
//! directly, so call them with bracket notation such as `bridge.main["world.query"]` and
//! `bridge.main["world.list_components+watch"]`.
//!
//! - Instant methods (run once, return a result):
//!
//! ```js
//! // Call the instant method with params but without callback.
//! // Returns the result wrapped in a Promise.
//! const result = await bridge.main['world.query']({ data: { option: 'all' } });
//! console.log(result);
//!
//! // Call the instant method with params and a callback that will be called with the result.
//! // Returns `undefined` wrapped in a Promise.
//! await bridge.main['world.query']({ data: { option: 'all' } }, (result) => console.log(result));
//! ```
//!
//! - Watching methods (stream results):
//!
//! ```js
//! // Call the watching method with params and a callback that will be called on each result.
//! // Returns a closer function wrapped in a Promise.
//! const close = await bridge.main['world.list_components+watch']({ entity: 123 }, (result) => console.log(result));
//!
//! // Stop the stream.
//! close();
//! ```

#![cfg(any(doc, target_family = "wasm"))]

use async_channel::Sender;
use bevy_app::{App, Plugin, Update};
use bevy_ecs::{
    schedule::{
        IntoScheduleConfigs,
        common_conditions::{resource_exists, resource_exists_and_changed},
    },
    system::Res,
};
use bevy_remote::{BrpMessage, BrpResult, BrpSender, RemoteMethodSystemId, RemoteMethods};
use serde::Serialize;
use serde_json::Value;
use std::{
    cell::RefCell,
    collections::BTreeMap,
    task::{Poll, Waker},
};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{future_to_promise, spawn_local};

/// Add this plugin to your [`App`] to allow "remote" connections over Wasm to inspect and modify the
/// [`World`](bevy_ecs::world::World).
/// It requires the [`RemotePlugin`](bevy_remote::RemotePlugin).
pub struct RemoteWasmPlugin;

impl Plugin for RemoteWasmPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            // `BrpSender` and `RemoteMethods` are inserted by `RemotePlugin`.
            update_wasm_bridge
                .run_if(resource_exists::<BrpSender>)
                .run_if(resource_exists_and_changed::<RemoteMethods>),
        );
    }
}

// The TypeScript definitions for the bridge, generated by `build.rs` and included in the wasm-bindgen output.
#[wasm_bindgen(typescript_custom_section)]
const TS_TYPES: &str = include_str!(concat!(env!("OUT_DIR"), "/ts_types.d.ts"));

/// Internal state for managing the bridge promise returned by `getBridge()`.
#[derive(Default)]
struct BridgeState {
    /// The bridge, once published by the plugin.
    bridge: Option<js_sys::Object>,
    /// Waker for the most recent pending `getBridge()` call.
    waker: Option<Waker>,
}

thread_local! {
    // JS may call `getBridge()` as soon as the module is instantiated, but the bridge is only built when Bevy runs its
    // systems. This thread-local bridges that timing gap.
    static BRIDGE_STATE: RefCell<BridgeState> = RefCell::new(BridgeState::default());
}

/// Get a promise which resolves into the bridge object once it is published by the plugin.
///
/// The returned object exposes a `main` property whose functions match all methods registered with
/// [`RemoteMethods`].
#[doc(hidden)]
#[wasm_bindgen(js_name = getBridge, skip_typescript)]
pub async fn get_bridge() -> js_sys::Object {
    if let Some(bridge) = BRIDGE_STATE.with(|state| state.borrow().bridge.clone()) {
        bridge
    } else {
        std::future::poll_fn(|cx| {
            BRIDGE_STATE.with_borrow_mut(|state| {
                if let Some(bridge) = state.bridge.clone() {
                    return Poll::Ready(bridge);
                }

                state.waker = Some(cx.waker().clone());
                Poll::Pending
            })
        })
        .await
    }
}

/// Wasm-facing method wrapper signature used by the BRP bridge.
///
/// Both instant and watching BRP methods take `(params?, callback?)` and return a Promise.
/// - Instant methods without a callback resolve to the result value.
/// - Instant methods with a callback resolve to `undefined`.
/// - Watching methods resolve to a closer function that can be called to stop the stream of updates
type WasmBridgeMethod = dyn Fn(Option<JsValue>, Option<js_sys::Function>) -> js_sys::Promise + 'static;

/// Wasm-facing closer function returned by watching BRP methods.
type WasmBridgeWatchCloser = dyn Fn() + 'static;

/// Internal map of methods for a single Bevy app.
struct BrpApp(BTreeMap<String, Closure<WasmBridgeMethod>>);

/// Internal bridge representation.
struct BrpBridge {
    main: BrpApp,
}

/// Publish the bridge to Wasm and wake any pending `getBridge()` call.
fn publish_bridge(bridge: BrpBridge) {
    if let Some(waker) = BRIDGE_STATE.with_borrow_mut(|state| {
        state.bridge = Some(bridge.into());
        state.waker.take()
    }) {
        waker.wake();
    }
}

/// Build the bridge object based on the registered remote methods.
fn update_wasm_bridge(brp_sender: Res<BrpSender>, remote_methods: Res<RemoteMethods>) {
    let main = BrpApp(
        remote_methods
            .methods()
            .into_iter()
            .filter_map(|name| remote_methods.get(&name).map(|id| (name, id)))
            .map(|(method_name, method_id)| {
                let function = build_function(&brp_sender, method_name.to_owned(), *method_id);
                (method_name, function)
            })
            .collect(),
    );

    publish_bridge(BrpBridge { main });
}

fn build_function(
    sender: &Sender<BrpMessage>,
    method_name: String,
    remote_method_system_id: RemoteMethodSystemId,
) -> Closure<WasmBridgeMethod> {
    let sender = sender.clone();
    Closure::<WasmBridgeMethod>::new(
        move |js_params: Option<JsValue>, callback: Option<js_sys::Function>| -> js_sys::Promise {
            let sender = sender.clone();
            let method = method_name.clone();
            future_to_promise(async move {
                match remote_method_system_id {
                    RemoteMethodSystemId::Instant(_) => {
                        build_instant_function(sender, method, js_params, callback).await
                    }
                    RemoteMethodSystemId::Watching(_) => {
                        build_watching_function(sender, method, js_params, callback).await
                    }
                }
            })
        },
    )
}

async fn build_instant_function(
    sender: Sender<BrpMessage>,
    method: String,
    js_params: Option<JsValue>,
    callback: Option<js_sys::Function>,
) -> Result<JsValue, JsValue> {
    let (result_tx, result_rx) = async_channel::bounded(1);

    let params = params_from_js(js_params);

    sender
        .send(BrpMessage {
            method,
            params,
            sender: result_tx,
        })
        .await
        .map_err(|e| js_sys::Error::new(&format!("Failed to send request: {e}")))?;

    let result = result_rx
        .recv()
        .await
        .map_err(|_| js_sys::Error::new("Channel closed unexpectedly"))?;
    let js_result = result_to_js(result)?;

    if let Some(callback) = callback {
        // If a callback was provided, call it with the result and resolve to undefined.
        callback.call1(&JsValue::NULL, &js_result)?;
        Ok(JsValue::UNDEFINED)
    } else {
        // If no callback, resolve the promise to the result value.
        Ok(js_result)
    }
}

async fn build_watching_function(
    sender: Sender<BrpMessage>,
    method: String,
    js_params: Option<JsValue>,
    callback: Option<js_sys::Function>,
) -> Result<JsValue, JsValue> {
    let (result_tx, result_rx) = async_channel::bounded::<BrpResult>(8);
    // A separate receiver handle for the closer to close the channel.
    let closer_rx = result_rx.clone();

    let params = params_from_js(js_params);

    sender
        .send(BrpMessage {
            method,
            params,
            sender: result_tx,
        })
        .await
        .map_err(|e| js_sys::Error::new(&format!("Failed to send request: {e}")))?;

    // Spawn the receive loop if a callback was provided.
    if let Some(callback) = callback {
        spawn_local(async move {
            while let Ok(result) = result_rx.recv().await {
                // The error is treated as a regular result to be passed to the callback.
                let arg = result_to_js(result).unwrap_or_else(std::convert::identity);
                let _ = callback.call1(&JsValue::NULL, &arg);
            }
        });
    }

    let closer = Closure::<WasmBridgeWatchCloser>::new(move || {
        // Closing the Receiver terminates the callback loop above and causes Bevy Remote to stop sending updates.
        closer_rx.close();
    });

    Ok(closer.into_js_value())
}

impl From<BrpApp> for js_sys::Object {
    fn from(app: BrpApp) -> Self {
        let object = js_sys::Object::new();

        for (method_name, function) in app.0 {
            js_sys::Reflect::set(&object, &JsValue::from_str(&method_name), &function.into_js_value()).unwrap_or(false);
        }

        object
    }
}

impl From<BrpBridge> for js_sys::Object {
    fn from(bridge: BrpBridge) -> Self {
        let object = js_sys::Object::new();
        let main = js_sys::Object::from(bridge.main);
        js_sys::Reflect::set(&object, &JsValue::from_str("main"), &main).unwrap_or(false);
        object
    }
}

fn params_from_js(params: Option<JsValue>) -> Option<Value> {
    serde_wasm_bindgen::from_value(params?).ok()
}

fn result_to_js(result: BrpResult) -> Result<JsValue, JsValue> {
    result
        .map(|value| {
            let serializer = serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true);
            value.serialize(&serializer).unwrap_or(JsValue::UNDEFINED)
        })
        .map_err(|err| {
            let msg = format!("[{}] {}", err.code, err.message);
            js_sys::Error::new(&msg).into()
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::prelude::*;
    use bevy_remote::RemotePlugin;
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test(async)]
    async fn get_bridge_with_default_methods() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        app.add_plugins((RemotePlugin::default(), RemoteWasmPlugin));
        app.update();

        let bridge = get_bridge().await;
        assert_eq!(js_sys::Object::keys(&bridge).length(), 1);

        let main = js_sys::Reflect::get(&bridge, &JsValue::from_str("main")).unwrap();
        let main = main.dyn_into::<js_sys::Object>().unwrap();

        // There are more than 10 default remote methods, actual number doesn't matter.
        assert!(js_sys::Object::keys(&main).length() > 10);

        let method = js_sys::Reflect::get(&main, &JsValue::from_str("rpc.discover")).unwrap();
        let method = method.dyn_into::<js_sys::Function>().unwrap();
        let promise = method
            .call0(&JsValue::NULL)
            .unwrap()
            .dyn_into::<js_sys::Promise>()
            .unwrap();

        let result = wasm_bindgen_futures::JsFuture::from(promise).await.unwrap();
        let info = js_sys::Reflect::get(&result, &JsValue::from_str("info")).unwrap();
        let version = js_sys::Reflect::get(&info, &JsValue::from_str("version")).unwrap();
        assert!(
            !version.is_undefined(),
            "Expected version to be present, got {:?}",
            version
        );
    }

    #[wasm_bindgen_test(async)]
    async fn get_bridge_without_methods() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        app.add_plugins((RemotePlugin::default(), RemoteWasmPlugin));
        app.insert_resource(RemoteMethods::new()); // Remove the default remote methods.
        app.update();

        let bridge = get_bridge().await;
        assert_eq!(js_sys::Object::keys(&bridge).length(), 1);

        let main = js_sys::Reflect::get(&bridge, &JsValue::from_str("main")).unwrap();
        let main = main.dyn_into::<js_sys::Object>().unwrap();

        assert_eq!(js_sys::Object::keys(&main).length(), 0);
    }

    #[wasm_bindgen_test(async)]
    async fn get_bridge_with_updated_methods() {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        app.add_plugins((RemotePlugin::default(), RemoteWasmPlugin));
        app.update();

        let default_bridge = get_bridge().await;
        let default_main = js_sys::Reflect::get(&default_bridge, &JsValue::from_str("main")).unwrap();
        let default_main = default_main.dyn_into::<js_sys::Object>().unwrap();

        let mut updated_methods = RemoteMethods::new();
        let my_handler = |In(_params): In<Option<Value>>| -> BrpResult { Ok(Value::Null) };
        let my_handler_id = app.register_system(my_handler);
        updated_methods.insert("my_method", RemoteMethodSystemId::Instant(my_handler_id));
        app.insert_resource(updated_methods);
        app.update();

        let updated_bridge = get_bridge().await;
        let updated_main = js_sys::Reflect::get(&updated_bridge, &JsValue::from_str("main")).unwrap();
        let updated_main = updated_main.dyn_into::<js_sys::Object>().unwrap();

        // Default bridge object is still valid and has the default remote methods.
        assert_eq!(js_sys::Object::keys(&default_bridge).length(), 1);
        assert!(js_sys::Object::keys(&default_main).length() > 10);
        // Updated bridge should only have "my_method".
        assert_eq!(js_sys::Object::keys(&updated_bridge).length(), 1);
        assert_eq!(js_sys::Object::keys(&updated_main).length(), 1);
        assert!(js_sys::Reflect::has(&updated_main, &JsValue::from_str("my_method")).unwrap());
    }
}