viewpoint-core 0.4.1

High-level browser automation API for Viewpoint
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
//! Navigation types and builder.

use std::collections::HashMap;
use std::time::Duration;

use tracing::{debug, info, instrument, trace, warn};
use viewpoint_cdp::protocol::page::{NavigateParams, NavigateResult};

use crate::error::NavigationError;
use crate::wait::{DocumentLoadState, LoadStateWaiter};

use super::{DEFAULT_NAVIGATION_TIMEOUT, Page};

/// Response from a navigation.
#[derive(Debug, Clone)]
pub struct NavigationResponse {
    /// The URL that was navigated to (final URL after redirects).
    url: String,
    /// The frame ID that navigated.
    frame_id: String,
    /// HTTP status code of the response (e.g., 200, 404, 302).
    status: Option<u16>,
    /// HTTP response headers.
    headers: Option<HashMap<String, String>>,
}

impl NavigationResponse {
    /// Create a new navigation response.
    pub(crate) fn new(url: String, frame_id: String) -> Self {
        Self {
            url,
            frame_id,
            status: None,
            headers: None,
        }
    }

    /// Create a navigation response with response data.
    pub(crate) fn with_response(
        url: String,
        frame_id: String,
        status: u16,
        headers: HashMap<String, String>,
    ) -> Self {
        Self {
            url,
            frame_id,
            status: Some(status),
            headers: Some(headers),
        }
    }

    /// Get the final URL after any redirects.
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Get the frame ID that navigated.
    pub fn frame_id(&self) -> &str {
        &self.frame_id
    }

    /// Get the HTTP status code of the final response.
    ///
    /// Returns `None` if status was not captured (e.g., for `about:blank`).
    pub fn status(&self) -> Option<u16> {
        self.status
    }

    /// Get the HTTP response headers.
    ///
    /// Returns `None` if headers were not captured.
    pub fn headers(&self) -> Option<&HashMap<String, String>> {
        self.headers.as_ref()
    }

    /// Check if the navigation resulted in an OK response (2xx status).
    pub fn ok(&self) -> bool {
        self.status.is_none_or(|s| (200..300).contains(&s))
    }
}

/// Builder for configuring page navigation.
#[derive(Debug)]
pub struct GotoBuilder<'a> {
    page: &'a Page,
    url: String,
    wait_until: DocumentLoadState,
    timeout: Duration,
    referer: Option<String>,
}

impl<'a> GotoBuilder<'a> {
    /// Create a new navigation builder.
    pub(crate) fn new(page: &'a Page, url: String) -> Self {
        Self {
            page,
            url,
            wait_until: DocumentLoadState::default(),
            timeout: DEFAULT_NAVIGATION_TIMEOUT,
            referer: None,
        }
    }

    /// Set the load state to wait for.
    ///
    /// Default is `DocumentLoadState::Load`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::DocumentLoadState;
    ///
    /// # async fn example(page: viewpoint_core::Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Wait only for DOM content loaded (faster)
    /// page.goto("https://example.com")
    ///     .wait_until(DocumentLoadState::DomContentLoaded)
    ///     .goto()
    ///     .await?;
    ///
    /// // Wait for network idle (slower but more complete)
    /// page.goto("https://example.com")
    ///     .wait_until(DocumentLoadState::NetworkIdle)
    ///     .goto()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn wait_until(mut self, state: DocumentLoadState) -> Self {
        self.wait_until = state;
        self
    }

    /// Set the navigation timeout.
    ///
    /// Default is 30 seconds.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    ///
    /// # async fn example(page: viewpoint_core::Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.goto("https://slow-site.com")
    ///     .timeout(Duration::from_secs(60))
    ///     .goto()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the referer header for the navigation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(page: viewpoint_core::Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.goto("https://example.com")
    ///     .referer("https://google.com")
    ///     .goto()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn referer(mut self, referer: impl Into<String>) -> Self {
        self.referer = Some(referer.into());
        self
    }

    /// Execute the navigation.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The page is closed
    /// - Navigation fails (network error, SSL error, etc.)
    /// - The wait times out
    #[instrument(level = "debug", skip(self), fields(url = %self.url, wait_until = ?self.wait_until, timeout_ms = self.timeout.as_millis(), has_referer = self.referer.is_some()))]
    pub async fn goto(self) -> Result<NavigationResponse, NavigationError> {
        debug!("Executing navigation via GotoBuilder");
        self.page
            .navigate_internal(
                &self.url,
                self.wait_until,
                self.timeout,
                self.referer.as_deref(),
            )
            .await
    }
}

// =============================================================================
// Navigation Internal Methods
// =============================================================================

impl Page {
    /// Navigate to a URL with the given options.
    #[instrument(level = "info", skip(self), fields(target_id = %self.target_id, url = %url, wait_until = ?wait_until, timeout_ms = timeout.as_millis()))]
    pub(crate) async fn navigate_internal(
        &self,
        url: &str,
        wait_until: DocumentLoadState,
        timeout: Duration,
        referer: Option<&str>,
    ) -> Result<NavigationResponse, NavigationError> {
        if self.closed {
            warn!("Attempted navigation on closed page");
            return Err(NavigationError::Cancelled);
        }

        info!("Starting navigation");

        // Create a load state waiter
        let event_rx = self.connection.subscribe_events();
        let mut waiter =
            LoadStateWaiter::new(event_rx, self.session_id.clone(), self.frame_id.clone());
        trace!("Created load state waiter");

        // Send the navigation command
        debug!("Sending Page.navigate command");
        let result: NavigateResult = self
            .connection
            .send_command(
                "Page.navigate",
                Some(NavigateParams {
                    url: url.to_string(),
                    referrer: referer.map(ToString::to_string),
                    transition_type: None,
                    frame_id: None,
                }),
                Some(&self.session_id),
            )
            .await?;

        debug!(frame_id = %result.frame_id, loader_id = ?result.loader_id, "Page.navigate completed");

        // Check for navigation errors
        // Note: Chrome reports HTTP error status codes (4xx, 5xx) as errors with
        // "net::ERR_HTTP_RESPONSE_CODE_FAILURE" or "net::ERR_INVALID_AUTH_CREDENTIALS".
        // Following Playwright's behavior, we treat these as successful navigations
        // that return a response with the appropriate status code.
        if let Some(ref error_text) = result.error_text {
            let is_http_error = error_text == "net::ERR_HTTP_RESPONSE_CODE_FAILURE"
                || error_text == "net::ERR_INVALID_AUTH_CREDENTIALS";

            if !is_http_error {
                warn!(error = %error_text, "Navigation failed with error");
                return Err(NavigationError::NetworkError(error_text.clone()));
            }
            debug!(error = %error_text, "HTTP error response - continuing to capture status");
        }

        // Mark commit as received
        trace!("Setting commit received");
        waiter.set_commit_received().await;

        // Wait for the target load state
        debug!(wait_until = ?wait_until, "Waiting for load state");
        waiter
            .wait_for_load_state_with_timeout(wait_until, timeout)
            .await?;

        // Get response data captured during navigation
        let response_data = waiter.response_data().await;

        info!(frame_id = %result.frame_id, "Navigation completed successfully");

        // Use the final URL from response data if available (handles redirects)
        let final_url = response_data.url.unwrap_or_else(|| url.to_string());

        // Build the response with captured data
        if let Some(status) = response_data.status {
            Ok(NavigationResponse::with_response(
                final_url,
                result.frame_id,
                status,
                response_data.headers,
            ))
        } else {
            Ok(NavigationResponse::new(final_url, result.frame_id))
        }
    }
}

// =============================================================================
// Navigation History Methods (impl extension for Page)
// =============================================================================

impl Page {
    /// Navigate back in history.
    ///
    /// Returns `None` if there is no previous page in history.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(page: viewpoint_core::Page) -> Result<(), viewpoint_core::CoreError> {
    /// if page.go_back().await?.is_some() {
    ///     println!("Navigated back");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(level = "info", skip(self))]
    pub async fn go_back(&self) -> Result<Option<NavigationResponse>, NavigationError> {
        if self.closed {
            return Err(NavigationError::Cancelled);
        }

        // Check if we can go back
        let history: viewpoint_cdp::protocol::page::GetNavigationHistoryResult = self
            .connection
            .send_command(
                "Page.getNavigationHistory",
                None::<()>,
                Some(&self.session_id),
            )
            .await?;

        if history.current_index <= 0 {
            debug!("No previous page in history");
            return Ok(None);
        }

        // Navigate to the previous entry
        let previous_entry = &history.entries[history.current_index as usize - 1];
        self.connection
            .send_command::<_, serde_json::Value>(
                "Page.navigateToHistoryEntry",
                Some(
                    viewpoint_cdp::protocol::page::NavigateToHistoryEntryParams {
                        entry_id: previous_entry.id,
                    },
                ),
                Some(&self.session_id),
            )
            .await?;

        info!("Navigated back to {}", previous_entry.url);
        Ok(Some(NavigationResponse::new(
            previous_entry.url.clone(),
            self.frame_id.clone(),
        )))
    }

    /// Navigate forward in history.
    ///
    /// Returns `None` if there is no next page in history.
    #[instrument(level = "info", skip(self))]
    pub async fn go_forward(&self) -> Result<Option<NavigationResponse>, NavigationError> {
        if self.closed {
            return Err(NavigationError::Cancelled);
        }

        // Check if we can go forward
        let history: viewpoint_cdp::protocol::page::GetNavigationHistoryResult = self
            .connection
            .send_command(
                "Page.getNavigationHistory",
                None::<()>,
                Some(&self.session_id),
            )
            .await?;

        let next_index = history.current_index as usize + 1;
        if next_index >= history.entries.len() {
            debug!("No next page in history");
            return Ok(None);
        }

        // Navigate to the next entry
        let next_entry = &history.entries[next_index];
        self.connection
            .send_command::<_, serde_json::Value>(
                "Page.navigateToHistoryEntry",
                Some(
                    viewpoint_cdp::protocol::page::NavigateToHistoryEntryParams {
                        entry_id: next_entry.id,
                    },
                ),
                Some(&self.session_id),
            )
            .await?;

        info!("Navigated forward to {}", next_entry.url);
        Ok(Some(NavigationResponse::new(
            next_entry.url.clone(),
            self.frame_id.clone(),
        )))
    }

    /// Reload the current page.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(page: viewpoint_core::Page) -> Result<(), viewpoint_core::CoreError> {
    /// page.reload().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(level = "info", skip(self))]
    pub async fn reload(&self) -> Result<NavigationResponse, NavigationError> {
        if self.closed {
            return Err(NavigationError::Cancelled);
        }

        info!("Reloading page");

        self.connection
            .send_command::<_, serde_json::Value>(
                "Page.reload",
                Some(viewpoint_cdp::protocol::page::ReloadParams::default()),
                Some(&self.session_id),
            )
            .await?;

        // Get current URL
        let url = self.url().await.unwrap_or_else(|_| String::new());

        info!("Page reloaded");
        Ok(NavigationResponse::new(url, self.frame_id.clone()))
    }
}