node-js 0.1.16

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
//! Node.js core modules implemented natively for node-js.
//!
//! A `require(spec)` (see `builtins::call_builtin_function`) resolves a supported
//! module to a `JsObj::Builtin("<module>")` namespace value — exactly the shape
//! of the built-in `console`/`Math` namespaces — so `mod.method(...)` dispatches
//! through `host::call_method` → `builtins::call_builtin_function("<module>.<method>")`
//! → `stdlib::call`, and `const { method } = require('mod')` reads the method as a
//! first-class `Builtin("mod.method")` via `namespace_property`.
//!
//! Every stdlib function is free-standing and acquires the thread-local `JsHost`
//! through `with_host` only around allocations (and releases it before any
//! re-entrant `host::invoke`), so callbacks (`fs` async, `EventEmitter.emit`,
//! `assert.throws`) never double-borrow the host. Stateful instances (`Buffer`,
//! crypto `Hash`, `EventEmitter`, `URL`) are plain objects carrying a hidden
//! `@@native` tag (filtered from enumeration/display like `@@iterator`); their
//! methods route through `instance_call` from `host::call_method`.

use crate::host::{with_host, JsObj};
use fusevm::Value;

pub mod assert;
pub mod assert_diff;
pub mod async_hooks;
pub mod buffer;
pub mod child_process;
pub mod cluster;
pub mod console;
pub mod constants;
pub mod crypto;
pub mod date;
pub mod dgram;
pub mod diagnostics_channel;
pub mod dns;
pub mod domain;
pub mod event_target;
pub mod events;
pub mod fetch;
pub mod fs;
pub mod fs_promises;
pub mod http;
pub mod http2;
pub mod https;
pub mod iterator;
pub mod net;
pub mod node_module;
pub mod os;
pub mod path;
pub mod perf_hooks;
pub mod process;
pub mod punycode;
pub mod querystring;
pub mod readline;
pub mod repl;
pub mod stream;
pub mod stream_consumers;
pub mod stream_promises;
pub mod stream_web;
pub mod string_decoder;
pub mod timers;
pub mod tls;
pub mod trace_events;
pub mod tty;
pub mod typedarray;
pub mod url;
pub mod url_legacy;
pub mod util;
pub mod util_types;
pub mod v8;
pub mod vm;
pub mod worker_threads;
pub mod zlib;

/// Native-heavy core modules that node-js does not yet implement (TLS handshakes,
/// HTTP/2 framing, OS worker threads sharing the thread-local heap, UDP sockets,
/// V8 inspector, etc.). `require`ing them succeeds and yields a namespace so that
/// programs which import-then-conditionally-use them still load; ACTUALLY calling
/// a method throws `Error: <mod>.<method> is not implemented in node-js`. This is
/// an honest not-yet-built surface, never a silent fake.
pub const UNIMPLEMENTED_MODULES: &[&str] = &["inspector", "wasi"];

/// True if `ns` is a known-but-unimplemented core module (see `UNIMPLEMENTED_MODULES`).
pub fn is_unimplemented(ns: &str) -> bool {
    UNIMPLEMENTED_MODULES.contains(&ns)
}

/// Canonical namespace name a `require(spec)` resolves to (after stripping an
/// optional `node:` prefix), or `None` for an unsupported module.
/// Core modules whose export is a plain DATA value rather than a namespace of
/// methods. `require('constants')` is the only one: every member is a number,
/// so it is built as a real object instead of a `Builtin` handle, whose members
/// are dispatchable methods by construction.
pub fn data_module(spec: &str) -> Option<Value> {
    match spec.strip_prefix("node:").unwrap_or(spec) {
        "constants" => {
            cached_module_value("@constants", || Some(constants::object(&constants::flat())))
        }
        _ => None,
    }
}

/// Whether `spec` names a core module of any kind — a method namespace or a
/// data module. This is what `require.resolve` answers with the bare specifier.
pub fn is_core(spec: &str) -> bool {
    resolve(spec).is_some() || matches!(spec.strip_prefix("node:").unwrap_or(spec), "constants")
}

pub fn resolve(spec: &str) -> Option<&'static str> {
    match spec.strip_prefix("node:").unwrap_or(spec) {
        "fs" => Some("fs"),
        "path" => Some("path"),
        "os" => Some("os"),
        "util" => Some("util"),
        "assert" => Some("assert"),
        "crypto" => Some("crypto"),
        "buffer" => Some("buffer"),
        "url" => Some("url"),
        "process" => Some("process"),
        "net" => Some("net"),
        "http" => Some("http"),
        // `require('stream')` IS the `Stream` constructor — `stream.Stream ===
        // stream`, and libraries still subclass it the ES5 way with
        // `Stream.call(this)` + `Object.create(Stream.prototype)`. It used to
        // resolve to a plain namespace, so `typeof` was `object`, `.prototype`
        // was `undefined`, and that subclassing pattern threw.
        "stream" => Some("Stream"),
        "tty" => Some("tty"),
        // The `events` module's export IS the EventEmitter constructor, so
        // `require('events')` yields the ctor namespace directly.
        "events" => Some("EventEmitter"),
        "string_decoder" => Some("string_decoder"),
        "zlib" => Some("zlib"),
        "querystring" => Some("querystring"),
        "console" => Some("console"),
        // `path/posix` is exactly our POSIX `path` (node-js targets a POSIX host,
        // so `require('path') === path.posix`); `path/win32` is the separate
        // backslash flavor. `assert/strict` is `assert` (already strict-based).
        "path/posix" => Some("path"),
        "path/win32" => Some("path/win32"),
        // `sys` is the long-deprecated alias for `util`.
        "sys" => Some("util"),
        // `require('assert/strict')` IS the strict namespace, so its `equal`
        // and `deepEqual` are the strict comparisons. Pointing it at the plain
        // `assert` made `require('assert/strict').equal(1, '1')` pass. The
        // strict namespace already existed for `assert.strict.*`.
        "assert/strict" => Some("assertStrict"),
        "child_process" => Some("child_process"),
        "dns" => Some("dns"),
        "punycode" => Some("punycode"),
        "timers" => Some("timers"),
        "timers/promises" => Some("timers/promises"),
        "perf_hooks" => Some("perf_hooks"),
        "async_hooks" => Some("async_hooks"),
        "util/types" => Some("util/types"),
        "diagnostics_channel" => Some("diagnostics_channel"),
        "v8" => Some("v8"),
        "readline" => Some("readline"),
        "readline/promises" => Some("readline/promises"),
        "vm" => Some("vm"),
        "fs/promises" => Some("fs/promises"),
        "dgram" => Some("dgram"),
        "dns/promises" => Some("dns/promises"),
        "worker_threads" => Some("worker_threads"),
        "tls" => Some("tls"),
        "https" => Some("https"),
        "repl" => Some("repl"),
        "cluster" => Some("cluster"),
        "domain" => Some("domain"),
        "http2" => Some("http2"),
        "trace_events" => Some("trace_events"),
        "module" => Some("module"),
        "stream/consumers" => Some("stream/consumers"),
        "stream/promises" => Some("stream/promises"),
        "stream/web" => Some("stream/web"),
        other => UNIMPLEMENTED_MODULES.iter().copied().find(|&m| m == other),
    }
}

/// True if `qualified` (`namespace.method`) is a stdlib method that
/// `call_builtin_function` should route into `call` (extends `is_known_builtin`).
pub fn is_method(qualified: &str) -> bool {
    let Some((ns, m)) = qualified.split_once('.') else {
        return qualified == "assert";
    };
    // Any method on an unimplemented namespace routes to `call`, which throws an
    // honest "not implemented" error (so `mod.foo()` fails clearly rather than
    // silently returning undefined).
    is_unimplemented(ns)
        || namespace_methods(ns).contains(&m)
        || namespace_ctors(ns).contains(&m)
        || namespace_values(ns).contains(&m)
}

/// The callable members of builtin namespace `ns`. THE single table backing both
/// `is_method` (does `ns.m` dispatch?) and `namespace_keys` (what does `for (k in
/// ns)` yield?), so a method can never be callable-but-unenumerable or the reverse.
pub fn namespace_methods(ns: &str) -> &'static [&'static str] {
    match ns {
        "fs" => fs::METHODS,
        "path" | "path/win32" => path::METHODS,
        "os" => os::METHODS,
        "util" => util::METHODS,
        "assert" | "assertStrict" => assert::METHODS,
        "crypto" => crypto::METHODS,
        "webcrypto" => crypto::WEBCRYPTO_METHODS,
        "SubtleCrypto" => crypto::SUBTLE_METHODS,
        "Buffer" => buffer::STATIC_METHODS,
        "buffer" => buffer::MODULE_METHODS,
        "Date" => date::STATIC_METHODS,
        "Response" => fetch::RESPONSE_STATICS,
        "AbortSignal" => fetch::ABORT_SIGNAL_STATICS,
        "Iterator" => iterator::STATIC_METHODS,
        n if typedarray::is_ctor(n) => typedarray::static_methods(n),
        "URL" => url::STATIC_METHODS,
        "url" => url::MODULE_METHODS,
        "net" => net::MODULE_METHODS,
        "http" => http::MODULE_METHODS,
        "stream" | "Stream" => stream::METHODS,
        n if stream::is_class(n) => stream::STATIC_METHODS,
        "worker_threads" => worker_threads::METHODS,
        "zlib" => zlib::MODULE_METHODS,
        "querystring" => querystring::METHODS,
        "tty" => tty::METHODS,
        "process" => process::METHODS,
        "EventEmitter" => events::STATIC_METHODS,
        "console" => console::METHODS,
        "child_process" => child_process::METHODS,
        "dns" => dns::METHODS,
        "dns/promises" => dns::PROMISES_METHODS,
        "punycode" => punycode::METHODS,
        "timers" => timers::METHODS,
        "timers/promises" => timers::PROMISES_METHODS,
        "perf_hooks" => perf_hooks::METHODS,
        "performance" => perf_hooks::PERFORMANCE_METHODS,
        "async_hooks" => async_hooks::METHODS,
        "AsyncResource" => async_hooks::RESOURCE_STATIC_METHODS,
        "AsyncLocalStorage" => async_hooks::ALS_STATIC_METHODS,
        "util/types" => util_types::METHODS,
        "diagnostics_channel" => diagnostics_channel::METHODS,
        "v8" => v8::METHODS,
        "readline" => readline::METHODS,
        "readline/promises" => readline::PROMISES_METHODS,
        "vm" => vm::METHODS,
        "fs/promises" => fs_promises::METHODS,
        "dgram" => dgram::MODULE_METHODS,
        "tls" => tls::MODULE_METHODS,
        "https" => https::MODULE_METHODS,
        "repl" => repl::METHODS,
        "cluster" => cluster::METHODS,
        "domain" => domain::METHODS,
        "http2" => http2::METHODS,
        "trace_events" => trace_events::METHODS,
        "module" => node_module::METHODS,
        "Module" => node_module::MODULE_STATIC_METHODS,
        "stream/consumers" => stream_consumers::METHODS,
        "stream/promises" => stream_promises::METHODS,
        _ => &[],
    }
}

/// Class/constructor members a namespace re-exports as values rather than
/// callable methods (`require('buffer').Buffer`, `require('url').URL`). They are
/// enumerable own keys too, so `for (k in buffer)` sees `Buffer`.
pub fn namespace_ctors(ns: &str) -> &'static [&'static str] {
    match ns {
        "buffer" => &["Buffer", "Blob", "File"],
        "stream" | "Stream" => stream::CLASSES,
        "url" => &["URL", "URLSearchParams"],
        "EventEmitter" => &["EventEmitter"],
        "async_hooks" => &["AsyncLocalStorage", "AsyncResource"],
        "string_decoder" => &["StringDecoder"],
        "assert" => &["AssertionError"],
        "console" => &["Console"],
        "vm" => &["Script"],
        "fs" => &["promises", "Dirent", "Stats"],
        // `stream/web` exports nothing BUT classes (`METHODS` is empty), so
        // without this arm the namespace had no enumerable key at all: measured
        // against node v26.7.0, `Object.keys(require('stream/web')).length` was
        // 0 here and 18 there, even though every one of the classes resolved
        // fine through `constant`. A namespace that answers property reads but
        // enumerates empty breaks the copy-the-module pattern
        // (`{ ...require('stream/web') }`, `for (k in web)`).
        "stream/web" => stream_web::CLASSES,
        _ => &[],
    }
}

/// The enumerable own keys of the builtin namespace `ns` — what `for (key in ns)`
/// and `Object.keys(ns)` yield. These are the members node-js ACTUALLY
/// implements, not Node's full export list, so a package that copies a namespace
/// key-by-key (safer-buffer clones `buffer` and `Buffer`) ends up with exactly the
/// working set rather than an empty object.
/// Whether a stdlib namespace's statics are ENUMERABLE own properties. A core
/// module's exports and a node or WebIDL class's statics (`Buffer.from`,
/// `URL.canParse`) are; an ECMAScript intrinsic constructor's are not
/// (`Iterator.from`, `Iterator.concat`).
pub fn namespace_statics_enumerable(ns: &str) -> bool {
    ns != "Iterator"
}

/// Non-callable members a namespace exports as enumerable VALUES — the nested
/// modules and cross-links (`timers.promises`, `assert.strict`, `path.posix`,
/// `crypto.subtle`). Listed apart from [`namespace_ctors`] because they are
/// values rather than constructors; like `fs.promises` among the ctors, each
/// read resolves through [`constant`] before any method thunk is considered.
pub fn namespace_values(ns: &str) -> &'static [&'static str] {
    match ns {
        "timers" | "readline" | "stream" | "Stream" => &["promises"],
        "dns" => dns::VALUE_KEYS,
        "assert" => &["strict"],
        "EventEmitter" => &[
            "usingDomains",
            "captureRejectionSymbol",
            "captureRejections",
            "errorMonitor",
            "defaultMaxListeners",
        ],
        "path" | "path/win32" => &["sep", "delimiter", "win32", "posix"],
        "crypto" => &["constants", "webcrypto", "subtle"],
        "os" => &["constants", "EOL", "devNull"],
        "fs" | "fs/promises" | "http2" => &["constants"],
        "buffer" => &[
            "kMaxLength",
            "kStringMaxLength",
            "constants",
            "INSPECT_MAX_BYTES",
        ],
        "http" => &["METHODS", "STATUS_CODES", "globalAgent"],
        "https" => &["globalAgent"],
        "perf_hooks" => &["performance", "constants"],
        "worker_threads" => &["isMainThread", "threadId", "parentPort", "workerData"],
        "cluster" => &[
            "isWorker",
            "isMaster",
            "isPrimary",
            "workers",
            "settings",
            "SCHED_NONE",
            "SCHED_RR",
            "schedulingPolicy",
        ],
        "domain" => &["active"],
        _ => &[],
    }
}

pub fn namespace_keys(ns: &str) -> Vec<String> {
    // A singleton's members are inherited from its class prototype; it owns
    // none (`Object.keys(performance)` is `[]`).
    if singleton_class(ns).is_some() {
        return Vec::new();
    }
    // The `require.cache` view enumerates the resolved filenames it holds.
    if ns == crate::builtins::REQUIRE_CACHE {
        return crate::module::cache_keys();
    }
    let mut out: Vec<String> = namespace_ctors(ns)
        .iter()
        .chain(namespace_values(ns))
        .map(|s| s.to_string())
        .collect();
    for m in namespace_methods(ns) {
        // A dotted entry (`util`'s `types.isMap`, `process`'s `hrtime.bigint`)
        // is a dispatch path into a member's own namespace, not a key of this
        // one; `Object.keys(util)` listed seven of them.
        if !m.contains('.') && !out.iter().any(|k| k == m) {
            out.push((*m).to_string());
        }
    }
    // A core module enumerates in NODE's order (measured into `CORE_KEYS`),
    // listing only what this frontend implements. This runs under the host
    // borrow (`for-in`), so it consults the static lists above and never
    // reads a value.
    if ns != "process" {
        if let Some(theirs) = core_keys(ns) {
            return theirs
                .iter()
                .filter(|k| out.iter().any(|o| o == *k))
                .map(|k| (*k).to_string())
                .collect();
        }
    }
    out
}

/// node's `Object.keys(require(id))` for the core module spelled `ns`.
pub fn core_keys(ns: &str) -> Option<&'static [&'static str]> {
    let t = crate::core_arity::CORE_KEYS;
    t.binary_search_by(|(k, _)| (*k).cmp(ns))
        .ok()
        .map(|i| t[i].1)
}

/// Dispatch a resolved stdlib builtin (`assert`, or `namespace.method`). Returns
/// `None` if `name` is not a stdlib builtin (the caller falls through to the core
/// builtin table).
pub fn call(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    if name == "assert" {
        return Some(assert::assert_ok(args));
    }
    let (ns, m) = name.split_once('.')?;
    Some(match ns {
        "fs" => fs::call(m, args)?,
        "path" => path::call(path::Flavor::Posix, m, args)?,
        "path/win32" => path::call(path::Flavor::Win32, m, args)?,
        "os" => os::call(m, args)?,
        "util" => util::call(m, args)?,
        "assert" => assert::call(m, args)?,
        "assertStrict" => assert::strict_call(m, args)?,
        "crypto" => crypto::call(m, args)?,
        // `webcrypto`'s two random helpers are the same implementations the
        // node-flavoured `crypto` module exposes.
        "webcrypto" => crypto::call(m, args)?,
        "SubtleCrypto" => crypto::subtle_call(m, args)?,
        "Buffer" => buffer::static_call(m, args)?,
        "buffer" if m == "Buffer" => Ok(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into())))),
        "buffer" => buffer::module_call(m, args)?,
        "Date" => date::static_call(m, args)?,
        "Response" | "AbortSignal" => fetch::static_call(ns, m, args)?,
        "Iterator" => iterator::static_call(m, args)?,
        n if typedarray::is_ctor(n) => typedarray::static_call(n, m, args)?,
        "URL" => url::static_call(m, args)?,
        "url" if m == "URL" => Ok(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
        "url" => url::call(m, args)?,
        "net" => net::call(m, args)?,
        "http" => http::call(m, args)?,
        "stream" | "Stream" => stream::call(m, args)?,
        "worker_threads" => worker_threads::call(m, args)?,
        "zlib" => zlib::call(m, args)?,
        "querystring" => querystring::call(m, args)?,
        "tty" => tty::call(m, args)?,
        "process" => process::call(m, args)?,
        "EventEmitter" if m == "EventEmitter" => Ok(with_host(|h| {
            h.alloc(JsObj::Builtin("EventEmitter".into()))
        })),
        "EventEmitter" => events::static_call(m, args)?,
        n if stream::is_class(n) => stream::static_call(n, m, args)?,
        "console" => console::call(m, args)?,
        "child_process" => child_process::call(m, args)?,
        "dns" => dns::call(m, args)?,
        "punycode" => punycode::call(m, args)?,
        "timers" => timers::call(m, args)?,
        "timers/promises" => timers::promises_call(m, args)?,
        "perf_hooks" | "performance" => perf_hooks::call(m, args)?,
        "async_hooks" => async_hooks::call(m, args)?,
        "AsyncResource" => async_hooks::static_call(m, args)?,
        "AsyncLocalStorage" => async_hooks::als_static_call(m, args)?,
        "util/types" => util_types::call(m, args)?,
        "diagnostics_channel" => diagnostics_channel::call(m, args)?,
        "v8" => v8::call(m, args)?,
        "readline" => readline::call(m, args)?,
        "readline/promises" => readline::promises_call(m, args)?,
        "vm" => vm::call(m, args)?,
        "fs/promises" => fs_promises::call(m, args)?,
        "dgram" => dgram::call(m, args)?,
        // dns/promises: getServers/setServers/get|setDefaultResultOrder are shared
        // sync fns; every other method maps to dns's `promise<Cap>` variant.
        "dns/promises" => match m {
            "getServers" | "setServers" | "getDefaultResultOrder" | "setDefaultResultOrder" => {
                dns::call(m, args)?
            }
            _ => {
                let mut pm = String::from("promise");
                let mut cs = m.chars();
                if let Some(c) = cs.next() {
                    pm.extend(c.to_uppercase());
                    pm.push_str(cs.as_str());
                }
                dns::call(&pm, args)?
            }
        },
        "tls" => tls::call(m, args)?,
        "https" => https::call(m, args)?,
        "repl" => repl::call(m, args)?,
        "cluster" => cluster::call(m, args)?,
        "domain" => domain::call(m, args)?,
        "http2" => http2::call(m, args)?,
        "trace_events" => trace_events::call(m, args)?,
        "module" => node_module::call(m, args)?,
        "Module" => node_module::static_call(m, args)?,
        "stream/consumers" => stream_consumers::call(m, args)?,
        "stream/promises" => stream_promises::call(m, args)?,
        _ if is_unimplemented(ns) => Err(format!("Error: {ns}.{m} is not implemented in node-js")),
        _ => return None,
    })
}

/// A non-function constant on a stdlib namespace (`path.sep`, `os.EOL`,
/// `buffer.Buffer`, `url.URL`), reachable via `namespace_property`.
pub fn constant(ns: &str, name: &str) -> Option<Value> {
    // A module's `constants` object is ONE object for the life of the process
    // (`fs.constants === fs.constants`, and `fs/promises` shares `fs`'s); each
    // read built a fresh one.
    if name == "constants" {
        let key = if ns == "fs/promises" { "fs" } else { ns };
        return cached_module_value(key, || constant_uncached(ns, name));
    }
    constant_uncached(ns, name)
}

/// One value per `key`, built by `make` on first use.
fn cached_module_value(key: &str, make: impl FnOnce() -> Option<Value>) -> Option<Value> {
    thread_local! {
        static CACHE: std::cell::RefCell<std::collections::HashMap<String, Value>> =
            std::cell::RefCell::new(std::collections::HashMap::new());
    }
    if let Some(v) = CACHE.with(|c| c.borrow().get(key).cloned()) {
        return Some(v);
    }
    let v = make()?;
    CACHE.with(|c| c.borrow_mut().insert(key.to_string(), v.clone()));
    Some(v)
}

fn constant_uncached(ns: &str, name: &str) -> Option<Value> {
    match ns {
        "Event" => event_target::constant(name),
        // Both flavors carry `.posix`/`.win32` cross-links, exactly as Node's
        // `posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix`.
        "path" | "path/win32" if name == "posix" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("path".into()))))
        }
        "path" | "path/win32" if name == "win32" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("path/win32".into()))))
        }
        "path" => path::constant(path::Flavor::Posix, name),
        "path/win32" => path::constant(path::Flavor::Win32, name),
        "os" => os::constant(name),
        // node caches the frozen bundled store, so every read is one array.
        "tls" if name == "rootCertificates" => {
            cached_module_value("tls.rootCertificates", || tls::constant(name))
        }
        "tls" => tls::constant(name),
        // `fs.constants` and `crypto.constants` were absent, so
        // `fs.constants.O_RDONLY` and `crypto.constants.RSA_PKCS1_PADDING` —
        // which libraries pass straight through to `open` and to RSA — read as
        // `undefined`.
        "fs" | "fs/promises" if name == "constants" => Some(constants::object(&constants::fs())),
        // `fs.Stats` / `fs.Dirent`: the classes of `statSync` and of a
        // `withFileTypes` entry, so `stat instanceof fs.Stats` holds.
        "fs" if matches!(name, "Stats" | "Dirent") => {
            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
        }
        "crypto" if name == "constants" => Some(constants::object(&constants::crypto())),
        // `crypto.webcrypto` is the WHATWG surface; `globalThis.crypto` is the
        // same object. Only its two random helpers and `subtle.digest` are
        // implemented — see `crypto::WEBCRYPTO_METHODS`.
        // `crypto.subtle` is `crypto.webcrypto.subtle`; it was absent.
        "crypto" if name == "subtle" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("SubtleCrypto".into()))
        })),
        // `timers.promises` is the `timers/promises` module; it was absent.
        "timers" if name == "promises" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("timers/promises".into()))
        })),
        "crypto" if name == "webcrypto" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("webcrypto".into()))))
        }
        "webcrypto" if name == "subtle" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("SubtleCrypto".into()))
        })),
        // `EventEmitter.defaultMaxListeners` is a DATA property, so it belongs
        // here rather than among the static methods (which would make it read
        // as a function). It was absent: node reports 10.
        "EventEmitter" | "events" if name == "defaultMaxListeners" => Some(Value::Float(10.0)),
        // The capture-rejections switch (off by default), the symbol a class
        // implements to receive captured rejections, the legacy domain flag,
        // and the private symbol whose listeners monitor `error` events. All
        // four were absent.
        "EventEmitter" | "events" if matches!(name, "captureRejections" | "usingDomains") => {
            Some(Value::Bool(false))
        }
        "EventEmitter" | "events" if name == "captureRejectionSymbol" => {
            Some(with_host(|h| h.symbol_for("nodejs.rejection")))
        }
        "EventEmitter" | "events" if name == "errorMonitor" => {
            Some(with_host(|h| h.internal_symbol("events.errorMonitor")))
        }
        // `Buffer.poolSize` is a DATA property, not a method, so it belongs here
        // rather than in `STATIC_METHODS` (which would make it read as a
        // function). It was absent entirely: `Buffer.poolSize` was `undefined`
        // where node v26.7.0 reports 65536. node-js allocates each Buffer on its
        // own, so this is the documented constant, not a live allocator figure.
        "Buffer" if name == "poolSize" => Some(Value::Float(65536.0)),
        // `Uint8Array.BYTES_PER_ELEMENT` is a property of the CONSTRUCTOR as
        // well as of every instance (23.2.6.2 / 23.2.5.1); only the instance
        // carried it, so the constructor read `undefined` — the form the
        // `byteLength = n * Ctor.BYTES_PER_ELEMENT` idiom uses.
        n if typedarray::is_ctor(n) && name == "BYTES_PER_ELEMENT" => {
            // `ArrayBuffer`/`DataView` are element-less and report nothing.
            typedarray::ELEMENT_KINDS
                .contains(&n)
                .then(|| Value::Float(typedarray::bytes_per_element(n) as f64))
        }
        "buffer" if name == "Buffer" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into()))))
        }
        "buffer" if matches!(name, "Blob" | "File") => {
            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
        }
        "buffer" => buffer::module_constant(name),
        "url" if name == "URL" => Some(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
        "net" => net::constant(name),
        "tty" => tty::constant(name),
        "repl" => repl::constant(name),
        // `readline.promises` is the same module reached as a property, so the
        // cross-link is checked before the shared constant table.
        "readline" if name == "promises" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("readline/promises".into()))
        })),
        "readline" | "readline/promises" => readline::constant(name),
        "diagnostics_channel" => diagnostics_channel::constant(name),
        "v8" => v8::constant(name),
        "console" if name == "Console" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("Console".into()))))
        }
        "assert" if name == "AssertionError" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("AssertionError".into()))
        })),
        "assert" if name == "strict" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("assertStrict".into()))
        })),
        // Every stream class's `.prototype` is the REAL prototype object the
        // hierarchy hangs off, not a `Builtin("X.prototype")` handle — an ES5
        // subclass reads it and passes it to `Object.create`, and
        // `getPrototypeOf(Readable.prototype)` has to reach `Stream.prototype`.
        n if stream::is_class(n) && name == "prototype" => with_host(|h| h.ensure_ctor_proto(n)),
        "stream" | "Stream" => stream::constant(name),
        "http" => http::constant(name),
        "string_decoder" if name == "StringDecoder" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("StringDecoder".into()))
        })),
        "process" => process::constant(name),
        "EventEmitter" if name == "EventEmitter" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("EventEmitter".into()))
        })),
        "perf_hooks" | "performance" => perf_hooks::constant(name),
        "dns" => dns::constant(name),
        "punycode" => punycode::constant(name),
        "async_hooks" if matches!(name, "AsyncLocalStorage" | "AsyncResource") => {
            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
        }
        "vm" if name == "Script" => Some(with_host(|h| h.alloc(JsObj::Builtin("Script".into())))),
        "url" if name == "URLSearchParams" => Some(with_host(|h| {
            h.alloc(JsObj::Builtin("URLSearchParams".into()))
        })),
        "fs" if name == "promises" => {
            Some(with_host(|h| h.alloc(JsObj::Builtin("fs/promises".into()))))
        }
        "worker_threads" => worker_threads::constant(name),
        "https" => https::constant(name),
        "cluster" => cluster::constant(name),
        "domain" => domain::constant(name),
        "http2" => http2::constant(name),
        "module" => node_module::constant(name),
        "Module" => node_module::static_constant(name),
        "stream/web" => stream_web::constant(name),
        // util.types / util.TextEncoder|TextDecoder / util.MIMEType|MIMEParams.
        "util" => util::constant(name),
        // crypto class-constructor exports (require('crypto').Sign etc.) — the
        // instances are made by factory fns, but the ctor names must resolve.
        "crypto"
            if matches!(
                name,
                "Sign"
                    | "Verify"
                    | "KeyObject"
                    | "DiffieHellman"
                    | "ECDH"
                    | "X509Certificate"
                    | "Hash"
                    | "Hmac"
                    | "Cipheriv"
                    | "Decipheriv"
            ) =>
        {
            Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
        }
        _ => None,
    }
}

/// Construct a stdlib class instance (`new URL(...)`, `new EventEmitter()`, and
/// `new Buffer(...)` legacy), reachable from `construct_builtin`. `None` if `name`
/// is not a stdlib constructor.
pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    match name {
        "URL" => Some(url::construct(args)),
        "EventEmitter" => Some(Ok(events::new_emitter())),
        // `new Buffer(x)` and the deprecated call form `Buffer(x)` are the same
        // operation, and it is NOT simply `Buffer.from`: a NUMBER allocates that
        // many zero bytes, where `Buffer.from(3)` is a TypeError in Node.
        // Measured on node v26.7.0, `new Buffer(3)` and `Buffer(3)` are both
        // `<Buffer 00 00 00>` (zero-filled since the `Buffer.alloc` semantics
        // landed), while `new Buffer('ab')` and `new Buffer([1,2])` behave as
        // `from`. Routing everything through `from` made `new Buffer(3)` one byte
        // long.
        "Buffer" => {
            let numeric = matches!(args.first(), Some(Value::Int(_)) | Some(Value::Float(_)))
                && args.len() == 1;
            let m = if numeric { "alloc" } else { "from" };
            Some(buffer::static_call(m, args).unwrap_or(Ok(Value::Undef)))
        }
        "Date" => Some(date::construct(args)),
        "StringDecoder" => Some(string_decoder::construct(args)),
        "WeakRef" => Some(typedarray::construct_weakref(args)),
        "FinalizationRegistry" => Some(typedarray::construct_finalization_registry(args)),
        n if fetch::is_class(n) => fetch::construct(n, args),
        n if event_target::is_class(n) => event_target::construct(n, args),
        "TextEncoder" => Some(typedarray::construct_text_encoder()),
        "TextDecoder" => Some(typedarray::construct_text_decoder(args)),
        "DataView" => Some(typedarray::construct_dataview(args)),
        n if typedarray::is_ctor(n) => Some(typedarray::construct(n, args)),
        n if stream::is_class(n) => Some(Ok(stream::construct(n, args))),
        "AsyncLocalStorage" | "AsyncResource" => async_hooks::construct(name, args),
        "Script" => Some(vm::construct(args)),
        "URLSearchParams" => Some(url::construct_search_params(args)),
        "Worker" => Some(worker_threads::construct_worker(args)),
        "Domain" => Some(domain::construct(args)),
        "Tracing" => Some(trace_events::construct(args)),
        "Blob" => Some(buffer::construct_blob(args)),
        "File" => Some(buffer::construct_file(args)),
        "AssertionError" => Some(Ok(assert::construct_assertion_error(args))),
        "X509Certificate" => Some(crypto::construct_x509(args)),
        "MIMEType" => Some(util::construct_mime_type(args)),
        "MIMEParams" => Some(util::construct_mime_params(args)),
        "Resolver" => Some(Ok(dns::construct_resolver(args))),
        "ReadStream" | "WriteStream" => Some(Ok(tty::construct(name, args))),
        "MessageChannel" => Some(worker_threads::construct_message_channel(args)),
        "BroadcastChannel" => Some(worker_threads::construct_broadcast_channel(args)),
        "PerformanceObserver" => Some(perf_hooks::construct(name, args)),
        // `performance`, `crypto`, `crypto.subtle` are the only instances.
        n if illegal_constructor(n) => Some(Err(crate::host::coded_error(
            "TypeError",
            "ERR_ILLEGAL_CONSTRUCTOR",
            "Illegal constructor",
        ))),
        "REPLServer" | "Recoverable" => Some(repl::construct(name, args)),
        "Interface" => Some(readline::construct(args)),
        "Console" => Some(console::construct(args)),
        "Serializer" | "DefaultSerializer" | "Deserializer" | "DefaultDeserializer" => {
            Some(v8::construct(name, args))
        }
        // net/http constructors: their `construct` already returns Option<Result>.
        "Socket" | "Stream" | "Server" | "SocketAddress" | "BlockList" => {
            net::construct(name, args)
        }
        "Agent" | "http.Server" => http::construct(name, args),
        _ => None,
    }
}

/// The hidden `@@native` instance tag of `recv` (`"Buffer"`/`"Hash"`/
/// `"EventEmitter"`/`"URL"`), or `None` for a non-native object.
pub fn native_tag(recv: &Value) -> Option<String> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@native").map(|v| h.str_of(v)),
        _ => None,
    })
}

/// Native instance tags whose `instance_call` implements `toJSON()`, which
/// `JSON.stringify` must invoke before serializing the value. (`instance_has_method`
/// only covers tags with a declared method table; `Date` dispatches directly.)
pub fn has_to_json(tag: &str) -> bool {
    matches!(tag, "Buffer" | "Date" | "URL" | "MIMEType" | "MIMEParams")
}

/// Whether `name` is a method of a native instance tagged `tag`. Used by
/// `get_property` so a method *read* (`server.listen.apply(...)`, the express
/// listen path) yields a bound method rather than `undefined` — the method is
/// still dispatched through `instance_call` when the bound method is invoked.
pub fn instance_has_method(tag: &str, name: &str) -> bool {
    // A class INHERITS its parent's methods: `equals` is on `KeyObject` and a
    // `SecretKeyObject` answers it. Asking only the leaf's own list reported
    // `false` for a method the prototype chain really carries.
    let mut ctor = Some(tag);
    while let Some(t) = ctor {
        let (base, emitter) = instance_method_lists(t);
        if base.contains(&name) || emitter.contains(&name) {
            return true;
        }
        ctor = native_parent(t);
    }
    false
}

/// The method names a native instance tagged `tag` carries, as
/// `(its own list, the EventEmitter surface it also gets or empty)`.
///
/// Split out of [`instance_has_method`] so the same table can be *enumerated*,
/// not only queried: `host::ensure_ctor_proto` builds a native constructor's
/// real `.prototype` object from it. A predicate alone would have forced a
/// second, hand-maintained list of the same names — the drift that put
/// `listeners` on nine dispatchers and not on the three that run.
/// The native class whose prototype `ctor`'s prototype inherits from, if any.
///
/// Only the stream hierarchy has one: node's is
/// `Readable/Writable/Duplex/Transform/PassThrough → Stream → EventEmitter`,
/// and every prototype used to hang straight off `Object.prototype` instead, so
/// `new Readable() instanceof Stream` and `instanceof EventEmitter` both read
/// false and an ES5 subclass built on `Object.create(Stream.prototype)`
/// inherited nothing.
pub fn native_parent(ctor: &str) -> Option<&'static str> {
    match ctor {
        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" => Some("Stream"),
        "Stream" => Some("EventEmitter"),
        // Emitter-backed native classes: `child instanceof EventEmitter` holds
        // in node, and the emitter methods are inherited.
        "ChildProcess" | "Socket" | "Server" => Some("EventEmitter"),
        // `AbortSignal` is an `EventTarget` in node, and `CustomEvent` an `Event`,
        // so `signal instanceof EventTarget` holds and both inherit the base
        // class's methods.
        "AbortSignal" => Some("EventTarget"),
        "CustomEvent" => Some("Event"),
        // `crypto.createSecretKey` and `generateKeyPair` hand back the LEAF
        // classes, not `KeyObject`: node's chain is
        // `SecretKeyObject → KeyObject` and
        // `PublicKeyObject → AsymmetricKeyObject → KeyObject`, which is why
        // `symmetricKeySize` exists on one and `asymmetricKeyType` on the other.
        // Everything was tagged `KeyObject`, so `key.constructor.name` read
        // `KeyObject` and neither accessor had a home.
        "SecretKeyObject" | "AsymmetricKeyObject" => Some("KeyObject"),
        "PublicKeyObject" | "PrivateKeyObject" => Some("AsymmetricKeyObject"),
        _ => None,
    }
}

/// The ACCESSOR properties a native class's prototype carries, as
/// `(name, has_setter)`, and the `Symbol.toStringTag` it stamps (empty for
/// none).
///
/// Node keeps these OFF the instance: `Object.keys(new AbortController())` is
/// empty and `JSON.stringify` of one is `{}`, because `signal` is a getter on
/// `AbortController.prototype`. Storing them as own data properties — what this
/// did — leaked them into every enumeration, every spread and every
/// serialization of an object that merely held one.
///
/// The getter reads the instance's hidden `@@<name>` slot, so a construction
/// site stores the value there rather than under the public name.
/// Run whatever a class has to do after one of its accessor SETTERS stored a
/// value — for a `URL`, rewriting the fields derived from the one just written.
///
/// Without this the setter was a plain slot write: `u.protocol = 'https:'` read
/// back as `https:` while `u.href` still showed `http://…`, so the object
/// disagreed with itself.
/// Whether a class's prototype MEMBERS are enumerable, as node defines them.
///
/// Most are: `for (const k in new URL('http://a/'))` walks `href`, `origin` and
/// the rest, because a WebIDL interface's members are enumerable and node
/// defines its own classes the same way. The exceptions are the ones written as
/// ES classes — `vm.Script` and the `KeyObject` family — whose methods are
/// non-enumerable like any class method's.
///
/// `constructor` is never enumerable, in either kind.
/// Methods a class defines AFTER its accessors.
///
/// Prototype members enumerate in definition order, and node defines
/// `URL.prototype` as `toString`, then every accessor, then `toJSON` — so a
/// `for-in` over a URL ends with `toJSON` rather than starting with it.
pub fn instance_late_methods(tag: &str) -> &'static [&'static str] {
    match tag {
        "URL" => &["toJSON"],
        "Event" => event_target::EVENT_LATE_METHODS,
        _ => &[],
    }
}

/// How `util.inspect` renders an instance of `tag`, as
/// `(accessors to show, whether to print the class name)`.
///
/// Node gives these classes a custom inspect that prints a CURATED set of
/// accessor values — a `URL` shows all twelve, an `AbortSignal` shows only
/// `aborted`, and a `KeyObject` shows none. With the values moved off the
/// instance and onto prototype getters, the generic own-property renderer has
/// nothing left to print, so every one of them rendered as an empty `{}`.
///
/// `TextEncoder` is the odd one: node's custom inspect omits the class name, so
/// it prints as a bare `{ encoding: 'utf-8' }`.
pub fn instance_inspect_members(tag: &str) -> (&'static [&'static str], bool) {
    match tag {
        "URL" => (
            &[
                "href",
                "origin",
                "protocol",
                "username",
                "password",
                "host",
                "hostname",
                "port",
                "pathname",
                "search",
                "searchParams",
                "hash",
            ],
            true,
        ),
        "AbortController" => (&["signal"], true),
        "AbortSignal" => (&["aborted"], true),
        // node's custom inspect for an `Event` prints these four; a `CustomEvent`
        // shows the same four (not `detail`).
        "Event" | "CustomEvent" => (
            &["type", "defaultPrevented", "cancelable", "timeStamp"],
            true,
        ),
        "TextDecoder" => (&["encoding", "fatal", "ignoreBOM"], true),
        "TextEncoder" => (&["encoding"], false),
        _ => (&[], true),
    }
}

/// Whether node gives instances of `tag` a CUSTOM `util.inspect` — one that
/// prints a curated view and nothing else. Such a class hides a subclass's own
/// properties and the `[Tag]` suffix: `class S extends AbortController {}` is
/// `S { signal: … }`, and an `EventTarget` subclass prints ` {}` even
/// with own fields.
pub fn instance_inspect_is_custom(tag: &str) -> bool {
    tag == "EventTarget" || !instance_inspect_members(tag).0.is_empty()
}

pub fn instance_members_enumerable(tag: &str) -> bool {
    !matches!(
        tag,
        "Script"
            | "KeyObject"
            | "SecretKeyObject"
            | "AsymmetricKeyObject"
            | "PublicKeyObject"
            | "PrivateKeyObject"
    )
}

pub fn instance_accessor_written(
    tag: &str,
    key: &str,
    recv: &Value,
    value: &Value,
) -> Result<(), String> {
    // A URL component goes through the URL Standard's setter for it.
    if tag == "URL" {
        return url::set_component(recv, key, value);
    }
    // `Event.cancelBubble` / `returnValue` are verbs, not stored values.
    if tag == "Event" {
        return event_target::accessor_written(recv, key, value);
    }
    // `signal.onabort = f`: node's `defineEventHandler` registers the handler's
    // listener slot on the FIRST assignment; the slot reads `@@onabort` at
    // dispatch time, and a non-function reads back as `null`.
    if tag == "AbortSignal" && key == "onabort" {
        if !with_host(|h| crate::host::is_callable(h, value)) {
            let null = with_host(|h| h.null());
            with_host(|h| {
                if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                    p.insert("@@onabort".into(), null);
                }
            });
        }
        event_target::ensure_handler_slot(recv, "abort");
    }
    Ok(())
}

pub fn instance_accessors(tag: &str) -> (&'static [(&'static str, bool)], &'static str) {
    match tag {
        "AbortController" => (&[("signal", false)], "AbortController"),
        "AbortSignal" => (
            &[("aborted", false), ("reason", false), ("onabort", true)],
            "AbortSignal",
        ),
        "KeyObject" => (&[("type", false)], "KeyObject"),
        "SecretKeyObject" => (&[("symmetricKeySize", false)], ""),
        "AsymmetricKeyObject" => (
            &[
                ("asymmetricKeyType", false),
                ("asymmetricKeyDetails", false),
            ],
            "",
        ),
        "TextEncoder" => (&[("encoding", false)], "TextEncoder"),
        "StringDecoder" => (string_decoder::ACCESSORS, ""),
        "Performance" => (&[("timeOrigin", false)], "Performance"),
        "Crypto" => (&[("subtle", false)], "Crypto"),
        "webcrypto.SubtleCrypto" => (&[], "SubtleCrypto"),
        "CryptoKey" => (
            &[
                ("type", false),
                ("extractable", false),
                ("algorithm", false),
                ("usages", false),
            ],
            "CryptoKey",
        ),
        "EventTarget" => (&[], "EventTarget"),
        "Event" => (event_target::EVENT_ACCESSORS, "Event"),
        "CustomEvent" => (&[("detail", false)], "CustomEvent"),
        // `origin` and `searchParams` are the two a caller cannot assign.
        "URL" => (
            &[
                ("href", true),
                ("origin", false),
                ("protocol", true),
                ("username", true),
                ("password", true),
                ("host", true),
                ("hostname", true),
                ("port", true),
                ("pathname", true),
                ("search", true),
                ("searchParams", false),
                ("hash", true),
            ],
            "URL",
        ),
        "TextDecoder" => (
            &[("encoding", false), ("fatal", false), ("ignoreBOM", false)],
            "TextDecoder",
        ),
        _ => (&[], ""),
    }
}

pub fn instance_method_lists(tag: &str) -> (&'static [&'static str], &'static [&'static str]) {
    // Shared EventEmitter surface for the emitter-backed instances. Read from
    // `events::METHODS` so what an instance ADVERTISES here can never drift from
    // what the dispatchers actually delegate.
    const EMITTER: &[&str] = events::METHODS;
    let base: &[&str] = match tag {
        "Timeout" => timers::TIMEOUT_METHODS,
        "IntervalIterator" => timers::INTERVAL_METHODS,
        "CollectionIterator" => &["next", "@@iterator"],
        "IteratorHelper" => iterator::METHODS,
        "Immediate" => timers::IMMEDIATE_METHODS,
        "Server" => &["listen", "close", "address"],
        "Socket" => &[
            "write",
            "end",
            "destroy",
            "pause",
            "resume",
            "setEncoding",
            "setKeepAlive",
            "setNoDelay",
            "setTimeout",
            "ref",
            "unref",
            "connect",
        ],
        "ServerResponse" => &[
            "writeHead",
            "setHeader",
            "getHeader",
            "getHeaderNames",
            "getHeaders",
            "hasHeader",
            "removeHeader",
            "write",
            "end",
            "flushHeaders",
        ],
        "IncomingMessage" => &["pause", "resume", "setEncoding", "destroy"],
        "Buffer" => buffer::INSTANCE_METHODS,
        "DataView" => typedarray::DATAVIEW_METHODS,
        "ArrayBuffer" => &["slice", "resize", "transfer", "transferToFixedLength"],
        "Date" => date::INSTANCE_METHODS,
        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => &[
            "read",
            "write",
            "end",
            "pipe",
            "pause",
            "resume",
            "setEncoding",
            "destroy",
            "push",
        ],
        // `toJSON` comes AFTER the accessors — see `instance_late_methods`.
        "URL" => &["toString"],
        "AsyncLocalStorage" => async_hooks::ALS_METHODS,
        "AsyncHook" => async_hooks::HOOK_METHODS,
        "AsyncResource" => async_hooks::RESOURCE_METHODS,
        "Channel" => &["subscribe", "unsubscribe", "publish"],
        "WriteStream" => &[
            "write",
            "end",
            "on",
            "once",
            "addListener",
            "prependListener",
            "removeListener",
            "off",
            "removeAllListeners",
            "listenerCount",
            "cork",
            "uncork",
            "setEncoding",
            "resume",
            "pause",
            "read",
            "pipe",
            "@@asyncIterator",
        ],
        "StdinIterator" => process::STDIN_ITERATOR_METHODS,
        // `Hash` and `Hmac` answer the same two methods (both route to
        // `crypto::hashlike_call`). Only `Hmac` was listed, so
        // `ensure_ctor_proto("Hash")` found nothing and `crypto.Hash.prototype`
        // read `undefined` — the ES5-subclassing hole this table exists to
        // close, still open for one of the two constructors it documents.
        // `copy` is Hash-only — an Hmac cannot be forked.
        "Hash" => &["update", "digest", "copy"],
        "Hmac" => &["update", "digest"],
        "Crypto" => crypto::WEBCRYPTO_METHODS,
        "webcrypto.SubtleCrypto" => crypto::SUBTLE_METHODS,
        // `performance` is the `Performance` instance; the methods it shares
        // with the `perf_hooks` module live on `Performance.prototype`.
        "Performance" => &[
            "clearResourceTimings",
            "setResourceTimingBufferSize",
            "now",
            "mark",
            "measure",
            "getEntriesByName",
            "getEntriesByType",
            "getEntries",
            "clearMarks",
            "clearMeasures",
            "eventLoopUtilization",
            "timerify",
        ],
        "StringDecoder" => string_decoder::INSTANCE_METHODS,
        "Interface" => readline::INTERFACE_METHODS,
        "ReadlineIterator" => readline::ITERATOR_METHODS,
        "Script" => vm::SCRIPT_METHODS,
        "URLSearchParams" => url::SEARCH_PARAMS_METHODS,
        "UdpSocket" => dgram::SOCKET_METHODS,
        "Worker" => worker_threads::WORKER_METHODS,
        "MessagePort" => worker_threads::PORT_METHODS,
        "TLSServer" => tls::SERVER_METHODS,
        "TLSSocket" => tls::SOCKET_METHODS,
        "HTTPSServerResponse" => https::RESPONSE_METHODS,
        "HTTPSClientRequest" => https::CLIENT_REQUEST_METHODS,
        "REPLServer" => repl::REPLSERVER_METHODS,
        "ClusterWorker" => cluster::WORKER_METHODS,
        "Domain" => domain::DOMAIN_METHODS,
        "Tracing" => trace_events::TRACING_METHODS,
        "Http2Server" => http2::SERVER_METHODS,
        "Http2Stream" => http2::STREAM_METHODS,
        "Http2Session" => http2::SESSION_METHODS,
        "Cipheriv" | "Decipheriv" => &["update", "final", "setAutoPadding"],
        "BlockList" => net::BLOCKLIST_METHODS,
        "ClientRequest" => http::CLIENT_REQUEST_METHODS,
        "Agent" => &["destroy", "getName"],
        "Blob" | "File" => buffer::BLOB_METHODS,
        "ReadStream" => tty::READ_STREAM_METHODS,
        "Dirent" | "Stats" | "BigIntStats" => fs::DIRENT_METHODS,
        "Dir" => fs::DIR_METHODS,
        "FSReadStream" => fs::READ_STREAM_METHODS,
        "FSWriteStream" => fs::WRITE_STREAM_METHODS,
        "Resolver" => dns::RESOLVER_METHODS,
        "Histogram" => perf_hooks::HISTOGRAM_METHODS,
        "PerformanceObserver" => perf_hooks::PERFORMANCE_OBSERVER_METHODS,
        "PerformanceObserverEntryList" => perf_hooks::OBSERVER_ENTRY_LIST_METHODS,
        "BroadcastChannel" => worker_threads::BROADCAST_CHANNEL_METHODS,
        "TracingChannel" => diagnostics_channel::TRACING_CHANNEL_METHODS,
        "Serializer" => v8::SERIALIZER_METHODS,
        "Deserializer" => v8::DESERIALIZER_METHODS,
        "Console" => console::CONSOLE_METHODS,
        "ChildProcess" => child_process::CHILD_PROCESS_METHODS,
        "ChildPipe" => child_process::CHILD_PIPE_METHODS,
        "Sign" => &["update", "sign"],
        "Verify" => &["update", "verify"],
        "KeyObject" => &["equals", "toCryptoKey"],
        // `export` is on each LEAF, since what it exports differs.
        "SecretKeyObject" | "PublicKeyObject" | "PrivateKeyObject" => &["export"],
        "DiffieHellman" => &[
            "generateKeys",
            "computeSecret",
            "getPrime",
            "getGenerator",
            "getPublicKey",
            "getPrivateKey",
            "setPublicKey",
            "setPrivateKey",
        ],
        "ECDH" => &[
            "generateKeys",
            "computeSecret",
            "getPublicKey",
            "getPrivateKey",
            "setPrivateKey",
        ],
        "X509Certificate" => &["toString"],
        "FinalizationRegistry" => &["register", "unregister"],
        "MIMEType" => util::MIME_TYPE_METHODS,
        "MIMEParams" => util::MIME_PARAMS_METHODS,
        t if fetch::is_class(t) => fetch::methods_for(t),
        "EventTarget" => event_target::EVENT_TARGET_METHODS,
        "Event" => event_target::EVENT_METHODS,
        _ => &[],
    };
    let is_emitter = matches!(
        tag,
        "Server"
            | "Socket"
            | "ServerResponse"
            | "IncomingMessage"
            | "EventEmitter"
            | "Readable"
            | "Writable"
            | "Duplex"
            | "Transform"
            | "PassThrough"
            | "Stream"
            | "UdpSocket"
            | "Worker"
            | "MessagePort"
            | "TLSServer"
            | "TLSSocket"
            | "HTTPSServerResponse"
            | "HTTPSClientRequest"
            | "ClusterWorker"
            | "Domain"
            | "Http2Server"
            | "Http2Stream"
            | "Http2Session"
            | "ClientRequest"
            | "FSReadStream"
            | "FSWriteStream"
            | "ChildProcess"
            | "ChildPipe"
    );
    (base, if is_emitter { EMITTER } else { &[] })
}

/// Dispatch a method call on a native stdlib instance (`recv` carries a
/// `@@native` tag). Called from `host::call_method` before the generic object
/// method resolution.
pub fn instance_call(
    tag: &str,
    recv: &Value,
    method: &str,
    args: Vec<Value>,
) -> Result<Value, String> {
    match tag {
        "Buffer" => buffer::instance_call(recv, method, &args),
        "Timeout" | "Immediate" => timers::instance_call(recv, method, &args),
        "IntervalIterator" => timers::interval_call(recv, method, &args),
        "CollectionIterator" => match method {
            "next" => crate::builtins::collection_iterator_next(recv),
            "@@iterator" => Ok(recv.clone()),
            m if iterator::is_helper(m) => iterator::call(recv, m, &args),
            _ => Err(crate::host::type_error(&format!(
                "mapIterator.{method} is not a function"
            ))),
        },
        "IteratorHelper" => match method {
            "next" => iterator::helper_next(recv),
            "@@iterator" => Ok(recv.clone()),
            // Abandoning a helper marks it exhausted AND closes its source, so
            // a later `next` is a done step and the generator underneath runs
            // its `finally`.
            "return" => Ok(iterator::helper_return(recv)),
            m if iterator::is_helper(m) => iterator::call(recv, m, &args),
            _ => Err(crate::host::type_error(&format!(
                "{method} is not a function"
            ))),
        },
        "Date" => date::instance_call(recv, method, &args),
        "StringDecoder" => string_decoder::instance_call(recv, method, &args),
        "WeakRef" => typedarray::weakref_call(recv, method),
        "FinalizationRegistry" => typedarray::finalization_registry_call(recv, method, &args),
        "TextEncoder" => typedarray::text_encoder_call(recv, method, &args),
        "TextDecoder" => typedarray::text_decoder_call(recv, method, &args),
        "TypedArray" => typedarray::instance_call(recv, method, &args),
        "DataView" => typedarray::dataview_call(recv, method, &args),
        // An `ArrayBuffer`'s only instance method is `slice`, which copies the
        // byte range into a fresh buffer.
        "ArrayBuffer" if method == "slice" => {
            if typedarray::is_detached(recv) {
                return Err(typedarray::detached_error(
                    "ArrayBuffer.prototype",
                    "slice",
                    true,
                ));
            }
            Ok(typedarray::buffer_slice(recv, &args))
        }
        "ArrayBuffer" if method == "resize" => typedarray::buffer_resize(recv, &args),
        "ArrayBuffer" if method == "transfer" => typedarray::buffer_transfer(recv, &args, false),
        "ArrayBuffer" if method == "transferToFixedLength" => {
            typedarray::buffer_transfer(recv, &args, true)
        }
        t if fetch::is_class(t) => fetch::instance_call(t, recv, method, &args),
        "EventTarget" | "Event" | "CustomEvent" => {
            event_target::instance_call(tag, recv, method, &args)
        }
        "Hash" => crypto::instance_call(recv, method, &args),
        "Hmac" => crypto::hmac_instance_call(recv, method, &args),
        "Interface" => readline::instance_call(recv, method, args),
        "ReadlineIterator" => readline::iterator_call(recv, method),
        "Script" => vm::instance_call(recv, method, args),
        "URLSearchParams" => url::search_params_call(recv, method, &args),
        "UdpSocket" => dgram::instance_call(recv, method, args),
        "Worker" | "MessagePort" | "BroadcastChannel" => {
            worker_threads::instance_call(tag, recv, method, args)
        }
        "TLSServer" | "TLSSocket" => tls::instance_call(tag, recv, method, args),
        "HTTPSServerResponse" | "HTTPSClientRequest" => {
            https::instance_call(tag, recv, method, args)
        }
        "REPLServer" => repl::instance_call(recv, method, args),
        "ClusterWorker" => cluster::instance_call(recv, method, args),
        "Domain" => domain::instance_call(recv, method, args),
        "Tracing" => trace_events::instance_call(recv, method, args),
        "Http2Server" | "Http2Stream" | "Http2Session" => {
            http2::instance_call(tag, recv, method, args)
        }
        "EventEmitter" => events::instance_call(recv, method, args),
        "URL" => url::instance_call(recv, method, &args),
        "Stats" | "BigIntStats" => fs::stats_call(recv, method),
        "Dirent" => fs::dirent_call(recv, method),
        "Dir" => fs::dir_call(recv, method, args),
        "FSReadStream" => fs::read_stream_call(recv, method, args),
        "FSWriteStream" => fs::write_stream_call(recv, method, args),
        "Server" | "Socket" | "BlockList" => net::instance_call(tag, recv, method, args),
        "IncomingMessage" | "ServerResponse" | "ClientRequest" | "Agent" => {
            http::instance_call(tag, recv, method, args)
        }
        "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => {
            stream::instance_call(tag, recv, method, args)
        }
        "Cipheriv" | "Decipheriv" => crypto::cipher_instance_call(tag, recv, method, &args),
        "Sign" | "Verify" => crypto::sign_verify_instance_call(tag, recv, method, &args),
        "KeyObject"
        | "SecretKeyObject"
        | "AsymmetricKeyObject"
        | "PublicKeyObject"
        | "PrivateKeyObject" => crypto::key_object_instance_call(recv, method, &args),
        "DiffieHellman" => crypto::dh_instance_call(recv, method, &args),
        "ECDH" => crypto::ecdh_instance_call(recv, method, &args),
        "X509Certificate" => crypto::x509_instance_call(recv, method, &args),
        "MIMEType" => util::mime_type_instance_call(recv, method, &args),
        "MIMEParams" => util::mime_params_instance_call(recv, method, &args),
        "Blob" | "File" => buffer::blob_call(recv, method, &args),
        "ReadStream" => tty::instance_call(recv, method, &args),
        "Resolver" => dns::resolver_instance_call(recv, method, args),
        "Histogram" => perf_hooks::histogram_instance_call(recv, method, &args),
        "PerformanceObserver" => perf_hooks::observer_instance_call(recv, method, &args),
        "PerformanceObserverEntryList" => perf_hooks::entry_list_instance_call(recv, method, &args),
        "TracingChannel" => diagnostics_channel::tracing_instance_call(recv, method, &args),
        "Serializer" | "Deserializer" => v8::instance_call(tag, recv, method, args),
        "Console" => console::instance_call(recv, method, args),
        "ChildProcess" => child_process::instance_call(recv, method, args),
        "ChildPipe" => child_process::pipe_call(recv, method, args),
        "AsyncLocalStorage" | "AsyncHook" | "AsyncResource" => {
            async_hooks::instance_call(tag, recv, method, args)
        }
        "Channel" => diagnostics_channel::instance_call(recv, method, &args),
        "WriteStream" => process::stream_instance_call(recv, method, &args),
        "StdinIterator" => process::stdin_iterator_call(recv, method),
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}

// ── shared helpers ──────────────────────────────────────────────────────────

/// The `Received …` tail Node appends to an `ERR_INVALID_ARG_TYPE` message
/// (`internal/errors.js` `determineSpecificType`): `null`/`undefined` verbatim,
/// a primitive as `type <typeof> (<inspected>)`, a function as
/// `function <name>`, an object as `an instance of <Ctor>`.
pub(crate) fn received_desc(v: &Value) -> String {
    with_host(|h| {
        if matches!(v, Value::Undef) {
            return "undefined".to_string();
        }
        if h.is_null(v) {
            return "null".to_string();
        }
        let ty = h.type_of(v);
        // A callable is named by its own `.name`, never by its constructor:
        // `determineSpecificType` reports `function foo` (and `function ` for an
        // anonymous one), where this used to say `an instance of Object`.
        if ty == "function" {
            return format!("function {}", h.callable_name(v));
        }
        if ty == "object" {
            // `ctor_name` is empty for the builtin shapes (they carry no user
            // class), so fall back to the intrinsic constructor name.
            let name = match h.ctor_name(v) {
                n if !n.is_empty() => n,
                _ => match h.get(v) {
                    Some(JsObj::Array(_)) => "Array".into(),
                    Some(JsObj::Map { .. }) => "Map".into(),
                    Some(JsObj::Set { .. }) => "Set".into(),
                    Some(JsObj::Promise { .. }) => "Promise".into(),
                    Some(JsObj::RegExp(_)) => "RegExp".into(),
                    Some(JsObj::Object(p)) => match p.get("@@native") {
                        Some(t) => h.str_of(t),
                        None => "Object".into(),
                    },
                    _ => "Object".into(),
                },
            };
            return format!("an instance of {name}");
        }
        let shown = match ty {
            "string" => format!("'{}'", h.str_of(v)),
            "bigint" => format!("{}n", h.str_of(v)),
            "number" if matches!(v, Value::Float(f) if *f == 0.0 && f.is_sign_negative()) => {
                "-0".to_string()
            }
            _ => h.str_of(v),
        };
        format!("type {ty} ({shown})")
    })
}

/// ToString of `args[i]` (empty string if absent).
pub(crate) fn arg_str(args: &[Value], i: usize) -> String {
    with_host(|h| args.get(i).map(|v| h.str_of(v)).unwrap_or_default())
}

/// ToNumber of `args[i]` (`NaN` if absent).
pub(crate) fn arg_num(args: &[Value], i: usize) -> f64 {
    with_host(|h| args.get(i).map(|v| h.to_number(v)).unwrap_or(f64::NAN))
}

/// Lowercase hex encoding of `bytes`.
pub(crate) fn to_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
        s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
    }
    s
}

/// Decode a hex string to bytes as node's `StringBytes` does: pair by pair
/// from the start, STOPPING at the first pair that is not two hex digits, and
/// dropping a trailing odd nibble. `Buffer.from('12zz34', 'hex')` is the one
/// byte `12`, not `12 34` — a non-digit is a terminator, never skipped.
pub(crate) fn from_hex(s: &str) -> Vec<u8> {
    let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
    s.as_bytes()
        .chunks_exact(2)
        .map_while(|p| Some((digit(p[0])? << 4) | digit(p[1])?))
        .collect()
}

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Standard base64 encoding (with `=` padding) of `bytes`.
pub(crate) fn to_base64(bytes: &[u8]) -> String {
    let mut out = String::new();
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
        out.push(B64[((n >> 18) & 63) as usize] as char);
        out.push(B64[((n >> 12) & 63) as usize] as char);
        out.push(if chunk.len() > 1 {
            B64[((n >> 6) & 63) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            B64[(n & 63) as usize] as char
        } else {
            '='
        });
    }
    out
}

/// URL-safe base64 (RFC 4648 §5) of `bytes`: `+/` become `-_` and the `=`
/// padding is dropped. This is `buf.toString('base64url')`, which is a distinct
/// encoding from `'base64'` — not an alias. Node emits `Buffer.from([251,255,
/// 190,1]).toString('base64url')` as `-_--AQ` where `'base64'` gives `+/++AQ==`.
pub(crate) fn to_base64url(bytes: &[u8]) -> String {
    to_base64(bytes)
        .chars()
        .filter(|c| *c != '=')
        .map(|c| match c {
            '+' => '-',
            '/' => '_',
            c => c,
        })
        .collect()
}

/// Decode a base64 string to bytes (ignores whitespace and padding).
///
/// BOTH alphabets are accepted, in either direction: node decodes `-_` under
/// `'base64'` and `+/` under `'base64url'` (measured — `Buffer.from('-_-_',
/// 'base64').toString('hex')` and `Buffer.from('+/+/','base64url')
/// .toString('hex')` are both `fbffbf` on v26.7.0), so the decoder does not need
/// to know which name it was reached by. Refusing the URL-safe characters here
/// silently produced an EMPTY buffer, because an unrecognized character is
/// dropped rather than rejected.
pub(crate) fn from_base64(s: &str) -> Vec<u8> {
    let rev = |c: u8| -> Option<u32> {
        let c = match c {
            b'-' => b'+',
            b'_' => b'/',
            c => c,
        };
        B64.iter().position(|&x| x == c).map(|p| p as u32)
    };
    let vals: Vec<u32> = s.bytes().filter_map(rev).collect();
    let mut out = Vec::new();
    for chunk in vals.chunks(4) {
        if chunk.len() < 2 {
            break;
        }
        let n = (chunk[0] << 18)
            | (chunk[1] << 12)
            | (chunk.get(2).copied().unwrap_or(0) << 6)
            | chunk.get(3).copied().unwrap_or(0);
        out.push((n >> 16) as u8);
        if chunk.len() > 2 {
            out.push((n >> 8) as u8);
        }
        if chunk.len() > 3 {
            out.push(n as u8);
        }
    }
    out
}

/// node's `validateInteger(value, name, min)` (`max` is
/// `Number.MAX_SAFE_INTEGER`): a Number, an integer, and within range — each
/// failure with node's own code and wording.
pub(crate) fn validate_integer(v: &Value, name: &str, min: f64) -> Result<f64, String> {
    validate_integer_in(v, name, min, 9_007_199_254_740_991.0)
}

/// `validateInteger(value, name, min, max)` with an explicit `max`.
pub(crate) fn validate_integer_in(
    v: &Value,
    name: &str,
    min: f64,
    max: f64,
) -> Result<f64, String> {
    if with_host(|h| h.type_of(v)) != "number" {
        return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
    }
    let n = with_host(|h| h.to_number(v));
    if n.fract() != 0.0 || !n.is_finite() {
        return Err(out_of_range(name, "an integer", n));
    }
    if n < min || n > max {
        let must = format!(
            ">= {} && <= {}",
            crate::host::fmt_number(min),
            crate::host::fmt_number(max)
        );
        return Err(out_of_range(name, &must, n));
    }
    Ok(n)
}

/// node's `ERR_OUT_OF_RANGE` for a numeric `name`: `It must be <must>.
/// Received <n>`, the received value rendered as node renders it.
pub(crate) fn out_of_range(name: &str, must: &str, n: f64) -> String {
    crate::host::coded_error(
        "RangeError",
        "ERR_OUT_OF_RANGE",
        &format!(
            "The value of \"{name}\" is out of range. It must be {must}. Received {}",
            buffer::out_of_range_received(n)
        ),
    )
}

/// A builtin SINGLETON kept as a namespace (`performance`, `crypto`,
/// `crypto.subtle`) and the class it is the one instance of, under the key
/// that class's `Builtin` is spelled with. Every view of the instance — its
/// prototype, `instanceof`, brand, `constructor`, own keys, `hasOwnProperty`,
/// and its methods (read off the class prototype) — consults this one table.
pub fn singleton_class(ns: &str) -> Option<&'static str> {
    match ns {
        "performance" => Some("Performance"),
        "webcrypto" => Some("Crypto"),
        "SubtleCrypto" => Some(SUBTLE_CRYPTO_CLASS),
        _ => None,
    }
}

/// The key of the `SubtleCrypto` CLASS. `SubtleCrypto` itself names the
/// `crypto.subtle` namespace, and the last dotted segment is the name the
/// class reports.
pub const SUBTLE_CRYPTO_CLASS: &str = "webcrypto.SubtleCrypto";

/// The display name of a class key (`webcrypto.SubtleCrypto` → `SubtleCrypto`).
pub fn class_display_name(key: &str) -> &str {
    key.rsplit('.').next().unwrap_or(key)
}

/// The web classes whose prototype getters brand-check `this` and throw
/// `ERR_INVALID_THIS` for any other receiver.
pub fn brand_checked_class(ctor: &str) -> bool {
    matches!(ctor, "Crypto" | "CryptoKey")
}

/// `new Performance()`, `new Crypto()`, … — classes node lets no script build.
pub fn illegal_constructor(name: &str) -> bool {
    matches!(
        name,
        "Performance" | "Crypto" | "CryptoKey" | SUBTLE_CRYPTO_CLASS
    )
}