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
// Copyright 2026 Paul Adamson
// Licensed under the Apache License, Version 2.0
//
// Object Factory - Creates protocol objects from type names
//
// Architecture Reference:
// - Python: playwright-python/playwright/_impl/_connection.py (_create_remote_object)
// - Java: playwright-java/.../impl/Connection.java (createRemoteObject)
// - JavaScript: playwright/.../client/connection.ts (_createRemoteObject)
//
// The object factory maps protocol type names (strings) to Rust constructors.
// When the server sends a `__create__` message, the factory instantiates
// the appropriate Rust object based on the type name.

use crate::error::{Error, Result};
use crate::protocol::{
    APIRequestContext, Android, BindingCall, Browser, BrowserContext, BrowserType, CDPSession,
    Dialog, Electron, Frame, JSHandle, LocalUtils, Page, Playwright, Request, ResponseObject,
    Route, Tracing, WebSocket, WebSocketRoute, Worker, artifact::Artifact,
};
use crate::server::channel_owner::{ChannelOwner, ParentOrConnection};
use crate::server::connection::ConnectionExt;
use serde_json::Value;
use std::sync::Arc;

/// Creates a protocol object from a `__create__` message.
///
/// This function is the central object factory for the Playwright protocol.
/// It maps type names from the server to Rust struct constructors.
///
/// # Arguments
///
/// * `parent` - Either a parent ChannelOwner or the root Connection
/// * `type_name` - Protocol type name (e.g., "Playwright", "BrowserType")
/// * `guid` - Unique GUID assigned by the server
/// * `initializer` - JSON object with initial state
///
/// # Returns
///
/// An `Arc<dyn ChannelOwner>` pointing to the newly created object.
///
/// # Errors
///
/// Returns `Error::ProtocolError` if the type name is unknown or if
/// object construction fails.
///
/// # Example
///
/// ```ignore
/// # use playwright_rs::server::object_factory::create_object;
/// # use playwright_rs::server::channel_owner::ParentOrConnection;
/// # use playwright_rs::server::connection::ConnectionLike;
/// # use std::sync::Arc;
/// # use serde_json::json;
/// # async fn example(connection: Arc<dyn ConnectionLike>) -> Result<(), Box<dyn std::error::Error>> {
/// let playwright_obj = create_object(
///     ParentOrConnection::Connection(connection),
///     "Playwright".to_string(),
///     Arc::from("playwright@1"),
///     json!({
///         "chromium": { "guid": "browserType@chromium" },
///         "firefox": { "guid": "browserType@firefox" },
///         "webkit": { "guid": "browserType@webkit" }
///     })
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn create_object(
    parent: ParentOrConnection,
    type_name: String,
    guid: Arc<str>,
    initializer: Value,
) -> Result<Arc<dyn ChannelOwner>> {
    // Match on type name and call appropriate constructor
    let object: Arc<dyn ChannelOwner> = match type_name.as_str() {
        "Playwright" => {
            // Playwright is the root object, so parent must be Connection
            let connection = match parent {
                ParentOrConnection::Connection(conn) => conn,
                ParentOrConnection::Parent(_) => {
                    return Err(Error::ProtocolError(
                        "Playwright must have Connection as parent".to_string(),
                    ));
                }
            };

            Arc::new(Playwright::new(connection, type_name, guid, initializer).await?)
        }

        "BrowserType" => {
            // BrowserType is a root child (created with parent="")
            // The Playwright object references them via its initializer
            Arc::new(BrowserType::new(parent, type_name, guid, initializer)?)
        }

        "Browser" => {
            // Browser has BrowserType as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Browser must have BrowserType as parent".to_string(),
                    ));
                }
            };

            Arc::new(Browser::new(parent_owner, type_name, guid, initializer)?)
        }

        "BrowserContext" => {
            // BrowserContext has Browser as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "BrowserContext must have Browser as parent".to_string(),
                    ));
                }
            };

            Arc::new(BrowserContext::new(
                parent_owner,
                type_name,
                guid,
                initializer,
            )?)
        }

        "Page" => {
            // Page has BrowserContext as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Page must have BrowserContext as parent".to_string(),
                    ));
                }
            };

            Arc::new(Page::new(parent_owner, type_name, guid, initializer)?)
        }

        "Frame" => {
            // Frame has Page as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Frame must have Page as parent".to_string(),
                    ));
                }
            };

            Arc::new(Frame::new(parent_owner, type_name, guid, initializer)?)
        }

        "Request" => {
            // Request's parent in the protocol is Page (not Frame)
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Request must have a parent object".to_string(),
                    ));
                }
            };

            let request = Arc::new(Request::new(
                parent_owner,
                type_name,
                guid,
                initializer.clone(),
            )?);

            // Eagerly resolve the Frame back-reference from initializer["frame"]["guid"]
            if let Some(frame_guid) = initializer
                .get("frame")
                .and_then(|v| v.get("guid"))
                .and_then(|v| v.as_str())
                && let Ok(frame) = request
                    .connection()
                    .get_typed::<crate::protocol::Frame>(frame_guid)
                    .await
            {
                request.set_frame(frame);
            }

            // Eagerly resolve the redirect chain from initializer["redirectedFrom"]["guid"]
            if let Some(from_guid) = initializer
                .get("redirectedFrom")
                .and_then(|v| v.get("guid"))
                .and_then(|v| v.as_str())
                && let Ok(from_request) = request.connection().get_typed::<Request>(from_guid).await
            {
                request.set_redirected_from(from_request.clone());
                // Set the reverse pointer on the original request
                from_request.set_redirected_to((*request).clone());
            }

            request
        }

        "Route" => {
            // Route has Frame as parent (created during network interception)
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Route must have Frame as parent".to_string(),
                    ));
                }
            };

            Arc::new(Route::new(parent_owner, type_name, guid, initializer)?)
        }

        "Response" => {
            // Response has Request as parent (not Frame!)
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Response must have Request as parent".to_string(),
                    ));
                }
            };

            let response_obj = Arc::new(ResponseObject::new(
                parent_owner.clone(),
                type_name,
                guid,
                initializer.clone(),
            )?);

            // Mirror the JS implementation: Response constructor sets this._request._response = this.
            // Downcast the parent to Request and store the back-reference so that
            // request.existing_response() returns Some immediately after the Response is created.
            if let Some(parent_request) = parent_owner
                .as_any()
                .downcast_ref::<crate::protocol::Request>()
            {
                let status = initializer
                    .get("status")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u16;
                let headers = initializer
                    .get("headers")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|h| {
                                let name = h.get("name")?.as_str()?;
                                let value = h.get("value")?.as_str()?;
                                Some((name.to_string(), value.to_string()))
                            })
                            .collect::<std::collections::HashMap<_, _>>()
                    })
                    .unwrap_or_default();
                let high_level_response = crate::protocol::page::Response::new(
                    initializer
                        .get("url")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                    status,
                    initializer
                        .get("statusText")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                    headers,
                    Some(
                        response_obj.clone() as Arc<dyn crate::server::channel_owner::ChannelOwner>
                    ),
                );
                parent_request.set_response(high_level_response);
            }

            response_obj
        }

        "ElementHandle" => {
            // ElementHandle has Frame as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "ElementHandle must have Frame as parent".to_string(),
                    ));
                }
            };

            Arc::new(crate::protocol::ElementHandle::new(
                parent_owner,
                type_name,
                guid,
                initializer,
            )?)
        }

        "JSHandle" => {
            // JSHandle can have Frame or BrowserContext as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "JSHandle must have a parent object".to_string(),
                    ));
                }
            };

            Arc::new(JSHandle::new(parent_owner, type_name, guid, initializer)?)
        }

        "Artifact" => {
            // Artifact has BrowserContext as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Artifact must have BrowserContext as parent".to_string(),
                    ));
                }
            };

            Arc::new(Artifact::new(parent_owner, type_name, guid, initializer)?)
        }

        "Dialog" => {
            // Dialog has Page as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Dialog must have Page as parent".to_string(),
                    ));
                }
            };

            Arc::new(Dialog::new(parent_owner, type_name, guid, initializer)?)
        }

        "Android" => {
            // Android stub
            Arc::new(Android::new(parent, type_name, guid, initializer)?)
        }

        "Electron" => {
            // Electron stub
            Arc::new(Electron::new(parent, type_name, guid, initializer)?)
        }

        "CDPSession" => {
            // CDPSession — Chrome DevTools Protocol session (Chromium only)
            Arc::new(CDPSession::new(parent, type_name, guid, initializer)?)
        }

        "Tracing" => {
            // Tracing — trace recording per BrowserContext
            Arc::new(Tracing::new(parent, type_name, guid, initializer)?)
        }

        "APIRequestContext" => {
            // APIRequestContext stub
            Arc::new(APIRequestContext::new(
                parent,
                type_name,
                guid,
                initializer,
            )?)
        }

        "LocalUtils" => {
            // LocalUtils stub
            Arc::new(LocalUtils::new(parent, type_name, guid, initializer)?)
        }

        "WebSocket" => {
            // WebSocket has Page as parent
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "WebSocket must have Page as parent".to_string(),
                    ));
                }
            };

            Arc::new(WebSocket::new(parent_owner, type_name, guid, initializer)?)
        }

        "BindingCall" => {
            // BindingCall — a JS → Rust callback invocation
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "BindingCall must have a parent object".to_string(),
                    ));
                }
            };

            Arc::new(BindingCall::new(
                parent_owner,
                type_name,
                guid,
                initializer,
            )?)
        }

        "Worker" => {
            // Worker — Web Worker or Service Worker
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "Worker must have a parent object".to_string(),
                    ));
                }
            };

            Arc::new(Worker::new(parent_owner, type_name, guid, initializer)?)
        }

        "WebSocketRoute" => {
            // WebSocketRoute — created when a WebSocket matches a route_web_socket pattern
            let parent_owner = match parent {
                ParentOrConnection::Parent(p) => p,
                ParentOrConnection::Connection(_) => {
                    return Err(Error::ProtocolError(
                        "WebSocketRoute must have a parent object".to_string(),
                    ));
                }
            };

            Arc::new(WebSocketRoute::new(
                parent_owner,
                type_name,
                guid,
                initializer,
            )?)
        }

        _ => {
            // Unknown type - log warning and return error
            tracing::warn!("Unknown protocol type: {}", type_name);
            return Err(Error::ProtocolError(format!(
                "Unknown protocol type: {}",
                type_name
            )));
        }
    };

    Ok(object)
}

// Note: Object factory testing is done via integration tests since it requires:
// - Real Connection with object registry
// - Protocol messages from the server
// See: crates/playwright-core/tests/connection_integration.rs