ferridriver 0.1.0

High-performance browser automation library with pluggable backends
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
//! `BrowserContext` -- isolated browser environment with pages, cookies, and logs.
//!
//! Mirrors Playwright's `BrowserContext` exactly:
//! - Owns pages (`Vec<AnyPage>`)
//! - Owns cookies (via any page in the context)
//! - Owns console/network/dialog logs
//! - Created by `Browser.new_context()`
//! - Pages are created by `context.new_page()`

use crate::backend::{AnyPage, CookieData};
use crate::page::Page;
use crate::state::SessionKey;
use arc_swap::ArcSwap;
use rustc_hash::FxHashMap as HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// A collected console message (matches Playwright's `ConsoleMessage`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConsoleMsg {
  /// Console message type: "log", "warn", "error", "info", "debug", "trace".
  pub r#type: String,
  pub text: String,
}

/// A collected network request with headers and optional post data.
#[derive(Debug, Clone, serde::Serialize)]
pub struct NetRequest {
  pub id: String,
  pub method: String,
  pub url: String,
  pub resource_type: String,
  pub status: Option<i64>,
  pub mime_type: Option<String>,
  /// Request headers (key -> value).
  #[serde(skip_serializing_if = "Option::is_none")]
  pub headers: Option<HashMap<String, String>>,
  /// POST body data (if applicable).
  #[serde(skip_serializing_if = "Option::is_none")]
  pub post_data: Option<String>,
}

/// A dismissed dialog event (alert, confirm, prompt).
#[derive(Debug, Clone, serde::Serialize)]
pub struct DialogEvent {
  pub dialog_type: String,
  pub message: String,
  pub action: String,
}

/// Isolated browser context. Directly holds pages, cookies, and event logs.
/// This IS the state -- not a wrapper around some other struct.
/// Stored in `BrowserState`'s context map.
pub struct BrowserContext {
  /// Pages in this context.
  pub pages: Vec<AnyPage>,
  /// Active page index.
  pub active_page_idx: usize,
  /// Element ref map for accessibility snapshots (wait-free reads via `ArcSwap`).
  pub ref_map: Arc<ArcSwap<HashMap<String, i64>>>,
  /// Console messages collected from page events.
  pub console_log: Arc<RwLock<Vec<ConsoleMsg>>>,
  /// Network requests collected from page events.
  pub network_log: Arc<RwLock<Vec<NetRequest>>>,
  /// Dialog events.
  pub dialog_log: Arc<RwLock<Vec<DialogEvent>>>,
  /// Context name (unique identifier).
  name: String,
  /// CDP browser context ID (for `Target.disposeBrowserContext` on close).
  /// None for the default context.
  pub cdp_context_id: Option<String>,
}

impl BrowserContext {
  /// Create a new empty context.
  pub(crate) fn new(name: String) -> Self {
    Self {
      pages: Vec::new(),
      active_page_idx: 0,
      ref_map: Arc::new(ArcSwap::from_pointee(HashMap::default())),
      console_log: Arc::new(RwLock::new(Vec::new())),
      network_log: Arc::new(RwLock::new(Vec::new())),
      dialog_log: Arc::new(RwLock::new(Vec::new())),
      name,
      cdp_context_id: None,
    }
  }

  /// Context name.
  #[must_use]
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Get the active page in this context.
  #[must_use]
  pub fn active_page(&self) -> Option<&AnyPage> {
    self.pages.get(self.active_page_idx)
  }

  // -- Cookies (operate on active page) ------------------------------------

  /// Get all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if cookies cannot be retrieved from the active page.
  pub async fn cookies(&self) -> Result<Vec<CookieData>, String> {
    if let Some(page) = self.active_page() {
      page.get_cookies().await
    } else {
      Ok(Vec::new())
    }
  }

  /// Add cookies to this context.
  ///
  /// # Errors
  ///
  /// Returns an error if no page exists or if setting a cookie fails.
  pub async fn add_cookies(&self, cookies: Vec<CookieData>) -> Result<(), String> {
    let page = self.active_page().ok_or("No page in context")?;
    for cookie in cookies {
      page.set_cookie(cookie).await?;
    }
    Ok(())
  }

  /// Clear all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if clearing cookies fails on the active page.
  pub async fn clear_cookies(&self) -> Result<(), String> {
    if let Some(page) = self.active_page() {
      page.clear_cookies().await?;
    }
    Ok(())
  }

  /// Delete specific cookies by name and optional domain.
  ///
  /// # Errors
  ///
  /// Returns an error if reading or re-setting cookies fails.
  pub async fn delete_cookie(&self, name: &str, domain: Option<&str>) -> Result<(), String> {
    let cookies = self.cookies().await?;
    if let Some(page) = self.active_page() {
      page.clear_cookies().await?;
      for cookie in cookies {
        let name_matches = cookie.name == name;
        let domain_matches = domain.is_none_or(|d| cookie.domain == d);
        if !(name_matches && domain_matches) {
          page.set_cookie(cookie).await?;
        }
      }
    }
    Ok(())
  }

  // -- Console/network/dialog log access -----------------------------------

  /// Get console messages, optionally filtered by level.
  pub async fn console_messages(&self, level: Option<&str>, limit: usize) -> Vec<ConsoleMsg> {
    let msgs = self.console_log.read().await;
    msgs
      .iter()
      .filter(|m| level.is_none_or(|l| l == "all" || m.r#type == l))
      .rev()
      .take(limit)
      .cloned()
      .collect::<Vec<_>>()
      .into_iter()
      .rev()
      .collect()
  }

  /// Get network requests.
  pub async fn network_requests(&self, limit: usize) -> Vec<NetRequest> {
    let reqs = self.network_log.read().await;
    reqs
      .iter()
      .rev()
      .take(limit)
      .cloned()
      .collect::<Vec<_>>()
      .into_iter()
      .rev()
      .collect()
  }

  /// Get dialog events.
  pub async fn dialog_messages(&self, limit: usize) -> Vec<DialogEvent> {
    let msgs = self.dialog_log.read().await;
    let start = msgs.len().saturating_sub(limit);
    msgs[start..].to_vec()
  }
}

// -- ContextRef: handle for the high-level Browser API -----------------------

use crate::state::BrowserState;

/// Handle to a browser context. Created by `Browser::new_context()` / `default_context()`.
/// Provides the Playwright-compatible context API by delegating to `BrowserState`.
#[derive(Clone)]
pub struct ContextRef {
  pub(crate) state: Arc<RwLock<BrowserState>>,
  pub(crate) name: Arc<str>,
  /// Pre-parsed session key (avoids re-parsing on every operation).
  pub(crate) key: SessionKey,
  /// Default timeout for actions in this context (ms). 0 = no override.
  default_timeout_ms: u64,
  /// Default navigation timeout in this context (ms). 0 = no override.
  default_navigation_timeout_ms: u64,
}

impl ContextRef {
  pub fn new(state: Arc<RwLock<BrowserState>>, name: String) -> Self {
    let key = SessionKey::parse(&name);
    Self {
      state,
      name: Arc::from(name),
      key,
      default_timeout_ms: 0,
      default_navigation_timeout_ms: 0,
    }
  }

  /// Context name.
  #[must_use]
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Create a new page in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if page creation fails.
  pub async fn new_page(&self) -> Result<Arc<Page>, String> {
    {
      let mut state = self.state.write().await;
      Box::pin(state.ensure_instance(&self.key.instance)).await?;
    }

    let plan = {
      let state = self.state.read().await;
      state.page_open_plan(&self.key)?
    };

    let (any_page, browser_context_id) = if &*self.key.context == "default" {
      (
        Box::pin(plan.browser.new_page(
          "about:blank",
          plan.browser_context_id.as_deref(),
          plan.viewport.as_ref(),
        ))
        .await?,
        None,
      )
    } else if let Some(existing_ctx_id) = plan.browser_context_id.clone() {
      (
        Box::pin(
          plan
            .browser
            .new_page("about:blank", Some(&existing_ctx_id), plan.viewport.as_ref()),
        )
        .await?,
        Some(existing_ctx_id),
      )
    } else {
      let ctx_id = plan.browser.new_context().await?;
      let page = Box::pin(
        plan
          .browser
          .new_page("about:blank", Some(&ctx_id), plan.viewport.as_ref()),
      )
      .await?;
      (page, Some(ctx_id))
    };

    {
      let mut state = self.state.write().await;
      state.register_opened_page(&self.key, any_page.clone(), browser_context_id)?;
    }

    Ok(Page::with_context(any_page, self.clone()))
  }

  /// Get all pages in this context as Page handles.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist.
  pub async fn pages(&self) -> Result<Vec<Arc<Page>>, String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    Ok(
      ctx
        .pages
        .iter()
        .map(|p| Page::with_context(p.clone(), self.clone()))
        .collect(),
    )
  }

  /// Get all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or cookie retrieval fails.
  pub async fn cookies(&self) -> Result<Vec<CookieData>, String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    ctx.cookies().await
  }

  /// Add cookies to this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or setting cookies fails.
  pub async fn add_cookies(&self, cookies: Vec<CookieData>) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    ctx.add_cookies(cookies).await
  }

  /// Clear all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or clearing cookies fails.
  pub async fn clear_cookies(&self) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    ctx.clear_cookies().await
  }

  /// Clear cookies matching the given filters (matches Playwright's `context.clearCookies(options?)`).
  /// If no filters are specified, all cookies are cleared.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or clearing cookies fails.
  pub async fn clear_cookies_filtered(&self, options: &crate::backend::ClearCookieOptions) -> Result<(), String> {
    if options.name.is_none() && options.domain.is_none() && options.path.is_none() {
      return self.clear_cookies().await;
    }
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    let cookies = ctx.cookies().await?;
    if let Some(page) = ctx.active_page() {
      page.clear_cookies().await?;
      for c in cookies {
        let name_match = options.name.as_ref().is_none_or(|n| &c.name == n);
        let domain_match = options.domain.as_ref().is_none_or(|d| &c.domain == d);
        let path_match = options.path.as_ref().is_none_or(|p| &c.path == p);
        if !(name_match && domain_match && path_match) {
          page.set_cookie(c).await?;
        }
      }
    }
    Ok(())
  }

  /// Delete a specific cookie by name and optional domain
  /// (matches Playwright's `context.clearCookies({ name })`).
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or deleting fails.
  pub async fn delete_cookie(&self, name: &str, domain: Option<&str>) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    ctx.delete_cookie(name, domain).await
  }

  /// Set the default timeout for actions in this context (ms).
  pub fn set_default_timeout(&mut self, ms: u64) {
    self.default_timeout_ms = ms;
  }

  /// Set the default navigation timeout for this context (ms).
  pub fn set_default_navigation_timeout(&mut self, ms: u64) {
    self.default_navigation_timeout_ms = ms;
  }

  /// Grant permissions in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context or page does not exist, or granting fails.
  pub async fn grant_permissions(&self, permissions: &[String], origin: Option<&str>) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    if let Some(page) = ctx.active_page() {
      page.grant_permissions(permissions, origin).await
    } else {
      Err("No page in context".into())
    }
  }

  /// Clear all granted permissions.
  ///
  /// # Errors
  ///
  /// Returns an error if resetting permissions fails.
  pub async fn clear_permissions(&self) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    if let Some(page) = ctx.active_page() {
      page.reset_permissions().await
    } else {
      Ok(())
    }
  }

  /// Close this context (remove from `BrowserState`).
  ///
  /// # Errors
  ///
  /// Returns an error if state lock acquisition fails.
  pub async fn close(&self) -> Result<(), String> {
    let mut state = self.state.write().await;
    state.remove_context(&self.name).await;
    Ok(())
  }

  /// Access the internal state (for MCP server integration).
  #[must_use]
  pub fn state(&self) -> &Arc<RwLock<BrowserState>> {
    &self.state
  }

  // ── Context-level APIs (apply to all pages) ────────────────────────────

  /// Add an init script to all pages in this context (current + future).
  /// Returns identifiers for each page.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or script injection fails.
  pub async fn add_init_script(&self, source: &str) -> Result<Vec<String>, String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    let mut ids = Vec::new();
    for page in &ctx.pages {
      ids.push(page.add_init_script(source).await?);
    }
    Ok(ids)
  }

  /// Set geolocation for all pages in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or geolocation emulation fails.
  pub async fn set_geolocation(&self, lat: f64, lng: f64, accuracy: f64) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.set_geolocation(lat, lng, accuracy).await?;
    }
    Ok(())
  }

  /// Set extra HTTP headers for all pages in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or setting headers fails.
  pub async fn set_extra_http_headers(&self, headers: &rustc_hash::FxHashMap<String, String>) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.set_extra_http_headers(headers).await?;
    }
    Ok(())
  }

  /// Set offline mode for all pages in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or network state change fails.
  pub async fn set_offline(&self, offline: bool) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.set_network_state(offline, 0.0, -1.0, -1.0).await?;
    }
    Ok(())
  }

  /// Register a route handler for all pages in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or route registration fails.
  pub async fn route(&self, pattern: &str, handler: crate::route::RouteHandler) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.route(pattern, handler.clone()).await?;
    }
    Ok(())
  }

  /// Remove route handlers matching pattern from all pages.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or route removal fails.
  pub async fn unroute(&self, pattern: &str) -> Result<(), String> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.unroute(pattern).await?;
    }
    Ok(())
  }
}