ferridriver 0.3.0

Browser automation in Rust with a Playwright-compatible API. Four pluggable backends: CDP pipe, CDP WebSocket, Playwright WebKit, Firefox BiDi.
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
#![allow(clippy::missing_errors_doc)]
//! Backend abstraction layer for browser automation.
//!
//! Provides a unified API across multiple browser backends:
//! - `CdpPipe`: Chrome `DevTools` Protocol over pipes (--remote-debugging-pipe, fd 3/4)
//! - `CdpRaw`: Chrome `DevTools` Protocol over WebSocket (our own, fully parallel)
//! - `WebKit`: Native `WKWebView` on macOS (subprocess model)
//!
//! Uses enum dispatch (not trait objects) for zero-cost abstraction and Clone support.

pub(crate) mod async_tempdir;
pub mod cdp;
pub(crate) mod json_scan;
pub(crate) mod process;
pub mod webkit;

pub mod bidi;

/// Empty JSON object `{}` — avoids `serde_json::json!({})` heap allocation per call.
#[inline]
pub(crate) fn empty_params() -> serde_json::Value {
  serde_json::Value::Object(serde_json::Map::new())
}

use crate::console_message::ConsoleMessage;
use crate::error::Result;
use crate::events::EventEmitter;
use crate::network::Request as NetworkRequest;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Mutable weak back-reference to the outer `Arc<Page>`. Every backend
/// page struct carries one of these so async event listeners
/// (file-chooser, future per-frame probes) can upgrade the weak on
/// demand and build `ElementHandle`s without threading the page
/// through the backend.
///
/// Why `Mutex<Weak<Page>>` and not `OnceLock<Weak<Page>>`: callers
/// like the MCP server construct a fresh `Arc<Page>` on every tool
/// invocation and drop it when the tool returns. A one-shot slot
/// would lock in the first `Arc<Page>`'s weak — whose target dies as
/// soon as that tool call completes, leaving every subsequent event
/// unable to resolve. The mutex lets successive `Page::new` calls
/// overwrite the slot with a weak that tracks the currently-live
/// outer page.
#[derive(Clone, Default)]
pub struct PageBackref {
  inner: Arc<std::sync::Mutex<std::sync::Weak<crate::page::Page>>>,
}

impl PageBackref {
  #[must_use]
  pub fn new() -> Self {
    Self::default()
  }

  /// Set the stored weak reference. Called by `Page::new` /
  /// `Page::with_context` on every construction.
  ///
  /// **Always overwrites.** Earlier behaviour was "skip overwrite if
  /// the existing weak still upgrades" to protect against transient
  /// `Page` wrappers (`ContextRef::pages()`, `frame.page()`) clobbering
  /// a long-lived persistent wrapper. In the MCP / script-engine path
  /// there IS no persistent outer `Page` -- every script call mints a
  /// new wrapper via `page_and_context` and drops it when the
  /// `RunContext` drops. With skip-on-upgrade, the very first transient
  /// wrapper "won" and stayed pinned in `page_backref`; once GC reaped
  /// its JS heap reference, the weak dangled while the listener thread
  /// kept silently dropping every console / file-chooser / dialog event
  /// for the rest of the session (reproduced via
  /// `test_file_chooser_multiple_string_array` running after
  /// `test_file_chooser_single_string_path`). Last-writer-wins matches
  /// the actual lifetime story: the wrapper most recently registered is
  /// the one the current call is using.
  pub fn set(&self, weak: std::sync::Weak<crate::page::Page>) {
    if let Ok(mut guard) = self.inner.lock() {
      *guard = weak;
    }
  }

  /// Upgrade to an `Arc<Page>` if the outer page is still alive.
  /// Backend listeners call this per event and silently skip events
  /// that arrive when no outer page wraps this backend page.
  #[must_use]
  pub fn upgrade(&self) -> Option<Arc<crate::page::Page>> {
    self.inner.lock().ok()?.upgrade()
  }
}

// ─── Backend-agnostic types ─────────────────────────────────────────────────

/// Frame metadata (backend-agnostic).
#[derive(Debug, Clone, serde::Serialize)]
pub struct FrameInfo {
  pub frame_id: String,
  pub parent_frame_id: Option<String>,
  pub name: String,
  pub url: String,
}

/// Accessibility tree node (backend-agnostic).
#[derive(Debug, Clone)]
pub struct AxNodeData {
  pub node_id: String,
  pub parent_id: Option<String>,
  pub backend_dom_node_id: Option<i64>,
  pub ignored: bool,
  pub role: Option<String>,
  pub name: Option<String>,
  pub description: Option<String>,
  pub properties: Vec<AxProperty>,
}

#[derive(Debug, Clone)]
pub struct AxProperty {
  pub name: String,
  pub value: Option<serde_json::Value>,
}

/// Cookie `SameSite` attribute (matches Playwright's `Strict | Lax | None`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SameSite {
  Strict,
  Lax,
  None,
}

impl SameSite {
  /// Convert to a CDP/WebKit string.
  #[must_use]
  pub fn as_str(self) -> &'static str {
    match self {
      Self::Strict => "Strict",
      Self::Lax => "Lax",
      Self::None => "None",
    }
  }
}

impl std::str::FromStr for SameSite {
  type Err = ();

  fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
    match s {
      "Strict" => Ok(Self::Strict),
      "Lax" => Ok(Self::Lax),
      "None" => Ok(Self::None),
      _ => Err(()),
    }
  }
}

/// Cookie data (backend-agnostic, matches Playwright's `NetworkCookie`).
///
/// Wire format is camelCase (`httpOnly`, `sameSite`) to match Playwright /
/// CDP / Web Cookies RFC; Rust field names stay `snake_case` per convention.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CookieData {
  pub name: String,
  pub value: String,
  pub domain: String,
  pub path: String,
  pub secure: bool,
  pub http_only: bool,
  pub expires: Option<f64>,
  /// `SameSite` attribute (`Strict`, `Lax`, or `None`).
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub same_site: Option<SameSite>,
  /// Playwright `SetNetworkCookieParam.url`: when set, the backend
  /// derives domain/path from it (CDP `Network.setCookie` accepts
  /// `url`; `BiDi`/`WebKit` have no `url`, so the host/path is parsed
  /// from it). Never populated on cookies READ back from the browser.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub url: Option<String>,
}

/// Options for setting a cookie (matches Playwright's `SetNetworkCookieParam`).
/// Use `url` to derive domain/path automatically, or set `domain`/`path` directly.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetCookieParams {
  pub name: String,
  pub value: String,
  /// URL to derive domain/path from. Mutually exclusive with domain/path.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub url: Option<String>,
  #[serde(default)]
  pub domain: String,
  #[serde(default)]
  pub path: String,
  #[serde(default)]
  pub secure: bool,
  #[serde(default)]
  pub http_only: bool,
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub expires: Option<f64>,
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub same_site: Option<SameSite>,
}

impl From<SetCookieParams> for CookieData {
  fn from(p: SetCookieParams) -> Self {
    Self {
      name: p.name,
      value: p.value,
      domain: p.domain,
      path: if p.path.is_empty() { "/".to_string() } else { p.path },
      secure: p.secure,
      http_only: p.http_only,
      expires: p.expires,
      same_site: p.same_site,
      url: p.url,
    }
  }
}

/// Options for clearing cookies (matches Playwright's `ClearNetworkCookieOptions`).
/// All fields are optional filters -- only cookies matching ALL specified filters are cleared.
/// If no filters are specified, all cookies are cleared.
#[derive(Debug, Clone, Default)]
pub struct ClearCookieOptions {
  /// Filter by cookie name (exact match).
  pub name: Option<String>,
  /// Filter by domain (exact match).
  pub domain: Option<String>,
  /// Filter by path (exact match).
  pub path: Option<String>,
}

/// Backend-level screenshot options — the flat, Playwright-independent
/// wire struct each backend consumes. `crate::options::ScreenshotOptions`
/// (the user-facing Playwright-shaped bag) is lowered into this by
/// [`crate::page::Page::screenshot`], which also handles the Rust-side
/// concerns (`path` write-to-disk, `timeout` race) that don't belong in
/// the per-backend dispatch path.
#[derive(Debug, Clone)]
pub struct ScreenshotOpts {
  pub format: ImageFormat,
  pub quality: Option<i64>,
  pub full_page: bool,
  /// Pixel rectangle relative to the viewport (or full-page bounds
  /// when `full_page` is true). `None` captures the whole viewport /
  /// full page.
  pub clip: Option<crate::options::ClipRect>,
  /// When `true`, emit a PNG with transparent pixels where the page
  /// doesn't have its own background. Ignored for JPEG (no alpha).
  pub omit_background: bool,
  /// `"css"` → one image pixel per CSS pixel (smaller, stable across
  /// DPR); `"device"` → one image pixel per device pixel (default,
  /// Retina captures are 2× bigger). `None` = Playwright default.
  pub scale: Option<ScreenshotScale>,
  /// `"disabled"` pauses CSS animations and Web Animations during
  /// capture; finite animations fast-forward to completion, infinite
  /// ones revert to their initial state. `"allow"` leaves them
  /// running. `None` = Playwright default (`"allow"`).
  pub animations: Option<ScreenshotAnimations>,
  /// `"hide"` (Playwright default) hides the text caret; `"initial"`
  /// leaves it visible. `None` = Playwright default.
  pub caret: Option<ScreenshotCaret>,
  /// Selectors whose matches are overlaid with [`Self::mask_color`]
  /// before capture. Backends resolve each against the target and
  /// paint a fixed-position div at each element's bounding rect.
  pub mask: Vec<String>,
  /// CSS color for the mask overlay. Backends default to `#FF00FF`
  /// (Playwright's pink) when this is `None`.
  pub mask_color: Option<String>,
  /// Raw CSS injected before capture and removed afterwards. Pierces
  /// shadow DOM, applies to subframes.
  pub style: Option<String>,
}

impl Default for ScreenshotOpts {
  fn default() -> Self {
    Self {
      format: ImageFormat::Png,
      quality: None,
      full_page: false,
      clip: None,
      omit_background: false,
      scale: None,
      animations: None,
      caret: None,
      mask: Vec::new(),
      mask_color: None,
      style: None,
    }
  }
}

/// `scale` option for screenshots — mirrors Playwright's `"css" | "device"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScreenshotScale {
  /// One image pixel per CSS pixel — small, DPR-independent output.
  Css,
  /// One image pixel per device pixel — sharp, larger on Retina.
  Device,
}

/// `animations` option for screenshots — mirrors Playwright's
/// `"disabled" | "allow"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScreenshotAnimations {
  /// Pause animations during capture.
  Disabled,
  /// Leave animations running.
  Allow,
}

/// `caret` option for screenshots — mirrors Playwright's `"hide" | "initial"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScreenshotCaret {
  /// Hide the text input caret (Playwright default).
  Hide,
  /// Leave the caret visible in its natural state.
  Initial,
}

/// Backend-agnostic JS helpers for the DOM-side part of `screenshot()`
/// — caret hiding, user-style injection, animation pause via CSS, and
/// mask overlay painting. Each backend wraps its own
/// protocol-specific execution (CDP `Runtime.evaluate`, `BiDi`
/// `script.callFunction`, `WebKit` `evaluate`) around these helpers so
/// all three produce the same observable DOM state before capturing.
pub mod screenshot_js {
  use super::{ScreenshotAnimations, ScreenshotCaret, ScreenshotOpts};

  /// Build the combined CSS rules that `screenshot()` injects before
  /// capture: caret-hide (unless the caller explicitly opted into
  /// `Initial`), optional user `style`, and optional animation pause.
  /// Returns an empty string when no rules apply — the caller should
  /// skip the install/teardown JS entirely in that case.
  #[must_use]
  pub fn build_css(opts: &ScreenshotOpts) -> String {
    let mut css = String::new();
    if !matches!(opts.caret, Some(ScreenshotCaret::Initial)) {
      css.push_str("* { caret-color: transparent !important; }");
    }
    if matches!(opts.animations, Some(ScreenshotAnimations::Disabled)) {
      css.push_str(" *, *::before, *::after { animation-play-state: paused !important; transition: none !important; }");
    }
    if let Some(ref user) = opts.style {
      css.push_str(user);
    }
    css
  }

  /// Build a JS expression that installs a `<style id="__fd_screenshot_style__">`
  /// element carrying the supplied CSS. Paired with [`uninstall_style_js`]
  /// for teardown.
  #[must_use]
  pub fn install_style_js(css: &str) -> String {
    let esc = css.replace('\\', "\\\\").replace('`', "\\`");
    format!(
      r"(function(){{
        const s = document.createElement('style');
        s.id = '__fd_screenshot_style__';
        s.textContent = `{esc}`;
        (document.head || document.documentElement).appendChild(s);
      }})()"
    )
  }

  /// Removes the style element installed by [`install_style_js`].
  #[must_use]
  pub fn uninstall_style_js() -> &'static str {
    "document.getElementById('__fd_screenshot_style__')?.remove()"
  }

  /// Build a JS expression that paints a fixed `<div>` over every
  /// match of each selector in [`ScreenshotOpts::mask`]. Returns
  /// `None` when there are no selectors to mask — caller should skip
  /// the install/teardown JS entirely.
  ///
  /// The overlay divs are tagged with a random class name stored on
  /// `window.__fd_mask_tag` so [`uninstall_mask_js`] can remove them
  /// without relying on the selectors resolving to the same matches
  /// a second time.
  #[must_use]
  pub fn install_mask_js(opts: &ScreenshotOpts) -> Option<String> {
    if opts.mask.is_empty() {
      return None;
    }
    let selectors_json = serde_json::to_string(&opts.mask).unwrap_or_else(|_| "[]".into());
    let color = opts.mask_color.clone().unwrap_or_else(|| "#FF00FF".into());
    let color_json = serde_json::to_string(&color).unwrap_or_else(|_| "\"#FF00FF\"".into());
    Some(format!(
      r"(function(){{
        const selectors = {selectors_json};
        const color = {color_json};
        const tag = '__fd_mask_' + Math.random().toString(36).slice(2);
        window.__fd_mask_tag = tag;
        for (const sel of selectors) {{
          try {{
            const els = document.querySelectorAll(sel);
            for (const el of els) {{
              const r = el.getBoundingClientRect();
              const o = document.createElement('div');
              o.className = tag;
              o.style.cssText = `all: initial; position: fixed; left: ${{r.left}}px; top: ${{r.top}}px; width: ${{r.width}}px; height: ${{r.height}}px; background: ${{color}}; z-index: 2147483647; pointer-events: none;`;
              document.body.appendChild(o);
            }}
          }} catch (e) {{}}
        }}
      }})()"
    ))
  }

  /// Removes the mask overlay divs installed by [`install_mask_js`].
  #[must_use]
  pub fn uninstall_mask_js() -> &'static str {
    "(function(){const t=window.__fd_mask_tag;if(!t)return;document.querySelectorAll('.'+t).forEach(n=>n.remove());delete window.__fd_mask_tag;})()"
  }
}

/// Image format for screenshots.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
  Png,
  Jpeg,
  Webp,
}

/// Performance metric (backend-agnostic).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MetricData {
  pub name: String,
  pub value: f64,
}

/// Backend-ready click arguments. Produced by
/// `BackendClickArgs::from_options` from the user's
/// [`crate::options::ClickOptions`]. Every per-backend `click_at_with`
/// receives this struct — keeps the wire-level per-backend impls free
/// of `ClickOptions` parsing and defaulting logic.
///
/// Modifiers are carried as the raw Playwright enum slice so each
/// backend can compute its own bitmask / key-name / wire format; the
/// CDP bitmask (`u32`) is cached in [`Self::modifiers_bitmask`] so the
/// hot mouse-dispatch paths don't recompute it.
#[derive(Debug, Clone)]
pub struct BackendClickArgs {
  pub button: crate::options::MouseButton,
  pub click_count: u32,
  /// Milliseconds to sleep between `mousedown` and `mouseup`.
  pub delay_ms: u64,
  /// CDP modifier bitmask (cached from [`Self::modifiers`]).
  pub modifiers_bitmask: u32,
  /// Full modifier list (for backends that need key-name strings).
  pub modifiers: Vec<crate::options::Modifier>,
  /// Interpolated `mousemove` events between the current cursor and
  /// `(x, y)`. `1` = single move at destination.
  pub steps: u32,
}

impl BackendClickArgs {
  #[must_use]
  pub fn from_options(opts: &crate::options::ClickOptions) -> Self {
    Self {
      button: opts.resolved_button(),
      click_count: opts.resolved_click_count(),
      delay_ms: opts.resolved_delay_ms(),
      modifiers_bitmask: crate::options::modifiers_bitmask(&opts.modifiers),
      modifiers: opts.modifiers.clone(),
      steps: opts.resolved_steps(),
    }
  }

  /// Convenience factory for the "no options, just click once with left"
  /// default path — wire for existing `click_at` call sites.
  #[must_use]
  pub fn default_left() -> Self {
    Self {
      button: crate::options::MouseButton::Left,
      click_count: 1,
      delay_ms: 0,
      modifiers_bitmask: 0,
      modifiers: Vec::new(),
      steps: 1,
    }
  }
}

/// Backend-ready hover arguments. Produced by
/// [`crate::actions::hover_with_opts`] from the user's
/// [`crate::options::HoverOptions`]. Shape is the subset of
/// [`BackendClickArgs`] a hover needs — modifiers bitmask + `steps`
/// interpolated `mousemove` events.
#[derive(Debug, Clone, Copy)]
pub struct BackendHoverArgs {
  /// CDP modifier bitmask carried on each synthesised mouse event.
  pub modifiers_bitmask: u32,
  /// Interpolated `mousemove` events between the current cursor and
  /// `(x, y)`. `1` = single move at destination.
  pub steps: u32,
}

/// Backend-ready tap arguments. Produced by
/// [`crate::actions::tap_with_opts`] from the user's
/// [`crate::options::TapOptions`]. Only CDP implements this natively
/// via `Input.dispatchTouchEvent`; `BiDi` and `WebKit` return
/// `FerriError::Unsupported` because neither exposes a public touch
/// injection primitive.
#[derive(Debug, Clone, Copy)]
pub struct BackendTapArgs {
  /// CDP modifier bitmask (same scheme as mouse/key events) carried on
  /// the dispatched touch events so `event.shiftKey` etc. are true when
  /// the caller requested them.
  pub modifiers_bitmask: u32,
}

/// Navigation lifecycle target — which CDP event to wait for after Page.navigate.
/// Matches Playwright's `waitUntil` semantics exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavLifecycle {
  /// `Page.frameNavigated` — response committed, new document started.
  Commit,
  /// `Page.lifecycleEvent` name="`DOMContentLoaded`" — HTML parsed, DOM ready.
  DomContentLoaded,
  /// `Page.lifecycleEvent` name="load" — all resources loaded.
  Load,
}

impl NavLifecycle {
  /// Parse from a `waitUntil` string (Playwright / MCP convention).
  /// Unknown values default to `Load`.
  #[must_use]
  pub fn parse_lifecycle(s: &str) -> Self {
    match s {
      "commit" => Self::Commit,
      "domcontentloaded" => Self::DomContentLoaded,
      _ => Self::Load,
    }
  }
}

/// Which backend to use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendKind {
  /// Chrome `DevTools` Protocol over pipes (--remote-debugging-pipe)
  CdpPipe,
  /// Chrome `DevTools` Protocol over WebSocket (our own, fully parallel)
  CdpRaw,
  /// Playwright `WebKit` Inspector protocol (cross-platform, bundled binary)
  WebKit,
  /// `WebDriver` `BiDi` protocol (cross-browser: Chrome, Firefox, future Safari)
  Bidi,
}

// ─── AnyBrowser ─────────────────────────────────────────────────────────────

/// Browser instance — enum dispatch across backends.
#[derive(Clone)]
pub enum AnyBrowser {
  CdpPipe(cdp::CdpBrowser<cdp::pipe::PipeTransport>),
  CdpRaw(cdp::CdpBrowser<cdp::ws::WsTransport>),
  WebKit(webkit::WebKitBrowser),
  Bidi(bidi::BidiBrowser),
}

impl AnyBrowser {
  /// List all open pages in this browser.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend fails to enumerate targets or pages.
  pub async fn pages(&self) -> Result<Vec<AnyPage>> {
    match self {
      Self::CdpPipe(b) => Box::pin(b.pages()).await,
      Self::CdpRaw(b) => Box::pin(b.pages()).await,
      Self::WebKit(b) => Box::pin(b.pages()).await,
      Self::Bidi(b) => Box::pin(b.pages()).await,
    }
  }

  /// Create a new browser context (isolated cookies, storage, cache).
  ///
  /// `options` carries the full `BrowserContextOptions` bag — most
  /// backends only need `proxy`, but webkit applies `locale` (via
  /// `Playwright.setLanguages`) at context-creation time and stashes
  /// the remainder so per-page settings (userAgent, timezone, JS-disabled)
  /// can be sent during `attach()` BEFORE the about:blank document is
  /// live. Mirrors PW's `WKBrowserContext.initialize` flow.
  ///
  /// # Errors
  ///
  /// Returns an error if context creation fails.
  pub async fn new_context(&self, options: Option<&crate::options::BrowserContextOptions>) -> Result<String> {
    let proxy = options.and_then(|o| o.proxy.as_ref());
    match self {
      Self::CdpPipe(b) => b.new_context(proxy).await,
      Self::CdpRaw(b) => b.new_context(proxy).await,
      Self::WebKit(b) => b.new_context_with_options(options).await,
      Self::Bidi(b) => b.new_context(proxy).await,
    }
  }

  /// Dispose a browser context.
  ///
  /// # Errors
  ///
  /// Returns an error if context disposal fails.
  pub async fn dispose_context(&self, browser_context_id: &str) -> Result<()> {
    match self {
      Self::CdpPipe(b) => b.dispose_context(browser_context_id).await,
      Self::CdpRaw(b) => b.dispose_context(browser_context_id).await,
      Self::WebKit(b) => b.dispose_context(browser_context_id).await,
      Self::Bidi(b) => b.dispose_context(browser_context_id).await,
    }
  }

  /// Open a new page, optionally in a specific browser context.
  ///
  /// # Errors
  ///
  /// Returns an error if the backend fails to create a new target or navigate to the URL.
  pub async fn new_page(
    &self,
    url: &str,
    browser_context_id: Option<&str>,
    viewport: Option<&crate::options::ViewportConfig>,
  ) -> Result<AnyPage> {
    match self {
      Self::CdpPipe(b) => Box::pin(b.new_page(url, browser_context_id, viewport)).await,
      Self::CdpRaw(b) => Box::pin(b.new_page(url, browser_context_id, viewport)).await,
      Self::WebKit(b) => Box::pin(b.new_page(url, browser_context_id, viewport)).await,
      Self::Bidi(b) => Box::pin(b.new_page(url, browser_context_id, viewport)).await,
    }
  }

  /// Close the browser and all its pages.
  ///
  /// # Errors
  ///
  /// Returns an error if the browser process fails to shut down cleanly.
  pub async fn close(&mut self) -> Result<()> {
    match self {
      Self::CdpPipe(b) => b.close().await,
      Self::CdpRaw(b) => b.close().await,
      Self::WebKit(b) => b.close().await,
      Self::Bidi(b) => b.close().await,
    }
  }

  /// Real product version string for the running browser, captured at
  /// handshake/session-open time. Every backend surfaces a genuine value
  /// — no placeholders:
  ///
  /// * `cdp-pipe` / `cdp-raw` → CDP `Browser.getVersion().product`
  ///   (e.g. `"HeadlessChrome/120.0.6099.109"`).
  /// * `webkit` → `Op::GetWebKitVersion` IPC → `CFBundleShortVersionString`
  ///   from the running `WebKit.framework` (e.g. `"WebKit/617.1.2 (17618)"`).
  /// * `bidi` → `BiDi` `session.new` response capabilities, formatted as
  ///   `"{browserName}/{browserVersion}"` (e.g. `"firefox/135.0.1"`).
  #[must_use]
  pub fn version(&self) -> String {
    match self {
      Self::CdpPipe(b) => b.version().to_string(),
      Self::CdpRaw(b) => b.version().to_string(),
      Self::WebKit(b) => b.version(),
      Self::Bidi(b) => b.version(),
    }
  }
}

// ─── AnyPage ────────────────────────────────────────────────────────────────

/// Page handle — enum dispatch across backends. Cheaply cloneable (Arc-based).
#[derive(Clone)]
pub enum AnyPage {
  CdpPipe(cdp::CdpPage<cdp::pipe::PipeTransport>),
  CdpRaw(cdp::CdpPage<cdp::ws::WsTransport>),
  WebKit(webkit::WebKitPage),
  Bidi(bidi::BidiPage),
}

/// Macro to dispatch a method call across all `AnyPage` variants.
macro_rules! page_dispatch {
    ($self:expr, $method:ident ( $($arg:expr),* $(,)? )) => {
        match $self {
            AnyPage::CdpPipe(p) => p.$method($($arg),*).await,
            AnyPage::CdpRaw(p) => p.$method($($arg),*).await,
            AnyPage::WebKit(p) => p.$method($($arg),*).await,
            AnyPage::Bidi(p) => p.$method($($arg),*).await,
        }
    };
}

impl AnyPage {
  // ── Events ──

  /// Get the event emitter for this page.
  #[must_use]
  pub fn events(&self) -> &EventEmitter {
    match self {
      AnyPage::CdpPipe(p) => &p.events,
      AnyPage::CdpRaw(p) => &p.events,
      AnyPage::WebKit(p) => &p.events,

      AnyPage::Bidi(p) => &p.events,
    }
  }

  /// Per-page dialog handler registry. Mirrors Playwright's server-side
  /// `DialogManager`. Register with
  /// [`crate::dialog::DialogManager::add_handler`] to receive live
  /// [`crate::dialog::Dialog`] handles when `alert` / `confirm` /
  /// `prompt` / `beforeunload` fire.
  #[must_use]
  pub fn dialog_manager(&self) -> &crate::dialog::DialogManager {
    match self {
      AnyPage::CdpPipe(p) => &p.dialog_manager,
      AnyPage::CdpRaw(p) => &p.dialog_manager,
      AnyPage::WebKit(p) => &p.dialog_manager,
      AnyPage::Bidi(p) => &p.dialog_manager,
    }
  }

  /// Per-page file-chooser handler registry. Mirrors Playwright's
  /// `FileChooser` dispatch path. Register with
  /// [`crate::file_chooser::FileChooserManager::add_handler`] to
  /// receive live [`crate::file_chooser::FileChooser`] handles when
  /// an `<input type=file>` click (or `showPicker()`) fires.
  #[must_use]
  pub fn file_chooser_manager(&self) -> &crate::file_chooser::FileChooserManager {
    match self {
      AnyPage::CdpPipe(p) => &p.file_chooser_manager,
      AnyPage::CdpRaw(p) => &p.file_chooser_manager,
      AnyPage::WebKit(p) => &p.file_chooser_manager,
      AnyPage::Bidi(p) => &p.file_chooser_manager,
    }
  }

  /// Per-page download handler registry. Mirrors Playwright's
  /// server-side download dispatch path. Register with
  /// [`crate::download::DownloadManager::add_handler`] to receive live
  /// [`crate::download::Download`] handles when the browser starts
  /// writing a file download.
  #[must_use]
  pub fn download_manager(&self) -> &crate::download::DownloadManager {
    match self {
      AnyPage::CdpPipe(p) => &p.download_manager,
      AnyPage::CdpRaw(p) => &p.download_manager,
      AnyPage::WebKit(p) => &p.download_manager,
      AnyPage::Bidi(p) => &p.download_manager,
    }
  }

  /// Idempotently fire the backend command that turns on
  /// file-chooser interception. Lazy parity with Playwright's
  /// `_updateFileChooserInterception` — the page-level listener
  /// loop is already subscribed to events, but the underlying
  /// browser only emits `fileChooserOpened` after we ask it to.
  /// Called from `Page::wait_for_file_chooser` and
  /// `Page::on('filechooser', ...)`.
  pub async fn enable_file_chooser_intercept(&self) -> Result<()> {
    match self {
      AnyPage::CdpPipe(p) => p.enable_file_chooser_intercept().await,
      AnyPage::CdpRaw(p) => p.enable_file_chooser_intercept().await,
      AnyPage::WebKit(p) => p.enable_file_chooser_intercept().await,
      AnyPage::Bidi(_) => Ok(()),
    }
  }

  /// Idempotently fire the backend command that turns on download
  /// reporting. Lazy parity with Playwright's per-context
  /// `Browser.setDownloadBehavior` (`crBrowser.ts:354`). Called from
  /// `Page::wait_for_download` and `Page::on('download', ...)`.
  pub async fn enable_download_behavior(&self) -> Result<()> {
    match self {
      AnyPage::CdpPipe(p) => p.enable_download_behavior().await,
      AnyPage::CdpRaw(p) => p.enable_download_behavior().await,
      AnyPage::WebKit(p) => p.enable_download_behavior().await,
      AnyPage::Bidi(_) => Ok(()),
    }
  }

  /// Populate the weak back-reference to the outer `Arc<Page>`.
  /// Called by [`crate::page::Page::new`] / `Page::with_context`
  /// every time a new `Arc<Page>` is constructed — callers like the
  /// MCP server wrap the same backend page fresh on every tool
  /// invocation, so successive calls must be able to overwrite the
  /// slot. See [`PageBackref`] for the rationale.
  pub fn set_page_backref(&self, weak: std::sync::Weak<crate::page::Page>) {
    let slot = match self {
      AnyPage::CdpPipe(p) => &p.page_backref,
      AnyPage::CdpRaw(p) => &p.page_backref,
      AnyPage::WebKit(p) => &p.page_backref,
      AnyPage::Bidi(p) => &p.page_backref,
    };
    slot.set(weak);
  }

  /// Backend-owned frame cache shared across `Arc<crate::page::Page>`
  /// wrappers. MCP tool handlers construct a fresh wrapper per call,
  /// so storing the cache on the wrapper would reset it between
  /// `navigate` and the next `run_script` — losing the subframe
  /// entries the navigate's frame-event listener wrote. Pinning the
  /// cache to the backend keeps it alive for the lifetime of the
  /// underlying browser page.
  pub(crate) fn frame_cache(&self) -> &std::sync::Arc<std::sync::Mutex<crate::frame_cache::FrameCache>> {
    match self {
      AnyPage::CdpPipe(p) => &p.frame_cache,
      AnyPage::CdpRaw(p) => &p.frame_cache,
      AnyPage::WebKit(p) => &p.frame_cache,
      AnyPage::Bidi(p) => &p.frame_cache,
    }
  }

  /// Atomic latch consulted by `Page::new` to spawn the frame-event
  /// listener exactly once per backend page (instead of once per
  /// wrapper). Subsequent wrappers see the latch set and skip the
  /// spawn — see `Page::seed_frame_cache`.
  pub(crate) fn frame_listener_started(&self) -> &std::sync::Arc<std::sync::atomic::AtomicBool> {
    match self {
      AnyPage::CdpPipe(p) => &p.frame_listener_started,
      AnyPage::CdpRaw(p) => &p.frame_listener_started,
      AnyPage::WebKit(p) => &p.frame_listener_started,
      AnyPage::Bidi(p) => &p.frame_listener_started,
    }
  }

  /// The backend kind this page lives on. Used by action paths that
  /// branch per-backend (e.g. `tap` needs a CDP-only native touch API
  /// and returns `FerriError::Unsupported` on `BiDi` / `WebKit` where
  /// the protocol has no public touch injection primitive).
  #[must_use]
  pub fn kind(&self) -> BackendKind {
    match self {
      AnyPage::CdpPipe(_) => BackendKind::CdpPipe,
      AnyPage::CdpRaw(_) => BackendKind::CdpRaw,
      AnyPage::WebKit(_) => BackendKind::WebKit,
      AnyPage::Bidi(_) => BackendKind::Bidi,
    }
  }

  // ── Frames ──

  pub async fn get_frame_tree(&self) -> Result<Vec<FrameInfo>> {
    page_dispatch!(self, get_frame_tree())
  }

  /// Backend's cached top-level `frameId`, if a prior op (page-init
  /// or navigation) populated it without a `Page.getFrameTree`
  /// round-trip. Used by `crate::Page::ensure_frame_cache_seeded`
  /// to seed the wrapper's frame cache for free after a `goto`,
  /// avoiding the extra RTT that would otherwise fire when the
  /// frameNavigated event hadn't propagated through the listener
  /// yet by goto-return time.
  #[must_use]
  pub fn peek_main_frame_id(&self) -> Option<String> {
    match self {
      Self::CdpPipe(p) => p.peek_main_frame_id(),
      Self::CdpRaw(p) => p.peek_main_frame_id(),
      Self::WebKit(p) => p.peek_main_frame_id(),
      // BiDi's top-level browsing context id IS the page's main-frame
      // identifier — `browsingContext.navigate` / `browsingContext.tree`
      // all key off the same value. Surface it through the same peek
      // hook so `Page::main_frame()` can seed the frame cache without
      // an extra `browsingContext.getTree` RTT.
      Self::Bidi(p) => Some(p.context_id.to_string()),
    }
  }

  pub async fn evaluate_in_frame(&self, expression: &str, frame_id: &str) -> Result<Option<serde_json::Value>> {
    page_dispatch!(self, evaluate_in_frame(expression, frame_id))
  }

  /// The content-frame id for an `<iframe>`/`<frame>` element given its
  /// remote-object id. Deterministic on CDP (`DOM.describeNode`);
  /// `None` on BiDi/WebKit (no equivalent — callers fall back to the
  /// frame-cache heuristic) or when the element hosts no frame.
  pub async fn content_frame_id(&self, object_id: &str) -> Result<Option<String>> {
    match self {
      AnyPage::CdpPipe(p) => p.content_frame_id(object_id).await,
      AnyPage::CdpRaw(p) => p.content_frame_id(object_id).await,
      AnyPage::WebKit(p) => p.content_frame_id(object_id).await,
      AnyPage::Bidi(_) => Ok(None),
    }
  }

  // ── Navigation ──

  pub async fn goto(
    &self,
    url: &str,
    lifecycle: NavLifecycle,
    timeout_ms: u64,
    referer: Option<&str>,
  ) -> Result<Option<crate::network::Response>> {
    page_dispatch!(self, goto(url, lifecycle, timeout_ms, referer))
  }

  pub async fn wait_for_navigation(&self) -> Result<()> {
    page_dispatch!(self, wait_for_navigation())
  }

  pub async fn reload(&self, lifecycle: NavLifecycle, timeout_ms: u64) -> Result<Option<crate::network::Response>> {
    page_dispatch!(self, reload(lifecycle, timeout_ms))
  }

  pub async fn go_back(&self, lifecycle: NavLifecycle, timeout_ms: u64) -> Result<Option<crate::network::Response>> {
    page_dispatch!(self, go_back(lifecycle, timeout_ms))
  }

  pub async fn go_forward(&self, lifecycle: NavLifecycle, timeout_ms: u64) -> Result<Option<crate::network::Response>> {
    page_dispatch!(self, go_forward(lifecycle, timeout_ms))
  }

  pub async fn url(&self) -> Result<Option<String>> {
    page_dispatch!(self, url())
  }

  pub async fn title(&self) -> Result<Option<String>> {
    page_dispatch!(self, title())
  }

  // ── JavaScript ──

  /// Returns a script that ensures the selector engine is injected.
  /// Mirrored after Playwright's `injectedScript()`.
  pub async fn injected_script(&self) -> Result<String> {
    page_dispatch!(self, injected_script())
  }

  pub async fn ensure_engine_injected(&self) -> Result<()> {
    page_dispatch!(self, ensure_engine_injected())
  }

  pub async fn evaluate(&self, expression: &str) -> Result<Option<serde_json::Value>> {
    page_dispatch!(self, evaluate(expression))
  }

  // ── Elements ──

  pub async fn find_element(&self, selector: &str) -> Result<AnyElement> {
    page_dispatch!(self, find_element(selector))
  }

  /// Evaluate `js` and return the resulting DOM element, resolving in
  /// the execution context of `frame_id` (or the main frame when
  /// `frame_id` is `None`). Mirrors Playwright's `Frame`-bound element
  /// resolution: every Locator carries a Frame, and actions reach the
  /// backend with that frame's id threaded all the way through. CDP
  /// uses `Runtime.evaluate.contextId`; `BiDi` uses the browsing-context
  /// realm; `WebKit` currently has no per-frame execution context, so
  /// non-main `frame_id` values fall back to the main page (DOM access
  /// via `WKFrameInfo` is a separate gap tracked in Section B of
  /// `PLAYWRIGHT_COMPAT.md`).
  pub async fn evaluate_to_element(&self, js: &str, frame_id: Option<&str>) -> Result<AnyElement> {
    page_dispatch!(self, evaluate_to_element(js, frame_id))
  }

  // ── Content ──

  pub async fn content(&self) -> Result<String> {
    page_dispatch!(self, content())
  }

  pub async fn set_content(&self, html: &str) -> Result<()> {
    page_dispatch!(self, set_content(html))
  }

  // ── Screenshots ──

  pub async fn screenshot(&self, opts: ScreenshotOpts) -> Result<Vec<u8>> {
    page_dispatch!(self, screenshot(opts))
  }

  // ── Accessibility ──

  pub async fn accessibility_tree(&self) -> Result<Vec<AxNodeData>> {
    page_dispatch!(self, accessibility_tree())
  }

  pub async fn accessibility_tree_with_depth(&self, depth: i32) -> Result<Vec<AxNodeData>> {
    page_dispatch!(self, accessibility_tree_with_depth(depth))
  }

  // ── Input ──

  pub async fn click_at(&self, x: f64, y: f64) -> Result<()> {
    page_dispatch!(self, click_at(x, y))
  }

  pub async fn click_at_opts(&self, x: f64, y: f64, button: &str, click_count: u32) -> Result<()> {
    page_dispatch!(self, click_at_opts(x, y, button, click_count))
  }

  /// Dispatch a click at page-level coordinates `(x, y)` with the full
  /// Playwright option bag: `button`, `click_count`, modifiers, delay
  /// between press/release, and `steps` interpolated `mousemove` events
  /// between the current cursor and the target. Modifier keydown/keyup
  /// is the caller's responsibility — use [`Self::press_modifiers`] /
  /// [`Self::release_modifiers`] around this call when
  /// `!args.modifiers.is_empty()`.
  pub async fn click_at_with(&self, x: f64, y: f64, args: &BackendClickArgs) -> Result<()> {
    page_dispatch!(self, click_at_with(x, y, args))
  }

  /// Dispatch a hover (no press/release) at `(x, y)` with `steps`
  /// interpolated `mousemove` events and the caller's modifier bitmask
  /// on each. Modifier keydown/keyup is the caller's responsibility.
  pub async fn hover_at_with(&self, x: f64, y: f64, args: &BackendHoverArgs) -> Result<()> {
    page_dispatch!(self, hover_at_with(x, y, args))
  }

  /// Dispatch a native tap at `(x, y)` — CDP `Input.dispatchTouchEvent`
  /// (`touchStart` + `touchEnd`), matching Playwright's
  /// `server/chromium/crInput.ts::RawTouchscreenImpl::tap`. `BiDi` and
  /// `WebKit` do not expose a public touch injection primitive and
  /// return a backend-level error with the `unsupported:` prefix;
  /// callers should surface it as [`crate::error::FerriError::Unsupported`].
  pub async fn tap_at_with(&self, x: f64, y: f64, args: &BackendTapArgs) -> Result<()> {
    page_dispatch!(self, tap_at_with(x, y, args))
  }

  /// Press all modifiers in `mods` via the backend's keyboard input
  /// protocol (CDP `Input.dispatchKeyEvent { type: "keyDown" }`, `BiDi`
  /// `input.performActions`, or `WebKit` host IPC). Idempotent for empty
  /// lists. Callers pair this with [`Self::release_modifiers`].
  pub async fn press_modifiers(&self, mods: &[crate::options::Modifier]) -> Result<()> {
    page_dispatch!(self, press_modifiers(mods))
  }

  /// Release all modifiers in `mods`. See [`Self::press_modifiers`].
  pub async fn release_modifiers(&self, mods: &[crate::options::Modifier]) -> Result<()> {
    page_dispatch!(self, release_modifiers(mods))
  }

  pub async fn move_mouse(&self, x: f64, y: f64) -> Result<()> {
    page_dispatch!(self, move_mouse(x, y))
  }

  pub async fn move_mouse_smooth(&self, from_x: f64, from_y: f64, to_x: f64, to_y: f64, steps: u32) -> Result<()> {
    page_dispatch!(self, move_mouse_smooth(from_x, from_y, to_x, to_y, steps))
  }

  pub async fn mouse_wheel(&self, delta_x: f64, delta_y: f64) -> Result<()> {
    page_dispatch!(self, mouse_wheel(delta_x, delta_y))
  }

  pub async fn mouse_down(&self, x: f64, y: f64, button: &str) -> Result<()> {
    page_dispatch!(self, mouse_down(x, y, button))
  }

  pub async fn mouse_up(&self, x: f64, y: f64, button: &str) -> Result<()> {
    page_dispatch!(self, mouse_up(x, y, button))
  }

  pub async fn click_and_drag(&self, from: (f64, f64), to: (f64, f64), steps: u32) -> Result<()> {
    page_dispatch!(self, click_and_drag(from, to, steps))
  }

  pub async fn type_str(&self, text: &str) -> Result<()> {
    page_dispatch!(self, type_str(text))
  }

  /// Insert text without emitting keyboard events (only `input` event).
  /// This is Playwright's `keyboard.insertText()` semantic.
  pub async fn insert_text(&self, text: &str) -> Result<()> {
    // type_str on all backends uses Input.insertText / equivalent
    self.type_str(text).await
  }

  pub async fn key_down(&self, key: &str) -> Result<()> {
    page_dispatch!(self, key_down(key))
  }

  pub async fn key_up(&self, key: &str) -> Result<()> {
    page_dispatch!(self, key_up(key))
  }

  pub async fn press_key(&self, key: &str) -> Result<()> {
    page_dispatch!(self, press_key(key))
  }

  // ── Cookies ──

  pub async fn get_cookies(&self) -> Result<Vec<CookieData>> {
    page_dispatch!(self, get_cookies())
  }

  pub async fn set_cookie(&self, cookie: CookieData) -> Result<()> {
    page_dispatch!(self, set_cookie(cookie))
  }

  pub async fn delete_cookie(&self, name: &str, domain: Option<&str>) -> Result<()> {
    page_dispatch!(self, delete_cookie(name, domain))
  }

  pub async fn clear_cookies(&self) -> Result<()> {
    page_dispatch!(self, clear_cookies())
  }

  /// Clear cookies matching the given filters. If no filters, clears all.
  pub async fn clear_cookies_filtered(&self, options: &ClearCookieOptions) -> Result<()> {
    if options.name.is_none() && options.domain.is_none() && options.path.is_none() {
      return self.clear_cookies().await;
    }
    // Get all cookies, delete the ones that match the filters.
    let cookies = self.get_cookies().await?;
    for c in &cookies {
      let name_match = options.name.as_ref().is_none_or(|n| &c.name == n);
      let domain_match = options.domain.as_ref().is_none_or(|d| &c.domain == d);
      let path_match = options.path.as_ref().is_none_or(|p| &c.path == p);
      if name_match && domain_match && path_match {
        self.delete_cookie(&c.name, Some(&c.domain)).await?;
      }
    }
    Ok(())
  }

  // ── Emulation ──

  /// Apply a full [`crate::options::BrowserContextOptions`] bag. The
  /// single dispatch point for context-level state — each backend
  /// implementation fires the relevant protocol commands in parallel
  /// via `tokio::join!` and aggregates errors. Callers in
  /// `ContextRef::new_page` and the context-level public setters
  /// (`setOffline`, `setGeolocation`, etc.) mutate the bag and
  /// re-apply.
  pub async fn apply_context_options(&self, opts: &crate::options::BrowserContextOptions) -> Result<()> {
    page_dispatch!(self, apply_context_options(opts))
  }

  pub async fn emulate_viewport(&self, config: &crate::options::ViewportConfig) -> Result<()> {
    page_dispatch!(self, emulate_viewport(config))
  }

  pub async fn emulate_media(&self, opts: &crate::options::EmulateMediaOptions) -> Result<()> {
    page_dispatch!(self, emulate_media(opts))
  }

  pub async fn set_extra_http_headers(&self, headers: &rustc_hash::FxHashMap<String, String>) -> Result<()> {
    page_dispatch!(self, set_extra_http_headers(headers))
  }

  /// Reset any context-granted permissions. Backs
  /// [`crate::ContextRef::clear_permissions`] (Playwright
  /// `browserContext.clearPermissions`).
  pub async fn reset_permissions(&self) -> Result<()> {
    page_dispatch!(self, reset_permissions())
  }

  // ── Tracing ──

  pub async fn start_tracing(&self) -> Result<()> {
    page_dispatch!(self, start_tracing())
  }

  pub async fn stop_tracing(&self) -> Result<()> {
    page_dispatch!(self, stop_tracing())
  }

  pub async fn metrics(&self) -> Result<Vec<MetricData>> {
    page_dispatch!(self, metrics())
  }

  // ── Ref resolution ──

  pub async fn resolve_backend_node(&self, backend_node_id: i64, ref_id: &str) -> Result<AnyElement> {
    page_dispatch!(self, resolve_backend_node(backend_node_id, ref_id))
  }

  // ── Event listeners ──

  pub fn attach_listeners(
    &self,
    console_log: Arc<RwLock<Vec<ConsoleMessage>>>,
    network_log: Arc<RwLock<Vec<NetworkRequest>>>,
    dialog_log: Arc<RwLock<Vec<crate::state::DialogEvent>>>,
  ) {
    match self {
      Self::CdpPipe(p) => p.attach_listeners(console_log, network_log, dialog_log),
      Self::CdpRaw(p) => p.attach_listeners(console_log, network_log, dialog_log),
      Self::WebKit(p) => p.attach_listeners(console_log, network_log, dialog_log),

      Self::Bidi(p) => p.attach_listeners(console_log, network_log, dialog_log),
    }
  }

  // ── Element screenshot (by selector) ──

  pub async fn screenshot_element(&self, selector: &str, format: ImageFormat) -> Result<Vec<u8>> {
    page_dispatch!(self, screenshot_element(selector, format))
  }

  // ── PDF generation ──

  pub async fn pdf(&self, opts: crate::options::PdfOptions) -> Result<Vec<u8>> {
    page_dispatch!(self, pdf(opts))
  }

  // ── Screencast (video recording) ──

  pub async fn start_screencast(
    &self,
    quality: u8,
    max_width: u32,
    max_height: u32,
  ) -> Result<(
    tokio::sync::mpsc::UnboundedReceiver<(Vec<u8>, f64)>,
    tokio::sync::oneshot::Sender<()>,
  )> {
    match self {
      AnyPage::CdpPipe(p) => p.start_screencast(quality, max_width, max_height).await,
      AnyPage::CdpRaw(p) => p.start_screencast(quality, max_width, max_height).await,
      AnyPage::WebKit(p) => {
        let rx = p.start_screencast(quality, max_width, max_height).await?;
        let (tx, _rx_shutdown) = tokio::sync::oneshot::channel();
        Ok((rx, tx))
      },
      AnyPage::Bidi(p) => {
        // BiDi backend does not yet expose a cooperative shutdown
        // channel; synthesise one so the unified return shape holds.
        // The signal is dropped (recorder doesn't use it for BiDi);
        // BiDi's own teardown drives the pump via `stop_screencast`.
        let rx = p.start_screencast(quality, max_width, max_height).await?;
        let (tx, _rx_shutdown) = tokio::sync::oneshot::channel();
        Ok((rx, tx))
      },
    }
  }

  pub async fn stop_screencast(&self) -> Result<()> {
    match self {
      AnyPage::CdpPipe(p) => p.stop_screencast().await,
      AnyPage::CdpRaw(p) => p.stop_screencast().await,
      AnyPage::WebKit(p) => p.stop_screencast().await,

      AnyPage::Bidi(p) => p.stop_screencast().await,
    }
  }

  // ── File upload ──

  pub async fn set_file_input(&self, selector: &str, paths: &[String]) -> Result<()> {
    page_dispatch!(self, set_file_input(selector, paths))
  }

  // ── Dialog handling ──
  //
  // `set_dialog_handler` was removed — dialogs are now observed via
  // `page.on('dialog', ...)` with live `crate::dialog::Dialog`
  // handles. When no listener is registered, each backend's dialog
  // listener auto-closes (accept for `beforeunload`, dismiss
  // otherwise).

  // ── Network Interception ──

  pub async fn route(
    &self,
    matcher: crate::url_matcher::UrlMatcher,
    handler: crate::route::RouteHandler,
  ) -> Result<()> {
    page_dispatch!(self, route(matcher, handler))
  }

  pub async fn unroute(&self, matcher: &crate::url_matcher::UrlMatcher) -> Result<()> {
    page_dispatch!(self, unroute(matcher))
  }

  // ── Lifecycle ──

  pub async fn close_page(&self, opts: crate::options::PageCloseOptions) -> Result<()> {
    page_dispatch!(self, close_page(opts))
  }

  #[must_use]
  pub fn is_closed(&self) -> bool {
    match self {
      Self::CdpPipe(p) => p.is_closed(),
      Self::CdpRaw(p) => p.is_closed(),
      Self::WebKit(p) => p.is_closed(),

      Self::Bidi(p) => p.is_closed(),
    }
  }

  // ── Exposed Functions ──

  pub async fn expose_function(&self, name: &str, func: crate::events::ExposedFn) -> Result<()> {
    page_dispatch!(self, expose_function(name, func))
  }

  pub async fn remove_exposed_function(&self, name: &str) -> Result<()> {
    page_dispatch!(self, remove_exposed_function(name))
  }

  // ── Init Scripts ──

  pub async fn add_init_script(&self, source: &str) -> Result<String> {
    page_dispatch!(self, add_init_script(source))
  }

  pub async fn remove_init_script(&self, identifier: &str) -> Result<()> {
    page_dispatch!(self, remove_init_script(identifier))
  }

  // ── Handle lifecycle ──

  /// Release the backend object the given [`crate::js_handle::HandleRemote`] refers to.
  ///
  /// Each backend uses its native release primitive:
  ///
  /// * CDP: `Runtime.releaseObject { objectId }`.
  /// * `BiDi`: `script.disown { handles: [sharedId], target: {context} }`.
  /// * `WebKit`: `Op::ReleaseRef` IPC — deletes the host-side
  ///   `window.__wr` entry so a subsequent `window.__wr[id]` returns
  ///   `undefined`.
  ///
  /// # Errors
  ///
  /// Forwards the backend's protocol error if the release call fails.
  /// Already-released handles are silently tolerated where the backend
  /// allows it (CDP raises an error only on structural issues like an
  /// invalid session id; `BiDi` returns `invalid argument` for an unknown
  /// `sharedId` which we surface).
  /// ferridriver's equivalent of Playwright's
  /// `evaluateExpression(context, expr, { returnByValue, isFunction }, ...args)`
  /// (`/tmp/playwright/packages/playwright-core/src/server/javascript.ts:248`).
  /// Dispatches to each backend's native `call_utility_evaluate`.
  ///
  /// `args` are the variadic user-function arguments after isomorphic
  /// serialization; `handles` is the shared handle table every
  /// `{h: idx}` reference inside `args` indexes into. For
  /// `page.evaluate(fn, arg)` that's `args = [arg], handles = [...]`;
  /// for `handle.evaluate(fn, arg)` it's `args = [handle, arg]`,
  /// `handles = [self, ...]` — matching Playwright's
  /// `JSHandle.evaluate`'s `evaluate(ctx, ..., this, arg)` shape at
  /// `javascript.ts:161-163`. There is no separate receiver / `this`
  /// binding; Playwright doesn't have one either.
  ///
  /// # Errors
  ///
  /// Forwards backend errors (protocol failure, page-side exception,
  /// handle/backend mismatch).
  #[allow(clippy::too_many_arguments)]
  pub async fn call_utility_evaluate(
    &self,
    fn_source: &str,
    args: &[crate::protocol::SerializedValue],
    handles: &[crate::protocol::HandleId],
    frame_id: Option<&str>,
    is_function: Option<bool>,
    return_by_value: bool,
  ) -> crate::error::Result<crate::js_handle::EvaluateResult> {
    match self {
      Self::CdpPipe(p) => {
        p.call_utility_evaluate(fn_source, args, handles, frame_id, is_function, return_by_value)
          .await
      },
      Self::CdpRaw(p) => {
        p.call_utility_evaluate(fn_source, args, handles, frame_id, is_function, return_by_value)
          .await
      },
      Self::WebKit(p) => {
        p.call_utility_evaluate(fn_source, args, handles, frame_id, is_function, return_by_value)
          .await
      },
      Self::Bidi(p) => {
        p.call_utility_evaluate(fn_source, args, handles, frame_id, is_function, return_by_value)
          .await
      },
    }
  }

  pub async fn release_handle(&self, remote: &crate::js_handle::HandleRemote) -> crate::error::Result<()> {
    use crate::js_handle::HandleRemote;
    match (self, remote) {
      (Self::CdpPipe(p), HandleRemote::Cdp(obj)) => p.release_object(obj).await,
      (Self::CdpRaw(p), HandleRemote::Cdp(obj)) => p.release_object(obj).await,
      (Self::WebKit(p), HandleRemote::WebKit(obj)) => p.release_object(obj).await,
      (Self::Bidi(p), HandleRemote::Bidi { shared_id, handle }) => p.release_handle(shared_id, handle.as_deref()).await,
      // A HandleRemote shape that doesn't match the backend kind is a
      // programming error — mixed-backend handle use.
      (page, remote) => Err(crate::error::FerriError::Backend(format!(
        "handle/backend mismatch: {:?} handle on {:?} backend",
        remote,
        page.kind()
      ))),
    }
  }
}

/// Extract a [`crate::js_handle::HandleRemote`] from a backend `AnyElement`.
///
/// Called by `crate::element_handle::ElementHandle::from_any_element`
/// when wrapping a backend element into a public `ElementHandle`. Each
/// backend exposes its native wire reference (CDP `objectId` string,
/// `BiDi` `sharedId`, `WebKit` `ref_id`); this helper maps them into
/// the unified [`crate::js_handle::HandleRemote`] enum.
///
/// # Errors
///
/// Returns an error if a CDP element has neither a cached `object_id`
/// nor a `node_id` that can be resolved into one — this should never
/// happen for elements freshly returned from `find_element` /
/// `evaluate_to_element` / `DOM.resolveNode`, which always produce at
/// least one of the two.
/// Re-wrap a [`crate::js_handle::HandleRemote`] as a backend
/// [`AnyElement`]. Inverse of [`element_handle_remote`] — used by
/// [`crate::js_handle::JSHandle::as_element`] when a
/// [`crate::js_handle::JSHandle`] turns out to reference a DOM node
/// and needs to be re-packaged as an
/// [`crate::element_handle::ElementHandle`].
///
/// The remote reference must match the backend the page is running on
/// (CDP remote on CDP page, etc.) — this is an invariant guaranteed
/// by [`crate::js_handle::JSHandle`]'s construction site, so a
/// mismatch is a programming error and surfaces as
/// [`crate::error::FerriError::Backend`].
///
/// # Errors
///
/// Returns a backend-mismatch error when the remote's variant doesn't
/// line up with the page's backend kind.
pub fn element_from_remote(
  page: &AnyPage,
  remote: &crate::js_handle::HandleRemote,
) -> crate::error::Result<AnyElement> {
  use crate::js_handle::HandleRemote;
  match (page, remote) {
    (AnyPage::CdpPipe(p), HandleRemote::Cdp(obj)) => Ok(AnyElement::CdpPipe(p.element_from_object_id(obj.clone()))),
    (AnyPage::CdpRaw(p), HandleRemote::Cdp(obj)) => Ok(AnyElement::CdpRaw(p.element_from_object_id(obj.clone()))),
    (AnyPage::WebKit(p), HandleRemote::WebKit(obj)) => {
      Ok(AnyElement::WebKit(p.element_from_object_id(obj.to_string())))
    },
    (AnyPage::Bidi(p), HandleRemote::Bidi { shared_id, .. }) => {
      Ok(AnyElement::Bidi(p.element_from_shared_id(shared_id.clone())))
    },
    (page, remote) => Err(crate::error::FerriError::Backend(format!(
      "element_from_remote: backend mismatch — {:?} remote on {:?} backend",
      remote,
      page.kind()
    ))),
  }
}

pub async fn element_handle_remote(element: &AnyElement) -> crate::error::Result<crate::js_handle::HandleRemote> {
  use crate::js_handle::HandleRemote;
  match element {
    AnyElement::CdpPipe(e) => {
      let obj = e.ensure_object_id().await?;
      Ok(HandleRemote::Cdp(obj))
    },
    AnyElement::CdpRaw(e) => {
      let obj = e.ensure_object_id().await?;
      Ok(HandleRemote::Cdp(obj))
    },
    AnyElement::WebKit(e) => Ok(HandleRemote::WebKit(std::sync::Arc::from(e.object_id()))),
    AnyElement::Bidi(e) => Ok(HandleRemote::Bidi {
      shared_id: e.shared_id.clone(),
      handle: None,
    }),
  }
}

// ─── AnyElement ─────────────────────────────────────────────────────────────

/// Element handle — enum dispatch across backends.
pub enum AnyElement {
  CdpPipe(cdp::CdpElement<cdp::pipe::PipeTransport>),
  CdpRaw(cdp::CdpElement<cdp::ws::WsTransport>),
  WebKit(webkit::WebKitElement),
  Bidi(bidi::BidiElement),
}

macro_rules! element_dispatch {
    ($self:expr, $method:ident ( $($arg:expr),* $(,)? )) => {
        match $self {
            AnyElement::CdpPipe(e) => e.$method($($arg),*).await,
            AnyElement::CdpRaw(e) => e.$method($($arg),*).await,
            AnyElement::WebKit(e) => e.$method($($arg),*).await,

            AnyElement::Bidi(e) => e.$method($($arg),*).await,
        }
    };
}

impl AnyElement {
  pub async fn click(&self) -> Result<()> {
    element_dispatch!(self, click())
  }

  pub async fn dblclick(&self) -> Result<()> {
    element_dispatch!(self, dblclick())
  }

  pub async fn hover(&self) -> Result<()> {
    element_dispatch!(self, hover())
  }

  pub async fn type_str(&self, text: &str) -> Result<()> {
    element_dispatch!(self, type_str(text))
  }

  pub async fn call_js_fn(&self, function: &str) -> Result<()> {
    element_dispatch!(self, call_js_fn(function))
  }

  pub async fn call_js_fn_value(&self, function: &str) -> Result<Option<serde_json::Value>> {
    element_dispatch!(self, call_js_fn_value(function))
  }

  pub async fn scroll_into_view(&self) -> Result<()> {
    element_dispatch!(self, scroll_into_view())
  }

  pub async fn screenshot(&self, format: ImageFormat) -> Result<Vec<u8>> {
    element_dispatch!(self, screenshot(format))
  }
}