eoka 0.16.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
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
//! Error types for eoka

use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;

pub(crate) mod classify;
mod code;
pub use code::ErrorCode;

/// Result type for eoka operations
pub type Result<T> = std::result::Result<T, Error>;

/// Error type for eoka: a stable [`ErrorCode`], a message and a
/// [`Detail`] with structured context.
///
/// Branch on [`Error::code`]. [`Error::receipt`] and [`Error::cause`]
/// expose an action failure's evidence and underlying error, and
/// [`Error::cdp_context`] the method and code of a Chrome protocol error.
#[derive(Debug, Clone)]
pub struct Error {
    code: ErrorCode,
    message: String,
    detail: Detail,
    source: Option<Arc<dyn StdError + Send + Sync>>,
}

/// Structured context of an [`Error`], beyond its code and message.
///
/// `#[non_exhaustive]`: match with a `_ =>` arm.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Detail {
    /// No further context.
    None,
    /// A `cdp_error`: a Chrome protocol error, a page JavaScript exception
    /// or an eoka-internal invariant. `method`/`code` carry command context
    /// when the error came from a command response, and are `None` otherwise.
    Cdp {
        /// CDP command method that failed, if known.
        method: Option<String>,
        /// CDP error code, if known.
        code: Option<i64>,
    },
    /// A failed high-level action, including whether its effect is uncertain.
    Action {
        /// Dispatch and verification evidence retained on failure.
        receipt: Box<crate::ActionReceipt>,
        /// Underlying cause of the failure.
        cause: Box<Error>,
    },
    /// An element was not found, or exists in the DOM but is not rendered.
    /// [`Error::message`] is the full text; the selector lives here.
    Element {
        /// Selector or description of the element.
        selector: String,
    },
    /// A form control settled on a different value than requested, for
    /// example because of a mask, `maxlength` or trimming. Values are not
    /// included: they may be passwords. Only their lengths are.
    ValueMismatch {
        /// Description of the filled control.
        selector: String,
        /// Character count of the requested value.
        expected_chars: usize,
        /// Character count of the value read back from the DOM.
        actual_chars: usize,
    },
    /// A checked JavaScript result exceeded its UTF-8 JSON byte limit.
    TooLarge {
        /// Maximum encoded result size accepted by the caller.
        maximum_bytes: usize,
    },
    /// Every attempt of a retried operation failed.
    RetryExhausted {
        /// Number of attempts made before giving up.
        attempts: u32,
        /// The last error encountered.
        last: Box<Error>,
    },
    /// Binary patching failed.
    Patching {
        /// Patching operation that failed.
        operation: String,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = &self.message;
        match &self.detail {
            Detail::Action { cause, .. } => write!(f, "Action {}: {cause}", self.code),
            Detail::Cdp { method, code } => match (method, code) {
                (Some(m), Some(c)) => write!(f, "CDP error in {m}: {message} (code {c})"),
                (Some(m), None) => write!(f, "CDP error in {m}: {message}"),
                _ => write!(f, "CDP error: {message}"),
            },
            Detail::Element { .. } => f.write_str(message),
            Detail::ValueMismatch {
                selector,
                expected_chars,
                actual_chars,
            } => write!(
                f,
                "Value mismatch for {selector}: the control holds {actual_chars} characters after filling {expected_chars}"
            ),
            Detail::TooLarge { maximum_bytes } => write!(
                f,
                "Evaluation result exceeds its JSON byte limit of {maximum_bytes}"
            ),
            Detail::RetryExhausted { attempts, last } => {
                write!(f, "Retry exhausted after {attempts} attempts: {last}")
            }
            Detail::Patching { operation } => {
                write!(f, "Patching error in {operation}: {message}")
            }
            Detail::None => match self.code {
                ErrorCode::Transport => match &self.source {
                    Some(source) => write!(f, "Transport error: {message}: {source}"),
                    None => write!(f, "Transport error: {message}"),
                },
                ErrorCode::Serialization => write!(f, "Serialization error: {message}"),
                ErrorCode::Io => write!(f, "IO error: {message}"),
                ErrorCode::InvalidUrl => write!(f, "Invalid URL: {message}"),
                ErrorCode::ChromeNotFound => f.write_str("Chrome not found"),
                code => write!(f, "{code}: {message}"),
            },
        }
    }
}

impl StdError for Error {
    /// The action or retry's inner error, else the io or serde error.
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match &self.detail {
            Detail::Action { cause, .. } => Some(cause.as_ref()),
            Detail::RetryExhausted { last, .. } => Some(last.as_ref()),
            _ => self
                .source
                .as_deref()
                .map(|source| source as &(dyn StdError + 'static)),
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Self::new(ErrorCode::Io, error.to_string(), Detail::None).with_source(error)
    }
}

impl From<serde_json::Error> for Error {
    fn from(error: serde_json::Error) -> Self {
        Self::new(ErrorCode::Serialization, error.to_string(), Detail::None).with_source(error)
    }
}

impl Error {
    fn new(code: ErrorCode, message: impl Into<String>, detail: Detail) -> Self {
        Self {
            code,
            message: message.into(),
            detail,
            source: None,
        }
    }

    fn with_source(mut self, source: impl StdError + Send + Sync + 'static) -> Self {
        self.source = Some(Arc::new(source));
        self
    }

    /// Decode a CDP JavaScript exception without exposing protocol implementation types.
    pub fn javascript_exception(details: &serde_json::Value) -> Self {
        match serde_json::from_value::<crate::cdp::types::ExceptionDetails>(details.clone()) {
            Ok(details) => Self::cdp_msg(details.message()),
            Err(_) => Self::cdp_msg("JavaScript exception details unavailable"),
        }
    }

    /// Create an [`ErrorCode::Transport`] error with context.
    pub fn transport(context: impl Into<String>) -> Self {
        Self::coded(ErrorCode::Transport, context)
    }

    /// Create an [`ErrorCode::Transport`] error with an IO source.
    pub fn transport_io(context: impl Into<String>, source: std::io::Error) -> Self {
        Self::transport(context).with_source(source)
    }

    /// Create a CDP error with full command context.
    pub fn cdp(method: impl Into<String>, code: i64, message: impl Into<String>) -> Self {
        Self::cdp_parts(Some(method.into()), Some(code), message)
    }

    /// Create a `cdp_error` without command context: a page JavaScript
    /// exception or an eoka-internal invariant.
    pub fn cdp_msg(message: impl Into<String>) -> Self {
        Self::cdp_parts(None, None, message)
    }

    pub(crate) fn cdp_parts(
        method: Option<String>,
        code: Option<i64>,
        message: impl Into<String>,
    ) -> Self {
        Self::new(ErrorCode::CdpError, message, Detail::Cdp { method, code })
    }

    /// Names the command of a CDP reply error, which Chrome sends without
    /// it. Other errors, and replies that already name one, are unchanged.
    pub(crate) fn with_cdp_method(mut self, command: &str) -> Self {
        if let Detail::Cdp {
            method: method @ None,
            code: Some(_),
        } = &mut self.detail
        {
            *method = Some(command.to_owned());
        }
        self
    }

    /// Create an error eoka raised itself, with a stable code. It displays
    /// as `"{code}: {message}"`, except that `transport`, `serialization`,
    /// `io`, `invalid_url` and `chrome_not_found` keep their fixed wording.
    pub fn coded(code: ErrorCode, message: impl Into<String>) -> Self {
        Self::new(code, message, Detail::None)
    }

    /// Create an [`ErrorCode::Timeout`] error. This and [`Error::launch`] are
    /// shortcuts for the codes callers commonly raise; use [`Error::coded`]
    /// for any other code.
    pub fn timeout(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::Timeout, message)
    }

    /// Create an [`ErrorCode::LaunchFailed`] error.
    pub fn launch(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::LaunchFailed, message)
    }

    pub(crate) fn navigation(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::NavigationFailed, message)
    }

    pub(crate) fn invalid_argument(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::InvalidArgument, message)
    }

    pub(crate) fn decode(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::DecodeFailed, message)
    }

    pub(crate) fn input_state(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::InputState, message)
    }

    /// Create an [`ErrorCode::ElementNotFound`] error.
    pub fn element_not_found(selector: impl Into<String>) -> Self {
        let selector = selector.into();
        Self::new(
            ErrorCode::ElementNotFound,
            format!("Element not found: {selector}"),
            Detail::Element { selector },
        )
    }

    /// Create an [`ErrorCode::ElementNotVisible`] error: the element exists
    /// in the DOM but is not rendered.
    pub fn element_not_visible(selector: impl Into<String>) -> Self {
        let selector = selector.into();
        Self::new(
            ErrorCode::ElementNotVisible,
            format!(
                "Element not visible: '{selector}' exists in DOM but is not rendered (hidden, display:none, or off-screen)"
            ),
            Detail::Element { selector },
        )
    }

    /// Create an [`ErrorCode::InvalidUrl`] error. The message should omit the
    /// URL, which may hold secrets.
    pub fn invalid_url(message: impl Into<String>) -> Self {
        Self::coded(ErrorCode::InvalidUrl, message)
    }

    /// Create an [`ErrorCode::ValueMismatch`] error from character counts,
    /// never the values.
    pub fn value_mismatch(
        selector: impl Into<String>,
        expected_chars: usize,
        actual_chars: usize,
    ) -> Self {
        let selector = selector.into();
        Self::new(
            ErrorCode::ValueMismatch,
            format!("the control holds {actual_chars} characters after filling {expected_chars}"),
            Detail::ValueMismatch {
                selector,
                expected_chars,
                actual_chars,
            },
        )
    }

    /// Create an [`ErrorCode::ResultTooLarge`] error for a JavaScript result
    /// over its UTF-8 JSON byte limit.
    pub fn too_large(maximum_bytes: usize) -> Self {
        Self::new(
            ErrorCode::ResultTooLarge,
            format!("result exceeds its JSON byte limit of {maximum_bytes}"),
            Detail::TooLarge { maximum_bytes },
        )
    }

    /// Create an [`ErrorCode::RetryExhausted`] error around the last failure.
    pub fn retry_exhausted(attempts: u32, last: Error) -> Self {
        Self::new(
            ErrorCode::RetryExhausted,
            String::new(),
            Detail::RetryExhausted {
                attempts,
                last: Box::new(last),
            },
        )
    }

    /// Create a failed-action error with its receipt and underlying cause.
    pub fn action(code: ErrorCode, receipt: crate::ActionReceipt, cause: Error) -> Self {
        Self::new(
            code,
            String::new(),
            Detail::Action {
                receipt: Box::new(receipt),
                cause: Box::new(cause),
            },
        )
    }

    /// Create an [`ErrorCode::ChromeNotFound`] error.
    pub fn chrome_not_found() -> Self {
        Self::coded(ErrorCode::ChromeNotFound, "Chrome not found")
    }

    /// Create an [`ErrorCode::Patching`] error.
    pub fn patching(operation: impl Into<String>, message: impl Into<String>) -> Self {
        Self::new(
            ErrorCode::Patching,
            message,
            Detail::Patching {
                operation: operation.into(),
            },
        )
    }

    /// The stable code of this error.
    pub fn code(&self) -> ErrorCode {
        self.code
    }

    /// The message as raised: a coded error's text, Chrome's CDP message or
    /// a transport error's context, which `Display` prefixes with the code or
    /// a fixed wording. An element error's message is its full text (the
    /// selector is in [`Detail::Element`]); `value_mismatch` and
    /// `result_too_large` carry a fixed phrase. An action or exhausted retry
    /// returns its cause's message.
    pub fn message(&self) -> &str {
        match &self.detail {
            Detail::Action { cause, .. } => cause.message(),
            Detail::RetryExhausted { last, .. } => last.message(),
            _ => &self.message,
        }
    }

    /// Structured context beyond the code and message.
    pub fn detail(&self) -> &Detail {
        &self.detail
    }

    /// The receipt of a failed action.
    pub fn receipt(&self) -> Option<&crate::ActionReceipt> {
        match &self.detail {
            Detail::Action { receipt, .. } => Some(receipt),
            _ => None,
        }
    }

    /// The error inside a failed action, or the last error of an exhausted
    /// retry.
    pub fn cause(&self) -> Option<&Error> {
        match &self.detail {
            Detail::Action { cause, .. } => Some(cause),
            Detail::RetryExhausted { last, .. } => Some(last),
            _ => None,
        }
    }

    /// The method and CDP code of a `cdp_error`, each when known.
    pub fn cdp_context(&self) -> Option<(Option<&str>, Option<i64>)> {
        match &self.detail {
            Detail::Cdp { method, code } => Some((method.as_deref(), *code)),
            _ => None,
        }
    }

    /// Whether retrying the same call unchanged can succeed.
    ///
    /// Follows [`ErrorCode::is_transient`]: usage errors (invalid URLs,
    /// arguments or options, serialization, oversized results, a missing
    /// Chrome, invalid held-input state) are permanent. An action error is
    /// transient only when no input was sent and its code is transient, so a
    /// retry never repeats input that may have landed.
    pub fn is_retryable(&self) -> bool {
        match &self.detail {
            Detail::Action { receipt, .. } => {
                receipt.dispatch == crate::DispatchState::NotSent && self.code.is_transient()
            }
            _ => self.code.is_transient(),
        }
    }
}

#[cfg(test)]
mod tests;