Skip to main content

nodejs/stdlib/
mod.rs

1//! Node.js core modules implemented natively for node-js.
2//!
3//! A `require(spec)` (see `builtins::call_builtin_function`) resolves a supported
4//! module to a `JsObj::Builtin("<module>")` namespace value — exactly the shape
5//! of the built-in `console`/`Math` namespaces — so `mod.method(...)` dispatches
6//! through `host::call_method` → `builtins::call_builtin_function("<module>.<method>")`
7//! → `stdlib::call`, and `const { method } = require('mod')` reads the method as a
8//! first-class `Builtin("mod.method")` via `namespace_property`.
9//!
10//! Every stdlib function is free-standing and acquires the thread-local `JsHost`
11//! through `with_host` only around allocations (and releases it before any
12//! re-entrant `host::invoke`), so callbacks (`fs` async, `EventEmitter.emit`,
13//! `assert.throws`) never double-borrow the host. Stateful instances (`Buffer`,
14//! crypto `Hash`, `EventEmitter`, `URL`) are plain objects carrying a hidden
15//! `@@native` tag (filtered from enumeration/display like `@@iterator`); their
16//! methods route through `instance_call` from `host::call_method`.
17
18use crate::host::{with_host, JsObj};
19use fusevm::Value;
20
21pub mod assert;
22pub mod assert_diff;
23pub mod async_hooks;
24pub mod buffer;
25pub mod child_process;
26pub mod cluster;
27pub mod console;
28pub mod constants;
29pub mod crypto;
30pub mod date;
31pub mod dgram;
32pub mod diagnostics_channel;
33pub mod dns;
34pub mod domain;
35pub mod event_target;
36pub mod events;
37pub mod fetch;
38pub mod fs;
39pub mod fs_promises;
40pub mod http;
41pub mod http2;
42pub mod https;
43pub mod iterator;
44pub mod net;
45pub mod node_module;
46pub mod os;
47pub mod path;
48pub mod perf_hooks;
49pub mod process;
50pub mod punycode;
51pub mod querystring;
52pub mod readline;
53pub mod repl;
54pub mod stream;
55pub mod stream_consumers;
56pub mod stream_promises;
57pub mod stream_web;
58pub mod string_decoder;
59pub mod timers;
60pub mod tls;
61pub mod trace_events;
62pub mod tty;
63pub mod typedarray;
64pub mod url;
65pub mod url_legacy;
66pub mod util;
67pub mod util_types;
68pub mod v8;
69pub mod vm;
70pub mod worker_threads;
71pub mod zlib;
72
73/// Native-heavy core modules that node-js does not yet implement (TLS handshakes,
74/// HTTP/2 framing, OS worker threads sharing the thread-local heap, UDP sockets,
75/// V8 inspector, etc.). `require`ing them succeeds and yields a namespace so that
76/// programs which import-then-conditionally-use them still load; ACTUALLY calling
77/// a method throws `Error: <mod>.<method> is not implemented in node-js`. This is
78/// an honest not-yet-built surface, never a silent fake.
79pub const UNIMPLEMENTED_MODULES: &[&str] = &["inspector", "wasi"];
80
81/// True if `ns` is a known-but-unimplemented core module (see `UNIMPLEMENTED_MODULES`).
82pub fn is_unimplemented(ns: &str) -> bool {
83    UNIMPLEMENTED_MODULES.contains(&ns)
84}
85
86/// Canonical namespace name a `require(spec)` resolves to (after stripping an
87/// optional `node:` prefix), or `None` for an unsupported module.
88/// Core modules whose export is a plain DATA value rather than a namespace of
89/// methods. `require('constants')` is the only one: every member is a number,
90/// so it is built as a real object instead of a `Builtin` handle, whose members
91/// are dispatchable methods by construction.
92pub fn data_module(spec: &str) -> Option<Value> {
93    match spec.strip_prefix("node:").unwrap_or(spec) {
94        "constants" => {
95            cached_module_value("@constants", || Some(constants::object(&constants::flat())))
96        }
97        _ => None,
98    }
99}
100
101/// Whether `spec` names a core module of any kind — a method namespace or a
102/// data module. This is what `require.resolve` answers with the bare specifier.
103pub fn is_core(spec: &str) -> bool {
104    resolve(spec).is_some() || matches!(spec.strip_prefix("node:").unwrap_or(spec), "constants")
105}
106
107pub fn resolve(spec: &str) -> Option<&'static str> {
108    match spec.strip_prefix("node:").unwrap_or(spec) {
109        "fs" => Some("fs"),
110        "path" => Some("path"),
111        "os" => Some("os"),
112        "util" => Some("util"),
113        "assert" => Some("assert"),
114        "crypto" => Some("crypto"),
115        "buffer" => Some("buffer"),
116        "url" => Some("url"),
117        "process" => Some("process"),
118        "net" => Some("net"),
119        "http" => Some("http"),
120        // `require('stream')` IS the `Stream` constructor — `stream.Stream ===
121        // stream`, and libraries still subclass it the ES5 way with
122        // `Stream.call(this)` + `Object.create(Stream.prototype)`. It used to
123        // resolve to a plain namespace, so `typeof` was `object`, `.prototype`
124        // was `undefined`, and that subclassing pattern threw.
125        "stream" => Some("Stream"),
126        "tty" => Some("tty"),
127        // The `events` module's export IS the EventEmitter constructor, so
128        // `require('events')` yields the ctor namespace directly.
129        "events" => Some("EventEmitter"),
130        "string_decoder" => Some("string_decoder"),
131        "zlib" => Some("zlib"),
132        "querystring" => Some("querystring"),
133        "console" => Some("console"),
134        // `path/posix` is exactly our POSIX `path` (node-js targets a POSIX host,
135        // so `require('path') === path.posix`); `path/win32` is the separate
136        // backslash flavor. `assert/strict` is `assert` (already strict-based).
137        "path/posix" => Some("path"),
138        "path/win32" => Some("path/win32"),
139        // `sys` is the long-deprecated alias for `util`.
140        "sys" => Some("util"),
141        // `require('assert/strict')` IS the strict namespace, so its `equal`
142        // and `deepEqual` are the strict comparisons. Pointing it at the plain
143        // `assert` made `require('assert/strict').equal(1, '1')` pass. The
144        // strict namespace already existed for `assert.strict.*`.
145        "assert/strict" => Some("assertStrict"),
146        "child_process" => Some("child_process"),
147        "dns" => Some("dns"),
148        "punycode" => Some("punycode"),
149        "timers" => Some("timers"),
150        "timers/promises" => Some("timers/promises"),
151        "perf_hooks" => Some("perf_hooks"),
152        "async_hooks" => Some("async_hooks"),
153        "util/types" => Some("util/types"),
154        "diagnostics_channel" => Some("diagnostics_channel"),
155        "v8" => Some("v8"),
156        "readline" => Some("readline"),
157        "readline/promises" => Some("readline/promises"),
158        "vm" => Some("vm"),
159        "fs/promises" => Some("fs/promises"),
160        "dgram" => Some("dgram"),
161        "dns/promises" => Some("dns/promises"),
162        "worker_threads" => Some("worker_threads"),
163        "tls" => Some("tls"),
164        "https" => Some("https"),
165        "repl" => Some("repl"),
166        "cluster" => Some("cluster"),
167        "domain" => Some("domain"),
168        "http2" => Some("http2"),
169        "trace_events" => Some("trace_events"),
170        "module" => Some("module"),
171        "stream/consumers" => Some("stream/consumers"),
172        "stream/promises" => Some("stream/promises"),
173        "stream/web" => Some("stream/web"),
174        other => UNIMPLEMENTED_MODULES.iter().copied().find(|&m| m == other),
175    }
176}
177
178/// True if `qualified` (`namespace.method`) is a stdlib method that
179/// `call_builtin_function` should route into `call` (extends `is_known_builtin`).
180pub fn is_method(qualified: &str) -> bool {
181    let Some((ns, m)) = qualified.split_once('.') else {
182        return qualified == "assert";
183    };
184    // Any method on an unimplemented namespace routes to `call`, which throws an
185    // honest "not implemented" error (so `mod.foo()` fails clearly rather than
186    // silently returning undefined).
187    is_unimplemented(ns)
188        || namespace_methods(ns).contains(&m)
189        || namespace_ctors(ns).contains(&m)
190        || namespace_values(ns).contains(&m)
191}
192
193/// The callable members of builtin namespace `ns`. THE single table backing both
194/// `is_method` (does `ns.m` dispatch?) and `namespace_keys` (what does `for (k in
195/// ns)` yield?), so a method can never be callable-but-unenumerable or the reverse.
196pub fn namespace_methods(ns: &str) -> &'static [&'static str] {
197    match ns {
198        "fs" => fs::METHODS,
199        "path" | "path/win32" => path::METHODS,
200        "os" => os::METHODS,
201        "util" => util::METHODS,
202        "assert" | "assertStrict" => assert::METHODS,
203        "crypto" => crypto::METHODS,
204        "webcrypto" => crypto::WEBCRYPTO_METHODS,
205        "SubtleCrypto" => crypto::SUBTLE_METHODS,
206        "Buffer" => buffer::STATIC_METHODS,
207        "buffer" => buffer::MODULE_METHODS,
208        "Date" => date::STATIC_METHODS,
209        "Response" => fetch::RESPONSE_STATICS,
210        "AbortSignal" => fetch::ABORT_SIGNAL_STATICS,
211        "Iterator" => iterator::STATIC_METHODS,
212        n if typedarray::is_ctor(n) => typedarray::static_methods(n),
213        "URL" => url::STATIC_METHODS,
214        "url" => url::MODULE_METHODS,
215        "net" => net::MODULE_METHODS,
216        "http" => http::MODULE_METHODS,
217        "stream" | "Stream" => stream::METHODS,
218        n if stream::is_class(n) => stream::STATIC_METHODS,
219        "worker_threads" => worker_threads::METHODS,
220        "zlib" => zlib::MODULE_METHODS,
221        "querystring" => querystring::METHODS,
222        "tty" => tty::METHODS,
223        "process" => process::METHODS,
224        "EventEmitter" => events::STATIC_METHODS,
225        "console" => console::METHODS,
226        "child_process" => child_process::METHODS,
227        "dns" => dns::METHODS,
228        "dns/promises" => dns::PROMISES_METHODS,
229        "punycode" => punycode::METHODS,
230        "timers" => timers::METHODS,
231        "timers/promises" => timers::PROMISES_METHODS,
232        "perf_hooks" => perf_hooks::METHODS,
233        "performance" => perf_hooks::PERFORMANCE_METHODS,
234        "async_hooks" => async_hooks::METHODS,
235        "AsyncResource" => async_hooks::RESOURCE_STATIC_METHODS,
236        "AsyncLocalStorage" => async_hooks::ALS_STATIC_METHODS,
237        "util/types" => util_types::METHODS,
238        "diagnostics_channel" => diagnostics_channel::METHODS,
239        "v8" => v8::METHODS,
240        "readline" => readline::METHODS,
241        "readline/promises" => readline::PROMISES_METHODS,
242        "vm" => vm::METHODS,
243        "fs/promises" => fs_promises::METHODS,
244        "dgram" => dgram::MODULE_METHODS,
245        "tls" => tls::MODULE_METHODS,
246        "https" => https::MODULE_METHODS,
247        "repl" => repl::METHODS,
248        "cluster" => cluster::METHODS,
249        "domain" => domain::METHODS,
250        "http2" => http2::METHODS,
251        "trace_events" => trace_events::METHODS,
252        "module" => node_module::METHODS,
253        "Module" => node_module::MODULE_STATIC_METHODS,
254        "stream/consumers" => stream_consumers::METHODS,
255        "stream/promises" => stream_promises::METHODS,
256        _ => &[],
257    }
258}
259
260/// Class/constructor members a namespace re-exports as values rather than
261/// callable methods (`require('buffer').Buffer`, `require('url').URL`). They are
262/// enumerable own keys too, so `for (k in buffer)` sees `Buffer`.
263pub fn namespace_ctors(ns: &str) -> &'static [&'static str] {
264    match ns {
265        "buffer" => &["Buffer", "Blob", "File"],
266        "stream" | "Stream" => stream::CLASSES,
267        "url" => &["URL", "URLSearchParams"],
268        "EventEmitter" => &["EventEmitter"],
269        "async_hooks" => &["AsyncLocalStorage", "AsyncResource"],
270        "string_decoder" => &["StringDecoder"],
271        "assert" => &["AssertionError"],
272        "console" => &["Console"],
273        "vm" => &["Script"],
274        "fs" => &["promises", "Dirent", "Stats"],
275        // `stream/web` exports nothing BUT classes (`METHODS` is empty), so
276        // without this arm the namespace had no enumerable key at all: measured
277        // against node v26.7.0, `Object.keys(require('stream/web')).length` was
278        // 0 here and 18 there, even though every one of the classes resolved
279        // fine through `constant`. A namespace that answers property reads but
280        // enumerates empty breaks the copy-the-module pattern
281        // (`{ ...require('stream/web') }`, `for (k in web)`).
282        "stream/web" => stream_web::CLASSES,
283        _ => &[],
284    }
285}
286
287/// The enumerable own keys of the builtin namespace `ns` — what `for (key in ns)`
288/// and `Object.keys(ns)` yield. These are the members node-js ACTUALLY
289/// implements, not Node's full export list, so a package that copies a namespace
290/// key-by-key (safer-buffer clones `buffer` and `Buffer`) ends up with exactly the
291/// working set rather than an empty object.
292/// Whether a stdlib namespace's statics are ENUMERABLE own properties. A core
293/// module's exports and a node or WebIDL class's statics (`Buffer.from`,
294/// `URL.canParse`) are; an ECMAScript intrinsic constructor's are not
295/// (`Iterator.from`, `Iterator.concat`).
296pub fn namespace_statics_enumerable(ns: &str) -> bool {
297    ns != "Iterator"
298}
299
300/// Non-callable members a namespace exports as enumerable VALUES — the nested
301/// modules and cross-links (`timers.promises`, `assert.strict`, `path.posix`,
302/// `crypto.subtle`). Listed apart from [`namespace_ctors`] because they are
303/// values rather than constructors; like `fs.promises` among the ctors, each
304/// read resolves through [`constant`] before any method thunk is considered.
305pub fn namespace_values(ns: &str) -> &'static [&'static str] {
306    match ns {
307        "timers" | "readline" | "stream" | "Stream" => &["promises"],
308        "dns" => dns::VALUE_KEYS,
309        "assert" => &["strict"],
310        "EventEmitter" => &[
311            "usingDomains",
312            "captureRejectionSymbol",
313            "captureRejections",
314            "errorMonitor",
315            "defaultMaxListeners",
316        ],
317        "path" | "path/win32" => &["sep", "delimiter", "win32", "posix"],
318        "crypto" => &["constants", "webcrypto", "subtle"],
319        "os" => &["constants", "EOL", "devNull"],
320        "fs" | "fs/promises" | "http2" => &["constants"],
321        "buffer" => &[
322            "kMaxLength",
323            "kStringMaxLength",
324            "constants",
325            "INSPECT_MAX_BYTES",
326        ],
327        "http" => &["METHODS", "STATUS_CODES", "globalAgent"],
328        "https" => &["globalAgent"],
329        "perf_hooks" => &["performance", "constants"],
330        "worker_threads" => &["isMainThread", "threadId", "parentPort", "workerData"],
331        "cluster" => &[
332            "isWorker",
333            "isMaster",
334            "isPrimary",
335            "workers",
336            "settings",
337            "SCHED_NONE",
338            "SCHED_RR",
339            "schedulingPolicy",
340        ],
341        "domain" => &["active"],
342        _ => &[],
343    }
344}
345
346pub fn namespace_keys(ns: &str) -> Vec<String> {
347    // A singleton's members are inherited from its class prototype; it owns
348    // none (`Object.keys(performance)` is `[]`).
349    if singleton_class(ns).is_some() {
350        return Vec::new();
351    }
352    // The `require.cache` view enumerates the resolved filenames it holds.
353    if ns == crate::builtins::REQUIRE_CACHE {
354        return crate::module::cache_keys();
355    }
356    let mut out: Vec<String> = namespace_ctors(ns)
357        .iter()
358        .chain(namespace_values(ns))
359        .map(|s| s.to_string())
360        .collect();
361    for m in namespace_methods(ns) {
362        // A dotted entry (`util`'s `types.isMap`, `process`'s `hrtime.bigint`)
363        // is a dispatch path into a member's own namespace, not a key of this
364        // one; `Object.keys(util)` listed seven of them.
365        if !m.contains('.') && !out.iter().any(|k| k == m) {
366            out.push((*m).to_string());
367        }
368    }
369    // A core module enumerates in NODE's order (measured into `CORE_KEYS`),
370    // listing only what this frontend implements. This runs under the host
371    // borrow (`for-in`), so it consults the static lists above and never
372    // reads a value.
373    if ns != "process" {
374        if let Some(theirs) = core_keys(ns) {
375            return theirs
376                .iter()
377                .filter(|k| out.iter().any(|o| o == *k))
378                .map(|k| (*k).to_string())
379                .collect();
380        }
381    }
382    out
383}
384
385/// node's `Object.keys(require(id))` for the core module spelled `ns`.
386pub fn core_keys(ns: &str) -> Option<&'static [&'static str]> {
387    let t = crate::core_arity::CORE_KEYS;
388    t.binary_search_by(|(k, _)| (*k).cmp(ns))
389        .ok()
390        .map(|i| t[i].1)
391}
392
393/// Dispatch a resolved stdlib builtin (`assert`, or `namespace.method`). Returns
394/// `None` if `name` is not a stdlib builtin (the caller falls through to the core
395/// builtin table).
396pub fn call(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
397    if name == "assert" {
398        return Some(assert::assert_ok(args));
399    }
400    let (ns, m) = name.split_once('.')?;
401    Some(match ns {
402        "fs" => fs::call(m, args)?,
403        "path" => path::call(path::Flavor::Posix, m, args)?,
404        "path/win32" => path::call(path::Flavor::Win32, m, args)?,
405        "os" => os::call(m, args)?,
406        "util" => util::call(m, args)?,
407        "assert" => assert::call(m, args)?,
408        "assertStrict" => assert::strict_call(m, args)?,
409        "crypto" => crypto::call(m, args)?,
410        // `webcrypto`'s two random helpers are the same implementations the
411        // node-flavoured `crypto` module exposes.
412        "webcrypto" => crypto::call(m, args)?,
413        "SubtleCrypto" => crypto::subtle_call(m, args)?,
414        "Buffer" => buffer::static_call(m, args)?,
415        "buffer" if m == "Buffer" => Ok(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into())))),
416        "buffer" => buffer::module_call(m, args)?,
417        "Date" => date::static_call(m, args)?,
418        "Response" | "AbortSignal" => fetch::static_call(ns, m, args)?,
419        "Iterator" => iterator::static_call(m, args)?,
420        n if typedarray::is_ctor(n) => typedarray::static_call(n, m, args)?,
421        "URL" => url::static_call(m, args)?,
422        "url" if m == "URL" => Ok(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
423        "url" => url::call(m, args)?,
424        "net" => net::call(m, args)?,
425        "http" => http::call(m, args)?,
426        "stream" | "Stream" => stream::call(m, args)?,
427        "worker_threads" => worker_threads::call(m, args)?,
428        "zlib" => zlib::call(m, args)?,
429        "querystring" => querystring::call(m, args)?,
430        "tty" => tty::call(m, args)?,
431        "process" => process::call(m, args)?,
432        "EventEmitter" if m == "EventEmitter" => Ok(with_host(|h| {
433            h.alloc(JsObj::Builtin("EventEmitter".into()))
434        })),
435        "EventEmitter" => events::static_call(m, args)?,
436        n if stream::is_class(n) => stream::static_call(n, m, args)?,
437        "console" => console::call(m, args)?,
438        "child_process" => child_process::call(m, args)?,
439        "dns" => dns::call(m, args)?,
440        "punycode" => punycode::call(m, args)?,
441        "timers" => timers::call(m, args)?,
442        "timers/promises" => timers::promises_call(m, args)?,
443        "perf_hooks" | "performance" => perf_hooks::call(m, args)?,
444        "async_hooks" => async_hooks::call(m, args)?,
445        "AsyncResource" => async_hooks::static_call(m, args)?,
446        "AsyncLocalStorage" => async_hooks::als_static_call(m, args)?,
447        "util/types" => util_types::call(m, args)?,
448        "diagnostics_channel" => diagnostics_channel::call(m, args)?,
449        "v8" => v8::call(m, args)?,
450        "readline" => readline::call(m, args)?,
451        "readline/promises" => readline::promises_call(m, args)?,
452        "vm" => vm::call(m, args)?,
453        "fs/promises" => fs_promises::call(m, args)?,
454        "dgram" => dgram::call(m, args)?,
455        // dns/promises: getServers/setServers/get|setDefaultResultOrder are shared
456        // sync fns; every other method maps to dns's `promise<Cap>` variant.
457        "dns/promises" => match m {
458            "getServers" | "setServers" | "getDefaultResultOrder" | "setDefaultResultOrder" => {
459                dns::call(m, args)?
460            }
461            _ => {
462                let mut pm = String::from("promise");
463                let mut cs = m.chars();
464                if let Some(c) = cs.next() {
465                    pm.extend(c.to_uppercase());
466                    pm.push_str(cs.as_str());
467                }
468                dns::call(&pm, args)?
469            }
470        },
471        "tls" => tls::call(m, args)?,
472        "https" => https::call(m, args)?,
473        "repl" => repl::call(m, args)?,
474        "cluster" => cluster::call(m, args)?,
475        "domain" => domain::call(m, args)?,
476        "http2" => http2::call(m, args)?,
477        "trace_events" => trace_events::call(m, args)?,
478        "module" => node_module::call(m, args)?,
479        "Module" => node_module::static_call(m, args)?,
480        "stream/consumers" => stream_consumers::call(m, args)?,
481        "stream/promises" => stream_promises::call(m, args)?,
482        _ if is_unimplemented(ns) => Err(format!("Error: {ns}.{m} is not implemented in node-js")),
483        _ => return None,
484    })
485}
486
487/// A non-function constant on a stdlib namespace (`path.sep`, `os.EOL`,
488/// `buffer.Buffer`, `url.URL`), reachable via `namespace_property`.
489pub fn constant(ns: &str, name: &str) -> Option<Value> {
490    // A module's `constants` object is ONE object for the life of the process
491    // (`fs.constants === fs.constants`, and `fs/promises` shares `fs`'s); each
492    // read built a fresh one.
493    if name == "constants" {
494        let key = if ns == "fs/promises" { "fs" } else { ns };
495        return cached_module_value(key, || constant_uncached(ns, name));
496    }
497    constant_uncached(ns, name)
498}
499
500/// One value per `key`, built by `make` on first use.
501fn cached_module_value(key: &str, make: impl FnOnce() -> Option<Value>) -> Option<Value> {
502    thread_local! {
503        static CACHE: std::cell::RefCell<std::collections::HashMap<String, Value>> =
504            std::cell::RefCell::new(std::collections::HashMap::new());
505    }
506    if let Some(v) = CACHE.with(|c| c.borrow().get(key).cloned()) {
507        return Some(v);
508    }
509    let v = make()?;
510    CACHE.with(|c| c.borrow_mut().insert(key.to_string(), v.clone()));
511    Some(v)
512}
513
514fn constant_uncached(ns: &str, name: &str) -> Option<Value> {
515    match ns {
516        "Event" => event_target::constant(name),
517        // Both flavors carry `.posix`/`.win32` cross-links, exactly as Node's
518        // `posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix`.
519        "path" | "path/win32" if name == "posix" => {
520            Some(with_host(|h| h.alloc(JsObj::Builtin("path".into()))))
521        }
522        "path" | "path/win32" if name == "win32" => {
523            Some(with_host(|h| h.alloc(JsObj::Builtin("path/win32".into()))))
524        }
525        "path" => path::constant(path::Flavor::Posix, name),
526        "path/win32" => path::constant(path::Flavor::Win32, name),
527        "os" => os::constant(name),
528        // node caches the frozen bundled store, so every read is one array.
529        "tls" if name == "rootCertificates" => {
530            cached_module_value("tls.rootCertificates", || tls::constant(name))
531        }
532        "tls" => tls::constant(name),
533        // `fs.constants` and `crypto.constants` were absent, so
534        // `fs.constants.O_RDONLY` and `crypto.constants.RSA_PKCS1_PADDING` —
535        // which libraries pass straight through to `open` and to RSA — read as
536        // `undefined`.
537        "fs" | "fs/promises" if name == "constants" => Some(constants::object(&constants::fs())),
538        // `fs.Stats` / `fs.Dirent`: the classes of `statSync` and of a
539        // `withFileTypes` entry, so `stat instanceof fs.Stats` holds.
540        "fs" if matches!(name, "Stats" | "Dirent") => {
541            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
542        }
543        "crypto" if name == "constants" => Some(constants::object(&constants::crypto())),
544        // `crypto.webcrypto` is the WHATWG surface; `globalThis.crypto` is the
545        // same object. Only its two random helpers and `subtle.digest` are
546        // implemented — see `crypto::WEBCRYPTO_METHODS`.
547        // `crypto.subtle` is `crypto.webcrypto.subtle`; it was absent.
548        "crypto" if name == "subtle" => Some(with_host(|h| {
549            h.alloc(JsObj::Builtin("SubtleCrypto".into()))
550        })),
551        // `timers.promises` is the `timers/promises` module; it was absent.
552        "timers" if name == "promises" => Some(with_host(|h| {
553            h.alloc(JsObj::Builtin("timers/promises".into()))
554        })),
555        "crypto" if name == "webcrypto" => {
556            Some(with_host(|h| h.alloc(JsObj::Builtin("webcrypto".into()))))
557        }
558        "webcrypto" if name == "subtle" => Some(with_host(|h| {
559            h.alloc(JsObj::Builtin("SubtleCrypto".into()))
560        })),
561        // `EventEmitter.defaultMaxListeners` is a DATA property, so it belongs
562        // here rather than among the static methods (which would make it read
563        // as a function). It was absent: node reports 10.
564        "EventEmitter" | "events" if name == "defaultMaxListeners" => Some(Value::Float(10.0)),
565        // The capture-rejections switch (off by default), the symbol a class
566        // implements to receive captured rejections, the legacy domain flag,
567        // and the private symbol whose listeners monitor `error` events. All
568        // four were absent.
569        "EventEmitter" | "events" if matches!(name, "captureRejections" | "usingDomains") => {
570            Some(Value::Bool(false))
571        }
572        "EventEmitter" | "events" if name == "captureRejectionSymbol" => {
573            Some(with_host(|h| h.symbol_for("nodejs.rejection")))
574        }
575        "EventEmitter" | "events" if name == "errorMonitor" => {
576            Some(with_host(|h| h.internal_symbol("events.errorMonitor")))
577        }
578        // `Buffer.poolSize` is a DATA property, not a method, so it belongs here
579        // rather than in `STATIC_METHODS` (which would make it read as a
580        // function). It was absent entirely: `Buffer.poolSize` was `undefined`
581        // where node v26.7.0 reports 65536. node-js allocates each Buffer on its
582        // own, so this is the documented constant, not a live allocator figure.
583        "Buffer" if name == "poolSize" => Some(Value::Float(65536.0)),
584        // `Uint8Array.BYTES_PER_ELEMENT` is a property of the CONSTRUCTOR as
585        // well as of every instance (23.2.6.2 / 23.2.5.1); only the instance
586        // carried it, so the constructor read `undefined` — the form the
587        // `byteLength = n * Ctor.BYTES_PER_ELEMENT` idiom uses.
588        n if typedarray::is_ctor(n) && name == "BYTES_PER_ELEMENT" => {
589            // `ArrayBuffer`/`DataView` are element-less and report nothing.
590            typedarray::ELEMENT_KINDS
591                .contains(&n)
592                .then(|| Value::Float(typedarray::bytes_per_element(n) as f64))
593        }
594        "buffer" if name == "Buffer" => {
595            Some(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into()))))
596        }
597        "buffer" if matches!(name, "Blob" | "File") => {
598            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
599        }
600        "buffer" => buffer::module_constant(name),
601        "url" if name == "URL" => Some(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
602        "net" => net::constant(name),
603        "tty" => tty::constant(name),
604        "repl" => repl::constant(name),
605        // `readline.promises` is the same module reached as a property, so the
606        // cross-link is checked before the shared constant table.
607        "readline" if name == "promises" => Some(with_host(|h| {
608            h.alloc(JsObj::Builtin("readline/promises".into()))
609        })),
610        "readline" | "readline/promises" => readline::constant(name),
611        "diagnostics_channel" => diagnostics_channel::constant(name),
612        "v8" => v8::constant(name),
613        "console" if name == "Console" => {
614            Some(with_host(|h| h.alloc(JsObj::Builtin("Console".into()))))
615        }
616        "assert" if name == "AssertionError" => Some(with_host(|h| {
617            h.alloc(JsObj::Builtin("AssertionError".into()))
618        })),
619        "assert" if name == "strict" => Some(with_host(|h| {
620            h.alloc(JsObj::Builtin("assertStrict".into()))
621        })),
622        // Every stream class's `.prototype` is the REAL prototype object the
623        // hierarchy hangs off, not a `Builtin("X.prototype")` handle — an ES5
624        // subclass reads it and passes it to `Object.create`, and
625        // `getPrototypeOf(Readable.prototype)` has to reach `Stream.prototype`.
626        n if stream::is_class(n) && name == "prototype" => with_host(|h| h.ensure_ctor_proto(n)),
627        "stream" | "Stream" => stream::constant(name),
628        "http" => http::constant(name),
629        "string_decoder" if name == "StringDecoder" => Some(with_host(|h| {
630            h.alloc(JsObj::Builtin("StringDecoder".into()))
631        })),
632        "process" => process::constant(name),
633        "EventEmitter" if name == "EventEmitter" => Some(with_host(|h| {
634            h.alloc(JsObj::Builtin("EventEmitter".into()))
635        })),
636        "perf_hooks" | "performance" => perf_hooks::constant(name),
637        "dns" => dns::constant(name),
638        "punycode" => punycode::constant(name),
639        "async_hooks" if matches!(name, "AsyncLocalStorage" | "AsyncResource") => {
640            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
641        }
642        "vm" if name == "Script" => Some(with_host(|h| h.alloc(JsObj::Builtin("Script".into())))),
643        "url" if name == "URLSearchParams" => Some(with_host(|h| {
644            h.alloc(JsObj::Builtin("URLSearchParams".into()))
645        })),
646        "fs" if name == "promises" => {
647            Some(with_host(|h| h.alloc(JsObj::Builtin("fs/promises".into()))))
648        }
649        "worker_threads" => worker_threads::constant(name),
650        "https" => https::constant(name),
651        "cluster" => cluster::constant(name),
652        "domain" => domain::constant(name),
653        "http2" => http2::constant(name),
654        "module" => node_module::constant(name),
655        "Module" => node_module::static_constant(name),
656        "stream/web" => stream_web::constant(name),
657        // util.types / util.TextEncoder|TextDecoder / util.MIMEType|MIMEParams.
658        "util" => util::constant(name),
659        // crypto class-constructor exports (require('crypto').Sign etc.) — the
660        // instances are made by factory fns, but the ctor names must resolve.
661        "crypto"
662            if matches!(
663                name,
664                "Sign"
665                    | "Verify"
666                    | "KeyObject"
667                    | "DiffieHellman"
668                    | "ECDH"
669                    | "X509Certificate"
670                    | "Hash"
671                    | "Hmac"
672                    | "Cipheriv"
673                    | "Decipheriv"
674            ) =>
675        {
676            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
677        }
678        _ => None,
679    }
680}
681
682/// Construct a stdlib class instance (`new URL(...)`, `new EventEmitter()`, and
683/// `new Buffer(...)` legacy), reachable from `construct_builtin`. `None` if `name`
684/// is not a stdlib constructor.
685pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
686    match name {
687        "URL" => Some(url::construct(args)),
688        "EventEmitter" => Some(Ok(events::new_emitter())),
689        // `new Buffer(x)` and the deprecated call form `Buffer(x)` are the same
690        // operation, and it is NOT simply `Buffer.from`: a NUMBER allocates that
691        // many zero bytes, where `Buffer.from(3)` is a TypeError in Node.
692        // Measured on node v26.7.0, `new Buffer(3)` and `Buffer(3)` are both
693        // `<Buffer 00 00 00>` (zero-filled since the `Buffer.alloc` semantics
694        // landed), while `new Buffer('ab')` and `new Buffer([1,2])` behave as
695        // `from`. Routing everything through `from` made `new Buffer(3)` one byte
696        // long.
697        "Buffer" => {
698            let numeric = matches!(args.first(), Some(Value::Int(_)) | Some(Value::Float(_)))
699                && args.len() == 1;
700            let m = if numeric { "alloc" } else { "from" };
701            Some(buffer::static_call(m, args).unwrap_or(Ok(Value::Undef)))
702        }
703        "Date" => Some(date::construct(args)),
704        "StringDecoder" => Some(string_decoder::construct(args)),
705        "WeakRef" => Some(typedarray::construct_weakref(args)),
706        "FinalizationRegistry" => Some(typedarray::construct_finalization_registry(args)),
707        n if fetch::is_class(n) => fetch::construct(n, args),
708        n if event_target::is_class(n) => event_target::construct(n, args),
709        "TextEncoder" => Some(typedarray::construct_text_encoder()),
710        "TextDecoder" => Some(typedarray::construct_text_decoder(args)),
711        "DataView" => Some(typedarray::construct_dataview(args)),
712        n if typedarray::is_ctor(n) => Some(typedarray::construct(n, args)),
713        n if stream::is_class(n) => Some(Ok(stream::construct(n, args))),
714        "AsyncLocalStorage" | "AsyncResource" => async_hooks::construct(name, args),
715        "Script" => Some(vm::construct(args)),
716        "URLSearchParams" => Some(url::construct_search_params(args)),
717        "Worker" => Some(worker_threads::construct_worker(args)),
718        "Domain" => Some(domain::construct(args)),
719        "Tracing" => Some(trace_events::construct(args)),
720        "Blob" => Some(buffer::construct_blob(args)),
721        "File" => Some(buffer::construct_file(args)),
722        "AssertionError" => Some(Ok(assert::construct_assertion_error(args))),
723        "X509Certificate" => Some(crypto::construct_x509(args)),
724        "MIMEType" => Some(util::construct_mime_type(args)),
725        "MIMEParams" => Some(util::construct_mime_params(args)),
726        "Resolver" => Some(Ok(dns::construct_resolver(args))),
727        "ReadStream" | "WriteStream" => Some(Ok(tty::construct(name, args))),
728        "MessageChannel" => Some(worker_threads::construct_message_channel(args)),
729        "BroadcastChannel" => Some(worker_threads::construct_broadcast_channel(args)),
730        "PerformanceObserver" => Some(perf_hooks::construct(name, args)),
731        // `performance`, `crypto`, `crypto.subtle` are the only instances.
732        n if illegal_constructor(n) => Some(Err(crate::host::coded_error(
733            "TypeError",
734            "ERR_ILLEGAL_CONSTRUCTOR",
735            "Illegal constructor",
736        ))),
737        "REPLServer" | "Recoverable" => Some(repl::construct(name, args)),
738        "Interface" => Some(readline::construct(args)),
739        "Console" => Some(console::construct(args)),
740        "Serializer" | "DefaultSerializer" | "Deserializer" | "DefaultDeserializer" => {
741            Some(v8::construct(name, args))
742        }
743        // net/http constructors: their `construct` already returns Option<Result>.
744        "Socket" | "Stream" | "Server" | "SocketAddress" | "BlockList" => {
745            net::construct(name, args)
746        }
747        "Agent" | "http.Server" => http::construct(name, args),
748        _ => None,
749    }
750}
751
752/// The hidden `@@native` instance tag of `recv` (`"Buffer"`/`"Hash"`/
753/// `"EventEmitter"`/`"URL"`), or `None` for a non-native object.
754pub fn native_tag(recv: &Value) -> Option<String> {
755    with_host(|h| match h.get(recv) {
756        Some(JsObj::Object(p)) => p.get("@@native").map(|v| h.str_of(v)),
757        _ => None,
758    })
759}
760
761/// Native instance tags whose `instance_call` implements `toJSON()`, which
762/// `JSON.stringify` must invoke before serializing the value. (`instance_has_method`
763/// only covers tags with a declared method table; `Date` dispatches directly.)
764pub fn has_to_json(tag: &str) -> bool {
765    matches!(tag, "Buffer" | "Date" | "URL" | "MIMEType" | "MIMEParams")
766}
767
768/// Whether `name` is a method of a native instance tagged `tag`. Used by
769/// `get_property` so a method *read* (`server.listen.apply(...)`, the express
770/// listen path) yields a bound method rather than `undefined` — the method is
771/// still dispatched through `instance_call` when the bound method is invoked.
772pub fn instance_has_method(tag: &str, name: &str) -> bool {
773    // A class INHERITS its parent's methods: `equals` is on `KeyObject` and a
774    // `SecretKeyObject` answers it. Asking only the leaf's own list reported
775    // `false` for a method the prototype chain really carries.
776    let mut ctor = Some(tag);
777    while let Some(t) = ctor {
778        let (base, emitter) = instance_method_lists(t);
779        if base.contains(&name) || emitter.contains(&name) {
780            return true;
781        }
782        ctor = native_parent(t);
783    }
784    false
785}
786
787/// The method names a native instance tagged `tag` carries, as
788/// `(its own list, the EventEmitter surface it also gets or empty)`.
789///
790/// Split out of [`instance_has_method`] so the same table can be *enumerated*,
791/// not only queried: `host::ensure_ctor_proto` builds a native constructor's
792/// real `.prototype` object from it. A predicate alone would have forced a
793/// second, hand-maintained list of the same names — the drift that put
794/// `listeners` on nine dispatchers and not on the three that run.
795/// The native class whose prototype `ctor`'s prototype inherits from, if any.
796///
797/// Only the stream hierarchy has one: node's is
798/// `Readable/Writable/Duplex/Transform/PassThrough → Stream → EventEmitter`,
799/// and every prototype used to hang straight off `Object.prototype` instead, so
800/// `new Readable() instanceof Stream` and `instanceof EventEmitter` both read
801/// false and an ES5 subclass built on `Object.create(Stream.prototype)`
802/// inherited nothing.
803pub fn native_parent(ctor: &str) -> Option<&'static str> {
804    match ctor {
805        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" => Some("Stream"),
806        "Stream" => Some("EventEmitter"),
807        // Emitter-backed native classes: `child instanceof EventEmitter` holds
808        // in node, and the emitter methods are inherited.
809        "ChildProcess" | "Socket" | "Server" => Some("EventEmitter"),
810        // `AbortSignal` is an `EventTarget` in node, and `CustomEvent` an `Event`,
811        // so `signal instanceof EventTarget` holds and both inherit the base
812        // class's methods.
813        "AbortSignal" => Some("EventTarget"),
814        "CustomEvent" => Some("Event"),
815        // `crypto.createSecretKey` and `generateKeyPair` hand back the LEAF
816        // classes, not `KeyObject`: node's chain is
817        // `SecretKeyObject → KeyObject` and
818        // `PublicKeyObject → AsymmetricKeyObject → KeyObject`, which is why
819        // `symmetricKeySize` exists on one and `asymmetricKeyType` on the other.
820        // Everything was tagged `KeyObject`, so `key.constructor.name` read
821        // `KeyObject` and neither accessor had a home.
822        "SecretKeyObject" | "AsymmetricKeyObject" => Some("KeyObject"),
823        "PublicKeyObject" | "PrivateKeyObject" => Some("AsymmetricKeyObject"),
824        _ => None,
825    }
826}
827
828/// The ACCESSOR properties a native class's prototype carries, as
829/// `(name, has_setter)`, and the `Symbol.toStringTag` it stamps (empty for
830/// none).
831///
832/// Node keeps these OFF the instance: `Object.keys(new AbortController())` is
833/// empty and `JSON.stringify` of one is `{}`, because `signal` is a getter on
834/// `AbortController.prototype`. Storing them as own data properties — what this
835/// did — leaked them into every enumeration, every spread and every
836/// serialization of an object that merely held one.
837///
838/// The getter reads the instance's hidden `@@<name>` slot, so a construction
839/// site stores the value there rather than under the public name.
840/// Run whatever a class has to do after one of its accessor SETTERS stored a
841/// value — for a `URL`, rewriting the fields derived from the one just written.
842///
843/// Without this the setter was a plain slot write: `u.protocol = 'https:'` read
844/// back as `https:` while `u.href` still showed `http://…`, so the object
845/// disagreed with itself.
846/// Whether a class's prototype MEMBERS are enumerable, as node defines them.
847///
848/// Most are: `for (const k in new URL('http://a/'))` walks `href`, `origin` and
849/// the rest, because a WebIDL interface's members are enumerable and node
850/// defines its own classes the same way. The exceptions are the ones written as
851/// ES classes — `vm.Script` and the `KeyObject` family — whose methods are
852/// non-enumerable like any class method's.
853///
854/// `constructor` is never enumerable, in either kind.
855/// Methods a class defines AFTER its accessors.
856///
857/// Prototype members enumerate in definition order, and node defines
858/// `URL.prototype` as `toString`, then every accessor, then `toJSON` — so a
859/// `for-in` over a URL ends with `toJSON` rather than starting with it.
860pub fn instance_late_methods(tag: &str) -> &'static [&'static str] {
861    match tag {
862        "URL" => &["toJSON"],
863        "Event" => event_target::EVENT_LATE_METHODS,
864        _ => &[],
865    }
866}
867
868/// How `util.inspect` renders an instance of `tag`, as
869/// `(accessors to show, whether to print the class name)`.
870///
871/// Node gives these classes a custom inspect that prints a CURATED set of
872/// accessor values — a `URL` shows all twelve, an `AbortSignal` shows only
873/// `aborted`, and a `KeyObject` shows none. With the values moved off the
874/// instance and onto prototype getters, the generic own-property renderer has
875/// nothing left to print, so every one of them rendered as an empty `{}`.
876///
877/// `TextEncoder` is the odd one: node's custom inspect omits the class name, so
878/// it prints as a bare `{ encoding: 'utf-8' }`.
879pub fn instance_inspect_members(tag: &str) -> (&'static [&'static str], bool) {
880    match tag {
881        "URL" => (
882            &[
883                "href",
884                "origin",
885                "protocol",
886                "username",
887                "password",
888                "host",
889                "hostname",
890                "port",
891                "pathname",
892                "search",
893                "searchParams",
894                "hash",
895            ],
896            true,
897        ),
898        "AbortController" => (&["signal"], true),
899        "AbortSignal" => (&["aborted"], true),
900        // node's custom inspect for an `Event` prints these four; a `CustomEvent`
901        // shows the same four (not `detail`).
902        "Event" | "CustomEvent" => (
903            &["type", "defaultPrevented", "cancelable", "timeStamp"],
904            true,
905        ),
906        "TextDecoder" => (&["encoding", "fatal", "ignoreBOM"], true),
907        "TextEncoder" => (&["encoding"], false),
908        _ => (&[], true),
909    }
910}
911
912/// Whether node gives instances of `tag` a CUSTOM `util.inspect` — one that
913/// prints a curated view and nothing else. Such a class hides a subclass's own
914/// properties and the `[Tag]` suffix: `class S extends AbortController {}` is
915/// `S { signal: … }`, and an `EventTarget` subclass prints ` {}` even
916/// with own fields.
917pub fn instance_inspect_is_custom(tag: &str) -> bool {
918    tag == "EventTarget" || !instance_inspect_members(tag).0.is_empty()
919}
920
921pub fn instance_members_enumerable(tag: &str) -> bool {
922    !matches!(
923        tag,
924        "Script"
925            | "KeyObject"
926            | "SecretKeyObject"
927            | "AsymmetricKeyObject"
928            | "PublicKeyObject"
929            | "PrivateKeyObject"
930    )
931}
932
933pub fn instance_accessor_written(
934    tag: &str,
935    key: &str,
936    recv: &Value,
937    value: &Value,
938) -> Result<(), String> {
939    // A URL component goes through the URL Standard's setter for it.
940    if tag == "URL" {
941        return url::set_component(recv, key, value);
942    }
943    // `Event.cancelBubble` / `returnValue` are verbs, not stored values.
944    if tag == "Event" {
945        return event_target::accessor_written(recv, key, value);
946    }
947    // `signal.onabort = f`: node's `defineEventHandler` registers the handler's
948    // listener slot on the FIRST assignment; the slot reads `@@onabort` at
949    // dispatch time, and a non-function reads back as `null`.
950    if tag == "AbortSignal" && key == "onabort" {
951        if !with_host(|h| crate::host::is_callable(h, value)) {
952            let null = with_host(|h| h.null());
953            with_host(|h| {
954                if let Some(JsObj::Object(p)) = h.get_mut(recv) {
955                    p.insert("@@onabort".into(), null);
956                }
957            });
958        }
959        event_target::ensure_handler_slot(recv, "abort");
960    }
961    Ok(())
962}
963
964pub fn instance_accessors(tag: &str) -> (&'static [(&'static str, bool)], &'static str) {
965    match tag {
966        "AbortController" => (&[("signal", false)], "AbortController"),
967        "AbortSignal" => (
968            &[("aborted", false), ("reason", false), ("onabort", true)],
969            "AbortSignal",
970        ),
971        "KeyObject" => (&[("type", false)], "KeyObject"),
972        "SecretKeyObject" => (&[("symmetricKeySize", false)], ""),
973        "AsymmetricKeyObject" => (
974            &[
975                ("asymmetricKeyType", false),
976                ("asymmetricKeyDetails", false),
977            ],
978            "",
979        ),
980        "TextEncoder" => (&[("encoding", false)], "TextEncoder"),
981        "StringDecoder" => (string_decoder::ACCESSORS, ""),
982        "Performance" => (&[("timeOrigin", false)], "Performance"),
983        "Crypto" => (&[("subtle", false)], "Crypto"),
984        "webcrypto.SubtleCrypto" => (&[], "SubtleCrypto"),
985        "CryptoKey" => (
986            &[
987                ("type", false),
988                ("extractable", false),
989                ("algorithm", false),
990                ("usages", false),
991            ],
992            "CryptoKey",
993        ),
994        "EventTarget" => (&[], "EventTarget"),
995        "Event" => (event_target::EVENT_ACCESSORS, "Event"),
996        "CustomEvent" => (&[("detail", false)], "CustomEvent"),
997        // `origin` and `searchParams` are the two a caller cannot assign.
998        "URL" => (
999            &[
1000                ("href", true),
1001                ("origin", false),
1002                ("protocol", true),
1003                ("username", true),
1004                ("password", true),
1005                ("host", true),
1006                ("hostname", true),
1007                ("port", true),
1008                ("pathname", true),
1009                ("search", true),
1010                ("searchParams", false),
1011                ("hash", true),
1012            ],
1013            "URL",
1014        ),
1015        "TextDecoder" => (
1016            &[("encoding", false), ("fatal", false), ("ignoreBOM", false)],
1017            "TextDecoder",
1018        ),
1019        _ => (&[], ""),
1020    }
1021}
1022
1023pub fn instance_method_lists(tag: &str) -> (&'static [&'static str], &'static [&'static str]) {
1024    // Shared EventEmitter surface for the emitter-backed instances. Read from
1025    // `events::METHODS` so what an instance ADVERTISES here can never drift from
1026    // what the dispatchers actually delegate.
1027    const EMITTER: &[&str] = events::METHODS;
1028    let base: &[&str] = match tag {
1029        "Timeout" => timers::TIMEOUT_METHODS,
1030        "IntervalIterator" => timers::INTERVAL_METHODS,
1031        "CollectionIterator" => &["next", "@@iterator"],
1032        "IteratorHelper" => iterator::METHODS,
1033        "Immediate" => timers::IMMEDIATE_METHODS,
1034        "Server" => &["listen", "close", "address"],
1035        "Socket" => &[
1036            "write",
1037            "end",
1038            "destroy",
1039            "pause",
1040            "resume",
1041            "setEncoding",
1042            "setKeepAlive",
1043            "setNoDelay",
1044            "setTimeout",
1045            "ref",
1046            "unref",
1047            "connect",
1048        ],
1049        "ServerResponse" => &[
1050            "writeHead",
1051            "setHeader",
1052            "getHeader",
1053            "getHeaderNames",
1054            "getHeaders",
1055            "hasHeader",
1056            "removeHeader",
1057            "write",
1058            "end",
1059            "flushHeaders",
1060        ],
1061        "IncomingMessage" => &["pause", "resume", "setEncoding", "destroy"],
1062        "Buffer" => buffer::INSTANCE_METHODS,
1063        "DataView" => typedarray::DATAVIEW_METHODS,
1064        "ArrayBuffer" => &["slice", "resize", "transfer", "transferToFixedLength"],
1065        "Date" => date::INSTANCE_METHODS,
1066        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => &[
1067            "read",
1068            "write",
1069            "end",
1070            "pipe",
1071            "pause",
1072            "resume",
1073            "setEncoding",
1074            "destroy",
1075            "push",
1076        ],
1077        // `toJSON` comes AFTER the accessors — see `instance_late_methods`.
1078        "URL" => &["toString"],
1079        "AsyncLocalStorage" => async_hooks::ALS_METHODS,
1080        "AsyncHook" => async_hooks::HOOK_METHODS,
1081        "AsyncResource" => async_hooks::RESOURCE_METHODS,
1082        "Channel" => &["subscribe", "unsubscribe", "publish"],
1083        "WriteStream" => &[
1084            "write",
1085            "end",
1086            "on",
1087            "once",
1088            "addListener",
1089            "prependListener",
1090            "removeListener",
1091            "off",
1092            "removeAllListeners",
1093            "listenerCount",
1094            "cork",
1095            "uncork",
1096            "setEncoding",
1097            "resume",
1098            "pause",
1099            "read",
1100            "pipe",
1101            "@@asyncIterator",
1102        ],
1103        "StdinIterator" => process::STDIN_ITERATOR_METHODS,
1104        // `Hash` and `Hmac` answer the same two methods (both route to
1105        // `crypto::hashlike_call`). Only `Hmac` was listed, so
1106        // `ensure_ctor_proto("Hash")` found nothing and `crypto.Hash.prototype`
1107        // read `undefined` — the ES5-subclassing hole this table exists to
1108        // close, still open for one of the two constructors it documents.
1109        // `copy` is Hash-only — an Hmac cannot be forked.
1110        "Hash" => &["update", "digest", "copy"],
1111        "Hmac" => &["update", "digest"],
1112        "Crypto" => crypto::WEBCRYPTO_METHODS,
1113        "webcrypto.SubtleCrypto" => crypto::SUBTLE_METHODS,
1114        // `performance` is the `Performance` instance; the methods it shares
1115        // with the `perf_hooks` module live on `Performance.prototype`.
1116        "Performance" => &[
1117            "clearResourceTimings",
1118            "setResourceTimingBufferSize",
1119            "now",
1120            "mark",
1121            "measure",
1122            "getEntriesByName",
1123            "getEntriesByType",
1124            "getEntries",
1125            "clearMarks",
1126            "clearMeasures",
1127            "eventLoopUtilization",
1128            "timerify",
1129        ],
1130        "StringDecoder" => string_decoder::INSTANCE_METHODS,
1131        "Interface" => readline::INTERFACE_METHODS,
1132        "ReadlineIterator" => readline::ITERATOR_METHODS,
1133        "Script" => vm::SCRIPT_METHODS,
1134        "URLSearchParams" => url::SEARCH_PARAMS_METHODS,
1135        "UdpSocket" => dgram::SOCKET_METHODS,
1136        "Worker" => worker_threads::WORKER_METHODS,
1137        "MessagePort" => worker_threads::PORT_METHODS,
1138        "TLSServer" => tls::SERVER_METHODS,
1139        "TLSSocket" => tls::SOCKET_METHODS,
1140        "HTTPSServerResponse" => https::RESPONSE_METHODS,
1141        "HTTPSClientRequest" => https::CLIENT_REQUEST_METHODS,
1142        "REPLServer" => repl::REPLSERVER_METHODS,
1143        "ClusterWorker" => cluster::WORKER_METHODS,
1144        "Domain" => domain::DOMAIN_METHODS,
1145        "Tracing" => trace_events::TRACING_METHODS,
1146        "Http2Server" => http2::SERVER_METHODS,
1147        "Http2Stream" => http2::STREAM_METHODS,
1148        "Http2Session" => http2::SESSION_METHODS,
1149        "Cipheriv" | "Decipheriv" => &["update", "final", "setAutoPadding"],
1150        "BlockList" => net::BLOCKLIST_METHODS,
1151        "ClientRequest" => http::CLIENT_REQUEST_METHODS,
1152        "Agent" => &["destroy", "getName"],
1153        "Blob" | "File" => buffer::BLOB_METHODS,
1154        "ReadStream" => tty::READ_STREAM_METHODS,
1155        "Dirent" | "Stats" | "BigIntStats" => fs::DIRENT_METHODS,
1156        "Dir" => fs::DIR_METHODS,
1157        "FSReadStream" => fs::READ_STREAM_METHODS,
1158        "FSWriteStream" => fs::WRITE_STREAM_METHODS,
1159        "Resolver" => dns::RESOLVER_METHODS,
1160        "Histogram" => perf_hooks::HISTOGRAM_METHODS,
1161        "PerformanceObserver" => perf_hooks::PERFORMANCE_OBSERVER_METHODS,
1162        "PerformanceObserverEntryList" => perf_hooks::OBSERVER_ENTRY_LIST_METHODS,
1163        "BroadcastChannel" => worker_threads::BROADCAST_CHANNEL_METHODS,
1164        "TracingChannel" => diagnostics_channel::TRACING_CHANNEL_METHODS,
1165        "Serializer" => v8::SERIALIZER_METHODS,
1166        "Deserializer" => v8::DESERIALIZER_METHODS,
1167        "Console" => console::CONSOLE_METHODS,
1168        "ChildProcess" => child_process::CHILD_PROCESS_METHODS,
1169        "ChildPipe" => child_process::CHILD_PIPE_METHODS,
1170        "Sign" => &["update", "sign"],
1171        "Verify" => &["update", "verify"],
1172        "KeyObject" => &["equals", "toCryptoKey"],
1173        // `export` is on each LEAF, since what it exports differs.
1174        "SecretKeyObject" | "PublicKeyObject" | "PrivateKeyObject" => &["export"],
1175        "DiffieHellman" => &[
1176            "generateKeys",
1177            "computeSecret",
1178            "getPrime",
1179            "getGenerator",
1180            "getPublicKey",
1181            "getPrivateKey",
1182            "setPublicKey",
1183            "setPrivateKey",
1184        ],
1185        "ECDH" => &[
1186            "generateKeys",
1187            "computeSecret",
1188            "getPublicKey",
1189            "getPrivateKey",
1190            "setPrivateKey",
1191        ],
1192        "X509Certificate" => &["toString"],
1193        "FinalizationRegistry" => &["register", "unregister"],
1194        "MIMEType" => util::MIME_TYPE_METHODS,
1195        "MIMEParams" => util::MIME_PARAMS_METHODS,
1196        t if fetch::is_class(t) => fetch::methods_for(t),
1197        "EventTarget" => event_target::EVENT_TARGET_METHODS,
1198        "Event" => event_target::EVENT_METHODS,
1199        _ => &[],
1200    };
1201    let is_emitter = matches!(
1202        tag,
1203        "Server"
1204            | "Socket"
1205            | "ServerResponse"
1206            | "IncomingMessage"
1207            | "EventEmitter"
1208            | "Readable"
1209            | "Writable"
1210            | "Duplex"
1211            | "Transform"
1212            | "PassThrough"
1213            | "Stream"
1214            | "UdpSocket"
1215            | "Worker"
1216            | "MessagePort"
1217            | "TLSServer"
1218            | "TLSSocket"
1219            | "HTTPSServerResponse"
1220            | "HTTPSClientRequest"
1221            | "ClusterWorker"
1222            | "Domain"
1223            | "Http2Server"
1224            | "Http2Stream"
1225            | "Http2Session"
1226            | "ClientRequest"
1227            | "FSReadStream"
1228            | "FSWriteStream"
1229            | "ChildProcess"
1230            | "ChildPipe"
1231    );
1232    (base, if is_emitter { EMITTER } else { &[] })
1233}
1234
1235/// Dispatch a method call on a native stdlib instance (`recv` carries a
1236/// `@@native` tag). Called from `host::call_method` before the generic object
1237/// method resolution.
1238pub fn instance_call(
1239    tag: &str,
1240    recv: &Value,
1241    method: &str,
1242    args: Vec<Value>,
1243) -> Result<Value, String> {
1244    match tag {
1245        "Buffer" => buffer::instance_call(recv, method, &args),
1246        "Timeout" | "Immediate" => timers::instance_call(recv, method, &args),
1247        "IntervalIterator" => timers::interval_call(recv, method, &args),
1248        "CollectionIterator" => match method {
1249            "next" => crate::builtins::collection_iterator_next(recv),
1250            "@@iterator" => Ok(recv.clone()),
1251            m if iterator::is_helper(m) => iterator::call(recv, m, &args),
1252            _ => Err(crate::host::type_error(&format!(
1253                "mapIterator.{method} is not a function"
1254            ))),
1255        },
1256        "IteratorHelper" => match method {
1257            "next" => iterator::helper_next(recv),
1258            "@@iterator" => Ok(recv.clone()),
1259            // Abandoning a helper marks it exhausted AND closes its source, so
1260            // a later `next` is a done step and the generator underneath runs
1261            // its `finally`.
1262            "return" => Ok(iterator::helper_return(recv)),
1263            m if iterator::is_helper(m) => iterator::call(recv, m, &args),
1264            _ => Err(crate::host::type_error(&format!(
1265                "{method} is not a function"
1266            ))),
1267        },
1268        "Date" => date::instance_call(recv, method, &args),
1269        "StringDecoder" => string_decoder::instance_call(recv, method, &args),
1270        "WeakRef" => typedarray::weakref_call(recv, method),
1271        "FinalizationRegistry" => typedarray::finalization_registry_call(recv, method, &args),
1272        "TextEncoder" => typedarray::text_encoder_call(recv, method, &args),
1273        "TextDecoder" => typedarray::text_decoder_call(recv, method, &args),
1274        "TypedArray" => typedarray::instance_call(recv, method, &args),
1275        "DataView" => typedarray::dataview_call(recv, method, &args),
1276        // An `ArrayBuffer`'s only instance method is `slice`, which copies the
1277        // byte range into a fresh buffer.
1278        "ArrayBuffer" if method == "slice" => {
1279            if typedarray::is_detached(recv) {
1280                return Err(typedarray::detached_error(
1281                    "ArrayBuffer.prototype",
1282                    "slice",
1283                    true,
1284                ));
1285            }
1286            Ok(typedarray::buffer_slice(recv, &args))
1287        }
1288        "ArrayBuffer" if method == "resize" => typedarray::buffer_resize(recv, &args),
1289        "ArrayBuffer" if method == "transfer" => typedarray::buffer_transfer(recv, &args, false),
1290        "ArrayBuffer" if method == "transferToFixedLength" => {
1291            typedarray::buffer_transfer(recv, &args, true)
1292        }
1293        t if fetch::is_class(t) => fetch::instance_call(t, recv, method, &args),
1294        "EventTarget" | "Event" | "CustomEvent" => {
1295            event_target::instance_call(tag, recv, method, &args)
1296        }
1297        "Hash" => crypto::instance_call(recv, method, &args),
1298        "Hmac" => crypto::hmac_instance_call(recv, method, &args),
1299        "Interface" => readline::instance_call(recv, method, args),
1300        "ReadlineIterator" => readline::iterator_call(recv, method),
1301        "Script" => vm::instance_call(recv, method, args),
1302        "URLSearchParams" => url::search_params_call(recv, method, &args),
1303        "UdpSocket" => dgram::instance_call(recv, method, args),
1304        "Worker" | "MessagePort" | "BroadcastChannel" => {
1305            worker_threads::instance_call(tag, recv, method, args)
1306        }
1307        "TLSServer" | "TLSSocket" => tls::instance_call(tag, recv, method, args),
1308        "HTTPSServerResponse" | "HTTPSClientRequest" => {
1309            https::instance_call(tag, recv, method, args)
1310        }
1311        "REPLServer" => repl::instance_call(recv, method, args),
1312        "ClusterWorker" => cluster::instance_call(recv, method, args),
1313        "Domain" => domain::instance_call(recv, method, args),
1314        "Tracing" => trace_events::instance_call(recv, method, args),
1315        "Http2Server" | "Http2Stream" | "Http2Session" => {
1316            http2::instance_call(tag, recv, method, args)
1317        }
1318        "EventEmitter" => events::instance_call(recv, method, args),
1319        "URL" => url::instance_call(recv, method, &args),
1320        "Stats" | "BigIntStats" => fs::stats_call(recv, method),
1321        "Dirent" => fs::dirent_call(recv, method),
1322        "Dir" => fs::dir_call(recv, method, args),
1323        "FSReadStream" => fs::read_stream_call(recv, method, args),
1324        "FSWriteStream" => fs::write_stream_call(recv, method, args),
1325        "Server" | "Socket" | "BlockList" => net::instance_call(tag, recv, method, args),
1326        "IncomingMessage" | "ServerResponse" | "ClientRequest" | "Agent" => {
1327            http::instance_call(tag, recv, method, args)
1328        }
1329        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => {
1330            stream::instance_call(tag, recv, method, args)
1331        }
1332        "Cipheriv" | "Decipheriv" => crypto::cipher_instance_call(tag, recv, method, &args),
1333        "Sign" | "Verify" => crypto::sign_verify_instance_call(tag, recv, method, &args),
1334        "KeyObject"
1335        | "SecretKeyObject"
1336        | "AsymmetricKeyObject"
1337        | "PublicKeyObject"
1338        | "PrivateKeyObject" => crypto::key_object_instance_call(recv, method, &args),
1339        "DiffieHellman" => crypto::dh_instance_call(recv, method, &args),
1340        "ECDH" => crypto::ecdh_instance_call(recv, method, &args),
1341        "X509Certificate" => crypto::x509_instance_call(recv, method, &args),
1342        "MIMEType" => util::mime_type_instance_call(recv, method, &args),
1343        "MIMEParams" => util::mime_params_instance_call(recv, method, &args),
1344        "Blob" | "File" => buffer::blob_call(recv, method, &args),
1345        "ReadStream" => tty::instance_call(recv, method, &args),
1346        "Resolver" => dns::resolver_instance_call(recv, method, args),
1347        "Histogram" => perf_hooks::histogram_instance_call(recv, method, &args),
1348        "PerformanceObserver" => perf_hooks::observer_instance_call(recv, method, &args),
1349        "PerformanceObserverEntryList" => perf_hooks::entry_list_instance_call(recv, method, &args),
1350        "TracingChannel" => diagnostics_channel::tracing_instance_call(recv, method, &args),
1351        "Serializer" | "Deserializer" => v8::instance_call(tag, recv, method, args),
1352        "Console" => console::instance_call(recv, method, args),
1353        "ChildProcess" => child_process::instance_call(recv, method, args),
1354        "ChildPipe" => child_process::pipe_call(recv, method, args),
1355        "AsyncLocalStorage" | "AsyncHook" | "AsyncResource" => {
1356            async_hooks::instance_call(tag, recv, method, args)
1357        }
1358        "Channel" => diagnostics_channel::instance_call(recv, method, &args),
1359        "WriteStream" => process::stream_instance_call(recv, method, &args),
1360        "StdinIterator" => process::stdin_iterator_call(recv, method),
1361        _ => Err(crate::host::type_error(&format!(
1362            "{method} is not a function"
1363        ))),
1364    }
1365}
1366
1367// ── shared helpers ──────────────────────────────────────────────────────────
1368
1369/// The `Received …` tail Node appends to an `ERR_INVALID_ARG_TYPE` message
1370/// (`internal/errors.js` `determineSpecificType`): `null`/`undefined` verbatim,
1371/// a primitive as `type <typeof> (<inspected>)`, a function as
1372/// `function <name>`, an object as `an instance of <Ctor>`.
1373pub(crate) fn received_desc(v: &Value) -> String {
1374    with_host(|h| {
1375        if matches!(v, Value::Undef) {
1376            return "undefined".to_string();
1377        }
1378        if h.is_null(v) {
1379            return "null".to_string();
1380        }
1381        let ty = h.type_of(v);
1382        // A callable is named by its own `.name`, never by its constructor:
1383        // `determineSpecificType` reports `function foo` (and `function ` for an
1384        // anonymous one), where this used to say `an instance of Object`.
1385        if ty == "function" {
1386            return format!("function {}", h.callable_name(v));
1387        }
1388        if ty == "object" {
1389            // `ctor_name` is empty for the builtin shapes (they carry no user
1390            // class), so fall back to the intrinsic constructor name.
1391            let name = match h.ctor_name(v) {
1392                n if !n.is_empty() => n,
1393                _ => match h.get(v) {
1394                    Some(JsObj::Array(_)) => "Array".into(),
1395                    Some(JsObj::Map { .. }) => "Map".into(),
1396                    Some(JsObj::Set { .. }) => "Set".into(),
1397                    Some(JsObj::Promise { .. }) => "Promise".into(),
1398                    Some(JsObj::RegExp(_)) => "RegExp".into(),
1399                    Some(JsObj::Object(p)) => match p.get("@@native") {
1400                        Some(t) => h.str_of(t),
1401                        None => "Object".into(),
1402                    },
1403                    _ => "Object".into(),
1404                },
1405            };
1406            return format!("an instance of {name}");
1407        }
1408        let shown = match ty {
1409            "string" => format!("'{}'", h.str_of(v)),
1410            "bigint" => format!("{}n", h.str_of(v)),
1411            "number" if matches!(v, Value::Float(f) if *f == 0.0 && f.is_sign_negative()) => {
1412                "-0".to_string()
1413            }
1414            _ => h.str_of(v),
1415        };
1416        format!("type {ty} ({shown})")
1417    })
1418}
1419
1420/// ToString of `args[i]` (empty string if absent).
1421pub(crate) fn arg_str(args: &[Value], i: usize) -> String {
1422    with_host(|h| args.get(i).map(|v| h.str_of(v)).unwrap_or_default())
1423}
1424
1425/// ToNumber of `args[i]` (`NaN` if absent).
1426pub(crate) fn arg_num(args: &[Value], i: usize) -> f64 {
1427    with_host(|h| args.get(i).map(|v| h.to_number(v)).unwrap_or(f64::NAN))
1428}
1429
1430/// Lowercase hex encoding of `bytes`.
1431pub(crate) fn to_hex(bytes: &[u8]) -> String {
1432    let mut s = String::with_capacity(bytes.len() * 2);
1433    for b in bytes {
1434        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
1435        s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
1436    }
1437    s
1438}
1439
1440/// Decode a hex string to bytes as node's `StringBytes` does: pair by pair
1441/// from the start, STOPPING at the first pair that is not two hex digits, and
1442/// dropping a trailing odd nibble. `Buffer.from('12zz34', 'hex')` is the one
1443/// byte `12`, not `12 34` — a non-digit is a terminator, never skipped.
1444pub(crate) fn from_hex(s: &str) -> Vec<u8> {
1445    let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
1446    s.as_bytes()
1447        .chunks_exact(2)
1448        .map_while(|p| Some((digit(p[0])? << 4) | digit(p[1])?))
1449        .collect()
1450}
1451
1452const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1453
1454/// Standard base64 encoding (with `=` padding) of `bytes`.
1455pub(crate) fn to_base64(bytes: &[u8]) -> String {
1456    let mut out = String::new();
1457    for chunk in bytes.chunks(3) {
1458        let b = [
1459            chunk[0],
1460            *chunk.get(1).unwrap_or(&0),
1461            *chunk.get(2).unwrap_or(&0),
1462        ];
1463        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
1464        out.push(B64[((n >> 18) & 63) as usize] as char);
1465        out.push(B64[((n >> 12) & 63) as usize] as char);
1466        out.push(if chunk.len() > 1 {
1467            B64[((n >> 6) & 63) as usize] as char
1468        } else {
1469            '='
1470        });
1471        out.push(if chunk.len() > 2 {
1472            B64[(n & 63) as usize] as char
1473        } else {
1474            '='
1475        });
1476    }
1477    out
1478}
1479
1480/// URL-safe base64 (RFC 4648 §5) of `bytes`: `+/` become `-_` and the `=`
1481/// padding is dropped. This is `buf.toString('base64url')`, which is a distinct
1482/// encoding from `'base64'` — not an alias. Node emits `Buffer.from([251,255,
1483/// 190,1]).toString('base64url')` as `-_--AQ` where `'base64'` gives `+/++AQ==`.
1484pub(crate) fn to_base64url(bytes: &[u8]) -> String {
1485    to_base64(bytes)
1486        .chars()
1487        .filter(|c| *c != '=')
1488        .map(|c| match c {
1489            '+' => '-',
1490            '/' => '_',
1491            c => c,
1492        })
1493        .collect()
1494}
1495
1496/// Decode a base64 string to bytes (ignores whitespace and padding).
1497///
1498/// BOTH alphabets are accepted, in either direction: node decodes `-_` under
1499/// `'base64'` and `+/` under `'base64url'` (measured — `Buffer.from('-_-_',
1500/// 'base64').toString('hex')` and `Buffer.from('+/+/','base64url')
1501/// .toString('hex')` are both `fbffbf` on v26.7.0), so the decoder does not need
1502/// to know which name it was reached by. Refusing the URL-safe characters here
1503/// silently produced an EMPTY buffer, because an unrecognized character is
1504/// dropped rather than rejected.
1505pub(crate) fn from_base64(s: &str) -> Vec<u8> {
1506    let rev = |c: u8| -> Option<u32> {
1507        let c = match c {
1508            b'-' => b'+',
1509            b'_' => b'/',
1510            c => c,
1511        };
1512        B64.iter().position(|&x| x == c).map(|p| p as u32)
1513    };
1514    let vals: Vec<u32> = s.bytes().filter_map(rev).collect();
1515    let mut out = Vec::new();
1516    for chunk in vals.chunks(4) {
1517        if chunk.len() < 2 {
1518            break;
1519        }
1520        let n = (chunk[0] << 18)
1521            | (chunk[1] << 12)
1522            | (chunk.get(2).copied().unwrap_or(0) << 6)
1523            | chunk.get(3).copied().unwrap_or(0);
1524        out.push((n >> 16) as u8);
1525        if chunk.len() > 2 {
1526            out.push((n >> 8) as u8);
1527        }
1528        if chunk.len() > 3 {
1529            out.push(n as u8);
1530        }
1531    }
1532    out
1533}
1534
1535/// node's `validateInteger(value, name, min)` (`max` is
1536/// `Number.MAX_SAFE_INTEGER`): a Number, an integer, and within range — each
1537/// failure with node's own code and wording.
1538pub(crate) fn validate_integer(v: &Value, name: &str, min: f64) -> Result<f64, String> {
1539    validate_integer_in(v, name, min, 9_007_199_254_740_991.0)
1540}
1541
1542/// `validateInteger(value, name, min, max)` with an explicit `max`.
1543pub(crate) fn validate_integer_in(
1544    v: &Value,
1545    name: &str,
1546    min: f64,
1547    max: f64,
1548) -> Result<f64, String> {
1549    if with_host(|h| h.type_of(v)) != "number" {
1550        return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
1551    }
1552    let n = with_host(|h| h.to_number(v));
1553    if n.fract() != 0.0 || !n.is_finite() {
1554        return Err(out_of_range(name, "an integer", n));
1555    }
1556    if n < min || n > max {
1557        let must = format!(
1558            ">= {} && <= {}",
1559            crate::host::fmt_number(min),
1560            crate::host::fmt_number(max)
1561        );
1562        return Err(out_of_range(name, &must, n));
1563    }
1564    Ok(n)
1565}
1566
1567/// node's `ERR_OUT_OF_RANGE` for a numeric `name`: `It must be <must>.
1568/// Received <n>`, the received value rendered as node renders it.
1569pub(crate) fn out_of_range(name: &str, must: &str, n: f64) -> String {
1570    crate::host::coded_error(
1571        "RangeError",
1572        "ERR_OUT_OF_RANGE",
1573        &format!(
1574            "The value of \"{name}\" is out of range. It must be {must}. Received {}",
1575            buffer::out_of_range_received(n)
1576        ),
1577    )
1578}
1579
1580/// A builtin SINGLETON kept as a namespace (`performance`, `crypto`,
1581/// `crypto.subtle`) and the class it is the one instance of, under the key
1582/// that class's `Builtin` is spelled with. Every view of the instance — its
1583/// prototype, `instanceof`, brand, `constructor`, own keys, `hasOwnProperty`,
1584/// and its methods (read off the class prototype) — consults this one table.
1585pub fn singleton_class(ns: &str) -> Option<&'static str> {
1586    match ns {
1587        "performance" => Some("Performance"),
1588        "webcrypto" => Some("Crypto"),
1589        "SubtleCrypto" => Some(SUBTLE_CRYPTO_CLASS),
1590        _ => None,
1591    }
1592}
1593
1594/// The key of the `SubtleCrypto` CLASS. `SubtleCrypto` itself names the
1595/// `crypto.subtle` namespace, and the last dotted segment is the name the
1596/// class reports.
1597pub const SUBTLE_CRYPTO_CLASS: &str = "webcrypto.SubtleCrypto";
1598
1599/// The display name of a class key (`webcrypto.SubtleCrypto` → `SubtleCrypto`).
1600pub fn class_display_name(key: &str) -> &str {
1601    key.rsplit('.').next().unwrap_or(key)
1602}
1603
1604/// The web classes whose prototype getters brand-check `this` and throw
1605/// `ERR_INVALID_THIS` for any other receiver.
1606pub fn brand_checked_class(ctor: &str) -> bool {
1607    matches!(ctor, "Crypto" | "CryptoKey")
1608}
1609
1610/// `new Performance()`, `new Crypto()`, … — classes node lets no script build.
1611pub fn illegal_constructor(name: &str) -> bool {
1612    matches!(
1613        name,
1614        "Performance" | "Crypto" | "CryptoKey" | SUBTLE_CRYPTO_CLASS
1615    )
1616}