1use crate::host::{with_host, JsObj};
10use fusevm::Value;
11use indexmap::IndexMap;
12
13pub const NODE_VERSION: &str = "v26.5.0";
18
19pub const METHODS: &[&str] = &[
20 "cwd",
21 "chdir",
22 "exit",
23 "hrtime",
24 "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 static UNCAUGHT_CAPTURE: std::cell::RefCell<Option<Value>> =
79 const { std::cell::RefCell::new(None) };
80}
81
82static TRACE_HINT_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
85
86pub fn emit_warning(name: &str, code: Option<&str>, message: &str, detail: Option<&str>) {
94 queue_warning(name, code, message, detail, None);
95}
96
97fn 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
157fn 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
190pub 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
204pub 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
237fn emit_warning_args(args: &[Value]) -> Result<(), String> {
239 let warning = args.first().cloned().unwrap_or(Value::Undef);
240 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
303fn 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
324fn 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 let ts = h.new_str("none");
346 m.insert("typescript".into(), ts);
347 h.new_object(m)
348 })
349}
350
351fn 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
372fn 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 "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 "version" => with_host(|h| h.new_str(NODE_VERSION)),
427 "versions" => memo("versions", versions),
428 "features" => memo("features", features),
434 "config" => memo("config", config),
438 "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 "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
455pub 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 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" => Ok(hrtime(args)),
531 "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 "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 "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 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 crate::cache::flush();
655 super::worker_threads::exit_if_worker(code);
657 crate::embed::exit_if_embedded(code);
659 std::process::exit(code);
660 }
661 "chdir" => {
665 let dir = super::arg_str(args, 0);
666 std::env::set_current_dir(&dir)
667 .map(|()| Value::Undef)
668 .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 "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 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 "setSourceMapsEnabled" => Ok(Value::Undef),
712
713 "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 "setuid" | "seteuid" | "setgid" | "setegid" => {
728 let id = super::arg_num(args, 0);
729 if id.is_finite() {
730 let id = id as u32;
731 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 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 unsafe {
758 libc::initgroups(c.as_ptr(), gid as _);
759 }
760 }
761 Ok(Value::Undef)
762 }
763
764 "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
816fn env_object() -> Value {
818 with_host(|h| {
819 let mut m = IndexMap::new();
820 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
832static ARGV: std::sync::OnceLock<(Vec<String>, Vec<String>)> = std::sync::OnceLock::new();
838
839pub 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 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
862static 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
871fn 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
887fn 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
904fn 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
914fn 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 let is_tty = unsafe { libc::isatty(fd) == 1 };
924 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 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
945pub 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 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 "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 "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 "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 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#[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 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 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
1071pub fn memory_usage_rss() -> Value {
1073 Value::Float(resident_bytes().unwrap_or(0) as f64)
1074}
1075
1076pub 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
1096pub 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
1112fn 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
1153fn 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
1161fn 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
1168fn tty_control(method: &str, args: &[Value]) -> String {
1170 match method {
1171 "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" => {
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" => 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 _ => "\x1b[0J".into(),
1209 }
1210}
1211
1212fn supplementary_groups() -> Vec<f64> {
1214 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
1230fn 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
1239fn get_rusage() -> Option<libc::rusage> {
1241 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
1248fn tv_micros(t: &libc::timeval) -> f64 {
1250 t.tv_sec as f64 * 1e6 + t.tv_usec as f64
1251}
1252
1253fn 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
1290fn 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
1304fn 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 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
1349fn 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
1380fn 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#[derive(Default)]
1399struct Stdin {
1400 listeners: Vec<(String, Value, bool)>,
1402 encoding: Option<String>,
1404 partial: Vec<u8>,
1406 pumping: bool,
1408 paused: bool,
1410 flowing: bool,
1411 readable_mode: bool,
1412 buffered: std::collections::VecDeque<Value>,
1414 waiters: std::collections::VecDeque<u32>,
1415 iterating: bool,
1416 ended: bool,
1417 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
1429fn 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
1467fn 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
1493fn 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
1512fn 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
1531fn 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
1559fn 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 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
1604fn stdin_value() -> Value {
1606 constant("stdin").unwrap_or(Value::Undef)
1607}
1608
1609fn 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 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
1736pub 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 "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}