Skip to main content

agent_first_http/cli/cmd/
cdp.rs

1//! `afhttp cdp` subcommand. Raw CDP method invocation.
2
3use serde::Serialize;
4
5use crate::cli::connect::Connection;
6use crate::cli::output;
7use crate::shared::error::{Error, ErrorCode};
8use crate::shared::ids::TabId;
9use crate::shared::time::parse_duration;
10
11#[derive(Serialize)]
12struct CdpResult {
13    result: serde_json::Value,
14}
15
16#[derive(Debug)]
17pub struct Args {
18    pub method: String,
19    pub connection: Connection,
20    pub tab: String,
21    pub params: Option<String>,
22    pub wait: Option<String>,
23}
24
25pub async fn run(args: Args) -> Result<(), Error> {
26    let client = args.connection.client().await?;
27    let params = if let Some(raw) = args.params {
28        if raw == "@-" {
29            use std::io::Read;
30            let mut buf = String::new();
31            std::io::stdin()
32                .read_to_string(&mut buf)
33                .map_err(|e| Error::new(ErrorCode::IoError, format!("read stdin: {e}")))?;
34            serde_json::from_str(&buf).map_err(|e| {
35                Error::new(
36                    ErrorCode::InvalidArgument,
37                    format!("--params @-: invalid JSON: {e}"),
38                )
39            })?
40        } else {
41            serde_json::from_str(&raw).map_err(|e| {
42                Error::new(
43                    ErrorCode::InvalidArgument,
44                    format!("--params: invalid JSON: {e}"),
45                )
46            })?
47        }
48    } else {
49        serde_json::Value::Object(Default::default())
50    };
51    let mut req = client
52        .cdp(args.method)
53        .tab(TabId::new(args.tab))
54        .params(params);
55    if let Some(spec) = args.wait {
56        let (ev, timeout) = spec.rsplit_once(':').ok_or_else(|| {
57            Error::new(
58                ErrorCode::InvalidArgument,
59                "--wait-event: expected <event>:<timeout>",
60            )
61        })?;
62        let d = parse_duration(timeout)?;
63        req = req.wait_for(ev, d);
64    }
65    let value = req.send().await?;
66    output::emit("cdp", &CdpResult { result: value })
67}