js-sys 0.3.105

Bindings for all JS global objects and functions in all JS environments like Node.js and browsers, built on `#[wasm_bindgen]` using the `wasm-bindgen` crate.
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
//! Converting between JavaScript `Promise`s to Rust `Future`s.
//!
//! This module provides a bridge for working with JavaScript `Promise` types as
//! a Rust `Future`, and similarly contains utilities to turn a rust `Future`
//! into a JavaScript `Promise`. This can be useful when working with
//! asynchronous or otherwise blocking work in Rust (wasm), and provides the
//! ability to interoperate with JavaScript events and JavaScript I/O
//! primitives.
//!
//! There are three main interfaces in this module currently:
//!
//! 1. [**`JsFuture`**](./struct.JsFuture.html)
//!
//!    A type that is constructed with a `Promise` and can then be used as a
//!    `Future<Output = Result<JsValue, JsValue>>`. This Rust future will resolve
//!    or reject with the value coming out of the `Promise`.
//!
//! 2. [**`future_to_promise`**](./fn.future_to_promise.html)
//!
//!    Converts a Rust `Future<Output = Result<JsValue, JsValue>>` into a
//!    JavaScript `Promise`. The future's result will translate to either a
//!    resolved or rejected `Promise` in JavaScript.
//!
//! 3. [**`spawn_local`**](./fn.spawn_local.html)
//!
//!    Spawns a `Future<Output = ()>` on the current thread. This is the
//!    best way to run a `Future` in Rust without sending it to JavaScript.
//!
//! These three items should provide enough of a bridge to interoperate the two
//! systems and make sure that Rust/JavaScript can work together with
//! asynchronous and I/O work.

extern crate alloc;

#[cfg(not(target_feature = "atomics"))]
mod jspi;

use crate::Promise;
use alloc::rc::Rc;
use core::cell::RefCell;
use core::fmt;
use core::future::{Future, IntoFuture};
use core::panic::AssertUnwindSafe;
use core::pin::Pin;
use core::task::{Context, Poll, Waker};
#[cfg(all(
    all(target_family = "wasm", not(target_os = "wasi")),
    feature = "std",
    panic = "unwind"
))]
use futures_util::FutureExt;
use wasm_bindgen::__rt::marker::ErasableGeneric;
#[cfg(all(
    all(target_family = "wasm", not(target_os = "wasi")),
    feature = "std",
    panic = "unwind"
))]
use wasm_bindgen::__rt::panic_to_panic_error;
use wasm_bindgen::convert::{FromWasmAbi, Upcast};
use wasm_bindgen::sys::Promising;
use wasm_bindgen::{prelude::*, JsError, JsGeneric};

#[cfg_attr(docsrs, doc(cfg(feature = "futures-core-03-stream")))]
#[cfg(feature = "futures-core-03-stream")]
pub mod stream;

mod queue;

mod task {
    use cfg_if::cfg_if;

    cfg_if! {
        if #[cfg(target_feature = "atomics")] {
            mod wait_async_polyfill;
            mod multithread;
            pub(crate) use multithread::*;

        } else {
            mod singlethread;
            pub(crate) use singlethread::*;
         }
    }
}

/// Runs a Rust `Future` on the current thread.
///
/// The `future` must be `'static` because it will be scheduled
/// to run in the background and cannot contain any stack references.
///
/// The `future` will always be run on the next microtask tick even if it
/// immediately returns `Poll::Ready`.
///
/// # JSPI
///
/// When called from within a JSPI context — a `#[wasm_bindgen(jspi)]` export
/// or a task itself spawned from one — the task's polls are entered through
/// a `WebAssembly.promising` boundary, so sync code reached from the future
/// may suspend via [`jspi_block_on_promise`]. The capability is inherited
/// transitively down the spawn tree; a suspension parks only that task's
/// poll. In modules that never use JSPI attributes this branch compiles to a
/// constant and no JSPI machinery is emitted.
///
/// # Panics
///
/// This function has the same panic behavior as `future_to_promise`.
#[inline]
pub fn spawn_local<F>(future: F)
where
    F: Future<Output = ()> + 'static,
{
    #[cfg(not(target_feature = "atomics"))]
    if jspi::in_context() {
        jspi::spawn_promising(future);
        return;
    }
    task::Task::spawn(future);
}

/// Suspend the current JSPI execution until `promise` settles, returning the
/// resolved value as `Ok` or the rejection reason as `Err` — without
/// blocking the event loop, and without an `async` call chain.
///
/// May only be called where a `WebAssembly.promising` frame is on the stack:
/// within a `#[wasm_bindgen(jspi)]` export, or a task spawned (transitively)
/// from a JSPI context. Calling it elsewhere throws a `SuspendError` at
/// runtime.
///
/// Promises are eager, so concurrency composes at the promise level: start
/// several JS calls, then suspend on each or on a `Promise::all` /
/// `Promise::race` combination. A Rust `Future` is awaited by suspending on
/// its completion promise: `jspi_block_on_promise(&future_to_promise(fut))`.
#[cfg(not(target_feature = "atomics"))]
#[deprecated(note = "JSPI support is experimental and subject to change; \
            `jspi_block_on_promise` requires a runtime with WebAssembly \
            JS Promise Integration enabled")]
pub fn jspi_block_on_promise(promise: &Promise) -> Result<JsValue, JsValue> {
    jspi::suspend(promise)
}

struct Inner<T = JsValue> {
    result: Option<Result<T, JsValue>>,
    task: Option<Waker>,
    callbacks: Option<(
        Closure<dyn FnMut(T) -> Result<(), JsError>>,
        Closure<dyn FnMut(JsValue) -> Result<(), JsError>>,
    )>,
}

/// A Rust `Future` backed by a JavaScript `Promise`.
///
/// This type is constructed with a JavaScript `Promise` object and translates
/// it to a Rust `Future`. This type implements the `Future` trait from the
/// `futures` crate and will either succeed or fail depending on what happens
/// with the JavaScript `Promise`.
///
/// Currently this type is constructed with `JsFuture::from`.
pub struct JsFuture<T = JsValue> {
    inner: Rc<RefCell<Inner<T>>>,
}

impl core::panic::UnwindSafe for JsFuture {}

unsafe impl<T> ErasableGeneric for JsFuture<T> {
    type Repr = JsFuture<JsValue>;
}

// Upcast for JsFuture is covariant in T (the success type)
// JsFuture<T> can upcast to JsFuture<Target> if T: Upcast<Target>
impl<T, Target> Upcast<JsFuture<Target>> for JsFuture<T> where T: Upcast<Target> {}

impl<T> fmt::Debug for JsFuture<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "JsFuture {{ ... }}")
    }
}

// `FromWasmAbi` is what the closure shim invokes on the resolved value;
// no layout equivalence with `JsValue` is required at this seam — the
// per-type `from_abi` does the conversion (e.g. for dynamic unions it
// runs the variant dispatcher).
impl<T: FromWasmAbi + 'static> From<Promise<T>> for JsFuture<T> {
    fn from(js: Promise<T>) -> JsFuture<T> {
        // Use the `then` method to schedule two callbacks, one for the
        // resolved value and one for the rejected value. We're currently
        // assuming that JS engines will unconditionally invoke precisely one of
        // these callbacks, no matter what.
        //
        // Ideally we'd have a way to cancel the callbacks getting invoked and
        // free up state ourselves when this `JsFuture` is dropped. We don't
        // have that, though, and one of the callbacks is likely always going to
        // be invoked.
        //
        // As a result we need to make sure that no matter when the callbacks
        // are invoked they are valid to be called at any time, which means they
        // have to be self-contained. Through the `Closure::once` and some
        // `Rc`-trickery we can arrange for both instances of `Closure`, and the
        // `Rc`, to all be destroyed once the first one is called.
        let state = Rc::new(RefCell::new(Inner::<T> {
            result: None,
            task: None,
            callbacks: None,
        }));

        fn finish<T>(state: &RefCell<Inner<T>>, val: Result<T, JsValue>) {
            let task = {
                let mut state = state.borrow_mut();
                assert!(
                    state.callbacks.is_some(),
                    "finish: callbacks should be Some"
                );
                assert!(state.result.is_none(), "finish: result should be None");

                // First up drop our closures as they'll never be invoked again and
                // this is our chance to clean up their state.
                drop(state.callbacks.take());

                // Next, store the value into the internal state.
                state.result = Some(val);
                state.task.take()
            };

            // And then finally if any task was waiting on the value wake it up and
            // let them know it's there.
            if let Some(task) = task {
                task.wake()
            }
        }

        let resolve = {
            let state = AssertUnwindSafe(state.clone());
            Closure::once(move |val: T| {
                finish(&*state, Ok(val));
                Ok(())
            })
        };

        let reject = {
            let state = AssertUnwindSafe(state.clone());
            Closure::once(move |val| {
                finish(&*state, Err(val));
                Ok(())
            })
        };

        let _ = js.then_with_reject(&resolve, &reject);

        state.borrow_mut().callbacks = Some((resolve, reject));

        JsFuture { inner: state }
    }
}

impl<T> Future for JsFuture<T> {
    type Output = Result<T, JsValue>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let mut inner = self.inner.borrow_mut();

        // If our value has come in then we return it...
        if let Some(val) = inner.result.take() {
            return Poll::Ready(val);
        }

        // ... otherwise we arrange ourselves to get woken up once the value
        // does come in
        inner.task = Some(cx.waker().clone());
        Poll::Pending
    }
}

impl<T: FromWasmAbi + 'static> IntoFuture for Promise<T> {
    type Output = Result<T, JsValue>;
    type IntoFuture = JsFuture<T>;

    fn into_future(self) -> JsFuture<T> {
        JsFuture::from(self)
    }
}

/// Converts a Rust `Future` into a JavaScript `Promise`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future
/// completes, depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// Note that in Wasm panics are currently translated to aborts, but "abort" in
/// this case means that a JavaScript exception is thrown. The Wasm module is
/// still usable (likely erroneously) after Rust panics.
#[cfg(not(all(
    all(target_family = "wasm", not(target_os = "wasi")),
    feature = "std",
    panic = "unwind"
)))]
pub fn future_to_promise<F>(future: F) -> Promise
where
    F: Future<Output = Result<JsValue, JsValue>> + 'static,
{
    let mut future = Some(future);

    Promise::new_typed(&mut move |resolve, reject| {
        let future = future.take().unwrap_throw();

        spawn_local(async move {
            match future.await {
                Ok(val) => {
                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
                Err(val) => {
                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
            }
        });
    })
}

/// Converts a Rust `Future` into a JavaScript `Promise`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future
/// completes, depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// If the `future` provided panics then the returned `Promise` will be rejected
/// with a PanicError.
#[cfg(all(
    all(target_family = "wasm", not(target_os = "wasi")),
    feature = "std",
    panic = "unwind"
))]
pub fn future_to_promise<F>(future: F) -> Promise
where
    F: Future<Output = Result<JsValue, JsValue>> + 'static + std::panic::UnwindSafe,
{
    // Wrap `future` in AssertUnwindSafe and move it into the closure so the closure
    // satisfies MaybeUnwindSafe (required when panic=unwind). Using `move` avoids
    // capturing a `&mut` reference, which is never UnwindSafe. The Promise executor
    // is not called inside a panic-catching context, so this is always safe.
    let mut future = core::panic::AssertUnwindSafe(Some(future));
    Promise::new(&mut move |resolve, reject| {
        let future = future.take().unwrap_throw();
        spawn_local(async move {
            let res = future.catch_unwind().await;
            match res {
                Ok(Ok(val)) => {
                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
                Ok(Err(val)) => {
                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
                Err(val) => {
                    reject
                        .call(&JsValue::UNDEFINED, (&panic_to_panic_error(val),))
                        .unwrap_throw();
                }
            }
        });
    })
}

// Note: Once we bump MSRV, we can type future_to_promise with backwards compatible inference.
/// Converts a Rust `Future` into a corresponding typed JavaScript `Promise<T>`.
///
/// This function will take any future in Rust and schedule it to be executed,
/// returning a JavaScript `Promise` which can then be passed to JavaScript.
///
/// The `future` must be `'static` because it will be scheduled to run in the
/// background and cannot contain any stack references.
///
/// The returned `Promise` will be resolved or rejected when the future completes,
/// depending on whether it finishes with `Ok` or `Err`.
///
/// # Panics
///
/// Note that in Wasm panics are currently translated to aborts, but "abort" in
/// this case means that a JavaScript exception is thrown. The Wasm module is
/// still usable (likely erroneously) after Rust panics.
///
/// If the `future` provided panics then the returned `Promise` **will not
/// resolve**. Instead it will be a leaked promise. This is an unfortunate
/// limitation of Wasm currently that's hoped to be fixed one day!
pub fn future_to_promise_typed<T, F>(future: F) -> Promise<<T as Promising>::Resolution>
where
    F: Future<Output = Result<T, JsValue>> + 'static,
    T: Promising + FromWasmAbi + JsGeneric,
    <T as Promising>::Resolution: JsGeneric,
{
    let mut future = Some(future);

    Promise::new_typed(&mut move |resolve, reject| {
        let future = future.take().unwrap_throw();
        spawn_local(async move {
            match future.await {
                Ok(val) => {
                    resolve.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
                Err(val) => {
                    reject.call(&JsValue::UNDEFINED, (&val,)).unwrap_throw();
                }
            }
        });
    })
}