chromiumoxide/
js.rs

1use serde::de::DeserializeOwned;
2
3use chromiumoxide_cdp::cdp::js_protocol::runtime::{
4    CallFunctionOnParams, EvaluateParams, RemoteObject,
5};
6
7use crate::utils::is_likely_js_function;
8
9#[derive(Debug, Clone)]
10pub struct EvaluationResult {
11    /// Mirror object referencing original JavaScript object
12    inner: RemoteObject,
13}
14
15impl EvaluationResult {
16    pub fn new(inner: RemoteObject) -> Self {
17        Self { inner }
18    }
19
20    pub fn object(&self) -> &RemoteObject {
21        &self.inner
22    }
23
24    pub fn value(&self) -> Option<&serde_json::Value> {
25        self.object().value.as_ref()
26    }
27
28    /// Attempts to deserialize the value into the given type
29    pub fn into_value<T: DeserializeOwned>(self) -> serde_json::Result<T> {
30        let value = self
31            .inner
32            .value
33            .ok_or_else(|| serde::de::Error::custom("No value found"))?;
34        serde_json::from_value(value)
35    }
36
37    /// Attempts to deserialize the value into as bytes.
38    pub fn into_bytes(self) -> serde_json::Result<Vec<u8>> {
39        let value = self
40            .inner
41            .value
42            .ok_or_else(|| serde::de::Error::custom("No value found"))?;
43
44        Ok(value.as_str().unwrap_or_default().into())
45    }
46}
47
48#[derive(Debug, Clone)]
49pub enum Evaluation {
50    Expression(EvaluateParams),
51    Function(CallFunctionOnParams),
52}
53
54impl From<&str> for Evaluation {
55    fn from(expression: &str) -> Self {
56        if is_likely_js_function(expression) {
57            CallFunctionOnParams::from(expression).into()
58        } else {
59            EvaluateParams::from(expression).into()
60        }
61    }
62}
63
64impl From<String> for Evaluation {
65    fn from(expression: String) -> Self {
66        expression.as_str().into()
67    }
68}
69
70impl From<EvaluateParams> for Evaluation {
71    fn from(params: EvaluateParams) -> Self {
72        Evaluation::Expression(params)
73    }
74}
75
76impl From<CallFunctionOnParams> for Evaluation {
77    fn from(params: CallFunctionOnParams) -> Self {
78        Evaluation::Function(params)
79    }
80}