plwr 0.21.0

Playwright CLI for browser automation using CSS selectors.
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
mod client;
mod daemon;
mod protocol;
mod pw_ext;

use crate::protocol::Command;
use clap::{CommandFactory, Parser, Subcommand};
use std::collections::HashSet;
use std::path::PathBuf;
use std::process::ExitCode;

#[derive(Parser)]
#[command(
    name = "plwr",
    about = "Playwright CLI for browser automation using CSS selectors",
    after_long_help = EXAMPLES,
    after_help = "Use --help for examples",
    disable_help_subcommand = true,
    version,
)]
struct Cli {
    /// Session name for parallel browser instances
    #[arg(
        short = 'S',
        long,
        global = true,
        env = "PLWR_SESSION",
        default_value = "default"
    )]
    session: String,

    /// Timeout in milliseconds for wait/click/fill operations
    #[arg(
        short = 'T',
        long,
        global = true,
        env = "PLWR_TIMEOUT",
        default_value_t = 5000
    )]
    timeout: u64,

    #[command(subcommand)]
    command: Cmd,
}

const EXAMPLES: &str = "\x1b[1;4mExamples:\x1b[0m

  Start the browser and navigate:
    plwr start                           # start headless browser
    plwr start --headed                  # start with visible window
    plwr open https://example.com
    plwr text h1                         # \"Example Domain\"
    plwr attr a href                     # \"https://www.iana.org/...\"
    plwr stop

  Fill a form and submit:
    plwr fill '#email' 'alice@test.com'
    plwr fill '#password' 'hunter2'
    plwr click 'button[type=submit]'
    plwr wait '.dashboard'               # wait for redirect

  When a selector matches multiple elements:
    plwr click 'li.item >> nth=0'        # first match
    plwr click 'li.item >> nth=2'        # third match
    plwr text ':nth-match(li.item, 2)'   # alternative syntax

  Chain with shell conditionals:
    plwr exists '.cookie-banner' && plwr click '.accept-cookies'

  Set headers for authenticated requests:
    plwr header Authorization 'Bearer tok_xxx'
    plwr open https://api.example.com/dashboard

  Manage cookies:
    plwr cookie session_id abc123
    plwr cookie --list                   # show all as JSON
    plwr cookie --clear

  Run JavaScript:
    plwr eval 'document.title'
    plwr eval '({count: document.querySelectorAll(\"li\").length})'

  Inspect the DOM:
    plwr tree '.sidebar'                 # JSON tree of element
    plwr count '.search-result'          # number of matches

  Screenshot and video:
    plwr screenshot --selector '.chart' --path chart.png
    plwr video-start
    plwr click '#run-demo'
    plwr video-stop demo.mp4

  Adjust viewport for responsive testing:
    plwr viewport 375 667               # iPhone SE
    plwr screenshot --path mobile.png
    plwr viewport 1280 720              # desktop

  Keyboard input:
    plwr press Enter
    plwr press Control+a                 # select all
    plwr press Meta+c                    # copy (macOS)

  Sessions — each session is an independent browser with its own
  cookies, headers, and page state:
    plwr -S admin start
    plwr -S user start --headed
    plwr -S admin open https://app.com/admin
    plwr -S user open https://app.com/login
    plwr -S user fill '#email' 'user@test.com'
    plwr -S admin text '.active-users'   # check admin view
    plwr -S admin stop
    plwr -S user stop

  Wait for one of several outcomes:
    plwr wait-any '.success-msg' '.error-msg'  # prints which matched
    plwr wait-all '.header' '.sidebar' '.main' # all must appear

  Custom timeout:
    plwr wait '.slow-element' -T 30000   # wait up to 30s

\x1b[1;4mSelector reference:\x1b[0m

  Playwright extends CSS selectors with extra features.

  CSS selectors (all standard CSS works):
    plwr click '#submit-btn'             # by id
    plwr click '.btn.primary'            # compound class
    plwr count 'input[type=email]'       # attribute match
    plwr count 'input:checked'           # pseudo-class
    plwr count 'input:disabled'          # form state
    plwr count 'input:required'          # form validation
    plwr count 'div:empty'              # empty elements
    plwr click 'li:first-child'          # positional
    plwr click 'li:last-child'           # positional
    plwr count '#list > li'              # child combinator
    plwr count 'h1 + p'                  # adjacent sibling
    plwr count 'h1 ~ p'                  # general sibling
    plwr count 'a[href^=/]'              # starts with
    plwr count 'a[href$=.pdf]'           # ends with
    plwr count 'a[href*=example]'        # contains
    plwr count 'a[download]'             # has attribute
    plwr click 'li:not(.done)'           # negation
    plwr click '.card:has(img)'          # has descendant

  Playwright extensions:
    plwr click ':has-text(\"Sign in\")'    # contains text
    plwr click 'text=Sign in'            # text shorthand
    plwr click 'li.item >> nth=0'        # pick nth match
    plwr click ':visible'                # only visible
    plwr text 'tr:has-text(\"Bob\") >> td.status'
                                         # chain with >>

  Some CSS pseudo-classes need the css= prefix to avoid
  Playwright's selector parser misinterpreting them:
    plwr text 'css=span:last-of-type'         # ✓ works
    plwr text 'span:last-of-type'             # ✗ misinterpreted
    plwr text 'css=li:nth-of-type(2)'         # ✓ works
    plwr text 'css=:is(.card, .sidebar)'      # ✓ works
    plwr text 'css=[data-id=\"login\"]'         # ✓ quoted attrs

  The css= prefix is needed for: :last-of-type, :first-of-type,
  :nth-of-type(), :nth-last-child(), :is(), :where(),
  and quoted attribute values [attr=\"val\"].

  These work without the prefix: :nth-child(), :first-child,
  :last-child, :not(), :has(), :empty, :checked, :disabled,
  :enabled, :required, :visible, :has-text().

\x1b[1;4mEnvironment variables:\x1b[0m

  PLAYWRIGHT_HEADED        Show browser window (set to any value)
  PLWR_SESSION             Default session name (default: \"default\")
  PLWR_TIMEOUT             Default timeout in ms (default: 5000)
  PLWR_IGNORE_CERT_ERRORS  Ignore TLS/SSL certificate errors
  PLWR_CDP                 Chrome channel for CDP connection (stable, beta, canary, dev)";

#[derive(Subcommand)]
enum Cmd {
    /// Start the browser session
    Start {
        /// Show the browser window
        #[arg(long)]
        headed: bool,
        /// Record video of the session, saved to this path on stop (.webm, .mp4, etc.)
        #[arg(long)]
        video: Option<String>,
        /// Ignore TLS/SSL certificate errors (useful behind corporate proxies)
        #[arg(long)]
        ignore_cert_errors: bool,
        /// Connect to your running Chrome via CDP.
        /// Value is a channel name, user-data-dir path, or ws:// URL.
        /// Channels: stable (default), beta, canary, dev.
        /// Path: reads DevToolsActivePort from the given directory.
        /// Enable in Chrome: chrome://inspect/#remote-debugging
        #[arg(long, env = "PLWR_CDP", num_args = 0..=1, default_missing_value = "stable")]
        cdp: Option<String>,
    },
    /// Stop the browser
    Stop,

    /// Navigate to a URL
    Open { url: String },
    /// Reload the current page
    Reload,
    /// Print the current page URL
    Url,

    /// Wait for a CSS selector to appear
    Wait { selector: String },
    /// Wait for a CSS selector to disappear
    WaitNot { selector: String },
    /// Wait for any of several selectors to appear, print the first match
    WaitAny {
        #[arg(required = true)]
        selectors: Vec<String>,
    },
    /// Wait for all selectors to appear
    WaitAll {
        #[arg(required = true)]
        selectors: Vec<String>,
    },

    /// Click an element matching a CSS selector
    Click {
        selector: String,
        /// Right-click instead of left-click
        #[arg(long)]
        right: bool,
        /// Middle-click instead of left-click
        #[arg(long)]
        middle: bool,
        /// Hold Alt during click
        #[arg(long)]
        alt: bool,
        /// Hold Control during click
        #[arg(long, alias = "ctrl")]
        control: bool,
        /// Hold Meta (Cmd on macOS) during click
        #[arg(long)]
        meta: bool,
        /// Hold Shift during click
        #[arg(long)]
        shift: bool,
    },
    /// Fill text into an input matching a CSS selector
    Fill { selector: String, text: String },

    /// Press a keyboard key or chord (e.g. Enter, Escape, Control+c)
    Press { key: String },

    /// Type text by sending individual key events for each character
    Type {
        text: String,
        /// Delay between keystrokes in milliseconds
        #[arg(long)]
        delay: Option<f64>,
    },

    /// Exit 0 if selector exists, exit 1 if not (for && chaining)
    Exists { selector: String },

    /// Print the textContent of the first matching element
    Text { selector: String },
    /// Print the value of an attribute on the first matching element
    Attr { selector: String, name: String },

    /// Print the number of elements matching a CSS selector
    Count { selector: String },

    /// Set a cookie (use --list to show all, --clear to remove all)
    Cookie {
        /// Cookie name (omit for --list or --clear)
        name: Option<String>,
        /// Cookie value
        value: Option<String>,
        /// URL the cookie applies to (defaults to current page URL)
        #[arg(long)]
        url: Option<String>,
        /// List all cookies as JSON
        #[arg(long)]
        list: bool,
        /// Clear all cookies
        #[arg(long)]
        clear: bool,
    },

    /// Set the browser viewport size
    Viewport {
        /// Width in pixels
        width: u32,
        /// Height in pixels
        height: u32,
    },

    /// Set an extra HTTP header sent with every request (use --clear to remove all)
    Header {
        /// Header name (omit to clear all headers)
        name: Option<String>,
        /// Header value
        value: Option<String>,
        /// Clear all extra headers
        #[arg(long)]
        clear: bool,
    },

    /// Set files on a file input element (e.g. for upload)
    InputFiles {
        /// CSS selector for the file input
        selector: String,
        /// File paths to set (omit to clear)
        #[arg(trailing_var_arg = true)]
        paths: Vec<String>,
    },

    /// Select option(s) in a <select> element by value
    Select {
        /// CSS selector for the <select> element
        selector: String,
        /// Option values to select
        #[arg(required = true)]
        values: Vec<String>,
        /// Match by visible label text instead of value attribute
        #[arg(long)]
        label: bool,
    },

    /// Hover over an element matching a CSS selector
    Hover { selector: String },

    /// Check a checkbox or radio button
    Check { selector: String },
    /// Uncheck a checkbox
    Uncheck { selector: String },

    /// Double-click an element matching a CSS selector
    Dblclick {
        selector: String,
        /// Right double-click instead of left
        #[arg(long)]
        right: bool,
        /// Middle double-click instead of left
        #[arg(long)]
        middle: bool,
        /// Hold Alt during double-click
        #[arg(long)]
        alt: bool,
        /// Hold Control during double-click
        #[arg(long, alias = "ctrl")]
        control: bool,
        /// Hold Meta (Cmd on macOS) during double-click
        #[arg(long)]
        meta: bool,
        /// Hold Shift during double-click
        #[arg(long)]
        shift: bool,
    },

    /// Focus an element matching a CSS selector
    Focus { selector: String },
    /// Blur (unfocus) an element matching a CSS selector
    Blur { selector: String },

    /// Print the innerHTML of the first matching element
    InnerHtml { selector: String },

    /// Print the value of an input, textarea, or select element
    InputValue { selector: String },

    /// Scroll an element into view
    Scroll { selector: String },

    /// Copy content from an element to the browser clipboard (text or images)
    ClipboardCopy { selector: String },

    /// Paste from the browser clipboard at the currently focused element
    ClipboardPaste,

    /// Print computed CSS styles for an element (all styles if no properties given)
    ComputedStyle {
        /// CSS selector for the element
        selector: String,
        /// CSS properties to retrieve (e.g. display flex-direction); omit for all
        #[arg(trailing_var_arg = true)]
        properties: Vec<String>,
    },

    /// Pre-register a one-shot handler for the next browser dialog (alert/confirm/prompt).
    ///
    /// Must be called BEFORE the action that triggers the dialog
    /// (e.g. before `plwr click`), because dialogs block execution.
    ///
    /// Examples:
    ///   plwr next-dialog accept           # click OK on alert/confirm
    ///   plwr next-dialog dismiss           # click Cancel on confirm
    ///   plwr next-dialog accept 'Alice'    # type into prompt, then OK
    NextDialog {
        /// "accept" (click OK) or "dismiss" (click Cancel)
        action: String,
        /// Text to enter in a prompt() dialog before accepting (ignored for alert/confirm)
        text: Option<String>,
    },

    /// Print captured browser console logs as JSON (automatically captured after open)
    Console {
        /// Clear the console log buffer
        #[arg(long)]
        clear: bool,
    },

    /// Print captured network requests as JSON (automatically captured after open)
    Network {
        /// Clear the network log buffer
        #[arg(long)]
        clear: bool,
        /// Filter by request type (comma-separated: doc,css,js,img,font,media,manifest,ws,wasm,fetch,xhr,other)
        #[arg(long, value_delimiter = ',')]
        r#type: Vec<String>,
        /// Filter by URL (regex pattern)
        #[arg(long)]
        url: Option<String>,
        /// Include WebSocket message log (send/recv with data and timestamps)
        #[arg(long)]
        include_ws_messages: bool,
    },

    /// Evaluate arbitrary JavaScript in page context, print the result
    Eval { js: String },

    /// Take a screenshot (optionally of a specific element)
    Screenshot {
        #[arg(long)]
        selector: Option<String>,
        #[arg(long, default_value = "screenshot.png")]
        path: String,
    },

    /// Dump the DOM tree as JSON (optionally rooted at a selector)
    Tree {
        /// CSS selector to use as root
        selector: Option<String>,
    },

    /// Internal: run the browser daemon (not for direct use)
    #[command(hide = true)]
    Daemon,
}

fn find_subcommand_in_args() -> Option<String> {
    let cmd = Cli::command();
    let names: HashSet<String> = cmd
        .get_subcommands()
        .flat_map(|s| {
            let mut names = vec![s.get_name().to_string()];
            names.extend(s.get_all_aliases().map(String::from));
            names
        })
        .collect();
    std::env::args().skip(1).find(|a| names.contains(a))
}

fn socket_path(session: &str) -> PathBuf {
    let dir = dirs::cache_dir()
        .unwrap_or_else(|| PathBuf::from("/tmp"))
        .join("plwr");
    std::fs::create_dir_all(&dir).ok();
    dir.join(format!("{}.sock", session))
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(e) => {
            match e.kind() {
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
                    e.exit()
                }
                _ => {
                    // Print clap's error line, then the full subcommand help
                    // so the user can see all available options.
                    let rendered = e.render().ansi().to_string();
                    // The "Usage:" heading has ANSI bold+underline codes around it,
                    // so find the raw escape sequence that starts the Usage block.
                    let msg = if let Some(idx) = rendered.find("Usage:") {
                        // Back up to the newline before the ANSI codes preceding "Usage:"
                        let before = &rendered[..idx];
                        let cut = before.rfind('\n').unwrap_or(idx);
                        rendered[..cut].trim_end()
                    } else {
                        rendered.trim_end()
                    };
                    eprintln!("{}\n", msg);
                    if let Some(name) = find_subcommand_in_args() {
                        let mut cmd = Cli::command();
                        if let Some(sub) = cmd.find_subcommand_mut(&name) {
                            let mut sub = sub
                                .clone()
                                .bin_name(format!("plwr {}", name))
                                .help_template("{usage-heading} {usage}\n\n{all-args}");
                            sub.print_help().ok();
                        }
                    }
                    return ExitCode::FAILURE;
                }
            }
        }
    };
    let sock = socket_path(&cli.session);

    match cli.command {
        Cmd::Daemon => {
            let headed = std::env::var("PLAYWRIGHT_HEADED").is_ok_and(|v| !v.is_empty());
            let ignore_cert_errors =
                std::env::var("PLWR_IGNORE_CERT_ERRORS").is_ok_and(|v| !v.is_empty());
            match daemon::run(&sock, headed, ignore_cert_errors).await {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    std::fs::remove_file(&sock).ok();
                    eprintln!("{}", e);
                    ExitCode::FAILURE
                }
            }
        }

        Cmd::Start {
            headed,
            video,
            ignore_cert_errors,
            cdp,
        } => {
            let headed = headed || std::env::var("PLAYWRIGHT_HEADED").is_ok_and(|v| !v.is_empty());
            if cdp.is_some() && headed {
                eprintln!(
                    "--cdp and --headed are mutually exclusive (the browser is already visible)"
                );
                return ExitCode::FAILURE;
            }
            if cdp.is_some() && video.is_some() {
                eprintln!("--cdp and --video are mutually exclusive (video recording requires a launched browser)");
                return ExitCode::FAILURE;
            }
            let ignore_cert_errors = ignore_cert_errors
                || std::env::var("PLWR_IGNORE_CERT_ERRORS").is_ok_and(|v| !v.is_empty());
            match client::ensure_started(
                &sock,
                headed,
                video.as_deref(),
                ignore_cert_errors,
                cdp.as_deref(),
            )
            .await
            {
                Ok(()) => {
                    println!("Started session '{}'", cli.session);
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("{}", e);
                    ExitCode::FAILURE
                }
            }
        }

        Cmd::Stop => match client::send_if_running(&sock, Command::Stop).await {
            Ok(Some(_)) => {
                println!("Stopped session '{}'", cli.session);
                ExitCode::SUCCESS
            }
            Ok(None) => {
                println!("No session '{}' running", cli.session);
                ExitCode::SUCCESS
            }
            Err(e) => {
                eprintln!("{}", e);
                ExitCode::FAILURE
            }
        },

        cmd => {
            let command = match cmd {
                Cmd::Daemon | Cmd::Stop | Cmd::Start { .. } => unreachable!(),
                Cmd::Open { url } => Command::Open {
                    url,
                    timeout: cli.timeout,
                },
                Cmd::Reload => Command::Reload,
                Cmd::Url => Command::Url,
                Cmd::Wait { selector } => Command::Wait {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::WaitNot { selector } => Command::WaitNot {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::WaitAny { selectors } => Command::WaitAny {
                    selectors,
                    timeout: cli.timeout,
                },
                Cmd::WaitAll { selectors } => Command::WaitAll {
                    selectors,
                    timeout: cli.timeout,
                },
                Cmd::Click {
                    selector,
                    right,
                    middle,
                    alt,
                    control,
                    meta,
                    shift,
                } => {
                    let mut modifiers = Vec::new();
                    if alt {
                        modifiers.push("Alt".to_string());
                    }
                    if control {
                        modifiers.push("Control".to_string());
                    }
                    if meta {
                        modifiers.push("Meta".to_string());
                    }
                    if shift {
                        modifiers.push("Shift".to_string());
                    }
                    let button = if right {
                        Some("right".to_string())
                    } else if middle {
                        Some("middle".to_string())
                    } else {
                        None
                    };
                    Command::Click {
                        selector,
                        timeout: cli.timeout,
                        modifiers,
                        button,
                    }
                }
                Cmd::Fill { selector, text } => Command::Fill {
                    selector,
                    text,
                    timeout: cli.timeout,
                },
                Cmd::Press { key } => Command::Press { key },
                Cmd::Type { text, delay } => Command::Type { text, delay },
                Cmd::Exists { selector } => Command::Exists { selector },
                Cmd::Cookie { list: true, .. } => Command::CookieList,
                Cmd::Cookie { clear: true, .. } => Command::CookieClear,
                Cmd::Cookie {
                    name: Some(name),
                    value: Some(value),
                    url,
                    ..
                } => {
                    let url = url.unwrap_or_default();
                    Command::Cookie { name, value, url }
                }
                Cmd::Cookie {
                    name: Some(name),
                    value: None,
                    ..
                } => {
                    eprintln!("Usage: plwr cookie <name> <value> [--url <url>], plwr cookie --list, or plwr cookie --clear");
                    eprintln!("Missing value for cookie '{}'", name);
                    return ExitCode::FAILURE;
                }
                Cmd::Cookie { .. } => {
                    eprintln!("Usage: plwr cookie <name> <value> [--url <url>], plwr cookie --list, or plwr cookie --clear");
                    return ExitCode::FAILURE;
                }
                Cmd::Viewport { width, height } => Command::Viewport { width, height },
                Cmd::Header { clear: true, .. } => Command::HeaderClear,
                Cmd::Header {
                    name: Some(name),
                    value: Some(value),
                    ..
                } => Command::Header { name, value },
                Cmd::Header {
                    name: Some(name),
                    value: None,
                    ..
                } => {
                    eprintln!("Usage: plwr header <name> <value> or plwr header --clear");
                    eprintln!("Missing value for header '{}'", name);
                    return ExitCode::FAILURE;
                }
                Cmd::Header { name: None, .. } => {
                    eprintln!("Usage: plwr header <name> <value> or plwr header --clear");
                    return ExitCode::FAILURE;
                }
                Cmd::Text { selector } => Command::Text {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Attr { selector, name } => Command::Attr {
                    selector,
                    name,
                    timeout: cli.timeout,
                },
                Cmd::Count { selector } => Command::Count { selector },
                Cmd::InputFiles { selector, paths } => Command::InputFiles {
                    selector,
                    paths,
                    timeout: cli.timeout,
                },
                Cmd::Select {
                    selector,
                    values,
                    label,
                } => Command::Select {
                    selector,
                    values,
                    by_label: label,
                    timeout: cli.timeout,
                },
                Cmd::Hover { selector } => Command::Hover {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Check { selector } => Command::Check {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Uncheck { selector } => Command::Uncheck {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Dblclick {
                    selector,
                    right,
                    middle,
                    alt,
                    control,
                    meta,
                    shift,
                } => {
                    let mut modifiers = Vec::new();
                    if alt {
                        modifiers.push("Alt".to_string());
                    }
                    if control {
                        modifiers.push("Control".to_string());
                    }
                    if meta {
                        modifiers.push("Meta".to_string());
                    }
                    if shift {
                        modifiers.push("Shift".to_string());
                    }
                    let button = if right {
                        Some("right".to_string())
                    } else if middle {
                        Some("middle".to_string())
                    } else {
                        None
                    };
                    Command::Dblclick {
                        selector,
                        timeout: cli.timeout,
                        modifiers,
                        button,
                    }
                }
                Cmd::Focus { selector } => Command::Focus {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Blur { selector } => Command::Blur {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::InnerHtml { selector } => Command::InnerHtml {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::InputValue { selector } => Command::InputValue {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::Scroll { selector } => Command::ScrollIntoView {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::NextDialog { action, text } => match action.as_str() {
                    "accept" => Command::DialogAccept { prompt_text: text },
                    "dismiss" => Command::DialogDismiss,
                    other => {
                        eprintln!(
                            "Unknown dialog action '{}'. Use 'accept' or 'dismiss'.",
                            other
                        );
                        return ExitCode::FAILURE;
                    }
                },
                Cmd::Console { clear: true } => Command::ConsoleClear,
                Cmd::Console { clear: false } => Command::Console,
                Cmd::Network { clear: true, .. } => Command::NetworkClear,
                Cmd::Network {
                    clear: false,
                    r#type,
                    url,
                    include_ws_messages,
                } => Command::Network {
                    types: r#type,
                    url_pattern: url,
                    include_ws_messages,
                },
                Cmd::ClipboardCopy { selector } => Command::ClipboardCopy {
                    selector,
                    timeout: cli.timeout,
                },
                Cmd::ClipboardPaste => Command::ClipboardPaste,
                Cmd::ComputedStyle {
                    selector,
                    properties,
                } => Command::ComputedStyle {
                    selector,
                    properties,
                    timeout: cli.timeout,
                },
                Cmd::Eval { js } => Command::Eval { js },
                Cmd::Screenshot { selector, path } => Command::Screenshot {
                    selector,
                    path,
                    timeout: cli.timeout,
                },
                Cmd::Tree { selector } => Command::Tree {
                    selector,
                    timeout: cli.timeout,
                },
            };

            match client::send(&sock, command).await {
                Ok(resp) => {
                    if resp.ok {
                        if let Some(value) = resp.value {
                            match value {
                                serde_json::Value::String(s) => println!("{}", s),
                                serde_json::Value::Bool(b) => {
                                    if !b {
                                        return ExitCode::FAILURE;
                                    }
                                }
                                serde_json::Value::Null => {}
                                other => {
                                    println!("{}", serde_json::to_string_pretty(&other).unwrap())
                                }
                            }
                        }
                        ExitCode::SUCCESS
                    } else {
                        eprintln!("{}", resp.error.unwrap_or_else(|| "Unknown error".into()));
                        ExitCode::FAILURE
                    }
                }
                Err(e) => {
                    eprintln!("{}", e);
                    ExitCode::FAILURE
                }
            }
        }
    }
}