browser_oxide 0.1.3

Stealth headless browser engine in Rust: real HTML/CSS/DOM/JS, V8 via deno_core, own BoringSSL TLS/JA4 fingerprint, no Chromium, no CDP — for anti-bot web scraping, archival, and AI agents
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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
use crate::dom::Dom;
use crate::event_loop::{BrowserEventLoop, IdleReason};
use crate::iframe;
use crate::js_runtime::{runtime::BrowserRuntimeOptions, BrowserJsRuntime};
use crate::script_runner;
use crate::stylesheet_collector;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

/// Whether a URL is a "secure context" per WICG/secure-contexts §3.2.
/// Secure: https, wss, file, plus http://localhost / http://127.0.0.1 /
/// http://[::1] / *.localhost loopback exceptions. Drives `isSecureContext`
/// and gates the ~18 secure-context-only Web Platform APIs.
pub(crate) fn is_secure_url(url: &str) -> bool {
    let parsed = match url::Url::parse(url) {
        Ok(u) => u,
        Err(_) => return false,
    };
    match parsed.scheme() {
        "https" | "wss" | "file" => true,
        "http" | "ws" => match parsed.host_str() {
            Some(h) => {
                h == "localhost"
                    || h.ends_with(".localhost")
                    || h == "127.0.0.1"
                    || h == "[::1]"
                    || h == "::1"
            }
            None => false,
        },
        _ => false, // about:, data:, blob:, javascript:, etc. — insecure
    }
}

#[cfg(test)]
mod is_secure_url_tests {
    use super::is_secure_url;
    #[test]
    fn classifies_schemes() {
        assert!(is_secure_url("https://example.com/"));
        assert!(is_secure_url("wss://example.com/"));
        assert!(is_secure_url("file:///etc/hosts"));
        assert!(is_secure_url("http://localhost:3000/"));
        assert!(is_secure_url("http://127.0.0.1/"));
        assert!(is_secure_url("http://my-app.localhost/"));
        assert!(!is_secure_url("http://example.com/"));
        assert!(!is_secure_url("data:text/html,<p>x"));
        assert!(!is_secure_url("about:blank"));
        assert!(!is_secure_url("blob:https://example.com/x"));
        assert!(!is_secure_url("javascript:void(0)"));
    }
}

/// RAII guard that fires `terminate_execution` on the V8 isolate after
/// a deadline expires, unless dropped first. Used by `navigate_with_init`
/// to bound how long any single iteration can spin in CPU-bound JS — for
/// sites like delta.com or taobao.com whose JS does not yield to tokio.
///
/// The `Drop` impl signals the watcher thread to exit cleanly (no
/// terminate fires). If the deadline elapses before drop, terminate
/// fires and the next `execute_script` call returns the
/// "Uncaught Error: execution terminated" exception — caller is
/// responsible for catching that and bailing out of the iteration.
struct V8DeadlineWatcher {
    cancel: Arc<AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl V8DeadlineWatcher {
    fn new(isolate: deno_core::v8::IsolateHandle, deadline: Duration) -> Self {
        let cancel = Arc::new(AtomicBool::new(false));
        let cancel_clone = cancel.clone();
        let handle = std::thread::spawn(move || {
            let start = std::time::Instant::now();
            // Poll the cancel flag at 100 ms granularity so drop is fast.
            while start.elapsed() < deadline {
                if cancel_clone.load(Ordering::Relaxed) {
                    return;
                }
                std::thread::sleep(Duration::from_millis(100));
            }
            if !cancel_clone.load(Ordering::Relaxed) {
                eprintln!(
                    "[V8DeadlineWatcher] deadline {}ms expired — firing terminate_execution",
                    deadline.as_millis()
                );
                let ok = isolate.terminate_execution();
                eprintln!("[V8DeadlineWatcher] terminate_execution returned {}", ok);
            }
        });
        Self {
            cancel,
            handle: Some(handle),
        }
    }
}

impl Drop for V8DeadlineWatcher {
    fn drop(&mut self) {
        self.cancel.store(true, Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            // Best-effort join — watcher polls every 100 ms so this returns fast.
            let _ = h.join();
        }
    }
}

/// Typed page outcome for measurement hygiene.
///
/// Replaces the old bare boolean "blocked?" guess. Every navigated
/// site resolves to exactly one of these so the re-baseline can tell a
/// genuine challenge apart from a render-incomplete false positive
/// (the cheap "wins" with zero stealth work).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChallengeVerdict {
    /// Real content rendered, no structural challenge markers.
    Pass,
    /// No challenge markers but a thin/empty stub or an SPA shell that
    /// never populated — a render-completeness issue, NOT a stealth
    /// failure (e.g. mail-ru redirect, captcha-shell, washingtonpost-
    /// style multi-MB body that the old classifier over-matched).
    RenderIncomplete,
    /// Challenge marker + small body: an explicit challenge/deny page
    /// (a small 429, a 2.6 KB sec-cpt PoW, a managed challenge, an
    /// interstitial) was served before our JS could
    /// earn trust — edge / interstitial class.
    EdgeBlock,
    /// Challenge marker + a large body that otherwise rendered: the
    /// vendor JS ran and the sensor scored the telemetry as bot.
    SensorFail,
    /// FP-B3: rendered, no challenge marker, but the body is below a
    /// real-content floor (above the THIN-BODY noise floor) — a thin
    /// shell / SPA pre-hydration stub, not the full content. Distinct
    /// from [`Self::Pass`] so a small shell is not over-counted as a
    /// full win (the bestbuy 7.8 KB / spotify 9.6 KB class). NOT a
    /// challenge (`is_challenge()==false`) — it is a content-depth
    /// caveat, like [`Self::RenderIncomplete`] but above the thin-body
    /// floor.
    ThinShell,
    /// FP-B4: a challenge is structurally present in a *large* body but
    /// the vendor flow never *completed* (no clearance / no nav) — e.g.
    /// a managed-challenge orchestrator shell that ran but
    /// did not issue `cf_clearance`. Distinct from [`Self::SensorFail`]
    /// (which implies the sensor *scored us bot* ⇒ misdirects work to
    /// fingerprint tuning) and from [`Self::Pass`] (the page never
    /// rendered real content). A 476 KB managed-challenge shell is the
    /// motivating case — it must not read as either a sensor-fail or a pass.
    ChallengeIncomplete,
}

impl ChallengeVerdict {
    /// True for every served-challenge outcome — the exact semantics of
    /// the old boolean `is_anti_bot_challenge`.
    pub fn is_challenge(self) -> bool {
        // ChallengeIncomplete IS an unsolved challenge (not a pass) — it
        // must keep the navigate-loop retry/poll paths active.
        matches!(
            self,
            Self::EdgeBlock | Self::SensorFail | Self::ChallengeIncomplete
        )
    }

    /// Stable lowercase tag for JSON/audit output.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pass => "pass",
            Self::RenderIncomplete => "render-incomplete",
            Self::EdgeBlock => "edge-block",
            Self::SensorFail => "sensor-fail",
            Self::ChallengeIncomplete => "challenge-incomplete",
            Self::ThinShell => "thin-shell",
        }
    }
}

/// Shared structural anti-bot challenge classifier.
///
/// FP-B1: this is now a thin delegate to the single canonical classifier
/// [`crate::classify::engine_classify`] so `page.rs`, `holistic_sweep`,
/// and the audit harness can never disagree about the same body again.
/// The per-marker / per-gate logic (and its rationale — weak markers
/// only count stub-sized, etc.) lives there as the single source of
/// truth; this wrapper keeps the four navigate-loop call sites stable.
fn body_has_challenge_marker(body: &str) -> bool {
    crate::classify::engine_classify(body)
        .verdict
        .is_challenge()
}

/// Public-engine interstitial detector for one challenge vendor.
///
/// Identifies a `rt:'i'` interstitial document by the
/// `captcha-delivery.com` substring — the vendor's CDN that serves the
/// daily-rotated WASM challenge bundle. The interstitial is small
/// (typically 1-5 KB) and loads `captcha-delivery.com` as a
/// `<script src=…>`; a rendered real page mentioning the CDN in passing
/// would be much larger. The 50 KB size gate guards against that false
/// positive while safely covering every shipped interstitial.
///
/// Used at three navigate-loop points to make the engine's
/// vendor-aware behaviour (CSP relaxation, iframe materialization,
/// solved-cookie retry) fire on ANY challenge document from this vendor,
/// not just navs where a registered solver claims the response. The
/// solver implementation itself is out of scope for this repository
/// (see `SCOPE.md`); these three defensive primitives are part of the
/// public engine (they enable the bundle's OWN self-solve flow to run).
fn is_interstitial_challenge(html: &str) -> bool {
    // Tightened. The 50 KB cap + CDN string alone could misclassify a
    // real rendered page that merely references captcha-delivery.com. Tiny
    // bodies (<8 KB) with the CDN are unambiguously the interstitial (every
    // shipped interstitial is 1-5 KB). In the 8-50 KB band, additionally
    // require a vendor-config structural token (`dd={ 'rt':…, 'cid':…, … }`)
    // so a real page can't trip the vendor-aware behaviour.
    if html.len() >= 50_000 || !html.contains("captcha-delivery.com") {
        return false;
    }
    if html.len() < 8_000 {
        return true;
    }
    html.contains("'cid'")
        || html.contains("\"cid\"")
        || html.contains("'rt'")
        || html.contains("\"rt\"")
        || html.contains("dd={")
        || html.contains("interstitial")
}

/// Public-engine solve detector for that challenge vendor.
///
/// A genuine solve = the cookie jar has `datadome=` AND the current
/// body is no longer an interstitial (post-solve body is the
/// real page content, not the captcha-delivery.com challenge document).
/// A `datadome=` cookie is set on EVERY nav to this vendor including
/// the failing 403, so the cookie alone is not a solve marker — the
/// body-shape transition is what differentiates "still bouncing on the
/// interstitial" from "passed through".
fn is_interstitial_solved(cookies: &str, body: &str) -> bool {
    cookies.contains("datadome=") && !is_interstitial_challenge(body)
}

/// Public-engine sec-cpt solve detector.
///
/// The sec-cpt cookie carries a state segment between two `~` delimiters
/// — the engine considers the challenge SOLVED only when:
///   1. The cookie jar holds `sec_cpt=`
///   2. The value contains the documented success marker
///   3. The current body is no longer the sec-cpt challenge page
///      (no `sec-if-cpt-container` / `sec-cpt-if` markers — those
///      transition out post-solve when the vendor serves the real homepage)
///
/// Mirrors `is_interstitial_solved`'s shape. Wired into the navigate loop's
/// `solved_signal` check so the public engine breaks out of the
/// poll-and-retry once the bundle's self-solve completes, EVEN WITHOUT
/// a solver registered (the default solver set is empty). The WASM /
/// signature computation stays in the bundle itself; this helper just
/// recognizes the success state.
fn is_seccpt_solved(cookies: &str, body: &str) -> bool {
    cookies.contains("sec_cpt=")
        && cookies.contains("~3~")
        && !body.contains("sec-if-cpt-container")
        && !body.contains("sec-cpt-if")
}

/// Public-engine AWS-WAF token-challenge detector.
///
/// The AWS-WAF "Challenge" / "Captcha" action serves a small (~2 KB) stub
/// that defines `window.gokuProps = {key,iv,context}` +
/// `window.awsWafCookieDomainList`, loads `challenge.js` from
/// `*.token.awswaf.com`, and calls
/// `AwsWafIntegration.checkForceRefresh().then(() => getToken())`. The PoW
/// runs in a blob-URL Web Worker; on success `getToken()` POSTs the
/// solution, sets the `aws-waf-token` cookie, and reloads. Mirrors
/// [`is_interstitial_challenge`]'s shape so the navigate loop arms the same
/// poll + cookie-diff retry primitives for AWS as it already does for
/// the other challenge vendors. The token solver itself is out of scope
/// here (see `SCOPE.md`) — these are the public-engine primitives
/// that let challenge.js's OWN self-solve run to completion (the
/// live-nav drain is what gives it the wall-clock to do so).
fn is_awswaf_challenge(html: &str) -> bool {
    html.len() < 4096 && html.contains("AwsWafIntegration") && html.contains("gokuProps")
}

/// Per-host navigate-budget overrides, sourced entirely from the environment.
///
/// The baseline navigate budget is 15 s — most pages render their primary
/// body well under that. A few classes of site legitimately need longer:
/// heavy proof-of-work VMs, sensor-payload flows, and large React/Vue SPA
/// shells whose hydration runs slower under our V8 than under headed Chrome.
/// Rather than ship a hardcoded list of hostnames (which would couple the
/// public engine to specific sites — see `SCOPE.md`), the operator supplies
/// their own overrides via `BROWSER_OXIDE_HOST_BUDGET_MS`:
///
/// ```text
/// BROWSER_OXIDE_HOST_BUDGET_MS="example.com=45000,spa.example=90000"
/// ```
///
/// Each entry is `<host-suffix>=<milliseconds>`, comma-separated. A host
/// matches an entry when it ends with the suffix (so `www.example.com`
/// matches `example.com`). When several entries match, the longest suffix
/// wins, so a more specific override takes precedence. Returns the 15 s
/// baseline when the variable is unset, empty, or has no matching entry.
fn host_budget_default_ms(host: Option<&str>) -> u64 {
    const BASELINE_MS: u64 = 15_000;
    let Some(host) = host else { return BASELINE_MS };
    let Ok(spec) = std::env::var("BROWSER_OXIDE_HOST_BUDGET_MS") else {
        return BASELINE_MS;
    };
    spec.split(',')
        .filter_map(|entry| {
            let (suffix, ms) = entry.split_once('=')?;
            let suffix = suffix.trim();
            let ms: u64 = ms.trim().parse().ok()?;
            host.ends_with(suffix).then_some((suffix.len(), ms))
        })
        .max_by_key(|(suffix_len, _)| *suffix_len)
        .map_or(BASELINE_MS, |(_, ms)| ms)
}

/// Geo country-selection splash follow (e.g. bestbuy "Best Buy
/// International: Select your Country"). A datacenter / non-US IP is served a
/// thin interstitial instead of the storefront; the splash's own region link
/// (here `https://www.bestbuy.com/?intl=nosplash` — same host, root path, with
/// a splash-skip query) serves the real site. A real regional visitor clicks
/// "United States"; we follow the same-host root link to the document's own
/// region exactly once.
///
/// Tightly gated to avoid false positives: thin body (interstitial-sized) +
/// an explicit country-selection phrase + a SAME-HOST link whose path is `/`
/// and which carries a query that differs from the current URL. A legitimate
/// cross-region selector links OFF-host (e.g. bestbuy.ca) and is never
/// followed; a normal storefront page is far above the size gate. Returns the
/// absolute URL to follow, or `None`.
fn geo_country_splash_target(body: &str, current_url: &str) -> Option<String> {
    if body.len() >= 30_000 {
        return None;
    }
    let lower = body.to_lowercase();
    let is_splash = lower.contains("country")
        && (lower.contains("select your country")
            || lower.contains("choose a country")
            || lower.contains("choisir un pays")
            || lower.contains("seleccione su país"));
    if !is_splash {
        return None;
    }
    let cur = url::Url::parse(current_url).ok()?;
    let cur_host = cur.host_str()?;
    let mut idx = 0usize;
    while let Some(hpos) = body[idx..].find("href=\"") {
        let start = idx + hpos + 6;
        let Some(rel_end) = body[start..].find('"') else {
            break;
        };
        let href = body[start..start + rel_end].replace("&amp;", "&");
        idx = start + rel_end + 1;
        if let Ok(u) = cur.join(&href) {
            if u.host_str() == Some(cur_host)
                && u.path() == "/"
                && u.query().is_some()
                && u.as_str() != cur.as_str()
            {
                return Some(u.to_string());
            }
        }
    }
    None
}

/// Public-engine AWS-WAF solve detector.
///
/// A genuine solve = the jar holds the `aws-waf-token` cookie AND the
/// current body is no longer the AWS challenge stub (challenge.js posted
/// the PoW token and the reload served real content). Mirrors
/// [`is_interstitial_solved`] / [`is_seccpt_solved`].
fn is_awswaf_solved(cookies: &str, body: &str) -> bool {
    cookies.contains("aws-waf-token=") && !is_awswaf_challenge(body)
}

/// Scrub a stale cross-domain cookie collision on entry.
///
/// When a site is reachable under two eTLD+1 identities (the classic case
/// being a domain rebrand whose redirect populates jar buckets for BOTH),
/// the WAF on one domain can read the other's inherited session +
/// bot-management cookies as a stale "previously-issued session" and serve a
/// tiny stub instead of the real page. The fix is to clear BOTH identities'
/// cookies, but ONLY when the jar already holds cookies for both (the
/// second-visit poisoning condition — a first visit with an empty jar must
/// not fire).
///
/// The engine ships NO hardcoded domain pairs (see `SCOPE.md`). Operators who
/// hit this opt in via `BROWSER_OXIDE_COOKIE_COLLISION_PAIRS`, a
/// comma-separated list of `<domain-a>=<domain-b>` pairs, e.g.
/// `BROWSER_OXIDE_COOKIE_COLLISION_PAIRS="twitter.com=x.com"`. When the
/// current host matches either side of a pair (exact host or a subdomain) and
/// the jar holds cookies for both sides, both are cleared.
///
/// Shared by `navigate_with_init_solvers` (cold) AND `navigate_warm`
/// (PagePool reuse), so a pooled Page can't silently serve the unpatched stub.
async fn scrub_cookie_collision(url: &str, client: &crate::net::HttpClient) {
    let Ok(pairs) = std::env::var("BROWSER_OXIDE_COOKIE_COLLISION_PAIRS") else {
        return;
    };
    let Ok(parsed) = url::Url::parse(url) else {
        return;
    };
    let Some(host) = parsed.host_str() else {
        return;
    };
    let h = host.to_ascii_lowercase();
    let host_matches = |d: &str| h == d || h.ends_with(&format!(".{d}"));
    for entry in pairs.split(',') {
        let Some((a, b)) = entry.split_once('=') else {
            continue;
        };
        let a = a.trim().to_ascii_lowercase();
        let b = b.trim().to_ascii_lowercase();
        if a.is_empty() || b.is_empty() || !(host_matches(&a) || host_matches(&b)) {
            continue;
        }
        let a_url = url::Url::parse(&format!("https://{a}/")).ok();
        let b_url = url::Url::parse(&format!("https://{b}/")).ok();
        let has_a = matches!(&a_url, Some(u) if client.cookies_for_url(u).await.is_some());
        let has_b = matches!(&b_url, Some(u) if client.cookies_for_url(u).await.is_some());
        if has_a && has_b {
            let evicted_a = client.clear_cookies_for_domain(&a).await;
            let evicted_b = client.clear_cookies_for_domain(&b).await;
            tracing::debug!(
                domain_a = %a,
                domain_b = %b,
                evicted_a,
                evicted_b,
                "cookie-collision isolation fired"
            );
        }
    }
}

/// A browser page. Owns a DOM, JS runtime, and event loop.
///
/// # Example
/// ```rust,ignore
/// let page = Page::from_html("<html><body><script>document.title = 'Hello'</script></body></html>", None::<crate::stealth::StealthProfile>).await?;
/// assert_eq!(page.title(), "Hello");
/// ```
pub struct Page {
    // Children hold V8 isolates created after parent — must drop first
    children: Vec<iframe::ChildIframe>,
    event_loop: BrowserEventLoop,
    url: String,
    /// Registered [`crate::ChallengeSolver`]s. `Page::navigate` registers
    /// an empty set (this repository ships no solver implementations — see
    /// `SCOPE.md`); embedders supply their own via
    /// `Page::navigate_with_solvers`. `Page::from_html` / direct
    /// construction also leave this empty (those paths don't run the
    /// challenge loop). The list is only consulted inside the navigate
    /// iteration.
    solvers: std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]>,
}

impl Drop for Page {
    fn drop(&mut self) {
        // Reap any Workers this page's V8 isolate spawned but never
        // explicitly `worker.terminate()`'d from JS. Without this,
        // each orphan worker keeps a 64 MB stack OS thread + child
        // JsRuntime heap alive for the rest of the process — the
        // dominant memory leak observed in the cold-sweep RSS curve
        // (cnn / bloomberg / youtube / discord / udemy and ~8 others
        // produce >15 MB step-ups that never reclaim).
        {
            let op_state = self.event_loop.runtime_mut().op_state();
            let mut state = op_state.borrow_mut();
            crate::js_runtime::extensions::worker_ext::drain_owned_workers(&mut state);
        }
        // Drop children (newer isolates) before parent (older isolate)
        // V8 requires reverse drop order
        while self.children.pop().is_some() {}
    }
}

impl Page {
    /// Simulate a user switching to another tab and then coming back.
    /// This defeats macro-behavioral heuristics that flag sessions
    /// without visibility/focus changes as automated.
    pub async fn simulate_tab_switch(&mut self) -> Result<(), deno_core::error::AnyError> {
        let code = r#"
            (function() {
                // 1. Blur the window (user clicked away)
                window.dispatchEvent(new Event('blur', { bubbles: false, cancelable: false }));
                document.hasFocus = () => false;

                // 2. Hide the document (tab backgrounded)
                Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });
                Object.defineProperty(document, 'hidden', { value: true, configurable: true });
                document.dispatchEvent(new Event('visibilitychange', { bubbles: true, cancelable: false }));
            })();
        "#;
        self.event_loop.execute_script(code)?;

        // Sleep for a random amount of time to simulate reading another tab (e.g., 2-5 seconds)
        // For testing we keep it short, but in a real scraper this would be realistic.
        tokio::time::sleep(std::time::Duration::from_millis(2500)).await;

        let code_focus = r#"
            (function() {
                // 3. Show the document (tab foregrounded)
                Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
                Object.defineProperty(document, 'hidden', { value: false, configurable: true });
                document.dispatchEvent(new Event('visibilitychange', { bubbles: true, cancelable: false }));

                // 4. Focus the window
                document.hasFocus = () => true;
                window.dispatchEvent(new Event('focus', { bubbles: false, cancelable: false }));
            })();
        "#;
        self.event_loop.execute_script(code_focus)?;
        Ok(())
    }

    /// Detect if the current page is an anti-bot challenge.
    ///
    /// Boolean drop-in retained for the four navigate-loop call sites.
    /// Delegates to the shared structural classifier so the
    /// false-positive tightening applies everywhere.
    pub fn is_anti_bot_challenge(&mut self) -> bool {
        let body = self.content();
        body_has_challenge_marker(&body)
    }

    /// Typed page outcome.
    ///
    /// Every navigated site gets exactly one [`ChallengeVerdict`] so a
    /// "blocked" verdict is no longer a bare substring guess. This is
    /// what the `audit_failing_sites` re-baseline consumes to separate
    /// genuine challenges from render-incomplete false positives.
    pub fn challenge_verdict(&mut self) -> ChallengeVerdict {
        // FP-B1: derived from the single canonical classifier so the
        // audit harness verdict and the holistic-sweep tag are computed
        // from the identical marker/gate pass (no more pass↔block
        // disagreement between call sites). The edge-vs-sensor split and
        // the thin band live in `crate::classify` as named constants.
        crate::classify::engine_classify(&self.content()).verdict
    }

    // Vendor-specific challenge resolution (challenge-orchestrator
    // runner, the sensor-payload flow) is NOT part of this engine —
    // concrete `ChallengeSolver` implementations are out of scope here
    // (see `SCOPE.md`). The engine's navigate loop dispatches through
    // whatever solvers an embedder registers (empty by default); see
    // `crate::challenge`.

    /// Create a page from an HTML string. Parses HTML, executes inline scripts,
    /// and runs the event loop until idle (or 30s timeout).
    pub async fn from_html(
        html: &str,
        profile: Option<crate::stealth::StealthProfile>,
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::from_html_with_url(html, "about:blank", profile).await
    }

    /// Create a page quickly — parses HTML, sets up DOM + JS runtime, executes
    /// inline scripts, but does NOT drain the event loop. Useful for CDP
    /// navigation where the caller controls script execution via Runtime.evaluate.
    pub async fn from_html_fast(
        html: &str,
        url: &str,
        profile: crate::stealth::StealthProfile,
    ) -> Result<Self, deno_core::error::AnyError> {
        let dom = crate::html_parser::parse_html(html);
        let scripts = script_runner::find_scripts(&dom);
        let stylesheet_entries = stylesheet_collector::find_stylesheets(&dom);
        let stylesheets = stylesheet_collector::resolve_inline_only(&stylesheet_entries);

        let runtime = BrowserJsRuntime::with_options(
            dom,
            BrowserRuntimeOptions {
                stealth_profile: Some(profile.clone()),
                stylesheets,
                is_secure_context: is_secure_url(url),
                ..Default::default()
            },
        );
        let mut event_loop = BrowserEventLoop::new(runtime);

        // Set location.href (URL-state setup, not a real navigation —
        // reset the nav-pending signal afterward so subsequent
        // run_until_idle calls don't short-circuit).
        let url_js = url.replace('\\', "\\\\").replace('\'', "\\'");
        event_loop
            .execute_script(&format!("location.href = '{}';", url_js))
            .ok();
        event_loop.reset_nav_pending();

        // Share the HTTP client with JS fetch()
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        crate::js_runtime::extensions::fetch_ext::set_fetch_client(client.clone());

        // Execute inline scripts (fast mode skips external scripts by default)
        for (i, script) in scripts.iter().enumerate() {
            if script.src.is_some() {
                continue;
            }
            if !script.code.is_empty() {
                // W2.7 — name inline scripts with document URL (Chrome
                // parity) instead of letting V8 default to <anonymous>.
                // document.currentScript parity (see build_page_with_scripts_init_and_storage).
                let _ = event_loop.execute_script(&format!(
                    "globalThis.__browser_oxide._setCurrentScript(globalThis.__browser_oxide._wrapNode({}))",
                    script.node_id
                ));
                if let Err(e) = event_loop.execute_script_with_name(&script.code, url) {
                    tracing::warn!(script_index = i, error = %e, "Script error in inline script");
                }
                let _ =
                    event_loop.execute_script("globalThis.__browser_oxide._setCurrentScript(null)");
            }
        }

        Ok(Self {
            event_loop,
            url: url.to_string(),
            children: Vec::new(),
            solvers: std::sync::Arc::from(Vec::<std::sync::Arc<dyn crate::ChallengeSolver>>::new()),
        })
    }

    /// Replace the page's content with new HTML, reusing the V8 isolate.
    /// Much faster than creating a new Page (~2ms vs ~17ms) since it skips
    /// V8 isolate creation and bootstrap script execution.
    pub fn reload_html(&mut self, html: &str, url: &str) {
        let dom = crate::html_parser::parse_html(html);
        let scripts = script_runner::find_scripts(&dom);
        let stylesheet_entries = stylesheet_collector::find_stylesheets(&dom);
        let stylesheets = stylesheet_collector::resolve_inline_only(&stylesheet_entries);

        // Swap DOM in existing runtime (no new V8 isolate needed)
        self.event_loop.runtime_mut().replace_dom(dom, stylesheets);

        // Drop old iframe children
        self.children.clear();

        // Update URL (URL-state setup, not a real navigation).
        self.url = url.to_string();
        let url_js = url.replace('\\', "\\\\").replace('\'', "\\'");
        self.event_loop
            .execute_script(&format!("location.href = '{}';", url_js))
            .ok();
        self.event_loop.reset_nav_pending();

        // Execute inline scripts in document order
        for (i, script) in scripts.iter().enumerate() {
            if script.src.is_some() {
                continue; // skip external scripts — caller handles fetching
            }
            if script.code.trim().is_empty() {
                continue;
            }
            // W2.7 — Chrome parity: inline scripts report the document URL.
            // document.currentScript parity (see build_page_with_scripts_init_and_storage).
            let _ = self.event_loop.execute_script(&format!(
                "globalThis.__browser_oxide._setCurrentScript(globalThis.__browser_oxide._wrapNode({}))",
                script.node_id
            ));
            if let Err(e) = self
                .event_loop
                .execute_script_with_name(&script.code, &self.url)
            {
                tracing::warn!(script_index = i, error = %e, "Script error in inline script");
            }
            let _ = self
                .event_loop
                .execute_script("globalThis.__browser_oxide._setCurrentScript(null)");
        }
    }

    /// Create a page with a specific URL.
    pub async fn from_html_with_url(
        html: &str,
        url: &str,
        profile: Option<crate::stealth::StealthProfile>,
    ) -> Result<Self, deno_core::error::AnyError> {
        let dom = crate::html_parser::parse_html(html);

        // Install CSP from any meta-tags present in the HTML (this code
        // path is for tests / synthetic HTML — there are no response
        // headers to merge from). The OnceLock-backed enforcement
        // applies to script-fetches issued below.
        {
            let policy_set = crate::csp_collector::collect_csp(&[], &dom);
            let enforce_csp = profile.as_ref().map(|p| p.enforce_csp).unwrap_or(true)
                && std::env::var("BROWSER_OXIDE_CSP_BYPASS").is_err();
            if !policy_set.is_empty() {
                if let Ok(origin) = url::Url::parse(url) {
                    crate::js_runtime::extensions::fetch_ext::set_csp_policy(
                        std::sync::Arc::new(policy_set),
                        origin,
                        enforce_csp,
                    );
                } else {
                    crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
                }
            } else {
                // No policy on this page — clear any leftover state from a
                // previous Page in the same process so site A's CSP can't
                // leak into site B in test runners.
                crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
            }
        }

        // Find scripts and stylesheets before handing DOM to runtime
        let scripts = script_runner::find_scripts(&dom);
        let stylesheet_entries = stylesheet_collector::find_stylesheets(&dom);
        let stylesheets = stylesheet_collector::resolve_inline_only(&stylesheet_entries);

        let runtime = BrowserJsRuntime::with_options(
            dom,
            BrowserRuntimeOptions {
                stealth_profile: profile.clone(),
                stylesheets,
                is_secure_context: is_secure_url(url),
                ..Default::default()
            },
        );
        let mut event_loop = BrowserEventLoop::new(runtime);

        // Set location.href (URL-state setup, not a real navigation).
        let url_js = url.replace('\\', "\\\\").replace('\'', "\\'");
        event_loop
            .execute_script(&format!("location.href = '{}';", url_js))
            .ok();
        event_loop.reset_nav_pending();

        // Share the HTTP client with JS fetch()
        let p = profile.unwrap_or_else(crate::stealth::presets::chrome_148_ru);
        let client = crate::net::HttpClient::new(&p)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        crate::js_runtime::extensions::fetch_ext::set_fetch_client(client.clone());

        // Execute scripts in document order
        for (i, script) in scripts.iter().enumerate() {
            if let Some(src) = &script.src {
                if let Some(full_url) = Self::resolve_url(url, src) {
                    // CSP gate — same enforcement point as the parallel
                    // pre-fetch path in `build_page_with_scripts_init_and_storage`.
                    if let Ok(parsed_url) = url::Url::parse(&full_url) {
                        if let Err(violated) = crate::js_runtime::extensions::fetch_ext::check_csp(
                            crate::net::csp::Directive::ScriptSrcElem,
                            &parsed_url,
                            script.nonce.as_deref(),
                            true,
                        ) {
                            eprintln!(
                                "[csp] Refused to load the script '{}' because it violates the following Content Security Policy directive: \"{}\".",
                                full_url, violated
                            );
                            continue;
                        }
                    }
                    match client.get_follow(&full_url, 10).await {
                        Ok(resp) => {
                            let code = resp.text();
                            // document.currentScript parity (see build_page_with_scripts_init_and_storage).
                            let _ = event_loop.execute_script(&format!(
                                "globalThis.__browser_oxide._setCurrentScript(globalThis.__browser_oxide._wrapNode({}))",
                                script.node_id
                            ));
                            if let Err(e) = event_loop.execute_script(&code) {
                                tracing::warn!(script_src = %src, error = %e, "Script error in external script");
                            }
                            let _ = event_loop.execute_script(
                                "globalThis.__browser_oxide._setCurrentScript(null)",
                            );
                        }
                        Err(e) => {
                            tracing::warn!(script_src = %src, error = %e, "Failed to fetch script")
                        }
                    }
                }
            } else if !script.code.is_empty() {
                // document.currentScript parity (see build_page_with_scripts_init_and_storage).
                let _ = event_loop.execute_script(&format!(
                    "globalThis.__browser_oxide._setCurrentScript(globalThis.__browser_oxide._wrapNode({}))",
                    script.node_id
                ));
                if let Err(e) = event_loop.execute_script(&script.code) {
                    tracing::warn!(script_index = i, error = %e, "Script error in inline script");
                }
                let _ =
                    event_loop.execute_script("globalThis.__browser_oxide._setCurrentScript(null)");
            }
        }

        // Set document.readyState = loading
        // Non-enumerable own property so it doesn't leak into
        // Object.keys(window) — defined here so subsequent
        // `globalThis.__browser_oxide.__documentReadyState = ...` assignments preserve
        // enumerable=false (writable=true, descriptor inherited).
        event_loop
            .execute_script("globalThis._browser_oxide.__documentReadyState = 'loading';")
            .ok();

        // Fire DOMContentLoaded and load events — many scripts wait for these
        event_loop
            .execute_script(
                "document.dispatchEvent(new Event('DOMContentLoaded', {bubbles: true}));",
            )
            .ok();

        // After DOMContentLoaded, readyState = interactive
        event_loop
            .execute_script("globalThis._browser_oxide.__documentReadyState = 'interactive';")
            .ok();

        event_loop
            .execute_script("window.dispatchEvent(new Event('load'));")
            .ok();

        // After load, readyState = complete
        event_loop
            .execute_script("globalThis._browser_oxide.__documentReadyState = 'complete';")
            .ok();

        // Run event loop until idle, capped at 8s. Real Chrome treats a page
        // as ready well before all background timers settle — analytics RUM
        // beacons + setInterval polling otherwise prevent "idle" indefinitely.
        // 8s comfortably covers a fast PoW (<1s), a turnstile-style
        // widget (2-4s), and most JS-heavy first-paint flows.
        event_loop.run_until_idle(Duration::from_secs(8)).await?;

        // Process <iframe srcdoc="..."> elements
        // Parse srcdoc HTML and execute scripts within an isolated scope
        let iframes = {
            let dom_ref = event_loop.runtime_mut().inner();
            let state = dom_ref.op_state();
            let state = state.borrow();
            let dom_state = state.borrow::<crate::js_runtime::state::DomState>();
            iframe::find_iframes(&dom_state.dom)
        };
        for iframe_info in &iframes {
            if let Some(srcdoc) = &iframe_info.srcdoc {
                // Execute srcdoc scripts in an isolated function scope
                let node_id = iframe_info.node_id.to_raw();
                let _escaped = srcdoc.replace('\\', "\\\\").replace('`', "\\`");
                let setup_js = format!(
                    r#"(() => {{
                        const _iframeEl = (() => {{
                            const nodeId = {node_id};
                            // Find iframe element and set up its contentDocument
                            const el = document.querySelectorAll('iframe')[0]; // simplified
                            if (el && el.contentWindow) {{
                                el.contentWindow._srcdocLoaded = true;
                            }}
                        }})();
                    }})()"#,
                );
                event_loop.execute_script(&setup_js).ok();
            }
        }

        // Create child Pages for iframes with srcdoc
        let mut children = Vec::new();
        let iframes = {
            let dom_ref = event_loop.runtime_mut().inner();
            let state = dom_ref.op_state();
            let state = state.borrow();
            let dom_state = state.borrow::<crate::js_runtime::state::DomState>();
            iframe::find_iframes(&dom_state.dom)
        };
        for info in &iframes {
            if let Some(srcdoc) = &info.srcdoc {
                match iframe::ChildIframe::from_srcdoc(info.node_id, srcdoc, &p).await {
                    Ok(child) => children.push(child),
                    Err(e) => tracing::warn!(error = %e, "iframe srcdoc error"),
                }
            }
        }

        Ok(Self {
            event_loop,
            url: url.to_string(),
            children,
            solvers: std::sync::Arc::from(Vec::<std::sync::Arc<dyn crate::ChallengeSolver>>::new()),
        })
    }

    /// Get a child iframe by index.
    pub fn child_iframe(&mut self, index: usize) -> Option<&mut iframe::ChildIframe> {
        self.children.get_mut(index)
    }

    /// Get the number of child iframes.
    pub fn child_iframe_count(&self) -> usize {
        self.children.len()
    }

    /// FP-E1: post-JS DOM rescan — materialize **script-injected**
    /// iframes.
    ///
    /// `find_iframes` runs only at *build time* over the parsed DOM
    /// (`build_page_with_scripts_init_and_storage`). When a vendor
    /// challenge script `appendChild`s `<iframe src="https://
    /// geo.captcha-delivery.com/…">` or a
    /// `challenges.…/…` turnstile-style widget *after* build, the
    /// `dom_bootstrap.js` hook only fabricates a synthetic
    /// `contentWindow` — the challenge document is **never fetched or
    /// executed**, which structurally blocks those vendor challenge
    /// iframes and modern managed-challenge widgets. This is currently
    /// the single highest-leverage rendering gap.
    ///
    /// This rescans the *current* (post-JS) DOM and, for every iframe
    /// whose `node_id` is not already materialized in `self.children`,
    /// performs the SAME real cross-origin fetch + child-context
    /// execution the build-time path does (`ChildIframe::from_url`,
    /// CSP-`frame-src`-gated identically to build time). Returns the
    /// number of newly materialized iframes. Idempotent: re-running
    /// only picks up iframes injected since the last call.
    ///
    /// Caller MUST gate this on a challenge-origin flag (it is invoked
    /// only inside the challenge poll) so it never runs for a benign
    /// nav ⇒ zero regression risk, same narrow-gating
    /// discipline as `started_as_dd/cf/seccpt_challenge`.
    pub async fn rematerialize_iframes(
        &mut self,
        base_url: &str,
        client: &crate::net::HttpClient,
        profile: &crate::stealth::StealthProfile,
    ) -> usize {
        // Snapshot the current DOM's iframes (scoped borrow, dropped
        // before any await / before touching self.children).
        let iframes = {
            let dom_ref = self.event_loop.runtime_mut().inner();
            let state = dom_ref.op_state();
            let state = state.borrow();
            let dom_state = state.borrow::<crate::js_runtime::state::DomState>();
            iframe::find_iframes(&dom_state.dom)
        };
        let already: Vec<_> = self.children.iter().map(|c| c.node_id).collect();
        let mut materialized = 0usize;
        for info in &iframes {
            if already.contains(&info.node_id) {
                continue; // already a real child context — not script-new
            }
            if let Some(srcdoc) = &info.srcdoc {
                match iframe::ChildIframe::from_srcdoc(info.node_id, srcdoc, profile).await {
                    Ok(child) => {
                        self.children.push(child);
                        materialized += 1;
                    }
                    Err(e) => tracing::warn!(error = %e, "rematerialize srcdoc error"),
                }
            } else if let Some(src) = &info.src {
                if src.is_empty() || src.starts_with("javascript:") {
                    continue; // blank/JS frames are handled at build time
                }
                if let Some(full_src) = Self::resolve_url(base_url, src) {
                    match iframe::ChildIframe::from_url(
                        info.node_id,
                        &full_src,
                        client,
                        Some(profile),
                    )
                    .await
                    {
                        Ok(child) => {
                            self.children.push(child);
                            materialized += 1;
                        }
                        Err(e) => tracing::warn!(
                            src = %full_src, error = %e,
                            "rematerialize src-iframe error (CSP-blocked or fetch failed)"
                        ),
                    }
                }
            }
        }
        materialized
    }

    /// Evaluate arbitrary JavaScript and return the result as a string.
    pub fn evaluate(&mut self, js: &str) -> Result<String, deno_core::error::AnyError> {
        self.event_loop.execute_script(js)
    }

    /// V8's `used_heap_size` for this page's isolate, in bytes.
    ///
    /// Useful for monitoring a [`crate::pool::PagePool`]: sample after each
    /// navigation and the value should stay flat. A monotonic climb means
    /// something is retaining the previous document — call
    /// [`Page::reset_for_reuse`] between navigations. Call
    /// [`Page::collect_garbage`] first if you want live-heap rather than
    /// including uncollected garbage.
    pub fn v8_heap_used_bytes(&mut self) -> usize {
        self.event_loop.runtime_mut().v8_heap_used_bytes()
    }

    /// Ask V8 for a full garbage collection. Measurement aid only — see
    /// [`Page::v8_heap_used_bytes`]. Never call this on a hot path.
    pub fn collect_garbage(&mut self) {
        self.event_loop.runtime_mut().collect_garbage();
    }

    /// Run scripts and wait for completion.
    pub async fn evaluate_async(
        &mut self,
        js: &str,
        timeout: Duration,
    ) -> Result<IdleReason, deno_core::error::AnyError> {
        self.event_loop.execute_and_run(js, timeout).await
    }

    /// Get the page title (document.title).
    pub fn title(&mut self) -> String {
        self.evaluate("document.title").unwrap_or_default()
    }

    /// Get the full HTML content of the page.
    pub fn content(&mut self) -> String {
        self.evaluate("document.documentElement.outerHTML")
            .unwrap_or_default()
    }

    /// Get text content of the body.
    pub fn text_content(&mut self) -> String {
        self.evaluate("document.body ? document.body.textContent : ''")
            .unwrap_or_default()
    }

    /// Get text content of an element matching a selector.
    pub fn text_of(&mut self, selector: &str) -> Option<String> {
        let sel = selector.replace('\\', "\\\\").replace('"', "\\\"");
        let result = self
            .evaluate(&format!(
                r#"(() => {{ const el = document.querySelector("{}"); return el ? el.textContent : ""; }})()"#,
                sel
            ))
            .ok()?;
        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    /// Check if an element exists.
    pub fn has_element(&mut self, selector: &str) -> bool {
        let sel = selector.replace('\\', "\\\\").replace('"', "\\\"");
        self.evaluate(&format!(r#"document.querySelector("{}") !== null"#, sel))
            .map(|r| r == "true")
            .unwrap_or(false)
    }

    /// Simulate a human-like mouse click on a CSS selector.
    /// Generates a Bezier curve mouse path, dispatches mousemove events along
    /// the path, then mousedown+mouseup+click at the target.
    pub fn human_click(&mut self, selector: &str) -> Result<String, deno_core::error::AnyError> {
        let sel = selector.replace('\\', "\\\\").replace('"', "\\\"");
        self.evaluate(&format!(r#"
            (() => {{
                const el = document.querySelector("{}");
                if (!el) return "element not found";
                const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : {{x:0,y:0,width:100,height:30}};
                const tx = rect.x + rect.width / 2;
                const ty = rect.y + rect.height / 2;
                const path = __browserOxide.humanMousePath(0, 0, tx, ty, 15);
                for (const p of path) {{
                    el.dispatchEvent(new MouseEvent('mousemove', {{clientX: p.x, clientY: p.y, bubbles: true}}));
                }}
                el.dispatchEvent(new MouseEvent('mousedown', {{clientX: tx, clientY: ty, bubbles: true, button: 0}}));
                el.dispatchEvent(new MouseEvent('mouseup', {{clientX: tx, clientY: ty, bubbles: true, button: 0}}));
                el.dispatchEvent(new MouseEvent('click', {{clientX: tx, clientY: ty, bubbles: true, button: 0}}));
                el.click && el.click();
                return "clicked";
            }})()
        "#, sel))
    }

    /// Simulate human-like typing into a CSS selector (input/textarea).
    /// Uses variable inter-key timing based on character pairs.
    pub fn human_type(
        &mut self,
        selector: &str,
        text: &str,
    ) -> Result<String, deno_core::error::AnyError> {
        let sel = selector.replace('\\', "\\\\").replace('"', "\\\"");
        let text_escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
        self.evaluate(&format!(
            r#"
            (() => {{
                const el = document.querySelector("{}");
                if (!el) return "element not found";
                el.focus && el.focus();
                const text = "{}";
                const delays = __browserOxide.humanTypingDelays(text, 65);
                for (let i = 0; i < text.length; i++) {{
                    const ch = text[i];
                    el.dispatchEvent(new KeyboardEvent('keydown', {{key: ch, bubbles: true}}));
                    el.dispatchEvent(new KeyboardEvent('keypress', {{key: ch, bubbles: true}}));
                    if (el.value !== undefined) el.value += ch;
                    el.dispatchEvent(new KeyboardEvent('keyup', {{key: ch, bubbles: true}}));
                    el.dispatchEvent(new Event('input', {{bubbles: true}}));
                }}
                return "typed " + text.length + " chars";
            }})()
        "#,
            sel, text_escaped
        ))
    }

    /// Get the page URL.
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Replace this page's [`crate::ChallengeSolver`] list. Returns the
    /// modified `Self` so it can be used builder-style. Default (set by
    /// `Page::navigate`) is the four built-in vendor solvers; embedders
    /// who want a vanilla engine can call `page.with_solvers(&[])` or
    /// build their own list of trait objects.
    pub fn with_solvers(
        mut self,
        solvers: impl Into<std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]>>,
    ) -> Self {
        self.solvers = solvers.into();
        self
    }

    /// Read-only view of the currently-registered solvers.
    pub fn solvers(&self) -> &[std::sync::Arc<dyn crate::ChallengeSolver>] {
        &self.solvers
    }

    /// Default solver set wired by `Page::navigate`. The open-source
    /// engine ships NO per-vendor solvers — the measured 126-corpus
    /// pass rate comes entirely from the from-scratch TLS + fingerprint
    /// + V8 engine, not from active challenge-solving (verified: empty
    /// vs full solvers both render the same sites). Per-vendor solver
    /// implementations (the sensor-payload flow, PoW, the i.js round-trip,
    /// the challenge orchestrator) are out of scope for this repository
    /// (see `SCOPE.md`); embedders that supply their own register them
    /// via `Page::with_solvers(...)`.
    pub fn default_solvers() -> std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]> {
        std::sync::Arc::from(Vec::<std::sync::Arc<dyn crate::ChallengeSolver>>::new())
    }

    /// Get the event loop (for advanced control).
    pub fn event_loop(&mut self) -> &mut BrowserEventLoop {
        &mut self.event_loop
    }

    /// Create a page with a stealth profile.
    pub async fn with_profile(
        html: &str,
        url: &str,
        profile: crate::stealth::StealthProfile,
    ) -> Result<Self, deno_core::error::AnyError> {
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        Self::build_page_with_scripts_and_init(html, url, &profile, &client, &[]).await
    }

    pub fn consume_and_print_logs(&mut self) {
        let logs = {
            let runtime = self.event_loop.runtime_mut().inner();
            let state = runtime.op_state();
            let mut state = state.borrow_mut();
            let dom_state = state.borrow_mut::<crate::js_runtime::state::DomState>();
            std::mem::take(&mut dom_state.console_output)
        };
        for log in logs {
            let prefix = match log.level {
                crate::js_runtime::state::ConsoleLevel::Log => "[JS LOG]",
                crate::js_runtime::state::ConsoleLevel::Warn => "[JS WARN]",
                crate::js_runtime::state::ConsoleLevel::Error => "[JS ERROR]",
                _ => "[JS INFO]",
            };
            println!("    {} {}", prefix, log.args.join(" "));
        }
    }

    /// Navigate to a URL using an HTTP client (real network request).
    /// Simple single-GET helper used by tests that don't need stealth or
    /// challenge handling. For production flows use [`Page::navigate`].
    pub async fn navigate_simple(
        url: &str,
        client: &crate::net::HttpClient,
        profile: crate::stealth::StealthProfile,
    ) -> Result<Self, deno_core::error::AnyError> {
        let resp = client
            .get(url)
            .await
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        let html = resp.text();
        Self::from_html_with_url(&html, url, Some(profile)).await
    }

    /// Navigate with a stealth profile.
    pub async fn navigate_stealth(
        url: &str,
        profile: crate::stealth::StealthProfile,
    ) -> Result<Self, deno_core::error::AnyError> {
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        let resp = client
            .get_follow(url, 10)
            .await
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        let html = resp.text();
        let _ = std::fs::write("oxide_dump/page_html.html", &html);
        let resp_url = resp.url.clone();
        Self::with_profile(&html, &resp_url, profile).await
    }

    /// Generic navigation entry point.
    ///
    /// Loops by re-fetching whenever a script sets
    /// `globalThis.__pendingNavigation` (via `location.reload`,
    /// `location.href = ...`, `location.assign/replace`, or a
    /// `<meta http-equiv="refresh">` tag). Each iteration drops the
    /// previous V8 isolate and builds a fresh one — identical to how a
    /// real browser does a top-level navigation. Zero per-engine logic.
    ///
    /// `max_iterations` caps the loop to prevent infinite reload cycles.
    /// `5` is a reasonable default for challenge flows (interstitial →
    /// solver → real page is the common case, so even 3 is enough).
    pub async fn navigate(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
    ) -> Result<Self, deno_core::error::AnyError> {
        // Phase F — humanization is default-on. Sensor-based detectors
        // score "zero user input in
        // first 2 s" as a strong bot signal. Real Chrome sessions
        // accumulate dozens of mousemove/scroll/click events before any
        // sensor VM posts; headless runs see none unless we synthesize
        // them. The cost is ~30 setTimeout dispatches over ~2 s of page
        // life — negligible compared to the navigation budget — and the
        // benefit is a measurable PASS bump on behaviorally-fingerprinted
        // sites.
        //
        // Opt-out via `navigate_pure(url, profile, max_iter)` for
        // deterministic snapshot tests where synthetic input would skew
        // results.
        let humanize = include_str!("js/humanize.js").to_string();
        Self::navigate_with_init(url, profile, max_iterations, vec![humanize]).await
    }

    /// Like [`Page::navigate`] but with a caller-supplied
    /// [`crate::ChallengeSolver`] list. This engine ships no solvers
    /// (`default_solvers()` is empty); embedders register their own
    /// `ChallengeSolver` implementations here:
    /// `Page::navigate_with_solvers(url, profile, n, my_solvers)`.
    pub async fn navigate_with_solvers(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
        solvers: std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]>,
    ) -> Result<Self, deno_core::error::AnyError> {
        let humanize = include_str!("js/humanize.js").to_string();
        Self::navigate_with_init_solvers(url, profile, max_iterations, vec![humanize], solvers)
            .await
    }

    /// Pure navigation — no humanization, no synthetic events. Use for
    /// deterministic snapshot tests, layout dump captures, or any
    /// scenario where the test wants to assert about the page's *own*
    /// behavior without injected mousemove/click activity.
    pub async fn navigate_pure(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::navigate_with_init(url, profile, max_iterations, Vec::new()).await
    }

    /// Alias of [`Page::navigate`] preserved for backward compatibility.
    /// `Page::navigate` is already humanized as of Phase F.
    pub async fn navigate_humanized(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::navigate(url, profile, max_iterations).await
    }

    /// Like [`Page::navigate`], but installs caller-supplied init scripts on
    /// every iteration's fresh runtime. Used by [`Page::navigate_humanized`]
    /// and any future feature that wants to carry JS across navigations
    /// within a single frame (equivalent to Chromium's
    /// `Page.addScriptToEvaluateOnNewDocument`).
    /// Like [`Page::navigate`], but installs caller-supplied init scripts on
    /// every iteration's fresh runtime. Used by [`Page::navigate_humanized`]
    /// and any future feature that wants to carry JS across navigations
    /// within a single frame (equivalent to Chromium's
    /// `Page.addScriptToEvaluateOnNewDocument`).
    pub async fn navigate_with_init(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
        init_scripts: Vec<String>,
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::navigate_with_init_solvers(
            url,
            profile,
            max_iterations,
            init_scripts,
            Self::default_solvers(),
        )
        .await
    }

    /// [`Self::navigate_with_init`] + an explicit solver list. The
    /// 4-arg `navigate_with_init` forwards here with `default_solvers()`.
    pub async fn navigate_with_init_solvers(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
        init_scripts: Vec<String>,
        solvers: std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]>,
    ) -> Result<Self, deno_core::error::AnyError> {
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;

        // Shared cold+warm cross-domain cookie-collision scrub (opt-in via
        // BROWSER_OXIDE_COOKIE_COLLISION_PAIRS). See `scrub_cookie_collision`.
        // Previously an inline block here only — the warm/PagePool path lacked it.
        scrub_cookie_collision(url, &client).await;

        // Share the HTTP client with JS fetch() so scripts running inside
        // the V8 isolate hit the same cookie jar as the Rust driver.
        crate::js_runtime::extensions::fetch_ext::set_fetch_client(client.clone());

        let iterations = max_iterations.max(1);
        let debug_nav = std::env::var("BROWSER_OXIDE_DEBUG_NAV").is_ok();

        tracing::debug!(url = %url, "navigate initial fetch");
        let resp = client
            .get_follow(url, 10)
            .await
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;

        if resp.status == 498 || resp.status == 403 || resp.status == 429 {
            eprintln!(
                "[navigate] Initial challenge response headers ({}):",
                resp.status
            );
            for (k, v) in &resp.headers {
                eprintln!("  {}: {}", k, v);
            }
        }
        // Log known anti-bot vendor response markers so post-run
        // analysis can split CHL outcomes by protocol. Each marker also
        // hints whether the site needs a vendor-specific solver. No
        // flow change yet —
        // the adaptive budget already short-circuits when
        // the body is small + readyState complete, so we don't burn the
        // full 75 s on a 2 KB challenge stub.
        if let Some(waf) = resp.headers.get("x-amzn-waf-action") {
            eprintln!("[challenge-detect] aws-waf {} on {}", waf, resp.url);
        }
        if resp.headers.contains_key("x-datadome") {
            eprintln!("[challenge-detect] interstitial-vendor on {}", resp.url);
        }
        if resp.headers.contains_key("x-wbaas-token") {
            eprintln!("[challenge-detect] token-vendor on {}", resp.url);
        }
        // Extended challenge-detect markers. Pure observability —
        // post-run analysis splits CHL outcomes by protocol.
        if let Some(v) = resp.headers.get("cf-mitigated") {
            eprintln!("[challenge-detect] managed-mitigated {} on {}", v, resp.url);
        }
        if let Some(v) = resp.headers.get("cf-ray") {
            if matches!(resp.status, 403 | 429 | 498 | 503) {
                eprintln!(
                    "[challenge-detect] managed cf-ray={} status={} on {}",
                    v, resp.status, resp.url
                );
            }
        }
        if let Some(v) = resp.headers.get("x-iinfo") {
            eprintln!("[challenge-detect] edge-vendor-a {} on {}", v, resp.url);
        }
        if resp
            .headers
            .get("x-cdn")
            .map(|v| v.to_ascii_lowercase().contains("imperva"))
            .unwrap_or(false)
        {
            eprintln!("[challenge-detect] edge-vendor-a-cdn on {}", resp.url);
        }
        if let Some(v) = resp.headers.get("x-perimeterx-id") {
            eprintln!("[challenge-detect] behavior-vendor {} on {}", v, resp.url);
        }
        if let Some(v) = resp.headers.get("x-sucuri-id") {
            eprintln!("[challenge-detect] edge-vendor-b {} on {}", v, resp.url);
        }
        if let Some(v) = resp.headers.get("x-akamai-transformed") {
            eprintln!("[challenge-detect] sensor-edge {} on {}", v, resp.url);
        }
        if resp
            .headers
            .iter()
            .any(|(k, _)| k.to_ascii_lowercase().starts_with("x-kpsdk"))
        {
            eprintln!(
                "[challenge-detect] script-vendor (x-kpsdk-*) on {}",
                resp.url
            );
        }
        if let Some(v) = resp.headers.get("x-armor-shield-zone") {
            eprintln!("[challenge-detect] edge-vendor-c {} on {}", v, resp.url);
        }
        if resp
            .headers
            .get("server")
            .map(|v| v.to_ascii_lowercase().contains("cloudflare"))
            .unwrap_or(false)
            && !resp.headers.contains_key("cf-mitigated")
            && !resp.headers.contains_key("cf-ray")
        {
            // Server: cloudflare with no cf-mitigated/ray = passive
            // CDN edge, not active bot management. Logged only when
            // we don't already have a more specific signal.
            eprintln!("[challenge-detect] managed-edge on {}", resp.url);
        }
        if resp
            .headers
            .get("via")
            .map(|v| v.to_ascii_lowercase().contains("varnish"))
            .unwrap_or(false)
        {
            eprintln!("[challenge-detect] cdn-edge (via: varnish) on {}", resp.url);
        }
        // Collect response-header CSP value(s) before consuming `resp`.
        // CSP3 §3.2 allows the header to repeat (multiple Policy values
        // applied conjunctively); we keep each instance separate so the
        // "all must allow" matcher semantic stays correct.
        let csp_headers: Vec<String> = resp
            .headers
            .iter()
            .filter(|(k, _)| k.eq_ignore_ascii_case("content-security-policy"))
            .map(|(_, v)| v.clone())
            .collect();
        let csp_headers_ro: Vec<String> = resp
            .headers
            .iter()
            .filter(|(k, _)| k.eq_ignore_ascii_case("content-security-policy-report-only"))
            .map(|(_, v)| v.clone())
            .collect();
        let html = resp.text();
        let resp_url = resp.url.clone();
        let timings = resp.timings.clone();
        let mut page = Self::navigate_loop_internal(
            html,
            resp_url,
            profile,
            client,
            iterations,
            0,
            init_scripts,
            debug_nav,
            csp_headers,
            csp_headers_ro,
            resp.accept_ch_upgrade,
            solvers,
        )
        .await?;

        page.event_loop()
            .runtime_mut()
            .record_resource_timing(timings);
        Ok(page)
    }

    /// For tests: start a navigation loop with a provided HTML instead of
    /// fetching from URL. Subsequent iterations (if any) will fetch from the URL.
    pub async fn navigate_with_html(
        html: &str,
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_iterations: u8,
    ) -> Result<Self, deno_core::error::AnyError> {
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        crate::js_runtime::extensions::fetch_ext::set_fetch_client(client.clone());

        let iterations = max_iterations.max(1);
        let debug_nav = std::env::var("BROWSER_OXIDE_DEBUG_NAV").is_ok();

        // Iteration 0 uses provided HTML — no headers means no CSP
        // (this entry point is for tests that hand us synthetic HTML).
        Self::navigate_loop_internal(
            html.to_string(),
            url.to_string(),
            profile,
            client,
            iterations,
            0,
            vec![],
            debug_nav,
            Vec::new(),
            Vec::new(),
            false,
            Self::default_solvers(),
        )
        .await
    }

    /// Reset all cross-navigation JS state on this Page so its V8 isolate
    /// can be safely reused for a different URL.
    ///
    /// Call this before pointing a warm `Page` at new content.
    /// [`Page::navigate_warm`] and [`crate::pool::PagePool`] already do;
    /// any consumer that hand-rolls page reuse (e.g. calling
    /// [`Page::reload_html`] on a `Page` it keeps alive) must call it
    /// itself, otherwise the reapers below never run — every one of them
    /// used to be wired only to `Page::drop`, so a pooling consumer
    /// silently lost all of them.
    ///
    /// What gets reaped:
    /// - In-flight `setTimeout` / `setInterval` callbacks (via
    ///   `__cancelAllTimers()` generation bump in `timer_bootstrap.js`).
    ///   Without this, the previous page's `humanize.js` 30 pending
    ///   timers + recurring 4 s setInterval would fire on the new DOM
    ///   and dispatch synthetic mouse events into the wrong document.
    /// - Every registered event listener (`__cancelAllListeners()` in
    ///   `event_bootstrap.js`). Listeners bound to `window` are keyed
    ///   against the one object that is never collected for the life of
    ///   the isolate, so their closures pinned the previous page's whole
    ///   object graph; node-keyed listeners additionally misfired on the
    ///   next document, because node IDs restart at zero.
    /// - DOM-side registries (`__resetDomRegistries()` in
    ///   `dom_bootstrap.js`): node-wrapper cache, scroll state,
    ///   MutationObservers, iframe/frame registries.
    /// - Custom-element definitions (`__resetCustomElements()` in
    ///   `window_bootstrap.js`).
    /// - Globals the previous page's scripts hung off `window`
    ///   (`__resetPageGlobals()` in `cleanup_bootstrap.js`) — everything
    ///   added since the engine marked its baseline.
    /// - Workers the page spawned but never `terminate()`d
    ///   (`drain_owned_workers`), which `Page::drop` also does.
    /// - `_browser_oxide.__pendingNavigation` — spurious value left by the
    ///   `location.href = …` setter inside the previous build.
    /// - `_browser_oxide.__fetchLog` — DevTools-style network log; must
    ///   reset so the new page's fetches aren't mixed with the old's.
    /// - `window.__cookieWrites`, `window.__scriptErrors` —
    ///   instrumentation buffers re-initialised per page.
    /// - `globalThis.__bo_input_events` (mouse / key / touch / scroll
    ///   buffers + counters) — humanize.js re-installs into these and
    ///   sensors read them on POST, so stale values would skew detection.
    /// - `globalThis.__jsCookies` — cookie cache snapshot (the real
    ///   source of truth is the HTTP client's jar, re-synced below).
    /// - `globalThis.__keepLongTimersRefed` — per-navigation challenge
    ///   flag; left set, it would pin long timers on every later page.
    ///
    /// What stays:
    /// - V8 isolate, bootstrap scripts (`window_bootstrap.js`,
    ///   `dom_bootstrap.js`, …), and the page-instrumentation wrappers
    ///   on `globalThis.fetch` / `document.cookie` / `XMLHttpRequest`.
    ///   These are the expensive bits we're reusing.
    pub fn reset_for_reuse(&mut self) {
        let _ = self.event_loop.execute_script(
            r#"(function() {
                const g = globalThis;
                try { g.__cancelAllTimers && g.__cancelAllTimers(); } catch (_) {}
                try { g.__cancelAllListeners && g.__cancelAllListeners(); } catch (_) {}
                try { g.__resetDomRegistries && g.__resetDomRegistries(); } catch (_) {}
                try { g.__resetCustomElements && g.__resetCustomElements(); } catch (_) {}
                try { delete g.__keepLongTimersRefed; } catch (_) {}
                if (g._browser_oxide) {
                    g._browser_oxide.__pendingNavigation = null;
                    if (Array.isArray(g._browser_oxide.__fetchLog)) {
                        g._browser_oxide.__fetchLog.length = 0;
                    }
                }
                const w = (g.window && g.window !== g) ? g.window : g;
                try { if (Array.isArray(w.__cookieWrites)) w.__cookieWrites.length = 0; } catch (_) {}
                try { if (Array.isArray(w.__scriptErrors)) w.__scriptErrors.length = 0; } catch (_) {}
                if (g.__bo_input_events) {
                    g.__bo_input_events.mouse.length = 0;
                    g.__bo_input_events.key.length = 0;
                    g.__bo_input_events.touch.length = 0;
                    g.__bo_input_events.scroll.length = 0;
                    if (g.__bo_input_events.counters) {
                        g.__bo_input_events.counters.key = 0;
                        g.__bo_input_events.counters.mouse = 0;
                        g.__bo_input_events.counters.touch = 0;
                        g.__bo_input_events.counters.scroll = 0;
                        g.__bo_input_events.counters.accel = 0;
                    }
                }
                if (g.__jsCookies) g.__jsCookies = {};
                // Last: drop everything the previous page's scripts hung
                // off `window`. Runs after the buffer resets above so those
                // engine-owned names are already back to a clean value (they
                // are baseline-allowlisted, so this does not remove them).
                try { g.__resetPageGlobals && g.__resetPageGlobals(); } catch (_) {}
            })();"#,
        );
        // Reap Workers the OUTGOING page spawned but never terminated. The
        // warm path reuses this isolate across navs, so — unlike the cold
        // `Page::drop` path, which already calls this — orphan Workers would
        // otherwise accumulate (64 MB stack + child JsRuntime EACH), driving
        // the single-process pool runaway (GATE_PERFORMANCE §5: 1.7 GB RSS,
        // stuck ~site 104). Mirrors the Drop reaper so warm reuse holds steady
        // RSS across hundreds of navigations. Timers (`__cancelAllTimers` +
        // `replace_dom` TimerState reset) and child isolates (`children.clear`)
        // are already handled on the warm path; Workers were the gap.
        {
            let op_state = self.event_loop.runtime_mut().op_state();
            let mut state = op_state.borrow_mut();
            crate::js_runtime::extensions::worker_ext::drain_owned_workers(&mut state);
        }
        // Drop the previous document's iframe isolates. Children are newer
        // isolates than this Page's, so clearing here keeps V8's
        // reverse-creation-order drop requirement satisfied.
        self.children.clear();
    }

    /// Navigate this *warm* Page to a new URL by reusing its V8 isolate
    /// and bootstrap. Saves ~150 ms vs the cold [`Page::navigate`] path
    /// by skipping isolate creation, bootstrap-script execution, and
    /// the page-instrumentation install (cookie-write / fetch wrapper /
    /// error-tracking wrappers stay across navigations).
    ///
    /// Use via [`crate::pool::PagePool::navigate`] for the canonical
    /// "scrape many URLs with one warm engine" pattern. The Page's
    /// existing stealth profile is reused — call sites that need a
    /// different profile should `pool.release` this Page and acquire a
    /// fresh one.
    ///
    /// **Scope**: warm reuse handles the benign content-extraction case.
    /// It does NOT run the cookie-diff / pending-nav iteration loop that
    /// [`Page::navigate`] does for anti-bot pages — challenge scripts
    /// keep V8 busy on their own so the savings from a warm isolate are
    /// negligible there anyway, and reproducing the iteration loop on
    /// the warm path is a known follow-up (see the comment above
    /// `Self::navigate_loop_internal`).
    pub async fn navigate_warm(&mut self, url: &str) -> Result<(), deno_core::error::AnyError> {
        let warm_trace = std::env::var("BROWSER_OXIDE_WARM_PROFILE").is_ok();
        let warm_t0 = std::time::Instant::now();
        macro_rules! wmark {
            ($label:expr) => {
                if warm_trace {
                    eprintln!("[warm] {:>5}ms {}", warm_t0.elapsed().as_millis(), $label);
                }
            };
        }

        // Pull the stealth profile out of the runtime's `StealthState`.
        // The pool stores Pages by profile; this guards against silent
        // misuse where a caller hand-builds a Page without a profile and
        // tries to warm-navigate it.
        let profile: crate::stealth::StealthProfile = {
            let op_state = self.event_loop.runtime_mut().op_state();
            let state = op_state.borrow();
            state
                .try_borrow::<crate::js_runtime::extensions::stealth_ext::StealthState>()
                .and_then(|s| s.profile.clone())
                .ok_or_else(|| {
                    deno_core::error::AnyError::msg(
                        "navigate_warm requires a Page built with a stealth profile",
                    )
                })?
        };
        let client = crate::net::HttpClient::shared(&profile)
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        crate::js_runtime::extensions::fetch_ext::set_fetch_client(client.clone());
        // The warm/PagePool reuse path previously skipped the cross-domain
        // cookie-collision scrub the cold path runs, so a pooled Page could
        // silently serve a stale stub.
        scrub_cookie_collision(url, &client).await;
        wmark!("profile + shared client");

        // Initial fetch (redirect-follow, same as cold path).
        let resp = client
            .get_follow(url, 10)
            .await
            .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
        let csp_headers: Vec<String> = resp
            .headers
            .iter()
            .filter(|(k, _)| k.eq_ignore_ascii_case("content-security-policy"))
            .map(|(_, v)| v.clone())
            .collect();
        let csp_headers_ro: Vec<String> = resp
            .headers
            .iter()
            .filter(|(k, _)| k.eq_ignore_ascii_case("content-security-policy-report-only"))
            .map(|(_, v)| v.clone())
            .collect();
        let html = resp.text();
        let resp_url = resp.url.clone();
        let timings = resp.timings.clone();
        drop(resp);
        wmark!("fetch done");

        // Install CSP for this navigation (same logic as the cold build).
        {
            let csp_dom = crate::html_parser::parse_html(&html);
            let header_refs: Vec<&str> = csp_headers.iter().map(|s| s.as_str()).collect();
            let report_refs: Vec<&str> = csp_headers_ro.iter().map(|s| s.as_str()).collect();
            let policy_set = crate::csp_collector::collect_csp_with_report_only(
                &header_refs,
                &report_refs,
                &csp_dom,
            );
            let env_bypass = std::env::var("BROWSER_OXIDE_CSP_BYPASS").is_ok();
            let enforce = profile.enforce_csp && !env_bypass;
            if let Ok(origin) = url::Url::parse(&resp_url) {
                if !policy_set.is_empty() {
                    crate::js_runtime::extensions::fetch_ext::set_csp_policy(
                        std::sync::Arc::new(policy_set),
                        origin,
                        enforce,
                    );
                } else {
                    crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
                }
            } else {
                crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
            }
        }
        wmark!("CSP set");

        // Parse + find subresources. Parsing the same DOM twice (once
        // for CSP, once here) is cheap (~µs for typical pages) and keeps
        // the CSP block lifted from the cold path without a refactor.
        let dom = crate::html_parser::parse_html(&html);
        let scripts_meta = script_runner::find_scripts(&dom);
        let stylesheet_entries = stylesheet_collector::find_stylesheets(&dom);

        // Parallel fetch external CSS + external scripts. Mirrors the
        // cold build path; we only inline the bits we actually need
        // here so this method stays self-contained.
        let mut inline_css: Vec<String> = Vec::new();
        let css_futures: Vec<_> = stylesheet_entries
            .iter()
            .filter_map(|entry| match entry {
                stylesheet_collector::StylesheetEntry::Inline(css) => {
                    inline_css.push(css.clone());
                    None
                }
                stylesheet_collector::StylesheetEntry::External(href) => {
                    let full_url = Self::resolve_url(&resp_url, href)?;
                    let client = client.clone();
                    Some(async move {
                        match client.get(&full_url).await {
                            Ok(r) if r.ok() => {
                                let text = r.text();
                                if !text.trim_start().starts_with("<!") {
                                    Some((text, r.timings.clone()))
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        }
                    })
                }
            })
            .collect();
        let script_futures: Vec<_> = scripts_meta
            .iter()
            .enumerate()
            .filter_map(|(i, script)| {
                let src = script.src.as_ref()?;
                let full_url = Self::resolve_url(&resp_url, src)?;
                let dbg = std::env::var("BROWSER_OXIDE_DEBUG_NAV").is_ok();
                if let Ok(parsed_url) = url::Url::parse(&full_url) {
                    if crate::js_runtime::extensions::fetch_ext::check_csp(
                        crate::net::csp::Directive::ScriptSrcElem,
                        &parsed_url,
                        script.nonce.as_deref(),
                        true,
                    )
                    .is_err()
                    {
                        if dbg {
                            eprintln!("[navigate] script[{i}] CSP-SKIP {full_url}");
                        }
                        return None;
                    }
                }
                if dbg {
                    eprintln!("[navigate] script[{i}] PREFETCH {full_url}");
                }
                let client = client.clone();
                let profile = profile.clone();
                let referer = resp_url.clone();
                Some(async move {
                    // Script fetches inherit the parent doc's
                    // regional accept-language (real Chrome sends one
                    // accept-language per session, not per-URL — keyed off
                    // the doc URL keeps sub-resource requests consistent).
                    let mut hdrs = crate::net::headers::nav_headers_for_url(&profile, &referer, false);
                    hdrs.push(("referer".to_string(), referer));
                    hdrs.push(("accept".to_string(), "*/*".to_string()));
                    hdrs.push(("sec-fetch-dest".to_string(), "script".to_string()));
                    hdrs.push(("sec-fetch-mode".to_string(), "no-cors".to_string()));
                    hdrs.push(("sec-fetch-site".to_string(), "cross-site".to_string()));
                    let dbg = std::env::var("BROWSER_OXIDE_DEBUG_NAV").is_ok();
                    match client.get_follow_with_headers(&full_url, &hdrs, 5).await {
                        Ok(r) if r.ok() => {
                            let text = r.text();
                            if text.trim_start().starts_with("<!")
                                || text.trim_start().starts_with("<html")
                            {
                                if dbg {
                                    eprintln!("[navigate] script[{i}] FETCHED-BUT-HTML-FILTERED {} ({} bytes)", full_url, text.len());
                                }
                                None
                            } else {
                                if dbg {
                                    eprintln!("[navigate] script[{i}] FETCHED-OK {} ({} bytes)", full_url, text.len());
                                }
                                Some((i, text, r.timings.clone()))
                            }
                        }
                        Ok(r) => {
                            if dbg {
                                eprintln!("[navigate] script[{i}] FETCH-NOT-OK status={} {}", r.status, full_url);
                            }
                            None
                        }
                        Err(e) => {
                            if dbg {
                                eprintln!("[navigate] script[{i}] FETCH-ERR {e} {full_url}");
                            }
                            None
                        }
                    }
                })
            })
            .collect();
        let (fetched_css, fetched_scripts) = futures_util::future::join(
            futures_util::future::join_all(css_futures),
            futures_util::future::join_all(script_futures),
        )
        .await;
        wmark!("subresources fetched");

        let mut all_timings = vec![timings];
        let mut stylesheets = inline_css;
        for r in fetched_css.into_iter().flatten() {
            stylesheets.push(r.0);
            all_timings.push(r.1);
        }
        let mut prefetched: std::collections::HashMap<usize, String> =
            std::collections::HashMap::new();
        for r in fetched_scripts.into_iter().flatten() {
            prefetched.insert(r.0, r.1);
            all_timings.push(r.2);
        }

        // Cancel all in-flight timers from the previous page and clear
        // cross-nav JS buffers BEFORE swapping the DOM, so any straggler
        // callbacks that try to fire don't see a half-installed state.
        self.reset_for_reuse();
        wmark!("reset_for_reuse");

        // Swap DOM (also resets `TimerState` Rust-side).
        self.event_loop.runtime_mut().replace_dom(dom, stylesheets);
        self.children.clear();
        self.url = resp_url.clone();
        for t in all_timings {
            self.event_loop.runtime_mut().record_resource_timing(t);
        }
        wmark!("replace_dom");

        // Build-phase deadline watcher — preempts CPU-bound inline-script
        // spins on the warm isolate the same way the cold build does.
        let build_budget_ms: u64 = std::env::var("BROWSER_OXIDE_BUILD_BUDGET_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(25_000);
        let _build_watcher = V8DeadlineWatcher::new(
            self.event_loop.runtime_mut().isolate_handle(),
            Duration::from_millis(build_budget_ms),
        );

        // Seed `location` for this navigation. The `reset_nav_pending` now
        // scrubs the spurious `__pendingNavigation` the setter writes, so
        // downstream `PENDING_NAV_JS` reads see a clean empty value.
        let url_js = resp_url.replace('\\', "\\\\").replace('\'', "\\'");
        let _ = self
            .event_loop
            .execute_script(&format!("location.href = '{}';", url_js));
        self.event_loop.reset_nav_pending();

        // Refresh `document.cookie` for the new origin. Fast op call,
        // 50 ms cap is plenty (same as the cold path).
        let _ = self
            .event_loop
            .execute_and_run(
                "globalThis.__syncCookiesFromNet && globalThis.__syncCookiesFromNet();",
                Duration::from_millis(50),
            )
            .await;

        // Run inline + external scripts in document order, draining
        // between each so microtasks land before the next script reads
        // them. Mirrors the cold path's script loop.
        for (i, script) in scripts_meta.iter().enumerate() {
            let code = if script.src.is_some() {
                match prefetched.get(&i) {
                    Some(c) => c.clone(),
                    None => continue,
                }
            } else {
                script.code.clone()
            };
            if code.trim().is_empty() {
                continue;
            }
            let name = script.src.clone().unwrap_or_else(|| resp_url.clone());
            if script.is_module {
                // Mirror the cold path (navigate_loop_internal): route
                // `<script type="module">` through the ES-module loader instead
                // of classic `execute_script`, which throws `SyntaxError: Cannot
                // use import statement outside a module` and drops the whole
                // bundle. Without this the warm/PagePool path serves only the
                // server shell for every modern Vite/React/Vue SPA — reddit's
                // 16 module scripts rendered 8 KB warm vs 676 KB cold (the
                // dominant warm-pool thin-render artifact; the gate runs pooled).
                // Bounded at 10s/module so a stalled import graph can't hang the
                // nav; on timeout we log and continue with what rendered.
                let eval_fut = async {
                    if let Some(src) = &script.src {
                        let module_url = url::Url::parse(&resp_url)
                            .ok()
                            .and_then(|base| base.join(src).ok())
                            .map(|u| u.to_string())
                            .unwrap_or_else(|| src.clone());
                        self.event_loop
                            .eval_module_code(&module_url, code.clone())
                            .await
                    } else {
                        let spec = format!("{resp_url}#oxide-mod-{i}");
                        self.event_loop.eval_module_code(&spec, code.clone()).await
                    }
                };
                match tokio::time::timeout(Duration::from_secs(10), eval_fut).await {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => {
                        tracing::warn!(script = %name, error = %e, "warm ES module eval error")
                    }
                    Err(_) => {
                        tracing::warn!(script = %name, "warm ES module eval timed out (10s) — continuing")
                    }
                }
            } else if let Err(e) = self.event_loop.execute_script_with_name(&code, &name) {
                tracing::warn!(script = %name, error = %e, "warm script error");
            }
            let _ = self
                .event_loop
                .run_until_idle(Duration::from_millis(50))
                .await;
        }
        wmark!("scripts executed");

        // Re-install `humanize.js` on the fresh DOM. The previous page's
        // humanize closure captured the old `document.body`; its setInterval
        // has been cancelled by the generation bump, so we install fresh.
        let _ = self
            .event_loop
            .execute_script(include_str!("js/humanize.js"));

        // DOMContentLoaded + load events — same setTimeout(0) trick the
        // cold build uses so dispatched handlers run inside the event
        // loop (not synchronously during setup).
        let _ = self.event_loop.execute_script(
            r#"setTimeout(() => {
                document.dispatchEvent(new Event('DOMContentLoaded', {bubbles: true}));
                window.dispatchEvent(new Event('DOMContentLoaded', {bubbles: true}));
                window.dispatchEvent(new Event('load'));
            }, 0);"#,
        );

        // Meta-refresh scanner — sets `__pendingNavigation` if the page
        // has one. The caller doesn't loop on it (warm path skips the
        // iter retry loop) but downstream `Page::content()` / classifier
        // calls won't see a half-applied refresh either way.
        let _ = self.event_loop.execute_script(
            r#"(function() {
                const metas = document.getElementsByTagName('meta');
                for (let i = 0; i < metas.length; i++) {
                    const m = metas[i];
                    const equiv = String(m.getAttribute('http-equiv') || '').toLowerCase();
                    if (equiv !== 'refresh') continue;
                    const content = String(m.getAttribute('content') || '');
                    const match = content.match(/^\s*(\d+)(?:\s*[;,]\s*url\s*=\s*(.+))?$/i);
                    if (!match) continue;
                    const delay = parseInt(match[1], 10) || 0;
                    const target = ((match[2] || '').trim()).replace(/^['"]|['"]$/g, '') || location.href;
                    setTimeout(() => {
                        globalThis.__pendingNavigation = { url: target, kind: 'assign' };
                        try { Deno.core.ops.op_set_pending_nav(); } catch (_) {}
                    }, delay * 1000);
                    break;
                }
            })();"#,
        );

        // Final drain to let async work settle. Same cap as the cold
        // build phase — humanize timers are unref'd so they don't pin.
        let _ = self
            .event_loop
            .run_until_idle(Duration::from_millis(500))
            .await;
        self.event_loop.runtime_mut().cancel_terminate_execution();
        drop(_build_watcher);
        wmark!("drain done [READY]");

        Ok(())
    }

    async fn navigate_loop_internal(
        html: String,
        resp_url: String,
        profile: crate::stealth::StealthProfile,
        client: crate::net::HttpClient,
        iterations: u8,
        start_iter: u8,
        init_scripts: Vec<String>,
        debug_nav: bool,
        csp_headers: Vec<String>,
        csp_headers_ro: Vec<String>,
        accept_ch_upgrade: bool,
        solvers: std::sync::Arc<[std::sync::Arc<dyn crate::ChallengeSolver>]>,
    ) -> Result<Self, deno_core::error::AnyError> {
        // The challenge-solver dispatch below iterates over `solvers`.
        // This engine passes an empty list (per-vendor solver
        // implementations are out of scope — see `SCOPE.md`); embedders
        // register their own via `Page::navigate_with_solvers`. An empty
        // list makes the dispatch a clean no-op.
        // Install CSP for this navigation. Headers + meta-tag sources
        // both contribute. The fetch_ext layer reads from a per-process
        // RwLock so async ops can enforce without borrowing OpState.
        // `enforce_csp` controls whether matches actually block; off
        // means CSP is parsed and reported but doesn't gate fetches —
        // useful for A/B comparison on the holistic sweep.
        {
            let csp_dom = crate::html_parser::parse_html(&html);
            let header_refs: Vec<&str> = csp_headers.iter().map(|s| s.as_str()).collect();
            let report_refs: Vec<&str> = csp_headers_ro.iter().map(|s| s.as_str()).collect();
            let policy_set = crate::csp_collector::collect_csp_with_report_only(
                &header_refs,
                &report_refs,
                &csp_dom,
            );
            // Bypass switch — useful to compare engine behaviour with
            // and without enforcement on the same site without rebuild.
            let env_bypass = std::env::var("BROWSER_OXIDE_CSP_BYPASS").is_ok();
            // A `rt:'i'` interstitial is a vendor-served
            // challenge document, NOT the origin's page — enforcing the
            // origin's restrictive 403-response CSP on it refuses
            // geo.captcha-delivery.com and kills the i.js self-solve
            // round-trip. Narrowly gated to the <4 KB interstitial shape
            // (detect_datadome_interstitial), so it cannot affect normal
            // pages (their bodies don't match). The cookie-diff retry then
            // re-issues the original URL once i.js lands `datadome=`.
            // A registered solver may request the origin CSP be
            // suspended for this nav (e.g. for `rt:'i'` interstitials so
            // i.js can reach captcha-delivery.com). Empty solver list ⇒
            // never relaxed.
            // Relax CSP on any such interstitial,
            // not just when a registered solver claims it. The interstitial
            // loads `captcha-delivery.com` scripts that the origin's own
            // CSP refuses; without relaxation the bundle never runs and
            // the daily-key WASM never gets a chance to land `datadome=`.
            let relax_csp = solvers.iter().any(|s| s.relax_response_csp(&html))
                || is_interstitial_challenge(&html);
            let enforce = profile.enforce_csp && !env_bypass && !relax_csp;
            if relax_csp && debug_nav {
                eprintln!("[solver] origin CSP not enforced for this challenge document");
            }
            if let Ok(origin) = url::Url::parse(&resp_url) {
                if !policy_set.is_empty() {
                    if debug_nav {
                        eprintln!(
                            "[csp] installed {} policies from headers={} meta={} enforce={}",
                            policy_set.policies.len(),
                            csp_headers.len(),
                            policy_set.policies.len() - csp_headers.len(),
                            enforce
                        );
                    }
                    crate::js_runtime::extensions::fetch_ext::set_csp_policy(
                        std::sync::Arc::new(policy_set),
                        origin,
                        enforce,
                    );
                } else {
                    crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
                }
            } else {
                crate::js_runtime::extensions::fetch_ext::clear_csp_policy();
            }
        }

        const PENDING_NAV_JS: &str = "(function(){\
                const browser_oxide = globalThis._browser_oxide;\
                const p = browser_oxide && browser_oxide.__pendingNavigation;\
                if (p) browser_oxide.__pendingNavigation = null;\
                return p ? JSON.stringify({url: p.url, method: p.method || 'GET', body: p.body, kind: p.kind}) : '';\
            })()";

        // Did this nav start as a challenge document that a registered
        // solver wants to keep the resolution path active for? (The
        // `rt:'i'` interstitials mutate the DOM via i.js, dropping the
        // body marker; without this pre-mutation flag the engine would
        // skip the pending-nav poll + cookie-diff retry before i.js
        // lands `datadome=`.) Reuses `relax_response_csp` as the
        // "is this my challenge doc" signal. Empty solver list ⇒ false.
        //
        // Public-engine primitive: also fire on a
        // raw interstitial shape (i.e. a small body that loads
        // a `captcha-delivery.com` script) so the iframe-materialization
        // poll runs even without a registered solver. The bundle
        // is the actor; the engine just needs to NOT interfere and to
        // re-fetch the original URL once `datadome=` is in the jar.
        let started_as_interstitial_challenge =
            solvers.iter().any(|s| s.relax_response_csp(&html)) || is_interstitial_challenge(&html);
        // sec-cpt analog: some sites serve the
        // rotating-obfuscated-bundle sec-cpt variant
        // (`<div id="sec-if-cpt-container">` + `<script src="/Wjv3…">`).
        // The bundle self-solves in our V8 and sets the `sec_cpt` cookie,
        // but it mutates the DOM the same way the i.js interstitial does, so the
        // post-exec `is_anti_bot_challenge()` can flip false and skip the
        // poll + cookie-diff retry before the bundle's round-trip lands.
        // Same narrow gating ⇒ false for every non-sec-cpt site ⇒ zero
        // regression. (If the marker happens to persist post-exec this
        // OR-in is simply a harmless no-op.)
        let started_as_seccpt_challenge =
            html.contains("sec-if-cpt-container") || html.contains("sec-cpt-if");
        // Persistent CDN-origin mutable-state guard. The
        // cookie-diff retry / pending-nav poll below gate on
        // `page.is_anti_bot_challenge()` (the *post-mutation* DOM). A
        // challenge orchestrator mutates the body, so the `_cf_chl_opt`
        // / `/cdn-cgi/challenge-platform/` marker can drop from the live
        // DOM while `cf_clearance` was NEVER issued ⇒ a
        // body-mutated-but-unsolved challenge page silently slips past the
        // retry gate. The interstitial and sec-cpt vendors already have
        // persistent origin-flags; this one did not. Capture it from the
        // *initial* response `html` (pre-mutation), mirroring the
        // existing detector at `handle_cloudflare_flow`. Narrow ⇒ false
        // for every site without this marker ⇒ no regression.
        let started_as_managed_challenge = crate::classify::is_managed_challenge_doc(&html);
        // AWS-WAF analog. The ~2 KB stub mutates
        // itself (challenge.js rewrites the body once the PoW worker posts
        // the token + reloads), so — exactly like the other vendors — the
        // post-exec `is_anti_bot_challenge()` can flip false while
        // `aws-waf-token` was never issued, silently slipping the poll +
        // cookie-diff retry gate. Capture it from the INITIAL response so
        // those primitives stay armed for the whole AWS self-solve. Narrow
        // (len<4096 + both envelope markers) ⇒ false for every non-AWS
        // site ⇒ zero regression.
        let started_as_awswaf_challenge = is_awswaf_challenge(&html);
        let mut current_html = html;
        let mut current_url = resp_url;
        let mut current_storage: Option<
            std::collections::HashMap<String, std::collections::HashMap<String, String>>,
        > = None;
        let mut last_accept_ch_upgrade = accept_ch_upgrade;
        let mut accept_ch_retry_done = false;

        // Wall-clock budget for this entire navigate_with_init call.
        // Default 50 s leaves headroom under the antibot_smoke 60 s wrapper.
        // Override via BROWSER_OXIDE_NAV_BUDGET_MS for slow-link or debugging runs.
        // The budget is mutable: if iter=0 returns a *real-content* page
        // (no challenge marker AND body > 50 KB), we extend the budget by
        // BROWSER_OXIDE_NAV_BUDGET_EXTEND_MS (default 25 s) to allow heavy
        // legitimate sites (large storefronts, media pages) to fully render.
        // Default budget aggressively low (15 s) — most pages render their
        // primary body well under that. Sites that legitimately need more
        // time get the per-iteration extension below; sites that hit a CHL
        // marker get retried with a fresh budget per iteration. The old
        // 50 s default left 35 s on the table for fast sites, which
        // dominated the holistic-sweep wall-clock (96 min for 126 sites).
        // Host-aware default. Most sites render under the 15s baseline; the
        // ones that don't (heavy PoW VMs, sensor-payload flows, large SPA
        // shells whose hydration runs slower under our V8) are tuned by the
        // operator via BROWSER_OXIDE_HOST_BUDGET_MS rather than a hardcoded
        // host list — see `host_budget_default_ms`. Challenge-class budgets
        // (sec-cpt PoW, AWS-WAF) are still handled generically below by their
        // own markers, not by host.
        let current_host = url::Url::parse(&current_url)
            .ok()
            .and_then(|u| u.host_str().map(str::to_string));
        let host_budget_default_ms = host_budget_default_ms(current_host.as_deref());
        // An AWS-WAF challenge nav (any *.token.awswaf.com-fronted host)
        // needs PoW-worker compute + token POST + reload to fit. The 15 s
        // default is half-consumed by the build phase, so the worker never
        // finishes before the budget expires. Give it the sensor-payload 25 s
        // tier. Gated on the AWS challenge flag (not the host) so it
        // generalizes across all such hosts and never fires for a benign
        // nav. The async drain still early-exits the instant the reload
        // sets nav_pending, so this is a ceiling, not a fixed wait.
        let host_budget_default_ms = if started_as_awswaf_challenge {
            host_budget_default_ms.max(25_000)
        } else {
            host_budget_default_ms
        };
        // Generic heavy proof-of-work challenge budget — applies to the whole
        // class (gated on the `started_as_seccpt_challenge` marker, not a
        // per-host hardcode). These challenges run an in-VM SHA-256 PoW that
        // takes ~tens of seconds under our V8, so the normal per-iteration
        // V8DeadlineWatcher tiers cut it off before it completes. ENV-
        // CONFIGURABLE via BROWSER_OXIDE_SECCPT_BUDGET_MS so the operator can
        // trade pass-rate for speed per run (e.g. 30000 = fast sweep that
        // skips the PoW, 140000 = default that lets it complete, 1000000 =
        // never cap). It is a CEILING, not a fixed wait — a page that renders
        // early still fast-exits.
        let host_budget_default_ms = if started_as_seccpt_challenge {
            let seccpt_budget = std::env::var("BROWSER_OXIDE_SECCPT_BUDGET_MS")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(140_000);
            host_budget_default_ms.max(seccpt_budget)
        } else {
            host_budget_default_ms
        };
        let mut nav_budget = Duration::from_millis(
            std::env::var("BROWSER_OXIDE_NAV_BUDGET_MS")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(host_budget_default_ms),
        );
        let nav_budget_extend = Duration::from_millis(
            std::env::var("BROWSER_OXIDE_NAV_BUDGET_EXTEND_MS")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(25_000),
        );
        let mut budget_extended = false;
        let mut geo_splash_followed = false;
        let nav_t0 = std::time::Instant::now();

        for iter in start_iter..iterations {
            // Bail before starting a new iteration if the wall-clock
            // budget is already exhausted — no point doing build_page
            // and drain if we have no time to react to the result.
            if nav_t0.elapsed() >= nav_budget {
                eprintln!(
                    "[navigate] budget exhausted ({}ms used / {}ms budget) before iter={} — bailing",
                    nav_t0.elapsed().as_millis(),
                    nav_budget.as_millis(),
                    iter
                );
                break;
            }

            // If we are re-using a page from a previous iteration that
            // was terminated, cancel the termination now so we can run
            // init scripts and other logic.
            // Note: we don't have a 'page' yet on iter 0, but we do on retries.
            // (The build_page_with_scripts... call below creates a fresh
            // runtime anyway, but the loop logic might eventually change).

            tracing::info!(iter = iter, url = %current_url, "navigation loop start");
            if debug_nav {
                eprintln!(
                    "[navigate] iter={} url={} html_len={}",
                    iter,
                    current_url,
                    current_html.len()
                );
            }

            // Reset the per-page sync-fetch counter at the start of each
            // iteration so MAX_SYNC_FETCH_PER_PAGE bounds *this* page's
            // chain, not the cumulative across iterations.
            crate::js_runtime::extensions::fetch_ext::reset_sync_fetch_count();

            // Snapshot cookies for this URL before the page runs. If the jar
            // gains new cookies during script execution (e.g. a /tl
            // response set a session cookie), we treat that as the
            // "challenge-solved" signal and retry — the vendor's ips.js solves
            // the PoW but never calls location.reload(), relying on the user
            // to hit F5. This primitive is that F5.
            let parsed_current = url::Url::parse(&current_url).ok();
            let cookies_before: String = if let Some(p) = parsed_current.as_ref() {
                client.cookies_for_url(p).await.unwrap_or_default()
            } else {
                String::new()
            };
            if debug_nav {
                tracing::debug!(cookies = %cookies_before, "navigate jar cookies (before)");
            }

            let mut page = Self::build_page_with_scripts_init_and_storage(
                &current_html,
                &current_url,
                &profile,
                &client,
                &init_scripts,
                current_storage.take(),
            )
            .await?;

            // Install the V8 deadline watcher for the remainder of the
            // wall-clock budget — but always with a minimum 5s floor so
            // even iterations past the nominal budget have a safety net.
            // Without the floor, a budget-exhausted iteration could spin
            // forever in V8 (no watcher → tokio::time::timeout can't
            // preempt CPU-bound JS).
            let remaining = nav_budget
                .saturating_sub(nav_t0.elapsed())
                .max(Duration::from_secs(5));
            eprintln!(
                "[navigate] iter={} installing V8DeadlineWatcher with {}ms remaining",
                iter,
                remaining.as_millis()
            );
            let _watcher =
                V8DeadlineWatcher::new(page.event_loop().runtime_mut().isolate_handle(), remaining);

            // Drain the event loop. Use the remaining nav budget (floored at 8s)
            // so that heavy PoW challenges (the VM can take 30+ seconds) can
            // complete their /tl POST AFTER the PoW finishes. The V8DeadlineWatcher
            // installed above provides the hard kill for analytics loops that never
            // reach idle on their own — once V8 is terminated, run_event_loop()
            // returns and the drain exits naturally.
            let drain_timeout = {
                let remaining = nav_budget.saturating_sub(nav_t0.elapsed());
                remaining.max(Duration::from_secs(8))
            };
            if let Err(e) = page.event_loop().run_until_idle(drain_timeout).await {
                tracing::warn!(error = %e, "navigate event loop error");
            }

            // If the watcher fired (or if we reached idle naturally), ensure
            // the isolate is ready for further script execution (draining
            // events, classification, etc.).
            page.event_loop().runtime_mut().cancel_terminate_execution();

            // NOTE: an earlier revision force-fired DOMContentLoaded/load +
            // readyState='complete' here for builds poisoned by a build-budget
            // terminate. REMOVED after measurement: it flipped NO site
            // (spotify/duolingo stay reCAPTCHA-gated; one site is a flaky
            // challenge vendor —
            // 2.4 KB or 1.48 MB on a risk-roll, with or without this), but on
            // GTM/OneTrust-heavy terminated builds (zoom.us) it fired lifecycle
            // events the poisoned build would NOT have, and the tag managers
            // injected a runaway DOM/tag graph that OOM-killed the process
            // (exit 137 — verified it still OOMs even with the otBannerSdk
            // re-fetch loop bounded by the sync-fetch cache, because the growth
            // is the injected DOM/JS, not the fetches). The safe readyState
            // advance still runs in the build's own lifecycle setTimeout for
            // NON-terminated builds (the common case; spotify still reaches
            // 'complete'). Terminated heavy builds keep readyState='loading',
            // strictly no worse than the prior behaviour.

            // Adaptive budget. Two paths after the first iteration:
            //
            // 1. FAST-EXIT — body > 50 KB AND no CHL marker AND readyState
            //    "complete" → the site rendered cleanly, return it now.
            //    Skips iter 1 and iter 2 entirely. Closes the dominant
            //    fast-site stall in the holistic sweep (where every fast
            //    page used to wait the full 50 s budget for nothing).
            //
            // 2. EXTEND — body > 50 KB but readyState still "loading"
            //    (e.g. footlocker, walmart pre-paint). Give one extension.
            //
            // CHL markers always continue iterating (cookie-delta retry path
            // below kicks in). Tiny-body responses also continue (challenges
            // often start as <50 KB stubs).
            if iter == start_iter {
                let body_len: usize = page
                    .event_loop()
                    .execute_script("document.body ? document.body.outerHTML.length : 0")
                    .unwrap_or_default()
                    .parse()
                    .unwrap_or(0);
                let is_chl = page.is_anti_bot_challenge();

                // SSR-preservation. Client hydration can CLEAR the server-
                // rendered DOM and then fail to rebuild it headless, collapsing
                // a full SSR page to an empty body. Seen on shopify: its inline
                // `<script type="module">` (React Router 7 / Remix) hydrates,
                // wipes the 410 KB SSR body, then never finishes the client
                // render → body=0. Running the module made us STRICTLY worse
                // than ignoring it (the SSR HTML was already the full page).
                // When the rendered body is below the pass floor but the server
                // HTML carried a substantial document, the SSR content IS the
                // page: rebuild the static server DOM via reload_html (the
                // destructive inline module re-throws under classic eval and is
                // skipped, so the SSR body survives). Gated on !challenge (the
                // challenge-solve path owns small bodies) and a large server
                // HTML (challenge stubs are tiny) — and we only KEEP the restore
                // if it actually yields a passing body, so a genuinely-thin page
                // is never falsely inflated.
                if !is_chl && body_len < 15_000 && current_html.len() > 50_000 {
                    page.reload_html(&current_html, &current_url);
                    let _ = page
                        .event_loop()
                        .run_until_idle(Duration::from_millis(200))
                        .await;
                    let restored: usize = page
                        .event_loop()
                        .execute_script("document.body ? document.body.outerHTML.length : 0")
                        .unwrap_or_default()
                        .parse()
                        .unwrap_or(0);
                    if restored >= 15_000 {
                        eprintln!(
                            "[navigate] SSR-preservation: hydration collapsed body to {}B; restored server DOM ({}B)",
                            body_len, restored
                        );
                        return Ok(page);
                    }
                }

                if !is_chl && body_len > 50 * 1024 {
                    let ready_state = page
                        .event_loop()
                        .execute_script("document.readyState")
                        .unwrap_or_default();
                    let ready_state = ready_state.trim().trim_matches('"');
                    if ready_state == "complete" {
                        eprintln!(
                            "[navigate] fast-exit on iter={} (body={}KB, no CHL, readyState=complete)",
                            iter,
                            body_len / 1024
                        );
                        return Ok(page);
                    }
                    if !budget_extended {
                        nav_budget += nav_budget_extend;
                        budget_extended = true;
                        eprintln!(
                            "[navigate] budget extended +{}ms (body={}KB, no CHL marker, readyState={})",
                            nav_budget_extend.as_millis(),
                            body_len / 1024,
                            ready_state
                        );
                    }
                }
                // SPA hydration early-exit.
                // For React/Vue/Next.js sites the `<body>` outerHTML may be
                // tiny (a 69-byte <noscript> + a single mount div) OR
                // moderately sized (twitter ships a 241KB shell of inline
                // state + script tags) — but the user-visible content is
                // always under one of the well-known mount-point IDs. If
                // ANY common SPA mount has ≥1 child element, the app is
                // alive and the loop's continued spinning is just noise
                // we'd terminate at drop time anyway. Without this signal,
                // twitter/x/hulu (heavy shells, slow hydration) burn the
                // full nav budget waiting for is_pending=false — which
                // never arrives because React's scheduler keeps queuing
                // setTimeout work forever. Empirically, pending state in
                // steady-state is ~33 op_timer_sleep, cycling
                // 33→18→1→33 driven by React.
                //
                // The mount-populated check is intentionally cheap (single
                // querySelector chain, fail-fast) so it adds <1ms per
                // iteration. Removed the prior `body_len <= 50KB` gate
                // because twitter's 241KB shell was tripping the wrong
                // branch — the mount-children count is the single source
                // of truth for "is this app rendered."
                if !is_chl {
                    let mount_populated: usize = page
                        .event_loop()
                        .execute_script(
                            "(function(){\
                                var sels = ['#react-root','#__next','#app','#root','[data-reactroot]','#main-app','#mount-point'];\
                                for (var i = 0; i < sels.length; i++) {\
                                    var el = document.querySelector(sels[i]);\
                                    if (el && el.children && el.children.length > 0) return el.children.length;\
                                }\
                                return 0;\
                            })()",
                        )
                        .unwrap_or_default()
                        .parse()
                        .unwrap_or(0);
                    if mount_populated > 0 {
                        eprintln!(
                            "[navigate] SPA-fast-exit on iter={} (body={}KB, mount has {} children)",
                            iter,
                            body_len / 1024,
                            mount_populated
                        );
                        return Ok(page);
                    }
                }
            }

            // Did a script request a re-navigation?
            let mut pending_info = page
                .event_loop()
                .execute_script(PENDING_NAV_JS)
                .unwrap_or_default();

            if !pending_info.is_empty() {
                tracing::info!(pending = %pending_info, "initial pending navigation found");
            }

            // Bounded poll for deferred navigation signals (auto-submitted forms,
            // PoW completions, challenge-driven assigns). Replaces the previous
            // fixed 2s wait. Checks every 200ms for up to 10s total; exits early
            // on first hit.
            if pending_info.is_empty()
                && (page.is_anti_bot_challenge()
                    || started_as_interstitial_challenge
                    || started_as_seccpt_challenge
                    || started_as_managed_challenge
                    || started_as_awswaf_challenge)
            {
                let deadline = std::time::Instant::now() + Duration::from_secs(90);
                while std::time::Instant::now() < deadline {
                    let _ = page
                        .event_loop()
                        .run_until_idle(Duration::from_millis(200))
                        .await;
                    // A challenge script may have appendChild'd a
                    // cross-origin challenge iframe (e.g. a
                    // geo.captcha-delivery.com or a
                    // challenges.…/ widget) during the tick above.
                    // `find_iframes` ran only at build time, so such a
                    // script-injected iframe otherwise gets ONLY a
                    // synthetic contentWindow shim and its challenge
                    // document is never fetched/executed (a structural
                    // blocker for modern challenge iframes). Materialize
                    // it for real here. Idempotent + cheap (DOM walk only)
                    // when nothing new appeared; gated by this poll's
                    // challenge condition ⇒ never runs for a benign nav
                    // (zero regression).
                    let _ = page
                        .rematerialize_iframes(&current_url, &client, &profile)
                        .await;
                    pending_info = page
                        .event_loop()
                        .execute_script(PENDING_NAV_JS)
                        .unwrap_or_default();
                    if !pending_info.is_empty() {
                        break;
                    }
                    // For this vendor's nav, i.js's round-trip
                    // typically lands a fresh `datadome=` cookie WITHOUT
                    // setting a pending nav — break as soon as it does so
                    // the cookie-diff retry below re-issues the original
                    // URL (instead of burning the full 90 s deadline).
                    if started_as_interstitial_challenge {
                        if let Some(p) = parsed_current.as_ref() {
                            let now = client.cookies_for_url(p).await.unwrap_or_default();
                            // A `datadome=` cookie is set on every
                            // nav incl. the failing 403 — break only on a
                            // genuine solve (cookie present AND the body
                            // is no longer a challenge document), not
                            // on a bare/gained cookie (false success).
                            // Any registered solver reporting solved on
                            // this (cookies, body) pair breaks the poll.
                            //
                            // Public primitive: also break on the
                            // engine-side `is_interstitial_solved` check so the
                            // cookie-diff retry fires even without a
                            // registered solver.
                            let body = page.content();
                            if solvers.iter().any(|s| s.solved_signal(&now, &body))
                                || is_interstitial_solved(&now, &body)
                            {
                                break;
                            }
                        }
                    }
                    // Deterministic sec-cpt break: the sec-cpt
                    // bundle self-solves in our V8 and transitions the
                    // `sec_cpt` cookie to the solved state WITHOUT
                    // setting a pending nav — exactly analogous to the
                    // interstitial break above. Break the instant the
                    // success marker appears so the post-sec-cpt reload is
                    // deterministic, not dependent on incidental budget
                    // stacking. Gated by `started_as_seccpt_challenge` ⇒
                    // false for every non-sec-cpt site ⇒ zero regression.
                    if started_as_seccpt_challenge {
                        if let Some(p) = parsed_current.as_ref() {
                            let now = client.cookies_for_url(p).await.unwrap_or_default();
                            // A registered solver's `solved_signal` reports
                            // the solve. Public-engine fallback
                            // `is_seccpt_solved` recognizes the solved-state
                            // cookie marker even when no solver is
                            // registered — mirrors is_interstitial_solved's shape.
                            let body = page.content();
                            if solvers.iter().any(|s| s.solved_signal(&now, &body))
                                || is_seccpt_solved(&now, &body)
                            {
                                // A cookie-only sec-cpt solve must
                                // get guaranteed build+drain budget for the
                                // post-solve reload. The +45 s bump on the
                                // JS-pending-nav branch (≈:2760) is unreachable
                                // from this cookie-only path, so a solve that
                                // doesn't also arm a JS pending-nav falls into
                                // the MIN_RETRY_BUDGET early-return and returns
                                // the ~2.7 KB interstitial when <15 s remain.
                                // Arm +45 s here, once. Gated by
                                // `started_as_seccpt_challenge` ⇒ zero non-sec-cpt
                                // regression.
                                if !budget_extended {
                                    nav_budget += Duration::from_secs(45);
                                    budget_extended = true;
                                }
                                if debug_nav {
                                    eprintln!(
                                        "[solver] solved_signal fired (likely sec-cpt ~3~) — armed +45s budget, breaking poll"
                                    );
                                }
                                break;
                            }
                        }
                    }
                    // AWS-WAF analog of the interstitial /
                    // sec-cpt breaks above. challenge.js's blob-URL PoW
                    // worker posts the `aws-waf-token` and reloads WITHOUT
                    // necessarily setting a JS pending-nav we observe, so
                    // break the instant the token cookie lands + the body
                    // is no longer the stub, letting the cookie-diff retry
                    // re-issue the original URL. Gated on
                    // `started_as_awswaf_challenge` ⇒ zero non-AWS impact.
                    if started_as_awswaf_challenge {
                        if let Some(p) = parsed_current.as_ref() {
                            let now = client.cookies_for_url(p).await.unwrap_or_default();
                            let body = page.content();
                            if solvers.iter().any(|s| s.solved_signal(&now, &body))
                                || is_awswaf_solved(&now, &body)
                            {
                                if debug_nav {
                                    eprintln!(
                                        "[awswaf] aws-waf-token landed + stub gone — breaking poll"
                                    );
                                }
                                break;
                            }
                        }
                    }
                }
            }

            // 3. Selective CSP bypass for known anti-bot challenge domains.
            // The hosts listed below often have CSPs that
            // block their own challenge-vendor trackers in emulated
            // environments due to origin/nonce mismatches. Without the bypass
            // we get body=0 because the ips.js script we'd LOAD to solve the
            // challenge is the very thing CSP refuses (the body collapses to
            // empty because CSP refused to load the ips.js script).
            if current_url.contains("walmart.com")
                || current_url.contains("canadagoose.com")
                || current_url.contains("hyatt.com")
                || current_url.contains("realtor.com")
                || current_url.contains("footlocker.com")
                || current_url.contains("ticketmaster.com")
                || current_url.contains("udemy.com")
            {
                tracing::info!(url = %current_url, "applying selective CSP bypass for anti-bot domain");
                let rt = page.event_loop().runtime_mut();
                let op_state = rt.op_state();
                let mut state = op_state.borrow_mut();
                if let Some(stealth_state) =
                    state
                        .try_borrow_mut::<crate::js_runtime::extensions::stealth_ext::StealthState>(
                        )
                {
                    if let Some(profile) = &mut stealth_state.profile {
                        profile.enforce_csp = false;
                    }
                }
            }

            // Iterate registered solvers and let each try to clear its
            // challenge. A well-behaved solver bails out on non-matching
            // bodies / cookies, so unconditional iteration is equivalent
            // to unconditional inline calls.
            //
            // We track whether *any* solver reported Solved this
            // iteration so the cookie-delta retry below can suppress
            // the retry-on-cookie-change for the previously
            // `challenge_state == Favorable` special case.
            //
            // sec-cpt guard preserved: when this nav started as
            // sec-cpt, the sensor-payload POST path is the wrong payload for
            // the verify endpoint. A solver is expected to short-circuit
            // on the "sec-cpt" sub_kind (returning InProgress), so the
            // unconditional iter is safe.
            let mut any_solved = false;
            for s in solvers.iter() {
                // Pre-iteration sec-cpt guard: when this nav started as
                // sec-cpt, the sensor-payload POST is the wrong
                // payload for the verify endpoint, so signal the solver
                // via sub_kind to short-circuit.
                let sub = if s.name() == "akamai-bmp" && started_as_seccpt_challenge {
                    "sec-cpt"
                } else {
                    ""
                };
                let kind = crate::challenge::ChallengeKind::new(s.name(), sub);
                if matches!(
                    s.solve(&mut page, &client, kind).await,
                    crate::challenge::SolveOutcome::Solved
                ) {
                    any_solved = true;
                }
            }

            // Geo country-selection splash follow (bestbuy etc.): if no script
            // requested a navigation and we were served a thin country-splash
            // instead of the storefront, follow the document's own same-host
            // region link ONCE — exactly what a real regional visitor does by
            // clicking "United States". The skip-link sets the locale cookie and
            // serves the real site. Tightly gated in `geo_country_splash_target`
            // ⇒ never fires on a normal page or an off-host cross-region link.
            if pending_info.is_empty() && !geo_splash_followed && iter + 1 < iterations {
                let body_now = page.content();
                if let Some(target) = geo_country_splash_target(&body_now, &current_url) {
                    geo_splash_followed = true;
                    if let Ok(u) = deno_core::serde_json::to_string(&target) {
                        pending_info = format!("{{\"url\":{u},\"kind\":\"assign\"}}");
                        tracing::info!(target = %target, "geo country-splash: following region link");
                    }
                }
            }

            if pending_info.is_empty() {
                // Post-settle cookie-delta retry: if the cookie jar gained new
                // values during this iteration AND the page still looks like a
                // challenge AND we have iterations left, retry the same URL
                // once. Covers engines whose solver sets a session cookie and
                // expects the NEXT top-level nav to carry it (some challenge
                // vendors). Universal primitive — no per-engine code.
                //
                // Also retry if the origin just upgraded to Accept-CH.
                // Only retry ONCE for the upgrade.
                if (page.is_anti_bot_challenge()
                    || started_as_interstitial_challenge
                    || started_as_seccpt_challenge
                    || started_as_managed_challenge
                    || started_as_awswaf_challenge
                    || (last_accept_ch_upgrade && !accept_ch_retry_done))
                    && iter + 1 < iterations
                {
                    let cookies_after: String = if let Some(p) = parsed_current.as_ref() {
                        client.cookies_for_url(p).await.unwrap_or_default()
                    } else {
                        String::new()
                    };

                    // Instrumentation: at the exact decision point
                    // where the cookie-diff retry would re-issue the
                    // original URL, record whether the i.js
                    // round-trip actually landed a `datadome=` cookie.
                    // `cookie_gained=false` here ⇒ the bundle's VM/WASM
                    // did not complete; `true` ⇒ the existing retry
                    // already re-issues. debug_nav-gated ⇒ zero impact.
                    // Same diagnostic for the sec-cpt bundle — did the
                    // bundle actually run and fire its PoW-answer verify
                    // POST? debug_nav-gated ⇒ zero impact.
                    if debug_nav && started_as_seccpt_challenge {
                        let fl = page
                            .event_loop()
                            .execute_script(
                                "JSON.stringify((globalThis._browser_oxide&&globalThis._browser_oxide.__fetchLog)||[])",
                            )
                            .unwrap_or_default();
                        let secck = page
                            .event_loop()
                            .execute_script(
                                "(function(){try{return /sec_cpt=/.test(document.cookie)?'sec_cpt-present':'no-sec_cpt'}catch(e){return 'err'}})()",
                            )
                            .unwrap_or_default();
                        eprintln!("[seccpt-trace] post-bundle cookie={secck} __fetchLog={fl}");
                    }

                    let mut should_retry = (cookies_after != cookies_before
                        && !cookies_after.is_empty())
                        || (last_accept_ch_upgrade && !accept_ch_retry_done);

                    // If a solver already reported the challenge solved
                    // this iteration, DON'T retry just because a cookie
                    // value changed (challenge cookies always rotate).
                    if (accept_ch_retry_done || !last_accept_ch_upgrade) && any_solved {
                        should_retry = false;
                    }

                    if should_retry {
                        if last_accept_ch_upgrade {
                            accept_ch_retry_done = true;
                        }
                        // Before launching the retry, check we have at least
                        // ~15s of nav budget left — a retry requires a fresh
                        // build + drain (~10-15s minimum). If the budget is
                        // too tight, return the current iter=0 page instead
                        // of blowing the budget and returning nothing
                        // (a regression we hit on one site — a vendor bm_sz
                        // cookie triggers the retry path even on real
                        // homepages).
                        const MIN_RETRY_BUDGET: Duration = Duration::from_secs(15);
                        if nav_budget.saturating_sub(nav_t0.elapsed()) < MIN_RETRY_BUDGET {
                            eprintln!(
                                "[navigate] iter={} skip cookie-delta retry: only {}ms left of {}ms budget",
                                iter,
                                nav_budget.saturating_sub(nav_t0.elapsed()).as_millis(),
                                nav_budget.as_millis()
                            );
                            return Ok(page);
                        }
                        if debug_nav {
                            eprintln!(
                                "[navigate] iter={} POST-SETTLE RETRY firing for {}",
                                iter, current_url
                            );
                        }
                        tracing::info!(
                            before_len = cookies_before.len(),
                            after_len = cookies_after.len(),
                            "cookie delta after challenge scripts — retrying"
                        );

                        // Option A: try an in-V8 refetch first. If a challenge
                        // engine patched window.fetch
                        // during script execution to inject session headers
                        // (x-kpsdk-ct and friends), those headers ride along
                        // on this fetch — which a fresh Rust-side GET would
                        // not carry. The page stays alive while we refetch so
                        // the patched fetch state is preserved.
                        let refetch_js = r#"
                            (async () => {
                                globalThis.__psrHtml = null;
                                globalThis.__psrStatus = 0;
                                globalThis.__psrErr = null;
                                try {
                                    const resp = await fetch(location.href, {
                                        method: 'GET',
                                        credentials: 'include',
                                        headers: {
                                            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
                                        },
                                    });
                                    globalThis.__psrStatus = resp.status;
                                    globalThis.__psrHtml = await resp.text();
                                } catch (e) {
                                    globalThis.__psrErr = String((e && e.message) || e);
                                }
                            })();
                        "#;
                        let _ = page
                            .event_loop()
                            .execute_and_run(refetch_js, Duration::from_secs(15))
                            .await;
                        let status_str = page
                            .event_loop()
                            .execute_script("String(globalThis.__psrStatus || 0)")
                            .unwrap_or_default();
                        let err_str = page
                            .event_loop()
                            .execute_script("String(globalThis.__psrErr || '')")
                            .unwrap_or_default();
                        let v8_html = page
                            .event_loop()
                            .execute_script("String(globalThis.__psrHtml || '')")
                            .unwrap_or_default();
                        if debug_nav {
                            eprintln!(
                                "[navigate] iter={} in-V8 refetch status={} err={} html_len={}",
                                iter,
                                status_str,
                                err_str,
                                v8_html.len()
                            );
                        }

                        // Accept the V8-fetched body if it's larger than the
                        // current challenge page AND doesn't re-trigger our
                        // anti-bot content markers. Otherwise fall back to a
                        // Rust-side GET (cookie-only flow — works for simpler
                        // engines that upgrade on any authenticated request).
                        // Coverage of the marker set must mirror
                        // is_anti_bot_challenge() — otherwise a vendor we
                        // detect at the top of the loop is silently accepted
                        // here, breaking the retry chain. Each marker
                        // string below is the same one classify.rs
                        // already keys on for the vendor — keeping this
                        // guard in sync with the verdict logic.
                        let v8_html_is_real = !v8_html.is_empty()
                            && v8_html.len() > current_html.len()
                            && !v8_html.contains("/ips.js")
                            && !v8_html.contains("/149e9513-")
                            && !v8_html.contains("kpsdk")
                            && !v8_html.contains("_abck")
                            && !v8_html.contains("bm_sz")
                            && !v8_html.contains("captcha-delivery.com")
                            && !v8_html.contains("dd-script")
                            && !v8_html.contains("dd_engagement")
                            && !v8_html.contains("/cdn-cgi/challenge-platform/")
                            && !v8_html.contains("AwsWafIntegration")
                            && !v8_html.contains("gokuProps")
                            && !v8_html.contains("_Incapsula_Resource")
                            && !v8_html.contains("visid_incap")
                            && !v8_html.contains("reese84")
                            && !v8_html.contains("_px3")
                            && !v8_html.contains("_pxhd")
                            && !v8_html.contains("px-captcha")
                            && !v8_html.contains("press &amp; hold")
                            && !v8_html.contains("sucuri_cloudproxy_js")
                            && !v8_html.contains("Incapsula incident ID");

                        // Extract any challenge-engine session headers that
                        // scripts collected during solves. For one vendor: the
                        // last successful POST /tl response carried a fresh
                        // x-kpsdk-ct that the retry GET must forward AS A
                        // REQUEST HEADER. Cookies alone are not enough.
                        let kpsdk_headers_js = r#"
                            JSON.stringify((() => {
                                const log = globalThis.__fetchLog || [];
                                const out = {};
                                for (const entry of log) {
                                    const resp = entry.respHeaders || {};
                                    for (const k of Object.keys(resp)) {
                                        if (k.toLowerCase().startsWith('x-kpsdk')) {
                                            out[k.toLowerCase()] = resp[k];
                                        }
                                    }
                                    const req = entry.reqHeaders || {};
                                    for (const k of Object.keys(req)) {
                                        const lk = k.toLowerCase();
                                        if (lk.startsWith('x-kpsdk') && !out[lk]) {
                                            out[lk] = req[k];
                                        }
                                    }
                                }
                                return out;
                            })())
                        "#;
                        let kpsdk_json = page
                            .event_loop()
                            .execute_script(kpsdk_headers_js)
                            .unwrap_or_default();
                        let kpsdk: std::collections::HashMap<String, String> =
                            deno_core::serde_json::from_str(&kpsdk_json).unwrap_or_default();
                        if debug_nav && !kpsdk.is_empty() {
                            let keys: Vec<&str> = kpsdk.keys().map(|s| s.as_str()).collect();
                            eprintln!(
                                "[navigate] iter={} harvested x-kpsdk-* headers: {:?}",
                                iter, keys
                            );
                        }

                        current_storage = Some(page.event_loop().get_storage());
                        drop(page);
                        if v8_html_is_real {
                            if debug_nav {
                                eprintln!(
                                    "[navigate] iter={} USING V8-fetched body ({} bytes)",
                                    iter,
                                    v8_html.len()
                                );
                            }
                            current_html = v8_html;
                            last_accept_ch_upgrade = false; // Reset on real content
                        } else {
                            // Reload-style headers + harvested x-kpsdk-*
                            // tokens on the retry GET.
                            let accept_ch_upgraded = if let Ok(u) = url::Url::parse(&current_url) {
                                client.has_accept_ch(u.host_str().unwrap_or_default()).await
                            } else {
                                false
                            };
                            let mut reload_hdrs = crate::net::headers::nav_headers_reload(
                                &profile,
                                &current_url,
                                accept_ch_upgraded,
                            );
                            for (k, v) in &kpsdk {
                                reload_hdrs.push((k.clone(), v.clone()));
                            }
                            let resp = client
                                .get_follow_exact_headers(&current_url, &reload_hdrs, 10)
                                .await
                                .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;
                            current_html = resp.text();
                            current_url = resp.url.clone();
                            last_accept_ch_upgrade = resp.accept_ch_upgrade;
                        }
                        continue;
                    }
                }
                return Ok(page);
            }

            let p: deno_core::serde_json::Value =
                deno_core::serde_json::from_str(&pending_info).unwrap_or_default();
            let pending_url = p["url"].as_str().unwrap_or_default();
            let pending_method = p["method"].as_str().unwrap_or("GET").to_string();
            let pending_body = p["body"].as_str().map(|s| s.to_string());
            let kind = p["kind"].as_str().unwrap_or("unknown");

            if pending_url.is_empty() {
                return Ok(page);
            }

            // Resolve relative pending URLs. resolve_url returns None for
            // non-http(s) schemes (about:blank, data:, javascript:, etc.) —
            // those are programmatic JS navigations that don't change the
            // navigable; treat as no-op and return the current page.
            // Example: JS that sets location.href='about:blank' in an
            // iframe bootstrap previously bubbled through the pending-nav
            // harvester as a hard error.
            let next_url = match Self::resolve_url(&current_url, pending_url) {
                Some(u) => u,
                None => return Ok(page),
            };
            tracing::debug!(kind = kind, url = %next_url, method = %pending_method, "navigate pending navigation");

            if iter + 1 == iterations {
                tracing::warn!(
                    max_iterations = iterations,
                    "navigate hit max iterations, returning current page"
                );
                return Ok(page);
            }

            // Same MIN_RETRY_BUDGET guard as the cookie-delta path.
            // The pending-nav path consumes the page (drop) and re-fetches.
            // If we don't have at least 15s left to build+drain the next
            // iteration, return the current page to avoid the no-page-FAIL
            // we hit on one site (a challenge-marked homepage triggers pending
            // nav, then iter=1 bails before producing anything usable).
            const MIN_PENDING_NAV_BUDGET: Duration = Duration::from_secs(15);
            if nav_budget.saturating_sub(nav_t0.elapsed()) < MIN_PENDING_NAV_BUDGET {
                nav_budget += Duration::from_secs(45);
            }

            // Harvest x-kpsdk-* headers from __fetchLog before dropping the
            // page. The last successful POST /tl response carries a fresh
            // x-kpsdk-ct that the retry GET must forward AS A REQUEST HEADER.
            // Cookies alone are not enough.
            let harvested_kpsdk: std::collections::HashMap<String, String> = {
                let js = r#"
                    JSON.stringify((() => {
                        const log = globalThis.__fetchLog || [];
                        const out = {};
                        for (const entry of log) {
                            const resp = entry.respHeaders || {};
                            for (const k of Object.keys(resp)) {
                                if (k.toLowerCase().startsWith('x-kpsdk')) {
                                    out[k.toLowerCase()] = resp[k];
                                }
                            }
                            const req = entry.reqHeaders || {};
                            for (const k of Object.keys(req)) {
                                const lk = k.toLowerCase();
                                if (lk.startsWith('x-kpsdk') && !out[lk]) {
                                    out[lk] = req[k];
                                }
                            }
                        }
                        return out;
                    })())
                "#;
                let j = page.event_loop().execute_script(js).unwrap_or_default();
                deno_core::serde_json::from_str(&j).unwrap_or_default()
            };
            if debug_nav && !harvested_kpsdk.is_empty() {
                let keys: Vec<&str> = harvested_kpsdk.keys().map(|s| s.as_str()).collect();
                eprintln!(
                    "[navigate] iter={} harvested x-kpsdk-* for retry: {:?}",
                    iter, keys
                );
            }

            // In-V8 refetch for same-origin reloads on challenge pages.
            // If the page's own scripts triggered a reload-style navigation
            // (location.href/reload/same-host assign) while challenge markers
            // are still present, the server is likely gating on a token that
            // only an engine-patched window.fetch injects (e.g. an x-kpsdk-ct
            // session header). A fresh Rust-side GET bypasses that patch.
            // Try the refetch through the live V8 fetch first; if the result
            // still looks like a challenge, fall back to the normal Rust path.
            let same_host_reload = pending_method == "GET" && page.is_anti_bot_challenge() && {
                let cur = url::Url::parse(&current_url).ok();
                let nxt = url::Url::parse(&next_url).ok();
                matches!(
                    (cur, nxt),
                    (Some(a), Some(b)) if a.host_str() == b.host_str()
                )
            };
            let v8_refetched: Option<String> = if same_host_reload {
                // Post-PoW jitter: real Chrome takes 100-500ms between the
                // challenge solve and the location.reload that follows. Without
                // this gap, an immediate back-to-back refetch can trip a
                // per-IP rate limiter and return 429. 250ms baseline
                // + small jitter mimics the natural human-action gap.
                let jitter_ms =
                    250 + (std::time::Instant::now().elapsed().as_nanos() & 0xFF) as u64;
                tokio::time::sleep(Duration::from_millis(jitter_ms)).await;
                // "Let the bundle self-solve": this vendor's `rt:'i'` nav
                // sets a reload __pendingNavigation EARLY, so the flow
                // lands here and would otherwise reload after ~250 ms —
                // long before i.js can create the geo.captcha-delivery.com
                // challenge iframe, let it run its WASM challenge +
                // postMessage, and write the `datadome=` cookie. The
                // extended challenge poll is gated under
                // `pending_info.is_empty()` so it is SKIPPED on this
                // branch. Give the challenge a bounded self-solve window:
                // pump the event loop and break the instant a `datadome=`
                // cookie appears (the success signal). Narrowly gated to
                // `started_as_interstitial_challenge` ⇒ false for every site that did
                // not start on this vendor ⇒ zero regression.
                //
                // This window is the *pending-nav* path for this vendor. The
                // other `rt:'i'` flow (no early pending nav) is NOT served
                // here — it is served by the `pending_info.is_empty() &&
                // started_as_interstitial_challenge` poll above, which also pumps
                // `rematerialize_iframes` and breaks on `datadome_solved`.
                // So the self-solve window is reachable on BOTH
                // branches; the poll-entry invariant is
                // `started_as_interstitial_challenge == is_challenge_doc(initial html)`.
                if started_as_interstitial_challenge {
                    let dd_deadline = std::time::Instant::now() + Duration::from_secs(45);
                    let parsed_cur = url::Url::parse(&current_url).ok();
                    while std::time::Instant::now() < dd_deadline {
                        let _ = page
                            .event_loop()
                            .run_until_idle(Duration::from_millis(250))
                            .await;
                        if let Some(p) = parsed_cur.as_ref() {
                            let now = client.cookies_for_url(p).await.unwrap_or_default();
                            // FP-D3: require a genuine solve (cookie +
                            // body no longer a challenge doc) — the
                            // bare `datadome=` cookie is set on the 403
                            // fail too, so the old check broke the
                            // self-solve window on a false success.
                            // E2 trait dispatch: a registered solver reports
                            // the solve via its `solved_signal`.
                            let body = page.content();
                            if solvers.iter().any(|s| s.solved_signal(&now, &body)) {
                                if debug_nav {
                                    eprintln!("[solver] self-solve signal — proceeding to reload");
                                }
                                break;
                            }
                        }
                    }
                }
                let refetch_js = format!(
                    r#"
                    (async () => {{
                        globalThis.__psrHtml = null;
                        globalThis.__psrStatus = 0;
                        globalThis.__psrErr = null;
                        try {{
                            const resp = await fetch({url_js}, {{
                                method: 'GET',
                                credentials: 'include',
                                headers: {{
                                    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
                                }},
                            }});
                            globalThis.__psrStatus = resp.status;
                            globalThis.__psrHtml = await resp.text();
                        }} catch (e) {{
                            globalThis.__psrErr = String((e && e.message) || e);
                        }}
                    }})();
                    "#,
                    url_js = deno_core::serde_json::to_string(&next_url)
                        .unwrap_or_else(|_| "''".to_string())
                );
                let _ = page
                    .event_loop()
                    .execute_and_run(&refetch_js, Duration::from_secs(15))
                    .await;
                let status = page
                    .event_loop()
                    .execute_script("String(globalThis.__psrStatus || 0)")
                    .unwrap_or_default();
                let err = page
                    .event_loop()
                    .execute_script("String(globalThis.__psrErr || '')")
                    .unwrap_or_default();
                let html = page
                    .event_loop()
                    .execute_script("String(globalThis.__psrHtml || '')")
                    .unwrap_or_default();
                if debug_nav {
                    eprintln!(
                        "[navigate] iter={} in-V8 refetch status={} err={} html_len={}",
                        iter,
                        status,
                        err,
                        html.len()
                    );
                }
                let looks_real = !html.is_empty()
                    && html.len() > current_html.len()
                    && !html.contains("/ips.js")
                    && !html.contains("/149e9513-")
                    && !html.contains("kpsdk")
                    && !html.contains("_abck")
                    && !html.contains("bm_sz");
                if looks_real {
                    Some(html)
                } else {
                    None
                }
            } else {
                None
            };

            current_storage = Some(page.event_loop().get_storage());
            drop(page);

            if let Some(html) = v8_refetched {
                if debug_nav {
                    eprintln!(
                        "[navigate] iter={} USING V8-fetched body ({} bytes)",
                        iter,
                        html.len()
                    );
                }
                current_html = html;
                // current_url unchanged (same origin reload)
                continue;
            }

            if debug_nav {
                eprintln!(
                    "[navigate] iter={} FETCH {} {}",
                    iter, pending_method, next_url
                );
            }

            // Fetch the next page. For form POSTs we must send the form
            // Content-Type or the server can't parse the body. For GETs that
            // are same-origin reload-style navigations (location.href/reload
            // assign from JS), use reload-semantic headers so engines can
            // distinguish a solved-session reload from a fresh user nav.
            let resp = if pending_method == "POST" {
                let post_headers = vec![
                    (
                        "content-type".to_string(),
                        "application/x-www-form-urlencoded".to_string(),
                    ),
                    ("origin".to_string(), {
                        url::Url::parse(&current_url)
                            .ok()
                            .and_then(|u| u.origin().ascii_serialization().into())
                            .unwrap_or_default()
                    }),
                    ("referer".to_string(), current_url.clone()),
                ];
                client
                    .post_bytes_follow(
                        &next_url,
                        pending_body.as_deref().unwrap_or("").as_bytes(),
                        &post_headers,
                        10,
                    )
                    .await
                    .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?
            } else {
                let same_origin = {
                    let a = url::Url::parse(&current_url).ok();
                    let b = url::Url::parse(&next_url).ok();
                    matches!((a, b), (Some(u), Some(v)) if u.host_str() == v.host_str())
                };
                if same_origin {
                    let accept_ch_upgraded = if let Ok(u) = url::Url::parse(&current_url) {
                        client.has_accept_ch(u.host_str().unwrap_or_default()).await
                    } else {
                        false
                    };
                    let mut reload_hdrs = crate::net::headers::nav_headers_reload(
                        &profile,
                        &current_url,
                        accept_ch_upgraded,
                    );
                    for (k, v) in &harvested_kpsdk {
                        reload_hdrs.push((k.clone(), v.clone()));
                    }
                    let resp = client
                        .get_follow_exact_headers(&next_url, &reload_hdrs, 10)
                        .await
                        .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?;

                    if resp.status == 498 || resp.status == 403 || resp.status == 429 {
                        eprintln!("[navigate] reload response headers ({}):", resp.status);
                        for (k, v) in &resp.headers {
                            eprintln!("  {}: {}", k, v);
                        }
                    }
                    resp
                } else {
                    client
                        .get_follow(&next_url, 10)
                        .await
                        .map_err(|e| deno_core::error::AnyError::msg(e.to_string()))?
                }
            };
            current_html = resp.text();
            current_url = resp.url.clone();
            last_accept_ch_upgrade = resp.accept_ch_upgrade;
        }

        // Fallback (should be reachable via the loop)
        Err(deno_core::error::AnyError::msg(
            "Navigation loop terminated without returning a page",
        ))
    }

    /// **DEPRECATED**: Legacy name — now a thin wrapper around [`Page::navigate`].
    ///
    /// This used to contain vendor-specific challenge logic, which
    /// has been removed in favor of the generic `__pendingNavigation`
    /// primitive. Callers should migrate to `Page::navigate` directly.
    #[deprecated(note = "use Page::navigate instead")]
    pub async fn navigate_with_challenges(
        url: &str,
        profile: crate::stealth::StealthProfile,
        max_retries: u8,
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::navigate(url, profile, max_retries.max(1)).await
    }

    /// Build a page with external script fetching.
    /// Resolve a potentially-relative URL against a base URL.
    fn resolve_url(base: &str, relative: &str) -> Option<String> {
        // Defence against the iphey.com regression: a JS-side
        // `location.href = 'about:blank'` (or `'data:...'`, `'javascript:'`,
        // etc.) can reach Rust as the literal `https://host/about:blank` if
        // the JS URL polyfill mis-joined a special-scheme URL against the
        // current http(s) base. Treat any path that begins with a known
        // special-scheme literal as a no-op pending navigation (return None
        // and let the caller keep the current page).
        if let Some(idx) = relative.find('/') {
            let tail = &relative[idx + 1..];
            for sch in &[
                "about:",
                "data:",
                "javascript:",
                "blob:",
                "mailto:",
                "tel:",
                "view-source:",
            ] {
                if tail.starts_with(sch) {
                    return None;
                }
            }
        }
        for sch in &[
            "about:",
            "data:",
            "javascript:",
            "blob:",
            "mailto:",
            "tel:",
            "view-source:",
        ] {
            if relative.starts_with(sch) {
                return None;
            }
        }
        let base_url = url::Url::parse(base).ok()?;
        let joined = base_url.join(relative).ok()?;
        // Reject any joined URL whose path begins with a special-scheme
        // literal (catches the rare case where the input was a clean
        // relative path but contained an embedded `about:blank` segment).
        if let Some(path) = joined.path().strip_prefix('/') {
            for sch in &[
                "about:",
                "data:",
                "javascript:",
                "blob:",
                "mailto:",
                "tel:",
                "view-source:",
            ] {
                if path.starts_with(sch) {
                    return None;
                }
            }
        }
        // We can only fetch http/https. about:blank, data:, blob:,
        // javascript:, chrome-extension:, etc. either have no host
        // (Url::host_str() returns None, causing "no host in URL"
        // downstream) or aren't network-addressable.
        match joined.scheme() {
            "http" | "https" => Some(joined.to_string()),
            _ => None,
        }
    }

    async fn build_page_with_scripts_and_init(
        html: &str,
        url: &str,
        profile: &crate::stealth::StealthProfile,
        client: &crate::net::HttpClient,
        init_scripts: &[String],
    ) -> Result<Self, deno_core::error::AnyError> {
        Self::build_page_with_scripts_init_and_storage(
            html,
            url,
            profile,
            client,
            init_scripts,
            None,
        )
        .await
    }

    async fn build_page_with_scripts_init_and_storage(
        html: &str,
        url: &str,
        profile: &crate::stealth::StealthProfile,
        client: &crate::net::HttpClient,
        init_scripts: &[String],
        storage: Option<
            std::collections::HashMap<String, std::collections::HashMap<String, String>>,
        >,
    ) -> Result<Self, deno_core::error::AnyError> {
        let bp_trace = std::env::var("BROWSER_OXIDE_BUILD_PROFILE").is_ok();
        let bp_t0 = std::time::Instant::now();
        macro_rules! mark {
            ($label:expr) => {
                if bp_trace {
                    eprintln!("[bp] {:>5}ms {}", bp_t0.elapsed().as_millis(), $label);
                }
            };
        }
        let dom = crate::html_parser::parse_html(html);
        let scripts = script_runner::find_scripts(&dom);
        let stylesheet_entries = stylesheet_collector::find_stylesheets(&dom);
        mark!("parse_html + find_scripts + find_stylesheets");

        // Fetch ALL external stylesheets in parallel
        let mut inline_css = Vec::new();
        let css_futures: Vec<_> = stylesheet_entries
            .iter()
            .filter_map(|entry| match entry {
                stylesheet_collector::StylesheetEntry::Inline(css) => {
                    inline_css.push(css.clone());
                    None
                }
                stylesheet_collector::StylesheetEntry::External(href) => {
                    let full_url = Self::resolve_url(url, href)?;
                    let client = client.clone();
                    Some(async move {
                        match client.get(&full_url).await {
                            Ok(resp) if resp.ok() => {
                                let text = resp.text();
                                if !text.trim_start().starts_with("<!") {
                                    Some((text, resp.timings.clone()))
                                } else {
                                    None
                                }
                            }
                            _ => {
                                tracing::warn!(url = %full_url, "Failed to fetch stylesheet");
                                None
                            }
                        }
                    })
                }
            })
            .collect();

        // Pre-fetch ALL external scripts in parallel (execute later in document order)
        let script_futures: Vec<_> = scripts
            .iter()
            .enumerate()
            .filter_map(|(i, script)| {
                let src = script.src.as_ref()?;
                let full_url = Self::resolve_url(url, src)?;
                // CSP `script-src-elem` enforcement. Parser-inserted scripts
                // (everything `find_scripts` produces from the initial HTML
                // parse) need a matching nonce to load under
                // `'strict-dynamic'`. Without this gate, browser_oxide
                // would fetch a `/akam/13/<hash>` bootstrap that real
                // Chrome blocks under CSP — a fidelity divergence.
                if let Ok(parsed_url) = url::Url::parse(&full_url) {
                    if let Err(violated) = crate::js_runtime::extensions::fetch_ext::check_csp(
                        crate::net::csp::Directive::ScriptSrcElem,
                        &parsed_url,
                        script.nonce.as_deref(),
                        true, // parser_inserted: came from HTML parse
                    ) {
                        eprintln!(
                            "[csp] Refused to load the script '{}' because it violates the following Content Security Policy directive: \"{}\".",
                            full_url, violated
                        );
                        return None;
                    }
                }
                let client = client.clone();
                let profile = profile.clone();
                Some(async move {
                    // Script fetches inherit parent doc's
                    // regional accept-language (see lib.rs::get_with_headers).
                    let mut hdrs = crate::net::headers::nav_headers_for_url(&profile, url, false);
                    hdrs.push(("referer".to_string(), url.to_string()));
                    hdrs.push(("accept".to_string(), "*/*".to_string()));
                    hdrs.push(("sec-fetch-dest".to_string(), "script".to_string()));
                    hdrs.push(("sec-fetch-mode".to_string(), "no-cors".to_string()));
                    hdrs.push(("sec-fetch-site".to_string(), "cross-site".to_string()));

                    // Instrumentation: trace the i.js
                    // external-script fetch to get hard evidence of
                    // whether the bundle even loads + its size. Env-gated,
                    // default off ⇒ zero behavioral/perf/log change.
                    let dd_trace = full_url.contains("captcha-delivery.com")
                        && std::env::var("BROWSER_OXIDE_CHALLENGE_TRACE").is_ok();
                    // Trace EVERY external-script fetch when
                    // BROWSER_OXIDE_SECCPT_TRACE is set, so we can see whether
                    // the obfuscated `/Wjv3…` sec-cpt bundle is actually
                    // fetched + its size/status. Env-gated, default off ⇒
                    // zero impact.
                    let sc_trace = std::env::var("BROWSER_OXIDE_SECCPT_TRACE").is_ok();
                    match client.get_follow_with_headers(&full_url, &hdrs, 5).await {
                        Ok(resp) if resp.ok() => {
                            let text = resp.text();
                            if dd_trace {
                                eprintln!(
                                    "[challenge-trace] i.js fetch OK {} status={} bytes={}",
                                    full_url,
                                    resp.status,
                                    text.len()
                                );
                            }
                            if sc_trace {
                                eprintln!(
                                    "[seccpt-trace] script fetch OK {} status={} bytes={}",
                                    full_url,
                                    resp.status,
                                    text.len()
                                );
                            }
                            if full_url.contains("qauth") || full_url.contains("ips.js") || full_url.contains("antibot") {
                                let safe_name = full_url.replace("/", "_").replace(":", "_").replace("?", "_");
                                let _ = std::fs::write(format!("oxide_dump/{}", safe_name), &text);
                            }
                            if text.trim_start().starts_with("<!")
                                || text.trim_start().starts_with("<html")
                            {
                                tracing::debug!(script_index = i, url = %full_url, "Script fetch returned HTML, skipping");
                                None
                            } else {
                                Some((i, text, resp.timings.clone()))
                            }
                        }
                        Ok(resp) => {
                            if dd_trace {
                                eprintln!(
                                    "[challenge-trace] i.js fetch NON-OK {} status={}",
                                    full_url, resp.status
                                );
                            }
                            if sc_trace {
                                eprintln!(
                                    "[seccpt-trace] script fetch NON-OK {} status={}",
                                    full_url, resp.status
                                );
                            }
                            tracing::warn!(script_index = i, url = %full_url, status = resp.status, "Script fetch returned non-OK status");
                            None
                        }
                        Err(e) => {
                            if dd_trace {
                                eprintln!(
                                    "[challenge-trace] i.js fetch ERR {} err={:?}",
                                    full_url, e
                                );
                            }
                            tracing::warn!(script_index = i, url = %full_url, error = ?e, "Script fetch failed");
                            None
                        }
                    }
                })
            })
            .collect();

        // Await all fetches in parallel
        let (fetched_css_results, fetched_scripts_results) = futures_util::future::join(
            futures_util::future::join_all(css_futures),
            futures_util::future::join_all(script_futures),
        )
        .await;
        mark!("subresource fetch join (css + scripts)");

        let mut all_timings = Vec::new();

        // Build stylesheet list: inline first, then fetched external
        let mut stylesheets = inline_css;
        for (css, timings) in fetched_css_results.into_iter().flatten() {
            stylesheets.push(css);
            all_timings.push(timings);
        }

        // Build pre-fetched script map
        let mut prefetched = std::collections::HashMap::new();
        for (i, text, timings) in fetched_scripts_results.into_iter().flatten() {
            prefetched.insert(i, text);
            all_timings.push(timings);
        }

        let runtime = BrowserJsRuntime::with_options(
            dom,
            BrowserRuntimeOptions {
                stealth_profile: Some(profile.clone()),
                stylesheets,
                init_scripts: init_scripts.to_vec(),
                storage,
                is_secure_context: is_secure_url(url),
                ..Default::default()
            },
        );
        let mut event_loop = BrowserEventLoop::new(runtime);
        mark!("BrowserJsRuntime::with_options (V8 isolate + bootstrap)");

        // Install all sub-resource timings
        for timings in all_timings {
            event_loop.runtime_mut().record_resource_timing(timings);
        }
        mark!("record_resource_timing");

        // Install a build-phase V8 deadline watcher to preempt CPU-bound
        // inline-script execution (delta.com, taobao.com — pages whose
        // first-paint scripts spawn document.write(<script>) chains or
        // tight setTimeout polling that hold the V8 thread indefinitely).
        // 25s is generous: any honest first-paint completes well under it.
        // Without this, build_page_with_scripts_and_init can run forever
        // because tokio::time::timeout cannot preempt V8 microtask spins.
        let build_budget_ms: u64 = std::env::var("BROWSER_OXIDE_BUILD_BUDGET_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(25_000);
        let _build_watcher = V8DeadlineWatcher::new(
            event_loop.runtime_mut().isolate_handle(),
            Duration::from_millis(build_budget_ms),
        );

        // Set location (URL-state setup, not a real navigation —
        // reset the nav-pending signal so subsequent run_until_idle calls
        // don't short-circuit immediately, see crates/event_loop).
        let url_js = url.replace('\\', "\\\\").replace('\'', "\\'");
        if let Err(e) = event_loop.execute_script(&format!("location.href = '{}';", url_js)) {
            tracing::error!(error = %e, "Failed to set location");
        }
        event_loop.reset_nav_pending();
        let loc = event_loop
            .execute_script("globalThis.location.href")
            .unwrap_or_default();
        tracing::debug!(location = %loc, "Location set");
        mark!("location.href setup + reset_nav_pending");

        // Synchronize cookies from the net client so document.cookie is accurate.
        // This is one async op (`op_cookie_get`) — it returns in ≪1 ms. The drain
        // here only needs to flush that one microtask. The previous 1 s cap was
        // pessimistic: with `humanize.js` already installed (~30 pending
        // setTimeouts that don't resolve for ~2 s), the drain hits its full
        // timeout on every navigation regardless of how trivial the page is.
        // 50 ms is more than enough for the one cookie microtask to land, and
        // the humanize timers continue firing during the outer nav-loop drain
        // where the budget is correctly allocated.
        let _ = event_loop
            .execute_and_run(
                "globalThis.__syncCookiesFromNet && globalThis.__syncCookiesFromNet();",
                Duration::from_millis(50),
            )
            .await;
        mark!("__syncCookiesFromNet");

        // Install cookie-write instrumentation. Generic DevTools-style
        // debugging — lets us see what values scripts assign to
        // `document.cookie` during the page run.
        event_loop
            .execute_script(r#"Object.defineProperty(window, '__cookieWrites', { value: [], enumerable: false, configurable: true });
            (function() {
                const proto = Document.prototype || (document && Object.getPrototypeOf(document));
                if (!proto) return;
                const desc = Object.getOwnPropertyDescriptor(proto, 'cookie');
                if (!desc || !desc.set) return;
                const origSet = desc.set;
                const origGet = desc.get;
                Object.defineProperty(proto, 'cookie', {
                    configurable: true,
                    enumerable: desc.enumerable,
                    get: function() { 
                        if (globalThis.__scriptErrors) {
                            globalThis.__scriptErrors.push('[INSTRUMENT] GET document.cookie');
                        }
                        return origGet ? origGet.call(this) : ''; 
                    },
                    set: function(v) {
                        try {
                            if (window.__cookieWrites.length < 100) {
                                window.__cookieWrites.push(String(v).substring(0, 300));
                            }
                        } catch (e) {}
                        return origSet.call(this, v);
                    },
                });
            })();"#)
            .ok();
        mark!("install cookie-write instrumentation");

        // Install error tracking + fetch/XHR logging BEFORE scripts run.
        // Generic request log, equivalent to DevTools' Network tab.
        event_loop
            .execute_script(r#"Object.defineProperty(window, '__scriptErrors', { value: [], enumerable: false, configurable: true });
            // Temporarily disable the stack filter so we can see the real
            // call sites when a TypeError fires inside a challenge VM.
            delete Error.prepareStackTrace;
            window.onerror = function(msg, src, line, col, err) {
                window.__scriptErrors.push(msg + ' @' + (src||'?') + ':' + line + '\n' + (err && err.stack || '').substring(0, 800));
            };
            window.addEventListener('unhandledrejection', function(e) {
                window.__scriptErrors.push('REJECT:' + String(e.reason).substring(0,200));
            });
            const _origFetch = globalThis.fetch;
            globalThis.fetch = async function(input, init) {
                const log = globalThis._browser_oxide && globalThis._browser_oxide.__fetchLog;
                const entry = { method: 'GET', url: '', hasBody: false };
                let args = Array.from(arguments);

                // Pre-check: reject non-fetch URL schemes BEFORE the logging
                // try/catch below (which silently swallows). Real Chrome
                // throws TypeError for fetch("ftp:"), fetch("file:"), etc.
                // ips.js uses fetch("ftp:") as a browser-authenticity canary.
                (() => {
                    let pre = '';
                    if (typeof args[0] === 'string') pre = args[0];
                    else if (args[0] && typeof args[0].url === 'string') pre = args[0].url;
                    else if (args[0] instanceof URL) pre = args[0].href;
                    const m = pre && pre.match(/^([a-z][a-z0-9+.-]*):/i);
                    if (m) {
                        const sch = m[1].toLowerCase();
                        if (!['http','https','data','blob','file','about'].includes(sch)) {
                            throw new TypeError("Failed to fetch: URL scheme \"" + sch + "\" is not supported.");
                        }
                    }
                })();

                try {
                    let urlStr = '';
                    let isRequest = false;
                    if (typeof args[0] === 'string') {
                        urlStr = args[0];
                    } else if (args[0] && typeof args[0].url === 'string') {
                        urlStr = args[0].url;
                        isRequest = true;
                    } else if (args[0] instanceof URL) {
                        urlStr = args[0].href;
                    }
                    
                    // Skip URL resolution if urlStr is already absolute
                    // (has a scheme). This prevents our URL polyfill from
                    // treating "ftp:" as a relative path.
                    const _schemeMatch = urlStr ? urlStr.match(/^([a-z][a-z0-9+.-]*):/i) : null;
                    const _scheme = _schemeMatch ? _schemeMatch[1].toLowerCase() : '';
                    // Resolve against the document base when there's no scheme —
                    // INCLUDING the empty-string url. Real Chrome resolves
                    // fetch('') / fetch('relative') against location.href; some
                    // scripts POST to fetch('') (= the document URL), and
                    // leaving it unresolved sent an empty url to the network op
                    // ("relative URL without a base"), so the request failed
                    // deterministically. Gate on a url arg actually being
                    // provided so a no-arg fetch() still throws.
                    const _urlProvided = (typeof args[0] === 'string')
                        || (args[0] instanceof URL)
                        || (args[0] && typeof args[0].url === 'string');
                    if (_urlProvided && !_scheme) {
                        try {
                            let base = globalThis.location ? globalThis.location.href : 'about:blank';
                            if (base === 'about:blank' || base === 'javascript:;' || base === '') {
                                try { base = globalThis.parent.location.href; } catch(e) {}
                            }
                            // Empty url resolves to the document URL itself (real
                            // Chrome: fetch('') hits location.href). Handle it
                            // explicitly — our URL polyfill throws on `new
                            // URL('', base)`, which the catch below was silently
                            // swallowing, leaving the empty url to fail at the
                            // network op.
                            urlStr = (urlStr === '') ? base : new URL(urlStr, base).href;
                            if (isRequest) {
                                // Recreate Request with absolute URL. Preserve all properties from the original.
                                args[0] = new Request(urlStr, args[0]);
                            } else {
                                args[0] = urlStr;
                            }
                        } catch(e) {
                            if (globalThis.__scriptErrors) {
                                globalThis.__scriptErrors.push('fetch url resolve error: ' + e.message);
                            }
                        }
                    }
                    entry.url = String(urlStr || '').substring(0, 200);
                    entry.method = (init && init.method) || (isRequest && args[0].method) || 'GET';
                    entry.hasBody = !!((init && init.body) || (isRequest && args[0].body));
                    // Capture request body for error reporter diagnosis.
                    if (init && init.body != null) {
                        try {
                            const b = init.body;
                            if (typeof b === 'string') {
                                entry.body = b.substring(0, 1000);
                            } else if (b instanceof ArrayBuffer || ArrayBuffer.isView(b)) {
                                const u8 = b instanceof Uint8Array ? b : new Uint8Array(b.buffer || b, b.byteOffset || 0, b.byteLength);
                                let s = '';
                                const max = Math.min(u8.length, 400);
                                for (let i = 0; i < max; i++) s += String.fromCharCode(u8[i]);
                                entry.body = '[bytes:' + u8.length + '] ' + s;
                            } else {
                                entry.body = String(b).substring(0, 400);
                            }
                        } catch {}
                    }
                    const hdrs = {};
                    const h = (init && init.headers) || {};
                    if (h && typeof h.forEach === 'function') {
                        h.forEach((v, k) => { hdrs[k] = String(v); });
                    } else if (h) {
                        for (const k in h) hdrs[k] = String(h[k]);
                    }
                    entry.reqHeaders = hdrs;
                } catch {}
                const log = globalThis._browser_oxide && globalThis._browser_oxide.__fetchLog;
                if (log) log.push(entry);
                try {
                    const resp = await _origFetch.apply(this, args);
                    entry.status = resp.status;
                    try {
                        const respHdrs = {};
                        if (resp.headers && typeof resp.headers.forEach === 'function') {
                            resp.headers.forEach((v, k) => { respHdrs[String(k).toLowerCase()] = String(v).substring(0, 300); });
                        } else if (resp.headers) {
                            for (const k in resp.headers) {
                                respHdrs[String(k).toLowerCase()] = String(resp.headers[k]).substring(0, 300);
                            }
                        }
                        entry.respHeaders = respHdrs;
                    } catch {}
                    return resp;
                } catch (e) {
                    entry.error = String(e && e.message || e).substring(0, 200);
                    throw e;
                }
            };
            // Also wrap XMLHttpRequest.send so XHR requests appear in __fetchLog.
            // This is critical for SDKs that use sync XHR for token fetches.
            (function() {
                const _XHR = globalThis.XMLHttpRequest;
                if (!_XHR) return;
                const _origOpen = _XHR.prototype.open;
                const _origSend = _XHR.prototype.send;
                _XHR.prototype.open = function(method, url, async) {
                    this.__logEntry = { method: String(method||'GET').toUpperCase(), url: String(url||''), sync: async === false };
                    return _origOpen.apply(this, arguments);
                };
                _XHR.prototype.send = function(body) {
                    const entry = this.__logEntry || { method: this._method||'GET', url: this._url||'', sync: !this._async };
                    entry.hasBody = body != null && body !== '';
                    const log = globalThis._browser_oxide && globalThis._browser_oxide.__fetchLog;
                if (log) log.push(entry);
                    const _origRSC = this.onreadystatechange;
                    const self = this;
                    const _finish = function() {
                        if (self.readyState === 4) entry.status = self.status;
                    };
                    const prev = this.onreadystatechange;
                    this.onreadystatechange = function() {
                        _finish();
                        if (prev) prev.apply(this, arguments);
                    };
                    return _origSend.apply(this, arguments);
                };
            })();"#)
            .ok();
        mark!("install error + fetch/XHR instrumentation");

        // Re-mark the global-namespace baseline now that every engine-owned
        // global exists — bootstrap's own (marked at the end of
        // cleanup_bootstrap.js) plus the instrumentation installed just
        // above, which is install-once and is NOT re-applied on the warm
        // path. Anything present after this line belongs to the engine;
        // anything a page adds later is what `Page::reset_for_reuse`
        // (`__resetPageGlobals`) sweeps. Must run BEFORE the page's own
        // scripts, which start below.
        event_loop
            .execute_script(
                "globalThis.__markGlobalsBaseline && globalThis.__markGlobalsBaseline();",
            )
            .ok();
        mark!("__markGlobalsBaseline");

        // If the initial document is an anti-bot
        // challenge (AWS-WAF / sec-cpt / one of the other vendors), keep all
        // long timers refed for this page so the self-solve's
        // `chlg_duration` wait + deferred PoW-worker continuation pin the
        // event loop instead of being unref'd at UNREF_THRESHOLD_MS=2000
        // (timer_bootstrap.js). Must be set BEFORE the page scripts run so
        // challenge.js's setTimeout calls see the flag at schedule time.
        // Narrow predicate set ⇒ false for every benign nav ⇒ no x.com /
        // twitter SPA-unref regression.
        let doc_is_challenge = is_awswaf_challenge(html)
            || is_interstitial_challenge(html)
            || html.contains("sec-if-cpt-container")
            || html.contains("sec-cpt-if")
            || crate::classify::is_managed_challenge_doc(html);
        if doc_is_challenge {
            let _ = event_loop.execute_script("globalThis.__keepLongTimersRefed = true;");
        }

        // Execute scripts in document order using pre-fetched code.
        // Interleave with event loop ticks to allow for microtasks and
        // macrotasks scheduled by one script to run before the next.
        for (i, script) in scripts.iter().enumerate() {
            let code = if script.src.is_some() {
                match prefetched.get(&i) {
                    Some(code) => code.clone(),
                    None => {
                        tracing::warn!(
                            script_index = i,
                            "Script not prefetched (fetch failed), skipping"
                        );
                        continue;
                    }
                }
            } else {
                script.code.clone()
            };

            if code.trim().is_empty() {
                continue;
            }

            let name = if let Some(src) = &script.src {
                src.clone()
            } else {
                // Real Chrome inline <script> stack frames report the
                // document URL, not a synthetic <script_N> tag. The
                // latter would leak the index/wrapper layer to a
                // challenge vendor's sensor.
                url.to_string()
            };

            if script.is_module {
                // P2 — `<script type="module">`: execute via the ES-module
                // loader (resolves + fetches the import graph) instead of
                // classic `v8::Script::compile`, which throws
                // `SyntaxError: Cannot use import statement outside a module`
                // and drops modern Vite/React/Vue bundles (the thin-render gap).
                // BOUND the module eval: a module whose import graph stalls (a
                // dep that never resolves) or whose top-level work never idles
                // must NOT hang the whole navigation. 10s/module is generous;
                // on timeout we log and continue so the page renders what it has.
                let eval_fut = async {
                    if let Some(src) = &script.src {
                        // External module: resolve src to an absolute specifier;
                        // reuse the prefetched entry, loader fetches the imports.
                        let module_url = url::Url::parse(url)
                            .ok()
                            .and_then(|base| base.join(src).ok())
                            .map(|u| u.to_string())
                            .unwrap_or_else(|| src.clone());
                        event_loop.eval_module_code(&module_url, code.clone()).await
                    } else {
                        // Inline module: unique specifier whose path is the doc
                        // URL so its relative imports resolve against the document.
                        let spec = format!("{url}#oxide-mod-{i}");
                        event_loop.eval_module_code(&spec, code.clone()).await
                    }
                };
                match tokio::time::timeout(Duration::from_secs(10), eval_fut).await {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => {
                        tracing::warn!(script = %name, error = %e, "ES module eval error")
                    }
                    Err(_) => {
                        tracing::warn!(script = %name, "ES module eval timed out (10s) — continuing")
                    }
                }
            } else {
                // Classic script. Set document.currentScript to THIS <script>
                // element's wrapper for the duration of execution (the web-API
                // contract: currentScript is the running classic script, null
                // for modules and outside execution). Scripts that locate their
                // own <script> via document.currentScript (to read a data-*
                // attribute or resolve a relative path) get null otherwise and
                // silently stall. The _wrapNode/_setCurrentScript hooks already
                // exist + are exported; this is the missing call site.
                let _ = event_loop.execute_script(&format!(
                    "globalThis.__browser_oxide._setCurrentScript(globalThis.__browser_oxide._wrapNode({}))",
                    script.node_id
                ));
                if let Err(e) = event_loop.execute_script_with_name(&code, &name) {
                    tracing::warn!(script = %name, error = %e, "Script execution error");
                }
                let _ =
                    event_loop.execute_script("globalThis.__browser_oxide._setCurrentScript(null)");
            }

            // Flush logs for this script
            {
                let _ = &script.src;
                let logs = {
                    let runtime = event_loop.runtime_mut().inner();
                    let state = runtime.op_state();
                    let mut state = state.borrow_mut();
                    let dom_state = state.borrow_mut::<crate::js_runtime::state::DomState>();
                    std::mem::take(&mut dom_state.console_output)
                };
                for log in logs {
                    let prefix = match log.level {
                        crate::js_runtime::state::ConsoleLevel::Log => "[JS LOG]",
                        crate::js_runtime::state::ConsoleLevel::Warn => "[JS WARN]",
                        crate::js_runtime::state::ConsoleLevel::Error => "[JS ERROR]",
                        _ => "[JS INFO]",
                    };
                    tracing::debug!(level = prefix, message = %log.args.join(" "), "JS console output");
                }
            }

            // Run loop for a short burst between scripts to flush tasks
            let _ = event_loop.run_until_idle(Duration::from_millis(50)).await;
        }
        mark!("inline scripts + interleaved drains");

        // Final cleanup — hides Deno and internal globals from user JS.
        event_loop
            .execute_script(include_str!("js_runtime/js/cleanup_bootstrap.js"))
            .ok();
        mark!("cleanup_bootstrap.js");

        // Fire DOMContentLoaded and load events via setTimeout so they execute
        // within the event loop (not synchronously during script setup).
        // This ensures async handlers can create Promises that the event loop tracks.
        event_loop
            .execute_script(
                r#"
            setTimeout(() => {
                // Advance the document lifecycle: loading -> interactive
                // (DOMContentLoaded) -> complete (load). The navigate build
                // path previously left __documentReadyState at the bootstrap
                // default 'loading', so document.readyState NEVER reached
                // 'complete' for any navigated page — frameworks that gate
                // mounting on readyState==='complete' (or poll it) would
                // spin/never mount. Fire readystatechange on each transition.
                try { globalThis._browser_oxide.__documentReadyState = 'interactive'; } catch (_e) {}
                document.dispatchEvent(new Event('readystatechange'));
                document.dispatchEvent(new Event('DOMContentLoaded', {bubbles: true}));
                window.dispatchEvent(new Event('DOMContentLoaded', {bubbles: true}));
                try { globalThis._browser_oxide.__documentReadyState = 'complete'; } catch (_e) {}
                document.dispatchEvent(new Event('readystatechange'));
                window.dispatchEvent(new Event('load'));
            }, 0);
        "#,
            )
            .ok();

        mark!("DOMContentLoaded/load setTimeout install");

        // Scan for <meta http-equiv="refresh" content="N;url=..."> and
        // schedule a pending navigation. Generic navigation primitive —
        // the Rust driver loop sees __pendingNavigation and re-fetches.
        event_loop
            .execute_script(r#"
            (function() {
                const metas = document.getElementsByTagName('meta');
                for (let i = 0; i < metas.length; i++) {
                    const m = metas[i];
                    const equiv = String(m.getAttribute('http-equiv') || '').toLowerCase();
                    if (equiv !== 'refresh') continue;
                    const content = String(m.getAttribute('content') || '');
                    const match = content.match(/^\s*(\d+)(?:\s*[;,]\s*url\s*=\s*(.+))?$/i);
                    if (!match) continue;
                    const delay = parseInt(match[1], 10) || 0;
                    const target = ((match[2] || '').trim()).replace(/^['"]|['"]$/g, '') || location.href;
                    setTimeout(() => {
                        globalThis.__pendingNavigation = {
                            url: target,
                            kind: 'assign',
                        };
                        // Wake the Rust event loop — see nav_ext.rs.
                        try { Deno.core.ops.op_set_pending_nav(); } catch (_) {}
                    }, delay * 1000);
                    break;
                }
            })();
        "#)
            .ok();

        mark!("meta-refresh scanner install");

        // Run event loop until idle. Script errors should NOT abort
        // navigation — log and continue, matching real browser behavior.
        //
        // 8 s cap. This drain flushes microtasks, zero-delay setTimeouts
        // (DOMContentLoaded / load handlers, meta-refresh scanner), and
        // any short async chains kicked off by inline scripts.
        //
        // Important: `humanize.js` now schedules its synthetic mouse /
        // scroll timers via `globalThis.__bgSetTimeout` (timer_bootstrap.js)
        // which is `.unref()`'d — so the humanize setTimeouts no longer
        // pin this drain to its full ceiling. Benign pages exit idle in
        // milliseconds; anti-bot challenge pages (AWS WAF / reddit verify /
        // recaptcha invisible / a vendor interstitial) get the full 8 s they need for
        // their async POST+reload chain to complete, which sets
        // `__pendingNavigation` and triggers iter 1 with the proper token
        // cookie. Cutting this below ~5 s causes those chains to never
        // complete and the outer loop returns the challenge stub as the
        // "rendered" page.
        if let Err(e) = event_loop.run_until_idle(Duration::from_secs(8)).await {
            tracing::warn!(error = %e, "Event loop error during run");
        }
        mark!("build-phase run_until_idle");

        // Log errors captured during script execution
        if let Ok(errors) = event_loop.execute_script("JSON.stringify(window.__scriptErrors || [])")
        {
            if errors != "[]" {
                let trimmed: String = errors.chars().take(500).collect();
                tracing::warn!(errors = %trimmed, "Script errors during page run");
            }
        }

        // Dump any cookie-set assignments that scripts made during the run.
        if let Ok(cookie_writes) =
            event_loop.execute_script("JSON.stringify(window.__cookieWrites || [])")
        {
            if cookie_writes != "[]" && !cookie_writes.is_empty() {
                use deno_core::serde_json;
                if let Ok(arr) = serde_json::from_str::<serde_json::Value>(&cookie_writes) {
                    if let Some(arr) = arr.as_array() {
                        tracing::debug!(count = arr.len(), "Cookie writes");
                        for (i, w) in arr.iter().take(20).enumerate() {
                            if let Some(s) = w.as_str() {
                                let trim: String = s.chars().take(140).collect();
                                tracing::debug!(index = i, value = %trim, "Cookie write");
                            }
                        }
                    }
                }
            }
        }
        // Dump a one-line summary of every fetch the page made during
        // the run — equivalent to DevTools' Network tab.
        if let Ok(fetches_json) = event_loop.execute_script(
            r#"JSON.stringify((window.__fetchLog || []).map(f => ({
                m: f.method,
                u: f.url,
                s: f.status,
                e: f.error,
            })))"#,
        ) {
            if fetches_json != "[]" {
                use deno_core::serde_json;
                if let Ok(arr) = serde_json::from_str::<serde_json::Value>(&fetches_json) {
                    if let Some(arr) = arr.as_array() {
                        tracing::debug!(count = arr.len(), "Page fetches");
                        for f in arr {
                            let m = f.get("m").and_then(|v| v.as_str()).unwrap_or("");
                            let u = f.get("u").and_then(|v| v.as_str()).unwrap_or("");
                            let s = f.get("s").and_then(|v| v.as_u64()).unwrap_or(0);
                            let e = f.get("e").and_then(|v| v.as_str()).unwrap_or("");
                            let u_trim: String = u.chars().take(100).collect();
                            if s == 0 {
                                tracing::warn!(method = m, status = s, url = %u_trim, error = e, "Page fetch failed");
                            } else {
                                tracing::debug!(method = m, status = s, url = %u_trim, "Page fetch");
                            }
                        }
                    }
                }
            }
        }

        // Process iframes (srcdoc and src)
        let mut children = Vec::new();
        let iframes = {
            let dom_ref = event_loop.runtime_mut().inner();
            let state = dom_ref.op_state();
            let state = state.borrow();
            let dom_state = state.borrow::<crate::js_runtime::state::DomState>();
            iframe::find_iframes(&dom_state.dom)
        };
        for info in &iframes {
            if let Some(srcdoc) = &info.srcdoc {
                match iframe::ChildIframe::from_srcdoc(info.node_id, srcdoc, profile).await {
                    Ok(child) => children.push(child),
                    Err(e) => tracing::warn!(error = %e, "iframe srcdoc error"),
                }
            } else if let Some(src) = &info.src {
                if !src.is_empty() && !src.starts_with("javascript:") {
                    if let Some(full_src) = Self::resolve_url(url, src) {
                        match iframe::ChildIframe::from_url(
                            info.node_id,
                            &full_src,
                            client,
                            Some(profile),
                        )
                        .await
                        {
                            Ok(child) => children.push(child),
                            Err(e) => {
                                tracing::warn!(src = %full_src, error = %e, "iframe src error")
                            }
                        }
                    }
                } else if src.starts_with("javascript:") {
                    // javascript:; or similar — create a blank frame so it can be written to
                    match iframe::ChildIframe::from_srcdoc(
                        info.node_id,
                        "<!DOCTYPE html><html><body></body></html>",
                        profile,
                    )
                    .await
                    {
                        Ok(child) => children.push(child),
                        Err(e) => tracing::warn!(error = %e, "iframe javascript blank error"),
                    }
                }
            }
        }

        // Cancel the build-phase watcher's terminate so the runtime is
        // usable for the drain phase (and downstream execute_script calls).
        // Drop the watcher first to stop the thread; then cancel any
        // pending termination on the isolate.
        drop(_build_watcher);
        event_loop.runtime_mut().cancel_terminate_execution();
        mark!("post-drain summary + iframes + watcher cleanup [DONE]");

        Ok(Self {
            event_loop,
            url: url.to_string(),
            children,
            solvers: std::sync::Arc::from(Vec::<std::sync::Arc<dyn crate::ChallengeSolver>>::new()),
        })
    }

    /// Consume the page and return the DOM.
    pub fn take_dom(mut self) -> Dom {
        // Drop children first (V8 reverse order requirement)
        self.children.clear();
        // Use ManuallyDrop to prevent the Drop impl from running
        let page = std::mem::ManuallyDrop::new(self);
        // SAFETY: `page` is `ManuallyDrop`, so its destructor will not
        // run and won't double-drop the bytes we read out of it.
        // `event_loop` is read by value exactly once via `ptr::read`,
        // and nothing else touches it after this — the surrounding
        // `ManuallyDrop` ensures the original location is never used
        // again (no aliasing, no double-free). The `children` field
        // that the event loop depends on was already cleared above
        // per V8's reverse-drop-order requirement.
        unsafe {
            let event_loop = std::ptr::read(&page.event_loop);
            event_loop.take_dom()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `is_interstitial_challenge` must catch a typical
    /// `rt:'i'` interstitial (small body + a captcha-delivery.com script).
    #[test]
    fn interstitial_challenge_detects_interstitial() {
        let interstitial = r#"<html><head><script src="https://geo.captcha-delivery.com/c"></script></head><body></body></html>"#;
        assert!(is_interstitial_challenge(interstitial));
    }

    #[test]
    fn geo_country_splash_follows_same_host_region_link() {
        // bestbuy "Select your Country" splash: follow the same-host root link
        // with the splash-skip query (the US link), NOT the off-host Canada link
        // and NOT the non-root more-details help link.
        let splash = r#"<html><body><h1>Best Buy International: Select your Country</h1>
            <a href="https://www.bestbuy.ca/en-ca?intlredir=x" class="canada-link">Canada</a>
            <a href="https://www.bestbuy.com/?intl=nosplash" class="us-link">United States</a>
            <a href="https://www.bestbuy.com/site/help-topics/international-orders/x.c?intl=nosplash" class="more-details">More</a>
            </body></html>"#;
        assert_eq!(
            geo_country_splash_target(splash, "https://www.bestbuy.com/").as_deref(),
            Some("https://www.bestbuy.com/?intl=nosplash")
        );
        // A normal storefront page (no country-selection phrase) is never followed.
        let store = r#"<html><body><h1>Top Deals</h1><a href="https://www.bestbuy.com/?x=1">cart</a></body></html>"#;
        assert_eq!(
            geo_country_splash_target(store, "https://www.bestbuy.com/"),
            None
        );
        // A large page that merely contains the phrase is above the size gate.
        let mut big = String::from("<html><body>select your country");
        big.push_str(&"<div>real product card</div>".repeat(2000));
        big.push_str("</body></html>");
        assert!(big.len() > 30_000);
        assert_eq!(
            geo_country_splash_target(&big, "https://www.bestbuy.com/"),
            None
        );
    }

    /// Legitimate page that mentions captcha-delivery.com in a benign
    /// context (e.g. CSP report-uri or text content) must NOT be flagged.
    /// We rely on the 50 KB size gate to differentiate the small
    /// interstitial from a full rendered page.
    #[test]
    fn interstitial_challenge_size_gates_false_positive() {
        let mut big = String::from("<html><body>");
        // 60 KB filler text containing the substring
        big.push_str(&"x".repeat(60_000));
        big.push_str("captcha-delivery.com (mentioned in passing)");
        big.push_str("</body></html>");
        assert!(!is_interstitial_challenge(&big));
    }

    /// A vanilla rendered page with no vendor substring is not a challenge.
    #[test]
    fn interstitial_challenge_rejects_non_interstitial_body() {
        let html =
            r#"<html><head><title>Real Site</title></head><body><h1>Welcome</h1></body></html>"#;
        assert!(!is_interstitial_challenge(html));
    }

    /// An 8-50 KB body that references captcha-delivery.com but has NO
    /// vendor-config structural token is a real page (e.g. CSP report-uri), NOT a
    /// challenge; adding the `dd={…'rt'…'cid'…}` config flips it to challenge.
    #[test]
    fn interstitial_challenge_midsize_needs_config() {
        let mut page = String::from("<html><body>");
        page.push_str(&"content ".repeat(2000)); // ~16 KB of real content
        page.push_str("<!-- csp report-uri https://x.captcha-delivery.com/ -->");
        page.push_str("</body></html>");
        assert!(page.len() > 8_000 && page.len() < 50_000);
        assert!(
            !is_interstitial_challenge(&page),
            "mid-size real page with only the CDN string must NOT flag"
        );
        page.push_str("<script>var dd={'rt':'i','cid':'abc','hsh':'X'};</script>");
        assert!(
            is_interstitial_challenge(&page),
            "DD-config token => interstitial"
        );
        // tiny body with the CDN is still unambiguously the interstitial
        let tiny = r#"<html><head><script src="https://geo.captcha-delivery.com/c.js"></script></head><body></body></html>"#;
        assert!(tiny.len() < 8_000 && is_interstitial_challenge(tiny));
    }

    /// `is_interstitial_solved` requires BOTH the `datadome=` cookie AND a
    /// body that is no longer an interstitial. The cookie alone is
    /// not a solve marker (FP-D3: the vendor sets the cookie on every nav incl.
    /// the failing 403).
    #[test]
    fn interstitial_solved_requires_cookie_and_clean_body() {
        let real_body = "<html><body><h1>Real Page</h1></body></html>";
        let interstitial = r#"<html><body><script src="https://geo.captcha-delivery.com/c"></script></body></html>"#;

        // Cookie + real body → solved.
        assert!(is_interstitial_solved("datadome=abc123", real_body));

        // Cookie + interstitial body → NOT solved (still on the challenge).
        assert!(!is_interstitial_solved("datadome=abc123", interstitial));

        // No cookie + real body → NOT solved (we never saw a token).
        assert!(!is_interstitial_solved("session=x; other=y", real_body));
    }

    /// `is_seccpt_solved` requires
    /// (a) the `sec_cpt=` cookie, (b) the `~3~` success-state marker
    /// inside the cookie, AND (c) a body that has TRANSITIONED out of
    /// the sec-cpt challenge page (real homepage, no
    /// `sec-if-cpt-container` / `sec-cpt-if` markers).
    #[test]
    fn seccpt_solved_requires_marker_and_clean_body() {
        let challenge_body = r#"<html><body><div id="sec-if-cpt-container"></div><script src="/qjBo8d0vY/..."></script></body></html>"#;
        let real_body = "<html><body><h1>The Home Depot</h1>main content</body></html>";

        // Solved cookie + real body → SOLVED.
        assert!(is_seccpt_solved(
            "sec_cpt=ABC123~3~XYZ; AKA_A2=A",
            real_body
        ));

        // Solved cookie BUT still-on-challenge body → NOT solved.
        assert!(!is_seccpt_solved("sec_cpt=ABC123~3~XYZ", challenge_body));

        // Cookie missing `~3~` marker (state ~1~ or ~2~) → NOT solved.
        assert!(!is_seccpt_solved("sec_cpt=ABC123~1~XYZ", real_body));
        assert!(!is_seccpt_solved("sec_cpt=ABC123~0~XYZ", real_body));

        // No `sec_cpt=` cookie → NOT solved.
        assert!(!is_seccpt_solved("session=x; other=~3~", real_body));

        // Empty cookies + real body → NOT solved.
        assert!(!is_seccpt_solved("", real_body));
    }

    /// The AWS-WAF challenge/solve predicates that
    /// arm the navigate-loop poll + cookie-diff retry. The stub must be
    /// recognized as a challenge; a solve requires both the
    /// `aws-waf-token` cookie AND a body that is no longer the stub.
    #[test]
    fn awswaf_challenge_and_solve_predicates() {
        let stub = r#"<html><head><script>window.awsWafCookieDomainList=[];window.gokuProps={"key":"AQ=="};</script><script src="https://x.token.awswaf.com/x/challenge.js"></script></head><body><script>AwsWafIntegration.checkForceRefresh().then(()=>{});</script></body></html>"#;
        let real_body = "<html><body><h1>Amazon.com</h1>product listings here</body></html>";

        // The ~2 KB stub is a challenge.
        assert!(is_awswaf_challenge(stub));
        // Real content (no envelope vars) is not.
        assert!(!is_awswaf_challenge(real_body));
        // A large body carrying the markers is NOT matched by the <4096
        // gate (that grown-shell case is INVERSE-CHL's job in classify.rs).
        let mut grown = String::from(stub);
        while grown.len() < 5000 {
            grown.push_str("<div>padding</div>");
        }
        assert!(!is_awswaf_challenge(&grown));

        // Solve = token cookie present AND body no longer the stub.
        assert!(is_awswaf_solved(
            "aws-waf-token=abc.def.ghi; other=1",
            real_body
        ));
        // Token cookie but still on the stub → NOT solved.
        assert!(!is_awswaf_solved("aws-waf-token=abc.def.ghi", stub));
        // No token cookie → NOT solved.
        assert!(!is_awswaf_solved("session=x", real_body));
        assert!(!is_awswaf_solved("", real_body));
    }

    /// Regression: a JS-side `location.href = 'about:blank'` (or any
    /// other special-scheme URL) must NOT cause the navigate loop to
    /// fetch `https://host/about:blank`. Caught on iphey.com where the
    /// URL polyfill mis-joined the special scheme and broke same-page
    /// rendering (THIN-BODY 901b instead of L3-RENDERED 29 KB).
    #[test]
    fn resolve_url_rejects_special_scheme_relative() {
        // Bare special-scheme strings → no-op
        assert_eq!(Page::resolve_url("https://iphey.com/", "about:blank"), None);
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "data:text/html,<p>x</p>"),
            None
        );
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "javascript:void(0)"),
            None
        );
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "blob:https://x/y"),
            None
        );
        // Path-encoded special schemes (the iphey symptom — pending URL
        // arrives as the literal "https://iphey.com/about:blank") → no-op
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "https://iphey.com/about:blank"),
            None
        );
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "/about:blank"),
            None
        );
        // Normal navigations are unaffected
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "/page2"),
            Some("https://iphey.com/page2".to_string())
        );
        assert_eq!(
            Page::resolve_url("https://iphey.com/", "https://other.example/foo"),
            Some("https://other.example/foo".to_string())
        );
    }

    #[tokio::test]
    async fn page_from_html_basic() {
        let mut page = Page::from_html(
            "<html><head><title>Test</title></head><body><p>Hello</p></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        assert_eq!(page.title(), "Test");
        assert_eq!(page.text_of("p"), Some("Hello".to_string()));
    }

    #[tokio::test]
    async fn page_script_execution() {
        let mut page = Page::from_html("<html><head></head><body><div id='target'></div><script>document.getElementById('target').textContent = 'JS works!';</script></body></html>", None::<crate::stealth::StealthProfile>).await.unwrap();
        assert_eq!(page.text_of("#target"), Some("JS works!".to_string()));
    }

    #[tokio::test]
    async fn page_script_creates_elements() {
        let mut page = Page::from_html(
            r#"<html><head></head><body>
                <script>
                    const p = document.createElement('p');
                    p.setAttribute('id', 'created');
                    p.textContent = 'Dynamic content';
                    document.body.appendChild(p);
                </script>
            </body></html>"#,
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        assert!(page.has_element("#created"));
        assert_eq!(
            page.text_of("#created"),
            Some("Dynamic content".to_string())
        );
    }

    #[tokio::test]
    async fn page_script_modifies_inner_html() {
        let mut page = Page::from_html(r#"<html><head></head><body>
                <div id="container"></div>
                <script>
                    document.getElementById('container').innerHTML = '<span class="inner">Injected</span>';
                </script>
            </body></html>"#, None::<crate::stealth::StealthProfile>)
        .await
        .unwrap();
        assert_eq!(page.text_of(".inner"), Some("Injected".to_string()));
    }

    #[tokio::test]
    async fn page_with_timeout_script() {
        let mut page = Page::from_html(
            r#"<html><head></head><body>
                <div id="output">before</div>
                <script>
                    setTimeout(() => {
                        document.getElementById('output').textContent = 'after';
                    }, 50);
                </script>
            </body></html>"#,
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        assert_eq!(page.text_of("#output"), Some("after".to_string()));
    }

    #[tokio::test]
    async fn page_evaluate() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let result = page.evaluate("1 + 2").unwrap();
        assert_eq!(result, "3");
    }

    #[tokio::test]
    async fn page_navigator_exists() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let result = page.evaluate("typeof navigator.userAgent").unwrap();
        assert_eq!(result, "string");
    }

    #[tokio::test]
    async fn page_document_has_focus() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let result = page.evaluate("document.hasFocus()").unwrap();
        assert_eq!(result, "true");
    }

    #[tokio::test]
    async fn page_webdriver_false() {
        // Modern Chrome (>=89, incl. Chrome-148): navigator.webdriver
        // === false for normal browsing — real Chrome reports the
        // boolean `false`, not `undefined`, so we match that for fidelity.
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let result = page.evaluate("typeof navigator.webdriver").unwrap();
        assert_eq!(result, "boolean");
        let val = page.evaluate("navigator.webdriver").unwrap();
        assert_eq!(val, "false");
    }

    #[tokio::test]
    async fn page_window_dimensions() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let w = page.evaluate("window.innerWidth").unwrap();
        assert_eq!(w, "1920");
        let h = page.evaluate("window.innerHeight").unwrap();
        assert_eq!(h, "1080");
    }

    /// Real Chrome returns the viewport (innerWidth × innerHeight) for
    /// `documentElement.clientWidth/Height`, not the full document size.
    /// Regression-locks the dom_bootstrap HTMLHtmlElement.prototype
    /// clientWidth/Height override.
    #[tokio::test]
    async fn document_element_client_dims_are_viewport_clipped() {
        let mut page = Page::from_html(
            "<html><head></head><body><div style=\"height:50000px\"></div></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let cw = page
            .evaluate("document.documentElement.clientWidth")
            .unwrap();
        let ch = page
            .evaluate("document.documentElement.clientHeight")
            .unwrap();
        assert_eq!(
            cw, "1920",
            "documentElement.clientWidth must equal innerWidth, got {cw}"
        );
        assert_eq!(
            ch, "1080",
            "documentElement.clientHeight must equal innerHeight, got {ch}"
        );
    }

    /// Real Chrome on macOS exposes the `window.ApplePaySession`
    /// constructor; we match that on the macOS UA for fidelity.
    /// Regression-locks the macOS-conditional shim in window_bootstrap.
    #[tokio::test]
    async fn apple_pay_session_present_on_macos_profile() {
        // ApplePaySession is gated on isSecureContext so the
        // page must be loaded over https:// for the macOS shim to install.
        let profile = crate::stealth::presets::chrome_148_macos();
        let mut page = Page::from_html_with_url(
            "<html><head></head><body></body></html>",
            "https://example.com/",
            Some(profile),
        )
        .await
        .unwrap();
        let t = page.evaluate("typeof ApplePaySession").unwrap();
        assert_eq!(
            t, "function",
            "macOS profile must expose ApplePaySession constructor"
        );
        let cmp = page.evaluate("ApplePaySession.canMakePayments()").unwrap();
        assert_eq!(cmp, "true");
        let v = page.evaluate("ApplePaySession.supportsVersion(3)").unwrap();
        assert_eq!(v, "true");
    }

    #[tokio::test]
    async fn apple_pay_session_absent_on_windows_profile() {
        let profile = crate::stealth::presets::chrome_148_windows();
        let mut page = Page::from_html("<html><head></head><body></body></html>", Some(profile))
            .await
            .unwrap();
        let t = page.evaluate("typeof ApplePaySession").unwrap();
        assert_eq!(
            t, "undefined",
            "Windows profile must NOT expose ApplePaySession"
        );
    }

    /// macOS profile: Helvetica Neue and Arial are both installed,
    /// each must produce a distinct width from sans-serif baseline AND
    /// from each other.
    ///
    /// Ignored: needs real `canvas.getContext('2d')` font-metrics — the
    /// `Page::from_html` test harness initialises a context that can't
    /// resolve named font families, so the assertion fails in the
    /// default test env even though the behaviour is correct against a
    /// real browser. Run with `--ignored` after wiring a fuller canvas
    /// context into the unit-test harness.
    #[tokio::test]
    #[ignore = "needs real canvas getContext in the test harness"]
    async fn canvas_font_detection_macos_helvetica_neue() {
        let profile = crate::stealth::presets::chrome_148_macos();
        let mut page = Page::from_html(
            "<html><head></head><body><canvas id=\"c\" width=\"200\" height=\"50\"></canvas></body></html>",
            Some(profile),
        )
        .await
        .unwrap();
        let script = r#"
            (() => {
                const ctx = document.getElementById('c').getContext('2d');
                ctx.font = "16px sans-serif";
                const a = ctx.measureText("mmmmmmmmmlli").width;
                ctx.font = "16px Arial";
                const b = ctx.measureText("mmmmmmmmmlli").width;
                ctx.font = "16px 'Helvetica Neue'";
                const c = ctx.measureText("mmmmmmmmmlli").width;
                ctx.font = "16px Calibri";
                const d = ctx.measureText("mmmmmmmmmlli").width;
                return JSON.stringify({
                    arial_installed: Math.abs(a-b) > 1e-3,
                    hn_installed: Math.abs(a-c) > 1e-3,
                    distinct_from_arial: Math.abs(b-c) > 1e-3,
                    calibri_not_installed_on_macos: Math.abs(a-d) < 1e-3,
                });
            })()
        "#;
        let r = page.evaluate(script).unwrap();
        assert!(
            r.contains("\"arial_installed\":true"),
            "Arial must be installed on macOS: {r}"
        );
        assert!(
            r.contains("\"hn_installed\":true"),
            "Helvetica Neue must be installed on macOS: {r}"
        );
        assert!(
            r.contains("\"distinct_from_arial\":true"),
            "HN must differ from Arial: {r}"
        );
        assert!(
            r.contains("\"calibri_not_installed_on_macos\":true"),
            "Calibri must not be installed on macOS: {r}"
        );
    }

    /// Canvas-based font detection: measureText widths must differ between
    /// distinct named families and the bare generic, otherwise sensors
    /// report `fonts=null`. The dom canvas2d backend
    /// aliases everything to Liberation Sans; the canvas_bootstrap shim
    /// adds a deterministic per-family micro-delta to keep widths unique.
    ///
    /// Ignored: same canvas-getContext harness limitation as
    /// `canvas_font_detection_macos_helvetica_neue` above.
    #[tokio::test]
    #[ignore = "needs real canvas getContext in the test harness"]
    async fn canvas_measure_text_distinguishes_named_fonts() {
        let mut page = Page::from_html(
            "<html><head></head><body><canvas id=\"c\" width=\"200\" height=\"50\"></canvas></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let script = r#"
            (() => {
                const ctx = document.getElementById('c').getContext('2d');
                ctx.font = "16px sans-serif";
                const a = ctx.measureText("mmmmmmmmmlli").width;
                ctx.font = "16px Arial";
                const b = ctx.measureText("mmmmmmmmmlli").width;
                ctx.font = "16px 'Helvetica Neue'";
                const c = ctx.measureText("mmmmmmmmmlli").width;
                return JSON.stringify({a, b, c, ab: Math.abs(a-b) > 1e-3, bc: Math.abs(b-c) > 1e-3});
            })()
        "#;
        let r = page.evaluate(script).unwrap();
        assert!(
            r.contains("\"ab\":true"),
            "Arial must measure differently than sans-serif: {r}"
        );
        assert!(
            r.contains("\"bc\":true"),
            "Helvetica Neue must measure differently than Arial: {r}"
        );
    }

    #[tokio::test]
    async fn page_local_storage() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        page.evaluate("localStorage.setItem('key', 'value')")
            .unwrap();
        let result = page.evaluate("localStorage.getItem('key')").unwrap();
        assert_eq!(result, "value");
    }

    #[tokio::test]
    async fn page_crypto_random() {
        let mut page = Page::from_html(
            "<html><head></head><body></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let result = page
            .evaluate("typeof crypto.getRandomValues(new Uint8Array(4))")
            .unwrap();
        assert_eq!(result, "object");
    }

    #[tokio::test]
    async fn page_promise_then() {
        let mut page = Page::from_html(
            r#"<html><head></head><body>
                <div id="out">waiting</div>
                <script>
                    Promise.resolve('done').then(v => {
                        document.getElementById('out').textContent = v;
                    });
                </script>
            </body></html>"#,
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        assert_eq!(page.text_of("#out"), Some("done".to_string()));
    }

    #[tokio::test]
    async fn page_multiple_scripts() {
        let mut page = Page::from_html(
            r#"<html><head></head><body>
                <div id="out"></div>
                <script>document.getElementById('out').textContent = 'A';</script>
                <script>document.getElementById('out').textContent += 'B';</script>
                <script>document.getElementById('out').textContent += 'C';</script>
            </body></html>"#,
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        assert_eq!(page.text_of("#out"), Some("ABC".to_string()));
    }

    #[tokio::test]
    async fn page_take_dom() {
        let page = Page::from_html(
            "<html><head></head><body><p>test</p></body></html>",
            None::<crate::stealth::StealthProfile>,
        )
        .await
        .unwrap();
        let dom = page.take_dom();
        let ps = dom.get_elements_by_tag_name(crate::dom::NodeId::DOCUMENT, "p");
        assert!(!ps.is_empty(), "expected at least 1 <p>, got {}", ps.len());
        assert_eq!(dom.text_content(ps[0]), "test");
    }

    // --- Network integration tests (require internet) ---

    #[tokio::test]
    #[ignore]
    async fn navigate_httpbin() {
        let profile = crate::stealth::presets::chrome_148_linux();
        let client = crate::net::HttpClient::new(&profile).unwrap();
        let mut page = Page::navigate_simple(
            "https://httpbin.org/html",
            &client,
            crate::stealth::presets::chrome_148_ru(),
        )
        .await
        .expect("navigate to httpbin failed");
        let title = page.title();
        println!("[httpbin] title: {title:?}");
        let text = page.text_content();
        println!("[httpbin] body length: {}", text.len());
        assert!(!text.is_empty(), "body should not be empty");
        assert!(
            text.contains("Herman Melville"),
            "expected Moby Dick excerpt"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn navigate_httpbin_user_agent() {
        let profile = crate::stealth::presets::chrome_148_windows();
        let client = crate::net::HttpClient::new(&profile).unwrap();
        let mut page = Page::navigate_simple(
            "https://httpbin.org/user-agent",
            &client,
            crate::stealth::presets::chrome_148_ru(),
        )
        .await
        .expect("navigate to httpbin/user-agent failed");
        let text = page.text_content();
        println!("[user-agent] response: {text}");
        assert!(
            text.contains("Chrome"),
            "expected Chrome in user-agent response"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn navigate_stealth_headers_check() {
        let profile = crate::stealth::presets::chrome_148_linux();
        let client = crate::net::HttpClient::new(&profile).unwrap();
        let mut page = Page::navigate_simple(
            "https://httpbin.org/headers",
            &client,
            crate::stealth::presets::chrome_148_ru(),
        )
        .await
        .expect("navigate to httpbin/headers failed");
        let text = page.text_content();
        println!("[headers] response: {}", &text[..text.len().min(500)]);
        // httpbin returns JSON with the request headers — verify UA was sent
        assert!(text.contains("User-Agent"), "expected User-Agent header");
        assert!(text.contains("Chrome"), "expected Chrome in UA string");
    }

    #[tokio::test]
    #[ignore]
    async fn navigate_stealth_js_fingerprint() {
        let profile = crate::stealth::presets::chrome_148_linux();
        let mut page = Page::navigate_stealth("https://httpbin.org/html", profile)
            .await
            .expect("stealth navigate failed");
        // Verify stealth properties are wired
        let ua = page.evaluate("navigator.userAgent").unwrap();
        println!("[stealth] userAgent: {ua}");
        assert!(ua.contains("Chrome"), "UA should contain Chrome");

        let webdriver = page.evaluate("typeof navigator.webdriver").unwrap();
        assert_eq!(webdriver, "undefined", "webdriver must be undefined");

        let langs = page
            .evaluate("JSON.stringify(navigator.languages)")
            .unwrap();
        println!("[stealth] languages: {langs}");
        assert!(langs.contains("en"), "should have English language");

        let platform = page.evaluate("navigator.platform").unwrap();
        println!("[stealth] platform: {platform}");
        assert!(platform.contains("Linux"), "profile is Linux");
    }

    #[test]
    fn host_budget_env_overrides_and_longest_suffix_wins() {
        // Unset → baseline regardless of host.
        std::env::remove_var("BROWSER_OXIDE_HOST_BUDGET_MS");
        assert_eq!(host_budget_default_ms(Some("www.example.com")), 15_000);
        assert_eq!(host_budget_default_ms(None), 15_000);

        // Suffix match (www.* matches the bare suffix); more specific suffix wins.
        std::env::set_var(
            "BROWSER_OXIDE_HOST_BUDGET_MS",
            "example.com=45000, shop.example.com=90000 , bad=notanumber",
        );
        assert_eq!(host_budget_default_ms(Some("www.example.com")), 45_000);
        assert_eq!(host_budget_default_ms(Some("shop.example.com")), 90_000);
        // No match → baseline; malformed entry is ignored, not fatal.
        assert_eq!(host_budget_default_ms(Some("other.test")), 15_000);
        std::env::remove_var("BROWSER_OXIDE_HOST_BUDGET_MS");
    }
}