viewpoint_cdp/transport/
mod.rs

1//! CDP message transport types.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// A CDP request message.
7#[derive(Debug, Clone, Serialize)]
8pub struct CdpRequest {
9    /// Unique message ID for matching responses.
10    pub id: u64,
11    /// CDP method name (e.g., "Target.createTarget").
12    pub method: String,
13    /// Method parameters.
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub params: Option<Value>,
16    /// Session ID for target-specific commands.
17    #[serde(rename = "sessionId", skip_serializing_if = "Option::is_none")]
18    pub session_id: Option<String>,
19}
20
21/// A CDP response message.
22#[derive(Debug, Clone, Deserialize)]
23pub struct CdpResponse {
24    /// Message ID matching the request.
25    pub id: u64,
26    /// Result on success.
27    pub result: Option<Value>,
28    /// Error on failure.
29    pub error: Option<CdpResponseError>,
30    /// Session ID if this was a session-specific response.
31    #[serde(rename = "sessionId")]
32    pub session_id: Option<String>,
33}
34
35/// Error details in a CDP response.
36#[derive(Debug, Clone, Deserialize)]
37pub struct CdpResponseError {
38    /// Error code.
39    pub code: i64,
40    /// Error message.
41    pub message: String,
42    /// Additional error data.
43    pub data: Option<String>,
44}
45
46/// A CDP event message.
47#[derive(Debug, Clone, Deserialize)]
48pub struct CdpEvent {
49    /// Event method name (e.g., "Page.loadEventFired").
50    pub method: String,
51    /// Event parameters.
52    pub params: Option<Value>,
53    /// Session ID if this event came from a specific session.
54    #[serde(rename = "sessionId")]
55    pub session_id: Option<String>,
56}
57
58/// An incoming CDP message (either response or event).
59#[derive(Debug, Clone, Deserialize)]
60#[serde(untagged)]
61pub enum CdpMessage {
62    /// A response to a previous request.
63    Response(CdpResponse),
64    /// An event pushed by the browser.
65    Event(CdpEvent),
66}
67
68impl CdpMessage {
69    /// Check if this message is a response with the given ID.
70    pub fn is_response_for(&self, id: u64) -> bool {
71        matches!(self, Self::Response(resp) if resp.id == id)
72    }
73
74    /// Try to extract this as a response.
75    pub fn into_response(self) -> Option<CdpResponse> {
76        match self {
77            Self::Response(resp) => Some(resp),
78            Self::Event(_) => None,
79        }
80    }
81
82    /// Try to extract this as an event.
83    pub fn into_event(self) -> Option<CdpEvent> {
84        match self {
85            Self::Event(evt) => Some(evt),
86            Self::Response(_) => None,
87        }
88    }
89}
90
91#[cfg(test)]
92mod tests;