Skip to main content

nodejs/stdlib/
stream_web.rs

1//! Node `stream/web` module: the WHATWG Streams API.
2//!
3//! The implementation is `webstreams.js`, a port of node v26.12.1's
4//! `lib/internal/webstreams/` (its files unchanged, behind a prelude that
5//! supplies the `primordials` and internals they import). It is evaluated
6//! once, on the first read of any stream class, and every class — the
7//! `stream/web` member and the global — is the port's constructor, so streams
8//! are ordinary script objects: the spec's promise-driven `start`/`pull`/
9//! `cancel`, backpressure through `highWaterMark`/`desiredSize`, byte streams
10//! with BYOB readers and `byobRequest`, `tee`, and `pipeTo`/`pipeThrough`
11//! with `signal`/`preventClose`/`preventAbort`/`preventCancel` are node's
12//! code.
13//!
14//! This replaced a native reimplementation that ran `pull` synchronously
15//! (a `pull` that returned a promise was not awaited), had no byte streams,
16//! and drained `pipeTo`/`tee` eagerly.
17
18use crate::host::{invoke, with_host, JsObj};
19use fusevm::Value;
20
21/// The members of `require('stream/web')`, in node's order (`lib/stream/web.js`).
22pub const CLASSES: &[&str] = &[
23    "ReadableStream",
24    "ReadableStreamTee",
25    "ReadableStreamDefaultReader",
26    "ReadableStreamBYOBReader",
27    "ReadableStreamBYOBRequest",
28    "ReadableByteStreamController",
29    "ReadableStreamDefaultController",
30    "TransformStream",
31    "TransformStreamDefaultController",
32    "WritableStream",
33    "WritableStreamDefaultWriter",
34    "WritableStreamDefaultController",
35    "ByteLengthQueuingStrategy",
36    "CountQueuingStrategy",
37    "TextEncoderStream",
38    "TextDecoderStream",
39    "CompressionStream",
40    "DecompressionStream",
41];
42
43/// `stream/web` exports no free functions that dispatch natively.
44pub const METHODS: &[&str] = &[];
45
46/// True if `name` is a member of `require('stream/web')`.
47pub fn is_class(name: &str) -> bool {
48    CLASSES.contains(&name)
49}
50
51/// True if `name` is one of the stream classes node also binds as a global —
52/// every member except `ReadableStreamTee`, which is a function.
53pub fn is_global_class(name: &str) -> bool {
54    name != "ReadableStreamTee" && is_class(name)
55}
56
57thread_local! {
58    static PORT: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
59}
60
61/// The evaluated port: `{ web, isReadableStream, isWritableStream,
62/// readableStreamCancel }`.
63fn port() -> Result<Value, String> {
64    if let Some(p) = PORT.with(|p| p.borrow().clone()) {
65        return Ok(p);
66    }
67    let factory = crate::eval_internal(include_str!("webstreams.js"))?;
68    let (node_error, promise_state) = with_host(|h| {
69        (
70            h.alloc(JsObj::Builtin("util.@@nodeError".into())),
71            h.alloc(JsObj::Builtin("util.@@promiseState".into())),
72        )
73    });
74    let made = invoke(&factory, vec![node_error, promise_state], None)?;
75    PORT.with(|p| *p.borrow_mut() = Some(made.clone()));
76    Ok(made)
77}
78
79/// `require('stream/web').<name>` (and the global of the same name).
80pub fn constant(name: &str) -> Option<Value> {
81    if !is_class(name) {
82        return None;
83    }
84    let web = crate::builtins::get_property(&port().ok()?, "web").ok()?;
85    crate::builtins::get_property(&web, name).ok()
86}
87
88/// One of the port's internals, by name.
89fn internal(name: &str) -> Result<Value, String> {
90    crate::builtins::get_property(&port()?, name)
91}
92
93/// The port's brand check `isReadableStream(v)` / `isWritableStream(v)`. No
94/// stream exists before the port is first evaluated, so an unloaded port
95/// answers `false` without loading it.
96fn brand(check: &str, v: &Value) -> Result<bool, String> {
97    if PORT.with(|p| p.borrow().is_none()) {
98        return Ok(false);
99    }
100    let f = internal(check)?;
101    let r = invoke(&f, vec![v.clone()], None)?;
102    Ok(with_host(|h| h.truthy(&r)))
103}
104
105/// node's `isReadableStream`.
106pub fn is_readable_stream(v: &Value) -> Result<bool, String> {
107    brand("isReadableStream", v)
108}
109
110/// node's `isWritableStream`.
111pub fn is_writable_stream(v: &Value) -> Result<bool, String> {
112    brand("isWritableStream", v)
113}
114
115/// node's `readableStreamCancel(stream, reason)`: cancel without the lock
116/// check `ReadableStream.prototype.cancel` makes.
117pub fn readable_stream_cancel(args: &[Value]) -> Result<Value, String> {
118    let f = internal("readableStreamCancel")?;
119    invoke(&f, args.to_vec(), None)
120}