Skip to main content

nodejs/stdlib/
process.rs

1//! Node `process` global — the subset packages read at load time.
2//!
3//! Data properties (`process.env`, `process.argv`, `process.platform`, the
4//! `stdout`/`stderr` stream stand-ins, …) are served through `constant`;
5//! callable members (`process.cwd()`, `process.hrtime()`, the EventEmitter-style
6//! `on`/`emit` no-ops, …) through `call`. `process.nextTick` is intentionally NOT
7//! handled here — it stays on the core microtask path in `builtins.rs`.
8
9use crate::host::{with_host, JsObj};
10use fusevm::Value;
11use indexmap::IndexMap;
12
13/// Callable members. `nextTick` is deliberately absent (handled in `builtins`).
14/// The node release this runtime reports itself as: `process.version`,
15/// `process.versions.node`, and the `Node.js <version>` line that ends a
16/// fatal-exception report.
17pub const NODE_VERSION: &str = "v26.5.0";
18
19pub const METHODS: &[&str] = &[
20    "cwd",
21    "chdir",
22    "exit",
23    "hrtime",
24    // `process.hrtime.bigint()` is a real member, not just a property that
25    // answers `typeof "function"`. It resolves as the qualified builtin
26    // `process.hrtime.bigint` (`namespace_property` composes `ns` + `name`),
27    // so it has to be declared here for `is_method` to route the call.
28    "hrtime.bigint",
29    "uptime",
30    "memoryUsage",
31    "cpuUsage",
32    "umask",
33    "binding",
34    "emit",
35    "on",
36    "once",
37    "off",
38    "addListener",
39    "removeListener",
40    "removeAllListeners",
41    "listeners",
42    "emitWarning",
43    "kill",
44    "getuid",
45    "getgid",
46    "geteuid",
47    "getegid",
48    "getgroups",
49    "setuid",
50    "setgid",
51    "seteuid",
52    "setegid",
53    "setgroups",
54    "initgroups",
55    "ref",
56    "unref",
57    "abort",
58    "getActiveResourcesInfo",
59    "resourceUsage",
60    "threadCpuUsage",
61    "availableMemory",
62    "constrainedMemory",
63    "getBuiltinModule",
64    "openStdin",
65    "hasUncaughtExceptionCaptureCallback",
66    "setUncaughtExceptionCaptureCallback",
67    "addUncaughtExceptionCaptureCallback",
68    "execve",
69    "reallyExit",
70    "loadEnvFile",
71    "setSourceMapsEnabled",
72];
73
74thread_local! {
75    /// The single `process.setUncaughtExceptionCaptureCallback` slot. Stored as a
76    /// heap handle (thread-local like the JS heap); read by
77    /// `hasUncaughtExceptionCaptureCallback`.
78    static UNCAUGHT_CAPTURE: std::cell::RefCell<Option<Value>> =
79        const { std::cell::RefCell::new(None) };
80}
81
82/// Whether the one-shot "(Use `node --trace-… ...`)" hint has been printed.
83/// Node prints it after the FIRST warning only, per process.
84static TRACE_HINT_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
85
86/// Port of `internal/process/warning.js` `emitWarning`: the warning is
87/// delivered on the NEXT TICK, not inline — first node's default `onWarning`
88/// printer, then every `process.on('warning')` listener with the warning
89/// `Error` (`name`, `message`, and `code`/`detail` when given). It used to
90/// print synchronously, ahead of output the script wrote after the call, and
91/// the `warning` event never fired. `--no-warnings` (and `--no-deprecation`
92/// for deprecations) silences only the printer, as in node.
93pub fn emit_warning(name: &str, code: Option<&str>, message: &str, detail: Option<&str>) {
94    queue_warning(name, code, message, detail, None);
95}
96
97/// [`emit_warning`], handing the listeners `obj` when the caller passed its own
98/// `Error` (`process.emitWarning(err)`) rather than a fresh one.
99fn queue_warning(
100    name: &str,
101    code: Option<&str>,
102    message: &str,
103    detail: Option<&str>,
104    obj: Option<Value>,
105) {
106    let argv: Vec<String> = std::env::args().collect();
107    let flag = |f: &str| argv.iter().any(|a| a == f);
108    let is_deprecation = name == "DeprecationWarning";
109    let printed = !(flag("--no-warnings") || (is_deprecation && flag("--no-deprecation")));
110    let text = printed.then(|| warning_text(name, code, message, detail, &flag));
111    let (name, code, message, detail) = (
112        name.to_string(),
113        code.map(str::to_string),
114        message.to_string(),
115        detail.map(str::to_string),
116    );
117    with_host(|h| {
118        let frame = h.async_frame.clone();
119        h.nextticks.push_back(crate::host::Task::Native(
120            Box::new(move || {
121                if let Some(text) = text {
122                    eprintln!("{text}");
123                }
124                let listeners = with_host(|h| h.take_process_listeners("warning"));
125                if listeners.is_empty() {
126                    return Ok(());
127                }
128                if let Some(w) = obj {
129                    for f in listeners {
130                        crate::host::invoke(&f, vec![w.clone()], None)?;
131                    }
132                    return Ok(());
133                }
134                let msg = with_host(|h| h.new_str(message));
135                let w = crate::builtins::call_builtin_function("Error", vec![msg])?;
136                let field = |k: &str, v: &str| {
137                    let v = with_host(|h| h.new_str(v.to_string()));
138                    crate::builtins::set_property_pub(&w, k, v)
139                };
140                field("name", &name)?;
141                if let Some(c) = &code {
142                    field("code", c)?;
143                }
144                if let Some(d) = &detail {
145                    field("detail", d)?;
146                }
147                for f in listeners {
148                    crate::host::invoke(&f, vec![w.clone()], None)?;
149                }
150                Ok(())
151            }),
152            frame,
153        ));
154    });
155}
156
157/// The stderr rendering of a warning: `(node:PID) [CODE] Name: message`, an
158/// optional detail line, and the one-time trace hint.
159fn warning_text(
160    name: &str,
161    code: Option<&str>,
162    message: &str,
163    detail: Option<&str>,
164    flag: &dyn Fn(&str) -> bool,
165) -> String {
166    let is_deprecation = name == "DeprecationWarning";
167    let trace = flag("--trace-warnings") || (is_deprecation && flag("--trace-deprecation"));
168
169    let mut msg = std::format!("(node:{}) ", std::process::id());
170    if let Some(c) = code {
171        msg.push_str(&std::format!("[{c}] "));
172    }
173    msg.push_str(&std::format!("{name}: {message}"));
174    if let Some(d) = detail {
175        msg.push_str(&std::format!("\n{d}"));
176    }
177    if !trace && !TRACE_HINT_SHOWN.swap(true, std::sync::atomic::Ordering::Relaxed) {
178        let trace_flag = if is_deprecation {
179            "--trace-deprecation"
180        } else {
181            "--trace-warnings"
182        };
183        msg.push_str(&std::format!(
184            "\n(Use `node {trace_flag} ...` to show where the warning was created)"
185        ));
186    }
187    msg
188}
189
190/// A `DeprecationWarning` fires at most once per `code` per process, matching
191/// the `warned` latches Node keeps at each deprecation site.
192pub fn emit_deprecation_warning(code: &str, message: &str) {
193    use std::cell::RefCell;
194    thread_local! {
195        static SEEN: RefCell<std::collections::HashSet<String>> =
196            RefCell::new(std::collections::HashSet::new());
197    }
198    let first = SEEN.with(|s| s.borrow_mut().insert(code.to_string()));
199    if first {
200        emit_warning("DeprecationWarning", Some(code), message, None);
201    }
202}
203
204/// A signal NAME (`"SIGKILL"`, case-insensitive) to its number, or `None` if the
205/// name is not one this platform defines.
206///
207/// The numbers come from `libc`, not from a hand-written table: signal numbering
208/// differs between macOS and Linux above SIGTERM (`SIGUSR1` is 30 on Darwin and
209/// 10 on Linux), so a literal table is only correct on the platform it was
210/// written for. Shared with `cluster`'s `worker.kill`.
211pub fn signal_number(name: &str) -> Option<libc::c_int> {
212    Some(match name.to_uppercase().as_str() {
213        "SIGHUP" => libc::SIGHUP,
214        "SIGINT" => libc::SIGINT,
215        "SIGQUIT" => libc::SIGQUIT,
216        "SIGILL" => libc::SIGILL,
217        "SIGTRAP" => libc::SIGTRAP,
218        "SIGABRT" => libc::SIGABRT,
219        "SIGBUS" => libc::SIGBUS,
220        "SIGFPE" => libc::SIGFPE,
221        "SIGKILL" => libc::SIGKILL,
222        "SIGUSR1" => libc::SIGUSR1,
223        "SIGSEGV" => libc::SIGSEGV,
224        "SIGUSR2" => libc::SIGUSR2,
225        "SIGPIPE" => libc::SIGPIPE,
226        "SIGALRM" => libc::SIGALRM,
227        "SIGTERM" => libc::SIGTERM,
228        "SIGCHLD" => libc::SIGCHLD,
229        "SIGCONT" => libc::SIGCONT,
230        "SIGSTOP" => libc::SIGSTOP,
231        "SIGTSTP" => libc::SIGTSTP,
232        "SIGWINCH" => libc::SIGWINCH,
233        _ => return None,
234    })
235}
236
237/// `process.emitWarning(warning[, options])` / `(warning[, type[, code]])`.
238fn emit_warning_args(args: &[Value]) -> Result<(), String> {
239    let warning = args.first().cloned().unwrap_or(Value::Undef);
240    // An `Error` is the warning itself: its own `name`/`message` render it and
241    // listeners receive that same object. It was stringified into the message
242    // of a fresh `Warning`, printing `Warning: Error: boom`.
243    if with_host(|h| h.as_str(&warning)).is_none() {
244        let error_ctor = with_host(|h| h.alloc(JsObj::Builtin("Error".into())));
245        let is_error = with_host(|h| matches!(h.type_of(&warning), "object" | "function"))
246            && crate::host::instance_of(&warning, &error_ctor)?;
247        if !is_error {
248            return Err(crate::host::coded_error(
249                "TypeError",
250                "ERR_INVALID_ARG_TYPE",
251                &format!(
252                    "The \"warning\" argument must be of type string or an instance of Error. Received {}",
253                    super::received_desc(&warning)
254                ),
255            ));
256        }
257        let text = |k: &str| -> Result<Option<String>, String> {
258            let v = crate::builtins::get_property(&warning, k)?;
259            Ok((!with_host(|h| h.is_nullish(&v))).then(|| with_host(|h| h.str_of(&v))))
260        };
261        let name = text("name")?.unwrap_or_else(|| "Error".into());
262        let message = text("message")?.unwrap_or_default();
263        let (code, detail) = (text("code")?, text("detail")?);
264        queue_warning(
265            &name,
266            code.as_deref(),
267            &message,
268            detail.as_deref(),
269            Some(warning),
270        );
271        return Ok(());
272    }
273    let message = super::arg_str(args, 0);
274    let mut name = "Warning".to_string();
275    let mut code: Option<String> = None;
276    let mut detail: Option<String> = None;
277    match args.get(1) {
278        Some(v) if with_host(|h| matches!(h.get(v), Some(JsObj::Object(_)))) => {
279            let field = |k: &str| {
280                with_host(|h| match h.get(v) {
281                    Some(JsObj::Object(p)) => {
282                        p.get(k).filter(|x| !h.is_nullish(x)).map(|x| h.str_of(x))
283                    }
284                    _ => None,
285                })
286            };
287            if let Some(t) = field("type") {
288                name = t;
289            }
290            code = field("code");
291            detail = field("detail");
292        }
293        Some(_) => {
294            name = super::arg_str(args, 1);
295            code = args.get(2).map(|_| super::arg_str(args, 2));
296        }
297        None => {}
298    }
299    emit_warning(&name, code.as_deref(), &message, detail.as_deref());
300    Ok(())
301}
302
303/// Data properties, served through `namespace_property` → `stdlib::constant`.
304/// Memoize an OBJECT-valued `process` property for the host's lifetime.
305///
306/// `process.env`, `process.argv` and the std streams were rebuilt on every read,
307/// so `process.env === process.env` was `false` and — much worse —
308/// `process.env.NODE_ENV = "production"` wrote to a throwaway object and read
309/// back `undefined`. Node hands out one object per property, and packages both
310/// mutate it and compare it by identity.
311///
312/// `builtin_static` is the existing side table for exactly this: state that must
313/// survive the fresh `Builtin` handle each `process` reference allocates. It is
314/// per-host, so `reset_host` clears it and a stale handle cannot outlive its heap.
315fn memo(name: &str, make: impl FnOnce() -> Value) -> Value {
316    if let Some(v) = with_host(|h| h.builtin_static("process", name)) {
317        return v;
318    }
319    let v = make();
320    with_host(|h| h.set_builtin_static("process", name, v.clone()));
321    v
322}
323
324/// `process.features` — what this runtime can do.
325fn features() -> Value {
326    with_host(|h| {
327        let mut m = IndexMap::new();
328        for (k, v) in [
329            ("inspector", false),
330            ("debug", false),
331            ("uv", false),
332            ("ipv6", true),
333            ("tls_alpn", false),
334            ("tls_sni", false),
335            ("tls_ocsp", false),
336            ("tls", true),
337            ("openssl_is_boringssl", false),
338            ("cached_builtins", true),
339            ("require_module", true),
340            ("quic", false),
341        ] {
342            m.insert(k.to_string(), Value::Bool(v));
343        }
344        // A string, not a boolean, in node too: it names the TypeScript mode.
345        let ts = h.new_str("none");
346        m.insert("typescript".into(), ts);
347        h.new_object(m)
348    })
349}
350
351/// `process.config`.
352fn config() -> Value {
353    with_host(|h| {
354        let mut vars = IndexMap::new();
355        let arch = h.new_str(super::os::arch());
356        let plat = h.new_str(super::os::platform());
357        vars.insert("host_arch".to_string(), arch.clone());
358        vars.insert("target_arch".to_string(), arch);
359        vars.insert("node_shared".to_string(), Value::Bool(false));
360        vars.insert("node_use_openssl".to_string(), Value::Bool(false));
361        vars.insert("v8_enable_i18n_support".to_string(), Value::Bool(false));
362        vars.insert("node_platform".to_string(), plat);
363        let variables = h.new_object(vars);
364        let defaults = h.new_object(IndexMap::new());
365        let mut m = IndexMap::new();
366        m.insert("target_defaults".to_string(), defaults);
367        m.insert("variables".to_string(), variables);
368        h.new_object(m)
369    })
370}
371
372/// The `NODE_OPTIONS` flags this runtime accepts, as a `Set`.
373fn allowed_flags() -> Value {
374    let flags = [
375        "--enable-source-maps",
376        "--max-old-space-size",
377        "--no-warnings",
378        "--preserve-symlinks",
379        "--stack-trace-limit",
380        "--throw-deprecation",
381        "--trace-warnings",
382        "--unhandled-rejections",
383        "--zero-fill-buffers",
384    ];
385    let vals: Vec<Value> = flags.iter().map(|f| with_host(|h| h.new_str(*f))).collect();
386    let set = with_host(|h| {
387        h.alloc(crate::host::JsObj::Set {
388            entries: indexmap::IndexMap::new(),
389            weak: false,
390        })
391    });
392    for v in vals {
393        let _ = crate::host::call_method(&set, "add", vec![v]);
394    }
395    set
396}
397
398pub fn constant(name: &str) -> Option<Value> {
399    Some(match name {
400        "env" => memo("env", env_object),
401        // `process.release` carried nothing, so the common
402        // `process.release.name === 'node'` probe threw on `undefined.name`.
403        // Only `name` is reported: it is consistent with the node version this
404        // already claims through `process.version`, whereas the `sourceUrl` and
405        // `headersUrl` node also carries would point at a release tarball that
406        // does not exist for this engine.
407        "release" => memo("release", || {
408            with_host(|h| {
409                let mut m = IndexMap::new();
410                let name = h.new_str("node");
411                m.insert("name".into(), name);
412                h.new_object(m)
413            })
414        }),
415        "argv" => memo("argv", argv),
416        "argv0" => with_host(|h| h.new_str(exec_path())),
417        "execPath" => with_host(|h| h.new_str(exec_path())),
418        "execArgv" => memo("execArgv", exec_argv),
419        "platform" => with_host(|h| h.new_str(super::os::platform())),
420        "arch" => with_host(|h| h.new_str(super::os::arch())),
421        "pid" => Value::Float(std::process::id() as f64),
422        "ppid" => Value::Float(0.0),
423        "title" => with_host(|h| h.new_str("node")),
424        // A best-effort Node-compatible version string. Kept low so a dep's
425        // `if (semver.lt(process.version, ...))` gate takes the conservative path.
426        "version" => with_host(|h| h.new_str(NODE_VERSION)),
427        "versions" => memo("versions", versions),
428        // A capability map tooling probes before reaching for an optional API.
429        // It reports what THIS runtime supports, not what node's own build
430        // does — claiming a feature that is not here would defeat the point of
431        // the probe. It was absent entirely, so `process.features.X` threw on
432        // `undefined`.
433        "features" => memo("features", features),
434        // Node's shape is `{ target_defaults, variables }`; the contents
435        // describe the build. Only what is true of this build is reported —
436        // there is no configure step to echo.
437        "config" => memo("config", config),
438        // The flags this runtime accepts in `NODE_OPTIONS`, as the Set-like
439        // node exposes. `process.allowedNodeEnvironmentFlags.has(f)` used to
440        // throw: the value was undefined.
441        "allowedNodeEnvironmentFlags" => memo("allowedNodeEnvironmentFlags", allowed_flags),
442        "stdout" => memo("stdout", || std_stream(1)),
443        "stderr" => memo("stderr", || std_stream(2)),
444        "stdin" => memo("stdin", || std_stream(0)),
445        // Unset reads back as `undefined`, not `0` — `process.exitCode` starts
446        // life absent and a script may test for that.
447        "exitCode" => match with_host(|h| h.exit_code) {
448            Some(c) => Value::Float(c as f64),
449            None => Value::Undef,
450        },
451        _ => return None,
452    })
453}
454
455/// The `process.exitCode` setter, ported from Node's
456/// `lib/internal/bootstrap/node.js` accessor:
457///
458/// ```js
459/// set(code) {
460///   if (code !== null && code !== undefined) {
461///     let value = code;
462///     if (typeof code === 'string' && code !== '' &&
463///       NumberIsNaN((value = Number(code)))) {
464///       value = code;
465///     }
466///     validateInteger(value, 'code');
467///     …
468///   } else { /* clear */ }
469/// }
470/// ```
471///
472/// So a NUMERIC string is accepted and coerced (`"3"` → 3, `"0x10"` → 16,
473/// `"  "` → 0), a non-numeric or empty string keeps its string identity and
474/// fails `validateInteger` as a TYPE error, a non-integer number fails as a
475/// RANGE error, and `null`/`undefined` clear the slot. Verified on node
476/// v26.7.0: `process.exitCode = "0x10"` exits 16, `= 3.7` throws
477/// `ERR_OUT_OF_RANGE`, `= ""` throws `ERR_INVALID_ARG_TYPE`, `= "  "` exits 0.
478pub fn set_exit_code(val: &Value) -> Result<(), String> {
479    if matches!(val, Value::Undef) || with_host(|h| h.is_null(val)) {
480        with_host(|h| h.exit_code = None);
481        return Ok(());
482    }
483    // A numeric string coerces; anything else keeps its own type for the error.
484    let numeric = match with_host(|h| h.as_str(val)) {
485        Some(s) if !s.is_empty() => {
486            let n = with_host(|h| h.to_number(val));
487            if n.is_nan() {
488                None
489            } else {
490                Some(n)
491            }
492        }
493        Some(_) => None,
494        None => match val {
495            Value::Float(_) | Value::Int(_) => Some(with_host(|h| h.to_number(val))),
496            _ => None,
497        },
498    };
499    match numeric {
500        Some(n) if n.fract() == 0.0 && n.is_finite() => {
501            with_host(|h| h.exit_code = Some(n as i32));
502            Ok(())
503        }
504        Some(n) => Err(crate::host::coded_error(
505            "RangeError",
506            "ERR_OUT_OF_RANGE",
507            &format!(
508                "The value of \"code\" is out of range. It must be an integer. Received {}",
509                crate::host::fmt_number(n)
510            ),
511        )),
512        None => Err(crate::host::invalid_arg_type(
513            "code", "argument", "number", val,
514        )),
515    }
516}
517
518pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
519    Some(match method {
520        "@@stdinPump" => stdin_pump().map(|_| Value::Undef),
521        "cwd" => {
522            let d = std::env::current_dir()
523                .map(|p| p.to_string_lossy().into_owned())
524                .unwrap_or_default();
525            Ok(with_host(|h| h.new_str(d)))
526        }
527        // `hrtime()` → `[seconds, nanoseconds]` since an arbitrary epoch (here the
528        // monotonic clock via `Instant` is unavailable statically, so use the
529        // system clock — sufficient for the timing scaffolding deps set up).
530        "hrtime" => Ok(hrtime(args)),
531        // Nanoseconds since an arbitrary epoch, as a BigInt.
532        "hrtime.bigint" => Ok(with_host(|h| {
533            let now = std::time::SystemTime::now()
534                .duration_since(std::time::UNIX_EPOCH)
535                .unwrap_or_default();
536            h.new_bigint(num_bigint::BigInt::from(now.as_nanos()))
537        })),
538        "uptime" => Ok(Value::Float(0.0)),
539        "memoryUsage" => Ok(memory_usage()),
540        "cpuUsage" => Ok(with_host(|h| {
541            let mut m = IndexMap::new();
542            m.insert("user".into(), Value::Float(0.0));
543            m.insert("system".into(), Value::Float(0.0));
544            h.new_object(m)
545        })),
546        "umask" => Ok(Value::Float(0.0)),
547        "binding" => Err(crate::host::type_error("process.binding is not supported")),
548        // EventEmitter-style registration. Listeners are REMEMBERED (the runtime
549        // emits `unhandledRejection`; signals still never fire), and every form
550        // returns the process namespace so `.on(...).on(...)` chains work.
551        "on" | "once" | "addListener" => {
552            let (event, f) = (event_name(args), args.get(1).cloned());
553            if let Some(f) = f {
554                let once = method == "once";
555                with_host(|h| {
556                    h.process_listeners
557                        .entry(event)
558                        .or_default()
559                        .push(crate::host::ProcListener { f, once })
560                });
561            }
562            Ok(with_host(|h| h.alloc(JsObj::Builtin("process".into()))))
563        }
564        "off" | "removeListener" => {
565            let (event, f) = (event_name(args), args.get(1).cloned());
566            if let Some(f) = f {
567                with_host(|h| {
568                    if let Some(l) = h.process_listeners.get_mut(&event) {
569                        if let Some(i) = l.iter().position(|x| x.f == f) {
570                            l.remove(i);
571                        }
572                    }
573                });
574            }
575            Ok(with_host(|h| h.alloc(JsObj::Builtin("process".into()))))
576        }
577        "removeAllListeners" => {
578            let event = event_name(args);
579            with_host(|h| {
580                if event.is_empty() {
581                    h.process_listeners.clear();
582                } else {
583                    h.process_listeners.shift_remove(&event);
584                }
585            });
586            Ok(with_host(|h| h.alloc(JsObj::Builtin("process".into()))))
587        }
588        "listeners" => {
589            let event = event_name(args);
590            Ok(with_host(|h| {
591                let l = h
592                    .process_listeners
593                    .get(&event)
594                    .map(|v| v.iter().map(|x| x.f.clone()).collect())
595                    .unwrap_or_default();
596                h.new_array(l)
597            }))
598        }
599        "emit" => {
600            let event = event_name(args);
601            let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
602            let listeners = with_host(|h| h.take_process_listeners(&event));
603            let any = !listeners.is_empty();
604            let mut r = Ok(Value::Bool(any));
605            for f in listeners {
606                if let Err(e) = crate::host::invoke(&f, rest.clone(), None) {
607                    r = Err(e);
608                    break;
609                }
610            }
611            r
612        }
613        "emitWarning" => emit_warning_args(args).map(|_| Value::Undef),
614        // `process.exit([code])` really exits, and does so IMMEDIATELY — nothing
615        // after the call runs. It used to return `undefined` and let execution
616        // continue, which is a silent lie with teeth: the idiom
617        // `if (done) { server.close(); process.exit(0); }` (no `return`, because
618        // in Node none is needed) fell through to the statement after it. In a
619        // request-sequencing loop that meant re-entering the loop past the end of
620        // its array and destructuring `undefined`. Measured on node v26.7.0,
621        // `console.log('before'); process.exit(0); console.log('after')` prints
622        // only `before`; it printed both here.
623        //
624        // Under `--build`/`--dap`/embedding this is still a real process exit,
625        // exactly as it is in Node — there is no "exit but keep going" in the API.
626        // stdout/stderr are flushed first because `std::process::exit` runs no
627        // destructors.
628        //
629        // Port of Node's `process.exit`: an argument (even `undefined`) is
630        // ASSIGNED to `process.exitCode` first — through the validating setter,
631        // so `process.exit(3.7)` throws instead of exiting — then the `exit`
632        // event fires with the resulting code, then the process leaves. With no
633        // argument the already-set `process.exitCode` decides, which is why
634        // `process.exitCode = 3; process.exit()` exits 3 on node v26.7.0.
635        "exit" | "reallyExit" => {
636            if !args.is_empty() {
637                if let Err(e) = set_exit_code(&args[0]) {
638                    return Some(Err(e));
639                }
640            }
641            let code = with_host(|h| h.exit_code).unwrap_or(0);
642            if let Err(e) = emit_exit_event(code) {
643                return Some(Err(e));
644            }
645            // An `exit` listener may raise the code; re-read before leaving.
646            let code = with_host(|h| h.exit_code).unwrap_or(0);
647            use std::io::Write;
648            let _ = std::io::stdout().flush();
649            let _ = std::io::stderr().flush();
650            // `std::process::exit` runs no destructors, so the bytecode cache
651            // has to reach disk here too — otherwise a script that ends in
652            // `process.exit()` would recompile every module it loaded, every
653            // run, and never benefit from the cache at all.
654            crate::cache::flush();
655            // In a worker this ends the worker thread and does not return.
656            super::worker_threads::exit_if_worker(code);
657            // Under `run_program` this unwinds to the embedder instead.
658            crate::embed::exit_if_embedded(code);
659            std::process::exit(code);
660        }
661        // `process.chdir(dir)` really changes the working directory, and throws on
662        // failure; it used to silently do nothing, so every later relative path
663        // still resolved against the old directory.
664        "chdir" => {
665            let dir = super::arg_str(args, 0);
666            std::env::set_current_dir(&dir)
667                .map(|()| Value::Undef)
668                // Node reports the libuv message and BOTH directories:
669                // `ENOENT: no such file or directory, chdir <cwd> -> <dir>`.
670                // The old text spliced in Rust's `io::Error` Display, whose
671                // `No such file or directory (os error 2)` no Node ever printed.
672                .map_err(|e| {
673                    let from = std::env::current_dir()
674                        .map(|p| p.display().to_string())
675                        .unwrap_or_default();
676                    format!(
677                        "Error: {}, chdir '{from}' -> '{dir}'",
678                        crate::stdlib::fs::libuv_message(&e)
679                    )
680                })
681        }
682        // `process.kill(pid[, signal])` really signals the process. Node's default
683        // is SIGTERM, and a numeric or `'SIGxxx'` signal is accepted; signal `0`
684        // is the existence probe and sends nothing.
685        "kill" => {
686            let pid = with_host(|h| args.first().map(|v| h.to_number(v)).unwrap_or(0.0)) as i32;
687            let sig: Result<libc::c_int, String> = match args.get(1) {
688                Some(v) if !matches!(v, Value::Undef) => match with_host(|h| h.as_str(v)) {
689                    Some(name) => signal_number(&name).ok_or(crate::host::coded_error(
690                        "TypeError",
691                        "ERR_UNKNOWN_SIGNAL",
692                        &format!("Unknown signal: {name}"),
693                    )),
694                    None => Ok(with_host(|h| h.to_number(v)) as libc::c_int),
695                },
696                _ => Ok(libc::SIGTERM),
697            };
698            sig.and_then(|sig| {
699                // SAFETY: `kill` is a plain syscall on a pid/signal pair; it
700                // mutates no process memory and reports failure through `errno`.
701                if unsafe { libc::kill(pid, sig) } != 0 {
702                    Err(format!("Error: {}", std::io::Error::last_os_error()))
703                } else {
704                    Ok(Value::Undef)
705                }
706            })
707        }
708        // A genuine no-op: node-js emits no source maps, so enabling their use
709        // changes nothing. Returning `undefined` is the whole of Node's contract
710        // here, so this is not a stub.
711        "setSourceMapsEnabled" => Ok(Value::Undef),
712
713        // POSIX identity queries (libc; pure reads, always safe).
714        "getuid" => Ok(Value::Float(unsafe { libc::getuid() } as f64)),
715        "geteuid" => Ok(Value::Float(unsafe { libc::geteuid() } as f64)),
716        "getgid" => Ok(Value::Float(unsafe { libc::getgid() } as f64)),
717        "getegid" => Ok(Value::Float(unsafe { libc::getegid() } as f64)),
718        "getgroups" => {
719            let groups = supplementary_groups();
720            Ok(with_host(|h| {
721                h.new_array(groups.into_iter().map(Value::Float).collect())
722            }))
723        }
724
725        // POSIX identity mutation (libc; best-effort — silently ignored when the
726        // process lacks the privilege, matching a no-throw best-effort surface).
727        "setuid" | "seteuid" | "setgid" | "setegid" => {
728            let id = super::arg_num(args, 0);
729            if id.is_finite() {
730                let id = id as u32;
731                // SAFETY: id is a plain uid/gid number; a failed call just returns -1.
732                unsafe {
733                    match method {
734                        "setuid" => libc::setuid(id),
735                        "seteuid" => libc::seteuid(id),
736                        "setgid" => libc::setgid(id),
737                        _ => libc::setegid(id),
738                    };
739                }
740            }
741            Ok(Value::Undef)
742        }
743        "setgroups" => {
744            let groups = gid_array(args.first());
745            // SAFETY: `groups` is a valid gid buffer of the given length.
746            unsafe {
747                libc::setgroups(groups.len() as _, groups.as_ptr());
748            }
749            Ok(Value::Undef)
750        }
751        "initgroups" => {
752            let user = super::arg_str(args, 0);
753            let extra = super::arg_num(args, 1);
754            if let Ok(c) = std::ffi::CString::new(user) {
755                let gid = if extra.is_finite() { extra as u32 } else { 0 };
756                // SAFETY: `c` is NUL-terminated; a failed call just returns -1.
757                unsafe {
758                    libc::initgroups(c.as_ptr(), gid as _);
759                }
760            }
761            Ok(Value::Undef)
762        }
763
764        // `ref`/`unref` on the process object are chainable no-ops (no libuv
765        // handle refcount to touch); return the process namespace.
766        "ref" | "unref" => Ok(with_host(|h| h.alloc(JsObj::Builtin("process".into())))),
767        "abort" => {
768            crate::embed::exit_if_embedded(134);
769            std::process::abort()
770        }
771        "getActiveResourcesInfo" => Ok(with_host(|h| h.new_array(Vec::new()))),
772        "resourceUsage" => Ok(resource_usage()),
773        "threadCpuUsage" => Ok(thread_cpu_usage()),
774        "availableMemory" | "constrainedMemory" => Ok(Value::Float(0.0)),
775        "getBuiltinModule" => {
776            let id = super::arg_str(args, 0);
777            let id = id.strip_prefix("node:").unwrap_or(&id);
778            match crate::stdlib::resolve(id) {
779                Some(ns) => Ok(with_host(|h| h.alloc(JsObj::Builtin(ns.to_string())))),
780                None => Ok(Value::Undef),
781            }
782        }
783        "openStdin" => Ok(std_stream(0)),
784
785        "hasUncaughtExceptionCaptureCallback" => {
786            Ok(Value::Bool(UNCAUGHT_CAPTURE.with(|c| c.borrow().is_some())))
787        }
788        "setUncaughtExceptionCaptureCallback" => {
789            let cb = args.first().cloned().unwrap_or(Value::Undef);
790            let clear = matches!(cb, Value::Undef) || with_host(|h| h.is_null(&cb));
791            if clear {
792                UNCAUGHT_CAPTURE.with(|c| *c.borrow_mut() = None);
793            } else if UNCAUGHT_CAPTURE.with(|c| c.borrow().is_some()) {
794                return Some(Err(crate::host::type_error(
795                    "`process.setUncaughtExceptionCaptureCallback()` was called \
796                     while a capture callback was already active",
797                )));
798            } else {
799                UNCAUGHT_CAPTURE.with(|c| *c.borrow_mut() = Some(cb));
800            }
801            Ok(Value::Undef)
802        }
803        "addUncaughtExceptionCaptureCallback" => {
804            let cb = args.first().cloned().unwrap_or(Value::Undef);
805            if !matches!(cb, Value::Undef) {
806                UNCAUGHT_CAPTURE.with(|c| *c.borrow_mut() = Some(cb));
807            }
808            Ok(Value::Undef)
809        }
810        "execve" => exec_ve(args),
811        "loadEnvFile" => load_env_file(&super::arg_str(args, 0)),
812        _ => return None,
813    })
814}
815
816/// `process.env` as a plain object built from the real environment.
817fn env_object() -> Value {
818    with_host(|h| {
819        let mut m = IndexMap::new();
820        // A marker the property-write path recognises, so an assignment into
821        // `process.env` coerces to a string the way a real environment does.
822        // Nothing dispatches on it; it is hidden from enumeration like any
823        // `@@` key.
824        m.insert("@@envObject".into(), Value::Bool(true));
825        for (k, v) in std::env::vars() {
826            m.insert(k, h.new_str(v));
827        }
828        h.new_object(m)
829    })
830}
831
832/// The `(execArgv, argv)` split installed by the binary's entry point.
833///
834/// Unset when the library is embedded (or driven by a sibling binary such as
835/// `parity-fuzz`, whose own command line is not a `node` command line), and the
836/// accessors below then fall back to the raw process arguments.
837static ARGV: std::sync::OnceLock<(Vec<String>, Vec<String>)> = std::sync::OnceLock::new();
838
839/// Publish Node's `process.argv` / `process.execArgv` split for this run, read
840/// off the real command line. Called once by the `node` binary's entry point;
841/// first call wins.
842///
843/// `argv[1]` is the entry script RESOLVED against the current directory, so
844/// `node ./x.js` reports the same absolute path `path.resolve` would — not the
845/// spelling that was typed.
846pub fn install_argv() {
847    let split = crate::cli::split_argv(std::env::args());
848    let mut argv = vec![exec_path()];
849    if let Some(s) = &split.script {
850        // `-` is Node's stdin entry point, not a path; it stays verbatim.
851        argv.push(if s == "-" {
852            s.clone()
853        } else {
854            super::path::resolve_one(s)
855        });
856    }
857    argv.extend(split.user);
858    let _ = EVAL_ENTRY.set(split.eval);
859    let _ = ARGV.set((split.exec, argv));
860}
861
862/// Whether this run's program is a `-e`/`-p` source rather than a script:
863/// node's `getOptionValue('--eval')`, which decides where `process.argv`'s
864/// program arguments start.
865static EVAL_ENTRY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
866
867pub fn eval_entry() -> bool {
868    EVAL_ENTRY.get().copied().unwrap_or(false)
869}
870
871/// `process.argv`: `[execPath, entryScript, ...userArgs]`.
872///
873/// The runtime's OWN flags are not in it — they are `process.execArgv` — and
874/// under `-e` there is no `argv[1]` at all. Returning the raw OS arguments put
875/// `-e` and the whole one-liner source into `argv`, which is what any script
876/// that reads `process.argv.slice(2)` for its options would have parsed.
877fn argv() -> Value {
878    with_host(|h| {
879        let items: Vec<Value> = match ARGV.get() {
880            Some((_, argv)) => argv.iter().map(|a| h.new_str(a.clone())).collect(),
881            None => std::env::args().map(|a| h.new_str(a)).collect(),
882        };
883        h.new_array(items)
884    })
885}
886
887/// `process.execArgv`: the runtime flags, `-e`/`--eval` and its source included.
888fn exec_argv() -> Value {
889    with_host(|h| {
890        let items: Vec<Value> = ARGV
891            .get()
892            .map(|(e, _)| e.iter().map(|a| h.new_str(a.clone())).collect())
893            .unwrap_or_default();
894        h.new_array(items)
895    })
896}
897
898fn exec_path() -> String {
899    std::env::current_exe()
900        .map(|p| p.to_string_lossy().into_owned())
901        .unwrap_or_else(|_| "node".into())
902}
903
904/// `process.versions` — a small map; only `node` is commonly gated on.
905fn versions() -> Value {
906    with_host(|h| {
907        let mut m = IndexMap::new();
908        m.insert("node".into(), h.new_str(&NODE_VERSION[1..]));
909        m.insert("v8".into(), h.new_str("0.0.0"));
910        h.new_object(m)
911    })
912}
913
914/// A minimal `process.stdout`/`stderr`/`stdin` stand-in: enough surface
915/// (`fd`, `isTTY`, `writable`, a `write`) for load-time probes like
916/// `tty.isatty(process.stderr.fd)`.
917fn std_stream(fd: i32) -> Value {
918    with_host(|h| {
919        let mut m = IndexMap::new();
920        m.insert("@@native".into(), h.new_str("WriteStream"));
921        m.insert("fd".into(), Value::Float(fd as f64));
922        // SAFETY: isatty is a pure query on the fd number.
923        let is_tty = unsafe { libc::isatty(fd) == 1 };
924        // Node defines `isTTY` only when the fd IS a terminal; off a pipe the
925        // property is absent, not `false`. Defining it either way made
926        // `typeof process.stdout.isTTY` report "boolean" where node says
927        // "undefined", which is exactly the check a library uses to decide
928        // whether to emit colour.
929        if is_tty {
930            m.insert("isTTY".into(), Value::Bool(true));
931        }
932        m.insert("writable".into(), Value::Bool(fd != 0));
933        m.insert("readable".into(), Value::Bool(fd == 0));
934        // A tty stream exposes its terminal dimensions (real ioctl reading).
935        if is_tty {
936            if let Some((cols, rows)) = super::tty::window_size(fd) {
937                m.insert("columns".into(), Value::Float(cols as f64));
938                m.insert("rows".into(), Value::Float(rows as f64));
939            }
940        }
941        h.new_object(m)
942    })
943}
944
945/// Instance methods of a `process.stdout`/`stderr` `WriteStream`: `write`/`end`
946/// emit the chunk raw (no newline) to the stream's fd, so ordering interleaves
947/// correctly with `console.log`.
948pub fn stream_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
949    if stream_fd(recv) == 0.0 {
950        if let Some(r) = stdin_call(recv, method, args) {
951            return r;
952        }
953    }
954    match method {
955        "write" | "end" => {
956            let fd = with_host(|h| match h.get(recv) {
957                Some(JsObj::Object(p)) => p.get("fd").map(|v| h.to_number(v)).unwrap_or(1.0),
958                _ => 1.0,
959            });
960            // `end()` with no chunk closes without writing; `write()` with no
961            // chunk is the argument error below.
962            if method == "end" && args.first().map(|v| matches!(v, Value::Undef)) != Some(false) {
963                return Ok(Value::Bool(true));
964            }
965            let bytes = chunk_bytes(args)?;
966            with_host(|h| h.write_out_bytes(&bytes, fd == 2.0));
967            Ok(Value::Bool(true))
968        }
969        // A no-op stream surface on stdout/stderr so `.on('drain')`/`.once`/
970        // `.end()` chaining loads; standard input answers these for real
971        // (`stdin_call`).
972        "on" | "once" | "addListener" | "prependListener" | "removeListener" | "off"
973        | "removeAllListeners" | "cork" | "uncork" | "setEncoding" | "resume" | "pause" => {
974            Ok(recv.clone())
975        }
976        "listenerCount" => Ok(Value::Float(0.0)),
977        "read" => Ok(with_host(|h| h.null())),
978        "pipe" => Ok(args.first().cloned().unwrap_or(Value::Undef)),
979        // `tty.WriteStream` cursor/erase control — emit the corresponding ANSI
980        // escape to the stream's fd (best-effort; only meaningful on a real tty).
981        "cursorTo" | "moveCursor" | "clearLine" | "clearScreenDown" => {
982            let seq = tty_control(method, args);
983            write_fd(stream_fd(recv), seq.as_bytes());
984            Ok(Value::Bool(true))
985        }
986        "getWindowSize" => {
987            let (c, r) = super::tty::window_size(stream_fd(recv) as i32).unwrap_or((80, 24));
988            Ok(with_host(|h| {
989                h.new_array(vec![Value::Float(c as f64), Value::Float(r as f64)])
990            }))
991        }
992        // A truecolor terminal advertises 24-bit depth; hasColors(count) is true
993        // for any request within that range.
994        "getColorDepth" => Ok(Value::Float(24.0)),
995        "hasColors" => Ok(Value::Bool(true)),
996        _ => Err(crate::host::type_error(&format!(
997            "{method} is not a function"
998        ))),
999    }
1000}
1001
1002fn hrtime(args: &[Value]) -> Value {
1003    let now = std::time::SystemTime::now()
1004        .duration_since(std::time::UNIX_EPOCH)
1005        .unwrap_or_default();
1006    let (mut secs, mut nanos) = (now.as_secs() as f64, now.subsec_nanos() as f64);
1007    // `hrtime(prev)` returns the diff from a prior reading.
1008    if let Some(Value::Obj(_)) = args.first() {
1009        if let Some(prev) = with_host(|h| match h.get(&args[0]) {
1010            Some(JsObj::Array(a)) if a.len() == 2 => Some((h.to_number(&a[0]), h.to_number(&a[1]))),
1011            _ => None,
1012        }) {
1013            secs -= prev.0;
1014            nanos -= prev.1;
1015        }
1016    }
1017    with_host(|h| h.new_array(vec![Value::Float(secs), Value::Float(nanos)]))
1018}
1019
1020/// The process's resident set size in bytes, or `None` where it cannot be read.
1021///
1022/// `process.memoryUsage()` reported a flat zero for every field, which is not a
1023/// measurement — a caller comparing it against a threshold got a wrong answer
1024/// rather than an honest refusal. RSS is the one figure both platforms expose
1025/// cheaply; the V8 heap figures below stay zero because this runtime has no V8
1026/// heap to report, and saying zero there is the truthful answer.
1027#[cfg(target_os = "macos")]
1028fn resident_bytes() -> Option<u64> {
1029    let mut info: libc::proc_taskinfo = unsafe { std::mem::zeroed() };
1030    let size = std::mem::size_of::<libc::proc_taskinfo>() as libc::c_int;
1031    let got = unsafe {
1032        libc::proc_pidinfo(
1033            std::process::id() as libc::c_int,
1034            libc::PROC_PIDTASKINFO,
1035            0,
1036            (&mut info as *mut libc::proc_taskinfo).cast(),
1037            size,
1038        )
1039    };
1040    (got == size).then_some(info.pti_resident_size)
1041}
1042
1043#[cfg(target_os = "linux")]
1044fn resident_bytes() -> Option<u64> {
1045    // `/proc/self/statm` field 2 is the resident page count.
1046    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
1047    let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
1048    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
1049    (page > 0).then(|| pages * page as u64)
1050}
1051
1052#[cfg(not(any(target_os = "macos", target_os = "linux")))]
1053fn resident_bytes() -> Option<u64> {
1054    None
1055}
1056
1057fn memory_usage() -> Value {
1058    let rss = resident_bytes().unwrap_or(0) as f64;
1059    with_host(|h| {
1060        let mut m = IndexMap::new();
1061        m.insert("rss".into(), Value::Float(rss));
1062        // The V8 heap figures have no counterpart here, so they stay zero
1063        // rather than being invented.
1064        for k in ["heapTotal", "heapUsed", "external", "arrayBuffers"] {
1065            m.insert(k.into(), Value::Float(0.0));
1066        }
1067        h.new_object(m)
1068    })
1069}
1070
1071/// `process.memoryUsage.rss()` — the same figure without building the object.
1072pub fn memory_usage_rss() -> Value {
1073    Value::Float(resident_bytes().unwrap_or(0) as f64)
1074}
1075
1076/// Emit `process.on('exit', code)` exactly once per process, the way Node's
1077/// `process._exiting` latch does — `process.exit()` inside an `exit` handler
1078/// must not re-enter it.
1079///
1080/// The handlers run SYNCHRONOUSLY and nothing they schedule ever runs: Node
1081/// leaves the loop straight after them, so a `setTimeout` or `.then` queued
1082/// here is dropped. An `exit` listener may still raise `process.exitCode`, and
1083/// that later value is the one the process uses, which is why the caller reads
1084/// the slot back after this returns.
1085pub fn emit_exit_event(code: i32) -> Result<(), String> {
1086    if with_host(|h| std::mem::replace(&mut h.exiting, true)) {
1087        return Ok(());
1088    }
1089    let listeners = with_host(|h| h.take_process_listeners("exit"));
1090    for f in listeners {
1091        crate::host::invoke(&f, vec![Value::Float(code as f64)], None)?;
1092    }
1093    Ok(())
1094}
1095
1096/// Emit `process.on('beforeExit', code)`. Node fires this when the loop has
1097/// drained but the process has NOT been told to exit, and — unlike `exit` —
1098/// work scheduled from a handler is honoured, so the loop runs again and
1099/// `beforeExit` can fire repeatedly. It never fires after an explicit
1100/// `process.exit()` or an uncaught exception.
1101///
1102/// Reports whether any listener ran, so the caller knows to re-drain.
1103pub fn emit_before_exit(code: i32) -> Result<bool, String> {
1104    let listeners = with_host(|h| h.take_process_listeners("beforeExit"));
1105    let any = !listeners.is_empty();
1106    for f in listeners {
1107        crate::host::invoke(&f, vec![Value::Float(code as f64)], None)?;
1108    }
1109    Ok(any)
1110}
1111
1112/// The bytes a `stream.write(chunk[, encoding])` call puts on the wire.
1113///
1114/// Node writes a `Buffer`/`TypedArray`/`DataView` chunk through UNTOUCHED, and
1115/// decodes a string chunk with the named encoding (default `utf8`). Both were
1116/// funnelled through `ToString` here, which is lossy in two separate ways:
1117/// `process.stdout.write(Buffer.from([0xff,0xfe,0x41]))` printed the 15 bytes of
1118/// `[object Object]` instead of `ff fe 41`, and even once the Buffer path
1119/// existed, a `String` round-trip would have replaced each non-UTF-8 byte with
1120/// `U+FFFD` (3 bytes out, 7 bytes on the wire). `write("4142","hex")` likewise
1121/// printed the four characters of the literal instead of the two bytes `AB`.
1122///
1123/// Anything that is neither a string nor a byte view is the same
1124/// `ERR_INVALID_ARG_TYPE` Node raises — a JS array of byte values included,
1125/// which is why this does NOT reuse `buffer::bytes_like` (that helper
1126/// deliberately accepts plain arrays, which `write` rejects).
1127fn chunk_bytes(args: &[Value]) -> Result<Vec<u8>, String> {
1128    let chunk = args.first().cloned().unwrap_or(Value::Undef);
1129    if with_host(|h| h.is_null(&chunk)) {
1130        return Err(crate::host::type_error(
1131            "May not write null values to stream",
1132        ));
1133    }
1134    if let Some(s) = with_host(|h| h.as_str(&chunk)) {
1135        let enc = match args.get(1) {
1136            Some(v) if !matches!(v, Value::Undef) => with_host(|h| h.str_of(v)),
1137            _ => "utf8".to_string(),
1138        };
1139        return Ok(super::buffer::decode_str(&s, &enc));
1140    }
1141    match super::native_tag(&chunk).as_deref() {
1142        Some("Buffer") | Some("TypedArray") | Some("DataView") => {
1143            Ok(super::buffer::bytes_like(&chunk).unwrap_or_default())
1144        }
1145        _ => Err(crate::host::type_error(&format!(
1146            "The \"chunk\" argument must be of type string or an instance of \
1147             Buffer, TypedArray, or DataView. Received {}",
1148            super::received_desc(&chunk)
1149        ))),
1150    }
1151}
1152
1153/// The `fd` numeric property of a stream stand-in (default stdout).
1154fn stream_fd(recv: &Value) -> f64 {
1155    with_host(|h| match h.get(recv) {
1156        Some(JsObj::Object(p)) => p.get("fd").map(|v| h.to_number(v)).unwrap_or(1.0),
1157        _ => 1.0,
1158    })
1159}
1160
1161/// Write raw bytes as program output on stdout/stderr (chosen by fd) — through
1162/// the host funnel, so an embedder capturing output receives these too.
1163fn write_fd(fd: f64, bytes: &[u8]) {
1164    let text = String::from_utf8_lossy(bytes).into_owned();
1165    with_host(|h| h.write_out(&text, fd == 2.0));
1166}
1167
1168/// The ANSI control sequence for a `tty.WriteStream` cursor/erase method.
1169fn tty_control(method: &str, args: &[Value]) -> String {
1170    match method {
1171        // cursorTo(x[, y]) → absolute column (`\e[<x+1>G`) or position.
1172        "cursorTo" => {
1173            let x = super::arg_num(args, 0);
1174            let y = super::arg_num(args, 1);
1175            let x = if x.is_finite() { x as i64 } else { 0 };
1176            if y.is_finite() {
1177                format!("\x1b[{};{}H", y as i64 + 1, x + 1)
1178            } else {
1179                format!("\x1b[{}G", x + 1)
1180            }
1181        }
1182        // moveCursor(dx, dy) → relative moves.
1183        "moveCursor" => {
1184            let dx = super::arg_num(args, 0);
1185            let dy = super::arg_num(args, 1);
1186            let mut s = String::new();
1187            let dx = if dx.is_finite() { dx as i64 } else { 0 };
1188            let dy = if dy.is_finite() { dy as i64 } else { 0 };
1189            if dx > 0 {
1190                s.push_str(&format!("\x1b[{dx}C"));
1191            } else if dx < 0 {
1192                s.push_str(&format!("\x1b[{}D", -dx));
1193            }
1194            if dy > 0 {
1195                s.push_str(&format!("\x1b[{dy}B"));
1196            } else if dy < 0 {
1197                s.push_str(&format!("\x1b[{}A", -dy));
1198            }
1199            s
1200        }
1201        // clearLine(dir): -1 left, 1 right, 0 whole line.
1202        "clearLine" => match super::arg_num(args, 0) {
1203            d if d < 0.0 => "\x1b[1K".into(),
1204            d if d > 0.0 => "\x1b[0K".into(),
1205            _ => "\x1b[2K".into(),
1206        },
1207        // clearScreenDown → erase from cursor to end of screen.
1208        _ => "\x1b[0J".into(),
1209    }
1210}
1211
1212/// The process's supplementary group ids (`getgroups(2)`).
1213fn supplementary_groups() -> Vec<f64> {
1214    // SAFETY: first call queries the count, second fills a buffer of that size.
1215    unsafe {
1216        let n = libc::getgroups(0, std::ptr::null_mut());
1217        if n <= 0 {
1218            return Vec::new();
1219        }
1220        let mut buf = vec![0 as libc::gid_t; n as usize];
1221        let filled = libc::getgroups(n, buf.as_mut_ptr());
1222        if filled < 0 {
1223            return Vec::new();
1224        }
1225        buf.truncate(filled as usize);
1226        buf.into_iter().map(|g| g as f64).collect()
1227    }
1228}
1229
1230/// Read a JS array of numbers as a gid buffer.
1231fn gid_array(v: Option<&Value>) -> Vec<libc::gid_t> {
1232    let Some(v) = v else { return Vec::new() };
1233    with_host(|h| match h.get(v) {
1234        Some(JsObj::Array(a)) => a.iter().map(|x| h.to_number(x) as libc::gid_t).collect(),
1235        _ => Vec::new(),
1236    })
1237}
1238
1239/// `getrusage(RUSAGE_SELF)` — `None` if the syscall fails.
1240fn get_rusage() -> Option<libc::rusage> {
1241    // SAFETY: getrusage fills a zeroed rusage; RUSAGE_SELF is a valid `who`.
1242    unsafe {
1243        let mut ru: libc::rusage = std::mem::zeroed();
1244        (libc::getrusage(libc::RUSAGE_SELF, &mut ru) == 0).then_some(ru)
1245    }
1246}
1247
1248/// microseconds from a `timeval`.
1249fn tv_micros(t: &libc::timeval) -> f64 {
1250    t.tv_sec as f64 * 1e6 + t.tv_usec as f64
1251}
1252
1253/// `process.resourceUsage()` — the full `getrusage` breakdown (zeros on failure).
1254fn resource_usage() -> Value {
1255    let ru = get_rusage();
1256    with_host(|h| {
1257        let mut m = IndexMap::new();
1258        let (utime, stime) = ru
1259            .as_ref()
1260            .map(|r| (tv_micros(&r.ru_utime), tv_micros(&r.ru_stime)))
1261            .unwrap_or((0.0, 0.0));
1262        m.insert("userCPUTime".into(), Value::Float(utime));
1263        m.insert("systemCPUTime".into(), Value::Float(stime));
1264        let fields = [
1265            ("maxRSS", ru.as_ref().map(|r| r.ru_maxrss)),
1266            ("sharedMemorySize", ru.as_ref().map(|r| r.ru_ixrss)),
1267            ("unsharedDataSize", ru.as_ref().map(|r| r.ru_idrss)),
1268            ("unsharedStackSize", ru.as_ref().map(|r| r.ru_isrss)),
1269            ("minorPageFault", ru.as_ref().map(|r| r.ru_minflt)),
1270            ("majorPageFault", ru.as_ref().map(|r| r.ru_majflt)),
1271            ("swappedOut", ru.as_ref().map(|r| r.ru_nswap)),
1272            ("fsRead", ru.as_ref().map(|r| r.ru_inblock)),
1273            ("fsWrite", ru.as_ref().map(|r| r.ru_oublock)),
1274            ("ipcSent", ru.as_ref().map(|r| r.ru_msgsnd)),
1275            ("ipcReceived", ru.as_ref().map(|r| r.ru_msgrcv)),
1276            ("signalsCount", ru.as_ref().map(|r| r.ru_nsignals)),
1277            ("voluntaryContextSwitches", ru.as_ref().map(|r| r.ru_nvcsw)),
1278            (
1279                "involuntaryContextSwitches",
1280                ru.as_ref().map(|r| r.ru_nivcsw),
1281            ),
1282        ];
1283        for (k, v) in fields {
1284            m.insert(k.into(), Value::Float(v.unwrap_or(0) as f64));
1285        }
1286        h.new_object(m)
1287    })
1288}
1289
1290/// `process.threadCpuUsage()` — best-effort via process-wide `getrusage` (no
1291/// per-thread accounting substrate), reported as `{user, system}` microseconds.
1292fn thread_cpu_usage() -> Value {
1293    let (u, s) = get_rusage()
1294        .map(|r| (tv_micros(&r.ru_utime), tv_micros(&r.ru_stime)))
1295        .unwrap_or((0.0, 0.0));
1296    with_host(|h| {
1297        let mut m = IndexMap::new();
1298        m.insert("user".into(), Value::Float(u));
1299        m.insert("system".into(), Value::Float(s));
1300        h.new_object(m)
1301    })
1302}
1303
1304/// `process.execve(file, args[, env])` — replace the process image (never returns
1305/// on success; throws the OS error otherwise).
1306fn exec_ve(args: &[Value]) -> Result<Value, String> {
1307    use std::ffi::CString;
1308    let prog = CString::new(super::arg_str(args, 0))
1309        .map_err(|_| crate::host::type_error("process.execve: invalid file path"))?;
1310
1311    let argv_strs: Vec<String> = with_host(|h| match args.get(1).and_then(|v| h.get(v)) {
1312        Some(JsObj::Array(a)) => a.iter().map(|x| h.str_of(x)).collect(),
1313        _ => Vec::new(),
1314    });
1315    let env_strs: Vec<String> = {
1316        let from_arg = with_host(|h| match args.get(2).and_then(|v| h.get(v)) {
1317            Some(JsObj::Object(p)) => Some(
1318                p.iter()
1319                    .map(|(k, v)| format!("{k}={}", h.str_of(v)))
1320                    .collect::<Vec<_>>(),
1321            ),
1322            _ => None,
1323        });
1324        from_arg.unwrap_or_else(|| std::env::vars().map(|(k, v)| format!("{k}={v}")).collect())
1325    };
1326
1327    let to_c = |s: String| {
1328        CString::new(s).map_err(|_| crate::host::type_error("process.execve: NUL in argument"))
1329    };
1330    let argv_c: Vec<CString> = argv_strs.into_iter().map(to_c).collect::<Result<_, _>>()?;
1331    let env_c: Vec<CString> = env_strs.into_iter().map(to_c).collect::<Result<_, _>>()?;
1332
1333    let mut argv_p: Vec<*const libc::c_char> = argv_c.iter().map(|c| c.as_ptr()).collect();
1334    argv_p.push(std::ptr::null());
1335    let mut envp_p: Vec<*const libc::c_char> = env_c.iter().map(|c| c.as_ptr()).collect();
1336    envp_p.push(std::ptr::null());
1337
1338    // SAFETY: argv/envp are NUL-terminated arrays of valid C strings kept alive
1339    // above; on success execve never returns.
1340    unsafe {
1341        libc::execve(prog.as_ptr(), argv_p.as_ptr(), envp_p.as_ptr());
1342    }
1343    Err(crate::host::type_error(&format!(
1344        "process.execve failed: {}",
1345        std::io::Error::last_os_error()
1346    )))
1347}
1348
1349/// `process.loadEnvFile([path])` — parse a `.env` file into `process.env`
1350/// (persisted through the real environment so a later `process.env` read sees it).
1351fn load_env_file(path: &str) -> Result<Value, String> {
1352    let path = if path.is_empty() { ".env" } else { path };
1353    let text =
1354        std::fs::read_to_string(path).map_err(|e| format!("Error: ENOENT: {e}, open '{path}'"))?;
1355    for line in text.lines() {
1356        let line = line.trim();
1357        if line.is_empty() || line.starts_with('#') {
1358            continue;
1359        }
1360        let line = line.strip_prefix("export ").unwrap_or(line);
1361        let Some((key, val)) = line.split_once('=') else {
1362            continue;
1363        };
1364        let key = key.trim();
1365        if key.is_empty() {
1366            continue;
1367        }
1368        let mut val = val.trim();
1369        if val.len() >= 2
1370            && ((val.starts_with('"') && val.ends_with('"'))
1371                || (val.starts_with('\'') && val.ends_with('\'')))
1372        {
1373            val = &val[1..val.len() - 1];
1374        }
1375        std::env::set_var(key, val);
1376    }
1377    Ok(Value::Undef)
1378}
1379
1380/// The event name argument of an EventEmitter-style `process` call.
1381fn event_name(args: &[Value]) -> String {
1382    args.first()
1383        .map(|v| with_host(|h| h.str_of(v)))
1384        .unwrap_or_default()
1385}
1386
1387// ── process.stdin as a readable stream ───────────────────────────────────────
1388//
1389// Standard input is read by a PUMP: a macrotask that reads one chunk (blocking,
1390// up to 64 KiB, through Rust's shared stdin buffer, which `readline` and
1391// `fs.readFileSync(0)` read through too) and re-arms itself until end of
1392// input. What a chunk becomes depends on how the program consumes the stream,
1393// as in node: a `'data'` listener or `resume()` makes it FLOW (each chunk is a
1394// `'data'` event), a `'readable'` listener buffers it for `read()`, and an
1395// async iterator hands it to `next()`. End of input is `'end'`, then `'close'`.
1396
1397/// The state of `process.stdin`.
1398#[derive(Default)]
1399struct Stdin {
1400    /// Registered `(event, callback, once)` listeners, in call order.
1401    listeners: Vec<(String, Value, bool)>,
1402    /// `setEncoding`: chunks are strings in this encoding instead of Buffers.
1403    encoding: Option<String>,
1404    /// The tail of a UTF-8 sequence a chunk split, held for the next one.
1405    partial: Vec<u8>,
1406    /// The pump has been scheduled and has not reached end of input.
1407    pumping: bool,
1408    /// `pause()` stops the pump; `resume()` restarts it.
1409    paused: bool,
1410    flowing: bool,
1411    readable_mode: bool,
1412    /// Chunks waiting for `read()` or an async iterator's `next()`.
1413    buffered: std::collections::VecDeque<Value>,
1414    waiters: std::collections::VecDeque<u32>,
1415    iterating: bool,
1416    ended: bool,
1417    /// Where `pipe(dest)` sends each chunk.
1418    pipe_dest: Option<Value>,
1419}
1420
1421thread_local! {
1422    static STDIN: std::cell::RefCell<Stdin> = std::cell::RefCell::new(Stdin::default());
1423}
1424
1425fn with_stdin<R>(f: impl FnOnce(&mut Stdin) -> R) -> R {
1426    STDIN.with(|s| f(&mut s.borrow_mut()))
1427}
1428
1429/// Schedule the pump if it is not running and the stream is not paused.
1430fn start_stdin() {
1431    let start = with_stdin(|s| {
1432        if s.pumping || s.paused || s.ended {
1433            return false;
1434        }
1435        s.pumping = true;
1436        true
1437    });
1438    if start {
1439        schedule_stdin_pump();
1440    }
1441}
1442
1443fn schedule_stdin_pump() {
1444    with_host(|h| {
1445        let cb = h.alloc(JsObj::Builtin("process.@@stdinPump".into()));
1446        h.add_timer(-1.0, cb, Vec::new(), None);
1447    });
1448}
1449
1450fn emit_stdin(recv: &Value, event: &str, args: Vec<Value>) -> Result<(), String> {
1451    let entries: Vec<(Value, bool)> = with_stdin(|s| {
1452        let found = s
1453            .listeners
1454            .iter()
1455            .filter(|(e, _, _)| e == event)
1456            .map(|(_, cb, once)| (cb.clone(), *once))
1457            .collect();
1458        s.listeners.retain(|(e, _, once)| !(e == event && *once));
1459        found
1460    });
1461    for (cb, _) in entries {
1462        crate::host::invoke(&cb, args.clone(), Some(recv.clone()))?;
1463    }
1464    Ok(())
1465}
1466
1467/// A chunk as the program sees it: a Buffer, or a string under `setEncoding`.
1468/// A UTF-8 sequence split between two reads is held back and completed by the
1469/// next one, as node's `StringDecoder` does.
1470fn stdin_chunk(bytes: &[u8]) -> Option<Value> {
1471    let enc = with_stdin(|s| s.encoding.clone());
1472    let Some(enc) = enc else {
1473        return Some(super::buffer::from_bytes(bytes));
1474    };
1475    if enc != "utf8" && enc != "utf-8" {
1476        return Some(with_host(|h| {
1477            h.new_str(super::buffer::encode_bytes(bytes, &enc))
1478        }));
1479    }
1480    let mut all = with_stdin(|s| std::mem::take(&mut s.partial));
1481    all.extend_from_slice(bytes);
1482    let keep = incomplete_utf8_tail(&all);
1483    let tail = all.split_off(all.len() - keep);
1484    with_stdin(|s| s.partial = tail);
1485    if all.is_empty() {
1486        return None;
1487    }
1488    Some(with_host(|h| {
1489        h.new_str(String::from_utf8_lossy(&all).into_owned())
1490    }))
1491}
1492
1493/// How many bytes at the end of `b` begin a UTF-8 sequence that is not yet
1494/// complete.
1495fn incomplete_utf8_tail(b: &[u8]) -> usize {
1496    for back in 1..=3.min(b.len()) {
1497        let c = b[b.len() - back];
1498        if c & 0xC0 == 0x80 {
1499            continue;
1500        }
1501        let need = match c {
1502            0xC0..=0xDF => 2,
1503            0xE0..=0xEF => 3,
1504            0xF0..=0xF7 => 4,
1505            _ => 1,
1506        };
1507        return if need > back { back } else { 0 };
1508    }
1509    0
1510}
1511
1512/// One turn of the stdin pump.
1513fn stdin_pump() -> Result<(), String> {
1514    let recv = stdin_value();
1515    if with_stdin(|s| s.paused) {
1516        with_stdin(|s| s.pumping = false);
1517        return Ok(());
1518    }
1519    let mut buf = vec![0u8; 65536];
1520    let n = crate::host::with_stdin_reader(|r| r.read(&mut buf)).unwrap_or(0);
1521    if n == 0 {
1522        return stdin_end(&recv);
1523    }
1524    schedule_stdin_pump();
1525    let Some(chunk) = stdin_chunk(&buf[..n]) else {
1526        return Ok(());
1527    };
1528    stdin_deliver(&recv, chunk)
1529}
1530
1531/// Hand a chunk to whatever is consuming the stream.
1532fn stdin_deliver(recv: &Value, chunk: Value) -> Result<(), String> {
1533    if let Some(dest) = with_stdin(|s| s.pipe_dest.clone()) {
1534        crate::host::call_method(&dest, "write", vec![chunk.clone()])?;
1535    }
1536    let (flowing, readable, waiter) = with_stdin(|s| {
1537        let waiter = if s.iterating {
1538            s.waiters.pop_front()
1539        } else {
1540            None
1541        };
1542        (s.flowing, s.readable_mode, waiter)
1543    });
1544    if let Some(id) = waiter {
1545        crate::host::resolve_promise_val(id, stdin_iter_result(chunk, false));
1546        return Ok(());
1547    }
1548    if flowing {
1549        emit_stdin(recv, "data", vec![chunk])?;
1550    } else if readable || with_stdin(|s| s.iterating) {
1551        with_stdin(|s| s.buffered.push_back(chunk));
1552        if readable {
1553            emit_stdin(recv, "readable", Vec::new())?;
1554        }
1555    }
1556    Ok(())
1557}
1558
1559/// End of input: a last `'readable'` (for `read()` to report `null`), `'end'`,
1560/// the end of any async iteration, then `'close'` on a later tick.
1561fn stdin_end(recv: &Value) -> Result<(), String> {
1562    let (readable, waiters, dest) = with_stdin(|s| {
1563        s.ended = true;
1564        s.pumping = false;
1565        (
1566            s.readable_mode,
1567            std::mem::take(&mut s.waiters),
1568            s.pipe_dest.clone(),
1569        )
1570    });
1571    if readable {
1572        emit_stdin(recv, "readable", Vec::new())?;
1573    }
1574    for id in waiters {
1575        crate::host::resolve_promise_val(id, stdin_iter_result(Value::Undef, true));
1576    }
1577    // `pipe` ends its destination, except the process's own stdout/stderr.
1578    if let Some(dest) = dest {
1579        let is_std = with_host(|h| match h.get(&dest) {
1580            Some(JsObj::Object(p)) => {
1581                p.get("@@native").map(|v| h.str_of(v)).as_deref() == Some("WriteStream")
1582            }
1583            _ => false,
1584        });
1585        if !is_std {
1586            crate::host::call_method(&dest, "end", Vec::new())?;
1587        }
1588    }
1589    emit_stdin(recv, "end", Vec::new())?;
1590    let target = recv.clone();
1591    with_host(|h| h.queue_micro_native(Box::new(move || emit_stdin(&target, "close", Vec::new()))));
1592    Ok(())
1593}
1594
1595fn stdin_iter_result(value: Value, done: bool) -> Value {
1596    with_host(|h| {
1597        let mut m = IndexMap::new();
1598        m.insert("value".into(), value);
1599        m.insert("done".into(), Value::Bool(done));
1600        h.new_object(m)
1601    })
1602}
1603
1604/// The `process.stdin` object.
1605fn stdin_value() -> Value {
1606    constant("stdin").unwrap_or(Value::Undef)
1607}
1608
1609/// The methods `process.stdin` answers as a readable stream. `None` hands the
1610/// call to the shared `WriteStream` surface.
1611fn stdin_call(recv: &Value, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
1612    let str_arg = |i: usize| with_host(|h| args.get(i).map(|v| h.str_of(v)).unwrap_or_default());
1613    Some(match method {
1614        "on" | "once" | "addListener" | "prependListener" => {
1615            let event = str_arg(0);
1616            if let Some(cb) = args.get(1).cloned() {
1617                with_stdin(|s| {
1618                    let entry = (event.clone(), cb, method == "once");
1619                    if method == "prependListener" {
1620                        s.listeners.insert(0, entry);
1621                    } else {
1622                        s.listeners.push(entry);
1623                    }
1624                    match event.as_str() {
1625                        "data" => s.flowing = true,
1626                        "readable" => s.readable_mode = true,
1627                        _ => {}
1628                    }
1629                });
1630                if matches!(event.as_str(), "data" | "readable") {
1631                    start_stdin();
1632                }
1633            }
1634            Ok(recv.clone())
1635        }
1636        "removeListener" | "off" => {
1637            let event = str_arg(0);
1638            if let Some(cb) = args.get(1) {
1639                with_stdin(|s| {
1640                    let pos = s
1641                        .listeners
1642                        .iter()
1643                        .position(|(e, f, _)| *e == event && with_host(|h| h.strict_eq(f, cb)));
1644                    if let Some(i) = pos {
1645                        s.listeners.remove(i);
1646                    }
1647                });
1648            }
1649            Ok(recv.clone())
1650        }
1651        "removeAllListeners" => {
1652            let event = args
1653                .first()
1654                .filter(|v| !matches!(v, Value::Undef))
1655                .map(|_| str_arg(0));
1656            with_stdin(|s| match &event {
1657                Some(e) => s.listeners.retain(|(x, _, _)| x != e),
1658                None => s.listeners.clear(),
1659            });
1660            Ok(recv.clone())
1661        }
1662        "listenerCount" => {
1663            let event = str_arg(0);
1664            let n = with_stdin(|s| s.listeners.iter().filter(|(e, _, _)| *e == event).count());
1665            Ok(Value::Float(n as f64))
1666        }
1667        "setEncoding" => {
1668            let enc = match args.first() {
1669                Some(v) if !matches!(v, Value::Undef) => str_arg(0).to_ascii_lowercase(),
1670                _ => "utf8".to_string(),
1671            };
1672            with_stdin(|s| s.encoding = Some(enc));
1673            Ok(recv.clone())
1674        }
1675        "resume" => {
1676            with_stdin(|s| {
1677                s.paused = false;
1678                s.flowing = true;
1679            });
1680            start_stdin();
1681            Ok(recv.clone())
1682        }
1683        "pause" => {
1684            with_stdin(|s| s.paused = true);
1685            Ok(recv.clone())
1686        }
1687        "read" => {
1688            let chunk = with_stdin(|s| {
1689                let parts: Vec<Value> = s.buffered.drain(..).collect();
1690                (!parts.is_empty()).then_some(parts)
1691            });
1692            match chunk {
1693                None => Ok(with_host(|h| h.null())),
1694                Some(parts) if parts.len() == 1 => {
1695                    Ok(parts.into_iter().next().unwrap_or(Value::Undef))
1696                }
1697                Some(parts) => {
1698                    // Several buffered chunks come back joined, as node's
1699                    // `read()` with no size returns everything buffered.
1700                    if with_stdin(|s| s.encoding.is_some()) {
1701                        let joined: String =
1702                            parts.iter().map(|p| with_host(|h| h.str_of(p))).collect();
1703                        Ok(with_host(|h| h.new_str(joined)))
1704                    } else {
1705                        let bytes: Vec<u8> = parts
1706                            .iter()
1707                            .flat_map(|p| super::buffer::view_bytes(p).unwrap_or_default())
1708                            .collect();
1709                        Ok(super::buffer::from_bytes(&bytes))
1710                    }
1711                }
1712            }
1713        }
1714        "pipe" => {
1715            let dest = args.first().cloned().unwrap_or(Value::Undef);
1716            with_stdin(|s| {
1717                s.pipe_dest = Some(dest.clone());
1718                s.flowing = true;
1719            });
1720            start_stdin();
1721            Ok(dest)
1722        }
1723        "@@asyncIterator" => {
1724            with_stdin(|s| s.iterating = true);
1725            start_stdin();
1726            Ok(with_host(|h| {
1727                let mut m = IndexMap::new();
1728                m.insert("@@native".into(), h.new_str("StdinIterator"));
1729                h.new_object(m)
1730            }))
1731        }
1732        _ => return None,
1733    })
1734}
1735
1736/// The methods of the async iterator `for await (const chunk of process.stdin)`
1737/// reads.
1738pub const STDIN_ITERATOR_METHODS: &[&str] = &["next", "return", "@@asyncIterator"];
1739
1740pub fn stdin_iterator_call(recv: &Value, method: &str) -> Result<Value, String> {
1741    match method {
1742        "@@asyncIterator" => Ok(recv.clone()),
1743        "next" => {
1744            let ready = with_stdin(|s| match s.buffered.pop_front() {
1745                Some(c) => Some(Some(c)),
1746                None if s.ended => Some(None),
1747                None => None,
1748            });
1749            match ready {
1750                Some(Some(c)) => crate::builtins::promise_resolve_pub(stdin_iter_result(c, false)),
1751                Some(None) => {
1752                    crate::builtins::promise_resolve_pub(stdin_iter_result(Value::Undef, true))
1753                }
1754                None => {
1755                    let (promise, id) = with_host(|h| {
1756                        let p = h.new_promise();
1757                        let id = h.promise_id(&p).unwrap_or(0);
1758                        (p, id)
1759                    });
1760                    with_stdin(|s| s.waiters.push_back(id));
1761                    Ok(promise)
1762                }
1763            }
1764        }
1765        // Leaving the loop early stops reading, as destroying the stream does.
1766        "return" => {
1767            with_stdin(|s| {
1768                s.iterating = false;
1769                s.paused = true;
1770            });
1771            crate::builtins::promise_resolve_pub(stdin_iter_result(Value::Undef, true))
1772        }
1773        _ => Err(crate::host::type_error(&format!(
1774            "{method} is not a function"
1775        ))),
1776    }
1777}