nodejs/stdlib/
stream_web.rs1use crate::host::{invoke, with_host, JsObj};
19use fusevm::Value;
20
21pub 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
43pub const METHODS: &[&str] = &[];
45
46pub fn is_class(name: &str) -> bool {
48 CLASSES.contains(&name)
49}
50
51pub 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
61fn 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
79pub 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
88fn internal(name: &str) -> Result<Value, String> {
90 crate::builtins::get_property(&port()?, name)
91}
92
93fn 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
105pub fn is_readable_stream(v: &Value) -> Result<bool, String> {
107 brand("isReadableStream", v)
108}
109
110pub fn is_writable_stream(v: &Value) -> Result<bool, String> {
112 brand("isWritableStream", v)
113}
114
115pub fn readable_stream_cancel(args: &[Value]) -> Result<Value, String> {
118 let f = internal("readableStreamCancel")?;
119 invoke(&f, args.to_vec(), None)
120}