zendriver 0.2.27

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

use serde_json::{Value, json};
use zendriver_transport::SessionHandle;

use crate::element::Element;
use crate::error::{Result, ZendriverError};
use crate::frame::Frame;
use crate::query::role::AriaRole;
use crate::tab::Tab;

/// A resolved CDP node handle. CSS / XPath / text / role queries all
/// hand back one (or many) of these; the caller wraps them into
/// `Element` values.
#[derive(Debug, Clone)]
#[allow(dead_code)] // Field reads land with the FindBuilder.one swap in T12.
pub(crate) struct RemoteRef {
    pub(crate) remote_object_id: String,
    pub(crate) backend_node_id: i64,
}

/// What the query runs against: a whole tab (root = `document`), a
/// subtree rooted at an existing element (root = `this`), or a specific
/// frame (root = the frame's `document`, dispatched on the frame's own
/// CDP session — distinct from the parent tab's session for OOPIFs).
#[allow(dead_code)] // Element-scoped queries land with FindBuilder ext in T12.
pub(crate) enum QueryScope<'a> {
    Tab(&'a Tab),
    Element(&'a Element),
    Frame(&'a Frame),
}

impl QueryScope<'_> {
    /// CDP session that should dispatch this query's commands. Tab and
    /// Element scopes both route to the owning tab's session; Frame
    /// scope routes to the frame's own session (same as the parent tab
    /// for same-origin frames, a distinct child session for OOPIFs).
    ///
    /// All `Runtime.evaluate` / `Runtime.callFunctionOn` /
    /// `Runtime.getProperties` / `DOM.describeNode` /
    /// `Accessibility.getPartialAXTree` calls in this module go through
    /// this accessor so adding a new scope variant only requires
    /// extending the match arm.
    pub(crate) fn session(&self) -> &SessionHandle {
        match self {
            QueryScope::Tab(t) => t.session(),
            QueryScope::Element(e) => e.tab().session(),
            QueryScope::Frame(f) => f.session(),
        }
    }

    /// Execution-context id that `Runtime.evaluate` should target for
    /// this scope, or `None` to let CDP pick the session's default
    /// (which is the main-frame main-world for a Tab/Element scope).
    ///
    /// Frame scope must NOT use the session default — for a same-origin
    /// iframe, the session is the parent tab's session and CDP's
    /// "default context" is the *parent* document. A
    /// `document.querySelectorAll(...)` evaluated without a contextId
    /// would walk the parent DOM, not the iframe's, and find nothing
    /// for selectors targeting iframe-only content. Returning the
    /// frame's isolated-world contextId pins the eval to the iframe's
    /// document.
    pub(crate) async fn execution_context_id(&self) -> Result<Option<i64>> {
        match self {
            QueryScope::Tab(_) | QueryScope::Element(_) => Ok(None),
            QueryScope::Frame(f) => Ok(Some(f.ensure_isolated_world().await?)),
        }
    }

    /// Owned `Tab` clone for `Element::synthesize_query`. Tab/Element
    /// scopes return a cheap `Arc` bump on the underlying `TabInner`;
    /// Frame scope upgrades the frame's `Weak<TabInner>` (which is
    /// always live in practice because every `Frame` is constructed by
    /// a `Tab` that holds the strong reference). A dead Weak indicates
    /// the owning Tab was dropped while the Frame clone outlived it —
    /// a logic bug worth a clear panic rather than a confusing
    /// `Result` propagation.
    pub(crate) fn synthesize_tab(&self) -> Tab {
        match self {
            QueryScope::Tab(t) => (*t).clone(),
            QueryScope::Element(e) => e.tab().clone(),
            QueryScope::Frame(f) => f
                .tab_for_synthesize()
                .expect("Frame outlived its owning Tab while a FindBuilder query was in flight"),
        }
    }
}

/// The set of supported selector kinds. T9 lands `Css` and `Xpath`;
/// T10 lands `Text` and `TextRegex`; `Role` is filled in by T11. Until
/// then the Role stub returns a clearly-attributed error so an
/// accidental dispatch surfaces immediately instead of returning an
/// empty match set (which would silently pass tests).
///
/// `TextRegex` stores pattern + flags as separate strings (rather than
/// a `regex::Regex`) so the JS-side `new RegExp(pat, flags)` mirrors
/// the user's intent exactly — `text_regex(re)` plumbs `re.as_str()`
/// + empty flags, while `text_regex_with_flags` (T12) plumbs both.
#[derive(Debug, Clone)]
#[allow(dead_code)] // Xpath/Text/TextRegex/Role wired up by T11/T12.
pub(crate) enum SelectorKind {
    Css(String),
    Xpath(String),
    Text { needle: String, exact: bool },
    TextRegex { pattern: String, flags: String },
    Role(AriaRole, Option<String>),
}

impl SelectorKind {
    /// Resolve this selector against `scope` and return the first match
    /// (or `None` if nothing matched). Element-scoped queries traverse
    /// only the scope element's subtree; tab-scoped queries traverse
    /// the whole document.
    #[allow(dead_code)] // First lib caller is FindBuilder.one after T12 swap.
    pub(crate) async fn resolve_one(&self, scope: &QueryScope<'_>) -> Result<Option<RemoteRef>> {
        self.resolve_one_inner(scope, false).await
    }

    /// `resolve_one` with the cross-cutting `best_match` flag.
    /// `best_match` only affects text selectors (`Text` / `TextRegex`),
    /// where the JS collector re-sorts candidates by closest text length
    /// before `[0]` is taken; it is a no-op for css/xpath/role.
    pub(crate) async fn resolve_one_inner(
        &self,
        scope: &QueryScope<'_>,
        best_match: bool,
    ) -> Result<Option<RemoteRef>> {
        match self {
            SelectorKind::Css(sel) => resolve_css_one(scope, sel).await,
            SelectorKind::Xpath(expr) => resolve_xpath_one(scope, expr).await,
            SelectorKind::Text { needle, exact } => {
                resolve_text_one(scope, needle, *exact, best_match).await
            }
            SelectorKind::TextRegex { pattern, flags } => {
                resolve_text_regex_one(scope, pattern, flags, best_match).await
            }
            SelectorKind::Role(role, name) => resolve_role_one(scope, *role, name.as_deref()).await,
        }
    }

    /// Resolve this selector against `scope` and return every match in
    /// document order. Empty `Vec` for no matches (not an error).
    #[allow(dead_code)] // First caller lands in T12 (FindBuilder.many).
    pub(crate) async fn resolve_many(&self, scope: &QueryScope<'_>) -> Result<Vec<RemoteRef>> {
        self.resolve_many_inner(scope, false).await
    }

    /// `resolve_many` with the cross-cutting `best_match` flag (see
    /// [`Self::resolve_one_inner`]). When set on a text selector the
    /// returned Vec is ordered closest-length first, so `.one()` taking
    /// `[0]` lands on the nearest match.
    pub(crate) async fn resolve_many_inner(
        &self,
        scope: &QueryScope<'_>,
        best_match: bool,
    ) -> Result<Vec<RemoteRef>> {
        match self {
            SelectorKind::Css(sel) => resolve_css_many(scope, sel).await,
            SelectorKind::Xpath(expr) => resolve_xpath_many(scope, expr).await,
            SelectorKind::Text { needle, exact } => {
                resolve_text_many(scope, needle, *exact, best_match).await
            }
            SelectorKind::TextRegex { pattern, flags } => {
                resolve_text_regex_many(scope, pattern, flags, best_match).await
            }
            SelectorKind::Role(role, name) => {
                resolve_role_many(scope, *role, name.as_deref()).await
            }
        }
    }
}

// ---------------------------------------------------------------------
// Shared eval-in-scope helper
// ---------------------------------------------------------------------

/// Evaluate `expression` via `Runtime.evaluate`, pinned to `scope`'s
/// execution context.
///
/// For a `Frame` scope this sets `contextId` to the frame's isolated-world
/// context (see [`QueryScope::execution_context_id`]) so a bare
/// `document`/`document.querySelectorAll(...)` inside `expression`
/// resolves against the *frame's* document rather than the parent tab's
/// default context — the bug this helper exists to prevent recurring.
/// For `Tab`/`Element` scope `execution_context_id()` is always `None`,
/// so `contextId` is omitted and CDP falls back to the session's default
/// (main-frame main-world) context, matching prior behavior exactly.
///
/// Every `Tab`/`Frame` match arm below (css/xpath/text/text_regex/
/// predicate, both `_one` and `_many`) routes through this one function
/// instead of hand-rolling the `contextId` dance per resolver.
async fn eval_expr_in_scope(scope: &QueryScope<'_>, expression: String) -> Result<Value> {
    let session = scope.session();
    let ctx = scope.execution_context_id().await?;
    let mut params = json!({
        "expression": expression,
        "returnByValue": false,
    });
    if let Some(id) = ctx {
        params["contextId"] = json!(id);
    }
    Ok(session.call("Runtime.evaluate", params).await?)
}

// ---------------------------------------------------------------------
// CSS
// ---------------------------------------------------------------------

#[allow(dead_code)] // Reached via SelectorKind::resolve_one, gated until T12.
async fn resolve_css_one(scope: &QueryScope<'_>, selector: &str) -> Result<Option<RemoteRef>> {
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(
                scope,
                format!("document.querySelector({})", json!(selector)),
            )
            .await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration": "function(s){return this.querySelector(s);}",
                        "arguments": [{ "value": selector }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_node_ref(session, &result["result"]).await
}

#[allow(dead_code)] // Called via `SelectorKind::resolve_many`; gated until T12.
async fn resolve_css_many(scope: &QueryScope<'_>, selector: &str) -> Result<Vec<RemoteRef>> {
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(
                scope,
                format!("Array.from(document.querySelectorAll({}))", json!(selector)),
            )
            .await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration": "function(s){return Array.from(this.querySelectorAll(s));}",
                        "arguments": [{ "value": selector }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_array_refs(session, &result["result"]).await
}

// ---------------------------------------------------------------------
// Predicate (bs4-like combinable matchers)
// ---------------------------------------------------------------------
//
// A `PredicateSet` compiles to a CSS selector (`tag` + structural attrs)
// plus a JS boolean post-filter (`attr_regex` + text predicates). The
// terminal builds ONE `querySelectorAll(css).filter(el => <jsFilter>)`
// per scope — exactly mirroring `resolve_css_many`'s scope dispatch
// (`contextId` for frames, `this` for element subtrees) so predicates
// cross frames the same way CSS does.

use crate::query::predicate::PredicateSet;

/// Resolve `pred` against `scope` and return every match in document
/// order. Compiles to `Array.from((document|this).querySelectorAll(css))
/// .filter(el => <jsFilter>)`, with the CSS selector JSON-embedded so a
/// quote/backslash in an attribute value can't break out of the JS
/// string literal. Empty `Vec` for no matches (not an error).
pub(crate) async fn resolve_predicate_many(
    scope: &QueryScope<'_>,
    pred: &PredicateSet,
) -> Result<Vec<RemoteRef>> {
    let session = scope.session();
    let css = pred.to_css_selector();
    let filter = pred.to_js_filter();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            let expr = format!(
                "Array.from(document.querySelectorAll({})).filter(function(el){{return {};}})",
                json!(css),
                filter,
            );
            eval_expr_in_scope(scope, expr).await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            let func = format!(
                "function(){{return Array.from(this.querySelectorAll({})).filter(function(el){{return {};}});}}",
                json!(css),
                filter,
            );
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration": func,
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_array_refs(session, &result["result"]).await
}

// ---------------------------------------------------------------------
// XPath
// ---------------------------------------------------------------------

#[allow(dead_code)] // Reached only via `SelectorKind::Xpath`, wired up in T12.
async fn resolve_xpath_one(scope: &QueryScope<'_>, expr: &str) -> Result<Option<RemoteRef>> {
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(
                scope,
                format!(
                    "document.evaluate({}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue",
                    json!(expr)
                ),
            )
            .await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration":
                            "function(e){return document.evaluate(e, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;}",
                        "arguments": [{ "value": expr }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_node_ref(session, &result["result"]).await
}

#[allow(dead_code)] // Called via `SelectorKind::resolve_many`; gated until T12.
async fn resolve_xpath_many(scope: &QueryScope<'_>, expr: &str) -> Result<Vec<RemoteRef>> {
    // Build an Array of nodes from an ORDERED_NODE_SNAPSHOT_TYPE result so
    // `extract_array_refs` can enumerate it via `Runtime.getProperties`.
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(
                scope,
                format!(
                    "(function(){{var r=document.evaluate({}, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);var a=[];for(var i=0;i<r.snapshotLength;i++)a.push(r.snapshotItem(i));return a;}})()",
                    json!(expr)
                ),
            )
            .await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration":
                            "function(e){var r=document.evaluate(e, this, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);var a=[];for(var i=0;i<r.snapshotLength;i++)a.push(r.snapshotItem(i));return a;}",
                        "arguments": [{ "value": expr }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_array_refs(session, &result["result"]).await
}

// ---------------------------------------------------------------------
// Text (case-insensitive substring or whitespace-collapsed exact)
// ---------------------------------------------------------------------
//
// Two paths:
//   - exact=true  -> XPath `//*[normalize-space(.)=<needle>]` with
//     `singleNodeValue` for `_one` / `ORDERED_NODE_SNAPSHOT_TYPE` for
//     `_many`. The XPath string is constructed *in JS* via
//     `JSON.stringify(needle)` (then `"`->`'`) so multi-quote needles
//     don't break XPath literal escaping.
//   - exact=false -> JS tree walk:
//     `Array.from(ctx.querySelectorAll('*')).filter(el => (el.innerText||el.textContent).toLowerCase().includes(needle.toLowerCase()))`.
//     `_one` slices `[0] || null`; `_many` returns the array.
//
// `innerText||textContent` matches Playwright's `getByText` and is
// resilient to hidden elements (which have `innerText === ""` but
// non-empty `textContent`).

/// JS fragment that re-sorts an array of elements ascending by
/// `abs(len(elementText) - needleLen)` — the nodriver "closest-length"
/// heuristic. Appended to the collector output only when `best_match`
/// is set so `.one()` (which takes `[0]`) lands on the nearest match.
/// `arr` is the in-scope identifier holding the candidate array.
fn best_match_sort_js(arr: &str, needle_len: usize) -> String {
    format!(
        "{arr}.sort(function(a,b){{\
            var la=(a.innerText||a.textContent||'').length;\
            var lb=(b.innerText||b.textContent||'').length;\
            return Math.abs(la-{n})-Math.abs(lb-{n});\
        }})",
        arr = arr,
        n = needle_len,
    )
}

fn build_text_substring_js_tab(needle: &str, best_match: bool) -> String {
    // Narrowest-match filter: every element whose own text contains the
    // needle, MINUS any element that also has a descendant whose text
    // contains the needle. Without the narrowing step, the naive filter
    // returns `[html, body, ...ancestors..., target]` in document
    // order — `.one()` then picks `<html>` and the caller's
    // `el.attr("id")` returns None even though the test's `<button id=…>`
    // matched the needle.
    //
    // When `best_match` is set, the narrowed array is re-sorted ascending
    // by `abs(len(text) - len(needle))` so `.one()` (which takes `[0]`)
    // returns the closest-length candidate rather than the first in
    // document order.
    let sort = if best_match {
        format!(";{}", best_match_sort_js("r", needle.chars().count()))
    } else {
        String::new()
    };
    format!(
        "(function(){{\
            var n={n};\
            var lc=n.toLowerCase();\
            var matches=Array.from(document.querySelectorAll('*')).filter(function(el){{\
                var t=el.innerText||el.textContent||'';\
                return t.toLowerCase().includes(lc);\
            }});\
            var r=matches.filter(function(el){{\
                return !Array.from(el.querySelectorAll('*')).some(function(c){{\
                    var t=c.innerText||c.textContent||'';\
                    return t.toLowerCase().includes(lc);\
                }});\
            }}){sort};\
            return r;\
        }})()",
        n = json!(needle),
        sort = sort,
    )
}

fn build_text_substring_fn_body(needle: &str, best_match: bool) -> String {
    // Element scope: `this` is the scope element. Used via
    // `Runtime.callFunctionOn` with the needle as the sole argument.
    // Same narrowing (+ optional best_match sort) semantics as the
    // tab/frame path above.
    let sort = if best_match {
        format!(";{}", best_match_sort_js("r", needle.chars().count()))
    } else {
        String::new()
    };
    format!(
        "function(n){{\
            var lc=n.toLowerCase();\
            var matches=Array.from(this.querySelectorAll('*')).filter(function(el){{\
                var t=el.innerText||el.textContent||'';\
                return t.toLowerCase().includes(lc);\
            }});\
            var r=matches.filter(function(el){{\
                return !Array.from(el.querySelectorAll('*')).some(function(c){{\
                    var t=c.innerText||c.textContent||'';\
                    return t.toLowerCase().includes(lc);\
                }});\
            }}){sort};\
            return r;\
        }}",
        sort = sort,
    )
}

fn build_text_exact_xpath_js_tab(needle: &str, snapshot: bool, best_match: bool) -> String {
    // Construct the XPath in JS so the needle literal is escaped by
    // JSON.stringify -> single-quoted XPath string. snapshot=true
    // returns an Array of all matches; snapshot=false returns the
    // first match or null. When `best_match` is set on the snapshot
    // path, the array is re-sorted by closest text length (see
    // `best_match_sort_js`). `best_match` is ignored for the single-node
    // (`snapshot=false`) form since there is no array to sort.
    let sort = if snapshot && best_match {
        format!(";{}", best_match_sort_js("a", needle.chars().count()))
    } else {
        String::new()
    };
    if snapshot {
        format!(
            "(function(){{var n={n};var xp=\"//*[normalize-space(.)=\"+JSON.stringify(n).replace(/\"/g,\"'\")+\"]\";var r=document.evaluate(xp,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);var a=[];for(var i=0;i<r.snapshotLength;i++)a.push(r.snapshotItem(i));{sort};return a;}})()",
            n = json!(needle),
            sort = sort,
        )
    } else {
        format!(
            "(function(){{var n={n};var xp=\"//*[normalize-space(.)=\"+JSON.stringify(n).replace(/\"/g,\"'\")+\"]\";return document.evaluate(xp,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;}})()",
            n = json!(needle),
        )
    }
}

fn build_text_exact_xpath_fn_body(needle: &str, snapshot: bool, best_match: bool) -> String {
    // Element scope: `this` is the context node. Needle passed as arg.
    let sort = if snapshot && best_match {
        format!(";{}", best_match_sort_js("a", needle.chars().count()))
    } else {
        String::new()
    };
    if snapshot {
        format!(
            "function(n){{var xp=\"//*[normalize-space(.)=\"+JSON.stringify(n).replace(/\"/g,\"'\")+\"]\";var r=document.evaluate(xp,this,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);var a=[];for(var i=0;i<r.snapshotLength;i++)a.push(r.snapshotItem(i));{sort};return a;}}",
            sort = sort,
        )
    } else {
        "function(n){var xp=\"//*[normalize-space(.)=\"+JSON.stringify(n).replace(/\"/g,\"'\")+\"]\";return document.evaluate(xp,this,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;}".to_string()
    }
}

#[allow(dead_code)] // Reached via SelectorKind::resolve_one, gated until T12.
async fn resolve_text_one(
    scope: &QueryScope<'_>,
    needle: &str,
    exact: bool,
    best_match: bool,
) -> Result<Option<RemoteRef>> {
    let session = scope.session();
    if exact {
        // XPath path. For best_match we need the full snapshot array
        // (sorted by closest length) and take `[0]`; otherwise the cheap
        // single-node form suffices.
        if best_match {
            let result = match scope {
                QueryScope::Tab(_) | QueryScope::Frame(_) => {
                    eval_expr_in_scope(
                        scope,
                        format!(
                            "({})[0] || null",
                            build_text_exact_xpath_js_tab(needle, true, true)
                        ),
                    )
                    .await?
                }
                QueryScope::Element(el) => {
                    let object_id = el.remote_object_id_cloned().await?;
                    session
                        .call(
                            "Runtime.callFunctionOn",
                            json!({
                                "objectId": object_id,
                                "functionDeclaration": format!(
                                    "function(n){{return ({})[0] || null;}}",
                                    format!("({}).call(this,n)", build_text_exact_xpath_fn_body(needle, true, true)),
                                ),
                                "arguments": [{ "value": needle }],
                                "returnByValue": false,
                            }),
                        )
                        .await?
                }
            };
            return extract_node_ref(session, &result["result"]).await;
        }
        // Single-node form (no best_match): returns a single node or null.
        let result = match scope {
            QueryScope::Tab(_) | QueryScope::Frame(_) => {
                eval_expr_in_scope(scope, build_text_exact_xpath_js_tab(needle, false, false))
                    .await?
            }
            QueryScope::Element(el) => {
                let object_id = el.remote_object_id_cloned().await?;
                session
                    .call(
                        "Runtime.callFunctionOn",
                        json!({
                            "objectId": object_id,
                            "functionDeclaration": build_text_exact_xpath_fn_body(needle, false, false),
                            "arguments": [{ "value": needle }],
                            "returnByValue": false,
                        }),
                    )
                    .await?
            }
        };
        extract_node_ref(session, &result["result"]).await
    } else {
        // Substring path returns an Array (best_match re-sorts it); pick
        // first match.
        let result = match scope {
            QueryScope::Tab(_) | QueryScope::Frame(_) => {
                eval_expr_in_scope(
                    scope,
                    format!(
                        "({})[0] || null",
                        build_text_substring_js_tab(needle, best_match)
                    ),
                )
                .await?
            }
            QueryScope::Element(el) => {
                let object_id = el.remote_object_id_cloned().await?;
                session
                    .call(
                        "Runtime.callFunctionOn",
                        json!({
                            "objectId": object_id,
                            "functionDeclaration": format!(
                                "function(n){{return ({}.call(this,n))[0] || null;}}",
                                // Reuse the narrowing + best_match body so
                                // `this` resolves to the scope element.
                                build_text_substring_fn_body(needle, best_match)
                            ),
                            "arguments": [{ "value": needle }],
                            "returnByValue": false,
                        }),
                    )
                    .await?
            }
        };
        extract_node_ref(session, &result["result"]).await
    }
}

#[allow(dead_code)] // Reached via SelectorKind::resolve_many, gated until T12.
async fn resolve_text_many(
    scope: &QueryScope<'_>,
    needle: &str,
    exact: bool,
    best_match: bool,
) -> Result<Vec<RemoteRef>> {
    let session = scope.session();
    let result = if exact {
        match scope {
            QueryScope::Tab(_) | QueryScope::Frame(_) => {
                eval_expr_in_scope(
                    scope,
                    build_text_exact_xpath_js_tab(needle, true, best_match),
                )
                .await?
            }
            QueryScope::Element(el) => {
                let object_id = el.remote_object_id_cloned().await?;
                session
                    .call(
                        "Runtime.callFunctionOn",
                        json!({
                            "objectId": object_id,
                            "functionDeclaration": build_text_exact_xpath_fn_body(needle, true, best_match),
                            "arguments": [{ "value": needle }],
                            "returnByValue": false,
                        }),
                    )
                    .await?
            }
        }
    } else {
        match scope {
            QueryScope::Tab(_) | QueryScope::Frame(_) => {
                eval_expr_in_scope(scope, build_text_substring_js_tab(needle, best_match)).await?
            }
            QueryScope::Element(el) => {
                let object_id = el.remote_object_id_cloned().await?;
                session
                    .call(
                        "Runtime.callFunctionOn",
                        json!({
                            "objectId": object_id,
                            "functionDeclaration": build_text_substring_fn_body(needle, best_match),
                            "arguments": [{ "value": needle }],
                            "returnByValue": false,
                        }),
                    )
                    .await?
            }
        }
    };
    extract_array_refs(session, &result["result"]).await
}

// ---------------------------------------------------------------------
// TextRegex (serialized as JS `new RegExp(pattern, flags)`)
// ---------------------------------------------------------------------
//
// JS path:
//   `Array.from(ctx.querySelectorAll('*')).filter(el => new RegExp(pat, flags).test(el.innerText||el.textContent))`,
//   then narrowed to the innermost matching element (see
//   `regex_narrowing_js`) — an ancestor whose only text-bearing
//   descendant is the match otherwise has an identical `innerText` and
//   also passes the filter, ranking first in document order.
//
// The regex is *re-parsed* on the JS side via `new RegExp`, so the
// pattern must use JS-flavored regex syntax (which is essentially the
// same as Rust's `regex` crate for the common subset). Flags are passed
// verbatim — caller is responsible for valid JS flag chars (e.g. "i",
// "im", "gi", etc.). Empty flags string is fine.
//
// We construct the RegExp *once outside* the filter callback so the
// pattern is only compiled per query rather than per element.

/// JS fragment implementing the same "narrowest match" filter the
/// substring builders use (see `build_text_substring_js_tab`), but with
/// the regex predicate (`r.test(t)`, reusing the already-constructed
/// `RegExp` `r`) in place of `.includes(lc)`. `matches_var` is the
/// in-scope identifier holding the raw (un-narrowed) candidate array;
/// the fragment declares `narrowed` as the result with any element that
/// has a descendant also matching `r` subtracted out. Shared between
/// `build_text_regex_js_tab` and `build_text_regex_fn_body` (kept
/// separate from the substring builders' fragment so their existing,
/// tested JS output stays untouched).
fn regex_narrowing_js(matches_var: &str) -> String {
    format!(
        "var narrowed={m}.filter(function(el){{\
            return !Array.from(el.querySelectorAll('*')).some(function(c){{\
                var t=c.innerText||c.textContent||'';\
                return r.test(t);\
            }});\
        }})",
        m = matches_var,
    )
}

fn build_text_regex_js_tab(pattern: &str, flags: &str, best_match: bool) -> String {
    // `best_match` has no literal needle for a regex; we use the pattern
    // length as the closest-length proxy (the only well-defined analog
    // for the regex case). The NARROWED array is re-sorted ascending by
    // `abs(len(text) - len(pattern))` when set, mirroring the substring
    // builder's order-of-operations (narrow first, then sort the
    // leaves).
    let sort = if best_match {
        format!(
            ";{}",
            best_match_sort_js("narrowed", pattern.chars().count())
        )
    } else {
        String::new()
    };
    format!(
        "(function(){{\
            var r=new RegExp({p}, {f});\
            var m=Array.from(document.querySelectorAll('*')).filter(function(el){{\
                var t=el.innerText||el.textContent||'';\
                return r.test(t);\
            }});\
            {narrowing}{sort};\
            return narrowed;\
        }})()",
        p = json!(pattern),
        f = json!(flags),
        narrowing = regex_narrowing_js("m"),
        sort = sort,
    )
}

fn build_text_regex_fn_body(pattern: &str, best_match: bool) -> String {
    // Element scope: `this` is the scope element. Pattern + flags
    // passed as arguments. See `build_text_regex_js_tab` for the
    // best_match proxy rationale and the narrowing semantics.
    let sort = if best_match {
        format!(
            ";{}",
            best_match_sort_js("narrowed", pattern.chars().count())
        )
    } else {
        String::new()
    };
    format!(
        "function(p,f){{\
            var r=new RegExp(p,f);\
            var m=Array.from(this.querySelectorAll('*')).filter(function(el){{\
                var t=el.innerText||el.textContent||'';\
                return r.test(t);\
            }});\
            {narrowing}{sort};\
            return narrowed;\
        }}",
        narrowing = regex_narrowing_js("m"),
        sort = sort,
    )
}

#[allow(dead_code)] // Reached via SelectorKind::resolve_one, gated until T12.
async fn resolve_text_regex_one(
    scope: &QueryScope<'_>,
    pattern: &str,
    flags: &str,
    best_match: bool,
) -> Result<Option<RemoteRef>> {
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(
                scope,
                format!(
                    "({})[0] || null",
                    build_text_regex_js_tab(pattern, flags, best_match)
                ),
            )
            .await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration": format!(
                            "function(p,f){{return (({}).call(this,p,f))[0] || null;}}",
                            build_text_regex_fn_body(pattern, best_match)
                        ),
                        "arguments": [{ "value": pattern }, { "value": flags }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_node_ref(session, &result["result"]).await
}

#[allow(dead_code)] // Reached via SelectorKind::resolve_many, gated until T12.
async fn resolve_text_regex_many(
    scope: &QueryScope<'_>,
    pattern: &str,
    flags: &str,
    best_match: bool,
) -> Result<Vec<RemoteRef>> {
    let session = scope.session();
    let result = match scope {
        QueryScope::Tab(_) | QueryScope::Frame(_) => {
            eval_expr_in_scope(scope, build_text_regex_js_tab(pattern, flags, best_match)).await?
        }
        QueryScope::Element(el) => {
            let object_id = el.remote_object_id_cloned().await?;
            session
                .call(
                    "Runtime.callFunctionOn",
                    json!({
                        "objectId": object_id,
                        "functionDeclaration": build_text_regex_fn_body(pattern, best_match),
                        "arguments": [{ "value": pattern }, { "value": flags }],
                        "returnByValue": false,
                    }),
                )
                .await?
        }
    };
    extract_array_refs(session, &result["result"]).await
}

// ---------------------------------------------------------------------
// Role (`[role="..."]` CSS + optional accessible-name post-filter)
// ---------------------------------------------------------------------

#[allow(dead_code)] // Reached via SelectorKind::resolve_one, gated until T12.
async fn resolve_role_one(
    scope: &QueryScope<'_>,
    role: AriaRole,
    name: Option<&str>,
) -> Result<Option<RemoteRef>> {
    // Always go through `resolve_css_many` (rather than `resolve_css_one`)
    // so that name-filter and no-filter paths share the same candidate
    // enumeration. With no name filter we just return the first match.
    // This delegation also means role queries already inherit
    // `resolve_css_many`'s `contextId` pinning for free — a Frame-scoped
    // role query correctly enumerates candidates from the frame's own
    // document, not the parent tab's.
    let css = role.to_css();
    let candidates = resolve_css_many(scope, &css).await?;
    let Some(needle) = name else {
        return Ok(candidates.into_iter().next());
    };
    let session = scope.session();
    for candidate in candidates {
        if accessible_name_matches(session, &candidate, needle).await? {
            return Ok(Some(candidate));
        }
    }
    Ok(None)
}

#[allow(dead_code)] // Reached via SelectorKind::resolve_many, gated until T12.
async fn resolve_role_many(
    scope: &QueryScope<'_>,
    role: AriaRole,
    name: Option<&str>,
) -> Result<Vec<RemoteRef>> {
    let css = role.to_css();
    let candidates = resolve_css_many(scope, &css).await?;
    let Some(needle) = name else {
        return Ok(candidates);
    };
    let session = scope.session();
    let mut out = Vec::new();
    for candidate in candidates {
        if accessible_name_matches(session, &candidate, needle).await? {
            out.push(candidate);
        }
    }
    Ok(out)
}

/// Returns `true` if the computed accessible name for `node` contains
/// `needle` as a case-insensitive substring.
///
/// Uses `Accessibility.getPartialAXTree { backendNodeId, fetchRelatives: false }`
/// to fetch the AX node and reads `name.value`. Nodes with no AX entry,
/// no name, or a name that isn't a string are treated as a non-match
/// (returns `Ok(false)`).
#[allow(dead_code)] // Called via resolve_role_*, gated until T12.
async fn accessible_name_matches(
    session: &SessionHandle,
    node: &RemoteRef,
    needle: &str,
) -> Result<bool> {
    let response = session
        .call(
            "Accessibility.getPartialAXTree",
            json!({
                "backendNodeId": node.backend_node_id,
                "fetchRelatives": false,
            }),
        )
        .await?;
    let needle_lower = needle.to_lowercase();
    let Some(nodes) = response["nodes"].as_array() else {
        return Ok(false);
    };
    for ax_node in nodes {
        let Some(name_value) = ax_node["name"]["value"].as_str() else {
            continue;
        };
        if name_value.to_lowercase().contains(&needle_lower) {
            return Ok(true);
        }
    }
    Ok(false)
}

// ---------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------

/// Turn a `Runtime.evaluate` / `Runtime.callFunctionOn` *single-node*
/// result into a `RemoteRef`. Null subtype (`document.querySelector`
/// returned `null`) or `undefined` => `Ok(None)`.
///
/// Takes a `SessionHandle` (not a `Tab`) so the follow-up
/// `DOM.describeNode` round-trip dispatches on the same session the
/// caller used to obtain `result` — Frame-scoped queries must keep the
/// follow-up on the Frame's session (which for OOPIFs is a distinct
/// child session from the parent tab's).
#[allow(dead_code)] // Used by resolve_css_one / resolve_xpath_one; both gated until T12.
pub(crate) async fn extract_node_ref(
    session: &SessionHandle,
    result: &Value,
) -> Result<Option<RemoteRef>> {
    if result["subtype"] == "null" || result["type"] == "undefined" {
        return Ok(None);
    }
    let Some(remote_object_id) = result["objectId"].as_str().map(str::to_string) else {
        return Ok(None);
    };
    let backend_node_id = describe_backend_id(session, &remote_object_id).await?;
    Ok(Some(RemoteRef {
        remote_object_id,
        backend_node_id,
    }))
}

/// Turn a `Runtime.evaluate` / `Runtime.callFunctionOn` *array* result
/// (an `Array` RemoteObject) into a `Vec<RemoteRef>` by enumerating
/// numeric properties via `Runtime.getProperties` and describing each
/// element node. Empty array yields an empty Vec, not an error.
///
/// See [`extract_node_ref`] for the rationale on taking a
/// `SessionHandle` rather than a `Tab` here.
#[allow(dead_code)] // First lib caller is FindBuilder.many in T12.
pub(crate) async fn extract_array_refs(
    session: &SessionHandle,
    result: &Value,
) -> Result<Vec<RemoteRef>> {
    if result["subtype"] == "null" || result["type"] == "undefined" {
        return Ok(Vec::new());
    }
    let Some(array_id) = result["objectId"].as_str() else {
        return Ok(Vec::new());
    };
    let props = session
        .call(
            "Runtime.getProperties",
            json!({
                "objectId": array_id,
                "ownProperties": true,
            }),
        )
        .await?;
    let entries = props["result"].as_array().cloned().unwrap_or_default();

    let mut out = Vec::new();
    for entry in entries {
        // Only numeric-indexed entries are array elements; "length",
        // proto, etc. are skipped here.
        let is_indexed = entry["name"]
            .as_str()
            .is_some_and(|n| n.parse::<usize>().is_ok());
        if !is_indexed {
            continue;
        }
        let value = &entry["value"];
        if value["subtype"] == "null" || value["type"] == "undefined" {
            continue;
        }
        if let Some(object_id) = value["objectId"].as_str().map(str::to_string) {
            let backend_node_id = describe_backend_id(session, &object_id).await?;
            out.push(RemoteRef {
                remote_object_id: object_id,
                backend_node_id,
            });
        }
    }
    // Sort by numeric index so the returned order matches the JS array
    // order. `Runtime.getProperties` is documented as preserving
    // insertion order in practice, but the explicit sort defends
    // against engine-specific reorderings.
    Ok(out)
}

/// Read the rendered text length of `node` via `Runtime.callFunctionOn`
/// returning `(this.innerText||this.textContent||'').length`. Dispatched
/// on `scope`'s session so an OOPIF frame's node is read over the frame's
/// own session. Used only by the cross-scope `include_frames` +
/// `best_match` path to compare each scope's top candidate and pick the
/// global closest-length winner. A missing/non-numeric result yields
/// `usize::MAX` so a scope whose length cannot be read never wins a tie.
pub(crate) async fn text_len_of(scope: &QueryScope<'_>, node: &RemoteRef) -> Result<usize> {
    let result = scope
        .session()
        .call(
            "Runtime.callFunctionOn",
            json!({
                "objectId": node.remote_object_id,
                "functionDeclaration":
                    "function(){return (this.innerText||this.textContent||'').length;}",
                "returnByValue": true,
            }),
        )
        .await?;
    Ok(result["result"]["value"]
        .as_u64()
        .map_or(usize::MAX, |v| v as usize))
}

#[allow(dead_code)] // Both callers (extract_node_ref/extract_array_refs) are gated until T12.
async fn describe_backend_id(session: &SessionHandle, object_id: &str) -> Result<i64> {
    let described = session
        .call("DOM.describeNode", json!({ "objectId": object_id }))
        .await?;
    described["node"]["backendNodeId"].as_i64().ok_or_else(|| {
        ZendriverError::Navigation("DOM.describeNode returned no backendNodeId".into())
    })
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;
    use zendriver_transport::SessionHandle;
    use zendriver_transport::testing::MockConnection;

    #[tokio::test]
    async fn css_one_sends_query_selector_with_selector() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let t = tab.clone();
            async move {
                let scope = QueryScope::Tab(&t);
                SelectorKind::Css("#btn".into()).resolve_one(&scope).await
            }
        });

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        let sent = mock.last_sent()["params"]["expression"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(
            sent.contains("document.querySelector") && sent.contains("#btn"),
            "expression should call document.querySelector with the selector, got: {sent}"
        );
        mock.reply(
            id_q,
            json!({ "result": { "objectId": "R7", "type": "object", "subtype": "node" } }),
        )
        .await;

        let id_d = mock.expect_cmd("DOM.describeNode").await;
        assert_eq!(mock.last_sent()["params"]["objectId"], "R7");
        mock.reply(id_d, json!({ "node": { "backendNodeId": 99 } }))
            .await;

        let r = fut.await.unwrap().unwrap().unwrap();
        assert_eq!(r.remote_object_id, "R7");
        assert_eq!(r.backend_node_id, 99);
        conn.shutdown();
    }

    #[tokio::test]
    async fn text_substring_eval_lowercases_and_includes_needle() {
        // Non-exact text selector: confirm the dispatched JS expression
        // contains the lowercase-fold (`.toLowerCase()`) + the needle
        // verbatim so the case-insensitive substring contract is
        // preserved. We respond with `null` so the future completes
        // immediately without needing the full describeNode dance.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let t = tab.clone();
            async move {
                let scope = QueryScope::Tab(&t);
                SelectorKind::Text {
                    needle: "Sign In".into(),
                    exact: false,
                }
                .resolve_one(&scope)
                .await
            }
        });

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        let sent = mock.last_sent()["params"]["expression"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(
            sent.contains(".toLowerCase()"),
            "substring path must lowercase-fold both sides; got: {sent}"
        );
        assert!(
            sent.contains("Sign In"),
            "substring path must embed the needle verbatim; got: {sent}"
        );
        assert!(
            sent.contains(".includes("),
            "substring path must call .includes; got: {sent}"
        );

        // null-out the result so resolve_one short-circuits to Ok(None).
        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_none(), "null subtype must yield Ok(None)");
        conn.shutdown();
    }

    #[tokio::test]
    async fn text_regex_eval_constructs_new_regexp_with_pattern_and_flags() {
        // TextRegex selector: confirm the dispatched JS expression
        // builds `new RegExp(<pat>, <flags>)` with both strings present.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let t = tab.clone();
            async move {
                let scope = QueryScope::Tab(&t);
                SelectorKind::TextRegex {
                    pattern: "hello.*world".into(),
                    flags: "im".into(),
                }
                .resolve_one(&scope)
                .await
            }
        });

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        let sent = mock.last_sent()["params"]["expression"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(
            sent.contains("new RegExp"),
            "regex path must instantiate `new RegExp`; got: {sent}"
        );
        assert!(
            sent.contains("hello.*world"),
            "regex path must embed the pattern; got: {sent}"
        );
        assert!(
            sent.contains("im"),
            "regex path must embed the flags string; got: {sent}"
        );

        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_none(), "null subtype must yield Ok(None)");
        conn.shutdown();
    }

    #[tokio::test]
    async fn text_regex_eval_narrows_to_innermost_matching_element() {
        // Regression test: `.text_regex()` used to have no "narrowest
        // match" step (unlike `.text()`/`.text_exact()`), so an ancestor
        // (`<html>`/`<body>`) whose only text-bearing descendant is the
        // real match ends up with an identical `innerText` and also
        // passes the regex filter — ranking first in document order and
        // winning `.one()`'s `[0]` instead of the intended leaf. Assert
        // the dispatched expression now subtracts any element that has a
        // matching descendant (mirroring `build_text_substring_js_tab`'s
        // narrowing), reusing the same `RegExp` object as the predicate.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let t = tab.clone();
            async move {
                let scope = QueryScope::Tab(&t);
                SelectorKind::TextRegex {
                    pattern: "unique-frame-text".into(),
                    flags: "".into(),
                }
                .resolve_one(&scope)
                .await
            }
        });

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        let sent = mock.last_sent()["params"]["expression"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(
            sent.contains(".querySelectorAll('*')).some("),
            "regex path must narrow via descendant-subtraction (some()); got: {sent}"
        );
        assert!(
            sent.matches("r.test(").count() >= 2,
            "narrowing predicate must reuse the same RegExp object `r` (once for the initial \
             filter, once for the descendant check); got: {sent}"
        );

        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_none(), "null subtype must yield Ok(None)");
        conn.shutdown();
    }

    #[tokio::test]
    async fn role_button_without_name_dispatches_attribute_selector_and_resolves_first_match() {
        // Role(Button, None) should:
        //   1. Runtime.evaluate `Array.from(document.querySelectorAll('[role="button"]'))`
        //   2. Runtime.getProperties on the returned Array
        //   3. DOM.describeNode on the first array element to fetch backendNodeId
        // and return a RemoteRef with the resolved id.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);

        let fut = tokio::spawn({
            let t = tab.clone();
            async move {
                let scope = QueryScope::Tab(&t);
                SelectorKind::Role(AriaRole::Button, None)
                    .resolve_one(&scope)
                    .await
            }
        });

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        let sent = mock.last_sent()["params"]["expression"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(
            sent.contains(r#"[role=\"button\"]"#),
            "role path must embed the `[role=\"button\"]` attribute selector verbatim; got: {sent}"
        );
        assert!(
            sent.contains("document.querySelectorAll"),
            "role path must call querySelectorAll for the candidate enumeration; got: {sent}"
        );
        mock.reply(
            id_q,
            json!({ "result": { "objectId": "RArr", "type": "object", "subtype": "array" } }),
        )
        .await;

        let id_p = mock.expect_cmd("Runtime.getProperties").await;
        assert_eq!(mock.last_sent()["params"]["objectId"], "RArr");
        mock.reply(
            id_p,
            json!({
                "result": [
                    {
                        "name": "0",
                        "value": { "objectId": "RN0", "type": "object", "subtype": "node" }
                    },
                    {
                        "name": "length",
                        "value": { "value": 1, "type": "number" }
                    }
                ]
            }),
        )
        .await;

        let id_d = mock.expect_cmd("DOM.describeNode").await;
        assert_eq!(mock.last_sent()["params"]["objectId"], "RN0");
        mock.reply(id_d, json!({ "node": { "backendNodeId": 42 } }))
            .await;

        let r = fut.await.unwrap().unwrap().unwrap();
        assert_eq!(r.remote_object_id, "RN0");
        assert_eq!(r.backend_node_id, 42);
        conn.shutdown();
    }

    // -------------------------------------------------------------------
    // Frame-scope `contextId` pinning (regression coverage for the bug
    // where xpath/text/text_regex `_many` resolvers silently queried the
    // main-frame document instead of the scoped frame's).
    // -------------------------------------------------------------------

    /// Build a synthetic `Frame` whose session sits on the supplied mock
    /// connection, with no parent tab/frame — sufficient for exercising
    /// `QueryScope::Frame` dispatch without a real `Tab`.
    fn frame_on(session: SessionHandle, frame_id: &str) -> Frame {
        Frame::new(
            frame_id.to_string(),
            None,
            String::new(),
            None,
            session,
            std::sync::Weak::new(),
        )
    }

    #[tokio::test]
    async fn xpath_many_frame_scope_pins_context_id() {
        // Frame scope must allocate/reuse the frame's isolated-world
        // context via `Page.createIsolatedWorld` and pin the follow-up
        // `Runtime.evaluate` to it via `contextId` — otherwise
        // `document.evaluate(...)` inside the expression walks the
        // parent tab's document instead of the frame's.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let frame = frame_on(sess, "F1");

        let fut = tokio::spawn(async move {
            let scope = QueryScope::Frame(&frame);
            SelectorKind::Xpath("//button".into())
                .resolve_many(&scope)
                .await
        });

        let id_iso = mock.expect_cmd("Page.createIsolatedWorld").await;
        assert_eq!(mock.last_sent()["params"]["frameId"], "F1");
        mock.reply(id_iso, json!({ "executionContextId": 777 }))
            .await;

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        assert_eq!(
            mock.last_sent()["params"]["contextId"],
            777,
            "xpath_many must pin Runtime.evaluate to the frame's isolated-world contextId"
        );
        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_empty(), "null subtype must yield an empty Vec");
        conn.shutdown();
    }

    #[tokio::test]
    async fn text_many_frame_scope_pins_context_id() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let frame = frame_on(sess, "F1");

        let fut = tokio::spawn(async move {
            let scope = QueryScope::Frame(&frame);
            SelectorKind::Text {
                needle: "hello".into(),
                exact: false,
            }
            .resolve_many(&scope)
            .await
        });

        let id_iso = mock.expect_cmd("Page.createIsolatedWorld").await;
        assert_eq!(mock.last_sent()["params"]["frameId"], "F1");
        mock.reply(id_iso, json!({ "executionContextId": 778 }))
            .await;

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        assert_eq!(
            mock.last_sent()["params"]["contextId"],
            778,
            "text_many must pin Runtime.evaluate to the frame's isolated-world contextId"
        );
        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_empty(), "null subtype must yield an empty Vec");
        conn.shutdown();
    }

    #[tokio::test]
    async fn text_regex_many_frame_scope_pins_context_id() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let frame = frame_on(sess, "F1");

        let fut = tokio::spawn(async move {
            let scope = QueryScope::Frame(&frame);
            SelectorKind::TextRegex {
                pattern: "hello.*world".into(),
                flags: "i".into(),
            }
            .resolve_many(&scope)
            .await
        });

        let id_iso = mock.expect_cmd("Page.createIsolatedWorld").await;
        assert_eq!(mock.last_sent()["params"]["frameId"], "F1");
        mock.reply(id_iso, json!({ "executionContextId": 779 }))
            .await;

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        assert_eq!(
            mock.last_sent()["params"]["contextId"],
            779,
            "text_regex_many must pin Runtime.evaluate to the frame's isolated-world contextId"
        );
        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_empty(), "null subtype must yield an empty Vec");
        conn.shutdown();
    }

    #[tokio::test]
    async fn role_many_frame_scope_pins_context_id_via_css_many_delegation() {
        // resolve_role_many delegates to resolve_css_many, which already
        // set contextId correctly before this fix. This test locks that
        // (already-correct) transitive behavior so a future refactor of
        // the role path can't silently drop it.
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let frame = frame_on(sess, "F1");

        let fut = tokio::spawn(async move {
            let scope = QueryScope::Frame(&frame);
            SelectorKind::Role(AriaRole::Button, None)
                .resolve_many(&scope)
                .await
        });

        let id_iso = mock.expect_cmd("Page.createIsolatedWorld").await;
        assert_eq!(mock.last_sent()["params"]["frameId"], "F1");
        mock.reply(id_iso, json!({ "executionContextId": 780 }))
            .await;

        let id_q = mock.expect_cmd("Runtime.evaluate").await;
        assert_eq!(
            mock.last_sent()["params"]["contextId"],
            780,
            "role_many must pin Runtime.evaluate to the frame's isolated-world contextId"
        );
        mock.reply(
            id_q,
            json!({ "result": { "type": "object", "subtype": "null" } }),
        )
        .await;

        let r = fut.await.unwrap().unwrap();
        assert!(r.is_empty(), "null subtype must yield an empty Vec");
        conn.shutdown();
    }
}