browser-commander 0.12.1

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
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
//! Browser launcher for browser automation.
//!
//! This module provides utilities for launching browser instances
//! with appropriate configuration.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use chromiumoxide::browser::{Browser as CdpBrowser, BrowserConfig};
use futures::StreamExt;

use crate::browser::chromiumoxide_adapter::ChromiumoxidePage;
use crate::browser::media::ColorScheme;
use crate::browser::node_bridge::NodeBridgePage;
use crate::core::constants::CHROME_ARGS;
use crate::core::engine::{EngineAdapter, EngineType};
use crate::downloads::{attach_downloads, DownloadManager, DownloadSetting};
use crate::fingerprint::apply::{apply_fingerprint, ApplyOptions};
use crate::fingerprint::automation_parity::{
    apply_automation_parity_args, parity_ignored_default_args,
};
use crate::fingerprint::profile::FingerprintProfile;

/// Options for launching a browser.
#[derive(Debug, Clone)]
pub struct LaunchOptions {
    /// The browser engine to use.
    pub engine: EngineType,
    /// Path to user data directory.
    pub user_data_dir: Option<PathBuf>,
    /// Run in headless mode.
    pub headless: bool,
    /// Slow down operations by this many milliseconds.
    pub slow_mo: u64,
    /// Enable verbose logging.
    pub verbose: bool,
    /// Additional Chrome arguments.
    pub args: Vec<String>,
    /// Additional Chrome arguments appended after the compatibility `args`.
    pub extra_args: Vec<String>,
    /// Browser Commander default arguments to omit.
    pub ignore_default_args: Vec<String>,
    /// Omit every Browser Commander and engine default argument.
    pub ignore_all_default_args: bool,
    /// Installed browser channel for Playwright/Puppeteer (for example, `chrome`).
    pub channel: Option<String>,
    /// Explicit path to a Chrome or Chromium executable.
    pub executable_path: Option<PathBuf>,
    /// Color scheme to emulate. `None` uses the system default.
    pub color_scheme: Option<ColorScheme>,
    /// Optional timeout for the browser launch handshake.
    pub launch_timeout: Option<Duration>,
    /// Whether to run the browser with the Chromium sandbox enabled.
    ///
    /// Defaults to `true`. Disable when running in environments where the
    /// sandbox is unavailable (e.g. CI containers without the required
    /// capabilities). This translates to the `--no-sandbox` /
    /// `--disable-setuid-sandbox` Chromium flags.
    pub sandbox: bool,
    /// Node.js executable for Playwright/Puppeteer fallback engines.
    pub node_executable: Option<PathBuf>,
    /// Working directory used to resolve Playwright/Puppeteer Node packages.
    pub node_working_dir: Option<PathBuf>,
    /// Keep `navigator.webdriver` false and the command line free of switches a
    /// hand-started Chrome does not carry.
    ///
    /// Defaults to `true`. Set to `false` to launch with the engine's own
    /// defaults, which is what the parity tests use as a negative control.
    pub automation_parity: bool,
    /// The environment pages should see: user agent, time zone, locale, core
    /// count, screen and the rest.
    ///
    /// Applied over CDP once the browser is up, so it only works for the
    /// chromiumoxide engine; see
    /// [`fingerprint::profile`](crate::fingerprint::profile) for the field list
    /// and [`presets`](crate::fingerprint::presets) for ready-made machines.
    pub fingerprint: Option<FingerprintProfile>,
    /// Manage the browser's downloads: where they are saved, how they are
    /// named, and whether they outlive the browser.
    ///
    /// Downloads are redirected over CDP, so this only works for the
    /// chromiumoxide engine; the other engines refuse rather than accept a
    /// setting they cannot honor. See [`downloads`](crate::downloads).
    pub downloads: DownloadSetting,
}

impl Default for LaunchOptions {
    fn default() -> Self {
        Self {
            engine: EngineType::Chromiumoxide,
            user_data_dir: None,
            headless: false,
            slow_mo: 0,
            verbose: false,
            args: Vec::new(),
            extra_args: Vec::new(),
            ignore_default_args: Vec::new(),
            ignore_all_default_args: false,
            channel: None,
            executable_path: None,
            color_scheme: None,
            launch_timeout: None,
            sandbox: true,
            node_executable: None,
            node_working_dir: None,
            automation_parity: true,
            fingerprint: None,
            downloads: DownloadSetting::Off,
        }
    }
}

impl LaunchOptions {
    /// Set the browser automation engine.
    pub fn engine(mut self, engine: EngineType) -> Self {
        self.engine = engine;
        if engine == EngineType::Playwright && self.slow_mo == 0 {
            self.slow_mo = 150;
        }
        self
    }

    /// Create options for chromiumoxide engine.
    pub fn chromiumoxide() -> Self {
        Self {
            engine: EngineType::Chromiumoxide,
            ..Default::default()
        }
    }

    /// Create options for fantoccini (WebDriver) engine.
    pub fn fantoccini() -> Self {
        Self {
            engine: EngineType::Fantoccini,
            ..Default::default()
        }
    }

    /// Create options for Playwright through the Node.js CLI bridge.
    pub fn playwright() -> Self {
        Self {
            engine: EngineType::Playwright,
            slow_mo: 150,
            ..Default::default()
        }
    }

    /// Create options for Puppeteer through the Node.js CLI bridge.
    pub fn puppeteer() -> Self {
        Self {
            engine: EngineType::Puppeteer,
            ..Default::default()
        }
    }

    /// Set headless mode.
    pub fn headless(mut self, headless: bool) -> Self {
        self.headless = headless;
        self
    }

    /// Set the user data directory.
    pub fn user_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.user_data_dir = Some(dir.into());
        self
    }

    /// Set slow motion delay.
    pub fn slow_mo(mut self, ms: u64) -> Self {
        self.slow_mo = ms;
        self
    }

    /// Enable verbose logging.
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Add additional Chrome arguments.
    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    /// Add Chrome arguments after the compatibility `args` field.
    pub fn with_extra_args(mut self, args: Vec<String>) -> Self {
        self.extra_args = args;
        self
    }

    /// Omit selected Browser Commander defaults.
    pub fn ignore_default_args(mut self, args: Vec<String>) -> Self {
        self.ignore_default_args = args;
        self
    }

    /// Omit every Browser Commander and engine default argument.
    pub fn ignore_all_default_args(mut self) -> Self {
        self.ignore_all_default_args = true;
        self
    }

    /// Select an installed browser channel for Playwright or Puppeteer.
    pub fn channel(mut self, channel: impl Into<String>) -> Self {
        self.channel = Some(channel.into());
        self
    }

    /// Select an explicit Chrome or Chromium executable.
    pub fn executable_path(mut self, executable_path: impl Into<PathBuf>) -> Self {
        self.executable_path = Some(executable_path.into());
        self
    }

    /// Set the color scheme for media emulation.
    pub fn color_scheme(mut self, color_scheme: ColorScheme) -> Self {
        self.color_scheme = Some(color_scheme);
        self
    }

    /// Override the browser launch timeout.
    pub fn launch_timeout(mut self, timeout: Duration) -> Self {
        self.launch_timeout = Some(timeout);
        self
    }

    /// Enable or disable the Chromium sandbox for the launched browser.
    pub fn sandbox(mut self, sandbox: bool) -> Self {
        self.sandbox = sandbox;
        self
    }

    /// Override the Node.js executable used by Playwright/Puppeteer engines.
    pub fn node_executable(mut self, executable: impl Into<PathBuf>) -> Self {
        self.node_executable = Some(executable.into());
        self
    }

    /// Set the directory where Node resolves `playwright` or `puppeteer`.
    pub fn node_working_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.node_working_dir = Some(dir.into());
        self
    }

    /// Turn fingerprint parity with a hand-started Chrome on or off.
    pub fn automation_parity(mut self, automation_parity: bool) -> Self {
        self.automation_parity = automation_parity;
        self
    }

    /// Set the environment pages should see.
    pub fn fingerprint(mut self, fingerprint: FingerprintProfile) -> Self {
        self.fingerprint = Some(fingerprint);
        self
    }

    /// Manage this browser's downloads.
    ///
    /// # Arguments
    ///
    /// * `downloads` - `true` for the defaults, `false` for none, or
    ///   [`DownloadOptions`](crate::downloads::DownloadOptions)
    pub fn downloads(mut self, downloads: impl Into<DownloadSetting>) -> Self {
        self.downloads = downloads.into();
        self
    }

    /// Get all Chrome arguments (default + custom).
    pub fn all_chrome_args(&self) -> Vec<String> {
        let mut all_args: Vec<String> = if self.ignore_all_default_args {
            Vec::new()
        } else {
            CHROME_ARGS
                .iter()
                .filter(|argument| {
                    !self
                        .ignore_default_args
                        .iter()
                        .any(|item| item == **argument)
                })
                .map(|argument| argument.to_string())
                .collect()
        };
        all_args.extend(self.args.clone());
        all_args.extend(self.extra_args.clone());
        if self.automation_parity {
            all_args = apply_automation_parity_args(&all_args);
        }
        all_args
    }

    /// Engine default switches to suppress so the command line matches a
    /// hand-started Chrome.
    ///
    /// Merged with the caller's `ignore_default_args`, because a switch the
    /// engine appends after the caller's arguments cannot be countered by
    /// passing a different value for it.
    pub fn all_ignored_default_args(&self) -> Vec<String> {
        let mut ignored = if self.automation_parity {
            parity_ignored_default_args(self.engine, self.headless)
        } else {
            Vec::new()
        };
        for argument in &self.ignore_default_args {
            if !ignored.contains(argument) {
                ignored.push(argument.clone());
            }
        }
        ignored
    }

    /// Get the user data directory, using a default if not specified.
    pub fn get_user_data_dir(&self) -> PathBuf {
        if let Some(ref dir) = self.user_data_dir {
            dir.clone()
        } else {
            let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
            home.join(".browser-commander")
                .join(format!("{}-data", self.engine))
        }
    }
}

/// Browser metadata returned alongside a launched page.
#[derive(Debug, Clone)]
pub struct Browser {
    /// The engine type being used.
    pub engine: EngineType,
    /// The user data directory.
    pub user_data_dir: PathBuf,
    /// Whether the browser is running headless.
    pub headless: bool,
}

/// Result of a browser launch.
///
/// Contains both static metadata (`browser`) and a live
/// [`EngineAdapter`] (`page`) that can be passed to the navigation,
/// interaction, and query helpers exposed by this crate.
pub struct LaunchResult {
    /// The browser metadata.
    pub browser: Browser,
    /// A live page/adapter tied to the launched browser.
    ///
    /// For `Chromiumoxide`, this is a [`ChromiumoxidePage`]
    /// implementing [`EngineAdapter`]. Pass `launch_result.page.as_ref()` to
    /// `goto`, `click`, `evaluate`, and other helpers.
    pub page: Arc<dyn EngineAdapter>,
    /// The download manager, when the caller asked for managed downloads.
    ///
    /// Downloads keep arriving while the browser is open, so the manager
    /// outlives any single call: hold on to it, and call
    /// [`DownloadManager::dispose`] before closing the browser.
    pub downloads: Option<Arc<DownloadManager>>,
}

impl std::fmt::Debug for LaunchResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LaunchResult")
            .field("browser", &self.browser)
            .field("page", &"<dyn EngineAdapter>")
            .field("downloads", &self.downloads)
            .finish()
    }
}

/// Launch a browser with the given options.
///
/// For the `Chromiumoxide` engine, this starts a Chromium process, waits for
/// the CDP handshake, opens a blank page, and returns a [`LaunchResult`]
/// containing both the metadata (`browser`) and a live page adapter (`page`)
/// implementing [`EngineAdapter`].
///
/// For the `Playwright` and `Puppeteer` engines, this starts a local Node.js
/// subprocess and uses the official Node package as a CLI bridge. The selected
/// package must be available to Node module resolution, usually by running
/// `npm install playwright` or `npm install puppeteer` in the configured
/// `node_working_dir`.
///
/// The `Fantoccini` engine is not yet implemented as a managed launcher; use
/// chromiumoxide or connect to an externally-managed WebDriver session.
///
/// # Arguments
///
/// * `options` - Launch options
///
/// # Returns
///
/// The launch result containing the browser metadata and a page adapter
///
/// # Errors
///
/// Returns an error if the browser fails to launch.
pub async fn launch_browser(options: LaunchOptions) -> Result<LaunchResult, anyhow::Error> {
    if options.verbose {
        tracing::info!("Launching browser with {} engine...", options.engine);
    }

    let user_data_dir = options.get_user_data_dir();
    std::fs::create_dir_all(&user_data_dir)?;

    match options.engine {
        EngineType::Chromiumoxide => launch_chromiumoxide(options, user_data_dir).await,
        EngineType::Playwright | EngineType::Puppeteer => {
            launch_node_bridge(options, user_data_dir).await
        }
        EngineType::Fantoccini => Err(anyhow::anyhow!(
            "fantoccini engine launch is not yet implemented; \
             connect to an existing WebDriver session or use EngineType::Chromiumoxide"
        )),
    }
}

/// A transport for engines that have none.
///
/// `attach_downloads` refuses an unsupported engine before it sends anything,
/// so this exists only to satisfy the signature; being asked to send is a bug,
/// and saying so is better than a command that silently goes nowhere.
struct UnavailableTransport;

#[async_trait::async_trait]
impl crate::fingerprint::CdpTransport for UnavailableTransport {
    async fn send(
        &self,
        method: &str,
        _params: serde_json::Value,
    ) -> anyhow::Result<serde_json::Value> {
        Err(anyhow::anyhow!(
            "this engine has no CDP transport, so {method} cannot be sent"
        ))
    }
}

async fn launch_node_bridge(
    options: LaunchOptions,
    user_data_dir: PathBuf,
) -> Result<LaunchResult, anyhow::Error> {
    let engine = options.engine;
    let headless = options.headless;
    if options.fingerprint.is_some() {
        // Failing here is the honest answer: the node bridge speaks its own
        // command protocol rather than CDP, so a profile handed to it would be
        // silently dropped and the page would report the real machine.
        return Err(anyhow::anyhow!(
            "the {engine} engine cannot apply a fingerprint profile yet; \
             use EngineType::Chromiumoxide, or apply the profile from the \
             JavaScript package, which drives Playwright and Puppeteer directly"
        ));
    }
    // Same reasoning as the fingerprint above: the bridge has no CDP route, so
    // a managed download would never be seen and every capture would time out.
    // `attach_downloads` returns `Ok(None)` when no manager was asked for, and
    // names the engine and what to use instead when one was.
    attach_downloads(engine, &UnavailableTransport, options.downloads.clone())
        .await
        .map_err(|error| anyhow::anyhow!("{error}"))?;
    let adapter = NodeBridgePage::launch(options, user_data_dir.clone()).await?;

    Ok(LaunchResult {
        browser: Browser {
            engine,
            user_data_dir,
            headless,
        },
        page: Arc::new(adapter),
        downloads: None,
    })
}

async fn launch_chromiumoxide(
    options: LaunchOptions,
    user_data_dir: PathBuf,
) -> Result<LaunchResult, anyhow::Error> {
    // chromiumoxide 0.9 stopped re-exporting `HeadlessMode`, so the mode is
    // selected through the builder's own methods instead of the enum.
    let builder = BrowserConfig::builder();
    let builder = if options.headless {
        builder.new_headless_mode()
    } else {
        builder.with_head()
    };
    let mut builder = builder
        .user_data_dir(&user_data_dir)
        .args(options.all_chrome_args());

    // Chromiumoxide only exposes an all-or-nothing switch for its own default
    // layer. Disable that layer whenever the caller requests an omission so an
    // engine-provided duplicate cannot silently re-add the selected flag.
    if options.ignore_all_default_args || !options.all_ignored_default_args().is_empty() {
        builder = builder.disable_default_args();
    }

    if !options.sandbox {
        builder = builder.no_sandbox();
    }

    if let Some(ref executable_path) = options.executable_path {
        builder = builder.chrome_executable(executable_path);
    }

    if let Some(timeout) = options.launch_timeout {
        builder = builder.launch_timeout(timeout);
    }

    let config = builder
        .build()
        .map_err(|e| anyhow::anyhow!("failed to build browser config: {}", e))?;

    let (browser, mut handler) = CdpBrowser::launch(config)
        .await
        .map_err(|e| anyhow::anyhow!("failed to launch chromium: {}", e))?;

    // Drain the CDP event stream on a background task. Dropping the handler
    // causes the browser to hang, so we must keep polling it for the lifetime
    // of the browser. Errors are logged but do not abort the task — the CDP
    // channel naturally returns errors once the browser is closed.
    let handler_task = tokio::spawn(async move {
        while let Some(event) = handler.next().await {
            if let Err(err) = event {
                tracing::debug!(error = %err, "chromiumoxide handler event error");
            }
        }
    });

    let page = browser
        .new_page("about:blank")
        .await
        .map_err(|e| anyhow::anyhow!("failed to open initial page: {}", e))?;

    let engine = options.engine;
    let headless = options.headless;
    let color_scheme = options.color_scheme.clone();

    let adapter = ChromiumoxidePage::new(page, browser, handler_task, user_data_dir.clone());

    // The fingerprint goes on before the caller can navigate, so the first
    // document a page loads already sees the configured environment. A failure
    // here is fatal rather than best-effort: a half-applied profile describes a
    // machine that does not exist, which is louder than no profile at all.
    if let Some(ref profile) = options.fingerprint {
        apply_fingerprint(&adapter, profile, ApplyOptions::default()).await?;
        if options.verbose {
            tracing::info!("Fingerprint profile applied");
        }
    }

    // Downloads are redirected before the caller can navigate too: a download
    // that starts on the first page must land in the managed directory like
    // every later one, rather than in whatever folder Chromium was using.
    let downloads = attach_downloads(engine, &adapter, options.downloads.clone())
        .await
        .map_err(|error| anyhow::anyhow!("{error}"))?;

    // Apply color scheme emulation (best-effort).
    if let Some(ref cs) = color_scheme {
        if let Err(err) = adapter.set_color_scheme(Some(cs)).await {
            if options.verbose {
                tracing::warn!(error = %err, "could not set color scheme");
            }
        }
    }

    // Bring the page to front so the address bar is not focused when running
    // headful — mirrors the JS launcher's behavior.
    if !headless {
        if let Err(err) = adapter.bring_to_front().await {
            if options.verbose {
                tracing::debug!(error = %err, "bring_to_front failed");
            }
        }
    }

    if options.verbose {
        tracing::info!("Browser launched with {} engine", engine);
    }

    Ok(LaunchResult {
        browser: Browser {
            engine,
            user_data_dir,
            headless,
        },
        page: Arc::new(adapter),
        downloads,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fingerprint::automation_parity::{
        AUTOMATION_CONTROLLED_OFF_ARG, PLAYWRIGHT_HEADLESS_POINTER_ARG,
        PLAYWRIGHT_SOFTWARE_WEBGL_ARG,
    };
    use crate::fingerprint::presets::create_default_fingerprint_preset;

    #[test]
    fn launch_options_default() {
        let options = LaunchOptions::default();
        assert_eq!(options.engine, EngineType::Chromiumoxide);
        assert!(!options.headless);
        assert_eq!(options.slow_mo, 0);
        assert!(!options.verbose);
        assert!(options.args.is_empty());
        assert!(options.extra_args.is_empty());
        assert!(options.ignore_default_args.is_empty());
        assert!(!options.ignore_all_default_args);
        assert!(options.automation_parity);
        assert!(options.channel.is_none());
        assert!(options.executable_path.is_none());
        assert!(options.node_executable.is_none());
        assert!(options.node_working_dir.is_none());
        // A launch without a profile has to leave the machine as it is, so the
        // browser reports the real hardware rather than a half-set one.
        assert!(options.fingerprint.is_none());
    }

    #[test]
    fn launch_options_builder() {
        let options = LaunchOptions::chromiumoxide()
            .headless(true)
            .slow_mo(100)
            .verbose(true)
            .with_args(vec!["--custom-arg".to_string()]);

        assert_eq!(options.engine, EngineType::Chromiumoxide);
        assert!(options.headless);
        assert_eq!(options.slow_mo, 100);
        assert!(options.verbose);
        assert_eq!(options.args, vec!["--custom-arg"]);
    }

    #[test]
    fn launch_options_fantoccini() {
        let options = LaunchOptions::fantoccini();
        assert_eq!(options.engine, EngineType::Fantoccini);
    }

    #[test]
    fn launch_options_playwright() {
        let options = LaunchOptions::playwright();
        assert_eq!(options.engine, EngineType::Playwright);
        assert_eq!(options.slow_mo, 150);
    }

    #[test]
    fn launch_options_puppeteer() {
        let options = LaunchOptions::puppeteer();
        assert_eq!(options.engine, EngineType::Puppeteer);
    }

    #[test]
    fn launch_options_node_bridge_configuration() {
        let options = LaunchOptions::playwright()
            .node_executable("/custom/node")
            .node_working_dir("/project/js")
            .channel("chrome-beta")
            .executable_path("/opt/google/chrome-beta");

        assert_eq!(options.node_executable, Some(PathBuf::from("/custom/node")));
        assert_eq!(options.node_working_dir, Some(PathBuf::from("/project/js")));
        assert_eq!(options.channel.as_deref(), Some("chrome-beta"));
        assert_eq!(
            options.executable_path,
            Some(PathBuf::from("/opt/google/chrome-beta"))
        );
    }

    #[test]
    fn all_chrome_args_includes_defaults() {
        let options = LaunchOptions::default();
        let args = options.all_chrome_args();

        assert!(args.contains(&"--disable-infobars".to_string()));
        assert!(args.contains(&"--password-store=basic".to_string()));
        assert!(args.contains(&"--no-first-run".to_string()));
    }

    #[test]
    fn all_chrome_args_appends_extra_args_and_ignores_selected_defaults() {
        let options = LaunchOptions::default()
            .with_args(vec!["--legacy-arg".to_string()])
            .with_extra_args(vec!["--lang=en-US".to_string()])
            .ignore_default_args(vec!["--no-default-browser-check".to_string()]);

        let args = options.all_chrome_args();
        assert!(args.contains(&"--password-store=basic".to_string()));
        assert!(!args.contains(&"--no-default-browser-check".to_string()));
        assert_eq!(
            &args[args.len() - 3..],
            [
                "--legacy-arg".to_string(),
                "--lang=en-US".to_string(),
                AUTOMATION_CONTROLLED_OFF_ARG.to_string()
            ]
        );
    }

    #[test]
    fn all_chrome_args_can_ignore_every_default() {
        let options = LaunchOptions::default()
            .ignore_all_default_args()
            .with_extra_args(vec!["--lang=en-US".to_string()]);

        assert_eq!(
            options.all_chrome_args(),
            [
                "--lang=en-US".to_string(),
                AUTOMATION_CONTROLLED_OFF_ARG.to_string()
            ]
        );
    }

    #[test]
    fn all_chrome_args_can_ignore_password_store_default_specifically() {
        let options = LaunchOptions::default()
            .ignore_default_args(vec!["--password-store=basic".to_string()]);

        let args = options.all_chrome_args();
        assert!(!args.contains(&"--password-store=basic".to_string()));
        assert!(args.contains(&"--no-first-run".to_string()));
    }

    #[test]
    fn all_chrome_args_includes_custom() {
        let options = LaunchOptions::default().with_args(vec!["--custom".to_string()]);
        let args = options.all_chrome_args();

        assert!(args.contains(&"--custom".to_string()));
    }

    #[test]
    fn all_chrome_args_disables_the_automation_controlled_feature() {
        let args = LaunchOptions::default().all_chrome_args();
        assert_eq!(
            args.last().map(String::as_str),
            Some(AUTOMATION_CONTROLLED_OFF_ARG)
        );
    }

    #[test]
    fn all_chrome_args_leaves_the_command_line_alone_when_parity_is_off() {
        let args = LaunchOptions::default()
            .automation_parity(false)
            .all_chrome_args();
        assert!(!args
            .iter()
            .any(|argument| argument == AUTOMATION_CONTROLLED_OFF_ARG));
    }

    #[test]
    fn all_ignored_default_args_merges_parity_with_the_caller_list() {
        let options = LaunchOptions::playwright()
            .headless(true)
            .ignore_default_args(vec!["--no-first-run".to_string()]);

        assert_eq!(
            options.all_ignored_default_args(),
            [
                "--enable-automation".to_string(),
                PLAYWRIGHT_SOFTWARE_WEBGL_ARG.to_string(),
                PLAYWRIGHT_HEADLESS_POINTER_ARG.to_string(),
                "--no-first-run".to_string()
            ]
        );
    }

    #[test]
    fn all_ignored_default_args_does_not_repeat_a_switch_the_caller_already_listed() {
        let options = LaunchOptions::playwright()
            .ignore_default_args(vec!["--enable-automation".to_string()]);

        assert_eq!(
            options.all_ignored_default_args(),
            [
                "--enable-automation".to_string(),
                PLAYWRIGHT_SOFTWARE_WEBGL_ARG.to_string()
            ]
        );
    }

    #[test]
    fn all_ignored_default_args_keeps_only_the_caller_list_when_parity_is_off() {
        let options = LaunchOptions::playwright()
            .headless(true)
            .automation_parity(false)
            .ignore_default_args(vec!["--no-first-run".to_string()]);

        assert_eq!(
            options.all_ignored_default_args(),
            ["--no-first-run".to_string()]
        );
    }

    #[test]
    fn chromiumoxide_excludes_nothing_by_default() {
        assert!(LaunchOptions::chromiumoxide()
            .all_ignored_default_args()
            .is_empty());
    }

    #[test]
    fn get_user_data_dir_uses_custom() {
        let options = LaunchOptions::default().user_data_dir("/custom/path");
        assert_eq!(options.get_user_data_dir(), PathBuf::from("/custom/path"));
    }

    #[test]
    fn get_user_data_dir_creates_default() {
        let options = LaunchOptions::default();
        let dir = options.get_user_data_dir();
        assert!(dir.to_string_lossy().contains("browser-commander"));
        assert!(dir.to_string_lossy().contains("chromiumoxide-data"));
    }

    #[tokio::test]
    async fn launch_fantoccini_is_unimplemented() {
        let options = LaunchOptions::fantoccini();
        let err = launch_browser(options).await.unwrap_err();
        assert!(err.to_string().contains("fantoccini"));
    }

    #[test]
    fn launch_options_carry_a_fingerprint_profile() {
        let profile = create_default_fingerprint_preset("windows-chrome").expect("preset");
        let options = LaunchOptions::default().fingerprint(profile.clone());

        assert_eq!(options.fingerprint, Some(profile));
    }

    #[tokio::test]
    async fn launch_playwright_refuses_a_fingerprint_it_cannot_apply() {
        // Dropping the profile silently would leave the page reporting the real
        // machine while the caller believes it is hidden.
        let options = LaunchOptions::playwright()
            .headless(true)
            .fingerprint(create_default_fingerprint_preset("windows-chrome").expect("preset"));

        let err = launch_browser(options).await.unwrap_err();

        assert!(err
            .to_string()
            .contains("cannot apply a fingerprint profile"));
    }

    #[test]
    fn launch_options_carry_a_download_setting() {
        assert!(matches!(
            LaunchOptions::default().downloads,
            DownloadSetting::Off
        ));
        assert!(matches!(
            LaunchOptions::default().downloads(true).downloads,
            DownloadSetting::On
        ));

        let configured = LaunchOptions::default()
            .downloads(crate::downloads::DownloadOptions::default().directory("/tmp/bc-downloads"));
        let DownloadSetting::Options(options) = configured.downloads else {
            panic!("the caller's download options were dropped");
        };
        assert_eq!(options.directory.as_deref(), Some("/tmp/bc-downloads"));
    }

    #[tokio::test]
    async fn launch_playwright_refuses_downloads_it_cannot_manage() {
        // Accepting the setting silently would leave the caller waiting on a
        // manager watching a directory the browser never writes into.
        let options = LaunchOptions::playwright().headless(true).downloads(true);

        let err = launch_browser(options).await.unwrap_err();

        assert!(
            err.to_string()
                .contains("managed downloads are not supported"),
            "unexpected message: {err}"
        );
    }

    #[tokio::test]
    async fn launch_playwright_reports_missing_node_executable() {
        let options = LaunchOptions::playwright()
            .headless(true)
            .node_executable("browser-commander-missing-node");
        let err = launch_browser(options).await.unwrap_err();
        assert!(err.to_string().contains("failed to start Node.js bridge"));
    }
}