browsing 0.1.7

Browser automation: navigate, click, extract, screenshot. Standalone browser control via CDP.
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
//! Browser view types

use base64::{Engine as _, engine::general_purpose};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// A browser cookie
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cookie {
    /// Cookie name
    pub name: String,
    /// Cookie value
    pub value: String,
    /// Cookie domain
    pub domain: String,
    /// Cookie path
    pub path: String,
    /// Whether cookie is secure (HTTPS only)
    pub secure: bool,
    /// Whether cookie is HTTP-only
    #[serde(rename = "httpOnly")]
    pub http_only: bool,
    /// Cookie expiration date as Unix timestamp (0 = session cookie)
    #[serde(rename = "expires")]
    pub expires: Option<f64>,
    /// SameSite attribute
    #[serde(rename = "sameSite")]
    pub same_site: Option<String>,
    /// Cookie size in bytes
    #[serde(skip)]
    pub size: Option<usize>,
    /// Whether cookie is a third-party cookie
    #[serde(skip)]
    pub third_party: Option<bool>,
}

/// Viewport configuration for device emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewportConfig {
    /// Viewport width in pixels
    pub width: u32,
    /// Viewport height in pixels
    pub height: u32,
    /// Device scale factor (DPR), e.g., 1.0, 2.0, 3.0
    pub device_scale_factor: f64,
    /// Whether to emulate mobile device
    pub mobile: bool,
    /// Whether to emulate touch events
    pub touch: bool,
    /// Orientation: "portraitPrimary", "portraitSecondary", "landscapePrimary", "landscapeSecondary"
    pub orientation: Option<String>,
    /// Whether to emulate device pixel ratio
    pub scale: Option<f64>,
}

/// Pre-configured device preset for emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevicePreset {
    /// Preset name (e.g., "iPhone 15")
    pub name: String,
    /// Viewport configuration
    pub viewport: ViewportConfig,
    /// User agent string
    pub user_agent: String,
    /// Accept language
    pub accept_language: Option<String>,
}

impl Default for ViewportConfig {
    fn default() -> Self {
        Self {
            width: 1280,
            height: 720,
            device_scale_factor: 1.0,
            mobile: false,
            touch: false,
            orientation: None,
            scale: None,
        }
    }
}

impl DevicePreset {
    /// iPhone 15 preset
    pub fn iphone_15() -> Self {
        Self {
            name: "iPhone 15".to_string(),
            viewport: ViewportConfig {
                width: 393,
                height: 852,
                device_scale_factor: 3.0,
                mobile: true,
                touch: true,
                orientation: Some("portraitPrimary".to_string()),
                scale: None,
            },
            user_agent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// iPhone 15 Pro Max preset
    pub fn iphone_15_pro_max() -> Self {
        Self {
            name: "iPhone 15 Pro Max".to_string(),
            viewport: ViewportConfig {
                width: 430,
                height: 932,
                device_scale_factor: 3.0,
                mobile: true,
                touch: true,
                orientation: Some("portraitPrimary".to_string()),
                scale: None,
            },
            user_agent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// iPad Air preset
    pub fn ipad_air() -> Self {
        Self {
            name: "iPad Air".to_string(),
            viewport: ViewportConfig {
                width: 820,
                height: 1180,
                device_scale_factor: 2.0,
                mobile: true,
                touch: true,
                orientation: Some("portraitPrimary".to_string()),
                scale: None,
            },
            user_agent: "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// Pixel 8 preset
    pub fn pixel_8() -> Self {
        Self {
            name: "Pixel 8".to_string(),
            viewport: ViewportConfig {
                width: 412,
                height: 915,
                device_scale_factor: 2.625,
                mobile: true,
                touch: true,
                orientation: Some("portraitPrimary".to_string()),
                scale: None,
            },
            user_agent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// Samsung Galaxy S24 preset
    pub fn galaxy_s24() -> Self {
        Self {
            name: "Galaxy S24".to_string(),
            viewport: ViewportConfig {
                width: 384,
                height: 824,
                device_scale_factor: 3.0,
                mobile: true,
                touch: true,
                orientation: Some("portraitPrimary".to_string()),
                scale: None,
            },
            user_agent: "Mozilla/5.0 (Linux; Android 14; SM-S921B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// Desktop 1080p preset
    pub fn desktop_1080p() -> Self {
        Self {
            name: "Desktop 1080p".to_string(),
            viewport: ViewportConfig::default(),
            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36".to_string(),
            accept_language: Some("en-US".to_string()),
        }
    }

    /// Get preset by name (case-insensitive)
    pub fn by_name(name: &str) -> Option<Self> {
        match name.to_lowercase().as_str() {
            "iphone 15" | "iphone15" => Some(Self::iphone_15()),
            "iphone 15 pro max" | "iphone15promax" | "iphone 15 pro" => Some(Self::iphone_15_pro_max()),
            "ipad air" | "ipadair" | "ipad" => Some(Self::ipad_air()),
            "pixel 8" | "pixel8" => Some(Self::pixel_8()),
            "galaxy s24" | "galaxys24" | "s24" => Some(Self::galaxy_s24()),
            "desktop" | "desktop 1080p" | "1080p" => Some(Self::desktop_1080p()),
            _ => None,
        }
    }

    /// List all available preset names
    pub fn list_names() -> Vec<&'static str> {
        vec![
            "iPhone 15",
            "iPhone 15 Pro Max",
            "iPad Air",
            "Pixel 8",
            "Galaxy S24",
            "Desktop 1080p",
        ]
    }
}

/// Page margins for PDF generation (in inches)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PageMargins {
    /// Top margin
    pub top: Option<f64>,
    /// Bottom margin
    pub bottom: Option<f64>,
    /// Left margin
    pub left: Option<f64>,
    /// Right margin
    pub right: Option<f64>,
}

/// Configuration for PDF generation via `Page.printToPDF`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PdfConfig {
    /// Paper width in inches (default: 8.5)
    pub paper_width: Option<f64>,
    /// Paper height in inches (default: 11.0)
    pub paper_height: Option<f64>,
    /// Whether to use landscape orientation
    pub landscape: Option<bool>,
    /// Whether to display header and footer
    pub display_header_footer: Option<bool>,
    /// Whether to print background graphics
    pub print_background: Option<bool>,
    /// Scale factor (default: 1.0)
    pub scale: Option<f64>,
    /// Page margins
    pub margins: Option<PageMargins>,
    /// Page ranges (e.g., "1-5, 8, 11-13")
    pub page_ranges: Option<String>,
    /// HTML template for header (requires display_header_footer: true)
    pub header_template: Option<String>,
    /// HTML template for footer (requires display_header_footer: true)
    pub footer_template: Option<String>,
    /// Whether to prefer CSS page size
    pub prefer_css_page_size: Option<bool>,
}

impl Default for PdfConfig {
    fn default() -> Self {
        Self {
            paper_width: None,
            paper_height: None,
            landscape: Some(false),
            display_header_footer: Some(false),
            print_background: Some(false),
            scale: None,
            margins: None,
            page_ranges: None,
            header_template: None,
            footer_template: None,
            prefer_css_page_size: Some(false),
        }
    }
}

/// Device metrics as reported by the browser
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceMetrics {
    /// Viewport width
    pub width: u32,
    /// Viewport height
    pub height: u32,
    /// Device pixel ratio
    pub device_scale_factor: f64,
    /// Whether mobile emulation is active
    pub mobile: bool,
}

/// Download state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DownloadState {
    /// Download is in progress
    #[serde(rename = "inProgress")]
    InProgress,
    /// Download completed successfully
    #[serde(rename = "completed")]
    Completed,
    /// Download was cancelled
    #[serde(rename = "cancelled")]
    Cancelled,
}

/// Information about a browser download
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadInfo {
    /// Download URL
    pub url: String,
    /// Suggested filename
    pub filename: String,
    /// Download GUID
    pub guid: String,
    /// Total expected bytes
    pub total_bytes: Option<u64>,
    /// Bytes received so far
    pub received_bytes: Option<u64>,
    /// Current download state
    pub state: Option<DownloadState>,
}

/// HTTP authentication credentials
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthCredentials {
    /// Username
    pub username: String,
    /// Password
    pub password: String,
    /// Optional realm (for digest auth, etc.)
    pub realm: Option<String>,
}

/// A captured network request for HAR export
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HarRequest {
    /// HTTP method
    pub method: String,
    /// Request URL
    pub url: String,
    /// Request headers
    pub headers: Vec<HarHeader>,
    /// Request body size in bytes (-1 if not available)
    pub body_size: i64,
    /// Request POST data / body content (if captured)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_data: Option<String>,
}

/// A captured network response for HAR export
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HarResponse {
    /// HTTP status code
    pub status: u16,
    /// HTTP status text
    pub status_text: String,
    /// Response headers
    pub headers: Vec<HarHeader>,
    /// Response body size in bytes (-1 if not available)
    pub body_size: i64,
    /// Response body content (if captured)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

/// A single name/value header pair
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarHeader {
    /// Header name
    pub name: String,
    /// Header value
    pub value: String,
}

/// A network entry in the HAR log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarEntry {
    /// When the request started (ISO 8601)
    pub started_date_time: String,
    /// Total time from request to response in milliseconds
    pub time: f64,
    /// The request
    pub request: HarRequest,
    /// The response (if received)
    pub response: Option<HarResponse>,
    /// Request ID for internal correlation
    #[serde(skip)]
    pub request_id: String,
}

/// The HAR log container
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarLog {
    /// HAR spec version
    pub version: String,
    /// Creator name and version
    pub creator: HarCreator,
    /// List of entries
    pub entries: Vec<HarEntry>,
}

/// HAR creator metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HarCreator {
    /// Tool name
    pub name: String,
    /// Tool version
    pub version: String,
}

/// Browser performance metrics snapshot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// Timestamp when metrics were collected (seconds since epoch)
    pub timestamp: Option<f64>,
    /// JS heap used size in bytes
    pub js_heap_used_size: Option<u64>,
    /// JS heap total size in bytes
    pub js_heap_total_size: Option<u64>,
    /// Number of documents
    pub documents: Option<u32>,
    /// Number of nodes
    pub nodes: Option<u32>,
    /// Number of JS event listeners
    pub js_event_listeners: Option<u32>,
    /// Layout duration in seconds
    pub layout_duration: Option<f64>,
    /// Recalc style duration in seconds
    pub recalc_style_duration: Option<f64>,
    /// Script duration in seconds
    pub script_duration: Option<f64>,
    /// Task duration in seconds
    pub task_duration: Option<f64>,
    /// Raw metric values from CDP
    #[serde(flatten)]
    pub raw: std::collections::HashMap<String, serde_json::Value>,
}

/// A captured browser console log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleLog {
    /// Log level: log, debug, info, error, warning, dir, dirxml, table, trace, clear,
    /// startGroup, startGroupCollapsed, endGroup, assert, profile, profileEnd,
    /// count, timeEnd, verbose
    pub level: String,
    /// Log message text
    pub text: String,
    /// Source URL
    pub url: Option<String>,
    /// Line number in source
    pub line: Option<u32>,
    /// Column number in source
    pub column: Option<u32>,
    /// Timestamp when captured (seconds since epoch)
    pub timestamp: Option<f64>,
}

/// Parameters for setting a cookie
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CookieParam {
    /// Cookie name (required)
    pub name: String,
    /// Cookie value (required)
    pub value: String,
    /// Cookie domain (defaults to current page domain)
    pub domain: Option<String>,
    /// Cookie path (defaults to "/")
    pub path: Option<String>,
    /// Whether cookie is secure
    pub secure: Option<bool>,
    /// Whether cookie is HTTP-only
    #[serde(rename = "httpOnly")]
    pub http_only: Option<bool>,
    /// Expiration date as Unix timestamp
    #[serde(rename = "expires")]
    pub expires: Option<f64>,
    /// SameSite attribute (Strict, Lax, None)
    #[serde(rename = "sameSite")]
    pub same_site: Option<String>,
    /// URL of the page (used to infer domain if not provided)
    pub url: Option<String>,
}

/// Represents information about a browser tab
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabInfo {
    /// URL of the tab
    pub url: String,
    /// Title of the tab
    pub title: String,
    /// Target ID of the tab
    #[serde(alias = "tab_id")]
    pub target_id: String,
    /// Parent target ID if this is a nested tab
    #[serde(alias = "parent_tab_id")]
    pub parent_target_id: Option<String>,
}

/// Comprehensive page size and scroll information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageInfo {
    /// Width of the viewport
    pub viewport_width: u32,
    /// Height of the viewport
    pub viewport_height: u32,
    /// Total width of the page
    pub page_width: u32,
    /// Total height of the page
    pub page_height: u32,
    /// Horizontal scroll position
    pub scroll_x: i32,
    /// Vertical scroll position
    pub scroll_y: i32,
    /// Pixels above current viewport
    pub pixels_above: u32,
    /// Pixels below current viewport
    pub pixels_below: u32,
    /// Pixels to the left of current viewport
    pub pixels_left: u32,
    /// Pixels to the right of current viewport
    pub pixels_right: u32,
}

/// Information about a pending network request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkRequest {
    /// URL of the request
    pub url: String,
    /// HTTP method used
    pub method: String,
    /// Duration of loading in milliseconds
    pub loading_duration_ms: f64,
    /// Type of resource being requested
    pub resource_type: Option<String>,
}

/// Information about a pagination button detected on the page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginationButton {
    /// Type of button ('next', 'prev', 'first', 'last', 'page_number')
    pub button_type: String,
    /// Backend node ID of the button
    pub backend_node_id: u32,
    /// Text content of the button
    pub text: String,
    /// CSS selector for the button
    pub selector: String,
    /// Whether the button is disabled
    pub is_disabled: bool,
}

/// Streamlined session information grouping commonly-accessed state
///
/// This consolidates multiple getter calls into a single struct for efficiency.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    /// Current page URL
    pub url: String,
    /// Current page title
    pub title: String,
    /// Current target ID (tab)
    pub target_id: String,
    /// Current session ID
    pub session_id: String,
}

impl SessionInfo {
    /// Create a new SessionInfo
    pub fn new(url: String, title: String, target_id: String, session_id: String) -> Self {
        Self {
            url,
            title,
            target_id,
            session_id,
        }
    }
}

/// The summary of the browser's current state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrowserStateSummary {
    /// Serialized DOM state
    pub dom_state: crate::dom::views::SerializedDOMState,
    /// Current URL
    pub url: String,
    /// Page title
    pub title: String,
    /// List of open tabs
    pub tabs: Vec<TabInfo>,
    /// Base64 encoded screenshot
    #[serde(skip_serializing_if = "Option::is_none")]
    pub screenshot: Option<String>,
    /// Page information
    pub page_info: Option<PageInfo>,
    /// Pixels above current viewport
    pub pixels_above: u32,
    /// Pixels below current viewport
    pub pixels_below: u32,
    /// List of browser errors
    pub browser_errors: Vec<String>,
    /// Whether viewing a PDF
    pub is_pdf_viewer: bool,
    /// Recent browser events
    pub recent_events: Option<String>,
    /// List of pending network requests
    pub pending_network_requests: Vec<NetworkRequest>,
    /// List of pagination buttons
    pub pagination_buttons: Vec<PaginationButton>,
    /// List of closed popup messages
    pub closed_popup_messages: Vec<String>,
}

/// A code coverage range (start offset, end offset)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageRange {
    /// Start offset in bytes
    pub start_offset: u32,
    /// End offset in bytes
    pub end_offset: u32,
    /// Whether this range was executed
    pub count: u32,
}

/// Coverage result for a single script/stylesheet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageResult {
    /// Script or stylesheet URL
    pub url: String,
    /// Content type: "script" or "css"
    pub content_type: String,
    /// Total length in bytes
    pub text_length: u32,
    /// Executed/covered ranges
    pub ranges: Vec<CoverageRange>,
}

/// URL pattern for network request interception
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterceptPattern {
    /// URL wildcard pattern (e.g., "*://*.example.com/*")
    pub url_pattern: String,
    /// Resource type filter (e.g., "Script", "XHR", "Document")
    pub resource_type: Option<String>,
    /// Interception stage: "Request" or "Response"
    pub interception_stage: Option<String>,
}

/// An intercepted network request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterceptedRequest {
    /// Fetch request ID
    pub request_id: String,
    /// Request URL
    pub url: String,
    /// HTTP method
    pub method: String,
    /// Request headers
    pub headers: Vec<HarHeader>,
    /// Post data (if any)
    pub post_data: Option<String>,
    /// Resource type
    pub resource_type: String,
}

/// A mock response to fulfill an intercepted request
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MockResponse {
    /// HTTP status code
    pub status: u16,
    /// HTTP status text
    pub status_text: String,
    /// Response headers
    pub headers: Vec<HarHeader>,
    /// Response body (plain text or base64)
    pub body: String,
    /// Whether body is base64 encoded
    pub base64_encoded: bool,
}

/// Configuration for Chrome tracing
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TraceConfig {
    /// Tracing categories to capture (e.g., ["devtools.timeline", "disabled-by-default-devtools.timeline"])
    pub categories: Vec<String>,
    /// Whether to use streaming (receive data via events)
    pub streaming: Option<bool>,
    /// Trace buffer size in bytes
    pub buffer_size: Option<u64>,
}

/// Result from a completed trace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceResult {
    /// Whether the trace was successfully collected
    pub success: bool,
    /// Raw trace events (JSON array of trace events)
    pub events: Vec<serde_json::Value>,
    /// Trace start timestamp
    pub start_time: Option<f64>,
    /// Trace end timestamp
    pub end_time: Option<f64>,
}

/// A single touch point for gesture emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TouchPoint {
    /// X coordinate in CSS pixels
    pub x: f64,
    /// Y coordinate in CSS pixels
    pub y: f64,
    /// Touch point radius in CSS pixels (optional)
    pub radius_x: Option<f64>,
    /// Touch point radius in CSS pixels (optional)
    pub radius_y: Option<f64>,
    /// Rotation angle in degrees (optional)
    pub rotation_angle: Option<f64>,
    /// Force value 0..1 (optional)
    pub force: Option<f64>,
    /// Touch point ID (for multi-touch)
    pub id: Option<u32>,
}

impl TouchPoint {
    /// Create a simple touch point at the given coordinates
    pub fn at(x: f64, y: f64) -> Self {
        Self {
            x,
            y,
            radius_x: None,
            radius_y: None,
            rotation_angle: None,
            force: None,
            id: None,
        }
    }
}

/// Color scheme preference for media feature emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColorScheme {
    /// Light mode
    #[serde(rename = "light")]
    Light,
    /// Dark mode
    #[serde(rename = "dark")]
    Dark,
    /// No preference (system default)
    #[serde(rename = "no-preference")]
    NoPreference,
}

/// Media feature for emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaFeature {
    /// Feature name (e.g., "prefers-color-scheme", "prefers-reduced-motion")
    pub name: String,
    /// Feature value (e.g., "dark", "light", "reduce")
    pub value: String,
}

/// Vision deficiency type for accessibility emulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VisionDeficiency {
    /// No vision deficiency
    #[serde(rename = "none")]
    None,
    /// Achromatopsia (no color)
    #[serde(rename = "achromatopsia")]
    Achromatopsia,
    /// Blurred vision
    #[serde(rename = "blurredVision")]
    BlurredVision,
    /// Deuteranopia (green-blind)
    #[serde(rename = "deuteranopia")]
    Deuteranopia,
    /// Protanopia (red-blind)
    #[serde(rename = "protanopia")]
    Protanopia,
    /// Tritanopia (blue-blind)
    #[serde(rename = "tritanopia")]
    Tritanopia,
}

/// Information about a web worker
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerInfo {
    /// Worker target ID
    pub target_id: String,
    /// Worker URL
    pub url: String,
    /// Worker type ("web", "service", "shared")
    pub worker_type: String,
    /// Session ID after attaching
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
}

/// Service worker registration info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceWorkerRegistration {
    /// Registration ID
    pub registration_id: String,
    /// Scope URL
    pub scope_url: String,
    /// Whether the registration is deleted
    pub is_deleted: bool,
}

/// Service worker version info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceWorkerVersion {
    /// Version ID
    pub version_id: String,
    /// Registration ID
    pub registration_id: String,
    /// Script URL
    pub script_url: String,
    /// Worker status (e.g., "installing", "installed", "activating", "activated", "redundant")
    pub status: String,
    /// Whether the worker is running
    pub running_status: Option<String>,
}

/// Browser permission type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PermissionType {
    /// Camera access
    #[serde(rename = "videoCapture")]
    VideoCapture,
    /// Microphone access
    #[serde(rename = "audioCapture")]
    AudioCapture,
    /// Geolocation
    #[serde(rename = "geolocation")]
    Geolocation,
    /// Notifications
    #[serde(rename = "notifications")]
    Notifications,
    /// Clipboard read/write
    #[serde(rename = "clipboardReadWrite")]
    ClipboardReadWrite,
    /// Display capture (screen sharing)
    #[serde(rename = "displayCapture")]
    DisplayCapture,
    /// Background sync
    #[serde(rename = "backgroundSync")]
    BackgroundSync,
    /// Payment handler
    #[serde(rename = "paymentHandler")]
    PaymentHandler,
    /// Sensors (accelerometer, gyroscope, etc.)
    #[serde(rename = "sensors")]
    Sensors,
    /// NFC
    #[serde(rename = "nfc")]
    Nfc,
    /// MIDI
    #[serde(rename = "midi")]
    Midi,
    /// MIDI SysEx
    #[serde(rename = "midiSysex")]
    MidiSysex,
    /// Wake lock (screen)
    #[serde(rename = "wakeLockScreen")]
    WakeLockScreen,
    /// Wake lock (system)
    #[serde(rename = "wakeLockSystem")]
    WakeLockSystem,
    /// Storage access
    #[serde(rename = "storageAccess")]
    StorageAccess,
    /// Window management
    #[serde(rename = "windowManagement")]
    WindowManagement,
}

/// Type of JavaScript dialog
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DialogType {
    /// alert() dialog
    #[serde(rename = "alert")]
    Alert,
    /// confirm() dialog
    #[serde(rename = "confirm")]
    Confirm,
    /// prompt() dialog
    #[serde(rename = "prompt")]
    Prompt,
    /// beforeunload dialog
    #[serde(rename = "beforeunload")]
    Beforeunload,
}

/// Information about an intercepted file chooser dialog
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileChooserInfo {
    /// Frame ID where the chooser was triggered
    pub frame_id: String,
    /// Backend node ID of the file input element
    pub backend_node_id: u32,
    /// Whether multiple files are accepted
    pub multiple: bool,
}

/// Information about a JavaScript dialog
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialogInfo {
    /// Dialog type
    pub dialog_type: DialogType,
    /// Dialog message text
    pub message: String,
    /// Default prompt text (for prompt dialogs)
    pub default_prompt: Option<String>,
    /// URL that opened the dialog
    pub url: String,
}

/// The summary of the browser's state at a past point in time
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrowserStateHistory {
    /// URL at the time
    pub url: String,
    /// Title at the time
    pub title: String,
    /// Tabs at the time
    pub tabs: Vec<TabInfo>,
    /// Elements that were interacted with
    pub interacted_element: Vec<Option<crate::dom::views::DOMInteractedElement>>,
    /// Path to screenshot file
    pub screenshot_path: Option<String>,
}

impl BrowserStateHistory {
    /// Gets the screenshot as base64 string
    pub fn get_screenshot(&self) -> Option<String> {
        if let Some(ref path) = self.screenshot_path
            && let Ok(data) = std::fs::read(path) {
                return Some(general_purpose::STANDARD.encode(&data));
            }
        None
    }

    /// Converts the state history to a dictionary
    pub fn to_dict(&self) -> HashMap<String, serde_json::Value> {
        let val = serde_json::to_value(self).unwrap();
        match val {
            serde_json::Value::Object(map) => map.into_iter().collect(),
            other => {
                let mut map = HashMap::new();
                map.insert("value".to_string(), other);
                map
            }
        }
    }
}