browser-commander 0.18.0

Universal browser automation library that supports multiple browser engines with a unified API
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
//! Browser engine detection and abstraction.
//!
//! This module provides traits and types for abstracting over different
//! browser automation engines.

use async_trait::async_trait;
use futures::stream::BoxStream;

use crate::interactions::click_result::{ClickEffect, Evidence};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// The type of browser automation engine being used.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EngineType {
    /// Chrome DevTools Protocol based engine (similar to Puppeteer)
    Chromiumoxide,
    /// Native WebDriver engine, also selected with `selenium` or `webdriver`.
    #[serde(alias = "selenium", alias = "webdriver")]
    Fantoccini,
    /// Playwright's native driver protocol, with an optional Node.js bridge.
    Playwright,
    /// Puppeteer driven through the Node.js package as a CLI bridge.
    Puppeteer,
}

impl std::fmt::Display for EngineType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EngineType::Chromiumoxide => write!(f, "chromiumoxide"),
            EngineType::Fantoccini => write!(f, "fantoccini"),
            EngineType::Playwright => write!(f, "playwright"),
            EngineType::Puppeteer => write!(f, "puppeteer"),
        }
    }
}

impl std::str::FromStr for EngineType {
    type Err = EngineError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "chromiumoxide" | "cdp" => Ok(EngineType::Chromiumoxide),
            "fantoccini" | "webdriver" | "selenium" => Ok(EngineType::Fantoccini),
            "playwright" => Ok(EngineType::Playwright),
            "puppeteer" => Ok(EngineType::Puppeteer),
            _ => Err(EngineError::InvalidEngine(s.to_string())),
        }
    }
}

/// Errors related to browser engine operations.
#[derive(Debug, Error)]
pub enum EngineError {
    /// Invalid engine type specified.
    #[error(
        "Invalid engine: {0}. Expected 'chromiumoxide', 'fantoccini'/'selenium'/'webdriver', 'playwright', or 'puppeteer'"
    )]
    InvalidEngine(String),

    /// Element not found.
    #[error("Element not found: {0}")]
    ElementNotFound(String),

    /// Operation timed out.
    #[error("Operation timed out: {0}")]
    Timeout(String),

    /// Navigation error.
    #[error("Navigation error: {0}")]
    Navigation(String),

    /// JavaScript evaluation error.
    #[error("JavaScript evaluation error: {0}")]
    Evaluation(String),

    /// Generic browser error.
    #[error("Browser error: {0}")]
    Browser(String),
}

/// Result of an element query.
#[derive(Debug, Clone)]
pub struct ElementInfo {
    /// The element's tag name.
    pub tag_name: String,
    /// The element's text content.
    pub text_content: Option<String>,
    /// Whether the element is visible.
    pub is_visible: bool,
    /// Whether the element is enabled (for form elements).
    pub is_enabled: bool,
    /// The element's bounding box (x, y, width, height).
    pub bounding_box: Option<(f64, f64, f64, f64)>,
}

/// Result of a click verification.
///
/// `verified` is a legacy alias for "the effect was confirmed". The verdict
/// itself lives in [`ClickVerificationResult::effect`], which can also say
/// "nothing was observed" - a distinct answer from "the click failed".
#[derive(Debug, Clone)]
pub struct ClickVerificationResult {
    /// Whether the click was verified as successful.
    pub verified: bool,
    /// The reason for the verification result.
    pub reason: String,
    /// Whether a navigation error occurred during verification.
    pub navigation_error: bool,
    /// What the page was observed to do.
    pub effect: ClickEffect,
    /// The observations behind the verdict.
    pub evidence: Vec<Evidence>,
}

impl ClickVerificationResult {
    /// Build a verdict from an observed effect.
    pub fn new(effect: ClickEffect, reason: impl Into<String>, evidence: Vec<Evidence>) -> Self {
        Self {
            verified: effect == ClickEffect::Confirmed,
            reason: reason.into(),
            navigation_error: false,
            effect,
            evidence,
        }
    }

    /// Build a verdict confirming that the click had an effect.
    pub fn confirmed(reason: impl Into<String>, evidence: Vec<Evidence>) -> Self {
        Self::new(ClickEffect::Confirmed, reason, evidence)
    }

    /// Build a verdict that observed nothing either way.
    pub fn not_observed(reason: impl Into<String>, evidence: Vec<Evidence>) -> Self {
        Self::new(ClickEffect::NotObserved, reason, evidence)
    }

    /// Mark this verdict as one reached while the page was navigating away.
    #[must_use]
    pub fn with_navigation_error(mut self, navigation_error: bool) -> Self {
        self.navigation_error = navigation_error;
        self
    }
}

/// Result of a scroll verification.
#[derive(Debug, Clone)]
pub struct ScrollVerificationResult {
    /// Whether the scroll was verified as successful.
    pub verified: bool,
    /// Whether the element is in the viewport.
    pub in_viewport: bool,
    /// Number of verification attempts.
    pub attempts: u32,
}

/// Result of a fill verification.
#[derive(Debug, Clone)]
pub struct FillVerificationResult {
    /// Whether the fill was verified as successful.
    pub verified: bool,
    /// The actual value in the element after filling.
    pub actual_value: String,
    /// Number of verification attempts.
    pub attempts: u32,
}

/// Options for PDF generation.
#[derive(Debug, Clone, Default)]
pub struct PdfOptions {
    /// Paper format (e.g. "A4", "Letter").
    pub format: Option<String>,
    /// Print background graphics.
    pub print_background: bool,
    /// Page margins as CSS strings (e.g. "1cm").
    pub margin_top: Option<String>,
    pub margin_right: Option<String>,
    pub margin_bottom: Option<String>,
    pub margin_left: Option<String>,
    /// Scale of the webpage rendering (0.1–2.0).
    pub scale: Option<f64>,
    /// Optional file path to save the PDF.
    pub path: Option<String>,
}

/// Pre-click state captured for verification.
#[derive(Debug, Clone, Default)]
pub struct PreClickState {
    /// Whether the element was disabled.
    pub disabled: Option<bool>,
    /// The aria-pressed attribute value.
    pub aria_pressed: Option<String>,
    /// The aria-expanded attribute value.
    pub aria_expanded: Option<String>,
    /// The aria-selected attribute value.
    pub aria_selected: Option<String>,
    /// Whether the element was checked (for checkboxes).
    pub checked: Option<bool>,
    /// The element's class name.
    pub class_name: Option<String>,
    /// Whether the element is connected to the DOM.
    pub is_connected: bool,
}

/// Something the browser did that a trace records (issue #108).
///
/// Engines that can report page activity hand these to a recorder through
/// [`EngineAdapter::trace_events`]; each maps to one `js/src/traces/observers.js`
/// record.
#[derive(Debug, Clone, PartialEq)]
pub enum TraceEngineEvent {
    /// A frame committed a navigation.
    Navigated {
        /// Whether it was the top-level frame.
        main_frame: bool,
        /// The URL it navigated to.
        url: String,
    },
    /// The page wrote to its console.
    Console {
        /// `log`, `warning`, `error`, ...
        level: String,
        /// The message text.
        text: String,
    },
    /// An uncaught exception.
    PageError {
        /// The error message.
        message: String,
        /// The stack, when the engine reports one.
        stack: Option<String>,
    },
    /// A request failed.
    RequestFailed {
        /// The request URL.
        url: String,
        /// The request method.
        method: String,
        /// Why it failed.
        error_text: Option<String>,
    },
    /// A dialog opened.
    Dialog {
        /// `alert`, `confirm`, `prompt` or `beforeunload`.
        dialog_type: String,
        /// The dialog message.
        message: String,
    },
    /// A download changed state.
    Download {
        /// `started`, `completed`, `failed`, ...
        phase: String,
        /// The engine's identifier for the download.
        id: Option<String>,
        /// The file name the page suggested.
        suggested_filename: Option<String>,
        /// Where it was saved.
        path: Option<String>,
        /// A checksum of the saved file.
        checksum: Option<String>,
        /// Bytes saved.
        bytes: Option<u64>,
        /// The download URL.
        url: Option<String>,
        /// Why it failed.
        failure: Option<String>,
    },
}

/// Trait for browser engine adapters.
///
/// This trait provides a unified interface for different browser automation
/// engines, allowing the library to work with multiple backends.
#[async_trait]
pub trait EngineAdapter: Send + Sync {
    /// Get the engine type.
    fn engine_type(&self) -> EngineType;

    /// Get the current page URL.
    async fn url(&self) -> Result<String, EngineError>;

    /// Navigate to a URL.
    async fn goto(&self, url: &str) -> Result<(), EngineError>;

    /// Query for a single element.
    async fn query_selector(&self, selector: &str) -> Result<Option<ElementInfo>, EngineError>;

    /// Query for all matching elements.
    async fn query_selector_all(&self, selector: &str) -> Result<Vec<ElementInfo>, EngineError>;

    /// Count matching elements.
    async fn count(&self, selector: &str) -> Result<usize, EngineError>;

    /// Click an element.
    async fn click(&self, selector: &str) -> Result<(), EngineError>;

    /// Click at viewport coordinates, without scrolling anything into view.
    ///
    /// This is what `ClickScroll::None` needs: the engine's element click
    /// scrolls the target into view first, so it cannot honor a "do not scroll"
    /// request. The default implementation reports that the engine has no such
    /// API, so the constraint is refused rather than silently ignored.
    ///
    /// # Arguments
    ///
    /// * `x` - Viewport x coordinate
    /// * `y` - Viewport y coordinate
    ///
    /// # Returns
    ///
    /// Nothing on success, or [`EngineError::Browser`] when unsupported.
    async fn mouse_click(&self, x: f64, y: f64) -> Result<(), EngineError> {
        let _ = (x, y);
        Err(EngineError::Browser(
            "this engine does not expose viewport-coordinate pointer input".to_string(),
        ))
    }

    /// Fill an input element with text.
    async fn fill(&self, selector: &str, text: &str) -> Result<(), EngineError>;

    /// Type text into an element (simulating key presses).
    async fn type_text(&self, selector: &str, text: &str) -> Result<(), EngineError>;

    /// Get the text content of an element.
    async fn text_content(&self, selector: &str) -> Result<Option<String>, EngineError>;

    /// Get the value of an input element.
    async fn input_value(&self, selector: &str) -> Result<Option<String>, EngineError>;

    /// Get an attribute value from an element.
    async fn get_attribute(
        &self,
        selector: &str,
        attribute: &str,
    ) -> Result<Option<String>, EngineError>;

    /// Check if an element is visible.
    async fn is_visible(&self, selector: &str) -> Result<bool, EngineError>;

    /// Check if an element is enabled.
    async fn is_enabled(&self, selector: &str) -> Result<bool, EngineError>;

    /// Wait for a selector to appear.
    async fn wait_for_selector(&self, selector: &str, timeout_ms: u64) -> Result<(), EngineError>;

    /// Scroll an element into view.
    async fn scroll_into_view(&self, selector: &str) -> Result<(), EngineError>;

    /// Evaluate JavaScript in the page context.
    async fn evaluate(&self, script: &str) -> Result<serde_json::Value, EngineError>;

    /// Read `chrome://version` in a fresh tab without changing the current page.
    async fn read_browser_version_page(&self) -> Result<serde_json::Value, EngineError> {
        Err(EngineError::Browser(format!(
            "browser version metadata is unavailable for the {} engine",
            self.engine_type()
        )))
    }

    /// Restore portable cookies and origin-scoped localStorage before navigation.
    async fn restore_storage_state(&self, _state: serde_json::Value) -> Result<(), EngineError> {
        Err(EngineError::Browser(format!(
            "portable storage state is unavailable for the {} engine",
            self.engine_type()
        )))
    }

    /// Export portable cookies and the current page's localStorage.
    async fn export_storage_state(&self) -> Result<serde_json::Value, EngineError> {
        Err(EngineError::Browser(format!(
            "portable storage state is unavailable for the {} engine",
            self.engine_type()
        )))
    }

    /// Take a screenshot.
    async fn screenshot(&self) -> Result<Vec<u8>, EngineError>;

    /// Generate a PDF of the current page.
    ///
    /// Only supported by Chromium-based engines (chromiumoxide).
    /// Returns an error for engines that do not support PDF generation.
    async fn pdf(&self, options: PdfOptions) -> Result<Vec<u8>, EngineError>;

    /// Bring the page to front.
    async fn bring_to_front(&self) -> Result<(), EngineError>;

    /// Wait for navigation to complete.
    async fn wait_for_navigation(&self, timeout_ms: u64) -> Result<(), EngineError>;

    // =========================================================================
    // Page-level Keyboard Operations
    // =========================================================================

    /// Press a key at the page level (e.g. "Escape", "Enter", "Tab").
    ///
    /// Key names follow the Playwright/Puppeteer convention.
    async fn keyboard_press(&self, key: &str) -> Result<(), EngineError>;

    /// Type text at the page level (dispatches key events for each character).
    async fn keyboard_type(&self, text: &str) -> Result<(), EngineError>;

    /// Hold a key down at the page level. Must be paired with `keyboard_up`.
    async fn keyboard_down(&self, key: &str) -> Result<(), EngineError>;

    /// Release a held key at the page level.
    async fn keyboard_up(&self, key: &str) -> Result<(), EngineError>;

    // =========================================================================
    // Trace recording (issue #108)
    // =========================================================================

    /// Run `script` in every document the page loads from now on; an
    /// identifier for [`EngineAdapter::remove_init_script`], or `None` when the
    /// engine cannot (the default).
    async fn add_init_script(&self, _script: &str) -> Result<Option<String>, EngineError> {
        Ok(None)
    }

    /// Stop running a script added with [`EngineAdapter::add_init_script`].
    async fn remove_init_script(&self, _identifier: &str) -> Result<(), EngineError> {
        Ok(())
    }

    /// A stream of page activity for a trace recorder, or `None` when the
    /// engine does not report any (the default).
    async fn trace_events(&self) -> Option<BoxStream<'static, TraceEngineEvent>> {
        None
    }
}

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

    #[test]
    fn engine_type_display() {
        assert_eq!(EngineType::Chromiumoxide.to_string(), "chromiumoxide");
        assert_eq!(EngineType::Fantoccini.to_string(), "fantoccini");
        assert_eq!(EngineType::Playwright.to_string(), "playwright");
        assert_eq!(EngineType::Puppeteer.to_string(), "puppeteer");
    }

    #[test]
    fn engine_type_from_str() {
        assert_eq!(
            "chromiumoxide".parse::<EngineType>().unwrap(),
            EngineType::Chromiumoxide
        );
        assert_eq!(
            "cdp".parse::<EngineType>().unwrap(),
            EngineType::Chromiumoxide
        );
        assert_eq!(
            "puppeteer".parse::<EngineType>().unwrap(),
            EngineType::Puppeteer
        );
        assert_eq!(
            "puppeteer".parse::<EngineType>().unwrap().to_string(),
            "puppeteer"
        );
        assert_eq!(
            "fantoccini".parse::<EngineType>().unwrap(),
            EngineType::Fantoccini
        );
        assert_eq!(
            "webdriver".parse::<EngineType>().unwrap(),
            EngineType::Fantoccini
        );
        assert_eq!(
            "playwright".parse::<EngineType>().unwrap(),
            EngineType::Playwright
        );
        assert_eq!(
            "playwright".parse::<EngineType>().unwrap().to_string(),
            "playwright"
        );
    }

    #[test]
    fn engine_type_from_str_case_insensitive() {
        assert_eq!(
            "CHROMIUMOXIDE".parse::<EngineType>().unwrap(),
            EngineType::Chromiumoxide
        );
        assert_eq!(
            "Fantoccini".parse::<EngineType>().unwrap(),
            EngineType::Fantoccini
        );
        assert_eq!(
            "Playwright".parse::<EngineType>().unwrap(),
            EngineType::Playwright
        );
        assert_eq!(
            "Puppeteer".parse::<EngineType>().unwrap(),
            EngineType::Puppeteer
        );
    }

    #[test]
    fn engine_type_from_str_invalid() {
        let result = "invalid".parse::<EngineType>();
        assert!(result.is_err());
        if let Err(EngineError::InvalidEngine(name)) = result {
            assert_eq!(name, "invalid");
        } else {
            panic!("Expected InvalidEngine error");
        }
    }

    // feature-parity: engines.webdriver@native-typed
    #[test]
    fn selenium_alias_selects_native_webdriver() {
        for name in ["selenium", "SELENIUM", "webdriver", "fantoccini"] {
            assert_eq!(name.parse::<EngineType>().unwrap(), EngineType::Fantoccini);
        }
        assert_eq!(
            serde_json::from_str::<EngineType>("\"selenium\"").unwrap(),
            EngineType::Fantoccini
        );
        let options =
            crate::browser::launcher::LaunchOptions::default().engine("selenium".parse().unwrap());
        assert_eq!(options.launch, crate::browser::launcher::LaunchMode::Engine);
    }

    #[test]
    fn pdf_options_default() {
        let opts = PdfOptions::default();
        assert!(opts.format.is_none());
        assert!(!opts.print_background);
        assert!(opts.margin_top.is_none());
        assert!(opts.path.is_none());
        assert!(opts.scale.is_none());
    }

    #[test]
    fn pdf_options_can_be_constructed() {
        let opts = PdfOptions {
            format: Some("A4".to_string()),
            print_background: true,
            margin_top: Some("1cm".to_string()),
            margin_right: Some("1cm".to_string()),
            margin_bottom: Some("1cm".to_string()),
            margin_left: Some("1cm".to_string()),
            scale: Some(1.0),
            path: None,
        };
        assert_eq!(opts.format.as_deref(), Some("A4"));
        assert!(opts.print_background);
        assert_eq!(opts.margin_top.as_deref(), Some("1cm"));
        assert_eq!(opts.scale, Some(1.0));
    }

    #[test]
    fn pre_click_state_default() {
        let state = PreClickState::default();
        assert!(state.disabled.is_none());
        assert!(state.aria_pressed.is_none());
        assert!(!state.is_connected);
    }

    #[test]
    fn click_verification_result_creation() {
        let result = ClickVerificationResult::confirmed(
            "element state changed",
            vec![Evidence::message("element-state", "className changed")],
        );
        assert!(result.verified);
        assert!(!result.navigation_error);
        assert_eq!(result.effect, ClickEffect::Confirmed);
        assert_eq!(result.evidence.len(), 1);

        // Regression test for issue #89: "nothing was observed" must never
        // present itself as a verified click.
        let unobserved = ClickVerificationResult::not_observed("no observable change", vec![]);
        assert!(!unobserved.verified);
        assert_eq!(unobserved.effect, ClickEffect::NotObserved);
    }
}