playwright-rs 0.12.0

Rust bindings for Microsoft Playwright
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! JSON-RPC Connection layer for Playwright protocol

use crate::error::{Error, Result};
use crate::server::transport::{TransportReceiver, TransportSender};
use parking_lot::Mutex as ParkingLotMutex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use tokio::sync::Mutex as TokioMutex;
use tokio::sync::{mpsc, oneshot};

use crate::protocol::selectors::Selectors;
use crate::server::channel_owner::ChannelOwner;

/// Trait defining the interface that ChannelOwner needs from a Connection.
///
/// Uses `#[async_trait]` for ergonomic async method definitions while
/// maintaining dyn-safety (`Arc<dyn ConnectionLike>`).
#[async_trait::async_trait]
pub trait ConnectionLike: Send + Sync {
    /// Send a message to the Playwright server and await response.
    async fn send_message(&self, guid: &str, method: &str, params: Value) -> Result<Value>;

    /// Register an object in the connection's registry.
    async fn register_object(&self, guid: Arc<str>, object: Arc<dyn ChannelOwner>);

    /// Unregister an object from the connection's registry.
    async fn unregister_object(&self, guid: &str);

    /// Get an object by GUID.
    async fn get_object(&self, guid: &str) -> Result<Arc<dyn ChannelOwner>>;

    /// Returns all objects currently registered in the connection's registry.
    ///
    /// Used for operations that need to search across all known objects,
    /// such as finding child frames by matching their `parentFrame` GUID.
    async fn get_all_objects(&self) -> Vec<Arc<dyn ChannelOwner>>;

    /// Returns all objects currently registered in the connection's registry, synchronously.
    ///
    /// This is a synchronous variant for use in non-async contexts such as `child_frames()`.
    /// Callers that hold a reference to `Arc<dyn ConnectionLike>` can call this without
    /// needing to enter an async context.
    fn all_objects_sync(&self) -> Vec<Arc<dyn ChannelOwner>>;

    /// Returns the shared Selectors coordinator for this connection.
    ///
    /// Selectors is a pure client-side object that tracks custom selector
    /// engine registrations and the test ID attribute, propagating them to
    /// all BrowserContext instances.
    fn selectors(&self) -> Arc<Selectors>;
}

/// Extension trait for typed object retrieval from a connection.
///
/// Provides `get_typed::<T>(guid)` which combines `get_object` + downcast
/// into a single call with a proper `TypeMismatch` error.
///
/// # Example
///
/// ```ignore
/// use playwright_rs::server::connection::ConnectionExt;
///
/// let page: Page = connection.get_typed::<Page>(&guid).await?;
/// ```
#[async_trait::async_trait]
pub trait ConnectionExt: ConnectionLike {
    /// Get an object by GUID and downcast to the expected concrete type.
    ///
    /// Returns `Error::TypeMismatch` if the object exists but is not of type `T`.
    async fn get_typed<T: ChannelOwner + Clone + 'static>(&self, guid: &str) -> Result<T> {
        let obj = self.get_object(guid).await?;
        obj.as_any()
            .downcast_ref::<T>()
            .cloned()
            .ok_or_else(|| Error::TypeMismatch {
                guid: guid.to_string(),
                expected: std::any::type_name::<T>().to_string(),
                actual: obj.type_name().to_string(),
            })
    }
}

// Blanket implementation: any ConnectionLike automatically gets ConnectionExt.
impl<C: ConnectionLike + ?Sized> ConnectionExt for C {}

/// Downcast a protocol object's parent to a concrete type.
///
/// Returns `None` if the object has no parent or the parent is not of type `T`.
///
/// # Example
///
/// ```ignore
/// let page: Option<Page> = downcast_parent::<Page>(&*dialog_arc);
/// ```
pub fn downcast_parent<T: ChannelOwner + Clone + 'static>(obj: &dyn ChannelOwner) -> Option<T> {
    obj.parent()
        .and_then(|p| p.as_any().downcast_ref::<T>().cloned())
}

/// Metadata attached to every Playwright protocol message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metadata {
    #[serde(rename = "wallTime")]
    pub wall_time: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub internal: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<Location>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Location {
    pub file: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub column: Option<i32>,
}

impl Metadata {
    pub fn now() -> Self {
        Self {
            wall_time: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock is before UNIX epoch")
                .as_millis() as i64,
            internal: Some(false),
            location: None,
            title: None,
        }
    }
}

/// Protocol request message sent to Playwright server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    pub id: u32,
    #[serde(
        serialize_with = "serialize_arc_str",
        deserialize_with = "deserialize_arc_str"
    )]
    pub guid: Arc<str>,
    pub method: String,
    #[serde(skip_serializing_if = "is_value_null")]
    pub params: Value,
    pub metadata: Metadata,
}

fn is_value_null(v: &Value) -> bool {
    v.is_null()
}

pub fn serialize_arc_str<S>(arc: &Arc<str>, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(arc)
}

pub fn deserialize_arc_str<'de, D>(deserializer: D) -> std::result::Result<Arc<str>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s: String = serde::Deserialize::deserialize(deserializer)?;
    Ok(Arc::from(s.as_str()))
}

/// Protocol response message from Playwright server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    pub id: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorWrapper>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorWrapper {
    pub error: ErrorPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorPayload {
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stack: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    #[serde(
        serialize_with = "serialize_arc_str",
        deserialize_with = "deserialize_arc_str"
    )]
    pub guid: Arc<str>,
    pub method: String,
    #[serde(default)]
    pub params: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Message {
    Response(Response),
    Event(Event),
}

type ObjectRegistry = HashMap<Arc<str>, Arc<dyn ChannelOwner>>;

/// JSON-RPC connection to Playwright server
pub struct Connection {
    last_id: AtomicU32,
    callbacks: Arc<TokioMutex<HashMap<u32, oneshot::Sender<Result<Value>>>>>,
    sender: Arc<TokioMutex<Box<dyn TransportSender>>>,
    message_rx: Arc<TokioMutex<Option<mpsc::UnboundedReceiver<Value>>>>,
    transport_receiver: Arc<TokioMutex<Option<Box<dyn TransportReceiver>>>>,
    objects: Arc<ParkingLotMutex<ObjectRegistry>>,
    /// Shared Selectors coordinator for this connection.
    ///
    /// Selectors is a client-side object; it is created once per Connection and
    /// wired into every BrowserContext that is created on this connection.
    selectors: Arc<Selectors>,
}

// Type alias for compatibility (though generic parameters are gone, we can keep alias if needed)
pub type RealConnection = Connection;

impl Connection {
    pub fn new(
        sender: impl TransportSender + 'static,
        receiver: impl TransportReceiver + 'static,
        message_rx: mpsc::UnboundedReceiver<Value>,
    ) -> Self {
        Self {
            last_id: AtomicU32::new(0),
            callbacks: Arc::new(TokioMutex::new(HashMap::new())),
            sender: Arc::new(TokioMutex::new(Box::new(sender))),
            message_rx: Arc::new(TokioMutex::new(Some(message_rx))),
            transport_receiver: Arc::new(TokioMutex::new(Some(Box::new(receiver)))),
            objects: Arc::new(ParkingLotMutex::new(HashMap::new())),
            selectors: Arc::new(Selectors::new()),
        }
    }

    pub async fn send_message(&self, guid: String, method: String, params: Value) -> Result<Value> {
        let id = self.last_id.fetch_add(1, Ordering::SeqCst);

        tracing::debug!(
            "Sending message: id={}, guid='{}', method='{}'",
            id,
            guid,
            method
        );

        let (tx, rx) = oneshot::channel();
        self.callbacks.lock().await.insert(id, tx);

        let request = Request {
            id,
            guid: Arc::from(guid),
            method,
            params,
            metadata: Metadata::now(),
        };

        let request_value = serde_json::to_value(&request)?;
        tracing::debug!("Request JSON: {}", request_value);

        match self.sender.lock().await.send(request_value).await {
            Ok(()) => tracing::debug!("Message sent successfully, awaiting response"),
            Err(e) => {
                tracing::error!("Failed to send message: {:?}", e);
                return Err(e);
            }
        }

        tracing::debug!("Waiting for response to ID {}", id);
        rx.await
            .map_err(|_| Error::ChannelClosed)
            .and_then(|result| result)
    }

    pub async fn initialize_playwright(self: &Arc<Self>) -> Result<Arc<dyn ChannelOwner>> {
        use crate::protocol::Root;
        use std::time::Duration;

        let root = Arc::new(Root::new(Arc::clone(self) as Arc<dyn ConnectionLike>))
            as Arc<dyn ChannelOwner>;

        self.objects.lock().insert(Arc::from(""), root.clone());

        tracing::debug!("Root object registered, sending initialize message");

        let root_typed: Root = self
            .get_typed::<Root>("")
            .await
            .expect("Root object should be Root type");

        let response = tokio::time::timeout(Duration::from_secs(30), root_typed.initialize())
            .await
            .map_err(|_| {
                Error::Timeout("Playwright initialization timeout after 30 seconds".to_string())
            })??;

        let playwright_guid = response["playwright"]["guid"].as_str().ok_or_else(|| {
            Error::ProtocolError("Initialize response missing 'playwright.guid' field".to_string())
        })?;

        tracing::debug!("Initialized Playwright with GUID: {}", playwright_guid);

        let playwright_obj = self.wait_for_object(playwright_guid).await?;

        // Validate that the object is indeed a Playwright instance
        let _: crate::protocol::Playwright = self
            .get_typed::<crate::protocol::Playwright>(playwright_guid)
            .await?;

        let empty_guid: Arc<str> = Arc::from("");
        self.objects.lock().remove(&empty_guid);
        tracing::debug!("Root object unregistered after successful initialization");

        Ok(playwright_obj)
    }

    pub async fn run(self: &Arc<Self>) {
        let mut transport_receiver = self
            .transport_receiver
            .lock()
            .await
            .take()
            .expect("run() can only be called once - transport receiver already taken");

        let transport_handle = tokio::spawn(async move {
            if let Err(e) = transport_receiver.run().await {
                tracing::error!("Transport error: {}", e);
            }
        });

        let mut message_rx = self
            .message_rx
            .lock()
            .await
            .take()
            .expect("run() can only be called once - message receiver already taken");

        while let Some(message_value) = message_rx.recv().await {
            match serde_json::from_value::<Message>(message_value) {
                Ok(message) => {
                    if let Err(e) = self.dispatch_internal(message).await {
                        tracing::error!("Error dispatching message: {}", e);
                    }
                }
                Err(e) => {
                    tracing::error!("Failed to parse message: {}", e);
                }
            }
        }

        tracing::debug!("Message loop ended (transport closed)");
        let _ = transport_handle.await;
    }

    #[cfg(test)]
    pub async fn dispatch(self: &Arc<Self>, message: Message) -> Result<()> {
        self.dispatch_internal(message).await
    }

    async fn dispatch_internal(self: &Arc<Self>, message: Message) -> Result<()> {
        tracing::debug!("Dispatching message: {:?}", message);
        match message {
            Message::Response(response) => {
                tracing::debug!("Processing response for ID: {}", response.id);
                let callback = self
                    .callbacks
                    .lock()
                    .await
                    .remove(&response.id)
                    .ok_or_else(|| {
                        Error::ProtocolError(format!(
                            "Cannot find request to respond: id={}",
                            response.id
                        ))
                    })?;

                let result = if let Some(error_wrapper) = response.error {
                    Err(parse_protocol_error(error_wrapper.error))
                } else {
                    Ok(response.result.unwrap_or(Value::Null))
                };

                let _ = callback.send(result);
                Ok(())
            }
            Message::Event(event) => match event.method.as_str() {
                "__create__" => self.handle_create(&event).await,
                "__dispose__" => self.handle_dispose(&event).await,
                "__adopt__" => self.handle_adopt(&event).await,
                _ => match self.objects.lock().get(&event.guid).cloned() {
                    Some(object) => {
                        object.on_event(&event.method, event.params);
                        Ok(())
                    }
                    None => {
                        tracing::warn!(
                            "Event for unknown object: guid={}, method={}",
                            event.guid,
                            event.method
                        );
                        Ok(())
                    }
                },
            },
        }
    }

    async fn handle_create(self: &Arc<Self>, event: &Event) -> Result<()> {
        use crate::server::channel_owner::ParentOrConnection;
        use crate::server::object_factory::create_object;

        let type_name = event.params["type"]
            .as_str()
            .ok_or_else(|| Error::ProtocolError("__create__ missing 'type'".to_string()))?
            .to_string();

        let object_guid: Arc<str> = Arc::from(
            event.params["guid"]
                .as_str()
                .ok_or_else(|| Error::ProtocolError("__create__ missing 'guid'".to_string()))?,
        );

        tracing::debug!(
            "DEBUG __create__: type={}, guid={}, parent_guid={}",
            type_name,
            object_guid,
            event.guid
        );

        let initializer = event.params["initializer"].clone();

        let parent_or_conn = if event.guid.is_empty() {
            ParentOrConnection::Connection(Arc::clone(self) as Arc<dyn ConnectionLike>)
        } else {
            let parent_obj = self
                .objects
                .lock()
                .get(&event.guid)
                .cloned()
                .ok_or_else(|| {
                    tracing::error!(
                        "DEBUG: Parent object not found for type={}, parent_guid={}",
                        type_name,
                        event.guid
                    );
                    Error::ProtocolError(format!("Parent object not found: {}", event.guid))
                })?;
            ParentOrConnection::Parent(parent_obj)
        };

        let object = match create_object(
            parent_or_conn.clone(),
            type_name.clone(),
            object_guid.clone(),
            initializer,
        )
        .await
        {
            Ok(obj) => obj,
            Err(e) => {
                tracing::error!(
                    "DEBUG: Failed to create object type={}, guid={}, error={}",
                    type_name,
                    object_guid,
                    e
                );
                return Err(e);
            }
        };

        self.register_object(Arc::clone(&object_guid), object.clone())
            .await;

        if let ParentOrConnection::Parent(parent) = &parent_or_conn {
            parent.add_child(Arc::clone(&object_guid), object);
        }

        tracing::debug!(
            "DEBUG: Successfully created and registered object: type={}, guid={}",
            type_name,
            object_guid
        );

        Ok(())
    }

    async fn handle_dispose(self: &Arc<Self>, event: &Event) -> Result<()> {
        use crate::server::channel_owner::DisposeReason;

        let guid = &event.guid;

        // Find object - check lock in scope
        let object = { self.objects.lock().get(guid).cloned() };

        if let Some(object) = object {
            // Unregister from connection
            self.unregister_object(guid).await;

            // Remove from parent
            if let Some(parent) = object.parent() {
                parent.remove_child(guid);
            }

            // Dispose object
            object.dispose(DisposeReason::Protocol);

            tracing::debug!("Disposed object: guid={}", guid);
        } else {
            tracing::debug!("Ignoring __dispose__ for unknown object: guid={}", guid);
        }

        Ok(())
    }

    pub async fn wait_for_object(&self, guid: &str) -> Result<Arc<dyn ChannelOwner>> {
        use tokio::time::{Duration, sleep};
        let start = std::time::Instant::now();
        loop {
            if let Some(obj) = self.objects.lock().get(guid) {
                return Ok(obj.clone());
            }
            if start.elapsed() > Duration::from_secs(30) {
                return Err(Error::Timeout(format!(
                    "Timed out waiting for object {}",
                    guid
                )));
            }
            sleep(Duration::from_millis(10)).await;
        }
    }

    async fn handle_adopt(self: &Arc<Self>, event: &Event) -> Result<()> {
        let child_guid = event.params["guid"]
            .as_str()
            .ok_or_else(|| Error::ProtocolError("__adopt__ missing 'guid'".to_string()))?;

        let new_parent_guid = &event.guid;

        let child = self.get_object(child_guid).await.map_err(|e| {
            Error::ProtocolError(format!("Child object not found during adopt: {}", e))
        })?;

        let new_parent = self.get_object(new_parent_guid).await.map_err(|e| {
            Error::ProtocolError(format!("Parent object not found during adopt: {}", e))
        })?;

        // 1. Remove from old parent
        if let Some(old_parent) = child.parent() {
            old_parent.remove_child(child_guid);
        }

        // 2. Add to new parent (this will update child's weak parent ref if we had mutable access,
        // but since we only have Arc<dyn ChannelOwner>, ChannelOwner logic needs to handle it.
        // Actually, ChannelOwner trait has `adopt` method.
        new_parent.adopt(child);

        Ok(())
    }
}

#[async_trait::async_trait]
impl ConnectionLike for Connection {
    async fn send_message(&self, guid: &str, method: &str, params: Value) -> Result<Value> {
        self.send_message(guid.to_string(), method.to_string(), params)
            .await
    }

    async fn register_object(&self, guid: Arc<str>, object: Arc<dyn ChannelOwner>) {
        self.objects.lock().insert(guid, object);
    }

    async fn unregister_object(&self, guid: &str) {
        self.objects.lock().remove(guid);
    }

    async fn get_object(&self, guid: &str) -> Result<Arc<dyn ChannelOwner>> {
        self.objects.lock().get(guid).cloned().ok_or_else(|| {
            Error::ObjectNotFound(format!(
                "{} (object may have been closed or disposed)",
                guid
            ))
        })
    }

    async fn get_all_objects(&self) -> Vec<Arc<dyn ChannelOwner>> {
        self.objects.lock().values().cloned().collect()
    }

    fn all_objects_sync(&self) -> Vec<Arc<dyn ChannelOwner>> {
        self.objects.lock().values().cloned().collect()
    }

    fn selectors(&self) -> Arc<Selectors> {
        Arc::clone(&self.selectors)
    }
}

/// Detects if an error message indicates a browser installation issue
fn is_browser_installation_error(message: &str) -> bool {
    message.contains("Looks like Playwright")
        || message.contains("Executable doesn't exist")
        || message.contains("not installed")
        || message.contains("Please run")
}

/// Extracts browser name from error message
fn extract_browser_name(message: &str) -> &str {
    // Check in priority order (specific to generic)
    if message.contains("chromium") {
        "chromium"
    } else if message.contains("firefox") {
        "firefox"
    } else if message.contains("webkit") {
        "webkit"
    } else {
        // If we can't detect the browser, use a generic message
        "browsers"
    }
}

fn parse_protocol_error(payload: ErrorPayload) -> Error {
    // Detect browser installation errors
    // Playwright server sends errors with messages like:
    // "Looks like Playwright Test or Playwright was just installed or updated."
    // or "browserType.launch: Executable doesn't exist at /path/to/chromium"

    let message = &payload.message;

    // Check for browser installation errors
    if is_browser_installation_error(message) {
        let browser_name = extract_browser_name(message);

        return Error::BrowserNotInstalled {
            browser_name: browser_name.to_string(),
            message: message.clone(),
            playwright_version: crate::PLAYWRIGHT_VERSION.to_string(),
        };
    }

    // Default: return as protocol error
    Error::ProtocolError(format!(
        "{} \n {}",
        payload.message,
        payload.stack.unwrap_or_default()
    ))
}