zendriver 0.2.0

Async-first, undetectable browser automation via the Chrome DevTools Protocol
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
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
//! Error hierarchy for the `zendriver` crate.
//!
//! Every fallible API in zendriver returns [`Result<T>`], which is an alias
//! for `std::result::Result<T, ZendriverError>`. [`ZendriverError`] is a
//! non-exhaustive enum covering CDP transport failures, navigation /
//! element / cookie / storage operation errors, and (when the relevant
//! cargo feature is enabled) wrappers around the sub-crate error types.

use std::path::PathBuf;
use std::time::Duration;

use zendriver_transport::CallError;

/// Top-level error type returned by every fallible API in this crate.
///
/// `#[non_exhaustive]` — new variants may be added in minor releases.
/// Pattern-match defensively (use a `_` arm).
///
/// # Examples
///
/// ```
/// # use zendriver::ZendriverError;
/// # use std::time::Duration;
/// let e = ZendriverError::Timeout(Duration::from_secs(5));
/// assert_eq!(e.to_string(), "timed out after 5s");
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ZendriverError {
    /// Chrome process / launch failure.
    #[error("browser process failed: {0}")]
    Browser(#[from] BrowserError),

    /// Lower-level transport (WebSocket) failure.
    #[error("transport: {0}")]
    Transport(Box<zendriver_transport::TransportError>),

    /// The connection to Chrome dropped unexpectedly — the WebSocket died
    /// without a caller-requested [`Browser::close`](crate::Browser::close)
    /// (Chrome crashed, the socket was severed, a Close frame arrived
    /// out-of-band). A CDP call awaiting a reply when the drop happened
    /// resolves to this, distinct from the clean-shutdown
    /// [`ZendriverError::Transport`] surfaced after `close()`.
    ///
    /// Recover with [`Browser::reconnect`](crate::Browser::reconnect) (which
    /// re-dials the live Chrome process) — but note that existing
    /// `Tab`/`Frame`/`Element` handles are invalidated by a reconnect and must
    /// be re-acquired via
    /// [`Browser::main_tab`](crate::Browser::main_tab) /
    /// [`Browser::tabs`](crate::Browser::tabs).
    #[error("connection to chrome lost unexpectedly")]
    Disconnected,

    /// Chrome returned a CDP RPC error (a method call returned `error.code` /
    /// `error.message`).
    #[error("CDP RPC error [{code}] {message}")]
    Cdp {
        /// CDP RPC error code (typically negative; see
        /// [JSON-RPC spec](https://www.jsonrpc.org/specification#error_object)).
        code: i32,
        /// Human-readable error message from Chrome.
        message: String,
        /// Optional `data` field from the RPC error payload.
        data: Option<serde_json::Value>,
    },

    /// A query selector did not match within the timeout.
    #[error("element not found: {selector}")]
    ElementNotFound {
        /// Description of the selector that failed to match (e.g.
        /// `"css(button.primary)"`, `"text_exact(Submit)"`).
        selector: String,
    },

    /// Generic operation timeout.
    #[error("timed out after {0:?}")]
    Timeout(Duration),

    /// Page navigation failed (DNS, connection refused, page crashed, etc.).
    #[error("navigation failed: {0}")]
    Navigation(String),

    /// A JS expression raised an exception during evaluation.
    #[error("javascript exception: {0}")]
    JsException(String),

    /// An element handle is stale and the auto-refresh path failed.
    #[error("element is stale: refresh failed or origin not refreshable")]
    ElementStale,

    /// An element handle obtained from raw JS evaluation cannot be refreshed
    /// (no selector to replay).
    #[error("element not refreshable (was returned from a JS evaluation)")]
    NotRefreshable,

    /// An element did not become actionable (visible + enabled + stable +
    /// hit-tested) within the gate timeout.
    #[error("element not actionable within {0:?}: {1}")]
    NotActionable(std::time::Duration, String),

    /// Frame lookup by id / url / name failed.
    #[error("frame not found: {0}")]
    FrameNotFound(String),

    /// Tab lookup by target_id / session_id failed.
    #[error("tab not found: {0}")]
    TabNotFound(String),

    /// A cookie operation failed (CDP refusal, malformed payload, etc.).
    #[error("cookie operation failed: {0}")]
    Cookie(String),

    /// A DOM storage operation failed (origin mismatch, CDP refusal, etc.).
    #[error("storage operation failed: {0}")]
    Storage(String),

    /// Session history navigation failed (no back/forward entry).
    #[error("history navigation failed: {0}")]
    HistoryNavigation(String),

    /// JSON serialization / deserialization error at the CDP boundary.
    #[error("serde: {0}")]
    Serde(#[from] serde_json::Error),

    /// I/O error (file read/write, etc.).
    #[error("io: {0}")]
    Io(#[from] std::io::Error),

    /// Stealth fingerprint resolution failed.
    #[error("stealth: {0}")]
    Stealth(Box<zendriver_stealth::StealthError>),

    /// Request-interception sub-crate error. Gated by feature `interception`.
    #[cfg(feature = "interception")]
    #[error("interception: {0}")]
    Interception(Box<zendriver_interception::InterceptionError>),

    /// Cloudflare bypass sub-crate error. Gated by feature `cloudflare`.
    #[cfg(feature = "cloudflare")]
    #[error("cloudflare: {0}")]
    Cloudflare(Box<zendriver_cloudflare::CloudflareError>),

    /// Imperva bypass sub-crate error. Gated by feature `imperva`.
    #[cfg(feature = "imperva")]
    #[error("imperva: {0}")]
    Imperva(Box<zendriver_imperva::ImpervaError>),

    /// Chrome-for-Testing fetcher error. Gated by feature `fetcher`.
    #[cfg(feature = "fetcher")]
    #[error("fetcher: {0}")]
    Fetcher(Box<zendriver_fetcher::FetcherError>),
}

impl From<zendriver_transport::TransportError> for ZendriverError {
    fn from(e: zendriver_transport::TransportError) -> Self {
        Self::Transport(Box::new(e))
    }
}

impl From<zendriver_stealth::StealthError> for ZendriverError {
    fn from(e: zendriver_stealth::StealthError) -> Self {
        Self::Stealth(Box::new(e))
    }
}

#[cfg(feature = "interception")]
impl From<zendriver_interception::InterceptionError> for ZendriverError {
    fn from(e: zendriver_interception::InterceptionError) -> Self {
        Self::Interception(Box::new(e))
    }
}

#[cfg(feature = "cloudflare")]
impl From<zendriver_cloudflare::CloudflareError> for ZendriverError {
    fn from(e: zendriver_cloudflare::CloudflareError) -> Self {
        Self::Cloudflare(Box::new(e))
    }
}

#[cfg(feature = "imperva")]
impl From<zendriver_imperva::ImpervaError> for ZendriverError {
    fn from(e: zendriver_imperva::ImpervaError) -> Self {
        Self::Imperva(Box::new(e))
    }
}

#[cfg(feature = "fetcher")]
impl From<zendriver_fetcher::FetcherError> for ZendriverError {
    fn from(e: zendriver_fetcher::FetcherError) -> Self {
        Self::Fetcher(Box::new(e))
    }
}

impl From<CallError> for ZendriverError {
    fn from(e: CallError) -> Self {
        match e {
            // An unexpected ws death drains in-flight calls with the
            // `Disconnected` transport variant; surface it as the distinct
            // top-level `Disconnected` so callers can tell a dropped
            // connection apart from a clean `close()`-driven shutdown.
            CallError::Transport(zendriver_transport::TransportError::Disconnected) => {
                ZendriverError::Disconnected
            }
            CallError::Transport(t) => ZendriverError::Transport(Box::new(t)),
            CallError::Rpc(code, message, data) => {
                // Special-case: Chrome returns -32000 "Cannot find context in
                // which to perform call" when the page navigated out from
                // under us. That's semantically a navigation failure, not a
                // raw protocol error.
                if code == -32000 && message.contains("Cannot find context") {
                    ZendriverError::Navigation(message)
                } else {
                    ZendriverError::Cdp {
                        code,
                        message,
                        data,
                    }
                }
            }
            // `CallError` is `#[non_exhaustive]`; if a new variant lands and
            // higher layers need to handle it specially, this fallback keeps
            // information by wrapping the Display in a transport-io error.
            other => ZendriverError::Io(std::io::Error::other(other.to_string())),
        }
    }
}

/// Convenience alias for `Result<T, ZendriverError>`.
///
/// All fallible APIs in this crate return this type.
pub type Result<T, E = ZendriverError> = std::result::Result<T, E>;

/// Errors specific to Chrome process discovery / spawn / WebSocket attach.
///
/// Surfaced inside [`ZendriverError::Browser`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BrowserError {
    /// No Chrome / Chromium binary found on PATH or in conventional install
    /// locations. `searched` lists every path that was probed.
    #[error("chrome executable not found; searched: {searched:?}")]
    ExecutableNotFound {
        /// Every candidate path the discovery routine probed.
        searched: Vec<PathBuf>,
    },

    /// `Command::spawn` returned an OS-level failure.
    #[error("chrome failed to start: {0}")]
    SpawnFailed(#[source] std::io::Error),

    /// Chrome exited before printing its `DevTools listening on` line —
    /// typically a profile lock, missing GPU sandbox, or invalid flag.
    #[error("chrome exited before WS endpoint became available (status: {0:?})")]
    EarlyExit(std::process::ExitStatus),

    /// Timeout waiting for the `DevTools listening on` line.
    #[error("timed out waiting for chrome WS endpoint")]
    WsTimeout,

    /// Stderr contained an unparseable DevTools URL line.
    #[error("could not parse devtools endpoint from chrome stderr")]
    DevtoolsParse,

    /// `tempfile` cleanup of the `user_data_dir` failed.
    #[error("failed to clean user_data_dir: {0}")]
    Cleanup(#[source] std::io::Error),

    /// A configured extension could not be resolved — the path is missing, is
    /// neither a directory nor a `.crx`, or a `.crx` failed to unzip.
    #[error("failed to load extension {path:?}: {reason}")]
    ExtensionLoad {
        /// The configured extension path that failed.
        path: PathBuf,
        /// Human-readable cause (missing path, bad archive, IO error, …).
        reason: String,
    },
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn display_for_element_not_found_includes_selector() {
        let e = ZendriverError::ElementNotFound {
            selector: "button.foo".into(),
        };
        assert_eq!(e.to_string(), "element not found: button.foo");
    }

    #[test]
    fn display_for_timeout_includes_duration() {
        let e = ZendriverError::Timeout(Duration::from_secs(5));
        assert_eq!(e.to_string(), "timed out after 5s");
    }

    #[test]
    fn display_for_cdp_includes_code_and_message() {
        let e = ZendriverError::Cdp {
            code: -32602,
            message: "Invalid params".into(),
            data: None,
        };
        assert_eq!(e.to_string(), "CDP RPC error [-32602] Invalid params");
    }

    #[test]
    fn display_for_executable_not_found_includes_paths() {
        let e = ZendriverError::Browser(BrowserError::ExecutableNotFound {
            searched: vec![PathBuf::from("/usr/bin/google-chrome")],
        });
        assert!(e.to_string().contains("/usr/bin/google-chrome"));
    }

    #[test]
    fn from_transport_error_works() {
        let te = zendriver_transport::TransportError::Shutdown;
        let ze: ZendriverError = te.into();
        assert!(matches!(ze, ZendriverError::Transport(_)));
        assert!(ze.to_string().contains("connection shut down"));
    }

    #[test]
    fn from_call_error_rpc_minus_32602_maps_to_cdp_variant() {
        let ce = CallError::Rpc(-32602, "Invalid params".into(), None);
        let ze: ZendriverError = ce.into();
        match ze {
            ZendriverError::Cdp {
                code,
                message,
                data,
            } => {
                assert_eq!(code, -32602);
                assert_eq!(message, "Invalid params");
                assert!(data.is_none());
            }
            other => panic!("expected Cdp, got {other:?}"),
        }
    }

    #[test]
    fn from_call_error_cannot_find_context_maps_to_navigation() {
        let ce = CallError::Rpc(-32000, "Cannot find context with specified id".into(), None);
        let ze: ZendriverError = ce.into();
        match ze {
            ZendriverError::Navigation(m) => assert!(m.contains("Cannot find context")),
            other => panic!("expected Navigation, got {other:?}"),
        }
    }

    #[test]
    fn from_call_error_transport_maps_to_transport() {
        let ce = CallError::Transport(zendriver_transport::TransportError::Shutdown);
        let ze: ZendriverError = ce.into();
        assert!(matches!(ze, ZendriverError::Transport(_)));
    }

    #[test]
    fn from_call_error_disconnected_maps_to_disconnected_not_transport() {
        // An unexpected ws death must surface as the distinct `Disconnected`
        // variant, NOT the opaque `Transport`/`Shutdown` one — that's the
        // whole point of typed disconnect.
        let ce = CallError::Transport(zendriver_transport::TransportError::Disconnected);
        let ze: ZendriverError = ce.into();
        assert!(matches!(ze, ZendriverError::Disconnected));
    }

    #[test]
    fn shutdown_and_disconnected_are_distinguishable() {
        let shutdown: ZendriverError =
            CallError::Transport(zendriver_transport::TransportError::Shutdown).into();
        let disconnected: ZendriverError =
            CallError::Transport(zendriver_transport::TransportError::Disconnected).into();
        assert!(matches!(shutdown, ZendriverError::Transport(_)));
        assert!(matches!(disconnected, ZendriverError::Disconnected));
    }

    #[test]
    fn display_disconnected_is_stable() {
        assert_eq!(
            ZendriverError::Disconnected.to_string(),
            "connection to chrome lost unexpectedly"
        );
    }

    #[test]
    fn from_stealth_error_works() {
        let se = zendriver_stealth::StealthError::ChromeVersionDetect("test".into());
        let ze: ZendriverError = se.into();
        assert!(matches!(ze, ZendriverError::Stealth(_)));
        assert!(ze.to_string().contains("test"));
    }

    #[test]
    fn display_element_stale() {
        let e = ZendriverError::ElementStale;
        assert_eq!(
            e.to_string(),
            "element is stale: refresh failed or origin not refreshable"
        );
    }

    #[test]
    fn display_not_refreshable() {
        let e = ZendriverError::NotRefreshable;
        assert_eq!(
            e.to_string(),
            "element not refreshable (was returned from a JS evaluation)"
        );
    }

    #[test]
    fn display_not_actionable_includes_duration_and_reason() {
        let e = ZendriverError::NotActionable(
            Duration::from_secs(5),
            "not visible: display: none".into(),
        );
        assert_eq!(
            e.to_string(),
            "element not actionable within 5s: not visible: display: none"
        );
    }

    #[test]
    fn display_frame_not_found() {
        let e = ZendriverError::FrameNotFound("F1".into());
        assert_eq!(e.to_string(), "frame not found: F1");
    }

    #[test]
    fn display_tab_not_found() {
        let e = ZendriverError::TabNotFound("S2".into());
        assert_eq!(e.to_string(), "tab not found: S2");
    }

    #[test]
    fn display_cookie() {
        let e = ZendriverError::Cookie("bad domain".into());
        assert_eq!(e.to_string(), "cookie operation failed: bad domain");
    }

    #[test]
    fn display_storage() {
        let e = ZendriverError::Storage("origin mismatch".into());
        assert_eq!(e.to_string(), "storage operation failed: origin mismatch");
    }

    #[test]
    fn display_history_navigation() {
        let e = ZendriverError::HistoryNavigation("no back history".into());
        assert_eq!(e.to_string(), "history navigation failed: no back history");
    }

    #[test]
    fn error_displays_snapshot() {
        let cases = vec![
            (
                "element_not_found",
                ZendriverError::ElementNotFound {
                    selector: "button.foo".into(),
                }
                .to_string(),
            ),
            (
                "timeout_5s",
                ZendriverError::Timeout(Duration::from_secs(5)).to_string(),
            ),
            (
                "cdp_invalid_params",
                ZendriverError::Cdp {
                    code: -32602,
                    message: "Invalid params".into(),
                    data: None,
                }
                .to_string(),
            ),
            (
                "navigation",
                ZendriverError::Navigation("ERR_NAME_NOT_RESOLVED".into()).to_string(),
            ),
            (
                "js_exception",
                ZendriverError::JsException("Error: boom".into()).to_string(),
            ),
        ];
        insta::assert_yaml_snapshot!("error_displays", cases);
    }
}