Skip to main content

nodejs/stdlib/
fs.rs

1//! Node `fs` module: synchronous file operations, the async callback forms, and
2//! the file-descriptor / directory / stream / watcher surfaces.
3//!
4//! Path operations map straight onto `std::fs`; descriptor operations
5//! (`open`/`read`/`write`/`fstat`/…) keep a thread-local table of open
6//! `std::fs::File`s keyed by a synthetic integer fd (starting at 3, after the
7//! stdio fds). Ownership / timestamp / statvfs operations that `std::fs` does not
8//! cover use `libc` directly (all targets are unix). Async callback variants run
9//! the same synchronous work then schedule the callback as a microtask, matching
10//! Node's ordering for simple scripts.
11
12use super::{arg_num, arg_str, native_tag};
13use crate::host::{invoke, with_host, JsObj};
14use fusevm::Value;
15use indexmap::IndexMap;
16use std::cell::RefCell;
17use std::collections::HashMap;
18use std::ffi::CString;
19use std::fs::File;
20use std::io::{Read, Write};
21use std::os::unix::fs::{MetadataExt, PermissionsExt};
22use std::os::unix::io::AsRawFd;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::Arc;
26use std::time::{Duration, UNIX_EPOCH};
27
28pub const METHODS: &[&str] = &[
29    // path — sync
30    "readFileSync",
31    "writeFileSync",
32    "appendFileSync",
33    "existsSync",
34    "readdirSync",
35    "mkdirSync",
36    "rmdirSync",
37    "unlinkSync",
38    "rmSync",
39    "statSync",
40    "lstatSync",
41    "statfsSync",
42    "accessSync",
43    "chmodSync",
44    "chownSync",
45    "lchownSync",
46    "copyFileSync",
47    "cpSync",
48    "linkSync",
49    "symlinkSync",
50    "readlinkSync",
51    "realpathSync",
52    "renameSync",
53    "truncateSync",
54    "utimesSync",
55    "lutimesSync",
56    "mkdtempSync",
57    "opendirSync",
58    "globSync",
59    // fd — sync
60    "openSync",
61    "closeSync",
62    "readSync",
63    "writeSync",
64    "readvSync",
65    "writevSync",
66    "fstatSync",
67    "fchmodSync",
68    "fchownSync",
69    "ftruncateSync",
70    "futimesSync",
71    "fsyncSync",
72    "fdatasyncSync",
73    // path — async (callback)
74    "readFile",
75    "writeFile",
76    "appendFile",
77    "readdir",
78    "mkdir",
79    "rmdir",
80    "rm",
81    "unlink",
82    "stat",
83    "lstat",
84    "statfs",
85    "access",
86    "chmod",
87    "chown",
88    "lchown",
89    "copyFile",
90    "cp",
91    "link",
92    "symlink",
93    "readlink",
94    "realpath",
95    "rename",
96    "truncate",
97    "utimes",
98    "lutimes",
99    "mkdtemp",
100    "opendir",
101    "glob",
102    "exists",
103    // fd — async (callback)
104    "open",
105    "close",
106    "read",
107    "write",
108    "readv",
109    "writev",
110    "fstat",
111    "fchmod",
112    "fchown",
113    "ftruncate",
114    "futimes",
115    "fsync",
116    "fdatasync",
117    // watchers + streams
118    "watchFile",
119    "unwatchFile",
120    "createReadStream",
121    "createWriteStream",
122];
123
124// ── file-descriptor table ────────────────────────────────────────────────────
125
126thread_local! {
127    static FD_TABLE: RefCell<HashMap<i32, File>> = RefCell::new(HashMap::new());
128    static NEXT_FD: RefCell<i32> = const { RefCell::new(3) };
129    static WATCHERS: RefCell<Vec<WatchEntry>> = const { RefCell::new(Vec::new()) };
130    static NEXT_WATCH_ID: RefCell<u64> = const { RefCell::new(1) };
131}
132
133struct WatchEntry {
134    // Reserved for a future StatWatcher handle; assigned but not yet read.
135    #[allow(dead_code)]
136    id: u64,
137    path: String,
138    listener: Value,
139    stop: Arc<AtomicBool>,
140}
141
142fn register_fd(file: File) -> i32 {
143    NEXT_FD.with(|n| {
144        let fd = *n.borrow();
145        *n.borrow_mut() = fd + 1;
146        FD_TABLE.with(|t| t.borrow_mut().insert(fd, file));
147        fd
148    })
149}
150
151fn with_file<R>(fd: i32, f: impl FnOnce(&File) -> R) -> Option<R> {
152    if FD_TABLE.with(|t| t.borrow().contains_key(&fd)) {
153        return FD_TABLE.with(|t| t.borrow().get(&fd).map(f));
154    }
155    // The process's own stdin/stdout/stderr are descriptors 0–2 in node too:
156    // `fs.writeSync(1, s)` writes to stdout and `fs.fstatSync(0)` stats stdin.
157    // They are never in the table (nothing here opened them), so they are
158    // borrowed for the one call — `ManuallyDrop`, so the borrow never closes
159    // the real descriptor.
160    if (0..=2).contains(&fd) {
161        use std::os::unix::io::FromRawFd;
162        let file = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(fd) });
163        return Some(f(&file));
164    }
165    None
166}
167
168/// The file descriptor an fs call names when its first argument is a number
169/// rather than a path.
170fn fd_arg(v: Option<&Value>) -> Option<i32> {
171    match v? {
172        Value::Int(n) => Some(*n as i32),
173        Value::Float(n) if n.fract() == 0.0 => Some(*n as i32),
174        _ => None,
175    }
176}
177
178/// Everything left to read on `fd`: standard input for `0`, otherwise a
179/// descriptor `openSync` handed out. `fstat` is the call node fails on for an
180/// unknown descriptor.
181fn read_fd_to_end(fd: i32) -> Result<Vec<u8>, String> {
182    let mut out = Vec::new();
183    let r = if fd == 0 {
184        // Through Rust's shared stdin buffer, so a read here and a
185        // `readline` read of the same input never skip each other's bytes.
186        crate::host::with_stdin_reader(|r| r.read_to_end(&mut out))
187    } else {
188        match with_file(fd, |file| {
189            let mut fr: &File = file;
190            fr.read_to_end(&mut out)
191        }) {
192            Some(r) => r,
193            None => return Err("Error: EBADF: bad file descriptor, fstat".to_string()),
194        }
195    };
196    r.map(|_| out).map_err(|e| err_str("read", "", &e))
197}
198
199fn close_fd(fd: i32) -> bool {
200    FD_TABLE.with(|t| t.borrow_mut().remove(&fd).is_some())
201}
202
203// ── dispatch ─────────────────────────────────────────────────────────────────
204
205pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
206    let op = method.strip_suffix("Sync").unwrap_or(method);
207    // `existsSync` reports an unusable path as absent rather than throwing.
208    if op == "exists" {
209        if let Err(e) = validated_paths("exists", args) {
210            // A wrongly-TYPED path to `existsSync` is deprecated (DEP0187),
211            // announced once; a string with a NUL is merely absent.
212            if method == "existsSync" && e.contains("[ERR_INVALID_ARG_TYPE]") {
213                super::process::emit_deprecation_warning(
214                    "DEP0187",
215                    "Passing invalid argument types to fs.existsSync is deprecated",
216                );
217            }
218            return Some(match method {
219                "existsSync" => Ok(Value::Bool(false)),
220                _ => exists_async(&[Value::Undef, args.get(1).cloned().unwrap_or(Value::Undef)]),
221            });
222        }
223    }
224    let normalized = match validated_paths(op, args) {
225        Ok(Some(a)) => a,
226        Ok(None) => args.to_vec(),
227        Err(e) => return Some(Err(e)),
228    };
229    let args = normalized.as_slice();
230    if let Err(e) = validate_call(op, args) {
231        return Some(Err(e));
232    }
233    Some(match method {
234        // ── path, sync ──
235        "readFileSync" => read_file_sync(args),
236        "writeFileSync" => write_file_impl(args),
237        "appendFileSync" => append_file_impl(args),
238        "existsSync" => Ok(Value::Bool(Path::new(&arg_str(args, 0)).exists())),
239        "readdirSync" => readdir_impl(args),
240        "mkdirSync" => mkdir_impl(args),
241        "rmdirSync" | "unlinkSync" | "rmSync" => rm_impl(method, args),
242        "statSync" => stat_impl("statSync", args, true),
243        "lstatSync" => stat_impl("lstatSync", args, false),
244        "statfsSync" => statfs_impl(args),
245        "accessSync" => access_impl(args),
246        "chmodSync" => chmod_impl(args),
247        "chownSync" => chown_impl(args, true),
248        "lchownSync" => chown_impl(args, false),
249        "copyFileSync" => copy_file_impl(args),
250        "cpSync" => cp_impl(args),
251        "linkSync" => link_impl(args),
252        "symlinkSync" => symlink_impl(args),
253        "readlinkSync" => readlink_impl(args),
254        "realpathSync" => realpath_impl(args),
255        "renameSync" => rename_impl(args),
256        "truncateSync" => truncate_impl(args),
257        "utimesSync" => utimes_impl(args, true),
258        "lutimesSync" => utimes_impl(args, false),
259        "mkdtempSync" => mkdtemp_impl(args),
260        "opendirSync" => opendir_impl(args),
261        "globSync" => glob_impl(args),
262        // ── fd, sync ──
263        "openSync" => open_impl(args),
264        "closeSync" => close_impl(args),
265        "readSync" => read_impl(args).map(|n| Value::Float(n as f64)),
266        "writeSync" => write_impl(args).map(|n| Value::Float(n as f64)),
267        "readvSync" => readv_impl(args).map(|n| Value::Float(n as f64)),
268        "writevSync" => writev_impl(args).map(|n| Value::Float(n as f64)),
269        "fstatSync" => fstat_impl(args),
270        "fchmodSync" => fchmod_impl(args),
271        "fchownSync" => fchown_impl(args),
272        "ftruncateSync" => ftruncate_impl(args),
273        "futimesSync" => futimes_impl(args),
274        "fsyncSync" => fsync_impl(args, false),
275        "fdatasyncSync" => fsync_impl(args, true),
276        // ── path, async ──
277        "readFile" => return Some(read_file_async(args)),
278        "writeFile" => async_cb(args, write_file_impl(args)),
279        "appendFile" => async_cb(args, append_file_impl(args)),
280        "readdir" => async_cb(args, readdir_impl(args)),
281        "mkdir" => async_cb(args, mkdir_impl(args)),
282        "rmdir" => async_cb(args, rm_impl("rmdir", args)),
283        "rm" => async_cb(args, rm_impl("rm", args)),
284        "unlink" => async_cb(args, rm_impl("unlink", args)),
285        "stat" => async_cb(args, stat_impl("stat", args, true)),
286        "lstat" => async_cb(args, stat_impl("lstat", args, false)),
287        "statfs" => async_cb(args, statfs_impl(args)),
288        "access" => async_cb(args, access_impl(args)),
289        "chmod" => async_cb(args, chmod_impl(args)),
290        "chown" => async_cb(args, chown_impl(args, true)),
291        "lchown" => async_cb(args, chown_impl(args, false)),
292        "copyFile" => async_cb(args, copy_file_impl(args)),
293        "cp" => async_cb(args, cp_impl(args)),
294        "link" => async_cb(args, link_impl(args)),
295        "symlink" => async_cb(args, symlink_impl(args)),
296        "readlink" => async_cb(args, readlink_impl(args)),
297        "realpath" => async_cb(args, realpath_impl(args)),
298        "rename" => async_cb(args, rename_impl(args)),
299        "truncate" => async_cb(args, truncate_impl(args)),
300        "utimes" => async_cb(args, utimes_impl(args, true)),
301        "lutimes" => async_cb(args, utimes_impl(args, false)),
302        "mkdtemp" => async_cb(args, mkdtemp_impl(args)),
303        "opendir" => async_cb(args, opendir_impl(args)),
304        "glob" => async_cb(args, glob_impl(args)),
305        "exists" => exists_async(args),
306        // ── fd, async ──
307        "open" => async_cb(args, open_impl(args)),
308        "close" => async_cb(args, close_impl(args)),
309        "read" => read_async(args),
310        "write" => return Some(read_write_async(args, write_impl(args))),
311        "readv" => async_cb(args, readv_impl(args).map(|n| Value::Float(n as f64))),
312        "writev" => async_cb(args, writev_impl(args).map(|n| Value::Float(n as f64))),
313        "fstat" => async_cb(args, fstat_impl(args)),
314        "fchmod" => async_cb(args, fchmod_impl(args)),
315        "fchown" => async_cb(args, fchown_impl(args)),
316        "ftruncate" => async_cb(args, ftruncate_impl(args)),
317        "futimes" => async_cb(args, futimes_impl(args)),
318        "fsync" => async_cb(args, fsync_impl(args, false)),
319        "fdatasync" => async_cb(args, fsync_impl(args, true)),
320        // ── watchers + streams ──
321        "watchFile" => watch_file(args),
322        "unwatchFile" => unwatch_file(args),
323        "createReadStream" => create_read_stream(args),
324        "createWriteStream" => create_write_stream(args),
325        _ => return None,
326    })
327}
328
329// ── async callback plumbing ──────────────────────────────────────────────────
330
331/// Schedule the trailing callback as a microtask: `cb(null, value)` on success,
332/// `cb(err)` (an error string, matching the existing `readFile`/`writeFile`
333/// callbacks) on failure. Always returns `undefined` (the method's own result).
334fn async_cb(args: &[Value], result: Result<Value, String>) -> Result<Value, String> {
335    let Some(cb) = args.last().cloned().filter(is_fn) else {
336        return Ok(Value::Undef);
337    };
338    match result {
339        Ok(v) => with_host(|h| {
340            let n = h.null();
341            h.queue_io_callback(cb, vec![n, v]);
342        }),
343        // An error-first callback is handed an ERROR OBJECT, not the message:
344        // `fs.stat(missing, (err) => …)` gives an `err` carrying `code`,
345        // `syscall`, `path` and `errno`, and `err.code === 'ENOENT'` is the most
346        // common check in node code. A bare string made every one of those
347        // `undefined` — and `err.message` too, so even printing it said
348        // `undefined`. The promise forms already built the object.
349        Err(e) => with_host(|h| {
350            let ev = crate::builtins::synth_error(h, &e);
351            h.queue_io_callback(cb, vec![ev]);
352        }),
353    }
354    Ok(Value::Undef)
355}
356
357/// `read`/`write` callbacks carry a third argument: `cb(err, count, buffer)`.
358fn read_write_async(args: &[Value], result: Result<usize, String>) -> Result<Value, String> {
359    let Some(cb) = args.last().cloned().filter(is_fn) else {
360        return Ok(Value::Undef);
361    };
362    let buffer = args.get(1).cloned().unwrap_or(Value::Undef);
363    match result {
364        Ok(n) => with_host(|h| {
365            let nul = h.null();
366            h.queue_io_callback(cb, vec![nul, Value::Float(n as f64), buffer]);
367        }),
368        Err(e) => with_host(|h| {
369            let ev = crate::builtins::synth_error(h, &e);
370            h.queue_io_callback(cb, vec![ev]);
371        }),
372    }
373    Ok(Value::Undef)
374}
375
376fn is_fn(v: &Value) -> bool {
377    with_host(|h| crate::host::is_callable(h, v))
378}
379
380// ── read/write/append ────────────────────────────────────────────────────────
381
382fn read_file_sync(args: &[Value]) -> Result<Value, String> {
383    let enc = encoding_arg(args, 1);
384    // A NUMBER is a file descriptor, read from its current position to the
385    // end: `readFileSync(0, 'utf8')` is how a script slurps its stdin. The
386    // number was stringified and opened as a path, so that was `ENOENT ... '0'`.
387    if let Some(fd) = fd_arg(args.first()) {
388        let bytes = read_fd_to_end(fd)?;
389        return Ok(match enc {
390            Some(e) => with_host(|h| h.new_str(super::buffer::encode_bytes(&bytes, &e))),
391            None => super::buffer::pooled(&bytes),
392        });
393    }
394    let path = arg_str(args, 0);
395
396    match std::fs::read(&path) {
397        // The encoding names the REPRESENTATION to return, not just "decode as
398        // text": `readFileSync(p, 'hex')` gives the hex digits of the file, and
399        // `'base64'` its base64. Every encoding used to come back as the raw
400        // UTF-8 text.
401        // node reads into `Buffer.allocUnsafe(size)`, a slice of the pool.
402        Ok(bytes) => Ok(match enc {
403            Some(e) => with_host(|h| h.new_str(super::buffer::encode_bytes(&bytes, &e))),
404            None => super::buffer::pooled(&bytes),
405        }),
406        // A DIRECTORY opens fine and fails at the `read`, which is the syscall
407        // node names — and it names no path there, because the descriptor no
408        // longer carries one. This reported `open '<dir>'`, an operation that
409        // had in fact succeeded.
410        // The raw errno rather than `ErrorKind::IsADirectory`, which is stable
411        // only since 1.83 and this crate's MSRV is 1.80.
412        Err(e) if e.raw_os_error() == Some(libc::EISDIR) => Err(err_str("read", "", &e)),
413        Err(e) => Err(err_str("readFileSync", &path, &e)),
414    }
415}
416
417/// The bytes a `writeFileSync`/`appendFileSync` should put on disk.
418///
419/// When an encoding is given, the DATA STRING is in that encoding and has to be
420/// decoded first — `writeFileSync(p, '68656c6c6f', 'hex')` writes `hello`, five
421/// bytes, not the ten digits. The encoding argument was ignored, so the digits
422/// themselves were written. A Buffer argument carries its own bytes and is
423/// unaffected.
424fn encoded_bytes(args: &[Value]) -> Vec<u8> {
425    let v = args.get(1).cloned().unwrap_or(Value::Undef);
426    // Any byte VIEW writes its bytes; only a string goes through the encoding.
427    // The Buffer case alone was handled, so `writeFileSync(p, new Uint8Array(…))`
428    // wrote the text `[object Object]`.
429    if let Some(bytes) = super::buffer::view_bytes(&v) {
430        return bytes;
431    }
432    let text = with_host(|h| h.str_of(&v));
433    match encoding_arg(args, 2) {
434        Some(e) => super::buffer::decode_str(&text, &e),
435        None => text.into_bytes(),
436    }
437}
438
439fn write_file_impl(args: &[Value]) -> Result<Value, String> {
440    let path = arg_str(args, 0);
441    let data = encoded_bytes(args);
442    match std::fs::write(&path, data) {
443        Ok(_) => Ok(Value::Undef),
444        Err(e) => Err(err_str("writeFile", &path, &e)),
445    }
446}
447
448fn append_file_impl(args: &[Value]) -> Result<Value, String> {
449    let path = arg_str(args, 0);
450    let data = encoded_bytes(args);
451    let r = std::fs::OpenOptions::new()
452        .create(true)
453        .append(true)
454        .open(&path)
455        .and_then(|mut f| f.write_all(&data));
456    match r {
457        Ok(_) => Ok(Value::Undef),
458        Err(e) => Err(err_str("appendFile", &path, &e)),
459    }
460}
461
462fn read_file_async(args: &[Value]) -> Result<Value, String> {
463    let path = arg_str(args, 0);
464    let Some(cb) = args.last().cloned().filter(is_fn) else {
465        return Ok(Value::Undef);
466    };
467    let enc = if args.len() >= 3 {
468        encoding_arg(args, 1)
469    } else {
470        None
471    };
472    let (err, data) = match std::fs::read(&path) {
473        Ok(bytes) => (
474            with_host(|h| h.null()),
475            // Same representation rule as the sync read: the encoding names
476            // what to return, so `readFile(p, 'hex', cb)` hands the callback
477            // hex digits.
478            match enc {
479                Some(e) => with_host(|h| h.new_str(super::buffer::encode_bytes(&bytes, &e))),
480                None => super::buffer::from_bytes(&bytes),
481            },
482        ),
483        Err(e) => (
484            // An ERROR OBJECT, as every error-first callback receives — see
485            // `async_cb`; this path built its own and handed over a string.
486            with_host(|h| {
487                // The ASYNC form names the path where the sync one does not:
488                // node's `fs.readFile(dir, cb)` reports `read '<dir>'` and
489                // `fs.readFileSync(dir)` reports a bare `read`. Measured, not
490                // assumed — the two really do differ.
491                let msg = if e.raw_os_error() == Some(libc::EISDIR) {
492                    err_str("read", &path, &e)
493                } else {
494                    err_str("readFile", &path, &e)
495                };
496                crate::builtins::synth_error(h, &msg)
497            }),
498            Value::Undef,
499        ),
500    };
501    with_host(|h| h.queue_io_callback(cb, vec![err, data]));
502    Ok(Value::Undef)
503}
504
505fn exists_async(args: &[Value]) -> Result<Value, String> {
506    let path = arg_str(args, 0);
507    let Some(cb) = args.last().cloned().filter(is_fn) else {
508        return Ok(Value::Undef);
509    };
510    let ex = Path::new(&path).exists();
511    with_host(|h| h.queue_io_callback(cb, vec![Value::Bool(ex)]));
512    Ok(Value::Undef)
513}
514
515// ── directories ──────────────────────────────────────────────────────────────
516
517fn mkdir_impl(args: &[Value]) -> Result<Value, String> {
518    let path = arg_str(args, 0);
519    let recursive = opt_flag(args, "recursive");
520    let r = if recursive {
521        std::fs::create_dir_all(&path)
522    } else {
523        std::fs::create_dir(&path)
524    };
525    match r {
526        Ok(_) => Ok(Value::Undef),
527        Err(e) => Err(err_str("mkdir", &path, &e)),
528    }
529}
530
531fn rm_impl(op: &str, args: &[Value]) -> Result<Value, String> {
532    let path = arg_str(args, 0);
533    let p = Path::new(&path);
534    let force = opt_flag(args, "force");
535    let r = if p.is_dir() {
536        if opt_flag(args, "recursive") {
537            std::fs::remove_dir_all(p)
538        } else {
539            std::fs::remove_dir(p)
540        }
541    } else {
542        std::fs::remove_file(p)
543    };
544    match r {
545        Ok(_) => Ok(Value::Undef),
546        Err(e) if force && e.kind() == std::io::ErrorKind::NotFound => Ok(Value::Undef),
547        Err(e) => Err(err_str(op, &path, &e)),
548    }
549}
550
551fn readdir_impl(args: &[Value]) -> Result<Value, String> {
552    let path = arg_str(args, 0);
553    let file_types = opt_flag(args, "withFileTypes");
554    let recursive = opt_flag(args, "recursive");
555    let mut names: Vec<(String, String, std::fs::FileType)> = Vec::new();
556    collect_dir(Path::new(&path), &path, "", recursive, &mut names)
557        .map_err(|e| err_str("readdir", &path, &e))?;
558    names.sort_by(|a, b| a.0.cmp(&b.0));
559    Ok(with_host(|h| {
560        let items: Vec<Value> = names
561            .into_iter()
562            .map(|(rel, parent, ft)| {
563                if file_types {
564                    let base = rel.rsplit('/').next().unwrap_or(&rel).to_string();
565                    build_dirent(h, base, &parent, ft)
566                } else {
567                    h.new_str(rel)
568                }
569            })
570            .collect();
571        h.new_array(items)
572    }))
573}
574
575/// Collect directory entries. `rel_prefix` is the path (relative to the root)
576/// under which `dir`'s children are listed; `parent` is the absolute-ish parent
577/// path recorded on each `Dirent`.
578fn collect_dir(
579    dir: &Path,
580    parent: &str,
581    rel_prefix: &str,
582    recursive: bool,
583    out: &mut Vec<(String, String, std::fs::FileType)>,
584) -> std::io::Result<()> {
585    for e in std::fs::read_dir(dir)? {
586        let e = e?;
587        let name = e.file_name().to_string_lossy().into_owned();
588        let rel = if rel_prefix.is_empty() {
589            name.clone()
590        } else {
591            format!("{rel_prefix}/{name}")
592        };
593        let ft = e.file_type()?;
594        out.push((rel.clone(), parent.to_string(), ft));
595        if recursive && ft.is_dir() {
596            let sub = e.path();
597            let sub_parent = sub.to_string_lossy().into_owned();
598            collect_dir(&sub, &sub_parent, &rel, recursive, out)?;
599        }
600    }
601    Ok(())
602}
603
604fn opendir_impl(args: &[Value]) -> Result<Value, String> {
605    let path = arg_str(args, 0);
606    let rd = std::fs::read_dir(&path).map_err(|e| err_str("opendir", &path, &e))?;
607    let mut entries: Vec<(String, std::fs::FileType)> = rd
608        .filter_map(|e| e.ok())
609        .filter_map(|e| {
610            e.file_type()
611                .ok()
612                .map(|ft| (e.file_name().to_string_lossy().into_owned(), ft))
613        })
614        .collect();
615    entries.sort_by(|a, b| a.0.cmp(&b.0));
616    Ok(with_host(|h| {
617        let dirents: Vec<Value> = entries
618            .into_iter()
619            .map(|(name, ft)| build_dirent(h, name, &path, ft))
620            .collect();
621        let arr = h.new_array(dirents);
622        let mut m = IndexMap::new();
623        m.insert("@@native".into(), h.new_str("Dir"));
624        m.insert("path".into(), h.new_str(path.clone()));
625        m.insert("@@entries".into(), arr);
626        m.insert("@@pos".into(), Value::Float(0.0));
627        h.new_object(m)
628    }))
629}
630
631// ── ownership / permissions / timestamps ─────────────────────────────────────
632
633fn access_impl(args: &[Value]) -> Result<Value, String> {
634    let path = arg_str(args, 0);
635    match std::fs::metadata(&path) {
636        Ok(_) => Ok(Value::Undef),
637        Err(e) => Err(err_str("access", &path, &e)),
638    }
639}
640
641fn chmod_impl(args: &[Value]) -> Result<Value, String> {
642    let path = arg_str(args, 0);
643    let mode = parse_file_mode(args.get(1).unwrap_or(&Value::Undef), "mode", None)?;
644    match std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)) {
645        Ok(_) => Ok(Value::Undef),
646        Err(e) => Err(err_str("chmod", &path, &e)),
647    }
648}
649
650fn chown_impl(args: &[Value], follow: bool) -> Result<Value, String> {
651    let path = arg_str(args, 0);
652    let uid = arg_num(args, 1) as libc::uid_t;
653    let gid = arg_num(args, 2) as libc::gid_t;
654    let c = cpath(&path, "chown")?;
655    let rc = unsafe {
656        if follow {
657            libc::chown(c.as_ptr(), uid, gid)
658        } else {
659            libc::lchown(c.as_ptr(), uid, gid)
660        }
661    };
662    ok_or_errno(rc, "chown", &path)
663}
664
665fn utimes_impl(args: &[Value], follow: bool) -> Result<Value, String> {
666    let path = arg_str(args, 0);
667    let times = [
668        to_timeval(time_secs(args, 1)),
669        to_timeval(time_secs(args, 2)),
670    ];
671    let c = cpath(&path, "utimes")?;
672    let rc = unsafe {
673        if follow {
674            libc::utimes(c.as_ptr(), times.as_ptr())
675        } else {
676            libc::lutimes(c.as_ptr(), times.as_ptr())
677        }
678    };
679    ok_or_errno(rc, "utimes", &path)
680}
681
682// ── copy / link / rename / truncate ──────────────────────────────────────────
683
684const COPYFILE_EXCL: u32 = 1;
685
686fn copy_file_impl(args: &[Value]) -> Result<Value, String> {
687    let src = arg_str(args, 0);
688    let dest = arg_str(args, 1);
689    let mode = arg_num(args, 2);
690    if !mode.is_nan() && (mode as u32) & COPYFILE_EXCL != 0 && Path::new(&dest).exists() {
691        return Err(format!(
692            "Error: EEXIST: file already exists, copyfile '{src}' -> '{dest}'"
693        ));
694    }
695    match std::fs::copy(&src, &dest) {
696        Ok(_) => Ok(Value::Undef),
697        Err(e) => Err(err_str2("copyFile", &src, &dest, &e)),
698    }
699}
700
701fn cp_impl(args: &[Value]) -> Result<Value, String> {
702    let src = arg_str(args, 0);
703    let dest = arg_str(args, 1);
704    let recursive = opt_flag(args, "recursive");
705    let r = if recursive {
706        cp_recursive(Path::new(&src), Path::new(&dest))
707    } else {
708        std::fs::copy(&src, &dest).map(|_| ())
709    };
710    match r {
711        Ok(_) => Ok(Value::Undef),
712        Err(e) => Err(err_str("cp", &src, &e)),
713    }
714}
715
716fn cp_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
717    if src.is_dir() {
718        std::fs::create_dir_all(dest)?;
719        for e in std::fs::read_dir(src)? {
720            let e = e?;
721            cp_recursive(&e.path(), &dest.join(e.file_name()))?;
722        }
723        Ok(())
724    } else {
725        if let Some(parent) = dest.parent() {
726            std::fs::create_dir_all(parent).ok();
727        }
728        std::fs::copy(src, dest).map(|_| ())
729    }
730}
731
732fn link_impl(args: &[Value]) -> Result<Value, String> {
733    let existing = arg_str(args, 0);
734    let new = arg_str(args, 1);
735    match std::fs::hard_link(&existing, &new) {
736        Ok(_) => Ok(Value::Undef),
737        Err(e) => Err(err_str("link", &existing, &e)),
738    }
739}
740
741fn symlink_impl(args: &[Value]) -> Result<Value, String> {
742    let target = arg_str(args, 0);
743    let path = arg_str(args, 1);
744    match std::os::unix::fs::symlink(&target, &path) {
745        Ok(_) => Ok(Value::Undef),
746        Err(e) => Err(err_str("symlink", &path, &e)),
747    }
748}
749
750fn readlink_impl(args: &[Value]) -> Result<Value, String> {
751    let path = arg_str(args, 0);
752    match std::fs::read_link(&path) {
753        Ok(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().into_owned()))),
754        Err(e) => Err(err_str("readlink", &path, &e)),
755    }
756}
757
758fn realpath_impl(args: &[Value]) -> Result<Value, String> {
759    let path = arg_str(args, 0);
760    match std::fs::canonicalize(&path) {
761        Ok(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().into_owned()))),
762        // The message names the path as far as it was RESOLVED before the walk
763        // failed — on macOS `/var` is a symlink, so node reports
764        // `/private/var/…` where the caller wrote `/var/…`. Reporting the
765        // argument verbatim names a path the failing `lstat` never saw.
766        Err(e) => Err(err_str("realpath", &resolved_prefix(&path), &e)),
767    }
768}
769
770/// `path` with its deepest EXISTING ancestor canonicalized and the rest of the
771/// components appended — what `realpath(3)` has resolved at the point it gives
772/// up.
773fn resolved_prefix(path: &str) -> String {
774    let p = Path::new(path);
775    let mut rest: Vec<&std::ffi::OsStr> = Vec::new();
776    let mut cur = p;
777    loop {
778        if let Ok(base) = std::fs::canonicalize(cur) {
779            let mut out = base;
780            for part in rest.iter().rev() {
781                out.push(part);
782            }
783            return out.to_string_lossy().into_owned();
784        }
785        match (cur.file_name(), cur.parent()) {
786            (Some(name), Some(parent)) if !parent.as_os_str().is_empty() => {
787                rest.push(name);
788                cur = parent;
789            }
790            _ => return path.to_string(),
791        }
792    }
793}
794
795fn rename_impl(args: &[Value]) -> Result<Value, String> {
796    let from = arg_str(args, 0);
797    let to = arg_str(args, 1);
798    match std::fs::rename(&from, &to) {
799        Ok(_) => Ok(Value::Undef),
800        Err(e) => Err(err_str2("rename", &from, &to, &e)),
801    }
802}
803
804fn truncate_impl(args: &[Value]) -> Result<Value, String> {
805    let path = arg_str(args, 0);
806    let len = arg_num(args, 1);
807    let len = if len.is_nan() { 0 } else { len as u64 };
808    let r = std::fs::OpenOptions::new()
809        .write(true)
810        .open(&path)
811        .and_then(|f| f.set_len(len));
812    match r {
813        Ok(_) => Ok(Value::Undef),
814        // The failure is in the `open` this does first, which is the syscall
815        // node names — `truncate` only appears once a descriptor exists.
816        Err(e) => Err(err_str("open", &path, &e)),
817    }
818}
819
820fn mkdtemp_impl(args: &[Value]) -> Result<Value, String> {
821    let prefix = arg_str(args, 0);
822    for _ in 0..64 {
823        let candidate = format!("{prefix}{}", random_suffix());
824        match std::fs::create_dir(&candidate) {
825            Ok(_) => return Ok(with_host(|h| h.new_str(candidate))),
826            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
827            Err(e) => return Err(err_str("mkdtemp", &prefix, &e)),
828        }
829    }
830    Err(format!(
831        "Error: EEXIST: file already exists, mkdtemp '{prefix}'"
832    ))
833}
834
835/// Six random `[0-9A-Za-z]` characters — Node's `mkdtemp` suffix alphabet.
836fn random_suffix() -> String {
837    const CHARS: &[u8; 62] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
838    let mut raw = [0u8; 6];
839    if getrandom::getrandom(&mut raw).is_err() {
840        // Fall back to a clock-derived seed; uniqueness is retried by the caller.
841        let nanos = std::time::SystemTime::now()
842            .duration_since(UNIX_EPOCH)
843            .map(|d| d.subsec_nanos())
844            .unwrap_or(0);
845        raw = nanos
846            .to_le_bytes()
847            .iter()
848            .cycle()
849            .take(6)
850            .copied()
851            .collect::<Vec<_>>()
852            .try_into()
853            .unwrap();
854    }
855    raw.iter()
856        .map(|b| CHARS[(*b as usize) % 62] as char)
857        .collect()
858}
859
860// ── argument validation for the descriptor and mode calls ────────────────────
861//
862// node checks these in JavaScript (`lib/fs.js`, `internal/fs/utils.js`,
863// `internal/validators.js`) and then in the binding (`fd`), always BEFORE any
864// I/O, and a callback form throws them synchronously rather than handing them
865// to the callback. They used to be read with an infallible `ToNumber`: a
866// string mode `'644'` set permissions 0o1204, `writeSync(fd, {})` wrote the 15
867// bytes of `[object Object]`, and an unknown flag string opened read-only.
868
869/// The checks one call makes before its I/O, in node's order. `op` is the API
870/// name without `Sync`; a FUNCTION in an optional position is the callback of
871/// the async form, not the argument.
872fn validate_call(op: &str, args: &[Value]) -> Result<(), String> {
873    let arg = |i: usize| match args.get(i) {
874        Some(v) if !is_fn(v) => v.clone(),
875        _ => Value::Undef,
876    };
877    match op {
878        "open" => {
879            string_to_flags(&arg(1))?;
880            parse_file_mode(&arg(2), "mode", Some(0o666))?;
881        }
882        "chmod" => {
883            parse_file_mode(&arg(1), "mode", None)?;
884        }
885        "utimes" | "lutimes" => {
886            to_unix_timestamp(&arg(1), "atime")?;
887            to_unix_timestamp(&arg(2), "mtime")?;
888        }
889        "close" | "fstat" | "fsync" | "fdatasync" => {
890            validate_fd(&arg(0))?;
891        }
892        "fchmod" => {
893            parse_file_mode(&arg(1), "mode", None)?;
894            validate_fd(&arg(0))?;
895        }
896        "fchown" => {
897            validate_id(&arg(1), "uid")?;
898            validate_id(&arg(2), "gid")?;
899            validate_fd(&arg(0))?;
900        }
901        "futimes" => {
902            to_unix_timestamp(&arg(1), "atime")?;
903            to_unix_timestamp(&arg(2), "mtime")?;
904            validate_fd(&arg(0))?;
905        }
906        "ftruncate" => {
907            let len = arg(1);
908            if !matches!(len, Value::Undef) {
909                super::validate_integer_in(&len, "len", -MAX_SAFE, MAX_SAFE)?;
910            }
911            validate_fd(&arg(0))?;
912        }
913        "readv" | "writev" => {
914            validate_buffer_array(&arg(1))?;
915            validate_fd(&arg(0))?;
916        }
917        "write" => {
918            validate_write(args)?;
919            validate_fd(&arg(0))?;
920        }
921        _ => {}
922    }
923    Ok(())
924}
925
926const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
927
928/// The path parameters of each call: argument position, the name node's
929/// `getValidatedPath(value, name)` reports, and whether a descriptor NUMBER is
930/// accepted in its place (`readFileSync(0)`).
931fn path_params(op: &str) -> &'static [(usize, &'static str, bool)] {
932    match op {
933        "readFile" | "writeFile" | "appendFile" | "truncate" => &[(0, "path", true)],
934        "access" | "exists" | "chmod" | "chown" | "lchown" | "utimes" | "lutimes" | "mkdir"
935        | "open" | "opendir" | "readdir" | "readlink" | "realpath" | "rm" | "rmdir" | "stat"
936        | "lstat" | "statfs" | "unlink" | "watchFile" | "unwatchFile" => &[(0, "path", false)],
937        "copyFile" | "cp" => &[(0, "src", false), (1, "dest", false)],
938        "link" => &[(0, "existingPath", false), (1, "newPath", false)],
939        "symlink" => &[(0, "target", false), (1, "path", false)],
940        "rename" => &[(0, "oldPath", false), (1, "newPath", false)],
941        _ => &[],
942    }
943}
944
945/// `getValidatedPath` for each path parameter of `op`: a string, a
946/// `Uint8Array` (its bytes), or a `file:` URL (its path), with no NUL. The
947/// arguments come back with each path replaced by its string, or `None` when
948/// `op` takes no path. A URL or Buffer used to be stringified as
949/// `[object Object]` and a number or `undefined` opened as the file `5` /
950/// `undefined`.
951fn validated_paths(op: &str, args: &[Value]) -> Result<Option<Vec<Value>>, String> {
952    let params = path_params(op);
953    if params.is_empty() {
954        return Ok(None);
955    }
956    let mut out = args.to_vec();
957    for &(i, name, fd_ok) in params {
958        let v = args.get(i).cloned().unwrap_or(Value::Undef);
959        if fd_ok && matches!(v, Value::Float(_) | Value::Int(_)) {
960            continue;
961        }
962        let path = validated_path(&v, name)?;
963        if i < out.len() {
964            out[i] = with_host(|h| h.new_str(path));
965        }
966    }
967    Ok(Some(out))
968}
969
970fn validated_path(v: &Value, name: &str) -> Result<String, String> {
971    let tag = native_tag(v);
972    let (path, shown) = if tag.as_deref() == Some("URL") {
973        let s = super::url::file_url_to_path(std::slice::from_ref(v))?;
974        let shown = with_host(|h| h.new_str(s.clone()));
975        (s, shown)
976    } else if let Some(s) = with_host(|h| h.as_str(v)) {
977        (s, v.clone())
978    } else if is_uint8_array(v) {
979        let bytes = super::buffer::view_bytes(v).unwrap_or_default();
980        (String::from_utf8_lossy(&bytes).into_owned(), v.clone())
981    } else {
982        return Err(crate::host::coded_error(
983            "TypeError",
984            "ERR_INVALID_ARG_TYPE",
985            &format!(
986                "The \"{name}\" argument must be of type string or an instance of Buffer or URL. Received {}",
987                super::received_desc(v)
988            ),
989        ));
990    };
991    if path.contains('\0') {
992        let kind = if name.contains('.') {
993            "property"
994        } else {
995            "argument"
996        };
997        return Err(crate::host::coded_error(
998            "TypeError",
999            "ERR_INVALID_ARG_VALUE",
1000            &format!(
1001                "The {kind} '{name}' must be a string, Uint8Array, or URL without null bytes. Received {}",
1002                with_host(|h| h.inspect(&shown))
1003            ),
1004        ));
1005    }
1006    Ok(path)
1007}
1008
1009/// `isUint8Array`: a Buffer or a `Uint8Array` (not another element type).
1010fn is_uint8_array(v: &Value) -> bool {
1011    match native_tag(v).as_deref() {
1012        Some("Buffer") => true,
1013        Some("TypedArray") => super::typedarray::kind_of(v) == "Uint8Array",
1014        _ => false,
1015    }
1016}
1017
1018/// The binding's descriptor check, `validateInt32(fd, 'fd', 0)`.
1019fn validate_fd(v: &Value) -> Result<i32, String> {
1020    validate_int32(v, "fd", 0.0)
1021}
1022
1023/// `validateInt32(value, name, min)`: a Number, an integer, in `[min, 2³¹)`.
1024fn validate_int32(v: &Value, name: &str, min: f64) -> Result<i32, String> {
1025    if with_host(|h| h.type_of(v)) != "number" {
1026        return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
1027    }
1028    let n = with_host(|h| h.to_number(v));
1029    if n.fract() != 0.0 || !n.is_finite() {
1030        return Err(super::out_of_range(name, "an integer", n));
1031    }
1032    if n < min || n > 2_147_483_647.0 {
1033        let must = format!(">= {} && <= 2147483647", crate::host::fmt_number(min));
1034        return Err(super::out_of_range(name, &must, n));
1035    }
1036    Ok(n as i32)
1037}
1038
1039/// A `uid`/`gid`: `validateInteger(id, name, -1, kMaxUserId)`.
1040fn validate_id(v: &Value, name: &str) -> Result<i64, String> {
1041    super::validate_integer_in(v, name, -1.0, 4_294_967_295.0).map(|n| n as i64)
1042}
1043
1044/// `parseFileMode(value, name, def)`: an octal string or a 32-bit unsigned
1045/// integer, `def` standing in for `undefined`/`null`.
1046fn parse_file_mode(v: &Value, name: &str, def: Option<u32>) -> Result<u32, String> {
1047    let nullish = matches!(v, Value::Undef) || with_host(|h| h.is_null(v));
1048    let v = match (nullish, def) {
1049        (true, Some(d)) => Value::Float(d as f64),
1050        (true, None) => Value::Undef,
1051        (false, _) => v.clone(),
1052    };
1053    let mut v = v;
1054    if let Some(s) = with_host(|h| h.as_str(&v)) {
1055        if s.is_empty() || !s.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
1056            return Err(crate::host::coded_error(
1057                "TypeError",
1058                "ERR_INVALID_ARG_VALUE",
1059                &format!(
1060                    "The argument '{name}' must be a 32-bit unsigned integer or an octal string. Received {}",
1061                    with_host(|h| h.inspect(&v))
1062                ),
1063            ));
1064        }
1065        // `NumberParseInt(value, 8)`, then the range check below.
1066        let n = s.bytes().fold(0.0, |n, b| n * 8.0 + f64::from(b - b'0'));
1067        v = Value::Float(n);
1068    }
1069    if with_host(|h| h.type_of(&v)) != "number" {
1070        return Err(crate::host::invalid_arg_type(
1071            name, "argument", "number", &v,
1072        ));
1073    }
1074    let n = with_host(|h| h.to_number(&v));
1075    if n.fract() != 0.0 || !n.is_finite() {
1076        return Err(super::out_of_range(name, "an integer", n));
1077    }
1078    if !(0.0..=4_294_967_295.0).contains(&n) {
1079        return Err(super::out_of_range(name, ">= 0 && <= 4294967295", n));
1080    }
1081    Ok(n as u32)
1082}
1083
1084/// `stringToFlags(flags)`: a number is the `open(2)` flags themselves, a
1085/// nullish value is `O_RDONLY`, and the strings are node's fixed table.
1086fn string_to_flags(v: &Value) -> Result<libc::c_int, String> {
1087    use libc::{O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_SYNC, O_TRUNC, O_WRONLY};
1088    if with_host(|h| h.type_of(v)) == "number" {
1089        return validate_int32(v, "flags", -2_147_483_648.0);
1090    }
1091    if matches!(v, Value::Undef) || with_host(|h| h.is_null(v)) {
1092        return Ok(O_RDONLY);
1093    }
1094    let s = with_host(|h| h.as_str(v));
1095    Ok(match s.as_deref() {
1096        Some("r") => O_RDONLY,
1097        Some("rs" | "sr") => O_RDONLY | O_SYNC,
1098        Some("r+") => O_RDWR,
1099        Some("rs+" | "sr+") => O_RDWR | O_SYNC,
1100        Some("w") => O_TRUNC | O_CREAT | O_WRONLY,
1101        Some("wx" | "xw") => O_TRUNC | O_CREAT | O_WRONLY | O_EXCL,
1102        Some("w+") => O_TRUNC | O_CREAT | O_RDWR,
1103        Some("wx+" | "xw+") => O_TRUNC | O_CREAT | O_RDWR | O_EXCL,
1104        Some("a") => O_APPEND | O_CREAT | O_WRONLY,
1105        Some("ax" | "xa") => O_APPEND | O_CREAT | O_WRONLY | O_EXCL,
1106        Some("as" | "sa") => O_APPEND | O_CREAT | O_WRONLY | O_SYNC,
1107        Some("a+") => O_APPEND | O_CREAT | O_RDWR,
1108        Some("ax+" | "xa+") => O_APPEND | O_CREAT | O_RDWR | O_EXCL,
1109        Some("as+" | "sa+") => O_APPEND | O_CREAT | O_RDWR | O_SYNC,
1110        _ => {
1111            return Err(crate::host::coded_error(
1112                "TypeError",
1113                "ERR_INVALID_ARG_VALUE",
1114                &format!(
1115                    "The argument 'flags' is invalid. Received {}",
1116                    with_host(|h| h.inspect(v))
1117                ),
1118            ))
1119        }
1120    })
1121}
1122
1123/// `toUnixTimestamp(time, name)`: seconds from a numeric string, a finite
1124/// number (a negative one meaning NOW), or a `Date`.
1125fn to_unix_timestamp(v: &Value, name: &str) -> Result<f64, String> {
1126    // `+time == time` holds for exactly the strings that convert to a number.
1127    if with_host(|h| h.as_str(v).is_some()) {
1128        let n = with_host(|h| h.to_number(v));
1129        if !n.is_nan() {
1130            return Ok(n);
1131        }
1132    }
1133    if matches!(v, Value::Float(_) | Value::Int(_)) {
1134        let n = with_host(|h| h.to_number(v));
1135        if n.is_finite() {
1136            if n < 0.0 {
1137                let now = std::time::SystemTime::now()
1138                    .duration_since(UNIX_EPOCH)
1139                    .map(|d| d.as_millis() as f64)
1140                    .unwrap_or(0.0);
1141                return Ok(now / 1000.0);
1142            }
1143            return Ok(n);
1144        }
1145    }
1146    if native_tag(v).as_deref() == Some("Date") {
1147        return Ok(super::date::ms_of(v) / 1000.0);
1148    }
1149    Err(crate::host::coded_error(
1150        "TypeError",
1151        "ERR_INVALID_ARG_TYPE",
1152        &format!(
1153            "The \"{name}\" argument must be an instance of Date or an Time in seconds. Received {}",
1154            super::received_desc(v)
1155        ),
1156    ))
1157}
1158
1159/// `validateBufferArray(buffers)`: an Array whose every element is a byte view.
1160fn validate_buffer_array(v: &Value) -> Result<(), String> {
1161    let items = with_host(|h| match h.get(v) {
1162        Some(JsObj::Array(items)) => Some(items.clone()),
1163        _ => None,
1164    });
1165    let all_views = items.as_ref().is_some_and(|items| {
1166        items.iter().all(|b| {
1167            matches!(
1168                native_tag(b).as_deref(),
1169                Some("Buffer" | "TypedArray" | "DataView")
1170            )
1171        })
1172    });
1173    if all_views {
1174        return Ok(());
1175    }
1176    Err(crate::host::coded_error(
1177        "TypeError",
1178        "ERR_INVALID_ARG_TYPE",
1179        &format!(
1180            "The \"buffers\" argument must be an ArrayBufferView[]. Received {}",
1181            super::received_desc(v)
1182        ),
1183    ))
1184}
1185
1186/// `writeSync`'s own checks (`lib/fs.js`): for a byte view, `offset` an
1187/// integer `>= 0` and `validateOffsetLengthWrite`; otherwise the data must be
1188/// a string (`validateStringAfterArrayBufferView`).
1189fn validate_write(args: &[Value]) -> Result<(), String> {
1190    let src = args.get(1).cloned().unwrap_or(Value::Undef);
1191    let Some(len) = super::buffer::view_bytes(&src).map(|b| b.len() as f64) else {
1192        if with_host(|h| h.as_str(&src).is_some()) {
1193            return Ok(());
1194        }
1195        return Err(crate::host::coded_error(
1196            "TypeError",
1197            "ERR_INVALID_ARG_TYPE",
1198            &format!(
1199                "The \"buffer\" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received {}",
1200                super::received_desc(&src)
1201            ),
1202        ));
1203    };
1204    let third = args.get(2).cloned().unwrap_or(Value::Undef);
1205    let (offset, length) = if with_host(|h| h.type_of(&third)) == "object" {
1206        let opts = third;
1207        let nullish = with_host(|h| h.is_null(&opts));
1208        let get = |k: &str| match nullish {
1209            true => Ok(Value::Undef),
1210            false => crate::builtins::get_property(&opts, k),
1211        };
1212        (get("offset")?, get("length")?)
1213    } else {
1214        (third, args.get(3).cloned().unwrap_or(Value::Undef))
1215    };
1216    let offset = if matches!(offset, Value::Undef) || with_host(|h| h.is_null(&offset)) {
1217        0.0
1218    } else {
1219        super::validate_integer(&offset, "offset", 0.0)?
1220    };
1221    let length = match length {
1222        Value::Float(n) => n,
1223        Value::Int(n) => n as f64,
1224        _ => len - offset,
1225    };
1226    // `validateOffsetLengthWrite`.
1227    if offset > len {
1228        return Err(super::out_of_range(
1229            "offset",
1230            &format!("<= {}", crate::host::fmt_number(len)),
1231            offset,
1232        ));
1233    }
1234    if length > len - offset {
1235        let must = format!("<= {}", crate::host::fmt_number(len - offset));
1236        return Err(super::out_of_range("length", &must, length));
1237    }
1238    if length < 0.0 {
1239        return Err(super::out_of_range("length", ">= 0", length));
1240    }
1241    Ok(())
1242}
1243
1244// ── file descriptors ─────────────────────────────────────────────────────────
1245
1246/// `fs.openSync(path, flags, mode)`: one `open(2)` with node's flag table and
1247/// `mode` (so `wx` really is exclusive, `as` really is synchronous, and a
1248/// numeric flag set or a created file's mode is honoured).
1249fn open_impl(args: &[Value]) -> Result<Value, String> {
1250    let arg = |i: usize| match args.get(i) {
1251        Some(v) if !is_fn(v) => v.clone(),
1252        _ => Value::Undef,
1253    };
1254    let flags = string_to_flags(&arg(1))?;
1255    let mode = parse_file_mode(&arg(2), "mode", Some(0o666))?;
1256    let path = arg_str(args, 0);
1257    let file = open_file(&path, flags, mode)?;
1258    Ok(Value::Float(register_fd(file) as f64))
1259}
1260
1261/// One `open(2)` of `path`, its failure worded as node words an `open`.
1262fn open_file(path: &str, flags: libc::c_int, mode: u32) -> Result<File, String> {
1263    use std::os::unix::io::FromRawFd;
1264    let c = cpath(path, "open")?;
1265    let fd = unsafe { libc::open(c.as_ptr(), flags | libc::O_CLOEXEC, mode as libc::c_uint) };
1266    if fd < 0 {
1267        return Err(err_str("open", path, &std::io::Error::last_os_error()));
1268    }
1269    Ok(unsafe { File::from_raw_fd(fd) })
1270}
1271
1272fn close_impl(args: &[Value]) -> Result<Value, String> {
1273    let fd = arg_num(args, 0) as i32;
1274    if close_fd(fd) {
1275        Ok(Value::Undef)
1276    } else {
1277        Err("Error: EBADF: bad file descriptor, close".to_string())
1278    }
1279}
1280
1281/// `fs.readSync(fd, buffer[, offset[, length[, position]]])` and its options
1282/// form, a port of `lib/fs.js`. Validation errors are the OUTER error (they
1283/// throw, even from the callback form); the read's own failure is the inner.
1284fn read_impl(args: &[Value]) -> Result<usize, String> {
1285    let buffer = args.get(1).cloned().unwrap_or(Value::Undef);
1286    let third = args.get(2).cloned().unwrap_or(Value::Undef);
1287    let req = if args.len() <= 3 || with_host(|h| h.type_of(&third)) == "object" {
1288        read_options(&buffer, &third)?
1289    } else {
1290        ReadArgs {
1291            offset: third,
1292            length: args.get(3).cloned().unwrap_or(Value::Undef),
1293            position: args.get(4).cloned().unwrap_or(Value::Undef),
1294        }
1295    };
1296    read_validated(args.first().unwrap_or(&Value::Undef), &buffer, &req)?
1297}
1298
1299/// The three operands of a read, before validation.
1300struct ReadArgs {
1301    offset: Value,
1302    length: Value,
1303    position: Value,
1304}
1305
1306/// The `{offset = 0, length = buffer.byteLength - offset, position = null}`
1307/// destructuring of a read's options object (`null`/`undefined` mean `{}`).
1308fn read_options(buffer: &Value, opts: &Value) -> Result<ReadArgs, String> {
1309    let nullish = matches!(opts, Value::Undef) || with_host(|h| h.is_null(opts));
1310    if !nullish && with_host(|h| h.type_of(opts)) != "object" {
1311        return Err(crate::host::invalid_arg_type(
1312            "options", "argument", "object", opts,
1313        ));
1314    }
1315    let field = |k: &str| -> Result<Value, String> {
1316        if nullish {
1317            Ok(Value::Undef)
1318        } else {
1319            crate::builtins::get_property(opts, k)
1320        }
1321    };
1322    let offset = match field("offset")? {
1323        Value::Undef => Value::Float(0.0),
1324        v => v,
1325    };
1326    let length = match field("length")? {
1327        Value::Undef => {
1328            let len = super::buffer::view_bytes(buffer).map_or(0, |b| b.len()) as f64;
1329            Value::Float(len - with_host(|h| h.to_number(&offset)))
1330        }
1331        v => v,
1332    };
1333    let position = field("position")?;
1334    Ok(ReadArgs {
1335        offset,
1336        length,
1337        position,
1338    })
1339}
1340
1341/// Validate a read's operands as `readSync` does, then read. The outer error
1342/// is a validation failure; the inner one the read itself. The bytes land at
1343/// `offset` BYTES into whatever view `buffer` is — a `Uint16Array` or a
1344/// `DataView` receives them exactly as a Buffer does — and a `position` reads
1345/// with `pread`, leaving the descriptor's own offset where it was.
1346fn read_validated(
1347    fd: &Value,
1348    buffer: &Value,
1349    req: &ReadArgs,
1350) -> Result<Result<usize, String>, String> {
1351    validate_read_buffer(buffer)?;
1352    let offset = match req.offset {
1353        Value::Undef => 0.0,
1354        ref v => super::validate_integer(v, "offset", 0.0)?,
1355    };
1356    let length = crate::host::to_number_value(&req.length)?;
1357    let length = crate::host::to_int32(length) as f64;
1358    if length == 0.0 {
1359        return Ok(Ok(0));
1360    }
1361    let mut bytes = super::buffer::view_bytes(buffer).unwrap_or_default();
1362    if bytes.is_empty() {
1363        return Err(crate::host::coded_error(
1364            "TypeError",
1365            "ERR_INVALID_ARG_VALUE",
1366            &format!(
1367                "The argument 'buffer' is empty and cannot be written. Received {}",
1368                with_host(|h| h.inspect(buffer))
1369            ),
1370        ));
1371    }
1372    if length < 0.0 {
1373        return Err(super::out_of_range("length", ">= 0", length));
1374    }
1375    let cap = bytes.len() as f64;
1376    if offset + length > cap {
1377        return Err(super::out_of_range(
1378            "length",
1379            &format!("<= {}", cap - offset),
1380            length,
1381        ));
1382    }
1383    let position = read_position(&req.position, length)?;
1384    // The binding checks the descriptor last, once the JavaScript-side checks
1385    // above have passed.
1386    let fd = validate_fd(fd)?;
1387    let (offset, length) = (offset as usize, length as usize);
1388    let dest = &mut bytes[offset..offset + length];
1389    let got = if fd == 0 && position.is_none() {
1390        crate::host::with_stdin_reader(|r| r.read(dest))
1391    } else {
1392        use std::os::unix::fs::FileExt;
1393        match with_file(fd, |file| match position {
1394            Some(pos) => file.read_at(dest, pos),
1395            None => {
1396                let mut fr: &File = file;
1397                fr.read(dest)
1398            }
1399        }) {
1400            Some(r) => r,
1401            None => return Ok(Err("Error: EBADF: bad file descriptor, read".to_string())),
1402        }
1403    };
1404    Ok(match got {
1405        Ok(n) => {
1406            super::buffer::write_view(buffer, &bytes);
1407            Ok(n)
1408        }
1409        Err(e) => Err(err_str("read", "", &e)),
1410    })
1411}
1412
1413/// node's `validatePosition`: `null`/`undefined`/`-1` read from the current
1414/// offset; otherwise an integer or a bigint at least `-1`.
1415fn read_position(v: &Value, length: f64) -> Result<Option<u64>, String> {
1416    if matches!(v, Value::Undef) || with_host(|h| h.is_null(v)) {
1417        return Ok(None);
1418    }
1419    let pos = match with_host(|h| h.type_of(v)) {
1420        "number" => super::validate_integer(v, "position", -1.0)?,
1421        "bigint" => {
1422            let p: i128 = with_host(|h| h.str_of(v)).parse().unwrap_or(-2);
1423            let max = i64::MAX as i128 - length as i128;
1424            if !(-1..=max).contains(&p) {
1425                return Err(crate::host::coded_error(
1426                    "RangeError",
1427                    "ERR_OUT_OF_RANGE",
1428                    &format!(
1429                        "The value of \"position\" is out of range. It must be >= -1n && <= {max}n. Received {p}n"
1430                    ),
1431                ));
1432            }
1433            p as f64
1434        }
1435        _ => {
1436            return Err(crate::host::invalid_arg_type(
1437                "position",
1438                "argument",
1439                "bigint or integer",
1440                v,
1441            ))
1442        }
1443    };
1444    Ok((pos >= 0.0).then_some(pos as u64))
1445}
1446
1447/// `validateBuffer`: a read's destination must be a Buffer, typed array or
1448/// `DataView` — an `ArrayBuffer` is not a view.
1449fn validate_read_buffer(buffer: &Value) -> Result<(), String> {
1450    if matches!(
1451        native_tag(buffer).as_deref(),
1452        Some("Buffer" | "TypedArray" | "DataView")
1453    ) {
1454        return Ok(());
1455    }
1456    Err(crate::host::coded_error(
1457        "TypeError",
1458        "ERR_INVALID_ARG_TYPE",
1459        &format!(
1460            "The \"buffer\" argument must be an instance of Buffer, TypedArray, or DataView. Received {}",
1461            super::received_desc(buffer)
1462        ),
1463    ))
1464}
1465
1466/// `fs.read`, whose callback is `(err, bytesRead, buffer)`. The argument forms
1467/// are `lib/fs.js`'s, counted with the descriptor: `(fd, cb)` reads into a fresh
1468/// 16 KiB Buffer, `(fd, bufferOrOptions, cb)`, `(fd, buffer, options, cb)`, and
1469/// the positional `(fd, buffer, offset, length, position, cb)`. A bad argument
1470/// throws here, synchronously; only the read's own failure reaches `cb`.
1471fn read_async(args: &[Value]) -> Result<Value, String> {
1472    let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Undef);
1473    let fresh = || super::buffer::from_bytes(&[0u8; 16384]);
1474    let (buffer, req, cb) = match args.len() {
1475        0..=2 => {
1476            let buffer = fresh();
1477            let req = read_options(&buffer, &Value::Undef)?;
1478            (buffer, req, arg(1))
1479        }
1480        3 if !matches!(
1481            native_tag(&arg(1)).as_deref(),
1482            Some("Buffer" | "TypedArray" | "DataView")
1483        ) =>
1484        {
1485            let params = arg(1);
1486            let nullish = matches!(params, Value::Undef) || with_host(|h| h.is_null(&params));
1487            let buffer = match nullish {
1488                true => Value::Undef,
1489                false => crate::builtins::get_property(&params, "buffer")?,
1490            };
1491            let buffer = if matches!(buffer, Value::Undef) {
1492                fresh()
1493            } else {
1494                buffer
1495            };
1496            let req = read_options(&buffer, &params)?;
1497            (buffer, req, arg(2))
1498        }
1499        3 => (arg(1), read_options(&arg(1), &Value::Undef)?, arg(2)),
1500        4 => (arg(1), read_options(&arg(1), &arg(2))?, arg(3)),
1501        _ => (
1502            arg(1),
1503            ReadArgs {
1504                offset: arg(2),
1505                length: arg(3),
1506                position: arg(4),
1507            },
1508            arg(5),
1509        ),
1510    };
1511    validate_read_buffer(&buffer)?;
1512    if !is_fn(&cb) {
1513        return Err(crate::host::invalid_arg_type(
1514            "cb", "argument", "function", &cb,
1515        ));
1516    }
1517    let result = read_validated(args.first().unwrap_or(&Value::Undef), &buffer, &req)?;
1518    with_host(|h| match result {
1519        Ok(n) => {
1520            let nul = h.null();
1521            h.queue_io_callback(cb, vec![nul, Value::Float(n as f64), buffer]);
1522        }
1523        Err(e) => {
1524            let ev = crate::builtins::synth_error(h, &e);
1525            h.queue_io_callback(cb, vec![ev]);
1526        }
1527    });
1528    Ok(Value::Undef)
1529}
1530
1531fn write_impl(args: &[Value]) -> Result<usize, String> {
1532    let fd = arg_num(args, 0) as i32;
1533    let src = args.get(1).cloned().unwrap_or(Value::Undef);
1534    // The positional form differs for a byte VIEW and a string, so the two are
1535    // distinguished by what the argument IS, not by whether it is a Buffer.
1536    let view = super::buffer::view_bytes(&src);
1537    // Buffer form: write(fd, buffer, offset, length, position)
1538    // String form: write(fd, string, position, encoding)
1539    let (data, position) = if let Some(all) = view {
1540        let offset = num_or(args, 2, 0.0) as usize;
1541        let length = num_or(args, 3, (all.len().saturating_sub(offset)) as f64) as usize;
1542        let end = (offset + length).min(all.len());
1543        (
1544            all[offset.min(all.len())..end].to_vec(),
1545            position_arg(args, 4),
1546        )
1547    } else {
1548        (
1549            with_host(|h| h.str_of(&src)).into_bytes(),
1550            position_arg(args, 2),
1551        )
1552    };
1553    // A numeric `position` is `pwrite`: the descriptor's offset stays where it
1554    // was, so a later position-less write continues from there.
1555    let r = with_file(fd, |file| write_maybe_at(file, &data, position));
1556    match r {
1557        Some(Ok(n)) => Ok(n),
1558        Some(Err(e)) => Err(err_str("write", "", &e)),
1559        None => Err("Error: EBADF: bad file descriptor, write".to_string()),
1560    }
1561}
1562
1563/// `fs.readvSync(fd, buffers[, position])`: fill each view in turn, stopping at
1564/// end of file. Any byte view takes part (a `Uint8Array` used to be skipped as
1565/// zero-capacity), and a numeric `position` reads with `pread`, leaving the
1566/// descriptor's offset where it was.
1567fn readv_impl(args: &[Value]) -> Result<usize, String> {
1568    use std::os::unix::fs::FileExt;
1569    let fd = arg_num(args, 0) as i32;
1570    let buffers = array_items(args.get(1));
1571    let mut position = position_arg(args, 2);
1572    let mut total = 0;
1573    for b in &buffers {
1574        let mut bytes = super::buffer::view_bytes(b).unwrap_or_default();
1575        let got = with_file(fd, |file| match position {
1576            Some(pos) => file.read_at(&mut bytes, pos),
1577            None => {
1578                let mut fr: &File = file;
1579                fr.read(&mut bytes)
1580            }
1581        });
1582        let n = match got {
1583            Some(Ok(n)) => n,
1584            // libuv reports a failed vectored read as the `read` it issues.
1585            Some(Err(e)) => return Err(err_str("read", "", &e)),
1586            None => return Err("Error: EBADF: bad file descriptor, read".to_string()),
1587        };
1588        if n == 0 {
1589            break;
1590        }
1591        super::buffer::write_view(b, &bytes);
1592        total += n;
1593        position = position.map(|p| p + n as u64);
1594        if n < bytes.len() {
1595            break;
1596        }
1597    }
1598    Ok(total)
1599}
1600
1601fn writev_impl(args: &[Value]) -> Result<usize, String> {
1602    let fd = arg_num(args, 0) as i32;
1603    let buffers = array_items(args.get(1));
1604    let position = position_arg(args, 2);
1605    let mut data = Vec::new();
1606    for b in &buffers {
1607        data.extend(buf_bytes(b));
1608    }
1609    // `pwritev` for a numeric position, as in `writeSync`. libuv reports a
1610    // failed vectored write as the `write` it issues.
1611    let r = with_file(fd, |file| write_maybe_at(file, &data, position));
1612    match r {
1613        Some(Ok(n)) => Ok(n),
1614        Some(Err(e)) => Err(err_str("write", "", &e)),
1615        None => Err("Error: EBADF: bad file descriptor, write".to_string()),
1616    }
1617}
1618
1619/// One `write(2)` at the descriptor's offset, or one `pwrite(2)` at `position`.
1620fn write_maybe_at(file: &File, data: &[u8], position: Option<u64>) -> std::io::Result<usize> {
1621    use std::os::unix::fs::FileExt;
1622    match position {
1623        Some(pos) => file.write_at(data, pos),
1624        None => {
1625            let mut fr: &File = file;
1626            fr.write(data)
1627        }
1628    }
1629}
1630
1631fn fstat_impl(args: &[Value]) -> Result<Value, String> {
1632    let fd = arg_num(args, 0) as i32;
1633    let md = with_file(fd, |file| file.metadata());
1634    match md {
1635        Some(Ok(md)) => {
1636            let bigint = bigint_opt(args);
1637            Ok(with_host(|h| build_stats(h, &md, bigint)))
1638        }
1639        Some(Err(e)) => Err(err_str("fstat", "", &e)),
1640        None => Err("Error: EBADF: bad file descriptor, fstat".to_string()),
1641    }
1642}
1643
1644fn fchmod_impl(args: &[Value]) -> Result<Value, String> {
1645    let fd = arg_num(args, 0) as i32;
1646    let mode = parse_file_mode(args.get(1).unwrap_or(&Value::Undef), "mode", None)? as libc::mode_t;
1647    let rc = with_file(fd, |file| unsafe { libc::fchmod(file.as_raw_fd(), mode) });
1648    fd_result(rc, "fchmod")
1649}
1650
1651fn fchown_impl(args: &[Value]) -> Result<Value, String> {
1652    let fd = arg_num(args, 0) as i32;
1653    let uid = arg_num(args, 1) as libc::uid_t;
1654    let gid = arg_num(args, 2) as libc::gid_t;
1655    let rc = with_file(fd, |file| unsafe {
1656        libc::fchown(file.as_raw_fd(), uid, gid)
1657    });
1658    fd_result(rc, "fchown")
1659}
1660
1661fn futimes_impl(args: &[Value]) -> Result<Value, String> {
1662    let fd = arg_num(args, 0) as i32;
1663    let times = [
1664        to_timeval(time_secs(args, 1)),
1665        to_timeval(time_secs(args, 2)),
1666    ];
1667    let rc = with_file(fd, |file| unsafe {
1668        libc::futimes(file.as_raw_fd(), times.as_ptr())
1669    });
1670    fd_result(rc, "futimes")
1671}
1672
1673fn ftruncate_impl(args: &[Value]) -> Result<Value, String> {
1674    let fd = arg_num(args, 0) as i32;
1675    let len = arg_num(args, 1);
1676    let len = if len.is_nan() { 0 } else { len as u64 };
1677    match with_file(fd, |file| file.set_len(len)) {
1678        Some(Ok(_)) => Ok(Value::Undef),
1679        Some(Err(e)) => Err(err_str("ftruncate", "", &e)),
1680        None => Err("Error: EBADF: bad file descriptor, ftruncate".to_string()),
1681    }
1682}
1683
1684/// libuv's `uv__fs_fsync` / `uv__fs_fdatasync`: on macOS `F_FULLFSYNC`, then
1685/// `F_BARRIERFSYNC`, then plain `fsync(2)`, so the error a descriptor that
1686/// cannot be synced reports is `fsync`'s (`EINVAL` for a pipe), not the
1687/// first fcntl's; elsewhere `fsync(2)` / `fdatasync(2)`.
1688fn uv_fsync(fd: libc::c_int, data_only: bool) -> std::io::Result<()> {
1689    #[cfg(target_os = "macos")]
1690    let rc = unsafe {
1691        let _ = data_only;
1692        let mut rc = libc::fcntl(fd, libc::F_FULLFSYNC);
1693        if rc != 0 {
1694            rc = libc::fcntl(fd, 85 /* F_BARRIERFSYNC */);
1695        }
1696        if rc != 0 {
1697            rc = libc::fsync(fd);
1698        }
1699        rc
1700    };
1701    #[cfg(not(target_os = "macos"))]
1702    let rc = unsafe {
1703        if data_only {
1704            libc::fdatasync(fd)
1705        } else {
1706            libc::fsync(fd)
1707        }
1708    };
1709    if rc == 0 {
1710        Ok(())
1711    } else {
1712        Err(std::io::Error::last_os_error())
1713    }
1714}
1715
1716fn fsync_impl(args: &[Value], data_only: bool) -> Result<Value, String> {
1717    let fd = arg_num(args, 0) as i32;
1718    let op = if data_only { "fdatasync" } else { "fsync" };
1719    let r = with_file(fd, |file| uv_fsync(file.as_raw_fd(), data_only));
1720    match r {
1721        Some(Ok(_)) => Ok(Value::Undef),
1722        Some(Err(e)) => Err(err_str(op, "", &e)),
1723        None => Err(format!("Error: EBADF: bad file descriptor, {op}")),
1724    }
1725}
1726
1727/// Translate the return of a `with_file` libc call: `None` = bad fd, `Some(0)` =
1728/// success, `Some(_)` = the C failure whose reason is in `errno`.
1729fn fd_result(rc: Option<libc::c_int>, op: &str) -> Result<Value, String> {
1730    match rc {
1731        Some(0) => Ok(Value::Undef),
1732        Some(_) => Err(err_str(op, "", &std::io::Error::last_os_error())),
1733        None => Err(format!("Error: EBADF: bad file descriptor, {op}")),
1734    }
1735}
1736
1737// ── stat / statfs ────────────────────────────────────────────────────────────
1738
1739fn stat_impl(op: &str, args: &[Value], follow: bool) -> Result<Value, String> {
1740    let path = arg_str(args, 0);
1741    let md = if follow {
1742        std::fs::metadata(&path)
1743    } else {
1744        std::fs::symlink_metadata(&path)
1745    };
1746    match md {
1747        Ok(md) => {
1748            let bigint = bigint_opt(args);
1749            Ok(with_host(|h| build_stats(h, &md, bigint)))
1750        }
1751        Err(e) => Err(err_str(op, &path, &e)),
1752    }
1753}
1754
1755fn statfs_impl(args: &[Value]) -> Result<Value, String> {
1756    let path = arg_str(args, 0);
1757    let c = cpath(&path, "statfs")?;
1758    let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
1759    if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
1760        return Err(err_str("statfs", &path, &std::io::Error::last_os_error()));
1761    }
1762    Ok(with_host(|h| {
1763        let mut m = IndexMap::new();
1764        m.insert("type".into(), Value::Float(st.f_fsid as f64));
1765        m.insert("bsize".into(), Value::Float(st.f_bsize as f64));
1766        m.insert("blocks".into(), Value::Float(st.f_blocks as f64));
1767        m.insert("bfree".into(), Value::Float(st.f_bfree as f64));
1768        m.insert("bavail".into(), Value::Float(st.f_bavail as f64));
1769        m.insert("files".into(), Value::Float(st.f_files as f64));
1770        m.insert("ffree".into(), Value::Float(st.f_ffree as f64));
1771        h.new_object(m)
1772    }))
1773}
1774
1775/// Build a full `fs.Stats` object from `Metadata` (unix fields via `MetadataExt`).
1776/// Whether a stat call's options ask for `BigIntStats` (`{ bigint: true }`).
1777fn bigint_opt(args: &[Value]) -> bool {
1778    match args.get(1) {
1779        Some(o) if !is_fn(o) && with_host(|h| h.type_of(o)) == "object" => {
1780            let v = crate::builtins::get_property(o, "bigint").unwrap_or(Value::Undef);
1781            with_host(|h| h.truthy(&v))
1782        }
1783        _ => false,
1784    }
1785}
1786
1787/// A `Stats` — or, with `bigint`, a `BigIntStats` — for `md`, in node's own-key
1788/// order.
1789///
1790/// `Stats` carries the four sub-millisecond remainders as own symbol-keyed
1791/// properties (`Symbol(partialAtimeNs)` …), which is how node keeps the
1792/// nanoseconds without a BigInt. `BigIntStats` has every number as a BigInt,
1793/// whole milliseconds in `*Ms`, and the full nanosecond times in `*Ns`. The
1794/// `is*` methods and the four Date accessors live on the prototype.
1795fn build_stats(h: &mut crate::host::JsHost, md: &std::fs::Metadata, bigint: bool) -> Value {
1796    let birth = md
1797        .created()
1798        .ok()
1799        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
1800        .map(|d| (d.as_secs() as i64, i64::from(d.subsec_nanos())))
1801        .unwrap_or((md.mtime(), md.mtime_nsec()));
1802    let times = [
1803        ("atime", (md.atime(), md.atime_nsec()), "partialAtimeNs"),
1804        ("mtime", (md.mtime(), md.mtime_nsec()), "partialMtimeNs"),
1805        ("ctime", (md.ctime(), md.ctime_nsec()), "partialCtimeNs"),
1806        ("birthtime", birth, "kPartialBirthtimeNs"),
1807    ];
1808    let ft = md.file_type();
1809    let mut m = IndexMap::new();
1810    let tag = if bigint { "BigIntStats" } else { "Stats" };
1811    m.insert("@@native".into(), h.new_str(tag));
1812    m.insert("@@isFile".into(), Value::Bool(md.is_file()));
1813    m.insert("@@isDir".into(), Value::Bool(md.is_dir()));
1814    insert_special_types(&mut m, &ft);
1815    m.insert("@@isSymlink".into(), Value::Bool(ft.is_symlink()));
1816    let fields: [(&str, i128); 10] = [
1817        ("dev", md.dev() as i128),
1818        ("mode", i128::from(md.mode())),
1819        ("nlink", md.nlink() as i128),
1820        ("uid", i128::from(md.uid())),
1821        ("gid", i128::from(md.gid())),
1822        ("rdev", md.rdev() as i128),
1823        ("blksize", md.blksize() as i128),
1824        ("ino", i128::from(md.ino())),
1825        ("size", i128::from(md.len())),
1826        ("blocks", md.blocks() as i128),
1827    ];
1828    let int = |h: &mut crate::host::JsHost, n: i128| {
1829        if bigint {
1830            h.new_bigint(num_bigint::BigInt::from(n))
1831        } else {
1832            Value::Float(n as f64)
1833        }
1834    };
1835    for (k, n) in fields {
1836        let v = int(h, n);
1837        m.insert(k.into(), v);
1838    }
1839    let ns_of = |(s, n): (i64, i64)| i128::from(s) * 1_000_000_000 + i128::from(n);
1840    // The Date fields: fractional milliseconds for `Stats`, whole ones for
1841    // `BigIntStats` (`Number(this.atimeMs)`).
1842    let mut date_ms = Vec::new();
1843    for (k, t, _) in times {
1844        let ms = if bigint {
1845            let whole = ns_of(t).div_euclid(1_000_000);
1846            m.insert(format!("{k}Ms"), int(h, whole));
1847            whole as f64
1848        } else {
1849            let ms = t.0 as f64 * 1000.0 + t.1 as f64 / 1_000_000.0;
1850            m.insert(format!("{k}Ms"), Value::Float(ms));
1851            ms
1852        };
1853        date_ms.push((k, ms));
1854    }
1855    if bigint {
1856        for (k, t, _) in times {
1857            let v = int(h, ns_of(t));
1858            m.insert(format!("{k}Ns"), v);
1859        }
1860    } else {
1861        for (_, t, sym) in times {
1862            let key = {
1863                let s = h.internal_symbol(sym);
1864                h.property_key(&s)
1865            };
1866            m.insert(key, Value::Float(t.1 as f64));
1867        }
1868    }
1869    for (k, ms) in &date_ms {
1870        let mut d = IndexMap::new();
1871        d.insert("@@native".into(), h.new_str("Date"));
1872        d.insert("@@ms".into(), Value::Float(*ms));
1873        let date = h.new_object(d);
1874        m.insert((*k).to_string(), date);
1875    }
1876    let obj = h.new_object(m);
1877    // The four Date fields are ACCESSORS on `Stats.prototype` in node, so they
1878    // are not own enumerable keys: `Object.keys(statSync(f))` is the numeric
1879    // fields and nothing else. They are stored here rather than computed, so
1880    // the equivalent is to hide them — a `JSON.stringify(stat)` or an
1881    // `{...stat}` carried four extra entries node does not.
1882    for (k, _) in &date_ms {
1883        h.hide_prop(&obj, k);
1884    }
1885    obj
1886}
1887
1888// ── watchFile / unwatchFile ──────────────────────────────────────────────────
1889
1890fn watch_file(args: &[Value]) -> Result<Value, String> {
1891    let path = arg_str(args, 0);
1892    let Some(listener) = args.last().cloned().filter(is_fn) else {
1893        return Ok(Value::Undef);
1894    };
1895    let interval = interval_opt(args).unwrap_or(5007.0).max(1.0) as u64;
1896    let abs = std::fs::canonicalize(&path)
1897        .map(|p| p.to_string_lossy().into_owned())
1898        .unwrap_or_else(|_| path.clone());
1899
1900    let stop = Arc::new(AtomicBool::new(false));
1901    let id = NEXT_WATCH_ID.with(|n| {
1902        let v = *n.borrow();
1903        *n.borrow_mut() = v + 1;
1904        v
1905    });
1906    WATCHERS.with(|w| {
1907        w.borrow_mut().push(WatchEntry {
1908            id,
1909            path: abs.clone(),
1910            listener: listener.clone(),
1911            stop: stop.clone(),
1912        });
1913    });
1914    with_host(|h| h.incr_handle());
1915
1916    let tx = with_host(|h| h.io_sender());
1917    let poll_stop = stop.clone();
1918    let poll_listener = listener;
1919    std::thread::spawn(move || {
1920        let mut prev = stat_parts(&abs);
1921        loop {
1922            if poll_stop.load(Ordering::Acquire) {
1923                break;
1924            }
1925            std::thread::sleep(Duration::from_millis(interval));
1926            if poll_stop.load(Ordering::Acquire) {
1927                break;
1928            }
1929            let curr = stat_parts(&abs);
1930            if curr != prev {
1931                let l = poll_listener.clone();
1932                let (p0, p1, p2) = prev;
1933                let (c0, c1, c2) = curr;
1934                let _ = tx.send(Box::new(move || {
1935                    let cur = with_host(|h| stats_from_parts(h, c0, c1, c2));
1936                    let old = with_host(|h| stats_from_parts(h, p0, p1, p2));
1937                    if let Err(e) = invoke(&l, vec![cur, old], None) {
1938                        eprintln!("{e}");
1939                    }
1940                    Ok(())
1941                }));
1942                prev = curr;
1943            }
1944        }
1945    });
1946    Ok(Value::Undef)
1947}
1948
1949fn unwatch_file(args: &[Value]) -> Result<Value, String> {
1950    let path = arg_str(args, 0);
1951    let abs = std::fs::canonicalize(&path)
1952        .map(|p| p.to_string_lossy().into_owned())
1953        .unwrap_or_else(|_| path.clone());
1954    let listener = args.get(1).cloned().filter(is_fn);
1955    let removed = WATCHERS.with(|w| {
1956        let mut w = w.borrow_mut();
1957        let mut count = 0;
1958        w.retain(|e| {
1959            let matches =
1960                e.path == abs && listener.as_ref().map(|l| *l == e.listener).unwrap_or(true);
1961            if matches {
1962                e.stop.store(true, Ordering::Release);
1963                count += 1;
1964            }
1965            !matches
1966        });
1967        count
1968    });
1969    for _ in 0..removed {
1970        with_host(|h| h.decr_handle());
1971    }
1972    // Wake the event loop so it can re-evaluate the handle count.
1973    if removed > 0 {
1974        let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1975    }
1976    Ok(Value::Undef)
1977}
1978
1979/// A file's watch-relevant state: `(exists, mtime_ms, size)`.
1980fn stat_parts(path: &str) -> (bool, i64, u64) {
1981    match std::fs::metadata(path) {
1982        Ok(md) => (
1983            true,
1984            md.mtime() * 1000 + md.mtime_nsec() / 1_000_000,
1985            md.len(),
1986        ),
1987        Err(_) => (false, 0, 0),
1988    }
1989}
1990
1991fn stats_from_parts(h: &mut crate::host::JsHost, exists: bool, mtime_ms: i64, size: u64) -> Value {
1992    let ms = mtime_ms as f64;
1993    let date = |h: &mut crate::host::JsHost, ms: f64| {
1994        let mut d = IndexMap::new();
1995        d.insert("@@native".into(), h.new_str("Date"));
1996        d.insert("@@ms".into(), Value::Float(ms));
1997        h.new_object(d)
1998    };
1999    let mut m = IndexMap::new();
2000    m.insert("@@native".into(), h.new_str("Stats"));
2001    m.insert("@@isFile".into(), Value::Bool(exists));
2002    m.insert("@@isDir".into(), Value::Bool(false));
2003    m.insert("@@isSymlink".into(), Value::Bool(false));
2004    m.insert(
2005        "size".into(),
2006        Value::Float(if exists { size as f64 } else { 0.0 }),
2007    );
2008    m.insert("atimeMs".into(), Value::Float(ms));
2009    m.insert("mtimeMs".into(), Value::Float(ms));
2010    m.insert("ctimeMs".into(), Value::Float(ms));
2011    m.insert("birthtimeMs".into(), Value::Float(ms));
2012    let mt = date(h, ms);
2013    m.insert("mtime".into(), mt);
2014    let at = date(h, ms);
2015    m.insert("atime".into(), at);
2016    h.new_object(m)
2017}
2018
2019// ── read / write streams ─────────────────────────────────────────────────────
2020
2021/// The byte window and chunk size of a read stream: `start`/`end` (inclusive,
2022/// absolute offsets) and `highWaterMark`, checked as `lib/internal/fs/streams`
2023/// checks them, synchronously.
2024struct ReadWindow {
2025    start: Option<u64>,
2026    end: Option<u64>,
2027    high_water_mark: usize,
2028}
2029
2030fn read_window(args: &[Value]) -> Result<ReadWindow, String> {
2031    let int_opt = |key: &str| -> Result<Option<f64>, String> {
2032        match option_value(args, key) {
2033            None | Some(Value::Undef) => Ok(None),
2034            Some(v) => super::validate_integer(&v, key, 0.0).map(Some),
2035        }
2036    };
2037    let start = int_opt("start")?;
2038    let end = match option_value(args, "end") {
2039        // `end` may be `Infinity` (the default).
2040        Some(Value::Float(f)) if f == f64::INFINITY => None,
2041        _ => int_opt("end")?,
2042    };
2043    if let (Some(s), Some(e)) = (start, end) {
2044        if s > e {
2045            let must = format!("<= \"end\" (here: {})", crate::host::fmt_number(e));
2046            return Err(super::out_of_range("start", &must, s));
2047        }
2048    }
2049    let high_water_mark = match option_value(args, "highWaterMark") {
2050        Some(v @ (Value::Float(_) | Value::Int(_))) => {
2051            (with_host(|h| h.to_number(&v)).max(1.0)) as usize
2052        }
2053        _ => 64 * 1024,
2054    };
2055    Ok(ReadWindow {
2056        start: start.map(|s| s as u64),
2057        end: end.map(|e| e as u64),
2058        high_water_mark,
2059    })
2060}
2061
2062/// The bytes of `file` the window covers: from `start` with positioned reads
2063/// (the descriptor's offset untouched), else from the current offset; cut at
2064/// `end` inclusive.
2065fn read_window_bytes(file: &File, w: &ReadWindow) -> std::io::Result<Vec<u8>> {
2066    use std::os::unix::fs::FileExt;
2067    let mut bytes = Vec::new();
2068    match w.start {
2069        Some(mut pos) => {
2070            let mut buf = vec![0u8; 64 * 1024];
2071            loop {
2072                let n = file.read_at(&mut buf, pos)?;
2073                if n == 0 {
2074                    break;
2075                }
2076                bytes.extend_from_slice(&buf[..n]);
2077                pos += n as u64;
2078            }
2079        }
2080        None => {
2081            let mut fr: &File = file;
2082            fr.read_to_end(&mut bytes)?;
2083        }
2084    }
2085    if let Some(end) = w.end {
2086        let max = (end + 1).saturating_sub(w.start.unwrap_or(0)) as usize;
2087        bytes.truncate(max);
2088    }
2089    Ok(bytes)
2090}
2091
2092fn create_read_stream(args: &[Value]) -> Result<Value, String> {
2093    let path = arg_str(args, 0);
2094    let enc = encoding_arg(args, 1);
2095    let window = read_window(args)?;
2096    let stream = with_host(|h| {
2097        let mut extra = IndexMap::new();
2098        extra.insert("path".into(), h.new_str(path.clone()));
2099        extra.insert("bytesRead".into(), Value::Float(0.0));
2100        if let Some(e) = &enc {
2101            extra.insert("@@encoding".into(), h.new_str(e.clone()));
2102        }
2103        extra
2104    });
2105    let stream = super::net::new_emitter_object("FSReadStream", stream);
2106    with_host(|h| h.incr_handle());
2107    // `{ fd }`: the stream reads an already-open descriptor and opens nothing
2108    // (so no `open`/`ready`). `autoClose` (default true) closes it after
2109    // `end`; with it off the stream never emits `close`.
2110    let fd = option_value(args, "fd").filter(|v| matches!(v, Value::Float(_) | Value::Int(_)));
2111    let auto_close = option_value(args, "autoClose").map_or(true, |v| with_host(|h| h.truthy(&v)));
2112    let recv = stream.clone();
2113    with_host(|h| {
2114        h.queue_micro_native(Box::new(move || {
2115            read_stream_pump(&recv, &path, fd, auto_close, &window);
2116            Ok(())
2117        }))
2118    });
2119    Ok(stream)
2120}
2121
2122/// The value of `key` in the options object among `args`, if present.
2123fn option_value(args: &[Value], key: &str) -> Option<Value> {
2124    with_host(|h| {
2125        args.iter().find_map(|v| match h.get(v) {
2126            Some(JsObj::Object(p)) => p.get(key).cloned(),
2127            _ => None,
2128        })
2129    })
2130}
2131
2132/// Read the stream's window and drive its events on the microtask tick after
2133/// creation (so synchronously-attached `on('data')`/`on('end')` listeners
2134/// fire): `open`/`ready` for a path, a `data` event per `highWaterMark`
2135/// bytes, `end`, then — with `autoClose` — the descriptor closed and `close`.
2136fn read_stream_pump(
2137    recv: &Value,
2138    path: &str,
2139    given_fd: Option<Value>,
2140    auto_close: bool,
2141    window: &ReadWindow,
2142) {
2143    with_host(|h| h.decr_handle());
2144    let fd = match given_fd {
2145        Some(v) => arg_num(&[v], 0) as i32,
2146        None => match File::open(path) {
2147            Ok(file) => {
2148                let fd = register_fd(file);
2149                let open = with_host(|h| h.new_str("open"));
2150                let _ =
2151                    super::events::instance_call(recv, "emit", vec![open, Value::Float(fd as f64)]);
2152                let ready = with_host(|h| h.new_str("ready"));
2153                let _ = super::events::instance_call(recv, "emit", vec![ready]);
2154                fd
2155            }
2156            Err(e) => {
2157                emit_stream_error(recv, &err_str("open", path, &e));
2158                return;
2159            }
2160        },
2161    };
2162    let bytes = match with_file(fd, |file| read_window_bytes(file, window)) {
2163        Some(Ok(b)) => b,
2164        Some(Err(e)) => return emit_stream_error(recv, &err_str("read", "", &e)),
2165        None => return emit_stream_error(recv, "Error: EBADF: bad file descriptor, read"),
2166    };
2167    emit_stream_bytes(recv, &bytes, window.high_water_mark);
2168    // `end` and then `close` each follow on a later tick, as node schedules
2169    // them, so what a `data` listener queued runs before the stream ends.
2170    let target = recv.clone();
2171    with_host(|h| {
2172        h.queue_micro_native(Box::new(move || {
2173            let end = with_host(|h| h.new_str("end"));
2174            super::events::instance_call(&target, "emit", vec![end])?;
2175            if !auto_close {
2176                return Ok(());
2177            }
2178            close_fd(fd);
2179            with_host(|h| {
2180                h.queue_micro_native(Box::new(move || {
2181                    let close = with_host(|h| h.new_str("close"));
2182                    super::events::instance_call(&target, "emit", vec![close]).map(|_| ())
2183                }))
2184            });
2185            Ok(())
2186        }))
2187    });
2188}
2189
2190fn emit_stream_error(recv: &Value, msg: &str) {
2191    let ev = with_host(|h| crate::builtins::synth_error(h, msg));
2192    let _ = super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("error")), ev]);
2193}
2194
2195/// Hand a read stream's bytes to its pipe destination, or emit them as `data`
2196/// events of at most `high_water_mark` bytes, decoded in the stream's encoding
2197/// by a `StringDecoder` so a character split across two chunks arrives whole.
2198/// `bytesRead` counts the bytes delivered so far.
2199fn emit_stream_bytes(recv: &Value, bytes: &[u8], high_water_mark: usize) {
2200    let enc = get_prop(recv, "@@encoding").map(|v| with_host(|h| h.str_of(&v)));
2201    let decoder = match enc.as_deref() {
2202        Some(e) if e != "buffer" => {
2203            let e = with_host(|h| h.new_str(e));
2204            super::string_decoder::construct(&[e]).ok()
2205        }
2206        _ => None,
2207    };
2208    let dest = get_prop(recv, "@@pipeDest");
2209    let deliver = |chunk: Value| match &dest {
2210        Some(d) => {
2211            let _ = crate::host::call_method(d, "write", vec![chunk]);
2212        }
2213        None => {
2214            let name = with_host(|h| h.new_str("data"));
2215            let _ = super::events::instance_call(recv, "emit", vec![name, chunk]);
2216        }
2217    };
2218    let decode = |method: &str, args: Vec<Value>| -> Option<Value> {
2219        let d = decoder.as_ref()?;
2220        let s = super::string_decoder::instance_call(d, method, &args).ok()?;
2221        (with_host(|h| h.as_str(&s)).is_some_and(|s| !s.is_empty())).then_some(s)
2222    };
2223    let mut read = 0usize;
2224    for part in bytes.chunks(high_water_mark.max(1)) {
2225        read += part.len();
2226        set_prop(recv, "bytesRead", Value::Float(read as f64));
2227        let buf = super::buffer::from_bytes(part);
2228        if decoder.is_some() {
2229            if let Some(s) = decode("write", vec![buf]) {
2230                deliver(s);
2231            }
2232        } else {
2233            deliver(buf);
2234        }
2235    }
2236    if let Some(s) = decode("end", Vec::new()) {
2237        deliver(s);
2238    }
2239    if let Some(d) = &dest {
2240        let _ = crate::host::call_method(d, "end", vec![]);
2241    }
2242}
2243
2244pub const READ_STREAM_METHODS: &[&str] = &[
2245    "pipe",
2246    "pause",
2247    "resume",
2248    "setEncoding",
2249    "destroy",
2250    "close",
2251    "read",
2252];
2253
2254/// `fs.ReadStream` instance dispatch (tag `FSReadStream`). The EventEmitter methods (`on`, `once`, `emit`, …) delegate to `events`, as every
2255/// other emitter-backed instance does; this covers the stream-only surface.
2256/// Nothing routed them here, so `fs.createReadStream(p).on('data', …)` threw
2257/// `on is not a function`.
2258pub fn read_stream_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
2259    if !READ_STREAM_METHODS.contains(&method) && super::events::METHODS.contains(&method) {
2260        return super::events::instance_call(recv, method, args);
2261    }
2262    match method {
2263        "pipe" => {
2264            if let Some(dest) = args.first().cloned() {
2265                set_prop(recv, "@@pipeDest", dest.clone());
2266                Ok(dest)
2267            } else {
2268                Ok(recv.clone())
2269            }
2270        }
2271        "setEncoding" => {
2272            set_prop(
2273                recv,
2274                "@@encoding",
2275                with_host(|h| h.new_str(super::arg_str(&args, 0))),
2276            );
2277            Ok(recv.clone())
2278        }
2279        "pause" | "resume" | "read" => Ok(recv.clone()),
2280        "destroy" | "close" => {
2281            let _ =
2282                super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))]);
2283            Ok(recv.clone())
2284        }
2285        _ => Err(crate::host::type_error(&format!(
2286            "stream.{method} is not a function"
2287        ))),
2288    }
2289}
2290
2291fn create_write_stream(args: &[Value]) -> Result<Value, String> {
2292    let path = arg_str(args, 0);
2293    let flags = match encoding_flag(args, "flags") {
2294        Some(f) => f,
2295        None => "w".to_string(),
2296    };
2297    // `{ fd }` writes to an already-open descriptor and opens nothing (no
2298    // `open`/`ready`); `autoClose: false` leaves it open after `finish`, and
2299    // the stream then never emits `close`.
2300    let given = option_value(args, "fd").filter(|v| matches!(v, Value::Float(_) | Value::Int(_)));
2301    let auto_close = option_value(args, "autoClose").map_or(true, |v| with_host(|h| h.truthy(&v)));
2302    let fd = match &given {
2303        Some(v) => arg_num(std::slice::from_ref(v), 0) as i32,
2304        None => {
2305            let flags = string_to_flags(&with_host(|h| h.new_str(flags)))?;
2306            register_fd(open_file(&path, flags, 0o666)?)
2307        }
2308    };
2309    let stream = with_host(|h| {
2310        let mut extra = IndexMap::new();
2311        extra.insert("path".into(), h.new_str(path));
2312        extra.insert("@@wfd".into(), Value::Float(fd as f64));
2313        extra.insert("@@autoClose".into(), Value::Bool(auto_close));
2314        extra.insert("bytesWritten".into(), Value::Float(0.0));
2315        extra
2316    });
2317    let stream = super::net::new_emitter_object("FSWriteStream", stream);
2318    with_host(|h| h.incr_handle());
2319    if given.is_some() {
2320        return Ok(stream);
2321    }
2322    let recv = stream.clone();
2323    with_host(|h| {
2324        h.queue_micro_native(Box::new(move || {
2325            let open = with_host(|h| h.new_str("open"));
2326            let _ =
2327                super::events::instance_call(&recv, "emit", vec![open, Value::Float(fd as f64)]);
2328            let _ = super::events::instance_call(
2329                &recv,
2330                "emit",
2331                vec![with_host(|h| h.new_str("ready"))],
2332            );
2333            Ok(())
2334        }))
2335    });
2336    Ok(stream)
2337}
2338
2339pub const WRITE_STREAM_METHODS: &[&str] = &[
2340    "write",
2341    "end",
2342    "destroy",
2343    "close",
2344    "cork",
2345    "uncork",
2346    "setDefaultEncoding",
2347];
2348
2349/// `fs.WriteStream` instance dispatch (tag `FSWriteStream`), with the
2350/// EventEmitter methods delegated to `events` as for a read stream.
2351pub fn write_stream_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
2352    if !WRITE_STREAM_METHODS.contains(&method) && super::events::METHODS.contains(&method) {
2353        return super::events::instance_call(recv, method, args);
2354    }
2355    match method {
2356        "write" => {
2357            write_stream_bytes(recv, args.first());
2358            // The write callback follows the call, with `null` for success.
2359            if let Some(cb) = args.iter().find(|v| is_fn(v)).cloned() {
2360                with_host(|h| {
2361                    h.queue_micro_native(Box::new(move || {
2362                        let null = with_host(|h| h.null());
2363                        invoke(&cb, vec![null], None).map(|_| ())
2364                    }))
2365                });
2366            }
2367            Ok(Value::Bool(true))
2368        }
2369        "end" => {
2370            if let Some(chunk) = args
2371                .first()
2372                .filter(|v| !matches!(v, Value::Undef) && !is_fn(v))
2373            {
2374                write_stream_bytes(recv, Some(chunk));
2375            }
2376            let auto_close =
2377                get_prop(recv, "@@autoClose").map_or(true, |v| with_host(|h| h.truthy(&v)));
2378            if let Some(fd) = get_prop(recv, "@@wfd")
2379                .filter(|_| auto_close)
2380                .map(|v| with_host(|h| h.to_number(&v)) as i32)
2381            {
2382                close_fd(fd);
2383            }
2384            with_host(|h| h.decr_handle());
2385            // `finish`, the `end` callback and `close` follow the call rather
2386            // than happening inside it: node finishes a write stream once its
2387            // pending writes have drained, so code after `end()` runs first.
2388            let target = recv.clone();
2389            let cb = args.iter().find(|v| is_fn(v)).cloned();
2390            with_host(|h| {
2391                h.queue_micro_native(Box::new(move || {
2392                    let ev = |name: &str| {
2393                        let n = with_host(|h| h.new_str(name));
2394                        super::events::instance_call(&target, "emit", vec![n]).map(|_| ())
2395                    };
2396                    // Node runs the `end` callbacks, with `null`, before it
2397                    // emits `finish`.
2398                    if let Some(cb) = cb {
2399                        let null = with_host(|h| h.null());
2400                        invoke(&cb, vec![null], None)?;
2401                    }
2402                    ev("finish")?;
2403                    if auto_close {
2404                        ev("close")?;
2405                    }
2406                    Ok(())
2407                }))
2408            });
2409            Ok(recv.clone())
2410        }
2411
2412        "destroy" | "close" => {
2413            if let Some(fd) = get_prop(recv, "@@wfd").map(|v| with_host(|h| h.to_number(&v)) as i32)
2414            {
2415                close_fd(fd);
2416            }
2417            let _ =
2418                super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))]);
2419            with_host(|h| h.decr_handle());
2420            Ok(recv.clone())
2421        }
2422        "cork" | "uncork" | "setDefaultEncoding" => Ok(recv.clone()),
2423        _ => Err(crate::host::type_error(&format!(
2424            "stream.{method} is not a function"
2425        ))),
2426    }
2427}
2428
2429fn write_stream_bytes(recv: &Value, chunk: Option<&Value>) {
2430    let Some(chunk) = chunk else { return };
2431    let data = value_bytes(chunk);
2432    if let Some(fd) = get_prop(recv, "@@wfd").map(|v| with_host(|h| h.to_number(&v)) as i32) {
2433        let written = with_file(fd, |file| {
2434            let mut fr: &File = file;
2435            fr.write(&data).unwrap_or(0)
2436        })
2437        .unwrap_or(0);
2438        let prev = get_prop(recv, "bytesWritten")
2439            .map(|v| with_host(|h| h.to_number(&v)))
2440            .unwrap_or(0.0);
2441        set_prop(recv, "bytesWritten", Value::Float(prev + written as f64));
2442    }
2443}
2444
2445// ── Stats / Dirent / Dir instance surfaces ───────────────────────────────────
2446
2447/// `fs.Stats` method dispatch (`isFile`/`isDirectory`/…).
2448pub fn stats_call(recv: &Value, method: &str) -> Result<Value, String> {
2449    type_test(recv, method, "stats")
2450}
2451
2452pub const DIRENT_METHODS: &[&str] = &[
2453    "isFile",
2454    "isDirectory",
2455    "isSymbolicLink",
2456    "isBlockDevice",
2457    "isCharacterDevice",
2458    "isFIFO",
2459    "isSocket",
2460];
2461
2462/// `fs.Dirent` method dispatch (tag `Dirent`); `name`/`parentPath`/`path` are
2463/// plain data properties resolved by the generic object path.
2464pub fn dirent_call(recv: &Value, method: &str) -> Result<Value, String> {
2465    type_test(recv, method, "dirent")
2466}
2467
2468/// Shared `is*` predicates for `Stats` and `Dirent`, read from the type flags
2469/// both carry (`@@isFile`, `@@isDir`, `@@isSymlink`, `@@isFIFO`, …).
2470fn type_test(recv: &Value, method: &str, what: &str) -> Result<Value, String> {
2471    let read = |key: &str| {
2472        with_host(|h| match h.get(recv) {
2473            Some(JsObj::Object(p)) => matches!(p.get(key), Some(Value::Bool(true))),
2474            _ => false,
2475        })
2476    };
2477    match method {
2478        "isFile" => Ok(Value::Bool(read("@@isFile"))),
2479        "isDirectory" => Ok(Value::Bool(read("@@isDir"))),
2480        "isSymbolicLink" => Ok(Value::Bool(read("@@isSymlink"))),
2481        "isBlockDevice" => Ok(Value::Bool(read("@@isBlockDev"))),
2482        "isCharacterDevice" => Ok(Value::Bool(read("@@isCharDev"))),
2483        "isFIFO" => Ok(Value::Bool(read("@@isFIFO"))),
2484        "isSocket" => Ok(Value::Bool(read("@@isSocket"))),
2485        _ => Err(crate::host::type_error(&format!(
2486            "{what}.{method} is not a function"
2487        ))),
2488    }
2489}
2490
2491pub const DIR_METHODS: &[&str] = &["read", "readSync", "close", "closeSync"];
2492
2493/// `fs.Dir` method dispatch (tag `Dir`); `path` is a plain data property.
2494pub fn dir_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
2495    match method {
2496        "readSync" => Ok(dir_next(recv)),
2497        "read" => {
2498            let v = dir_next(recv);
2499            if let Some(cb) = args.first().filter(|c| is_fn(c)).cloned() {
2500                with_host(|h| {
2501                    let n = h.null();
2502                    h.queue_io_callback(cb, vec![n, v]);
2503                });
2504                Ok(Value::Undef)
2505            } else {
2506                Ok(settled_ok(v))
2507            }
2508        }
2509        "closeSync" => Ok(Value::Undef),
2510        "close" => {
2511            if let Some(cb) = args.first().filter(|c| is_fn(c)).cloned() {
2512                with_host(|h| {
2513                    let n = h.null();
2514                    h.queue_io_callback(cb, vec![n]);
2515                });
2516                Ok(Value::Undef)
2517            } else {
2518                Ok(settled_ok(Value::Undef))
2519            }
2520        }
2521        _ => Err(crate::host::type_error(&format!(
2522            "dir.{method} is not a function"
2523        ))),
2524    }
2525}
2526
2527/// Advance the `Dir` cursor and return the next `Dirent`, or `null` when drained.
2528fn dir_next(recv: &Value) -> Value {
2529    with_host(|h| {
2530        let (entries, pos) = match h.get(recv) {
2531            Some(JsObj::Object(p)) => (
2532                p.get("@@entries").cloned(),
2533                p.get("@@pos").map(|v| h.to_number(v) as usize).unwrap_or(0),
2534            ),
2535            _ => (None, 0),
2536        };
2537        let item = match entries.as_ref().and_then(|e| h.get(e)) {
2538            Some(JsObj::Array(items)) => items.get(pos).cloned(),
2539            _ => None,
2540        };
2541        if item.is_some() {
2542            if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2543                p.insert("@@pos".into(), Value::Float((pos + 1) as f64));
2544            }
2545        }
2546        item.unwrap_or_else(|| h.null())
2547    })
2548}
2549
2550fn build_dirent(
2551    h: &mut crate::host::JsHost,
2552    name: String,
2553    parent: &str,
2554    ft: std::fs::FileType,
2555) -> Value {
2556    let mut m = IndexMap::new();
2557    m.insert("@@native".into(), h.new_str("Dirent"));
2558    m.insert("name".into(), h.new_str(name));
2559    let pp = h.new_str(parent.to_string());
2560    m.insert("parentPath".into(), pp.clone());
2561    m.insert("path".into(), pp);
2562    m.insert("@@isFile".into(), Value::Bool(ft.is_file()));
2563    m.insert("@@isDir".into(), Value::Bool(ft.is_dir()));
2564    m.insert("@@isSymlink".into(), Value::Bool(ft.is_symlink()));
2565    insert_special_types(&mut m, &ft);
2566    h.new_object(m)
2567}
2568
2569// ── glob ─────────────────────────────────────────────────────────────────────
2570
2571fn glob_impl(args: &[Value]) -> Result<Value, String> {
2572    let pattern = arg_str(args, 0);
2573    let absolute = pattern.starts_with('/');
2574    let base = if absolute {
2575        PathBuf::from("/")
2576    } else {
2577        std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
2578    };
2579    let segs: Vec<String> = pattern
2580        .split('/')
2581        .filter(|s| !s.is_empty())
2582        .map(String::from)
2583        .collect();
2584    let mut out: Vec<String> = Vec::new();
2585    let prefix = if absolute {
2586        "/".to_string()
2587    } else {
2588        String::new()
2589    };
2590    glob_walk(&base, &segs, 0, &prefix, &mut out);
2591    out.sort();
2592    out.dedup();
2593    Ok(with_host(|h| {
2594        let items: Vec<Value> = out.into_iter().map(|s| h.new_str(s)).collect();
2595        h.new_array(items)
2596    }))
2597}
2598
2599fn glob_walk(dir: &Path, segs: &[String], idx: usize, prefix: &str, out: &mut Vec<String>) {
2600    if idx >= segs.len() {
2601        if !prefix.is_empty() && prefix != "/" {
2602            out.push(prefix.trim_end_matches('/').to_string());
2603        }
2604        return;
2605    }
2606    let seg = &segs[idx];
2607    if seg == "**" {
2608        glob_walk(dir, segs, idx + 1, prefix, out);
2609        if let Ok(rd) = std::fs::read_dir(dir) {
2610            for e in rd.flatten() {
2611                if e.path().is_dir() {
2612                    let name = e.file_name().to_string_lossy().into_owned();
2613                    let np = join_glob(prefix, &name);
2614                    glob_walk(&e.path(), segs, idx, &np, out);
2615                }
2616            }
2617        }
2618        return;
2619    }
2620    let last = idx + 1 == segs.len();
2621    if let Ok(rd) = std::fs::read_dir(dir) {
2622        for e in rd.flatten() {
2623            let name = e.file_name().to_string_lossy().into_owned();
2624            if name.starts_with('.') && !seg.starts_with('.') {
2625                continue;
2626            }
2627            if wildcard_match(seg, &name) {
2628                let np = join_glob(prefix, &name);
2629                if last {
2630                    out.push(np);
2631                } else if e.path().is_dir() {
2632                    glob_walk(&e.path(), segs, idx + 1, &np, out);
2633                }
2634            }
2635        }
2636    }
2637}
2638
2639fn join_glob(prefix: &str, name: &str) -> String {
2640    if prefix.is_empty() {
2641        name.to_string()
2642    } else if prefix.ends_with('/') {
2643        format!("{prefix}{name}")
2644    } else {
2645        format!("{prefix}/{name}")
2646    }
2647}
2648
2649/// Match a single path segment against a `*`/`?` glob (no character classes).
2650fn wildcard_match(pat: &str, name: &str) -> bool {
2651    let p: Vec<char> = pat.chars().collect();
2652    let n: Vec<char> = name.chars().collect();
2653    let (mut pi, mut ni) = (0usize, 0usize);
2654    let (mut star, mut mark) = (None, 0usize);
2655    while ni < n.len() {
2656        if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
2657            pi += 1;
2658            ni += 1;
2659        } else if pi < p.len() && p[pi] == '*' {
2660            star = Some(pi);
2661            mark = ni;
2662            pi += 1;
2663        } else if let Some(s) = star {
2664            pi = s + 1;
2665            mark += 1;
2666            ni = mark;
2667        } else {
2668            return false;
2669        }
2670    }
2671    while pi < p.len() && p[pi] == '*' {
2672        pi += 1;
2673    }
2674    pi == p.len()
2675}
2676
2677// ── small helpers ────────────────────────────────────────────────────────────
2678
2679fn settled_ok(v: Value) -> Value {
2680    let p = with_host(|h| h.new_promise());
2681    let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
2682    crate::host::resolve_promise_val(id, v);
2683    p
2684}
2685
2686fn get_prop(recv: &Value, key: &str) -> Option<Value> {
2687    with_host(|h| match h.get(recv) {
2688        Some(JsObj::Object(p)) => p.get(key).cloned(),
2689        _ => None,
2690    })
2691}
2692
2693fn set_prop(recv: &Value, key: &str, val: Value) {
2694    with_host(|h| {
2695        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
2696            p.insert(key.to_string(), val);
2697        }
2698    });
2699}
2700
2701/// Raw bytes of a byte-view arg, or the utf-8 bytes of anything else.
2702fn value_bytes(v: &Value) -> Vec<u8> {
2703    match super::buffer::view_bytes(v) {
2704        Some(b) => b,
2705        None => with_host(|h| h.str_of(v)).into_bytes(),
2706    }
2707}
2708
2709fn buf_bytes(v: &Value) -> Vec<u8> {
2710    with_host(|h| match h.get(v) {
2711        Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
2712        _ => Vec::new(),
2713    })
2714}
2715
2716fn array_items(v: Option<&Value>) -> Vec<Value> {
2717    match v {
2718        Some(v) => with_host(|h| match h.get(v) {
2719            Some(JsObj::Array(items)) => items.clone(),
2720            _ => Vec::new(),
2721        }),
2722        None => Vec::new(),
2723    }
2724}
2725
2726fn opt_flag(args: &[Value], key: &str) -> bool {
2727    with_host(|h| {
2728        args.iter().any(|v| {
2729            matches!(h.get(v), Some(JsObj::Object(p)) if matches!(p.get(key), Some(Value::Bool(true))))
2730        })
2731    })
2732}
2733
2734fn encoding_flag(args: &[Value], key: &str) -> Option<String> {
2735    with_host(|h| {
2736        for v in args {
2737            if let Some(JsObj::Object(p)) = h.get(v) {
2738                if let Some(val) = p.get(key) {
2739                    return Some(h.str_of(val));
2740                }
2741            }
2742        }
2743        None
2744    })
2745}
2746
2747fn interval_opt(args: &[Value]) -> Option<f64> {
2748    with_host(|h| {
2749        for v in args {
2750            if let Some(JsObj::Object(p)) = h.get(v) {
2751                if let Some(val) = p.get("interval") {
2752                    return Some(h.to_number(val));
2753                }
2754            }
2755        }
2756        None
2757    })
2758}
2759
2760fn num_or(args: &[Value], i: usize, default: f64) -> f64 {
2761    match args.get(i) {
2762        Some(v) if !matches!(v, Value::Undef) => {
2763            let n = with_host(|h| h.to_number(v));
2764            if n.is_nan() {
2765                default
2766            } else {
2767                n
2768            }
2769        }
2770        _ => default,
2771    }
2772}
2773
2774/// A byte `position` argument: `null`/`undefined` means "current file offset".
2775fn position_arg(args: &[Value], i: usize) -> Option<u64> {
2776    match args.get(i) {
2777        Some(Value::Undef) | None => None,
2778        Some(v) if with_host(|h| h.is_null(v)) => None,
2779        Some(v) => {
2780            let n = with_host(|h| h.to_number(v));
2781            if n.is_nan() || n < 0.0 {
2782                None
2783            } else {
2784                Some(n as u64)
2785            }
2786        }
2787    }
2788}
2789
2790/// A timestamp argument in **seconds** (`toUnixTimestamp`). `validate_call`
2791/// has already refused one that does not convert.
2792fn time_secs(args: &[Value], i: usize) -> f64 {
2793    to_unix_timestamp(args.get(i).unwrap_or(&Value::Undef), "time").unwrap_or(f64::NAN)
2794}
2795
2796fn to_timeval(secs: f64) -> libc::timeval {
2797    let s = secs.floor();
2798    let us = ((secs - s) * 1_000_000.0).round();
2799    libc::timeval {
2800        tv_sec: s as libc::time_t,
2801        tv_usec: us as libc::suseconds_t,
2802    }
2803}
2804
2805fn cpath(path: &str, op: &str) -> Result<CString, String> {
2806    CString::new(path).map_err(|_| format!("Error: EINVAL: invalid argument, {op} '{path}'"))
2807}
2808
2809fn ok_or_errno(rc: libc::c_int, op: &str, path: &str) -> Result<Value, String> {
2810    if rc == 0 {
2811        Ok(Value::Undef)
2812    } else {
2813        Err(err_str(op, path, &std::io::Error::last_os_error()))
2814    }
2815}
2816
2817/// The encoding an fs call was given, from either the string form
2818/// (`readFileSync(p, 'hex')`) or the options-object form
2819/// (`readFileSync(p, { encoding: 'hex' })`).
2820///
2821/// The object form used to be discarded — it was detected by its
2822/// `"[object Object]"` stringification and treated as absent — so
2823/// `{ encoding: 'utf8' }` returned a Buffer. `{ encoding: null }` really does
2824/// mean "no encoding", and so returns `None`.
2825fn encoding_arg(args: &[Value], i: usize) -> Option<String> {
2826    match args.get(i) {
2827        Some(Value::Undef) | None => None,
2828        Some(v) => {
2829            if with_host(|h| matches!(h.get(v), Some(JsObj::Object(_)))) {
2830                let e = crate::builtins::get_property(v, "encoding").ok()?;
2831                if matches!(e, Value::Undef) || with_host(|h| h.is_null(&e)) {
2832                    return None;
2833                }
2834                return Some(with_host(|h| h.str_of(&e)));
2835            }
2836            let s = with_host(|h| h.str_of(v));
2837            if s == "undefined" || s == "null" {
2838                None
2839            } else {
2840                Some(s)
2841            }
2842        }
2843    }
2844}
2845
2846/// The failing *syscall* Node names in a filesystem error, for the JS-level
2847/// entry points whose API name differs from it. `fs.readFileSync('/nope')`
2848/// reports `open`, not `readFileSync`, because `open(2)` is what failed —
2849/// and `err.syscall` is load-bearing for packages that branch on it.
2850fn syscall_name(op: &str) -> &str {
2851    match op {
2852        "readFileSync" | "readFile" | "writeFile" | "writeFileSync" | "appendFile"
2853        | "appendFileSync" | "createReadStream" | "createWriteStream" => "open",
2854        "readdir" | "readdirSync" | "opendir" => "scandir",
2855        // The rest name the C call, which for most of these is the JS name
2856        // minus its `Sync` suffix — `fs.statSync('/nope')` reports `stat`. Only
2857        // the ones whose spelling ALSO changes need an entry: libuv writes
2858        // `copyfile` in one word, and `realpath` fails inside the `lstat` it
2859        // walks the path with.
2860        "copyFile" | "copyFileSync" => "copyfile",
2861        "realpath" | "realpathSync" => "lstat",
2862        other => other.strip_suffix("Sync").unwrap_or(other),
2863    }
2864}
2865
2866/// The second path a two-argument call names in its message: node renders
2867/// `rename '/a' -> '/b'`, and a message with only the source reads as though
2868/// the destination were never part of the operation.
2869fn err_str2(op: &str, from: &str, to: &str, e: &std::io::Error) -> String {
2870    format!("{} -> '{to}'", err_str(op, from, e))
2871}
2872
2873/// The `CODE: reason` half of a libuv error message (`ENOENT: no such file or
2874/// directory`), shared by every syscall wrapper that has to render one.
2875///
2876/// Deliberately NOT Rust's `io::Error` `Display`: Rust capitalizes and appends
2877/// its own `(os error 2)`, so `No such file or directory (os error 2)` is a
2878/// string no Node has ever printed. `process.chdir` was assembling its message
2879/// that way.
2880/// The libuv error CODE for an `io::Error` — `ENOENT`, `EACCES` and the rest.
2881/// Node exposes it as `err.code`, and every error it renders leads with it.
2882pub(crate) fn libuv_code(e: &std::io::Error) -> &'static str {
2883    use std::io::ErrorKind::*;
2884    // An OS error names itself: its errno is looked up in the same table
2885    // `util.getSystemErrorMap` reports, so `EBADF`, `ELOOP`, `ENAMETOOLONG`,
2886    // `EXDEV`, … keep their own codes. Mapping by `ErrorKind` alone folded
2887    // every kind Rust does not single out into `EIO`.
2888    if let Some(name) = e.raw_os_error().and_then(crate::stdlib::util::errno_name) {
2889        return name;
2890    }
2891    match e.kind() {
2892        NotFound => "ENOENT",
2893        PermissionDenied => "EACCES",
2894        AlreadyExists => "EEXIST",
2895        NotADirectory => "ENOTDIR",
2896        IsADirectory => "EISDIR",
2897        DirectoryNotEmpty => "ENOTEMPTY",
2898        InvalidInput => "EINVAL",
2899        BrokenPipe => "EPIPE",
2900        _ => "EIO",
2901    }
2902}
2903
2904pub(crate) fn libuv_message(e: &std::io::Error) -> String {
2905    let code = libuv_code(e);
2906    format!("{code}: {}", libuv_reason(code))
2907}
2908
2909/// libuv's own lowercase reason string for a code.
2910fn libuv_reason(code: &str) -> &'static str {
2911    crate::stdlib::util::errno_by_name(code).map_or("i/o error", |(_, m)| m)
2912}
2913
2914fn err_str(op: &str, path: &str, e: &std::io::Error) -> String {
2915    let code = libuv_code(e);
2916    // libuv's own reason strings, not Rust's `io::Error` `Display` — Rust
2917    // capitalizes ("No such file or directory") where libuv (and therefore
2918    // Node's `err.message`) does not.
2919    let reason = libuv_reason(code);
2920    let op = syscall_name(op);
2921    if path.is_empty() {
2922        format!("Error: {code}: {reason}, {op}")
2923    } else {
2924        format!("Error: {code}: {reason}, {op} '{path}'")
2925    }
2926}
2927
2928/// The four file types node tests besides file/directory/symlink — a pipe
2929/// (stdin under `|`), a terminal or `/dev/null`, a block device, a socket —
2930/// recorded for `Stats`/`Dirent`'s `isFIFO`/`isCharacterDevice`/… They all
2931/// answered `false`.
2932fn insert_special_types(m: &mut IndexMap<String, Value>, ft: &std::fs::FileType) {
2933    use std::os::unix::fs::FileTypeExt;
2934    m.insert("@@isFIFO".into(), Value::Bool(ft.is_fifo()));
2935    m.insert("@@isCharDev".into(), Value::Bool(ft.is_char_device()));
2936    m.insert("@@isBlockDev".into(), Value::Bool(ft.is_block_device()));
2937    m.insert("@@isSocket".into(), Value::Bool(ft.is_socket()));
2938}