viewpoint-core 0.2.10

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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Frame management and navigation.
//!
//! Frames represent separate browsing contexts within a page, typically
//! created by `<iframe>` elements. Each frame has its own DOM, JavaScript
//! context, and URL.

// Allow dead code for frame scaffolding (spec: frames)

use std::sync::Arc;
use std::time::Duration;

use parking_lot::RwLock;
use tracing::{debug, info, instrument};
use viewpoint_cdp::CdpConnection;
use viewpoint_cdp::protocol::page::{NavigateParams, NavigateResult};
use viewpoint_cdp::protocol::runtime::EvaluateParams;

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

/// Default navigation timeout.
const DEFAULT_NAVIGATION_TIMEOUT: Duration = Duration::from_secs(30);

/// Internal frame data that can be updated.
#[derive(Debug, Clone)]
struct FrameData {
    /// Frame's current URL.
    url: String,
    /// Frame's name attribute.
    name: String,
    /// Whether the frame is detached.
    detached: bool,
}

/// A frame within a page.
///
/// Frames are separate browsing contexts, typically created by `<iframe>` elements.
/// Each frame has its own DOM and JavaScript execution context.
#[derive(Debug)]
pub struct Frame {
    /// CDP connection.
    connection: Arc<CdpConnection>,
    /// Session ID for this frame's page.
    session_id: String,
    /// Unique frame identifier.
    id: String,
    /// Parent frame ID (None for main frame).
    parent_id: Option<String>,
    /// Loader ID for this frame.
    loader_id: String,
    /// Mutable frame data.
    data: RwLock<FrameData>,
}

impl Frame {
    /// Create a new frame from CDP frame info.
    pub(crate) fn new(
        connection: Arc<CdpConnection>,
        session_id: String,
        id: String,
        parent_id: Option<String>,
        loader_id: String,
        url: String,
        name: String,
    ) -> Self {
        Self {
            connection,
            session_id,
            id,
            parent_id,
            loader_id,
            data: RwLock::new(FrameData {
                url,
                name,
                detached: false,
            }),
        }
    }

    /// Get the unique frame identifier.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the parent frame ID.
    ///
    /// Returns `None` for the main frame.
    pub fn parent_id(&self) -> Option<&str> {
        self.parent_id.as_deref()
    }

    /// Check if this is the main frame.
    pub fn is_main(&self) -> bool {
        self.parent_id.is_none()
    }

    /// Get the loader ID.
    pub fn loader_id(&self) -> &str {
        &self.loader_id
    }

    /// Get the frame's current URL.
    pub fn url(&self) -> String {
        self.data.read().url.clone()
    }

    /// Get the frame's name attribute.
    pub fn name(&self) -> String {
        self.data.read().name.clone()
    }

    /// Check if the frame has been detached.
    pub fn is_detached(&self) -> bool {
        self.data.read().detached
    }

    /// Update the frame's URL (called when frame navigates).
    pub(crate) fn set_url(&self, url: String) {
        self.data.write().url = url;
    }

    /// Update the frame's name.
    pub(crate) fn set_name(&self, name: String) {
        self.data.write().name = name;
    }

    /// Mark the frame as detached.
    pub(crate) fn set_detached(&self) {
        self.data.write().detached = true;
    }

    /// Get the frame's HTML content.
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is detached or the evaluation fails.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id))]
    pub async fn content(&self) -> Result<String, PageError> {
        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
            .connection
            .send_command(
                "Runtime.evaluate",
                Some(EvaluateParams {
                    expression: "document.documentElement.outerHTML".to_string(),
                    object_group: None,
                    include_command_line_api: None,
                    silent: Some(true),
                    context_id: None, // TODO: Use frame's execution context
                    return_by_value: Some(true),
                    await_promise: Some(false),
                }),
                Some(&self.session_id),
            )
            .await?;

        result
            .result
            .value
            .and_then(|v| v.as_str().map(ToString::to_string))
            .ok_or_else(|| PageError::EvaluationFailed("Failed to get content".to_string()))
    }

    /// Get the frame's document title.
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is detached or the evaluation fails.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id))]
    pub async fn title(&self) -> Result<String, PageError> {
        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
            .connection
            .send_command(
                "Runtime.evaluate",
                Some(EvaluateParams {
                    expression: "document.title".to_string(),
                    object_group: None,
                    include_command_line_api: None,
                    silent: Some(true),
                    context_id: None, // TODO: Use frame's execution context
                    return_by_value: Some(true),
                    await_promise: Some(false),
                }),
                Some(&self.session_id),
            )
            .await?;

        result
            .result
            .value
            .and_then(|v| v.as_str().map(ToString::to_string))
            .ok_or_else(|| PageError::EvaluationFailed("Failed to get title".to_string()))
    }

    /// Navigate the frame to a URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is detached or navigation fails.
    #[instrument(level = "info", skip(self), fields(frame_id = %self.id, url = %url))]
    pub async fn goto(&self, url: &str) -> Result<(), NavigationError> {
        self.goto_with_options(url, DocumentLoadState::Load, DEFAULT_NAVIGATION_TIMEOUT)
            .await
    }

    /// Navigate the frame to a URL with options.
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is detached or navigation fails.
    #[instrument(level = "info", skip(self), fields(frame_id = %self.id, url = %url, wait_until = ?wait_until))]
    pub async fn goto_with_options(
        &self,
        url: &str,
        wait_until: DocumentLoadState,
        timeout: Duration,
    ) -> Result<(), NavigationError> {
        if self.is_detached() {
            return Err(NavigationError::Cancelled);
        }

        info!("Navigating frame to URL");

        // Create a load state waiter
        let event_rx = self.connection.subscribe_events();
        let mut waiter = LoadStateWaiter::new(event_rx, self.session_id.clone(), self.id.clone());

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

        debug!(frame_id = %result.frame_id, "Page.navigate completed for frame");

        // Check for navigation errors
        if let Some(error_text) = result.error_text {
            return Err(NavigationError::NetworkError(error_text));
        }

        // Mark commit as 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?;

        // Update the frame's URL
        self.set_url(url.to_string());

        info!(frame_id = %self.id, "Frame navigation completed");
        Ok(())
    }

    /// Set the frame's HTML content.
    ///
    /// # Errors
    ///
    /// Returns an error if the frame is detached or setting content fails.
    #[instrument(level = "info", skip(self, html), fields(frame_id = %self.id))]
    pub async fn set_content(&self, html: &str) -> Result<(), PageError> {
        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        use viewpoint_cdp::protocol::page::SetDocumentContentParams;

        self.connection
            .send_command::<_, serde_json::Value>(
                "Page.setDocumentContent",
                Some(SetDocumentContentParams {
                    frame_id: self.id.clone(),
                    html: html.to_string(),
                }),
                Some(&self.session_id),
            )
            .await?;

        info!("Frame content set");
        Ok(())
    }

    /// Wait for the frame to reach a specific load state.
    ///
    /// # Errors
    ///
    /// Returns an error if the wait times out or the frame is detached.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id, state = ?state))]
    pub async fn wait_for_load_state(
        &self,
        state: DocumentLoadState,
    ) -> Result<(), NavigationError> {
        self.wait_for_load_state_with_timeout(state, DEFAULT_NAVIGATION_TIMEOUT)
            .await
    }

    /// Wait for the frame to reach a specific load state with timeout.
    ///
    /// # Errors
    ///
    /// Returns an error if the wait times out or the frame is detached.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id, state = ?state, timeout_ms = timeout.as_millis()))]
    pub async fn wait_for_load_state_with_timeout(
        &self,
        state: DocumentLoadState,
        timeout: Duration,
    ) -> Result<(), NavigationError> {
        if self.is_detached() {
            return Err(NavigationError::Cancelled);
        }

        let event_rx = self.connection.subscribe_events();
        let mut waiter = LoadStateWaiter::new(event_rx, self.session_id.clone(), self.id.clone());

        // Assume commit already happened for existing frames
        waiter.set_commit_received().await;

        waiter
            .wait_for_load_state_with_timeout(state, timeout)
            .await?;

        debug!("Frame reached load state {:?}", state);
        Ok(())
    }

    /// Get the session ID.
    pub(crate) fn session_id(&self) -> &str {
        &self.session_id
    }

    /// Get the connection.
    pub(crate) fn connection(&self) -> &Arc<CdpConnection> {
        &self.connection
    }

    /// Get child frames of this frame.
    ///
    /// Returns a list of frames that are direct children of this frame.
    ///
    /// # Errors
    ///
    /// Returns an error if querying the frame tree fails.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id))]
    pub async fn child_frames(&self) -> Result<Vec<Frame>, PageError> {
        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        // Get the frame tree from CDP
        let result: viewpoint_cdp::protocol::page::GetFrameTreeResult = self
            .connection
            .send_command("Page.getFrameTree", None::<()>, Some(&self.session_id))
            .await?;

        // Find this frame in the tree and return its children
        let children = find_child_frames(
            &result.frame_tree,
            &self.id,
            &self.connection,
            &self.session_id,
        );

        Ok(children)
    }

    /// Get the parent frame.
    ///
    /// Returns `None` if this is the main frame.
    ///
    /// # Errors
    ///
    /// Returns an error if querying the frame tree fails.
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id))]
    pub async fn parent_frame(&self) -> Result<Option<Frame>, PageError> {
        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        // Main frame has no parent
        if self.is_main() {
            return Ok(None);
        }

        // Get the frame tree from CDP
        let result: viewpoint_cdp::protocol::page::GetFrameTreeResult = self
            .connection
            .send_command("Page.getFrameTree", None::<()>, Some(&self.session_id))
            .await?;

        // Find the parent frame
        let parent = find_parent_frame(
            &result.frame_tree,
            &self.id,
            &self.connection,
            &self.session_id,
        );

        Ok(parent)
    }

    /// Capture an ARIA accessibility snapshot of this frame's document.
    ///
    /// The snapshot represents the accessible structure of the frame's content
    /// as it would be exposed to assistive technologies. This is useful for
    /// accessibility testing and MCP (Model Context Protocol) integrations.
    ///
    /// # Frame Boundaries
    ///
    /// Any iframes within this frame are marked as frame boundaries in the snapshot
    /// with `is_frame: true`. Their content is NOT traversed (for security reasons).
    /// To capture multi-frame accessibility trees, use `Page::aria_snapshot_with_frames()`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use viewpoint_core::Page;
    ///
    /// # async fn example(page: Page) -> Result<(), viewpoint_core::CoreError> {
    /// // Get snapshot of main frame
    /// let main_frame = page.main_frame().await?;
    /// let snapshot = main_frame.aria_snapshot().await?;
    /// println!("{}", snapshot);
    ///
    /// // Get snapshot of a child iframe
    /// for frame in page.frames().await? {
    ///     if !frame.is_main() {
    ///         let frame_snapshot = frame.aria_snapshot().await?;
    ///         println!("Frame {}: {}", frame.name(), frame_snapshot);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The frame is detached
    /// - JavaScript evaluation fails
    /// - The snapshot cannot be parsed
    #[instrument(level = "debug", skip(self), fields(frame_id = %self.id))]
    pub async fn aria_snapshot(&self) -> Result<crate::page::locator::AriaSnapshot, PageError> {
        use crate::page::locator::aria::aria_snapshot_js;
        use viewpoint_js::js;

        if self.is_detached() {
            return Err(PageError::EvaluationFailed("Frame is detached".to_string()));
        }

        // Build JavaScript to capture aria snapshot of the entire document
        let snapshot_fn = aria_snapshot_js();
        let js_code = js! {
            (function() {
                const getSnapshot = @{snapshot_fn};
                return getSnapshot(document.body || document.documentElement);
            })()
        };

        // Use Runtime.evaluate with the frame's execution context
        // CDP allows targeting specific frames via contextId, but for simplicity
        // we use Page.createIsolatedWorld for frame-specific execution
        let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
            .connection
            .send_command(
                "Runtime.evaluate",
                Some(EvaluateParams {
                    expression: js_code,
                    object_group: None,
                    include_command_line_api: None,
                    silent: Some(true),
                    context_id: None, // TODO: Use frame-specific context when available
                    return_by_value: Some(true),
                    await_promise: Some(false),
                }),
                Some(&self.session_id),
            )
            .await?;

        if let Some(exception) = result.exception_details {
            return Err(PageError::EvaluationFailed(exception.text));
        }

        let value = result.result.value.ok_or_else(|| {
            PageError::EvaluationFailed("No result from aria snapshot".to_string())
        })?;

        // Parse the snapshot
        let snapshot: crate::page::locator::AriaSnapshot =
            serde_json::from_value(value).map_err(|e| {
                PageError::EvaluationFailed(format!("Failed to parse aria snapshot: {e}"))
            })?;

        Ok(snapshot)
    }
}

/// Recursively find child frames of a given frame ID.
fn find_child_frames(
    tree: &viewpoint_cdp::protocol::page::FrameTree,
    parent_id: &str,
    connection: &Arc<CdpConnection>,
    session_id: &str,
) -> Vec<Frame> {
    let mut children = Vec::new();

    // Check if this is the parent we're looking for
    if tree.frame.id == parent_id {
        // Return all direct children
        if let Some(ref child_frames) = tree.child_frames {
            for child in child_frames {
                children.push(Frame::new(
                    connection.clone(),
                    session_id.to_string(),
                    child.frame.id.clone(),
                    Some(parent_id.to_string()),
                    child.frame.loader_id.clone(),
                    child.frame.url.clone(),
                    child.frame.name.clone().unwrap_or_default(),
                ));
            }
        }
    } else {
        // Recurse into children to find the parent
        if let Some(ref child_frames) = tree.child_frames {
            for child in child_frames {
                let found = find_child_frames(child, parent_id, connection, session_id);
                children.extend(found);
            }
        }
    }

    children
}

/// Recursively find the parent frame of a given frame ID.
fn find_parent_frame(
    tree: &viewpoint_cdp::protocol::page::FrameTree,
    frame_id: &str,
    connection: &Arc<CdpConnection>,
    session_id: &str,
) -> Option<Frame> {
    // Check if any direct child is the frame we're looking for
    if let Some(ref child_frames) = tree.child_frames {
        for child in child_frames {
            if child.frame.id == frame_id {
                // Found it - return the current frame as the parent
                return Some(Frame::new(
                    connection.clone(),
                    session_id.to_string(),
                    tree.frame.id.clone(),
                    tree.frame.parent_id.clone(),
                    tree.frame.loader_id.clone(),
                    tree.frame.url.clone(),
                    tree.frame.name.clone().unwrap_or_default(),
                ));
            }
        }

        // Recurse into children
        for child in child_frames {
            if let Some(parent) = find_parent_frame(child, frame_id, connection, session_id) {
                return Some(parent);
            }
        }
    }

    None
}