void_crawl_core 0.5.0

Rust-native CDP browser automation core — stealth-patched headless Chrome, profile leasing, captcha detection
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
//! High-level wrapper around a `chromiumoxide::Page`.

use std::{
    collections::{HashMap, HashSet},
    fs, future,
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use chromiumoxide::{
    Page as CdpPage,
    cdp::{
        browser_protocol::{
            accessibility::{AxNode, AxValue, GetFullAxTreeParams, QueryAxTreeParams},
            browser::{
                GetWindowForTargetParams, PermissionDescriptor, PermissionSetting,
                SetDownloadBehaviorBehavior, SetDownloadBehaviorParams, SetPermissionParams,
            },
            dom::{BackendNodeId, GetBoxModelParams, GetDocumentParams, ResolveNodeParams},
            emulation::{
                ClearDeviceMetricsOverrideParams, SetDeviceMetricsOverrideParams,
                SetGeolocationOverrideParams, SetLocaleOverrideParams, SetTimezoneOverrideParams,
                SetTouchEmulationEnabledParams, SetUserAgentOverrideParams, UserAgentBrandVersion,
                UserAgentMetadata,
            },
            input::{
                DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams,
                DispatchMouseEventType, MouseButton,
            },
            network::{
                Cookie, CookieParam, DeleteCookiesParams, EnableParams as NetworkEnableParams,
                EventRequestWillBeSent, EventResponseReceived, Headers, ResourceType,
                SetExtraHttpHeadersParams,
            },
            page::{
                AddScriptToEvaluateOnNewDocumentParams, CaptureScreenshotFormat,
                EventLifecycleEvent, FrameId, PrintToPdfParams, SetBypassCspParams,
                Viewport as CdpClipViewport,
            },
            target::GetTargetsParams,
        },
        js_protocol::runtime::{CallFunctionOnParams, EvaluateParams, ExecutionContextId},
    },
    page::ScreenshotParams,
};
use futures::StreamExt;
use serde_json::Value;
use tokio::{sync::Mutex as AsyncMutex, time};

use crate::{
    antibot::{self, AntibotVerdict},
    ax::compact_outline,
    error::{Result, VoidCrawlError},
    input::{HumanizeOptions, Rng, humanized_path},
    interrupt::InterruptRegistry,
    response::{ResponseCapture, ResponseCaptureLimits},
    selector::{self, RawRect, SelectorEntry, SelectorKind, SelectorResolution},
    stealth::StealthConfig,
    viewport::{ScrollTarget, Viewport},
};

/// Wall-clock-derived seed for live humanized pointer paths. Tests seed the
/// generator explicitly for determinism; production just wants variety.
fn runtime_seed() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0x1234_5678_9ABC_DEF0, |d| {
        d.as_secs() ^ u64::from(d.subsec_nanos()).rotate_left(32)
    })
}

/// The result of a [`Page::goto_and_wait_for_idle`] call.
///
/// Bundles the final HTML, URL, and HTTP response metadata captured during
/// navigation.  `status_code` is `None` when the page was served from a
/// service worker, disk cache, or the browser failed to capture a network
/// response (e.g. `file://` URLs).
#[derive(Debug, Clone)]
pub struct PageResponse {
    /// Outer HTML of `<html>` after the page reached network idle.
    pub html: String,
    /// Final URL after any redirects.
    pub url: String,
    /// HTTP status code of the last response in the navigation chain.
    pub status_code: Option<u16>,
    /// `true` when at least one HTTP redirect occurred before the final URL.
    pub redirected: bool,
    /// Response headers of the final Document response (`name`, `value`),
    /// lowercased names, in arrival order. Empty when no network response was
    /// captured (cache/service-worker/`file://`). Feeds anti-bot fingerprinting
    /// and replay-grade provenance (`cf-ray`, `x-cache`, …).
    pub headers: Vec<(String, String)>,
    /// Signature-based anti-bot / CDN vendor fingerprint of the final response,
    /// computed from `status_code` + `headers` + `html`. `None` when no
    /// network response was captured. Non-fatal: presence is a routing hint,
    /// `challenged` means an active wall — see [`crate::antibot`].
    pub antibot: Option<AntibotVerdict>,
    /// Data-plane network endpoints (XHR + Fetch request URLs) observed during
    /// navigation — a sorted, deduplicated set of `scheme://host[:port]/path`
    /// strings with query/fragment/userinfo stripped and secret-like path
    /// segments redacted at the source (a replay-grade archive must never
    /// persist a token; see [`safe_endpoint`] and
    /// `ENDPOINT_SANITIZER_VERSION`). `None` when capture was not requested
    /// (opt-in); `Some(empty)` when requested but the page made no
    /// XHR/fetch calls. The *consumer* templatizes id-bearing path segments
    /// — this stays a generic, faithful observation.
    pub endpoints: Option<Vec<String>>,
    /// `true` when the captured endpoint set hit its cap and further endpoints
    /// were dropped — so a consumer can tell "made few calls" from "we stopped
    /// counting". Always `false` when `endpoints` is `None`.
    pub endpoints_truncated: bool,
    /// The [`ENDPOINT_SANITIZER_VERSION`] the `endpoints` were redacted under,
    /// so a long-term archive can reproduce/audit exactly which rules produced
    /// the set (mirrors `AntibotVerdict::corpus_version`). `None` iff
    /// `endpoints` is `None` (capture was not requested).
    pub endpoint_sanitizer_version: Option<&'static str>,
}

/// Per-tab CDP instrumentation state.
///
/// Tabs start in a human-first, low-CDP state. Calling network-heavy helpers
/// lazily enables the required CDP domains on that tab and flips these flags;
/// use this state to route sensitive challenge traversal away from tabs that
/// have already escalated into instrumentation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "state snapshot intentionally exposes independent routing flags"
)]
pub struct TabInstrumentationState {
    /// `true` while the tab has not enabled higher-signal CDP domains.
    pub low_cdp:                bool,
    /// `true` after `Network.enable` has been sent for this target.
    pub network_enabled:        bool,
    /// `true` after `Runtime.enable` has been sent for frame-scoped JS.
    /// `eval_js` uses one-shot `Runtime.evaluate` without enabling the Runtime
    /// domain.
    pub runtime_enabled:        bool,
    /// Reserved for future isolated utility-world escalation tracking.
    pub utility_world_enabled:  bool,
    /// `true` if VoidCrawl applied UA/viewport pre-navigation stealth to this
    /// tab.
    pub pre_navigation_stealth: bool,
}

/// Version of the endpoint-sanitization rules ([`safe_endpoint`]). Bump on any
/// change to the redaction patterns so a captured set is reproducible/auditable
/// at replay time — mirrors `antibot::CORPUS_VERSION`.
pub const ENDPOINT_SANITIZER_VERSION: &str = "ep-2026.06.06";

/// Largest distinct-endpoint set kept per navigation; past this, capture stops
/// and `PageResponse::endpoints_truncated` is set. Bounds memory on chatty
/// SPAs.
const MAX_ENDPOINTS: usize = 256;

/// Reduce a raw request URL to a `scheme://host[:port]/path` key with secrets
/// removed, or `None` if it must not be archived at all.
///
/// A replay-grade archive cannot retroactively un-persist a secret, so this
/// strips at the source — BEFORE the string is ever stored — and is
/// **redact-by-default** on the path (deny-unknown, not allow-unknown):
///   * query string + fragment removed (where tokens/PII/cache-busters live),
///   * userinfo (`user:pass@`) removed,
///   * non-`http(s)` schemes and loopback/private/CGNAT/`.local` hosts dropped
///     entirely (an operator-environment leak, not page signal),
///   * a path segment is KEPT only when it is clearly a short, low-entropy
///     template token ([`is_safe_segment`]); ANYTHING else — long blobs
///     (JWT/signed-URL/hash), kv/matrix markers (`;`/`=`/`%`), emails, long
///     digit runs — becomes `:redacted`.
///
/// This is a best-effort *security* filter, not a proof: a short high-entropy
/// secret can still resemble a word. It deliberately does NOT templatize
/// ordinary id segments (`/users/123/` keeps `123`) — that semantic
/// normalization is the *consumer's* fingerprint concern; this function's job
/// is only to keep secrets out while staying a faithful, generic observation.
pub fn safe_endpoint(raw_url: &str) -> Option<String> {
    // Cut everything from the first `?` or `#` — query and fragment never enter.
    let head = raw_url.split(['?', '#']).next().unwrap_or("");

    let (scheme, rest) = head.split_once("://")?;
    let scheme = scheme.to_ascii_lowercase();
    if scheme != "http" && scheme != "https" {
        return None;
    }

    // Authority is everything up to the first `/`; the rest is the path.
    let (authority, path) = match rest.split_once('/') {
        Some((a, p)) => (a, format!("/{p}")),
        None => (rest, String::new()),
    };
    // Drop userinfo (`user:pass@host`) — embedded credentials — then lowercase
    // the host:port ONCE (the single source of truth for both the local-host
    // guard and the emitted key).
    let host_port = authority.rsplit_once('@').map_or(authority, |(_, hp)| hp).to_ascii_lowercase();
    let host = bare_host(&host_port);
    if host.is_empty() || is_local_host(host) {
        return None;
    }

    let safe_path: String = path
        .split('/')
        .map(|seg| if is_safe_segment(seg) { seg } else { ":redacted" })
        .collect::<Vec<_>>()
        .join("/");

    Some(format!("{scheme}://{host_port}{safe_path}"))
}

/// The bare host from a (already-lowercased) `host[:port]` authority, handling
/// the bracketed IPv6 form `[::1]:9000` → `::1` (a plain `split(':')` would
/// return `"["` and let loopback IPv6 slip past [`is_local_host`]).
fn bare_host(host_port: &str) -> &str {
    if let Some(after) = host_port.strip_prefix('[') {
        return after.split(']').next().unwrap_or("");
    }
    host_port.split(':').next().unwrap_or("")
}

/// Loopback / private / CGNAT / link-local / mDNS hosts — never archive these
/// (they describe the crawl operator's machine/network, not the page). `host`
/// is the bare, lowercased host (no brackets, no port).
fn is_local_host(host: &str) -> bool {
    // IPv6 loopback / unspecified / link-local / unique-local (fc00::/7).
    if host == "::1"
        || host == "::"
        || host.starts_with("fe80:")
        || host.starts_with("fc")
        || host.starts_with("fd")
    {
        return true;
    }
    // mDNS `*.local` (compare the final label, not via ends_with — that trips
    // clippy's file-extension lint and would also match a bare "local").
    let mdns_local = host.rsplit_once('.').is_some_and(|(_, tld)| tld == "local");
    if host == "localhost" || host == "0.0.0.0" || mdns_local {
        return true;
    }
    if host.starts_with("127.")
        || host.starts_with("10.")
        || host.starts_with("192.168.")
        || host.starts_with("169.254.")
    {
        return true;
    }
    // RFC-1918 172.16.0.0/12 and RFC-6598 CGNAT 100.64.0.0/10.
    let second_octet = |s: &str| s.split('.').nth(1).and_then(|o| o.parse::<u8>().ok());
    if host.starts_with("172.") {
        return second_octet(host).is_some_and(|o| (16..=31).contains(&o));
    }
    if host.starts_with("100.") {
        return second_octet(host).is_some_and(|o| (64..=127).contains(&o));
    }
    false
}

/// True when a path segment is clearly a SAFE template token worth keeping —
/// the allow-list half of the redact-by-default policy. Conservative: anything
/// that isn't obviously a short, low-entropy lexical/id token is redacted.
///
/// Keeps: `finance`, `quoteSummary`, `v10`, `users`, `123`, `AAPL` (the
/// consumer templatizes ordinary ids). Redacts: JWTs/signed-URLs/hashes (long
/// or high-entropy), emails / kv / matrix params (`@`/`=`/`;`/`%`), and long
/// digit runs (card/SSN/phone).
fn is_safe_segment(seg: &str) -> bool {
    // Empty (a `//` or trailing `/`) is structure, not content — keep it.
    if seg.is_empty() {
        return true;
    }
    // Any kv / matrix / userinfo / percent-encoding marker → not a plain token.
    if seg.contains(['@', '=', ';', '%', ':']) {
        return false;
    }
    // Only ordinary url-path token characters.
    if !seg.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~')) {
        return false;
    }
    // Long segments are tokens/blobs, not template words (`recommendations` is 15).
    if seg.len() > 15 {
        return false;
    }
    let digits = seg.chars().filter(char::is_ascii_digit).count();
    // 9+ digits → SSN / card / phone range (ordinary numeric ids are shorter).
    if digits >= 9 {
        return false;
    }
    // A 12+ char all-hex blob is a hash/token, never a word.
    if seg.len() >= 12 && seg.chars().all(|c| c.is_ascii_hexdigit()) {
        return false;
    }
    // A 12+ char segment spanning 3 character classes (lower AND upper AND
    // digit) is an opaque mixed-case token, not a template word — `oAuth2…`-
    // style names are rare in paths and over-redacting them is the safe trade.
    if seg.len() >= 12 {
        let has_lower = seg.chars().any(|c| c.is_ascii_lowercase());
        let has_upper = seg.chars().any(|c| c.is_ascii_uppercase());
        let has_digit = seg.chars().any(|c| c.is_ascii_digit());
        if has_lower && has_upper && has_digit {
            return false;
        }
    }
    true
}

/// Turn the in-loop deduped endpoint set into the final field value: `None`
/// when capture was off, else a SORTED `Vec` (a stable set — arrival order is a
/// session/timing tell, and the consumer set-ifies anyway).
fn finalize_endpoints(seen: &HashSet<String>, capture: bool) -> Option<Vec<String>> {
    if !capture {
        return None;
    }
    let mut v: Vec<String> = seen.iter().cloned().collect();
    v.sort();
    Some(v)
}

/// Flatten CDP's `Network.Response.headers` (a JSON object of name → string
/// value) into ordered `(lowercased-name, value)` pairs. Non-string values are
/// skipped; an unexpected non-object yields an empty list.
fn flatten_headers(value: &serde_json::Value) -> Vec<(String, String)> {
    value
        .as_object()
        .map(|map| {
            map.iter()
                .filter_map(|(k, v)| v.as_str().map(|s| (k.to_lowercase(), s.to_string())))
                .collect()
        })
        .unwrap_or_default()
}

/// Rectangular crop in CSS pixels for [`ScreenshotOptions::bbox`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct Bbox {
    pub x:      u32,
    pub y:      u32,
    pub width:  u32,
    pub height: u32,
}

/// Options for [`Page::screenshot`].
#[derive(Debug, Clone)]
pub struct ScreenshotOptions {
    /// Write PNG to this path instead of returning bytes.
    pub path:      Option<PathBuf>,
    /// Crop to this CSS-pixel region. Takes precedence over `full_page`.
    /// With `scroll` set, coordinates are relative to wherever that scroll
    /// lands rather than the top of the document.
    pub bbox:      Option<Bbox>,
    /// Crop to a Yosoi selector's resolved rectangle instead of an explicit
    /// `bbox`. Mutually exclusive with `bbox`: setting both is an error.
    /// A non-[`Resolved`](crate::selector::SelectorResolution::Resolved)
    /// outcome (nothing matched, hidden/zero-area target, ambiguous match,
    /// or a non-visual kind like `jsonld`/`regex`) becomes an actionable
    /// `Err` here — see [`Page::resolve_selector`] for a version that
    /// returns the typed outcome instead of erroring.
    pub selector:  Option<SelectorEntry>,
    /// Apply this viewport/device override for just this capture, then
    /// restore whatever was active before (even on error). See
    /// [`Page::set_viewport`] for a persistent version.
    pub viewport:  Option<Viewport>,
    /// Scroll to this position before capturing, then restore the original
    /// scroll position after (even on error). Combine with `bbox` to crop a
    /// specific on-screen region after paging down a fixed viewport, or use
    /// alone with `full_page: false` to capture whatever's scrolled into
    /// view without cropping.
    pub scroll:    Option<ScrollTarget>,
    /// Capture the full scrollable page (default `true`) vs just what's
    /// currently visible in the viewport. Ignored when `bbox` is set — a
    /// crop always wins. Set `false` via [`ScreenshotOptions::viewport_only`]
    /// to capture only the visible fold: cheaper, and the right choice when
    /// "screenshot this page" really means "what does a visitor see first,"
    /// not the whole scroll history.
    pub full_page: bool,
}

impl Default for ScreenshotOptions {
    fn default() -> Self {
        Self {
            path:      None,
            bbox:      None,
            selector:  None,
            viewport:  None,
            scroll:    None,
            full_page: true,
        }
    }
}

impl ScreenshotOptions {
    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.path = Some(path.into());
        self
    }

    pub fn with_bbox(mut self, bbox: Bbox) -> Self {
        self.bbox = Some(bbox);
        self
    }

    pub fn with_selector(mut self, selector: SelectorEntry) -> Self {
        self.selector = Some(selector);
        self
    }

    pub fn with_viewport(mut self, viewport: Viewport) -> Self {
        self.viewport = Some(viewport);
        self
    }

    pub fn with_scroll(mut self, scroll: ScrollTarget) -> Self {
        self.scroll = Some(scroll);
        self
    }

    /// Capture only the currently visible viewport instead of the full
    /// scrollable page.
    pub fn viewport_only(mut self) -> Self {
        self.full_page = false;
        self
    }
}

/// Return type of [`Page::screenshot`].
#[derive(Debug)]
pub enum ScreenshotOutput {
    /// PNG bytes held in memory (no path supplied).
    Bytes(Vec<u8>),
    /// Path the PNG was written to.
    Path(PathBuf),
}

/// Outcome of [`Page::download_to_dir`]: the file that landed on disk.
#[derive(Debug, Clone)]
pub struct DownloadOutcome {
    /// Absolute path to the downloaded file inside the target directory.
    pub path:         PathBuf,
    /// Size of the downloaded file in bytes.
    pub bytes:        u64,
    /// The `Content-Type` the server sent for the download (parameters
    /// stripped), if any — fed to the scanner to catch disguised payloads.
    /// `None` for action-captured downloads (see [`Page::arm_download`]), where
    /// Chrome streams to disk and the header isn't observed.
    pub content_type: Option<String>,
}

/// A primed capture for an **action-triggered** download — created by
/// [`Page::arm_download`], consumed by [`DownloadCapture::wait`].
///
/// Use this when the download is started by a page action (clicking a
/// "Download" button, a generated/redirected/cross-origin URL) rather than a
/// URL you already hold — e.g. Google Drive. The flow is *arm → act → await*:
///
/// ```no_run
/// # async fn f(page: &void_crawl_core::Page) -> void_crawl_core::Result<()> {
/// # use std::{path::Path, time::Duration};
/// let cap = page.arm_download(Path::new("/tmp/dl"), 100 << 20).await?;
/// page.click_by_role("button", "Download all", 0, false).await?; // the triggering action
/// let file = cap.wait(page, Duration::from_secs(120)).await?;
/// # Ok(()) }
/// ```
///
/// `arm_download` snapshots the directory's existing files, so `wait` only
/// accepts a file that appears *after* arming. Not `Clone` — a capture is
/// consumed exactly once.
#[derive(Debug)]
pub struct DownloadCapture {
    dir:       PathBuf,
    before:    HashSet<PathBuf>,
    max_bytes: u64,
}

impl DownloadCapture {
    /// Wait for a new completed download to settle in the armed directory, then
    /// reset `page`'s download behavior. `page` must be the page that armed
    /// this capture.
    ///
    /// The size cap is enforced *after* the file lands (Chrome streams a native
    /// download straight to disk — it can't be aborted mid-stream the way
    /// [`Page::download_to_dir`] aborts its in-page fetch). An oversized file
    /// is deleted and an error returned.
    pub async fn wait(self, page: &Page, timeout: Duration) -> Result<DownloadOutcome> {
        let result = self.poll(timeout).await;
        page.reset_download_behavior().await;
        result
    }

    /// Poll for the download **without** touching the page, so a caller holding
    /// the page lock elsewhere doesn't hold it for the whole wait. Does NOT
    /// reset download behavior — pair with [`Page::reset_download_behavior`].
    pub async fn poll(&self, timeout: Duration) -> Result<DownloadOutcome> {
        wait_for_new_download(&self.dir, &self.before, self.max_bytes, timeout).await
    }
}

const DOCUMENT_SNAPSHOT_JS: &str = r#"
(() => {
  const MAX = {
    headings: 80,
    textBlocks: 240,
    links: 160,
    controls: 160,
    forms: 60,
    formControls: 30,
    textChars: 700,
    smallChars: 220
  };
  const clean = (value) => String(value || '').replace(/\s+/g, ' ').trim();
  const clip = (value, limit) => {
    const text = clean(value);
    return text.length > limit ? text.slice(0, Math.max(0, limit - 3)) + '...' : text;
  };
  const visible = (el) => {
    if (!el || !el.isConnected) return false;
    const style = window.getComputedStyle(el);
    if (!style || style.display === 'none' || style.visibility === 'hidden') return false;
    const rect = el.getBoundingClientRect();
    return rect.width > 0 && rect.height > 0;
  };
  const attr = (el, name) => {
    const value = el.getAttribute(name);
    return value == null || value === '' ? null : clip(value, MAX.smallChars);
  };
  const labelText = (el) => {
    const id = el.id ? CSS.escape(el.id) : null;
    const label = id ? document.querySelector(`label[for="${id}"]`) : null;
    return clip(
      el.getAttribute('aria-label')
        || el.getAttribute('title')
        || el.getAttribute('placeholder')
        || (label && label.textContent)
        || el.value
        || el.textContent
        || el.name
        || '',
      MAX.smallChars
    );
  };
  const control = (el) => ({
    tag: el.tagName.toLowerCase(),
    type: attr(el, 'type'),
    role: attr(el, 'role'),
    name: labelText(el) || null,
    placeholder: attr(el, 'placeholder'),
    disabled: Boolean(el.disabled || el.getAttribute('aria-disabled') === 'true')
  });
  const all = (selector) => Array.from(document.querySelectorAll(selector)).filter(visible);
  const unique = (items) => Array.from(new Set(items));

  const headingNodes = all('h1,h2,h3,h4,h5,h6');
  const headings = headingNodes.slice(0, MAX.headings).map((el) => ({
    level: Number(el.tagName.slice(1)),
    text: clip(el.textContent, MAX.smallChars)
  })).filter((h) => h.text);

  const textNodes = unique([
    ...all('main p, main li, article p, article li, section p, blockquote, body > p, td, th'),
    ...all('[role="main"] p, [role="article"] p')
  ]).filter((el) => clean(el.textContent).length >= 20);
  const text_blocks = textNodes.slice(0, MAX.textBlocks).map((el) => ({
    tag: el.tagName.toLowerCase(),
    text: clip(el.textContent, MAX.textChars)
  })).filter((b) => b.text);

  const linkNodes = all('a[href]');
  const links = linkNodes.slice(0, MAX.links).map((el) => ({
    text: clip(el.textContent || el.getAttribute('aria-label') || el.href, MAX.smallChars),
    href: clip(el.href, MAX.smallChars)
  })).filter((l) => l.href);

  const controlNodes = all('button,input,select,textarea,[role="button"],[role="link"],[role="textbox"],[role="combobox"],[contenteditable="true"]');
  const controls = controlNodes.slice(0, MAX.controls).map(control);

  const formNodes = all('form');
  const forms = formNodes.slice(0, MAX.forms).map((form) => {
    const fields = Array.from(form.querySelectorAll('button,input,select,textarea,[role="button"],[role="textbox"],[role="combobox"]'))
      .filter(visible)
      .slice(0, MAX.formControls)
      .map(control);
    return {
      action: attr(form, 'action') || (form.action ? clip(form.action, MAX.smallChars) : null),
      method: clip(form.method || 'get', 20).toLowerCase(),
      controls: fields
    };
  });

  return {
    url: location.href,
    title: document.title || null,
    headings,
    text_blocks,
    links,
    controls,
    forms,
    total: {
      headings: headingNodes.length,
      text_blocks: textNodes.length,
      links: linkNodes.length,
      controls: controlNodes.length,
      forms: formNodes.length
    }
  };
})()
"#;

/// Thin wrapper over `chromiumoxide::Page` exposing a clean async API.
#[derive(Debug)]
pub struct Page {
    inner:                  CdpPage,
    interrupts:             Arc<InterruptRegistry>,
    /// `true` between [`Page::arm_download`] / a `download_to_dir` in flight
    /// and the matching reset. The pool checks this on release to reset an
    /// abandoned download behavior cheaply (no CDP call on the common path).
    download_armed:         AtomicBool,
    /// Last virtual cursor position (CSS px), so a humanized move starts from
    /// where the pointer actually is. Defaults to the top-left.
    cursor:                 Mutex<(f64, f64)>,
    /// Shared with every other `Page` from the same `BrowserSession`.
    /// Headless Chrome only reliably composites frames for the foregrounded
    /// tab, so `screenshot()` holds this while it brings itself to front and
    /// captures — serializing just that instant across tabs on one browser,
    /// not the tabs' navigation/JS work.
    capture_lock:           Arc<AsyncMutex<()>>,
    /// The viewport/device override currently in effect via
    /// [`Page::set_viewport`], or `None` when using the session's launch-time
    /// default. `screenshot()`'s one-shot `viewport` option snapshots and
    /// restores this so a temporary override never leaks to later calls on the
    /// same page.
    viewport_override:      Mutex<Option<Viewport>>,
    network_enabled:        AtomicBool,
    runtime_enabled:        AtomicBool,
    pre_navigation_stealth: AtomicBool,
}

impl Page {
    /// Wrap an existing CDP page. `capture_lock` and `interrupts` are shared
    /// by every page created from the same `BrowserSession`.
    pub(crate) fn new(
        inner: CdpPage,
        capture_lock: Arc<AsyncMutex<()>>,
        interrupts: Arc<InterruptRegistry>,
    ) -> Self {
        Self {
            inner,
            interrupts,
            download_armed: AtomicBool::new(false),
            cursor: Mutex::new((0.0, 0.0)),
            network_enabled: AtomicBool::new(false),
            runtime_enabled: AtomicBool::new(false),
            pre_navigation_stealth: AtomicBool::new(false),
            capture_lock,
            viewport_override: Mutex::new(None),
        }
    }

    /// The underlying CDP page, for sibling modules that need to issue raw
    /// protocol commands (see [`crate::recording`], which drives the
    /// `Page.startScreencast` domain directly).
    pub(crate) fn cdp(&self) -> &CdpPage {
        &self.inner
    }

    /// A second handle on the same tab, sharing the browser's capture lock and
    /// interrupt registry.
    ///
    /// For background tasks that need to *query* a page the caller still owns —
    /// [`crate::recording`]'s mask tracker re-resolves selectors on a timer
    /// while the original `Page` stays behind its own lock. Deliberately not
    /// `Clone`: the per-page state that isn't shared (virtual cursor position,
    /// one-shot viewport override) resets on the new handle, so this is only
    /// safe for read-only work like [`Page::resolve_selector`].
    pub(crate) fn clone_handle(&self) -> Self {
        Self::new(self.inner.clone(), Arc::clone(&self.capture_lock), Arc::clone(&self.interrupts))
    }

    /// The browser-wide capture lock this page shares with its siblings.
    /// Cloned rather than borrowed so a caller can hold it across an await
    /// without borrowing the page for that whole span.
    pub(crate) fn capture_lock(&self) -> Arc<AsyncMutex<()>> {
        Arc::clone(&self.capture_lock)
    }

    /// The id of the browser window this tab lives in.
    ///
    /// Chrome composites only the frontmost tab *of a window*, so two pages
    /// sharing a window id cannot both paint — the constraint behind
    /// [`Page::screenshot`]'s capture lock and
    /// [`RecordingOptions::foreground`](crate::RecordingOptions::foreground).
    /// Use this to check that a page intended for concurrent recording really
    /// is alone in its window.
    pub async fn window_id(&self) -> Result<i64> {
        let params =
            GetWindowForTargetParams::builder().target_id(self.inner.target_id().clone()).build();
        let result = self
            .inner
            .execute(params)
            .await
            .map_err(|e| VoidCrawlError::PageError(format!("getWindowForTarget: {e}")))?;
        Ok(result.result.window_id.inner().to_owned())
    }

    /// Whether this tab is the only one in its browser window.
    ///
    /// Chrome composites only a window's frontmost tab, so a page that shares
    /// its window with others cannot paint while a sibling is active. A page
    /// that is alone in its window keeps painting regardless of what other
    /// windows do — which is what makes a concurrent, non-foregrounded
    /// [`recording`](crate::recording) possible.
    ///
    /// Costs one `Target.getTargets` plus one `Browser.getWindowForTarget`
    /// per page target, so it's a per-operation check, not a per-frame one.
    pub async fn alone_in_window(&self) -> Result<bool> {
        let mine = self.window_id().await?;
        let targets = self
            .inner
            .execute(GetTargetsParams::default())
            .await
            .map_err(|e| VoidCrawlError::PageError(format!("getTargets: {e}")))?;

        let own_target = self.target_id();
        for info in &targets.result.target_infos {
            // Only page targets occupy a window's tab strip; workers and
            // iframes report a window but never occlude anything.
            if info.r#type != "page" || info.target_id.inner() == &own_target {
                continue;
            }
            let params =
                GetWindowForTargetParams::builder().target_id(info.target_id.clone()).build();
            // A target can die between enumeration and lookup; a target we
            // can't place can't be proven to share this window.
            if let Ok(result) = self.inner.execute(params).await
                && *result.result.window_id.inner() == mine
            {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Reject a mutation while this target is parked by an explicit interrupt.
    pub async fn ensure_active(&self) -> Result<()> {
        self.interrupts.page_is_active(&self.target_id()).await
    }

    pub(crate) fn belongs_to_interrupt_registry(&self, registry: &Arc<InterruptRegistry>) -> bool {
        Arc::ptr_eq(&self.interrupts, registry)
    }

    /// Whether a download is currently armed on this page (set by
    /// `arm_download` / `download_to_dir`, cleared by
    /// `reset_download_behavior`).
    pub fn is_download_armed(&self) -> bool {
        self.download_armed.load(Ordering::Relaxed)
    }

    /// The CDP target id of the underlying page, as a string.
    ///
    /// Stable across same-tab navigations, so another connection (a second
    /// process attached to the same Chrome via `ws_url`) can re-adopt this
    /// exact tab with
    /// [`BrowserSession::attach_page`](crate::BrowserSession::attach_page).
    pub fn target_id(&self) -> String {
        self.inner.target_id().inner().clone()
    }

    /// Snapshot this tab's instrumentation state for routing/debugging.
    pub fn instrumentation_state(&self) -> TabInstrumentationState {
        let network_enabled = self.network_enabled.load(Ordering::Relaxed);
        let runtime_enabled = self.runtime_enabled.load(Ordering::Relaxed);
        let pre_navigation_stealth = self.pre_navigation_stealth.load(Ordering::Relaxed);
        TabInstrumentationState {
            low_cdp: !(network_enabled || runtime_enabled),
            network_enabled,
            runtime_enabled,
            utility_world_enabled: false,
            pre_navigation_stealth,
        }
    }

    async fn ensure_network_enabled(&self) -> Result<()> {
        if !self.network_enabled.load(Ordering::Relaxed) {
            self.inner
                .execute(NetworkEnableParams::default())
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            self.network_enabled.store(true, Ordering::Relaxed);
        }
        Ok(())
    }

    async fn ensure_runtime_enabled(&self) -> Result<()> {
        if !self.runtime_enabled.load(Ordering::Relaxed) {
            self.inner
                .enable_runtime()
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            self.runtime_enabled.store(true, Ordering::Relaxed);
        }
        Ok(())
    }

    async fn frame_execution_context_with_runtime(
        &self,
        frame_id: FrameId,
        frame_url_pattern: &str,
    ) -> Result<ExecutionContextId> {
        self.ensure_runtime_enabled().await?;
        for attempt in 0..20 {
            if let Some(context_id) = self
                .inner
                .frame_execution_context(frame_id.clone())
                .await
                .map_err(|e| VoidCrawlError::JsEvalError(e.to_string()))?
            {
                return Ok(context_id);
            }
            if attempt < 19 {
                time::sleep(Duration::from_millis(50)).await;
            }
        }
        Err(VoidCrawlError::FrameNotFound(format!(
            "{frame_url_pattern:?}: matched frame has no scriptable execution context \
             (sandboxed without allow-scripts, cross-process, or not yet loaded)"
        )))
    }

    /// Apply stealth settings to this page.
    pub(crate) async fn apply_stealth(&self, cfg: &StealthConfig) -> Result<()> {
        self.pre_navigation_stealth.store(true, Ordering::Relaxed);
        // 1. Built-in stealth (patches navigator.webdriver etc.)
        if cfg.use_builtin_stealth {
            if let Some(ua) = &cfg.user_agent {
                self.inner
                    .enable_stealth_mode_with_agent(ua)
                    .await
                    .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            } else {
                self.inner
                    .enable_stealth_mode()
                    .await
                    .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            }
        }

        // 2. User-agent override + matching Client Hints.
        //
        // Three cases, in precedence order:
        //   a. Caller supplied an explicit `user_agent` — use it verbatim.
        //   b. No explicit UA, but `use_builtin_stealth` already applied
        //      its own agent via `enable_stealth_mode_with_agent` — skip.
        //   c. Default (cfg.user_agent = None, builtin stealth off): probe
        //      the browser's *real* UA and strip any "Headless" token. We
        //      override even when nothing was stripped, because the override
        //      is also what makes `navigator.platform` and
        //      `navigator.userAgentData` (Client Hints) CONSISTENT with the
        //      UA — a UA that says Linux while `navigator.platform` says
        //      "Win32" or `userAgentData.brands` is empty is itself a strong
        //      bot signal.
        let override_ua = if let Some(ua) = cfg.user_agent.clone() {
            Some(ua)
        } else if cfg.use_builtin_stealth {
            None
        } else {
            probe_user_agent(&self.inner).await?.map(|ua| dehead(&ua))
        };

        if let Some(ua) = override_ua {
            // Derive a coherent navigator.platform + Client-Hints metadata
            // from the UA so all three agree.
            let (nav_platform, metadata) = client_hints_for_ua(&ua);
            let mut builder = SetUserAgentOverrideParams::builder()
                .user_agent(ua)
                .accept_language(&cfg.locale)
                .platform(nav_platform);
            if let Some(metadata) = metadata {
                builder = builder.user_agent_metadata(metadata);
            }
            let params = builder.build().map_err(VoidCrawlError::PageError)?;
            self.inner
                .execute(params)
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        }

        // 3. Viewport / device metrics — through `set_viewport` (not a raw
        // CDP call) so `viewport_override` reflects this as the page's
        // baseline. Otherwise a later one-shot `screenshot(viewport: ...)`
        // would see `current_viewport() == None`, "restore" by calling
        // `clear_viewport`, and wipe this launch-time override instead of
        // putting it back.
        self.set_viewport(Viewport::custom(cfg.viewport_width, cfg.viewport_height)).await?;

        // 4. Bypass CSP so our injected JS can run
        if cfg.bypass_csp {
            let csp = SetBypassCspParams::new(true);
            self.inner.execute(csp).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        }

        // 5. Inject custom JS before every navigation
        if let Some(js) = &cfg.inject_js {
            let params = AddScriptToEvaluateOnNewDocumentParams::new(js.clone());
            self.inner
                .execute(params)
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        }

        Ok(())
    }

    /// Install JavaScript that runs before every subsequent document in this
    /// tab. The script is registered through CDP; it does not modify fetch,
    /// XHR, or request interception.
    pub async fn add_init_script(&self, script: &str) -> Result<()> {
        self.ensure_active().await?;
        self.inner
            .execute(AddScriptToEvaluateOnNewDocumentParams::new(script.to_string()))
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Arm a passive response-body capture before performing a triggering
    /// action. Every `(name, pattern)` must be fulfilled once.
    pub async fn expect_responses(
        &self,
        patterns: Vec<(String, String)>,
        timeout: Duration,
        limits: ResponseCaptureLimits,
    ) -> Result<ResponseCapture> {
        ResponseCapture::arm(self.inner.clone(), patterns, timeout, limits).await
    }

    // ── Navigation ──────────────────────────────────────────────────────

    /// Navigate to `url` and wait for the CDP response.
    pub async fn navigate(&self, url: &str) -> Result<()> {
        self.ensure_active().await?;
        self.inner.goto(url).await.map_err(|e| VoidCrawlError::NavigationFailed(e.to_string()))?;
        Ok(())
    }

    /// Navigate to `url` and wait for network idle, returning a
    /// [`PageResponse`].
    ///
    /// Subscribes to both `Page.lifecycleEvent` and `Network.responseReceived`
    /// **before** navigation starts so that no events are missed.  The
    /// `networkIdle` terminates the wait; reaching the deadline raises a
    /// structured navigation timeout.
    ///
    /// Equivalent to Playwright's `page.goto(url, wait_until='networkidle')`.
    pub async fn goto_and_wait_for_idle(
        &self,
        url: &str,
        timeout: Duration,
    ) -> Result<PageResponse> {
        self.goto_and_wait_for_idle_with_capture(url, timeout, false).await
    }

    /// Like [`Page::goto_and_wait_for_idle`], but when `capture_endpoints` is
    /// `true` also records the page's data-plane network endpoint set (XHR +
    /// Fetch request URLs) onto [`PageResponse::endpoints`].
    ///
    /// Capture is **opt-in** so the default fetch path pays no extra cost: the
    /// `Network.requestWillBeSent` listener is only subscribed when requested.
    /// It is passive (listen-only — no request interception, invisible to the
    /// site) and the endpoints are PII-stripped at the source via
    /// [`safe_endpoint`]. The listener is function-local and dropped on return,
    /// so nothing leaks across a pooled tab's recycle.
    #[allow(
        clippy::cognitive_complexity,
        reason = "a single navigate select-loop reads more clearly inline than split across helpers"
    )]
    pub async fn goto_and_wait_for_idle_with_capture(
        &self,
        url: &str,
        timeout: Duration,
        capture_endpoints: bool,
    ) -> Result<PageResponse> {
        self.ensure_active().await?;
        self.ensure_network_enabled().await?;
        let started = Instant::now();
        // Subscribe to ALL event streams BEFORE navigation so no events slip
        // through the gap between goto() and the listener setup.
        let mut lifecycle = self
            .inner
            .event_listener::<EventLifecycleEvent>()
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        let mut network = self
            .inner
            .event_listener::<EventResponseReceived>()
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        // Request listener is gated on the opt-in so the wire/decode cost is
        // only paid when a caller wants the endpoint set.
        let mut requests = if capture_endpoints {
            Some(
                self.inner
                    .event_listener::<EventRequestWillBeSent>()
                    .await
                    .map_err(|e| VoidCrawlError::PageError(e.to_string()))?,
            )
        } else {
            None
        };

        // Start navigation (non-blocking CDP command)
        self.inner.goto(url).await.map_err(|e| VoidCrawlError::NavigationFailed(e.to_string()))?;

        let deadline = time::sleep(timeout);
        tokio::pin!(deadline);

        let mut status_code: Option<u16> = None;
        let mut redirect_count: u32 = 0;
        // Headers of the final (non-redirect) Document response. Overwritten if
        // a later navigation supersedes it, mirroring `status_code`.
        let mut headers: Vec<(String, String)> = Vec::new();
        // Deduped data-plane endpoint set (only populated when capturing).
        let mut endpoints: HashSet<String> = HashSet::new();
        let mut endpoints_truncated = false;

        loop {
            tokio::select! {
                biased;
                maybe_lifecycle = lifecycle.next() => {
                    match maybe_lifecycle {
                        Some(event) if event.name == "networkIdle" => break,
                        Some(_) => {}
                        None => break,
                    }
                }
                maybe_network = network.next() => {
                    if let Some(event) = maybe_network {
                        // Only the Document response carries the page's actual
                        // status code. Sub-resources (images, scripts, XHRs)
                        // are ignored so a 404 favicon doesn't overwrite a 200
                        // document status.
                        if event.r#type == ResourceType::Document {
                            // status is i64 from the CDP spec; real HTTP codes
                            // fit in u16, so the lossy truncation is intentional.
                            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                            let code = event.response.status as u16;
                            if (300..400).contains(&code) {
                                // Redirect in the navigation chain.
                                redirect_count += 1;
                            } else if code != 0 {
                                // Chrome emits 0 for cancelled/intercepted
                                // requests — treat as "no network response".
                                status_code = Some(code);
                                headers = flatten_headers(event.response.headers.inner());
                            }
                        }
                    }
                }
                // Endpoint capture — only polled when capturing (guard ensures
                // `requests` is Some). Sits BELOW lifecycle so a chatty request
                // stream can never starve the networkIdle break.
                //
                // select! evaluates every branch's future expression even when
                // its `if` guard is false, so the `None` branch must still yield
                // a same-typed future that never resolves — pending() parks it
                // harmlessly (it's unreachable in practice: requests is Some iff
                // capture_endpoints).
                maybe_request = async {
                    match requests.as_mut() {
                        Some(s) => s.next().await,
                        None => future::pending().await,
                    }
                }, if capture_endpoints => {
                    if let Some(event) = maybe_request {
                        if matches!(event.r#type, Some(ResourceType::Xhr | ResourceType::Fetch)) {
                            if let Some(ep) = safe_endpoint(&event.request.url) {
                                // A duplicate (already counted) applies no cap
                                // pressure; only a NEW endpoint past the cap
                                // flips the truncated flag.
                                if !endpoints.contains(&ep) {
                                    if endpoints.len() < MAX_ENDPOINTS {
                                        endpoints.insert(ep);
                                    } else {
                                        endpoints_truncated = true;
                                    }
                                }
                            }
                        }
                    }
                }
                () = &mut deadline => {
                    return Err(VoidCrawlError::NavigationTimeout {
                        url: url.to_string(),
                        wait_phase: "networkidle".to_string(),
                        timeout_secs: timeout.as_secs_f64(),
                        elapsed_secs: started.elapsed().as_secs_f64(),
                    });
                }
            }
        }

        let html = self.content().await?;
        let final_url = self.url().await?.unwrap_or_default();
        let antibot = status_code.map(|c| antibot::classify(c, &headers, &html));
        Ok(PageResponse {
            html,
            url: final_url,
            status_code,
            redirected: redirect_count > 0,
            headers,
            antibot,
            endpoints: finalize_endpoints(&endpoints, capture_endpoints),
            endpoints_truncated,
            endpoint_sanitizer_version: capture_endpoints.then_some(ENDPOINT_SANITIZER_VERSION),
        })
    }

    /// Wait for the in-flight navigation to finish.
    pub async fn wait_for_navigation(&self) -> Result<()> {
        self.inner
            .wait_for_navigation()
            .await
            .map_err(|e| VoidCrawlError::NavigationFailed(e.to_string()))?;
        Ok(())
    }

    /// Event-driven wait for the network to become idle.
    ///
    /// Subscribes to `Page.lifecycleEvent` and waits for one of these
    /// events (in priority order):
    ///
    /// 1. **`networkIdle`** — 0 in-flight requests for 500 ms (best signal)
    /// 2. **`networkAlmostIdle`** — ≤ 2 in-flight requests for 500 ms (fallback
    ///    when analytics / long-polls prevent true idle)
    ///
    /// Returns the name of the lifecycle event that resolved the wait
    /// (`"networkIdle"` or `"networkAlmostIdle"`), or `None` if the
    /// timeout was reached without either event firing.
    ///
    /// This is fully async and event-driven — **no polling**.
    pub async fn wait_for_network_idle(&self, timeout: Duration) -> Result<Option<String>> {
        self.ensure_network_enabled().await?;
        let mut events = self
            .inner
            .event_listener::<EventLifecycleEvent>()
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        let deadline = time::sleep(timeout);
        tokio::pin!(deadline);

        // Track the best event we've seen so far
        let mut got_almost_idle = false;

        loop {
            tokio::select! {
                biased;
                maybe_event = events.next() => {
                    match maybe_event {
                        Some(event) => {
                            match event.name.as_str() {
                                "networkIdle" => return Ok(Some("networkIdle".into())),
                                "networkAlmostIdle" => { got_almost_idle = true; }
                                _ => {} // DOMContentLoaded, load, etc — ignore
                            }
                        }
                        None => break, // stream closed
                    }
                }
                () = &mut deadline => break,
            }
        }

        // Timeout reached — return best fallback
        if got_almost_idle { Ok(Some("networkAlmostIdle".into())) } else { Ok(None) }
    }

    /// Wait until `document.querySelector(selector)` matches an element,
    /// driven by a `MutationObserver` inside the page — no Rust-side polling.
    /// Resolves immediately if the element is already present. Rejects with
    /// `VoidCrawlError::Timeout` after `timeout`.
    pub async fn wait_for_selector(&self, selector: &str, timeout: Duration) -> Result<()> {
        let sel_lit = serde_json::to_string(selector)
            .map_err(|e| VoidCrawlError::Other(format!("selector encode: {e}")))?;
        let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
        let js = format!(
            "new Promise((resolve, reject) => {{\
              const sel = {sel_lit};\
              if (document.querySelector(sel)) return resolve(true);\
              const root = document.documentElement || document.body;\
              const obs = new MutationObserver(() => {{\
                if (document.querySelector(sel)) {{\
                  obs.disconnect();\
                  clearTimeout(t);\
                  resolve(true);\
                }}\
              }});\
              obs.observe(root, {{ childList: true, subtree: true }});\
              const t = setTimeout(() => {{\
                obs.disconnect();\
                reject(new Error('wait_for_selector timeout: ' + sel));\
              }}, {timeout_ms});\
            }})"
        );
        let params = EvaluateParams::builder()
            .expression(js)
            .return_by_value(true)
            .await_promise(true)
            .build()
            .map_err(VoidCrawlError::JsEvalError)?;
        match self.inner.evaluate_expression(params).await {
            Ok(_) => Ok(()),
            Err(e) => {
                let msg = e.to_string();
                if msg.contains("wait_for_selector timeout") {
                    Err(VoidCrawlError::Timeout(format!(
                        "selector {selector:?} did not appear within {timeout_ms}ms"
                    )))
                } else {
                    Err(VoidCrawlError::JsEvalError(msg))
                }
            }
        }
    }

    // ── Content ─────────────────────────────────────────────────────────

    /// Return the full HTML of the page (outer HTML of `<html>`).
    pub async fn content(&self) -> Result<String> {
        self.inner.content().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Return the page title.
    pub async fn title(&self) -> Result<Option<String>> {
        self.inner.get_title().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Return the current URL.
    pub async fn url(&self) -> Result<Option<String>> {
        self.inner.url().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Collect the fixed, read-only document snapshot used by MCP inspection.
    ///
    /// This deliberately bypasses [`Self::ensure_active`]: the script is
    /// internal, has no caller-provided input, and only reads the current DOM.
    /// Arbitrary JavaScript remains blocked while an interrupt is active.
    pub async fn document_snapshot(&self) -> Result<Value> {
        let result = self
            .inner
            .evaluate(DOCUMENT_SNAPSHOT_JS)
            .await
            .map_err(|e| VoidCrawlError::JsEvalError(e.to_string()))?;
        Ok(result.value().cloned().unwrap_or(Value::Null))
    }

    // ── JavaScript ──────────────────────────────────────────────────────

    /// Evaluate a JS expression and return the result as a JSON value.
    pub async fn evaluate_js(&self, expression: &str) -> Result<Value> {
        self.ensure_active().await?;
        let result = self
            .inner
            .evaluate(expression)
            .await
            .map_err(|e| VoidCrawlError::JsEvalError(e.to_string()))?;
        // `into_value()` fails when the JS expression returns null/undefined
        // (the RemoteObject has no `value` field).  Fall back to Value::Null.
        match result.value() {
            Some(v) => Ok(v.clone()),
            None => Ok(Value::Null),
        }
    }

    /// Evaluate a JS expression **inside a specific frame's** execution
    /// context and return the result as a JSON value.
    ///
    /// Unlike [`Page::evaluate_js`] — which always runs in the top document —
    /// this targets the frame whose current URL contains `frame_url_pattern`.
    /// It is the only way to read or drive a **cross-origin** iframe: that
    /// frame's `contentDocument` is `null` from the parent under the
    /// same-origin policy, but CDP can evaluate in the frame's own execution
    /// context, where the origin check is satisfied. `expression` runs as if
    /// it were the frame's own page script (`document` is the frame's
    /// document).
    ///
    /// The match must be unique: more than one frame containing
    /// `frame_url_pattern` returns [`VoidCrawlError::AmbiguousFrame`]; no match
    /// (or a matched frame with no scriptable execution context — e.g. a
    /// `sandbox`ed frame without `allow-scripts`, or one not yet loaded)
    /// returns [`VoidCrawlError::FrameNotFound`].
    ///
    /// **In-process requirement.** The target frame must be in the page's
    /// renderer process for its context to be reachable here. VoidCrawl's
    /// default flags keep ordinary cross-origin frames in-process, but Chrome
    /// *field-trial*-isolates a few origins (notably google.com, hence
    /// reCAPTCHA's bframe) out-of-process regardless; those surface as
    /// `FrameNotFound`. To reach them, launch the session with
    /// `extra_args=["disable-site-isolation-trials"]` (an explicit opt-in,
    /// since it weakens the browser's isolation posture).
    pub async fn evaluate_js_in_frame(
        &self,
        frame_url_pattern: &str,
        expression: &str,
    ) -> Result<Value> {
        self.ensure_active().await?;
        let frame_id = self.resolve_frame(frame_url_pattern).await?;
        let context_id =
            self.frame_execution_context_with_runtime(frame_id, frame_url_pattern).await?;
        let params = EvaluateParams::builder()
            .expression(expression)
            .context_id(context_id)
            .return_by_value(true)
            .await_promise(true)
            .build()
            .map_err(VoidCrawlError::JsEvalError)?;
        // `evaluate_expression` (not `evaluate`) so chromiumoxide does not
        // overwrite our explicit `context_id` with the top-document context.
        let result = self
            .inner
            .evaluate_expression(params)
            .await
            .map_err(|e| VoidCrawlError::JsEvalError(e.to_string()))?;
        match result.value() {
            Some(v) => Ok(v.clone()),
            None => Ok(Value::Null),
        }
    }

    /// Resolve the single frame whose URL contains `pattern`.
    ///
    /// chromiumoxide's handler already tracks the frame tree and each frame's
    /// execution context, so this is a cheap lookup with no extra CDP round
    /// trips beyond reading cached frame URLs.
    ///
    /// **Fails closed on ambiguity.** The match must be *unique*: if more than
    /// one frame's URL contains `pattern`, this returns
    /// [`VoidCrawlError::AmbiguousFrame`] rather than silently picking one.
    /// Frame enumeration order is not stable, and a hostile page can embed a
    /// decoy frame whose URL contains a common substring — so guessing would
    /// risk running the caller's JS in the wrong (possibly attacker-scripted)
    /// frame. Use a specific pattern (e.g. `recaptcha/api2/bframe`, not
    /// `recaptcha`); [`Page::frame_urls`] helps you find one.
    async fn resolve_frame(&self, pattern: &str) -> Result<FrameId> {
        let frames =
            self.inner.frames().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let mut matched: Vec<(FrameId, String)> = Vec::new();
        for frame_id in frames {
            let url = self
                .inner
                .frame_url(frame_id.clone())
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            if let Some(url) = url {
                if url.contains(pattern) {
                    matched.push((frame_id, url));
                }
            }
        }
        match matched.len() {
            0 => Err(VoidCrawlError::FrameNotFound(pattern.to_string())),
            1 => Ok(matched.swap_remove(0).0),
            n => {
                let urls = matched.iter().map(|(_, u)| u.as_str()).collect::<Vec<_>>().join(", ");
                Err(VoidCrawlError::AmbiguousFrame(format!(
                    "{pattern:?} matched {n} frames ({urls}); use a more specific substring"
                )))
            }
        }
    }

    /// List the URLs of every frame currently tracked on this page, in no
    /// particular order. Useful for discovering the right `frame_url_pattern`
    /// to pass to [`Page::evaluate_js_in_frame`].
    pub async fn frame_urls(&self) -> Result<Vec<String>> {
        let frames =
            self.inner.frames().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let mut urls = Vec::with_capacity(frames.len());
        for frame_id in frames {
            if let Some(url) = self
                .inner
                .frame_url(frame_id)
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?
            {
                urls.push(url);
            }
        }
        Ok(urls)
    }

    // ── Viewport / device emulation ──────────────────────────────────────

    /// Persistently override this page's CDP viewport: dimensions, device
    /// pixel ratio, mobile/touch identity, and (if set) UA — the "set the
    /// viewport once, then click/navigate/screenshot as that device" flow.
    /// Stays in effect until [`Page::clear_viewport`] or another call to
    /// this method; does **not** auto-restore.
    ///
    /// `device_scale_factor` drives `window.devicePixelRatio` and CSS
    /// media-query matching (`min-resolution`, etc.) correctly, so layout
    /// and JS see a real Retina/mobile device. It does **not** change the
    /// pixel dimensions of a [`Page::screenshot`] PNG, though — CDP's
    /// `Page.captureScreenshot` renders at CSS-pixel size regardless of
    /// DPR in this configuration (tried both the device-metrics `scale`
    /// field and the per-clip `scale`; neither affected raster output).
    /// For pixel-perfect high-DPI captures, request `width`/`height`
    /// already multiplied by the density you want.
    ///
    /// For a one-off override scoped to a single capture, pass
    /// [`ScreenshotOptions::viewport`] to [`Page::screenshot`] instead —
    /// that snapshots and restores whatever was here before, so it can't
    /// leak a device identity to the next unrelated caller of a pooled tab.
    pub async fn set_viewport(&self, viewport: Viewport) -> Result<()> {
        let metrics = SetDeviceMetricsOverrideParams::new(
            i64::from(viewport.width),
            i64::from(viewport.height),
            viewport.device_scale_factor,
            viewport.mobile,
        );
        self.inner.execute(metrics).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        self.inner
            .execute(SetTouchEmulationEnabledParams::new(viewport.has_touch))
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        if let Some(ua) = viewport.user_agent.clone() {
            let (nav_platform, metadata) = if viewport.mobile {
                mobile_ua_platform_and_metadata(&ua)
            } else {
                client_hints_for_ua(&ua)
            };
            let mut builder =
                SetUserAgentOverrideParams::builder().user_agent(ua).platform(nav_platform);
            if let Some(metadata) = metadata {
                builder = builder.user_agent_metadata(metadata);
            }
            let params = builder.build().map_err(VoidCrawlError::PageError)?;
            self.inner
                .execute(params)
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        }
        *self
            .viewport_override
            .lock()
            .map_err(|_| VoidCrawlError::Other("viewport lock poisoned".into()))? = Some(viewport);
        // The device-metrics change doesn't always reflect in
        // `window.innerWidth`/media queries synchronously once the CDP
        // response returns — settle it before returning.
        self.wait_for_repaint().await
    }

    /// Clear a [`Page::set_viewport`] override, returning to the session's
    /// launch-time default viewport. Does not restore a prior UA override
    /// — call `set_viewport` again with the desired identity if you need
    /// one back.
    pub async fn clear_viewport(&self) -> Result<()> {
        self.inner
            .execute(ClearDeviceMetricsOverrideParams {})
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        self.inner
            .execute(SetTouchEmulationEnabledParams::new(false))
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        *self
            .viewport_override
            .lock()
            .map_err(|_| VoidCrawlError::Other("viewport lock poisoned".into()))? = None;
        self.wait_for_repaint().await
    }

    /// The viewport override currently in effect via [`Page::set_viewport`],
    /// or `None` if using the session's launch-time default.
    pub fn current_viewport(&self) -> Option<Viewport> {
        self.viewport_override.lock().ok().and_then(|guard| guard.clone())
    }

    // ── Screenshots & PDF ───────────────────────────────────────────────

    /// Capture a full-page PNG screenshot, returned as raw bytes.
    ///
    /// Backward-compatible shim around [`Page::screenshot`] with no
    /// options (full page, no crop, bytes in memory).
    pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
        match self.screenshot(ScreenshotOptions::default()).await? {
            ScreenshotOutput::Bytes(b) => Ok(b),
            ScreenshotOutput::Path(_) => unreachable!("no path supplied"),
        }
    }

    /// Capture a PNG screenshot with optional cropping, viewport override,
    /// scrolling, and/or writing to disk.
    ///
    /// * No `path` → returns bytes in memory.
    /// * `path` set → writes PNG to disk and returns that path.
    /// * `bbox` crops to a pixel region (CSS pixels, pre-DPR); with `scroll`
    ///   set, `bbox.x`/`bbox.y` are relative to wherever that scroll lands
    ///   rather than the top of the document.
    /// * `viewport` swaps in a device/dimension override (see
    ///   [`Page::set_viewport`]) for just this capture and restores whatever
    ///   was active before, even on error.
    /// * `scroll` moves the page before capturing (see [`ScrollTarget`]) and
    ///   restores the original scroll position after, even on error.
    pub async fn screenshot(&self, opts: ScreenshotOptions) -> Result<ScreenshotOutput> {
        if opts.bbox.is_some() && opts.selector.is_some() {
            return Err(VoidCrawlError::Other(
                "ScreenshotOptions: `bbox` and `selector` are mutually exclusive".into(),
            ));
        }

        // One-shot viewport override for just this capture — snapshot
        // whatever's already in effect so it's restored exactly, even on
        // error, so a temporary device identity never leaks to the next
        // call on this page (important on pooled tabs shared across
        // unrelated callers).
        let restore_viewport = if let Some(ref viewport) = opts.viewport {
            let prev = self.current_viewport();
            self.set_viewport(viewport.clone()).await?;
            Some(prev)
        } else {
            None
        };

        let result = self.screenshot_inner(&opts).await;

        if let Some(prev) = restore_viewport {
            let restored = match prev {
                Some(v) => self.set_viewport(v).await,
                None => self.clear_viewport().await,
            };
            let _ = restored;
        }

        result
    }

    async fn screenshot_inner(&self, opts: &ScreenshotOptions) -> Result<ScreenshotOutput> {
        // Scroll before cropping — lets a fixed viewport (e.g. a 4K
        // desktop) be paged through and a specific on-screen region cropped
        // from wherever it lands, the way a human scrolling and
        // screenshotting would. Restored after capture for the same
        // leak-proofing reason as the viewport override above.
        let restore_scroll = match opts.scroll {
            Some(_) => Some(self.scroll_position().await?),
            None => None,
        };
        let bbox_shift = if let Some(target) = opts.scroll {
            self.scroll_to(target).await?;
            self.scroll_position().await?
        } else {
            (0.0, 0.0)
        };

        // A `selector` resolves to viewport-relative coordinates *as of
        // right now* (after any scroll above), so unlike a caller-supplied
        // numeric `bbox` — specified relative to the page and shifted by
        // `bbox_shift` below — it needs no shift: `getBoundingClientRect`
        // already reflects wherever the page is currently scrolled to.
        let effective_bbox: Option<(Bbox, bool)> = if let Some(bbox) = opts.bbox {
            Some((bbox, true))
        } else if let Some(entry) = &opts.selector {
            match self.resolve_selector(entry).await? {
                SelectorResolution::Resolved { bbox } => Some((bbox, false)),
                SelectorResolution::Empty { reason } => {
                    return Err(VoidCrawlError::ElementNotVisible(reason));
                }
                SelectorResolution::Ambiguous { reason, .. } => {
                    return Err(VoidCrawlError::AmbiguousSelector(reason));
                }
            }
        } else {
            None
        };

        let mut builder = ScreenshotParams::builder().format(CaptureScreenshotFormat::Png);
        if let Some((bbox, apply_shift)) = effective_bbox {
            let (shift_x, shift_y) = if apply_shift { bbox_shift } else { (0.0, 0.0) };
            builder = builder
                .clip(CdpClipViewport {
                    x:      f64::from(bbox.x) + shift_x,
                    y:      f64::from(bbox.y) + shift_y,
                    width:  f64::from(bbox.width),
                    height: f64::from(bbox.height),
                    scale:  1.0,
                })
                // A region can legitimately sit outside the layout viewport
                // (e.g. paging through a fixed viewport via `scroll`), so
                // always allow capture beyond it rather than silently
                // clamping to whatever's currently on screen.
                .capture_beyond_viewport(true);
        } else if opts.full_page {
            builder = builder.full_page(true);
        } else if let Some(vp) = self.current_viewport() {
            // Viewport-only: an explicit clip at the tracked viewport's exact
            // size, rather than relying on Chrome's ambient "currently
            // visible" state. A prior full-page/capture-beyond-viewport
            // capture on this same page can leave that ambient state stale,
            // so an explicit size makes this mode order-independent.
            builder = builder.clip(CdpClipViewport {
                x:      0.0,
                y:      0.0,
                width:  f64::from(vp.width),
                height: f64::from(vp.height),
                scale:  1.0,
            });
        }
        // else: no tracked viewport (e.g. a page adopted via attach_page
        // that skipped apply_stealth) — leave unset and take whatever
        // Chrome currently considers the visible viewport.

        // Headless Chrome only reliably composites a frame for the
        // foregrounded tab. With several tabs sharing one browser process
        // (the pool's normal case), an un-guarded capture on a backgrounded
        // tab can fail with CDP -32000 ("Unable to capture screenshot").
        // Hold the browser-wide capture lock only for the activate+capture
        // instant — navigation, JS, and extraction on other tabs stay fully
        // concurrent; they just take turns for this one step.
        let capture_guard = self.capture_lock.lock().await;
        self.inner
            .bring_to_front()
            .await
            .map_err(|e| VoidCrawlError::ScreenshotError(e.to_string()))?;
        let bytes = self
            .inner
            .screenshot(builder.build())
            .await
            .map_err(|e| VoidCrawlError::ScreenshotError(e.to_string()))?;
        drop(capture_guard);

        if let Some((x, y)) = restore_scroll {
            let _ = self.evaluate_js(&format!("window.scrollTo({x}, {y})")).await;
        }

        if let Some(path) = opts.path.clone() {
            fs::write(&path, &bytes).map_err(|e| {
                VoidCrawlError::ScreenshotError(format!("write {}: {e}", path.display()))
            })?;
            Ok(ScreenshotOutput::Path(path))
        } else {
            Ok(ScreenshotOutput::Bytes(bytes))
        }
    }

    /// Current `window.scrollX`/`scrollY`, in CSS pixels.
    pub(crate) async fn scroll_position(&self) -> Result<(f64, f64)> {
        let value = self.evaluate_js("[window.scrollX, window.scrollY]").await?;
        let arr = value.as_array().ok_or_else(|| {
            VoidCrawlError::JsEvalError("scroll position: expected a [x, y] array".into())
        })?;
        let x = arr.first().and_then(serde_json::Value::as_f64).unwrap_or(0.0);
        let y = arr.get(1).and_then(serde_json::Value::as_f64).unwrap_or(0.0);
        Ok((x, y))
    }

    /// Scroll to `target` (see [`ScrollTarget`]) and wait for the resulting
    /// layout to actually paint — two animation frames — before the caller
    /// captures, rather than a blind sleep.
    #[allow(
        clippy::cast_precision_loss,
        reason = "scroll offsets are CSS pixels, always far below f64's 2^52 exact-integer range"
    )]
    pub(crate) async fn scroll_to(&self, target: ScrollTarget) -> Result<()> {
        let y = match target {
            ScrollTarget::Pixels(y) => y as f64,
            ScrollTarget::Viewports(n) => {
                let height = self.evaluate_js("window.innerHeight").await?.as_f64().unwrap_or(0.0);
                height * n
            }
        };
        self.evaluate_js(&format!("window.scrollTo(0, {y})")).await?;
        self.wait_for_repaint().await
    }

    /// Wait for two animation frames — a layout-affecting CDP command
    /// (device-metrics override, scroll) doesn't always reflect in
    /// `window.innerWidth`/`scrollY`/etc. synchronously once the CDP
    /// response returns; this settles it before the caller reads or
    /// captures, without a blind sleep.
    ///
    /// Bounded: `requestAnimationFrame` never fires on a backgrounded tab in
    /// headless Chrome (the same reason `screenshot()` brings a tab to
    /// front before capturing — see `capture_lock`), and this is called
    /// from `set_viewport`/`clear_viewport`, which run on pool tabs that
    /// are *not* guaranteed to be foregrounded. An unbounded wait there
    /// would deadlock pool warmup/eviction forever instead of just being
    /// occasionally stale. Best-effort: on timeout the caller's JS-visible
    /// state may lag by a frame until the tab is next foregrounded or
    /// navigated, which is an acceptable trade for "never hangs."
    async fn wait_for_repaint(&self) -> Result<()> {
        let _ = time::timeout(
            Duration::from_millis(500),
            self.evaluate_js(
                "new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))",
            ),
        )
        .await;
        Ok(())
    }

    /// Generate a PDF of the page, returned as raw bytes.
    pub async fn pdf_bytes(&self) -> Result<Vec<u8>> {
        let params = PrintToPdfParams::default();
        self.inner.pdf(params).await.map_err(|e| VoidCrawlError::PdfError(e.to_string()))
    }

    /// Download the resource at `url` into `dir`, returning the file that
    /// landed.
    ///
    /// The transfer runs inside this page's browser context — cookies, TLS
    /// fingerprint, and stealth patches are all preserved, unlike a
    /// side-channel HTTP GET. CDP
    /// `Browser.setDownloadBehavior(allowAndName)` routes the bytes to `dir`.
    ///
    /// A plain navigation only triggers a download for `Content-Disposition:
    /// attachment` responses — `inline` resources (e.g. a PDF) get rendered by
    /// Chrome's built-in viewer instead. To download *any* content type, the
    /// save is forced from inside the page: navigate to the URL's origin so an
    /// in-page `fetch` is same-origin (and carries cookies), then stream the
    /// response — **aborting past `max_bytes`** so a hostile server can't OOM
    /// the tab — into a blob and click a `download` anchor.
    ///
    /// Completion is detected by **watching the directory** (the file settling
    /// without a `.crdownload` suffix), not by `Browser.downloadProgress`
    /// events, which are unreliable in headless Chrome. The in-page fetch also
    /// reports its `Content-Type` and any error back through a `window` flag,
    /// so a failed fetch returns promptly instead of waiting out the
    /// timeout.
    ///
    /// The CDP download behavior is **always reset** before returning, so a
    /// pooled tab recycled to the next caller never inherits this download's
    /// `allowAndName` mode or output path.
    ///
    /// `dir` should be a fresh, empty directory the caller treats as quarantine
    /// and scans before trusting the file.
    pub async fn download_to_dir(
        &self,
        url: &str,
        dir: &Path,
        timeout: Duration,
        max_bytes: u64,
    ) -> Result<DownloadOutcome> {
        self.ensure_active().await?;
        let outcome = self.run_download(url, dir, timeout, max_bytes).await;
        // ALWAYS reset: setDownloadBehavior is browser-context-scoped and our
        // download_path points at a quarantine dir the caller is about to
        // delete. Leaving it set would mis-route or break the next user of a
        // recycled pool tab.
        self.reset_download_behavior().await;
        outcome
    }

    /// Arm a capture for an **action-triggered** download into `dir`, returning
    /// a [`DownloadCapture`]. Set CDP download behavior to route files into
    /// `dir`, then snapshot the directory's current contents so the matching
    /// `wait` only accepts a *new* file.
    ///
    /// Use this for the *arm → act → await* flow when a page action (a button
    /// click, a generated/redirected/cross-origin URL) starts the download —
    /// the Google-Drive case — rather than [`Page::download_to_dir`], which
    /// needs a URL in hand. After arming, perform the triggering action with
    /// the normal methods (e.g. [`Page::click_by_role`]), then call
    /// [`DownloadCapture::wait`].
    ///
    /// `dir` should be a fresh directory the caller treats as quarantine and
    /// scans before trusting the file.
    pub async fn arm_download(&self, dir: &Path, max_bytes: u64) -> Result<DownloadCapture> {
        self.ensure_active().await?;
        let params = SetDownloadBehaviorParams::builder()
            .behavior(SetDownloadBehaviorBehavior::AllowAndName)
            .download_path(dir.to_string_lossy().into_owned())
            .build()
            .map_err(VoidCrawlError::PageError)?;
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        self.download_armed.store(true, Ordering::Relaxed);
        Ok(DownloadCapture { dir: dir.to_path_buf(), before: dir_entries(dir), max_bytes })
    }

    /// Reset CDP download behavior to Chrome's default and clear the armed
    /// flag. Best-effort: failures here must not mask the download result,
    /// so errors are swallowed.
    ///
    /// Does **not** navigate the page — a caller's page state (e.g. an open
    /// session sitting on the download's origin) is left intact.
    pub async fn reset_download_behavior(&self) {
        if let Ok(params) = SetDownloadBehaviorParams::builder()
            .behavior(SetDownloadBehaviorBehavior::Default)
            .build()
        {
            let _ = self.inner.execute(params).await;
        }
        self.download_armed.store(false, Ordering::Relaxed);
    }

    async fn run_download(
        &self,
        url: &str,
        dir: &Path,
        timeout: Duration,
        max_bytes: u64,
    ) -> Result<DownloadOutcome> {
        // Snapshot the dir so we only accept a file that appears *after* arming
        // — correctness no longer depends on the caller handing us a fresh dir.
        let before = dir_entries(dir);

        let params = SetDownloadBehaviorParams::builder()
            .behavior(SetDownloadBehaviorBehavior::AllowAndName)
            .download_path(dir.to_string_lossy().into_owned())
            .build()
            .map_err(VoidCrawlError::PageError)?;
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        self.download_armed.store(true, Ordering::Relaxed);

        // Land on the target's origin so the in-page fetch below is same-origin
        // (no CORS wall, cookies included). Best-effort: a 4xx/5xx on the origin
        // root is fine, we only need a document in the right security context.
        if let Some(origin) = origin_of(url) {
            let _ = self.inner.goto(&origin).await;
        }

        // Kick off the streaming fetch→blob→anchor-click download. The IIFE
        // returns synchronously (so `evaluate_js` doesn't await a pending value)
        // and stashes progress on `window.__vcDl` for the poll loop to read.
        let url_json = serde_json::to_string(url).unwrap_or_else(|_| "''".to_string());
        let js =
            DOWNLOAD_JS.replace("__URL__", &url_json).replace("__MAX__", &max_bytes.to_string());
        self.evaluate_js(&js).await?;

        const POLL: Duration = Duration::from_millis(200);
        let deadline = time::Instant::now() + timeout;
        let mut settle = SettleTracker::new();
        let mut content_type: Option<String> = None;
        let mut done = false;

        loop {
            // Read in-page progress: surface a fetch error immediately, capture
            // the server's Content-Type, and learn when the blob save fired.
            if let Ok(state) = self.evaluate_js("window.__vcDl || null").await {
                if let Some(ct) = state.get("ct").and_then(|v| v.as_str()) {
                    content_type = Some(strip_mime_params(ct));
                }
                if let Some(err) = state.get("err").and_then(|v| v.as_str()) {
                    return Err(VoidCrawlError::Other(format!("download failed: {err}")));
                }
                if state.get("done").and_then(Value::as_bool) == Some(true) {
                    done = true;
                }
            }

            // Only trust the directory once the in-page driver reports the save
            // fired — the authoritative completion signal, not a heuristic.
            if done {
                if let Some(outcome) = settle.poll(dir, &before, max_bytes)? {
                    return Ok(DownloadOutcome { content_type, ..outcome });
                }
            }

            if time::Instant::now() >= deadline {
                return Err(VoidCrawlError::Timeout(format!(
                    "download did not complete within {}s",
                    timeout.as_secs()
                )));
            }
            time::sleep(POLL).await;
        }
    }

    /// Fetch the browser-computed accessibility (AX) tree for the root frame.
    ///
    /// Wraps CDP `Accessibility.getFullAXTree`. The result is the raw,
    /// browser-computed semantic view assistive tech sees: a **flat JSON
    /// array of nodes** linked by `childIds`/`parentId`, each carrying
    /// `role`, computed accessible `name`, `properties` (state like
    /// `focusable`/`expanded`), and `backendDOMNodeId` (the bridge back to
    /// the DOM). Implicit roles are resolved and `aria-hidden`/`display:none`
    /// nodes are pruned, so this is far more redesign-durable than markup.
    ///
    /// The tree only reflects real content once JavaScript has rendered the
    /// page — call it after navigation has settled.
    ///
    /// `depth` bounds how far descendants are walked; `None` returns the
    /// whole tree. Nodes are returned verbatim from CDP (no reshaping) so
    /// callers can address into them however they like.
    pub async fn get_full_ax_tree(&self, depth: Option<i64>) -> Result<Value> {
        let params = GetFullAxTreeParams { depth, frame_id: None };
        let resp = self
            .inner
            .execute(params)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        serde_json::to_value(&resp.result.nodes)
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Fetch the AX tree and render it as a compact, indented `role "name"`
    /// outline — the readable view, with text-noise and hidden nodes pruned.
    /// See [`crate::ax::compact_outline`] for the raw-nodes → string helper.
    pub async fn ax_tree_outline(&self, depth: Option<i64>) -> Result<String> {
        let tree = self.get_full_ax_tree(depth).await?;
        let nodes = tree.as_array().map_or(&[][..], Vec::as_slice);
        Ok(compact_outline(nodes))
    }

    /// Query the accessibility tree for nodes matching `role` and/or the
    /// computed accessible `name`, rooted at the document.
    ///
    /// Wraps CDP `Accessibility.queryAXTree`. Name matching is exact (the
    /// browser's computed accessible name). Returns the matching nodes as
    /// raw CDP JSON — the AX analogue of `query_selector_all`, but addressing
    /// by semantics rather than markup. Passing neither `role` nor `name`
    /// returns every node under the root.
    pub async fn query_ax_tree(&self, role: Option<&str>, name: Option<&str>) -> Result<Value> {
        let nodes = self.query_ax_nodes(role, name).await?;
        serde_json::to_value(&nodes).map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Internal: run `Accessibility.queryAXTree` rooted at the document and
    /// return the typed matches.
    async fn query_ax_nodes(&self, role: Option<&str>, name: Option<&str>) -> Result<Vec<AxNode>> {
        let doc = self
            .inner
            .execute(GetDocumentParams::default())
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let params = QueryAxTreeParams {
            node_id: Some(doc.result.root.node_id),
            accessible_name: name.map(str::to_string),
            role: role.map(str::to_string),
            ..Default::default()
        };
        let resp = self
            .inner
            .execute(params)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(resp.result.nodes)
    }

    /// Click an element addressed by its accessibility `role` and accessible
    /// `name` — the durable, markup-independent analogue of [`click_element`].
    ///
    /// Resolves via `Accessibility.queryAXTree`, picks the `nth` non-ignored
    /// match (0-based), bridges to the DOM through `backendDOMNodeId`, then
    /// scrolls it into view and clicks it. Errors if no such node exists.
    ///
    /// With `humanize = true`, the element is scrolled into view and then
    /// clicked at its box-model centre with a **trusted compositor** event
    /// along a human-like cursor path (see [`click_xy`]) — rather than the
    /// DOM `this.click()` used by default. Untrusted `.click()` is fine for
    /// ordinary forms but rejected by some challenge widgets.
    ///
    /// [`click_element`]: Self::click_element
    /// [`click_xy`]: Self::click_xy
    pub async fn click_by_role(
        &self,
        role: &str,
        name: &str,
        nth: usize,
        humanize: bool,
    ) -> Result<()> {
        self.ensure_active().await?;
        let nodes = self.query_ax_nodes(Some(role), Some(name)).await?;
        let backends: Vec<_> =
            nodes.iter().filter(|n| !n.ignored).filter_map(|n| n.backend_dom_node_id).collect();
        let backend_id = backends.get(nth).copied().ok_or_else(|| {
            VoidCrawlError::PageError(format!(
                "no AX node with role={role:?} name={name:?} at index {nth} (found {} match(es))",
                backends.len()
            ))
        })?;

        // Bridge AX node → DOM → JS handle. Resolve once; both paths scroll it
        // into view first.
        let resolved = self
            .inner
            .execute(ResolveNodeParams { backend_node_id: Some(backend_id), ..Default::default() })
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let object_id = resolved.result.object.object_id.ok_or_else(|| {
            VoidCrawlError::PageError("AX node could not be resolved to a DOM handle".into())
        })?;

        if humanize {
            // Scroll into view, then a trusted compositor click at the box centre.
            let scroll = CallFunctionOnParams::builder()
                .object_id(object_id)
                .function_declaration(
                    "function(){ this.scrollIntoView({block:'center',inline:'center'}); }",
                )
                .await_promise(false)
                .build()
                .map_err(VoidCrawlError::PageError)?;
            self.inner
                .execute(scroll)
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            let bm = self
                .inner
                .execute(GetBoxModelParams {
                    backend_node_id: Some(backend_id),
                    ..Default::default()
                })
                .await
                .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
            let q = bm.result.model.content.inner();
            if q.len() < 8 {
                return Err(VoidCrawlError::PageError(
                    "element has no box-model content quad".into(),
                ));
            }
            let cx = (q[0] + q[2] + q[4] + q[6]) / 4.0;
            let cy = (q[1] + q[3] + q[5] + q[7]) / 4.0;
            return self.click_xy(cx, cy, true).await;
        }

        // Default: the element's own click() — avoids box-model math and survives
        // elements that are off-screen until scrolled into view.
        let call = CallFunctionOnParams::builder()
            .object_id(object_id)
            .function_declaration(
                "function(){ this.scrollIntoView({block:'center',inline:'center'}); this.click(); }",
            )
            .await_promise(false)
            .build()
            .map_err(VoidCrawlError::PageError)?;
        self.inner.execute(call).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    // ── Selector-backed bbox resolution ──────────────────────────────────

    /// Resolve a Yosoi [`SelectorEntry`] (any of its 8 kinds) to a CSS-pixel
    /// rectangle. See the [`selector`](crate::selector) module docs for the
    /// full design: all three outcomes — resolved, empty, ambiguous — are a
    /// typed `Ok(...)`, not an exception; `Err` is reserved for genuine
    /// infra failures (a bad regex/XPath pattern, a CDP call failing).
    ///
    /// For a one-off crop, pass [`ScreenshotOptions::selector`] to
    /// [`Page::screenshot`] instead — that converts a non-`Resolved`
    /// outcome into an actionable `Err`, since a screenshot fundamentally
    /// needs a rectangle.
    pub async fn resolve_selector(&self, entry: &SelectorEntry) -> Result<SelectorResolution> {
        match entry.kind {
            SelectorKind::Jsonld => Ok(SelectorResolution::Empty {
                reason: "jsonld selectors address non-visual structured data (a <script> tag \
                         has no render box); not resolved to a rectangle"
                    .into(),
            }),
            SelectorKind::Regex => Ok(SelectorResolution::Empty {
                reason: "regex selectors match raw HTML text, which has no canonical DOM \
                         element; not resolved to a rectangle"
                    .into(),
            }),
            SelectorKind::Visual => Ok(self.resolve_visual_selector(entry).await?),
            SelectorKind::Role => self.resolve_role_selector(entry).await,
            SelectorKind::Css
            | SelectorKind::Xpath
            | SelectorKind::Attr
            | SelectorKind::GlobalId => self.resolve_dom_selector(entry).await,
        }
    }

    /// `visual`: an exact 1x1 CSS-pixel box at `(x, y)` — no invented
    /// hit-radius. `Empty` when coordinates are missing or fall outside the
    /// current viewport (`window.innerWidth`/`innerHeight`).
    async fn resolve_visual_selector(&self, entry: &SelectorEntry) -> Result<SelectorResolution> {
        let (Some(x), Some(y)) = (entry.x, entry.y) else {
            return Ok(SelectorResolution::Empty {
                reason: "visual selector requires both x and y".into(),
            });
        };
        if x < 0.0 || y < 0.0 {
            return Ok(SelectorResolution::Empty {
                reason: format!("visual point ({x}, {y}) has a negative coordinate"),
            });
        }
        let dims = self
            .evaluate_js("[window.innerWidth, window.innerHeight]")
            .await?
            .as_array()
            .cloned()
            .unwrap_or_default();
        let (vw, vh) = (
            dims.first().and_then(Value::as_f64).unwrap_or(f64::INFINITY),
            dims.get(1).and_then(Value::as_f64).unwrap_or(f64::INFINITY),
        );
        if x > vw || y > vh {
            return Ok(SelectorResolution::Empty {
                reason: format!(
                    "visual point ({x}, {y}) is outside the current viewport ({vw}x{vh})"
                ),
            });
        }
        Ok(SelectorResolution::Resolved {
            bbox: RawRect { x, y, width: 1.0, height: 1.0 }.to_bbox(),
        })
    }

    /// `role`: `Accessibility.queryAXTree` role + exact accessible-name
    /// match — the same resolution [`Page::click_by_role`] uses, so a
    /// selector that could click an element can also crop it.
    async fn resolve_role_selector(&self, entry: &SelectorEntry) -> Result<SelectorResolution> {
        let name = entry.name.as_deref();
        let nodes = self.query_ax_nodes(Some(&entry.value), name).await?;
        let backends: Vec<_> =
            nodes.iter().filter(|n| !n.ignored).filter_map(|n| n.backend_dom_node_id).collect();
        let describe = || format!("role={:?} name={:?}", entry.value, name.unwrap_or(""));

        if backends.is_empty() {
            return Ok(SelectorResolution::Empty {
                reason: format!("{} matched no AX nodes", describe()),
            });
        }
        // AX-tree matches are already "exists in the accessibility tree",
        // which excludes `display:none`/`aria-hidden` — but the box model
        // can still be a zero-area detached node, so resolve+filter each
        // candidate the same way `pick_resolution` treats DOM rects.
        let mut visible = Vec::with_capacity(backends.len());
        for backend_id in &backends {
            let bm = self
                .inner
                .execute(GetBoxModelParams {
                    backend_node_id: Some(*backend_id),
                    ..Default::default()
                })
                .await;
            let Ok(bm) = bm else { continue };
            // The *border* box, not the content box: it's what
            // `getBoundingClientRect()` returns for a typical element, and
            // every other selector kind here resolves via that same JS
            // call — using the content box would exclude an element's own
            // padding/border and disagree with them for no reason.
            let q = bm.result.model.border.inner();
            if q.len() < 8 {
                continue;
            }
            let xs = [q[0], q[2], q[4], q[6]];
            let ys = [q[1], q[3], q[5], q[7]];
            let left = xs.iter().copied().fold(f64::INFINITY, f64::min);
            let top = ys.iter().copied().fold(f64::INFINITY, f64::min);
            let right = xs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            let bottom = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            let (width, height) = (right - left, bottom - top);
            if width > 0.0 && height > 0.0 {
                visible.push(RawRect { x: left, y: top, width, height });
            }
        }
        Ok(selector::pick_resolution(backends.len(), &visible, entry.nth, describe))
    }

    /// `css` / `xpath` / `attr` / `global_id`: gather DOM candidates (see
    /// [`selector::candidates_js`]), filter to visible ones, then resolve
    /// via [`selector::pick_resolution`].
    async fn resolve_dom_selector(&self, entry: &SelectorEntry) -> Result<SelectorResolution> {
        let candidates = selector::candidates_js(entry).ok_or_else(|| {
            VoidCrawlError::PageError(format!("{:?} has no DOM candidate step", entry.kind))
        })?;
        let count_js = format!("({candidates}).length");
        let count = self.evaluate_js(&count_js).await?.as_u64().ok_or_else(|| {
            VoidCrawlError::JsEvalError("candidate count was not a number".into())
        })?;
        let total_matches = usize::try_from(count).map_err(|_| {
            VoidCrawlError::JsEvalError(format!("implausible candidate count: {count}"))
        })?;

        let rects_js = selector::visible_rects_js(&candidates);
        let raw: Value = self.evaluate_js(&rects_js).await?;
        let visible: Vec<RawRect> = serde_json::from_value(raw)
            .map_err(|e| VoidCrawlError::JsEvalError(format!("rect decode failed: {e}")))?;

        let describe = || format!("{:?} {:?}", entry.kind, entry.value);
        Ok(selector::pick_resolution(total_matches, &visible, entry.nth, describe))
    }

    /// Compact accessibility outline of a specific (possibly cross-origin)
    /// **frame** — the cross-frame analogue of [`ax_tree_outline`].
    ///
    /// Roots `Accessibility.getFullAXTree` at the frame matched by
    /// `frame_url_pattern` (resolved like [`evaluate_js_in_frame`]). The AX
    /// tree is browser-computed and ignores shadow-DOM mode, so this
    /// **pierces closed shadow roots** the page's own JavaScript cannot
    /// read — use it to discover the `role` / accessible-name to pass to
    /// [`click_ax_in_frame`].
    ///
    /// [`ax_tree_outline`]: Self::ax_tree_outline
    /// [`evaluate_js_in_frame`]: Self::evaluate_js_in_frame
    /// [`click_ax_in_frame`]: Self::click_ax_in_frame
    pub async fn ax_outline_in_frame(
        &self,
        frame_url_pattern: &str,
        depth: Option<i64>,
    ) -> Result<String> {
        let frame_id = self.resolve_frame(frame_url_pattern).await?;
        let resp = self
            .inner
            .execute(GetFullAxTreeParams { depth, frame_id: Some(frame_id) })
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let nodes = serde_json::to_value(&resp.result.nodes)
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(compact_outline(nodes.as_array().map_or(&[][..], Vec::as_slice)))
    }

    /// Locate an element by accessibility `role` + accessible `name` **inside a
    /// specific (possibly cross-origin) frame** and click it with a real
    /// **compositor** mouse event. The cross-frame, shadow-piercing analogue of
    /// [`click_by_role`].
    ///
    /// `Accessibility.getFullAXTree` rooted at the resolved frame descends into
    /// that frame's tree **including closed shadow roots** (the AX tree is
    /// browser-computed and ignores shadow mode), so it reaches widgets that
    /// `contentDocument` / page-JS cannot — e.g. Cloudflare Turnstile's
    /// "Verify you are human" checkbox, which lives in a closed shadow root
    /// inside a cross-origin `challenges.cloudflare.com` iframe. The matched
    /// node is clicked at its box-model centre via `Input.dispatchMouseEvent`
    /// (a **trusted** event), *not* a DOM `.click()` — challenge widgets reject
    /// untrusted clicks, and crucially this does **no page-JS shadow
    /// tampering**, so it does not trip Turnstile's closed-shadow check
    /// (ERROR 600010).
    ///
    /// An empty `name` matches any node of that `role`. Picks the `nth`
    /// (0-based) non-ignored match; errors if there is none.
    ///
    /// In-process requirement: as with [`evaluate_js_in_frame`], the frame must
    /// be in the page's renderer process — cross-origin google.com / cloudflare
    /// frames need the session launched with `disable-site-isolation-trials`.
    ///
    /// [`click_by_role`]: Self::click_by_role
    /// [`evaluate_js_in_frame`]: Self::evaluate_js_in_frame
    pub async fn click_ax_in_frame(
        &self,
        frame_url_pattern: &str,
        role: &str,
        name: &str,
        nth: usize,
        humanize: bool,
    ) -> Result<()> {
        let q = self.ax_content_quad_in_frame(frame_url_pattern, role, name, nth).await?;
        let cx = (q[0] + q[2] + q[4] + q[6]) / 4.0;
        let cy = (q[1] + q[3] + q[5] + q[7]) / 4.0;
        // Trusted compositor click (optionally humanized approach).
        self.click_xy(cx, cy, humanize).await
    }

    /// Locate an element by accessibility `role` + `name` **inside a specific
    /// frame** and return its on-page rectangle `[x, y, width, height]` in CSS
    /// pixels — the geometry needed to drive a **humanized** click yourself
    /// (e.g. move the cursor along a curved path with [`dispatch_mouse_event`]
    /// and press at a jittered point inside the box), rather than the single
    /// centre click of [`click_ax_in_frame`].
    ///
    /// Same cross-frame, closed-shadow-piercing resolution as
    /// [`click_ax_in_frame`]; an empty `name` matches any node of that `role`.
    ///
    /// [`dispatch_mouse_event`]: Self::dispatch_mouse_event
    /// [`click_ax_in_frame`]: Self::click_ax_in_frame
    pub async fn ax_box_in_frame(
        &self,
        frame_url_pattern: &str,
        role: &str,
        name: &str,
        nth: usize,
    ) -> Result<Vec<f64>> {
        let q = self.ax_content_quad_in_frame(frame_url_pattern, role, name, nth).await?;
        let xs = [q[0], q[2], q[4], q[6]];
        let ys = [q[1], q[3], q[5], q[7]];
        let left = xs.iter().copied().fold(f64::INFINITY, f64::min);
        let top = ys.iter().copied().fold(f64::INFINITY, f64::min);
        let right = xs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        let bottom = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        Ok(vec![left, top, right - left, bottom - top])
    }

    /// Resolve a frame-scoped AX `role`+`name` match to its box-model content
    /// quad `[x1,y1, x2,y2, x3,y3, x4,y4]` in page coordinates.
    async fn ax_content_quad_in_frame(
        &self,
        frame_url_pattern: &str,
        role: &str,
        name: &str,
        nth: usize,
    ) -> Result<Vec<f64>> {
        let backend_id = self.ax_backend_in_frame(frame_url_pattern, role, name, nth).await?;
        let bm = self
            .inner
            .execute(GetBoxModelParams { backend_node_id: Some(backend_id), ..Default::default() })
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let quad = bm.result.model.content.inner().clone();
        if quad.len() < 8 {
            return Err(VoidCrawlError::PageError("AX node has no box-model content quad".into()));
        }
        Ok(quad)
    }

    /// Resolve a frame-scoped AX `role`+`name` match to its `backendDOMNodeId`.
    async fn ax_backend_in_frame(
        &self,
        frame_url_pattern: &str,
        role: &str,
        name: &str,
        nth: usize,
    ) -> Result<BackendNodeId> {
        fn ax_text(v: Option<&AxValue>) -> &str {
            v.and_then(|a| a.value.as_ref()).and_then(Value::as_str).unwrap_or("")
        }
        let frame_id = self.resolve_frame(frame_url_pattern).await?;
        let resp = self
            .inner
            .execute(GetFullAxTreeParams { depth: None, frame_id: Some(frame_id) })
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let matched = resp
            .result
            .nodes
            .iter()
            .filter(|n| {
                !n.ignored
                    && ax_text(n.role.as_ref()) == role
                    && (name.is_empty() || ax_text(n.name.as_ref()) == name)
            })
            .filter_map(|n| n.backend_dom_node_id)
            .nth(nth);
        matched.ok_or_else(|| {
            VoidCrawlError::PageError(format!(
                "no AX node with role={role:?} name={name:?} at index {nth} in frame {frame_url_pattern:?}"
            ))
        })
    }

    // ── Humanized pointer input (CAS-147) ───────────────────────────────

    /// Move the virtual cursor to `(x, y)` via CDP `Input.dispatchMouseEvent`.
    ///
    /// With `humanize = true` the cursor travels a realistic path from its last
    /// position — non-linear (arc) curvature, a minimum-jerk velocity profile,
    /// small tremor, and a brief dwell — as multiple `MouseMoved` events
    /// ([`crate::input`]). With `humanize = false` it jumps in a single event.
    /// **No page-world JS** is injected. The path length/duration scale with
    /// distance and stay bounded for agent workflows.
    pub async fn move_mouse(&self, x: f64, y: f64, humanize: bool) -> Result<()> {
        self.ensure_active().await?;
        if humanize {
            let start = *self
                .cursor
                .lock()
                .map_err(|_| VoidCrawlError::Other("cursor lock poisoned".into()))?;
            let mut rng = Rng::seed(runtime_seed());
            let path = humanized_path(start, (x, y), &HumanizeOptions::default(), &mut rng);
            for step in path {
                time::sleep(Duration::from_millis(step.delay_ms)).await;
                self.dispatch_mouse_event(
                    DispatchMouseEventType::MouseMoved,
                    step.x,
                    step.y,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .await?;
            }
        } else {
            self.dispatch_mouse_event(
                DispatchMouseEventType::MouseMoved,
                x,
                y,
                None,
                None,
                None,
                None,
                None,
            )
            .await?;
        }
        *self.cursor.lock().map_err(|_| VoidCrawlError::Other("cursor lock poisoned".into()))? =
            (x, y);
        Ok(())
    }

    /// Click at `(x, y)` with a **trusted** compositor event (press → release).
    /// With `humanize = true`, the cursor first travels a human-like path to
    /// the point (see [`move_mouse`]). The analogue of
    /// `click_visual_coords`.
    ///
    /// [`move_mouse`]: Self::move_mouse
    pub async fn click_xy(&self, x: f64, y: f64, humanize: bool) -> Result<()> {
        self.ensure_active().await?;
        self.move_mouse(x, y, humanize).await?;
        self.dispatch_mouse_event(
            DispatchMouseEventType::MousePressed,
            x,
            y,
            Some(MouseButton::Left),
            Some(1),
            None,
            None,
            None,
        )
        .await?;
        self.dispatch_mouse_event(
            DispatchMouseEventType::MouseReleased,
            x,
            y,
            Some(MouseButton::Left),
            Some(1),
            None,
            None,
            None,
        )
        .await?;
        Ok(())
    }

    // ── Emulation ───────────────────────────────────────────────────────

    /// Override the page's geolocation. Geo-aware sites (maps, "near me"
    /// search, store locators) will behave as if the browser is at these
    /// coordinates. `accuracy` defaults to 50 metres.
    ///
    /// Note: sites that read `navigator.geolocation` still gate on the
    /// geolocation *permission* (granted here) and require a secure context
    /// (https / localhost), not `data:` URLs. Header/IP-driven geo (e.g.
    /// Google Maps) keys off [`set_locale`] and the request URL more than this.
    ///
    /// [`set_locale`]: Self::set_locale
    pub async fn set_geolocation(
        &self,
        latitude: f64,
        longitude: f64,
        accuracy: Option<f64>,
    ) -> Result<()> {
        self.ensure_active().await?;
        // Grant the geolocation permission first, otherwise headless Chrome
        // auto-denies `navigator.geolocation` and the override is never read.
        // Origin omitted → applies to every origin (incl. opaque `data:`).
        let grant = SetPermissionParams {
            permission:         PermissionDescriptor::new("geolocation"),
            setting:            PermissionSetting::Granted,
            origin:             None,
            embedded_origin:    None,
            browser_context_id: None,
        };
        self.inner.execute(grant).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        let params = SetGeolocationOverrideParams {
            latitude: Some(latitude),
            longitude: Some(longitude),
            accuracy: Some(accuracy.unwrap_or(50.0)),
            ..Default::default()
        };
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Override the JS locale and `Accept-Language` (e.g. `"en-US"`,
    /// `"fr-FR"`). This is the lever that shifts region-aware content like
    /// Google Maps results or localized pricing.
    pub async fn set_locale(&self, locale: &str) -> Result<()> {
        self.ensure_active().await?;
        let params = SetLocaleOverrideParams { locale: Some(locale.to_string()) };
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Override the timezone by IANA id (e.g. `"America/New_York"`). Affects
    /// `Date`, `Intl`, and any server probes that read the rendered clock.
    pub async fn set_timezone(&self, timezone_id: &str) -> Result<()> {
        self.ensure_active().await?;
        let params = SetTimezoneOverrideParams::new(timezone_id.to_string());
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    // ── DOM Queries ─────────────────────────────────────────────────────

    /// Run `document.querySelector(selector)` and return the inner HTML.
    /// Returns `None` if no element matches. Void elements (e.g. `<input>`)
    /// return `Some("")`.
    ///
    /// Uses a JS eval rather than `find_element` so that a missing element
    /// returns `Ok(None)` without any CDP error — real errors (closed browser,
    /// network failure, etc.) still propagate as `Err`.
    pub async fn query_selector(&self, selector: &str) -> Result<Option<String>> {
        // `querySelector` returns null for no match — never throws — so the
        // only error path here is a real CDP failure, not a missing element.
        let js = format!(
            "(function(){{ var el = document.querySelector({selector:?}); \
             return el === null ? null : el.innerHTML; }})()"
        );
        let result = self
            .inner
            .evaluate_expression(js)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        // `into_value()` returns Err("No value found") when JS evaluates to
        // null/undefined — that is exactly the "not found" case, not a real
        // error, so map it to Ok(None).
        let val: Value = match result.into_value() {
            Ok(v) => v,
            Err(_) => return Ok(None),
        };

        match val {
            Value::Null => Ok(None),
            Value::String(s) => Ok(Some(s)),
            other => Ok(Some(other.to_string())),
        }
    }

    /// Run `document.querySelectorAll(selector)` and return inner HTML of each.
    /// One entry is returned per matched element; void elements yield `""`.
    pub async fn query_selector_all(&self, selector: &str) -> Result<Vec<String>> {
        // Single JS eval returns all innerHTML at once — avoids N serial CDP
        // round-trips (one per element) that the old find_elements approach needed.
        let js = format!("[...document.querySelectorAll({selector:?})].map(e => e.innerHTML)");
        let val: Value = self
            .inner
            .evaluate_expression(js)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?
            .into_value()
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;

        match val {
            Value::Array(arr) => Ok(arr
                .into_iter()
                .map(|v| match v {
                    Value::String(s) => s,
                    other => other.to_string(),
                })
                .collect()),
            _ => Ok(Vec::new()),
        }
    }

    // ── Interaction ─────────────────────────────────────────────────────

    /// Click on the first element matching `selector`.
    pub async fn click_element(&self, selector: &str) -> Result<()> {
        self.ensure_active().await?;
        let el = self
            .inner
            .find_element(selector)
            .await
            .map_err(|e| VoidCrawlError::ElementNotFound(e.to_string()))?;
        el.click().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Type text into the first element matching `selector`.
    ///
    /// Focuses the element first so that key events are directed to it.
    pub async fn type_into(&self, selector: &str, text: &str) -> Result<()> {
        self.ensure_active().await?;
        let el = self
            .inner
            .find_element(selector)
            .await
            .map_err(|e| VoidCrawlError::ElementNotFound(e.to_string()))?;
        el.focus().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        el.type_str(text).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    // ── Headers & Network ───────────────────────────────────────────────

    /// Set extra HTTP headers for all subsequent requests from this page.
    pub async fn set_headers(&self, headers: HashMap<String, String>) -> Result<()> {
        self.ensure_active().await?;
        self.ensure_network_enabled().await?;
        let json_val =
            serde_json::to_value(&headers).map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        let params = SetExtraHttpHeadersParams::new(Headers::new(json_val));
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    // ── Cookies ─────────────────────────────────────────────────────────

    /// Return all cookies that match the current page URL.
    pub async fn get_cookies(&self) -> Result<Vec<Cookie>> {
        self.inner.get_cookies().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))
    }

    /// Set a single cookie on the current page.
    pub async fn set_cookie(&self, cookie: CookieParam) -> Result<()> {
        self.ensure_active().await?;
        self.inner
            .set_cookie(cookie)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Set multiple cookies at once.
    pub async fn set_cookies(&self, cookies: Vec<CookieParam>) -> Result<()> {
        self.ensure_active().await?;
        self.inner
            .set_cookies(cookies)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Delete cookies by name, optionally scoped by domain and path.
    pub async fn delete_cookies(&self, cookies: Vec<DeleteCookiesParams>) -> Result<()> {
        self.ensure_active().await?;
        self.inner
            .delete_cookies(cookies)
            .await
            .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    // ── CDP Input ───────────────────────────────────────────────────────

    /// Dispatch a mouse event via the CDP `Input.dispatchMouseEvent` command.
    ///
    /// This sends a **browser-level** input event — as opposed to a JS
    /// `dispatchEvent(new MouseEvent(...))` — so it is processed by the
    /// compositor and behaves like a real user action (including triggering
    /// hover states, native drag, etc.).
    #[allow(clippy::too_many_arguments)]
    pub async fn dispatch_mouse_event(
        &self,
        event_type: DispatchMouseEventType,
        x: f64,
        y: f64,
        button: Option<MouseButton>,
        click_count: Option<i64>,
        delta_x: Option<f64>,
        delta_y: Option<f64>,
        modifiers: Option<i64>,
    ) -> Result<()> {
        self.ensure_active().await?;
        let mut builder = DispatchMouseEventParams::builder().r#type(event_type).x(x).y(y);

        if let Some(b) = button {
            builder = builder.button(b);
        }
        if let Some(c) = click_count {
            builder = builder.click_count(c);
        }
        if let Some(dx) = delta_x {
            builder = builder.delta_x(dx);
        }
        if let Some(dy) = delta_y {
            builder = builder.delta_y(dy);
        }
        if let Some(m) = modifiers {
            builder = builder.modifiers(m);
        }

        let params = builder.build().map_err(VoidCrawlError::PageError)?;
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Dispatch a key event via the CDP `Input.dispatchKeyEvent` command.
    ///
    /// Sends a browser-level keyboard event. Use `KeyDown` + `KeyUp` for
    /// modifier keys or special keys, and `Char` for text input.
    pub async fn dispatch_key_event(
        &self,
        event_type: DispatchKeyEventType,
        key: Option<&str>,
        code: Option<&str>,
        text: Option<&str>,
        modifiers: Option<i64>,
    ) -> Result<()> {
        self.ensure_active().await?;
        let mut builder = DispatchKeyEventParams::builder().r#type(event_type);

        if let Some(k) = key {
            builder = builder.key(k);
        }
        if let Some(c) = code {
            builder = builder.code(c);
        }
        if let Some(t) = text {
            builder = builder.text(t);
        }
        if let Some(m) = modifiers {
            builder = builder.modifiers(m);
        }

        let params = builder.build().map_err(VoidCrawlError::PageError)?;
        self.inner.execute(params).await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Close this page / tab.
    pub async fn close(&self) -> Result<()> {
        self.inner.clone().close().await.map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
        Ok(())
    }

    /// Access the underlying chromiumoxide Page for advanced usage.
    pub fn inner(&self) -> &CdpPage {
        &self.inner
    }
}

/// In-page download driver. `__URL__` and `__MAX__` are substituted before
/// evaluation. Streams the response, aborting past `__MAX__` bytes so a hostile
/// server can't OOM the tab, then saves the bytes via a blob `download` anchor
/// (which forces a save even for `Content-Disposition: inline` resources like
/// PDFs that Chrome would otherwise render). Progress is reported on
/// `window.__vcDl = { ct, err, done }` for the Rust poll loop.
const DOWNLOAD_JS: &str = r"(() => {
  window.__vcDl = { ct: null, err: null, done: false };
  (async () => {
    try {
      const MAX = __MAX__;
      const ctrl = new AbortController();
      const resp = await fetch(__URL__, { credentials: 'include', signal: ctrl.signal });
      window.__vcDl.ct = resp.headers.get('content-type');
      const cl = resp.headers.get('content-length');
      if (cl && Number(cl) > MAX) { ctrl.abort(); throw new Error('content-length ' + cl + ' exceeds limit ' + MAX); }
      let blob;
      if (resp.body && resp.body.getReader) {
        const reader = resp.body.getReader();
        const chunks = []; let total = 0;
        for (;;) {
          const { done, value } = await reader.read();
          if (done) break;
          total += value.byteLength;
          if (total > MAX) { ctrl.abort(); throw new Error('exceeded size limit ' + MAX + ' bytes'); }
          chunks.push(value);
        }
        blob = new Blob(chunks);
      } else {
        blob = await resp.blob();
        if (blob.size > MAX) throw new Error('exceeded size limit ' + MAX + ' bytes');
      }
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = (__URL__.split(/[?#]/)[0].split('/').pop()) || 'download';
      (document.body || document.documentElement).appendChild(a);
      a.click();
      window.__vcDl.done = true;
    } catch (e) {
      window.__vcDl.err = String((e && e.message) || e);
    }
  })();
  return true;
})()";

/// Strip parameters from a MIME type: `application/pdf; charset=utf-8` →
/// `application/pdf`.
fn strip_mime_params(mime: &str) -> String {
    mime.split(';').next().unwrap_or(mime).trim().to_ascii_lowercase()
}

/// `scheme://host[:port]` for `url`, or `None` if it isn't an absolute URL.
fn origin_of(url: &str) -> Option<String> {
    let (scheme, rest) = url.split_once("://")?;
    let host = rest.split(['/', '?', '#']).next()?;
    if host.is_empty() {
        return None;
    }
    Some(format!("{scheme}://{host}"))
}

/// Snapshot the set of paths currently in `dir` (empty on a read error).
fn dir_entries(dir: &Path) -> HashSet<PathBuf> {
    fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).collect()
}

/// Finished (non-`.crdownload`, non-empty) files in `dir` that are **not** in
/// `before` — i.e. downloads that appeared after the snapshot.
fn new_complete_files(dir: &Path, before: &HashSet<PathBuf>) -> Vec<(PathBuf, u64)> {
    let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
    rd.flatten()
        .filter_map(|entry| {
            let path = entry.path();
            if before.contains(&path) || path.extension().is_some_and(|e| e == "crdownload") {
                return None;
            }
            match entry.metadata() {
                Ok(m) if m.is_file() && m.len() > 0 => Some((path, m.len())),
                _ => None,
            }
        })
        .collect()
}

/// Number of identical consecutive size samples required before a file is
/// accepted — ~2 poll intervals of an unchanged size, so a stream that pauses
/// mid-write isn't captured truncated.
const SETTLE_SIGHTINGS: u32 = 3;

/// Tracks the size-stability of the newest new download across polls.
struct SettleTracker {
    prev:   Option<(PathBuf, u64)>,
    stable: u32,
}

impl SettleTracker {
    fn new() -> Self {
        Self { prev: None, stable: 0 }
    }

    /// One poll over `dir`. `Ok(Some(_))` once a single new file's size has
    /// held steady for [`SETTLE_SIGHTINGS`] samples; `Ok(None)` to keep
    /// waiting; `Err` if more than one new file appeared (ambiguous) or the
    /// file is oversized (deleted first).
    fn poll(
        &mut self,
        dir: &Path,
        before: &HashSet<PathBuf>,
        max_bytes: u64,
    ) -> Result<Option<DownloadOutcome>> {
        let files = new_complete_files(dir, before);
        if files.len() > 1 {
            let names = files
                .iter()
                .filter_map(|(p, _)| p.file_name().map(|n| n.to_string_lossy().into_owned()))
                .collect::<Vec<_>>()
                .join(", ");
            return Err(VoidCrawlError::Other(format!(
                "ambiguous download: {} new files appeared ({names}); expected exactly one",
                files.len()
            )));
        }
        let Some((path, size)) = files.into_iter().next() else {
            self.prev = None;
            self.stable = 0;
            return Ok(None);
        };

        if self.prev.as_ref().is_some_and(|(p, s)| *p == path && *s == size) {
            self.stable += 1;
        } else {
            self.prev = Some((path.clone(), size));
            self.stable = 1;
        }
        if self.stable < SETTLE_SIGHTINGS {
            return Ok(None);
        }
        if size > max_bytes {
            let _ = fs::remove_file(&path);
            return Err(VoidCrawlError::Other(format!(
                "download is {size} bytes, over the {max_bytes}-byte limit"
            )));
        }
        Ok(Some(DownloadOutcome { path, bytes: size, content_type: None }))
    }
}

/// Poll `dir` until a **new** completed download settles (see
/// [`SettleTracker::poll`]), or `timeout` elapses.
async fn wait_for_new_download(
    dir: &Path,
    before: &HashSet<PathBuf>,
    max_bytes: u64,
    timeout: Duration,
) -> Result<DownloadOutcome> {
    const POLL: Duration = Duration::from_millis(250);
    let deadline = time::Instant::now() + timeout;
    let mut settle = SettleTracker::new();

    loop {
        if let Some(outcome) = settle.poll(dir, before, max_bytes)? {
            return Ok(outcome);
        }
        if time::Instant::now() >= deadline {
            return Err(VoidCrawlError::Timeout(format!(
                "no download completed within {}s",
                timeout.as_secs()
            )));
        }
        time::sleep(POLL).await;
    }
}

/// Probe the browser's real User-Agent and strip any "Headless"
/// qualifier. Returns `Some(stripped_ua)` when the probe finds
/// `HeadlessChrome` (or similar) and a rewrite is needed; returns
/// `None` otherwise, signalling "no override necessary".
///
/// Headless Chrome advertises itself as `HeadlessChrome/<ver>` — an
/// instant bot signal. By probing the real UA and rewriting only the
/// `Headless` substring, we keep the version accurate (no stale
/// hardcoded UA string) while removing the fingerprint.
async fn probe_user_agent(page: &CdpPage) -> Result<Option<String>> {
    let probe = page
        .evaluate("navigator.userAgent")
        .await
        .map_err(|e| VoidCrawlError::PageError(e.to_string()))?;
    match probe.value().cloned() {
        Some(Value::String(ua)) => Ok(Some(ua)),
        _ => Ok(None),
    }
}

/// Strip any "Headless" token from a UA. Headless Chrome advertises
/// `HeadlessChrome/<ver>` — an instant bot signal. Rewriting only the
/// `Headless` substring keeps the version accurate (no stale hardcoded UA).
fn dehead(ua: &str) -> String {
    if ua.contains("HeadlessChrome") {
        ua.replace("HeadlessChrome", "Chrome")
    } else if ua.contains("Headless") {
        ua.replace("Headless", "")
    } else {
        ua.to_string()
    }
}

/// Derive a coherent `navigator.platform` value and Client-Hints
/// [`UserAgentMetadata`] from a UA string, so the UA, `navigator.platform`,
/// and `navigator.userAgentData` all agree. A mismatch between them (e.g. a
/// Linux UA with `navigator.platform == "Win32"`, or empty `brands`) is a
/// strong bot signal. Best-effort: an unrecognized UA gets a generic
/// Linux/x86_64 identity, and a missing Chrome version yields empty brands
/// rather than a wrong one.
fn client_hints_for_ua(ua: &str) -> (String, Option<UserAgentMetadata>) {
    // (navigator.platform, Sec-CH-UA-Platform, platformVersion)
    let (nav_platform, ch_platform, platform_version) = if ua.contains("Windows") {
        ("Win32", "Windows", "15.0.0")
    } else if ua.contains("Mac OS X") || ua.contains("Macintosh") {
        ("MacIntel", "macOS", "14.5.0")
    } else {
        ("Linux x86_64", "Linux", "6.8.0")
    };

    // Chrome version from the UA: "…Chrome/148.0.0.0 …" → major "148", full
    // "148.0.0.0". `None` when absent (non-Chrome UA) → no brands.
    let chrome_ver: Option<&str> =
        ua.split("Chrome/").nth(1).and_then(|s| s.split_whitespace().next());
    let major: Option<&str> = chrome_ver.and_then(|v| v.split('.').next());

    let mut builder = UserAgentMetadata::builder()
        .platform(ch_platform)
        .platform_version(platform_version)
        .architecture("x86")
        .model("")
        .mobile(false)
        .bitness("64")
        .wow64(false);

    if let (Some(major), Some(full)) = (major, chrome_ver) {
        // Low-entropy `brands` (major only) + `fullVersionList` (full), each
        // with a GREASE entry, mirroring what real Chrome emits.
        builder = builder
            .brands([
                UserAgentBrandVersion::new("Chromium", major),
                UserAgentBrandVersion::new("Google Chrome", major),
                UserAgentBrandVersion::new("Not_A Brand", "24"),
            ])
            .full_version_lists([
                UserAgentBrandVersion::new("Chromium", full),
                UserAgentBrandVersion::new("Google Chrome", full),
                UserAgentBrandVersion::new("Not_A Brand", "24.0.0.0"),
            ]);
    }

    // build() only errors if a mandatory field is unset; platform,
    // platform_version, architecture, model, and mobile are all set above, so
    // this is `Some` in practice. `None` (unreachable) simply skips metadata.
    (nav_platform.to_string(), builder.build().ok())
}

/// The mobile counterpart to [`client_hints_for_ua`], used by
/// [`Page::set_viewport`] for device-preset UAs. Real Safari (iPhone/iPad
/// UAs) never sends Client-Hints headers at all, so those get a plain UA
/// override with no fabricated metadata — matching a real device rather
/// than inventing brands Safari itself doesn't have. Chrome-on-Android UAs
/// get `mobile: true` metadata built the same way `client_hints_for_ua`
/// builds it for desktop Chrome.
fn mobile_ua_platform_and_metadata(ua: &str) -> (String, Option<UserAgentMetadata>) {
    if ua.contains("iPad") {
        return ("iPad".to_string(), None);
    }
    if ua.contains("iPhone") {
        return ("iPhone".to_string(), None);
    }

    let chrome_ver: Option<&str> =
        ua.split("Chrome/").nth(1).and_then(|s| s.split_whitespace().next());
    let major: Option<&str> = chrome_ver.and_then(|v| v.split('.').next());

    let mut builder = UserAgentMetadata::builder()
        .platform("Android")
        .platform_version("14.0.0")
        .architecture("")
        .model("")
        .mobile(true)
        .bitness("64")
        .wow64(false);

    if let (Some(major), Some(full)) = (major, chrome_ver) {
        builder = builder
            .brands([
                UserAgentBrandVersion::new("Chromium", major),
                UserAgentBrandVersion::new("Google Chrome", major),
                UserAgentBrandVersion::new("Not_A Brand", "24"),
            ])
            .full_version_lists([
                UserAgentBrandVersion::new("Chromium", full),
                UserAgentBrandVersion::new("Google Chrome", full),
                UserAgentBrandVersion::new("Not_A Brand", "24.0.0.0"),
            ]);
    }

    ("Linux armv8l".to_string(), builder.build().ok())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, reason = "test harness")]
mod download_tests {
    use std::{fs, path::Path};

    use super::{SETTLE_SIGHTINGS, SettleTracker, dir_entries, new_complete_files};

    fn touch(dir: &Path, name: &str, bytes: usize) {
        fs::write(dir.join(name), vec![0u8; bytes]).unwrap();
    }

    #[test]
    fn new_complete_files_excludes_before_crdownload_and_empty() {
        let d = tempfile::tempdir().unwrap();
        touch(d.path(), "old.bin", 10);
        let before = dir_entries(d.path());
        touch(d.path(), "new.bin", 10);
        touch(d.path(), "partial.crdownload", 10);
        touch(d.path(), "empty.bin", 0);
        let files = new_complete_files(d.path(), &before);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].0.file_name().unwrap(), "new.bin");
    }

    #[test]
    fn settle_requires_stable_samples_then_accepts() {
        let d = tempfile::tempdir().unwrap();
        let before = dir_entries(d.path());
        touch(d.path(), "f.bin", 100);
        let mut s = SettleTracker::new();
        for _ in 0..(SETTLE_SIGHTINGS - 1) {
            assert!(s.poll(d.path(), &before, 1_000).unwrap().is_none());
        }
        assert_eq!(s.poll(d.path(), &before, 1_000).unwrap().unwrap().bytes, 100);
    }

    #[test]
    fn settle_resets_when_size_still_changing() {
        let d = tempfile::tempdir().unwrap();
        let before = dir_entries(d.path());
        touch(d.path(), "f.bin", 10);
        let mut s = SettleTracker::new();
        s.poll(d.path(), &before, 1_000).unwrap();
        touch(d.path(), "f.bin", 20); // still growing → counter resets
        assert!(s.poll(d.path(), &before, 1_000).unwrap().is_none());
    }

    #[test]
    fn settle_rejects_and_deletes_oversize() {
        let d = tempfile::tempdir().unwrap();
        let before = dir_entries(d.path());
        touch(d.path(), "big.bin", 50);
        let mut s = SettleTracker::new();
        let mut last = Ok(None);
        for _ in 0..SETTLE_SIGHTINGS {
            last = s.poll(d.path(), &before, 8);
        }
        assert!(last.is_err());
        assert!(!d.path().join("big.bin").exists(), "oversize file should be deleted");
    }

    #[test]
    fn settle_errors_on_multiple_new_files() {
        let d = tempfile::tempdir().unwrap();
        let before = dir_entries(d.path());
        touch(d.path(), "a.bin", 10);
        touch(d.path(), "b.bin", 10);
        let mut s = SettleTracker::new();
        assert!(s.poll(d.path(), &before, 1_000).is_err());
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, reason = "test harness")]
mod tests {
    use std::collections::HashSet;

    use super::{client_hints_for_ua, dehead, finalize_endpoints, safe_endpoint};

    #[test]
    fn safe_endpoint_strips_query_and_fragment() {
        assert_eq!(
            safe_endpoint("https://api.example.com/v2/search?token=SECRET&q=ada#frag"),
            Some("https://api.example.com/v2/search".to_string())
        );
        // host + scheme lowercased; bare host, no path.
        assert_eq!(
            safe_endpoint("HTTPS://API.Example.COM"),
            Some("https://api.example.com".to_string())
        );
        // non-default port is kept (it's infra signature, not a secret).
        assert_eq!(
            safe_endpoint("https://api.example.com:8443/v1/quote"),
            Some("https://api.example.com:8443/v1/quote".to_string())
        );
    }

    #[test]
    fn safe_endpoint_drops_userinfo_and_nonhttp_and_local() {
        // userinfo (embedded credentials) removed.
        assert_eq!(
            safe_endpoint("https://alice:hunter2@host.com/p"),
            Some("https://host.com/p".to_string())
        );
        // non-http(s) schemes are never archived.
        assert_eq!(safe_endpoint("ws://host.com/socket"), None);
        assert_eq!(safe_endpoint("data:text/html,hi"), None);
        // loopback / private / link-local hosts (operator environment) dropped.
        assert_eq!(safe_endpoint("http://127.0.0.1:9000/api"), None);
        assert_eq!(safe_endpoint("http://localhost/api"), None);
        assert_eq!(safe_endpoint("http://192.168.1.5/api"), None);
        assert_eq!(safe_endpoint("http://172.16.0.9/api"), None);
        // 172.x outside the private 16-31 band is public — kept.
        assert!(safe_endpoint("http://172.32.0.1/api").is_some());
    }

    #[test]
    fn safe_endpoint_redacts_secret_path_segments() {
        // JWT-like high-entropy blob.
        let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        assert_eq!(
            safe_endpoint(&format!("https://h.com/reset/{jwt}")),
            Some("https://h.com/reset/:redacted".to_string())
        );
        // email PII segment.
        assert_eq!(
            safe_endpoint("https://h.com/u/ada@example.com/profile"),
            Some("https://h.com/u/:redacted/profile".to_string())
        );
        // long digit run (card/SSN/phone range).
        assert_eq!(
            safe_endpoint("https://h.com/pay/4111111111111111"),
            Some("https://h.com/pay/:redacted".to_string())
        );
        // an ordinary short numeric id is NOT redacted — templatizing is the
        // consumer's job, not the crawler's.
        assert_eq!(
            safe_endpoint("https://h.com/users/123/profile"),
            Some("https://h.com/users/123/profile".to_string())
        );
    }

    #[test]
    fn safe_endpoint_redacts_by_default_holes() {
        // Holes a denylist missed; redact-by-default catches them:
        // a >15-char opaque token (a real key would be kept under the old >=32
        // rule; a low-entropy stand-in here keeps the secret-scanner happy).
        assert_eq!(
            safe_endpoint("https://h.com/v1/keys/tokentokentokentoken"),
            Some("https://h.com/v1/keys/:redacted".to_string())
        );
        // a 16-char all-hex token (2-class, slipped the old digit+alpha gate).
        assert_eq!(
            safe_endpoint("https://h.com/t/a1b2c3d4e5f6a7b8"),
            Some("https://h.com/t/:redacted".to_string())
        );
        // matrix-param session id (`;jsessionid=`) — never handled before.
        assert_eq!(
            safe_endpoint("https://h.com/store;jsessionid=ABC123/cart"),
            Some("https://h.com/:redacted/cart".to_string())
        );
        // a 12-15 char mixed-case+digit token (under the length/digit/hex caps)
        // is still an opaque secret → redacted by the 3-character-class rule.
        assert_eq!(
            safe_endpoint("https://h.com/s/aB3xK9mP2qR5w"),
            Some("https://h.com/s/:redacted".to_string())
        );
        // template words + a version segment survive (the endpoint skeleton);
        // path case is preserved (only the host is lowercased).
        assert_eq!(
            safe_endpoint("https://q1.finance.yahoo.com/v10/finance/quoteSummary/AAPL"),
            Some("https://q1.finance.yahoo.com/v10/finance/quoteSummary/AAPL".to_string())
        );
    }

    #[test]
    fn safe_endpoint_handles_ipv6_and_cgnat_local_hosts() {
        // bracketed IPv6 loopback — `split(':')` would yield "[" and leak it.
        assert_eq!(safe_endpoint("http://[::1]:9000/api"), None);
        assert_eq!(safe_endpoint("http://[fe80::1]/api"), None);
        // CGNAT (RFC-6598) and mDNS .local are operator-network, not the page.
        assert_eq!(safe_endpoint("http://100.64.0.7/api"), None);
        assert_eq!(safe_endpoint("http://printer.local/status"), None);
        // a public IPv6 host is kept (bracket form parsed correctly).
        assert!(safe_endpoint("http://[2606:4700::1111]/cdn-cgi").is_some());
    }

    #[test]
    fn finalize_endpoints_none_when_not_capturing_else_sorted() {
        let mut seen = HashSet::new();
        seen.insert("https://b.com/2".to_string());
        seen.insert("https://a.com/1".to_string());
        assert_eq!(finalize_endpoints(&seen, false), None);
        assert_eq!(
            finalize_endpoints(&seen, true),
            Some(vec!["https://a.com/1".to_string(), "https://b.com/2".to_string()])
        );
        // capturing with nothing seen → Some(empty), distinct from None ("not
        // captured").
        assert_eq!(finalize_endpoints(&HashSet::new(), true), Some(vec![]));
    }

    const LINUX_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36";
    const WIN_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36";
    const MAC_UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36";

    #[test]
    fn dehead_strips_headless_token() {
        assert_eq!(
            dehead("Mozilla/5.0 HeadlessChrome/148.0.0.0 Safari"),
            "Mozilla/5.0 Chrome/148.0.0.0 Safari"
        );
        // No Headless token → unchanged.
        assert_eq!(dehead(LINUX_UA), LINUX_UA);
    }

    /// navigator.platform + Sec-CH-UA-Platform must match the UA's OS — the
    /// mismatch (Linux UA + "Win32") was the bug.
    #[test]
    fn platform_matches_ua_os() {
        assert_eq!(client_hints_for_ua(LINUX_UA).0, "Linux x86_64");
        assert_eq!(client_hints_for_ua(WIN_UA).0, "Win32");
        assert_eq!(client_hints_for_ua(MAC_UA).0, "MacIntel");

        let md = client_hints_for_ua(LINUX_UA).1.unwrap();
        assert_eq!(md.platform, "Linux");
        assert!(!md.mobile);
        assert_eq!(md.architecture, "x86");
    }

    /// Client-Hints brands are populated and carry the UA's Chrome major
    /// version (empty brands was the other half of the bug).
    #[test]
    fn brands_carry_chrome_major_version() {
        let md = client_hints_for_ua(LINUX_UA).1.unwrap();
        let brands = md.brands.unwrap();
        assert!(brands.iter().any(|b| b.brand == "Google Chrome" && b.version == "148"));
        assert!(brands.iter().any(|b| b.brand == "Chromium" && b.version == "148"));
        // A GREASE entry is present (3 brands total).
        assert_eq!(brands.len(), 3);
        // fullVersionList carries the full version.
        let full = md.full_version_list.unwrap();
        assert!(full.iter().any(|b| b.brand == "Google Chrome" && b.version == "148.0.0.0"));
    }

    /// A non-Chrome UA yields no brands rather than a wrong/fabricated one,
    /// but still gets a coherent platform.
    #[test]
    fn non_chrome_ua_has_no_brands() {
        let firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0";
        let (nav_platform, md) = client_hints_for_ua(firefox);
        assert_eq!(nav_platform, "Linux x86_64");
        assert!(md.unwrap().brands.is_none());
    }
}