cdp_driver/
action_parse.rs1use serde::Deserialize;
4
5use crate::action::BrowserAction;
6use crate::error::{CdpError, Result};
7
8const DEFAULT_SELECTOR_TIMEOUT_MS: u64 = 5000;
10
11#[derive(Debug, Deserialize)]
14struct RawAction {
15 action: String,
16 url: Option<String>,
17 selector: Option<String>,
18 value: Option<String>,
19 text: Option<String>,
20 key: Option<String>,
21 path: Option<String>,
22 ms: Option<u64>,
23 x: Option<f64>,
24 y: Option<f64>,
25 expression: Option<String>,
26 width: Option<i32>,
27 height: Option<i32>,
28 mobile: Option<bool>,
29 timeout_ms: Option<u64>,
30}
31
32pub fn parse_action(json_str: &str) -> Result<BrowserAction> {
37 let a: RawAction = serde_json::from_str(json_str)?;
38
39 macro_rules! need {
40 ($field:expr, $name:literal) => {
41 $field.ok_or_else(|| CdpError::Protocol(concat!($name, " is required").into()))?
42 };
43 }
44
45 Ok(match a.action.as_str() {
46 "navigate" => BrowserAction::Navigate {
47 url: need!(a.url, "url"),
48 },
49 "back" | "go_back" => BrowserAction::GoBack,
50 "forward" | "go_forward" => BrowserAction::GoForward,
51 "reload" => BrowserAction::Reload,
52 "click" => BrowserAction::Click {
53 selector: a.selector,
54 x: a.x,
55 y: a.y,
56 },
57 "type" => BrowserAction::Type {
58 text: need!(a.text, "text"),
59 selector: a.selector,
60 },
61 "fill" => BrowserAction::Fill {
62 selector: need!(a.selector, "selector"),
63 value: need!(a.value, "value"),
64 },
65 "submit" => BrowserAction::Submit {
66 selector: a.selector,
67 },
68 "press_key" | "key" => BrowserAction::PressKey {
69 key: need!(a.key, "key"),
70 },
71 "get_title" | "title" => BrowserAction::GetTitle,
72 "get_url" | "url" => BrowserAction::GetUrl,
73 "get_text" | "text" => BrowserAction::GetText,
74 "get_content" | "content" => BrowserAction::GetContent {
75 selector: a.selector,
76 },
77 "get_links" | "links" => BrowserAction::GetLinks,
78 "get_attributes" | "attributes" => BrowserAction::GetAttributes {
79 selector: need!(a.selector, "selector"),
80 },
81 "exists" => BrowserAction::Exists {
82 selector: need!(a.selector, "selector"),
83 },
84 "screenshot" => BrowserAction::Screenshot { path: a.path },
85 "evaluate" | "eval" => BrowserAction::Evaluate {
86 expression: need!(a.expression, "expression"),
87 },
88 "wait" => BrowserAction::Wait {
89 ms: need!(a.ms, "ms"),
90 },
91 "wait_for_selector" => BrowserAction::WaitForSelector {
92 selector: need!(a.selector, "selector"),
93 timeout_ms: a.timeout_ms.unwrap_or(DEFAULT_SELECTOR_TIMEOUT_MS),
94 },
95 "scroll" => BrowserAction::Scroll {
96 x: a.x.unwrap_or(0.0),
97 y: a.y.unwrap_or(0.0),
98 },
99 "set_viewport" => BrowserAction::SetViewport {
100 width: need!(a.width, "width"),
101 height: need!(a.height, "height"),
102 mobile: a.mobile.unwrap_or(false),
103 },
104 "get_metrics" | "metrics" => BrowserAction::GetMetrics,
105 other => return Err(CdpError::Protocol(format!("unknown action: {other}"))),
106 })
107}