ferridriver-script 0.4.0

Sandboxed QuickJS scripting engine for ferridriver. Runs JS scripts against Page/Browser/Context with bound args, per-call isolation, scoped fs, and structured errors.
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! QuickJS bindings for `ferridriver::network::{Request, Response, WebSocket}`.
//!
//! Each wrapper is a thin pass-through to the core type per Rule 1.
//! Method names mirror Playwright's `client/network.ts` exactly so
//! scripts use the same `request.url()`, `response.body()`,
//! `webSocket.waitForEvent()` shapes as Playwright tests.

use ferridriver::network::{
  Request as CoreRequest, Response as CoreResponse, WebSocket as CoreWebSocket, WebSocketEvent, WebSocketPayload,
};
use ferridriver::route::{ContinueOverrides, FulfillResponse, Route as CoreRoute};
use rquickjs::{Ctx, JsLifetime, Value, class::Trace};
use std::sync::{Arc, Mutex as StdMutex};

use crate::bindings::convert::{FerriResultExt, serde_from_js, serde_to_js};

// ── RequestJs ────────────────────────────────────────────────────────────────

#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "Request")]
pub struct RequestJs {
  #[qjs(skip_trace)]
  inner: CoreRequest,
  /// Owning page reference, used by `frame()` to resolve frame_id via
  /// the page's frame cache. `None` when the wrapper was constructed
  /// without page context.
  #[qjs(skip_trace)]
  page: Option<Arc<ferridriver::Page>>,
}

impl RequestJs {
  #[must_use]
  pub fn new(inner: CoreRequest) -> Self {
    Self { inner, page: None }
  }

  #[must_use]
  pub fn new_with_page(inner: CoreRequest, page: Arc<ferridriver::Page>) -> Self {
    Self {
      inner,
      page: Some(page),
    }
  }
}

#[rquickjs::methods]
impl RequestJs {
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self.inner.url().to_string()
  }

  #[qjs(rename = "method")]
  pub fn method(&self) -> String {
    self.inner.method().to_string()
  }

  #[qjs(rename = "resourceType")]
  pub fn resource_type(&self) -> String {
    self.inner.resource_type().to_string()
  }

  #[qjs(rename = "isNavigationRequest")]
  pub fn is_navigation_request(&self) -> bool {
    self.inner.is_navigation_request()
  }

  #[qjs(rename = "postData")]
  pub fn post_data(&self) -> Option<String> {
    self.inner.post_data()
  }

  /// Mirrors Playwright `request.postDataBuffer(): Buffer | null`.
  /// QuickJS has no native `Buffer`, so the raw body bytes are returned
  /// base64-encoded (same convention as `response.body()`); `null` when
  /// the request has no post body.
  #[qjs(rename = "postDataBuffer")]
  pub fn post_data_buffer(&self) -> Option<String> {
    self
      .inner
      .post_data_buffer()
      .map(|b| base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b))
  }

  #[qjs(rename = "postDataJSON")]
  pub fn post_data_json<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let v = self.inner.post_data_json().into_js()?;
    let v = v.unwrap_or(serde_json::Value::Null);
    serde_to_js(&ctx, &v)
  }

  #[qjs(rename = "headers")]
  pub fn headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    serde_to_js(&ctx, &self.inner.headers())
  }

  #[qjs(rename = "headersArray")]
  pub async fn headers_array<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let arr = self.inner.headers_array().await;
    let pairs: Vec<(String, String)> = arr.into_iter().map(|h| (h.name, h.value)).collect();
    crate::bindings::convert::name_value_array_to_js(&ctx, &pairs)
  }

  #[qjs(rename = "allHeaders")]
  pub async fn all_headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let h = self.inner.all_headers().await.into_js()?;
    serde_to_js(&ctx, &h)
  }

  #[qjs(rename = "headerValue")]
  pub async fn header_value(&self, name: String) -> rquickjs::Result<Option<String>> {
    self.inner.header_value(&name).await.into_js()
  }

  #[qjs(rename = "failure")]
  pub fn failure<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    match self.inner.failure() {
      Some(error_text) => {
        let o = rquickjs::Object::new(ctx.clone())?;
        o.set("errorText", error_text)?;
        Ok(o.into_value())
      },
      None => Ok(Value::new_null(ctx.clone())),
    }
  }

  #[qjs(rename = "timing")]
  pub fn timing<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    serde_to_js(&ctx, &self.inner.timing())
  }

  #[qjs(rename = "sizes")]
  pub async fn sizes<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let sizes = self.inner.sizes().await.into_js()?;
    serde_to_js(&ctx, &sizes)
  }

  #[qjs(rename = "redirectedFrom")]
  pub fn redirected_from(&self) -> Option<RequestJs> {
    self.inner.redirected_from().map(|r| match self.page.as_ref() {
      Some(page) => RequestJs::new_with_page(r, page.clone()),
      None => RequestJs::new(r),
    })
  }

  #[qjs(rename = "redirectedTo")]
  pub fn redirected_to(&self) -> Option<RequestJs> {
    self.inner.redirected_to().map(|r| match self.page.as_ref() {
      Some(page) => RequestJs::new_with_page(r, page.clone()),
      None => RequestJs::new(r),
    })
  }

  #[qjs(rename = "response")]
  pub async fn response(&self) -> rquickjs::Result<Option<ResponseJs>> {
    let resp = self.inner.response().await.into_js()?;
    Ok(resp.map(|r| match self.page.as_ref() {
      Some(page) => ResponseJs::new_with_page(r, page.clone()),
      None => ResponseJs::new(r),
    }))
  }

  /// Mirrors Playwright `request.frame(): Frame`. Resolves the
  /// initiating frame_id via the owning page's frame cache. Returns
  /// `null` when no frame context is attached.
  #[qjs(rename = "frame")]
  pub fn frame(&self) -> Option<crate::bindings::frame::FrameJs> {
    let page = self.page.as_ref()?;
    let frame_id = self.inner.frame_id()?;
    for f in page.frames() {
      if f.frame_id() == frame_id {
        return Some(crate::bindings::frame::FrameJs::new(f));
      }
    }
    None
  }

  /// Mirrors Playwright `request.serviceWorker(): Worker | null`.
  /// Backed by `Request::service_worker` which always returns `None`
  /// today (Tier-2 §2.7 hasn't landed). Surface kept stable so flipping
  /// the implementation on later is non-breaking.
  #[qjs(rename = "serviceWorker")]
  pub fn service_worker<'js>(&self, ctx: Ctx<'js>) -> Value<'js> {
    // Query the core accessor so this stays self-aware once §2.7 fills
    // in the Worker class — the binding then maps `Some(worker)` to a
    // real WorkerJs instance.
    let _ = self.inner.service_worker();
    Value::new_null(ctx)
  }
}

// ── ResponseJs ───────────────────────────────────────────────────────────────

#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "Response")]
pub struct ResponseJs {
  #[qjs(skip_trace)]
  inner: CoreResponse,
  #[qjs(skip_trace)]
  page: Option<Arc<ferridriver::Page>>,
}

impl ResponseJs {
  #[must_use]
  pub fn new(inner: CoreResponse) -> Self {
    Self { inner, page: None }
  }

  #[must_use]
  pub fn new_with_page(inner: CoreResponse, page: Arc<ferridriver::Page>) -> Self {
    Self {
      inner,
      page: Some(page),
    }
  }
}

#[rquickjs::methods]
impl ResponseJs {
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self.inner.url().to_string()
  }

  #[qjs(rename = "status")]
  pub fn status(&self) -> i32 {
    i32::try_from(self.inner.status()).unwrap_or(i32::MAX)
  }

  #[qjs(rename = "statusText")]
  pub fn status_text(&self) -> String {
    self.inner.status_text().to_string()
  }

  #[qjs(rename = "ok")]
  pub fn ok(&self) -> bool {
    self.inner.ok()
  }

  #[qjs(rename = "fromServiceWorker")]
  pub fn is_from_service_worker(&self) -> bool {
    self.inner.is_from_service_worker()
  }

  #[qjs(rename = "headers")]
  pub fn headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    serde_to_js(&ctx, &self.inner.headers())
  }

  #[qjs(rename = "allHeaders")]
  pub async fn all_headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let h = self.inner.all_headers().await.into_js()?;
    serde_to_js(&ctx, &h)
  }

  #[qjs(rename = "headersArray")]
  pub async fn headers_array<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let arr = self.inner.headers_array().await;
    let pairs: Vec<(String, String)> = arr.into_iter().map(|h| (h.name, h.value)).collect();
    crate::bindings::convert::name_value_array_to_js(&ctx, &pairs)
  }

  #[qjs(rename = "headerValue")]
  pub async fn header_value(&self, name: String) -> rquickjs::Result<Option<String>> {
    self.inner.header_value(&name).await.into_js()
  }

  #[qjs(rename = "headerValues")]
  pub async fn header_values(&self, name: String) -> rquickjs::Result<Vec<String>> {
    self.inner.header_values(&name).await.into_js()
  }

  /// Response body as base64-encoded string. QuickJS does not have
  /// `Buffer`; scripts decode if they need raw bytes.
  #[qjs(rename = "body")]
  pub async fn body<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let bytes = self.inner.body().await.into_js()?;
    let encoded = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes);
    serde_to_js(&ctx, &encoded)
  }

  #[qjs(rename = "text")]
  pub async fn text(&self) -> rquickjs::Result<String> {
    self.inner.text().await.into_js()
  }

  #[qjs(rename = "json")]
  pub async fn json<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    // Body -> JS via QuickJS's C JSON parser; no serde_json::Value
    // middle allocation, no dependence on the JS `JSON` global.
    let text = self.inner.text().await.into_js()?;
    ctx.json_parse(text)
  }

  /// Mirrors Playwright `response.finished()`. Resolves to `null` on
  /// success, throws on failure.
  #[qjs(rename = "finished")]
  pub async fn finished<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    match self.inner.finished().await {
      Ok(()) => Ok(Value::new_null(ctx.clone())),
      Err(e) => Err(rquickjs::Error::new_from_js_message(
        "Response.finished failure",
        "Error",
        e.to_string(),
      )),
    }
  }

  #[qjs(rename = "serverAddr")]
  pub async fn server_addr<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    match self.inner.server_addr().await {
      Some(a) => {
        let o = rquickjs::Object::new(ctx.clone())?;
        o.set("ipAddress", a.ip_address)?;
        o.set("port", a.port)?;
        Ok(o.into_value())
      },
      None => Ok(Value::new_null(ctx.clone())),
    }
  }

  #[qjs(rename = "securityDetails")]
  pub async fn security_details<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    match self.inner.security_details().await {
      Some(s) => serde_to_js(&ctx, &s),
      None => Ok(Value::new_null(ctx.clone())),
    }
  }

  /// Mirrors Playwright `response.httpVersion(): Promise<string>`.
  /// Empty string when the backend did not report a protocol version.
  #[qjs(rename = "httpVersion")]
  pub async fn http_version(&self) -> String {
    self.inner.http_version().await.unwrap_or_default()
  }

  #[qjs(rename = "request")]
  pub fn request(&self) -> RequestJs {
    match self.page.as_ref() {
      Some(page) => RequestJs::new_with_page(self.inner.request(), page.clone()),
      None => RequestJs::new(self.inner.request()),
    }
  }

  /// Mirrors Playwright `response.frame(): Frame`. Convenience for
  /// `response.request().frame()`.
  #[qjs(rename = "frame")]
  pub fn frame(&self) -> Option<crate::bindings::frame::FrameJs> {
    self.request().frame()
  }
}

// ── WebSocketJs ──────────────────────────────────────────────────────────────

#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "WebSocket")]
pub struct WebSocketJs {
  #[qjs(skip_trace)]
  inner: CoreWebSocket,
}

impl WebSocketJs {
  #[must_use]
  pub fn new(inner: CoreWebSocket) -> Self {
    Self { inner }
  }
}

#[rquickjs::methods]
impl WebSocketJs {
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self.inner.url().to_string()
  }

  #[qjs(rename = "isClosed")]
  pub fn is_closed(&self) -> bool {
    self.inner.is_closed()
  }

  /// Mirrors Playwright `webSocket.waitForEvent(event, options?)`.
  /// Resolves with `{ event, payload, error }`.
  #[qjs(rename = "waitForEvent")]
  pub async fn wait_for_event<'js>(
    &self,
    ctx: Ctx<'js>,
    event: String,
    timeout_ms: Option<f64>,
  ) -> rquickjs::Result<Value<'js>> {
    let timeout = std::time::Duration::from_millis(
      #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
      {
        timeout_ms.unwrap_or(30000.0) as u64
      },
    );
    let mut rx = self.inner.subscribe();
    let event_lc = event.to_ascii_lowercase();
    let deadline = tokio::time::Instant::now() + timeout;
    loop {
      let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
      if remaining.is_zero() {
        return Err(rquickjs::Error::new_from_js_message(
          "WebSocket.waitForEvent",
          "TimeoutError",
          format!(
            "Timeout {}ms exceeded while waiting for WebSocket event {event:?}",
            timeout.as_millis()
          ),
        ));
      }
      match tokio::time::timeout(remaining, rx.recv()).await {
        Ok(Ok(ev)) => {
          if let Some(v) = ws_event_to_js(&ctx, &event_lc, &ev)? {
            return Ok(v);
          }
        },
        Ok(Err(_)) => {
          return Err(rquickjs::Error::new_from_js_message(
            "WebSocket.waitForEvent",
            "Error",
            "WebSocket channel closed".to_string(),
          ));
        },
        Err(_) => {
          return Err(rquickjs::Error::new_from_js_message(
            "WebSocket.waitForEvent",
            "TimeoutError",
            format!(
              "Timeout {}ms exceeded while waiting for WebSocket event {event:?}",
              timeout.as_millis()
            ),
          ));
        },
      }
    }
  }
}

/// Build the `{ event, payload, error }` JS object for a matched
/// WebSocket event directly — no serde_json::Value middle allocation.
fn ws_event_to_js<'js>(ctx: &Ctx<'js>, name: &str, ev: &WebSocketEvent) -> rquickjs::Result<Option<Value<'js>>> {
  let make = |event: &str, payload: Value<'js>, error: Value<'js>| -> rquickjs::Result<Value<'js>> {
    let o = rquickjs::Object::new(ctx.clone())?;
    o.set("event", event)?;
    o.set("payload", payload)?;
    o.set("error", error)?;
    Ok(o.into_value())
  };
  let null = || Value::new_null(ctx.clone());
  let js_str =
    |s: &str| -> rquickjs::Result<Value<'js>> { Ok(rquickjs::String::from_str(ctx.clone(), s)?.into_value()) };
  let payload = |p: &WebSocketPayload| -> rquickjs::Result<Value<'js>> {
    match p {
      WebSocketPayload::Text(s) => js_str(s),
      WebSocketPayload::Binary(b) => js_str(&base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b)),
    }
  };
  Ok(match (name, ev) {
    ("framesent", WebSocketEvent::FrameSent(p)) => Some(make("framesent", payload(p)?, null())?),
    ("framereceived", WebSocketEvent::FrameReceived(p)) => Some(make("framereceived", payload(p)?, null())?),
    ("socketerror", WebSocketEvent::Error(msg)) => Some(make("socketerror", null(), js_str(msg)?)?),
    ("close", WebSocketEvent::Close) => Some(make("close", null(), null())?),
    _ => None,
  })
}

// ── RouteJs ──────────────────────────────────────────────────────────────────
//
// Mirrors Playwright's `Route` interface: `fulfill`, `continue`, `abort`,
// plus the `request()` getter. The handler-callback path (registering
// the JS function with `page.route(matcher, fn)`) lives in `bindings/page.rs`
// — `RouteJs` itself is the per-invocation wrapper passed into the
// handler.

#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "Route")]
pub struct RouteJs {
  #[qjs(skip_trace)]
  inner: StdMutex<Option<CoreRoute>>,
}

/// `Request` returned by `route.request()` (Playwright parity) — a
/// read-only snapshot of the intercepted request's url / method /
/// headers / postData / resourceType so handlers can `route.request()
/// .headers()['x-foo']` exactly like Playwright code does.
#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "RouteRequest")]
pub struct RouteRequestJs {
  #[qjs(skip_trace)]
  url: String,
  #[qjs(skip_trace)]
  method: String,
  #[qjs(skip_trace)]
  headers: rustc_hash::FxHashMap<String, String>,
  #[qjs(skip_trace)]
  post_data: Option<String>,
  #[qjs(skip_trace)]
  resource_type: String,
}

#[rquickjs::methods]
impl RouteRequestJs {
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self.url.clone()
  }
  #[qjs(rename = "method")]
  pub fn method(&self) -> String {
    self.method.clone()
  }
  /// Playwright: `request.headers(): Record<string, string>`.
  #[qjs(rename = "headers")]
  pub fn headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    serde_to_js(&ctx, &self.headers)
  }
  /// Playwright: `request.headersArray(): { name, value }[]`.
  #[qjs(rename = "headersArray")]
  pub fn headers_array<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let pairs: Vec<(&str, &str)> = self.headers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    crate::bindings::convert::name_value_array_to_js(&ctx, &pairs)
  }
  /// Playwright: `request.headerValue(name): Promise<string | null>`.
  #[qjs(rename = "headerValue")]
  pub fn header_value(&self, name: String) -> Option<String> {
    let lower = name.to_ascii_lowercase();
    self
      .headers
      .iter()
      .find(|(k, _)| k.to_ascii_lowercase() == lower)
      .map(|(_, v)| v.clone())
  }
  #[qjs(rename = "postData")]
  pub fn post_data(&self) -> Option<String> {
    self.post_data.clone()
  }
  #[qjs(rename = "resourceType")]
  pub fn resource_type(&self) -> String {
    self.resource_type.clone()
  }
}

impl RouteJs {
  /// Construct a wrapper around a paused-route handle. The handle is
  /// consumed on the first call to `fulfill` / `continue` / `abort`;
  /// subsequent calls become no-ops. If the JS callback returns
  /// without invoking any of the three, the inner [`CoreRoute`]'s
  /// own `Drop` falls open and continues the request.
  #[must_use]
  pub fn new(inner: CoreRoute) -> Self {
    Self {
      inner: StdMutex::new(Some(inner)),
    }
  }
}

/// WHATWG/Playwright `Headers` — `{ [name: string]: string }` record.
/// Deserialised as a map then flattened to pairs at the call site so
/// the core API (which takes `Vec<(String, String)>`) sees the
/// expected shape. Accepting the record is REQUIRED for Playwright
/// parity: `route.fulfill({ headers: { 'x-from': 'route' } })` is
/// the documented form (see `client/network.ts`).
type JsHeadersMap = std::collections::BTreeMap<String, String>;

#[derive(serde::Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase", default)]
struct JsFulfillOptions {
  status: Option<i32>,
  body: Option<String>,
  content_type: Option<String>,
  headers: Option<JsHeadersMap>,
}

#[derive(serde::Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase", default)]
struct JsContinueOptions {
  url: Option<String>,
  method: Option<String>,
  headers: Option<JsHeadersMap>,
  post_data: Option<String>,
}

/// Lower the Playwright `Headers` record (`{name: value}`) the bindings
/// accept down to the `Vec<(String, String)>` core expects.
fn headers_to_pairs(map: Option<JsHeadersMap>) -> Vec<(String, String)> {
  map.map(|m| m.into_iter().collect()).unwrap_or_default()
}

#[rquickjs::methods]
impl RouteJs {
  /// Playwright: `route.request(): Request` — the intercepted request,
  /// inspectable as a real Request class (`.url()`, `.method()`,
  /// `.headers()`, `.headerValue(name)`, `.headersArray()`,
  /// `.postData()`, `.resourceType()`). LLM-generated Playwright code
  /// uses `route.request().headers()['x-foo']` constantly; previously
  /// `route.request` was undefined and the handler silently threw,
  /// falling through to the network (`Failed to fetch`).
  #[qjs(rename = "request")]
  pub fn request(&self) -> RouteRequestJs {
    let snap = self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().map(|r| r.request().clone()));
    if let Some(r) = snap {
      RouteRequestJs {
        url: r.url,
        method: r.method,
        headers: r.headers,
        post_data: r.post_data,
        resource_type: r.resource_type,
      }
    } else {
      RouteRequestJs {
        url: String::new(),
        method: String::new(),
        headers: rustc_hash::FxHashMap::default(),
        post_data: None,
        resource_type: String::new(),
      }
    }
  }

  /// Mirrors Playwright `route.url(): string`.
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().map(|r| r.request().url.clone()))
      .unwrap_or_default()
  }

  /// Mirrors Playwright `route.request().method()`.
  #[qjs(rename = "method")]
  pub fn method(&self) -> String {
    self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().map(|r| r.request().method.clone()))
      .unwrap_or_default()
  }

  /// Mirrors Playwright `route.request().resourceType()`.
  #[qjs(rename = "resourceType")]
  pub fn resource_type(&self) -> String {
    self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().map(|r| r.request().resource_type.clone()))
      .unwrap_or_default()
  }

  /// Mirrors Playwright `route.request().postData(): string | null`.
  #[qjs(rename = "postData")]
  pub fn post_data(&self) -> Option<String> {
    self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().and_then(|r| r.request().post_data.clone()))
  }

  /// Headers as a plain JS object (`Record<string, string>`).
  #[qjs(rename = "headers")]
  pub fn headers<'js>(&self, ctx: Ctx<'js>) -> rquickjs::Result<Value<'js>> {
    let map: rustc_hash::FxHashMap<String, String> = self
      .inner
      .lock()
      .ok()
      .and_then(|g| g.as_ref().map(|r| r.request().headers.clone()))
      .unwrap_or_default();
    serde_to_js(&ctx, &map)
  }

  /// Mirrors Playwright `route.fulfill(options?)`.
  #[qjs(rename = "fulfill")]
  pub fn fulfill<'js>(&self, ctx: Ctx<'js>, options: rquickjs::function::Opt<Value<'js>>) -> rquickjs::Result<()> {
    let opts: JsFulfillOptions = match options.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => serde_from_js(&ctx, v)?,
      _ => JsFulfillOptions::default(),
    };
    let route = self
      .inner
      .lock()
      .ok()
      .and_then(|mut g| g.take())
      .ok_or_else(|| rquickjs::Error::new_from_js_message("Route", "Error", "Route already handled".to_string()))?;
    let mut headers: Vec<(String, String)> = headers_to_pairs(opts.headers);
    if let Some(ct) = opts.content_type.clone() {
      if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
        headers.push(("content-type".to_string(), ct));
      }
    }
    let body_bytes = opts.body.unwrap_or_default().into_bytes();
    route.fulfill(FulfillResponse {
      status: opts.status.unwrap_or(200),
      headers,
      body: body_bytes,
      content_type: opts.content_type,
    });
    Ok(())
  }

  /// Mirrors Playwright `route.continue(options?)`.
  #[qjs(rename = "continue")]
  pub fn continue_<'js>(&self, ctx: Ctx<'js>, options: rquickjs::function::Opt<Value<'js>>) -> rquickjs::Result<()> {
    let opts: JsContinueOptions = match options.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => serde_from_js(&ctx, v)?,
      _ => JsContinueOptions::default(),
    };
    let route = self
      .inner
      .lock()
      .ok()
      .and_then(|mut g| g.take())
      .ok_or_else(|| rquickjs::Error::new_from_js_message("Route", "Error", "Route already handled".to_string()))?;
    route.continue_route(ContinueOverrides {
      url: opts.url,
      method: opts.method,
      headers: opts.headers.map(|m| m.into_iter().collect()),
      post_data: opts.post_data.map(String::into_bytes),
    });
    Ok(())
  }

  /// Mirrors Playwright `route.fallback(options?)`
  /// (`client/network.ts`): hand the request to the next matching
  /// handler with the given overrides applied. ferridriver dispatches a
  /// single handler per matched route, so `fallback` resolves the route
  /// by continuing the request with the overrides applied (with no
  /// overrides this is the unmodified request, matching the end state
  /// Playwright's `fallback` reaches once no further handler claims it).
  #[qjs(rename = "fallback")]
  pub fn fallback<'js>(&self, ctx: Ctx<'js>, options: rquickjs::function::Opt<Value<'js>>) -> rquickjs::Result<()> {
    let opts: JsContinueOptions = match options.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => serde_from_js(&ctx, v)?,
      _ => JsContinueOptions::default(),
    };
    let route = self
      .inner
      .lock()
      .ok()
      .and_then(|mut g| g.take())
      .ok_or_else(|| rquickjs::Error::new_from_js_message("Route", "Error", "Route already handled".to_string()))?;
    route.fallback(ContinueOverrides {
      url: opts.url,
      method: opts.method,
      headers: opts.headers.map(|m| m.into_iter().collect()),
      post_data: opts.post_data.map(String::into_bytes),
    });
    Ok(())
  }

  /// Mirrors Playwright `route.abort(errorCode?)`.
  #[qjs(rename = "abort")]
  pub fn abort(&self, error_code: Option<String>) -> rquickjs::Result<()> {
    let route = self
      .inner
      .lock()
      .ok()
      .and_then(|mut g| g.take())
      .ok_or_else(|| rquickjs::Error::new_from_js_message("Route", "Error", "Route already handled".to_string()))?;
    route.abort(&error_code.unwrap_or_else(|| "blockedbyclient".to_string()));
    Ok(())
  }
}