Skip to content

The headless browser for AI agents and web scraping

1.2 MB
Raw Blame
use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};

use deno_core::{JsRuntime, RuntimeOptions, v8};
use obscura_dom::{DomTree, NodeId};
#[cfg(feature = "render")]
use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};

/// Re-exported so other crates (obscura-browser, obscura-cdp) can name the V8
/// isolate handle without taking a direct dependency on deno_core.
pub use deno_core::v8::IsolateHandle;

use crate::import_map::ImportMap;
use crate::module_loader::{ModuleLoadActivity, ObscuraModuleLoader};
#[cfg(all(test, feature = "render"))]
use crate::ops::ensure_prepared_render;
use crate::ops::{
    ObscuraState, OriginStorage, RuntimeEvent, StoredNetworkResponseBody,
    begin_animation_task, build_extension, node_is_script,
};
#[cfg(feature = "render")]
use crate::ops::{
    clamp_scroll_offset, document_base_url, ensure_resolved_scroll,
};

#[cfg(feature = "render")]
struct RuntimeCanvasSurfaceSource<'a>(&'a HashMap<NodeId, crate::ops::CanvasBackingSurface>);

#[cfg(feature = "render")]
impl obscura_render::CanvasSurfaceSource for RuntimeCanvasSurfaceSource<'_> {
    fn surface(&self, node: NodeId) -> Option<obscura_render::CanvasSurface<'_>> {
        let surface = self.0.get(&node)?;
        obscura_render::CanvasSurface::from_rgba8(
            surface.width,
            surface.height,
            surface.pixels.as_ref(),
        )
    }
}

static SNAPSHOT: &[u8] = include_bytes!(env!("OBSCURA_SNAPSHOT_PATH"));

/// Serialize first initialization (#430), then allow two snapshot restorations
/// at a time. Unbounded construction increases CPU and peak memory contention.
static ISOLATE_CREATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
static ISOLATE_CREATE_SECOND_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
static NEXT_ISOLATE_CREATE_SLOT: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);
static ISOLATE_INITIALIZED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);
static NEXT_CDP_OBJECT_ID: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(1);
#[cfg(test)]
static CLASSIC_CODE_CACHE_ACCEPTED: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

struct ClassicCodeCacheEntry {
    origin: String,
    name: String,
    source: String,
    data: std::sync::Arc<[u8]>,
}

impl ClassicCodeCacheEntry {
    fn bytes(&self) -> usize {
        self.origin.len() + self.name.len() + self.source.len() + self.data.len()
    }
}

const CLASSIC_CODE_CACHE_BYTES: usize = 32 * 1024 * 1024;
// ponytail: bounded FIFO; only add LRU bookkeeping if eviction profiles justify it.
static CLASSIC_CODE_CACHE: std::sync::Mutex<std::collections::VecDeque<ClassicCodeCacheEntry>> =
    std::sync::Mutex::new(std::collections::VecDeque::new());

fn cached_classic_code(origin: &str, name: &str, source: &str) -> Option<std::sync::Arc<[u8]>> {
    let cache = CLASSIC_CODE_CACHE.lock().unwrap_or_else(|error| error.into_inner());
    cache.iter().rev().find(|entry| {
        entry.origin == origin && entry.name == name && entry.source == source
    }).map(|entry| entry.data.clone())
}

fn remember_classic_code(origin: &str, name: &str, source: &str, data: &[u8]) {
    let bytes = origin.len() + name.len() + source.len() + data.len();
    if bytes > CLASSIC_CODE_CACHE_BYTES {
        return;
    }
    let mut cache = CLASSIC_CODE_CACHE.lock().unwrap_or_else(|error| error.into_inner());
    cache.retain(|entry| entry.origin != origin || entry.name != name);
    let mut used = cache.iter().map(ClassicCodeCacheEntry::bytes).sum::<usize>();
    while used + bytes > CLASSIC_CODE_CACHE_BYTES || cache.len() >= 64 {
        let Some(old) = cache.pop_front() else { break };
        used -= old.bytes();
    }
    cache.push_back(ClassicCodeCacheEntry {
        origin: origin.to_string(), name: name.to_string(), source: source.to_string(),
        data: std::sync::Arc::from(data),
    });
}

/// Enter a tokio runtime context when the caller is not already in one.
///
/// deno_core registers each isolate with the tokio handle current at
/// `JsRuntime::new` time and aborts the process if V8 posts a delayed
/// foreground task (GC memory reducer, idle tasks) while no handle is
/// registered. Normal callers (CLI, CDP, MCP) run inside tokio, but plain
/// `#[test]`s and non-tokio embedders do not, so fall back to a
/// process-wide single-worker runtime kept alive for the whole process.
/// The guard must stay in scope across `JsRuntime::new`; the registered
/// handle outlives it.
fn enter_tokio_context() -> Option<tokio::runtime::EnterGuard<'static>> {
    if tokio::runtime::Handle::try_current().is_ok() {
        return None;
    }
    static FALLBACK: std::sync::LazyLock<tokio::runtime::Runtime> =
        std::sync::LazyLock::new(|| {
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(1)
                .enable_time()
                .build()
                .expect("fallback tokio runtime")
        });
    Some(FALLBACK.enter())
}

#[doc(hidden)]
pub const DEFAULT_CDP_AWAIT_TIMEOUT_MS: u64 = 30_000;
const HEAP_LIMIT_RECOVERY_HEADROOM_BYTES: usize = 64 * 1024 * 1024;
#[cfg(feature = "render")]
const MAX_PENDING_RENDER_RESOURCES: usize = 128;

#[cfg(feature = "render")]
fn page_render_resource_url_allowed(document_url: &str, resource_url: &str) -> bool {
    url::Url::parse(resource_url)
        .map(|resource| match resource.scheme() {
            "http" | "https" => true,
            "file" => url::Url::parse(document_url)
                .map(|document| document.scheme() == "file")
                .unwrap_or(false),
            _ => false,
        })
        .unwrap_or(false)
}

#[derive(Default)]
struct HeapLimitState {
    tripped: std::sync::atomic::AtomicBool,
    restore_limit: std::sync::atomic::AtomicUsize,
}

fn install_heap_limit_guard(
    runtime: &mut JsRuntime,
    isolate_handle: IsolateHandle,
    state: std::sync::Arc<HeapLimitState>,
) {
    runtime.add_near_heap_limit_callback(move |current_limit, _initial_limit| {
        let _ = state.restore_limit.compare_exchange(
            0,
            current_limit,
            std::sync::atomic::Ordering::SeqCst,
            std::sync::atomic::Ordering::SeqCst,
        );
        state
            .tripped
            .store(true, std::sync::atomic::Ordering::SeqCst);
        isolate_handle.terminate_execution();
        current_limit.saturating_add(HEAP_LIMIT_RECOVERY_HEADROOM_BYTES)
    });
}

fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> &str {
    payload
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| payload.downcast_ref::<&'static str>().copied())
        .unwrap_or("unknown panic")
}

/// Whether an event-loop task error is fatal to the page or page-local noise.
/// deno_core reports a task's uncaught exception and an unhandled promise
/// rejection as an event-loop error, but a browser treats both as page-local:
/// window.onerror / unhandledrejection fire and later tasks still run. Only
/// engine-level failures (watchdog termination, the heap cap, an exhausted
/// task budget) make the loop itself unusable. (#699)
pub fn is_fatal_event_loop_error(error: &str) -> bool {
    error.contains("execution terminated")
        || error.contains("heap limit exceeded")
        || error.contains("task budget")
}

#[cfg(feature = "render")]
fn with_sync_render_loading_disabled<R>(
    state: &mut ObscuraState,
    capture: impl FnOnce(&mut ObscuraState) -> R,
) -> R {
    let previous = state.render_resources.set_sync_loading_enabled(false);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| capture(state)));
    state.render_resources.set_sync_loading_enabled(previous);
    match result {
        Ok(value) => value,
        Err(payload) => std::panic::resume_unwind(payload),
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct AccessibilityStyle {
    pub display_none: bool,
    pub visibility_hidden: Option<bool>,
}

#[doc(hidden)]
#[derive(Debug)]
pub enum HistoryUpdate {
    Url(String),
    Entries {
        url: String,
        start: usize,
        index: usize,
        old_length: usize,
        truncate_forward: bool,
        first: usize,
        urls: Vec<String>,
    },
}

#[derive(Debug, Clone)]
pub struct RemoteObjectInfo {
    /// True when this object is a value that was thrown or that a promise
    /// rejected with, rather than the evaluation result. CDP reports those
    /// through `exceptionDetails` on a successful reply, so the difference
    /// has to survive the trip out of the runtime.
    pub thrown: bool,
    pub js_type: String,
    pub subtype: Option<String>,
    pub class_name: String,
    pub description: String,
    pub object_id: Option<String>,
    pub value: Option<serde_json::Value>,
    pub unserializable_value: Option<String>,
}

/// A started CDP command, so the browser can service frame work while awaiting it.
#[doc(hidden)]
pub enum CdpEvaluation {
    Complete(RemoteObjectInfo),
    Pending(PendingCdpEvaluation),
}

#[doc(hidden)]
pub struct PendingCdpEvaluation {
    object_id: String,
    recipe: Option<String>,
    // A numeric frame id can be reused after its realm is retired.
    frame: Option<(u32, v8::Global<v8::Context>)>,
}

/// CDP remote objects that can be rebuilt when a page's V8 runtime is
/// temporarily replaced during tab switching.
///
/// Obscura currently keeps one entered isolate per connection. Switching tabs
/// therefore rebuilds the target page's runtime, but CDP clients reasonably
/// expect handles returned by `Runtime.evaluate` to remain usable. Retaining
/// the originating expressions lets the page restore a handle on demand under
/// the same id without retaining a second isolate.
#[derive(Default)]
pub struct CdpObjectState {
    object_counter: u64,
    evaluation_recipes: HashMap<String, String>,
}

struct CdpObjectRecord {
    retrieval: String,
    // The evaluation world can differ from the value's creation realm.
    frame: Option<(u32, v8::Global<v8::Context>)>,
}

pub struct ObscuraJsRuntime {
    state: Rc<RefCell<ObscuraState>>,
    object_store: HashMap<String, CdpObjectRecord>,
    evaluation_recipes: HashMap<String, String>,
    object_counter: u64,
    import_map: Rc<RefCell<ImportMap>>,
    /// Loader-owned signal for pending dynamic-import graph fetches. This is
    /// intentionally separate from page fetch/XHR activity so analytics does
    /// not hold screenshot readiness open.
    module_load_activity: std::sync::Arc<ModuleLoadActivity>,
    /// Thread-safe handle to this runtime's V8 isolate, captured at
    /// construction. Lets a watchdog be armed from `&self` (the CDP dispatcher
    /// only holds `&Page` on the hot path) and is stable for the isolate's life.
    isolate_handle: IsolateHandle,
    /// Signals that V8 approached its configured heap limit. The callback
    /// terminates the current script and temporarily raises the limit just
    /// enough for V8 to unwind instead of aborting the worker process.
    heap_limit_state: std::sync::Arc<HeapLimitState>,
    /// Browser module-map evaluation is idempotent. deno_core 0.350 asserts if
    /// the same ModuleId is evaluated twice, so retain the first outcome for
    /// duplicate script tags and roots already seen by Obscura.
    module_evaluations: HashMap<deno_core::ModuleId, Result<(), String>>,
    /// Append-only record owned by the module loader. A cursor around each
    /// graph load identifies the dependency specifiers that become evaluated
    /// with its root.
    loaded_module_specifiers: Rc<RefCell<Vec<String>>>,
    /// Successful graph evaluation also evaluates every dependency. Remember
    /// those URLs so a dependency later encountered as a top-level script is a
    /// browser-style no-op instead of a second deno_core `mod_evaluate` call.
    evaluated_module_specifiers: HashMap<String, Result<(), String>>,
    /// The bound op table, taken from bootstrap at construction and removed from
    /// the global in the same step. Child frame realms are handed this object so
    /// their shims can call ops; nothing else can reach it, including page
    /// script.
    ops_handoff: Option<deno_core::v8::Global<deno_core::v8::Value>>,
    // Pending commands are runtime-owned, not client handles that releaseObjectGroup can discard.
    pending_cdp_evaluations: HashMap<String, v8::Global<v8::Value>>,
    // Keep the runtime last: custom `Drop` enters its isolate, then every
    // V8-backed field above is released before `OwnedIsolate` performs the
    // matching exit and disposes the isolate.
    js_runtime: JsRuntime,
}

/// Renders a caught V8 exception as a message for realm evaluation errors.
fn exception_text(
    scope: &mut v8::PinnedRef<'_, v8::TryCatch<'_, '_, v8::HandleScope<'_>>>,
) -> String {
    match scope.exception() {
        Some(exception) => exception.to_rust_string_lossy(scope),
        None => "unknown error".to_string(),
    }
}

fn cdp_result_record<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    value: v8::Local<'s, v8::Value>,
    rejected: bool,
    await_promise: bool,
) -> Result<v8::Global<v8::Value>, String> {
    let should_await = await_promise && !rejected;
    let pending = v8::Object::new(scope);
    let done = v8::Boolean::new(scope, !should_await);
    let rejected = v8::Boolean::new(scope, rejected);
    let initial_value = if should_await { v8::undefined(scope).into() } else { value };
    for (name, value) in [
        ("done", done.into()), ("rejected", rejected.into()), ("value", initial_value),
    ] {
        let key = v8::String::new(scope, name).ok_or("CDP result key allocation failed")?;
        if pending.create_data_property(scope, key.into(), value) != Some(true) {
            return Err("CDP result allocation failed".into());
        }
    }
    if should_await {
        // Await uses the intrinsic Promise and assimilates thenables.
        let source = v8::String::new(scope, r#"(async function(value, pending) {
            try { pending.value = await value; }
            catch (error) { pending.value = error; pending.rejected = true; }
            pending.done = true;
        })"#).ok_or("CDP await allocation failed")?;
        let function = v8::Script::compile(scope, source, None)
            .and_then(|script| script.run(scope))
            .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
            .ok_or("Cannot initialize awaited CDP result")?;
        let receiver = v8::undefined(scope).into();
        function.call(scope, receiver, &[value, pending.into()])
            .ok_or("Cannot await CDP result")?;
    }
    let pending: v8::Local<v8::Value> = pending.into();
    Ok(v8::Global::new(scope, pending))
}

/// A fetched and instantiated module graph whose evaluation is intentionally
/// delayed until the HTML script scheduler reaches its post-parse turn.
pub struct PreparedModule {
    module_id: deno_core::ModuleId,
    description: String,
    entry_specifier: Option<String>,
    graph_specifiers: Vec<String>,
}

/// Embed a string as a JS string literal — double-quoted, with backslash,
/// quotes, and control characters (newline, CR, NUL) escaped — for safe
/// interpolation into generated script. Mirrors `object_id_literal` in
/// obscura-cdp; a hand-rolled `replace('\'', ...)` misses backslashes and
/// control chars, which either breaks out of the literal or SyntaxErrors.
fn js_string_literal(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string())
}

/// The values CDP allows in `RemoteObject.unserializableValue` /
/// `CallArgument.unserializableValue`: the non-JSON numbers and a bigint
/// literal. Used to keep that field from acting as an implicit eval.
fn is_cdp_unserializable_value(value: &str) -> bool {
    if matches!(value, "Infinity" | "-Infinity" | "NaN" | "-0") {
        return true;
    }
    value
        .strip_suffix('n')
        .map(|digits| digits.strip_prefix('-').unwrap_or(digits))
        .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
}

fn remaining_deadline_ms(deadline: tokio::time::Instant) -> Option<u64> {
    let remaining = deadline.checked_duration_since(tokio::time::Instant::now())?;
    if remaining.is_zero() {
        return None;
    }
    // Round up so a positive sub-millisecond remainder still gets one bounded
    // event-loop turn. The watchdog supplies the hard wall-clock boundary.
    let millis = remaining
        .as_millis()
        .saturating_add(u128::from(remaining.subsec_nanos() % 1_000_000 != 0));
    Some(millis.min(u128::from(u64::MAX)) as u64)
}

/// Handle to an armed V8 execution watchdog (see [`ObscuraJsRuntime::arm_watchdog`]).
/// Holds a deadline on the shared watchdog; pass it back to
/// `disarm_watchdog` to stop the watchdog and learn whether it fired.
pub struct WatchdogToken {
    armed: Option<crate::cdp_watchdog::Armed>,
}

/// Arm a V8 termination watchdog directly from an isolate handle, with no
/// runtime borrow. The CDP dispatcher uses this to bound every command so a
/// hung page cannot hold this connection's V8 lock forever. Pair with
/// [`WatchdogToken::stop`]; if `stop` returns true, clear the termination flag
/// via [`ObscuraJsRuntime::cancel_termination`] before reusing the isolate.
pub fn spawn_watchdog(handle: IsolateHandle, budget: std::time::Duration) -> WatchdogToken {
    WatchdogToken {
        armed: Some(crate::cdp_watchdog::arm(handle, budget)),
    }
}

impl WatchdogToken {
    /// Stop the watchdog. Returns true if it had already fired (terminated the
    /// isolate). The caller must then clear the termination flag via
    /// [`ObscuraJsRuntime::cancel_termination`] before the next eval.
    pub fn stop(mut self) -> bool {
        self.armed.take().map(crate::cdp_watchdog::disarm).unwrap_or(false)
    }
}

impl Drop for WatchdogToken {
    fn drop(&mut self) {
        // Futures which own a watchdog may be cancelled while parked on I/O.
        // Dropping the token must not leave an armed deadline which later
        // terminates an isolate that has already moved on to another task.
        if let Some(armed) = self.armed.take() {
            crate::cdp_watchdog::disarm(armed);
        }
    }
}

// Observation deadlines are checked between browser tasks. A task which has
// already started receives this bounded completion allowance, matching the
// fixed-wait path while retaining an absolute backstop for infinite script.
const SYNCHRONOUS_TASK_FLOOR_MS: u64 = 5_000;
const WATCHDOG_SCHEDULING_MARGIN_MS: u64 = 500;

/// A [`JsRuntime`] whose isolate is entered for the duration of one operation.
///
/// V8 requires the isolate that owns a context to be the thread's *current*
/// one whenever that context is entered or left, and rusty_v8's scopes do not
/// arrange that themselves -- they only ever pass the isolate explicitly. What
/// made it work by accident was rusty_v8 entering an isolate when it is
/// constructed and leaving it entered for life: with a single page, that page's
/// isolate is trivially the current one.
///
/// With two pages it is not. The isolates form a stack, only the newest is
/// current, and the consequences were both immediate and fatal:
///
/// - running any script on the *older* page aborted the process
///   (`Check failed: heap->isolate() == Isolate::TryGetCurrent()`), so a second
///   page effectively disabled the first;
/// - dropping either page aborted too, because rusty_v8 requires isolates to
///   be dropped in reverse construction order -- a contract an embedder holding
///   independent `Page` objects cannot keep (#756).
///
/// So the isolate is exited once construction finishes and entered again only
/// around work that touches V8. Entries are then properly nested no matter how
/// many pages exist or what order they are used and dropped in.
struct EnteredRuntime<'a>(&'a mut JsRuntime);

/// Enters an isolate only while an async deno_core operation is being polled.
/// Holding an entry across `.await` would let interleaved page futures violate
/// V8's per-thread isolate stack.
struct EnteredRuntimeFuture<F> {
    isolate: *mut deno_core::v8::Isolate,
    future: Option<Pin<Box<F>>>,
    _not_send: PhantomData<Rc<()>>,
}

struct IsolateEntry(*mut deno_core::v8::Isolate);

impl IsolateEntry {
    unsafe fn new(isolate: *mut deno_core::v8::Isolate) -> Self {
        unsafe { (&mut *isolate).enter() };
        Self(isolate)
    }
}

impl Drop for IsolateEntry {
    fn drop(&mut self) {
        unsafe { (&mut *self.0).exit() };
    }
}

impl<F: Future> Future for EnteredRuntimeFuture<F> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // SAFETY: construction ties the pointer and future to the same
        // borrowed JsRuntime, which cannot move or drop while this exists.
        let this = unsafe { self.get_unchecked_mut() };
        let _entry = unsafe { IsolateEntry::new(this.isolate) };
        this.future
            .as_mut()
            .expect("entered runtime future polled after drop")
            .as_mut()
            .poll(cx)
    }
}

impl<F> Drop for EnteredRuntimeFuture<F> {
    fn drop(&mut self) {
        // deno_core futures can own V8 handles, so drop them while their
        // isolate is current too.
        let _entry = unsafe { IsolateEntry::new(self.isolate) };
        drop(self.future.take());
    }
}

fn entered_runtime_future<'a, F>(
    runtime: &'a mut JsRuntime,
    make_future: impl FnOnce(&'a mut JsRuntime) -> F,
) -> EnteredRuntimeFuture<F>
where
    F: Future,
{
    let isolate: *mut deno_core::v8::Isolate = &mut **runtime.v8_isolate();
    let entry = unsafe { IsolateEntry::new(isolate) };
    let future = Box::pin(make_future(runtime));
    drop(entry);
    EnteredRuntimeFuture {
        isolate,
        future: Some(future),
        _not_send: PhantomData,
    }
}

impl std::ops::Deref for EnteredRuntime<'_> {
    type Target = JsRuntime;

    fn deref(&self) -> &JsRuntime {
        self.0
    }
}

impl std::ops::DerefMut for EnteredRuntime<'_> {
    fn deref_mut(&mut self) -> &mut JsRuntime {
        self.0
    }
}

impl Drop for EnteredRuntime<'_> {
    fn drop(&mut self) {
        // SAFETY: this isolate was entered by the matching `runtime()` call
        // and, entries being a per-thread stack, is the current one: any
        // isolate entered since belongs to a nested operation that has already
        // exited it.
        unsafe {
            self.0.v8_isolate().exit();
        }
    }
}

impl Drop for ObscuraJsRuntime {
    fn drop(&mut self) {
        // Background render-resource loads belong to this runtime's document;
        // a dropped JoinHandle would only detach them (the page also calls
        // `abandon_render_resources`, a directly embedded runtime may not).
        #[cfg(feature = "render")]
        for task in self.state.borrow_mut().render_resource_tasks.drain(..) {
            task.abort();
        }
        // Teardown needs the isolate current as much as any other V8 work:
        // deno_core's context cleanup clears the context's embedder slots, and
        // rusty_v8's `OwnedIsolate::drop` asserts it before disposing. Both run
        // when `js_runtime` is dropped, immediately after this returns, and
        // that `OwnedIsolate::drop` performs the matching exit.
        //
        // SAFETY: `enter` only pushes this isolate onto the current thread's
        // entry stack; the pop is guaranteed by the drop that follows.
        unsafe {
            self.js_runtime.v8_isolate().enter();
        }
    }
}

impl ObscuraJsRuntime {
    /// The V8 runtime, with its isolate entered for as long as the returned
    /// guard lives. Every path that touches V8 goes through here; see
    /// [`EnteredRuntime`] for why.
    fn runtime(&mut self) -> EnteredRuntime<'_> {
        // SAFETY: entering is always sound -- it pushes this isolate onto the
        // current thread's entry stack -- and the guard's `Drop` pops it.
        unsafe {
            self.js_runtime.v8_isolate().enter();
        }
        EnteredRuntime(&mut self.js_runtime)
    }

    /// Read native isolate statistics without evaluating scripts or forcing GC.
    pub fn heap_statistics(&mut self) -> v8::HeapStatistics {
        self.runtime().v8_isolate().get_heap_statistics()
    }

    /// Run a full collection only when an automation client explicitly asks.
    pub fn collect_garbage(&mut self) {
        self.runtime().v8_isolate().low_memory_notification();
    }

    /// Freeze the document timeline for one JavaScript task. Browser timelines
    /// update at task/rendering boundaries, not on each forced style or layout
    /// read. Keeping one sample across the task also lets repeated CSSOM reads
    /// share the retained layout on pages with running animations.
    fn begin_javascript_task(&mut self) {
        // Some internal callers intentionally ignore script errors. Recover a
        // heap-limit termination before any later task enters V8 even when the
        // caller that triggered it did not need the error value.
        self.recover_heap_limit();
        begin_animation_task(&mut self.state.borrow_mut());
        self.poll_indexed_db_notifications();
    }

    fn poll_indexed_db_notifications(&mut self) {
        if !self.state.borrow().indexed_db.has_pending_notifications() { return; }
        let root_notices = self.state.borrow().indexed_db_owner.as_ref()
            .map(|owner| owner.take_notices()).unwrap_or_default();
        let realms = self.realm_states().borrow().media_realms();
        let mut deliveries = Vec::new();
        if !root_notices.is_empty() {
            deliveries.push((self.runtime().main_context(), root_notices));
        }
        for (context, state) in realms {
            let notices = state.borrow().indexed_db_owner.as_ref()
                .map(|owner| owner.take_notices()).unwrap_or_default();
            if !notices.is_empty() { deliveries.push((context, notices)); }
        }
        for (context, notices) in deliveries {
            let script = format!("globalThis.__obscura_poll_indexeddb({});", serde_json::json!(notices));
            if let Err(error) = self.eval_in_realm(&context, &script) {
                tracing::warn!("IndexedDB notification failed: {error}");
            }
        }
    }
    pub fn new() -> Self {
        Self::with_base_url("about:blank")
    }

    pub fn with_base_url(base_url: &str) -> Self {
        Self::with_base_url_and_proxy(base_url, None)
    }

    /// Construct a runtime whose ES-module loader routes dynamic imports
    /// through `proxy_url` (#139). `None` is equivalent to `with_base_url`
    /// (direct connection).
    pub fn with_base_url_and_proxy(base_url: &str, proxy_url: Option<String>) -> Self {
        // A runtime is about to initialize the V8 platform; from here on a
        // set_v8_flags call must be refused rather than aborting the process.
        crate::v8_flags::mark_platform_started();
        let state = Rc::new(RefCell::new(ObscuraState::new()));
        let state_clone = state.clone();
        let import_map = state.borrow().import_map.clone();

        let module_loader =
            ObscuraModuleLoader::with_page_state(base_url, proxy_url, &state, import_map.clone());
        let module_load_activity = module_loader.activity();
        let loaded_module_specifiers = module_loader.loaded_specifiers();
        let module_loader = Rc::new(module_loader);

        let (runtime, isolate_handle, heap_limit_state) = {
            // Keep the guard alive for the whole construction: deno_core
            // captures the current tokio handle at `JsRuntime::new` time and
            // aborts if a V8 delayed task is posted without one.
            let _tokio_guard = enter_tokio_context();
            let create_lock = if ISOLATE_INITIALIZED.load(std::sync::atomic::Ordering::Acquire)
                && NEXT_ISOLATE_CREATE_SLOT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 2 != 0 {
                &ISOLATE_CREATE_SECOND_LOCK
            } else {
                &ISOLATE_CREATE_LOCK
            };
            let _create_guard = create_lock
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());

            // ICU falls back to the host OS locale when no default is set,
            // so Intl.* formats and resolvedOptions().locale leaked the
            // operator's real locale (an en-AU host showed en-AU) while
            // navigator.language and Accept-Language say en-US. Pin the one
            // locale the other surfaces claim (#734). This is process-global.
            // Set it under the first-creation lock, before parallel restorations.
            if !ISOLATE_INITIALIZED.load(std::sync::atomic::Ordering::Relaxed) {
                deno_core::v8::icu::set_default_locale("en-US");
            }

            let mut runtime = JsRuntime::new(RuntimeOptions {
                extensions: if cfg!(obscura_external_bootstrap) {
                    vec![deno_core::Extension {
                        name: "obscura_bootstrap",
                        ..Default::default()
                    }, build_extension()]
                } else {
                    vec![build_extension()]
                },
                module_loader: Some(module_loader),
                startup_snapshot: Some(SNAPSHOT),
                ..Default::default()
            });

            {
                let op_state = runtime.op_state();
                let mut op_state = op_state.borrow_mut();
                op_state.put(state_clone);
                // Empty until a frame realm exists, which is what keeps the
                // lookup free for pages that have no frames.
                op_state.put(Rc::new(RefCell::new(crate::ops::RealmStates::default())));
            }

            let isolate_handle = runtime.v8_isolate().thread_safe_handle();
            let heap_limit_state = std::sync::Arc::new(HeapLimitState::default());
            install_heap_limit_guard(
                &mut runtime,
                isolate_handle.clone(),
                heap_limit_state.clone(),
            );

            runtime
                .execute_script(
                    "<obscura:init>",
                    "globalThis.__obscura_objects = {}; globalThis.__obscura_oid = 0; if (typeof _installWasmStreamingFallback === 'function') _installWasmStreamingFallback();".to_string(),
                )
                .expect("init should not fail");

            ISOLATE_INITIALIZED.store(true, std::sync::atomic::Ordering::Release);
            (runtime, isolate_handle, heap_limit_state)
        };

        let mut instance = ObscuraJsRuntime {
            state,
            object_store: HashMap::new(),
            evaluation_recipes: HashMap::new(),
            object_counter: 0,
            import_map,
            module_load_activity,
            isolate_handle,
            heap_limit_state,
            module_evaluations: HashMap::new(),
            loaded_module_specifiers,
            evaluated_module_specifiers: HashMap::new(),
            ops_handoff: None,
            pending_cdp_evaluations: HashMap::new(),
            js_runtime: runtime,
        };
        // Take the op table before any page script can run, and drop the global
        // that exposed it in the same step.
        instance.ops_handoff = instance.take_ops_handoff();
        #[cfg(test)]
        instance.expose_ops_for_tests();

        // `JsRuntime::new` entered this isolate and rusty_v8 would leave it
        // entered for life. Leave the thread's entry stack empty instead; every
        // operation enters for its own duration. See `EnteredRuntime`.
        //
        // SAFETY: this isolate is the current one -- it was entered above and
        // nothing on this thread has entered another since.
        unsafe {
            instance.js_runtime.v8_isolate().exit();
        }

        instance
    }

    /// Creates an additional realm in this isolate: a second `v8::Context`.
    ///
    /// The startup snapshot already contains the whole bootstrap (see
    /// `build.rs`), so a context restored from it arrives with every DOM class
    /// and shim installed. Building a realm is therefore a context restore, not
    /// a re-parse of the whole bootstrap.
    ///
    /// The new context has no ops: deno_core binds those into the main context
    /// only. Use [`Self::share_ops_with_realm`] to give it the same `Deno.core`
    /// object, which is legal because native function objects are shareable
    /// between contexts of one isolate.
    pub(crate) fn create_realm_context(
        &mut self,
    ) -> Option<deno_core::v8::Global<deno_core::v8::Context>> {
        let context = {
            let mut entered = self.runtime();
            let isolate = entered.v8_isolate();
            deno_core::v8::scope!(let scope, isolate);
            let context = deno_core::v8::Context::from_snapshot(
                scope,
                1,
                deno_core::v8::ContextOptions::default(),
            )
            .or_else(|| {
                deno_core::v8::Context::from_snapshot(
                    scope,
                    0,
                    deno_core::v8::ContextOptions::default(),
                )
            })?;
            deno_core::v8::Global::new(scope, context)
        };
        Some(context)
    }

    /// Takes the ops object bootstrap handed out, and removes the handoff from
    /// the global so page script can never reach `Deno.core.ops`.
    ///
    /// Bootstrap keeps the core reference in a private const. Once deno_core
    /// has bound the ops, this removes the public globals (`Deno`, the handoff
    /// and deno_core's `__bootstrap`) before page code can run, leaving the
    /// handoff as the host's only route to child realms.
    fn take_ops_handoff(&mut self) -> Option<deno_core::v8::Global<deno_core::v8::Value>> {
        use deno_core::v8;

        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let context = v8::Local::new(scope, main);
        let scope = &mut v8::ContextScope::new(scope, context);

        let handoff_key = v8::String::new(scope, "__obscura_core_handoff")?;
        let deno_key = v8::String::new(scope, "Deno")?;
        // deno_core's own alias of the same core object (`__bootstrap.core`).
        // Deno's runtime deletes it after bootstrap (99_main.js); left here it
        // handed every page the raw op table.
        let bootstrap_key = v8::String::new(scope, "__bootstrap")?;
        let ops_key = v8::String::new(scope, "ops")?;
        let global = context.global(scope);

        let core = global.get(scope, handoff_key.into())?;
        let core = core.to_object(scope)?;
        let ops = core.get(scope, ops_key.into())?;
        if !ops.is_object() {
            return None;
        }
        let ops = v8::Global::new(scope, ops);
        global.delete(scope, handoff_key.into());
        global.delete(scope, deno_key.into());
        global.delete(scope, bootstrap_key.into());
        Some(ops)
    }

    /// Test-only instrumentation seam for assertions about native-op batching.
    /// Production builds do not compile this method or publish the op table.
    #[cfg(test)]
    fn expose_ops_for_tests(&mut self) {
        use deno_core::v8;

        let Some(ops) = self.ops_handoff.clone() else {
            return;
        };
        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let context = v8::Local::new(scope, main);
        let scope = &mut v8::ContextScope::new(scope, context);
        let Some(key) = v8::String::new(scope, "__obscura_test_ops") else {
            return;
        };
        let value = v8::Local::new(scope, ops);
        let _ = context.global(scope).set(scope, key.into(), value);
    }

    /// Points a child realm's `Deno.core.ops` at the main realm's ops object.
    ///
    /// A realm restored from the snapshot has its own `Deno.core` with an empty
    /// ops table, and its bootstrap captured that exact object, so filling the
    /// `ops` table on it is enough to give every shim in that realm a working
    /// op surface. The functions are shared, not copied: same isolate.
    /// deno_core's isolate-global promise-reject and dynamic-`import()`
    /// callbacks read per-context state from V8's `ContextState` and
    /// `ModuleMap` embedder-data slots in the *current* context. A
    /// snapshot-created frame realm leaves those slots null, so a promise
    /// rejection or dynamic import inside a frame null-dereferenced in
    /// deno_core's `clone_rc_raw` and segfaulted the whole process (#850, #841).
    /// Alias the main context's slot pointers into the frame context so those
    /// callbacks resolve to the main realm's state instead of crashing.
    ///
    /// Safe: the frame context only *borrows* these pointers. The callbacks
    /// `clone_rc_raw` (increment then drop) them — net-zero on the strong count
    /// — and obscura never tears a frame context down through deno_core's
    /// `Rc::from_raw` destroy path (only the main realm owns and frees the Rc),
    /// so no double-free is possible.
    pub(crate) fn share_deno_context_state_with_realm(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
    ) {
        use deno_core::{CONTEXT_STATE_SLOT_INDEX, MODULE_MAP_SLOT_INDEX, v8};

        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let main_ctx = v8::Local::new(scope, main);
        let realm_ctx = v8::Local::new(scope, realm);
        // SAFETY: these slots on the main context are `Rc::into_raw` pointers
        // set by deno_core at runtime construction; they outlive every frame
        // realm. We only copy (alias) them and never reconstruct the Rc from
        // the frame.
        unsafe {
            let cs = main_ctx.get_aligned_pointer_from_embedder_data(CONTEXT_STATE_SLOT_INDEX);
            let mm = main_ctx.get_aligned_pointer_from_embedder_data(MODULE_MAP_SLOT_INDEX);
            realm_ctx.set_aligned_pointer_in_embedder_data(CONTEXT_STATE_SLOT_INDEX, cs);
            realm_ctx.set_aligned_pointer_in_embedder_data(MODULE_MAP_SLOT_INDEX, mm);
        }
        // These borrowed native fields need no Rust slot annex. Leaving its
        // weak finalizer alive until isolate disposal can access freed memory
        // in rusty_v8; clearing it now preserves the native fields (#1161).
        realm_ctx.clear_all_slots();
    }

    pub(crate) fn share_ops_with_realm(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
    ) -> bool {
        use deno_core::v8;

        let Some(ops) = self.ops_handoff.clone() else {
            return false;
        };
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let context = v8::Local::new(scope, realm);
        let scope = &mut v8::ContextScope::new(scope, context);

        let Some(handoff_key) = v8::String::new(scope, "__obscura_core_handoff") else {
            return false;
        };
        let Some(ops_key) = v8::String::new(scope, "ops") else {
            return false;
        };
        let Some(deno_key) = v8::String::new(scope, "Deno") else {
            return false;
        };
        let Some(bootstrap_key) = v8::String::new(scope, "__bootstrap") else {
            return false;
        };
        let global = context.global(scope);
        let Some(core) = global.get(scope, handoff_key.into()) else {
            return false;
        };
        let Some(core) = core.to_object(scope) else {
            return false;
        };
        // `Deno.core.ops` is non-writable and non-configurable, so the table
        // cannot be swapped wholesale: V8 reports success and changes nothing.
        // Copy the bound op functions into the realm's existing table instead.
        let Some(target) = core
            .get(scope, ops_key.into())
            .and_then(|value| value.to_object(scope))
        else {
            return false;
        };
        let source = v8::Local::new(scope, ops);
        let Some(source) = source.to_object(scope) else {
            return false;
        };
        let Some(names) = source.get_own_property_names(scope, Default::default()) else {
            return false;
        };
        let mut copied = 0;
        for index in 0..names.length() {
            let Some(key) = names.get_index(scope, index) else {
                continue;
            };
            let Some(value) = source.get(scope, key) else {
                continue;
            };
            if target.set(scope, key, value).unwrap_or(false) {
                copied += 1;
            }
        }
        // The child realm must not expose the handoff to frame script either.
        global.delete(scope, handoff_key.into());
        global.delete(scope, deno_key.into());
        global.delete(scope, bootstrap_key.into());
        copied > 0
    }

    /// Runs `source` inside `realm` and returns its value as a string. Errors
    /// come back as `Err(message)`.
    pub(crate) fn eval_in_realm(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
        source: &str,
    ) -> Result<String, String> {
        use deno_core::v8;

        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let context = v8::Local::new(scope, realm);
        let scope = &mut v8::ContextScope::new(scope, context);
        v8::tc_scope!(let tc_scope, scope);

        let code = v8::String::new(tc_scope, source).ok_or("source too large")?;
        let script = match v8::Script::compile(tc_scope, code, None) {
            Some(script) => script,
            None => return Err(exception_text(tc_scope)),
        };
        match script.run(tc_scope) {
            Some(value) => Ok(value.to_rust_string_lossy(tc_scope)),
            None => Err(exception_text(tc_scope)),
        }
    }

    /// Copies the browser-identity globals from the main realm into `realm`.
    ///
    /// A frame must present the same identity as its parent: anti-bot code
    /// fingerprints inside the frame and compares it with the top document.
    /// Copying the values the parent already has makes that true by
    /// construction, instead of relying on a caller to reapply the same
    /// settings to both.
    pub(crate) fn copy_identity_to_realm(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
    ) {
        use deno_core::v8;

        const IDENTITY_GLOBALS: [&str; 7] = [
            "__obscura_ua",
            "__obscura_platform",
            "__obscura_ua_platform",
            "__obscura_ua_platform_version",
            "__obscura_stealth",
            "__obscura_geo_lat",
            "__obscura_geo_lon",
        ];

        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);

        let main_context = v8::Local::new(scope, main);
        let mut carried = Vec::new();
        {
            let scope = &mut v8::ContextScope::new(scope, main_context);
            let global = main_context.global(scope);
            for name in IDENTITY_GLOBALS {
                let Some(key) = v8::String::new(scope, name) else {
                    continue;
                };
                match global.get(scope, key.into()) {
                    Some(value) if !value.is_undefined() => {
                        carried.push((name, v8::Global::new(scope, value)));
                    }
                    _ => {}
                }
            }
        }

        let realm_context = v8::Local::new(scope, realm);
        let scope = &mut v8::ContextScope::new(scope, realm_context);
        let global = realm_context.global(scope);
        for (name, value) in carried {
            let Some(key) = v8::String::new(scope, name) else {
                continue;
            };
            let value = v8::Local::new(scope, value);
            global.set(scope, key.into(), value);
        }
    }

    /// Gives a frame's state the resources the page owns: cookie jar, HTTP
    /// client, callbacks and the stealth transport. A frame shares these with
    /// its page, exactly as it shares them in a browser.
    pub(crate) fn share_resources_with(&self, frame: &mut ObscuraState) {
        // A frame realm shares the page transport, so its renderer cache must
        // not open synchronous requests either. Frame geometry currently
        // resolves against the main document's renderer state, so frame-scoped
        // background loading is not wired up here.
        frame.inherit_resources(&self.state.borrow());
    }

    pub fn forget_frame_state(&mut self, frame_id: u32) {
        self.realm_states().borrow_mut().forget_frame(frame_id);
    }

    /// Pending initial realms can already own children before Page adopts them.
    pub fn frame_is_active(&self, frame_id: u32) -> bool {
        self.realm_states().borrow().frame_timers_active(frame_id) != Some(false)
    }

    /// The origin of the document this runtime is running, or `"null"` for a
    /// scheme that has no tuple origin.
    pub(crate) fn page_origin(&self) -> String {
        let url = self.state.borrow().url.clone();
        match url::Url::parse(&url) {
            Ok(parsed) if parsed.origin().is_tuple() => parsed.origin().ascii_serialization(),
            _ => "null".to_string(),
        }
    }

    /// Gives a same-origin frame realm the page's security token.
    ///
    /// V8 access-checks property reads across contexts and answers `undefined`
    /// unless the two carry the same token, which is how a browser keeps one
    /// origin out of another's window. Two contexts of one origin must share a
    /// token, or the page reads its own frame's globals as undefined. Only
    /// ever called after an origin comparison; a cross-origin frame keeps its
    /// own token and stays opaque.
    pub(crate) fn share_security_token_with_realm(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
    ) {
        use deno_core::v8;

        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);
        let main = v8::Local::new(scope, main);
        let realm = v8::Local::new(scope, realm);
        let token = main.get_security_token(scope);
        realm.set_security_token(token);
    }

    /// Publishes a frame realm's own `window` and `document` objects into the
    /// page realm, under `__obscura_frameObjects[frameId]`.
    ///
    /// This is what the single isolate buys. Objects cannot cross isolates, so
    /// a parent could only ever be handed a copy or a shim; within one isolate
    /// it can hold the frame's real globals, which is what a browser gives it
    /// for a same-origin frame. `contentWindow.someGlobal` is then a plain
    /// property read of the frame's own object, and `contentDocument` is the
    /// document the frame's scripts actually mutated.
    pub(crate) fn publish_realm_objects(
        &mut self,
        realm: &deno_core::v8::Global<deno_core::v8::Context>,
        frame_id: u32,
    ) -> bool {
        use deno_core::v8;

        let main = self.runtime().main_context();
        let mut entered = self.runtime();
        let isolate = entered.v8_isolate();
        v8::scope!(let scope, isolate);

        // Read the frame's globals first, then install them in the page realm.
        // Both contexts belong to this isolate, so the handles stay valid
        // across the switch.
        let realm_context = v8::Local::new(scope, realm);
        let (frame_window, frame_document) = {
            let scope = &mut v8::ContextScope::new(scope, realm_context);
            let global = realm_context.global(scope);
            let Some(key) = v8::String::new(scope, "document") else {
                return false;
            };
            let document = global.get(scope, key.into());
            (
                v8::Global::new(scope, global),
                document.map(|value| v8::Global::new(scope, value)),
            )
        };

        let main_context = v8::Local::new(scope, main);
        let scope = &mut v8::ContextScope::new(scope, main_context);
        let global = main_context.global(scope);
        let Some(registry_key) = v8::String::new(scope, "__obscura_frameObjects") else {
            return false;
        };
        let registry = match global
            .get(scope, registry_key.into())
            .and_then(|value| value.to_object(scope))
        {
            Some(registry) if !registry.is_null_or_undefined() => registry,
            _ => {
                let fresh = v8::Object::new(scope);
                global.set(scope, registry_key.into(), fresh.into());
                fresh
            }
        };

        let entry = v8::Object::new(scope);
        let window = v8::Local::new(scope, frame_window);
        if let Some(key) = v8::String::new(scope, "window") {
            entry.set(scope, key.into(), window.into());
        }
        if let (Some(key), Some(document)) = (
            v8::String::new(scope, "document"),
            frame_document.map(|document| v8::Local::new(scope, document)),
        ) {
            entry.set(scope, key.into(), document);
        }
        let index = v8::Integer::new_from_unsigned(scope, frame_id);
        registry
            .set(scope, index.into(), entry.into())
            .unwrap_or(false)
    }

    /// The table ops consult to find the calling realm's document.
    pub(crate) fn realm_states(&self) -> Rc<RefCell<crate::ops::RealmStates>> {
        // `op_state` is a plain Rust-side table; no V8 access, no guard.
        self.js_runtime
            .op_state()
            .borrow()
            .borrow::<Rc<RefCell<crate::ops::RealmStates>>>()
            .clone()
    }

    /// Frame documents fetched by any realm that still need one of their own.
    /// The op queues onto the page's state whichever frame asked, so a frame
    /// nested inside a frame is drained here too.
    pub fn take_pending_frames(&self) -> Vec<crate::ops::PendingFrame> {
        let mut state = self.state.borrow_mut();
        state.pending_frame_bytes = 0;
        std::mem::take(&mut state.pending_frames)
    }

    #[doc(hidden)]
    pub fn has_pending_frame_tasks(&self) -> bool {
        let state = self.state.borrow();
        !state.pending_frames.is_empty() || !state.pending_frame_messages.is_empty()
            || self.realm_states().borrow().has_pending_navigation()
    }

    #[doc(hidden)]
    pub fn take_pending_frame_navigations(&self) -> Vec<(u32, String, String, String)> {
        self.realm_states().borrow().take_pending_navigations()
    }

    /// postMessage traffic waiting to be delivered to another realm.
    pub fn take_pending_frame_messages(&self) -> Vec<crate::ops::PendingFrameMessage> {
        let mut state = self.state.borrow_mut();
        state.pending_frame_message_bytes = 0;
        std::mem::take(&mut state.pending_frame_messages)
    }

    /// Restore the configured V8 heap limit after the emergency headroom has
    /// allowed a terminated allocation to unwind. The callback is then armed
    /// again so a second hostile script cannot grow the isolate without bound.
    fn recover_heap_limit(&mut self) -> bool {
        if !self
            .heap_limit_state
            .tripped
            .swap(false, std::sync::atomic::Ordering::SeqCst)
        {
            return false;
        }

        self.runtime().v8_isolate().cancel_terminate_execution();
        let restore_limit = self
            .heap_limit_state
            .restore_limit
            .swap(0, std::sync::atomic::Ordering::SeqCst);
        self.runtime()
            .remove_near_heap_limit_callback(restore_limit);
        let isolate_handle = self.isolate_handle.clone();
        let heap_limit_state = self.heap_limit_state.clone();
        install_heap_limit_guard(&mut *self.runtime(), isolate_handle, heap_limit_state);
        tracing::warn!("V8 heap limit reached: terminated the current JavaScript task");
        true
    }

    fn finish_heap_checked<T>(&mut self, result: Result<T, String>) -> Result<T, String> {
        if self.recover_heap_limit() {
            Err("JavaScript heap limit exceeded; execution terminated".to_string())
        } else {
            result
        }
    }

    fn execute_runtime_script(
        &mut self,
        name: &'static str,
        source: String,
    ) -> Result<deno_core::v8::Global<deno_core::v8::Value>, String> {
        let result = self
            .runtime()
            .execute_script(name, source)
            .map_err(|error| error.to_string());
        self.finish_heap_checked(result)
    }

    /// Parse and merge an inline document import map. Rules which would alter
    /// already-observed module resolutions are discarded while unrelated new
    /// rules remain available, matching Chromium's multiple-map model.
    pub fn add_import_map(&self, source: &str, base_url: &str) -> Result<(), String> {
        let map = ImportMap::parse(source, base_url)?;
        self.import_map
            .try_borrow_mut()
            .map_err(|_| "Import map is already borrowed".to_string())?
            .merge(map);
        Ok(())
    }

    pub fn set_cookie_jar(&self, jar: std::sync::Arc<obscura_net::CookieJar>) {
        self.state.borrow_mut().cookie_jar = Some(jar);
    }

    /// Install the context-scoped `localStorage` backing store. The Arc lives on
    /// the BrowserContext, so entries outlive the V8 realm that wrote them.
    pub fn set_local_storage(&self, storage: std::sync::Arc<OriginStorage>) {
        self.state.borrow_mut().local_storage = Some(storage);
    }

    pub fn set_indexed_db(&self, storage: std::sync::Arc<crate::indexed_db::IndexedDbStorage>) {
        let mut state = self.state.borrow_mut();
        state.indexed_db_owner = None;
        state.indexed_db = storage;
    }

    /// Install the page-owned `sessionStorage` backing store, so an entry
    /// survives realm teardown on a same-origin navigation and on CDP target
    /// switching while staying inside the tab (issue #678).
    pub fn set_session_storage(&self, storage: std::sync::Arc<OriginStorage>) {
        self.state.borrow_mut().session_storage = Some(storage);
    }

    pub fn set_http_client(&self, client: std::sync::Arc<obscura_net::ObscuraHttpClient>) {
        let mut state = self.state.borrow_mut();
        state.http_client = Some(client);
        // A page transport makes the renderer cache-only; see
        // `ops::fresh_render_resources` for why layout must not fetch itself.
        #[cfg(feature = "render")]
        state.render_resources.set_sync_loading_enabled(false);
    }

    /// Install the owning page's passive on_request/on_response callback
    /// registry so scripted fetch()/XHR observation is page-scoped (issue #408).
    pub fn set_callbacks(&self, callbacks: std::sync::Arc<obscura_net::CallbackRegistry>) {
        self.state.borrow_mut().callbacks = Some(callbacks);
    }

    /// Install the stealth (wreq) HTTP client so scripted fetch()/XHR is routed
    /// through it in stealth mode (see op_fetch_url / stealth_fetch_all).
    #[cfg(feature = "stealth")]
    pub fn set_stealth_client(&self, client: std::sync::Arc<obscura_net::StealthHttpClient>) {
        let mut state = self.state.borrow_mut();
        state.stealth_client = Some(client);
        #[cfg(feature = "render")]
        state.render_resources.set_sync_loading_enabled(false);
    }

    pub fn set_dom(&self, dom: DomTree) {
        let mut gs = self.state.borrow_mut();
        gs.replace_dom(dom);
        gs.document_generation = gs.document_generation.wrapping_add(1);
        gs.activity_generation = 0;
        gs.page_in_flight = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        gs.already_started_scripts.borrow_mut().clear();
        // A new document owns a fresh retained scene and resource cache.
        #[cfg(feature = "render")]
        {
            gs.prepared_render = None;
            gs.style_query_cache = None;
            gs.animation_sample = obscura_render::AnimationSample::default();
            gs.animation_timeline = obscura_render::AnimationTimelineState::default();
            gs.animation_timeline_origin = std::time::Instant::now();
            gs.animation_task_generation = 0;
            gs.animation_sampled_task_generation = 0;
            gs.pending_style_mutations.clear();
            let render_resources = crate::ops::fresh_render_resources(&gs);
            gs.render_resources = render_resources;
            gs.render_image_in_flight.clear();
            for task in gs.render_resource_tasks.drain(..) {
                task.abort();
            }
            gs.render_resource_in_flight.clear();
            gs.render_resource_backlog.clear();
            gs.render_resource_events.clear();
            // A fresh channel: a load of the old document that is still
            // finishing (abort is not a join) delivers into a dropped
            // receiver, never into this document's results.
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
            gs.render_resource_tx = tx;
            gs.render_resource_rx = rx;
            gs.stylesheet_cache = obscura_render::StylesheetCache::default();
            gs.dynamic_fonts.clear();
            gs.canvas_surfaces.clear();
            gs.scroll_offset = (0.0, 0.0);
            gs.element_scroll_offsets.clear();
            gs.scroll_generation = 0;
            gs.resolved_scroll = None;
        }
        drop(gs);
        let realms = self.realm_states();
        let mut realms = realms.borrow_mut();
        realms.cancel_inactive_frame_timers();
        realms.prune_frame_contexts();
        realms.connect_document_frames(&self.state);
    }

    pub fn set_url(&self, url: &str) {
        let mut state = self.state.borrow_mut();
        if state.url != url {
            state.url = url.to_string();
            #[cfg(feature = "render")]
            {
                // Relative resources use the document URL when no <base> is
                // present. Keep already-fetched absolute bytes, but rebuild
                // candidate selection/layout against the new base.
                state.prepared_render = None;
                state.pending_style_mutations.clear();
                state.resolved_scroll = None;
            }
        }
    }

    pub fn document_url(&self) -> String {
        self.state.borrow().url.clone()
    }

    /// Set the document's character encoding (WHATWG canonical name). Backs
    /// `document.characterSet` and the `<a>`/`<area>` URL query encoding
    /// override for legacy-charset documents.
    pub fn set_encoding(&self, encoding: &str) {
        self.state.borrow_mut().encoding = encoding.to_string();
    }

    /// Set the document's MIME type. Backs `document.contentType`, which
    /// reports the type of the main resource rather than one guessed from
    /// the URL.
    pub fn set_content_type(&self, content_type: &str) {
        self.state.borrow_mut().content_type = content_type.to_string();
    }

    pub fn set_title(&self, title: &str) {
        self.state.borrow_mut().title = title.to_string();
    }

    /// Set the source document URL exposed as `document.referrer`. Navigation
    /// owns this value; it is not derived from the current URL because direct
    /// navigations and document-initiated navigations have different
    /// referrer semantics.
    pub fn set_referrer(&self, referrer: &str) {
        self.state.borrow_mut().referrer = referrer.to_string();
    }

    pub fn set_blocked_urls(&self, patterns: Vec<String>) {
        self.state.borrow_mut().blocked_urls = patterns;
    }

    pub fn take_pending_navigation(&self) -> Option<(String, String, String)> {
        self.state.borrow_mut().pending_navigation.take()
    }

    /// Session history index that accompanies the pending navigation when
    /// page script traversed to another document with `history.go()`.
    pub fn take_pending_history_traversal(&self) -> Option<usize> {
        self.state.borrow_mut().pending_history_traversal.take()
    }

    pub fn set_session_history(&self, urls: Vec<String>, document_start: usize, current: usize) {
        self.state.borrow_mut().session_history = crate::ops::SessionHistory {
            urls,
            document_start,
            current,
        };
    }

    pub fn has_pending_navigation(&self) -> bool {
        self.state.borrow().pending_navigation.is_some()
    }

    pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {
        std::mem::take(&mut self.state.borrow_mut().pending_binding_calls)
    }

    pub fn take_pending_runtime_events(&mut self) -> Vec<RuntimeEvent> {
        let events: Vec<_> = self
            .state
            .borrow_mut()
            .pending_runtime_events
            .drain(..)
            .collect();
        for event in &events {
            let RuntimeEvent::Console(event) = event else {
                continue;
            };
            for arg in &event.args {
                let Some(object_id) = arg.get("objectId").and_then(|value| value.as_str()) else {
                    continue;
                };
                let frame_id = object_id
                    .strip_prefix("console-")
                    .and_then(|rest| rest.split_once('-'))
                    .and_then(|(frame_id, _)| frame_id.parse::<u32>().ok())
                    .unwrap_or(0);
                if let Err(error) = self.retain_console_object(object_id, frame_id) {
                    tracing::warn!(object_id, %error, "Could not retain console object");
                }
            }
        }
        events
    }

    fn retain_console_object(&mut self, object_id: &str, frame_id: u32) -> Result<(), String> {
        let watchdog = self.arm_watchdog(std::time::Duration::from_secs(5));
        let result = self.retain_console_object_in_context(object_id, frame_id);
        if self.disarm_watchdog(watchdog) {
            return Err("Console object retention exceeded its deadline".into());
        }
        self.finish_heap_checked(result)
    }

    fn retain_console_object_in_context(&mut self, object_id: &str, frame_id: u32) -> Result<(), String> {
        let frame = if frame_id == 0 { None } else {
            Some((frame_id, self.cdp_context(Some(frame_id))?))
        };
        if let Some((_, context)) = &frame {
            let value = {
                let mut entered = self.runtime();
                v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
                v8::tc_scope!(let scope, scope);
                let key = v8::String::new(scope, "__obscura_objects").ok_or("Console store allocation failed")?;
                let global = scope.get_current_context().global(scope);
                let objects = global.get(scope, key.into()).and_then(|value| value.to_object(scope))
                    .ok_or("Console object store unavailable")?;
                let key = v8::String::new(scope, object_id).ok_or("Console object key allocation failed")?;
                let value = objects.get(scope, key.into()).ok_or("Console object unavailable")?;
                let value = v8::Global::new(scope, value);
                if objects.delete(scope, key.into()) != Some(true) { return Err("Cannot move console object".into()); }
                value
            };
            let mut entered = self.runtime();
            let context = entered.main_context();
            v8::scope_with_context!(scope, entered.v8_isolate(), context);
            v8::tc_scope!(let scope, scope);
            let key = v8::String::new(scope, "__obscura_objects").ok_or("Console store allocation failed")?;
            let global = scope.get_current_context().global(scope);
            let objects = global.get(scope, key.into()).and_then(|value| value.to_object(scope))
                .ok_or("Console object store unavailable")?;
            let key = v8::String::new(scope, object_id).ok_or("Console object key allocation failed")?;
            let value = v8::Local::new(scope, value);
            if objects.set(scope, key.into(), value) != Some(true) { return Err("Cannot retain console object".into()); }
        }
        self.object_store.insert(object_id.to_string(), CdpObjectRecord {
            retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id)), frame,
        });
        Ok(())
    }

    pub fn set_runtime_events_enabled(&self, enabled: bool) {
        self.state.borrow_mut().runtime_events_enabled = enabled;
    }

    pub fn set_console_messages_enabled(&self, enabled: bool) {
        self.state.borrow_mut().console_messages_enabled = enabled;
    }

    pub fn take_pending_console_messages(&self) -> Vec<String> {
        self.state
            .borrow_mut()
            .pending_console_messages
            .drain(..)
            .collect()
    }

    fn record_uncaught_exception(&self, error: &deno_core::error::JsError, fallback_url: &str) {
        crate::ops::record_uncaught_exception(&mut self.state.borrow_mut(), error, fallback_url);
    }

    pub fn get_network_response_body(&self, request_id: &str) -> Option<StoredNetworkResponseBody> {
        self.state
            .borrow()
            .network_response_bodies
            .get(request_id)
            .cloned()
    }

    /// Move retained bodies in completion order before the runtime is suspended.
    pub fn take_network_response_bodies(&self) -> Vec<(String, StoredNetworkResponseBody)> {
        let mut state = self.state.borrow_mut();
        let order = std::mem::take(&mut state.network_response_body_order);
        order.into_iter().filter_map(|id| {
            state.network_response_bodies.remove(&id).map(|body| (id, body))
        }).collect()
    }

    pub fn clear_network_response_bodies(&self) {
        let mut state = self.state.borrow_mut();
        state.network_response_bodies.clear();
        state.network_response_body_order.clear();
    }

    /// Wire up the interception channel without enabling interception.
    /// Use set_intercept_enabled separately. The two were entangled before
    /// and every navigation auto-enabled interception, which made
    /// `fetch()` from page JS hang forever waiting for a CDP client to
    /// answer Fetch.requestPaused events that the client never asked for.
    pub fn set_intercept_tx(
        &self,
        tx: tokio::sync::mpsc::UnboundedSender<crate::ops::InterceptedRequest>,
    ) {
        let mut state = self.state.borrow_mut();
        state.intercept_tx = Some(tx);
    }

    pub fn set_intercept_enabled(&self, enabled: bool) {
        let mut state = self.state.borrow_mut();
        state.intercept_enabled = enabled;
    }

    pub fn set_intercept_page_id(&self, page_id: &str) {
        self.state.borrow_mut().intercept_page_id = page_id.to_string();
    }

    /// `Fetch.enable` URL patterns that decide which fetch()/XHR requests
    /// are sent to the interception channel.
    pub fn set_intercept_url_patterns(&self, patterns: Vec<String>) {
        self.state.borrow_mut().intercept_url_patterns = patterns;
    }

    /// `Fetch.enable` URL patterns of the owning page. Renderer resource
    /// loads honour them like the page's own subresource fetches do.
    #[cfg(feature = "render")]
    pub fn set_intercept_block_patterns(&self, patterns: Vec<String>) {
        self.state.borrow_mut().intercept_block_patterns = patterns;
    }

    pub fn set_user_agent(&mut self, ua: &str) {
        let _ = self.execute_runtime_script(
            "<set-ua>",
            format!("globalThis.__obscura_ua = {};", js_string_literal(ua)),
        );
    }

    pub fn set_locale(&mut self, locale: &str) {
        let _ = self.execute_runtime_script(
            "<set-locale>",
            format!(
                "globalThis.__obscura_language = {};",
                js_string_literal(locale)
            ),
        );
    }

    pub fn set_platform(&mut self, platform: &str, ua_platform: &str, ua_platform_version: &str) {
        let _ = self.execute_runtime_script(
            "<set-platform>",
            format!(
                "globalThis.__obscura_platform={};globalThis.__obscura_ua_platform={};globalThis.__obscura_ua_platform_version={};",
                js_string_literal(platform),
                js_string_literal(ua_platform),
                js_string_literal(ua_platform_version),
            ),
        );
    }

    pub fn set_stealth(&mut self, enabled: bool) {
        let _ = self.execute_runtime_script(
            "<set-stealth>",
            format!("globalThis.__obscura_stealth = {};", enabled),
        );
    }

    /// Set the CSS viewport exposed to page JavaScript. This must run before
    /// `run_page_init` for navigation-time responsive code; it may also be
    /// called later by CDP emulation to update the live window surfaces.
    pub fn set_viewport(&mut self, width: f64, height: f64) {
        if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
            return;
        }
        #[cfg(feature = "render")]
        self.state.borrow_mut().set_viewport(width, height);
        let _ = self.execute_runtime_script(
            "<set-viewport>",
            format!(
                "globalThis.__obscura_viewport_w={width};\
                 globalThis.__obscura_viewport_h={height};\
                 globalThis.innerWidth={width};globalThis.innerHeight={height};\
                 globalThis.__obscura_recompute_media_queries();\
                 if(globalThis.visualViewport){{\
                   globalThis.visualViewport.width={width};\
                   globalThis.visualViewport.height={height};\
                 }}\
                 if(typeof globalThis.__obscura_recompute_intersections==='function'){{\
                   globalThis.__obscura_recompute_intersections();\
                 }}\
                 if(typeof globalThis.__obscura_recompute_resizes==='function'){{\
                   globalThis.__obscura_recompute_resizes();\
                 }}",
            ),
        );
    }

    /// Apply preference overrides together so compound query listeners observe
    /// one media change, including in existing child documents.
    pub fn set_media_preferences(&mut self, reduce: bool, dark: bool) {
        self.state.borrow().media_preferences.set((reduce, dark));
        let realms = self.realm_states().borrow().media_realms();
        #[cfg(feature = "render")]
        {
            let media = self.state.borrow().render_media
                .with_reduced_motion(reduce).with_dark_color_scheme(dark);
            self.set_render_media(media);
            for (_, state) in &realms {
                let mut state = state.borrow_mut();
                let media = state.render_media.with_reduced_motion(reduce).with_dark_color_scheme(dark);
                if state.render_media != media {
                    state.render_media = media;
                    state.prepared_render = None;
                    state.resolved_scroll = None;
                }
            }
        }
        let script = "globalThis.__obscura_update_media_preferences();";
        let _ = self.execute_runtime_script("<media-preferences>", script.into());
        for (context, _) in realms {
            let _ = self.eval_in_realm(&context, script);
        }
    }

    #[cfg(feature = "render")]
    pub fn prefers_dark_color_scheme(&self) -> bool {
        self.state.borrow().media_preferences.get().1
    }

    /// Keep JavaScript media queries and CSS selection on the same preference.
    pub fn set_reduced_motion(&mut self, reduce: bool) {
        let dark = self.state.borrow().media_preferences.get().1;
        self.set_media_preferences(reduce, dark);
    }

    /// Override the physical screen metrics exposed to page JavaScript.
    /// Unlike the CSS viewport, CDP only changes these when both optional
    /// screen dimensions are supplied. Passing `None` restores the native
    /// screen surface while keeping the viewport override intact.
    pub fn set_screen_size_override(&mut self, size: Option<(f64, f64)>, emulated: bool) {
        let script = match size {
            Some((width, height))
                if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 =>
            {
                format!("globalThis.__obscura_set_screen_override({width},{height},{emulated});")
            }
            _ => format!("globalThis.__obscura_set_screen_override(null,null,{emulated});"),
        };
        let _ = self.execute_runtime_script("<set-screen-size>", script);
    }

    /// Current clamped root scroll offset shared by CSSOM geometry and paint.
    #[cfg(feature = "render")]
    pub fn scroll_offset(&self) -> (f32, f32) {
        let mut state = self.state.borrow_mut();
        let requested = state.scroll_offset;
        clamp_scroll_offset(&mut state, requested)
    }

    /// Select the document-timeline instant used by the next render flush.
    /// Returns false for invalid times and preserves the current sample.
    #[cfg(feature = "render")]
    pub fn set_animation_sample_time(&self, sample: obscura_render::AnimationSampleTime) -> bool {
        self.set_animation_sample(obscura_render::AnimationSample::document(
            sample.milliseconds,
        ))
    }

    #[cfg(feature = "render")]
    pub fn set_animation_sample(&self, sample: obscura_render::AnimationSample) -> bool {
        if !sample.time.milliseconds.is_finite() || sample.time.milliseconds < 0.0 {
            return false;
        }
        let mut state = self.state.borrow_mut();
        if state.animation_sample != sample {
            let forward_document_sample = sample.mode
                == obscura_render::AnimationSampleMode::DocumentTime
                && state.animation_sample.mode == obscura_render::AnimationSampleMode::DocumentTime
                && sample.time.milliseconds > state.animation_sample.time.milliseconds;
            if forward_document_sample
                && state.pending_style_mutations.is_empty()
                && state.prepared_render.as_mut().is_some_and(|prepared| {
                    prepared.advance_inactive_animation_sample_time(sample.time)
                })
            {
                state.animation_sample = sample;
                return true;
            }
            state.animation_sample = sample;
            if !forward_document_sample {
                state.prepared_render = None;
                state.pending_style_mutations.clear();
            }
            state.resolved_scroll = None;
        }
        true
    }

    /// Select the CSS media type for the next synchronous render flush.
    /// Changing media invalidates geometry and the compiled stylesheet key but
    /// leaves the live DOM, scroll offsets, and resource bytes untouched.
    #[cfg(feature = "render")]
    pub fn prefers_reduced_motion(&self) -> bool {
        self.state.borrow().render_media.reduced_motion()
    }

    #[cfg(feature = "render")]
    pub fn set_render_media(
        &self,
        media: obscura_render::CssMediaType,
    ) -> obscura_render::CssMediaType {
        let mut state = self.state.borrow_mut();
        let previous = state.render_media;
        if previous != media {
            state.render_media = media;
            state.prepared_render = None;
            state.resolved_scroll = None;
        }
        previous
    }

    #[cfg(feature = "render")]
    pub fn animation_sample_time(&self) -> obscura_render::AnimationSampleTime {
        self.state.borrow().animation_sample.time
    }

    #[cfg(feature = "render")]
    pub fn live_animation_sample(&self) -> obscura_render::AnimationSample {
        let state = self.state.borrow();
        obscura_render::AnimationSample::document(
            (state.animation_timeline_origin.elapsed().as_secs_f64() * 1_000.0)
                .min(f64::from(f32::MAX)) as f32,
        )
    }

    #[cfg(feature = "render")]
    pub fn reset_animation_timeline(&self) {
        let mut state = self.state.borrow_mut();
        state.animation_timeline_origin = std::time::Instant::now();
        state.animation_timeline = obscura_render::AnimationTimelineState::default();
        state.animation_sample = obscura_render::AnimationSample::default();
        state.prepared_render = None;
        state.pending_style_mutations.clear();
        state.resolved_scroll = None;
    }

    /// Read animation damage from the last prepared frame without causing a
    /// style/layout flush. Screencast scheduling uses this to avoid rasterizing
    /// static pages on every compositor tick.
    #[cfg(feature = "render")]
    pub fn prepared_has_active_css_animations(&self) -> bool {
        self.state
            .borrow()
            .prepared_render
            .as_ref()
            .is_some_and(|prepared| prepared.has_active_css_animations())
    }

    /// Capture the live render viewport from the same prepared layout used by
    /// CSSOM geometry. A mismatched ad-hoc viewport/base returns `None` so the
    /// browser layer can retain its compatibility one-shot path.
    #[cfg(feature = "render")]
    pub fn screenshot_prepared(
        &self,
        viewport: (f32, f32),
        base_url: Option<&str>,
    ) -> Option<Vec<u8>> {
        self.screenshot_prepared_with_surface_color(viewport, base_url, [255, 255, 255, 255])
    }

    /// Paint an unprepared view of the current document against the runtime's
    /// retained resource cache.
    ///
    /// `Page` falls back to a raw-DOM paint when a capture's viewport does not
    /// match the prepared render key. That fallback used a fresh
    /// `RenderResourceCache`, so it refetched every image on every call and a
    /// repeated capture paid the network cost per frame. Reusing the cache the
    /// runtime already holds for this document keeps the fallback correct while
    /// fetching each resource once.
    #[cfg(feature = "render")]
    pub fn screenshot_unprepared_with_retained_resources(
        &self,
        viewport: (f32, f32),
        base_url: Option<&str>,
        scroll: (f32, f32),
        animation_sample_time: obscura_render::AnimationSampleTime,
        surface_color: [u8; 4],
    ) -> Option<Vec<u8>> {
        let mut state = self.state.borrow_mut();
        let ObscuraState {
            dom,
            render_resources,
            render_media,
            dynamic_fonts,
            ..
        } = &mut *state;
        // An ad-hoc capture must select the same preference rules as CSSOM.
        // Keep its viewport-specific cascade separate from the live cache.
        if *render_media != obscura_render::CssMediaType::Screen {
            let tree = dom.as_ref()?;
            let mut cache = obscura_render::StylesheetCache::default();
            let mut timeline = obscura_render::AnimationTimelineState::default();
            let mut prepared = obscura_render::prepare_dom_with_dynamic_fonts_and_stylesheet_cache_for_media_with_animation_state(
                tree, viewport, base_url, render_resources, dynamic_fonts,
                &mut cache, *render_media,
                obscura_render::AnimationSample::local_override(animation_sample_time.milliseconds),
                &mut timeline,
            )?;
            let resolved = prepared.resolve_scroll_state(tree, scroll, &Default::default());
            return obscura_render::screenshot_prepared_with_scroll_and_surface_color(
                tree, &mut prepared, render_resources, &resolved, surface_color,
            );
        }
        obscura_render::screenshot_png_scrolled_at_animation_time_with_surface_color_and_resources(
            dom.as_ref()?,
            viewport,
            base_url,
            scroll,
            animation_sample_time,
            surface_color,
            render_resources,
        )
    }

    #[cfg(feature = "render")]
    pub fn screenshot_prepared_with_surface_color(
        &self,
        viewport: (f32, f32),
        base_url: Option<&str>,
        surface_color: [u8; 4],
    ) -> Option<Vec<u8>> {
        let mut state = self.state.borrow_mut();
        let effective_base = document_base_url(&state);
        if viewport != state.viewport || base_url != effective_base.as_deref() {
            return None;
        }
        with_sync_render_loading_disabled(&mut state, |state| {
            ensure_resolved_scroll(state)?;
            let ObscuraState {
                dom,
                prepared_render,
                render_resources,
                resolved_scroll,
                canvas_surfaces,
                ..
            } = state;
            let (_, scroll) = resolved_scroll.as_ref()?;
            let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
            obscura_render::screenshot_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
                dom.as_ref()?,
                prepared_render.as_mut()?,
                render_resources,
                scroll,
                surface_color,
                &canvas_surfaces,
            )
        })
    }

    /// Capture a document-space rectangle without changing the live viewport,
    /// root scroll, element scroll offsets, or retained layout. The current
    /// resolved scroll snapshot supplies fixed/sticky and nested-scroll state.
    #[cfg(feature = "render")]
    pub fn screenshot_prepared_region(
        &self,
        region: obscura_render::CaptureRegion,
    ) -> Result<Vec<u8>, obscura_render::CaptureError> {
        self.screenshot_prepared_region_with_surface_color(region, [255, 255, 255, 255])
    }

    #[cfg(feature = "render")]
    pub fn screenshot_prepared_region_with_surface_color(
        &self,
        region: obscura_render::CaptureRegion,
        surface_color: [u8; 4],
    ) -> Result<Vec<u8>, obscura_render::CaptureError> {
        self.paint_prepared_region_with_surface_color(region, surface_color)?
            .encode_png()
            .map_err(|_| obscura_render::CaptureError::EncodeFailed)
    }

    #[cfg(feature = "render")]
    pub fn screenshot_prepared_region_raster_with_surface_color(
        &self,
        region: obscura_render::CaptureRegion,
        surface_color: [u8; 4],
    ) -> Result<(u32, u32, Vec<u8>), obscura_render::CaptureError> {
        let raster = self.paint_prepared_region_with_surface_color(region, surface_color)?;
        let (width, height) = (raster.width(), raster.height());
        // Opaque frames already contain straight RGBA. Avoid rewriting every
        // pixel, but inspect the final surface so transparent captures retain
        // the renderer's exact demultiplication and rounding behavior.
        let pixels = if raster.pixels().iter().all(|pixel| pixel.is_opaque()) {
            raster.take()
        } else {
            raster.take_demultiplied()
        };
        Ok((width, height, pixels))
    }

    #[cfg(feature = "render")]
    fn paint_prepared_region_with_surface_color(
        &self,
        region: obscura_render::CaptureRegion,
        surface_color: [u8; 4],
    ) -> Result<obscura_render::Pixmap, obscura_render::CaptureError> {
        let mut state = self.state.borrow_mut();
        with_sync_render_loading_disabled(&mut state, |state| {
            ensure_resolved_scroll(state).ok_or(obscura_render::CaptureError::PaintFailed)?;
            let ObscuraState {
                dom,
                prepared_render,
                render_resources,
                resolved_scroll,
                canvas_surfaces,
                ..
            } = state;
            let (_, scroll) = resolved_scroll
                .as_ref()
                .ok_or(obscura_render::CaptureError::PaintFailed)?;
            let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
            obscura_render::paint_prepared_region_with_scroll_and_surface_color_and_canvas_surfaces(
                dom.as_ref()
                    .ok_or(obscura_render::CaptureError::PaintFailed)?,
                prepared_render
                    .as_mut()
                    .ok_or(obscura_render::CaptureError::PaintFailed)?,
                render_resources,
                scroll,
                region,
                surface_color,
                &canvas_surfaces,
            )
        })
    }

    /// Capture a document-space rectangle with the PDF print-background
    /// policy without mutating the page DOM or retained geometry.
    #[cfg(feature = "render")]
    pub fn screenshot_prepared_region_with_backgrounds(
        &self,
        region: obscura_render::CaptureRegion,
        paint_backgrounds: bool,
    ) -> Result<Vec<u8>, obscura_render::CaptureError> {
        let mut state = self.state.borrow_mut();
        with_sync_render_loading_disabled(&mut state, |state| {
            ensure_resolved_scroll(state).ok_or(obscura_render::CaptureError::PaintFailed)?;
            let ObscuraState {
                dom,
                prepared_render,
                render_resources,
                resolved_scroll,
                canvas_surfaces,
                ..
            } = state;
            let (_, scroll) = resolved_scroll
                .as_ref()
                .ok_or(obscura_render::CaptureError::PaintFailed)?;
            let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
            obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
                dom.as_ref()
                    .ok_or(obscura_render::CaptureError::PaintFailed)?,
                prepared_render
                    .as_mut()
                    .ok_or(obscura_render::CaptureError::PaintFailed)?,
                render_resources,
                scroll,
                region,
                paint_backgrounds,
                &canvas_surfaces,
            )
        })
    }

    /// Capture one immutable document slice as if its origin were the root
    /// scroll position of a virtual viewport. This leaves the live page scroll
    /// untouched while giving fixed and sticky descendants page-local paint
    /// geometry, which paginated raster PDF export requires.
    #[cfg(feature = "render")]
    pub fn screenshot_prepared_region_at_scroll_with_backgrounds(
        &self,
        region: obscura_render::CaptureRegion,
        root_scroll: (f32, f32),
        paint_backgrounds: bool,
    ) -> Result<Vec<u8>, obscura_render::CaptureError> {
        let mut state = self.state.borrow_mut();
        with_sync_render_loading_disabled(&mut state, |state| {
            ensure_resolved_scroll(state).ok_or(obscura_render::CaptureError::PaintFailed)?;
            let ObscuraState {
                dom,
                prepared_render,
                render_resources,
                element_scroll_offsets,
                canvas_surfaces,
                ..
            } = state;
            let dom = dom
                .as_ref()
                .ok_or(obscura_render::CaptureError::PaintFailed)?;
            let scroll = prepared_render
                .as_ref()
                .ok_or(obscura_render::CaptureError::PaintFailed)?
                .resolve_scroll_state_for_viewport(
                    dom,
                    root_scroll,
                    element_scroll_offsets,
                    (region.width, region.height),
                );
            let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
            obscura_render::screenshot_prepared_region_with_scroll_and_backgrounds_and_canvas_surfaces(
                dom,
                prepared_render
                    .as_mut()
                    .ok_or(obscura_render::CaptureError::PaintFailed)?,
                render_resources,
                &scroll,
                region,
                paint_backgrounds,
                &canvas_surfaces,
            )
        })
    }

    /// Return the retained layout's scrollable document size without changing
    /// the live viewport or scroll position. PDF/full-document consumers use
    /// this to paginate document-space captures from the same geometry.
    #[cfg(feature = "render")]
    pub fn prepared_content_size(&self) -> Option<(f32, f32)> {
        let mut state = self.state.borrow_mut();
        with_sync_render_loading_disabled(&mut state, |state| {
            ensure_resolved_scroll(state)?;
            state
                .prepared_render
                .as_ref()
                .map(|render| render.content_size())
        })
    }

    /// Return the exact responsive candidates selected for live `<img>`
    /// elements and `<video poster>` resources without loading them. The
    /// browser layer can then fetch them concurrently through the page-owned
    /// transport before synchronous layout or paint observes the cache.
    #[cfg(feature = "render")]
    pub fn pending_render_image_urls(&self) -> Vec<(String, crate::ops::ImageRequestProfile)> {
        let state = self.state.borrow();
        let base_url = document_base_url(&state);
        let Some(dom) = state.dom.as_ref() else {
            return Vec::new();
        };
        let mut urls = Vec::new();
        for id in dom.descendants(dom.document()) {
            let Some(node) = dom.get_node(id) else {
                continue;
            };
            let Some(element) = node.as_element() else {
                continue;
            };
            let candidate = match element.local.as_ref() {
                "img" => state
                    .render_resources
                    .cached_image_element_metadata(dom, id, state.viewport, base_url.as_deref())
                    .map(|(url, _, known, _)| {
                        let profile = match node
                            .get_attribute("crossorigin")
                            .map(|value| value.trim().to_ascii_lowercase())
                            .as_deref()
                        {
                            Some("use-credentials") => crate::ops::ImageRequestProfile::CorsInclude,
                            Some(_) => crate::ops::ImageRequestProfile::CorsSameOrigin,
                            None => crate::ops::ImageRequestProfile::NoCorsInclude,
                        };
                        (url, profile, known)
                    }),
                "video" => state
                    .render_resources
                    .cached_video_poster_metadata(dom, id, base_url.as_deref())
                    .map(|(url, profile, known, _)| (url, profile, known)),
                _ => None,
            };
            let Some((url, profile, known)) = candidate else {
                continue;
            };
            if !known && !url.starts_with("data:") {
                urls.push((url, profile));
            }
        }
        urls.sort();
        urls.dedup();
        urls
    }

    /// Insert one page-transport resource outcome into the retained renderer
    /// cache. Successful image/font bytes queue one resource-dependent layout
    /// refresh while preserving computed styles and any DOM damage already
    /// queued. A negative outcome cannot change geometry and preserves the
    /// retained layout/scroll.
    #[cfg(feature = "render")]
    pub fn seed_render_resource(&mut self, url: String, bytes: Option<Vec<u8>>) {
        self.seed_shared_render_resource(url, bytes.map(std::sync::Arc::from));
    }

    #[cfg(feature = "render")]
    fn seed_shared_render_resource(&mut self, url: String, bytes: Option<std::sync::Arc<[u8]>>) {
        let mut state = self.state.borrow_mut();
        match bytes {
            Some(bytes) => {
                state.render_resources.seed_shared(url, bytes);
                crate::ops::invalidate_render_resource_geometry(&mut state);
            }
            None => state.render_resources.seed_missing(url),
        }
    }

    #[cfg(feature = "render")]
    pub fn seed_render_image_resource(
        &mut self,
        url: String,
        profile: crate::ops::ImageRequestProfile,
        bytes: Option<Vec<u8>>,
    ) {
        self.seed_shared_render_image_resource(url, profile, bytes.map(std::sync::Arc::from));
    }

    #[cfg(feature = "render")]
    fn seed_shared_render_image_resource(
        &mut self,
        url: String,
        profile: crate::ops::ImageRequestProfile,
        bytes: Option<std::sync::Arc<[u8]>>,
    ) {
        let mut state = self.state.borrow_mut();
        match bytes {
            Some(bytes) if obscura_render::image_intrinsic_dimensions(&bytes).is_some() => {
                let needs_geometry = match (&state.prepared_render, &state.dom) {
                    (Some(prepared), Some(dom)) => {
                        prepared.image_resource_needs_geometry(dom, &url, profile)
                    }
                    _ => true,
                };
                state
                    .render_resources
                    .seed_image_shared(url, profile, bytes);
                state.activity_generation = state.activity_generation.wrapping_add(1);
                if needs_geometry {
                    crate::ops::invalidate_render_resource_geometry(&mut state);
                }
            }
            _ => state.render_resources.seed_image_missing(url, profile),
        }
    }

    #[cfg(feature = "render")]
    pub fn render_resource_is_known(&self, url: &str) -> bool {
        self.state.borrow().render_resources.has_live_outcome(url)
    }

    /// Whether layout and paint may still open synchronous compatibility
    /// requests. False for every runtime owned by a page transport.
    #[cfg(feature = "render")]
    pub fn render_resource_sync_loading_enabled(&self) -> bool {
        self.state.borrow().render_resources.sync_loading_enabled()
    }

    #[cfg(test)]
    fn document_generation(&self) -> u64 {
        self.state.borrow().document_generation
    }

    /// Resources cache-only layout or paint asked for and did not have, ready
    /// for the page transport: blocked URLs are remembered as missing instead
    /// of returned, URLs already loading are skipped, the rest are marked in
    /// flight. Cheap when nothing was missed.
    #[cfg(feature = "render")]
    pub fn take_render_resource_requests(
        &self,
    ) -> Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)> {
        let mut state = self.state.borrow_mut();
        if !state.render_resources.has_sync_misses() {
            return Vec::new();
        }
        let misses = state.render_resources.take_sync_misses();
        let mut requests = Vec::new();
        for (url, profile, is_font) in misses {
            // Fetch interception patterns pause requests; they are not a URL
            // blocklist. Static renderer resources currently pass through,
            // while Network.setBlockedURLs remains authoritative here.
            let blocked = state
                .blocked_urls
                .iter()
                .any(|pattern| crate::ops::glob_match(pattern, &url));
            let allowed = page_render_resource_url_allowed(&state.url, &url);
            if blocked || !allowed {
                match profile {
                    Some(profile) => state.render_resources.seed_image_missing(url, profile),
                    None => state.render_resources.seed_missing(url),
                }
                continue;
            }
            if state.render_resource_in_flight.len() >= MAX_PENDING_RENDER_RESOURCES {
                continue;
            }
            if state
                .render_resource_in_flight
                .insert((url.clone(), profile, is_font))
            {
                requests.push((url, profile, is_font));
            }
        }
        requests
    }

    /// Mark resources the page discovered itself (navigation warmup scan) as
    /// loading, returning the ones that were not already in flight.
    #[cfg(feature = "render")]
    pub fn mark_render_resources_in_flight(
        &self,
        candidates: Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)>,
    ) -> Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)> {
        let mut state = self.state.borrow_mut();
        let available =
            MAX_PENDING_RENDER_RESOURCES.saturating_sub(state.render_resource_in_flight.len());
        candidates
            .into_iter()
            .filter(|(url, profile, is_font)| {
                state
                    .render_resource_in_flight
                    .insert((url.clone(), *profile, *is_font))
            })
            .take(available)
            .collect()
    }

    /// Abort every background load of this document and discard results
    /// that already arrived. The page calls this when the document goes away
    /// (navigation, blank reset, suspension, teardown); `set_dom` and
    /// `take_dom` do the same. Aborting drops the in-progress HTTP requests;
    /// a load that is past the point of no return delivers into the old,
    /// dropped channel.
    #[cfg(feature = "render")]
    pub fn abandon_render_resources(&self) {
        let mut state = self.state.borrow_mut();
        for task in state.render_resource_tasks.drain(..) {
            task.abort();
        }
        state.render_resource_in_flight.clear();
        state.render_resource_backlog.clear();
        state.render_resource_events.clear();
        // A fresh channel fences results that are still on their way (abort
        // is not a join) even when this runtime survives, as after a failed
        // navigation.
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        state.render_resource_tx = tx;
        state.render_resource_rx = rx;
    }

    /// Cancel this document's current loads without letting the next render
    /// turn rediscover and restart them. Future new URLs can still load.
    #[cfg(feature = "render")]
    pub fn stop_render_resource_loading(&mut self) {
        self.service_render_resources();
        let (pending, backlog, queued, images) = {
            let mut state = self.state.borrow_mut();
            (std::mem::take(&mut state.render_resource_in_flight),
                std::mem::take(&mut state.render_resource_backlog),
                state.render_resources.take_sync_misses(),
                std::mem::take(&mut state.render_image_in_flight))
        };
        self.abandon_render_resources();
        let mut state = self.state.borrow_mut();
        for (url, profile, _) in pending.into_iter().chain(backlog).chain(queued) {
            state.render_resources.stop_resource(&url, profile);
        }
        for ((_, url, profile), (cancel, _)) in images {
            state.render_resources.stop_resource(&url, Some(profile));
            let _ = cancel.send(());
        }
    }

    /// Whether a page transport (plain or stealth client) is installed.
    #[cfg(feature = "render")]
    pub fn has_page_transport(&self) -> bool {
        crate::ops::has_page_transport(&self.state.borrow())
    }

    /// Wake-up shared with the background loads: notified after every
    /// finished load. Waiters must create and enable their `Notified`
    /// before checking `has_pending_render_resources`, or a load finishing
    /// in between is missed.
    #[cfg(feature = "render")]
    pub fn render_resource_notify(&self) -> std::sync::Arc<tokio::sync::Notify> {
        self.state.borrow().render_resource_notify.clone()
    }

    /// Start page-transport loads for `requests` (already marked in flight).
    /// Requests keep cookies, proxy policy, callbacks, CORS and response
    /// limits of the page transport, share the page-wide concurrency limit,
    /// run to completion in the background and deliver into this runtime's
    /// result channel. Outside a Tokio context the requests are kept in a
    /// backlog and started at the next event-loop turn. Returns the number
    /// of requests started now.
    #[cfg(feature = "render")]
    pub fn start_render_resource_loads(
        &self,
        requests: Vec<(String, Option<crate::ops::ImageRequestProfile>, bool)>,
    ) -> usize {
        if requests.is_empty() {
            return 0;
        }
        let mut state = self.state.borrow_mut();
        if tokio::runtime::Handle::try_current().is_err() {
            state.render_resource_backlog.extend(requests);
            return 0;
        }
        // The page transport is the plain client or, when installed, the
        // stealth client; either one on its own is enough (`has_page_transport`).
        let http_client = state.http_client.clone();
        #[cfg(feature = "stealth")]
        let stealth_client = state.stealth_client.clone();
        let initiator = url::Url::parse(&state.url).ok();
        if !crate::ops::has_page_transport(&state) || initiator.is_none() {
            // No transport or no document URL: nothing can be loaded; forget
            // the in-flight marks so a later scan may retry.
            for request in &requests {
                state.render_resource_in_flight.remove(request);
            }
            return 0;
        }
        let initiator = initiator.expect("checked above");
        let callbacks = state.callbacks.clone();
        let generation = state.document_generation;
        let tx = state.render_resource_tx.clone();
        let limiter = state.render_resource_limiter.clone();
        let notify = state.render_resource_notify.clone();
        let started = requests.len();
        let task = tokio::spawn(async move {
            use deno_core::futures::StreamExt as _;
            let loads = deno_core::futures::stream::iter(requests.into_iter().map(
                |(raw, profile, is_font)| {
                let http_client = http_client.clone();
                #[cfg(feature = "stealth")]
                let stealth_client = stealth_client.clone();
                let callbacks = callbacks.clone();
                let initiator = initiator.clone();
                let limiter = limiter.clone();
                let fallback = (raw.clone(), profile, is_font);
                let load = async move {
                    // Every load of this page waits for the same permits, so
                    // repeated scans cannot multiply the request rate.
                    let _permit = limiter.acquire_owned().await.ok();
                    let parsed = match url::Url::parse(&raw) {
                        Ok(parsed) => parsed,
                        Err(_) => {
                            return crate::ops::RenderResourceLoad {
                                generation,
                                url: raw,
                                profile,
                                is_font,
                                response: None,
                                };
                        }
                    };
                    let kind = if is_font {
                        obscura_net::ResourceType::Font
                    } else {
                        obscura_net::ResourceType::Image
                    };
                    let mut request = ResourceRequest::subresource(kind, &initiator);
                    match profile {
                        Some(crate::ops::ImageRequestProfile::CorsSameOrigin) => {
                            request.mode = RequestMode::Cors;
                            request.credentials = RequestCredentials::SameOrigin;
                        }
                        Some(crate::ops::ImageRequestProfile::CorsInclude) => {
                            request.mode = RequestMode::Cors;
                            request.credentials = RequestCredentials::Include;
                        }
                        _ => {}
                    }
                    #[cfg(feature = "stealth")]
                    let response = match (stealth_client, http_client) {
                        (Some(stealth_client), _) => stealth_client
                                .fetch_resource_with_callbacks(
                                    &parsed,
                                    request,
                                    callbacks.as_deref(),
                                )
                            .await
                            .ok(),
                        (None, Some(http_client)) => http_client
                                .fetch_resource_with_callbacks(
                                    &parsed,
                                    request,
                                    callbacks.as_deref(),
                                )
                            .await
                            .ok(),
                        (None, None) => None,
                    };
                    #[cfg(not(feature = "stealth"))]
                    let response = match http_client {
                        Some(http_client) => http_client
                                .fetch_resource_with_callbacks(
                                    &parsed,
                                    request,
                                    callbacks.as_deref(),
                                )
                            .await
                            .ok(),
                        None => None,
                    };
                    crate::ops::RenderResourceLoad {
                        generation,
                        url: raw,
                        profile,
                        is_font,
                        response: response.map(|response| crate::ops::RenderResourceResponse {
                            url: response.url.to_string(),
                            status: response.status,
                            headers: response.headers,
                            body: std::sync::Arc::from(response.body),
                        }),
                    }
                };
                // One failing load must not strand the rest of the batch: an
                // in-flight entry without a result would keep waiters waiting.
                use deno_core::futures::FutureExt as _;
                std::panic::AssertUnwindSafe(load)
                    .catch_unwind()
                    .map(move |outcome| {
                        outcome.unwrap_or_else(|_| crate::ops::RenderResourceLoad {
                            generation,
                            url: fallback.0,
                            profile: fallback.1,
                            is_font: fallback.2,
                            response: None,
                        })
                    })
                },
            ))
            .buffer_unordered(crate::ops::RENDER_RESOURCE_CONCURRENCY);
            deno_core::futures::pin_mut!(loads);
            while let Some(load) = loads.next().await {
                tracing::debug!(
                    url = %load.url,
                    ok = load.response.is_some(),
                    "render resource load finished"
                );
                if tx.send(load).is_err() {
                    break;
                }
                notify.notify_waiters();
            }
            notify.notify_waiters();
        });
        state
            .render_resource_tasks
            .retain(|task| !task.is_finished());
        state.render_resource_tasks.push(task);
        tracing::debug!(
            started,
            generation,
            "started background render resource loads"
        );
        started
    }

    /// One service step for the renderer's resources: apply every finished
    /// load, then start loads for everything layout or paint missed since
    /// the last step. Runs at every event-loop turn and promise wait of this
    /// runtime, so a script that creates a miss while a command is waiting
    /// still gets its bytes without a further protocol round trip. Returns
    /// the number of loads that stored usable bytes.
    #[cfg(feature = "render")]
    pub fn service_render_resources(&mut self) -> usize {
        {
            let state = self.state.borrow();
            if state.render_resource_rx.is_empty()
                && state.render_resource_backlog.is_empty()
                && !state.render_resources.has_sync_misses()
            {
                return 0;
            }
        }
        let loaded = self.apply_render_resource_results();
        let mut requests = std::mem::take(&mut self.state.borrow_mut().render_resource_backlog);
        requests.extend(self.take_render_resource_requests());
        self.start_render_resource_loads(requests);
        loaded
    }

    /// Whether page-transport loads are still running for this document.
    #[cfg(feature = "render")]
    pub fn has_pending_render_resources(&self) -> bool {
        !self.state.borrow().render_resource_in_flight.is_empty()
    }

    /// Apply every finished page-transport load without waiting. Called at
    /// the runtime's own event-loop turns and promise waits and by the page
    /// around protocol commands, so late bytes reach layout, paint and the
    /// lifecycle getters wherever the runtime is being driven. Returns the
    /// number of loads that stored usable bytes.
    #[cfg(feature = "render")]
    pub fn apply_render_resource_results(&mut self) -> usize {
        let loads = {
            let mut state = self.state.borrow_mut();
            let mut loads = Vec::new();
            while let Ok(load) = state.render_resource_rx.try_recv() {
                loads.push(load);
            }
            loads
        };
        let mut loaded = 0;
        for load in loads {
            let generation = self.state.borrow().document_generation;
            if load.generation != generation {
                // A previous document's response: no seed, no event, and it
                // must not clear a same-URL request of the current document.
                tracing::debug!(url = %load.url, "discarded render resource load of a retired document");
                continue;
            }
            self.state.borrow_mut().render_resource_in_flight.remove(&(
                load.url.clone(),
                load.profile,
                load.is_font,
            ));
            let is_font = load.is_font;
            let bytes = match &load.response {
                Some(response) if (200..300).contains(&response.status) => {
                    loaded += 1;
                    Some(std::sync::Arc::clone(&response.body))
                }
                _ => None,
            };
            tracing::debug!(url = %load.url, loaded = bytes.is_some(), "applied render resource load");
            match load.profile {
                Some(profile) => self.seed_shared_render_image_resource(load.url, profile, bytes),
                None => self.seed_shared_render_resource(load.url, bytes),
            }
            if let Some(response) = load.response {
                self.state
                    .borrow_mut()
                    .render_resource_events
                    .push(crate::ops::RenderResourceEvent { is_font, response });
            }
        }
        loaded
    }

    /// Applied transport responses the page has not reported as Network
    /// events yet.
    #[cfg(feature = "render")]
    pub fn take_render_resource_events(&self) -> Vec<crate::ops::RenderResourceEvent> {
        std::mem::take(&mut self.state.borrow_mut().render_resource_events)
    }

    #[cfg(feature = "render")]
    pub fn render_image_resource_is_known(
        &self,
        url: &str,
        profile: crate::ops::ImageRequestProfile,
    ) -> bool {
        self.state
            .borrow()
            .render_resources
            .has_live_image_outcome(url, profile)
    }

    #[doc(hidden)]
    pub fn set_frame_preload_scripts(&self, scripts: &[String]) {
        self.realm_states().borrow_mut().frame_preload_scripts = scripts.to_vec();
    }

    /// Run __obscura_init() after all per-page properties (UA, platform, stealth, etc.)
    /// have been set. Must be called once per page setup, after all set_* methods.
    pub fn run_page_init(&mut self) {
        self.state.borrow_mut().navigation_timing.record("domLoading");
        let _ = self.execute_script_with_timeout(
            "<obscura:page-init>",
            "globalThis.__obscura_init();",
            std::time::Duration::from_secs(5),
        );
    }

    pub fn navigation_timing(&self) -> crate::ops::NavigationTiming {
        self.state.borrow().navigation_timing.clone()
    }

    pub fn set_navigation_timing(&self, timing: crate::ops::NavigationTiming) {
        self.state.borrow_mut().navigation_timing = timing;
    }

    pub fn record_navigation_timing(&self, name: &str) {
        self.state.borrow_mut().navigation_timing.record(name);
    }

    /// Override the coordinates the navigator.geolocation shim reports. The
    /// values are injected as numeric globals the bootstrap reads; when unset it
    /// keeps the built-in default. Callers validate the range before calling.
    pub fn set_geolocation(&mut self, latitude: f64, longitude: f64) {
        let _ = self.execute_runtime_script(
            "<set-geo>",
            format!(
                "globalThis.__obscura_geo_lat={};globalThis.__obscura_geo_lon={};",
                latitude, longitude
            ),
        );
    }

    pub fn evaluate(&mut self, expression: &str) -> Result<serde_json::Value, String> {
        #[cfg(feature = "render")]
        self.service_render_resources();
        self.begin_javascript_task();
        let wrapped = Self::wrap_expression(expression);
        let result = self
            .execute_runtime_script("<eval>", wrapped)
            .map_err(|e| format!("JS error: {}", e))?;
        self.v8_to_json(result)
    }

    /// Evaluate a script without converting an exception into a null result.
    pub fn evaluate_script(&mut self, script: &str) -> Result<serde_json::Value, String> {
        #[cfg(feature = "render")]
        self.service_render_resources();
        self.begin_javascript_task();
        let result = self.execute_runtime_script("<eval-script>", script.to_owned())?;
        self.v8_to_json(result)
    }

    /// Read host history metadata without invoking author-defined JSON hooks.
    pub fn take_history_update(&mut self) -> Result<HistoryUpdate, String> {
        #[cfg(feature = "render")]
        self.service_render_resources();
        self.begin_javascript_task();
        let result = self.execute_runtime_script("<history-update>",
            "(() => { const update = globalThis.__obscuraHistory.take(); if (update) return update; const url = globalThis.__virtualUrl; return typeof url === 'string' ? url : ''; })()".to_owned())?;
        let document_start = self.state.borrow().session_history.document_start;
        let mut entered = self.runtime();
        let context = entered.main_context();
        v8::scope_with_context!(scope, entered.v8_isolate(), context);
        let value = v8::Local::new(scope, result);
        if value.is_string() {
            return Ok(HistoryUpdate::Url(value.to_rust_string_lossy(scope)));
        }
        let update: (String, usize, usize, bool, usize, Vec<String>) =
            deno_core::serde_v8::from_v8(scope, value).map_err(|error| error.to_string())?;
        Ok(HistoryUpdate::Entries {
            url: update.0, start: document_start, index: update.1,
            old_length: update.2, truncate_forward: update.3,
            first: update.4, urls: update.5,
        })
    }

    pub async fn evaluate_for_cdp(
        &mut self,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<RemoteObjectInfo, String> {
        self.evaluate_for_cdp_with_timeout(
            expression,
            return_by_value,
            await_promise,
            DEFAULT_CDP_AWAIT_TIMEOUT_MS,
        )
        .await
    }

    pub async fn evaluate_for_cdp_with_timeout(
        &mut self,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<RemoteObjectInfo, String> {
        let evaluation = self.start_cdp_evaluation(expression, return_by_value, await_promise)?;
        self.await_cdp_evaluation(evaluation, return_by_value, await_timeout_ms, "Runtime.evaluate").await
    }

    #[doc(hidden)]
    pub fn start_cdp_evaluation(
        &mut self,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<CdpEvaluation, String> {
        self.start_cdp_evaluation_in_frame(None, expression, return_by_value, await_promise)
    }

    fn cdp_context(&mut self, frame_id: Option<u32>) -> Result<v8::Global<v8::Context>, String> {
        match frame_id {
            Some(id) => self.realm_states().borrow().context(id)
                .ok_or_else(|| "Execution context was destroyed".to_string()),
            None => Ok(self.runtime().main_context()),
        }
    }

    #[doc(hidden)]
    pub fn start_cdp_evaluation_in_frame(
        &mut self,
        frame_id: Option<u32>,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<CdpEvaluation, String> {
        let context = self.cdp_context(frame_id)?;
        self.begin_javascript_task();
        self.object_counter += 1;
        let oid = self.make_oid(self.object_counter);
        // Compile the script itself, not a string passed through the page's eval.
        let record = (|| {
            let mut entered = self.runtime();
            v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
            v8::tc_scope!(let scope, scope);
            let source = v8::String::new(scope, expression).ok_or("CDP source allocation failed")?;
            let name = v8::String::new(scope, "<eval-remote>").ok_or("CDP origin allocation failed")?;
            let origin = v8::ScriptOrigin::new(
                scope, name.into(), 0, 0, false, 0, None, false, false, false, None,
            );
            let result = v8::Script::compile(scope, source, Some(&origin))
                .and_then(|script| script.run(scope));
            if scope.is_execution_terminating() {
                scope.cancel_terminate_execution();
                return Err("JS error: Uncaught Error: execution terminated".to_string());
            }
            let rejected = result.is_none();
            let value = result.or_else(|| scope.exception())
                .ok_or("CDP evaluation failed without an exception")?;
            scope.reset();
            cdp_result_record(scope, value, rejected, await_promise)
        })();
        let record = self.finish_heap_checked(record)?;
        self.pending_cdp_evaluations.insert(oid.clone(), record);
        let pending = PendingCdpEvaluation {
            object_id: oid,
            recipe: if return_by_value || frame_id.is_some() { None } else { Some(expression.to_string()) },
            frame: frame_id.map(|id| (id, context)),
        };
        if await_promise {
            Ok(CdpEvaluation::Pending(pending))
        } else {
            self.finish_cdp_evaluation(pending, return_by_value).map(CdpEvaluation::Complete)
        }
    }

    pub async fn call_function_on_for_cdp(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        arguments: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<RemoteObjectInfo, String> {
        self.call_function_on_for_cdp_with_timeout(
            function_declaration,
            object_id,
            arguments,
            return_by_value,
            await_promise,
            DEFAULT_CDP_AWAIT_TIMEOUT_MS,
        )
        .await
    }

    pub async fn call_function_on_for_cdp_with_timeout(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        arguments: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<RemoteObjectInfo, String> {
        let evaluation = self.start_cdp_call(function_declaration, object_id, arguments, return_by_value, await_promise)?;
        self.await_cdp_evaluation(evaluation, return_by_value, await_timeout_ms, "Runtime.callFunctionOn").await
    }

    #[doc(hidden)]
    pub fn start_cdp_call(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        arguments: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<CdpEvaluation, String> {
        self.start_cdp_call_in_frame(
            None, function_declaration, object_id, arguments, return_by_value, await_promise,
        )
    }

    #[doc(hidden)]
    pub fn start_cdp_call_in_frame(
        &mut self,
        mut frame_id: Option<u32>,
        function_declaration: &str,
        object_id: Option<&str>,
        arguments: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
    ) -> Result<CdpEvaluation, String> {
        if let Some(object_id) = object_id {
            self.validate_cdp_object_context(object_id)?;
            let object_frame = self.object_store.get(object_id)
                .and_then(|record| record.frame.as_ref().map(|(id, _)| *id));
            if frame_id.is_some() && frame_id != object_frame {
                return Err("Object belongs to a different execution context".into());
            }
            frame_id = object_frame;
        }
        let context = self.cdp_context(frame_id)?;
        self.begin_javascript_task();
        let receiver = if object_id.is_some() {
            let this_expr = self.resolve_this(object_id)?;
            self.execute_runtime_script("<cdp-receiver>", this_expr)
                .map_err(|error| format!("JS error: {error}"))?
        } else {
            let mut entered = self.runtime();
            v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
            let global = scope.get_current_context().global(scope);
            let value: v8::Local<v8::Value> = global.into();
            v8::Global::new(scope, value)
        };
        let arguments = arguments.iter().map(|argument| self.cdp_call_argument(argument, &context))
            .collect::<Result<Vec<_>, _>>()?;
        self.object_counter += 1;
        let oid = self.make_oid(self.object_counter);
        let record = (|| {
            let mut entered = self.runtime();
            v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
            v8::tc_scope!(let scope, scope);
            let receiver = v8::Local::new(scope, &receiver);
            let arguments = arguments.iter().map(|argument| v8::Local::new(scope, argument))
                .collect::<Vec<_>>();
            let source = v8::String::new(scope, &format!("(\n{function_declaration}\n)"))
                .ok_or("CDP function allocation failed")?;
            let result = v8::Script::compile(scope, source, None)
                .and_then(|script| script.run(scope))
                .and_then(|value| {
                    match v8::Local::<v8::Function>::try_from(value) {
                        Ok(function) => function.call(scope, receiver, &arguments),
                        Err(_) => {
                            let message = v8::String::new(scope, "Given expression does not evaluate to a function")?;
                            let error = v8::Exception::type_error(scope, message);
                            scope.throw_exception(error);
                            None
                        }
                    }
                });
            if scope.is_execution_terminating() {
                scope.cancel_terminate_execution();
                return Err("JS error: Uncaught Error: execution terminated".into());
            }
            let rejected = result.is_none();
            let value = result.or_else(|| scope.exception())
                .ok_or("CDP call failed without an exception")?;
            scope.reset();
            cdp_result_record(scope, value, rejected, await_promise)
        })();
        let record = self.finish_heap_checked(record)?;
        self.pending_cdp_evaluations.insert(oid.clone(), record);
        let pending = PendingCdpEvaluation {
            object_id: oid, recipe: None, frame: frame_id.map(|id| (id, context)),
        };
        if await_promise {
            Ok(CdpEvaluation::Pending(pending))
        } else {
            self.finish_cdp_evaluation(pending, return_by_value).map(CdpEvaluation::Complete)
        }
    }

    #[doc(hidden)]
    pub fn has_cdp_evaluation(&self, pending: &PendingCdpEvaluation) -> bool {
        self.pending_cdp_evaluations.contains_key(&pending.object_id)
            && pending.frame.as_ref().is_none_or(|(id, context)| {
                self.realm_states().borrow().context(*id).as_ref() == Some(context)
            })
    }

    fn has_ready_cdp_evaluations(&mut self) -> bool {
        if self.pending_cdp_evaluations.is_empty() { return false; }
        let records: Vec<_> = self.pending_cdp_evaluations.values().cloned().collect();
        let mut entered = self.runtime();
        let context = entered.main_context();
        v8::scope_with_context!(scope, entered.v8_isolate(), context);
        let Some(key) = v8::String::new(scope, "done") else { return false; };
        records.into_iter().any(|record| {
            let Ok(record) = v8::Local::<v8::Object>::try_from(v8::Local::new(scope, record)) else { return false; };
            record.get(scope, key.into()).is_some_and(|value| value.is_true())
        })
    }

    #[doc(hidden)]
    pub fn cdp_evaluation_ready(&mut self, pending: &PendingCdpEvaluation) -> bool {
        if !self.has_cdp_evaluation(pending) { return false; }
        let Some(record) = self.pending_cdp_evaluations.get(&pending.object_id).cloned() else {
            return false;
        };
        let mut entered = self.runtime();
        let context = entered.main_context();
        v8::scope_with_context!(scope, entered.v8_isolate(), context);
        let Ok(record) = v8::Local::<v8::Object>::try_from(v8::Local::new(scope, record)) else {
            return false;
        };
        let Some(key) = v8::String::new(scope, "done") else { return false; };
        record.get(scope, key.into()).is_some_and(|value| value.is_true())
    }

    #[doc(hidden)]
    pub fn finish_cdp_evaluation(
        &mut self,
        pending: PendingCdpEvaluation,
        return_by_value: bool,
    ) -> Result<RemoteObjectInfo, String> {
        let oid = pending.object_id;
        let record = self.pending_cdp_evaluations.remove(&oid)
            .ok_or("Evaluation result unavailable")?;
        if pending.frame.as_ref().is_some_and(|(id, context)| {
            self.realm_states().borrow().context(*id).as_ref() != Some(context)
        }) {
            return Err("Execution context was destroyed".into());
        }
        let (value, rejected) = {
            let mut entered = self.runtime();
            let context = entered.main_context();
            v8::scope_with_context!(scope, entered.v8_isolate(), context);
            v8::tc_scope!(let scope, scope);
            let record = v8::Local::<v8::Object>::try_from(v8::Local::new(scope, record))
                .map_err(|_| "Invalid evaluation record")?;
            let done_key = v8::String::new(scope, "done").ok_or("Cannot read evaluation result")?;
            if !record.get(scope, done_key.into()).is_some_and(|value| value.is_true()) {
                return Err("Evaluation result unavailable".into());
            }
            let rejected_key = v8::String::new(scope, "rejected").ok_or("Cannot read evaluation result")?;
            let rejected = record.get(scope, rejected_key.into()).is_some_and(|value| value.is_true());
            let value_key = v8::String::new(scope, "value").ok_or("Cannot read evaluation result")?;
            let value = record.get(scope, value_key.into()).ok_or("Cannot read evaluation result")?;
            if !return_by_value || rejected {
                let objects_key = v8::String::new(scope, "__obscura_objects").ok_or("Cannot store evaluation result")?;
                let global = scope.get_current_context().global(scope);
                let objects = global.get(scope, objects_key.into())
                    .and_then(|value| value.to_object(scope)).ok_or("Cannot store evaluation result")?;
                let key = v8::String::new(scope, &oid).ok_or("Cannot store evaluation result")?;
                if objects.set(scope, key.into(), value) != Some(true) {
                    return Err("Cannot store evaluation result".into());
                }
            }
            (v8::Global::new(scope, value), rejected)
        };
        if return_by_value && !rejected { return self.v8_to_cdp_value(value); }
        let meta = if let Some((_, context)) = &pending.frame {
            let result = (|| {
                let mut entered = self.runtime();
                v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
                v8::tc_scope!(let scope, scope);
                let source = format!("(function(value) {{ return {}; }})", Self::meta_extract_js("value"));
                let source = v8::String::new(scope, &source).ok_or("CDP metadata allocation failed")?;
                let function = v8::Script::compile(scope, source, None)
                    .and_then(|script| script.run(scope))
                    .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
                    .ok_or_else(|| exception_text(scope))?;
                let value = v8::Local::new(scope, &value);
                let receiver = v8::undefined(scope).into();
                let result = function.call(scope, receiver, &[value])
                    .ok_or_else(|| exception_text(scope))?;
                Ok(v8::Global::new(scope, result))
            })();
            self.finish_heap_checked(result)?
        } else {
            self.execute_runtime_script(
                "<readMeta>", Self::meta_extract_js(&format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid))),
            ).map_err(|e| format!("JS error: {e}"))?
        };
        let meta = self.v8_to_json(meta)?;
        let meta = if let serde_json::Value::String(value) = &meta {
            serde_json::from_str(value).unwrap_or(meta)
        } else { meta };
        let mut info = self.finish_cdp_result(&meta, &oid)?;
        info.thrown = rejected;
        if info.object_id.is_some() {
            self.object_store.get_mut(&oid).ok_or("Cannot store evaluation context")?.frame = pending.frame;
        }
        if !rejected && info.object_id.is_some() {
            if let Some(recipe) = pending.recipe { self.evaluation_recipes.insert(oid, recipe); }
        }
        Ok(info)
    }

    #[doc(hidden)]
    pub fn cancel_cdp_evaluation(&mut self, pending: PendingCdpEvaluation) {
        self.pending_cdp_evaluations.remove(&pending.object_id);
    }

    async fn await_cdp_evaluation(
        &mut self,
        evaluation: CdpEvaluation,
        return_by_value: bool,
        timeout_ms: u64,
        method: &str,
    ) -> Result<RemoteObjectInfo, String> {
        let pending = match evaluation {
            CdpEvaluation::Complete(info) => return Ok(info),
            CdpEvaluation::Pending(pending) => pending,
        };
        if !self.resolve_promises_until(|rt| rt.cdp_evaluation_ready(&pending), timeout_ms).await {
            self.cancel_cdp_evaluation(pending);
            return Err(format!("{method} promise did not settle within {timeout_ms}ms"));
        }
        self.finish_cdp_evaluation(pending, return_by_value)
    }
    pub async fn call_function_on(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        arguments: &[serde_json::Value],
        return_by_value: bool,
    ) -> Result<RemoteObjectInfo, String> {
        self.call_function_on_for_cdp(
            function_declaration,
            object_id,
            arguments,
            return_by_value,
            false,
        )
        .await
    }
    pub fn store_object(&mut self, js_expression: &str) -> Result<String, String> {
        self.begin_javascript_task();
        self.object_counter += 1;
        let oid = self.make_oid(self.object_counter);
        let code = format!(
            "globalThis.__obscura_objects[{}] = ({});",
            js_string_literal(&oid), js_expression,
        );
        self.execute_runtime_script("<store>", code)
            .map_err(|e| format!("Store error: {}", e))?;
        self.object_store.insert(
            oid.clone(),
            CdpObjectRecord {
                retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(&oid)),
                frame: None,
            },
        );
        Ok(oid)
    }

    pub fn store_object_with_meta(
        &mut self,
        js_expression: &str,
    ) -> Result<RemoteObjectInfo, String> {
        self.begin_javascript_task();
        self.object_counter += 1;
        let oid = self.make_oid(self.object_counter);
        let code = format!(
            "(function() {{\n\
                var __result = (\n{expr}\n);\n\
                globalThis.__obscura_objects[{oid}] = __result;\n\
                return {meta_fn};\n\
            }})()",
            expr = js_expression,
            oid = js_string_literal(&oid),
            meta_fn = Self::meta_extract_js("__result"),
        );
        let result = self
            .execute_runtime_script("<store-meta>", code)
            .map_err(|e| format!("Store error: {}", e))?;
        let meta_str = self.v8_to_json(result)?;
        let meta_json = if let serde_json::Value::String(s) = &meta_str {
            serde_json::from_str(s).unwrap_or(meta_str.clone())
        } else {
            meta_str
        };
        self.finish_cdp_result(&meta_json, &oid)
    }

    #[doc(hidden)]
    pub fn validate_cdp_object_context(&self, object_id: &str) -> Result<(), String> {
        let record = self.object_store.get(object_id);
        if record.is_none() && !self.evaluation_recipes.contains_key(object_id)
            && !object_id.strip_prefix("node-").is_some_and(|id| {
                !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()) && id.parse::<u32>().is_ok()
            })
        {
            return Err("Could not find object with given id".into());
        }
        if record.and_then(|record| record.frame.as_ref())
            .is_some_and(|(id, context)| self.realm_states().borrow().context(*id).as_ref() != Some(context))
        {
            return Err("Execution context was destroyed".into());
        }
        Ok(())
    }

    #[doc(hidden)]
    pub fn cdp_object_expression(&mut self, object_id: &str) -> Result<String, String> {
        self.validate_cdp_object_context(object_id)?;
        self.resolve_this(Some(object_id))
    }

    #[doc(hidden)]
    pub fn register_cdp_property_object(&mut self, parent_id: &str, object_id: &str) -> Result<(), String> {
        self.validate_cdp_object_context(parent_id)?;
        let frame = self.object_store.get(parent_id).and_then(|record| record.frame.clone());
        self.object_store.insert(object_id.to_string(), CdpObjectRecord {
            retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id)),
            frame,
        });
        Ok(())
    }

    pub fn release_object(&mut self, object_id: &str) {
        self.evaluation_recipes.remove(object_id);
        if let Some(record) = self.object_store.remove(object_id) {
            let code = format!("delete ({});", record.retrieval);
            let _ = self.execute_runtime_script("<release>", code);
        }
    }

    pub fn release_object_group(&mut self) {
        let _ = self.execute_runtime_script("<releaseGroup>", "globalThis.__obscura_objects = {};".to_string());
        self.object_store.clear();
        self.evaluation_recipes.clear();
    }

    pub fn take_cdp_object_state(&mut self) -> CdpObjectState {
        CdpObjectState {
            object_counter: self.object_counter,
            evaluation_recipes: std::mem::take(&mut self.evaluation_recipes),
        }
    }

    pub fn restore_cdp_object_state(&mut self, state: CdpObjectState) {
        self.object_counter = self.object_counter.max(state.object_counter);
        self.evaluation_recipes = state.evaluation_recipes;
    }
    pub async fn load_module(&mut self, url: &str, budget_ms: u64) -> Result<(), String> {
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(budget_ms);
        let prepared = self.prepare_module(url, budget_ms).await?;
        let remaining_ms = remaining_deadline_ms(deadline).ok_or_else(|| {
            format!(
                "Module {} exhausted its {}ms load+evaluation budget",
                url, budget_ms
            )
        })?;
        self.evaluate_prepared_module(prepared, remaining_ms).await
    }

    pub async fn prepare_module(
        &mut self,
        url: &str,
        budget_ms: u64,
    ) -> Result<PreparedModule, String> {
        let budget = tokio::time::Duration::from_millis(budget_ms);
        let specifier = deno_core::ModuleSpecifier::parse(url)
            .map_err(|e| format!("Invalid module URL {}: {}", url, e))?;
        let loaded_start = self.loaded_module_specifiers.borrow().len();

        // Bound the recursive import-graph fetch. deno_core fetches the graph
        // concurrently through the one page-scoped module loader. Loading the
        // entry from that loader too is important: cookies, configured request
        // headers, redirects, interception, and callbacks must not change at
        // the first import edge.
        // The caller sizes the budget: short for enhancement modules on an
        // already-rendered page, full for an unmounted SPA shell (#205).
        let load = entered_runtime_future(&mut self.js_runtime, |runtime| {
            runtime.load_side_es_module(&specifier)
        });
        let module_id = match tokio::time::timeout(budget, load).await {
            Ok(Ok(id)) => id,
            Ok(Err(e)) => return Err(format!("Module load error: {}", e)),
            Err(_) => {
                return Err(format!(
                    "Module graph load timed out after {}ms: {}",
                    budget_ms, url
                ));
            }
        };

        // Return as soon as the module finishes evaluating rather than waiting
        // for the loop to go fully idle: a page timer (setInterval) keeps the
        // loop busy forever and would otherwise burn the whole budget (#374).
        let mut graph_specifiers = self.loaded_module_specifiers.borrow()[loaded_start..].to_vec();
        graph_specifiers.push(specifier.to_string());
        graph_specifiers.sort_unstable();
        graph_specifiers.dedup();

        Ok(PreparedModule {
            module_id,
            description: format!("Module {}", url),
            entry_specifier: Some(specifier.to_string()),
            graph_specifiers,
        })
    }

    /// Drive a just-started module evaluation to completion, or up to
    /// `budget_ms`. Returns as soon as the module finishes rather than waiting
    /// for the event loop to go idle: a page timer (setInterval) keeps the loop
    /// busy forever and would otherwise burn the whole budget, abandoning a
    /// module that had already evaluated (issue #374).
    ///
    /// A module eval error or timeout is returned to the page lifecycle. The
    /// caller may continue rendering, but must not report a failed module as
    /// successfully loaded. An event-loop error is propagated out of the
    /// select and handled the same way.
    async fn drive_module_eval(
        &mut self,
        module_id: deno_core::ModuleId,
        budget_ms: u64,
        what: &str,
    ) -> Result<(), String> {
        if let Some(outcome) = self.module_evaluations.get(&module_id) {
            return outcome.clone();
        }

        self.begin_javascript_task();
        let budget = tokio::time::Duration::from_millis(budget_ms);
        // deno_core 0.350 asserts instead of treating a second evaluation as
        // the module-map no-op required by browsers. The local outcome cache
        // covers duplicate roots prepared by Obscura. A root can also have
        // been evaluated earlier as another graph's dependency, which is only
        // observable when mod_evaluate checks V8's private module status, so
        // contain that dependency assertion at this boundary as well.
        let evaluation = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            self.runtime().mod_evaluate(module_id)
        }));
        let result = match evaluation {
            Ok(result) => result,
            Err(payload) => {
                let message = panic_payload_message(payload.as_ref());
                let outcome = if message.contains("Module already evaluated") {
                    self.runtime()
                        .get_module_namespace(module_id)
                        .map(|_| ())
                        .map_err(|error| format!("{} eval error: {}", what, error))
                } else {
                    Err(format!("{} evaluation panicked: {}", what, message))
                };
                self.module_evaluations.insert(module_id, outcome.clone());
                return outcome;
            }
        };
        tokio::pin!(result);

        let outcome = tokio::time::timeout(
            budget,
            std::future::poll_fn(|cx| {
                let mut entered = self.runtime();
                match entered.poll_event_loop(cx, deno_core::PollEventLoopOptions::default()) {
                    Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
                    Poll::Ready(Ok(())) => result.as_mut().poll(cx),
                    Poll::Pending => result.as_mut().poll(cx),
                }
            }),
        )
        .await;

        let outcome = match outcome {
            Ok(Ok(())) => self
                .runtime()
                .get_module_namespace(module_id)
                .map(|_| ())
                .map_err(|error| format!("{} eval error: {}", what, error)),
            Ok(Err(e)) => Err(format!("{} eval error: {}", what, e)),
            Err(_) => Err(format!(
                "{} evaluation timed out after {}ms",
                what, budget_ms
            )),
        };
        let outcome = self.finish_heap_checked(outcome);
        self.module_evaluations.insert(module_id, outcome.clone());
        outcome
    }

    pub async fn load_inline_module(
        &mut self,
        code: &str,
        base_url: &str,
        budget_ms: u64,
    ) -> Result<(), String> {
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(budget_ms);
        let prepared = self
            .prepare_inline_module(code, base_url, budget_ms)
            .await?;
        let remaining_ms = remaining_deadline_ms(deadline).ok_or_else(|| {
            format!(
                "Inline module exhausted its {}ms load+evaluation budget",
                budget_ms
            )
        })?;
        self.evaluate_prepared_module(prepared, remaining_ms).await
    }

    pub async fn prepare_inline_module(
        &mut self,
        code: &str,
        base_url: &str,
        budget_ms: u64,
    ) -> Result<PreparedModule, String> {
        let budget = tokio::time::Duration::from_millis(budget_ms);
        // Inline modules use the document base URL as their module URL. This is
        // observable through import.meta.url and is also the referrer used for
        // relative imports and import-map scope matching. deno_core permits
        // multiple side modules with this name; the returned ModuleId keeps
        // each prepared module distinct until its scheduled evaluation.
        let specifier = deno_core::ModuleSpecifier::parse(base_url)
            .unwrap_or_else(|_| deno_core::ModuleSpecifier::parse("about:blank").unwrap());
        let loaded_start = self.loaded_module_specifiers.borrow().len();

        let load = entered_runtime_future(&mut self.js_runtime, |runtime| {
            runtime.load_side_es_module_from_code(
                &specifier,
                deno_core::ModuleCodeString::from(code.to_string()),
            )
        });
        let module_id = match tokio::time::timeout(budget, load).await {
            Ok(Ok(id)) => id,
            Ok(Err(e)) => return Err(format!("Inline module load error: {}", e)),
            Err(_) => {
                return Err(format!(
                    "Inline module graph load timed out after {}ms",
                    budget_ms
                ));
            }
        };

        // Return as soon as the module finishes evaluating rather than waiting
        // for idle: Vite's HMR / React-Refresh client installs a setInterval that
        // keeps the loop busy forever, and waiting for idle burned the whole
        // budget on this preamble module and starved the module that mounts the
        // app, leaving #root empty (issue #374).
        let mut graph_specifiers = self.loaded_module_specifiers.borrow()[loaded_start..].to_vec();
        graph_specifiers.sort_unstable();
        graph_specifiers.dedup();

        Ok(PreparedModule {
            module_id,
            description: "Inline module".to_string(),
            // Multiple inline modules intentionally share the document URL,
            // but each has its own source and ModuleId.
            entry_specifier: None,
            graph_specifiers,
        })
    }

    pub async fn evaluate_prepared_module(
        &mut self,
        prepared: PreparedModule,
        budget_ms: u64,
    ) -> Result<(), String> {
        let PreparedModule {
            module_id,
            description,
            entry_specifier,
            graph_specifiers,
        } = prepared;
        if let Some(outcome) = entry_specifier
            .as_ref()
            .and_then(|specifier| self.evaluated_module_specifiers.get(specifier))
        {
            return outcome.clone();
        }
        // Tokio timeouts cannot run while synchronous top-level module work
        // pins the runtime thread in V8. Pair the async timeout with a hard V8
        // watchdog so this budget is a real wall-clock ceiling for both forms
        // of evaluation.
        let watchdog = self.arm_watchdog(std::time::Duration::from_millis(budget_ms));
        let result = self
            .drive_module_eval(module_id, budget_ms, &description)
            .await;
        let watchdog_fired = self.disarm_watchdog(watchdog);
        let result = if watchdog_fired {
            Err(format!(
                "{} evaluation timed out after {}ms",
                description, budget_ms
            ))
        } else {
            result
        };

        if let Some(entry_specifier) = entry_specifier {
            self.evaluated_module_specifiers
                .insert(entry_specifier, result.clone());
        }
        if result.is_ok() {
            for specifier in graph_specifiers {
                self.evaluated_module_specifiers.insert(specifier, Ok(()));
            }
        }
        result
    }

    fn execute_classic_script(&mut self, name: &str, source: &str) -> Result<(), String> {
        self.begin_javascript_task();
        let script_url = name.to_string();
        // Reuse only serialized compilation data, never a context or live value.
        // Exact source matching also protects same-URL, same-length edits that
        // V8's cache validation alone does not identify. Internal/eval snippets
        // and opaque document origins do not enter this process-wide cache.
        let cache_origin = (source.len() >= 4096 && source.len() <= CLASSIC_CODE_CACHE_BYTES / 2
            && url::Url::parse(name).is_ok_and(|url| matches!(url.scheme(), "http" | "https")))
            .then(|| url::Url::parse(&self.state.borrow().url).ok())
            .flatten()
            .filter(|url| matches!(url.scheme(), "http" | "https"))
            .map(|url| url.origin().ascii_serialization());
        let cached = cache_origin.as_deref().and_then(|origin| cached_classic_code(origin, name, source));
        let source_text = source;
        // JsRuntime::execute_script in deno_core 0.350 restricts `name` to a
        // &'static str. Browser script URLs are runtime data, and V8 uses this
        // origin as import()'s referrer, so compile in the runtime's main
        // context directly instead of substituting the fixed "<script>" name.
        let result: Result<(), (String, Option<Box<deno_core::error::JsError>>)> = (|| {
            let mut entered = self.runtime();
            let context = entered.main_context();
            let isolate = entered.v8_isolate();
            v8::scope!(let scope, isolate);
            let context = v8::Local::new(scope, context);
            let scope = &mut v8::ContextScope::new(scope, context);
            let source = deno_core::v8::String::new(scope, source)
                .ok_or_else(|| ("JS error: source allocation failed".to_string(), None))?;
            let name = deno_core::v8::String::new(scope, name)
                .ok_or_else(|| ("JS error: script URL allocation failed".to_string(), None))?;
            let origin = deno_core::v8::ScriptOrigin::new(
                scope,
                name.into(),
                0,
                0,
                false,
                0,
                None,
                false,
                false,
                false,
                None,
            );
            v8::tc_scope!(let tc_scope, scope);
            let mut compilation = match cached.as_deref() {
                Some(bytes) => v8::script_compiler::Source::new_with_cached_data(
                    source, Some(&origin), v8::script_compiler::CachedData::new(bytes)),
                None => v8::script_compiler::Source::new(source, Some(&origin)),
            };
            let script = v8::script_compiler::compile(
                tc_scope, &mut compilation,
                if cached.is_some() { v8::script_compiler::CompileOptions::ConsumeCodeCache }
                else { v8::script_compiler::CompileOptions::NoCompileOptions },
                v8::script_compiler::NoCacheReason::NoReason,
            );
            let Some(script) = script else {
                if tc_scope.is_execution_terminating() {
                    tc_scope.cancel_terminate_execution();
                    return Err((
                        "JS error: Uncaught Error: execution terminated".to_string(),
                        None,
                    ));
                }
                return match tc_scope.exception() {
                    Some(exception) => {
                        let error =
                            deno_core::error::JsError::from_v8_exception(tc_scope, exception);
                        Err((format!("JS error: {error}"), Some(error)))
                    }
                    None => Err((
                        "JS error: script compilation failed without an exception".to_string(),
                        None,
                    )),
                };
            };
            if script.run(tc_scope).is_none() {
                if tc_scope.is_execution_terminating() {
                    tc_scope.cancel_terminate_execution();
                    return Err((
                        "JS error: Uncaught Error: execution terminated".to_string(),
                        None,
                    ));
                }
                return match tc_scope.exception() {
                    Some(exception) => {
                        let error =
                            deno_core::error::JsError::from_v8_exception(tc_scope, exception);
                        Err((format!("JS error: {error}"), Some(error)))
                    }
                    None => Err((
                        "JS error: script execution failed without an exception".to_string(),
                        None,
                    )),
                };
            }
            let cache_accepted = compilation.get_cached_data().is_some_and(|data| !data.rejected());
            #[cfg(test)]
            if cache_accepted {
                CLASSIC_CODE_CACHE_ACCEPTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
            // A browser runs the microtask checkpoint at the end of each task.
            // queueMicrotask/observer delivery from this script is observable
            // to the caller (canvas damage, resize/intersection bookkeeping).
            tc_scope.perform_microtask_checkpoint();
            if !cache_accepted {
                if let Some(cache_origin) = cache_origin.as_deref() {
                    if let Some(data) = script.get_unbound_script(tc_scope).create_code_cache() {
                        remember_classic_code(cache_origin, &script_url, source_text, &data);
                    }
                }
            }
            Ok(())
        })();
        let result = match result {
            Ok(()) => Ok(()),
            Err((message, error)) => {
                if let Some(error) = error.as_ref() {
                    self.record_uncaught_exception(error, &script_url);
                }
                Err(message)
            }
        };
        self.finish_heap_checked(result)
    }

    pub fn execute_script(&mut self, name: &str, source: &str) -> Result<(), String> {
        self.execute_classic_script(name, source)
    }

    pub fn execute_script_guarded(&mut self, name: &str, source: &str) -> Result<(), String> {
        if source.len() < 10_000 {
            self.execute_script(name, source)
        } else {
            self.execute_script_with_timeout(name, source, std::time::Duration::from_secs(5))
        }
    }

    pub fn execute_script_with_timeout(
        &mut self,
        name: &str,
        source: &str,
        timeout: std::time::Duration,
    ) -> Result<(), String> {
        if timeout.is_zero() {
            return self.execute_classic_script(name, source);
        }

        let watchdog = self.arm_watchdog(timeout);
        let result = self.execute_classic_script(name, source);
        self.disarm_watchdog(watchdog);

        match result {
            Ok(()) => Ok(()),
            Err(msg) => {
                if msg.contains("Uncaught Error: execution terminated") {
                    tracing::warn!("Script killed after {}s timeout", timeout.as_secs());
                    Ok(())
                } else {
                    Err(msg)
                }
            }
        }
    }

    pub async fn run_event_loop(&mut self) -> Result<(), String> {
        self.begin_javascript_task();
        // A browser performs a microtask checkpoint at the end of each task.
        // deno_core's event loop may return immediately when no async op is
        // pending, leaving an already-resolved Promise continuation stranded
        // (document.fonts.load(...).then(...), framework post-render hooks,
        // and hydration follow-ups all rely on this boundary).
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        let event_loop = entered_runtime_future(&mut self.js_runtime, |runtime| {
            runtime.run_event_loop(deno_core::PollEventLoopOptions::default())
        });
        let result = event_loop
            .await
            .map_err(|e| format!("Event loop error: {}", e));
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        self.finish_heap_checked(result)
    }

    /// Poll page work, then park until the runtime's timer/I/O waker fires.
    /// Unlike run-to-idle, an already idle runtime does not complete the first
    /// poll. Lifecycle callers can wait for their quiet-window deadline without
    /// busy-polling, and can recheck network state after each subsequent wake.
    /// The caller owns the timeout and synchronous-execution watchdog.
    #[doc(hidden)]
    pub async fn wait_for_event_loop_activity(&mut self) -> Result<(), String> {
        self.begin_javascript_task();
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        let mut waiting_for_wake = false;
        let result = std::future::poll_fn(|cx| {
            let tick = self
                .runtime()
                .poll_event_loop(cx, deno_core::PollEventLoopOptions::default());
            match tick {
                std::task::Poll::Ready(Err(error)) => {
                    std::task::Poll::Ready(Err(format!("Event loop error: {error}")))
                }
                _ if waiting_for_wake => std::task::Poll::Ready(Ok(())),
                _ => {
                    // poll_event_loop registers this waker even at true idle.
                    // Do not self-wake: real work or the caller's deadline
                    // will schedule the next poll.
                    waiting_for_wake = true;
                    std::task::Poll::Pending
                }
            }
        })
        .await;
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        self.finish_heap_checked(result)
    }

    /// Whether the serialized dynamic-script queue is still fetching or
    /// evaluating a script. The queue stays private to the bootstrap closure;
    /// Rust reads it through a hidden status function so page declarations
    /// cannot collide with or overwrite the queue itself.
    pub fn has_pending_dynamic_scripts(&mut self) -> bool {
        let pending_dom_script = self
            .evaluate("globalThis.__obscura_hasPendingDynamicScripts?.() === true")
            .ok()
            .and_then(|value| value.as_bool())
            .unwrap_or(false);
        // A short tail bridges the parser/evaluator hand-off between one
        // fetched module and the next dependency. It is below the lifecycle's
        // existing 500ms fast-settle floor, so static entry graphs pay no new
        // latency while lazy import graphs remain observable. deno_core's
        // dynamic-module evaluation/TLA counters are private; the event-loop
        // pump itself remains responsible for that non-fetch portion.
        pending_dom_script
            || self
                .module_load_activity
                .is_pending_or_recent(std::time::Duration::from_millis(100))
    }

    /// Whether a connected dynamic script prepared before the document load
    /// event still has fetch/evaluation/load-or-error work outstanding.
    ///
    /// This intentionally excludes `import()` and scripts created by a load
    /// handler. Those are ordinary post-load enhancement work and should only
    /// be driven when an automation caller explicitly asks the page to settle.
    pub fn has_pending_load_delaying_scripts(&mut self) -> bool {
        self.evaluate("globalThis.__obscura_hasPendingLoadDelayingScripts?.() === true")
            .ok()
            .and_then(|value| value.as_bool())
            .unwrap_or(false)
    }

    /// Whether a parser-blocking script inserted by `document.write()` still
    /// has fetch or evaluation work outstanding.
    pub fn has_pending_parser_blocking_scripts(&mut self) -> bool {
        self.evaluate("globalThis.__obscura_hasPendingParserBlockingScripts?.() === true")
        .ok()
        .and_then(|value| value.as_bool())
        .unwrap_or(false)
    }

    /// Consume the native signal that the current parser script called
    /// `document.write()` with a script node.
    pub fn take_document_write_inserted_script(&self) -> bool {
        self.state
            .borrow()
            .document_write_inserted_script
            .replace(false)
    }

    /// Generation of observable connected-document mutations. This excludes
    /// detached-tree construction and no-op writes, which cannot affect a
    /// screenshot or DOM dump.
    pub fn activity_generation(&self) -> u64 {
        self.state.borrow().activity_generation
    }

    fn has_pending_network_requests(&self) -> bool {
        let state = self.state.borrow();
        state
            .page_in_flight
            .load(std::sync::atomic::Ordering::Relaxed)
            > 0
    }

    fn next_pending_timeout_delay_ms(&mut self) -> Option<f64> {
        self.evaluate("globalThis.__obscura_nextPendingTimeoutDelay?.() ?? -1")
        .ok()
        .and_then(|value| value.as_f64())
        .filter(|delay| *delay >= 0.0)
    }

    /// Arm a hard wall-clock backstop on synchronous V8 work. A page stuck in a
    /// synchronous loop or a microtask storm pins the OS thread inside V8, so
    /// `tokio::time::timeout` (which can only cancel at await points) never
    /// fires. The shared watchdog thread terminates the isolate once
    /// `budget` elapses, forcing V8 to throw an uncatchable error and hand
    /// control back. Always balance with [`Self::disarm_watchdog`].
    pub fn arm_watchdog(&mut self, budget: std::time::Duration) -> WatchdogToken {
        spawn_watchdog(self.runtime().v8_isolate().thread_safe_handle(), budget)
    }

    /// Stop a watchdog armed by [`Self::arm_watchdog`]. If it had already fired
    /// (terminated the isolate), clear V8's termination flag so the isolate is
    /// usable again, and return `true`.
    pub fn disarm_watchdog(&mut self, token: WatchdogToken) -> bool {
        let fired = token.stop();
        if fired {
            self.runtime().v8_isolate().cancel_terminate_execution();
            tracing::warn!("V8 watchdog fired: terminated a synchronous overrun");
        }
        fired
    }

    /// This runtime's V8 isolate handle (captured at construction, stable for
    /// the isolate's life). Lets the CDP dispatcher arm a per-command watchdog
    /// from `&self`.
    pub fn isolate_handle(&self) -> IsolateHandle {
        self.isolate_handle.clone()
    }

    /// Clear V8's termination flag after a watchdog armed externally (via the
    /// isolate handle) fired, so the isolate is usable for the next command.
    /// No-op when the isolate is not terminating.
    pub fn cancel_termination(&mut self) {
        self.runtime().v8_isolate().cancel_terminate_execution();
    }

    /// Drive the event loop for at most `budget_ms`, bounded against BOTH async
    /// idle (Tokio deadline) and synchronous hangs (V8 watchdog). The deadline
    /// is observed between browser tasks; a task already running there gets a
    /// five-second completion allowance plus a 500ms scheduling margin before
    /// the watchdog terminates it. A well-behaved page returns as soon as the
    /// loop goes idle.
    pub async fn run_event_loop_bounded(&mut self, budget_ms: u64) -> Result<(), String> {
        #[cfg(feature = "render")]
        self.service_render_resources();
        if budget_ms == 0 {
            return self.run_event_loop().await;
        }
        let budget = std::time::Duration::from_millis(budget_ms);
        let deadline = tokio::time::Instant::now() + budget;
        // A capture/readiness deadline is observed only between browser tasks.
        // Chromium does not terminate the JavaScript task which happens to be
        // active when a screenshot delay expires; the capture waits for that
        // task boundary. Keep a separate long-task floor so short compositor
        // slices and explicit waits do not kill legitimate framework work,
        // while an actually unyielding task remains bounded.
        // One watchdog for the complete pump avoids spawning a native thread
        // per cooperative task. Adding the floor after the observation budget
        // guarantees that even a task beginning just before `deadline` gets
        // the same bounded completion allowance.
        let synchronous_budget =
            budget.saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS));
        let token = self.arm_watchdog(
            synchronous_budget + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),
        );
        let result = loop {
            if tokio::time::Instant::now() >= deadline {
                break Ok(());
            }
            // Timer-driven page script observes resources that landed during
            // the interval, and misses it creates start loading right away.
            #[cfg(feature = "render")]
            self.service_render_resources();

            match tokio::time::timeout_at(deadline, self.run_cooperative_event_loop_tick()).await {
                Ok(Ok(true)) => break Ok(()),
                Ok(Ok(false)) => {
                    // End-of-task microtasks belong to this turn, but work
                    // queued from them belongs to a subsequent cooperative
                    // turn. The cooperative helper yields to Tokio even when
                    // every turn immediately schedules another one.
                    self.runtime().v8_isolate().perform_microtask_checkpoint();
                }
                Ok(Err(error)) => {
                    if is_fatal_event_loop_error(&error) {
                        break Err(error);
                    }
                    // A page task threw or a promise rejected without a
                    // handler. Chrome reports it and keeps scheduling; the
                    // pump must do the same, or one throwing script starves
                    // every later task (#699). The wall deadline above still
                    // bounds a page that errors on every turn.
                    tracing::warn!("page task error, continuing the event loop: {error}");
                }
                Err(_) => break Ok(()),
            }
        };
        let fired = self.disarm_watchdog(token);
        match result {
            Err(error) if error.contains("heap limit exceeded") => Err(error),
            Err(error) if fired || error.contains("execution terminated") => Ok(()),
            other => other,
        }
    }

    /// Drive page tasks for a fixed observation interval without asking
    /// deno_core's run-to-idle future to own that entire interval.
    ///
    /// Modern schedulers commonly keep the event loop continuously ready with
    /// animation frames, zero-delay tasks, or streaming work. A single
    /// `run_event_loop()` poll then never yields to Tokio, so the fixed-delay
    /// deadline can only be enforced by terminating otherwise valid page JS.
    /// Cooperative turns preserve the requested wall interval while returning
    /// to the embedder between task-queue wakes. The watchdog remains solely as
    /// a backstop for one genuinely synchronous, unyielding turn.
    pub async fn run_event_loop_for_duration(&mut self, budget_ms: u64) -> Result<(), String> {
        if budget_ms == 0 {
            return Ok(());
        }
        self.run_event_loop_bounded(budget_ms).await
    }

    /// Return after a poll that delivers browser tasks. If the first poll
    /// has no ready task, wait for its registered waker and process one more
    /// poll before returning, including V8 maintenance wakes. Busy turns also
    /// yield to Tokio so every caller can make network and timer progress.
    ///
    /// `JsRuntime::run_event_loop()` is a run-to-idle future. When a page keeps
    /// it continuously ready (zero-delay schedulers, streaming traffic, or a
    /// framework work queue), Tokio never regains control to observe a timeout
    /// or our readiness policy. A pending poll can already have delivered a
    /// task; do not await another wake in that case. If no work is immediately
    /// ready, it remains parked on deno_core's real I/O/timer waker, so the
    /// adaptive settle loop does not poll at a fixed frequency.
    async fn run_cooperative_event_loop_tick(&mut self) -> Result<bool, String> {
        self.begin_javascript_task();
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        let mut waiting_for_wake = false;
        let result = std::future::poll_fn(|cx| {
            let task_generation = self.state.borrow().animation_task_generation;
            let tick = self
                .runtime()
                .poll_event_loop(cx, deno_core::PollEventLoopOptions::default());
            match tick {
                std::task::Poll::Ready(Ok(())) => std::task::Poll::Ready(Ok(true)),
                std::task::Poll::Ready(Err(error)) => {
                    std::task::Poll::Ready(Err(format!("Event loop error: {error}")))
                }
                std::task::Poll::Pending if waiting_for_wake
                    || self.state.borrow().animation_task_generation != task_generation =>
                {
                    std::task::Poll::Ready(Ok(false))
                }
                std::task::Poll::Pending => {
                    waiting_for_wake = true;
                    std::task::Poll::Pending
                }
            }
        })
        .await;
        if matches!(result, Ok(false)) {
            tokio::task::yield_now().await;
        }
        self.finish_heap_checked(result)
    }

    /// Drive one browser task while allowing the future to remain parked on
    /// deno_core's real timer/network waker. This is the long-lived browser
    /// server counterpart to bounded screenshot settling: the owner selects
    /// this future alongside incoming protocol commands, so a page continues
    /// to make progress while the automation client is idle without polling at
    /// a fixed frequency.
    ///
    /// The shared CDP watchdog is armed only around synchronous V8 entry. It is
    /// deliberately disarmed while `Poll::Pending`; a legitimate distant timer
    /// must not look like a hung JavaScript task merely because the runtime is
    /// asleep waiting for it.
    #[doc(hidden)]
    pub async fn run_autonomous_event_loop_turn(&mut self) -> Result<bool, String> {
        const AUTONOMOUS_TASK_WATCHDOG_MS: u64 =
            SYNCHRONOUS_TASK_FLOOR_MS + WATCHDOG_SCHEDULING_MARGIN_MS;

        #[cfg(feature = "render")]
        self.service_render_resources();
        self.begin_javascript_task();

        let checkpoint_watchdog = crate::cdp_watchdog::arm(
            self.isolate_handle(),
            std::time::Duration::from_millis(AUTONOMOUS_TASK_WATCHDOG_MS),
        );
        self.runtime().v8_isolate().perform_microtask_checkpoint();
        if crate::cdp_watchdog::disarm(checkpoint_watchdog) {
            self.cancel_termination();
            return Err("autonomous microtask checkpoint exceeded its task budget".into());
        }
        if self.recover_heap_limit() {
            return Err("JavaScript heap limit exceeded; execution terminated".into());
        }

        // Let the page adopt frame documents and deliver messages before parking.
        if self.has_ready_cdp_evaluations() || self.has_pending_frame_tasks() { return Ok(false); }

        let isolate_handle = self.isolate_handle();
        let mut waiting_for_wake = false;
        let result = std::future::poll_fn(|cx| {
            let task_generation = self.state.borrow().animation_task_generation;
            let watchdog = crate::cdp_watchdog::arm(
                isolate_handle.clone(),
                std::time::Duration::from_millis(AUTONOMOUS_TASK_WATCHDOG_MS),
            );
            let tick = self
                .runtime()
                .poll_event_loop(cx, deno_core::PollEventLoopOptions::default());
            let watchdog_fired = crate::cdp_watchdog::disarm(watchdog);
            if watchdog_fired {
                self.runtime().v8_isolate().cancel_terminate_execution();
                return std::task::Poll::Ready(Err(
                    "autonomous browser task exceeded its task budget".into(),
                ));
            }
            if self.has_ready_cdp_evaluations() || self.has_pending_frame_tasks() {
                return std::task::Poll::Ready(Ok(false));
            }
            match tick {
                std::task::Poll::Ready(Ok(())) => std::task::Poll::Ready(Ok(true)),
                // A page task error (uncaught exception, unhandled rejection)
                // is page-local in a browser: log it, report one delivered
                // task, and let the owner keep pumping (#699).
                std::task::Poll::Ready(Err(error))
                    if !is_fatal_event_loop_error(&error.to_string()) =>
                {
                    tracing::warn!("page task error, continuing the event loop: {error}");
                    std::task::Poll::Ready(Ok(false))
                }
                std::task::Poll::Ready(Err(error)) => {
                    std::task::Poll::Ready(Err(format!("Event loop error: {error}")))
                }
                std::task::Poll::Pending if waiting_for_wake
                    || self.state.borrow().animation_task_generation != task_generation =>
                {
                    std::task::Poll::Ready(Ok(false))
                }
                std::task::Poll::Pending => {
                    waiting_for_wake = true;
                    std::task::Poll::Pending
                }
            }
        })
        .await;
        if matches!(result, Ok(false)) {
            tokio::task::yield_now().await;
        }
        self.finish_heap_checked(result)
    }

    /// Drive one cooperative event-loop turn for browser lifecycle code that
    /// must re-check an external readiness predicate after every wake. The
    /// boolean is true only when deno_core reached full idle.
    #[doc(hidden)]
    pub async fn run_load_delaying_event_loop_tick(&mut self) -> Result<bool, String> {
        #[cfg(feature = "render")]
        self.service_render_resources();
        self.run_cooperative_event_loop_tick().await
    }

    /// Pump deferred work until deno_core reports true idle, or until the page
    /// has had no connected-document mutation, relevant request/dynamic-script
    /// work, or near-term one-shot timeout for `quiet_ms`. Network and script
    /// work gets a bounded post-load grace period: this retains ordinary app
    /// hydration without allowing analytics, telemetry, or a hung endpoint to
    /// consume the caller's complete budget. Long timers and perpetual visual
    /// mutations are bounded separately for the same reason.
    /// `budget_ms` remains an absolute wall-clock bound.
    pub async fn run_event_loop_until_quiescent(
        &mut self,
        budget_ms: u64,
        quiet_ms: u64,
    ) -> Result<(), String> {
        if budget_ms == 0 {
            return Ok(());
        }

        let budget = std::time::Duration::from_millis(budget_ms);
        let quiet = std::time::Duration::from_millis(quiet_ms.max(1).min(budget_ms));
        let started = tokio::time::Instant::now();
        let deadline = started + budget;
        // A one-second grace covers the common load -> fetch -> framework
        // commit path (and matches the CLI's established one-second useful
        // hydration window), but it is intentionally independent of a larger
        // caller budget. Requests which remain pending after this point are no
        // longer readiness evidence by themselves. Their eventual connected
        // DOM mutation is still observed during the bounded activity tail.
        const EXTERNAL_WORK_GRACE_MS: u64 = 1_000;
        const OBSERVABLE_ACTIVITY_TAIL_MS: u64 = 500;
        let external_work_grace =
            std::time::Duration::from_millis(EXTERNAL_WORK_GRACE_MS).min(budget);
        let external_work_deadline = started + external_work_grace;
        let activity_tail = std::time::Duration::from_millis(OBSERVABLE_ACTIVITY_TAIL_MS);
        let mut activity_deadline = deadline.min(started + activity_tail);
        let token = self.arm_watchdog(
            budget.saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS))
                + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),
        );
        let mut generation = self.activity_generation();
        let mut quiet_since: Option<tokio::time::Instant> = None;
        let result = loop {
            #[cfg(feature = "render")]
            self.service_render_resources();
            let now = tokio::time::Instant::now();
            let Some(_remaining) = deadline.checked_duration_since(now) else {
                break Ok(());
            };
            let next_generation = self.activity_generation();
            // One-shot timers up to two quiet windows away are commonly app
            // hydration/debounce work (`setTimeout(render, 200)`). Intervals
            // are intentionally excluded, and distant one-shots are treated
            // like Chromium after `load`: callers needing an arbitrary fixed
            // delay can request strict settle.
            let near_timeout = self
                .next_pending_timeout_delay_ms()
                .is_some_and(|delay| delay <= quiet.as_secs_f64() * 2_000.0);
            let external_work_pending = now < external_work_deadline
                && (self.has_pending_network_requests() || self.has_pending_dynamic_scripts());
            if external_work_pending {
                activity_deadline = deadline.min(external_work_deadline + activity_tail);
                generation = next_generation;
                quiet_since = None;
            } else if now < activity_deadline && near_timeout {
                generation = next_generation;
                quiet_since = None;
            } else {
                if now < activity_deadline && next_generation != generation {
                    // A mutation starts a fresh quiet interval at its observed
                    // delivery time. There is no need for a fixed-rate poll to
                    // discover that the interval has begun.
                    quiet_since = Some(now);
                }
                generation = next_generation;
                let since = quiet_since.get_or_insert(now);
                if now.duration_since(*since) >= quiet {
                    break Ok(());
                }
            }

            // Park on the runtime's actual waker. The policy deadline is only
            // a fallback for a hung request, a quiet-window expiry, or the
            // caller's absolute budget; it is not a periodic polling quantum.
            let policy_deadline = if external_work_pending {
                external_work_deadline
            } else if now < activity_deadline && near_timeout {
                activity_deadline
            } else {
                quiet_since.map_or(deadline, |since| since + quiet)
            }
            .min(deadline);
            // deno_core's public poll is one event-loop iteration, but an
            // iteration may synchronously drain an arbitrarily long chain of
            // nextTick/macrotask/microtask callbacks before returning. Tokio's
            // deadline cannot preempt that native V8 call. Bound the individual
            // turn beyond the readiness horizon by the same bounded task
            // allowance as fixed waits. The observation window may expire
            // while valid framework/layout work is running; browser capture
            // waits for that task boundary instead of terminating it midway.
            let tick_watchdog = self.arm_watchdog(
                policy_deadline.saturating_duration_since(now)
                    + std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)
                    + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),
            );
            let tick =
                tokio::time::timeout_at(policy_deadline, self.run_cooperative_event_loop_tick())
            .await;
            let tick_fired = self.disarm_watchdog(tick_watchdog);
            if tick_fired {
                break Ok(());
            }
            self.runtime().v8_isolate().perform_microtask_checkpoint();
            match tick {
                Ok(Ok(true)) => break Ok(()),
                Ok(Ok(false)) | Err(_) => {}
                // A page task error is page-local noise, not a reason to stop
                // settling: later timers and fetches still run (#699).
                Ok(Err(error)) if !is_fatal_event_loop_error(&error) => {
                    tracing::warn!("page task error, continuing the event loop: {error}");
                }
                Ok(Err(error)) => break Err(error),
            }
        };
        let fired = self.disarm_watchdog(token);
        match result {
            Err(error) if error.contains("heap limit exceeded") => Err(error),
            Err(error) if fired || error.contains("execution terminated") => Ok(()),
            other => other,
        }
    }

    /// Like [`Self::evaluate`] but bounded by a V8 watchdog, so a `--eval`
    /// expression that loops forever (or awaits a promise that never settles in
    /// synchronous form) cannot hang the process.
    pub fn evaluate_with_timeout(
        &mut self,
        expression: &str,
        timeout: std::time::Duration,
    ) -> Result<serde_json::Value, String> {
        if timeout.is_zero() {
            return self.evaluate(expression);
        }
        self.begin_javascript_task();
        let wrapped = Self::wrap_expression(expression);
        let token = self.arm_watchdog(timeout);
        let result = self.runtime().execute_script("<eval>", wrapped);
        let fired = self.disarm_watchdog(token);
        if self.recover_heap_limit() {
            return Err("JavaScript heap limit exceeded; execution terminated".to_string());
        }
        match result {
            Ok(v) if !fired => self.v8_to_json(v),
            Ok(_) => Err("eval timed out".to_string()),
            Err(e) => {
                let msg = e.to_string();
                if fired || msg.contains("execution terminated") {
                    Err("eval timed out".to_string())
                } else {
                    Err(format!("JS error: {}", msg))
                }
            }
        }
    }

    pub async fn resolve_promises(&mut self) {
        self.begin_javascript_task();
        // Default settle: just pump until idle or 5s.
        let event_loop = entered_runtime_future(&mut self.js_runtime, |runtime| {
            runtime.run_event_loop(deno_core::PollEventLoopOptions::default())
        });
        let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), event_loop).await;
        self.recover_heap_limit();
    }

    /// Pump the event loop until `done_check` returns true (e.g. an IIFE
    /// has written its result sentinel), or `max_total_ms` elapses. Returns
    /// whether the predicate completed before the deadline.
    ///
    /// Why this exists: `run_event_loop(default)` only returns when there is
    /// no pending work. Page JS routinely schedules long setTimeouts
    /// (IntersectionObserver re-fires at 7s, requestIdleCallback, etc.) that
    /// the caller does not care about. With the plain timeout we waited 5s
    /// even when the IIFE we cared about resolved in <1ms — the click flow
    /// added ~7s per click because Puppeteer's `isIntersectingViewport`
    /// disconnects its observer in the callback, but our scheduled
    /// re-fires keep the event loop "busy" until they all fire.
    pub async fn resolve_promises_until<F>(&mut self, mut done_check: F, max_total_ms: u64) -> bool
    where
        F: FnMut(&mut Self) -> bool,
    {
        let deadline =
            tokio::time::Instant::now() + tokio::time::Duration::from_millis(max_total_ms);
        let mut tick_ms: u64 = 1;
        loop {
            #[cfg(feature = "render")]
            self.service_render_resources();
            self.begin_javascript_task();
            // An already-resolved evaluation only needs its promise reactions.
            // Polling the whole event loop first also executes unrelated ready
            // timers/rendering callbacks, which can delay a trivial CDP read by
            // seconds. Keep those tasks for the autonomous browser pump.
            self.runtime().v8_isolate().perform_microtask_checkpoint();
            if self.recover_heap_limit() {
                return false;
            }
            if done_check(self) {
                return true;
            }
            if tokio::time::Instant::now() >= deadline {
                return false;
            }
            // Return between browser turns even when a framework keeps its
            // posted-task queue ready. A run-to-idle wait can spend the whole
            // slice in JS, then repeatedly observe expired sleeps without
            // yielding to the network reactor.
            let slice_deadline = (tokio::time::Instant::now()
                + tokio::time::Duration::from_millis(tick_ms)).min(deadline);
            let turn = tokio::time::timeout_at(
                slice_deadline, self.run_cooperative_event_loop_tick(),
            ).await;
            if self.recover_heap_limit() {
                return false;
            }
            if done_check(self) {
                return true;
            }
            if matches!(turn, Ok(Ok(true)) | Ok(Err(_))) {
                // An idle loop or repeated page error must not spin while
                // an unresolvable promise remains pending.
                tokio::time::sleep_until(slice_deadline).await;
                tick_ms = (tick_ms * 2).min(50);
            } else {
                // A busy turn may already exceed the slice. An expired sleep
                // is not a yield; let I/O and other tasks make progress now.
                tokio::task::yield_now().await;
            }
        }
    }
    pub fn take_dom(&self) -> Option<DomTree> {
        let mut state = self.state.borrow_mut();
        state.base_url_cache.get_mut().take();
        #[cfg(feature = "render")]
        {
            state.prepared_render = None;
            state.style_query_cache = None;
            state.pending_style_mutations.clear();
            let render_resources = crate::ops::fresh_render_resources(&state);
            state.render_resources = render_resources;
            for task in state.render_resource_tasks.drain(..) {
                task.abort();
            }
            state.render_resource_in_flight.clear();
            state.render_resource_backlog.clear();
            state.render_resource_events.clear();
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
            state.render_resource_tx = tx;
            state.render_resource_rx = rx;
            state.stylesheet_cache = obscura_render::StylesheetCache::default();
            state.dynamic_fonts.clear();
            state.element_scroll_offsets.clear();
            state.resolved_scroll = None;
        }
        state.take_dom()
    }

    /// Export document-owned script preparation state before the runtime realm
    /// is temporarily destroyed.  Page suspension keeps the DOM alive, so the
    /// HTML "already started" flags must travel with it rather than resetting
    /// like window-global JavaScript state.
    pub fn started_script_ids(&self) -> Vec<u32> {
        let state = self.state.borrow();
        let mut ids = state
            .already_started_scripts
            .borrow()
            .iter()
            .map(|node_id| node_id.raw())
            .collect::<Vec<_>>();
        ids.sort_unstable();
        ids
    }

    /// Restore script preparation state only onto script nodes in the current
    /// DOM.  Callers use this exclusively for the same DomTree surviving a
    /// suspend/resume cycle; normal set_dom navigation starts from an empty set.
    pub fn restore_started_script_ids(&self, ids: &[u32]) {
        let state = self.state.borrow();
        let Some(dom) = state.dom.as_ref() else {
            return;
        };
        let valid = ids
            .iter()
            .copied()
            .map(NodeId::new)
            .filter(|node_id| node_is_script(dom, *node_id))
            .collect::<Vec<_>>();
        state.already_started_scripts.borrow_mut().extend(valid);
    }

    pub fn with_dom<R>(&self, f: impl FnOnce(&DomTree) -> R) -> Option<R> {
        let state = self.state.borrow();
        // Native callers can mutate this interior-mutable tree without a JS
        // activity notification. Do not retain a base value across that access.
        // No-render builds retain their existing JS-only cache behavior.
        #[cfg(feature = "render")]
        state.base_url_cache.borrow_mut().take();
        state.dom.as_ref().map(f)
    }

    /// The live child browsing context owned by a node in the specified realm.
    pub fn child_frame_for_node(&self, parent_frame_id: u32, node: NodeId) -> Option<u32> {
        let realms = self.realm_states();
        let realms = realms.borrow();
        let parent = if parent_frame_id == 0 { self.state.clone() }
            else { realms.by_frame_id(parent_frame_id)? };
        realms.child_frame_for_node(&parent, node)
    }

    /// Inspect a genuine remote node in its owning document, including foreign
    /// handles returned through the parent realm. Detached frame handles fail
    /// instead of resolving the same numeric node id in the main document.
    pub fn with_remote_dom_node<R>(&mut self, object_id: &str,
        inspect: impl FnOnce(&DomTree, NodeId, u32, &str, &str) -> R) -> Result<R, String> {
        self.begin_javascript_task();
        let retrieval = self.cdp_object_expression(object_id)?;
        let receiver = self.execute_runtime_script("<cdp-dom-node>", retrieval)
            .map_err(|error| format!("Could not resolve remote node: {error}"))?;
        let watchdog = self.arm_watchdog(std::time::Duration::from_secs(5));
        let reference = (|| {
            let mut entered = self.runtime();
            let context = entered.main_context();
            v8::scope_with_context!(scope, entered.v8_isolate(), context);
            v8::tc_scope!(let scope, scope);
            let receiver = v8::Local::new(scope, &receiver);
            let object = v8::Local::<v8::Object>::try_from(receiver)
                .map_err(|_| "Remote object is not a DOM node".to_string())?;
            let (frame_id, members) = crate::ops::document_realm(scope, object)
                .ok_or("Remote node has no owning document")?;
            let key = v8::String::new(scope, "domNodeReference").ok_or("DOM member allocation failed")?;
            let member = members.get(scope, key.into()).ok_or("DOM node member unavailable")?;
            let function = v8::Local::<v8::Function>::try_from(member)
                .map_err(|_| "DOM node member is not a function".to_string())?;
            let value = function.call(scope, receiver, &[])
                .ok_or_else(|| format!("Could not inspect remote node: {}", exception_text(scope)))?;
            let metadata = v8::Local::<v8::Array>::try_from(value)
                .map_err(|_| "Remote node metadata is unavailable".to_string())?;
            let node_id = metadata.get_index(scope, 0).and_then(|value| value.integer_value(scope))
                .and_then(|id| u32::try_from(id).ok())
                .ok_or("Remote object is not a current DOM node")?;
            let url = metadata.get_index(scope, 1).filter(|value| value.is_string())
                .ok_or("Remote document URL is unavailable")?.to_rust_string_lossy(scope);
            let base = metadata.get_index(scope, 2).filter(|value| value.is_string())
                .ok_or("Remote document base URL is unavailable")?.to_rust_string_lossy(scope);
            Ok::<_, String>((frame_id, NodeId::new(node_id), url, base))
        })();
        let fired = self.disarm_watchdog(watchdog);
        if fired { return Err("Remote node inspection exceeded its deadline".into()); }
        let (frame_id, node_id, url, base) = reference?;
        let state = if frame_id == 0 {
            self.state.clone()
        } else {
            let realms = self.realm_states();
            let realms = realms.borrow();
            if realms.frame_timers_active(frame_id) != Some(true) {
                return Err("Remote node belongs to a detached frame".into());
            }
            realms.by_frame_id(frame_id).ok_or("Remote node document is unavailable")?
        };
        let state = state.borrow();
        let dom = state.dom.as_ref().ok_or("Remote node document has no DOM")?;
        if dom.get_node(node_id).is_none() { return Err("Remote node is no longer available".into()); }
        Ok(inspect(dom, node_id, frame_id, &url, &base))
    }

    #[cfg(feature = "render")]
    pub fn accessibility_styles(&self) -> HashMap<NodeId, AccessibilityStyle> {
        let mut state = self.state.borrow_mut();
        crate::ops::sample_live_document_animations(&mut state);
        if state.animation_timeline.waapi_nodes().is_empty() {
            if let Some(styles) = state.dom.as_ref().and_then(|dom| {
                obscura_render::dom::accessibility_styles_without_layout(
                    dom, state.viewport, state.render_media, &state.stylesheet_cache,
                )
            }) {
                return styles.into_iter().map(|(id, (display_none, visibility_hidden))| {
                    (id, AccessibilityStyle { display_none, visibility_hidden })
                }).collect();
            }
        }
        let Some(prepared) = crate::ops::ensure_prepared_render(&mut state) else {
            return HashMap::new();
        };
        prepared
            .layout()
            .styles
            .iter()
            .map(|(id, style)| {
                (
                    *id,
                    AccessibilityStyle {
                        display_none: style.display == obscura_render::Display::None,
                        visibility_hidden: style.visibility_hidden,
                    },
                )
            })
            .collect()
    }

    /// Absolute URLs the page requested via fetch()/XHR, in request order
    /// (issue #301). Backs `--dump assets`.
    pub fn fetched_urls(&self) -> Vec<String> {
        self.state.borrow().fetched_urls.clone()
    }

    /// Drain the network events recorded for script-initiated requests
    /// (fetch/XHR/dynamic resource). The Page moves these into its own
    /// network_events so the CDP layer emits Network events for them (#406).
    pub fn take_js_network_events(&self) -> Vec<crate::ops::JsNetworkEvent> {
        std::mem::take(&mut self.state.borrow_mut().js_network_events)
    }

    pub fn dom_ref(&self) -> Option<std::cell::Ref<'_, Option<DomTree>>> {
        let r = self.state.borrow();
        if r.dom.is_some() {
            #[cfg(feature = "render")]
            r.base_url_cache.borrow_mut().take();
            Some(std::cell::Ref::map(r, |s| &s.dom))
        } else {
            None
        }
    }
    fn make_oid(&self, _counter: u64) -> String {
        let id = NEXT_CDP_OBJECT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        format!("{{\"injectedScriptId\":1,\"id\":{}}}", id)
    }

    fn wrap_expression(expression: &str) -> String {
        let trimmed = expression.trim();

        let is_multi_statement = trimmed.starts_with("var ")
            || trimmed.starts_with("let ")
            || trimmed.starts_with("const ")
            || trimmed.starts_with("if ")
            || trimmed.starts_with("for ")
            || trimmed.starts_with("while ")
            || trimmed.starts_with("return ");

        if is_multi_statement {
            format!(
                "(function() {{ try {{\n{}\n}} catch(e) {{ return null; }} }})()",
                expression
            )
        } else {
            // Strip trailing semicolons + whitespace before wrapping in
            // `return (...);`. Playwright's utility-script expression is
            // an IIFE that ends with `})();` — leaving the `;` in place
            // produces `return (...;);`, a SyntaxError. The script fails
            // to parse, the catch never fires (parse errors are not
            // catchable), and the function silently returns `undefined`.
            // Stripping makes the wrapped expression syntactically valid.
            //
            // The newline before the trailing `)` also terminates any
            // `//# sourceURL=...` line comment the caller may have appended
            // (Puppeteer's evaluated bundles do).
            let cleaned = trimmed.trim_end_matches(|c: char| c == ';' || c.is_whitespace());
            format!(
                "(function() {{ try {{ return (\n{}\n); }} catch(e) {{ return null; }} }})()",
                cleaned
            )
        }
    }

    fn meta_extract_js(var_name: &str) -> String {
        format!(
            r#"(function(v) {{
                var t = typeof v;
                var st = null, cn = '', desc = '';
                if (v === null) {{ t = 'object'; st = 'null'; }}
                else if (v === undefined) {{ t = 'undefined'; }}
                else if (Array.isArray(v)) {{
                    st = 'array'; cn = 'Array';
                    desc = 'Array(' + v.length + ')';
                }}
                else if (t === 'object' && typeof v._nid === 'number') {{
                    st = 'node';
                    cn = v.constructor ? v.constructor.name : 'Node';
                    if (v.nodeType === 9) cn = 'HTMLDocument';
                    else if (v.nodeType === 1) cn = 'HTML' + (v.tagName || 'Element').charAt(0) + (v.tagName || 'Element').slice(1).toLowerCase() + 'Element';
                    desc = v.tagName ? v.tagName.toLowerCase() : (v.nodeName || 'node');
                }}
                else if (t === 'function') {{
                    cn = 'Function';
                    desc = v.name ? 'function ' + v.name + '()' : 'function()';
                }}
                else if (t === 'object' && v instanceof Error) {{
                    st = 'error';
                    cn = (v.constructor && v.constructor.name) || 'Error';
                    desc = (typeof v.stack === 'string' && v.stack) ? v.stack
                         : (cn + (v.message ? ': ' + v.message : ''));
                }}
                else if (t === 'object') {{
                    cn = (v.constructor && v.constructor.name) || 'Object';
                    desc = cn;
                }}
                else {{ desc = String(v); }}
                return JSON.stringify({{type:t,subtype:st,className:cn,description:desc}});
            }})({var_name})"#,
            var_name = var_name,
        )
    }

    fn resolve_remote_object(&mut self, object_id: &str) -> Option<String> {
        if let Some(retrieval) = self.object_store.get(object_id) {
            return Some(retrieval.retrieval.clone());
        }
        let expression = self.evaluation_recipes.get(object_id)?.clone();
        let object_id_literal = js_string_literal(object_id);
        let code =
            format!("globalThis.__obscura_objects[{object_id_literal}] = (\n{expression}\n);");
        self.execute_runtime_script("<restore-cdp-object>", code)
            .ok()?;
        let retrieval = format!("globalThis.__obscura_objects[{object_id_literal}]");
        self.object_store.insert(object_id.to_string(), CdpObjectRecord {
            retrieval: retrieval.clone(), frame: None,
        });
        Some(retrieval)
    }

    fn resolve_this(&mut self, object_id: Option<&str>) -> Result<String, String> {
        match object_id {
            Some(oid) => {
                if let Some(retrieval) = self.resolve_remote_object(oid) {
                    Ok(retrieval)
                } else if oid.starts_with("node-") {
                    let nid = oid.strip_prefix("node-").filter(|id| {
                        !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit())
                    }).and_then(|id| id.parse::<u32>().ok())
                        .ok_or("Could not find object with given id")?;
                    Ok(format!(
                        "(function() {{ \
                            var nid = {}; \
                            var cache = globalThis._cache || new Map(); \
                            if (cache.has(nid)) return cache.get(nid); \
                            return null; \
                        }})()",
                        nid
                    ))
                } else {
                    Err("Could not find object with given id".into())
                }
            }
            None => Ok("globalThis".to_string()),
        }
    }

    fn cdp_call_argument(
        &mut self,
        argument: &serde_json::Value,
        context: &v8::Global<v8::Context>,
    ) -> Result<v8::Global<v8::Value>, String> {
        // Remote handles take precedence over value, including rod's value:null.
        if let Some(id) = argument.get("objectId").and_then(|value| value.as_str()) {
            let expression = self.cdp_object_expression(id)?;
            let object_context = self.object_store.get(id).and_then(|record| record.frame.as_ref())
                .map(|(_, context)| context.clone()).unwrap_or_else(|| self.runtime().main_context());
            if &object_context != context {
                return Err("Object belongs to a different execution context".into());
            }
            return self.execute_runtime_script("<cdp-argument>", expression)
                .map_err(|error| format!("JS error: {error}"));
        }
        if argument.get("value").is_none() {
            if let Some(value) = argument.get("unserializableValue").and_then(|value| value.as_str()) {
                if is_cdp_unserializable_value(value) {
                    return self.execute_runtime_script("<cdp-argument>", value.to_string())
                        .map_err(|error| format!("JS error: {error}"));
                }
            }
        }
        let result = (|| {
            let mut entered = self.runtime();
            v8::scope_with_context!(scope, entered.v8_isolate(), context.clone());
            v8::tc_scope!(let scope, scope);
            let value = if let Some(value) = argument.get("value") {
                // JSON data is not an object literal: __proto__ must be an own property.
                let json = serde_json::to_string(value).map_err(|error| error.to_string())?;
                let json = v8::String::new(scope, &json).ok_or("CDP argument allocation failed")?;
                v8::json::parse(scope, json).ok_or_else(|| exception_text(scope))?
            } else {
                v8::undefined(scope).into()
            };
            Ok(v8::Global::new(scope, value))
        })();
        self.finish_heap_checked(result)
    }

    fn v8_to_json(
        &mut self,
        result: deno_core::v8::Global<deno_core::v8::Value>,
    ) -> Result<serde_json::Value, String> {
        let mut entered = self.runtime();
        let context = entered.main_context();
        v8::scope_with_context!(scope, entered.v8_isolate(), context);
        let local = deno_core::v8::Local::new(scope, result);

        if local.is_undefined() || local.is_null() {
            return Ok(serde_json::Value::Null);
        }
        if local.is_boolean() {
            return Ok(serde_json::Value::Bool(local.boolean_value(scope)));
        }
        if local.is_number() {
            let n = local.number_value(scope).unwrap_or(0.0);
            return Ok(serde_json::json!(n));
        }
        if local.is_string() {
            let s = local.to_rust_string_lossy(scope);
            return Ok(serde_json::Value::String(s));
        }

        let global = scope.get_current_context().global(scope);
        let json_obj_str = deno_core::v8::String::new(scope, "JSON").unwrap();
        if let Some(json_obj) = global.get(scope, json_obj_str.into()) {
            if let Some(json_obj) = json_obj.to_object(scope) {
                let stringify_str = deno_core::v8::String::new(scope, "stringify").unwrap();
                if let Some(stringify_fn) = json_obj.get(scope, stringify_str.into()) {
                    if let Ok(stringify_fn) =
                        deno_core::v8::Local::<deno_core::v8::Function>::try_from(stringify_fn)
                    {
                        let args = [local];
                        if let Some(result) = stringify_fn.call(scope, json_obj.into(), &args) {
                            let json_str = result.to_rust_string_lossy(scope);
                            if let Ok(val) = serde_json::from_str(&json_str) {
                                return Ok(val);
                            }
                        }
                    }
                }
            }
        }

        let s = local.to_rust_string_lossy(scope);
        Ok(serde_json::Value::String(s))
    }

    fn finish_cdp_result(
        &mut self,
        meta: &serde_json::Value,
        oid: &str,
    ) -> Result<RemoteObjectInfo, String> {
        // Primitive results have no client handle to release. Preserve their
        // V8 types and remove the temporary root, just like by-value results.
        if !matches!(meta.get("type").and_then(|v| v.as_str()),
            Some("object" | "function" | "symbol")) || meta["subtype"] == "null"
        {
            return self.take_cdp_result_by_value(oid);
        }
        self.object_store.insert(
            oid.to_string(),
            CdpObjectRecord {
                retrieval: format!("globalThis.__obscura_objects[{}]", js_string_literal(oid)),
                frame: None,
            },
        );
        Ok(Self::info_from_meta(meta, Some(oid.to_string())))
    }

    fn take_cdp_result_by_value(&mut self, oid: &str) -> Result<RemoteObjectInfo, String> {
        // The client receives no handle to release. Keep the value rooted in
        // V8's returned Global while removing the temporary page reference.
        let oid = js_string_literal(oid);
        let value = self.execute_runtime_script(
            "<takeResult>",
            format!("(function() {{ var result = globalThis.__obscura_objects[{oid}]; \
                delete globalThis.__obscura_objects[{oid}]; return result; }})()"),
        ).map_err(|e| format!("JS error: {}", e))?;
        self.v8_to_cdp_value(value)
    }

    fn v8_to_cdp_value(
        &mut self,
        result: deno_core::v8::Global<deno_core::v8::Value>,
    ) -> Result<RemoteObjectInfo, String> {
        // JSON cannot preserve undefined, bigint, or exceptional numbers.
        let primitive = {
            let mut entered = self.runtime();
            let context = entered.main_context();
            v8::scope_with_context!(scope, entered.v8_isolate(), context);
            let value = deno_core::v8::Local::new(scope, &result);
            if value.is_undefined() {
                Some(("undefined", None))
            } else if value.is_big_int() {
                Some(("bigint", Some(format!("{}n", value.to_rust_string_lossy(scope)))))
            } else if value.is_number() {
                let number = value.number_value(scope).unwrap();
                let text = if number.is_nan() {
                    Some("NaN")
                } else if number == f64::INFINITY {
                    Some("Infinity")
                } else if number == f64::NEG_INFINITY {
                    Some("-Infinity")
                } else if number == 0.0 && number.is_sign_negative() {
                    Some("-0")
                } else {
                    None
                };
                text.map(|text| ("number", Some(text.to_string())))
            } else {
                None
            }
        };
        if let Some((kind, unserializable_value)) = primitive {
            return Ok(RemoteObjectInfo {
                thrown: false,
                js_type: kind.into(),
                subtype: None,
                class_name: String::new(),
                description: unserializable_value.clone().unwrap_or_default(),
                object_id: None,
                value: None,
                unserializable_value,
            });
        }
        let value = self.v8_to_json(result)?;
        Ok(Self::info_from_json(&value))
    }

    fn info_from_json(value: &serde_json::Value) -> RemoteObjectInfo {
        match value {
            serde_json::Value::Null => RemoteObjectInfo {
                thrown: false,
                js_type: "object".into(),
                subtype: Some("null".into()),
                class_name: String::new(),
                description: "null".into(),
                object_id: None,
                value: Some(serde_json::Value::Null),
                unserializable_value: None,
            },
            serde_json::Value::Bool(b) => RemoteObjectInfo {
                thrown: false,
                js_type: "boolean".into(),
                subtype: None,
                class_name: String::new(),
                description: b.to_string(),
                object_id: None,
                value: Some(value.clone()),
                unserializable_value: None,
            },
            serde_json::Value::Number(n) => RemoteObjectInfo {
                thrown: false,
                js_type: "number".into(),
                subtype: None,
                class_name: String::new(),
                description: n.to_string(),
                object_id: None,
                value: Some(value.clone()),
                unserializable_value: None,
            },
            serde_json::Value::String(s) => RemoteObjectInfo {
                thrown: false,
                js_type: "string".into(),
                subtype: None,
                class_name: String::new(),
                description: s.clone(),
                object_id: None,
                value: Some(value.clone()),
                unserializable_value: None,
            },
            serde_json::Value::Array(arr) => RemoteObjectInfo {
                thrown: false,
                js_type: "object".into(),
                subtype: Some("array".into()),
                class_name: "Array".into(),
                description: format!("Array({})", arr.len()),
                object_id: None,
                value: Some(value.clone()),
                unserializable_value: None,
            },
            serde_json::Value::Object(_) => RemoteObjectInfo {
                thrown: false,
                js_type: "object".into(),
                subtype: None,
                class_name: "Object".into(),
                description: "Object".into(),
                object_id: None,
                value: Some(value.clone()),
                unserializable_value: None,
            },
        }
    }

    fn info_from_meta(meta: &serde_json::Value, object_id: Option<String>) -> RemoteObjectInfo {
        let js_type = meta
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("undefined")
            .to_string();
        let subtype = meta
            .get("subtype")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let class_name = meta
            .get("className")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let description = meta
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        RemoteObjectInfo {
            thrown: false,
            js_type,
            subtype,
            class_name,
            description,
            object_id,
            value: None,
            unserializable_value: None,
        }
    }
}

impl Default for ObscuraJsRuntime {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn form_ownership_tracks_explicit_ids_and_tree_order() {
        let mut rt = setup_runtime("<form id='f'><input id='a'><input id='b' form='g'><input id='empty' form=''></form><form id='g'></form><input id='c' form='f'><div id='block'></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const f = document.getElementById('f'), g = document.getElementById('g');
            const a = document.getElementById('a'), b = document.getElementById('b');
            const c = document.getElementById('c'), block = document.getElementById('block');
            const ids = form => Array.from(form.elements, node => node.id).join(',');
            const initial = [a.form === f, b.form === g, c.form === f,
                document.getElementById('empty').form === null, ids(f), ids(g)];
            block.id = 'f'; f.before(block);
            const blocked = [c.form === null, ids(f)];
            f.before(c); block.remove();
            const reordered = [c.form === f, ids(f)];
            f.id = 'new';
            const renamed = [c.form === null, ids(f)];
            c.setAttribute('form', 'new');
            return {initial, blocked, reordered, renamed, restored:ids(f)};
        })()"#).unwrap(), serde_json::json!({
            "initial":[true,true,true,true,"a,c","b"], "blocked":[true,"a"],
            "reordered":[true,"c,a"], "renamed":[true,"a"], "restored":"c,a"
        }));
    }

    #[test]
    fn form_ownership_lazy_snapshots_preserve_observation_and_array_mutation() {
        let mut rt = setup_runtime("<form id=f><input id=a name=first><input id=b name=NaN></form><input id=c form=f name=outside>");
        assert_eq!(rt.evaluate(r#"(() => {
            const f = document.getElementById('f'), a = document.getElementById('a');
            const b = document.getElementById('b'), c = document.getElementById('c');
            const fresh = () => f.elements;
            const collection = fresh();
            const descriptor = Object.getOwnPropertyDescriptor(collection, '1');
            const observed = [Array.isArray(collection), collection instanceof HTMLCollection,
                collection.length === 3, collection.item(0) === a, collection.NaN === b,
                collection.namedItem('outside') === c, 'outside' in collection,
                descriptor.value === b && descriptor.writable && descriptor.enumerable && descriptor.configurable,
                Array.from(collection).every((node, i) => node === [a,b,c][i]),
                Object.assign({}, collection)[2] === c, c.form === f];
            const shortened = fresh(); shortened.length = 0; shortened.length = 3;
            const deleted = fresh(); delete deleted[0];
            const written = fresh(); written[0] = 'changed';
            const defined = fresh(); Object.defineProperty(defined, '1', {value:'defined'});
            const frozen = Object.freeze(fresh());
            return {observed, mutations:[shortened[0] === undefined, deleted[0] === undefined,
                written[0] === 'changed', defined[1] === 'defined', frozen[2] === c,
                fresh()[0] === a && fresh()[1] === b]};
        })()"#).unwrap(), serde_json::json!({
            "observed":vec![true;11], "mutations":vec![true;6]
        }));
        rt.with_dom(|dom| {
            let c = dom.get_element_by_id("c").unwrap();
            dom.form_cache_generation_handle().store(u32::MAX as u64, std::sync::atomic::Ordering::Relaxed);
            dom.with_node_mut(c, |node| node.set_attribute("form", "missing".into()));
        });
        assert_eq!(rt.evaluate("document.getElementById('f').elements.length === 2 && document.getElementById('c').form === null").unwrap(),
            serde_json::json!(true));
        rt.with_dom(|dom| {
            let c = dom.get_element_by_id("c").unwrap();
            dom.form_cache_generation_handle().store((2u64 << 32) - 1, std::sync::atomic::Ordering::Relaxed);
            dom.with_node_mut(c, |node| node.set_attribute("form", "f".into()));
        });
        assert_eq!(rt.evaluate("document.getElementById('f').elements.length === 3 && document.getElementById('c').form === document.getElementById('f')").unwrap(),
            serde_json::json!(true));
        let dom = rt.state.borrow_mut().dom.take().unwrap();
        let dom = std::thread::spawn(move || {
            let c = dom.get_element_by_id("c").unwrap();
            dom.with_node_mut(c, |node| node.set_attribute("form", "missing".into()));
            dom
        }).join().unwrap();
        rt.state.borrow_mut().dom = Some(dom);
        assert_eq!(rt.evaluate("document.getElementById('f').elements.length === 2 && document.getElementById('c').form === null").unwrap(),
            serde_json::json!(true));
        rt.set_dom(parse_html("<form id=f><input></form>"));
        assert_eq!(rt.evaluate("(() => {const f=document.getElementById('f'); return {length:f.elements.length, ids:Array.from(f.elements,n=>n.id)}})()").unwrap(),
            serde_json::json!({"length":1,"ids":[""]}));
    }

    #[test]
    fn form_ownership_dom_export_invalidates_and_rebinds_cached_getters() {
        let mut rt = setup_runtime("<form id=f></form><input id=input form=f>");
        assert_eq!(rt.evaluate("(() => {globalThis.savedInput=document.getElementById('input');globalThis.savedForm=document.getElementById('f');return savedInput.form===savedForm && savedForm.elements.length===1})()").unwrap(),
            serde_json::json!(true));
        let dom = rt.take_dom().unwrap();
        assert_eq!(rt.evaluate_script("savedInput.form===null").unwrap(),
            serde_json::json!(true));
        assert!(rt.evaluate_script("savedForm.elements").unwrap_err().contains("TypeError: Illegal invocation"));
        let dom = std::thread::spawn(move || {
            let form = dom.get_element_by_id("f").unwrap();
            dom.with_node_mut(form, |node| node.set_attribute("id", "changed".into()));
            dom
        }).join().unwrap();
        rt.set_dom(dom);
        assert_eq!(rt.evaluate_script("savedInput.form===null && savedForm.elements.length===0").unwrap(),
            serde_json::json!(true));
        rt.with_dom(|dom| {
            let input = dom.get_element_by_id("input").unwrap();
            dom.with_node_mut(input, |node| node.set_attribute("form", "changed".into()));
        });
        assert_eq!(rt.evaluate("savedInput.form===savedForm && savedForm.elements.length===1").unwrap(),
            serde_json::json!(true));
    }

    #[test]
    fn form_ownership_retired_documents_cannot_publish_into_replacement_caches() {
        let mut rt = setup_runtime("<form id=old><input></form>");
        rt.evaluate("document.getElementById('old').elements.length").unwrap();
        let retired = rt.state.borrow_mut().dom.take().unwrap();
        rt.set_dom(parse_html("<form id=f></form><input id=input form=f>"));
        let epoch = rt.with_dom(|dom| dom.form_cache_generation_handle().load(std::sync::atomic::Ordering::Relaxed)).unwrap();
        retired.form_cache_generation_handle().store(epoch, std::sync::atomic::Ordering::Relaxed);
        let old_form = retired.get_element_by_id("old").unwrap();
        std::thread::spawn(move || {
            retired.with_node_mut(old_form, |node| node.set_attribute("id", "retired".into()));
        }).join().unwrap();
        assert_eq!(rt.evaluate("document.getElementById('input').form === document.getElementById('f')").unwrap(),
            serde_json::json!(true));
        rt.with_dom(|dom| {
            let form = dom.get_element_by_id("f").unwrap();
            dom.with_node_mut(form, |node| node.set_attribute("id", "changed".into()));
        });
        assert_eq!(rt.evaluate("document.getElementById('input').form === null").unwrap(),
            serde_json::json!(true));
    }

    #[test]
    fn form_ownership_updates_cached_lists_on_reset_and_reparenting() {
        let mut rt = setup_runtime("<form id='f'><input id='a' value='initial'><input id='b' form='g' value='other'></form><form id='g'></form><input id='c' form='f' value='outside'>");
        assert_eq!(rt.evaluate(r#"(() => {
            const f = document.getElementById('f'), g = document.getElementById('g');
            const a = document.getElementById('a'), b = document.getElementById('b');
            const c = document.getElementById('c'), old = f.elements;
            a.value='changed'; b.value='kept'; c.value='changed'; f.reset();
            const reset = [a.value,b.value,c.value];
            g.appendChild(a);
            const moved = [a.form === g, Array.from(f.elements,n=>n.id).join(','),
                Array.from(g.elements,n=>n.id).join(',')];
            c.removeAttribute('form');
            return {reset,moved,removed:f.elements.length,oldSnapshot:old.length};
        })()"#).unwrap(), serde_json::json!({
            "reset":["initial","kept","outside"], "moved":[true,"c","b,a"],
            "removed":0,"oldSnapshot":2
        }));
    }

    #[test]
    fn form_ownership_preserves_parser_association_until_reset() {
        let mut rt = setup_runtime("<table><form id='f'><tr><td><span id='box'><input id='a'><button id='b'>Go</button></span></td></tr></form></table><form id='g'></form>");
        assert_eq!(rt.evaluate(r#"(() => {
            const f = document.getElementById('f'), a = document.getElementById('a');
            const b = document.getElementById('b'), box = document.getElementById('box');
            const ids = () => Array.from(f.elements, node => node.id).join(',');
            const initial = [f.children.length, a.form === f, b.form === f, ids()];
            a.className = 'kept';
            const unchanged = a.form === f;
            a.setAttribute('form', 'missing'); a.removeAttribute('form');
            const resetAttribute = [a.form === null, ids()];
            document.body.appendChild(box);
            return {initial, unchanged, resetAttribute, moved:[b.form === null, ids()]};
        })()"#).unwrap(), serde_json::json!({
            "initial":[0,true,true,"a,b"], "unchanged":true,
            "resetAttribute":[true,"b"], "moved":[true,""]
        }));
    }

    #[test]
    fn form_ownership_stays_inside_detached_and_shadow_trees() {
        let mut rt = setup_runtime("<form id='same'><input id='outer'></form><div id='host'></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const host = document.getElementById('host'), root = host.attachShadow({mode:'open'});
            root.innerHTML = '<form id="same"><input id="a"></form><input id="b" form="same">';
            const form = root.querySelector('form'), b = root.querySelector('#b');
            const initial = [b.form === form, Array.from(form.elements, n => n.id).join(','),
                document.getElementById('same').elements.length];
            host.remove();
            const disconnected = [b.form === null, Array.from(form.elements, n => n.id).join(',')];
            document.body.appendChild(host);
            const restored = b.form === form;
            const detached = document.createElement('div');
            detached.innerHTML = '<form id="same"><input id="ancestor" form="missing"></form><input id="explicit" form="same">';
            const input = detached.querySelector('#explicit'), owned = detached.querySelector('form');
            const separate = [input.form === owned, owned.elements[0] === input];
            const detachedAncestor = detached.querySelector('#ancestor').form === owned;
            document.body.appendChild(input);
            return {initial, disconnected, restored, separate, detachedAncestor,
                moved:input.form === document.getElementById('same')};
        })()"#).unwrap(), serde_json::json!({
            "initial":[true,"a,b",1], "disconnected":[true,"a"], "restored":true,
            "separate":[false,false], "detachedAncestor":true, "moved":true
        }));
    }

    #[test]
    fn html_interface_brands_use_distinct_native_prototypes() {
        let mut rt = setup_runtime("<html><head><style></style><link></head><body><div></div><span></span><a></a><p></p><button></button><h2></h2><template></template></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const pairs = [
                ['a','HTMLAnchorElement'], ['br','HTMLBRElement'], ['body','HTMLBodyElement'],
                ['button','HTMLButtonElement'], ['datalist','HTMLDataListElement'], ['details','HTMLDetailsElement'],
                ['dialog','HTMLDialogElement'], ['div','HTMLDivElement'], ['fieldset','HTMLFieldSetElement'],
                ['hr','HTMLHRElement'], ['head','HTMLHeadElement'], ['h2','HTMLHeadingElement'],
                ['html','HTMLHtmlElement'], ['label','HTMLLabelElement'], ['legend','HTMLLegendElement'],
                ['link','HTMLLinkElement'], ['p','HTMLParagraphElement'], ['pre','HTMLPreElement'],
                ['progress','HTMLProgressElement'], ['script','HTMLScriptElement'], ['span','HTMLSpanElement'],
                ['style','HTMLStyleElement'], ['template','HTMLTemplateElement'], ['ul','HTMLUListElement'],
            ];
            const xhtml = 'http://www.w3.org/1999/xhtml';
            const nodes = pairs.map(([tag]) => document.createElement(tag));
            const correct = pairs.map(([tag,name], index) => {
                const C = globalThis[name];
                const node = nodes[index];
                let rejected = false;
                try { new C(); } catch (error) { rejected = error instanceof TypeError; }
                return node instanceof C && node.constructor === C
                    && Function.prototype[Symbol.hasInstance].call(C, node)
                    && Object.getPrototypeOf(node) === C.prototype
                    && Object.prototype.toString.call(node) === '[object '+name+']'
                    && C.length === 0 && rejected
                    && node.cloneNode().constructor === C
                    && document.createElementNS(xhtml, 'x:'+tag).constructor === C
                    && !(document.createElementNS(xhtml, tag.toUpperCase()) instanceof C)
                    && !(document.createElementNS('urn:foreign', tag) instanceof C)
                    && nodes.every((other, otherIndex) => (other instanceof C) === (index === otherIndex));
            });
            const parsed = pairs.filter(([tag]) => document.querySelector(tag)).every(([tag,name]) => {
                const node = document.querySelector(tag);
                return node.constructor === globalThis[name]
                    && Object.getPrototypeOf(node) === globalThis[name].prototype;
            });
            HTMLDivElement.prototype.__brandProbe = 42;
            const isolated = document.querySelector('div').__brandProbe === 42
                && document.createElement('div').__brandProbe === 42
                && document.querySelector('span').__brandProbe === undefined
                && document.querySelector('a').__brandProbe === undefined
                && Element.prototype.__brandProbe === undefined;
            delete HTMLDivElement.prototype.__brandProbe;
            return {correct, parsed, isolated};
        })()"#).unwrap(), serde_json::json!({
            "correct":vec![true;24], "parsed":true, "isolated":true,
        }));
    }

    #[test]
    fn html_interface_brands_preserve_existing_specialized_behavior() {
        let mut rt = setup_runtime("<html><head></head><body><input><select><option>one</option></select><textarea></textarea><form></form><iframe></iframe><div></div></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const input = document.querySelector('input');
            input.value = 'typed';
            const select = document.querySelector('select');
            const textarea = document.querySelector('textarea');
            textarea.value = 'text';
            const style = document.createElement('style');
            style.textContent = 'body {color: red}';
            let target = document.head;
            if (target instanceof HTMLIFrameElement) target = target.contentDocument.head;
            target.appendChild(style);
            return [input instanceof HTMLInputElement, input.value,
                select instanceof HTMLSelectElement, select.item(0).index,
                textarea instanceof HTMLTextAreaElement, textarea.value,
                document.querySelector('form') instanceof HTMLFormElement,
                document.querySelector('iframe') instanceof HTMLIFrameElement,
                !(document.querySelector('div') instanceof HTMLIFrameElement),
                style.parentNode === document.head, style.constructor === HTMLStyleElement];
        })()"#).unwrap(), serde_json::json!([
            true,"typed",true,0,true,"text",true,true,true,true,true,
        ]));
    }

    #[test]
    fn file_input_validation_is_nonmutating_and_selection_honors_multiple() {
        let mut rt = setup_runtime("<input id=single type=file><input id=multi type=file multiple><div id=wrong></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const single = document.getElementById('single');
            const multi = document.getElementById('multi');
            const specs = [{name:'one',b64:'AID/'},{name:'two',b64:'BAU='}];
            const events = [];
            for (const type of ['input','change']) {
                single.addEventListener(type, event => events.push([type,event.isTrusted]));
            }
            const selected = __obscura_setInputFiles(single, specs);
            const previous = single.files;
            const validation = __obscura_setInputFiles(single, [], true);
            const preserved = single.files === previous;
            __obscura_setInputFiles(multi, specs);
            const counts = [single.files.length, multi.files.length];
            const invalid = __obscura_setInputFiles(document.getElementById('wrong'), specs);
            const forged = __obscura_setInputFiles(Object.create(HTMLInputElement.prototype), specs);
            __obscura_setInputFiles(single, []);
            return {selected,validation,preserved,counts,invalid,forged,events,empty:single.files.length};
        })()"#).unwrap(), serde_json::json!({
            "selected":true, "validation":true, "preserved":true, "counts":[1,2],
            "invalid":false, "forged":false,
            "events":[["input",true],["change",true],["input",true],["change",true]], "empty":0,
        }));
    }

    #[test]
    fn select_options_use_native_ownership_and_live_option_indexes() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.createElement('select');
            document.body.append(select);
            const add = (parent, id) => {
                const option = new Option(id, id);
                option.id = id;
                parent.append(option);
                return option;
            };
            const first = add(select, 'first');
            const div = document.createElement('div');
            select.append(div);
            const second = add(div, 'second');
            const group = document.createElement('optgroup');
            select.append(group);
            const third = add(group, 'third');
            const nested = document.createElement('select');
            select.append(nested);
            const hidden = add(nested, 'nested');
            hidden.selected = true;
            const datalist = document.createElement('datalist');
            select.append(datalist);
            const suggested = add(datalist, 'suggested');
            const outer = add(select, 'outer');
            const inner = add(outer, 'inner');
            const initial = [select.length, Array.from(select.options, o => o.id),
                [first.index, second.index, third.index, hidden.index, suggested.index, outer.index, inner.index],
                select.value, select.selectedIndex, select.item(2) === third,
                select.namedItem('second') === second];
            select.value = 'third';
            const chosen = [third.selected, hidden.selected, select.value, select.selectedIndex];
            second.remove();
            return {initial, chosen, moved: [third.index, select.length], liveRows:
                typeof Object.getOwnPropertyDescriptor(HTMLTableElement.prototype, 'rows').get};
        })()"#).unwrap(), serde_json::json!({
            "initial":[4,["first","second","third","outer"],[0,1,2,0,0,3,0],"first",0,true,true],
            "chosen":[true,true,"third",2], "moved":[1,3], "liveRows":"function",
        }));
    }

    #[test]
    fn select_length_snapshot_stays_live_and_private() {
        let mut rt = setup_runtime("<html><body><select id='s'><option>A</option><optgroup><option>B</option></optgroup></select><select id='other'></select></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.getElementById('s');
            const other = document.getElementById('other');
            const counts = [select.length, select.length];
            const exposed = select.options;
            exposed.length = 0;
            counts.push(select.length);
            other.append(select.item(0));
            counts.push(select.length, other.length);
            const group = select.querySelector('optgroup');
            group.append(new Option('C'));
            counts.push(select.length);
            group.replaceWith(new Option('D'));
            counts.push(select.length);
            const nested = document.createElement('select');
            nested.append(new Option('hidden'));
            select.append(nested);
            const datalist = document.createElement('datalist');
            datalist.append(new Option('suggested'));
            select.append(datalist);
            counts.push(select.length);
            select.innerHTML = '<option>E</option><option>F</option>';
            counts.push(select.length, select[1].text);
            select.length = 0;
            counts.push(select.length, select[0] === undefined);
            select.remove();
            select.append(new Option('detached'));
            counts.push(select.length, select[0].text);
            return counts;
        })()"#).unwrap(), serde_json::json!([2,2,2,1,1,2,1,1,2,"F",0,true,1,"detached"]));
    }

    #[test]
    fn select_length_snapshot_observes_native_dom_mutations() {
        let mut rt = setup_runtime("<html><body><select id='s'><option>A</option><option id='b'>B</option></select></body></html>");
        assert_eq!(rt.evaluate("(() => { globalThis.savedSelect = document.getElementById('s'); return savedSelect.length; })()")
            .unwrap(), serde_json::json!(2.0));
        {
            let state = rt.state.borrow();
            let dom = state.dom.as_ref().unwrap();
            dom.remove_child(dom.query_selector("#b").unwrap().unwrap());
        }
        assert_eq!(rt.evaluate("[savedSelect.length, savedSelect[1] === undefined]").unwrap(),
            serde_json::json!([1,true]));
    }

    #[test]
    fn select_add_respects_group_parents_and_union_conversions() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const result = [];
            for (const kind of ['number','string','bigint','symbol','object','group','self','foreign']) {
                const select = document.createElement('select');
                select.innerHTML = '<option id="a">A</option><optgroup><option id="b">B</option></optgroup>';
                const option = new Option('X');
                const before = {number:1, string:'1', bigint:1n, symbol:Symbol(),
                    object:{valueOf() { return 1; }}, group:select.querySelector('optgroup'),
                    self:select, foreign:document.createElementNS('urn:foreign','option')}[kind];
                try {
                    select.add(option, before);
                    result.push([kind, option.parentNode.localName, Array.from(select.options, o => o.text)]);
                } catch (error) { result.push([kind, error.name]); }
            }
            return result;
        })()"#).unwrap(), serde_json::json!([
            ["number","optgroup",["A","X","B"]], ["string","optgroup",["A","X","B"]],
            ["bigint","TypeError"], ["symbol","TypeError"], ["object","optgroup",["A","X","B"]],
            ["group","select",["A","X","B"]], ["self","NotFoundError"], ["foreign","select",["X","A","B"]],
        ]));
    }

    #[test]
    fn select_length_and_remove_overloads_modify_owned_options_only() {
        let mut rt = setup_runtime("<html><body><select><option id='a'>A</option><optgroup><option id='b'>B</option><option id='c'>C</option></optgroup></select></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.querySelector('select');
            const group = select.querySelector('optgroup');
            select.length = 5;
            const grown = [select.length, select.item(4).text, select.item(4) instanceof HTMLOptionElement];
            select.length = 2;
            const shrunk = [select.length, group.children.length, select.item(1).id];
            select.remove(-1);
            select.remove(99);
            const untouched = [select.length, select.isConnected];
            select.remove(null);
            const removedFirst = [select.length, select.item(0).id, select.isConnected];
            select.length = 0;
            select.length = 1;
            const cleared = [select.length, group.children.length, select.item(0).index];
            select.remove();
            return {grown, shrunk, untouched, removedFirst, cleared, connected:select.isConnected};
        })()"#).unwrap(), serde_json::json!({
            "grown":[5,"",true], "shrunk":[2,1,"b"], "untouched":[2,true],
            "removedFirst":[1,"b",true], "cleared":[1,0,0], "connected":false,
        }));
    }

    #[test]
    fn select_legacy_methods_enforce_webidl_conversions_and_bounded_lengths() {
        let mut rt = setup_runtime("<html><body><select><option id='first' name='alias'>A</option><option>B</option></select></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.querySelector('select');
            const throws = f => { try { f(); return false; } catch (e) { return e instanceof TypeError; } };
            const errors = [throws(() => select.item()), throws(() => select.namedItem()),
                throws(() => select.item(0n)), throws(() => select.length = 2n),
                throws(() => select.namedItem(Symbol())), throws(() => select.remove(Symbol())),
                throws(() => select.length = Symbol())];
            const reads = [select.item('0').id, select.item(-1), select.item(undefined).id,
                select.namedItem('alias').id, select.namedItem(''), select.namedItem('missing')];
            const warnings = [];
            console.warn = value => warnings.push(value);
            select.length = 100001;
            select.length = -1;
            const bounded = [select.length, warnings.length,
                warnings.every(value => value.includes('100000'))];
            select.length = '3';
            return {errors, reads, bounded, converted:select.length};
        })()"#).unwrap(), serde_json::json!({
            "errors":[true,true,true,true,true,true,true], "reads":["first",null,"first","first",null,null],
            "bounded":[2,2,true], "converted":3,
        }));
    }

    #[test]
    fn select_legacy_methods_read_options_after_argument_coercion() {
        let mut rt = setup_runtime("<html><body><select><option id='first'>A</option></select></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.querySelector('select');
            const change = id => { select.innerHTML = '<option id="'+id+'">X</option>'; };
            const item = select.item({valueOf() { change('item'); return 0; }}).id;
            const named = select.namedItem({toString() { change('named'); return 'named'; }}).id;
            select.remove({valueOf() { change('removed'); return 0; }});
            const removed = select.length;
            select.length = {valueOf() { change('length'); return 0; }};
            return [item, named, removed, select.length];
        })()"#).unwrap(), serde_json::json!(["item","named",0,0]));
    }

    #[test]
    fn select_and_option_interfaces_preserve_factories_and_validate_receivers() {
        let mut rt = setup_runtime("<html><body><select><option>A</option></select><div></div></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const select = document.querySelector('select');
            const option = select.item(0);
            const length = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'length');
            const index = Object.getOwnPropertyDescriptor(HTMLOptionElement.prototype, 'index').get;
            const errors = [];
            for (const value of [document.querySelector('div'), {}, Object.create(HTMLSelectElement.prototype),
                document.createElementNS('urn:foreign', 'select'), document.createElementNS('http://www.w3.org/1999/xhtml', 'SELECT')]) {
                for (const method of [() => length.get.call(value), () => length.set.call(value, 2),
                    () => HTMLSelectElement.prototype.item.call(value, 0),
                    () => HTMLSelectElement.prototype.namedItem.call(value, ''),
                    () => HTMLSelectElement.prototype.remove.call(value)]) {
                    try { method(); errors.push(false); } catch (e) { errors.push(e instanceof TypeError); }
                }
            }
            for (const value of [select, {}, document.createElementNS('urn:foreign', 'option')]) {
                try { index.call(value); errors.push(false); } catch (e) { errors.push(e instanceof TypeError); }
            }
            const constructors = [HTMLSelectElement, HTMLOptionElement].map(C => {
                try { new C(); return false; } catch (e) { return e instanceof TypeError; }
            });
            return {brands:[select instanceof HTMLSelectElement, option instanceof HTMLOptionElement,
                select.cloneNode(true) instanceof HTMLSelectElement,
                option.cloneNode() instanceof HTMLOptionElement, new Option() instanceof HTMLOptionElement,
                document.createElement('div') instanceof HTMLSelectElement],
                noGenericLength:!('length' in document.createElement('div')),
                errors:errors.every(Boolean), constructors, detached:new Option().index,
                signatures:[HTMLSelectElement.length, HTMLOptionElement.length, index.name,
                    index.toString(), HTMLSelectElement.prototype.item.length,
                    HTMLSelectElement.prototype.namedItem.length, HTMLSelectElement.prototype.remove.length]};
        })()"#).unwrap(), serde_json::json!({
            "brands":[true,true,true,true,true,false], "noGenericLength":true,
            "errors":true, "constructors":[true,true], "detached":0,
            "signatures":[0,0,"get index","function get index() { [native code] }",1,1,0],
        }));
    }

    #[test]
    fn select_legacy_methods_work_in_child_realms() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body><select><option id='a'>A</option><optgroup><option id='b'>B</option></optgroup></select></body></html>").unwrap();
        assert_eq!(frame.evaluate(&mut rt, r#"(() => {
            const select = document.querySelector('select');
            const branded = select instanceof HTMLSelectElement && select.item(1) instanceof HTMLOptionElement;
            const index = select.namedItem('b').index;
            select.remove(0);
            select.length = 3;
            return [branded, index, select.item(0).id, select.item(2).index, select.length];
        })()"#).unwrap(), serde_json::json!([true,1,"b",2,3]));
    }

    #[test]
    fn cdp_frame_console_retention_bounds_page_owned_store_getters() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_runtime_events_enabled(true);
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://foreign.test/child", "<html><body>child</body></html>").unwrap();
        frame.execute_script(&mut rt, r#"console.log({answer:42});
            globalThis.__obscura_objects = new Proxy({}, {get() { while (true) {} }});
            void 0;
        "#).unwrap();
        let events = rt.take_pending_runtime_events();
        assert!(events.iter().any(|event| matches!(event, RuntimeEvent::Console(_))));
        assert!(rt.object_store.is_empty());
        assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
        drop(frame);
    }

    #[test]
    fn cdp_frame_console_objects_keep_their_world_without_leaking_child_store_entries() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_runtime_events_enabled(true);
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://foreign.test/child", "<html><body>child</body></html>").unwrap();
        frame.execute_script(&mut rt, "console.log({answer:42})").unwrap();
        let events = rt.take_pending_runtime_events();
        let oid = events.iter().find_map(|event| match event {
            RuntimeEvent::Console(event) => event.args.iter().find_map(|arg| arg["objectId"].as_str()),
            _ => None,
        }).expect("missing console object").to_string();
        let CdpEvaluation::Complete(result) = rt.start_cdp_call(
            "function() { return [document.URL, this.answer]; }", Some(&oid), &[], true, false,
        ).unwrap() else { panic!("expected a value"); };
        assert_eq!(result.value.unwrap(), serde_json::json!(["http://foreign.test/child",42]));
        assert_eq!(frame.evaluate(&mut rt, "Object.keys(globalThis.__obscura_objects).length").unwrap(),
            serde_json::json!(0));
        rt.release_object(&oid);
        assert_eq!(rt.evaluate("Object.keys(globalThis.__obscura_objects).length").unwrap(), serde_json::json!(0.0));
        assert!(rt.start_cdp_call("function() { return this; }", Some(&oid), &[], true, false).is_err());
        drop(frame);
    }

    #[test]
    fn cdp_frame_handles_keep_the_wrapping_world_and_reject_reused_realms() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body>child</body></html>").unwrap();
        frame.evaluate(&mut rt, "globalThis.childObject = {nested: {answer:42}}").unwrap();
        let child = rt.start_cdp_evaluation_in_frame(Some(1), "childObject", false, false).unwrap();
        let CdpEvaluation::Complete(child) = child else { panic!("expected a handle"); };
        let child_id = child.object_id.unwrap();
        let root = rt.start_cdp_evaluation(
            "globalThis.__obscura_frameObjects[1].window.childObject", false, false,
        ).unwrap();
        let CdpEvaluation::Complete(root) = root else { panic!("expected a handle"); };
        let root_id = root.object_id.unwrap();
        for (id, expected) in [(&root_id, "http://example.com/test"), (&child_id, "http://example.com/child")] {
            let result = rt.start_cdp_call("function() { return document.URL; }", Some(id), &[], true, false).unwrap();
            let CdpEvaluation::Complete(result) = result else { panic!("expected a value"); };
            assert_eq!(result.value.unwrap(), serde_json::json!(expected));
        }
        drop(frame);
        let _replacement = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/new", "<html><body>new</body></html>").unwrap();
        assert_eq!(rt.validate_cdp_object_context(&child_id).unwrap_err(), "Execution context was destroyed");
        assert!(rt.start_cdp_call("function() { return 1; }", Some(&child_id), &[], true, false).is_err());
        assert!(rt.start_cdp_call("function() { return document.URL; }", Some(&root_id), &[], true, false).is_ok());
    }

    #[test]
    fn cdp_calls_reject_unknown_released_cross_world_and_malformed_node_handles() {
        let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body>child</body></html>").unwrap();
        let CdpEvaluation::Complete(child) = rt.start_cdp_evaluation_in_frame(
            Some(1), "({answer:42})", false, false,
        ).unwrap() else { panic!("expected a handle"); };
        let child_id = child.object_id.unwrap();
        let invalid = ["unknown", "node-", "node--1", "node-+1", "node-1e1", "node-4294967296",
            "node-1;globalThis.__pwned=1;//", "node-1\n"];
        for id in invalid {
            assert!(rt.start_cdp_call("function() { globalThis.__pwned=1; }",
                Some(id), &[], true, false).is_err(), "{id}");
            assert!(rt.start_cdp_call("function(value) { globalThis.__pwned=1; }",
                None, &[serde_json::json!({"objectId":id,"value":null})], true, false).is_err(), "{id}");
        }
        assert!(rt.start_cdp_call("function(value) { globalThis.__pwned=1; }", None,
            &[serde_json::json!({"objectId":child_id})], true, false).is_err());
        assert!(rt.start_cdp_call_in_frame(Some(1), "function(value) { return value.answer; }", None,
            &[serde_json::json!({"objectId":child_id,"value":null})], true, false).is_ok());
        let node_id = rt.with_dom(|dom| dom.query_selector("h1").unwrap().unwrap().raw()).unwrap();
        assert!(rt.start_cdp_call("function() { return this.textContent; }",
            Some(&format!("node-{node_id}")), &[], true, false).is_ok());
        rt.release_object(&child_id);
        assert!(rt.start_cdp_call("function() { globalThis.__pwned=1; }",
            Some(&child_id), &[], true, false).is_err());
        assert_eq!(rt.evaluate("globalThis.__pwned").unwrap(), serde_json::Value::Null);
        drop(frame);
    }

    #[test]
    fn cdp_suspension_recipes_never_restore_child_handles_in_the_main_world() {
        let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body>child</body></html>").unwrap();
        let CdpEvaluation::Complete(child) = rt.start_cdp_evaluation_in_frame(
            Some(1), "({answer:42})", false, false,
        ).unwrap() else { panic!("expected a handle"); };
        let child_id = child.object_id.unwrap();
        let CdpEvaluation::Complete(root) = rt.start_cdp_evaluation(
            "document.querySelector('h1')", false, false,
        ).unwrap() else { panic!("expected a handle"); };
        let root_id = root.object_id.unwrap();
        let state = rt.take_cdp_object_state();
        drop(frame);
        drop(rt);
        let mut rt = setup_runtime("<html><body><h1>Main</h1></body></html>");
        rt.restore_cdp_object_state(state);
        assert!(rt.start_cdp_call("function() { return document.URL; }",
            Some(&child_id), &[], true, false).is_err());
        let CdpEvaluation::Complete(value) = rt.start_cdp_call("function() { return this.textContent; }",
            Some(&root_id), &[], true, false).unwrap() else { panic!("expected a value"); };
        assert_eq!(value.value.unwrap(), serde_json::json!("Main"));
        rt.release_object_group();
        assert!(rt.start_cdp_call("function() { return this; }",
            Some(&root_id), &[], true, false).is_err());
    }

    #[test]
    fn pending_cdp_frame_evaluation_rejects_a_retired_realm_with_a_reused_id() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body>old</body></html>").unwrap();
        let evaluation = rt.start_cdp_evaluation_in_frame(
            Some(1), "new Promise(() => {})", true, true,
        ).unwrap();
        let CdpEvaluation::Pending(pending) = evaluation else {
            panic!("expected a pending child evaluation");
        };
        assert!(rt.has_cdp_evaluation(&pending));
        drop(frame);
        let _replacement = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body>new</body></html>").unwrap();
        assert!(!rt.has_cdp_evaluation(&pending));
        assert!(!rt.cdp_evaluation_ready(&pending));
        assert_eq!(rt.finish_cdp_evaluation(pending, true).unwrap_err(),
            "Execution context was destroyed");
        assert!(rt.pending_cdp_evaluations.is_empty());
    }

    #[test]
    fn table_rows_are_live_ordered_readonly_collections() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const table = document.createElement('table');
            document.body.append(table);
            for (const [section, id] of [['tfoot','foot'],['tbody','body'],['thead','head']]) {
                const group = document.createElement(section);
                group.innerHTML = '<tr id="'+id+'"><td></td></tr>';
                table.append(group);
            }
            const direct = document.createElement('tr');
            direct.id = 'direct';
            table.append(direct);
            table.querySelector('td').innerHTML = '<table><tr id="nested"><td></td></tr></table>';
            table.querySelector('thead').append(document.createElementNS('urn:foreign', 'tr'));
            const rows = table.rows;
            const initial = Array.from(rows, row => row.id);
            const collection = [rows === table.rows, rows instanceof HTMLCollection,
                Array.isArray(rows), Object.prototype.toString.call(rows),
                rows.item(1).id, rows.namedItem('head').id, rows.head.id,
                Object.keys(rows), 'head' in rows, rows.item(99)];
            const writes = [Reflect.set(rows, '0', null), Reflect.set(rows, 'length', 0),
                Reflect.defineProperty(rows, '1', {value:null}), Reflect.deleteProperty(rows, '0')];
            rows.custom = 'expando';
            const reflection = [Object.keys(rows), Object.getOwnPropertyNames(rows),
                Reflect.deleteProperty(rows, '99')];
            Object.defineProperty(rows, Symbol.toStringTag, {value:'CustomCollection', configurable:false});
            reflection.push(Object.prototype.toString.call(rows));
            table.querySelector('thead').textContent = '';
            direct.id = 'renamed';
            direct.setAttribute('name', 'alias');
            const changed = [rows.length, rows[0].id, rows.renamed === direct,
                rows.alias === direct, 'head' in rows, rows.head === undefined];
            direct.id = '99';
            const numericName = [Object.getOwnPropertyNames(rows).includes('99'),
                rows[99] === undefined, rows.namedItem('99') === direct,
                Reflect.deleteProperty(rows, '99')];
            table.textContent = '';
            return {initial, collection, writes, reflection, changed, numericName, empty:rows.length};
        })()"#).unwrap(), serde_json::json!({
            "initial":["head","body","direct","foot"],
            "collection":[true,true,false,"[object HTMLCollection]","body","head","head",
                ["0","1","2","3"],true,null],
            "writes":[false,false,false,false],
            "reflection":[["0","1","2","3","custom"],
                ["0","1","2","3","head","body","direct","foot","custom"],true,"[object CustomCollection]"],
            "changed":[3,"body",true,true,false,true], "numericName":[true,true,true,true], "empty":0,
        }));
    }

    #[test]
    fn table_rows_preserve_factory_brands_and_reject_non_table_receivers() {
        let mut rt = setup_runtime("<html><body><table><tr><th>Header</th></tr></table><h1>Heading</h1></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const parsed = document.querySelector('table');
            const created = document.createElement('table');
            const cloned = parsed.cloneNode(true);
            const getter = Object.getOwnPropertyDescriptor(HTMLTableElement.prototype, 'rows').get;
            const invalid = [document.createElement('div'), {},
                document.createElementNS('urn:foreign', 'table')].map(value => {
                try { getter.call(value); return false; } catch (error) { return error instanceof TypeError; }
            });
            let illegalConstructor = false;
            try { new HTMLTableElement(); } catch (error) { illegalConstructor = error instanceof TypeError; }
            return [parsed instanceof HTMLTableElement, created instanceof HTMLTableElement,
                cloned instanceof HTMLTableElement, cloned.rows.length, parsed.rows.length,
                document.querySelector('h1') instanceof HTMLTableElement, invalid, illegalConstructor,
                HTMLTableElement.length, getter.name, getter.toString()];
        })()"#).unwrap(), serde_json::json!([true,true,true,1,1,false,[true,true,true],true,
            0,"get rows","function get rows() { [native code] }"]));
    }

    #[test]
    fn table_rows_are_live_in_child_realms() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body><table><tr><th>Header</th></tr></table></body></html>").unwrap();
        assert_eq!(frame.evaluate(&mut rt, r#"(() => {
            const table = document.querySelector('table');
            const rows = table.rows;
            const branded = table instanceof HTMLTableElement && rows instanceof HTMLCollection;
            table.querySelector('tbody').append(document.createElement('tr'));
            return [branded, rows.length, table.cloneNode(true).rows.length];
        })()"#).unwrap(), serde_json::json!([true,2,2]));
    }

    #[test]
    fn table_members_preserve_child_realm_collections_and_borrowed_methods() {
        let mut rt = setup_runtime("<html><body><table><tr><td>Parent</td></tr></table></body></html>");
        let _frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body><table><tr><th>Header</th></tr></table></body></html>").unwrap();
        assert_eq!(rt.evaluate(r#"(() => {
            const child = globalThis.__obscura_frameObjects[1].document;
            const table = child.querySelector('table'), body = table.tBodies[0], row = body.rows[0];
            const cells = row.cells;
            const outerGetter = Object.getOwnPropertyDescriptor(HTMLTableRowElement.prototype, 'cells').get;
            const outerMethod = HTMLTableRowElement.prototype.insertCell;
            const cell = outerMethod.call(row);
            const branded = cells instanceof child.defaultView.HTMLCollection
                && cell instanceof child.defaultView.HTMLTableCellElement;
            const borrowed = outerGetter !== Object.getOwnPropertyDescriptor(child.defaultView.HTMLTableRowElement.prototype, 'cells').get
                && outerGetter.call(row) === cells;
            table.insertRow(0).insertCell();
            const indices = [row.rowIndex, row.sectionRowIndex, cell.cellIndex];
            row.deleteCell(0);
            return [branded, borrowed, cells.length, indices, cell.cellIndex,
                table.cloneNode(true).rows[1].cells.length, document.querySelector('td').textContent];
        })()"#).unwrap(), serde_json::json!([true,true,1,[1,1,1],0,1,"Parent"]));
    }

    #[test]
    fn native_select_factory_preserves_child_clones_and_custom_upgrade_identity() {
        let mut rt = setup_runtime("<html><body><select id='custom' is='native-select'><option value='a'>A</option></select></body></html>");
        let _frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body><select><option value='a'>A</option><option value='b'>B</option></select></body></html>").unwrap();
        assert_eq!(rt.evaluate(r#"(() => {
            const child = globalThis.__obscura_frameObjects[1].document;
            const select = child.querySelector('select'), option = child.createElement('option');
            option.value = 'n'; select[0] = option;
            const clone = select.cloneNode(true);
            const childChecks = [select[0] === option,
                select instanceof child.defaultView.HTMLSelectElement,
                clone[0].value, clone[0] instanceof child.defaultView.HTMLOptionElement,
                Object.getOwnPropertyDescriptor(select, '0').value === option,
                Reflect.deleteProperty(select, '0')];
            Reflect.defineProperty(select, '1', {value:null});
            let strictDelete = false;
            try { (function(){'use strict';delete select[0];})(); }
            catch(e) { strictDelete = e instanceof TypeError; }
            const retained = document.getElementById('custom');
            retained.marker = 'retained';
            class NativeSelect extends HTMLSelectElement {
                constructor() { super(); this.upgraded = true; this[0].value = 'upgraded'; }
            }
            customElements.define('native-select', NativeSelect, {extends:'select'});
            // Customized-built-in matching is separate from the existing upgrade mechanism.
            customElements._upgradeElement(retained, NativeSelect);
            const created = document.createElement('select');
            created.appendChild(document.createElement('option'));
            const foreign = document.createElementNS('urn:foreign', 'select');
            return [childChecks, select.length, select[1] === undefined, strictDelete,
                retained === document.getElementById('custom'), retained.marker,
                retained.upgraded, retained instanceof NativeSelect, retained[0].value,
                created[0] === created.item(0), '0' in foreign];
        })()"#).unwrap(), serde_json::json!([[true,true,"n",true,true,false],
            1,true,true,true,"retained",true,true,"upgraded",true,false]));
    }

    #[test]
    fn noninteractive_dialogs_do_not_accept_destructive_confirmation() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const records = ["keep"];
            const accepted = confirm("Delete this record?");
            if (accepted) records.pop();
            return {accepted, records, prompt: prompt("Edit", "draft"),
                alertResult: typeof alert("Notice")};
        })()"#).unwrap(), serde_json::json!({
            "accepted": false, "records": ["keep"], "prompt": null,
            "alertResult": "undefined",
        }));
    }

    #[test]
    fn noninteractive_dialog_defaults_apply_to_child_realms() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let frame = crate::frame::FrameRealm::new(&mut rt, 1, 0,
            "http://example.com/child", "<html><body></body></html>").unwrap();
        assert_eq!(frame.evaluate(&mut rt, "confirm('Delete?')").unwrap(),
            serde_json::json!(false));
    }

    #[cfg(obscura_external_bootstrap)]
    #[test]
    fn snapshot_core_methods_have_bytecode_before_first_use() {
        crate::v8_flags::set_v8_flags("--allow-natives-syntax");
        let mut rt = super::ObscuraJsRuntime::new();
        assert_eq!(rt.evaluate(r#"(() => {
            const methods = [Node, Element, Document, Response, Headers,
                Node.prototype.appendChild, Document.prototype.createElement,
                Object.getOwnPropertyDescriptor(Node.prototype, 'textContent').get,
                Object.getOwnPropertyDescriptor(Node.prototype, 'textContent').set];
            // V8's kInterpreted bit identifies shared bytecode, including
            // restored closures whose entry point is still CompileLazy.
            return methods.filter(fn => !(%GetOptimizationStatus(fn) & (1 << 6)))
                .map(fn => fn.name);
        })()"#).unwrap(), serde_json::json!([]),
            "common browser operations must not recompile in each fresh document");
    }

    #[test]
    fn snapshot_compiler_is_not_available_in_page_or_frame_realms() {
        let mut rt = setup_runtime("<html><body><iframe id='frame'></iframe></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const check = `(function() {
                let denied = false;
                try { Function('return %GetOptimizationStatus(function() {});')(); }
                catch (error) { denied = error instanceof SyntaxError; }
                return denied && !('__obscura_snapshot_compile' in globalThis);
            })()`;
            return [eval(check), document.getElementById('frame').contentWindow.eval(check)];
        })()"#).unwrap(), serde_json::json!([true, true]));
    }

    #[test]
    fn bootstrap_source_uses_ascii_snapshot_storage() {
        let source = include_str!("../js/bootstrap.js")
            .replace("/* INDEXED_DB */", include_str!("../js/indexed_db.js"));
        assert!(source.is_ascii(), "use Unicode escapes in bootstrap literals so source can be shared");
        if cfg!(obscura_external_bootstrap) {
            assert_eq!(super::SNAPSHOT.windows(source.len())
                .filter(|window| *window == source.as_bytes()).count(), 1,
                "native snapshots must retain one shared source backing");
        }
    }

    #[test]
    fn custom_element_names_keep_unicode_characters() {
        let mut rt = setup_runtime("<main></main>");
        assert_eq!(rt.evaluate(r#"['widget-\u00e9','widget-\u00b7','widget-\u0100'].every(name => {
            customElements.define(name, class extends HTMLElement {});
            return typeof customElements.get(name) === 'function';
        })"#).unwrap(), serde_json::json!(true));
    }

    #[test]
    fn classic_code_cache_reuses_compilation_not_page_state() {
        use std::sync::atomic::Ordering;
        let declarations = (0..256).map(|i| format!("function f{i}(){{return {i};}}"))
            .collect::<String>();
        let source = format!("{declarations}\nglobalThis.answer=f137();\
            globalThis.runs=(globalThis.runs||0)+1;");
        let url = "https://code-cache.test/app.js";
        for _ in 0..2 {
            let mut runtime = super::ObscuraJsRuntime::with_base_url("https://code-cache.test/page");
            runtime.set_url("https://code-cache.test/page");
            runtime.execute_script(url, &source).unwrap();
            assert_eq!(runtime.evaluate("[answer,runs]").unwrap(), serde_json::json!([137,1]));
            runtime.execute_script("<mutate>", "answer=999;runs=99;").unwrap();
        }
        assert_eq!(super::CLASSIC_CODE_CACHE_ACCEPTED.load(Ordering::Relaxed), 1,
            "fresh isolate should consume compiled data for identical source");
        // Same URL and byte length must not make changed source share bytecode.
        let changed = source.replace("return 137;", "return 731;");
        let mut runtime = super::ObscuraJsRuntime::with_base_url("https://code-cache.test/page");
        runtime.set_url("https://code-cache.test/page");
        runtime.execute_script(url, &changed).unwrap();
        assert_eq!(runtime.evaluate("[answer,runs]").unwrap(), serde_json::json!([731,1]));
        assert_eq!(super::CLASSIC_CODE_CACHE_ACCEPTED.load(Ordering::Relaxed), 1);
        drop(runtime);
        let mut other_origin = super::ObscuraJsRuntime::with_base_url("https://other.test/page");
        other_origin.set_url("https://other.test/page");
        other_origin.execute_script(url, &changed).unwrap();
        assert_eq!(other_origin.evaluate("[answer,runs]").unwrap(), serde_json::json!([731,1]));
        assert_eq!(super::CLASSIC_CODE_CACHE_ACCEPTED.load(Ordering::Relaxed), 1,
            "code reuse is partitioned by document origin");
    }

    use super::*;
    use obscura_dom::parse_html;

    #[test]
    fn one_busy_isolate_constructor_does_not_block_all_pages() {
        let warmup = ObscuraJsRuntime::new();
        let guard = ISOLATE_CREATE_LOCK.lock().unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let workers = (0..8).map(|id| {
            let tx = tx.clone();
            std::thread::spawn(move || {
                for _ in 0..4 {
                    let mut rt = ObscuraJsRuntime::new();
                    rt.set_dom(parse_html("<p id='value'>fresh</p>"));
                    rt.run_page_init();
                    assert_eq!(rt.evaluate("typeof globalThis.worker").unwrap(), serde_json::json!("undefined"));
                    rt.execute_script("worker", &format!("globalThis.worker={id};")).unwrap();
                    assert_eq!(rt.evaluate("[worker,document.getElementById('value').textContent]").unwrap(),
                        serde_json::json!([id, "fresh"]));
                    tx.send(()).unwrap();
                }
            })
        }).collect::<Vec<_>>();
        let independent = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok();
        drop(guard);
        for worker in workers { worker.join().unwrap(); }
        drop(warmup);
        assert!(independent, "one busy isolate constructor blocked every page");
        assert_eq!(rx.try_iter().count(), 31);
    }

    #[test]
    fn completed_scripts_do_not_wait_for_watchdog_deadline() {
        let mut rt = ObscuraJsRuntime::new();
        for _ in 0..200 {
            let started = std::time::Instant::now();
            rt.execute_script_with_timeout(
                "fast-script", "globalThis.completed = true;",
                std::time::Duration::from_secs(2),
            ).unwrap();
            assert!(started.elapsed() < std::time::Duration::from_secs(1),
                "completed script waited for its cancelled watchdog: {:?}", started.elapsed());
        }
        assert_eq!(rt.evaluate("globalThis.completed").unwrap(), serde_json::json!(true));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn overlapping_watchdogs_do_not_allocate_a_thread_per_deadline() {
        let mut rt = ObscuraJsRuntime::new();
        let thread_count = || std::fs::read_dir("/proc/self/task").unwrap().count();
        let before = thread_count();
        let guards: Vec<_> = (0..64)
            .map(|_| rt.arm_watchdog(std::time::Duration::from_secs(30)))
            .collect();
        let armed = thread_count();
        for guard in guards {
            assert!(!rt.disarm_watchdog(guard));
        }
        assert!(armed <= before + 8,
            "bounded operations created unbounded watchdog threads: {before} -> {armed}");
        assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
    }

    fn setup_runtime(html: &str) -> ObscuraJsRuntime {
        let dom = parse_html(html);
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.com/test");
        rt.set_title("Test Page");
        rt.run_page_init();
        rt
    }

    #[cfg(feature = "render")]
    #[test]
    fn static_accessibility_visibility_does_not_allocate_geometry() {
        let rt = setup_runtime("<!doctype html><style>.gone{display:none}.hidden{visibility:hidden}.shown{visibility:visible}</style><div class=gone id=gone>hidden</div><div class=hidden id=hidden><span class=shown id=shown>visible</span></div>");
        let styles = rt.accessibility_styles();
        let ids = rt.with_dom(|dom| ["gone", "hidden", "shown"].map(|id| dom.get_element_by_id(id).unwrap())).unwrap();
        assert!(styles[&ids[0]].display_none);
        assert_eq!(styles[&ids[1]].visibility_hidden, Some(true));
        assert_eq!(styles[&ids[2]].visibility_hidden, Some(false));
        assert!(rt.state.borrow().prepared_render.is_none(), "a static visibility read must not retain layout/text geometry for an entire document");
    }

    #[test]
    fn document_content_type_retains_url_fallback_without_response_metadata() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html("<html><body></body></html>"));
        rt.set_url("https://example.com/document.xhtml");
        rt.run_page_init();
        assert_eq!(rt.evaluate("document.contentType").unwrap(),
            serde_json::json!("application/xhtml+xml"));
    }

    #[test]
    fn screen_override_clear_before_page_init_preserves_mutable_hidden_slots() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_screen_size_override(None, false);
        rt.set_dom(parse_html("<p>Screen override lifecycle</p>"));
        rt.set_url("http://example.com/test");
        rt.run_page_init();
        for (width, height) in [(1280, 800), (700, 500)] {
            rt.set_screen_size_override(Some((width as f64, height as f64)), true);
            assert_eq!(rt.evaluate("[screen.width, screen.height, screen.availWidth, screen.availHeight]").unwrap(),
                serde_json::json!([width, height, width, height]));
            assert_eq!(rt.evaluate(r#"(() => {
                const names = ['__obscura_screen_w', '__obscura_screen_h'];
                return names.every(name => {
                    const descriptor = Object.getOwnPropertyDescriptor(window, name);
                    return descriptor.writable && descriptor.configurable && !descriptor.enumerable
                        && !Reflect.ownKeys(window).includes(name);
                });
            })()"#).unwrap(), serde_json::json!(true));
            rt.set_screen_size_override(None, false);
            assert_eq!(rt.evaluate("[__obscura_screen_w, __obscura_screen_h].every(value => value === undefined)").unwrap(),
                serde_json::json!(true));
        }
    }

    #[test]
    fn late_runtime_internal_names_use_the_existing_reflection_registry() {
        let mut rt = setup_runtime("<button id='target'>Click</button>");
        rt.set_viewport(900.0, 700.0);
        rt.set_screen_size_override(Some((1280.0, 800.0)), true);
        assert_eq!(rt.evaluate(r#"(() => {
            document.getElementById('target').click();
            globalThis.__obscura_await_rejected = false;
            globalThis.__obscura_page_owned = 42;
            const names = ['__obscura_await_rejected', '__obscura_click_target',
                '__obscura_screen_emulated', '__obscura_screen_w', '__obscura_screen_h',
                '__obscura_viewport_w', '__obscura_viewport_h'];
            const surfaces = [Object.keys(window), Object.getOwnPropertyNames(window),
                Reflect.ownKeys(window), Object.keys(Object.getOwnPropertyDescriptors(window))];
            const ordinary = { __obscura_screen_w: 1 };
            return [surfaces.every(keys => names.every(name => !keys.includes(name))),
                surfaces.every(keys => keys.includes('__obscura_page_owned')),
                Object.keys(ordinary).includes('__obscura_screen_w'),
                innerWidth, innerHeight, screen.width, screen.height];
        })()"#).unwrap(), serde_json::json!([true, true, true, 900, 700, 1280, 800]));
        rt.set_screen_size_override(None, false);
        rt.set_screen_size_override(Some((1400.0, 900.0)), true);
        assert_eq!(rt.evaluate("[Reflect.ownKeys(window).includes('__obscura_screen_w'), screen.width]").unwrap(),
            serde_json::json!([false, 1400]));
    }

    #[test]
    fn page_script_cannot_reach_deno_core_or_bootstrap_handoff() {
        let mut rt = setup_runtime("<html><body><p id='value'>safe</p></body></html>");
        rt.evaluate("delete globalThis.__obscura_test_ops").unwrap();

        assert_eq!(
            rt.evaluate("[typeof Deno, typeof __obscuraCore, typeof __obscura_core_handoff, typeof __bootstrap]")
                .unwrap(),
            serde_json::json!(["undefined", "undefined", "undefined", "undefined"])
        );
        // A list of names missed deno_core's `__bootstrap.core` alias, which
        // handed every page the raw ops. Check what any global leads to.
        assert_eq!(
            rt.evaluate(r#"(() => {
                const names = new Set([...Reflect.ownKeys(globalThis), ...(globalThis.__obscura_hide_list || [])]);
                const reaches = (value) => {
                    try {
                        return !!value && (typeof value === 'object' || typeof value === 'function')
                            && [value, value.core, value.ops && value, value.core && value.core.ops && value.core]
                                .some((v) => v && v.ops && typeof v.ops.op_dom === 'function');
                    } catch (e) { return false; }
                };
                return [...names].filter((name) => { try { return reaches(globalThis[name]); } catch (e) { return false; } }).map(String);
            })()"#).unwrap(),
            serde_json::json!([]),
            "no page-visible global may lead to the op table"
        );
        assert_eq!(
            rt.evaluate("document.getElementById('value').textContent")
                .unwrap(),
            serde_json::json!("safe"),
            "DOM ops must continue to work through the private closure"
        );
    }

    #[test]
    fn native_metadata_does_not_retain_removed_methods() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let value = rt.execute_runtime_script("<removed-native-method>", r#"(() => {
            const fn = AudioBuffer.prototype.copyToChannel;
            if (Function.prototype.toString.call(fn) !== 'function copyToChannel() { [native code] }') {
                throw new Error('Live method lost its native source');
            }
            delete AudioBuffer.prototype.copyToChannel;
            return fn;
        })()"#.into()).unwrap();
        let weak = deno_core::v8::Weak::new(rt.runtime().v8_isolate(), &value);
        rt.collect_garbage();
        assert!(!weak.is_empty(), "a caller-held method must remain live");
        drop(value);
        rt.collect_garbage();
        assert!(weak.is_empty(), "native-source metadata must not own a removed method");
    }

    #[test]
    fn native_metadata_does_not_retain_removed_accessors() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let value = rt.execute_runtime_script("<removed-native-accessor>", r#"(() => {
            const fn = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'x').get;
            if (Function.prototype.toString.call(fn) !== 'function get x() { [native code] }') {
                throw new Error('Live accessor lost its native source');
            }
            delete MouseEvent.prototype.x;
            return fn;
        })()"#.into()).unwrap();
        let weak = deno_core::v8::Weak::new(rt.runtime().v8_isolate(), &value);
        rt.collect_garbage();
        assert!(!weak.is_empty(), "a caller-held accessor must remain live");
        drop(value);
        rt.collect_garbage();
        assert!(weak.is_empty(), "native-source metadata must not own a removed accessor");
    }

    #[test]
    fn native_source_survives_page_replacement_of_weak_collection_methods() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate_script(r#"(() => {
            const method = AudioBuffer.prototype.copyToChannel;
            const getter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'x').get;
            const fail = () => { throw new Error('Page collection method called'); };
            WeakSet.prototype.has = WeakSet.prototype.add = fail;
            WeakMap.prototype.has = WeakMap.prototype.get = WeakMap.prototype.set = fail;
            return [method.toString(), getter.toString()];
        })()"#).unwrap(), serde_json::json!([
            "function copyToChannel() { [native code] }",
            "function get x() { [native code] }",
        ]));
    }

    // #1013: removeAttribute('id') must update the id_index so getElementById no
    // longer returns the (still-attached) element.
    #[test]
    fn get_element_by_id_reflects_remove_attribute() {
        let mut rt = setup_runtime("<html><body><div id='test'>x</div></body></html>");
        assert_eq!(
            rt.evaluate("document.getElementById('test') !== null")
                .unwrap(),
            serde_json::json!(true),
            "the element should be found before its id is removed"
        );
        rt.evaluate("document.getElementById('test').removeAttribute('id')")
            .unwrap();
        assert_eq!(
            rt.evaluate("document.getElementById('test') === null")
                .unwrap(),
            serde_json::json!(true),
            "getElementById must not return an element whose id was removed"
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn page_transport_keeps_render_resources_cache_only_across_document_resets() {
        let standalone = ObscuraJsRuntime::new();
        assert!(
            standalone.render_resource_sync_loading_enabled(),
            "standalone render runtimes keep the compatibility loader"
        );
        standalone.set_dom(parse_html("<html><body></body></html>"));
        assert!(standalone.render_resource_sync_loading_enabled());

        let rt = ObscuraJsRuntime::new();
        rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));
        assert!(
            !rt.render_resource_sync_loading_enabled(),
            "installing a page transport must switch the cache to cache-only"
        );
        rt.set_dom(parse_html(
            "<html><body><img src=\"https://example.test/a.png\"></body></html>",
        ));
        assert!(
            !rt.render_resource_sync_loading_enabled(),
            "set_dom rebuilds the cache and must keep it cache-only"
        );
        assert!(rt.take_dom().is_some());
        assert!(
            !rt.render_resource_sync_loading_enabled(),
            "take_dom rebuilds the cache and must keep it cache-only"
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn renderer_resource_transport_preserves_file_subresource_policy() {
        let file = "file:///tmp/obscura-render-resource.svg";
        assert!(page_render_resource_url_allowed(
            "file:///tmp/obscura-page.html",
            file
        ));
        assert!(!page_render_resource_url_allowed(
            "https://example.test/page",
            file
        ));
        assert!(page_render_resource_url_allowed(
            "https://example.test/page",
            "https://assets.test/image.svg"
        ));
    }

    #[cfg(feature = "render")]
    #[test]
    fn render_resource_in_flight_set_has_a_page_wide_bound() {
        let rt = ObscuraJsRuntime::new();
        let requests = (0..(MAX_PENDING_RENDER_RESOURCES + 4))
            .map(|index| (format!("https://assets.test/{index}.png"), None, false))
            .collect();

        assert_eq!(
            rt.mark_render_resources_in_flight(requests).len(),
            MAX_PENDING_RENDER_RESOURCES
        );
        assert!(
            rt.mark_render_resources_in_flight(vec![(
                "https://assets.test/extra.png".to_string(),
                None,
                false,
            )])
            .is_empty()
        );
    }

    /// A load that answers after the document was retired (abort is not a
    /// join) must neither seed the surviving runtime nor clear a same-URL
    /// request of the document that replaced it.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn late_channel_answer_of_a_retired_document_is_discarded() {
        let url = "https://example.test/a.svg".to_string();
        let mut rt = ObscuraJsRuntime::new();
        rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::new()));
        rt.set_dom(parse_html(&format!(
            "<html><body><img src=\"{url}\"></body></html>"
        )));
        rt.set_url("https://example.test/page");
        let body = std::sync::Arc::<[u8]>::from(
            br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"></svg>"##
                .as_slice(),
        );
        let answer = |generation, tx: &tokio::sync::mpsc::UnboundedSender<_>| {
            tx.send(crate::ops::RenderResourceLoad {
                generation,
                url: url.clone(),
                profile: None,
                is_font: false,
                response: Some(crate::ops::RenderResourceResponse {
                    url: url.clone(),
                    status: 200,
                    headers: Default::default(),
                    body: body.clone(),
                }),
            })
        };
        // The old document's load holds the sender it was started with.
        let old_tx = rt.state.borrow().render_resource_tx.clone();
        let generation = rt.document_generation();
        rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
        rt.abandon_render_resources();
        assert!(!rt.has_pending_render_resources());
        assert!(
            answer(generation, &old_tx).is_err(),
            "retired channel is closed"
        );
        assert_eq!(rt.apply_render_resource_results(), 0);
        assert!(
            !rt.render_resource_is_known(&url),
            "late bytes must not seed the runtime"
        );

        // The same runtime requests the URL again; a stale-generation answer
        // that somehow reaches the live channel is fenced too.
        let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
        assert_eq!(requests.len(), 1);
        let live_tx = rt.state.borrow().render_resource_tx.clone();
        assert!(answer(generation.wrapping_sub(1), &live_tx).is_ok());
        assert_eq!(rt.apply_render_resource_results(), 0);
        assert!(
            rt.has_pending_render_resources(),
            "stale answer must not clear the live request"
        );
        assert!(!rt.render_resource_is_known(&url));
        assert!(answer(generation, &live_tx).is_ok());
        assert_eq!(rt.apply_render_resource_results(), 1);
        assert!(!rt.has_pending_render_resources());
        assert!(rt.render_resource_is_known(&url));
    }

    /// A runtime with only the stealth client installed has a page transport
    /// (`has_page_transport`, cache-only renderer) and must load through it.
    #[cfg(all(feature = "render", feature = "stealth"))]
    #[tokio::test(flavor = "current_thread")]
    async fn stealth_only_transport_starts_render_resource_loads() {
        let url = "http://127.0.0.1:9/a.svg".to_string();
        let mut rt = ObscuraJsRuntime::new();
        rt.set_stealth_client(std::sync::Arc::new(
            obscura_net::StealthHttpClient::with_proxy(
            std::sync::Arc::new(obscura_net::CookieJar::new()),
            None,
            true,
            ),
        ));
        assert!(rt.has_page_transport());
        assert!(!rt.render_resource_sync_loading_enabled());
        rt.set_dom(parse_html(&format!(
            "<html><body><img src=\"{url}\"></body></html>"
        )));
        rt.set_url("http://127.0.0.1:9/page");
        let requests = rt.mark_render_resources_in_flight(vec![(url.clone(), None, false)]);
        assert_eq!(
            rt.start_render_resource_loads(requests),
            1,
            "stealth client is a transport"
        );
        assert!(rt.has_pending_render_resources());
        // The unreachable origin answers with a failed load, which settles it.
        for _ in 0..200 {
            if rt.apply_render_resource_results() > 0 || !rt.has_pending_render_resources() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            !rt.has_pending_render_resources(),
            "the load must finish through the stealth client"
        );
        assert!(rt.render_resource_is_known(&url));
    }

    #[cfg(feature = "render")]
    #[test]
    fn live_form_values_paint_without_mutating_content_attributes() {
        let mut rt = setup_runtime(
            "<!doctype html><html><body><input id=field value=initial><input id=box type=checkbox></body></html>",
        );
        rt.set_viewport(320.0, 120.0);
        let before = rt
            .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
            .unwrap();
        let prepared_address =
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize;
        rt.evaluate("document.getElementById('field').value = 'changed'")
            .unwrap();
        assert_eq!(
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address,
            "live text values must not discard unchanged layout"
        );
        let changed_value = rt
            .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
            .unwrap();
        assert_ne!(before, changed_value, "live text value must affect pixels");
        rt.evaluate("document.getElementById('box').indeterminate = true")
            .unwrap();
        assert_eq!(
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address,
            "indeterminate paint state must not discard unchanged layout"
        );
        let indeterminate = rt
            .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
            .unwrap();
        assert_ne!(
            changed_value, indeterminate,
            "indeterminate state must affect pixels"
        );
        rt.evaluate("document.getElementById('box').indeterminate = false")
            .unwrap();
        rt.evaluate("document.getElementById('box').checked = true")
            .unwrap();
        let after = rt
            .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
            .unwrap();
        assert_ne!(changed_value, after, "checked state must affect pixels");
        assert_eq!(rt.evaluate("[document.getElementById('field').value, document.getElementById('field').getAttribute('value'), document.getElementById('box').getAttribute('checked'), document.querySelectorAll(':checked').length]").unwrap(), serde_json::json!(["changed", "initial", null, 1]));
        rt.evaluate("(document.getElementById('field').value = 'initial', document.getElementById('box').checked = false)").unwrap();
        assert_eq!(
            before,
            rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
                .unwrap()
        );
        rt.evaluate("document.getElementById('field').value = ''")
            .unwrap();
        assert_eq!(
            rt.evaluate("document.getElementById('field').value")
                .unwrap(),
            serde_json::json!("")
        );
        assert_ne!(
            before,
            rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
                .unwrap(),
            "empty current value must override a nonempty default"
        );
    }

    #[test]
    fn cloned_controls_keep_current_value_and_checked_state() {
        let mut rt = setup_runtime(
            "<html><body><div id=group><input id=field value=default><input id=box type=checkbox></div></body></html>",
        );
        let result = rt.evaluate("(() => {const field=document.getElementById('field'), box=document.getElementById('box');field.value='current';box.checked=true;box.indeterminate=true;const clone=document.getElementById('group').cloneNode(true);return [clone.children[0].value,clone.children[0].getAttribute('value'),clone.children[1].checked,clone.children[1].indeterminate];})()").unwrap();
        assert_eq!(
            result,
            serde_json::json!(["current", "default", true, false])
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn form_reset_restores_default_input_state_and_pixels() {
        let mut rt = setup_runtime(
            "<html><body><form id=form><input id=field value=default><input id=box type=checkbox checked></form></body></html>",
        );
        rt.set_viewport(320.0, 120.0);
        let before = rt
            .screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
            .unwrap();
        rt.evaluate("const field=document.getElementById('field'),box=document.getElementById('box');field.value='typed';box.checked=false;box.indeterminate=true").unwrap();
        assert_ne!(
            before,
            rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
                .unwrap()
        );
        rt.evaluate("document.getElementById('form').reset()")
            .unwrap();
        assert_eq!(
            rt.evaluate("[field.value,field.getAttribute('value'),box.checked,box.indeterminate,box.hasAttribute('checked')]").unwrap(),
            serde_json::json!(["default", "default", true, false, true])
        );
        assert_eq!(
            before,
            rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test"))
                .unwrap()
        );
    }

    // SEC-503 / #820 — createObjectURL must reject non-Blob input (an object
    // that merely has a .text() method, e.g. Response) with a TypeError, as
    // Chrome does; a real Blob is still accepted.
    #[test]
    fn create_object_url_rejects_non_blob_input() {
        let mut rt = setup_runtime("<html><body></body></html>");

        // A real Blob is accepted and yields a blob: URL.
        let ok = rt
            .evaluate("URL.createObjectURL(new Blob(['hello'])).startsWith('blob:')")
            .unwrap();
        assert_eq!(ok, serde_json::json!(true), "a real Blob must be accepted");

        // A non-Blob object with only .text() must be rejected.
        let rejected = rt
            .evaluate(
                "(function(){ try { URL.createObjectURL({ text: () => Promise.resolve('x') }); return false; }\
                   catch (e) { return !!(e && e.name === 'TypeError'); } })()",
            )
            .unwrap();
        assert_eq!(
            rejected,
            serde_json::json!(true),
            "createObjectURL must throw TypeError for non-Blob input"
        );
    }

    // #751 — the accepted case above only asserts the `blob:` scheme, which the
    // old `blob:obscura/<base36>` form also satisfied. Pin the shape itself:
    // Chrome mints `blob:<document origin>/<v4 UUID>`, so a URL that names the
    // engine, or carries a token no UUID parser accepts, is a regression even
    // though it still starts with `blob:`.
    #[test]
    fn a_blob_url_is_chrome_shaped() {
        let mut rt = setup_runtime("<html><body></body></html>");

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const url = URL.createObjectURL(new Blob(["x"]));
                    const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
                    const second = URL.createObjectURL(new Blob(["y"]));
                    const threw = argument => {
                        try {
                            argument === undefined ? URL.createObjectURL() : URL.createObjectURL(argument);
                            return "did not throw";
                        } catch (error) {
                            return error instanceof TypeError ? error.message : String(error);
                        }
                    };
                    return {
                        origin: url.slice(0, "blob:http://example.com/".length),
                        uuid: uuid.test(url.slice("blob:http://example.com/".length)),
                        names_the_engine: /obscura|fake/.test(url),
                        unique: url !== second,
                        no_argument: threw(undefined),
                        string: threw("nope"),
                        number: threw(7),
                        null_value: threw(null),
                        file_is_a_blob: URL.createObjectURL(new File(["x"], "a.txt")).startsWith("blob:http://example.com/"),
                    };
                })()"#,
            )
            .unwrap(),
            serde_json::json!({
                "origin": "blob:http://example.com/",
                "uuid": true,
                "names_the_engine": false,
                "unique": true,
                "no_argument": "Failed to execute 'createObjectURL' on 'URL': 1 argument required, but only 0 present.",
                "string": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",
                "number": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",
                "null_value": "Failed to execute 'createObjectURL' on 'URL': parameter 1 is not of type 'Blob'.",
                "file_is_a_blob": true,
            })
        );
    }

    // #751 — the source has to be in the store by the time createObjectURL
    // returns. Blob-URL Worker construction is synchronous in a real browser,
    // so an async `blob.text().then()` store races the Worker constructor and
    // the Worker falls through to fetch() and fails; revocation then has to
    // remove it again rather than leaving the entry readable.
    #[test]
    fn a_blob_url_is_stored_synchronously_and_revocation_removes_it() {
        let mut rt = setup_runtime("<html><body></body></html>");

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const url = URL.createObjectURL(new Blob(["self.onmessage = () => {};"]));
                    const stored = globalThis.__blobStore[url];
                    URL.revokeObjectURL(url);
                    return {
                        stored_synchronously: stored === "self.onmessage = () => {};",
                        revoked: globalThis.__blobStore[url] === undefined,
                    };
                })()"#,
            )
            .unwrap(),
            serde_json::json!({
                "stored_synchronously": true,
                "revoked": true,
            })
        );
    }

    // SEC-301 / SEC-302 / #792 — the profile setters must embed values safely.
    // set_platform must not allow a backslash-before-quote to break out of the
    // JS string literal (injection), and set_user_agent must not silently fail
    // on a control character; both must store the value verbatim.
    #[test]
    fn profile_setters_escape_backslash_and_control_characters() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("globalThis.__pwned = 0;").unwrap();

        // SEC-301: `Win\';...` — the trailing backslash used to escape our own
        // closing quote, letting the rest run as JS.
        rt.set_platform("Win\\';globalThis.__pwned=1;//", "px", "pv");
        assert_ne!(
            rt.evaluate("globalThis.__pwned").unwrap().as_f64(),
            Some(1.0),
            "set_platform must not execute JS injected via the platform value"
        );
        assert_eq!(
            rt.evaluate("globalThis.__obscura_platform").unwrap(),
            serde_json::json!("Win\\';globalThis.__pwned=1;//"),
            "the platform value must be stored verbatim"
        );

        // SEC-302: a UA with a literal newline used to SyntaxError into a silent
        // no-op, leaving the wrong UA.
        rt.set_user_agent("Mozilla/5.0 line1\nline2");
        assert_eq!(
            rt.evaluate("globalThis.__obscura_ua").unwrap(),
            serde_json::json!("Mozilla/5.0 line1\nline2"),
            "the UA must be stored verbatim, including control characters"
        );
    }

    #[test]
    fn function_to_string_has_native_function_shape() {
        let mut rt = setup_runtime("<html><body></body></html>");

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const fn = Function.prototype.toString;
                    let constructible = true;
                    try {
                        Reflect.construct(function () {}, [], fn);
                    } catch (error) {
                        constructible = false;
                    }
                    return {
                        source: fn.toString(),
                        name: fn.name,
                        length: fn.length,
                        hasOwnPrototype: Object.prototype.hasOwnProperty.call(fn, "prototype"),
                        constructible,
                    };
                })()"#,
            )
            .unwrap(),
            serde_json::json!({
                "source": "function toString() { [native code] }",
                "name": "toString",
                "length": 0,
                "hasOwnPrototype": false,
                "constructible": false,
            })
        );
    }

    #[test]
    fn initial_blank_iframe_has_no_doctype_and_starts_in_quirks_mode() {
        let mut rt = setup_runtime("<!doctype html><body></body>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const child = iframe.contentWindow;
            const initial = JSON.parse(child.eval(`JSON.stringify([
                document.compatMode, document.doctype,
                Array.from(document.childNodes, node => node.nodeType),
                document.documentElement.nodeName, document.head.nodeName, document.body.nodeName
            ])`));
            return [initial, document.compatMode];
        })()"#).unwrap(), serde_json::json!([
            ["BackCompat", null, [1], "HTML", "HEAD", "BODY"], "CSS1Compat"
        ]));
    }

    #[test]
    fn retained_initial_frame_contexts_survive_runtime_teardown_under_gc_stress() {
        crate::set_v8_flags("--stress-compaction --stress-marking=1");
        for _ in 0..10 {
            let mut rt = setup_runtime("<html><body></body></html>");
            assert_eq!(rt.evaluate(r#"(() => {
                globalThis.retainedFrames = [];
                for (let i = 0; i < 4; i++) {
                    const frame = document.createElement('iframe');
                    document.body.appendChild(frame);
                    const child = frame.contentWindow;
                    child.document.body.textContent = 'retained';
                    retainedFrames.push(child);
                    frame.remove();
                }
                return retainedFrames.map(child => child.document.body.textContent);
            })()"#).unwrap(), serde_json::json!(["retained", "retained", "retained", "retained"]));
            drop(rt);
        }
    }

    #[test]
    fn document_realm_registration_preserves_main_context_rust_slots() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.expose_ops_for_tests();
        {
            let mut entered = rt.runtime();
            let context = entered.main_context();
            v8::scope_with_context!(scope, entered.v8_isolate(), context);
            scope.get_current_context().set_slot(Rc::new(String::from("main context state")));
        }
        rt.evaluate("__obscura_test_ops.op_register_document_realm({}, 123)").unwrap();
        let mut entered = rt.runtime();
        let context = entered.main_context();
        v8::scope_with_context!(scope, entered.v8_isolate(), context);
        assert_eq!(scope.get_current_context().get_slot::<String>().as_deref().map(String::as_str),
            Some("main context state"));
    }

    #[test]
    fn document_realm_registration_with_zero_id_survives_teardown_under_gc_stress() {
        crate::set_v8_flags("--stress-compaction --stress-marking=1");
        for _ in 0..10 {
            let mut rt = setup_runtime("<html><body></body></html>");
            rt.expose_ops_for_tests();
            assert_eq!(rt.evaluate(r#"(() => {
                globalThis.retainedFrames = [];
                for (let i = 0; i < 4; i++) {
                    const frame = document.createElement('iframe');
                    document.body.appendChild(frame);
                    const child = frame.contentWindow;
                    __obscura_test_ops.op_register_document_realm(child.eval('({})'), 0);
                    retainedFrames.push(child);
                    frame.remove();
                }
                return retainedFrames.length;
            })()"#).unwrap(), serde_json::json!(4.0));
            drop(rt);
        }
    }

    #[test]
    fn initial_blank_iframe_eval_uses_the_child_realm() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const iframe = document.createElement('iframe');
                    document.body.appendChild(iframe);
                    const child = iframe.contentWindow;
                    const globalMatches = child.eval('globalThis') === child;
                    const constructorMatches = child.eval('Array') === child.Array;
                    child.eval('globalThis.__initialFrameSentinel = 123');
                    return [globalMatches, constructorMatches,
                        child.__initialFrameSentinel === 123,
                        globalThis.__initialFrameSentinel === undefined];
                })()"#,
            ).unwrap(),
            serde_json::json!([true, true, true, true])
        );
    }

    #[test]
    fn borrowed_input_activation_uses_the_receiver_realm() {
        let mut rt = setup_runtime("<input id='parent' type='checkbox'><iframe></iframe>");
        assert_eq!(rt.evaluate(r#"(() => {
            const child = document.querySelector('iframe').contentDocument;
            child.body.innerHTML = '<input id="control" type="checkbox">';
            const input = child.getElementById('control');
            const events = [];
            input.indeterminate = true;
            input.addEventListener('click', event => {
                events.push(['click', input.checked, input.indeterminate]);
                if (cancel) event.preventDefault();
            });
            for (const type of ['input', 'change']) {
                input.addEventListener(type, () => events.push([type, input.checked, input.indeterminate]));
            }
            let cancel = true;
            HTMLElement.prototype.click.call(input);
            const cancelled = [input.checked, input.indeterminate,
                document.getElementById('parent').checked, events.splice(0)];
            cancel = false;
            HTMLElement.prototype.click.call(input);
            return [cancelled, [input.checked, input.indeterminate,
                document.getElementById('parent').checked, events]];
        })()"#).unwrap(), serde_json::json!([
            [false, true, false, [["click", true, false]]],
            [true, false, false, [["click", true, false], ["input", true, false], ["change", true, false]]]
        ]));
    }

    #[test]
    fn document_open_does_not_use_overridden_head_or_body_getters() {
        let mut rt = setup_runtime(
            "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const childDocument = iframe.contentDocument;
            Object.defineProperties(childDocument, {
                head: { get: () => document.head },
                body: { get: () => document.body },
            });
            Document.prototype.open.call(childDocument);
            return [document.body.textContent, document.baseURI];
        })()"#).unwrap(), serde_json::json!(["parent", "https://parent.example/"]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn synchronous_iframe_geometry_uses_the_owning_document() {
        let mut rt = setup_runtime(
            "<html><head><style>body{margin:4px}#parent{width:45px;height:30px}</style></head><body><div id='parent'></div></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const d = iframe.contentDocument;
            d.body.innerHTML = '<style>body{margin:8px}div{width:100px;height:20px}</style><div id="child"></div>';
            const element = d.getElementById('child');
            const range = d.createRange(); range.selectNode(element);
            return [[...element.getClientRects()].map(r => [r.width, r.height, r.bottom]),
                [...range.getClientRects()].map(r => r.bottom),
                [element.clientWidth, element.clientHeight, element.offsetWidth, element.offsetHeight],
                d.elementFromPoint(10, 10) === element,
                document.getElementById('parent').getBoundingClientRect().width];
        })()"#).unwrap(), serde_json::json!([
            [[100, 20, 28]], [28], [100, 20, 100, 20], true, 45
        ]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn document_carets_use_shaped_text_and_utf16_offsets() {
        let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}span{display:inline-block}</style><span id='text'>A😀BC</span>");
        assert_eq!(rt.evaluate(r#"(() => {
            if (typeof document.caretRangeFromPoint !== 'function' ||
                typeof document.caretPositionFromPoint !== 'function') return 'missing caret API';
            const element = document.getElementById('text'), text = element.firstChild;
            const r = element.getBoundingClientRect();
            const results = [];
            for (const name of ['caretRangeFromPoint', 'caretPositionFromPoint']) {
                for (const x of [r.left + .1, r.right - .1]) {
                    const c = document[name](x, r.top + 12);
                    results.push([(c.startContainer || c.offsetNode) === text,
                        c.startOffset ?? c.offset]);
                }
                results.push(document[name](-1, 12) === null);
            }
            return results;
        })()"#).unwrap(), serde_json::json!([
            [true, 0], [true, 5], true, [true, 0], [true, 5], true
        ]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn document_carets_find_flattened_mixed_content_runs() {
        let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}</style><div>AAAA<div style='height:30px'></div><span id='text'>ABCD</span></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const text = document.getElementById('text').firstChild;
            const caret = document.caretPositionFromPoint(1, 66);
            return [caret.offsetNode === text, caret.offset];
        })()"#).unwrap(), serde_json::json!([true, 0]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn document_carets_legacy_ranges_exclude_widget_internal_text() {
        let mut rt = setup_runtime("<style>body{margin:0}input,textarea{display:block;border:0;padding:0;font:20px/24px monospace;width:200px;height:24px}</style><div></div><input id='input'><textarea id='textarea'>ABCD</textarea>");
        assert_eq!(rt.evaluate(r#"(() => {
            const result = [];
            for (const id of ['input', 'textarea']) {
                const widget = document.getElementById(id);
                widget.value = 'A😀BC';
                const rect = widget.getBoundingClientRect();
                for (const x of [rect.left + .1, rect.right - .1]) {
                    const range = document.caretRangeFromPoint(x, rect.top + 12);
                    result.push([range.startContainer === document.body,
                        range.startOffset, range.collapsed]);
                }
            }
            return result;
        })()"#).unwrap(), serde_json::json!([
            [true, 1, true], [true, 1, true], [true, 2, true], [true, 2, true]
        ]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn document_carets_keep_receiver_realm_and_current_geometry() {
        let mut rt = setup_runtime("<style>body{margin:0;font:20px/24px monospace}#parent{display:inline-block}</style><span id='parent'>ABCD</span>");
        assert_eq!(rt.evaluate(r#"(() => {
            if (typeof document.caretPositionFromPoint !== 'function') return 'missing caret API';
            const iframe = document.createElement('iframe'); iframe.style.display = 'block'; document.body.appendChild(iframe);
            const d = iframe.contentDocument;
            d.body.innerHTML = '<style>body{margin:0;font:20px/24px monospace}#child{display:inline-block}</style><span id="child">WXYZ</span>';
            const child = d.getElementById('child'), parent = document.getElementById('parent');
            const foreign = iframe.contentWindow.Document.prototype;
            const borrowed = Document.prototype.caretPositionFromPoint.call(d, .1, 12);
            const reverse = foreign.caretPositionFromPoint.call(document, .1, 12);
            const position = document.caretPositionFromPoint(.1, 12);
            const before = position.getClientRect();
            parent.style.transform = 'translate(40px,50px)';
            const after = position.getClientRect();
            let invalid = false;
            try { document.caretPositionFromPoint(Infinity, 0); } catch (e) { invalid = e instanceof TypeError; }
            return [borrowed.offsetNode === child.firstChild, reverse.offsetNode === parent.firstChild,
                position.offset === 0, before.width === 0 && before.height > 0,
                Math.abs(after.x - before.x - 40) < .01, Math.abs(after.y - before.y - 50) < .01,
                new Document().caretPositionFromPoint(1, 12) === null, invalid];
        })()"#).unwrap(), serde_json::json!([true, true, true, true, true, true, true, true]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn borrowed_document_hit_testing_uses_the_receiver_realm() {
        let mut rt = setup_runtime(
            "<style>body{margin:4px}#parent{width:45px;height:30px}</style><div id='parent'></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const d = iframe.contentDocument;
            d.body.innerHTML = '<style>body{margin:8px}div{width:100px;height:20px}</style><div id="child"></div>';
            const child = d.getElementById('child'), parent = document.getElementById('parent');
            const foreign = iframe.contentWindow.Document.prototype;
            return [document.elementFromPoint(10, 10) === parent,
                d.elementFromPoint(10, 10) === child,
                Document.prototype.elementFromPoint.call(d, 10, 10) === child,
                foreign.elementFromPoint.call(document, 10, 10) === parent,
                Document.prototype.elementFromPoint.call(d, 400, 10) === null,
                foreign.elementFromPoint.call(document, 400, 10) === document.body,
                Document.prototype.elementsFromPoint.call(d, 10, 10)[0] === child,
                foreign.elementsFromPoint.call(document, 10, 10)[0] === parent];
        })()"#).unwrap(), serde_json::json!([true, true, true, true, true, true, true, true]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn computed_style_on_a_foreign_frame_element_tracks_its_document() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const d = iframe.contentDocument;
            d.body.innerHTML = '<style>#child{width:100px;height:20px;color:rgb(12,34,56)}</style><div id="child"></div>';
            const element = d.getElementById('child');
            const style = getComputedStyle(element);
            const before = [style.width, style.color];
            element.style.width = '120px';
            element.style.color = 'rgb(78,90,12)';
            return [before, [style.width, style.color], getComputedStyle(element).color];
        })()"#).unwrap(), serde_json::json!([
            ["100px", "rgb(12, 34, 56)"], ["120px", "rgb(78, 90, 12)"], "rgb(78, 90, 12)"
        ]));
    }

    #[test]
    fn borrowed_document_methods_keep_the_receiver_realm_after_prototype_remap() {
        let mut rt = setup_runtime(
            "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const child = iframe.contentWindow;
            const childDocument = child.document;
            Object.setPrototypeOf(childDocument, Document.prototype);
            const initialUrl = childDocument.URL;
            const separateBody = childDocument.querySelector('body') !== document.body;
            Document.prototype.open.call(childDocument);
            return [document.body.textContent, document.baseURI, document.readyState,
                separateBody, initialUrl];
        })()"#).unwrap(), serde_json::json!([
            "parent", "https://parent.example/", "complete", true, "about:blank"
        ]));
    }

    #[test]
    fn iframe_content_window_exposes_realm_globals() {
        let mut rt = setup_runtime("<html><body></body></html>");

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const iframe = document.createElement("iframe");
                    document.body.appendChild(iframe);
                    const child = iframe.contentWindow;
                    const names = [
                        "Object", "Function", "Error", "Promise", "Proxy",
                        "XMLHttpRequest", "Worker", "Blob", "FormData",
                        "WebSocket", "MutationObserver",
                    ];
                    return {
                        types: names.map(name => typeof child[name]),
                        separate: [
                            child.Object !== Object,
                            child.Promise !== Promise,
                            child.XMLHttpRequest !== XMLHttpRequest,
                            child.Math !== Math,
                        ],
                        constructible: [
                            new child.Object() instanceof child.Object,
                            new child.Promise(resolve => resolve()) instanceof child.Promise,
                            new child.XMLHttpRequest() instanceof child.XMLHttpRequest,
                            new child.Blob([]) instanceof child.Blob,
                            new child.FormData() instanceof child.FormData,
                            new child.MutationObserver(() => {}) instanceof child.MutationObserver,
                        ],
                        utilities: [
                            child.Object.keys({ first: 1 })[0] === "first",
                            child.Array.isArray([]),
                            child.Promise.resolve(1) instanceof child.Promise,
                            child.Function("return 7")() === 7,
                            Object.getOwnPropertyNames(child).includes("XMLHttpRequest"),
                            child.globalThis === child,
                        ],
                    };
                })()"#,
            )
            .unwrap(),
            serde_json::json!({
                "types": vec!["function"; 11],
                "separate": vec![true; 4],
                "constructible": vec![true; 6],
                "utilities": vec![true; 6],
            })
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_domain_getter_and_valid_relaxation_match_effective_host() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("https://deep.assets.example.co.uk:8443/page");
        rt.run_page_init();

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const initial = document.domain;
                    document.domain = "ASSETS.EXAMPLE.CO.UK";
                    const first = document.domain;
                    document.domain = "example.co.uk";
                    return [initial, first, document.domain, location.hostname,
                            (new Document()).domain,
                            new DOMParser().parseFromString("", "text/html").domain];
                })()"#,
            )
            .unwrap(),
            serde_json::json!([
                "deep.assets.example.co.uk",
                "assets.example.co.uk",
                "example.co.uk",
                "deep.assets.example.co.uk",
                "example.co.uk",
                "example.co.uk"
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_domain_rejects_unrelated_child_and_public_suffix_hosts() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("https://app.user.github.io/page");
        rt.run_page_init();

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const attempts = ["", ".github.io", "github.io", "evilgithub.io",
                                      "other.github.io", "child.app.user.github.io"];
                    const rejected = attempts.map(value => {
                        try { document.domain = value; return "accepted"; }
                        catch (error) { return error.name; }
                    });
                    document.domain = "user.github.io";
                    return rejected.concat(document.domain);
                })()"#,
            )
            .unwrap(),
            serde_json::json!([
                "SecurityError",
                "SecurityError",
                "SecurityError",
                "SecurityError",
                "SecurityError",
                "SecurityError",
                "user.github.io"
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_domain_detached_and_hostless_setters_throw_security_error() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const detached = [new Document(),
                        document.implementation.createHTMLDocument("x"),
                        document.implementation.createDocument(null, "root")];
                    const errors = detached.map(doc => {
                        try { doc.domain = "example.com"; return "accepted"; }
                        catch (error) { return error.name; }
                    });
                    return [typeof document.domain, document.domain].concat(errors);
                })()"#,
            )
            .unwrap(),
            serde_json::json!([
                "string",
                "example.com",
                "SecurityError",
                "SecurityError",
                "SecurityError"
            ])
        );

        let dom = parse_html("<html><body></body></html>");
        let mut hostless = ObscuraJsRuntime::new();
        hostless.set_dom(dom);
        hostless.set_url("about:blank");
        hostless.run_page_init();
        assert_eq!(
            hostless
                .evaluate(
                    r#"(() => {
                        let error = "";
                        try { document.domain = "example.com"; }
                        catch (caught) { error = caught.name; }
                        return [document.domain, error];
                    })()"#,
                )
                .unwrap(),
            serde_json::json!(["", "SecurityError"])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn string_timeout_handler_executes_in_global_scope() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("var __timerValue='pending'; setTimeout('__timerValue=\"done\"', 0)")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("globalThis.__timerValue").unwrap(),
            serde_json::json!("done")
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn string_timeout_declarations_reach_global_scope() {
        // A string timer handler runs as a classic script in global scope, so a
        // top-level var/function declaration in it becomes a global. new Function()
        // kept those declarations local to the compiled function, so they never
        // reached globalThis.
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("setTimeout('var __leaked = 42; function __leakedFn(){ return 7; }', 0)")
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        let v = rt
            .evaluate(
                "String(globalThis.__leaked) + '|' + (typeof globalThis.__leakedFn === 'function' ? globalThis.__leakedFn() : 'missing')",
            )
            .unwrap();
        assert_eq!(v, serde_json::json!("42|7"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn string_interval_handler_repeats_and_can_clear_itself() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("globalThis.__ticks=0").unwrap();
        rt.evaluate(
            "globalThis.__timerId=setInterval('__ticks++;if(__ticks===2)clearInterval(__timerId)',1)",
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("globalThis.__ticks").unwrap(),
            serde_json::json!(2.0)
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn zero_delay_timer_runs_as_a_task_after_microtasks() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "zero-delay-task-order",
            r#"
                globalThis.__taskOrder = ["sync"];
                setTimeout(() => __taskOrder.push("timer"), 0);
                Promise.resolve().then(() => __taskOrder.push("microtask"));
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__taskOrder").unwrap(),
            serde_json::json!(["sync", "microtask", "timer"])
        );
    }

    #[tokio::test]
    async fn microtask_exception_reports_error_without_discarding_queued_work() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate(r#"(() => {
            globalThis.microtaskOrder = [];
            const failure = new Error('fixture microtask failure');
            addEventListener('error', event => {
                microtaskOrder.push(event.error === failure ? 'error' : 'wrong-error');
                event.preventDefault();
            });
            queueMicrotask(() => microtaskOrder.push('before'));
            queueMicrotask(() => { throw failure; });
            queueMicrotask(() => microtaskOrder.push('after'));
            Promise.resolve().then(() => microtaskOrder.push('promise'));
            return true;
        })()"#).unwrap();
        rt.run_event_loop().await.unwrap();
        assert_eq!(rt.evaluate("microtaskOrder").unwrap(),
            serde_json::json!(["before", "error", "after", "promise"]));
    }

    #[tokio::test]
    async fn microtask_exception_reports_only_uncanceled_runtime_errors() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_runtime_events_enabled(true);
        rt.evaluate(r#"(() => {
            globalThis.reportedMicrotaskErrors = [];
            addEventListener('error', event => {
                reportedMicrotaskErrors.push(event.message);
                if (event.message === 'canceled failure') event.preventDefault();
            });
            queueMicrotask(() => { throw new TypeError('uncanceled failure'); });
            queueMicrotask(() => { throw new Error('canceled failure'); });
            queueMicrotask(() => reportedMicrotaskErrors.push('after'));
            return true;
        })()"#).unwrap();
        rt.run_event_loop().await.unwrap();
        assert_eq!(rt.evaluate("reportedMicrotaskErrors").unwrap(),
            serde_json::json!(["uncanceled failure", "canceled failure", "after"]));
        let exceptions: Vec<_> = rt.take_pending_runtime_events().into_iter()
            .filter_map(|event| match event {
                RuntimeEvent::Exception(error) => Some(error),
                _ => None,
            }).collect();
        assert_eq!(exceptions.len(), 1);
        assert_eq!(exceptions[0].name, "TypeError");
        assert!(exceptions[0].description.contains("uncanceled failure"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn scheduler_post_task_observes_priority_fifo_and_task_boundaries() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "scheduler-priority-order",
            r#"
                globalThis.__schedulerOrder = ["sync"];
                const schedule = (name, priority) => scheduler.postTask(() => {
                    __schedulerOrder.push(name);
                    Promise.resolve().then(() => __schedulerOrder.push(name + "-microtask"));
                    return name + "-result";
                }, { priority });
                globalThis.__schedulerResults = Promise.all([
                    schedule("background-1", "background"),
                    schedule("background-2", "background"),
                    schedule("visible", "user-visible"),
                    schedule("blocking-1", "user-blocking"),
                    schedule("blocking-2", "user-blocking"),
                ]).then(values => { globalThis.__schedulerValues = values; });
                Promise.resolve().then(() => __schedulerOrder.push("initial-microtask"));
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__schedulerOrder").unwrap(),
            serde_json::json!([
                "sync",
                "initial-microtask",
                "blocking-1",
                "blocking-1-microtask",
                "blocking-2",
                "blocking-2-microtask",
                "visible",
                "visible-microtask",
                "background-1",
                "background-1-microtask",
                "background-2",
                "background-2-microtask",
            ])
        );
        assert_eq!(
            rt.evaluate("__schedulerValues").unwrap(),
            serde_json::json!([
                "background-1-result",
                "background-2-result",
                "visible-result",
                "blocking-1-result",
                "blocking-2-result",
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn scheduler_abort_delay_and_yield_follow_task_state() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "scheduler-abort-delay-yield",
            r#"
                globalThis.__schedulerState = {
                    order: [],
                    canceledCallbackRan: false,
                    exactAbortReason: false,
                    selfAbortCallbackRan: false,
                    exactSelfAbortReason: false,
                };
                const abortReason = { reason: "stop" };
                const canceled = new AbortController();
                scheduler.postTask(() => {
                    __schedulerState.canceledCallbackRan = true;
                }, { signal: canceled.signal, delay: 20 }).catch(error => {
                    __schedulerState.exactAbortReason = error === abortReason;
                });
                canceled.abort(abortReason);

                const selfAbortReason = { reason: "inside callback" };
                const selfCanceled = new AbortController();
                scheduler.postTask(() => {
                    __schedulerState.selfAbortCallbackRan = true;
                    selfCanceled.abort(selfAbortReason);
                    return "ignored result";
                }, { signal: selfCanceled.signal }).catch(error => {
                    __schedulerState.exactSelfAbortReason = error === selfAbortReason;
                });

                scheduler.postTask(async () => {
                    __schedulerState.order.push("blocking-start");
                    await scheduler.yield();
                    __schedulerState.order.push("blocking-continuation");
                }, { priority: "user-blocking" });
                scheduler.postTask(() => {
                    __schedulerState.order.push("background");
                }, { priority: "background" });
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                r#"[
                    __schedulerState.order,
                    __schedulerState.canceledCallbackRan,
                    __schedulerState.exactAbortReason,
                    __schedulerState.selfAbortCallbackRan,
                    __schedulerState.exactSelfAbortReason,
                    scheduler instanceof Scheduler,
                    Object.prototype.toString.call(scheduler),
                    Scheduler.prototype.postTask.length,
                    Scheduler.prototype.yield.length,
                ]"#,
            )
            .unwrap(),
            serde_json::json!([
                ["blocking-start", "blocking-continuation", "background"],
                false,
                true,
                true,
                true,
                true,
                "[object Scheduler]",
                1,
                0,
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_onmessage_bindings_do_not_mutate_window() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("worker-onmessage-bindings", r#"
            globalThis.__workerReplies = {};
            const originalHandler = window.onmessage;
            const sources = {
                bare: 'onmessage = function(event) { postMessage([event.data, this === self]); };',
                declared: 'var onmessage = function(event) { postMessage([event.data, this === self]); };',
                strict: '"use strict"; onmessage = function(event) { postMessage([event.data, this === self]); };',
            };
            for (const [name, source] of Object.entries(sources)) {
                const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
                const worker = new Worker(url);
                worker.onmessage = event => {
                    __workerReplies[name] = event.data;
                    worker.terminate();
                    URL.revokeObjectURL(url);
                };
                worker.postMessage(name);
            }
            globalThis.__workerWindowUnchanged = () => window.onmessage === originalHandler;
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!({
                "bare": ["bare", true], "declared": ["declared", true], "strict": ["strict", true],
            })
        );
        assert_eq!(
            rt.evaluate("__workerWindowUnchanged()").unwrap(),
            serde_json::json!(true)
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_initializes_once_and_retains_message_state() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("worker-persistent-state", r#"
            globalThis.__workerReplies = [];
            const source = 'let count = 0; postMessage("ready"); self.onmessage = () => postMessage(++count);';
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => {
                __workerReplies.push(event.data);
                if (event.data === 2) {
                    worker.terminate();
                    URL.revokeObjectURL(url);
                }
            };
            worker.postMessage(null);
            worker.postMessage(null);
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!(["ready", 1, 2])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_scopes_keep_counters_and_handlers_independent() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-independent-scopes",
            r#"
            globalThis.__workerReplies = [[], []];
            const source = 'let count = 0; onmessage = () => postMessage(++count);';
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const workers = [new Worker(url), new Worker(url)];
            workers.forEach((worker, index) => {
                worker.onmessage = event => __workerReplies[index].push(event.data);
            });
            workers[0].postMessage(null);
            workers[1].postMessage(null);
            workers[0].postMessage(null);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!([[1, 2], [1]])
        );
        rt.execute_script(
            "worker-cleanup",
            "workers.forEach(worker => worker.terminate()); URL.revokeObjectURL(url);",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_delivers_to_handler_and_listener_without_reinitializing() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-handler-and-listener",
            r#"
            globalThis.__workerReplies = [];
            const source = `
                let count = 0;
                self.onmessage = event => postMessage(['handler', ++count]);
                addEventListener('message', function(event) {
                    postMessage(['listener', count, this === self]);
                });
            `;
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => __workerReplies.push(event.data);
            worker.postMessage(null);
            worker.postMessage(null);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!([
                ["handler", 1],
                ["listener", 1, true],
                ["handler", 2],
                ["listener", 2, true],
            ])
        );
        rt.execute_script(
            "worker-cleanup",
            "worker.terminate(); URL.revokeObjectURL(url);",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_queues_messages_while_source_is_loading() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("worker-queued-messages", r#"
            globalThis.__workerReplies = [];
            const originalFetch = globalThis.fetch;
            let finishSource;
            globalThis.fetch = async () => ({ text: () => new Promise(resolve => { finishSource = resolve; }) });
            const worker = new Worker('https://example.com/worker.js');
            worker.onmessage = event => __workerReplies.push(event.data);
            worker.postMessage('first');
            worker.postMessage('second');
            setTimeout(() => {
                globalThis.fetch = originalFetch;
                finishSource('let count = 0; onmessage = event => postMessage([++count, event.data]);');
            }, 0);
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!([[1, "first"], [2, "second"]])
        );
        rt.execute_script("worker-cleanup", "worker.terminate();")
            .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_termination_discards_queued_messages() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-terminated-messages",
            r#"
            globalThis.__workerReplies = [];
            const source = 'postMessage("started"); onmessage = () => postMessage("reply");';
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => __workerReplies.push(event.data);
            worker.postMessage('queued');
            worker.terminate();
            worker.postMessage('after termination');
            URL.revokeObjectURL(url);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!([])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_source_preserves_strict_mode_in_message_closures() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-strict-closure",
            r#"
            globalThis.__workerReplies = [];
            const source = `
                'use strict';
                onmessage = () => {
                    try { workerUndeclaredVariable = 1; postMessage('unexpected assignment'); }
                    catch (error) { postMessage(error.name); }
                };
            `;
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => __workerReplies.push(event.data);
            worker.postMessage(null);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!(["ReferenceError"])
        );
        assert_eq!(
            rt.evaluate("typeof workerUndeclaredVariable").unwrap(),
            serde_json::json!("undefined")
        );
        rt.execute_script(
            "worker-cleanup",
            "worker.terminate(); URL.revokeObjectURL(url);",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_scope_exposes_builtins_as_properties() {
        // Go's wasm_exec uses `self` as its global object and reads
        // self.Object / self.Promise / self.JSON; an undefined one makes the
        // wasm panic with "call of Value.Invoke on undefined".
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-scope-builtins",
            r#"
            globalThis.__workerReplies = [];
            const source = `
                const names = ['Object', 'Array', 'Promise', 'JSON', 'Uint8Array', 'Date', 'Reflect', 'WebAssembly', 'Headers', 'AbortController'];
                postMessage({
                    missing: names.filter(n => typeof self[n] === 'undefined'),
                    viaGlobalThis: names.filter(n => typeof globalThis[n] === 'undefined'),
                    sameObject: self.Object === Object && self.Promise === Promise,
                    globalThisIsSelf: globalThis === self,
                    noDocument: typeof self.document === 'undefined' && typeof self.window === 'undefined',
                    callable: self.JSON.stringify(new self.Promise(() => {}) instanceof self.Promise),
                });
            `;
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => {
                __workerReplies.push(event.data);
                worker.terminate();
                URL.revokeObjectURL(url);
            };
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!([{
                "missing": [], "viaGlobalThis": [], "sameObject": true,
                "globalThisIsSelf": true, "noDocument": true, "callable": "true",
            }])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_initialization_error_does_not_rerun_source() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-initialization-error",
            r#"
            globalThis.__workerReplies = [];
            globalThis.__workerErrors = [];
            const source = 'postMessage("started"); throw new Error("initialization failed");';
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            worker.onmessage = event => __workerReplies.push(event.data);
            worker.onerror = error => __workerErrors.push(error.message);
            worker.postMessage(null);
            worker.postMessage(null);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!(["started"])
        );
        assert_eq!(
            rt.evaluate("__workerErrors").unwrap(),
            serde_json::json!(["initialization failed"])
        );
        rt.execute_script(
            "worker-cleanup",
            "worker.terminate(); URL.revokeObjectURL(url);",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn worker_startup_reply_does_not_overtake_queued_messages() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "worker-startup-order",
            r#"
            globalThis.__workerReplies = [];
            const source = 'postMessage("ready"); onmessage = event => postMessage(event.data);';
            const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));
            const worker = new Worker(url);
            let replied = false;
            worker.onmessage = event => {
                __workerReplies.push(event.data);
                if (event.data === 'ready' && !replied) {
                    replied = true;
                    worker.postMessage(3);
                }
            };
            worker.postMessage(1);
            worker.postMessage(2);
        "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__workerReplies").unwrap(),
            serde_json::json!(["ready", 1, 2, 3])
        );
        rt.execute_script(
            "worker-cleanup",
            "worker.terminate(); URL.revokeObjectURL(url);",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn self_requeueing_message_channel_yields_to_timers() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-channel-task-yield",
            r#"
                globalThis.__messageCount = 0;
                globalThis.__timerObserved = false;
                const channel = new MessageChannel();
                channel.port2.onmessage = () => {
                    __messageCount++;
                    if (!__timerObserved) channel.port1.postMessage(null);
                };
                channel.port1.postMessage(null);
                setTimeout(() => { __timerObserved = true; }, 1);
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        let result = rt.evaluate("[__messageCount, __timerObserved]").unwrap();
        let values = result.as_array().unwrap();
        assert!(
            values[0]
                .as_u64()
                .is_some_and(|count| count > 0 && count < 10_000),
            "message task did not yield: {result}"
        );
        assert_eq!(values[1], serde_json::json!(true));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_queues_until_start_and_clones_at_post_time() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-port-start-and-clone",
            r#"
                const channel = new MessageChannel();
                const payload = { nested: { value: 7 } };
                globalThis.__messagePortResult = {
                    portInstance: channel.port1 instanceof MessagePort,
                    channelInstance: channel instanceof MessageChannel,
                    deliveredBeforeStart: false,
                    delivered: false,
                };
                channel.port2.addEventListener("message", function(event) {
                    __messagePortResult.delivered = true;
                    __messagePortResult.value = event.data.nested.value;
                    __messagePortResult.targetIsPort = event.target === channel.port2;
                    __messagePortResult.thisIsPort = this === channel.port2;
                    __messagePortResult.origin = event.origin;
                    __messagePortResult.portCount = event.ports.length;
                });
                channel.port1.postMessage(payload);
                payload.nested.value = 99;
                setTimeout(() => {
                    __messagePortResult.deliveredBeforeStart = __messagePortResult.delivered;
                    channel.port2.start();
                }, 0);
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__messagePortResult").unwrap(),
            serde_json::json!({
                "portInstance": true,
                "channelInstance": true,
                "deliveredBeforeStart": false,
                "delivered": true,
                "value": 7,
                "targetIsPort": true,
                "thisIsPort": true,
                "origin": "",
                "portCount": 0,
            })
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_onmessage_starts_and_yields_between_messages() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-port-task-boundaries",
            r#"
                globalThis.__messagePortOrder = [];
                const channel = new MessageChannel();
                channel.port1.postMessage(1);
                channel.port1.postMessage(2);
                channel.port2.onmessage = (event) => {
                    __messagePortOrder.push("message-" + event.data);
                    if (event.currentTarget !== channel.port2) __messagePortOrder.push("bad-current-target");
                    Promise.resolve().then(() => __messagePortOrder.push("microtask-" + event.data));
                };
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__messagePortOrder").unwrap(),
            serde_json::json!(["message-1", "microtask-1", "message-2", "microtask-2",])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_drops_old_document_payloads_before_fresh_delivery() {
        let mut rt = setup_runtime("<html><body data-document='old'></body></html>");
        rt.execute_script(
            "message-port-old-document",
            r#"
                globalThis.__replacementPortOrder = [];
                globalThis.__replacementChannel = new MessageChannel();
                __replacementChannel.port2.onmessage = event => {
                    __replacementPortOrder.push(event.data);
                };
                __replacementChannel.port1.postMessage("old");
            "#,
        )
        .unwrap();

        rt.set_dom(parse_html("<html><body data-document='new'></body></html>"));
        rt.execute_script(
            "message-port-new-document",
            r#"__replacementChannel.port1.postMessage("fresh");"#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();

        assert_eq!(
            rt.evaluate("__replacementPortOrder").unwrap(),
            serde_json::json!(["fresh"]),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_close_discards_delivery_already_queued_for_a_task() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-port-close-cancels-queued-delivery",
            r#"
                globalThis.__closedPortDeliveries = 0;
                const channel = new MessageChannel();
                channel.port2.onmessage = () => { __closedPortDeliveries++; };
                channel.port1.postMessage("queued");
                channel.port2.close();
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__closedPortDeliveries").unwrap(),
            serde_json::json!(0.0)
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_handler_and_listener_follow_registration_order() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-port-mixed-registration-order",
            r#"
                globalThis.__messagePortRegistrationOrder = [];

                const handlerFirst = new MessageChannel();
                handlerFirst.port2.onmessage = () => __messagePortRegistrationOrder.push("handler-first:handler");
                handlerFirst.port2.addEventListener("message", () => __messagePortRegistrationOrder.push("handler-first:listener"));
                handlerFirst.port1.postMessage(null);

                const listenerFirst = new MessageChannel();
                listenerFirst.port2.addEventListener("message", () => __messagePortRegistrationOrder.push("listener-first:listener"));
                listenerFirst.port2.onmessage = () => __messagePortRegistrationOrder.push("listener-first:handler");
                listenerFirst.port1.postMessage(null);
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__messagePortRegistrationOrder").unwrap(),
            serde_json::json!([
                "handler-first:handler",
                "handler-first:listener",
                "listener-first:listener",
                "listener-first:handler",
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn message_port_internal_state_is_hidden_and_ignores_own_property_tampering() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "message-port-hidden-state",
            r#"
                const channel = new MessageChannel();
                globalThis.__messagePortOwnKeys = Object.keys(channel.port2);
                globalThis.__messagePortOwnNames = Object.getOwnPropertyNames(channel.port2);
                globalThis.__messagePortTamperResult = [];
                channel.port2.onmessage = (event) => __messagePortTamperResult.push(event.data);

                // These names used to be the actual implementation state. An
                // expando with any of them must not alter delivery now.
                channel.port1._closed = true;
                channel.port1._entangled = null;
                channel.port2._closed = true;
                channel.port2._messageQueue = [];
                channel.port2._messageQueueEnabled = false;
                channel.port2._messageDeliveryPending = true;
                channel.port2._onmessage = null;
                channel.port2._scheduleMessageDelivery = () => {};
                channel.port2.dispatchEvent = () => { throw new Error("tampered dispatchEvent called"); };
                channel.port1.postMessage("delivered");
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[__messagePortOwnKeys, __messagePortOwnNames, __messagePortTamperResult]")
                .unwrap(),
            serde_json::json!([[], [], ["delivered"]])
        );
    }

    #[test]
    fn message_port_has_browser_shaped_construction_and_clone_errors() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    let constructorError = "";
                    let cloneError = "";
                    try { new MessagePort(); } catch (error) { constructorError = error.name; }
                    try { new MessageChannel().port1.postMessage(() => {}); }
                    catch (error) { cloneError = error.name; }
                    return [constructorError, cloneError, Object.prototype.toString.call(new MessageChannel().port1)];
                })()"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["TypeError", "DataCloneError", "[object MessagePort]"])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_channel_delivers_independent_post_time_clones_to_matching_peers() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "broadcast-channel-clone-delivery",
            r#"
                globalThis.__broadcastResults = { sender: 0, otherName: 0, peers: [] };
                const sender = new BroadcastChannel("session-sync");
                const first = new BroadcastChannel("session-sync");
                const second = new BroadcastChannel("session-sync");
                const other = new BroadcastChannel("other-name");
                sender.onmessage = () => { __broadcastResults.sender++; };
                other.onmessage = () => { __broadcastResults.otherName++; };
                first.onmessage = (event) => {
                    __broadcastResults.peers.push({
                        peer: "first",
                        value: event.data.nested.value,
                        bytes: Array.from(event.data.bytes),
                        source: event.source,
                        ports: event.ports.length,
                    });
                    event.data.nested.value = 500;
                    event.data.bytes[0] = 99;
                };
                second.onmessage = (event) => {
                    __broadcastResults.peers.push({
                        peer: "second",
                        value: event.data.nested.value,
                        bytes: Array.from(event.data.bytes),
                        source: event.source,
                        ports: event.ports.length,
                    });
                };
                const payload = { nested: { value: 7 }, bytes: new Uint8Array([1, 2, 3]) };
                sender.postMessage(payload);
                payload.nested.value = 42;
                payload.bytes[0] = 88;
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__broadcastResults").unwrap(),
            serde_json::json!({
                "sender": 0,
                "otherName": 0,
                "peers": [
                    { "peer": "first", "value": 7, "bytes": [1, 2, 3], "source": null, "ports": 0 },
                    { "peer": "second", "value": 7, "bytes": [1, 2, 3], "source": null, "ports": 0 },
                ],
            })
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_channel_handlers_follow_registration_order_and_task_timing() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "broadcast-channel-registration-order",
            r#"
                globalThis.__broadcastOrder = ["sync"];
                const sender = new BroadcastChannel("ordering");
                const handlerFirst = new BroadcastChannel("ordering");
                const listenerFirst = new BroadcastChannel("ordering");
                handlerFirst.onmessage = () => __broadcastOrder.push("handler-first:handler");
                handlerFirst.addEventListener("message", () => __broadcastOrder.push("handler-first:listener"));
                listenerFirst.addEventListener("message", () => __broadcastOrder.push("listener-first:listener"));
                listenerFirst.onmessage = () => __broadcastOrder.push("listener-first:handler");
                sender.postMessage(null);
                Promise.resolve().then(() => __broadcastOrder.push("microtask"));
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__broadcastOrder").unwrap(),
            serde_json::json!([
                "sync",
                "microtask",
                "handler-first:handler",
                "handler-first:listener",
                "listener-first:listener",
                "listener-first:handler",
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn broadcast_channel_close_cancels_delivery_and_closed_post_throws() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "broadcast-channel-close",
            r#"
                globalThis.__broadcastCloseResult = { deliveries: 0 };
                const sender = new BroadcastChannel("close-test");
                const recipient = new BroadcastChannel("close-test");
                recipient.onmessage = () => { __broadcastCloseResult.deliveries++; };
                sender.postMessage("queued");
                recipient.close();
                sender.close();
                try { sender.postMessage("closed"); }
                catch (error) { __broadcastCloseResult.closedError = error.name; }
                try { new BroadcastChannel(); }
                catch (error) { __broadcastCloseResult.constructorError = error.name; }
                try { new BroadcastChannel("no-peers").postMessage(() => {}); }
                catch (error) { __broadcastCloseResult.cloneError = error.name; }
                __broadcastCloseResult.ownKeys = Object.keys(new BroadcastChannel("shape"));
                __broadcastCloseResult.tag = Object.prototype.toString.call(new BroadcastChannel("shape"));
                __broadcastCloseResult.eventTarget = new BroadcastChannel("shape") instanceof EventTarget;
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__broadcastCloseResult").unwrap(),
            serde_json::json!({
                "deliveries": 0,
                "closedError": "InvalidStateError",
                "constructorError": "TypeError",
                "cloneError": "DataCloneError",
                "ownKeys": [],
                "tag": "[object BroadcastChannel]",
                "eventTarget": true,
            })
        );
    }

    #[test]
    fn user_timing_named_measures_resolve_recorded_timestamps() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            performance.mark('start', {startTime: 20});
            performance.mark('start', {startTime: 5});
            performance.mark('end', {startTime: 12});
            const measure = performance.measure('work', 'start', 'end');
            return [measure.startTime, measure.duration, measure.entryType,
                performance.getEntriesByType('mark').map(e => e.startTime),
                performance.getEntriesByName('work', 'measure').length];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([20, -8, "measure", [5, 12, 20], 1]));
    }

    #[test]
    fn user_timing_options_clone_details_without_registering_constructors() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            const detail = {values: new Map([['count', 7]])}; detail.self = detail;
            const entry = performance.measure('work', {start: 3, duration: 4, detail});
            detail.values.set('count', 9);
            const standalone = new PerformanceMark('standalone', {startTime: 2});
            return [entry.startTime, entry.duration, entry.detail.values.get('count'),
                entry.detail.self === entry.detail, entry instanceof PerformanceMeasure,
                entry instanceof PerformanceEntry, Object.keys(entry),
                Object.prototype.toString.call(entry), standalone.duration,
                performance.getEntriesByName('standalone').length,
                performance.measure('backward', {start: 8, end: 2}).duration,
                performance.measure('derived', {end: 3, duration: 4}).startTime];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([3, 4, 7, true, true, true, [],
            "[object PerformanceMeasure]", 0, 0, -6, -1]));
    }

    #[test]
    fn user_timing_clear_methods_preserve_other_entry_types() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            performance.mark('same', {startTime: 1});
            performance.mark('other', {startTime: 2});
            performance.measure('same', {start: 1, end: 3});
            performance.clearMarks('same');
            const before = performance.getEntries().map(e => e.entryType + ':' + e.name);
            performance.clearMeasures();
            return [before, performance.getEntries().map(e => e.name)];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([["measure:same", "mark:other"], ["other"]]));
    }

    #[test]
    fn user_timing_rejects_invalid_measurements_without_recording_them() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            const errors = [
                () => performance.mark(), () => performance.measure(),
                () => performance.mark('navigationStart'),
                () => performance.mark('x', {startTime: -1}),
                () => performance.mark('x', {startTime: Infinity}),
                () => performance.mark('x', {detail: () => {}}),
                () => performance.measure('x', 'missing'),
                () => performance.measure('x', {duration: 2}),
                () => performance.measure('x', {detail: 2}),
                () => performance.measure('x', {start: 1, end: 2, duration: 1}),
                () => performance.measure('x', {start: 1}, 'missing'),
                () => performance.measure('x', {start: -1}),
                () => performance.measure('x', {start: NaN}),
                () => performance.getEntriesByName(),
                () => new PerformanceEntry(), () => new PerformanceMeasure(),
            ].map(fn => { try { fn(); return 'none'; } catch (error) { return error.name; } });
            return [errors, performance.getEntries().length];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([[
            "TypeError", "TypeError", "SyntaxError", "TypeError", "TypeError", "DataCloneError",
            "SyntaxError", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError",
            "TypeError", "TypeError", "TypeError", "TypeError"], 0]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn user_timing_observer_delivers_buffered_entries_after_the_current_task() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("user-timing-observer", r#"
            globalThis.__timingDelivery = [];
            let synchronous = true;
            performance.mark('old', {startTime: 9});
            const observer = new PerformanceObserver(function(list, owner) {
                __timingDelivery.push([!synchronous, this === owner && owner === observer,
                    list.getEntries().map(e => e.name), list.getEntriesByName('new', 'mark').length,
                    Object.prototype.toString.call(list)]);
                observer.disconnect();
            });
            observer.observe({type: 'mark', buffered: true});
            performance.mark('new', {startTime: 2});
            performance.clearMarks();
            synchronous = false;
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("__timingDelivery").unwrap(), serde_json::json!([
            [true, true, ["new", "old"], 1, "[object PerformanceObserverEntryList]"]
        ]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn user_timing_drained_observers_do_not_starve_other_observers() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("user-timing-drain", r#"
            globalThis.__timingDrain = {callbacks: []};
            const drained = new PerformanceObserver(() => __timingDrain.callbacks.push('drained'));
            const cancelled = new PerformanceObserver(() => __timingDrain.callbacks.push('cancelled'));
            const active = new PerformanceObserver(list => {
                __timingDrain.callbacks.push(list.getEntries().map(e => e.name));
                active.disconnect();
            });
            drained.observe({type: 'mark'});
            cancelled.observe({type: 'mark'});
            active.observe({type: 'mark'});
            performance.mark('first', {startTime: 5});
            performance.mark('second', {startTime: 1});
            __timingDrain.records = drained.takeRecords().map(e => e.name);
            cancelled.disconnect();
            __timingDrain.cancelledRecords = cancelled.takeRecords().length;
            try { cancelled.observe({entryTypes: ['mark']}); }
            catch (error) { __timingDrain.modeError = error.name; }
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("__timingDrain").unwrap(), serde_json::json!({
            "callbacks": [["second", "first"]], "records": ["first", "second"],
            "cancelledRecords": 0, "modeError": "InvalidModificationError",
        }));
    }

    #[test]
    fn user_timing_unknown_entry_types_return_empty_lists() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"['__proto__', 'constructor', 'toString', 'unsupported']
            .map(type => performance.getEntriesByType(type).length)"#).unwrap();
        assert_eq!(result, serde_json::json!([0, 0, 0, 0]));
    }

    #[test]
    fn user_timing_webidl_dictionary_getters_are_read_once() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            let durationReads = 0, typeReads = 0;
            const measure = performance.measure('work', {start: 3,
                get duration() { durationReads++; return 4; }});
            const observer = new PerformanceObserver(() => {});
            observer.observe({get type() { typeReads++; return 'mark'; }});
            observer.disconnect();
            return [measure.duration, durationReads, typeReads];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([4, 1, 1]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn user_timing_buffered_observers_accept_large_timelines() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("large-timing-timeline", r#"
            for (let i = 0; i < 150000; i++) performance.mark('work', {startTime: i});
            globalThis.__largeTimingDelivery = [];
            const observer = new PerformanceObserver(list => {
                const entries = list.getEntries();
                __largeTimingDelivery = [entries.length, entries[0].startTime,
                    entries[entries.length - 1].startTime];
                observer.disconnect();
            });
            observer.observe({type: 'mark', buffered: true});
            performance.clearMarks();
        "#).unwrap();
        rt.run_event_loop_bounded(1000).await.unwrap();
        assert_eq!(rt.evaluate("__largeTimingDelivery").unwrap(),
            serde_json::json!([150000, 0, 149999]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn user_timing_observer_reports_dropped_entries_once_per_observe() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("timing-callback-options", r#"
            globalThis.__timingOptions = [];
            const observer = new PerformanceObserver((list, owner, options) => {
                __timingOptions.push([list.getEntries().map(e => e.name),
                    Object.hasOwn(options, 'droppedEntriesCount') ? options.droppedEntriesCount : 'unset']);
                if (__timingOptions.length === 1) performance.mark('second');
                else if (__timingOptions.length === 2) {
                    owner.observe({type: 'mark'});
                    performance.mark('third');
                } else owner.disconnect();
            });
            observer.observe({type: 'mark'});
            performance.mark('first');
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("__timingOptions").unwrap(), serde_json::json!([
            [["first"], 0], [["second"], "unset"], [["third"], 0]
        ]));
    }

    #[test]
    fn user_timing_interfaces_expose_inherited_operations() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(function() {
            if (typeof Performance !== 'function') return 'Performance missing';
            const mark = Performance.prototype.mark.call(performance, 'work', {startTime: 7});
            const measure = Performance.prototype.measure.call(performance, 'work', {start: 7, duration: 3});
            let illegal = 'none';
            try { new Performance(); } catch (error) { illegal = error.name; }
            return [performance instanceof Performance, illegal, mark.startTime, measure.duration,
                ['mark', 'clearMarks', 'measure', 'clearMeasures'].map(name =>
                    [Object.hasOwn(performance, name), performance[name].length, performance[name].name]),
                ['Performance', 'PerformanceMark', 'PerformanceMeasure', 'PerformanceObserver'].map(name =>
                    Object.getOwnPropertyDescriptor(globalThis, name).enumerable)];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([true, "TypeError", 7, 3,
            [[false, 1, "mark"], [false, 0, "clearMarks"], [false, 1, "measure"],
                [false, 0, "clearMeasures"]], [false, false, false, false]]));
    }

    #[test]
    fn performance_now_is_monotonic_under_bursty_calls() {
        let mut rt = setup_runtime("<html><body></body></html>");
        // Hammer performance.now() so many calls land in the same millisecond and
        // the wall clock rolls over repeatedly; the value must never go backwards.
        let violations = rt
            .evaluate(
                "(function(){var prev=-Infinity, bad=0; for(var i=0;i<500000;i++){var t=performance.now(); if(t<prev) bad++; prev=t;} return bad;})()",
            )
            .unwrap();
        assert_eq!(
            violations.as_f64(),
            Some(0.0),
            "performance.now() went backwards"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_close_navigation_timing_records_real_lifecycle_only_once() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate("performance.timing.loadEventEnd").unwrap().as_f64(), Some(0.0));
        rt.execute_script("document-close-timing", r#"
            document.open();
            globalThis.samples = [];
            document.addEventListener('DOMContentLoaded', () => samples.push([
                performance.timing.domContentLoadedEventStart, performance.timing.domContentLoadedEventEnd]));
            window.addEventListener('load', () => samples.push([
                performance.timing.loadEventStart, performance.timing.loadEventEnd]));
            Date.now = () => 0;
            document.write('<p>Written document</p>'); document.close();
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate(r#"(() => {
            const [dom, load] = samples;
            const end = performance.timing.loadEventEnd;
            const origin = performance.timeOrigin;
            window.dispatchEvent(new Event('load'));
            document.open(); document.write('<p>Written again</p>'); document.close();
            return [dom[0] > 0 && dom[1] === 0, load[0] > 0 && load[1] === 0,
                end >= load[0], performance.timing.loadEventEnd === end,
                performance.timeOrigin === origin];
        })()"#).unwrap(), serde_json::json!([true, true, true, true, true]));
        let before = rt.evaluate("[performance.timeOrigin, performance.timing.loadEventEnd]").unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("[performance.timeOrigin, performance.timing.loadEventEnd]").unwrap(), before);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn performance_now_does_not_outrun_elapsed_time() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let lead = rt
            .evaluate(
                "(function(){for(var i=0;i<500000;i++)performance.now(); return performance.now()-(Date.now()-performance.timeOrigin);})()",
            )
            .unwrap();
        assert!(
            lead.as_f64().unwrap() <= 1.0,
            "performance.now() advanced ahead of elapsed time: {lead}"
        );
    }

    #[test]
    fn time_origin_never_lands_in_the_future() {
        // __obscura_init deletes itself, so a realm yields one draw of the
        // origin jitter. Build a fresh runtime per draw, do not hoist this out.
        for _ in 0..40 {
            let mut rt = setup_runtime("<html><body></body></html>");
            let skew = rt
                .evaluate("performance.timeOrigin - Date.now()")
                .unwrap()
                .as_f64()
                .unwrap();
            assert!(
                skew <= 0.0,
                "performance.timeOrigin is {skew} ms ahead of Date.now()"
            );
        }
    }

    #[test]
    fn childnode_helpers_coerce_non_string_primitives_to_text() {
        let mut rt =
            setup_runtime(r#"<html><body><div id="p"><span id="t">x</span></div></body></html>"#);
        let before = rt
            .evaluate("(function(){var t=document.getElementById('t'); t.before(5); return t.previousSibling ? t.previousSibling.textContent : 'NULL';})()")
            .unwrap();
        assert_eq!(before, serde_json::json!("5"));
        let after = rt
            .evaluate("(function(){var t=document.getElementById('t'); t.after(true); return t.nextSibling ? t.nextSibling.textContent : 'NULL';})()")
            .unwrap();
        assert_eq!(after, serde_json::json!("true"));
        let replaced = rt
            .evaluate("(function(){var t=document.getElementById('t'); t.replaceWith(42); return document.getElementById('p').textContent;})()")
            .unwrap();
        assert!(
            replaced.as_str().unwrap().contains("42"),
            "replaceWith(42) should leave text '42': {replaced}"
        );
    }

    #[test]
    fn replace_state_without_url_preserves_current_location() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let path = rt
            .evaluate(
                "(function(){history.pushState({}, '', '/dashboard'); history.replaceState({scroll:1}); return location.pathname;})()",
            )
            .unwrap();
        assert_eq!(path, serde_json::json!("/dashboard"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn location_hash_navigates_to_a_fragment_in_the_same_document() {
        let mut rt = setup_runtime("<html><body><a id=tab href='#tab'>tab</a></body></html>");
        rt.execute_script(
            "fragment-navigation",
            r#"
                globalThis.__events = [];
                addEventListener('hashchange', (e) => __events.push(e.oldURL + ' -> ' + e.newURL));
                globalThis.__marker = 'same-document';
                location.hash = 'one';
                globalThis.__syncHash = location.hash;
                location.hash = '#one';
                location.href = '#two';
                document.getElementById('tab').click();
            "#,
        )
        .unwrap();
        assert_eq!(rt.take_pending_navigation(), None, "a fragment change must not load a new document");
        rt.run_event_loop_bounded(100).await.unwrap();
        let result = rt
            .evaluate("[__syncHash, location.href, history.length, __marker, __events]")
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "#one",
                "http://example.com/test#tab",
                4,
                "same-document",
                [
                    "http://example.com/test -> http://example.com/test#one",
                    "http://example.com/test#one -> http://example.com/test#two",
                    "http://example.com/test#two -> http://example.com/test#tab",
                ],
            ])
        );
        rt.evaluate("history.back()").unwrap();
        assert_eq!(rt.evaluate("location.hash").unwrap(), serde_json::json!("#two"));
    }

    #[test]
    fn location_replace_with_a_fragment_replaces_the_history_entry() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate("(function(){ location.replace('#r'); return [location.hash, history.length]; })()")
            .unwrap();
        assert_eq!(result, serde_json::json!(["#r", 1]));
        assert_eq!(rt.take_pending_navigation(), None);
    }

    #[test]
    fn location_component_setters_load_the_new_url() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("location.search = 'q=1'").unwrap();
        assert_eq!(
            rt.take_pending_navigation(),
            Some(("http://example.com/test?q=1".into(), "GET".into(), String::new())),
        );
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("location.pathname = '/other'").unwrap();
        assert_eq!(
            rt.take_pending_navigation().map(|(url, _, _)| url),
            Some("http://example.com/other".into()),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn location_hash_preserves_leading_hashes_and_ignores_an_unchanged_empty_fragment() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("hash-setter", r#"
            globalThis.__hashEvents = [];
            addEventListener('hashchange', e => __hashEvents.push([e.oldURL, e.newURL]));
            location.hash = '';
            location.hash = '#';
            globalThis.__emptyHashResult = [location.href, history.length];
            location.hash = '##panel';
            location.hash = '##panel';
        "#).unwrap();
        assert_eq!(rt.take_pending_navigation(), None);
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("[__emptyHashResult, location.href, location.hash, history.length, __hashEvents]").unwrap(),
            serde_json::json!([
                ["http://example.com/test", 1],
                "http://example.com/test##panel", "##panel", 2,
                [["http://example.com/test", "http://example.com/test##panel"]],
            ]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn same_fragment_navigation_preserves_history_state() {
        let mut rt = setup_runtime("<html><body><a id=tab href='#panel'>tab</a></body></html>");
        rt.execute_script("same-fragment", r#"
            history.replaceState({saved: 1}, '', '#panel');
            globalThis.__sameHashEvents = 0;
            addEventListener('hashchange', () => __sameHashEvents++);
            location.assign('#panel');
            location.href = '#panel';
            location.replace('#panel');
            document.getElementById('tab').click();
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.take_pending_navigation(), None);
        assert_eq!(rt.evaluate("[history.state, history.length, location.hash, __sameHashEvents]").unwrap(),
            serde_json::json!([{ "saved": 1 }, 1, "#panel", 0]));
    }

    #[test]
    fn push_state_without_url_preserves_current_location() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let path = rt
            .evaluate(
                "(function(){history.pushState({}, '', '/a'); history.pushState({b:1}); return location.pathname;})()",
            )
            .unwrap();
        assert_eq!(path, serde_json::json!("/a"));
    }

    // #1055: pushState/replaceState must reject a cross-origin (or file:) URL
    // with a SecurityError rather than adopting it. Otherwise a page can spoof
    // its own URL, which the host adopts as page.url via sync_virtual_url.
    #[test]
    fn push_and_replace_state_reject_cross_origin_urls() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(function(){
                    function attempt(fn) {
                        try { fn(); return 'no-throw'; }
                        catch (e) { return e && e.name; }
                    }
                    return {
                        push_cross: attempt(() => history.pushState({}, '', 'http://evil.example/x')),
                        push_file: attempt(() => history.pushState({}, '', 'file:///etc/passwd')),
                        replace_cross: attempt(() => history.replaceState({}, '', 'https://evil.example/x')),
                        // Same-origin routing still works.
                        same_origin: attempt(() => history.pushState({}, '', '/dashboard')),
                        href: location.href,
                    };
                })()"#,
            )
            .unwrap();
        assert_eq!(result["push_cross"], serde_json::json!("SecurityError"));
        assert_eq!(result["push_file"], serde_json::json!("SecurityError"));
        assert_eq!(result["replace_cross"], serde_json::json!("SecurityError"));
        assert_eq!(result["same_origin"], serde_json::json!("no-throw"));
        // The rejected cross-origin URLs never became the page URL.
        assert_eq!(result["href"], serde_json::json!("http://example.com/dashboard"));
    }

    #[test]
    fn history_exposes_the_web_platform_constructor_and_prototype() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(function(){
                    const original = history.replaceState;
                    History.prototype.replaceState.call(history, {ok:true}, "", "/prototype");
                    let illegal = false;
                    try { new History(); } catch (error) { illegal = error instanceof TypeError; }
                    return {
                        instance: history instanceof History,
                        prototype: Object.getPrototypeOf(history) === History.prototype,
                        method: original === History.prototype.replaceState,
                        tag: Object.prototype.toString.call(history),
                        path: location.pathname,
                        illegal,
                    };
                })()"#,
            )
            .unwrap();
        assert_eq!(result["instance"], serde_json::json!(true));
        assert_eq!(result["prototype"], serde_json::json!(true));
        assert_eq!(result["method"], serde_json::json!(true));
        assert_eq!(result["tag"], serde_json::json!("[object History]"));
        assert_eq!(result["path"], serde_json::json!("/prototype"));
        assert_eq!(result["illegal"], serde_json::json!(true));
    }

    #[test]
    fn history_reads_host_session_entries_and_queues_cross_document_traversal() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_session_history(
            vec!["http://example.com/one".into(), "http://example.com/two".into()],
            1,
            1,
        );
        assert_eq!(rt.evaluate("history.length").unwrap(), serde_json::json!(2.0));
        rt.evaluate("history.back()").unwrap();
        assert_eq!(
            rt.take_pending_navigation(),
            Some(("http://example.com/one".into(), "GET".into(), String::new())),
        );
        assert_eq!(rt.take_pending_history_traversal(), Some(0));
    }

    #[test]
    fn element_style_is_not_replaced_by_a_page_expando() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="d" style="color: red">hi</div></body></html>"#,
        );
        assert_eq!(rt.evaluate(r#"(() => {
            const element = document.getElementById('d');
            element._style = { color: 'poisoned' };
            const style = element.style;
            return [style instanceof CSSStyleDeclaration, style.color, style === element.style];
        })()"#).unwrap(), serde_json::json!([true, "red", true]));
    }

    #[test]
    fn first_element_style_access_ignores_replaced_page_intrinsics() {
        let mut rt = setup_runtime("<html><body>Style</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const element = document.body;
            const original = [globalThis.Proxy, Object.defineProperty,
                WeakMap.prototype.get, WeakMap.prototype.set, Reflect.apply];
            const fail = () => { throw new Error('page intrinsic called'); };
            let style;
            try {
                globalThis.Proxy = fail;
                Object.defineProperty = fail;
                WeakMap.prototype.get = fail;
                WeakMap.prototype.set = fail;
                Reflect.apply = fail;
                style = element.style;
            } finally {
                [globalThis.Proxy, Object.defineProperty, WeakMap.prototype.get,
                    WeakMap.prototype.set, Reflect.apply] = original;
            }
            return [style instanceof CSSStyleDeclaration, style === element.style];
        })()"#).unwrap(), serde_json::json!([true, true]));
    }

    #[test]
    fn element_style_first_read_observes_prior_attribute_mutations() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const element = document.createElement('div');
            element.setAttribute('style', 'color: red');
            element.removeAttributeNS(null, 'style');
            element.setAttributeNS(null, 'style', 'color: blue');
            const style = element.style;
            const before = style.color;
            element.style = 'color: green';
            const assigned = style.color;
            element.removeAttribute('style');
            const removed = style.color;
            style.color = 'purple';
            return [before, assigned, removed, style === element.style,
                element.getAttribute('style')];
        })()"#).unwrap(), serde_json::json!(["blue", "green", "", true, "color: purple;"]));
    }

    #[test]
    fn style_attribute_parses_into_style_object() {
        // Inline styles present in the parsed HTML must be visible via el.style.*
        let mut rt = setup_runtime(
            r#"<html><body><div id="d" style="color: red; display: none">hi</div></body></html>"#,
        );
        assert_eq!(
            rt.evaluate("document.getElementById('d').style.color")
                .unwrap(),
            serde_json::json!("red")
        );
        assert_eq!(
            rt.evaluate("document.getElementById('d').style.display")
                .unwrap(),
            serde_json::json!("none")
        );
    }

    #[test]
    fn set_style_attribute_updates_style_object() {
        let mut rt = setup_runtime(r#"<html><body><div id="d">hi</div></body></html>"#);
        let margin = rt
            .evaluate(
                "(function(){var e=document.getElementById('d'); e.setAttribute('style','margin: 5px'); return e.style.margin;})()",
            )
            .unwrap();
        assert_eq!(margin, serde_json::json!("5px"));
    }

    #[test]
    fn null_namespace_style_attribute_stays_in_sync() {
        let mut rt = setup_runtime(r#"<html><body><div id="d">hi</div></body></html>"#);
        let result = rt
            .evaluate(
                "(function(){var e=document.getElementById('d'); e.setAttributeNS(null,'style','color: green'); var before=e.style.color; e.removeAttributeNS(null,'style'); return before+'|'+e.style.color+'|'+String(e.getAttribute('style'));})()",
            )
            .unwrap();
        assert_eq!(result, serde_json::json!("green||null"));
    }

    #[test]
    fn setting_style_property_updates_the_attribute_and_serialization() {
        let mut rt = setup_runtime(r#"<html><body><div id="d">hi</div></body></html>"#);
        let attr = rt
            .evaluate(
                "(function(){var e=document.getElementById('d'); e.style.color='blue'; return e.getAttribute('style');})()",
            )
            .unwrap();
        assert_eq!(attr, serde_json::json!("color: blue;"));
        let html = rt
            .evaluate("document.getElementById('d').outerHTML")
            .unwrap();
        assert!(
            html.as_str().unwrap().contains("color: blue"),
            "outerHTML should carry the style set via el.style: {html}"
        );
    }

    #[test]
    fn style_object_reflects_external_attribute_change() {
        // A later setAttribute('style', …) must supersede an earlier value read
        // through el.style (the declaration re-syncs from the attribute).
        let mut rt =
            setup_runtime(r#"<html><body><div id="d" style="color: red">hi</div></body></html>"#);
        let color = rt
            .evaluate(
                "(function(){var e=document.getElementById('d'); e.style.color; e.setAttribute('style','color: green'); return e.style.color;})()",
            )
            .unwrap();
        assert_eq!(color, serde_json::json!("green"));
    }

    #[test]
    fn clone_node_deep_preserves_context_sensitive_elements() {
        // A <tr> is not a valid child of <div>, so cloning through a throwaway
        // <div>.innerHTML dropped it and returned null. A structural clone keeps it.
        let mut rt = setup_runtime("<html><body></body></html>");
        let tag = rt
            .evaluate("(document.createElement('tr').cloneNode(true) || {}).tagName || 'NULL'")
            .unwrap();
        assert_eq!(tag, serde_json::json!("TR"));
        let td = rt
            .evaluate("(document.createElement('td').cloneNode(true) || {}).tagName || 'NULL'")
            .unwrap();
        assert_eq!(td, serde_json::json!("TD"));
    }

    #[test]
    fn clone_node_deep_copies_children_and_attributes() {
        let mut rt = setup_runtime(
            r#"<html><body><ul id="l"><li class="a">one</li><li class="b">two</li></ul></body></html>"#,
        );
        let out = rt
            .evaluate(
                "(function(){var c=document.getElementById('l').cloneNode(true); return c.children.length + '|' + c.children[0].className + '|' + c.children[1].textContent;})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("2|a|two"));
    }

    #[test]
    fn clone_node_deep_preserves_table_rows() {
        let mut rt = setup_runtime(
            r#"<html><body><table id="t"><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>"#,
        );
        // Navigate the detached clone directly (querySelector does not traverse
        // detached subtrees). tbody > tr > (td, td).
        let out = rt
            .evaluate(
                "(function(){var tb=document.querySelector('#t tbody').cloneNode(true); var tr=tb.children[0]; return tr.tagName + '|' + tr.children.length + '|' + tr.children[1].textContent;})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("TR|2|2"));
    }

    #[test]
    fn clone_node_shallow_copies_attributes_without_children() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="d" data-x="7"><span>kid</span></div></body></html>"#,
        );
        let out = rt
            .evaluate(
                "(function(){var c=document.getElementById('d').cloneNode(false); return c.getAttribute('data-x') + '|' + c.childNodes.length;})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("7|0"));
    }

    #[test]
    fn clone_node_copies_js_assigned_inline_styles() {
        let mut rt = setup_runtime("<html><body><div id='d'></div></body></html>");
        let out = rt
            .evaluate(
                "(function(){var d=document.getElementById('d');d.style.color='red';d.style.fontSize='12px';var c=d.cloneNode(false);return c.style.color+'|'+c.style.fontSize+'|'+c.style.cssText;})()",
            )
            .unwrap();
        assert_eq!(
            out,
            serde_json::json!("red|12px|color: red; font-size: 12px;")
        );
    }

    #[test]
    fn clone_node_deep_copies_template_content() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let out = rt
            .evaluate(
                "(function(){var t=document.createElement('template');t.content.appendChild(document.createElement('option')).textContent='choice';var c=t.cloneNode(true);return c.content.childNodes.length+'|'+c.content.firstChild.tagName+'|'+c.content.firstChild.textContent;})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("1|OPTION|choice"));
    }

    #[test]
    fn insert_adjacent_html_parses_table_fragments() {
        let mut rt = setup_runtime(
            r#"<html><body><table id="t"><tbody id="tb"></tbody></table></body></html>"#,
        );
        let out = rt
            .evaluate("(function(){var tb=document.getElementById('tb'); tb.insertAdjacentHTML('beforeend','<tr><td>1</td><td>2</td></tr>'); var tr=tb.firstElementChild; return tr ? (tr.tagName+':'+tr.children.length) : 'NULL';})()")
            .unwrap();
        assert_eq!(out, serde_json::json!("TR:2"));
    }

    #[test]
    fn insert_adjacent_html_position_is_case_insensitive() {
        let mut rt =
            setup_runtime(r#"<html><body><div id="host"><span>base</span></div></body></html>"#);
        let out = rt
            .evaluate("(function(){var h=document.getElementById('host'); h.insertAdjacentHTML('BeforeEnd','<b>x</b>'); return h.lastElementChild ? h.lastElementChild.tagName : 'NULL';})()")
            .unwrap();
        assert_eq!(out, serde_json::json!("B"));
    }

    #[test]
    fn insert_adjacent_html_rejects_invalid_position() {
        let mut rt = setup_runtime(r#"<html><body><div id="host"></div></body></html>"#);
        let out = rt
            .evaluate("(function(){var h=document.getElementById('host'); try { h.insertAdjacentHTML('nope','<b>x</b>'); return 'no-throw'; } catch(e){ return e.name; }})()")
            .unwrap();
        assert_eq!(out, serde_json::json!("SyntaxError"));
    }

    #[test]
    fn insert_adjacent_html_keeps_leading_comments_in_table_contexts() {
        let mut rt = setup_runtime(
            r#"<html><body><table><tbody id="tb"><tr id="row"></tr></tbody></table></body></html>"#,
        );
        let out = rt
            .evaluate(
                "(function(){var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<!--m--><tr><td>v</td></tr>');var row=document.getElementById('row');row.insertAdjacentHTML('beforeend','<!--n--><td>x</td>');return Array.from(tb.childNodes).map(function(n){return n.nodeName}).join('|')+';'+Array.from(row.childNodes).map(function(n){return n.nodeName}).join('|');})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("TR|#comment|TR;#comment|TD"));
    }

    #[test]
    fn insert_adjacent_html_uses_the_insertion_element_as_context() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="d"></div><table id="table"><tbody id="tb"></tbody></table></body></html>"#,
        );
        let out = rt
            .evaluate(
                "(function(){var d=document.getElementById('d');d.insertAdjacentHTML('beforeend','<tr><td>v</td></tr>');var table=document.getElementById('table');table.insertAdjacentHTML('beforeend','<tr><td>x</td></tr>');var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<tr><td>y</td></tr>tail');return d.firstChild.nodeName+':'+d.textContent+';'+table.lastElementChild.tagName+';'+Array.from(tb.childNodes).map(function(n){return n.nodeName+(n.data?':'+n.data:'')}).join('|');})()",
            )
            .unwrap();
        assert_eq!(out, serde_json::json!("#text:v;TBODY;TR|#text:tail"));
    }

    #[test]
    fn set_attribute_ns_is_retrievable_by_namespace_and_local_name() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")
            .unwrap();
        assert_eq!(v, serde_json::json!("#g"));
    }

    #[test]
    fn remove_attribute_ns_removes_by_namespace() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); s.removeAttributeNS('http://www.w3.org/1999/xlink','href'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")
            .unwrap();
        assert_eq!(v, serde_json::json!(null));
    }

    #[test]
    fn get_attribute_ns_reads_plain_attributes_with_null_namespace() {
        // Backward-compat: getAttributeNS(null, name) still reads a plain attr.
        let mut rt = setup_runtime(r#"<html><body><div id="d" title="hi"></div></body></html>"#);
        let v = rt
            .evaluate("document.getElementById('d').getAttributeNS(null,'title')")
            .unwrap();
        assert_eq!(v, serde_json::json!("hi"));
    }

    #[test]
    fn namespaced_attribute_keeps_its_qualified_name() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g');return s.getAttribute('xlink:href')+'|'+s.getAttributeNames()[0]+'|'+s.outerHTML;})()")
            .unwrap();
        assert_eq!(
            v,
            serde_json::json!("#g|xlink:href|<svg xlink:href=\"#g\"></svg>")
        );
    }

    #[test]
    fn parsed_xlink_attribute_is_available_through_both_apis() {
        let mut rt = setup_runtime(
            r##"<html><body><svg><use id="u" xlink:href="#icon"></use></svg></body></html>"##,
        );
        let v = rt
            .evaluate("(function(){var u=document.getElementById('u');return u.getAttribute('xlink:href')+'|'+u.getAttributeNS('http://www.w3.org/1999/xlink','href')+'|'+u.getAttributeNames().join(',');})()")
            .unwrap();
        assert_eq!(v, serde_json::json!("#icon|#icon|id,xlink:href"));
    }

    #[test]
    fn set_attribute_updates_a_parsed_namespaced_attribute_in_place() {
        // setAttribute matched the stored attribute by local name only, so a
        // parsed `xlink:href` (prefix=xlink, local=href) was never found by the
        // qualified name "xlink:href": the update was pushed as a *second*
        // attribute, getAttribute kept returning the stale original, and the
        // element serialized `xlink:href` twice.
        let mut rt = setup_runtime(
            r##"<html><body><svg><use id="u" xlink:href="#a"></use></svg></body></html>"##,
        );
        let v = rt
            .evaluate("(function(){var u=document.getElementById('u');u.setAttribute('xlink:href','#b');var dup=(u.outerHTML.match(/xlink:href/g)||[]).length;return u.getAttribute('xlink:href')+'|'+u.getAttributeNS('http://www.w3.org/1999/xlink','href')+'|'+u.getAttributeNames().join(',')+'|'+dup;})()")
            .unwrap();
        assert_eq!(v, serde_json::json!("#b|#b|id,xlink:href|1"));
    }

    #[test]
    fn set_attribute_ns_validates_namespace_constraints() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate("(function(){var e=document.createElement('div'),out=[];for(const args of [[null,'x:y'],['urn:test','a:b:c'],['urn:test','xml:lang'],['urn:test','xmlns:x']]){try{e.setAttributeNS(args[0],args[1],'v');out.push('none')}catch(err){out.push(err.name)}}return out.join('|');})()")
            .unwrap();
        assert_eq!(
            v,
            serde_json::json!("NamespaceError|InvalidCharacterError|NamespaceError|NamespaceError")
        );
    }

    #[test]
    fn dom_parser_flags_malformed_xml_with_parsererror() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let has_err = rt
            .evaluate("(function(){var d=new DOMParser().parseFromString('<a><b></a>','application/xml'); return d.querySelector('parsererror') ? true : false;})()")
            .unwrap();
        assert_eq!(has_err, serde_json::json!(true));
    }

    #[test]
    fn dom_parser_ignores_page_startswith_polyfill() {
        // iasWorld county sites replace startsWith with a polyfill that ignores
        // the position argument; their SOAP responses start with `<?xml`.
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(r#"(function(){
                String.prototype.startsWith = function(a){ return this.substr(0, a.length) === a; };
                var xml = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><R xmlns="http://tempuri.org/"><GetSearchExistsResult>true</GetSearchExistsResult></R></soap:Body></soap:Envelope>';
                var d = new DOMParser().parseFromString(xml, 'text/xml');
                if (d.querySelector('parsererror')) return 'ERR';
                return d.getElementsByTagName('GetSearchExistsResult')[0].textContent;
            })()"#)
            .unwrap();
        assert_eq!(result, serde_json::json!("true"));
    }

    #[test]
    fn dom_parser_accepts_well_formed_xml() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let ok = rt
            .evaluate("(function(){var d=new DOMParser().parseFromString('<root><child>x</child></root>','application/xml'); return d.querySelector('parsererror') ? 'ERR' : 'OK';})()")
            .unwrap();
        assert_eq!(ok, serde_json::json!("OK"));
    }

    #[test]
    fn a_parsererror_says_what_was_wrong() {
        // The <div> is where Chrome puts the reason, and callers show it. A
        // parsererror that only says "error while parsing XML" tells a user
        // nothing the presence of the element did not already say.
        let mut rt = setup_runtime("<html><body></body></html>");
        let detail = rt
            .evaluate("(function(){var d=new DOMParser().parseFromString('<a><b></a>','application/xml'); return d.querySelector('parsererror').textContent;})()")
            .unwrap();
        let detail = detail.as_str().unwrap_or_default().to_string();
        assert!(
            detail.contains("mismatch") && detail.contains('b') && detail.contains('a'),
            "the reason must name the fault and the tags involved, got: {detail}"
        );
    }

    #[test]
    fn a_parsererror_detail_is_text_not_markup() {
        // The reason quotes a tag name lifted from the input and is written
        // through innerHTML, so an input tag name must not become an element.
        //
        // The input has to be one whose message carries the angle brackets:
        // "unclosed tag <img>" does, "mismatch: img and a" does not, and a test
        // built on the latter passes with the escaping removed.
        let mut rt = setup_runtime("<html><body></body></html>");
        let n = rt
            .evaluate("(function(){var d=new DOMParser().parseFromString('<img src=x>','application/xml'); var e=d.querySelector('parsererror'); return e ? e.querySelectorAll('img').length : -1;})()")
            .unwrap();
        // JS numbers arrive as f64, so compare as one.
        assert_eq!(
            n.as_f64(),
            Some(0.0),
            "a tag name from the input became an element in the error detail"
        );
    }

    #[test]
    fn dom_parser_html_never_gets_parsererror() {
        // HTML parsing is tolerant and must never synthesize a parsererror.
        let mut rt = setup_runtime("<html><body></body></html>");
        let ok = rt
            .evaluate("(function(){var d=new DOMParser().parseFromString('<div><p>hi</a>','text/html'); return d.querySelector('parsererror') ? 'ERR' : 'OK';})()")
            .unwrap();
        assert_eq!(ok, serde_json::json!("OK"));
    }

    #[test]
    fn custom_element_upgrade_runs_class_constructor_on_existing_element() {
        let mut rt = setup_runtime(
            r#"<html><body><svelte-like id="component"></svelte-like></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const before = document.getElementById("component");
                class SvelteLike extends HTMLElement {
                    constructor() {
                        super();
                        this.$$s = [];
                        this.attachShadow({ mode: "open" });
                    }
                    connectedCallback() {
                        for (const subscription of this.$$s) subscription();
                        this.$$s.push(() => {});
                        this.shadowRoot.textContent = "ready";
                    }
                }
                customElements.define("svelte-like", SvelteLike);
                return [
                    document.getElementById("component") === before,
                    before instanceof SvelteLike,
                    before.constructor === SvelteLike,
                    before.$$s.length,
                    before.shadowRoot && before.shadowRoot.textContent
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true, true, 1, "ready"]));
    }

    #[test]
    fn slot_element_has_own_brand_and_named_assignment() {
        // Regression for the idealo search result slider: Swiper's getChildren
        // helper guards with `instanceof HTMLSlotElement` before calling
        // assignedElements(). With `HTMLSlotElement = Element` the guard matched
        // a plain <div> and the missing method threw a TypeError.
        let mut rt = setup_runtime(
            r#"<html><body><div id="plain"><i></i></div><slot id="light"><i></i></slot></body></html>"#,
        );
        let result = rt
            .evaluate(
                r##"
                const tags = nodes => nodes.map(n => n.nodeType === 3 ? "#text" : n.tagName).join(",");
                const children = el => {
                    const out = [...el.children];
                    if (window.HTMLSlotElement && el instanceof HTMLSlotElement) {
                        out.push(...el.assignedElements());
                    }
                    return out;
                };
                const plain = document.getElementById("plain");
                const light = document.getElementById("light");
                const created = document.createElement("slot");

                const host = document.createElement("x-host");
                document.body.appendChild(host);
                host.innerHTML = '<b slot="title">T</b>text<span>S</span><em slot="missing">M</em>';
                const root = host.attachShadow({ mode: "open" });
                root.innerHTML = '<slot name="title"></slot><div><slot></slot></div>'
                    + '<slot name="title"></slot><slot name="empty"><u>fallback</u></slot>';
                const title = root.childNodes[0];
                const dflt = root.childNodes[1].firstChild;
                const dupe = root.childNodes[2];
                const empty = root.childNodes[3];

                const outer = document.createElement("x-outer");
                document.body.appendChild(outer);
                outer.innerHTML = "<p>deep</p>";
                const outerRoot = outer.attachShadow({ mode: "open" });
                outerRoot.innerHTML = "<x-inner><slot></slot></x-inner>";
                const inner = outerRoot.firstChild;
                const innerRoot = inner.attachShadow({ mode: "open" });
                innerRoot.innerHTML = '<slot name="unused"></slot><slot></slot>';
                const innerDefault = innerRoot.childNodes[1];

                created.name = "n1";

                // Later same-name slot: no direct assignment, but its own
                // fallback children with flatten (comments are not slottable).
                const dupHost = document.createElement("x-dup");
                document.body.appendChild(dupHost);
                dupHost.innerHTML = '<b slot="title">T</b>';
                const dupRoot = dupHost.attachShadow({ mode: "open" });
                dupRoot.innerHTML = '<slot name="title"></slot><slot name="title"><i>fb</i>text<!--c--></slot>';
                const dupSlot = dupRoot.childNodes[1];

                // Manual slot assignment is not implemented: nothing assigned, fallback only.
                const manHost = document.createElement("x-man");
                document.body.appendChild(manHost);
                manHost.innerHTML = "<b>light</b>";
                const manRoot = manHost.attachShadow({ mode: "open", slotAssignment: "manual" });
                manRoot.innerHTML = "<slot><u>fb</u></slot>";
                const manSlot = manRoot.firstChild;

                // Foreign-namespace "SLOT" (also via cloneNode) is no HTML slot
                // and must not steal the assignment of a following real slot.
                const foreign = document.createElementNS("urn:example", "SLOT");
                const foreignClone = foreign.cloneNode();
                const fHost = document.createElement("x-foreign");
                document.body.appendChild(fHost);
                fHost.innerHTML = "<b>light</b>";
                const fRoot = fHost.attachShadow({ mode: "open" });
                fRoot.appendChild(foreignClone);
                const realSlot = document.createElement("slot");
                fRoot.appendChild(realSlot);

                // Deep shadow tree: assignment must not depend on JS recursion depth.
                const deepHost = document.createElement("x-deep");
                document.body.appendChild(deepHost);
                deepHost.innerHTML = "<b>deep-light</b>";
                const deepRoot = deepHost.attachShadow({ mode: "open" });
                let cursor = deepRoot;
                for (let i = 0; i < 20000; i++) {
                    const div = document.createElement("div");
                    cursor.appendChild(div);
                    cursor = div;
                }
                const deepSlot = document.createElement("slot");
                cursor.appendChild(deepSlot);

                return [
                    plain instanceof HTMLSlotElement,
                    light instanceof HTMLSlotElement,
                    created instanceof HTMLSlotElement,
                    light instanceof HTMLElement && light instanceof Element,
                    typeof plain.assignedElements,
                    light.assignedNodes().length + light.assignedElements().length
                        + light.assignedNodes({ flatten: true }).length,
                    children(plain).length,
                    children(light).length,
                    created.name + "|" + created.getAttribute("name") + "|" + title.name + "|" + dflt.name,
                    tags(title.assignedElements()),
                    tags(dflt.assignedNodes()),
                    tags(dflt.assignedElements()),
                    dupe.assignedNodes().length,
                    empty.assignedNodes().length,
                    tags(empty.assignedNodes({ flatten: true })),
                    tags(innerDefault.assignedNodes()),
                    tags(innerDefault.assignedNodes({ flatten: true })),
                    tags(children(dflt)),
                    dupSlot.assignedNodes().length,
                    tags(dupSlot.assignedNodes({ flatten: true })),
                    tags(dupSlot.assignedElements({ flatten: true })),
                    manSlot.assignedNodes().length,
                    tags(manSlot.assignedNodes({ flatten: true })),
                    foreign instanceof HTMLSlotElement,
                    foreignClone instanceof HTMLSlotElement,
                    typeof foreignClone.assignedNodes,
                    tags(realSlot.assignedNodes()),
                    tags(deepSlot.assignedNodes()),
                ];
                "##,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                false,
                true,
                true,
                true,
                "undefined",
                0,
                1,
                1,
                "n1|n1|title|",
                "B",
                "#text,SPAN",
                "SPAN",
                0,
                0,
                "U",
                "SLOT",
                "P",
                "SPAN",
                0,
                "I,#text",
                "I",
                0,
                "U",
                false,
                false,
                "undefined",
                "B",
                "B"
            ])
        );
    }

    #[test]
    fn shadow_root_children_expose_parent_siblings_and_composed_root() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const host = document.createElement("lit-host");
                document.body.appendChild(host);
                const root = host.attachShadow({ mode: "open" });
                const start = document.createComment("start");
                const end = document.createComment("end");
                root.appendChild(start);
                root.appendChild(end);

                const text = document.createTextNode("rendered");
                start.parentNode.insertBefore(text, end);
                const inserted = [
                    start.parentNode === root,
                    start.nextSibling === text,
                    text.previousSibling === start,
                    text.nextSibling === end,
                    end.previousSibling === text,
                    root.contains(text),
                    text.getRootNode() === root,
                    text.getRootNode({ composed: true }) === document,
                    root.getRootNode({ composed: true }) === document,
                    root.isConnected,
                    text.isConnected,
                    root.textContent
                ];

                root.removeChild(text);
                const removed = [
                    text.parentNode === null,
                    start.nextSibling === end,
                    end.previousSibling === start
                ];

                document.body.appendChild(start);
                const moved = [
                    start.parentNode === document.body,
                    start.getRootNode() === document,
                    root.firstChild === end
                ];

                root.innerHTML = "<span id='inside'>inside</span>";
                const inside = root.firstChild;
                const parsed = [
                    inside.parentNode === root,
                    inside.getRootNode() === root,
                    root.textContent,
                    inside.matches("span#inside"),
                    root.querySelector("span#inside") === inside,
                    root.querySelectorAll("span#inside").length === 1
                ];

                const a = document.createElement("a");
                const b = document.createElement("b");
                const c = document.createElement("i");
                root.replaceChildren(a, b, c);
                root.insertBefore(a, c);
                const movedWithin = Array.from(root.children, el => el.localName);

                const fragment = document.createDocumentFragment();
                const x = document.createElement("x-one");
                const y = document.createElement("x-two");
                fragment.append(x, y);
                root.insertBefore(fragment, c);
                const flattened = [
                    Array.from(root.children, el => el.localName),
                    fragment.childNodes.length,
                    x.parentNode === root,
                    y.parentNode === root
                ];

                root.replaceChild(b, c);
                const replaced = [
                    Array.from(root.children, el => el.localName),
                    c.parentNode === null,
                    b.parentNode === root
                ];

                const detached = document.createElement("detached-node");
                const errors = [];
                for (const operation of [
                    () => root.insertBefore(detached, c),
                    () => root.removeChild(c),
                    () => root.replaceChild(detached, c),
                    () => root.appendChild(root),
                    () => root.appendChild(host)
                ]) {
                    try {
                        operation();
                        errors.push("none");
                    } catch (error) {
                        errors.push(error.name);
                    }
                }
                return [inserted, removed, moved, parsed, movedWithin, flattened, replaced, errors];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [
                    true, true, true, true, true, true, true, true, true, true, true, "rendered"
                ],
                [true, true, true],
                [true, true, true],
                [true, true, "inside", true, true, true],
                ["b", "a", "i"],
                [["b", "a", "x-one", "x-two", "i"], 0, true, true],
                [["a", "x-one", "x-two", "b"], true, true],
                [
                    "NotFoundError",
                    "NotFoundError",
                    "NotFoundError",
                    "HierarchyRequestError",
                    "HierarchyRequestError"
                ]
            ])
        );
    }

    #[test]
    fn replacement_script_runs_after_the_old_child_is_removed_without_observers() {
        let mut rt = setup_runtime("<!doctype html><body><span id=old>old</span></body>");
        let result = rt.evaluate(r#"(() => {
            const old = document.getElementById('old');
            const script = document.createElement('script');
            script.textContent = "globalThis.oldPresentDuringReplacement = document.getElementById('old') !== null";
            const removed = document.body.replaceChild(script, old);
            return [oldPresentDuringReplacement, removed === old, old.parentNode === null];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([false, true, true]));
    }

    #[test]
    fn pre_insertion_validity_checks_arguments_and_order() {
        let mut rt = setup_runtime("<!DOCTYPE html><html><body><p id='log'></p></body></html>");
        let result = rt
            .evaluate(
                r#"
                const name = (fn) => {
                    try { fn(); return "none"; }
                    catch (error) { return error instanceof TypeError ? "TypeError" : error.name; }
                };
                const body = document.body;
                const text = document.createTextNode("t");
                const a = document.createElement("a");
                const b = document.createElement("b");
                const c = document.createElement("i");
                a.appendChild(b);
                const doc = document.implementation.createHTMLDocument("title");
                const doctype = document.implementation.createDocumentType("html", "", "");
                return [
                    name(() => body.insertBefore(null, null)),
                    name(() => body.insertBefore(text)),
                    name(() => body.insertBefore(text, {})),
                    name(() => body.appendChild({})),
                    name(() => body.removeChild(null)),
                    name(() => body.replaceChild(text, null)),
                    name(() => text.insertBefore(document.createTextNode("x"), null)),
                    name(() => text.appendChild(text)),
                    name(() => b.insertBefore(a, c)),
                    name(() => b.insertBefore(text, c)),
                    name(() => a.insertBefore(doc, null)),
                    name(() => a.insertBefore(doctype, null)),
                    name(() => doc.insertBefore(doc.createTextNode("x"), doc.documentElement)),
                    name(() => doc.appendChild(doc.createElement("x"))),
                    name(() => doc.insertBefore(doctype, null)),
                    Array.from(doc.childNodes, n => n.nodeType),
                    doc.doctype === doc.firstChild,
                    body.insertBefore(text, undefined) === text,
                    body.lastChild === text,
                    document.doctype === document.firstChild,
                    Node.prototype.insertBefore.length,
                    Node.prototype.appendChild.length
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError",
                "HierarchyRequestError", "HierarchyRequestError", "HierarchyRequestError",
                "NotFoundError", "HierarchyRequestError", "HierarchyRequestError",
                "HierarchyRequestError", "HierarchyRequestError", "HierarchyRequestError",
                [10, 1], true, true, true, true, 2, 1
            ])
        );
    }

    #[test]
    fn document_child_constraints_follow_dom_order() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const name = (fn) => { try { fn(); return "none"; } catch (error) { return error.name; } };
                const doc = document.implementation.createHTMLDocument("t");
                const comment = doc.insertBefore(doc.createComment("c"), doc.firstChild);
                const root = doc.documentElement;
                doc.removeChild(root);
                const afterRemove = Array.from(doc.childNodes, n => n.nodeType);
                const fragment = doc.createDocumentFragment();
                fragment.appendChild(doc.createElement("a"));
                const beforeDoctype = name(() => doc.insertBefore(fragment, doc.doctype));
                const beforeComment = name(() => doc.insertBefore(fragment, comment));
                const appended = name(() => doc.appendChild(fragment));
                const two = doc.createDocumentFragment();
                two.append(doc.createElement("x"), doc.createElement("y"));
                const replacedDoctype = name(() => doc.replaceChild(doc.createElement("z"), doc.doctype));
                return [
                    afterRemove, beforeDoctype, beforeComment, appended,
                    doc.documentElement.localName, name(() => doc.appendChild(two)),
                    replacedDoctype
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [8, 10], "HierarchyRequestError", "HierarchyRequestError", "none", "a",
                "HierarchyRequestError", "HierarchyRequestError"
            ])
        );
    }

    #[test]
    fn child_list_records_match_the_dom_mutation_algorithms() {
        let mut rt = setup_runtime("<html><body><div id='p'><a></a><b></b><i></i></div><div id='q'><u></u></div></body></html>");
        let result = rt
            .evaluate(
                r#"
                const p = document.getElementById("p");
                const q = document.getElementById("q");
                const [a, b, i] = Array.from(p.childNodes);
                const u = q.firstChild;
                const observer = new MutationObserver(() => {});
                observer.observe(p, { childList: true, attributes: true, characterData: true, subtree: true });
                const describe = (records) => records.map(r => [
                    r.type,
                    r.target.id || r.target.nodeName,
                    Array.from(r.addedNodes, n => n.nodeName),
                    Array.from(r.removedNodes, n => n.nodeName),
                    r.previousSibling && r.previousSibling.nodeName,
                    r.nextSibling && r.nextSibling.nodeName,
                    r.attributeName,
                    r.attributeNamespace,
                    r.oldValue
                ]);
                const out = {};
                p.insertBefore(b, a);
                out.moveWithin = describe(observer.takeRecords());
                const fragment = document.createDocumentFragment();
                fragment.append(document.createElement("x"), document.createElement("y"));
                p.appendChild(fragment);
                out.fragment = describe(observer.takeRecords());
                p.replaceChild(u, i);
                out.replaceFromOtherParent = describe(observer.takeRecords());
                p.replaceChild(a, a);
                out.replaceSelf = describe(observer.takeRecords());
                const e = document.createElement("em");
                e.textContent = "";
                p.appendChild(e);
                observer.takeRecords();
                e.textContent = "";
                out.emptyTextContent = describe(observer.takeRecords());
                e.append("one", "two");
                out.appendTwo = describe(observer.takeRecords());
                e.normalize();
                out.normalize = describe(observer.takeRecords());
                e.setAttribute("title", "x");
                e.setAttribute("title", "y");
                e.removeAttribute("title");
                out.attributes = describe(observer.takeRecords());
                out.recordType = [
                    typeof MutationRecord,
                    (() => { p.appendChild(document.createElement("s")); return observer.takeRecords()[0] instanceof MutationRecord; })(),
                    Object.keys((() => { p.appendChild(document.createElement("s")); return observer.takeRecords()[0]; })()).length
                ];
                out.options = [
                    (() => { try { observer.observe(p, {}); return "none"; } catch (error) { return error.constructor.name; } })(),
                    (() => { try { observer.observe(p, { attributeOldValue: true, attributes: false }); return "none"; } catch (error) { return error.constructor.name; } })()
                ];
                return out;
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "moveWithin": [
                    ["childList", "p", [], ["B"], "A", "I", null, null, null],
                    ["childList", "p", ["B"], [], null, "A", null, null, null]
                ],
                "fragment": [["childList", "p", ["X", "Y"], [], "I", null, null, null, null]],
                "replaceFromOtherParent": [["childList", "p", ["U"], ["I"], "A", "X", null, null, null]],
                "replaceSelf": [
                    ["childList", "p", [], ["A"], "B", "U", null, null, null],
                    ["childList", "p", ["A"], [], "B", "U", null, null, null]
                ],
                "emptyTextContent": [],
                "appendTwo": [["childList", "EM", ["#text", "#text"], [], null, null, null, null, null]],
                "normalize": [
                    ["characterData", "#text", [], [], null, null, null, null, null],
                    ["childList", "EM", [], ["#text"], "#text", null, null, null, null]
                ],
                "attributes": [
                    ["attributes", "EM", [], [], null, null, "title", null, null],
                    ["attributes", "EM", [], [], null, null, "title", null, null],
                    ["attributes", "EM", [], [], null, null, "title", null, null]
                ],
                "recordType": ["function", true, 0],
                "options": ["TypeError", "TypeError"]
            })
        );
    }

    #[test]
    fn constructed_document_fragment_keeps_its_identity_as_parent() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const check = (fragment) => {
                    const child = document.createElement("div");
                    fragment.appendChild(child);
                    const scratch = document.createElement("span");
                    document.body.appendChild(scratch);
                    scratch.remove();
                    const parent = child.parentNode;
                    let removed;
                    try { fragment.removeChild(child); removed = "ok"; } catch (error) { removed = error.name; }
                    return [parent === fragment, parent && parent.nodeType, removed, child.parentNode];
                };
                return {
                    constructed: check(new DocumentFragment()),
                    created: check(document.createDocumentFragment())
                };
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "constructed": [true, 11, "ok", null],
                "created": [true, 11, "ok", null]
            })
        );
    }

    #[test]
    fn parent_node_insertion_of_several_nodes_is_one_mutation() {
        let mut rt = setup_runtime("<html><body><div id='p'><i id='first'></i></div><div id='q'><u></u></div></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    const p = document.getElementById("p");
                    const q = document.getElementById("q");
                    const first = document.getElementById("first");
                    const observer = new MutationObserver(() => {});
                    observer.observe(document.body, { childList: true, subtree: true });
                    const describe = (records) => records.map(r => [
                        r.target.id, Array.from(r.addedNodes, n => n.nodeName), Array.from(r.removedNodes, n => n.nodeName),
                        r.previousSibling && r.previousSibling.nodeName, r.nextSibling && r.nextSibling.nodeName
                    ]);
                    const a = document.createElement("a");
                    p.append(a, "t", q.firstChild);
                    const appended = describe(observer.takeRecords());
                    const b = document.createElement("b");
                    p.prepend(b, "s");
                    const prepended = describe(observer.takeRecords());
                    first.after(first, "x");
                    const withSelf = describe(observer.takeRecords());
                    const errors = [];
                    try { p.append(document.createElement("em"), document.body); } catch (e) { errors.push(e.name); }
                    return [appended, prepended, withSelf, errors, Array.from(p.childNodes, n => n.nodeName)];
                })()"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [["q", [], ["U"], null, null], ["p", ["A", "#text", "U"], [], "I", null]],
                [["p", ["B", "#text"], [], null, "I"]],
                [["p", [], ["I"], "#text", "A"], ["p", ["I", "#text"], [], "#text", "A"]],
                ["HierarchyRequestError"],
                ["B", "#text", "I", "#text", "A", "#text", "U"]
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn mutation_observer_old_values_and_callback_this() {
        let mut rt = setup_runtime("<html><body><p id='p' title='a'>text</p></body></html>");
        let result = rt
            .evaluate(
                r#"
                const p = document.getElementById("p");
                const observer = new MutationObserver(() => {});
                observer.observe(p, { attributeOldValue: true, characterDataOldValue: true, subtree: true, attributeFilter: ["title"] });
                p.setAttribute("title", "b");
                p.setAttribute("lang", "en");
                p.firstChild.data = "changed";
                const records = observer.takeRecords().map(r => [r.type, r.attributeName, r.oldValue]);
                let seenThis = null;
                const callbackObserver = new MutationObserver(function (list, obs) {
                    seenThis = [this === callbackObserver, obs === callbackObserver, arguments.length, Array.isArray(list)];
                });
                callbackObserver.observe(p, { childList: true });
                p.appendChild(document.createElement("span"));
                globalThis.__callbackThis = () => seenThis;
                return records;
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([["attributes", "title", "a"], ["characterData", null, "text"]])
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__callbackThis()").unwrap(),
            serde_json::json!([true, true, 2, true])
        );
    }

    #[test]
    fn range_mutations_move_nodes_and_queue_records() {
        let mut rt = setup_runtime("<html><body><div id='d'><b>bold</b><i>ital</i><u>under</u></div></body></html>");
        let result = rt
            .evaluate(
                r#"
                const d = document.getElementById("d");
                const [b, i, u] = Array.from(d.children);
                const observer = new MutationObserver(() => {});
                observer.observe(d, { childList: true, characterData: true, subtree: true });
                const range = document.createRange();
                range.setStart(b.firstChild, 2);
                range.setEnd(u.firstChild, 3);
                const cloned = range.cloneContents();
                const clonedText = Array.from(cloned.childNodes, n => n.textContent);
                const unchanged = d.textContent;
                observer.takeRecords();
                const extracted = range.extractContents();
                const extractedText = Array.from(extracted.childNodes, n => [n.nodeName, n.textContent]);
                const afterExtract = [d.innerHTML, range.startContainer === d, range.startOffset, range.collapsed];
                const extractRecords = observer.takeRecords().map(r => [r.type, Array.from(r.removedNodes, n => n.nodeName)]);
                const insertRange = document.createRange();
                insertRange.setStart(d, 1);
                insertRange.collapse(true);
                const marker = document.createElement("mark");
                insertRange.insertNode(marker);
                const afterInsert = [d.innerHTML, insertRange.endContainer === d, insertRange.endOffset];
                const surround = document.createRange();
                surround.selectNode(marker);
                const wrapper = document.createElement("span");
                surround.surroundContents(wrapper);
                const deleteRange = document.createRange();
                deleteRange.selectNodeContents(d);
                deleteRange.deleteContents();
                return [clonedText, unchanged, extractedText, afterExtract, extractRecords, afterInsert, marker.parentNode === wrapper, d.childNodes.length];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                ["ld", "ital", "und"],
                "bolditalunder",
                [["B", "ld"], ["I", "ital"], ["U", "und"]],
                ["<b>bo</b><u>er</u>", true, 1, true],
                [["characterData", []], ["childList", ["I"]], ["characterData", []]],
                ["<b>bo</b><mark></mark><u>er</u>", true, 2],
                true,
                0
            ])
        );
    }

    #[test]
    fn node_document_follows_the_creating_document_and_adoption() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const doc = document.implementation.createHTMLDocument();
                const el = doc.createElement("p");
                const text = doc.createTextNode("t");
                const created = [el.ownerDocument === doc, text.ownerDocument === doc, doc.ownerDocument, doc.title, !!doc.body, doc.defaultView];
                doc.body.appendChild(el);
                el.innerHTML = "<span>parsed</span>";
                const parsed = el.firstChild;
                const inTree = [el.ownerDocument === doc, parsed.ownerDocument === doc, doc.querySelector("span") === parsed, document.querySelector("span")];
                doc.body.removeChild(el);
                const removed = [el.ownerDocument === doc, parsed.ownerDocument === doc];
                document.body.appendChild(el);
                const adopted = [el.ownerDocument === document, parsed.ownerDocument === document, el.isConnected];
                document.body.removeChild(el);
                const leftMain = el.ownerDocument === document;
                const imported = doc.importNode(document.createElement("q"), true);
                const adoptedNode = doc.adoptNode(el);
                const xml = document.implementation.createDocument(null, "root", null);
                const parser = new DOMParser().parseFromString("<p>x</p>", "text/html");
                return [
                    created, inTree, removed, adopted, leftMain,
                    imported.ownerDocument === doc, adoptedNode.ownerDocument === doc,
                    xml instanceof XMLDocument, xml.documentElement.localName, xml.contentType,
                    xml.documentElement.ownerDocument === xml,
                    parser.querySelector("p").ownerDocument === parser,
                    document.createElement("div").ownerDocument === document,
                    document.documentElement.ownerDocument === document
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [true, true, null, "", true, null],
                [true, true, true, null],
                [true, true],
                [true, true, true],
                true,
                true, true,
                true, "root", "application/xml",
                true, true, true, true
            ])
        );
    }

    #[test]
    fn mutation_errors_use_the_dom_exception_of_the_node_frame() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    const iframe = document.createElement("iframe");
                    document.body.appendChild(iframe);
                    const child = iframe.contentWindow;
                    const doc = child.document;
                    const caught = (fn) => { try { fn(); return null; } catch (error) { return error; } };
                    const out = [];
                    for (const make of [
                        () => doc.createElement("a"),
                        () => doc.createTextNode("t"),
                        () => doc.createComment("c"),
                    ]) {
                        const node = make();
                        doc.body.appendChild(node);
                        const error = caught(() => node.removeChild(doc));
                        out.push([
                            node.ownerDocument === doc,
                            error && error.name,
                            error && error.constructor === child.DOMException,
                            error && error.constructor === DOMException,
                        ]);
                    }
                    const local = caught(() => document.body.removeChild(document.createElement("p")));
                    out.push([local.name, local.constructor === DOMException, local.constructor === child.DOMException]);
                    return [child.DOMException !== DOMException, out];
                })()"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true,
                [
                    [true, "NotFoundError", true, false],
                    [true, "NotFoundError", true, false],
                    [true, "NotFoundError", true, false],
                    ["NotFoundError", true, false]
                ]
            ])
        );
    }

    #[test]
    fn media_rules_expose_nested_rules_and_accept_insert_rule() {
        let mut rt = setup_runtime("<html><head><style id='s'>#t { color: black; } @media all { #t { color: blue; } }</style></head><body><div id='t'></div></body></html>");
        let result = rt
            .evaluate(
                r##"
                const sheet = document.getElementById("s").sheet;
                const media = sheet.cssRules[1];
                const before = [media instanceof CSSMediaRule, media instanceof CSSGroupingRule, media.type, media.conditionText, media.cssRules.length];
                const index = media.insertRule("#t { color: red; }", 1);
                const inserted = [index, media.cssRules.length, media.cssRules[1].parentRule === media, media.cssRules[1].parentStyleSheet === sheet];
                media.deleteRule(1);
                return [before, inserted, media.cssRules.length, typeof CSSSupportsRule];
                "##,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([[true, true, 4, "all", 1], [1, 2, true, true], 1, "function"])
        );
    }

    #[test]
    fn new_dom_interfaces_have_browser_shapes() {
        let mut rt = setup_runtime("<html><head><style id='s'>@media all { p { color: red } }</style></head><body></body></html>");
        let result = rt
            .evaluate(
                r##"(() => {
                    const caught = (fn) => { try { fn(); return "none"; } catch (e) { return e.message; } };
                    const observer = new MutationObserver(() => {});
                    const div = document.createElement("div");
                    observer.observe(div, { childList: true });
                    div.appendChild(document.createElement("i"));
                    const record = observer.takeRecords()[0];
                    const media = document.getElementById("s").sheet.cssRules[0];
                    return [
                        Object.prototype.toString.call(record),
                        Object.prototype.toString.call(media),
                        caught(() => new MutationRecord()),
                        caught(() => new IntersectionObserverEntry({})),
                        [MutationRecord.length, IntersectionObserverEntry.length, CSSConditionRule.length, CSSMediaRule.length],
                        ["MutationRecord", "IntersectionObserverEntry", "CSSMediaRule", "XMLDocument"]
                            .map(name => Object.getOwnPropertyDescriptor(globalThis, name).enumerable),
                        Object.getOwnPropertyNames(CSSConditionRule.prototype).sort(),
                        media.cssText,
                        Document.prototype.importNode.length
                    ];
                })()"##,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "[object MutationRecord]",
                "[object CSSMediaRule]",
                "Failed to construct 'MutationRecord': Illegal constructor",
                "Failed to construct 'IntersectionObserverEntry': Illegal constructor",
                [0, 0, 0, 0],
                [false, false, false, false],
                ["conditionText", "constructor"],
                "@media all {\n  p { color: red; }\n}",
                1
            ])
        );
    }

    #[test]
    fn computed_style_is_empty_outside_a_document() {
        let mut rt = setup_runtime("<html><body><div id='c' style='color: red'></div></body></html>");
        let result = rt
            .evaluate(
                r#"
                const detached = document.createElement("div");
                detached.style.color = "red";
                const style = getComputedStyle(detached);
                const empty = [style.length, style.color, style.getPropertyValue("color"), style.display];
                document.body.appendChild(detached);
                const live = style.color !== "";
                const host = document.createElement("div");
                const shadow = host.attachShadow({ mode: "open" });
                shadow.innerHTML = "<p id='in'></p>";
                const inDetachedShadow = getComputedStyle(shadow.getElementById("in")).display;
                return [empty, live, inDetachedShadow, typeof getComputedStyle(document.getElementById("c")).color];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([[0, "", "", ""], true, "", "string"])
        );
    }

    #[test]
    fn shadow_root_identity_and_children_are_native_tree_backed() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r##"
                const host = document.createElement("native-shadow-host");
                document.body.appendChild(host);
                const root = host.attachShadow({ mode: "open", delegatesFocus: true });
                root.innerHTML = "<section id='inside'><span>native</span></section>";
                const inside = root.querySelector("#inside");
                const records = [];
                const observer = new MutationObserver(batch => records.push(...batch));
                observer.observe(root, { childList: true, subtree: true });
                const added = document.createElement("strong");
                inside.appendChild(added);
                records.push(...observer.takeRecords());

                host._shadowRoot = { mode: "closed" };
                let duplicateError = "none";
                try { host.attachShadow({ mode: "open" }); }
                catch (error) { duplicateError = error.name; }

                class ClosedShadowHost extends HTMLElement {
                    constructor() {
                        super();
                        this.closedRoot = this.attachShadow({ mode: "closed" });
                        this.internals = this.attachInternals();
                    }
                }
                customElements.define("closed-shadow-host", ClosedShadowHost);
                const closedHost = document.createElement("closed-shadow-host");

                return [
                    root instanceof ShadowRoot,
                    root.nodeType,
                    root.nodeName,
                    root.host === host,
                    root.mode,
                    root.delegatesFocus,
                    host.shadowRoot === root,
                    duplicateError,
                    inside.parentNode === root,
                    inside.getRootNode() === root,
                    inside.getRootNode({ composed: true }) === document,
                    root.isConnected,
                    inside.isConnected,
                    host.contains(inside),
                    document.querySelector("#inside") === null,
                    root.querySelector("#inside") === inside,
                    records.length,
                    records[0] && records[0].target === inside,
                    records[0] && records[0].addedNodes[0] === added,
                    closedHost.shadowRoot,
                    closedHost.internals.shadowRoot === closedHost.closedRoot
                ];
                "##,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true,
                11,
                "#document-fragment",
                true,
                "open",
                true,
                true,
                "NotSupportedError",
                true,
                true,
                true,
                true,
                true,
                false,
                true,
                true,
                1,
                true,
                true,
                null,
                true
            ])
        );
    }

    #[test]
    fn create_element_synchronously_constructs_an_existing_definition() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const testStart = true;
                class CreatedLater extends HTMLElement {
                    constructor() {
                        super();
                        this.constructorState = ["initialized"];
                        this.attachShadow({ mode: "open" });
                        this.shadowRoot.textContent = "constructed";
                    }
                    connectedCallback() {
                        this.constructorState.push("connected");
                    }
                }
                customElements.define("created-later", CreatedLater);
                const element = document.createElement("created-later");
                const foreign = document.createElementNS(
                    "http://www.w3.org/2000/svg", "created-later"
                );
                return [
                    element instanceof CreatedLater,
                    element.constructor === CreatedLater,
                    element.localName,
                    element.constructorState,
                    element.shadowRoot && element.shadowRoot.textContent,
                    element.isConnected,
                    foreign instanceof CreatedLater
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true,
                true,
                "created-later",
                ["initialized"],
                "constructed",
                false,
                false
            ])
        );
    }

    #[test]
    fn created_foreign_element_keeps_native_qualified_name_through_clone() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate(
                "(function(){const ns='http://www.w3.org/2000/svg';const el=document.createElementNS(ns,'linearGradient');const clone=el.cloneNode(true);return [el.namespaceURI,el.localName,el.tagName,el.nodeName,clone.namespaceURI,clone.localName,clone.outerHTML].join('|');})()",
            )
            .unwrap();
        assert_eq!(
            v,
            serde_json::json!(
                "http://www.w3.org/2000/svg|linearGradient|linearGradient|linearGradient|http://www.w3.org/2000/svg|linearGradient|<linearGradient></linearGradient>"
            )
        );
    }

    #[test]
    fn svg_path_uses_the_standard_interface_chain() {
        let mut rt = setup_runtime(
            r#"<html><body><svg><path id="shape" d="M0 0L1 1"></path></svg></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const parsed = document.getElementById("shape");
                SVGPathElement.prototype.polyfillProbe = () => "path";
                const created = document.createElementNS(
                    "http://www.w3.org/2000/svg", "path"
                );
                const div = document.createElement("div");
                return [
                    parsed.constructor.name,
                    parsed instanceof SVGPathElement,
                    parsed instanceof SVGGeometryElement,
                    parsed instanceof SVGGraphicsElement,
                    parsed instanceof SVGElement,
                    parsed instanceof Element,
                    created instanceof SVGPathElement,
                    Object.getPrototypeOf(SVGPathElement.prototype) === SVGGeometryElement.prototype,
                    Object.getPrototypeOf(SVGGeometryElement.prototype) === SVGGraphicsElement.prototype,
                    Object.getPrototypeOf(SVGGraphicsElement.prototype) === SVGElement.prototype,
                    Object.getPrototypeOf(SVGElement.prototype) === Element.prototype,
                    parsed.polyfillProbe(),
                    typeof div.polyfillProbe
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "SVGPathElement",
                true,
                true,
                true,
                true,
                true,
                true,
                true,
                true,
                true,
                true,
                "path",
                "undefined"
            ])
        );
    }

    #[test]
    fn concrete_svg_element_interfaces_are_defined_and_carry_their_tag() {
        // #1043: a bare reference to a missing interface throws ReferenceError
        // rather than evaluating to undefined, which is what took down
        // html-to-image. `typeof` does not surface this, so probe with a bare
        // reference the way page-side libraries do.
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                return [
                    SVGImageElement, SVGUseElement, SVGTextElement,
                    SVGCircleElement, SVGRectElement, SVGAnimateElement,
                    SVGMarkerElement, SVGTSpanElement, SVGLineElement,
                    SVGGElement, SVGDefsElement, SVGStopElement,
                    SVGFEImageElement, SVGFEFuncRElement, SVGFEGaussianBlurElement,
                    SVGLinearGradientElement, SVGRadialGradientElement,
                    SVGClipPathElement, SVGMaskElement, SVGPatternElement,
                    SVGFilterElement, SVGForeignObjectElement, SVGSymbolElement,
                    SVGAElement, SVGSwitchElement, SVGViewElement,
                    SVGTitleElement, SVGDescElement, SVGMetadataElement,
                    SVGStyleElement, SVGScriptElement, SVGSVGElement,
                ].every((ctor) => typeof ctor === "function");
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(true));
    }

    #[test]
    fn svg_elements_use_their_own_interface_not_the_generic_one() {
        let mut rt = setup_runtime(
            r#"<html><body><svg><image id="i"></image><use id="u"></use><text id="t">hi</text><circle id="c"></circle></svg></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                return [
                    document.getElementById("i").constructor.name,
                    document.getElementById("i") instanceof SVGImageElement,
                    document.getElementById("u").constructor.name,
                    document.getElementById("u") instanceof SVGUseElement,
                    document.getElementById("t").constructor.name,
                    document.getElementById("t") instanceof SVGTextElement,
                    document.getElementById("c").constructor.name,
                    document.getElementById("c") instanceof SVGCircleElement,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "SVGImageElement",
                true,
                "SVGUseElement",
                true,
                "SVGTextElement",
                true,
                "SVGCircleElement",
                true
            ])
        );
    }

    #[test]
    fn created_svg_elements_use_their_own_interface() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const ns = "http://www.w3.org/2000/svg";
                const made = document.createElementNS(ns, "image");
                const rect = document.createElementNS(ns, "rect");
                const defs = document.createElementNS(ns, "defs");
                return [
                    made instanceof SVGImageElement,
                    made instanceof SVGGraphicsElement,
                    rect instanceof SVGRectElement,
                    rect instanceof SVGGeometryElement,
                    defs instanceof SVGDefsElement,
                    Object.getPrototypeOf(defs) === SVGDefsElement.prototype,
                    defs instanceof SVGGraphicsElement,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, true, true, true, true, true, true])
        );
    }

    #[test]
    fn svg_interfaces_share_the_standard_ancestor_chain() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                // Parent interfaces are from SVG and Filter Effects IDL, not
                // inferred from the implementation's own declarations.
                const cases = [
                    ['svg', SVGSVGElement, SVGGraphicsElement],
                    ['g', SVGGElement, SVGGraphicsElement],
                    ['defs', SVGDefsElement, SVGGraphicsElement],
                    ['symbol', SVGSymbolElement, SVGGraphicsElement],
                    ['marker', SVGMarkerElement, SVGElement],
                    ['a', SVGAElement, SVGGraphicsElement],
                    ['switch', SVGSwitchElement, SVGGraphicsElement],
                    ['foreignObject', SVGForeignObjectElement, SVGGraphicsElement],
                    ['title', SVGTitleElement, SVGElement],
                    ['desc', SVGDescElement, SVGElement],
                    ['text', SVGTextElement, SVGTextPositioningElement],
                    ['textPath', SVGTextPathElement, SVGTextContentElement],
                    ['image', SVGImageElement, SVGGraphicsElement],
                    ['use', SVGUseElement, SVGGraphicsElement],
                    ['circle', SVGCircleElement, SVGGeometryElement],
                    ['rect', SVGRectElement, SVGGeometryElement],
                    ['linearGradient', SVGLinearGradientElement, SVGGradientElement],
                    ['feImage', SVGFEImageElement, SVGElement],
                    ['feFlood', SVGFEFloodElement, SVGElement],
                    ['fePointLight', SVGFEPointLightElement, SVGElement],
                    ['feFuncR', SVGFEFuncRElement, SVGComponentTransferFunctionElement],
                ];
                const ns = 'http://www.w3.org/2000/svg';
                const root = document.createElementNS(ns, 'svg');
                root.innerHTML = cases.map(([name]) => `<${name}></${name}>`).join('');
                const mismatches = cases.flatMap(([name, ctor, parent], index) => {
                    const created = document.createElementNS(ns, name);
                    const parsed = root.children[index];
                    return Object.getPrototypeOf(ctor.prototype) === parent.prototype
                        && created instanceof ctor && parsed instanceof ctor
                        && created instanceof parent && parsed instanceof parent
                        ? [] : [name];
                });
                if (Object.getPrototypeOf(SVGGradientElement.prototype) !== SVGElement.prototype)
                    mismatches.push('SVGGradientElement');
                return mismatches;
                })()"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([])
        );
    }

    #[test]
    fn svg_interface_lookup_ignores_html_and_dangerous_keys() {
        // The lookup table is keyed by a page-supplied local name, so a
        // `<constructor>` or `__proto__` element must not resolve to an
        // inherited Object property and be handed back as a constructor.
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const ns = "http://www.w3.org/2000/svg";
                const probe = (name) => {
                    const el = document.createElementNS(ns, name);
                    return el.constructor.name;
                };
                return [
                    probe("constructor"),
                    probe("__proto__"),
                    probe("toString"),
                    probe("hasOwnProperty"),
                    document.createElement("constructor").constructor.name,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["SVGElement", "SVGElement", "SVGElement", "SVGElement", "Element"])
        );
    }

    #[test]
    fn html_lookalike_tags_keep_their_html_interfaces() {
        // A `<text>` or `<image>` in the HTML namespace is not an SVG element,
        // so the new SVG table must not claim it.
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const text = document.createElement("text");
                const image = document.createElement("image");
                const div = document.createElement("div");
                return [
                    text instanceof SVGTextElement,
                    text instanceof Element,
                    image instanceof SVGImageElement,
                    div instanceof SVGElement,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([false, true, false, false]));
    }

    #[test]
    fn foreign_inner_html_and_contextual_fragments_keep_svg_namespace() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let v = rt
            .evaluate(
                "(function(){const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.innerHTML='<linearGradient id=paint></linearGradient>';const range=document.createRange();range.selectNodeContents(svg);const fragment=range.createContextualFragment('<circle></circle>');const circle=fragment.firstElementChild;return [svg.firstElementChild.namespaceURI,svg.firstElementChild.localName,circle.namespaceURI,circle.localName].join('|');})()",
            )
            .unwrap();
        assert_eq!(
            v,
            serde_json::json!(
                "http://www.w3.org/2000/svg|linearGradient|http://www.w3.org/2000/svg|circle"
            )
        );
    }

    #[test]
    fn throwing_custom_element_constructor_marks_upgrade_failed_without_connecting() {
        let mut rt = setup_runtime(
            r#"<html><body><throws-during-upgrade id="target"></throws-during-upgrade></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                let constructorCalls = 0;
                let connectedCalls = 0;
                class ThrowsDuringUpgrade extends HTMLElement {
                    constructor() {
                        super();
                        constructorCalls++;
                        throw new Error("expected constructor failure");
                    }
                    connectedCallback() {
                        connectedCalls++;
                    }
                }
                customElements.define("throws-during-upgrade", ThrowsDuringUpgrade);
                const element = document.getElementById("target");
                customElements.upgrade(document);
                return [
                    constructorCalls,
                    connectedCalls,
                    element.__customUpgradeFailed === true
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([1, 0, true]));
    }

    #[test]
    fn custom_element_attribute_reactions_observe_removal_and_can_restore_the_attribute() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const log = [];
            class RestoreEl extends HTMLElement {
                static get observedAttributes() { return ['mode']; }
                attributeChangedCallback(name, oldValue, newValue) {
                    log.push([oldValue, newValue, this.getAttribute(name)]);
                    if (newValue === null) this.setAttribute(name, 'restored');
                }
            }
            customElements.define('restore-el', RestoreEl);
            const results = [];
            for (const remove of [
                el => el.removeAttribute('mode'),
                el => el.toggleAttribute('mode', false),
                el => el.removeAttributeNS(null, 'mode'),
            ]) {
                const el = document.createElement('restore-el');
                el.setAttribute('mode', 'before');
                log.length = 0;
                remove(el);
                results.push([log.slice(), el.getAttribute('mode'), el.getAttributeNS(null, 'mode')]);
            }
            return results;
        "#).unwrap();
        let expected = serde_json::json!([
            [["before", null, null], [null, "restored", "restored"]], "restored", "restored"
        ]);
        assert_eq!(result, serde_json::json!([expected, expected, expected]));
    }

    #[test]
    fn custom_element_namespace_reactions_observe_updated_attributes_and_style() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const log = [];
            class StyledEl extends HTMLElement {
                static get observedAttributes() { return ['style']; }
                attributeChangedCallback(name, oldValue, newValue) {
                    log.push([newValue, this.getAttribute(name), this.style.color]);
                    if (newValue === null) this.setAttribute('style', 'color: red');
                }
            }
            customElements.define('styled-el', StyledEl);
            const el = document.createElement('styled-el');
            el.setAttribute('style', 'color: blue');
            log.length = 0;
            el.setAttributeNS(null, 'style', 'color: green');
            el.removeAttributeNS(null, 'style');
            return [log, el.getAttribute('style'), el.style.color];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [["color: green", "color: green", "green"], [null, null, ""],
                ["color: red", "color: red", "red"]],
            "color: red", "red"
        ]));
    }

    #[test]
    fn custom_elements_connect_and_upgrade_on_insertion() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const log = [];
                class XEl extends HTMLElement {
                    constructor() { super(); log.push('ctor'); }
                    connectedCallback() {
                        log.push('connected');
                        if (!this.shadowRoot) this.attachShadow({ mode: 'open' });
                    }
                    disconnectedCallback() { log.push('disconnected'); }
                }
                customElements.define('x-el', XEl);
                const created = document.createElement('x-el');
                log.push('created');
                document.body.appendChild(created);
                log.push('appended:' + (created.shadowRoot !== null));
                const holder = document.createElement('div');
                holder.innerHTML = '<x-el></x-el>';
                log.push('parsed:' + (holder.firstChild instanceof XEl));
                document.body.appendChild(holder);
                log.push('inner:' + (holder.firstChild.shadowRoot !== null));
                document.body.innerHTML = '<x-el></x-el>';
                log.push('set:' + (document.body.firstChild instanceof XEl));
                document.body.firstChild.remove();
                return log;
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "ctor", "created", "connected", "appended:true",
                "parsed:false", "ctor", "connected", "inner:true",
                "disconnected", "disconnected", "ctor", "connected", "set:true",
                "disconnected"
            ])
        );
    }

    #[test]
    fn custom_elements_get_reactions_for_moves_and_observed_attributes() {
        let mut rt = setup_runtime(r#"<html><body><a-el id="a" mode="x" other="y"></a-el><p id="p"></p></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                const log = [];
                class AEl extends HTMLElement {
                    static get observedAttributes() { return ['mode']; }
                    attributeChangedCallback(name, oldValue, newValue) {
                        log.push(name + ':' + oldValue + '>' + newValue);
                    }
                    connectedCallback() { log.push('connected'); }
                    disconnectedCallback() { log.push('disconnected'); }
                }
                customElements.define('a-el', AEl);
                const a = document.getElementById('a');
                a.setAttribute('mode', 'y');
                a.setAttribute('other', 'z');
                a.removeAttribute('mode');
                a.removeAttribute('mode');
                document.getElementById('p').appendChild(a);
                const detached = document.createElement('div');
                detached.appendChild(a);
                detached.removeChild(a);
                return log;
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "mode:null>x", "connected", "mode:x>y", "mode:y>null",
                "disconnected", "connected", "disconnected"
            ])
        );
    }

    #[test]
    fn custom_elements_in_a_connected_shadow_tree_connect() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const log = [];
                class InEl extends HTMLElement {
                    connectedCallback() { log.push('inner'); }
                }
                class OutEl extends HTMLElement {
                    connectedCallback() {
                        const root = this.attachShadow({ mode: 'open' });
                        root.innerHTML = '<in-el></in-el>';
                        log.push('outer');
                    }
                }
                customElements.define('in-el', InEl);
                customElements.define('out-el', OutEl);
                const host = document.createElement('out-el');
                document.body.appendChild(host);
                host.shadowRoot.appendChild(document.createElement('in-el'));
                return [log, host.shadowRoot.firstChild instanceof InEl];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([["inner", "outer", "inner"], true]));
    }

    #[test]
    fn throwing_connected_callback_is_reported_not_thrown() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const reported = [];
                globalThis.reportError = (e) => reported.push(e.message);
                class BadEl extends HTMLElement {
                    connectedCallback() { throw new Error('connect failed'); }
                }
                customElements.define('bad-el', BadEl);
                const el = document.createElement('bad-el');
                document.body.appendChild(el);
                return [el.isConnected, reported];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, ["connect failed"]]));
    }

    #[test]
    fn editing_command_detection_reports_unsupported_commands_without_mutation() {
        let mut rt = setup_runtime("<body><p>unchanged</p><iframe></iframe></body>");
        assert_eq!(rt.evaluate(r#"(() => {
            const docs = [document, document.implementation.createHTMLDocument('detached'),
                new DOMParser().parseFromString('<p>parsed</p>', 'text/html')];
            const commands = ['copy', 'cut', 'paste', 'bold', 'obscura-unknown-command'];
            const support = docs.map(doc => commands.map(command => doc.queryCommandSupported(command)));
            const child = document.querySelector('iframe').contentDocument;
            const borrowed = Document.prototype.queryCommandSupported;
            Object.setPrototypeOf(child, Document.prototype);
            Object.defineProperty(child, 'nodeType', { get() { throw new Error('author getter'); } });
            return [support, borrowed.call(child, 'copy'), document.execCommand('copy'),
                document.querySelector('p').textContent];
        })()"#).unwrap(), serde_json::json!([
            [[false, false, false, false, false], [false, false, false, false, false],
                [false, false, false, false, false]], false, false, "unchanged"
        ]));
    }

    #[test]
    fn editing_command_detection_checks_receiver_and_converts_domstring() {
        let mut rt = setup_runtime("<body></body>");
        assert_eq!(rt.evaluate(r#"(() => {
            const hints = [];
            const command = { [Symbol.toPrimitive](hint) { hints.push(hint); return 'unknown'; } };
            const supported = document.queryCommandSupported(command);
            const errorName = action => { try { action(); return null; } catch (e) { return e.name; } };
            const errors = [errorName(() => document.queryCommandSupported()),
                errorName(() => document.queryCommandSupported(Symbol('command'))),
                errorName(() => Document.prototype.queryCommandSupported.call({}, command)),
                errorName(() => Document.prototype.queryCommandSupported.call(Object.create(Document.prototype), command)),
                errorName(() => document.queryCommandSupported({ toString() { throw new RangeError(); } }))];
            return [supported, hints, errors];
        })()"#).unwrap(), serde_json::json!([
            false, ["string"], ["TypeError", "TypeError", "TypeError", "TypeError", "RangeError"]
        ]));
    }

    #[test]
    fn test_document_title() {
        let mut rt = setup_runtime("<html><head><title>Test</title></head><body></body></html>");
        let title = rt.evaluate("document.title").unwrap();
        assert_eq!(title, serde_json::json!("Test"));

        let result = rt
            .evaluate(
                r#"
                (function() {
                  document.title = "A <new> title";
                  return [
                    document.title,
                    document.querySelector("head > title").textContent,
                    document.querySelectorAll("title").length
                  ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["A <new> title", "A <new> title", 1])
        );

        let normalized = rt
            .evaluate(
                r#"
                (function() {
                  document.querySelector("title").textContent = "  live\n\tDOM   title  ";
                  return document.title;
                })()
                "#,
            )
            .unwrap();
        assert_eq!(normalized, serde_json::json!("live DOM title"));
    }

    #[test]
    fn character_data_uses_webidl_ranges_and_rejects_children() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                (function() {
                  const errorName = callback => {
                    try { callback(); return null; } catch (error) { return error.name; }
                  };
                  const data = document.createTextNode("test");
                  data.data = undefined;
                  const undefinedData = data.data;
                  data.data = null;

                  const appended = document.createTextNode("a");
                  appended.appendData(null);
                  const inserted = document.createTextNode("test");
                  inserted.insertData(-0x100000000 + 2, "X");
                  const deleted = document.createTextNode("test");
                  deleted.deleteData(2, -1);
                  const replaced = document.createTextNode("test");
                  replaced.replaceData(2, -1, "yo");
                  const substring = document.createTextNode("test");

                  return [
                    undefinedData, data.data, appended.data, inserted.data,
                    deleted.data, replaced.data,
                    substring.substringData(-0x100000000 + 2, 1),
                    errorName(() => substring.substringData(5, 0)),
                    errorName(() => substring.substringData()),
                    errorName(() => substring.splitText(5)),
                    errorName(() => substring.appendChild(document.createComment("child")))
                  ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "undefined",
                "",
                "anull",
                "teXst",
                "te",
                "teyo",
                "s",
                "IndexSizeError",
                "TypeError",
                "IndexSizeError",
                "HierarchyRequestError"
            ])
        );
    }

    #[test]
    fn node_identity_and_element_id_follow_dom_conversion_rules() {
        let mut rt = setup_runtime(
            r#"<html><body><div id=""></div><div id="null"></div><div id="undefined"></div></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                (function() {
                  const node = document.body.firstChild;
                  return [
                    node.contains(node),
                    node.isSameNode(null),
                    document.getElementById("") === null,
                    document.getElementById(null)?.id,
                    document.getElementById(undefined)?.id
                  ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, false, true, "null", "undefined"])
        );
    }

    #[test]
    fn document_title_setter_creates_missing_title_element() {
        let mut rt = setup_runtime("<html><body><main>content</main></body></html>");
        let result = rt
            .evaluate(
                r#"
                (function() {
                  document.title = "Created";
                  return [
                    document.title,
                    document.head.tagName,
                    document.head.firstElementChild.tagName,
                    document.head.firstElementChild.textContent,
                    document.documentElement.firstElementChild === document.head
                  ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["Created", "HEAD", "TITLE", "Created", true])
        );

        let detached = rt
            .evaluate(
                r#"
                (function() {
                  const doc = document.implementation.createHTMLDocument();
                  doc.title = "  Detached   title  ";
                  return [doc.title, doc.querySelector("title").textContent, doc.referrer];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            detached,
            serde_json::json!(["Detached title", "  Detached   title  ", ""])
        );
    }

    #[test]
    fn document_referrer_has_explicit_navigation_state() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(
            rt.evaluate("document.referrer").unwrap(),
            serde_json::json!("")
        );

        rt.set_referrer("https://source.example/path?q=1");
        assert_eq!(
            rt.evaluate("document.referrer").unwrap(),
            serde_json::json!("https://source.example/path?q=1")
        );
    }

    #[test]
    fn global_window_has_browser_constructor_identity() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                "return [window === self, self.constructor === Window,\
                         window instanceof Window, self.document === document,\
                         self.location === location, self.history === history,\
                         self.navigator === navigator];",
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, true, true, true, true, true, true])
        );
    }

    #[test]
    fn window_named_access_exposes_ids_and_eligible_names() {
        let mut rt = setup_runtime(
            r#"<html><body>
                <script id="payload" type="application/json">{"ready":true}</script>
                <div id="duplicate"></div><span id="duplicate"></span>
                <form name="login"></form><img name="hero">
                <div name="not-exposed"></div>
            </body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                return [
                    window.payload === document.getElementById("payload"),
                    window.payload.text,
                    window.duplicate instanceof HTMLCollection,
                    window.duplicate.length,
                    window.login === document.querySelector("form"),
                    window.hero === document.querySelector("img"),
                    typeof window["not-exposed"]
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, "{\"ready\":true}", true, 2, true, true, "undefined"])
        );
    }

    #[test]
    fn window_named_access_uses_native_attributes_not_page_overrides() {
        let mut rt = setup_runtime("<html><body><div id='nativeName'></div></body></html>");
        let result = rt.evaluate(r#"
            const element = document.getElementById('nativeName');
            let calls = 0;
            element.getAttribute = () => { calls++; return null; };
            const documentQuery = document.querySelectorAll;
            document.querySelectorAll = function(selector) {
                if (selector.includes('[id]')) { calls++; return []; }
                return documentQuery.call(this,selector);
            };
            const existing = window.nativeName === element;
            const subtree = document.createElement('section');
            subtree.innerHTML = '<span id="insertedName"></span><img name="insertedImage">';
            const span = subtree.firstElementChild;
            const image = subtree.lastElementChild;
            const elementQuery = subtree.querySelectorAll;
            subtree.querySelectorAll = function(selector) {
                if (selector.includes('[id]')) { calls++; return []; }
                return elementQuery.call(this,selector);
            };
            span.getAttribute = image.getAttribute = () => { calls++; return null; };
            document.body.appendChild(subtree);
            const inserted = window.insertedName === span && window.insertedImage === image;
            subtree.remove();
            return [existing, inserted, 'insertedName' in window, 'insertedImage' in window, calls];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([true,true,false,false,0]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn inserting_a_frame_before_itself_retires_its_old_document_without_reordering() {
        let mut rt = setup_runtime("<html><body><b id='before'></b><iframe id='frame'></iframe><b id='after'></b></body></html>");
        rt.execute_script("frame-self-insertion", r#"
            const frame = document.getElementById('frame');
            const oldWindow = frame.contentWindow;
            globalThis.oldSignal = oldWindow.AbortSignal.timeout(5);
            globalThis.oldCalls = 0;
            oldWindow.setTimeout(() => oldCalls++,5);
            globalThis.sameNode = document.body.insertBefore(frame,frame) === frame;
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("return {aborted:oldSignal.aborted, calls:oldCalls, sameNode, order:Array.from(document.body.children,node=>node.id)};").unwrap(),
            serde_json::json!({"aborted":false,"calls":0,"sameNode":true,
                "order":["before","frame","after"]}));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn child_frame_timers_do_not_run_after_their_document_is_destroyed() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("frame-timer-lifetime", r#"
            const retained = document.createElement('iframe');
            document.body.appendChild(retained);
            globalThis.retainedSignal = retained.contentWindow.AbortSignal.timeout(5);
            globalThis.retainedTimers = 0;
            retained.contentWindow.setTimeout(() => retainedTimers++,5);
            globalThis.removedSignals = [];
            globalThis.removedTimers = Array(8).fill(0);
            globalThis.freshFrameTimers = [0,0,0];
            globalThis.freshFrameWindows = [];
            for (let i=0; i<8; i++) {
                const container = document.createElement(i===2 ? 'iframe' : 'div');
                document.body.appendChild(container);
                const frame = (i===2 ? container.contentDocument : document).createElement('iframe');
                (i===2 ? container.contentDocument.body : container).appendChild(frame);
                const oldWindow = frame.contentWindow;
                removedSignals.push(oldWindow.AbortSignal.timeout(5));
                oldWindow.setTimeout(() => removedTimers[i]++,5);
                if (i===0) frame.remove();
                if (i===1 || i===2) container.remove();
                if (i===3) container.innerHTML = '<p>replacement</p>';
                if (i===4) container.textContent = 'replacement';
                if (i===5) { frame.remove(); container.appendChild(frame); }
                if (i===6) document.body.appendChild(frame);
                if (i===7) container.appendChild(frame);
                if (i>=5) {
                    freshFrameWindows.push(frame.contentWindow !== oldWindow);
                    frame.contentWindow.setTimeout(() => freshFrameTimers[i-5]++,5);
                }
            }
        "#).unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        let result = rt.evaluate("return {retainedSignal:retainedSignal.aborted, retainedTimers, \
            removedSignals:removedSignals.map(signal=>signal.aborted), removedTimers, \
            freshFrameTimers, freshFrameWindows};").unwrap();
        assert_eq!(result, serde_json::json!({
            "retainedSignal":true, "retainedTimers":1,
            "removedSignals":[false,false,false,false,false,false,false,false],
            "removedTimers":[0,0,0,0,0,0,0,0],
            "freshFrameTimers":[1,1,1], "freshFrameWindows":[true,true,true],
        }));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn destroying_a_child_document_cancels_its_pending_native_sleeps() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("frame-pending-timers", r#"
            const frame = document.createElement('iframe');
            document.body.appendChild(frame);
            globalThis.oldFrame = frame.contentWindow;
            globalThis.timerCalls = 0;
            oldFrame.setTimeout(() => timerCalls++,60000);
            oldFrame.setInterval(() => timerCalls++,60000);
            frame.remove();
        "#).unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(1),rt.run_event_loop())
            .await.expect("Destroyed frame timers must not keep the native event loop alive")
            .unwrap();
        assert_eq!(rt.evaluate("return timerCalls;").unwrap().as_f64(),Some(0.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn child_frame_teardown_does_not_panic_or_cancel_siblings_when_the_owner_is_borrowed() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("frame-owner-contention", r#"
            globalThis.frameCalls = [0,0];
            for (let i=0;i<2;i++) {
                const frame = document.createElement('iframe');
                document.body.appendChild(frame);
                frame.contentWindow.setTimeout(() => frameCalls[i]++,5);
            }
        "#).unwrap();
        let pending = rt.take_pending_frames().remove(0);
        let doomed = crate::frame::FrameRealm::new(&mut rt,pending.frame_id,
            pending.parent_frame_id,&pending.url,&pending.html).unwrap();
        let owner = rt.state.clone();
        let borrowed = owner.borrow_mut();
        drop(doomed);
        drop(borrowed);
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(rt.evaluate("return frameCalls;").unwrap(),serde_json::json!([0,1]));
    }

    #[test]
    fn window_named_access_distinguishes_iframe_ids_from_child_context_names() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(() => {
            const byId = document.createElement('iframe'); byId.id = 'idOnlyFrame';
            const collision = document.createElement('div'); collision.id = 'namedContext';
            const first = document.createElement('iframe');
            first.id = 'namedFrameId'; first.name = 'namedContext';
            const second = document.createElement('iframe'); second.name = 'namedContext';
            document.body.append(byId,collision,first,second);
            const results = [window.idOnlyFrame===byId, window.namedFrameId===first,
                window.namedContext===first.contentWindow];
            first.remove();
            results.push(window.namedContext===second.contentWindow);
            second.remove();
            results.push(window.namedContext===collision);
            byId.name = 'idOnlyFrame';
            results.push(window.idOnlyFrame===byId && byId.contentWindow.name==='');
            byId.removeAttribute('name');
            results.push(window.idOnlyFrame===byId);
            const duplicate = document.createElement('div'); duplicate.id = 'idOnlyFrame';
            document.body.appendChild(duplicate);
            results.push(window.idOnlyFrame instanceof HTMLCollection,
                window.idOnlyFrame.length===2, window.idOnlyFrame[0]===byId);
            return results;
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([true,true,true,true,true,true,true,true,true,true]));
    }

    #[test]
    fn window_named_access_tracks_dynamic_ids_and_fragment_parsing() {
        let mut rt = setup_runtime("<html><body><div id='host'></div></body></html>");
        let result = rt
            .evaluate(
                r#"
                const made = document.createElement("section");
                made.id = "dynamicName";
                const detachedIdAbsent = !("dynamicName" in window);
                document.body.appendChild(made);
                const first = window.dynamicName === made;
                made.id = "renamedDynamic";
                const renamed = !("dynamicName" in window)
                    && window.renamedDynamic === made;
                document.body.removeChild(made);
                const removed = !("renamedDynamic" in window);
                document.body.appendChild(made);
                const reattached = window.renamedDynamic === made;
                document.getElementById("host").innerHTML =
                    "<script id='parsedName'>payload</script>";
                const parsed = window.parsedName === document.getElementById("parsedName")
                    && window.parsedName.text === "payload";
                document.getElementById("host").innerHTML = "";
                const subtree = document.createElement("div");
                subtree.innerHTML = "<svg><path id='nestedSvg' name='svgName'></path></svg>";
                const detachedNestedAbsent = !("nestedSvg" in window);
                document.body.appendChild(subtree);
                const nested = window.nestedSvg === subtree.querySelector("path")
                    && typeof window.svgName === "undefined";
                document.body.removeChild(subtree);
                const nestedRemoved = !("nestedSvg" in window);
                document.body.appendChild(subtree);
                const shadowHost = document.createElement("div");
                const shadowRoot = shadowHost.attachShadow({ mode: "open" });
                const shadowChild = document.createElement("span");
                shadowChild.id = "shadowOnly";
                shadowRoot.appendChild(shadowChild);
                document.body.appendChild(shadowHost);
                const originalFetch = window.fetch;
                const collision = document.createElement("div");
                collision.id = "fetch";
                document.body.appendChild(collision);
                document.body.removeChild(collision);
                return [
                    detachedIdAbsent,
                    first,
                    renamed,
                    removed,
                    reattached,
                    parsed,
                    !("parsedName" in window),
                    detachedNestedAbsent,
                    nested,
                    nestedRemoved,
                    window.nestedSvg === subtree.querySelector("path"),
                    !("shadowOnly" in window),
                    window.fetch === originalFetch
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true, true, true, true, true, true, true, true, true, true, true, true, true
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn explicit_viewport_is_distinct_from_fingerprinted_screen() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(1024.0, 768.0);
        rt.run_page_init();
        let result = rt
            .evaluate(
                "return [innerWidth, innerHeight, visualViewport.width,\
                         visualViewport.height, screen.width > 0, screen.height > 0];",
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([1024, 768, 1024, 768, true, true])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn screen_override_is_independent_live_and_preserves_screen_identity() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(1024.0, 768.0);
        rt.run_page_init();
        rt.execute_script(
            "remember-screen",
            "globalThis.__screenBefore = screen;\
             globalThis.__screenSizeBefore = [screen.width, screen.height];",
        )
        .unwrap();

        rt.set_screen_size_override(Some((1440.0, 900.0)), true);
        assert_eq!(
            rt.evaluate(
                "[innerWidth, innerHeight, screen.width, screen.height,\
                  screen.availWidth, screen.availHeight, screen === __screenBefore]"
            )
            .unwrap(),
            serde_json::json!([1024, 768, 1440, 900, 1440, 900, true])
        );

        rt.set_screen_size_override(None, false);
        assert_eq!(
            rt.evaluate(
                "[innerWidth, innerHeight, screen.width === __screenSizeBefore[0],\
                  screen.height === __screenSizeBefore[1],\
                  screen.availHeight === screen.height - 40,\
                  screen === __screenBefore]"
            )
            .unwrap(),
            serde_json::json!([1024, 768, true, true, true, true])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn match_media_evaluates_query_lists_conjunctions_ranges_and_orientation() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(1280.0, 720.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                return [
                    matchMedia("(min-width: 1024px) and (min-height: 700px)").matches,
                    matchMedia("(min-width: 1024px) and (min-height: 900px)").matches,
                    matchMedia("(max-width: 600px), screen and (orientation: landscape)").matches,
                    matchMedia("not print").matches,
                    matchMedia("not screen").matches,
                    matchMedia("only screen and (width: 1280px) and (height = 720px)").matches,
                    matchMedia("(1000px <= width < 1400px) and (height > 700px)").matches,
                    matchMedia("(orientation: portrait)").matches,
                    matchMedia("(prefers-color-scheme: light) and (pointer: fine) and (hover: hover)").matches,
                    matchMedia("(obscura-unknown-feature: yes)").matches
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true, false, true, true, false, true, true, false, true, false
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn match_media_matches_are_live_across_viewport_resizes() {
        let dom = parse_html("<html><body></body></html>");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(900.0, 600.0);
        rt.run_page_init();
        assert_eq!(
            rt.evaluate(
                r#"
                return [
                    (globalThis.__wideAndShort = matchMedia(
                        "(min-width: 800px) and (max-height: 700px)"
                    )).matches,
                    (globalThis.__portrait = matchMedia(
                        "(orientation: portrait)"
                    )).matches
                ];
                "#,
            )
            .unwrap(),
            serde_json::json!([true, false])
        );

        rt.set_viewport(600.0, 900.0);
        assert_eq!(
            rt.evaluate(
                "return [__wideAndShort.matches, __portrait.matches,\
                         matchMedia('(max-width: 600px), print').matches];",
            )
            .unwrap(),
            serde_json::json!([false, true, true])
        );
    }

    #[test]
    fn computed_style_access_does_not_get_shadowed_by_inline_style_proxy() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="box" style="opacity:.5;width:40px"></div></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const box = document.getElementById("box");
                const computed = getComputedStyle(box);
                return [
                    computed.display,
                    computed.visibility,
                    computed.opacity,
                    computed.width,
                    computed.getPropertyValue("display"),
                    computed.getPropertyValue("background-color")
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                "block",
                "visible",
                "0.5",
                "40px",
                "block",
                "rgba(0, 0, 0, 0)"
            ])
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn computed_style_exposes_generated_pseudo_content() {
        let mut rt = setup_runtime(
            r#"<html><head><style>label::before { content: "❯"; }</style></head>
                <body><label id="toggle">Mark all as complete</label></body></html>"#,
        );
        assert_eq!(
            rt.evaluate(
                "const style = getComputedStyle(document.getElementById('toggle'), '::before');\
                 return [style.content, style.display]"
            ).unwrap(),
            serde_json::json!(["\"❯\"", "inline"])
        );
    }

    #[test]
    fn non_bubbling_events_reach_capture_listeners_on_ancestors() {
        let mut rt = setup_runtime("<html><body><input id='editor'></body></html>");
        assert_eq!(
            rt.evaluate(
                "let seen = [];\
                 document.addEventListener('blur', event => seen.push([event.target.id, event.eventPhase]), true);\
                 document.getElementById('editor').dispatchEvent(new FocusEvent('blur'));\
                 return seen"
            ).unwrap(),
            serde_json::json!([["editor", 1]])
        );
    }

    #[test]
    fn dom_events_only_reach_window_through_document() {
        let mut rt = setup_runtime("<html><head></head><body></body></html>");
        assert_eq!(
            rt.evaluate(
                "const seen = [];\
                 window.addEventListener('load', () => seen.push('window-capture'), true);\
                 window.addEventListener('click', () => seen.push('window-click-capture'), true);\
                 document.addEventListener('load', () => seen.push('document-capture'), true);\
                 document.addEventListener('load', () => seen.push('document-bubble'));\
                 const script = document.createElement('script');\
                 script.addEventListener('load', () => seen.push('script'));\
                 document.head.appendChild(script);\
                 script.dispatchEvent(new Event('load'));\
                 script.dispatchEvent(new Event('click'));\
                 script.remove();\
                 script.dispatchEvent(new Event('load'));\
                 script.dispatchEvent(new Event('click'));\
                 return seen"
            )
            .unwrap(),
            serde_json::json!([
                "document-capture",
                "script",
                "window-click-capture",
                "script"
            ])
        );
    }

    #[test]
    fn elements_have_host_object_brands_for_plain_object_guards() {
        let mut rt = setup_runtime("<html><body><div id='carousel'></div></body></html>");
        assert_eq!(
            rt.evaluate(
                "const element = document.getElementById('carousel');\
                 const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\
                 const isPlainObject = value => typeof value === 'object' && value !== null\
                     && value.constructor\
                     && Object.prototype.toString.call(value).slice(8, -1) === 'Object';\
                 const target = {};\
                 const source = { element };\
                 target.element = isPlainObject(source.element) ? {} : source.element;\
                 return [Object.prototype.toString.call(element),\
                     Object.prototype.toString.call(svg), isPlainObject(element),\
                     target.element === element]"
            )
            .unwrap(),
            serde_json::json!(["[object HTMLDivElement]", "[object SVGElement]", false, true])
        );
    }

    #[test]
    fn iframe_brand_does_not_match_other_elements() {
        // style-loader resolves its insert target with
        // `found instanceof HTMLIFrameElement ? found.contentDocument.head : found`;
        // with the interface aliased to Element, <head> took the iframe branch.
        let mut rt = setup_runtime(
            r#"<html><head></head><body><iframe id="frame"></iframe><div id="plain"></div></body></html>"#,
        );
        let result = rt.evaluate(r#"
            const frame = document.getElementById('frame');
            const created = document.createElement('iframe');
            const nodes = [document.head, document.documentElement, document.body,
                document.getElementById('plain'), document.createElement('div'),
                document.createElementNS('urn:test', 'IFRAME')];
            return [frame instanceof HTMLIFrameElement, created instanceof HTMLIFrameElement,
                frame.cloneNode() instanceof HTMLIFrameElement,
                frame instanceof HTMLElement && frame instanceof Element,
                nodes.map(node => node instanceof HTMLIFrameElement)];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            true, true, true, true,
            [false, false, false, false, false, false]
        ]));
    }

    #[test]
    fn list_element_brands_survive_parsing_creation_and_cloning() {
        let mut rt = setup_runtime("<html><body><ol><li>item</li></ol></body></html>");
        let result = rt.evaluate(r#"
            return [['ol', HTMLOListElement], ['li', HTMLLIElement]].map(([tag, C]) => {
                const parsed = document.querySelector(tag);
                const created = document.createElement(tag);
                const nodes = [parsed, created, parsed.cloneNode(true), created.cloneNode(),
                    document.importNode(parsed, true)];
                return [nodes.map(node => node instanceof C && node instanceof HTMLElement
                    && node.constructor === C), Object.prototype.toString.call(created),
                    [document.createElement('div'), document.createElement('ul'),
                        document.createElementNS('urn:test', tag),
                        document.createElementNS('urn:test', tag.toUpperCase()).cloneNode(),
                        document.createElementNS('http://www.w3.org/2000/svg', tag)]
                        .map(node => node instanceof C)];
            });
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [[true, true, true, true, true], "[object HTMLOListElement]",
                [false, false, false, false, false]],
            [[true, true, true, true, true], "[object HTMLLIElement]",
                [false, false, false, false, false]]
        ]));
    }

    #[test]
    fn list_element_properties_reflect_boolean_and_string_attributes() {
        let mut rt = setup_runtime(
            "<html><body><ol reversed start='-2' type='A'><li value='-4'>item</li></ol></body></html>",
        );
        let result = rt.evaluate(r#"
            const parsed = document.querySelector('ol');
            const list = document.createElement('ol');
            const initial = [parsed.reversed, parsed.start, parsed.type,
                document.querySelector('li').value, list.reversed, list.start, list.type];
            const states = [];
            list.reversed = true;
            states.push([list.reversed, list.getAttribute('reversed')]);
            list.reversed = false;
            states.push([list.reversed, list.getAttribute('reversed')]);
            list.setAttribute('reversed', 'false');
            states.push([list.reversed, list.getAttribute('reversed')]);
            list.removeAttribute('reversed');
            states.push([list.reversed, list.getAttribute('reversed')]);
            list.type = 'i';
            const written = [list.type, list.getAttribute('type')];
            list.setAttribute('type', 'invalid');
            const changed = list.type;
            list.removeAttribute('type');
            const removed = list.type;
            list.type = null;
            return [initial, states, written, changed, removed, list.getAttribute('type'),
                'reversed' in document.createElement('div'),
                'start' in document.createElement('li'),
                ['reversed', 'start', 'type'].every(name =>
                    Object.getOwnPropertyDescriptor(HTMLOListElement.prototype, name)?.enumerable),
                Object.getOwnPropertyDescriptor(HTMLLIElement.prototype, 'value')?.enumerable];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [true, -2, "A", -4, false, 1, ""],
            [[true, ""], [false, null], [true, "false"], [false, null]],
            ["i", "i"], "invalid", "", "null", false, false,
            true, true
        ]));
    }

    #[test]
    fn list_element_integer_reflection_defaults_parses_and_wraps() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const list = document.createElement('ol');
            const item = document.createElement('li');
            const attributes = [null, '', 'invalid', '  +12tail', '-3.8',
                '2147483648', '-2147483649', '99999999999999999999', '0x10'].map(value => {
                if (value === null) { list.removeAttribute('start'); item.removeAttribute('value'); }
                else { list.setAttribute('start', value); item.setAttribute('value', value); }
                return [list.start, item.value];
            });
            const setters = [4294967297, 2147483648, -2147483649, NaN, Infinity,
                -0, 3.8, null].map(value => {
                list.start = value;
                item.value = value;
                return [list.start, list.getAttribute('start'), item.value, item.getAttribute('value')];
            });
            const bigints = [[list, 'start'], [item, 'value'], [list, 'tabIndex']].map(([node, key]) => {
                try { node[key] = 1n; return 'accepted'; } catch (error) { return error.name; }
            });
            return [attributes, setters, bigints];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [[1, 0], [1, 0], [1, 0], [12, 12], [-3, -3], [1, 0], [1, 0], [1, 0], [0, 0]],
            [[1, "1", 1, "1"], [-2147483648i64, "-2147483648", -2147483648i64, "-2147483648"],
                [2147483647, "2147483647", 2147483647, "2147483647"], [0, "0", 0, "0"],
                [0, "0", 0, "0"], [0, "0", 0, "0"], [3, "3", 3, "3"], [0, "0", 0, "0"]],
            ["TypeError", "TypeError", "TypeError"]
        ]));
    }

    #[test]
    fn meta_http_equiv_reflection_supports_snapshot_csp_filtering() {
        let mut rt = setup_runtime(
            r#"<html><head><meta id="plain" charset="utf-8">
                <meta id="policy" http-equiv="Content-Security-Policy" content="default-src 'self'">
            </head><body></body></html>"#,
        );
        let result = rt.evaluate(r#"
            const plain = document.getElementById('plain');
            const policy = document.getElementById('policy');
            const kept = Array.from(document.querySelectorAll('meta'))
                .filter(node => node.httpEquiv.toLowerCase() !== 'content-security-policy')
                .map(node => node.id);
            const created = document.createElement('meta');
            created.httpEquiv = 'Refresh';
            const cloned = created.cloneNode();
            const initial = [plain.httpEquiv, policy.httpEquiv,
                created.getAttribute('http-equiv'), cloned.httpEquiv];
            created.setAttribute('http-equiv', 'Content-Type');
            const changed = created.httpEquiv;
            created.removeAttribute('http-equiv');
            const removed = created.httpEquiv;
            created.httpEquiv = null;
            return [kept, initial, changed, removed, created.getAttribute('http-equiv'),
                plain instanceof HTMLMetaElement, cloned instanceof HTMLMetaElement,
                document.createElement('div') instanceof HTMLMetaElement,
                document.createElementNS('urn:test', 'META').cloneNode() instanceof HTMLMetaElement];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            ["plain"], ["", "Content-Security-Policy", "Refresh", "Refresh"],
            "Content-Type", "", "null", true, true, false, false
        ]));
    }

    #[test]
    fn input_brand_separates_button_labels_and_preserves_native_setters() {
        let mut rt = setup_runtime(
            r#"<html><body><button id="button" type="button">Visible label</button>
                <input id="input" type="button" value="Input label"><div id="other"></div>
            </body></html>"#,
        );
        let result = rt.evaluate(r#"
            const button = document.getElementById('button');
            const input = document.getElementById('input');
            const created = document.createElement('input');
            const brands = [input, button, document.getElementById('other'), created,
                document.createElementNS('http://www.w3.org/1999/xhtml', 'x:input'),
                document.createElementNS('urn:test', 'INPUT').cloneNode(), input.cloneNode()]
                .map(node => node instanceof HTMLInputElement);
            const label = node => node instanceof HTMLInputElement && node.type === 'button'
                ? node.value : node.textContent;
            const labels = [label(button), label(input)];
            const value = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
            const checked = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked');
            value.set.call(created, 'edited');
            checked.set.call(created, true);
            return [brands, labels, value.get.call(created), checked.get.call(created)];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [true, false, false, true, true, false, true],
            ["Visible label", "Input label"], "edited", true
        ]));
    }

    #[test]
    fn readonly_controls_reflect_boolean_attributes_without_polluting_other_elements() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const enumerated = [];
            const states = ['input', 'textarea'].map(tag => {
                const field = document.createElement(tag);
                const values = [[field.readOnly, field.getAttribute('readonly')]];
                field.readOnly = true;
                values.push([field.readOnly, field.getAttribute('readonly')]);
                field.readOnly = false;
                values.push([field.readOnly, field.getAttribute('readonly')]);
                field.setAttribute('readonly', 'false');
                values.push([field.readOnly, field.getAttribute('readonly')]);
                field.removeAttribute('readonly');
                values.push([field.readOnly, field.getAttribute('readonly')]);
                for (const key in field) if (key === 'readOnly') enumerated.push(field[key]);
                return values;
            });
            return [states, 'readOnly' in document.createElement('div'), enumerated];
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [
                [[false, null], [true, ""], [false, null], [true, "false"], [false, null]],
                [[false, null], [true, ""], [false, null], [true, "false"], [false, null]]
            ], false, [false, false]
        ]));
    }

    #[test]
    fn hyperlink_content_attributes_reflect_through_the_idl_surface() {
        let mut rt = setup_runtime(
            r#"<html><body>
                <a id="locale" hreflang="en-US" rel="alternate"
                   target="_blank" download="guide.pdf"
                   ping="/audit" referrerpolicy="no-referrer">English</a>
            </body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const link = document.getElementById("locale");
                const initial = [
                    link.hreflang, link.rel, link.target, link.download,
                    link.ping, link.referrerPolicy,
                    link.hreflang.split("-")[1]
                ];
                link.hreflang = "de-DE";
                link.referrerPolicy = "origin";
                return [
                    initial,
                    link.getAttribute("hreflang"),
                    link.getAttribute("referrerpolicy")
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [
                    "en-US",
                    "alternate",
                    "_blank",
                    "guide.pdf",
                    "/audit",
                    "no-referrer",
                    "US"
                ],
                "de-DE",
                "origin"
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn ordinary_inline_keeps_computed_sizes_but_uses_content_geometry() {
        let dom = parse_html(
            r#"<html><head><style>
                html,body,p { margin:0 }
                #host { width:300px; font-size:16px; line-height:20px }
                #token {
                    position:relative;
                    width:100%; height:100px;
                    min-width:100%; min-height:100px;
                    max-width:100%; max-height:100px;
                    padding:0 5px; background:red
                }
                #after { position:relative }
                #atomic {
                    display:inline-block; box-sizing:border-box;
                    width:80px; height:30px; padding:0; border:0
                }
                #replaced {
                    display:inline; box-sizing:border-box;
                    width:80px; height:30px; min-width:0; min-height:0;
                    max-width:none; max-height:none; padding:0; border:0
                }
                #items { display:flex }
                #item {
                    display:inline; box-sizing:border-box; flex:none;
                    width:90px; height:25px; padding:0; border:0
                }
            </style></head><body>
                <p id="host">A <code id="token">token</code> <span id="after">after</span></p>
                <span id="atomic"></span>
                <input id="replaced">
                <div id="items"><span id="item"></span></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 240.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const token = document.getElementById("token");
                const after = document.getElementById("after");
                const computed = getComputedStyle(token);
                const rect = token.getBoundingClientRect();
                const afterRect = after.getBoundingClientRect();
                const atomic = document.getElementById("atomic").getBoundingClientRect();
                const replaced = document.getElementById("replaced").getBoundingClientRect();
                const item = document.getElementById("item").getBoundingClientRect();
                return {
                    computed: [
                        computed.width, computed.height,
                        computed.minWidth, computed.minHeight,
                        computed.maxWidth, computed.maxHeight
                    ],
                    rect: [rect.x, rect.y, rect.width, rect.height],
                    after: [afterRect.x, afterRect.y],
                    client: [token.clientWidth, token.clientHeight],
                    clientRects: Array.from(token.getClientRects(), r => [
                        r.x, r.y, r.width, r.height
                    ]),
                    atomic: [atomic.width, atomic.height],
                    replaced: [replaced.width, replaced.height],
                    item: [item.width, item.height, getComputedStyle(item).display]
                };
                "#,
            )
            .unwrap();

        assert_eq!(
            result["computed"],
            serde_json::json!(["100%", "100px", "100%", "100px", "100%", "100px"])
        );
        let rect = result["rect"].as_array().unwrap();
        let token_x = rect[0].as_f64().unwrap();
        let token_y = rect[1].as_f64().unwrap();
        let token_width = rect[2].as_f64().unwrap();
        let token_height = rect[3].as_f64().unwrap();
        assert!(
            token_width > 20.0 && token_width < 100.0,
            "ordinary inline should hug text and padding: {rect:?}"
        );
        assert!(
            token_height < 40.0,
            "ignored block size leaked into geometry"
        );
        assert_eq!(result["client"], serde_json::json!([0, 0]));
        let client_rects = result["clientRects"].as_array().unwrap();
        assert_eq!(client_rects.len(), 1);
        let client_rect = client_rects[0].as_array().unwrap();
        for (actual, expected) in client_rect
            .iter()
            .map(|value| value.as_f64().unwrap())
            .zip([token_x, token_y, token_width, token_height])
        {
            assert!(
                (actual - expected).abs() < 0.001,
                "getClientRects must expose the renderer's inline fragments"
            );
        }
        let after = result["after"].as_array().unwrap();
        assert!(after[0].as_f64().unwrap() >= token_x + token_width - 0.01);
        assert!((after[1].as_f64().unwrap() - token_y).abs() < 0.01);
        assert_eq!(result["atomic"], serde_json::json!([80, 30]));
        assert_eq!(result["replaced"], serde_json::json!([80, 30]));
        assert_eq!(result["item"], serde_json::json!([90, 25, "block"]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_refreshes_after_viewport_changes_without_dom_mutation() {
        let mut rt = setup_runtime(r#"<style>
            body { margin:0 }
            #box { width:50vw; height:25vh; color:rgb(12,34,56) }
            @media(max-width:250px) { #box { color:rgb(78,90,12) } }
        </style><div id=box></div>"#);
        rt.set_viewport(300.0, 80.0);
        assert_eq!(rt.evaluate(r#"(() => {
            globalThis.savedStyle = getComputedStyle(document.getElementById('box'));
            return [savedStyle.width, savedStyle.height, savedStyle.color];
        })()"#).unwrap(), serde_json::json!(["150px", "20px", "rgb(12, 34, 56)"]));
        rt.set_viewport(200.0, 120.0);
        assert_eq!(rt.evaluate(r#"(() => {
            const fresh = getComputedStyle(document.getElementById('box'));
            return [[savedStyle.width, savedStyle.height, savedStyle.color],
                [fresh.width, fresh.height, fresh.color]];
        })()"#).unwrap(), serde_json::json!([
            ["100px", "30px", "rgb(78, 90, 12)"],
            ["100px", "30px", "rgb(78, 90, 12)"]
        ]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_animation_only_reads_reuse_the_prepared_frame() {
        let mut rt = setup_runtime(r#"<!doctype html><style>
            @keyframes move { to { transform:translateX(20px) } }
            #box { width:20px; height:20px; color:blue; animation:move 1s linear infinite }
        </style><div id=box></div>"#);
        rt.set_viewport(100.0, 100.0);
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(0.0)));
        assert_eq!(rt.evaluate("document.getElementById('box').getBoundingClientRect().width").unwrap(),
            serde_json::json!(20.0));
        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(500);
        assert_eq!(rt.evaluate(r#"(() => {
            const style = getComputedStyle(document.getElementById('box'));
            return [style.display, style.color];
        })()"#).unwrap(), serde_json::json!(["block", "rgb(0, 0, 255)"]));
        let state = rt.state.borrow();
        assert!(state.style_query_cache.is_none(),
            "animation-only reads must not duplicate an existing retained style graph");
        assert_eq!(state.prepared_render.as_ref().unwrap().animation_sample(), state.animation_sample);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_sibling_reads_do_not_repeat_the_ancestor_cascade() {
        let variables = (0..2500).map(|i| format!("--token-{i}:{i}px;"))
            .collect::<String>();
        let mut rt = setup_runtime(&format!(r#"<!doctype html><style>
            body {{ {variables} color:rgb(12,34,56) }}
            .row {{ display:block; width:var(--token-80); height:1px }}
            body[data-active=yes] {{ color:rgb(78,90,12) }}
        </style><body><main><section>{}</section></main></body>"#,
            "<div class=row></div>".repeat(1024)));
        // Prime the compiled stylesheet, then leave layout damage pending.
        rt.evaluate("document.body.getBoundingClientRect().width").unwrap();
        let started = std::time::Instant::now();
        assert_eq!(rt.evaluate(r#"(() => {
            let matched = 0;
            for (const row of document.querySelectorAll('.row')) {
                const style = getComputedStyle(row);
                matched += style.display === 'block' && style.color === 'rgb(12, 34, 56)';
            }
            return matched;
        })()"#).unwrap(), serde_json::json!(1024.0));
        assert!(started.elapsed() < std::time::Duration::from_secs(1),
            "style-only reads serialized the full CSS variable environment: {:?}", started.elapsed());
        let started = std::time::Instant::now();
        assert_eq!(rt.evaluate(r#"(() => {
            document.body.setAttribute('data-active', 'yes');
            let matched = 0;
            for (const row of document.querySelectorAll('.row')) {
                const style = getComputedStyle(row);
                matched += style.display === 'block' && style.color === 'rgb(78, 90, 12)';
            }
            return matched;
        })()"#).unwrap(), serde_json::json!(1024.0));
        assert!(started.elapsed() < std::time::Duration::from_secs(1),
            "sibling style reads repeated their large inherited cascade: {:?}", started.elapsed());
        assert!(!rt.state.borrow().pending_style_mutations.is_empty());
        assert_eq!(rt.evaluate("getComputedStyle(document.querySelector('.row')).width").unwrap(),
            serde_json::json!("80px"));
        assert_eq!(rt.evaluate(r#"(() => {
            const style = getComputedStyle(document.querySelector('.row'));
            return [style.getPropertyValue('--token-80'), style.length > 2500];
        })()"#).unwrap(), serde_json::json!(["80px", true]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn non_geometric_style_cache_observes_mutations_between_sibling_reads() {
        let mut rt = setup_runtime(r#"<!doctype html><style>
            body { --tone:blue; color:var(--tone) }
            body[data-active=yes] { --tone:red }
            section { display:flex }
            .row { display:inline }
        </style><body><section><span class=row id=first></span>
            <span class=row id=second></span></section></body>"#);
        rt.evaluate("document.body.getBoundingClientRect().width").unwrap();
        assert_eq!(rt.evaluate(r#"(() => {
            const first = document.getElementById('first');
            const second = document.getElementById('second');
            document.body.setAttribute('data-active', 'yes');
            const before = getComputedStyle(second).color;
            document.body.removeAttribute('data-active');
            const after = getComputedStyle(first).color;
            document.querySelector('section').style.display = 'block';
            const display = getComputedStyle(second).display;
            document.querySelector('style').sheet.insertRule('.row { color:green }', 0);
            return [before, after, display, getComputedStyle(first).color];
        })()"#).unwrap(), serde_json::json!([
            "rgb(255, 0, 0)", "rgb(0, 0, 255)", "inline", "rgb(0, 128, 0)"
        ]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_non_geometric_reads_defer_layout_without_losing_damage() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(r#"<!doctype html><style>
            body { margin:0; --tone:blue; color:var(--tone) }
            body[data-active=yes] { --tone:red }
            #box { width:80px; height:20px }
            body[data-active=yes] #box { width:160px }
        </style><body><div id=box>text</div></body>"#));
        rt.set_viewport(400.0, 200.0);
        rt.run_page_init();
        assert_eq!(rt.evaluate("document.getElementById('box').getBoundingClientRect().width").unwrap(), serde_json::json!(80.0));
        let result = rt.evaluate(r#"(() => {
            globalThis.savedStyle = getComputedStyle(document.getElementById('box'));
            document.body.setAttribute('data-active', 'yes');
            return [savedStyle.color, savedStyle.display, savedStyle.opacity];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!(["rgb(255, 0, 0)", "block", "1"]));
        assert!(!rt.state.borrow().pending_style_mutations.is_empty(),
            "a non-geometric read must leave pending layout damage for the next geometry consumer");
        assert_eq!(rt.evaluate("savedStyle.width").unwrap(), serde_json::json!("160px"));
        assert!(rt.state.borrow().pending_style_mutations.is_empty());
        assert_eq!(rt.evaluate(r#"(() => {
            document.body.removeAttribute('data-active');
            return [savedStyle.color, savedStyle.width, savedStyle.length > 20];
        })()"#).unwrap(), serde_json::json!(["rgb(0, 0, 255)", "80px", true]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_uses_renderer_stylesheet_cascade_and_invalidates() {
        let dom = parse_html(
            r#"<html><head><style>
                .base {
                    display:flex; position:relative; z-index:7;
                    visibility:hidden; opacity:.35;
                    background-color:rgb(10,20,30); color:rgb(40,50,60);
                    width:120px; height:40px; min-width:20px; max-width:160px;
                    box-sizing:border-box; overflow-x:clip; overflow-y:visible;
                    margin:1px 2px 3px 4px; padding:5px 6px 7px 8px;
                    border:2px solid rgb(70,80,90);
                    flex-direction:column; flex-wrap:wrap;
                    align-items:center; justify-content:space-between;
                    gap:6px 9px; transform:translate(3px,4px);
                }
                .alt { display:grid; width:150px; opacity:.8; }
            </style></head><body><div id="box" class="base"></div></body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 200.0);
        rt.run_page_init();

        let initial = rt
            .evaluate(
                r#"
                const box = document.getElementById("box");
                const c = getComputedStyle(box);
                return [
                    c.display, c.position, c.zIndex, c.visibility, c.opacity,
                    c.backgroundColor, c.getPropertyValue("color"),
                    c.width, c.height, c.minWidth, c.maxWidth, c.boxSizing,
                    c.overflowX, c.overflowY,
                    c.marginTop, c.marginRight, c.marginBottom, c.marginLeft,
                    c.paddingTop, c.borderLeftWidth, c.borderLeftColor,
                    c.flexDirection, c.flexWrap, c.alignItems,
                    c.justifyContent, c.rowGap, c.columnGap, c.transform
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            initial,
            serde_json::json!([
                "flex",
                "relative",
                "7",
                "hidden",
                "0.35",
                "rgb(10, 20, 30)",
                "rgb(40, 50, 60)",
                "120px",
                "40px",
                "20px",
                "160px",
                "border-box",
                "clip",
                "visible",
                "1px",
                "2px",
                "3px",
                "4px",
                "5px",
                "2px",
                "rgb(70, 80, 90)",
                "column",
                "wrap",
                "center",
                "space-between",
                "6px",
                "9px",
                "matrix(1, 0, 0, 1, 3, 4)"
            ])
        );

        assert_eq!(
            rt.evaluate(
                r#"
                const box = document.getElementById("box");
                box.className = "alt";
                const c = getComputedStyle(box);
                return [c.display, c.width, c.opacity];
                "#,
            )
            .unwrap(),
            serde_json::json!(["grid", "150px", "0.8"])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn webkit_truncation_computed_names_use_native_support_and_vendor_prefixes() {
        let dom = parse_html(
            r#"<html><head><style>
              #clamp { display:-webkit-box; -webkit-box-orient:vertical;
                       -webkit-line-clamp:2; overflow:hidden; }
              #legacy { display:-webkit-inline-box; -webkit-box-orient:horizontal; }
            </style></head><body>
              <div id="clamp">one two three four five six seven eight</div>
              <span id="legacy">legacy</span>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(120.0, 200.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const clamp = getComputedStyle(document.getElementById("clamp"));
                const legacy = getComputedStyle(document.getElementById("legacy"));
                return {
                  supports: [
                    CSS.supports("text-overflow", "ellipsis"),
                    CSS.supports("-webkit-line-clamp", "2"),
                    CSS.supports("-webkit-line-clamp", "0"),
                    CSS.supports("display", "-webkit-box"),
                    CSS.supports("-webkit-box-orient", "vertical")
                  ],
                  clamp: [clamp.display, clamp.webkitLineClamp,
                    clamp.webkitBoxOrient,
                    clamp.getPropertyValue("-webkit-line-clamp")],
                  legacy: [legacy.display, legacy.webkitBoxOrient]
                };
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "supports": [true, true, false, true, true],
                "clamp": ["flow-root", "2", "vertical", "2"],
                "legacy": ["-webkit-inline-box", "horizontal"]
            })
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_typography_uses_resolved_renderer_values() {
        let dom = parse_html(
            r#"<html><head><style>
                #parent {
                    font-size:20px; line-height:1.5;
                    letter-spacing:-.05em; white-space:pre-wrap;
                    text-align:end
                }
                #child { font-size:10px }
                #zero { letter-spacing:0px; white-space:break-spaces }
            </style></head><body>
                <div id="parent"><span id="child">child</span></div>
                <div id="zero">zero</div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 200.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const sample = id => {
                    const s = getComputedStyle(document.getElementById(id));
                    return [s.lineHeight, s.letterSpacing, s.whiteSpace, s.textAlign];
                };
                return [sample("parent"), sample("child"), sample("zero")];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                ["30px", "-1px", "pre-wrap", "end"],
                ["15px", "-1px", "pre-wrap", "end"],
                ["normal", "normal", "break-spaces", "start"],
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn computed_style_exposes_cascaded_custom_properties_and_invalidates() {
        let dom = parse_html(
            r#"<html><head><style>
                :root { --inherited-space: 17px; --derived-space: var(--inherited-space); }
                #nav {
                    --r-globalnav-font-size:17px;
                    --local-scale:1.25;
                    font-size:var(--r-globalnav-font-size);
                }
            </style></head><body>
                <nav id="nav"><span id="child"></span></nav>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 200.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate(
                r#"
                const nav = document.getElementById("nav");
                const child = document.getElementById("child");
                const navStyle = getComputedStyle(nav);
                const childStyle = getComputedStyle(child);
                let enumeratesBase = false;
                for (let i = 0; i < navStyle.length; i++) {
                    if (navStyle.item(i) === "--r-globalnav-font-size")
                        enumeratesBase = true;
                }
                return [
                    navStyle.fontSize,
                    navStyle.getPropertyValue("--r-globalnav-font-size"),
                    parseInt(navStyle.fontSize) /
                        parseInt(navStyle.getPropertyValue("--r-globalnav-font-size")),
                    navStyle.getPropertyValue("--inherited-space"),
                    navStyle.getPropertyValue("--derived-space"),
                    navStyle.getPropertyValue("--local-scale"),
                    childStyle.getPropertyValue("--inherited-space"),
                    childStyle.getPropertyValue("--local-scale"),
                    enumeratesBase
                ];
                "#,
            )
            .unwrap(),
            serde_json::json!([
                "17px", "17px", 1, "17px", "17px", "1.25", "17px", "1.25", true
            ])
        );

        assert_eq!(
            rt.evaluate(
                r#"
                const nav = document.getElementById("nav");
                const computed = getComputedStyle(nav);
                nav.style.setProperty("--inherited-space", "23px");
                nav.style.fontSize = "19px";
                return [
                    computed.fontSize,
                    computed.getPropertyValue("--inherited-space"),
                    computed.getPropertyValue("--derived-space")
                ];
                "#,
            )
            .unwrap(),
            serde_json::json!(["19px", "23px", "17px"])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_activity_wait_parks_an_idle_runtime() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.run_event_loop().await.unwrap();
        let mut wait = std::pin::pin!(rt.wait_for_event_loop_activity());
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(
            wait.as_mut().poll(&mut cx).is_pending(),
            "an idle runtime must park instead of completing synchronously",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_activity_wait_drives_timer_microtasks_and_observers() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("network-idle-tasks", r#"
            globalThis.__idleEvents = [];
            new MutationObserver(() => __idleEvents.push('observer'))
                .observe(document.body, { attributes: true });
            setTimeout(() => {
                __idleEvents.push('timer');
                Promise.resolve().then(() => {
                    __idleEvents.push('microtask');
                    document.body.setAttribute('data-ready', 'yes');
                });
            }, 15);
        "#).unwrap();
        // No periodic sleep drives the runtime here. If it loses the timer's
        // waker, the generous safety deadline fails instead of pumping it.
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            loop {
                rt.wait_for_event_loop_activity().await.unwrap();
                if rt.evaluate("__idleEvents.includes('observer')").unwrap()
                    == serde_json::json!(true)
                {
                    break;
                }
            }
        }).await.expect("timer and observer must wake the parked runtime");
        assert_eq!(rt.evaluate("__idleEvents").unwrap(),
            serde_json::json!(["timer", "microtask", "observer"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_activity_wait_drives_network_completion() {
        let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_millis(30));
        rt.execute_script("network-idle-fetch", r#"
            fetch('/value').then(r => r.text()).then(value => {
                document.body.setAttribute('data-response', value);
            });
        "#).unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            loop {
                rt.wait_for_event_loop_activity().await.unwrap();
                if rt.evaluate("document.body.getAttribute('data-response')").unwrap()
                    == serde_json::json!("hydrated")
                {
                    break;
                }
            }
        }).await.expect("network response must wake the parked runtime");
        accepted.try_recv().expect("real HTTP request was received");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_activity_wait_cancellation_preserves_timer() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("network-idle-cancel", r#"
            globalThis.__afterCancel = false;
            setTimeout(() => { __afterCancel = true; }, 15);
        "#).unwrap();
        {
            let mut wait = std::pin::pin!(rt.wait_for_event_loop_activity());
            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
            assert!(wait.as_mut().poll(&mut cx).is_pending());
        }
        tokio::time::timeout(std::time::Duration::from_secs(2), rt.run_event_loop())
            .await.expect("timer survives cancellation").unwrap();
        assert_eq!(rt.evaluate("__afterCancel").unwrap(), serde_json::json!(true));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn idle_event_loop_flushes_resolved_promise_continuations() {
        let mut rt = setup_runtime("<html><body><div id='state'>pending</div></body></html>");
        rt.execute_script(
            "font-ready",
            "document.fonts.load('normal 1px Example').then(() => {\
                 document.getElementById('state').textContent = 'ready';\
             });",
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("document.getElementById('state').textContent")
                .unwrap(),
            serde_json::json!("ready")
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_does_not_wait_for_analytics_interval() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "quiescent-long-interval",
            "setInterval(() => { globalThis.__analyticsTicks = (globalThis.__analyticsTicks || 0) + 1; }, 1000);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(1_000, 50).await.unwrap();
        assert!(
            started.elapsed() < std::time::Duration::from_millis(400),
            "a future analytics interval must not consume the full settle budget"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fixed_duration_event_loop_yields_from_continuously_ready_tasks() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "fixed-duration-continuously-ready",
            "globalThis.__fixedTicks = 0;\
             setInterval(() => { __fixedTicks++; }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_bounded(40).await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed < std::time::Duration::from_millis(300),
            "a continuously-ready queue must return between tasks instead of waiting for the watchdog: {elapsed:?}",
        );
        assert!(
            rt.evaluate("globalThis.__fixedTicks > 0")
                .unwrap()
                .as_bool()
                .unwrap_or(false),
            "the cooperative fixed wait must still execute queued tasks",
        );
        assert_eq!(
            rt.evaluate(
                "(document.body.setAttribute('data-after-fixed-wait', 'usable'), \
                 document.body.getAttribute('data-after-fixed-wait'))",
            )
            .unwrap(),
            serde_json::json!("usable"),
            "the isolate must remain usable after the fixed wait",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn zero_delay_interval_created_by_timer_yields_to_embedder() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "nested-zero-interval",
            "globalThis.__outerTimerRan = false;\
             globalThis.__zeroIntervalTicks = 0;\
             setTimeout(() => {\
               globalThis.__outerTimerRan = true;\
               globalThis.__zeroInterval = setInterval(\
                 () => __zeroIntervalTicks++, 0);\
             }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_autonomous_event_loop_turn().await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "a repeating timer must yield between ticks; elapsed={elapsed:?}",
        );
        assert_eq!(
            rt.evaluate("globalThis.__outerTimerRan").unwrap(),
            serde_json::json!(true),
        );
        let mut ticks = 0.0;
        for _ in 0..12 {
            rt.run_autonomous_event_loop_turn().await.unwrap();
            let next = rt
                .evaluate("globalThis.__zeroIntervalTicks")
                .unwrap()
                .as_f64()
                .unwrap();
            assert!(
                next <= ticks + 1.0,
                "a repeating timer must yield between ticks: {ticks} -> {next}",
            );
            ticks = next;
            if ticks == 6.0 {
                break;
            }
        }
        assert_eq!(
            ticks, 6.0,
            "V8 maintenance wakes must not starve the repeating timer",
        );
        rt.execute_script(
            "clear-zero-interval",
            "clearInterval(globalThis.__zeroInterval)",
        )
            .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn ready_interval_yields_before_polling_v8_again() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "ready-interval",
            "globalThis.__readyTicks = 0;\
             globalThis.__readyInterval = setInterval(() => __readyTicks++, 0);",
        ).unwrap();

        for (autonomous, expected_ticks) in [(true, 1.0), (false, 2.0)] {
            // Make the timer due before the first poll. Even if the future
            // yields to Tokio, resuming it must not deliver another tick.
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            let result = {
                let mut turn: Pin<Box<dyn Future<Output = Result<bool, String>> + '_>> =
                    if autonomous {
                        Box::pin(rt.run_autonomous_event_loop_turn())
                    } else {
                        Box::pin(rt.run_cooperative_event_loop_tick())
                    };
                match std::future::poll_fn(|cx| Poll::Ready(turn.as_mut().poll(cx))).await {
                    Poll::Ready(result) => result,
                    Poll::Pending => {
                        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                        turn.await
                    }
                }
            };
            result.unwrap();
            assert_eq!(rt.evaluate("__readyTicks").unwrap(), serde_json::json!(expected_ticks));
        }
        rt.execute_script("clear-ready-interval", "clearInterval(__readyInterval)").unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn adaptive_settle_yields_to_tokio_during_ready_posted_tasks() {
        use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
        let mut rt = setup_runtime("<html><body></body></html>");
        let awake = Arc::new(AtomicBool::new(false));
        let observed = awake.clone();
        let heartbeat = tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            observed.store(true, Ordering::Relaxed);
        });
        tokio::task::yield_now().await;
        rt.execute_script("ready-posted-tasks", r#"
            const channel = new MessageChannel();
            const deadline = Date.now() + 1000;
            globalThis.__settleMessages = 0;
            channel.port1.onmessage = () => {
                __settleMessages++;
                if (Date.now() < deadline) channel.port2.postMessage(null);
            };
            channel.port2.postMessage(null);
        "#).unwrap();
        rt.run_event_loop_until_quiescent(100, 30).await.unwrap();
        heartbeat.abort();
        assert!(awake.load(Ordering::Relaxed),
            "adaptive settle starved Tokio while page tasks stayed ready");
        assert!(rt.evaluate("__settleMessages > 0").unwrap().as_bool().unwrap());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn top_level_zero_delay_interval_clamps_after_six_ticks() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "top-level-zero-interval",
            "globalThis.__nestedTimerDelays = [];\
             globalThis.__topInterval = setInterval(\
               () => {\
                 const nested = setTimeout(() => {}, 0);\
                 __nestedTimerDelays.push(__obscura_nextPendingTimeoutDelay());\
                 clearTimeout(nested);\
               }, 0);",
        )
        .unwrap();

        // A V8 maintenance wake may finish a turn without delivering a timer.
        // Count actual ticks, while retaining a bound and the per-turn yield.
        let mut ticks = 0.0;
        for _ in 0..14 {
            rt.run_autonomous_event_loop_turn().await.unwrap();
            let next = rt.evaluate("globalThis.__nestedTimerDelays.length")
                .unwrap().as_f64().unwrap();
            assert!(next <= ticks + 1.0,
                "a repeating timer must yield between ticks: {ticks} -> {next}");
            ticks = next;
            if ticks == 7.0 {
                break;
            }
        }
        assert_eq!(
            ticks, 7.0,
            "the interval must continue yielding and making progress",
        );
        let observed = rt.evaluate("globalThis.__nestedTimerDelays").unwrap();
        let delays = observed.as_array().unwrap();
        assert!(
            delays[0].as_f64().unwrap() < 2.0,
            "a shallow nested timer must remain unclamped: {delays:?}",
        );
        assert!(
            delays[4].as_f64().unwrap() < 2.0,
            "the fifth-level parent must remain below the clamp boundary: {delays:?}",
        );
        assert!(
            delays[5].as_f64().unwrap() >= 2.0,
            "a timer nested from the sixth interval task must receive the four-millisecond clamp: {delays:?}",
        );
        rt.execute_script(
            "clear-top-interval",
            "clearInterval(globalThis.__topInterval)",
        )
            .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn deeply_nested_interval_inherits_the_timer_task_nesting() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "deep-zero-interval",
            "globalThis.__deepIntervalTicks = 0;\
             function installDeepInterval(depth) {\
               if (depth === 0) {\
                 globalThis.__deepIntervalInstalledAt = performance.now();\
                 globalThis.__deepInterval = setInterval(\
                   () => { __deepIntervalTicks++; globalThis.__deepIntervalFiredAt = performance.now(); }, 0);\
               } else {\
                 setTimeout(() => installDeepInterval(depth - 1), 0);\
               }\
             }\
             installDeepInterval(6);",
        )
        .unwrap();

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while rt.evaluate("globalThis.__deepInterval !== undefined").unwrap()
                != serde_json::json!(true)
            {
                rt.run_autonomous_event_loop_turn().await.unwrap();
            }
        }).await.expect("nested interval was installed");
        assert_eq!(
            rt.evaluate("globalThis.__deepIntervalTicks").unwrap(),
            serde_json::json!(0.0),
            "an interval installed by a level-six timer must clamp before its first tick",
        );
        // A cooperative turn can return on deno_core's internal self-wake
        // before a timer is due. Assert delivery and the HTML minimum delay,
        // not a one-to-one relationship between wakes and timer callbacks.
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while rt.evaluate("globalThis.__deepIntervalTicks").unwrap() == serde_json::json!(0.0) {
                rt.run_autonomous_event_loop_turn().await.unwrap();
            }
        }).await.expect("nested interval delivered its first callback");
        assert_eq!(
            rt.evaluate("globalThis.__deepIntervalTicks").unwrap(),
            serde_json::json!(1.0),
        );
        assert!(rt.evaluate("__deepIntervalFiredAt - __deepIntervalInstalledAt")
            .unwrap().as_f64().unwrap() >= 4.0, "nested intervals must retain the four-ms clamp");
        rt.execute_script(
            "clear-deep-interval",
            "clearInterval(globalThis.__deepInterval)",
        )
        .unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn short_observation_deadline_does_not_terminate_the_active_task() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "task-crossing-observation-deadline",
            "globalThis.__longTaskCompleted = false;\
             setTimeout(() => {\
               const end = performance.now() + 600;\
               while (performance.now() < end) {}\
               __longTaskCompleted = true;\
             }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_bounded(20).await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed >= std::time::Duration::from_millis(500)
                && elapsed < std::time::Duration::from_millis(1_500),
            "capture must wait for the active task boundary without becoming unbounded: {elapsed:?}",
        );
        assert_eq!(
            rt.evaluate("globalThis.__longTaskCompleted").unwrap(),
            serde_json::json!(true),
            "a screenshot/readiness deadline must not terminate valid page work",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn adaptive_observation_deadline_does_not_terminate_the_active_task() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "adaptive-task-crossing-observation-deadline",
            "globalThis.__adaptiveLongTaskCompleted = false;\
             setTimeout(() => {\
               const end = performance.now() + 600;\
               while (performance.now() < end) {}\
               __adaptiveLongTaskCompleted = true;\
             }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(20, 10).await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed >= std::time::Duration::from_millis(500)
                && elapsed < std::time::Duration::from_millis(1_500),
            "adaptive settle must wait for the active task boundary: {elapsed:?}",
        );
        assert_eq!(
            rt.evaluate("globalThis.__adaptiveLongTaskCompleted")
                .unwrap(),
            serde_json::json!(true),
            "adaptive readiness must not terminate valid page work",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_yields_from_continuously_ready_non_visual_work() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "quiescent-continuously-ready",
            "setInterval(() => {\
                 globalThis.__schedulerTicks = (globalThis.__schedulerTicks || 0) + 1;\
             }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(2_000, 150).await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "a continuously-ready non-visual scheduler pinned adaptive settle: {elapsed:?}"
        );
        assert!(
            rt.evaluate("globalThis.__schedulerTicks > 0")
                .unwrap()
                .as_bool()
                .unwrap_or(false),
            "the cooperative policy must still drive scheduler work"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_bounds_a_single_unyielding_callback_drain() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "quiescent-unyielding-task",
            "setTimeout(() => { while (true) {} }, 0);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(2_000, 150).await.unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed >= std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)
                && elapsed < std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS + 1_500,),
            "one synchronous callback drain escaped the bounded task allowance: {elapsed:?}"
        );
        assert_eq!(
            rt.evaluate(
                "(document.body.setAttribute('data-after-watchdog', 'usable'), \
                  document.body.getAttribute('data-after-watchdog'))",
            )
            .unwrap(),
            serde_json::json!("usable"),
            "the per-turn watchdog must leave the isolate reusable",
        );
    }

    #[test]
    fn cancelling_one_watchdog_preserves_other_deadlines_and_recovery() {
        let mut rt = ObscuraJsRuntime::new();
        let deadline = rt.arm_watchdog(std::time::Duration::from_millis(100));
        let cancelled = rt.arm_watchdog(std::time::Duration::from_secs(30));
        drop(cancelled);
        // An independent backstop keeps a broken slot implementation bounded.
        rt.execute_script_with_timeout(
            "overlapping-deadlines",
            "while (true) {}",
            std::time::Duration::from_secs(2),
        ).unwrap();
        assert!(rt.disarm_watchdog(deadline));
        assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
    }

    #[test]
    fn dropping_a_watchdog_cannot_terminate_later_work() {
        let mut rt = setup_runtime("<html><body></body></html>");
        {
            let _cancelled = rt.arm_watchdog(std::time::Duration::from_millis(500));
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        std::thread::sleep(std::time::Duration::from_millis(600));

        assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_retains_delayed_network_and_dom_update() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let client = std::sync::Arc::new(obscura_net::ObscuraHttpClient::with_full_options(
            std::sync::Arc::new(obscura_net::CookieJar::new()),
            None,
            true,
        ));
        let in_flight = rt.state.borrow().page_in_flight.clone();
        in_flight.store(1, std::sync::atomic::Ordering::SeqCst);
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(80));
            in_flight.store(0, std::sync::atomic::Ordering::SeqCst);
        });
        rt.set_http_client(client);
        rt.execute_script(
            "quiescent-delayed-work",
            "setInterval(() => {}, 1000);\
             setTimeout(() => document.body.setAttribute('data-ready', 'ready'), 40);",
        )
        .unwrap();

        rt.run_event_loop_until_quiescent(1_000, 150).await.unwrap();
        assert_eq!(
            rt.evaluate("document.body.getAttribute('data-ready')")
                .unwrap(),
            serde_json::json!("ready"),
        );
    }

    fn delayed_fetch_runtime(
        response_delay: std::time::Duration,
    ) -> (ObscuraJsRuntime, std::sync::mpsc::Receiver<()>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (accepted_tx, accepted_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let _ = stream.read(&mut request);
            accepted_tx.send(()).unwrap();
            std::thread::sleep(response_delay);
            let body = "hydrated";
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len(),
            );
            let _ = stream.write_all(response.as_bytes());
        });

        let origin = format!("http://{address}");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html("<html><body></body></html>"));
        rt.set_url(&format!("{origin}/page"));
        rt.set_http_client(std::sync::Arc::new(
            obscura_net::ObscuraHttpClient::with_full_options(
                std::sync::Arc::new(obscura_net::CookieJar::new()),
                None,
                true,
            ),
        ));
        rt.run_page_init();
        (rt, accepted_rx)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_allows_fetch_hydration_within_network_grace() {
        let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_millis(700));
        rt.execute_script(
            "quiescent-fetch-hydration",
            "fetch('/hydrate').then(response => response.text()).then(text => {\
                 document.body.setAttribute('data-ready', text);\
             });",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(3_000, 150).await.unwrap();
        let elapsed = started.elapsed();

        accepted
            .recv_timeout(std::time::Duration::from_millis(100))
            .expect("fixture fetch was not issued");
        assert!(
            elapsed >= std::time::Duration::from_millis(650),
            "settle returned before the delayed response: {elapsed:?}"
        );
        assert!(
            elapsed < std::time::Duration::from_millis(1_500),
            "completed hydration should only pay its following quiet window: {elapsed:?}"
        );
        assert_eq!(
            rt.evaluate("document.body.getAttribute('data-ready')")
                .unwrap(),
            serde_json::json!("hydrated"),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_bounds_a_hanging_page_request() {
        let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_secs(3));
        rt.execute_script(
            "quiescent-hanging-fetch",
            "fetch('/analytics').catch(() => {});",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(4_000, 150).await.unwrap();
        let elapsed = started.elapsed();

        accepted
            .recv_timeout(std::time::Duration::from_millis(100))
            .expect("fixture fetch was not issued");
        assert!(
            elapsed >= std::time::Duration::from_millis(900),
            "pending page work must receive the network grace: {elapsed:?}"
        );
        assert!(
            elapsed < std::time::Duration::from_millis(1_700),
            "a hanging request consumed more than its bounded grace: {elapsed:?}"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_gives_post_grace_dom_activity_a_quiet_window() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.state
            .borrow()
            .page_in_flight
            .store(1, std::sync::atomic::Ordering::SeqCst);
        rt.execute_script(
            "quiescent-post-grace-commit",
            "setInterval(() => {}, 1000);\
             setTimeout(() => document.body.setAttribute('data-ready', 'late'), 1100);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(4_000, 150).await.unwrap();
        let elapsed = started.elapsed();

        assert_eq!(
            rt.evaluate("document.body.getAttribute('data-ready')")
                .unwrap(),
            serde_json::json!("late"),
        );
        assert!(
            elapsed >= std::time::Duration::from_millis(1_200),
            "the late commit did not receive a following quiet window: {elapsed:?}"
        );
        assert!(
            elapsed < std::time::Duration::from_millis(1_800),
            "late observable work escaped the bounded activity tail: {elapsed:?}"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescence_ignores_another_pages_shared_client_request() {
        let client = std::sync::Arc::new(obscura_net::ObscuraHttpClient::with_full_options(
            std::sync::Arc::new(obscura_net::CookieJar::new()),
            None,
            true,
        ));
        client
            .in_flight
            .store(1, std::sync::atomic::Ordering::SeqCst);
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_http_client(client);
        rt.execute_script("quiescent-shared-client", "setInterval(() => {}, 1000);")
            .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(1_000, 50).await.unwrap();
        assert!(
            started.elapsed() < std::time::Duration::from_millis(400),
            "an unrelated page request on the shared client must not pin settle"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_retains_near_term_render_timeout() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "quiescent-render-timeout",
            "setInterval(() => {}, 1000);\
             setTimeout(() => document.body.setAttribute('data-ready', 'ready'), 200);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(1_000, 150).await.unwrap();
        assert!(started.elapsed() >= std::time::Duration::from_millis(180));
        assert_eq!(
            rt.evaluate("document.body.getAttribute('data-ready')")
                .unwrap(),
            serde_json::json!("ready"),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn quiescent_event_loop_bounds_continuous_visual_mutations() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "quiescent-animated-page",
            "let tick=0;setInterval(() =>\
               document.body.setAttribute('data-frame', String(++tick)), 10);",
        )
        .unwrap();

        let started = std::time::Instant::now();
        rt.run_event_loop_until_quiescent(2_000, 150).await.unwrap();
        assert!(
            started.elapsed() < std::time::Duration::from_millis(1_000),
            "an animated document must not consume the complete settle budget"
        );
        assert!(
            rt.evaluate("Number(document.body.getAttribute('data-frame')) > 0")
                .unwrap()
                .as_bool()
                .unwrap_or(false),
            "the policy must still pump animation work before capture"
        );
    }

    #[test]
    fn font_face_set_tracks_authored_and_script_created_faces() {
        let mut rt = setup_runtime(
            r#"<html><head><style>
                @font-face {
                    font-family: "Authored One";
                    src: url("https://assets.test/one.woff2") format("woff2");
                    font-weight: 350 650;
                }
                @font-face {
                    font-family: AuthoredTwo;
                    src: url(data:font/woff2;base64,d09GMg==);
                    font-style: italic;
                }
            </style></head><body></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"(() => {
                    const authored = Array.from(document.fonts);
                    const cssDelete = document.fonts.delete(authored[0]);
                    const dynamic = new FontFace("Dynamic", "url('/dynamic.ttf')", {
                        style: "oblique 12deg",
                        weight: "700",
                        stretch: "condensed",
                        unicodeRange: "U+20-7E",
                        display: "swap"
                    });
                    const addResult = document.fonts.add(dynamic);
                    const visited = [];
                    document.fonts.forEach((value, key, set) => {
                        visited.push(value === key && set === document.fonts);
                    });
                    const afterAdd = [
                        document.fonts.size,
                        document.fonts.has(dynamic),
                        addResult === document.fonts,
                        dynamic.family,
                        dynamic.style,
                        dynamic.weight,
                        dynamic.stretch,
                        dynamic.unicodeRange,
                        dynamic.display,
                        visited.every(Boolean)
                    ];
                    const deleted = document.fonts.delete(dynamic);
                    document.fonts.clear();
                    const bytes = new Uint8Array([0, 1, 2, 253, 254, 255]);
                    const binary = new FontFace("Binary", bytes, { weight: 600 });
                    return [
                        authored.length,
                        authored.map(face => face.family),
                        cssDelete,
                        afterAdd,
                        deleted,
                        document.fonts.size,
                        binary.status,
                        binary.loaded === binary.load()
                    ];
                })()"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                2,
                ["Authored One", "AuthoredTwo"],
                false,
                [
                    3,
                    true,
                    true,
                    "Dynamic",
                    "oblique 12deg",
                    "700",
                    "condensed",
                    "U+20-7E",
                    "swap",
                    true
                ],
                true,
                2,
                "loaded",
                true
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn font_face_load_updates_status_set_readiness_and_matching() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "font-face-lifecycle",
            r#"
                globalThis.__fontEvents = [];
                const face = new FontFace("Lifecycle", "url('/lifecycle.woff2')", {
                    weight: "700"
                });
                document.fonts.onloading = event => __fontEvents.push([event.type, event.fontfaces.length]);
                document.fonts.onloadingdone = event => __fontEvents.push([event.type, event.fontfaces.length]);
                document.fonts.add(face);
                globalThis.__fontBefore = [
                    face.status,
                    document.fonts.status,
                    document.fonts.check("700 16px Lifecycle")
                ];
                globalThis.__fontLoadResult = "pending";
                document.fonts.load("700 16px Lifecycle").then(faces => {
                    __fontLoadResult = [faces.length, faces[0] === face, face.status,
                        document.fonts.check("700 16px Lifecycle")];
                });
                document.fonts.ready.then(set => {
                    globalThis.__fontReady = set === document.fonts;
                });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        let result = rt
            .evaluate("return [__fontBefore, __fontLoadResult, __fontReady, __fontEvents];")
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                ["unloaded", "loaded", false],
                [1, true, "loaded", true],
                true,
                [["loading", 1], ["loadingdone", 1]]
            ])
        );
    }

    #[test]
    fn animation_frame_requires_a_callable_callback() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    try {
                        requestAnimationFrame(null);
                        return [false, ""];
                    } catch (error) {
                        return [error instanceof TypeError, error.name];
                    }
                })()"#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, "TypeError"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn animation_frames_are_ordered_batches_with_rendering_timestamps() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "animation-frame-order",
            r#"
                globalThis.__rafEvents = [];
                globalThis.__rafStamps = [];
                Promise.resolve().then(() => __rafEvents.push("microtask-before"));
                setTimeout(() => __rafEvents.push("timer"), 1);
                requestAnimationFrame((timestamp) => {
                    __rafEvents.push("raf-a");
                    __rafStamps.push(timestamp);
                    Promise.resolve().then(() => __rafEvents.push("microtask-in-raf"));
                    requestAnimationFrame((nextTimestamp) => {
                        __rafEvents.push("raf-next");
                        __rafStamps.push(nextTimestamp);
                    });
                });
                requestAnimationFrame((timestamp) => {
                    __rafEvents.push("raf-b");
                    __rafStamps.push(timestamp);
                });
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(150).await.unwrap();
        let result = rt
            .evaluate(
                r#"[
                    __rafEvents,
                    __rafStamps.length,
                    __rafStamps[0] === __rafStamps[1],
                    __rafStamps[2] > __rafStamps[1]
                ]"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [
                    "microtask-before",
                    "timer",
                    "raf-a",
                    "raf-b",
                    "microtask-in-raf",
                    "raf-next"
                ],
                3,
                true,
                true
            ])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn rendering_opportunity_orders_raf_resize_and_intersection_phases() {
        let mut rt = setup_runtime(
            "<html><body><div id='target' style='width:20px;height:20px'></div></body></html>",
        );
        rt.execute_script(
            "rendering-opportunity-order",
            r#"
                globalThis.__renderPhaseOrder = [];
                const target = document.getElementById("target");
                new ResizeObserver(() => __renderPhaseOrder.push("resize")).observe(target);
                new IntersectionObserver(() => __renderPhaseOrder.push("intersection")).observe(target);
                requestAnimationFrame(() => {
                    __renderPhaseOrder.push("raf");
                    target.style.width = "40px";
                });
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__renderPhaseOrder.slice(0, 3)").unwrap(),
            serde_json::json!(["raf", "resize", "intersection"]),
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn raf_geometry_mutation_reaches_settled_intersection_before_next_frame() {
        let mut rt = setup_runtime(
            "<html><body style='margin:0'><div id='spacer' style='height:150px'></div><div id='target' style='height:20px'></div></body></html>",
        );
        rt.set_viewport(200.0, 100.0);
        rt.execute_script(
            "settle-intersection",
            r#"
                globalThis.__sameFrameOrder = [];
                globalThis.__sameFrameInitial = false;
                const target = document.getElementById("target");
                globalThis.__sameFrameObserver = new IntersectionObserver(entries => {
                    if (!__sameFrameInitial) {
                        __sameFrameInitial = true;
                        return;
                    }
                    if (entries.some(entry => entry.isIntersecting)) {
                        __sameFrameOrder.push("intersection");
                    }
                });
                __sameFrameObserver.observe(target);
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(50).await.unwrap();

        rt.execute_script(
            "mutate-in-animation-frame",
            r#"
                requestAnimationFrame(() => {
                    __sameFrameOrder.push("raf");
                    document.getElementById("spacer").style.height = "0px";
                    requestAnimationFrame(() => __sameFrameOrder.push("next-raf"));
                });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(80).await.unwrap();

        assert_eq!(
            rt.evaluate("__sameFrameOrder").unwrap(),
            serde_json::json!(["raf", "intersection", "next-raf"]),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cancel_animation_frame_removes_pending_and_current_batch_callbacks() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "animation-frame-cancel",
            r#"
                globalThis.__rafEvents = [];
                const pending = requestAnimationFrame(() => __rafEvents.push("pending"));
                cancelAnimationFrame(pending);
                let sameBatch;
                requestAnimationFrame(() => {
                    __rafEvents.push("first");
                    cancelAnimationFrame(sameBatch);
                });
                sameBatch = requestAnimationFrame(() => __rafEvents.push("same-batch"));
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__rafEvents").unwrap(),
            serde_json::json!(["first"])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn self_requeueing_animation_frame_yields_to_timer_tasks() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script(
            "animation-frame-yield",
            r#"
                globalThis.__rafCount = 0;
                globalThis.__rafStopped = false;
                globalThis.__timerAfterAnimation = false;
                let frameId = 0;
                function frame() {
                    __rafCount++;
                    frameId = requestAnimationFrame(frame);
                }
                frameId = requestAnimationFrame(frame);
                setTimeout(() => {
                    cancelAnimationFrame(frameId);
                    __rafStopped = true;
                }, 55);
                setTimeout(() => {
                    __timerAfterAnimation = true;
                }, 65);
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(200).await.unwrap();
        let result = rt
            .evaluate("[__rafCount, __rafStopped, __timerAfterAnimation]")
            .unwrap();
        let values = result.as_array().unwrap();
        let frame_count = values[0].as_u64().unwrap();
        assert!(
            (2..=5).contains(&frame_count),
            "expected a few paced animation frames before cancellation, got {frame_count}"
        );
        assert_eq!(values[1], serde_json::json!(true));
        assert_eq!(values[2], serde_json::json!(true));
    }

    #[test]
    fn test_document_url() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let url = rt.evaluate("document.URL").unwrap();
        assert_eq!(url, serde_json::json!("http://example.com/test"));
    }

    #[test]
    fn test_query_selector() {
        let mut rt = setup_runtime("<html><body><h1>Hello</h1><p>World</p></body></html>");
        let text = rt
            .evaluate("document.querySelector('h1').textContent")
            .unwrap();
        assert_eq!(text, serde_json::json!("Hello"));
    }

    #[test]
    fn test_query_selector_all() {
        let mut rt = setup_runtime("<ul><li>A</li><li>B</li><li>C</li></ul>");
        let count = rt
            .evaluate("document.querySelectorAll('li').length")
            .unwrap();
        assert_eq!(count.as_f64().unwrap() as i64, 3);
    }

    #[test]
    fn css_supports_matches_capabilities_and_boolean_conditions() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"JSON.stringify([
                    CSS.supports("-webkit-hyphens", "none"),
                    CSS.supports("margin-trim", "inline"),
                    CSS.supports("-moz-orient", "inline"),
                    CSS.supports("color", "rgb(from red r g b)"),
                    CSS.supports("(((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b))))"),
                    CSS.supports("display", "grid"),
                    CSS.supports("(display:grid) and (selector(.card > *))"),
                    CSS.supports("not (unknown-engine-prop:value)"),
                    CSS.supports("selector(.card >)"),
                    CSS.supports("selector(:obscura-unknown)"),
                    CSS.supports("selector(.card,)"),
                    CSS.supports("scrollbar-gutter", "stable"),
                    CSS.supports("scrollbar-gutter", "floating"),
                    CSS.supports("color", "light-dark(rgb(1, 2, 3), color-mix(in srgb, white 50%, black))"),
                    CSS.supports("(color:light-dark(red, light-dark(white, black)))"),
                    CSS.supports("color", "light-dark(red)"),
                    CSS.supports("color", "light-dark(red, rgb(1, 2, 3)"),
                    CSS.supports("border", "2px dashed red"),
                    CSS.supports("border-width", "10%"),
                    CSS.supports("word-break", "break-all"),
                    CSS.supports("filter", "blur(2px)"),
                    CSS.supports("content", "attr(data-label)"),
                    CSS.supports("display", "grid;"),
                    CSS.supports("flex-flow", "column"),
                    CSS.supports("flex-flow", "wrap column"),
                    CSS.supports("flex-flow", "column wrap"),
                    CSS.supports("flex-flow", "row column"),
                    CSS.supports("flex-flow", "nowrap wrap-reverse"),
                    CSS.supports("(flex-flow:column)")
                ])"#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(
                "[false,false,false,false,false,true,true,true,false,false,false,true,false,true,true,false,false,true,false,true,false,true,false,true,true,true,false,false,true]"
            )
        );
    }

    #[test]
    fn test_get_element_by_id() {
        let mut rt = setup_runtime(r#"<div id="test">Content</div>"#);
        let tag = rt
            .evaluate("document.getElementById('test').tagName")
            .unwrap();
        assert_eq!(tag, serde_json::json!("DIV"));
    }

    #[test]
    fn attributes_named_node_map_is_live() {
        let mut rt = setup_runtime(r#"<div id="test" class="card" data-state="ready"></div>"#);
        let result = rt
            .evaluate(
                r#"
                const element = document.getElementById("test");
                const attributes = element.attributes;
                const sameObject = attributes === element.attributes;
                const firstName = attributes[0].name;
                let removed = 0;
                while (attributes.length) {
                    element.removeAttributeNode(attributes[0]);
                    removed++;
                    if (removed > 10) throw new Error("NamedNodeMap is not live");
                }
                return {
                    sameObject,
                    namedNodeMap: attributes instanceof NamedNodeMap,
                    firstName,
                    removed,
                    length: attributes.length,
                    hasAttributes: element.hasAttributes(),
                };
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "sameObject": true,
                "namedNodeMap": true,
                "firstName": "id",
                "removed": 3,
                "length": 0,
                "hasAttributes": false,
            })
        );
    }

    #[test]
    fn script_created_attribute_reads_stay_coherent_across_mutation_apis() {
        let mut rt = setup_runtime(r#"<html><body></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const element = document.createElement("DIV");
                    const initial = element.getAttribute("data-state");
                    element.setAttribute("DATA-STATE", "ready");
                    const ordinary = [
                        element.getAttribute("data-state"),
                        element.getAttribute("DATA-STATE"),
                    ];
                    element.setAttributeNS(null, "data-state", "namespaced");
                    const namespaced = element.getAttribute("data-state");
                    element.removeAttributeNS(null, "data-state");
                    const removed = element.getAttribute("data-state");
                    return { initial, ordinary, namespaced, removed };
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "initial": null,
                "ordinary": ["ready", "ready"],
                "namespaced": "namespaced",
                "removed": null,
            })
        );
    }

    #[test]
    fn structural_cache_tracks_detach_reparent_and_rejected_mutations() {
        let mut rt = setup_runtime(r#"<html><body></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const host = document.createElement("div");
                    const child = document.createElement("span");
                    const text = document.createTextNode("hello");
                    const fresh = [host.parentNode, host.isConnected, text.parentNode, text.isConnected];

                    host.appendChild(child);
                    const detachedTree = [child.parentNode === host, host.isConnected, child.isConnected];
                    document.body.appendChild(host);
                    const connectedTree = [host.isConnected, child.isConnected, child.parentNode === host];

                    const other = document.createElement("section");
                    document.body.appendChild(other);
                    const afterUnrelatedMutation = [host.parentNode === document.body, child.isConnected];

                    other.appendChild(child);
                    const reparented = [child.parentNode === other, child.isConnected, host.firstChild === null];

                    let wrongReference = "";
                    try { other.insertBefore(document.createElement("b"), host); }
                    catch (error) { wrongReference = error.name; }
                    let wrongReplacement = "";
                    try { other.replaceChild(document.createElement("i"), host); }
                    catch (error) { wrongReplacement = error.name; }
                    let cycle = "";
                    try { child.appendChild(other); }
                    catch (error) { cycle = error.name; }

                    document.body.removeChild(other);
                    const removedTree = [other.parentNode, other.isConnected, child.isConnected, child.parentNode === other];
                    document.body.appendChild(other);
                    const reattachedTree = [other.isConnected, child.isConnected];
                    return {
                        fresh,
                        detachedTree,
                        connectedTree,
                        afterUnrelatedMutation,
                        reparented,
                        wrongReference,
                        wrongReplacement,
                        cycle,
                        removedTree,
                        reattachedTree,
                    };
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "fresh": [null, false, null, false],
                "detachedTree": [true, false, false],
                "connectedTree": [true, true, true],
                "afterUnrelatedMutation": [true, true],
                "reparented": [true, true, true],
                "wrongReference": "NotFoundError",
                "wrongReplacement": "NotFoundError",
                "cycle": "HierarchyRequestError",
                "removedTree": [null, false, false, true],
                "reattachedTree": [true, true],
            })
        );
    }

    #[test]
    fn element_scroll_methods_update_scroll_offsets() {
        let mut rt = setup_runtime(
            r#"<div id="scroller" style="width:100px;height:100px;overflow:auto">
                   <div style="width:300px;height:300px"></div>
               </div>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const element = document.getElementById("scroller");
                element.scrollTo({left: 12, top: 20, behavior: "smooth"});
                element.scrollBy(3, -5);
                element.scroll({left: 7});
                return {
                    left: element.scrollLeft,
                    top: element.scrollTop,
                    methods: [
                        typeof element.scroll,
                        typeof element.scrollTo,
                        typeof element.scrollBy,
                    ],
                };
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!({
                "left": 7,
                "top": 15,
                "methods": ["function", "function", "function"],
            })
        );
    }

    #[test]
    fn document_fragment_get_element_by_id_searches_descendants() {
        let mut rt = setup_runtime(r#"<div id="target">document</div>"#);
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const frag = document.createDocumentFragment();
                    const section = document.createElement('section');
                    section.innerHTML = '<div><span id="target">fragment</span></div><p id="a.b">literal</p>';
                    frag.appendChild(section);

                    const dup = document.createDocumentFragment();
                    const deepParent = document.createElement('div');
                    deepParent.innerHTML = '<span id="dup">deep</span>';
                    const shallow = document.createElement('p');
                    shallow.id = 'dup';
                    shallow.textContent = 'shallow';
                    dup.appendChild(deepParent);
                    dup.appendChild(shallow);

                    return [
                        frag.getElementById('target').textContent,
                        frag.getElementById('missing') === null,
                        frag.getElementById('a.b').textContent,
                        frag.getElementById(123) === null,
                        dup.getElementById('dup').textContent,
                    ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["fragment", true, "literal", true, "deep"])
        );
    }

    /// Issue #461: FILTER_REJECT must prune the rejected node's whole subtree,
    /// while FILTER_SKIP only skips the node and leaves descendants eligible.
    /// Collapsing both into "not accepted" let a TreeWalker yield nodes from
    /// inside a subtree the page explicitly rejected.
    #[test]
    fn tree_walker_filter_reject_prunes_the_whole_subtree() {
        let mut rt = setup_runtime(r#"<div id="root"><section><p>deep</p></section><a></a></div>"#);
        rt.run_page_init();
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                function walk(verdict) {
                    const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                        acceptNode(node) {
                            return node.tagName === 'SECTION' ? verdict : NodeFilter.FILTER_ACCEPT;
                        }
                    });
                    const seen = [];
                    let node;
                    while ((node = w.nextNode())) seen.push(node.tagName);
                    return seen;
                }
                return [walk(NodeFilter.FILTER_REJECT), walk(NodeFilter.FILTER_SKIP)];
                "#,
            )
            .unwrap();
        // REJECT drops <p> with its <section> parent; SKIP drops only <section>.
        assert_eq!(result, serde_json::json!([["A"], ["P", "A"]]));
    }

    /// Issue #462: previousNode() must walk reverse document order until a node
    /// is accepted, not give up as soon as the first candidate is filtered out.
    #[test]
    fn previous_node_walks_reverse_document_order() {
        let mut rt = setup_runtime(r#"<div id="root"><a><b></b></a><c></c></div>"#);
        rt.run_page_init();
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                    acceptNode(node) {
                        return node.tagName === 'B'
                            ? NodeFilter.FILTER_SKIP
                            : NodeFilter.FILTER_ACCEPT;
                    }
                });
                const forward = [];
                let node;
                while ((node = w.nextNode())) forward.push(node.tagName);
                const backward = [];
                while ((node = w.previousNode())) backward.push(node.tagName);
                return [forward, backward];
                "#,
            )
            .unwrap();
        // From <c>, the previous sibling's deepest last child <b> is skipped, so
        // the walk must keep going up to <a> instead of returning null.
        assert_eq!(result, serde_json::json!([["A", "C"], ["A"]]));
    }

    /// Issue #462: a backward walk must retrace a forward walk exactly, and stop
    /// at the root without ever returning it.
    #[test]
    fn previous_node_retraces_a_full_forward_walk() {
        let mut rt = setup_runtime(
            r#"<div id="root"><section><p>one</p><span></span></section><a><b></b></a></div>"#,
        );
        rt.run_page_init();
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
                const forward = [];
                let node;
                while ((node = w.nextNode())) forward.push(node.tagName);
                const backward = [];
                while ((node = w.previousNode())) backward.push(node.tagName);
                backward.reverse();
                // previousNode never yields root, and never yields the node the
                // forward walk ended on, so compare against forward minus its last.
                // A failed traversal leaves currentNode untouched (DOM 6.1), so
                // it stays on the last node previousNode did return.
                return [forward, backward, w.currentNode.tagName];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                ["SECTION", "P", "SPAN", "A", "B"],
                ["SECTION", "P", "SPAN", "A"],
                "SECTION"
            ])
        );
    }

    /// Issue #462: FILTER_REJECT prunes a subtree in the backward direction too
    /// — the descent into a rejected node's last children must stop.
    #[test]
    fn previous_node_honours_filter_reject_subtree_pruning() {
        let mut rt =
            setup_runtime(r#"<div id="root"><a></a><section><p>deep</p></section><c></c></div>"#);
        rt.run_page_init();
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                    acceptNode(node) {
                        return node.tagName === 'SECTION'
                            ? NodeFilter.FILTER_REJECT
                            : NodeFilter.FILTER_ACCEPT;
                    }
                });
                while (w.nextNode()) { /* advance to the last accepted node */ }
                const backward = [];
                let node;
                while ((node = w.previousNode())) backward.push(node.tagName);
                return backward;
                "#,
            )
            .unwrap();
        // <p> lives inside the rejected <section>, so the backward walk from <c>
        // must jump straight to <a>.
        assert_eq!(result, serde_json::json!(["A"]));
    }

    /// Issue #461: NodeIterator has no subtree pruning — DOM 6.2 says
    /// FILTER_REJECT behaves as FILTER_SKIP there. The shared walker must not
    /// Issue #475: parentNode() must never surface a node above `root`. With
    /// currentNode at root, the old guard stepped to root's own parent and
    /// returned it — escaping the walker's subtree entirely.
    #[test]
    fn tree_walker_parent_node_does_not_escape_above_root() {
        let mut rt = setup_runtime(r#"<div id="root"><a></a></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
                const escaped = w.parentNode();
                return [escaped, w.currentNode.id];
                "#,
            )
            .unwrap();
        // No parent within the subtree, and currentNode stays put at root.
        assert_eq!(result, serde_json::json!([null, "root"]));
    }

    /// Issue #475: when the accepted ancestor is `root` itself, parentNode()
    /// returns it and moves currentNode there — the old `parent !== root` guard
    /// wrongly excluded it.
    #[test]
    fn tree_walker_parent_node_can_return_the_root() {
        let mut rt = setup_runtime(r#"<div id="root"><a></a></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
                w.currentNode = root.querySelector('a');
                const p = w.parentNode();
                return [p ? p.id : null, w.currentNode === root];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(["root", true]));
    }

    /// Issue #475: parentNode() climbs past a skipped ancestor to the first
    /// accepted one, instead of stopping at the immediate parent.
    #[test]
    fn tree_walker_parent_node_climbs_past_skipped_ancestors() {
        let mut rt =
            setup_runtime(r#"<div id="root"><main id="m"><section><a></a></section></main></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                    acceptNode(n) {
                        return n.tagName === 'SECTION'
                            ? NodeFilter.FILTER_SKIP
                            : NodeFilter.FILTER_ACCEPT;
                    }
                });
                w.currentNode = root.querySelector('a');
                const p = w.parentNode();
                return p ? p.id : null;
                "#,
            )
            .unwrap();
        // <a>'s parent <section> is skipped, so <main> is the first accepted
        // ancestor — not null, and not the immediate <section>.
        assert_eq!(result, serde_json::json!("m"));
    }

    /// leak TreeWalker's pruning into it.
    #[test]
    fn node_iterator_treats_filter_reject_as_skip() {
        let mut rt = setup_runtime(r#"<div id="root"><section><p>deep</p></section><a></a></div>"#);
        rt.run_page_init();
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const it = document.createNodeIterator(root, NodeFilter.SHOW_ELEMENT, {
                    acceptNode(node) {
                        return node.tagName === 'SECTION'
                            ? NodeFilter.FILTER_REJECT
                            : NodeFilter.FILTER_ACCEPT;
                    }
                });
                const seen = [];
                let node;
                while ((node = it.nextNode())) seen.push(node.tagName);
                return seen;
                "#,
            )
            .unwrap();
        // The rejected <section> is skipped but not pruned, so <p> still shows.
        // The leading root is #467: an iterator yields the node it is rooted at.
        assert_eq!(result, serde_json::json!(["DIV", "P", "A"]));
    }

    /// Issue #467: a NodeIterator starts *before* its root, so the first
    /// nextNode() returns the root itself. Aliasing createTreeWalker silently
    /// dropped exactly the element the iterator was rooted at.
    #[test]
    fn node_iterator_yields_the_root_node_first() {
        let mut rt = setup_runtime(r#"<div id="root"><a></a></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const it = document.createNodeIterator(root, NodeFilter.SHOW_ELEMENT);
                const seen = [];
                let node;
                while ((node = it.nextNode())) seen.push(node.tagName);
                return seen;
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(["DIV", "A"]));
    }

    /// Issue #467: the NodeIterator interface surface, and that TreeWalker-only
    /// members are not exposed on it.
    #[test]
    fn node_iterator_exposes_its_own_interface() {
        let mut rt = setup_runtime(r#"<div id="root"><a></a></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const it = document.createNodeIterator(root, NodeFilter.SHOW_ELEMENT);
                const before = [it.referenceNode === root, it.pointerBeforeReferenceNode];
                it.nextNode();
                return [
                    before,
                    typeof it.detach,
                    it.detach() === undefined,
                    typeof it.previousNode,
                    it.root === root,
                    it.whatToShow,
                    // TreeWalker-only members must not leak onto a NodeIterator.
                    typeof it.currentNode,
                    typeof it.firstChild,
                    typeof it.parentNode,
                    // The pointer advanced past the root it just returned.
                    [it.referenceNode.tagName, it.pointerBeforeReferenceNode],
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [true, true],
                "function",
                true,
                "function",
                true,
                1,
                "undefined",
                "undefined",
                "undefined",
                ["DIV", false]
            ])
        );
    }

    /// Issue #467: previousNode() retraces the iterator, and the root is the
    /// last node it yields going backwards.
    #[test]
    fn node_iterator_previous_node_retraces_the_walk() {
        let mut rt = setup_runtime(r#"<div id="root"><a><b></b></a><c></c></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const it = document.createNodeIterator(root, NodeFilter.SHOW_ELEMENT);
                const forward = [];
                let node;
                while ((node = it.nextNode())) forward.push(node.tagName);
                const backward = [];
                while ((node = it.previousNode())) backward.push(node.tagName);
                return [forward, backward];
                "#,
            )
            .unwrap();
        // Forward ends on <c>; going back re-yields <c> (the pointer sits after
        // it), then the rest in reverse, root included.
        assert_eq!(
            result,
            serde_json::json!([["DIV", "A", "B", "C"], ["C", "B", "A", "DIV"]])
        );
    }

    /// Issue #463: `<template>` contents are parsed into the node's
    /// `template_contents` document, but no op exposed it, so `.content` handed
    /// back a fabricated empty fragment and the parsed markup was unreachable.
    #[test]
    fn template_content_exposes_parsed_markup() {
        let mut rt = setup_runtime(
            r#"<body><template id="t"><p class="row">a</p><p class="row">b</p></template></body>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const t = document.getElementById('t');
                return [
                    t.content.childNodes.length,
                    t.content.querySelectorAll('.row').length,
                    t.content.firstElementChild.textContent,
                    t.innerHTML,
                    t.content.nodeType,
                    t.content instanceof DocumentFragment,
                    // Identity is stable: frameworks stash `.content` and reuse it.
                    t.content === t.content,
                    // The children stay off the element itself, per the HTML spec.
                    t.childNodes.length,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                2,
                2,
                "a",
                r#"<p class="row">a</p><p class="row">b</p>"#,
                11,
                true,
                true,
                0
            ])
        );
    }

    /// Setting innerHTML on the <html> element parses in the "before head"
    /// insertion mode, which synthesizes head and body. The importer must keep
    /// both; it previously returned the synthesized body and dropped the head
    /// (so a <title>/<meta> assigned this way vanished).
    #[test]
    fn documentelement_inner_html_keeps_head_and_body() {
        let mut rt = setup_runtime("<html><head></head><body></body></html>");
        let v = rt
            .evaluate(
                "(function(){ document.documentElement.innerHTML = '<head><title>T</title></head><body><p>hi</p></body>'; \
                 var t = document.querySelector('title'); var p = document.querySelector('p'); \
                 return (t ? t.textContent : 'no-title') + '|' + (p ? p.textContent : 'no-p'); })()",
            )
            .unwrap();
        assert_eq!(v, serde_json::json!("T|hi"));
    }

    /// Regression guard: innerHTML on an ordinary element still imports the
    /// parsed nodes directly (no head/body is synthesized for a div context),
    /// so the fix above must not change the common case.
    #[test]
    fn ordinary_element_inner_html_imports_content_directly() {
        let mut rt = setup_runtime("<html><body><div id=\"d\"></div></body></html>");
        let v = rt
            .evaluate(
                "(function(){ var d=document.getElementById('d'); d.innerHTML='<span>a</span><span>b</span>'; \
                 return d.children.length + '|' + d.textContent; })()",
            )
            .unwrap();
        assert_eq!(v, serde_json::json!("2|ab"));
    }

    /// Issue #463: the same must hold for a template that arrives via innerHTML
    /// rather than the initial document parse — that is how most frameworks
    /// inject templates.
    #[test]
    fn template_content_works_for_templates_added_via_inner_html() {
        let mut rt = setup_runtime(r#"<body><div id="host"></div></body>"#);
        let result = rt
            .evaluate(
                r#"
                const host = document.getElementById('host');
                host.innerHTML = '<template id="t2"><li class="item">x</li></template>';
                const t = document.getElementById('t2');
                const stamped = t.content.cloneNode(true);
                host.appendChild(stamped);
                return [
                    t.content.childNodes.length,
                    t.content.querySelector('.item').textContent,
                    host.querySelectorAll('li.item').length,
                ];
                "#,
            )
            .unwrap();
        // cloneNode(true) of the content is the canonical stamping idiom.
        assert_eq!(result, serde_json::json!([1, "x", 1]));
    }

    /// Issue #463: a template built with createElement has no parsed contents,
    /// so `.content` must allocate a backing fragment on demand and round-trip
    /// through innerHTML.
    #[test]
    fn template_content_round_trips_for_created_templates() {
        let mut rt = setup_runtime(r#"<body></body>"#);
        let result = rt
            .evaluate(
                r#"
                const t = document.createElement('template');
                t.innerHTML = '<span class="s">hi</span>';
                return [
                    t.content.childNodes.length,
                    t.content.querySelector('.s').textContent,
                    t.innerHTML,
                    t.childNodes.length,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([1, "hi", r#"<span class="s">hi</span>"#, 0])
        );
    }

    /// Issue #463: serializing a `<template>` must emit its contents, or the
    /// markup silently disappears from outerHTML/innerHTML round-trips — and
    /// `cloneNode(true)`, which round-trips through outer_html, yields an empty
    /// template.
    #[test]
    fn template_contents_survive_serialization_and_clone() {
        let mut rt =
            setup_runtime(r#"<body><template id="t"><li class="item">x</li></template></body>"#);
        let result = rt
            .evaluate(
                r#"
                const t = document.getElementById('t');
                const clone = t.cloneNode(true);
                return [
                    t.outerHTML,
                    document.body.innerHTML,
                    clone.content.childNodes.length,
                    clone.content.querySelector('.item').textContent,
                    // The clone's contents are its own, not shared with the original.
                    (clone.content.firstElementChild === t.content.firstElementChild),
                ];
                "#,
            )
            .unwrap();
        let expected = r#"<template id="t"><li class="item">x</li></template>"#;
        assert_eq!(
            result,
            serde_json::json!([expected, expected, 1, "x", false])
        );
    }

    /// Issue #468: window.scrollTo/scrollBy/scroll were no-op stubs, so the
    /// dominant infinite-scroll idiom never advanced the page offset.
    #[cfg(not(feature = "render"))]
    #[test]
    fn window_scroll_methods_move_the_page_offset() {
        let mut rt = setup_runtime(r#"<html><body><div id="d"></div></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                const scrolled = window.scrollTo(0, 500);
                const afterTo = [window.scrollX, window.scrollY];
                window.scrollBy(0, 200);
                const afterBy = [window.pageXOffset, window.pageYOffset];
                window.scrollTo({ left: 10, top: 40 });
                const afterOptions = [window.scrollX, window.scrollY];
                window.scroll(5, 5);
                const afterScroll = [window.scrollX, window.scrollY];
                // Negative offsets clamp to 0, as they do for elements.
                window.scrollTo(0, -100);
                return [afterTo, afterBy, afterOptions, afterScroll, window.scrollY];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([[0, 500], [0, 700], [10, 40], [5, 5], 0])
        );
    }

    /// Issue #468: the page offset is one value, readable and writable through
    /// either `window.scrollY` or `document.scrollingElement.scrollTop`.
    #[cfg(not(feature = "render"))]
    #[test]
    fn window_scroll_offset_is_shared_with_the_scrolling_element() {
        let mut rt = setup_runtime(r#"<html><body><div id="d"></div></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                const isDocEl = document.scrollingElement === document.documentElement;
                window.scrollTo(0, 300);
                // Written through the window, read through the element...
                const viaElement = document.scrollingElement.scrollTop;
                // ...and the reverse.
                document.scrollingElement.scrollTop = 90;
                return [isDocEl, viaElement, window.scrollY, window.pageYOffset];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, 300, 90, 90]));
    }

    /// Issue #468: a scroll event must reach listeners on both the window and
    /// the document — that is the signal lazy loaders wait for.
    #[cfg(not(feature = "render"))]
    #[tokio::test(flavor = "current_thread")]
    async fn window_scroll_fires_a_scroll_event() {
        let mut rt = setup_runtime(r#"<html><body><div id="d"></div></body></html>"#);
        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    let win = 0, doc = 0;
                    window.addEventListener('scroll', () => win++);
                    document.addEventListener('scroll', () => doc++);
                    window.scrollBy(0, 400);
                    setTimeout(() => resolve([win, doc, window.scrollY]), 5);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!([1, 1, 400]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn rendered_window_scroll_clamps_and_geometry_is_viewport_relative() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="wide" style="width:600px;height:700px"></div>
                <div id="target" style="width:20px;height:300px"></div>
                <div id="fixed" style="position:fixed;left:12px;top:14px;width:30px;height:25px">
                    <span id="fixed-child">fixed</span>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(320.0, 200.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const target = document.getElementById("target");
                const fixed = document.getElementById("fixed");
                const fixedChild = document.getElementById("fixed-child");
                const before = {
                    target: target.getBoundingClientRect(),
                    fixed: fixed.getBoundingClientRect(),
                    fixedChild: fixedChild.getBoundingClientRect(),
                };
                window.scrollTo(99999, 99999);
                const maxX = document.documentElement.scrollWidth - innerWidth;
                const maxY = document.documentElement.scrollHeight - innerHeight;
                const after = {
                    target: target.getBoundingClientRect(),
                    fixed: fixed.getBoundingClientRect(),
                    fixedChild: fixedChild.getBoundingClientRect(),
                };
                return [
                    innerWidth, innerHeight,
                    document.documentElement.clientWidth,
                    document.documentElement.clientHeight,
                    document.documentElement.scrollWidth,
                    document.documentElement.scrollHeight,
                    window.scrollX, window.scrollY,
                    document.scrollingElement.scrollLeft,
                    document.scrollingElement.scrollTop,
                    maxX, maxY,
                    Math.abs(after.target.left - (before.target.left - maxX)) < 0.01,
                    Math.abs(after.target.top - (before.target.top - maxY)) < 0.01,
                    Math.abs(after.fixed.left - before.fixed.left) < 0.01,
                    Math.abs(after.fixed.top - before.fixed.top) < 0.01,
                    Math.abs(after.fixedChild.left - before.fixedChild.left) < 0.01,
                    Math.abs(after.fixedChild.top - before.fixedChild.top) < 0.01,
                ];
                "#,
            )
            .unwrap();
        let values = result.as_array().expect("array");
        assert_eq!(
            &values[0..4],
            &serde_json::json!([320, 200, 320, 200]).as_array().unwrap()[..]
        );
        let scroll_width = values[4].as_f64().expect("scrollWidth");
        let scroll_height = values[5].as_f64().expect("scrollHeight");
        assert!(scroll_width >= 600.0, "scrollWidth was {scroll_width}");
        assert!(scroll_height >= 1000.0, "scrollHeight was {scroll_height}");
        assert_eq!(values[6], values[10]);
        assert_eq!(values[7], values[11]);
        assert_eq!(values[8], values[10]);
        assert_eq!(values[9], values[11]);
        assert!(
            values[12..]
            .iter()
                .all(|value| value == &serde_json::json!(true))
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn nested_scroll_metrics_geometry_pixels_and_relayout_share_one_state() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="outer" style="box-sizing:border-box;width:120px;height:100px;
                     border:4px solid red;overflow:hidden;position:relative;background:red">
                  <div id="inner" style="width:220px;height:200px;overflow:hidden;
                       position:relative;background:blue">
                    <div id="target" style="position:absolute;left:300px;top:280px;
                         width:30px;height:20px;background:lime"></div>
                  </div>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(360.0, 240.0);
        rt.run_page_init();

        let top = rt
            .screenshot_prepared((360.0, 240.0), Some("about:blank"))
            .expect("top screenshot");
        let result = rt
            .evaluate(
                r#"
                const outer = document.getElementById('outer');
                const inner = document.getElementById('inner');
                const target = document.getElementById('target');
                const before = {
                  outer: outer.getBoundingClientRect(),
                  inner: inner.getBoundingClientRect(),
                  target: target.getBoundingClientRect(),
                };
                outer.scrollTo(9999, 9999);
                inner.scrollTo(9999, 9999);
                const after = {
                  outer: outer.getBoundingClientRect(),
                  inner: inner.getBoundingClientRect(),
                  target: target.getBoundingClientRect(),
                };
                const first = [target.getBoundingClientRect().left, target.getBoundingClientRect().top];
                outer.scrollTo(0, 0); inner.scrollTo(0, 0);
                outer.scrollTo(9999, 9999); inner.scrollTo(9999, 9999);
                const repeated = [target.getBoundingClientRect().left, target.getBoundingClientRect().top];
                return {
                  outerMetrics: [outer.clientWidth, outer.clientHeight, outer.scrollWidth, outer.scrollHeight],
                  innerMetrics: [inner.clientWidth, inner.clientHeight, inner.scrollWidth, inner.scrollHeight],
                  offsets: [outer.scrollLeft, outer.scrollTop, inner.scrollLeft, inner.scrollTop],
                  outerDelta: [after.outer.left - before.outer.left, after.outer.top - before.outer.top],
                  innerDelta: [after.inner.left - before.inner.left, after.inner.top - before.inner.top],
                  targetDelta: [after.target.left - before.target.left, after.target.top - before.target.top],
                  repeated: [first[0] === repeated[0], first[1] === repeated[1]],
                };
                "#,
            )
            .expect("nested scroll state");
        assert_eq!(
            result["outerMetrics"],
            serde_json::json!([112, 92, 220, 200])
        );
        assert_eq!(
            result["innerMetrics"],
            serde_json::json!([220, 200, 330, 300])
        );
        assert_eq!(result["offsets"], serde_json::json!([108, 108, 110, 100]));
        assert_eq!(result["outerDelta"], serde_json::json!([0, 0]));
        assert_eq!(result["innerDelta"], serde_json::json!([-108, -108]));
        assert_eq!(result["targetDelta"], serde_json::json!([-218, -208]));
        assert_eq!(result["repeated"], serde_json::json!([true, true]));

        let scrolled = rt
            .screenshot_prepared((360.0, 240.0), Some("about:blank"))
            .expect("scrolled screenshot");
        let scrolled_repeat = rt
            .screenshot_prepared((360.0, 240.0), Some("about:blank"))
            .expect("repeat screenshot");
        assert_ne!(top, scrolled, "nested scroll must move painted pixels");
        assert_eq!(
            scrolled, scrolled_repeat,
            "capture must not accumulate movement"
        );

        let retained = rt
            .evaluate(
                r#"
                const outer = document.getElementById('outer');
                const inner = document.getElementById('inner');
                outer.setAttribute('data-relayout', '1');
                return [outer.scrollLeft, outer.scrollTop, inner.scrollLeft, inner.scrollTop];
                "#,
            )
            .expect("retained offsets");
        assert_eq!(retained, serde_json::json!([108, 108, 110, 100]));

        let reclamped = rt
            .evaluate(
                r#"
                const outer = document.getElementById('outer');
                const inner = document.getElementById('inner');
                inner.setAttribute('style', 'width:150px;height:120px;overflow:hidden;position:relative;background:blue');
                document.getElementById('target').setAttribute(
                  'style',
                  'position:absolute;left:100px;top:80px;width:30px;height:20px;background:lime'
                );
                return [outer.scrollLeft, outer.scrollTop, inner.scrollLeft, inner.scrollTop];
                "#,
            )
            .expect("reclamped offsets");
        assert_eq!(reclamped, serde_json::json!([38, 28, 0, 0]));

        rt.evaluate("(function(){ document.getElementById('outer').remove(); document.documentElement.getBoundingClientRect(); return true; })()")
            .expect("remove scroller");
        assert!(
            rt.state.borrow().element_scroll_offsets.is_empty(),
            "removed scroll containers must be pruned after relayout"
        );
    }

    /// Chromium 150 oracle for CSSOM scrolling overflow. Visible and clip
    /// boxes expose descendant overflow but cannot move; an actual scrolling
    /// box includes trailing padding. A clip boundary suppresses propagation
    /// only on its clipped axis, and ordinary inline boxes expose zero metrics.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn element_scroll_metrics_match_chromium_overflow_oracles() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
              <style>
                .box { width:100px;height:80px;padding:10px;border:2px solid;position:absolute }
                .child { width:200px;height:150px }
              </style>
              <div id="visible" class="box" style="overflow:visible;top:0"><div class="child"></div></div>
              <div id="clip" class="box" style="overflow:clip;top:150px"><div class="child"></div></div>
              <div id="hidden" class="box" style="overflow:hidden;top:300px"><div class="child"></div></div>
              <div id="outer" style="width:100px;height:80px;overflow:visible;position:absolute;top:450px">
                <div id="axis" style="width:150px;height:120px;overflow-x:visible;overflow-y:clip">
                  <div style="width:300px;height:250px"></div>
                </div>
              </div>
              <div id="f1" style="width:10px;overflow:visible"><div style="width:100.1px;height:1px"></div></div>
              <div id="f2" style="width:10px;overflow:visible"><div style="width:100.6px;height:1px"></div></div>
              <span id="inline">long inline text</span>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(420.0, 700.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const visible = document.getElementById('visible');
                const clip = document.getElementById('clip');
                const hidden = document.getElementById('hidden');
                const outer = document.getElementById('outer');
                const axis = document.getElementById('axis');
                const inline = document.getElementById('inline');
                visible.scrollTo(99, 99);
                clip.scrollTo(99, 99);
                hidden.scrollTo(99, 99);
                return {
                  visible: [visible.scrollWidth, visible.scrollHeight, visible.scrollLeft, visible.scrollTop],
                  clip: [clip.scrollWidth, clip.scrollHeight, clip.scrollLeft, clip.scrollTop],
                  hidden: [hidden.scrollWidth, hidden.scrollHeight, hidden.scrollLeft, hidden.scrollTop],
                  axis: [outer.scrollWidth, outer.scrollHeight, axis.scrollWidth, axis.scrollHeight],
                  fractional: [document.getElementById('f1').scrollWidth, document.getElementById('f2').scrollWidth],
                  inline: [inline.scrollWidth, inline.scrollHeight, inline.clientWidth, inline.clientHeight],
                };
                "#,
            )
            .expect("overflow oracle metrics");
        assert_eq!(result["visible"], serde_json::json!([210, 160, 0, 0]));
        assert_eq!(result["clip"], serde_json::json!([210, 160, 0, 0]));
        assert_eq!(result["hidden"], serde_json::json!([220, 170, 99, 70]));
        assert_eq!(result["axis"], serde_json::json!([300, 120, 300, 250]));
        assert_eq!(result["fractional"], serde_json::json!([100, 101]));
        assert_eq!(result["inline"], serde_json::json!([0, 0, 0, 0]));
    }

    /// Chromium quantizes effective scrolling ranges and assigned offsets to
    /// the current device-pixel grid. At the renderer's present 1x scale a
    /// 100.4px area cannot move a 100px scrollport, while 100.6px rounds to a
    /// one-pixel range and assigning `.5` moves geometry and paint by 1px.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fractional_scroll_ranges_quantize_geometry_and_pixels_at_one_x() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
              <div id="low" style="width:100px;height:40px;overflow:auto;position:absolute;top:0">
                <div style="width:100.4px;height:40px;position:relative;background:white">
                  <div id="lowChild" style="position:absolute;left:40px;top:5px;width:10px;height:25px;background:red"></div>
                </div>
              </div>
              <div id="high" style="width:100px;height:40px;overflow:auto;position:absolute;top:60px">
                <div style="width:100.6px;height:40px;position:relative;background:white">
                  <div id="highChild" style="position:absolute;left:40px;top:5px;width:10px;height:25px;background:blue"></div>
                </div>
              </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(160.0, 120.0);
        rt.run_page_init();

        let initial = rt
            .screenshot_prepared((160.0, 120.0), Some("about:blank"))
            .expect("initial fractional screenshot");
        let low = rt
            .evaluate(
                r#"
                const low = document.getElementById('low');
                const child = document.getElementById('lowChild');
                const before = child.getBoundingClientRect();
                low.scrollLeft = 999;
                const after = child.getBoundingClientRect();
                return [low.scrollWidth, low.clientWidth, low.scrollLeft, after.left - before.left];
                "#,
            )
            .expect("low fractional range");
        assert_eq!(low, serde_json::json!([100, 100, 0, 0]));
        let after_low = rt
            .screenshot_prepared((160.0, 120.0), Some("about:blank"))
            .expect("low fractional screenshot");
        assert_eq!(
            initial, after_low,
            "a rounded-zero range cannot move pixels"
        );

        let high = rt
            .evaluate(
                r#"
                const high = document.getElementById('high');
                const child = document.getElementById('highChild');
                const before = child.getBoundingClientRect();
                high.scrollLeft = .5;
                const after = child.getBoundingClientRect();
                return [high.scrollWidth, high.clientWidth, high.scrollLeft, after.left - before.left];
                "#,
            )
            .expect("high fractional range");
        assert_eq!(high, serde_json::json!([101, 100, 1, -1]));
        let after_high = rt
            .screenshot_prepared((160.0, 120.0), Some("about:blank"))
            .expect("high fractional screenshot");
        assert_ne!(after_low, after_high, "the quantized pixel must repaint");

        let root_dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                 <div id="wide" style="width:100.6px;height:20px"></div>
               </body></html>"#,
        );
        let mut root_rt = ObscuraJsRuntime::new();
        root_rt.set_dom(root_dom);
        root_rt.set_viewport(100.0, 60.0);
        root_rt.run_page_init();
        let root = root_rt
            .evaluate(
                r#"
                const wide = document.getElementById('wide');
                const before = wide.getBoundingClientRect();
                window.scrollTo(.5, 0);
                const after = wide.getBoundingClientRect();
                const high = [document.documentElement.scrollWidth, window.scrollX, after.left - before.left];
                wide.style.width = '100.4px';
                window.scrollTo(999, 0);
                return { high, low: [document.documentElement.scrollWidth, window.scrollX] };
                "#,
            )
            .expect("root fractional range");
        assert_eq!(root["high"], serde_json::json!([101, 1, -1]));
        assert_eq!(root["low"], serde_json::json!([100, 0]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn element_scroll_offsets_follow_chromium_box_and_dom_lifecycles() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
              <div id="first"><div id="scroller" style="width:100px;height:80px;overflow:auto">
                <div style="width:250px;height:200px"></div>
              </div></div>
              <div id="second"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(360.0, 240.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const scroller = document.getElementById('scroller');
                const first = document.getElementById('first');
                const second = document.getElementById('second');
                scroller.scrollTo(70, 60);
                const initial = [scroller.scrollLeft, scroller.scrollTop];
                scroller.style.overflow = 'visible';
                const visible = [scroller.scrollLeft, scroller.scrollTop];
                scroller.style.overflow = 'auto';
                const restoredStyle = [scroller.scrollLeft, scroller.scrollTop];
                scroller.style.display = 'none';
                const noBox = [scroller.scrollWidth, scroller.scrollHeight, scroller.scrollLeft, scroller.scrollTop];
                scroller.scrollTo(5, 5);
                scroller.style.display = 'block';
                const restoredDisplay = [scroller.scrollLeft, scroller.scrollTop];
                second.appendChild(scroller);
                const moved = [scroller.scrollLeft, scroller.scrollTop];
                scroller.scrollTo(40, 30);
                second.removeChild(scroller);
                first.appendChild(scroller);
                const reattached = [scroller.scrollLeft, scroller.scrollTop];
                scroller.scrollTo(20, 10);
                first.textContent = 'replacement';
                document.body.appendChild(scroller);
                const textReplacement = [scroller.scrollLeft, scroller.scrollTop];
                const detached = document.createElement('div');
                detached.style.cssText = 'width:100px;height:80px;overflow:auto';
                let recomputes = 0;
                globalThis.__obscura_recompute_intersections = () => { recomputes++; };
                detached.scrollTo(30, 20);
                scroller.scrollTo(11, 12);
                return {
                  initial, visible, restoredStyle, noBox, restoredDisplay,
                  moved, reattached, textReplacement,
                  detached: [detached.scrollWidth, detached.scrollHeight, detached.scrollLeft, detached.scrollTop],
                  atomic: [scroller.scrollLeft, scroller.scrollTop, recomputes],
                };
                "#,
            )
            .expect("scroll lifecycle state");
        assert_eq!(result["initial"], serde_json::json!([70, 60]));
        assert_eq!(result["visible"], serde_json::json!([0, 0]));
        assert_eq!(result["restoredStyle"], serde_json::json!([70, 60]));
        assert_eq!(result["noBox"], serde_json::json!([0, 0, 0, 0]));
        assert_eq!(result["restoredDisplay"], serde_json::json!([70, 60]));
        assert_eq!(result["moved"], serde_json::json!([0, 0]));
        assert_eq!(result["reattached"], serde_json::json!([0, 0]));
        assert_eq!(result["textReplacement"], serde_json::json!([0, 0]));
        assert_eq!(result["detached"], serde_json::json!([0, 0, 0, 0]));
        assert_eq!(result["atomic"], serde_json::json!([11, 12, 1]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fixed_panels_scroll_locally_and_transformed_descendants_remain_supported() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;height:1800px">
              <div id="modal" style="position:fixed;left:20px;top:20px;width:140px;height:120px;background:red">
                <div id="panel" style="width:100px;height:80px;overflow:hidden;position:relative;background:blue">
                  <div id="fixedTarget" style="position:absolute;left:180px;top:160px;width:20px;height:20px;background:lime"></div>
                </div>
              </div>
              <div id="transformedScroller" style="position:absolute;top:300px;width:100px;height:80px;overflow:hidden">
                <div id="transformedTarget" style="width:240px;height:180px;transform:scale(1.1)"></div>
              </div>
              <div style="position:absolute;top:600px;transform:scale(1.2)">
                <div id="affineAncestorScroller" style="width:100px;height:80px;overflow:hidden">
                  <div style="width:240px;height:180px"></div>
                </div>
              </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(360.0, 240.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const modal = document.getElementById('modal');
                const panel = document.getElementById('panel');
                const fixedTarget = document.getElementById('fixedTarget');
                const transformedScroller = document.getElementById('transformedScroller');
                const transformedTarget = document.getElementById('transformedTarget');
                const affineAncestorScroller = document.getElementById('affineAncestorScroller');
                const before = {
                  modal: modal.getBoundingClientRect(),
                  fixedTarget: fixedTarget.getBoundingClientRect(),
                  transformedTarget: transformedTarget.getBoundingClientRect(),
                };
                panel.scrollTo(60, 50);
                transformedScroller.scrollTo(50, 40);
                affineAncestorScroller.scrollTo(50, 40);
                window.scrollTo(0, 500);
                const after = {
                  modal: modal.getBoundingClientRect(),
                  fixedTarget: fixedTarget.getBoundingClientRect(),
                  transformedTarget: transformedTarget.getBoundingClientRect(),
                };
                return {
                  modalDelta: [after.modal.left - before.modal.left, after.modal.top - before.modal.top],
                  fixedDelta: [after.fixedTarget.left - before.fixedTarget.left, after.fixedTarget.top - before.fixedTarget.top],
                  transformedDelta: [after.transformedTarget.left - before.transformedTarget.left, after.transformedTarget.top - before.transformedTarget.top],
                  offsets: [panel.scrollLeft, panel.scrollTop, transformedScroller.scrollLeft, transformedScroller.scrollTop, affineAncestorScroller.scrollLeft, affineAncestorScroller.scrollTop],
                };
                "#,
            )
            .expect("fixed and transformed scroll state");
        assert_eq!(result["modalDelta"], serde_json::json!([0, 0]));
        assert_eq!(result["fixedDelta"], serde_json::json!([-60, -50]));
        assert_eq!(result["transformedDelta"], serde_json::json!([-50, -540]));
        assert_eq!(result["offsets"], serde_json::json!([60, 50, 50, 40, 0, 0]));
    }

    /// CSSOM View exposes the viewport through the standards-mode root, but
    /// ordinary elements (including body) report their padding box. Modern
    /// animation libraries commonly measure a fixed 100vh sentinel through
    /// clientHeight; the old synthetic 100x20 fallback collapsed all of their
    /// viewport-relative trigger ranges.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn rendered_client_metrics_use_the_live_padding_box() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="tracker"
                     style="position:fixed;top:0;width:100%;height:100vh"></div>
                <div id="box"
                     style="box-sizing:content-box;width:100.4px;height:50.6px;
                            padding:5px 8.2px 6px 7.2px;
                            border-style:solid;
                            border-width:2px 4.1px 3px 3.1px"></div>
                <div style="height:900px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(320.0, 200.0);
        rt.run_page_init();

        let initial = rt
            .evaluate(
                r#"
                const tracker = document.getElementById("tracker");
                const box = document.getElementById("box");
                return {
                    root: [
                        document.documentElement.clientWidth,
                        document.documentElement.clientHeight
                    ],
                    body: [document.body.clientWidth, document.body.clientHeight],
                    tracker: [
                        tracker.clientWidth, tracker.clientHeight,
                        tracker.offsetWidth, tracker.offsetHeight
                    ],
                    box: [
                        box.clientWidth, box.clientHeight,
                        box.getBoundingClientRect().width,
                        box.getBoundingClientRect().height
                    ]
                };
                "#,
            )
            .unwrap();
        assert_eq!(initial["root"], serde_json::json!([320, 200]));
        assert_eq!(initial["body"], serde_json::json!([320, 967]));
        assert_eq!(initial["tracker"], serde_json::json!([320, 200, 320, 200]));
        assert_eq!(initial["box"][0], serde_json::json!(116));
        assert_eq!(initial["box"][1], serde_json::json!(62));
        assert!((initial["box"][2].as_f64().unwrap() - 123.0).abs() < 0.05);
        assert_eq!(initial["box"][3], serde_json::json!(67));

        // Attribute-backed inline-style changes invalidate the retained
        // render. Borders do not change the padding box; padding does.
        let mutated = rt
            .evaluate(
                r#"
                const tracker = document.getElementById("tracker");
                const box = document.getElementById("box");
                tracker.style.height = "50vh";
                box.style.borderLeftWidth = "13px";
                box.style.paddingLeft = "17px";
                return [
                    tracker.clientHeight,
                    box.clientWidth,
                    box.getBoundingClientRect().width
                ];
                "#,
            )
            .unwrap();
        assert_eq!(mutated[0], serde_json::json!(100));
        assert_eq!(mutated[1], serde_json::json!(126));
        assert_eq!(mutated[2], serde_json::json!(143));

        // A later CDP/emulation viewport update invalidates the layout too;
        // both the root special case and an ordinary 100vh box are live.
        rt.set_viewport(640.0, 360.0);
        assert_eq!(
            rt.evaluate(
                r#"const tracker = document.getElementById("tracker");
                return [
                    document.documentElement.clientWidth,
                    document.documentElement.clientHeight,
                    tracker.clientWidth,
                    tracker.clientHeight
                ]"#,
            )
            .unwrap(),
            serde_json::json!([640, 360, 640, 180])
        );
    }

    /// CSSOM View distinguishes "no associated CSS box" from a real box whose
    /// dimensions happen to be zero. Blink and Gecko return an all-zero
    /// bounding rect and no client rects for display:none/detached elements;
    /// a laid-out zero-size box still contributes one client rect.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn rendered_cssom_rects_distinguish_no_box_from_zero_size_box() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="hidden" style="display:none;width:80px;height:40px"></div>
                <div id="zero" style="display:block;width:0;height:0"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(320.0, 200.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const hidden = document.getElementById("hidden");
                const detached = document.createElement("div");
                detached.style.cssText = "display:block;width:90px;height:50px";
                const zero = document.getElementById("zero");
                const sample = element => {
                    const rect = element.getBoundingClientRect();
                    const rects = element.getClientRects();
                    return {
                        rect: [
                            rect.x, rect.y, rect.width, rect.height,
                            rect.top, rect.right, rect.bottom, rect.left
                        ],
                        rectCount: rects.length,
                        firstWidth: rects.length ? rects[0].width : null,
                    };
                };
                return {
                    hidden: sample(hidden),
                    detached: sample(detached),
                    zero: sample(zero),
                };
                "#,
            )
            .unwrap();

        for name in ["hidden", "detached"] {
            assert_eq!(
                result[name]["rect"],
                serde_json::json!([0, 0, 0, 0, 0, 0, 0, 0]),
                "{name} must expose the CSSOM View no-box bounding rect"
            );
            assert_eq!(
                result[name]["rectCount"],
                serde_json::json!(0),
                "{name} must expose an empty client rect list"
            );
            assert_eq!(result[name]["firstWidth"], serde_json::Value::Null);
        }
        assert_eq!(result["zero"]["rect"][2], serde_json::json!(0));
        assert_eq!(result["zero"]["rect"][3], serde_json::json!(0));
        assert_eq!(
            result["zero"]["rectCount"],
            serde_json::json!(1),
            "a real zero-size layout box must not be mistaken for no box"
        );
        assert_eq!(result["zero"]["firstWidth"], serde_json::json!(0));
    }

    #[cfg(not(feature = "render"))]
    #[test]
    fn non_render_cssom_rects_keep_compatibility_geometry() {
        let mut rt = setup_runtime(r#"<html><body><div id="box"></div></body></html>"#);
        let result = rt
            .evaluate(
                r#"
                const box = document.getElementById("box");
                const detached = document.createElement("div");
                return [box, detached].map(element => {
                    const rect = element.getBoundingClientRect();
                    return [rect.width, rect.height, element.getClientRects().length];
                });
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([[100, 20, 1], [100, 20, 1]]));
    }

    /// Chromium 150 reference (800x513 CSS-pixel viewport):
    /// top=[60,20,20,-267], bottom=[448,448,231,31,-496] at the sampled
    /// root scroll offsets. This keeps sticky distinct from fixed positioning,
    /// verifies subtree movement, bottom-only sticking, and the containing
    /// block's lower boundary without depending on a live site.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn root_scroll_sticky_geometry_matches_chromium_constraints() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:40px"></div>
                <div id="cb" style="box-sizing:border-box;height:900px;padding:10px 12px;border:4px solid #333">
                    <div id="top" style="box-sizing:border-box;position:sticky;top:20px;height:60px;margin:6px">
                        <div id="top-child" style="height:12px"></div>
                    </div>
                    <div style="height:500px"></div>
                    <div id="bottom" style="box-sizing:border-box;position:sticky;bottom:15px;height:50px;margin:5px"></div>
                </div>
                <div style="height:700px"></div>
                <div id="fixed" style="position:fixed;left:600px;top:20px;width:60px;height:60px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(800.0, 513.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const top = document.getElementById("top");
                const child = document.getElementById("top-child");
                const bottom = document.getElementById("bottom");
                const fixed = document.getElementById("fixed");
                const sample = y => {
                    window.scrollTo(0, y);
                    return [
                        window.scrollY,
                        top.getBoundingClientRect().top,
                        child.getBoundingClientRect().top,
                        bottom.getBoundingClientRect().top,
                        fixed.getBoundingClientRect().top,
                    ];
                };
                return [sample(0), sample(100), sample(400), sample(600), sample(9999)];
                "#,
            )
            .unwrap();
        let rows = result.as_array().expect("rows");
        let number =
            |row: usize, column: usize| rows[row].as_array().unwrap()[column].as_f64().unwrap();
        let close = |actual: f64, expected: f64| {
            assert!(
                (actual - expected).abs() < 0.05,
                "expected {expected}, got {actual}"
            );
        };

        close(number(0, 1), 60.0);
        close(number(0, 3), 448.0);
        close(number(1, 1), 20.0);
        close(number(1, 2), 20.0);
        close(number(1, 3), 448.0);
        close(number(2, 1), 20.0);
        close(number(2, 3), 231.0);
        close(number(3, 1), 20.0);
        close(number(3, 3), 31.0);
        close(number(4, 0), 1127.0);
        close(number(4, 1), -267.0);
        close(number(4, 2), -267.0);
        close(number(4, 3), -496.0);
        for row in 0..rows.len() {
            close(number(row, 4), 20.0);
        }
    }

    /// Chromium 150 horizontal reference for the same constraint algorithm:
    /// the sticky subtree pins at x=20, remains distinct from fixed, then
    /// leaves with its 500px containing block at the right boundary.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn root_scroll_sticky_supports_the_inline_axis() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="box-sizing:border-box;margin-left:40px;width:500px;height:100px;padding:10px;border:4px solid">
                    <div id="sticky" style="box-sizing:border-box;position:sticky;left:20px;width:60px;height:30px;margin:6px">
                        <div id="child" style="width:10px;height:10px"></div>
                    </div>
                </div>
                <div style="width:1600px;height:600px"></div>
                <div id="fixed" style="position:fixed;left:20px;top:100px;width:60px;height:30px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(800.0, 513.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const sticky = document.getElementById("sticky");
                const child = document.getElementById("child");
                const fixed = document.getElementById("fixed");
                const sample = x => {
                    window.scrollTo(x, 0);
                    return [
                        window.scrollX,
                        sticky.getBoundingClientRect().left,
                        child.getBoundingClientRect().left,
                        fixed.getBoundingClientRect().left,
                    ];
                };
                return [sample(0), sample(100), sample(400), sample(800)];
                "#,
            )
            .unwrap();
        let rows = result.as_array().unwrap();
        let expected = [
            [0.0, 60.0, 60.0, 20.0],
            [100.0, 20.0, 20.0, 20.0],
            [400.0, 20.0, 20.0, 20.0],
            [800.0, -340.0, -340.0, 20.0],
        ];
        for (row, expected) in rows.iter().zip(expected) {
            for (actual, expected) in row.as_array().unwrap().iter().zip(expected) {
                let actual = actual.as_f64().unwrap();
                assert!(
                    (actual - expected).abs() < 0.05,
                    "expected {expected}, got {actual}"
                );
            }
        }
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn prepared_render_shares_resource_geometry_with_cssom_and_screenshots() {
        let dom = parse_html(
            r#"<html style="margin:0"><head>
                <base href="/assets/">
            </head><body style="margin:0">
                <div id="frame" style="width:160px">
                    <img id="hero" src="hero.svg" style="display:block;width:100%;height:auto">
                </div>
                <div style="height:400px;background:#0000ff"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/docs/page");
        rt.set_viewport(200.0, 100.0);

        let loads = std::sync::Arc::new(std::sync::Mutex::new(0usize));
        let loader_loads = std::sync::Arc::clone(&loads);
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(move |url: &str| {
                assert_eq!(url, "http://example.test/assets/hero.svg");
                *loader_loads.lock().expect("loader count") += 1;
                Some(
                    br##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
                        <rect width="400" height="100" fill="#ffff00"/>
                    </svg>"##
                        .to_vec(),
                )
            });
        rt.run_page_init();

        let before = rt
            .evaluate(
                r#"
                const hero = document.getElementById("hero");
                const rect = hero.getBoundingClientRect();
                return [rect.width, rect.height, document.documentElement.scrollHeight];
                "#,
            )
            .expect("initial geometry");
        let before = before.as_array().expect("initial tuple");
        assert_eq!(before[0].as_f64(), Some(160.0));
        assert_eq!(before[1].as_f64(), Some(40.0));
        let cssom_height = before[2].as_f64().expect("scroll height") as f32;
        let (prepared_address, prepared_height) = {
            let state = rt.state.borrow();
            let prepared = state.prepared_render.as_ref().expect("prepared by CSSOM");
            (
                prepared as *const obscura_render::PreparedRender as usize,
                prepared.content_size().1,
            )
        };
        assert_eq!(cssom_height, prepared_height);
        assert_eq!(*loads.lock().expect("prepare load count"), 1);

        let base_url = Some("http://example.test/assets/");
        let top = rt
            .screenshot_prepared((200.0, 100.0), base_url)
            .expect("top screenshot");
        rt.evaluate(
            "(function(){ window.scrollTo(0, document.documentElement.scrollHeight); return window.scrollY; })()",
        )
        .expect("scroll to bottom");
        let bottom = rt
            .screenshot_prepared((200.0, 100.0), base_url)
            .expect("bottom screenshot");
        let bottom_repeat = rt
            .screenshot_prepared((200.0, 100.0), base_url)
            .expect("repeated bottom screenshot");
        assert_ne!(top, bottom);
        assert_eq!(bottom, bottom_repeat);
        {
            let state = rt.state.borrow();
            let prepared = state
                .prepared_render
                .as_ref()
                .expect("retained prepared render");
            assert_eq!(
                prepared as *const obscura_render::PreparedRender as usize, prepared_address,
                "screenshots must consume the CSSOM-prepared layout"
            );
            assert_eq!(prepared.content_size().1, cssom_height);
        }
        assert_eq!(*loads.lock().expect("paint load count"), 1);

        let after = rt
            .evaluate(
                r#"
                const hero = document.getElementById("hero");
                document.getElementById("frame").setAttribute("style", "width:80px");
                const rect = hero.getBoundingClientRect();
                return [rect.width, rect.height, document.documentElement.scrollHeight];
                "#,
            )
            .expect("mutated geometry");
        let after = after.as_array().expect("mutated tuple");
        assert_eq!(after[0].as_f64(), Some(80.0));
        assert_eq!(after[1].as_f64(), Some(20.0));
        let mutated_height = after[2].as_f64().expect("mutated scroll height") as f32;
        assert_eq!(
            rt.state
                .borrow()
                .prepared_render
                .as_ref()
                .expect("rebuilt prepared render")
                .content_size()
                .1,
            mutated_height
        );
        rt.screenshot_prepared((200.0, 100.0), base_url)
            .expect("mutated screenshot");
        assert_eq!(
            *loads.lock().expect("mutation load count"),
            1,
            "relayout must retain successful resource bytes"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn missing_render_resource_preserves_prepared_layout_and_scroll() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;height:240px">
                <div style="height:240px;background:blue"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.run_page_init();
        rt.evaluate("window.scrollTo(0, 40)")
            .expect("scroll fixture");
        let before_png = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("prepare retained render");
        let (prepared_address, resolved_address, scroll_generation, root_offset) = {
            let state = rt.state.borrow();
            let prepared = state.prepared_render.as_ref().expect("prepared layout");
            let resolved = &state.resolved_scroll.as_ref().expect("resolved scroll").1;
            (
                prepared as *const obscura_render::PreparedRender as usize,
                resolved as *const obscura_render::ResolvedScrollState as usize,
                state.scroll_generation,
                resolved.root_offset(),
            )
        };

        let missing_url = "http://example.test/missing.svg".to_string();
        rt.seed_render_resource(missing_url.clone(), None);
        assert!(rt.render_resource_is_known(&missing_url));
        {
            let state = rt.state.borrow();
            let prepared = state.prepared_render.as_ref().expect("retained layout");
            let resolved = &state.resolved_scroll.as_ref().expect("retained scroll").1;
            assert_eq!(
                prepared as *const obscura_render::PreparedRender as usize, prepared_address,
                "negative cache entries cannot change intrinsic geometry"
            );
            assert_eq!(
                resolved as *const obscura_render::ResolvedScrollState as usize, resolved_address,
                "negative cache entries must retain resolved scrolling"
            );
            assert_eq!(state.scroll_generation, scroll_generation);
            assert_eq!(resolved.root_offset(), root_offset);
        }
        assert_eq!(
            rt.screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
                .expect("capture retained render"),
            before_png,
        );

        rt.seed_render_resource(
            "http://example.test/loaded.svg".to_string(),
            Some(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"/>"#.to_vec()),
        );
        let state = rt.state.borrow();
        let prepared = state
            .prepared_render
            .as_ref()
            .expect("retained style graph");
        assert_eq!(
            prepared as *const obscura_render::PreparedRender as usize, prepared_address,
            "resource arrival waits for the next geometry flush"
        );
        assert_eq!(
            state.pending_style_mutations,
            vec![obscura_render::RetainedStyleMutation::Resource],
            "successful bytes queue one resource-dependent rebuild"
        );
        assert!(
            state.resolved_scroll.is_none(),
            "successful bytes invalidate scroll geometry"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn image_resource_arrival_retains_styles_and_rebuilds_intrinsic_geometry() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <img id="hero" src="http://example.test/late.png" style="display:block">
                <div id="after" style="height:10px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(|_: &str| None);
        rt.run_page_init();

        let before = rt
            .evaluate("[hero.getBoundingClientRect().height, after.getBoundingClientRect().top]")
            .expect("geometry before image arrival");
        assert_eq!(before, serde_json::json!([0, 0]));
        let prepared_address = {
            let state = rt.state.borrow();
            state
                .prepared_render
                .as_ref()
                .expect("initial prepared render")
                as *const obscura_render::PreparedRender as usize
        };

        // Preserve already queued framework damage and coalesce repeated
        // notification of the same shared resource into one refresh marker.
        rt.evaluate("after.setAttribute('data-ready', 'true')")
            .expect("queued DOM mutation");
        let png = two_by_three_png();
        rt.seed_render_image_resource(
            "http://example.test/late.png".to_string(),
            crate::ops::ImageRequestProfile::NoCorsInclude,
            Some(png.clone()),
        );
        rt.seed_render_image_resource(
            "http://example.test/late.png".to_string(),
            crate::ops::ImageRequestProfile::NoCorsInclude,
            Some(png),
        );
        {
            let state = rt.state.borrow();
            assert_eq!(
                state
                    .prepared_render
                    .as_ref()
                    .expect("style graph remains available")
                    as *const obscura_render::PreparedRender as usize,
                prepared_address,
            );
            assert_eq!(
                state
                    .pending_style_mutations
                    .iter()
                    .filter(|mutation| matches!(
                        mutation,
                        obscura_render::RetainedStyleMutation::Resource
                    ))
                    .count(),
                1,
            );
            assert!(
                state
                    .pending_style_mutations
                    .iter()
                    .any(|mutation| matches!(
                mutation,
                obscura_render::RetainedStyleMutation::Attribute(_)
                    ))
            );
        }

        let after = rt
            .evaluate("[hero.getBoundingClientRect().height, after.getBoundingClientRect().top]")
            .expect("geometry after image arrival");
        assert_eq!(after, serde_json::json!([3, 3]));
        assert!(rt.state.borrow().pending_style_mutations.is_empty());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fixed_image_resource_arrival_repaints_without_rebuilding_geometry() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <img id="hero" src="http://example.test/fixed.png"
                     style="display:block;width:20px;height:10px">
                <div id="after" style="height:10px;background:blue"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(|_: &str| None);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("[hero.offsetWidth, hero.offsetHeight, after.offsetTop]")
                .expect("fixed geometry"),
            serde_json::json!([20, 10, 10])
        );
        let before_png = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("capture before image arrival");
        let (prepared_address, resolved_address, activity_before) = {
            let state = rt.state.borrow();
            (
                state.prepared_render.as_ref().unwrap() as *const _ as usize,
                &state.resolved_scroll.as_ref().unwrap().1 as *const _ as usize,
                state.activity_generation,
            )
        };

        rt.seed_render_image_resource(
            "http://example.test/fixed.png".to_string(),
            crate::ops::ImageRequestProfile::NoCorsInclude,
            Some(two_by_three_png()),
        );
        {
            let state = rt.state.borrow();
            assert_eq!(
                state.prepared_render.as_ref().unwrap() as *const _ as usize,
                prepared_address,
                "fixed replaced content must keep the prepared geometry"
            );
            assert_eq!(
                &state.resolved_scroll.as_ref().unwrap().1 as *const _ as usize,
                resolved_address,
                "paint-only resource damage must keep resolved scrolling"
            );
            assert!(state.pending_style_mutations.is_empty());
            assert!(state.activity_generation > activity_before);
        }
        assert_eq!(
            rt.evaluate("[hero.offsetWidth, hero.offsetHeight, after.offsetTop]")
                .expect("retained fixed geometry"),
            serde_json::json!([20, 10, 10])
        );
        let after_png = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("capture after image arrival");
        assert_ne!(after_png, before_png, "new image pixels must reach paint");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fixed_flex_image_resource_arrival_still_rebuilds_geometry() {
        let dom = parse_html(
            r#"<html><body><div style="display:flex">
                <img id="hero" src="http://example.test/flex.png"
                     style="width:20px;height:10px">
            </div></body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(|_: &str| None);
        rt.run_page_init();
        rt.evaluate("hero.getBoundingClientRect().width")
            .expect("prepare flex geometry");
        assert!(rt.state.borrow().resolved_scroll.is_some());

        rt.seed_render_image_resource(
            "http://example.test/flex.png".to_string(),
            crate::ops::ImageRequestProfile::NoCorsInclude,
            Some(two_by_three_png()),
        );
        let state = rt.state.borrow();
        assert_eq!(
            state.pending_style_mutations,
            vec![obscura_render::RetainedStyleMutation::Resource]
        );
        assert!(state.resolved_scroll.is_none());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fixed_css_content_image_arrival_still_rebuilds_intrinsic_geometry() {
        let dom = parse_html(
            r#"<html><body><img id="hero" src="fallback.png"
                style="display:block;width:20px;height:10px;content:url('http://example.test/content.png')">
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(|_: &str| None);
        rt.run_page_init();
        rt.evaluate("hero.getBoundingClientRect().width")
            .expect("prepare CSS replaced content");
        assert!(rt.state.borrow().resolved_scroll.is_some());

        rt.seed_render_image_resource(
            "http://example.test/content.png".to_string(),
            crate::ops::ImageRequestProfile::NoCorsInclude,
            Some(two_by_three_png()),
        );
        let state = rt.state.borrow();
        assert_eq!(
            state.pending_style_mutations,
            vec![obscura_render::RetainedStyleMutation::Resource]
        );
        assert!(state.resolved_scroll.is_none());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn document_region_capture_preserves_live_runtime_state_and_resource_cache() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;height:260px">
                <div style="height:120px;background:red"></div>
                <img src="http://example.test/marker.svg"
                     style="display:block;width:20px;height:20px">
                <div style="height:120px;background:blue"></div>
                <div style="position:fixed;left:0;top:0;width:10px;height:10px;background:lime"></div>
            </body></html>"#,
        );
        let loads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let loader_loads = loads.clone();
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(move |url: &str| {
                assert_eq!(url, "http://example.test/marker.svg");
                loader_loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Some(
                    br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
                        <rect width="20" height="20" fill="#ffff00"/>
                    </svg>"##
                        .to_vec(),
                )
            });
        rt.run_page_init();
        assert_eq!(
            rt.evaluate("(function(){ window.scrollTo(0, 50); return window.scrollY; })()")
                .expect("live scroll")
                .as_f64(),
            Some(50.0)
        );
        let live_before = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("live screenshot");
        let (
            prepared_address,
            viewport,
            scroll_offset,
            scroll_generation,
            resolved_root,
            full_height,
        ) = {
            let state = rt.state.borrow();
            let prepared = state.prepared_render.as_ref().expect("prepared render");
            (
                prepared as *const obscura_render::PreparedRender as usize,
                state.viewport,
                state.scroll_offset,
                state.scroll_generation,
                state
                    .resolved_scroll
                    .as_ref()
                    .expect("resolved scroll")
                    .1
                    .root_offset(),
                prepared.content_size().1,
            )
        };
        assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);

        let region_png = rt
            .screenshot_prepared_region(obscura_render::CaptureRegion::new(
                0.0, 115.0, 80.0, 40.0, 1.5,
            ))
            .expect("offscreen scaled region");
        let full_png = rt
            .screenshot_prepared_region(obscura_render::CaptureRegion::new(
                0.0,
                0.0,
                80.0,
                full_height,
                1.0,
            ))
            .expect("full-content region");
        let png_size = |bytes: &[u8]| {
            assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
            (
                u32::from_be_bytes(bytes[16..20].try_into().expect("PNG width")),
                u32::from_be_bytes(bytes[20..24].try_into().expect("PNG height")),
            )
        };
        assert_eq!(png_size(&region_png), (120, 60));
        assert_eq!(png_size(&full_png), (80, full_height.ceil() as u32));

        let live_after = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("unchanged live screenshot");
        assert_eq!(live_after, live_before);
        let state = rt.state.borrow();
        let prepared = state.prepared_render.as_ref().expect("retained render");
        assert_eq!(
            prepared as *const obscura_render::PreparedRender as usize,
            prepared_address
        );
        assert_eq!(state.viewport, viewport);
        assert_eq!(state.scroll_offset, scroll_offset);
        assert_eq!(state.scroll_generation, scroll_generation);
        assert_eq!(
            state
                .resolved_scroll
                .as_ref()
                .expect("retained resolved scroll")
                .1
                .root_offset(),
            resolved_root
        );
        assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[cfg(feature = "render")]
    #[test]
    fn script_registered_url_font_reaches_render_resource_collection() {
        let loads = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let loader_loads = std::sync::Arc::clone(&loads);
        let font = include_bytes!("../../obscura-render/assets/liberation-serif.ttf").to_vec();
        let mut rt = parser_image_runtime(
            r#"<html><body style="margin:0">
                <span id="sample" style="display:inline-block;width:max-content;
                    font-family:DynamicFixture;font-size:40px;white-space:nowrap">WWWWiiii</span>
            </body></html>"#,
            move |url: &str| {
                loader_loads
                    .lock()
                    .expect("font loads")
                    .push(url.to_string());
                (url == "http://example.com/fonts/dynamic.ttf").then(|| font.clone())
            },
        );
        rt.set_viewport(400.0, 100.0);
        let before = rt
            .evaluate("document.getElementById('sample').getBoundingClientRect().width")
            .unwrap()
            .as_f64()
            .expect("fallback width");
        assert!(loads.lock().expect("initial loads").is_empty());

        let registered = rt
            .evaluate(
                r#"(() => {
                    const face = new FontFace("DynamicFixture",
                        "url('../fonts/dynamic.ttf') format('truetype')",
                        { weight: "normal", style: "normal", unicodeRange: "U+20-7E" });
                    return [document.fonts.add(face) === document.fonts,
                        document.fonts.size, document.fonts.has(face)];
                })()"#,
            )
            .unwrap();
        assert_eq!(registered, serde_json::json!([true, 1, true]));
        {
            let state = rt.state.borrow();
            assert_eq!(state.dynamic_fonts.len(), 1);
            assert!(state.prepared_render.is_some());
            assert_eq!(
                state.pending_style_mutations,
                vec![obscura_render::RetainedStyleMutation::Resource],
                "font registry changes need reshaping and layout, not a fresh cascade"
            );
        }

        let after = rt
            .evaluate("document.getElementById('sample').getBoundingClientRect().width")
            .unwrap()
            .as_f64()
            .expect("dynamic font width");
        assert_ne!(
            before, after,
            "registered face must affect final text geometry"
        );
        assert_eq!(
            *loads.lock().expect("dynamic font loads"),
            vec!["http://example.com/fonts/dynamic.ttf".to_string()]
        );
        rt.screenshot_prepared((400.0, 100.0), Some("http://example.com/page/index.html"))
            .expect("dynamic font screenshot");
        assert_eq!(loads.lock().expect("repeated font loads").len(), 1);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn rendered_layout_cache_is_invalidated_by_style_mutations() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="box" style="height:300px;width:40px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const box = document.getElementById("box");
                const before = [
                    document.documentElement.scrollHeight,
                    box.getBoundingClientRect().height,
                ];
                box.setAttribute("style", "height:900px;width:80px");
                const after = [
                    document.documentElement.scrollHeight,
                    box.getBoundingClientRect().height,
                    box.getBoundingClientRect().width,
                ];
                return [before, after];
                "#,
            )
            .unwrap();
        let values = result.as_array().expect("result");
        let before = values[0].as_array().expect("before");
        let after = values[1].as_array().expect("after");
        assert!(after[0].as_f64().unwrap() > before[0].as_f64().unwrap());
        assert_eq!(before[1].as_f64(), Some(300.0));
        assert_eq!(after[1].as_f64(), Some(900.0));
        assert_eq!(after[2].as_f64(), Some(80.0));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn element_text_content_replacement_recomputes_empty_selector() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<style>#x { width: 10px; height: 5px } #x:empty { width: 30px }</style>
               <div id="x">text</div>"#,
        ));
        rt.run_page_init();

        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const x = document.getElementById("x");
                    const before = x.getBoundingClientRect().width;
                    x.textContent = "";
                    return [before, x.matches(":empty"), x.getBoundingClientRect().width];
                })()"#,
            )
            .unwrap(),
            serde_json::json!([10, true, 30])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn prepared_render_survives_detached_no_op_and_same_viewport_updates() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="box" class="box" style="height:30px;width:40px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(40.0)
        );
        assert!(rt.state.borrow().prepared_render.is_some());

        // Modern frameworks build and decorate substantial detached trees.
        // None of this can affect the connected document's style or geometry.
        rt.evaluate(
            r#"
            const parent = document.createElement('section');
            const child = document.createElement('div');
            child.setAttribute('class', 'box');
            child.setAttribute('style', 'height:900px');
            parent.appendChild(child);
            child.setAttribute('data-state', 'ready');
            "#,
        )
        .unwrap();
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "detached subtree construction must retain connected layout"
        );

        // Attribute setters still fire their DOM/observer semantics when the
        // assigned value is identical, but layout is not dirtied.
        rt.evaluate(
            r#"
            const box = document.getElementById('box');
            box.setAttribute('class', 'box');
            box.removeAttribute('data-absent');
            "#,
        )
        .unwrap();
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "no-op connected attributes must retain prepared layout"
        );

        rt.set_viewport(200.0, 100.0);
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "reapplying the current viewport must not force layout"
        );

        rt.evaluate(
            "document.getElementById('box').setAttribute('style', 'height:60px;width:40px')",
        )
        .unwrap();
        {
            let state = rt.state.borrow();
            assert!(
                state.prepared_render.is_some(),
                "a retained inline-style change must keep the prior style maps until flush"
            );
            assert!(matches!(
                state.pending_style_mutations.as_slice(),
                [obscura_render::RetainedStyleMutation::Attribute(
                    obscura_render::AttributeStyleMutation { name, .. }
                )] if name == "style"
            ));
        }
        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().height")
                .unwrap()
                .as_f64(),
            Some(60.0)
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn same_parent_moves_keep_geometry_and_observer_records_consistent() {
        let mut rt = setup_runtime(
            "<style>body{margin:0}#parent{display:flex}.item{flex:0 0 40px;height:20px}</style>\
             <div id=parent><div id=a class=item></div><div id=b class=item></div></div>",
        );
        rt.evaluate("document.getElementById('b').getBoundingClientRect().x").unwrap();
        assert!(rt.state.borrow().prepared_render.is_some());
        let records = rt.evaluate(
            "(function(){ const parent=document.getElementById('parent'), b=document.getElementById('b'); \
             globalThis.moveObserver=new MutationObserver(()=>{}); moveObserver.observe(parent,{childList:true}); \
             parent.appendChild(b); return moveObserver.takeRecords().map(record=>[record.type, \
               record.removedNodes[0]?.id || null, record.addedNodes[0]?.id || null]); })()"
        ).unwrap();
        assert_eq!(records, serde_json::json!([
            ["childList", "b", null], ["childList", null, "b"],
        ]));
        assert!(rt.state.borrow().prepared_render.is_some(), "a last-child move must retain geometry");
        let moved = rt.evaluate(
            "(function(){ const parent=document.getElementById('parent'), a=document.getElementById('a'), \
             b=document.getElementById('b'); parent.appendChild(a); const records=moveObserver.takeRecords(); \
             moveObserver.disconnect(); return [a.getBoundingClientRect().x, b.getBoundingClientRect().x, \
               records.length, records[0].removedNodes[0]===a, records[1].addedNodes[0]===a]; })()"
        ).unwrap();
        assert_eq!(moved, serde_json::json!([40, 0, 2, true, true]));
    }

    #[cfg(feature = "render")]
    #[test]
    fn waapi_pause_seek_and_cancel_preserve_authored_inline_style() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="box" style="opacity:.2;width:20px;height:20px"></div></body></html>"#,
        );
        rt.execute_script(
            "waapi",
            r#"
                globalThis.box = document.getElementById('box');
                globalThis.__animation = box.animate(
                    [{opacity:.2, transform:'translateX(0px)'}, {opacity:1, transform:'translateX(100px)'}],
                    {duration:100, fill:'both', easing:'linear'}
                );
                __animation.pause();
                __animation.currentTime = 50;
            "#,
        ).unwrap();
        assert_eq!(
            rt.evaluate("box.style.opacity").unwrap(),
            serde_json::json!(".2")
        );
        assert_eq!(
            rt.evaluate("box.getAnimations()[0] === __animation")
                .unwrap(),
            serde_json::json!(true)
        );
        assert_eq!(
            rt.evaluate("document.getAnimations()[0] === __animation")
                .unwrap(),
            serde_json::json!(true)
        );
        assert_eq!(
            rt.evaluate("__animation.playState").unwrap(),
            serde_json::json!("paused")
        );
        assert_eq!(
            rt.evaluate("!('easingBezier' in __animation.effect.getTiming()) && !('linearEasing' in __animation.effect.getComputedTiming())").unwrap(),
            serde_json::json!(true),
        );
        let opacity = rt.evaluate("getComputedStyle(box).opacity").unwrap();
        let opacity = opacity.as_str().unwrap().parse::<f32>().unwrap();
        assert!(
            (opacity - 0.6).abs() < 0.001,
            "midpoint opacity was {opacity}"
        );

        rt.execute_script("cancel", "__animation.cancel()").unwrap();
        assert_eq!(
            rt.evaluate("box.style.opacity").unwrap(),
            serde_json::json!(".2")
        );
        assert_eq!(
            rt.evaluate("getComputedStyle(box).opacity").unwrap(),
            serde_json::json!("0.2")
        );
        assert_eq!(
            rt.evaluate("box.getAnimations().length").unwrap(),
            serde_json::json!(0.0)
        );
        assert_eq!(
            rt.evaluate("document.getAnimations().length").unwrap(),
            serde_json::json!(0.0)
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn waapi_zero_duration_finishes_asynchronously_and_fires_lifecycle() {
        let mut rt = setup_runtime(r#"<div id="box" style="opacity:.1"></div>"#);
        rt.execute_script(
            "waapi-lifecycle",
            r#"
                globalThis.box = document.getElementById('box');
                globalThis.__ready = false;
                globalThis.__finished = false;
                globalThis.__finishEvent = false;
                globalThis.__animation = box.animate([{opacity:.1}, {opacity:1}], {duration:0, fill:'both'});
                __animation.onfinish = () => { __finishEvent = true; };
                __animation.ready.then(() => { __ready = true; });
                __animation.finished.then(() => { __finished = true; });
            "#,
        ).unwrap();
        rt.run_event_loop_bounded(20).await.unwrap();
        assert_eq!(rt.evaluate("__ready").unwrap(), serde_json::json!(true));
        assert_eq!(rt.evaluate("__finished").unwrap(), serde_json::json!(true));
        assert_eq!(
            rt.evaluate("__finishEvent").unwrap(),
            serde_json::json!(true)
        );
        assert_eq!(
            rt.evaluate("__animation.playState").unwrap(),
            serde_json::json!("finished")
        );
        assert_eq!(
            rt.evaluate("getComputedStyle(box).opacity").unwrap(),
            serde_json::json!("1")
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn waapi_positive_infinite_iterations_remain_active() {
        let mut rt = setup_runtime(r#"<div id="box" style="opacity:.1"></div>"#);
        rt.execute_script(
            "waapi-infinite",
            r#"
                globalThis.__infiniteFinished = false;
                globalThis.__infiniteAnimation = document.getElementById('box').animate(
                    [{opacity:.1}, {opacity:1}],
                    {duration:1, iterations:Infinity, fill:'both', easing:'linear'}
                );
                __infiniteAnimation.finished.then(() => { __infiniteFinished = true; });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(20).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[__infiniteAnimation.playState, __infiniteAnimation.effect.getTiming().iterations === Infinity, __infiniteFinished]",
            )
            .unwrap(),
            serde_json::json!(["running", true, false]),
        );
        rt.evaluate("getComputedStyle(document.getElementById('box')).opacity")
            .unwrap();
        assert!(rt.prepared_has_active_css_animations());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn forward_animation_samples_retain_static_prepared_render() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="width:80px;height:60px;background:#1769aa"></div>
            </body></html>"#,
        ));
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.run_page_init();

        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime {
            milliseconds: 100.0,
            })
        );
        let first = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("first static frame");
        let prepared_address = {
            let state = rt.state.borrow();
            state.prepared_render.as_ref().unwrap() as *const _ as usize
        };

        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime {
            milliseconds: 250.0,
            })
        );
        let second = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("second static frame");
        let state = rt.state.borrow();
        assert_eq!(
            state.prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address,
            "a live timestamp alone must not relayout a static document"
        );
        assert_eq!(first, second);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn forward_active_animation_sample_updates_geometry_and_paint_from_retained_frame() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><head><style>
                @keyframes grow {
                    from { width:20px; background-color:#ff0000 }
                    to { width:100px; background-color:#0000ff }
                }
                #box { height:40px; animation:grow 1000ms linear both }
            </style></head><body style="margin:0"><div id="box"></div></body></html>"#,
        ));
        rt.set_url("http://example.test/page");
        rt.set_viewport(120.0, 40.0);
        rt.run_page_init();

        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(0.0)));
        let initial = rt
            .screenshot_prepared((120.0, 40.0), Some("http://example.test/page"))
            .expect("initial animation frame");
        assert!((animation_test_width(&rt, "box") - 20.0).abs() < 0.1);

        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(500.0)));
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "a forward active sample should retain the previous style graph until flush"
        );
        let midpoint = rt
            .screenshot_prepared((120.0, 40.0), Some("http://example.test/page"))
            .expect("retained midpoint animation frame");

        assert!((animation_test_width(&rt, "box") - 60.0).abs() < 0.1);
        assert_ne!(initial, midpoint, "animated paint output must advance");
        assert_eq!(
            rt.state
                .borrow()
                .prepared_render
                .as_ref()
                .unwrap()
                .animation_sample_time()
                .milliseconds,
            500.0
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn forward_waapi_sample_updates_retained_style_and_paint() {
        let mut rt = setup_runtime(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="box" style="width:40px;height:40px;background:#1769aa"></div>
            </body></html>"#,
        );
        rt.set_viewport(120.0, 40.0);
        rt.state.borrow_mut().animation_timeline_origin = std::time::Instant::now();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(0.0)));
        rt.screenshot_prepared((120.0, 40.0), Some("http://example.com/test"))
            .expect("static frame before WAAPI registration");
        rt.execute_script(
            "waapi-retained-frame",
            r#"document.getElementById('box').animate(
                [{opacity:0,transform:'translateX(0px)'},
                 {opacity:1,transform:'translateX(80px)'}],
                {duration:1000,fill:'both',easing:'linear'}
            )"#,
        )
        .unwrap();
        {
            let state = rt.state.borrow();
            let box_node = state
                .dom
                .as_ref()
                .unwrap()
                .get_element_by_id("box")
                .unwrap();
            assert!(
                state.prepared_render.is_some(),
                "registering one WAAPI effect must retain the previous style graph"
            );
            assert_eq!(
                state.pending_style_mutations,
                vec![obscura_render::RetainedStyleMutation::WaapiAnimation { node: box_node }]
            );
        }
        let initial = rt
            .screenshot_prepared((120.0, 40.0), Some("http://example.com/test"))
            .expect("initial WAAPI frame");

        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(500.0)));
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "a forward WAAPI sample should preserve the prepared style graph until flush"
        );
        let midpoint = rt
            .screenshot_prepared((120.0, 40.0), Some("http://example.com/test"))
            .expect("retained WAAPI midpoint");
        let midpoint_opacity = {
            let state = rt.state.borrow();
            let dom = state.dom.as_ref().unwrap();
            let box_node = dom.get_element_by_id("box").unwrap();
            state.prepared_render.as_ref().unwrap().layout().styles[&box_node]
                .opacity
                .unwrap()
        };

        assert!(
            (0.45..0.55).contains(&midpoint_opacity),
            "WAAPI midpoint opacity={midpoint_opacity}"
        );
        assert_ne!(initial, midpoint, "WAAPI paint output must advance");
    }

    #[cfg(feature = "render")]
    #[test]
    fn waapi_cancel_retains_static_style_graph_and_restores_authored_style() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="box" style="opacity:.25;width:20px;height:20px"></div></body></html>"#,
        );
        rt.set_viewport(40.0, 40.0);
        rt.screenshot_prepared((40.0, 40.0), Some("http://example.com/test"))
            .expect("static frame");
        rt.execute_script(
            "waapi-retained-cancel",
            r#"globalThis.__cancelAnimation = document.getElementById('box').animate(
                [{opacity:1}, {opacity:0}], {duration:1000, fill:'both'}
            )"#,
        )
        .unwrap();
        let animated_opacity = rt
            .evaluate("Number(getComputedStyle(document.getElementById('box')).opacity)")
            .unwrap()
            .as_f64()
            .unwrap();
        assert!(
            animated_opacity > 0.9,
            "animated opacity={animated_opacity}"
        );

        rt.evaluate("__cancelAnimation.cancel()").unwrap();
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "canceling one WAAPI effect must retain the previous style graph until recascade"
        );
        assert_eq!(
            rt.evaluate("getComputedStyle(document.getElementById('box')).opacity")
                .unwrap(),
            serde_json::json!("0.25")
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn completed_animation_retains_forward_frame_but_backward_seek_rebuilds() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><head><style>
                @keyframes fade { from { opacity:1 } to { opacity:0 } }
                #box { width:80px; height:60px; background:#ff0000;
                       animation:fade 100ms linear forwards }
            </style></head><body style="margin:0"><div id="box"></div></body></html>"#,
        ));
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.run_page_init();

        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime {
            milliseconds: 150.0,
            })
        );
        let completed = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("completed animation frame");
        assert!(!rt.prepared_has_active_css_animations());
        let prepared_address = {
            let state = rt.state.borrow();
            state.prepared_render.as_ref().unwrap() as *const _ as usize
        };

        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime {
            milliseconds: 300.0,
            })
        );
        let later = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("later completed frame");
        assert_eq!(completed, later);
        assert_eq!(
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address,
            "a finite fill-forwards animation must not relayout after completion"
        );

        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime { milliseconds: 0.0 })
        );
        assert!(
            rt.state.borrow().prepared_render.is_none(),
            "backward timeline seeks must invalidate the completed frame"
        );
        let initial = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("initial animation frame");
        assert_ne!(completed, initial);
        assert!(rt.prepared_has_active_css_animations());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn unsupported_custom_property_animation_does_not_keep_render_damage_active() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><head><style>
                @property --brand-cycle { syntax:"<color>"; inherits:true; initial-value:#2dacf9 }
                @keyframes brand-cycle {
                    from { --brand-cycle:#2dacf9 }
                    to { --brand-cycle:#7ce95a }
                }
                :root { animation:brand-cycle 10s linear infinite }
            </style></head><body style="margin:0">
                <div style="width:80px;height:60px;background:#1769aa"></div>
            </body></html>"#,
        ));
        rt.set_url("http://example.test/page");
        rt.set_viewport(80.0, 60.0);
        rt.run_page_init();

        let first = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("initial frame");
        assert!(
            !rt.prepared_has_active_css_animations(),
            "an unsupported custom-property-only animation has no render damage"
        );
        let prepared_address = {
            let state = rt.state.borrow();
            state.prepared_render.as_ref().unwrap() as *const _ as usize
        };
        assert!(
            rt.set_animation_sample_time(obscura_render::AnimationSampleTime {
            milliseconds: 5_000.0,
            })
        );
        let later = rt
            .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))
            .expect("later frame");
        assert_eq!(first, later);
        assert_eq!(
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address
        );
    }

    #[cfg(feature = "render")]
    fn animation_test_width(rt: &ObscuraJsRuntime, id: &str) -> f32 {
        let state = rt.state.borrow();
        let dom = state.dom.as_ref().unwrap();
        let node = dom.query_selector(&format!("#{id}")).unwrap().unwrap();
        match state.prepared_render.as_ref().unwrap().layout().styles[&node].width {
            obscura_render::Dimension::Px(width) => width,
            ref other => panic!("expected animated pixel width, got {other:?}"),
        }
    }

    #[cfg(feature = "render")]
    fn animation_epoch_runtime() -> ObscuraJsRuntime {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><head><style>
                @keyframes grow { from { width:0px } to { width:100px } }
                .anim { height:10px; animation:grow 1000ms linear forwards }
            </style></head><body style="margin:0"><i id="anchor"></i></body></html>"#,
        ));
        rt.set_url("http://example.test/page");
        rt.set_viewport(200.0, 80.0);
        rt.run_page_init();
        rt
    }

    #[cfg(feature = "render")]
    #[test]
    fn remove_and_reappend_restarts_animation_without_intermediate_flush() {
        let mut rt = animation_epoch_runtime();
        rt.evaluate("var box=document.createElement('div');box.id='box';box.className='anim';document.body.appendChild(box)")
            .unwrap();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(1_000.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        assert!(animation_test_width(&rt, "box") > 95.0);

        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(1_000);
        rt.evaluate(
            "var box=document.getElementById('box');box.remove();document.body.appendChild(box)",
        )
            .unwrap();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(1_100.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        let restarted = animation_test_width(&rt, "box");
        assert!(
            (5.0..20.0).contains(&restarted),
            "restarted width={restarted}"
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn scoped_animation_epochs_survive_later_unrelated_mutations_and_t0_capture() {
        let mut rt = animation_epoch_runtime();
        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(100);
        rt.evaluate("var a=document.createElement('div');a.id='first';a.className='anim';document.body.appendChild(a)")
            .unwrap();
        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(500);
        rt.evaluate("var b=document.createElement('div');b.id='second';b.className='anim';document.body.appendChild(b)")
            .unwrap();
        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(600);
        rt.evaluate("document.getElementById('anchor').setAttribute('data-unrelated','yes')")
            .unwrap();

        assert!(rt.set_animation_sample(obscura_render::AnimationSample::local_override(0.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        assert_eq!(animation_test_width(&rt, "first"), 0.0);
        assert_eq!(animation_test_width(&rt, "second"), 0.0);

        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(700.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        let first = animation_test_width(&rt, "first");
        let second = animation_test_width(&rt, "second");
        assert!((55.0..65.0).contains(&first), "first width={first}");
        assert!((15.0..25.0).contains(&second), "second width={second}");
    }

    #[cfg(feature = "render")]
    #[test]
    fn timing_edits_preserve_identity_and_pause_holds_then_resumes() {
        let mut rt = animation_epoch_runtime();
        rt.evaluate("var box=document.createElement('div');box.id='box';box.className='anim';document.body.appendChild(box)")
            .unwrap();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(300.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        assert!((25.0..35.0).contains(&animation_test_width(&rt, "box")));

        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(300);
        rt.evaluate("document.getElementById('box').setAttribute('style','animation-duration:2000ms;animation-play-state:paused')")
            .unwrap();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(700.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        let held = animation_test_width(&rt, "box");
        assert!((12.0..18.0).contains(&held), "held width={held}");

        rt.state.borrow_mut().animation_timeline_origin =
            std::time::Instant::now() - std::time::Duration::from_millis(800);
        rt.evaluate("document.getElementById('box').setAttribute('style','animation-duration:2000ms;animation-play-state:running')")
            .unwrap();
        assert!(rt.set_animation_sample(obscura_render::AnimationSample::document(1_000.0)));
        rt.screenshot_prepared((200.0, 80.0), Some("http://example.test/page"))
            .unwrap();
        let resumed = animation_test_width(&rt, "box");
        assert!((22.0..28.0).contains(&resumed), "resumed width={resumed}");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn cssom_geometry_samples_live_document_time() {
        let mut rt = animation_epoch_runtime();
        rt.evaluate("var box=document.createElement('div');box.id='box';box.className='anim';document.body.appendChild(box)")
            .unwrap();
        let initial = rt
            .evaluate("document.getElementById('box').getBoundingClientRect().width")
            .unwrap()
            .as_f64()
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(120));
        let later = rt
            .evaluate("document.getElementById('box').getBoundingClientRect().width")
            .unwrap()
            .as_f64()
            .unwrap();
        assert!(later >= initial + 8.0, "initial={initial}, later={later}");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fixed_animation_capture_is_invariant_after_geometry_flush() {
        let make_runtime = || {
            let mut rt = ObscuraJsRuntime::new();
            rt.set_dom(parse_html(
                r#"<html style="margin:0"><head><style>
                    @keyframes dismiss {
                        from { opacity:1; transform:translateY(0) }
                        to { opacity:0; transform:translateY(-80px) }
                    }
                    body { margin:0; width:160px; height:100px; background:#f5f7fa }
                    #content { width:120px; height:50px; margin:20px; background:#1769aa }
                    #shell { position:fixed; inset:0; background:#111827 }
                    #shell.dismissed { animation:dismiss 600ms linear forwards }
                </style></head><body><div id="content"></div>
                    <div id="shell"></div></body></html>"#,
            ));
            rt.set_url("http://example.test/github-like-shell");
            rt.set_viewport(160.0, 100.0);
            rt.run_page_init();
            rt.evaluate("document.getElementById('shell').className='dismissed'")
                .unwrap();
            rt
        };
        let fixed = obscura_render::AnimationSample::local_override(750.0);
        let direct_rt = make_runtime();
        assert!(direct_rt.set_animation_sample(fixed));
        let direct = direct_rt
            .screenshot_prepared(
                (160.0, 100.0),
                Some("http://example.test/github-like-shell"),
            )
            .expect("direct fixed-time capture");

        let mut geometry_rt = make_runtime();
        let rect = geometry_rt
            .evaluate("document.getElementById('content').getBoundingClientRect().toJSON()")
            .expect("geometry flush before capture");
        assert_eq!(rect["width"].as_f64(), Some(120.0));
        assert!(geometry_rt.set_animation_sample(fixed));
        let after_geometry = geometry_rt
            .screenshot_prepared(
                (160.0, 100.0),
                Some("http://example.test/github-like-shell"),
            )
            .expect("fixed-time capture after geometry");

        assert_eq!(
            direct, after_geometry,
            "a CSSOM geometry flush must not change fixed-time capture output"
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn cssom_animation_sample_is_frozen_within_one_javascript_task() {
        let mut rt = animation_epoch_runtime();
        rt.evaluate("var box=document.createElement('div');box.id='box';box.className='anim';document.body.appendChild(box)")
            .unwrap();
        let values = rt
            .evaluate(
                r#"(function(){
                    const box = document.getElementById('box');
                    const first = box.getBoundingClientRect().width;
                    const deadline = Date.now() + 120;
                    while (Date.now() < deadline) {}
                    return [first, box.getBoundingClientRect().width];
                })()"#,
            )
            .unwrap();
        let widths = values.as_array().unwrap();
        assert_eq!(
            widths[0].as_f64(),
            widths[1].as_f64(),
            "forced layout reads in one long task must share one animation frame"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn timer_callback_starts_a_fresh_lazy_animation_sample() {
        let mut rt = animation_epoch_runtime();
        rt.execute_script(
            "timer-animation-sample",
            r#"
                var box=document.createElement('div');
                box.id='box';box.className='anim';document.body.appendChild(box);
                globalThis.__beforeTimerWidth=box.getBoundingClientRect().width;
                setTimeout(() => {
                    globalThis.__afterTimerWidth=box.getBoundingClientRect().width;
                }, 100);
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(250).await.unwrap();
        let values = rt
            .evaluate("[globalThis.__beforeTimerWidth, globalThis.__afterTimerWidth]")
            .unwrap();
        let widths = values.as_array().unwrap();
        let before = widths[0].as_f64().unwrap();
        let after = widths[1].as_f64().unwrap();
        assert!(after >= before + 7.0, "before={before}, after={after}");
    }

    #[cfg(feature = "render")]
    #[test]
    fn transform_only_writes_retain_untransformed_cssom_box_metrics() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="box" style="width:40px;height:20px;transform:scale(2)"></div>
                <div id="parent" style="width:80px;height:20px">
                    <div id="fixed" style="position:fixed;width:50%;height:5px"></div>
                </div>
            </body></html>"#,
        ));
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let initial = rt
            .evaluate(
                r#"(() => {
                    const box = document.getElementById('box');
                    return [box.offsetWidth, box.clientWidth, box.getBoundingClientRect().width];
                })()"#,
            )
            .unwrap();
        assert_eq!(initial[0].as_f64(), Some(40.0));
        assert_eq!(initial[1].as_f64(), Some(40.0));
        assert_eq!(initial[2].as_f64(), Some(80.0));

        let retained = rt
            .evaluate(
                r#"(() => {
                    const box = document.getElementById('box');
                    box.style.transform = 'scale(3)';
                    return [box.offsetWidth, box.clientWidth];
                })()"#,
            )
            .unwrap();
        let retained = retained.as_array().unwrap();
        assert_eq!(retained[0].as_f64(), Some(40.0));
        assert_eq!(retained[1].as_f64(), Some(40.0));
        assert!(
            !rt.state.borrow().pending_style_mutations.is_empty(),
            "layout-only metrics must leave transform paint damage pending"
        );

        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(120.0),
            "visual geometry must still materialize the pending transform"
        );
        assert!(rt.state.borrow().pending_style_mutations.is_empty());

        assert_eq!(
            rt.evaluate(
                "(() => { const box = document.getElementById('box'); box.style.width='70px'; return box.offsetWidth; })()"
            )
            .unwrap()
            .as_f64(),
            Some(70.0),
            "layout-affecting inline edits must not use the transform fast path"
        );

        assert_eq!(
            rt.evaluate("document.getElementById('fixed').offsetWidth")
                .unwrap()
                .as_f64(),
            Some(100.0)
        );
        assert_eq!(
            rt.evaluate(
                "(() => { document.getElementById('parent').style.transform='translateZ(0)'; return document.getElementById('fixed').offsetWidth; })()"
            )
            .unwrap()
            .as_f64(),
            Some(40.0),
            "an ancestor transform can change a positioned descendant's containing block"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn autocomplete_attribute_retains_prepared_render_until_geometry_flush() {
        let dom = parse_html(
            r#"<html style="margin:0"><head><style>
                input { display:block; width:40px; height:20px }
                input[autocomplete="off"] { width:90px }
            </style></head><body style="margin:0">
                <input id="field" autocomplete="on">
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("document.getElementById('field').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(40.0)
        );
        assert!(rt.state.borrow().prepared_render.is_some());

        rt.evaluate("document.getElementById('field').setAttribute('autocomplete', 'off')")
            .unwrap();
        {
            let state = rt.state.borrow();
            assert!(
                state.prepared_render.is_some(),
                "ordinary selector attributes must retain the prepared render until flush"
            );
            assert!(matches!(
                state.pending_style_mutations.as_slice(),
                [obscura_render::RetainedStyleMutation::Attribute(
                    obscura_render::AttributeStyleMutation { name, old_value, new_value, .. }
                )] if name == "autocomplete"
                    && old_value.as_deref() == Some("on")
                    && new_value.as_deref() == Some("off")
            ));
        }

        assert_eq!(
            rt.evaluate("document.getElementById('field').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(90.0),
            "the retained selector invalidation must observe the new attribute value"
        );
        assert!(rt.state.borrow().pending_style_mutations.is_empty());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn namespaced_attribute_mutations_participate_in_id_and_render_invalidation() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0"><div id="box" class="box" style="height:30px;width:40px"></div></body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().height")
                .unwrap()
                .as_f64(),
            Some(30.0)
        );
        assert!(rt.state.borrow().prepared_render.is_some());

        rt.evaluate("document.getElementById('box').setAttributeNS(null, 'class', 'box')")
        .unwrap();
        assert!(
            rt.state.borrow().prepared_render.is_some(),
            "an identical null-namespace attribute must retain layout"
        );

        rt.evaluate(
            "document.getElementById('box').setAttributeNS(null, 'style', 'height:70px;width:40px')",
        )
        .unwrap();
        assert!(
            rt.state.borrow().prepared_render.is_none(),
            "a connected namespace-aware style mutation must invalidate layout"
        );
        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().height")
                .unwrap()
                .as_f64(),
            Some(70.0)
        );

        let id_result = rt
            .evaluate(
                "(function(){const box=document.getElementById('box');box.setAttributeNS(null,'id','renamed');const found=document.getElementById('renamed')===box;box.removeAttributeNS(null,'id');return found && document.getElementById('renamed')===null;})()",
            )
            .unwrap();
        assert_eq!(id_result, serde_json::json!(true));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn stylesheet_index_cache_reuses_sources_but_not_live_cascade_or_viewport() {
        let dom = parse_html(
            r#"<html style="margin:0"><head><style id="sheet">
                .a { width:40px; height:20px }
                .b { width:80px; height:20px }
            </style></head><body style="margin:0">
                <div id="box" class="a"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(40.0)
        );
        {
            let state = rt.state.borrow();
            assert_eq!(state.stylesheet_cache.miss_count(), 1);
            assert_eq!(state.stylesheet_cache.hit_count(), 0);
            assert!(state.stylesheet_cache.retained_source_bytes() > 0);
        }

        // The compiled selector index is reusable, but matching and cascade
        // must observe the new class on the live connected element.
        rt.evaluate("document.getElementById('box').className = 'b'")
            .unwrap();
        {
            let state = rt.state.borrow();
            assert!(state.prepared_render.is_some());
            assert_eq!(state.pending_style_mutations.len(), 1);
        }
        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(80.0)
        );
        {
            let state = rt.state.borrow();
            assert_eq!(state.stylesheet_cache.miss_count(), 1);
            assert_eq!(state.stylesheet_cache.hit_count(), 1);
        }

        // Style text is part of the exact key and cannot reuse stale rules.
        rt.evaluate(
            r#"document.getElementById('sheet').textContent =
                '.b{width:120px;height:20px}@media(min-width:250px){.b{width:160px}}'"#,
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(120.0)
        );
        {
            let state = rt.state.borrow();
            assert_eq!(state.stylesheet_cache.miss_count(), 2);
            assert_eq!(state.stylesheet_cache.hit_count(), 1);
        }

        // Media-query filtering is viewport-dependent, so an exact source hit
        // at a different viewport must still reparse and reindex.
        rt.set_viewport(300.0, 100.0);
        assert_eq!(
            rt.evaluate("document.getElementById('box').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(160.0)
        );
        let state = rt.state.borrow();
        assert_eq!(state.stylesheet_cache.miss_count(), 3);
        assert_eq!(state.stylesheet_cache.hit_count(), 1);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn connected_tree_mutations_queue_retained_styles_until_geometry_flush() {
        let dom = parse_html(
            r#"<html style="margin:0"><head><style>
                .item{display:block;width:40px;height:12px}
                .item:nth-child(2){width:80px}
            </style></head><body style="margin:0">
                <main id="list"><div id="first" class="item"></div></main>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("document.getElementById('first').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(40.0)
        );
        rt.evaluate(
            "const added=document.createElement('div');added.id='added';added.className='item';document.getElementById('list').appendChild(added)",
        )
        .unwrap();
        {
            let state = rt.state.borrow();
            assert!(state.prepared_render.is_some());
            assert!(matches!(
                state.pending_style_mutations.as_slice(),
                [obscura_render::RetainedStyleMutation::Tree(
                    obscura_render::TreeStyleMutation::Insert { .. }
                )]
            ));
        }
        assert_eq!(
            rt.evaluate("document.getElementById('added').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(80.0)
        );
        assert!(rt.state.borrow().pending_style_mutations.is_empty());

        rt.evaluate("document.getElementById('added').style.width='65px'")
            .unwrap();
        {
            let state = rt.state.borrow();
            assert!(state.prepared_render.is_some());
            assert!(matches!(
                state.pending_style_mutations.as_slice(),
                [obscura_render::RetainedStyleMutation::Attribute(
                    obscura_render::AttributeStyleMutation { name, .. }
                )] if name == "style"
            ));
        }
        assert_eq!(
            rt.evaluate("document.getElementById('added').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(65.0)
        );
        assert_eq!(
            rt.evaluate("(function(){const added=document.getElementById('added');added.style.width='';return added.getBoundingClientRect().width})()")
                .unwrap()
                .as_f64(),
            Some(80.0)
        );

        rt.evaluate(
            "document.getElementById('list').removeChild(document.getElementById('first'))",
        )
        .unwrap();
        {
            let state = rt.state.borrow();
            assert!(state.prepared_render.is_some());
            assert!(matches!(
                state.pending_style_mutations.as_slice(),
                [obscura_render::RetainedStyleMutation::Tree(
                    obscura_render::TreeStyleMutation::Remove { .. }
                )]
            ));
        }
        assert_eq!(
            rt.evaluate("document.getElementById('added').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(40.0)
        );
        assert!(rt.state.borrow().pending_style_mutations.is_empty());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn root_overflow_clip_preserves_cssom_scroll_range() {
        let dom = parse_html(
            r#"<html style="margin:0;height:100%;overflow:hidden">
                <body style="margin:0;height:100%">
                    <main id="main" style="padding-top:48px">
                        <div style="height:5000px"></div>
                    </main>
                </body>
            </html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(900.0, 1000.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const main = document.getElementById("main");
                const before = main.getBoundingClientRect();
                scrollTo(0, 99999);
                const after = main.getBoundingClientRect();
                return [
                    before.height,
                    document.documentElement.scrollHeight,
                    document.body.scrollHeight,
                    scrollY,
                    after.top,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([5048, 5048, 5048, 4048, -4048]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn rendered_window_scroll_events_require_actual_movement() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:1000px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(320.0, 200.0);
        rt.run_page_init();

        let moved = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    let win = 0, doc = 0;
                    window.addEventListener("scroll", () => win++);
                    document.addEventListener("scroll", () => doc++);
                    window.scrollTo(0, 100);
                    setTimeout(() => resolve([win, doc, window.scrollY]), 5);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(moved.value.unwrap(), serde_json::json!([1, 1, 100]));

        rt.evaluate("window.scrollTo(0, 99999)").unwrap();
        rt.run_event_loop_bounded(20).await.unwrap();
        let no_op = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    let win = 0, doc = 0;
                    window.addEventListener("scroll", () => win++);
                    document.addEventListener("scroll", () => doc++);
                    const before = window.scrollY;
                    window.scrollTo(0, 99999);
                    setTimeout(() => resolve([win, doc, before, window.scrollY]), 5);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        let values = no_op.value.unwrap();
        let values = values.as_array().expect("array");
        assert_eq!(
            &values[0..2],
            &serde_json::json!([0, 0]).as_array().unwrap()[..]
        );
        assert_eq!(values[2], values[3]);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn fingerprinted_screen_does_not_invent_a_device_scale_factor() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html("<html><body></body></html>"));
        rt.set_viewport(300.0, 200.0);
        // Force the fingerprint seed whose screen-pool entry is 2560x1440.
        // That physical screen must not silently turn a 1x render surface into
        // a 2x devicePixelContentBoxSize surface.
        rt.execute_script(
            "deterministic-high-resolution-screen",
            "Date.now = () => 0; Math.random = () => 2 / 0xFFFFFFFF;",
        )
        .unwrap();
        rt.run_page_init();

        assert_eq!(
            rt.evaluate("[screen.width, screen.height, devicePixelRatio]")
                .unwrap(),
            serde_json::json!([2560, 1440, 1])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn resize_observer_reports_real_boxes_only_when_selected_size_changes() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="target" style="box-sizing:border-box;width:120px;height:80px;
                     padding:5px 7px;border:2px solid black"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(300.0, 200.0);
        rt.run_page_init();
        rt.execute_script(
            "resize-observer-boxes",
            r#"
                globalThis.__resizeRecords = [];
                globalThis.__resizeObserver = new ResizeObserver(entries => {
                    __resizeRecords.push(...entries.map(entry => ({
                        interfaces: [
                            entry instanceof ResizeObserverEntry,
                            entry.contentBoxSize[0] instanceof ResizeObserverSize,
                            entry.borderBoxSize[0] instanceof ResizeObserverSize,
                            entry.devicePixelContentBoxSize[0] instanceof ResizeObserverSize,
                        ],
                        contentRect: [
                            entry.contentRect.x, entry.contentRect.y,
                            entry.contentRect.width, entry.contentRect.height,
                        ],
                        content: [
                            entry.contentBoxSize[0].inlineSize,
                            entry.contentBoxSize[0].blockSize,
                        ],
                        border: [
                            entry.borderBoxSize[0].inlineSize,
                            entry.borderBoxSize[0].blockSize,
                        ],
                        device: [
                            entry.devicePixelContentBoxSize[0].inlineSize,
                            entry.devicePixelContentBoxSize[0].blockSize,
                        ],
                    })));
                });
                __resizeObserver.observe(document.getElementById("target"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__resizeRecords").unwrap(),
            serde_json::json!([{
                "interfaces": [true, true, true, true],
                "contentRect": [7, 5, 102, 66],
                "content": [102, 66],
                "border": [120, 80],
                "device": [102, 66],
            }])
        );

        // A style mutation still causes a rendering checkpoint, but unchanged
        // observed geometry must not produce a speculative notification.
        rt.evaluate(r#"document.getElementById("target").style.color = "red""#)
            .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__resizeRecords.length").unwrap().as_f64(),
            Some(1.0)
        );

        rt.evaluate(r#"document.getElementById("target").style.width = "140px""#)
            .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__resizeRecords.map(record => [record.content[0], record.border[0]])")
            .unwrap(),
            serde_json::json!([[102, 120], [122, 140]])
        );
        assert_eq!(
            rt.evaluate("__obscura_nextPendingTimeoutDelay()")
                .unwrap()
                .as_f64(),
            Some(-1.0)
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn resize_observer_batches_unique_targets_into_one_native_layout_read() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="a" style="box-sizing:border-box;width:100px;height:30px;padding:2px 3px;border:1px solid"></div>
                <div id="b" style="box-sizing:border-box;width:110px;height:30px;padding:2px 3px;border:1px solid"></div>
                <div id="c" style="box-sizing:border-box;width:120px;height:30px;padding:2px 3px;border:1px solid"></div>
                <div id="d" style="box-sizing:border-box;width:130px;height:30px;padding:2px 3px;border:1px solid"></div>
                <div id="vertical" style="box-sizing:border-box;width:140px;height:30px;padding:2px 3px;border:1px solid;writing-mode:vertical-rl"></div>
                <div id="hidden" style="display:none;width:50px;height:20px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 300.0);
        rt.run_page_init();
        rt.execute_script(
            "batch-resize-observer-targets",
            r#"
                globalThis.__resizeBulkCalls = 0;
                globalThis.__resizeBulkSizes = [];
                globalThis.__resizeLegacyGeometryCalls = 0;
                globalThis.__resizeComputedStyleCalls = 0;
                const nativeBulk = __obscura_test_ops.op_resize_observer_measurements;
                const nativeGeometry = __obscura_test_ops.op_layout_geometry;
                const nativeComputedStyle = __obscura_test_ops.op_computed_style;
                __obscura_test_ops.op_resize_observer_measurements = (input, frameId) => {
                    __resizeBulkCalls++;
                    __resizeBulkSizes.push(JSON.parse(input).length);
                    return nativeBulk(input, frameId);
                };
                __obscura_test_ops.op_layout_geometry = (...args) => {
                    __resizeLegacyGeometryCalls++;
                    return nativeGeometry(...args);
                };
                __obscura_test_ops.op_computed_style = (...args) => {
                    __resizeComputedStyleCalls++;
                    return nativeComputedStyle(...args);
                };

                globalThis.__resizeBatchRecords = [];
                const detached = document.createElement("div");
                detached.id = "detached";
                detached.style.cssText = "width:60px;height:20px";
                const targets = ["a", "b", "c", "d", "vertical", "hidden"]
                    .map(id => document.getElementById(id));
                targets.push(detached);
                const observer = new ResizeObserver(entries => {
                    __resizeBatchRecords.push(entries.map(entry => [
                        entry.target.id,
                        entry.contentBoxSize[0].inlineSize,
                        entry.contentBoxSize[0].blockSize,
                        entry.borderBoxSize[0].inlineSize,
                        entry.borderBoxSize[0].blockSize,
                    ]));
                });
                for (const target of targets) observer.observe(target);
                // A second observer of an existing target must share the same
                // native measurement rather than adding it to the batch twice.
                globalThis.__duplicateResizeRecords = 0;
                const duplicate = new ResizeObserver(entries => {
                    __duplicateResizeRecords += entries.length;
                });
                duplicate.observe(targets[2], { box: "border-box" });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();

        assert_eq!(
            rt.evaluate(
                r#"[
                    __resizeBulkCalls,
                    __resizeBulkSizes,
                    __resizeLegacyGeometryCalls,
                    __resizeComputedStyleCalls,
                    __duplicateResizeRecords,
                    __resizeBatchRecords,
                ]"#,
            )
            .unwrap(),
            serde_json::json!([
                1,
                [7],
                0,
                0,
                1,
                [[
                    ["a", 92, 24, 100, 30],
                    ["b", 102, 24, 110, 30],
                    ["c", 112, 24, 120, 30],
                    ["d", 122, 24, 130, 30],
                    ["vertical", 24, 132, 30, 140],
                    ["hidden", 0, 0, 0, 0],
                    ["detached", 0, 0, 0, 0],
                ]],
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn resize_observer_selected_box_and_viewport_lifecycle_match_chromium() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="target" style="box-sizing:border-box;width:50vw;height:40px;
                     padding:4px;border:2px solid"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        rt.execute_script(
            "resize-observer-selected-box",
            r#"
                globalThis.__contentWidths = [];
                globalThis.__borderWidths = [];
                const target = document.getElementById("target");
                globalThis.__contentObserver = new ResizeObserver(entries => {
                    __contentWidths.push(entries[0].contentBoxSize[0].inlineSize);
                });
                globalThis.__borderObserver = new ResizeObserver(entries => {
                    __borderWidths.push(entries[0].borderBoxSize[0].inlineSize);
                });
                __contentObserver.observe(target, { box: "content-box" });
                __borderObserver.observe(target, { box: "border-box" });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("[__contentWidths, __borderWidths]").unwrap(),
            serde_json::json!([[88], [100]])
        );

        // A viewport update is a rendering update even without a DOM mutation.
        rt.set_viewport(300.0, 100.0);
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("[__contentWidths, __borderWidths]").unwrap(),
            serde_json::json!([[88, 138], [100, 150]])
        );

        // With border-box sizing a thicker border shrinks the content box but
        // leaves the selected border box unchanged.
        rt.evaluate(r#"document.getElementById("target").style.borderWidth = "4px""#)
            .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("[__contentWidths, __borderWidths]").unwrap(),
            serde_json::json!([[88, 138, 134], [100, 150]])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn scrolling_does_not_remeasure_resize_observer_targets() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;height:1000px">
                <div id="probe" style="width:40px;height:20px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        rt.execute_script(
            "observe-before-scroll",
            r#"
                globalThis.__scrollResizeRecords = 0;
                globalThis.__scrollResizeObserver = new ResizeObserver(entries => {
                    __scrollResizeRecords += entries.length;
                });
                __scrollResizeObserver.observe(document.getElementById("probe"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__scrollResizeRecords").unwrap().as_f64(),
            Some(1.0)
        );

        rt.execute_script(
            "count-scroll-geometry-reads",
            r#"
                globalThis.__scrollGeometryReads = 0;
                globalThis.__nativeLayoutGeometry = __obscura_test_ops.op_layout_geometry;
                __obscura_test_ops.op_layout_geometry = (...args) => {
                    __scrollGeometryReads++;
                    return __nativeLayoutGeometry(...args);
                };
                window.scrollTo(0, 50);
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        let result = rt
            .evaluate("[scrollY, __scrollGeometryReads, __scrollResizeRecords]")
            .unwrap();
        rt.execute_script(
            "restore-layout-geometry-op",
            "__obscura_test_ops.op_layout_geometry = __nativeLayoutGeometry;",
        )
        .unwrap();
        assert_eq!(result, serde_json::json!([50, 0, 1]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn resize_observer_disconnect_is_reusable_and_inline_boxes_are_empty() {
        let dom = parse_html(
            r#"<html><body><div id="first" style="width:40px;height:20px"></div>
                <span id="inline" style="padding:8px;border:2px solid">text</span>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const deliveries = [];
                    const observer = new ResizeObserver(entries => {
                        deliveries.push(entries.map(entry => [
                            entry.target.id,
                            entry.contentRect.width,
                            entry.borderBoxSize[0].inlineSize,
                        ]));
                        if (deliveries.length === 1) {
                            observer.disconnect();
                            observer.observe(document.getElementById("inline"));
                        } else {
                            observer.disconnect();
                            resolve([deliveries, __resizeObservers.length]);
                        }
                    });
                    observer.observe(document.getElementById("first"));
                    setTimeout(() => resolve(["timed out"]), 100);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([[[["first", 40, 40]], [["inline", 0, 0]]], 0])
        );

        assert_eq!(
            rt.evaluate(
                r#"[
                    (() => { try { new ResizeObserver(null); } catch (e) { return e.name; } })(),
                    (() => { try { new ResizeObserver(() => {}).observe(document); } catch (e) { return e.name; } })(),
                    (() => { try { new ResizeObserver(() => {}).observe(document.body, {box:"margin-box"}); } catch (e) { return e.name; } })(),
                ]"#,
            )
            .unwrap(),
            serde_json::json!(["TypeError", "TypeError", "TypeError"])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn resize_observer_self_resize_is_depth_bounded_without_timer_spin() {
        let dom = parse_html(
            r#"<html><body><div id="target" style="width:40px;height:20px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        rt.execute_script(
            "resize-observer-loop-limit",
            r#"
                globalThis.__resizeCallbacks = 0;
                globalThis.__resizeLoopErrors = 0;
                addEventListener("error", event => {
                    if (event.message === "ResizeObserver loop completed with undelivered notifications.") {
                        __resizeLoopErrors++;
                    }
                });
                const target = document.getElementById("target");
                globalThis.__loopingResizeObserver = new ResizeObserver(() => {
                    __resizeCallbacks++;
                    target.style.width = (40 + __resizeCallbacks) + "px";
                });
                __loopingResizeObserver.observe(target);
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[__resizeCallbacks, __resizeLoopErrors, __obscura_nextPendingTimeoutDelay()]"
            )
            .unwrap(),
            serde_json::json!([1, 1, -1])
        );

        // A later external rendering change starts a fresh bounded cycle; the
        // suppressed same-depth observation did not poison future delivery.
        rt.evaluate(r#"document.getElementById("target").style.width = "60px""#)
            .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("[__resizeCallbacks, __resizeLoopErrors]")
                .unwrap(),
            serde_json::json!([2, 2])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_tracks_viewport_threshold_crossings() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:150px"></div>
                <div id="target" style="height:100px"></div>
                <div style="height:300px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const records = [];
                    const target = document.getElementById("target");
                    const observer = new IntersectionObserver(entries => {
                        for (const entry of entries) {
                            records.push([
                                entry.isIntersecting,
                                Math.round(entry.intersectionRatio * 100) / 100,
                                Math.round(entry.boundingClientRect.top),
                                Math.round(entry.intersectionRect.height),
                            ]);
                        }
                    }, { threshold: [0, 0.5, 1] });
                    observer.observe(target);
                    setTimeout(() => window.scrollTo(0, 100), 25);
                    setTimeout(() => window.scrollTo(0, 260), 50);
                    setTimeout(() => resolve(records), 80);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([[false, 0, 150, 0], [true, 0.5, 50, 50], [false, 0, -110, 0],])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_batches_unique_clip_graph_into_one_native_layout_read() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="root" style="width:200px;height:100px;overflow:hidden">
                    <div id="clip" style="width:150px;height:80px;overflow:auto">
                        <div id="a" style="width:30px;height:20px"></div>
                        <div id="b" style="width:40px;height:20px"></div>
                        <div id="hidden" style="display:none"></div>
                    </div>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(300.0, 200.0);
        rt.run_page_init();
        rt.execute_script(
            "batch-intersection-observer-clip-graph",
            r#"
                globalThis.__intersectionBulkCalls = 0;
                globalThis.__intersectionBulkSizes = [];
                globalThis.__intersectionLegacyGeometryCalls = 0;
                globalThis.__intersectionComputedStyleCalls = 0;
                const nativeBulk = __obscura_test_ops.op_intersection_observer_measurements;
                const nativeGeometry = __obscura_test_ops.op_layout_geometry;
                const nativeComputedStyle = __obscura_test_ops.op_computed_style;
                __obscura_test_ops.op_intersection_observer_measurements = (input, frameId) => {
                    __intersectionBulkCalls++;
                    __intersectionBulkSizes.push(JSON.parse(input).length);
                    return nativeBulk(input, frameId);
                };
                __obscura_test_ops.op_layout_geometry = (...args) => {
                    __intersectionLegacyGeometryCalls++;
                    return nativeGeometry(...args);
                };
                __obscura_test_ops.op_computed_style = (...args) => {
                    __intersectionComputedStyleCalls++;
                    return nativeComputedStyle(...args);
                };

                const root = document.getElementById("root");
                const a = document.getElementById("a");
                const b = document.getElementById("b");
                const hidden = document.getElementById("hidden");
                const detached = document.createElement("div");
                detached.id = "detached";
                globalThis.__intersectionBatchRecords = [];
                const first = new IntersectionObserver(entries => {
                    __intersectionBatchRecords.push(entries.map(entry => [
                        entry.target.id,
                        entry.isIntersecting,
                    ]));
                }, { root });
                const second = new IntersectionObserver(entries => {
                    __intersectionBatchRecords.push(entries.map(entry => [
                        entry.target.id,
                        entry.isIntersecting,
                    ]));
                }, { root });
                first.observe(a);
                first.observe(b);
                first.observe(hidden);
                first.observe(detached);
                // The second observer shares its target, root, and clip ancestor
                // with the first and must not duplicate any native measurements.
                second.observe(b);
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();

        assert_eq!(
            rt.evaluate(
                r#"[
                    __intersectionBulkCalls,
                    __intersectionBulkSizes,
                    __intersectionLegacyGeometryCalls,
                    __intersectionComputedStyleCalls,
                    __intersectionBatchRecords,
                ]"#,
            )
            .unwrap(),
            serde_json::json!([
                1,
                [6],
                0,
                0,
                [
                    [
                        ["a", true],
                        ["b", true],
                        ["hidden", false],
                        ["detached", false],
                    ],
                    [["b", true]],
                ],
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_delivers_document_batch_before_callback_posted_tasks() {
        let dom = parse_html(
            r#"<html><body><div id="first"></div><div id="second"></div></body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.run_page_init();
        rt.execute_script(
            "intersection-document-delivery-batch",
            r#"
                globalThis.__intersectionDeliveryOrder = [];
                const first = new IntersectionObserver(() => {
                    __intersectionDeliveryOrder.push("first-observer");
                    scheduler.postTask(() => {
                        __intersectionDeliveryOrder.push("callback-posted-task");
                    }, { priority: "user-blocking" });
                });
                const second = new IntersectionObserver(() => {
                    __intersectionDeliveryOrder.push("second-observer");
                });
                first.observe(document.getElementById("first"));
                second.observe(document.getElementById("second"));
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__intersectionDeliveryOrder").unwrap(),
            serde_json::json!(["first-observer", "second-observer", "callback-posted-task",])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_delivery_recovers_across_document_replacement() {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html("<html><body></body></html>"));
        rt.run_page_init();
        rt.execute_script(
            "old-intersection-delivery",
            r#"
                globalThis.__intersectionReplacementOrder = [];
                const oldObserver = new IntersectionObserver(() => {
                    __intersectionReplacementOrder.push("old");
                });
                oldObserver._records.push({ old: true });
                oldObserver._check([], false, new Map());
            "#,
        )
        .unwrap();

        rt.set_dom(parse_html("<html><body></body></html>"));
        rt.execute_script(
            "fresh-intersection-delivery",
            r#"
                const freshObserver = new IntersectionObserver(() => {
                    __intersectionReplacementOrder.push("fresh");
                });
                freshObserver._records.push({ fresh: true });
                freshObserver._check([], false, new Map());
            "#,
        )
        .unwrap();

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("__intersectionReplacementOrder").unwrap(),
            serde_json::json!(["fresh"]),
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_element_root_uses_live_padding_box_and_scroll() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="root" style="position:absolute;left:10px;top:20px;width:100px;
                     height:80px;padding:10px;border:5px solid;overflow:auto">
                    <div style="height:100px"></div>
                    <div id="target" style="height:20px"></div>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(300.0, 200.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const records = [];
                    const root = document.getElementById("root");
                    const observer = new IntersectionObserver(entries => {
                        records.push(...entries.map(entry => ({
                            intersecting: entry.isIntersecting,
                            ratio: entry.intersectionRatio,
                            root: [
                                entry.rootBounds.x, entry.rootBounds.y,
                                entry.rootBounds.width, entry.rootBounds.height,
                            ],
                            intersection: [
                                entry.intersectionRect.x, entry.intersectionRect.y,
                                entry.intersectionRect.width, entry.intersectionRect.height,
                            ],
                        })));
                    }, { root, threshold: [0, 1] });
                    observer.observe(document.getElementById("target"));
                    setTimeout(() => { root.scrollTop = 999; }, 25);
                    setTimeout(() => resolve(records), 60);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([
                {
                    "intersecting": false,
                    "ratio": 0,
                    "root": [15, 25, 120, 100],
                    "intersection": [0, 0, 0, 0],
                },
                {
                    "intersecting": true,
                    "ratio": 1,
                    "root": [15, 25, 120, 100],
                    "intersection": [25, 95, 100, 20],
                },
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_clips_through_intermediate_overflow_ancestors() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="root" style="position:absolute;left:10px;top:20px;
                     width:300px;height:300px;overflow:visible">
                    <div id="clip" style="width:100px;height:100px;overflow:hidden">
                        <div style="height:150px"></div>
                        <div id="target" style="height:20px"></div>
                    </div>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(400.0, 400.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const records = [];
                    const clip = document.getElementById("clip");
                    const observer = new IntersectionObserver(entries => {
                        records.push(...entries.map(entry => [
                            entry.isIntersecting,
                            entry.intersectionRatio,
                            [
                                entry.intersectionRect.x,
                                entry.intersectionRect.y,
                                entry.intersectionRect.width,
                                entry.intersectionRect.height,
                            ],
                        ]));
                    }, {
                        root: document.getElementById("root"),
                        threshold: [0, 1],
                    });
                    observer.observe(document.getElementById("target"));
                    setTimeout(() => { clip.scrollTop = 999; }, 25);
                    setTimeout(() => resolve(records), 60);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        // Chromium reports the initial target as non-intersecting: although it
        // lies inside the explicit root, the intermediate overflow container
        // clips it. Programmatic scrolling then reveals the complete box.
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([[false, 0, [0, 0, 0, 0]], [true, 1, [10, 100, 100, 20]],])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_initial_geometry_waits_for_one_render_checkpoint() {
        let mut rt = setup_runtime(
            r#"<html><body><div id="first"></div><div id="second"></div></body></html>"#,
        );
        rt.execute_script(
            "intersection-render-checkpoint",
            r#"
                globalThis.__ioOrder = ["sync"];
                globalThis.__ioReads = 0;
                const first = document.getElementById("first");
                const second = document.getElementById("second");
                for (const element of [first, second]) {
                    const nativeRect = element.getBoundingClientRect.bind(element);
                    element.getBoundingClientRect = () => {
                        __ioReads++;
                        return nativeRect();
                    };
                }
                const observer = new IntersectionObserver(
                    () => __ioOrder.push("observer")
                );
                observer.observe(first);
                observer.observe(second);
                Promise.resolve().then(() => __ioOrder.push("microtask"));
                __ioOrder.push("after-observe-" + __ioReads);
            "#,
        )
        .unwrap();

        assert_eq!(
            rt.evaluate("[__ioOrder, __ioReads]").unwrap(),
            serde_json::json!([["sync", "after-observe-0", "microtask"], 0])
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        #[cfg(feature = "render")]
        let expected_geometry_reads = 0;
        #[cfg(not(feature = "render"))]
        let expected_geometry_reads = 2;
        assert_eq!(
            rt.evaluate("[__ioOrder, __ioReads]").unwrap(),
            serde_json::json!([
                ["sync", "after-observe-0", "microtask", "observer"],
                expected_geometry_reads,
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_honors_root_margin_zero_area_and_no_fake_refires() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;position:relative">
                <div style="height:110px"></div>
                <div id="margin-target" style="height:10px"></div>
                <div id="zero" style="position:absolute;left:20px;top:50px;width:0;height:0"></div>
                <div id="root" style="height:20px;overflow:auto"></div>
                <div style="height:300px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const marginRecords = [], zeroRecords = [];
                    const marginObserver = new IntersectionObserver(
                        entries => marginRecords.push(...entries.map(entry => [
                            entry.isIntersecting,
                            entry.intersectionRatio,
                            entry.rootBounds.bottom,
                        ])),
                        { rootMargin: "0px 0px 20px", threshold: [0, 1] }
                    );
                    const zeroObserver = new IntersectionObserver(
                        entries => zeroRecords.push(...entries.map(entry => [
                            entry.isIntersecting,
                            entry.intersectionRatio,
                        ]))
                    );
                    marginObserver.observe(document.getElementById("margin-target"));
                    zeroObserver.observe(document.getElementById("zero"));
                    let elementRoot = false;
                    try {
                        const rooted = new IntersectionObserver(() => {}, {
                            root: document.getElementById("root")
                        });
                        elementRoot = rooted.root === document.getElementById("root");
                    } catch (error) {
                        elementRoot = error.name;
                    }
                    setTimeout(() => resolve([
                        marginRecords, zeroRecords, elementRoot,
                        marginObserver.rootMargin, marginObserver.thresholds,
                    ]), 200);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([
                [[true, 1, 120]],
                [[true, 1]],
                true,
                "0px 0px 20px 0px",
                [0, 1],
            ])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_does_not_refire_while_target_stays_intersecting() {
        let dom = parse_html(
            r#"<html><body>
                <div id="feed"></div>
                <div id="sentinel"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(1280.0, 720.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const feed = document.getElementById("feed");
                    let loaded = 0;
                    const observer = new IntersectionObserver(entries => {
                        for (const entry of entries) {
                            if (!entry.isIntersecting) continue;
                            for (let i = 0; i < 10; i++) {
                                const card = document.createElement("div");
                                card.textContent = "Item " + loaded++;
                                feed.appendChild(card);
                            }
                        }
                    });
                    observer.observe(document.getElementById("sentinel"));
                    setTimeout(() => resolve([
                        loaded,
                        feed.querySelectorAll("div").length,
                    ]), 200);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!([10, 10]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_can_be_reused_after_disconnect() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="stale" style="height:10px"></div>
                <div id="first" style="height:10px"></div>
                <div id="second" style="height:10px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    const deliveries = [];
                    const observer = new IntersectionObserver(entries => {
                        deliveries.push(entries.map(entry => entry.target.id));
                        if (deliveries.length === 1) {
                            observer.disconnect();
                            observer.observe(document.getElementById("second"));
                        } else {
                            observer.disconnect();
                            resolve([
                                deliveries,
                                globalThis.__intersectionObservers.length,
                            ]);
                        }
                    });

                    // A pending record from before disconnect must be discarded.
                    observer.observe(document.getElementById("stale"));
                    observer.disconnect();
                    observer.observe(document.getElementById("first"));
                    setTimeout(() => resolve(["timed out"]), 100);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([[["first"], ["second"]], 0,])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_recomputes_after_style_mutation_and_resize() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div id="spacer" style="height:150px"></div>
                <div id="target" style="height:20px"></div>
                <div style="height:300px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        rt.execute_script(
            "intersection-mutation",
            r#"
                globalThis.__ioRecords = [];
                globalThis.__io = new IntersectionObserver(entries => {
                    __ioRecords.push(...entries.map(entry => [
                        entry.isIntersecting,
                        Math.round(entry.boundingClientRect.top),
                    ]));
                });
                __io.observe(document.getElementById("target"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();

        rt.evaluate(r#"document.getElementById("spacer").setAttribute("style", "height:120px")"#)
            .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__ioRecords").unwrap(),
            serde_json::json!([[false, 150]])
        );

        rt.set_viewport(200.0, 160.0);
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__ioRecords").unwrap(),
            serde_json::json!([[false, 150], [true, 120]])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn intersection_observer_recomputes_after_root_scroll() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:150px"></div>
                <div id="target" style="height:20px"></div>
                <div style="height:300px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();
        rt.execute_script(
            "intersection-root-scroll",
            r#"
                globalThis.__rootScrollIoRecords = [];
                globalThis.__rootScrollIo = new IntersectionObserver(entries => {
                    __rootScrollIoRecords.push(...entries.map(entry => [
                        entry.isIntersecting,
                        Math.round(entry.boundingClientRect.top),
                    ]));
                });
                __rootScrollIo.observe(document.getElementById("target"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        rt.evaluate("window.scrollTo(0, 100)").unwrap();
        rt.run_event_loop_bounded(40).await.unwrap();
        assert_eq!(
            rt.evaluate("__rootScrollIoRecords").unwrap(),
            serde_json::json!([[false, 150], [true, 50]])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn scroll_into_view_aligns_the_root_viewport_and_clamps() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:300px"></div>
                <div id="target" style="height:40px"></div>
                <div style="height:340px"></div>
                <div id="bottom" style="height:20px"></div>
                <div id="fixed" style="position:fixed;top:10px;height:20px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        let result = rt
            .evaluate(
                r#"
                const target = document.getElementById("target");
                const bottom = document.getElementById("bottom");
                const fixed = document.getElementById("fixed");
                target.scrollIntoView();
                const start = scrollY;
                scrollTo(0, 0);
                target.scrollIntoView({ block: "center" });
                const center = scrollY;
                scrollTo(0, 0);
                target.scrollIntoView({ block: "end" });
                const end = scrollY;
                scrollTo(0, 0);
                target.scrollIntoView({ block: "nearest" });
                const nearestOutside = scrollY;
                scrollTo(0, 250);
                target.scrollIntoView({ block: "nearest" });
                const nearestVisible = scrollY;
                fixed.scrollIntoView();
                const afterFixed = scrollY;
                bottom.scrollIntoView({ block: "start" });
                const clamped = scrollY;
                const max = document.documentElement.scrollHeight - innerHeight;
                return [
                    start, center, end, nearestOutside, nearestVisible,
                    afterFixed, clamped, max,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([300, 270, 240, 240, 250, 250, 600, 600])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn scroll_into_view_moves_nested_scrollports_before_the_viewport() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;height:1800px">
                <div id="scroller" style="margin-top:200px;height:200px;overflow:auto">
                    <div style="height:600px"></div>
                    <div id="target" style="height:40px"></div>
                    <div style="height:600px"></div>
                </div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(800.0, 600.0);
        rt.run_page_init();
        let result = rt.evaluate(r#"
            const scroller = document.getElementById('scroller');
            const target = document.getElementById('target');
            const results = [];
            for (const block of ['nearest', 'center', 'start', 'end']) {
                scrollTo(0, 0);
                scroller.scrollTop = 0;
                target.scrollIntoView({block});
                results.push([scroller.scrollTop, scrollY, target.getBoundingClientRect().top]);
            }
            scrollTo(0, 0);
            target.scrollIntoView({block: 'nearest'});
            results.push([scroller.scrollTop, scrollY, target.getBoundingClientRect().top]);
            return results;
        "#).unwrap();
        assert_eq!(result, serde_json::json!([
            [440, 0, 360], [520, 0, 280], [600, 200, 0],
            [440, 0, 360], [440, 0, 360],
        ]));
    }

    #[test]
    fn removing_a_focused_subtree_clears_focus_without_firing_blur() {
        let mut rt = setup_runtime("<main id=parent></main>");
        let result = rt.evaluate(r#"
            const parent = document.getElementById('parent');
            const rows = [];
            for (const remove of [
                host => host.remove(),
                host => parent.removeChild(host),
                host => parent.replaceChild(document.createElement('div'), host),
                host => { parent.innerHTML = ''; },
                host => { parent.textContent = ''; },
                host => parent.replaceChildren(),
                host => host.replaceWith(document.createElement('div')),
            ]) {
                parent.innerHTML = '<section><button>Apply</button></section>';
                const host = parent.firstChild, button = host.firstChild;
                let blurred = 0;
                button.addEventListener('blur', () => blurred++);
                button.addEventListener('focusout', () => blurred++);
                button.focus();
                const focused = document.activeElement === button;
                remove(host);
                // Reinsert without reading activeElement while disconnected.
                parent.appendChild(host);
                rows.push([focused, document.activeElement === document.body, blurred]);
            }
            return rows;
        "#).unwrap();
        assert_eq!(result, serde_json::json!(vec![serde_json::json!([true,true,0]); 7]));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn scroll_into_view_emits_events_only_when_the_root_moves() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:300px"></div>
                <div id="target" style="height:40px"></div>
                <div style="height:300px"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_viewport(200.0, 100.0);
        rt.run_page_init();

        rt.evaluate("window.scrollTo(0, 250)").unwrap();
        rt.run_event_loop_bounded(20).await.unwrap();
        let no_op = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    let win = 0, doc = 0;
                    window.addEventListener("scroll", () => win++);
                    document.addEventListener("scroll", () => doc++);
                    document.getElementById("target").scrollIntoView({ block: "nearest" });
                    setTimeout(() => resolve([win, doc, scrollY]), 5);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(no_op.value.unwrap(), serde_json::json!([0, 0, 250]));

        rt.evaluate("window.scrollTo(0, 0)").unwrap();
        rt.run_event_loop_bounded(20).await.unwrap();
        let moved = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    let win = 0, doc = 0;
                    window.addEventListener("scroll", () => win++);
                    document.addEventListener("scroll", () => doc++);
                    document.getElementById("target").scrollIntoView({ block: "center" });
                    setTimeout(() => resolve([win, doc, scrollY]), 5);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(moved.value.unwrap(), serde_json::json!([1, 1, 270]));
    }

    /// Issue #469: FILTER_SKIP leaves a skipped node's children eligible, so
    /// firstChild()/lastChild() must descend into them. FILTER_REJECT must not.
    #[test]
    fn tree_walker_child_movers_descend_on_skip_but_not_on_reject() {
        let mut rt = setup_runtime(r#"<div id="root"><section><a></a><b></b></section></div>"#);
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                function mover(verdict, method) {
                    const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                        acceptNode(node) {
                            return node.tagName === 'SECTION' ? verdict : NodeFilter.FILTER_ACCEPT;
                        }
                    });
                    const found = w[method]();
                    return found ? found.tagName : null;
                }
                return [
                    mover(NodeFilter.FILTER_SKIP, 'firstChild'),
                    mover(NodeFilter.FILTER_SKIP, 'lastChild'),
                    mover(NodeFilter.FILTER_REJECT, 'firstChild'),
                    mover(NodeFilter.FILTER_REJECT, 'lastChild'),
                ];
                "#,
            )
            .unwrap();
        // SKIP descends into <section>; REJECT prunes it and finds nothing else.
        assert_eq!(result, serde_json::json!(["A", "B", null, null]));
    }

    /// Issue #469: nextSibling()/previousSibling() must descend into a skipped
    /// sibling's subtree rather than stepping straight over it.
    #[test]
    fn tree_walker_sibling_movers_descend_into_skipped_siblings() {
        let mut rt = setup_runtime(
            r#"<div id="root"><p id="start"></p><section><a></a></section><q></q></div>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                function mover(verdict, method, from) {
                    const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                        acceptNode(node) {
                            return node.tagName === 'SECTION' ? verdict : NodeFilter.FILTER_ACCEPT;
                        }
                    });
                    w.currentNode = document.getElementById(from);
                    const found = w[method]();
                    return found ? found.tagName : null;
                }
                return [
                    // <section> is skipped, so its child <a> is the next sibling.
                    mover(NodeFilter.FILTER_SKIP, 'nextSibling', 'start'),
                    // Rejected: the subtree is off-limits, so skip past to <q>.
                    mover(NodeFilter.FILTER_REJECT, 'nextSibling', 'start'),
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(["A", "Q"]));
    }

    /// Issue #469: the backward sibling mover descends to *last* children.
    #[test]
    fn tree_walker_previous_sibling_descends_to_last_child() {
        let mut rt = setup_runtime(
            r#"<div id="root"><section><a></a><b></b></section><p id="start"></p></div>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const root = document.getElementById('root');
                const w = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
                    acceptNode(node) {
                        return node.tagName === 'SECTION'
                            ? NodeFilter.FILTER_SKIP
                            : NodeFilter.FILTER_ACCEPT;
                    }
                });
                w.currentNode = document.getElementById('start');
                const found = w.previousSibling();
                return found ? found.tagName : null;
                "#,
            )
            .unwrap();
        // Reverse order descends to <section>'s last child, not its first.
        assert_eq!(result, serde_json::json!("B"));
    }

    #[test]
    fn append_child_flattens_document_fragment() {
        let mut rt = setup_runtime(r#"<main id="host"></main>"#);
        let result = rt
            .evaluate(
                r#"
                const host = document.getElementById('host');
                const fragment = document.createDocumentFragment();
                const first = document.createElement('article');
                const second = document.createElement('article');
                first.id = 'first';
                second.id = 'second';
                first.className = second.className = 'quote';
                fragment.appendChild(first);
                fragment.appendChild(second);

                const returned = host.appendChild(fragment);
                return [
                    returned === fragment,
                    Array.from(host.children).map(node => node.id),
                    host.querySelectorAll('.quote').length,
                    fragment.childNodes.length,
                    first.parentNode === host,
                    first.parentElement === host,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, ["first", "second"], 2, 0, true, true])
        );
    }

    #[test]
    fn insert_before_flattens_document_fragment_in_order() {
        let mut rt = setup_runtime(r#"<main id="host"><article id="last"></article></main>"#);
        let result = rt
            .evaluate(
                r#"
                const host = document.getElementById('host');
                const last = document.getElementById('last');
                const fragment = document.createDocumentFragment();
                const first = document.createElement('article');
                const second = document.createElement('article');
                first.id = 'first';
                second.id = 'second';
                fragment.appendChild(first);
                fragment.appendChild(second);

                const returned = host.insertBefore(fragment, last);
                return [
                    returned === fragment,
                    Array.from(host.children).map(node => node.id),
                    fragment.childNodes.length,
                    first.parentElement === host,
                    second.parentElement === host,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, ["first", "second", "last"], 0, true, true])
        );
    }

    #[test]
    fn replace_child_flattens_document_fragment_and_removes_old_child() {
        let mut rt = setup_runtime(
            r#"<main id="host"><article id="old"></article><article id="tail"></article></main>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const host = document.getElementById('host');
                const old = document.getElementById('old');
                const fragment = document.createDocumentFragment();
                const first = document.createElement('article');
                const second = document.createElement('article');
                first.id = 'first';
                second.id = 'second';
                fragment.appendChild(first);
                fragment.appendChild(second);

                const returned = host.replaceChild(fragment, old);
                return [
                    returned === old,
                    Array.from(host.children).map(node => node.id),
                    fragment.childNodes.length,
                    old.parentNode === null,
                    first.parentElement === host,
                    second.parentElement === host,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, ["first", "second", "tail"], 0, true, true, true])
        );
    }

    #[test]
    fn test_inner_html() {
        let mut rt = setup_runtime(r#"<div id="x"><p>Hello</p></div>"#);
        let html = rt
            .evaluate("document.getElementById('x').innerHTML")
            .unwrap();
        assert!(html.as_str().unwrap().contains("<p>"));
    }

    #[test]
    fn template_inner_html_preserves_table_fragments() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const template = document.createElement('template');
                template.innerHTML = '<tr><td>first</td><td>second</td></tr>';
                const clone = template.content.firstChild.cloneNode(true);
                return [
                    clone.tagName,
                    clone.firstElementChild.tagName,
                    clone.firstElementChild.children.length,
                    clone.textContent,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(["TR", "TD", 0, "firstsecond"]));
    }

    #[test]
    fn document_exposes_parent_node_element_children_api() {
        let mut rt = setup_runtime("<html><head></head><body></body></html>");
        let result = rt
            .evaluate(
                "return [document.firstElementChild === document.documentElement,\
                         document.lastElementChild === document.documentElement,\
                         document.children.length, document.childElementCount];",
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true, 1, 1]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn atob_decodes_large_payload_without_argument_stack_overflow() {
        let mut rt = setup_runtime("<html><body></body></html>");
        // 60k four-character groups decode to 180k bytes, comfortably above
        // V8's maximum argument count for a single fromCharCode(...bytes).
        let encoded = "QUFB".repeat(60_000);
        let result = rt.evaluate(&format!("atob('{}').length", encoded)).unwrap();
        assert_eq!(result.as_f64().unwrap() as usize, 180_000);
    }

    // #996: btoa maps each code unit to one Latin-1 byte and throws for code
    // points above 0xFF — it must not UTF-8-encode the input.
    #[test]
    fn btoa_encodes_latin1_not_utf8() {
        let mut rt = setup_runtime("<html><body></body></html>");
        // é (U+00E9) is the single byte 0xE9 -> "6Q==", not UTF-8's "w6k=".
        assert_eq!(rt.evaluate("btoa('é')").unwrap(), serde_json::json!("6Q=="));
        assert_eq!(
            rt.evaluate("btoa('hello')").unwrap(),
            serde_json::json!("aGVsbG8=")
        );
        // A code point above 0xFF must throw InvalidCharacterError.
        let name = rt
            .evaluate(
                r#"(() => { try { btoa('\u{1F600}'); return 'no-throw'; } catch (e) { return e.name; } })()"#,
            )
            .unwrap();
        assert_eq!(name, serde_json::json!("InvalidCharacterError"));
    }

    #[test]
    fn navigation_api_updates_current_entry_state() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                (() => {
                    navigation.updateCurrentEntry({state: {route: 'home'}});
                    const first = navigation.currentEntry;
                    navigation.navigate('/docs', {state: {route: 'docs'}});
                    return [
                        typeof navigation.updateCurrentEntry,
                        first.getState().route,
                        navigation.currentEntry.getState().route,
                        navigation.currentEntry.url,
                    ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["function", "home", "docs", "http://example.com/docs"])
        );
    }

    #[test]
    fn stylesheet_cssom_exposes_trace_instrumentation_interfaces() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(
            rt.evaluate(
                "return [typeof StyleSheet, typeof CSSGroupingRule,\
                  new CSSStyleSheet() instanceof StyleSheet,\
                  typeof CSSGroupingRule.prototype.insertRule,\
                  typeof Object.getOwnPropertyDescriptor(StyleSheet.prototype, 'disabled')?.set]"
            ).unwrap(),
            serde_json::json!(["function", "function", true, "function", "function"])
        );
    }

    #[test]
    fn stylesheet_rule_iteration_does_not_copy_the_sheet_per_rule() {
        let mut rt = setup_runtime("<html><head></head><body></body></html>");
        let result = rt.evaluate(r#"
            (() => {
                const style = document.createElement('style');
                style.textContent = Array.from({length: 512}, (_, i) =>
                    `.r${i} { width: ${i}px }`).join('\n');
                document.head.append(style);
                const sheet = style.sheet;
                const descriptor = Object.getOwnPropertyDescriptor(Node.prototype, 'textContent');
                let reads = 0;
                Object.defineProperty(style, 'textContent', {
                    get() { reads++; return descriptor.get.call(this); },
                    set(value) { descriptor.set.call(this, value); },
                });
                const rules = sheet.cssRules;
                const selectors = Array.from(rules, rule => rule.selectorText);
                const iterationReads = reads;
                const first = rules[0];
                first.style.width = '91px';
                const edited = rules[0] === first && rules[0].style.width === '91px';
                style.firstChild.data = '.replacement { height: 8px }';
                const replaced = rules.length === 1 && rules[0].selectorText === '.replacement';
                style.append(document.createTextNode('.appended { height: 9px }'));
                const appended = rules.length === 2 && rules[1].selectorText === '.appended';
                style.lastChild.remove();
                return {iterationReads, count: selectors.length, last: selectors.at(-1),
                    edited, replaced, appended, removed: rules.length === 1};
            })()
        "#).unwrap();
        assert!(result["iterationReads"].as_u64().unwrap() <= 1,
            "unchanged CSSRuleList iteration copied its whole source repeatedly: {result}");
        assert_eq!(result["count"], 512);
        assert_eq!(result["last"], ".r511");
        for key in ["edited", "replaced", "appended", "removed"] {
            assert_eq!(result[key], true, "live CSSOM lost {key}: {result}");
        }
    }

    #[cfg(feature = "render")]
    #[test]
    fn stylesheet_rule_writes_preserve_dom_source_and_update_layout() {
        let mut rt = setup_runtime("<html><head><style id='rules'>#box { width: 11px }</style></head><body><div id='box'></div></body></html>");
        let result = rt.evaluate(r#"
            (() => {
                const style = document.getElementById('rules');
                const source = style.textContent;
                const text = style.firstChild;
                const sheet = style.sheet;
                const first = sheet.cssRules[0];
                const observer = new MutationObserver(() => {});
                observer.observe(style, {subtree: true, childList: true, characterData: true});
                let serialized = 0;
                const descriptor = Object.getOwnPropertyDescriptor(CSSStyleRule.prototype, 'cssText');
                Object.defineProperty(first, 'cssText', {get() {
                    serialized++;
                    return descriptor.get.call(this);
                }});
                for (let i = 0; i < 512; i++) sheet.insertRule(`.r${i} { height: ${i}px }`, sheet.cssRules.length);
                sheet.insertRule('#box { width: 73px }', sheet.cssRules.length);
                const inserted = document.getElementById('box').getBoundingClientRect().width;
                sheet.cssRules[513].style.width = '91px';
                const edited = document.getElementById('box').getBoundingClientRect().width;
                sheet.deleteRule(513);
                const deleted = document.getElementById('box').getBoundingClientRect().width;
                const preserved = style.textContent === source && style.firstChild === text;
                const records = observer.takeRecords().length;
                observer.disconnect();
                style.textContent = '#box { width: 17px }';
                const reset = style.sheet.cssRules.length;
                return {preserved, records, serialized, inserted, edited, deleted, reset};
            })()
        "#).unwrap();
        assert_eq!(result["preserved"], true, "CSSOM writes changed DOM source: {result}");
        assert_eq!(result["records"], 0, "CSSOM writes emitted DOM mutations: {result}");
        assert!(result["serialized"].as_u64().unwrap() <= 4, "append serialized prior rules repeatedly: {result}");
        assert_eq!(result["inserted"], 73);
        assert_eq!(result["edited"], 91);
        assert_eq!(result["deleted"], 11);
        assert_eq!(result["reset"], 1);
    }

    #[cfg(feature = "render")]
    #[test]
    fn stylesheet_same_text_data_assignment_discards_cssom_override() {
        let mut rt = setup_runtime("<html><head><style id='s'>#box { width: 11px }</style></head><body><div id='box'></div></body></html>");
        let result = rt.evaluate(r#"(() => {
            const style = document.getElementById('s');
            const box = document.getElementById('box');
            style.sheet.insertRule('#box { width: 73px }', 1);
            const inserted = box.getBoundingClientRect().width;
            style.firstChild.data = style.firstChild.data;
            return [inserted, box.getBoundingClientRect().width, style.sheet.cssRules.length];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([73, 11, 1]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cache_storage_feature_detection_does_not_select_a_noop_backend() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate_for_cdp_with_timeout(r#"
            (async () => {
                const response = new Response('resource bytes');
                if (!('caches' in globalThis)) return response.text();
                const cache = await caches.open('capability-contract');
                await cache.put('https://example.com/resource', response);
                const stored = await cache.match('https://example.com/resource');
                return stored ? stored.text() : null;
            })()
        "#, true, true, 1000).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!("resource bytes")),
            "an advertised cache must retain bytes, otherwise callers must be able to fall back");
    }

    #[test]
    fn linked_stylesheet_reads_are_bounded_and_host_updates_invalidate() {
        let mut rt = setup_runtime("<html><head><link id='sheet' rel='stylesheet' href='/rules.css'></head><body></body></html>");
        let owner = rt.state.borrow().dom.as_ref().unwrap().get_element_by_id("sheet").unwrap();
        let css = (0..512).map(|i| format!(".r{i} {{ width: {i}px }}")).collect::<Vec<_>>().join("\n");
        assert!(rt.state.borrow().dom.as_ref().unwrap().replace_external_stylesheet(owner, css, true));
        rt.execute_script("<linked-sheet>", "globalThis.__obscura_registerLinkedStylesheet(document.getElementById('sheet'), 'http://example.com/rules.css')").unwrap();
        let result = rt.evaluate(r#"
            (() => {
                globalThis.linkedSheet = document.getElementById('sheet').sheet;
                globalThis.linkedRules = linkedSheet.cssRules;
                const parse = JSON.parse;
                let copies = 0;
                JSON.parse = function(source, ...args) {
                    if (typeof source === 'string' && source.includes('"originClean"')) copies++;
                    return parse(source, ...args);
                };
                try {
                    const selectors = Array.from(linkedRules, rule => rule.selectorText);
                    return { copies, count: selectors.length, last: selectors.at(-1) };
                } finally { JSON.parse = parse; }
            })()
        "#).unwrap();
        assert_eq!(result["count"], 512);
        assert_eq!(result["last"], ".r511");
        assert!(result["copies"].as_u64().unwrap() <= 1, "linked sheet copied per rule: {result}");
        // Host loading bypasses JS DOM mutation hooks, including @import taint.
        assert!(rt.state.borrow().dom.as_ref().unwrap().append_external_stylesheet(owner, ".host { height: 9px }".into(), true));
        assert_eq!(rt.evaluate("[linkedRules.length, linkedRules[512].selectorText]").unwrap(), serde_json::json!([513, ".host"]));
        assert!(rt.state.borrow().dom.as_ref().unwrap().append_external_stylesheet(owner, ".secret { color: red }".into(), false));
        assert_eq!(rt.evaluate("(() => { try { linkedSheet.cssRules; return 'leaked'; } catch(e) { return e.name; } })()").unwrap(), serde_json::json!("SecurityError"));
        assert!(rt.state.borrow().dom.as_ref().unwrap().replace_external_stylesheet(owner, ".replacement { width: 3px }".into(), true));
        assert_eq!(rt.evaluate("[linkedRules.length, linkedRules[0].selectorText]").unwrap(), serde_json::json!([1, ".replacement"]));
    }

    #[test]
    fn inline_stylesheet_cssom_lists_and_rules_are_live_same_objects() {
        let mut rt = setup_runtime(
            r#"<html><head>
                <style id="first">.one { color:red } .two { width:20px }</style>
                <style id="second">.three { display:block }</style>
            </head><body></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const list = document.styleSheets;
                    const style = document.getElementById('first');
                    const sheet = style.sheet;
                    const rules = sheet.cssRules;
                    const firstRule = rules[0];
                    const initial = [
                        list === document.styleSheets,
                        list.length,
                        list[0] === sheet,
                        list.item(0) === sheet,
                        list.item(9),
                        sheet.ownerNode === style,
                        rules === sheet.cssRules,
                        rules.length,
                        rules.item(0) === firstRule,
                        firstRule instanceof CSSRule,
                        firstRule instanceof CSSStyleRule,
                        firstRule.type,
                        firstRule.selectorText,
                        firstRule.style.color,
                        firstRule.parentStyleSheet === sheet,
                    ];

                    sheet.insertRule('.middle { height: 30px; }', 1);
                    const inserted = [
                        rules.length,
                        rules[0] === firstRule,
                        rules[1].selectorText,
                        style.textContent.includes('.middle'),
                    ];
                    sheet.deleteRule(1);

                    const extra = document.createElement('style');
                    document.head.appendChild(extra);
                    const afterAppend = list.length;
                    const emptySheet = extra.sheet;
                    const emptyIdentity = emptySheet === list[2]
                        && emptySheet.cssRules.length === 0;
                    extra.textContent = '.extra { opacity:.5 }';
                    const emptyBecameLive = emptySheet.cssRules.length === 1;
                    extra.remove();
                    const afterRemove = list.length;

                    style.textContent = '.replacement { padding: 4px; }';
                    const reparsed = [
                        style.sheet === sheet,
                        sheet.cssRules === rules,
                        rules.length,
                        rules[0].selectorText,
                        rules[0].style.padding,
                    ];
                    style.remove();
                    const disconnected = style.sheet === null
                        && sheet.ownerNode === null
                        && list.length === 1;
                    document.head.appendChild(style);
                    const reconnected = style.sheet !== sheet
                        && style.sheet.ownerNode === style
                        && list.length === 2;

                    const left = document.createElement('div');
                    const right = document.createElement('div');
                    document.body.append(left, right);
                    const moving = document.createElement('style');
                    moving.textContent = '.moving { color: red }';
                    left.appendChild(moving);
                    const beforeMove = moving.sheet;
                    right.appendChild(moving);
                    const reparented = beforeMove.ownerNode === null
                        && moving.sheet !== beforeMove
                        && moving.sheet.ownerNode === moving;
                    right.remove();
                    left.remove();

                    const bulk = document.createElement('div');
                    document.body.appendChild(bulk);
                    bulk.innerHTML = '<style>.bulk { color: blue }</style><span></span>';
                    const bulkSheet = bulk.querySelector('style').sheet;
                    bulk.innerHTML = '';
                    const innerHTMLDetached = bulkSheet.ownerNode === null;
                    bulk.innerHTML = '<section><style>.text { color: green }</style></section>';
                    const textSheet = bulk.querySelector('style').sheet;
                    bulk.textContent = '';
                    const textContentDetached = textSheet.ownerNode === null;
                    bulk.remove();
                    return {
                        initial, inserted, afterAppend, emptyIdentity, emptyBecameLive,
                        afterRemove, reparsed, disconnected, reconnected, reparented,
                        innerHTMLDetached, textContentDetached,
                    };
                })()
                "#,
            )
            .unwrap();

        assert_eq!(
            result,
            serde_json::json!({
                "initial": [true, 2, true, true, null, true, true, 2, true,
                    true, true, 1, ".one", "red", true],
                "inserted": [3, true, ".middle", false],
                "afterAppend": 3,
                "emptyIdentity": true,
                "emptyBecameLive": true,
                "afterRemove": 2,
                "reparsed": [true, true, 1, ".replacement", "4px"],
                "disconnected": true,
                "reconnected": true,
                "reparented": true,
                "innerHTMLDetached": true,
                "textContentDetached": true,
            })
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn stylesheet_cssom_mutations_update_the_live_cascade() {
        let mut rt = setup_runtime(
            r#"<html style="margin:0"><head>
                <style>#box { width:11px; height:10px }</style>
                </head><body style="margin:0"><div id="box"></div></body></html>"#,
        );
        rt.set_viewport(200.0, 100.0);
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const style = document.createElement('style');
                    style.type = 'text/css';
                    style.setAttribute('data-framer-css', 'true');
                    document.head.appendChild(style);
                    const sheet = style.sheet;
                    const rules = sheet.cssRules;
                    const termius = [
                        !!sheet,
                        rules.length,
                        document.styleSheets[1] === sheet,
                        sheet.ownerNode === style,
                    ];
                    sheet.insertRule('#box { width:73px; height:10px; }', rules.length);
                    termius.push(rules.length);
                    sheet.insertRule('.other { color: blue; }', rules.length);
                    termius.push(rules.length);
                    sheet.insertRule('.semicolon { content: "a;b"; background-image: url("data:image/svg+xml;utf8,<svg/>"); }', rules.length);
                    const semicolonValues = [
                        rules[2].style.content,
                        rules[2].style.backgroundImage,
                    ];
                    let multiRuleSyntaxError = false;
                    try {
                        sheet.insertRule('.invalid-a {} .invalid-b {}', rules.length);
                    } catch (error) {
                        multiRuleSyntaxError = error?.name === 'SyntaxError';
                    }
                    const inserted = document.getElementById('box').getBoundingClientRect().width;
                    rules[0].style.setProperty('width', '91px');
                    const edited = document.getElementById('box').getBoundingClientRect().width;
                    const computed = getComputedStyle(document.getElementById('box')).width;
                    sheet.deleteRule(0);
                    const deleted = document.getElementById('box').getBoundingClientRect().width;
                    sheet.replaceSync('#box { width:64px } .other { color: blue }');
                    const replaced = document.getElementById('box').getBoundingClientRect().width;
                    return [termius, semicolonValues, multiRuleSyntaxError, inserted, edited, computed, deleted,
                            replaced, rules.length, rules[0].selectorText,
                            style.textContent.includes('.other')];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                [true, 0, true, true, 1, 2],
                ["\"a;b\"", "url(\"data:image/svg+xml;utf8,<svg/>\")"],
                true,
                73,
                91,
                "91px",
                11,
                64,
                2,
                "#box",
                false
            ])
        );
    }

    #[test]
    fn adopted_stylesheets_materialize_into_the_document() {
        let mut rt =
            setup_runtime("<html><head></head><body><div class=\"card\"></div></body></html>");
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const sheet = new CSSStyleSheet();
                    document.adoptedStyleSheets.push(sheet);
                    sheet.insertRule('.card { display: flex; color: red; }', 0);
                    const node = document.querySelector('style[data-obscura-adopted]');
                    const inserted = node.textContent;
                    sheet.replaceSync('.card { content: "a;b"; background-image: url("data:image/svg+xml;utf8,<svg/>"); }');
                    const preserved = [
                        sheet.cssRules[0].style.content,
                        sheet.cssRules[0].style.backgroundImage,
                        node.textContent.includes('a;b'),
                        node.textContent.includes('svg+xml;utf8'),
                    ];
                    sheet.deleteRule(0);
                    return [
                        document.adoptedStyleSheets.length,
                        document.querySelectorAll('style[data-obscura-adopted]').length,
                        inserted.includes('display: flex'),
                        preserved,
                        node.textContent,
                    ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                1,
                1,
                true,
                [
                    "\"a;b\"",
                    "url(\"data:image/svg+xml;utf8,<svg/>\")",
                    true,
                    true
                ],
                ""
            ])
        );
    }

    #[test]
    fn shadow_stylesheet_lists_and_adoption_are_live_across_roots() {
        let mut rt = setup_runtime(
            "<html><head></head><body><div id='one'></div><div id='two'></div></body></html>",
        );
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const first = document.getElementById('one').attachShadow({ mode: 'open' });
                    const second = document.getElementById('two').attachShadow({ mode: 'open' });
                    const inline = document.createElement('style');
                    inline.textContent = '.local { width: 17px }';
                    first.appendChild(inline);
                    const inlineSheet = inline.sheet;
                    const firstList = first.styleSheets;
                    const firstAdopted = first.adoptedStyleSheets;
                    const secondAdopted = second.adoptedStyleSheets;
                    const documentAdopted = document.adoptedStyleSheets;

                    const shared = new CSSStyleSheet();
                    first.adoptedStyleSheets = [shared];
                    second.adoptedStyleSheets.push(shared);
                    document.adoptedStyleSheets = [shared];

                    const firstNode = first.querySelector('style[data-obscura-adopted]');
                    const secondNode = second.querySelector('style[data-obscura-adopted]');
                    const documentNode = document.querySelector('style[data-obscura-adopted]');
                    const initial = [
                        first.styleSheets === firstList,
                        firstList.length,
                        firstList[0] === inlineSheet,
                        firstList.item(0) === inlineSheet,
                        second.styleSheets === second.styleSheets,
                        second.styleSheets.length,
                        first.adoptedStyleSheets === firstAdopted,
                        second.adoptedStyleSheets === secondAdopted,
                        document.adoptedStyleSheets === documentAdopted,
                        firstAdopted.length,
                        secondAdopted.length,
                        documentAdopted.length,
                        firstNode.parentNode === first,
                        secondNode.parentNode === second,
                        documentNode.parentNode === document.head,
                    ];

                    shared.insertRule('.shared { width: 31px }', 0);
                    const synchronized = [firstNode, secondNode, documentNode]
                        .map(node => node.textContent.includes('width: 31px'));

                    second.adoptedStyleSheets = [];
                    shared.replaceSync('.shared { width: 47px }');
                    const afterRemoval = [
                        second.adoptedStyleSheets === secondAdopted,
                        secondAdopted.length,
                        secondNode.parentNode,
                        second.querySelectorAll('style[data-obscura-adopted]').length,
                        firstNode.textContent.includes('width: 47px'),
                        documentNode.textContent.includes('width: 47px'),
                        secondNode.textContent.includes('width: 31px'),
                    ];

                    inline.remove();
                    const inlineRemoval = [
                        first.styleSheets === firstList,
                        firstList.length,
                        inlineSheet.ownerNode,
                    ];
                    return { initial, synchronized, afterRemoval, inlineRemoval };
                })()
                "#,
            )
            .unwrap();

        assert_eq!(
            result,
            serde_json::json!({
                "initial": [
                    true, 1, true, true, true, 0,
                    true, true, true, 1, 1, 1,
                    true, true, true
                ],
                "synchronized": [true, true, true],
                "afterRemoval": [true, 0, null, 0, true, true, true],
                "inlineRemoval": [true, 0, null],
            })
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn shadow_adopted_stylesheets_apply_and_sync_the_live_cascade() {
        let mut rt = setup_runtime(
            r#"<html style="margin:0"><head>
                <style>.target { width:11px; height:10px }</style>
                </head><body style="margin:0">
                <div id="one"></div><div id="two"></div><div class="target" id="outside"></div>
                </body></html>"#,
        );
        rt.set_viewport(200.0, 100.0);
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const first = document.getElementById('one').attachShadow({ mode: 'open' });
                    const second = document.getElementById('two').attachShadow({ mode: 'open' });
                    first.innerHTML = '<style>.target { width:18px; height:10px }</style><div class="target"></div>';
                    second.innerHTML = '<style>.target { width:23px; height:10px }</style><div class="target"></div>';
                    const firstTarget = first.querySelector('.target');
                    const secondTarget = second.querySelector('.target');
                    const outside = document.getElementById('outside');
                    const widths = () => [firstTarget, secondTarget, outside]
                        .map(node => node.getBoundingClientRect().width);

                    const inline = widths();
                    const shared = new CSSStyleSheet();
                    shared.replaceSync('.target { width:42px; height:10px }');
                    first.adoptedStyleSheets = [shared];
                    second.adoptedStyleSheets = [shared];
                    document.adoptedStyleSheets = [shared];
                    const adopted = widths();

                    shared.cssRules[0].style.setProperty('width', '67px');
                    const mutated = widths();

                    second.adoptedStyleSheets = [];
                    document.adoptedStyleSheets = [];
                    const selectivelyRemoved = widths();

                    shared.replaceSync('.target { width:81px; height:10px }');
                    const remainingRootUpdated = widths();
                    return [
                        inline, adopted, mutated, selectivelyRemoved, remainingRootUpdated,
                        first.styleSheets.length,
                        second.styleSheets.length,
                    ];
                })()
                "#,
            )
            .unwrap();

        assert_eq!(
            result,
            serde_json::json!([
                [18, 23, 11],
                [42, 42, 42],
                [67, 67, 67],
                [67, 23, 11],
                [81, 23, 11],
                1,
                1,
            ])
        );
    }

    #[test]
    fn unavailable_webgl_context_does_not_claim_success() {
        let mut rt = setup_runtime("<html><body><canvas></canvas></body></html>");
        let result = rt
            .evaluate(
                r#"
                (() => {
                    const canvas = document.querySelector('canvas');
                    const fallback = document.createElement('p');
                    if (!canvas.getContext('webgl')) {
                        fallback.textContent = 'static fallback';
                        document.body.appendChild(fallback);
                    }
                    return [
                        canvas.getContext('webgl'),
                        canvas.getContext('webgl2'),
                        canvas.getContext('experimental-webgl'),
                        fallback.isConnected,
                        fallback.textContent,
                    ];
                })()
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([null, null, null, true, "static fallback"])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn canvas_2d_live_backing_paints_immediately_with_scaling_clips_and_effects() {
        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0;width:64px;height:40px;background:#0000ff">
                <div style="position:absolute;left:4px;top:4px;width:18px;height:14px;overflow:hidden">
                  <canvas id="paint" width="2" height="1"
                    style="display:block;width:20px;height:10px;border:2px solid #ffff00;opacity:.5"></canvas>
                </div>
                <canvas id="blank" width="4" height="4"
                  style="position:absolute;left:30px;top:4px;width:10px;height:10px"></canvas>
                <canvas id="padding" width="2" height="1"
                  style="position:absolute;left:30px;top:20px;width:10px;height:4px;padding:2px 2px 2px 4px;border:1px solid #ffff00;background:#00ffff"></canvas>
                <div style="position:absolute;z-index:2;left:10px;top:7px;width:4px;height:4px;background:#ff00ff"></div>
            </body></html>"#,
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.test/canvas");
        rt.set_viewport(64.0, 40.0);
        rt.run_page_init();

        let blank_api = rt
            .evaluate(
                r#"(() => {
                    const blank = document.getElementById('blank');
                    const encoded = blank.toDataURL();
                    const blankContext = blank.getContext('2d');
                    const pixels = blankContext.getImageData(0, 0, 4, 4).data;
                    blankContext.fillStyle = '#ff0000'; blankContext.fillRect(0, 0, 1, 1);
                    blank.width = 6;
                    const resetPixel = blankContext.getImageData(0, 0, 1, 1).data;
                    const untouched = document.createElement('canvas');
                    const defaultEncoded = untouched.toDataURL();
                    const defaultPixels = untouched.getContext('2d').getImageData(0, 0, 1, 1).data;
                    return [
                      blank instanceof HTMLCanvasElement,
                      typeof document.createElement('div').getContext,
                      blank.width, blank.height, blank.getContext('2d') === blankContext,
                      encoded.startsWith('data:image/png;base64,'),
                      atob(encoded.split(',')[1]).charCodeAt(25) === 6,
                      Array.from(pixels).every((value, index) => index % 4 !== 3 || value === 0),
                      untouched.width, untouched.height,
                      defaultEncoded.startsWith('data:image/png;base64,'),
                      Array.from(defaultPixels),
                      Array.from(resetPixel),
                    ];
                })()"#,
            )
            .expect("transparent default canvas API");
        assert_eq!(
            blank_api,
            serde_json::json!([
                true,
                "undefined",
                6,
                4,
                true,
                true,
                true,
                true,
                300,
                150,
                true,
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ])
        );

        // Prepare layout before drawing so the assertions below prove canvas
        // damage retains layout, while the following capture proves pixels
        // are read from the live backing immediately after the script task.
        {
            let mut state = rt.state.borrow_mut();
            ensure_resolved_scroll(&mut state).expect("initial resolved canvas scroll");
        }
        let prepared_address = {
            let state = rt.state.borrow();
            state.prepared_render.as_ref().unwrap() as *const _ as usize
        };
        let activity_before = rt.activity_generation();
        rt.execute_script(
            "canvas-fill",
            r#"const canvas = document.getElementById('paint');
               const ctx = canvas.getContext('2d');
               ctx.fillStyle = '#ff0000'; ctx.fillRect(0, 0, 1, 1);
               ctx.fillStyle = '#00ff00'; ctx.fillRect(1, 0, 1, 1);
               const padding = document.getElementById('padding').getContext('2d');
               padding.fillStyle = '#ff0000'; padding.fillRect(0, 0, 1, 1);
               padding.fillStyle = '#00ff00'; padding.fillRect(1, 0, 1, 1);"#,
        )
        .expect("fill live canvas backing");
        assert!(rt.activity_generation() > activity_before);
        assert_eq!(
            rt.state.borrow().prepared_render.as_ref().unwrap() as *const _ as usize,
            prepared_address,
            "canvas damage must not invalidate retained layout"
        );

        let pixmap = {
            let mut state = rt.state.borrow_mut();
            ensure_resolved_scroll(&mut state).expect("resolved canvas scroll");
            let ObscuraState {
                dom,
                prepared_render,
                render_resources,
                resolved_scroll,
                canvas_surfaces,
                ..
            } = &mut *state;
            let (_, scroll) = resolved_scroll.as_ref().expect("scroll snapshot");
            let canvas_surfaces = RuntimeCanvasSurfaceSource(canvas_surfaces);
            obscura_render::paint_prepared_with_scroll_and_surface_color_and_canvas_surfaces(
                dom.as_ref().expect("canvas DOM"),
                prepared_render.as_mut().expect("prepared canvas layout"),
                render_resources,
                scroll,
                [255, 255, 255, 255],
                &canvas_surfaces,
            )
            .expect("canvas pixmap")
        };

        let red_half = pixmap.pixel(7, 8).expect("scaled red canvas pixel");
        assert!(red_half.red() > 100 && red_half.blue() > 100 && red_half.green() < 20);
        // Bilinear filtering blends at the exact source-pixel transition
        // (x=16), so sample several CSS pixels into the green half.
        let green_half = pixmap.pixel(19, 8).expect("scaled green canvas pixel");
        assert!(
            green_half.green() > 45 && green_half.blue() > 100 && green_half.red() < 20,
            "pixel at (19, 8) was rgba({}, {}, {}, {})",
            green_half.red(),
            green_half.green(),
            green_half.blue(),
            green_half.alpha()
        );
        let clipped = pixmap.pixel(23, 8).expect("outside overflow clip");
        assert_eq!(
            (clipped.red(), clipped.green(), clipped.blue()),
            (0, 0, 255)
        );
        let blank = pixmap.pixel(34, 8).expect("transparent blank canvas");
        assert_eq!((blank.red(), blank.green(), blank.blue()), (0, 0, 255));
        let overlay = pixmap.pixel(11, 8).expect("higher z-index overlay");
        assert!(overlay.red() > 240 && overlay.blue() > 240 && overlay.green() < 20);
        let border = pixmap.pixel(4, 8).expect("canvas border above content");
        assert!(border.red() > 100 && border.green() > 100 && border.blue() > 100);
        let padding = pixmap.pixel(33, 23).expect("canvas padding pixel");
        assert_eq!(
            (padding.red(), padding.green(), padding.blue()),
            (0, 255, 255),
            "canvas pixels must not cover authored padding"
        );
        let padded_content = pixmap.pixel(36, 23).expect("padded canvas content pixel");
        assert!(
            padded_content.red() > 220 && padded_content.green() < 40 && padded_content.blue() < 40,
            "canvas bitmap must start at the CSS content-box origin"
        );
    }

    #[test]
    fn test_script_execution() {
        let mut rt = setup_runtime("<ul><li>A</li><li>B</li></ul>");
        rt.execute_script(
            "test",
            r#"
            globalThis.__result = [];
            document.querySelectorAll('li').forEach(function(el) {
                globalThis.__result.push(el.textContent);
            });
        "#,
        )
        .unwrap();
        let result = rt.evaluate("globalThis.__result").unwrap();
        assert_eq!(result, serde_json::json!(["A", "B"]));
    }

    #[test]
    fn page_var_declarations_do_not_collide_with_dom_interfaces() {
        let mut rt = setup_runtime("<html><body></body></html>");

        rt.execute_script(
            "legacy-node-guard",
            "if (!window.Node) { var Node = {}; } globalThis.__legacyNodeRan = true;",
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("globalThis.__legacyNodeRan").unwrap(),
            serde_json::json!(true)
        );

        rt.execute_script(
            "page-element",
            "var Element = function PageElement() {}; globalThis.__createdTag = document.createElement('div').tagName;",
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("globalThis.__createdTag").unwrap(),
            serde_json::json!("DIV")
        );
    }

    #[test]
    fn dynamic_script_status_bridge_is_hidden_and_idle() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert!(!rt.has_pending_dynamic_scripts());
        assert!(!rt.has_pending_load_delaying_scripts());
        assert!(!rt.has_pending_parser_blocking_scripts());
        assert_eq!(rt.next_pending_timeout_delay_ms(), None);
        assert_eq!(
            rt.evaluate("typeof __dynScriptBusy").unwrap(),
            serde_json::json!("undefined")
        );
        assert_eq!(
            rt.evaluate(
                "Object.getOwnPropertyNames(globalThis).includes('__obscura_hasPendingDynamicScripts')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(
            rt.evaluate(
                "Reflect.ownKeys(globalThis).includes('__obscura_hasPendingDynamicScripts')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(
            rt.evaluate(
                "Reflect.ownKeys(globalThis).includes('__obscura_hasPendingLoadDelayingScripts')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(
            rt.evaluate(
                "Reflect.ownKeys(globalThis).includes('__obscura_hasPendingParserBlockingScripts')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(
            rt.evaluate(
                "Object.getOwnPropertyNames(globalThis).includes('__obscura_nextPendingTimeoutDelay')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(
            rt.evaluate(
                "Reflect.ownKeys(globalThis).includes('__obscura_nextPendingTimeoutDelay')"
            )
            .unwrap(),
            serde_json::json!(false)
        );
    }

    /// Regression test for #147: a TypeError in one script must not poison
    /// the runtime so that subsequent scripts (or DOM queries) collapse to
    /// empty. The reporter saw `--dump text` return 1 byte after offside.js
    /// crashed; that cascade should never happen.
    #[test]
    fn script_typeerror_does_not_poison_subsequent_execution() {
        let mut rt = setup_runtime("<html><body><p id=hit>BODY_TEXT</p></body></html>");

        // 1. First script throws the same flavor of error offside.js produced
        //    (`Cannot read properties of undefined (reading 'classList')`).
        let err = rt
            .execute_script("buggy", "var x; x.classList.add('y');")
            .unwrap_err();
        assert!(
            err.contains("classList") || err.contains("undefined"),
            "expected classList/undefined error, got: {}",
            err
        );

        // 2. The runtime must still be usable: a follow-up script runs.
        rt.execute_script("ok", "globalThis.__after_error = 'still alive';")
            .unwrap();
        let result = rt.evaluate("globalThis.__after_error").unwrap();
        assert_eq!(result, serde_json::json!("still alive"));

        // 3. DOM queries still work after the script error.
        let text = rt
            .evaluate("document.querySelector('#hit').textContent")
            .unwrap();
        assert_eq!(text, serde_json::json!("BODY_TEXT"));
    }

    /// Regression test for #355: an explicit `throw` in one inline <script> must
    /// not stop later independent <script>s from running. Each <script> executes
    /// as its own `execute_script` call, mirroring how page.rs runs them, so a
    /// thrown error is reported but the next script still runs.
    #[test]
    fn thrown_error_in_one_script_does_not_stop_later_scripts() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("s1", "globalThis.__ran1 = true;")
            .unwrap();
        let err = rt
            .execute_script(
                "s2",
                "throw new Error('only one instance of babel-polyfill is allowed');",
            )
            .unwrap_err();
        assert!(
            err.contains("babel-polyfill"),
            "expected the thrown message, got: {}",
            err
        );
        rt.execute_script("s3", "globalThis.__ran3 = true;")
            .unwrap();
        let ran = rt
            .evaluate("JSON.stringify([globalThis.__ran1 === true, globalThis.__ran3 === true])")
            .unwrap();
        assert_eq!(ran, serde_json::json!("[true,true]"));
    }

    /// Regression test for #356: the `in` operator and `Object.keys` must work on
    /// `el.style` (CSSStyleDeclaration) and `el.dataset` (DOMStringMap), `_props`
    /// must not leak, and cssText must serialize dashed names with a trailing
    /// semicolon.
    #[test]
    fn style_and_dataset_support_in_operator_and_keys() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    const el = document.createElement('div');
                    el.style.color = 'red';
                    el.style.fontSize = '14px';
                    el.dataset.foo = 'bar';
                    const keys = Object.keys(el.style);
                    return JSON.stringify({
                        colorInStyle: 'color' in el.style,
                        objectFitInStyle: 'object-fit' in el.style,
                        keysHasSet: keys.includes('color') && keys.includes('fontSize'),
                        noPropsLeak: !keys.includes('_props'),
                        fooInDataset: 'foo' in el.dataset,
                        datasetKeys: Object.keys(el.dataset),
                        cssText: el.style.cssText,
                        length: el.style.length,
                        getByDash: el.style.getPropertyValue('font-size'),
                        reflectedAttribute: el.getAttribute('style')
                    });
                })()"#,
            )
            .unwrap();
        let p: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(p["colorInStyle"], true);
        assert_eq!(p["objectFitInStyle"], true);
        assert_eq!(p["keysHasSet"], true);
        assert_eq!(p["noPropsLeak"], true);
        assert_eq!(p["fooInDataset"], true);
        assert_eq!(p["datasetKeys"], serde_json::json!(["foo"]));
        assert_eq!(p["cssText"], "color: red; font-size: 14px;");
        assert_eq!(p["length"], 2);
        assert_eq!(p["getByDash"], "14px");
        assert_eq!(p["reflectedAttribute"], "color: red; font-size: 14px;");
    }

    #[test]
    fn dom_string_map_is_exposed_and_backs_dataset() {
        let mut rt = setup_runtime(r#"<div id="x" data-foo="bar"></div>"#);
        let result = rt
            .evaluate(
                r#"(() => {
                    const dataset = document.getElementById("x").dataset;
                    const interface = window.DOMStringMap;
                    const descriptor = Object.getOwnPropertyDescriptor(window, "DOMStringMap");
                    let illegalConstructor = false;
                    if (interface) {
                        try { new interface(); }
                        catch (error) { illegalConstructor = error instanceof TypeError; }
                    }
                    return JSON.stringify({
                        type: typeof interface,
                        instance: !!interface && dataset instanceof interface,
                        prototype: !!interface && Object.getPrototypeOf(dataset) === interface.prototype,
                        constructor: !!interface && dataset.constructor === interface,
                        tag: Object.prototype.toString.call(dataset),
                        enumerable: descriptor ? descriptor.enumerable : "missing",
                        illegalConstructor,
                        value: dataset.foo,
                    });
                })()"#,
            )
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
                "type": "function",
                "instance": true,
                "prototype": true,
                "constructor": true,
                "tag": "[object DOMStringMap]",
                "enumerable": false,
                "illegalConstructor": true,
                "value": "bar",
            })
        );
    }

    #[test]
    fn style_declaration_reflects_and_removes_parsed_attributes() {
        let mut rt = setup_runtime(
            "<html><body><div id='icon' style='font-size: 0px; color: red'></div></body></html>",
        );
        let result = rt
            .evaluate(
                r#"(() => {
                    const el = document.getElementById('icon');
                    const before = [el.style.fontSize, el.style.color, el.style.length];
                    const removed = el.style.removeProperty('font-size');
                    return JSON.stringify({
                        before,
                        removed,
                        after: el.style.cssText,
                        attribute: el.getAttribute('style')
                    });
                })()"#,
            )
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(value["before"], serde_json::json!(["0px", "red", 2]));
        assert_eq!(value["removed"], "0px");
        assert_eq!(value["after"], "color: red;");
        assert_eq!(value["attribute"], "color: red;");
    }

    // #1168: `Option` is a legacy factory function like `Image`. WPForms does
    // `new Option().style`, so the result must be a real <option> element.
    #[test]
    fn option_named_constructor_builds_an_option_element() {
        let mut rt = setup_runtime("<html><body><select id='s'></select></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    const describe = option => ({
                        tag: option.localName,
                        text: option.text,
                        value: option.value,
                        valueAttr: option.getAttribute('value'),
                        selectedAttr: option.hasAttribute('selected'),
                        selected: option.selected,
                        children: option.childNodes.length
                    });
                    const full = new Option('Greek', 'el', true, true);
                    const select = document.getElementById('s');
                    select.add(new Option('English', 'en'));
                    select.add(full);
                    return JSON.stringify({
                        type: typeof Option,
                        empty: describe(new Option()),
                        textOnly: describe(new Option('Label')),
                        full: describe(full),
                        defaultOnly: describe(new Option('a', 'b', true, false)),
                        selectedOnly: new Option('a', 'b', false, true).selected,
                        coerced: describe(new Option(7, 0)),
                        hasStyle: typeof new Option().style,
                        isElement: new Option() instanceof HTMLOptionElement,
                        isOption: new Option() instanceof Option,
                        ownerDocument: new Option().ownerDocument === document,
                        detached: new Option().parentNode === null,
                        selectValue: select.value,
                        selectHtml: select.innerHTML
                    });
                })()"#,
            )
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(value["type"], "function");
        assert_eq!(
            value["empty"],
            serde_json::json!({
                "tag": "option", "text": "", "value": "", "valueAttr": null,
                "selectedAttr": false, "selected": false, "children": 0
            })
        );
        assert_eq!(
            value["textOnly"],
            serde_json::json!({
                "tag": "option", "text": "Label", "value": "Label", "valueAttr": null,
                "selectedAttr": false, "selected": false, "children": 1
            })
        );
        assert_eq!(
            value["full"],
            serde_json::json!({
                "tag": "option", "text": "Greek", "value": "el", "valueAttr": "el",
                "selectedAttr": true, "selected": true, "children": 1
            })
        );
        // defaultSelected sets the content attribute; selected=false still
        // leaves the option unselected.
        assert_eq!(value["defaultOnly"]["selectedAttr"], true);
        assert_eq!(value["defaultOnly"]["selected"], false);
        assert_eq!(value["selectedOnly"], true);
        assert_eq!(value["coerced"]["text"], "7");
        assert_eq!(value["coerced"]["valueAttr"], "0");
        assert_eq!(value["hasStyle"], "object");
        assert_eq!(value["isElement"], true);
        assert_eq!(value["isOption"], true);
        assert_eq!(value["ownerDocument"], true);
        assert_eq!(value["detached"], true);
        assert_eq!(value["selectValue"], "el");
        assert_eq!(
            value["selectHtml"],
            "<option value=\"en\">English</option><option value=\"el\" selected=\"\">Greek</option>"
        );
    }

    #[test]
    fn select_add_and_option_text_update_the_live_dom() {
        let mut rt = setup_runtime("<html><body><select id='language'></select></body></html>");
        let result = rt
            .evaluate(
                r#"(() => {
                    const select = document.getElementById('language');
                    const english = document.createElement('option');
                    english.value = 'en';
                    english.text = 'English';
                    english.selected = true;
                    select.add(english);
                    const greek = document.createElement('option');
                    greek.value = 'el';
                    greek.text = 'Greek';
                    greek.setAttribute('label', 'Ελληνικά');
                    select.add(greek, 0);
                    return JSON.stringify({
                        labels: [...select.options].map(option => option.textContent),
                        optionLabels: [...select.options].map(option => option.label),
                        selectedIndex: select.selectedIndex,
                        value: select.value,
                        html: select.outerHTML
                    });
                })()"#,
            )
            .unwrap();
        let value: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(value["labels"], serde_json::json!(["Greek", "English"]));
        assert_eq!(value["optionLabels"], serde_json::json!(["Ελληνικά", "English"]));
        assert_eq!(value["selectedIndex"], 1);
        assert_eq!(value["value"], "en");
        assert!(
            value["html"]
            .as_str()
            .unwrap()
                .contains(r#"<option value="en" selected="">English</option>"#)
        );
    }

    /// Regression for #105: `element.querySelector` and `querySelectorAll`
    /// must scope to the receiver's subtree, not the whole document.
    #[test]
    fn element_query_selector_is_scoped_to_subtree() {
        let mut rt = setup_runtime(
            r#"<div id="a"><span class="x">in a</span></div><div id="b"><span class="x">in b</span></div>"#,
        );
        let text = rt
            .evaluate("document.getElementById('a').querySelector('.x').textContent")
            .unwrap();
        assert_eq!(text, serde_json::json!("in a"));

        let count_in_a = rt
            .evaluate("document.getElementById('a').querySelectorAll('.x').length")
            .unwrap();
        assert_eq!(count_in_a.as_f64().unwrap() as i64, 1);

        // Document-scoped query still sees both.
        let count_doc = rt
            .evaluate("document.querySelectorAll('.x').length")
            .unwrap();
        assert_eq!(count_doc.as_f64().unwrap() as i64, 2);
    }

    #[test]
    fn document_evaluate_exposes_basic_xpath_result() {
        let mut rt = setup_runtime("");

        let exposed = rt
            .evaluate("`${typeof XPathResult}:${typeof Document.prototype.evaluate}:${XPathResult.FIRST_ORDERED_NODE_TYPE}`")
            .unwrap();
        assert_eq!(exposed, serde_json::json!("function:function:9"));
    }

    /// Regression for #105: `document.forms` / `images` / `links` must be
    /// live, not hardcoded `[]`. jQuery 1.x's submit-event setup iterates
    /// `document.forms` and crashes when it's empty for pages that have forms.
    #[tokio::test(flavor = "current_thread")]
    async fn document_forms_images_links_are_live() {
        let mut rt =
            setup_runtime(r#"<form></form><form></form><img><a href="x">l</a><a>no-href</a>"#);
        assert_eq!(
            rt.evaluate("document.forms.length")
                .unwrap()
                .as_f64()
                .unwrap() as i64,
            2
        );
        assert_eq!(
            rt.evaluate("document.images.length")
                .unwrap()
                .as_f64()
                .unwrap() as i64,
            1
        );
        assert_eq!(
            rt.evaluate("document.links.length")
                .unwrap()
                .as_f64()
                .unwrap() as i64,
            1
        );
    }

    #[cfg(feature = "render")]
    fn parser_image_runtime(
        html: &str,
        loader: impl obscura_render::RenderResourceLoader + 'static,
    ) -> ObscuraJsRuntime {
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(html));
        rt.set_url("http://example.com/page/index.html");
        rt.state.borrow_mut().render_resources =
            obscura_render::RenderResourceCache::with_loader(loader);
        rt.run_page_init();
        rt
    }

    #[cfg(feature = "render")]
    fn two_by_three_png() -> Vec<u8> {
        use base64::Engine as _;
        base64::engine::general_purpose::STANDARD
            .decode(
                "iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAYAAAC56t6B\
                 AAAAFklEQVR4nGP8z8Dwn4GBgYGJAQrgDAAxOwIE7x6DkQAAAABJRU5ErkJggg=="
                    .replace(char::is_whitespace, ""),
            )
            .unwrap()
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_images_load_concurrently_without_blocking_the_event_loop() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let accepted = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let active = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let max_active = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let server_accepted = accepted.clone();
        let server_active = active.clone();
        let server_max_active = max_active.clone();
        let png = two_by_three_png();
        std::thread::spawn(move || {
            for _ in 0..4 {
                let (mut stream, _) = listener.accept().unwrap();
                server_accepted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let active = server_active.clone();
                let max_active = server_max_active.clone();
                let png = png.clone();
                std::thread::spawn(move || {
                    use std::io::{Read as _, Write as _};

                    let mut request = [0u8; 2048];
                    let _ = stream.read(&mut request);
                    let concurrent = active.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
                    max_active.fetch_max(concurrent, std::sync::atomic::Ordering::SeqCst);
                    std::thread::sleep(std::time::Duration::from_millis(150));
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                        png.len()
                    );
                    stream.write_all(response.as_bytes()).unwrap();
                    stream.write_all(&png).unwrap();
                    active.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
                });
            }
        });

        let base = format!("http://{address}");
        let html = format!(
            r#"<img src="{base}/one.png"><img src="{base}/two.png">
                <img src="{base}/three.png"><img src="{base}/shared.png">
                <img src="{base}/shared.png">"#
        );
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(&html));
        rt.set_url(&format!("{base}/page.html"));
        rt.set_http_client(std::sync::Arc::new(
            obscura_net::ObscuraHttpClient::with_full_options(
                std::sync::Arc::new(obscura_net::CookieJar::new()),
                None,
                true,
            ),
        ));
        rt.run_page_init();

        let started = std::time::Instant::now();
        let result = rt
            .evaluate_for_cdp(
                r#"
                new Promise(resolve => {
                    globalThis.__imageTimerRan = false;
                    setTimeout(() => { __imageTimerRan = true; }, 10);
                    const images = Array.from(document.images);
                    const events = [];
                    const finish = (type, image) => {
                        events.push([
                            type,
                            __imageTimerRan,
                            image.naturalWidth,
                            image.naturalHeight,
                        ]);
                        if (events.length === images.length) resolve(events);
                    };
                    for (const image of images) {
                        image.addEventListener("load", () => finish("load", image));
                        image.addEventListener("error", () => finish("error", image));
                        void image.complete;
                    }
                    setTimeout(() => resolve([["timed out"]]), 2000);
                })
                "#,
                true,
                true,
            )
            .await
            .unwrap();
        let elapsed = started.elapsed();
        assert_eq!(
            result.value.unwrap(),
            serde_json::json!([
                ["load", true, 2, 3],
                ["load", true, 2, 3],
                ["load", true, 2, 3],
                ["load", true, 2, 3],
                ["load", true, 2, 3],
            ])
        );
        assert_eq!(
            accepted.load(std::sync::atomic::Ordering::SeqCst),
            4,
            "two elements selecting one URL must share a single request"
        );
        assert!(
            max_active.load(std::sync::atomic::Ordering::SeqCst) >= 3,
            "slow image requests did not overlap"
        );
        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "four 150ms image requests serialized: {elapsed:?}"
        );
        assert_eq!(
            rt.state
                .borrow()
                .page_in_flight
                .load(std::sync::atomic::Ordering::SeqCst),
            0
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn image_lifecycle_cache_is_separated_by_cors_credentials_profile() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let server_requests = requests.clone();
        let png = two_by_three_png();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            for _ in 0..4 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 4096];
                let read = stream.read(&mut request).unwrap();
                let request = String::from_utf8_lossy(&request[..read]).to_ascii_lowercase();
                let path = request
                    .lines()
                    .next()
                    .and_then(|line| line.split_whitespace().nth(1))
                    .unwrap_or("")
                    .to_string();
                let mode = request
                    .lines()
                    .find_map(|line| line.strip_prefix("sec-fetch-mode: "))
                    .unwrap_or("")
                    .trim()
                    .to_string();
                server_requests.lock().unwrap().push((path.clone(), mode));
                let cors_headers = if path == "/cors.png" {
                    // Anonymous accepts wildcard; use-credentials must reject
                    // it even when credentials permission is also present.
                    "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Credentials: true\r\n"
                } else {
                    ""
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\n{cors_headers}Content-Length: {}\r\nConnection: close\r\n\r\n",
                    png.len()
                );
                stream.write_all(response.as_bytes()).unwrap();
                stream.write_all(&png).unwrap();
            }
        });

        let base = format!("http://{address}");
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(parse_html(&format!(
            r#"<img id="image" src="{base}/plain.png">"#
        )));
        // Deliberately make the image cross-origin from the document.
        rt.set_url("http://127.0.0.1:1/page.html");
        rt.set_http_client(std::sync::Arc::new(
            obscura_net::ObscuraHttpClient::with_full_options(
                std::sync::Arc::new(obscura_net::CookieJar::new()),
                None,
                true,
            ),
        ));
        rt.run_page_init();
        rt.execute_script(
            "observe-profiled-image",
            r#"
                globalThis.image = document.getElementById("image");
                globalThis.__profileEvents = [];
                image.addEventListener("load", () => __profileEvents.push("load"));
                image.addEventListener("error", () => __profileEvents.push("error"));
                void image.complete;
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 2, ["load"]])
        );

        rt.execute_script(
            "require-anonymous-cors",
            r#"image.crossOrigin = "anonymous";"#,
        )
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 0, ["load", "error"]]),
            "URL-keyed no-CORS bytes must not satisfy an anonymous CORS request"
        );

        rt.execute_script("restore-no-cors", "image.removeAttribute('crossorigin');")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 2, ["load", "error", "load"]]),
            "a CORS failure must not poison the earlier no-CORS success"
        );

        rt.execute_script(
            "load-anonymous-cors",
            &format!(r#"image.crossOrigin = "anonymous"; image.src = "{base}/cors.png";"#),
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 2, ["load", "error", "load", "load"]])
        );

        rt.execute_script(
            "require-credentialed-cors",
            r#"image.crossOrigin = "use-credentials";"#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 0, ["load", "error", "load", "load", "error"]]),
            "anonymous CORS success must not satisfy use-credentials"
        );

        rt.execute_script(
            "restore-anonymous-cors",
            r#"image.crossOrigin = "anonymous";"#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.naturalWidth, __profileEvents]")
                .unwrap(),
            serde_json::json!([true, 2, ["load", "error", "load", "load", "error", "load"]]),
            "credentialed CORS failure must not poison anonymous success"
        );

        assert_eq!(
            *requests.lock().unwrap(),
            vec![
                ("/plain.png".to_string(), "no-cors".to_string()),
                ("/plain.png".to_string(), "cors".to_string()),
                ("/cors.png".to_string(), "cors".to_string()),
                ("/cors.png".to_string(), "cors".to_string()),
            ]
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_data_src_mutation_does_not_restart_lifecycle() {
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen = requests.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="image" src="real.png" data-src="deferred.png">"#,
            move |url: &str| {
                seen.lock().unwrap().push(url.to_string());
                Some(png.clone())
            },
        );
        rt.execute_script(
            "observe-data-src-mutation",
            r#"
                globalThis.__dataSrcEvents = [];
                const image = document.getElementById("image");
                image.addEventListener("load", () => __dataSrcEvents.push(image.currentSrc));
                void image.complete;
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[image.complete, image.currentSrc, __dataSrcEvents]")
                .unwrap(),
            serde_json::json!([
                true,
                "http://example.com/page/real.png",
                ["http://example.com/page/real.png"]
            ])
        );

        rt.execute_script(
            "mutate-non-source-data-attribute",
            r#"
                image.dataset.src = "ignored.png";
                globalThis.__afterDataSrcMutation = [image.complete, image.currentSrc];
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[__afterDataSrcMutation, __dataSrcEvents]")
                .unwrap(),
            serde_json::json!([
                [true, "http://example.com/page/real.png"],
                ["http://example.com/page/real.png"]
            ])
        );
        assert_eq!(
            *requests.lock().unwrap(),
            vec!["http://example.com/page/real.png".to_string()]
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_data_src_is_inert_until_script_assigns_src() {
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen = requests.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="image" data-src="promoted.png">"#,
            move |url: &str| {
                seen.lock().unwrap().push(url.to_string());
                Some(png.clone())
            },
        );
        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    globalThis.image = document.getElementById("image");
                    globalThis.__promotedEvents = [];
                    image.addEventListener("load", () => __promotedEvents.push(image.currentSrc));
                    return [image.src, image.currentSrc, image.complete,
                            image.naturalWidth, image.naturalHeight];
                })()"#,
            )
            .unwrap(),
            serde_json::json!(["", "", true, 0, 0])
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        assert!(requests.lock().unwrap().is_empty());

        rt.execute_script(
            "promote-data-src-through-page-script",
            r#"
                image.src = image.dataset.src;
                globalThis.__afterSrcPromotion = [image.complete, image.currentSrc];
            "#,
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("__afterSrcPromotion").unwrap(),
            serde_json::json!([false, "http://example.com/page/promoted.png"])
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[image.complete, image.naturalWidth, image.naturalHeight, \
                  image.currentSrc, __promotedEvents]"
            )
            .unwrap(),
            serde_json::json!([
                true,
                2,
                3,
                "http://example.com/page/promoted.png",
                ["http://example.com/page/promoted.png"]
            ])
        );
        assert_eq!(
            *requests.lock().unwrap(),
            vec!["http://example.com/page/promoted.png".to_string()]
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_lifecycle_uses_shared_render_resource() {
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let loader_calls = calls.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="hero" src="../assets/hero.png">"#,
            move |_url: &str| {
                loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Some(png.clone())
            },
        );
        rt.execute_script(
            "observe-parser-image",
            r#"
                globalThis.__imageEvents = [];
                globalThis.__decodeState = "pending";
                const image = document.getElementById("hero");
                globalThis.__imageInitial = [
                    image instanceof HTMLImageElement,
                    image.complete,
                    image.naturalWidth,
                    image.naturalHeight
                ];
                image.addEventListener("load", () => __imageEvents.push("load"));
                image.addEventListener("error", () => __imageEvents.push("error"));
                image.decode().then(
                    () => { __decodeState = "resolved"; },
                    error => { __decodeState = error.name; }
                );
            "#,
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("__imageInitial").unwrap(),
            serde_json::json!([true, false, 0, 0])
        );

        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                r#"[
                    image.complete,
                    image.naturalWidth,
                    image.naturalHeight,
                    image.currentSrc,
                    __imageEvents,
                    __decodeState
                ]"#,
            )
            .unwrap(),
            serde_json::json!([
                true,
                2,
                3,
                "http://example.com/assets/hero.png",
                ["load"],
                "resolved"
            ])
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);

        // A subsequent request for the same URL is served by the retained
        // renderer bytes rather than calling the loader again.
        rt.execute_script("reload-image", r#"image.src = "../assets/hero.png";"#)
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_failure_completes_and_rejects_decode() {
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let loader_calls = calls.clone();
        let mut rt = parser_image_runtime(
            r#"<img id="broken" src="missing.png">"#,
            move |_url: &str| {
                loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                None
            },
        );
        rt.execute_script(
            "observe-broken-image",
            r#"
                globalThis.__brokenEvents = [];
                globalThis.__brokenDecode = "pending";
                const broken = document.getElementById("broken");
                broken.onload = () => __brokenEvents.push("load");
                broken.onerror = () => __brokenEvents.push("error");
                broken.decode().then(
                    () => { __brokenDecode = "resolved"; },
                    error => { __brokenDecode = error.name; }
                );
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[broken.complete, broken.naturalWidth, broken.naturalHeight, \
                  __brokenEvents, __brokenDecode]"
            )
            .unwrap(),
            serde_json::json!([true, 0, 0, ["error"], "EncodingError"])
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[cfg(feature = "render")]
    #[test]
    fn parser_image_first_getter_observes_prepare_seeded_cache_synchronously() {
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let loader_calls = calls.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="cached" src="cached.png">"#,
            move |_url: &str| {
                loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Some(png.clone())
            },
        );
        {
            let mut state = rt.state.borrow_mut();
            assert!(ensure_prepared_render(&mut state).is_some());
        }
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);

        // Constructing the JS wrapper happens here, after prepare_dom loaded
        // the resource. The first complete getter must see that cache hit
        // immediately; it must not briefly regress to pending/zero.
        assert_eq!(
            rt.evaluate(
                r#"(() => {
                    const cached = document.getElementById("cached");
                    return [
                        cached.complete,
                        cached.naturalWidth,
                        cached.naturalHeight,
                        cached.currentSrc
                    ];
                })()"#,
            )
            .unwrap(),
            serde_json::json!([true, 2, 3, "http://example.com/page/cached.png"])
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_fallback_invalidates_only_new_intrinsic_geometry() {
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let loader_calls = calls.clone();
        let png = two_by_three_png();
        let mut rt =
            parser_image_runtime(r#"<img id="late" src="late.png">"#, move |_url: &str| {
                loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Some(png.clone())
            });
        {
            let mut state = rt.state.borrow_mut();
            let previous = state.render_resources.set_sync_loading_enabled(false);
            assert!(ensure_prepared_render(&mut state).is_some());
            state.render_resources.set_sync_loading_enabled(previous);
            assert!(state.prepared_render.is_some());
        }
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);

        rt.execute_script(
            "load-image-after-layout",
            r#"
                globalThis.__lateEvents = [];
                const late = document.getElementById("late");
                late.addEventListener("load", () => __lateEvents.push("load"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[late.complete, late.naturalWidth, late.naturalHeight, __lateEvents]")
            .unwrap(),
            serde_json::json!([true, 2, 3, ["load"]])
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        {
            let state = rt.state.borrow();
            assert!(state.prepared_render.is_some());
            assert_eq!(
                state.pending_style_mutations,
                vec![obscura_render::RetainedStyleMutation::Resource]
            );
        }

        // Once the successful dimensions are retained, another loading-form
        // metadata probe is only a cache hit and must preserve fresh layout.
        {
            let mut state = rt.state.borrow_mut();
            assert!(ensure_prepared_render(&mut state).is_some());
            assert!(state.prepared_render.is_some());
        }
        rt.execute_script("reload-retained-image", r#"late.src = "late.png";"#)
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert!(rt.state.borrow().prepared_render.is_some());

        let missing_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let missing_loader_calls = missing_calls.clone();
        let mut missing = parser_image_runtime(
            r#"<img id="missing" src="missing.png">"#,
            move |_url: &str| {
                missing_loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                None
            },
        );
        {
            let mut state = missing.state.borrow_mut();
            let previous = state.render_resources.set_sync_loading_enabled(false);
            assert!(ensure_prepared_render(&mut state).is_some());
            state.render_resources.set_sync_loading_enabled(previous);
            assert!(state.prepared_render.is_some());
        }
        missing
            .execute_script(
                "fail-image-after-layout",
                r#"
                    globalThis.__missingEvents = [];
                    const missing = document.getElementById("missing");
                    missing.addEventListener("error", () => __missingEvents.push("error"));
                "#,
            )
            .unwrap();
        missing.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            missing
                .evaluate(
                    "[missing.complete, missing.naturalWidth, missing.naturalHeight, __missingEvents]"
                )
                .unwrap(),
            serde_json::json!([true, 0, 0, ["error"]])
        );
        assert_eq!(missing_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert!(missing.state.borrow().prepared_render.is_some());
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn stable_cached_image_getters_do_not_queue_resize_geometry_work() {
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="cached" src="cached.png">
               <div id="probe" style="width:40px;height:20px"></div>"#,
            move |_url: &str| Some(png.clone()),
        );
        rt.execute_script(
            "settle-cached-image",
            r#"
                const cached = document.getElementById("cached");
                void cached.complete;
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[cached.complete, cached.naturalWidth, cached.naturalHeight]")
                .unwrap(),
            serde_json::json!([true, 2, 3])
        );

        rt.execute_script(
            "observe-unrelated-geometry",
            r#"
                globalThis.__stableGetterResizeRecords = 0;
                globalThis.__stableGetterObserver = new ResizeObserver(entries => {
                    __stableGetterResizeRecords += entries.length;
                });
                __stableGetterObserver.observe(document.getElementById("probe"));
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]")
            .unwrap(),
            serde_json::json!([1, -1])
        );

        rt.execute_script(
            "read-stable-image-cache",
            r#"
                for (let i = 0; i < 50; i++) {
                    void cached.complete;
                    void cached.currentSrc;
                    void cached.naturalWidth;
                    void cached.naturalHeight;
                }
            "#,
        )
        .unwrap();
        // Cached lifecycle reads do not change intrinsic dimensions, so they
        // must not enqueue a rendering checkpoint (and its geometry walk).
        assert_eq!(
            rt.evaluate("[__stableGetterResizeRecords, __obscura_nextPendingTimeoutDelay()]")
            .unwrap(),
            serde_json::json!([1, -1])
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn parser_image_source_replacement_cancels_queued_completion() {
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen = requests.clone();
        let first = two_by_three_png();
        use base64::Engine as _;
        let second = base64::engine::general_purpose::STANDARD
            .decode(
                "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAFCAYAAABirU3b\
                 AAAAFUlEQVR4nGNk+M/wnwEJMDGgATIEAKVaAgg/Jbt7AAAAAElFTkSuQmCC"
                    .replace(char::is_whitespace, ""),
            )
            .unwrap();
        let mut rt = parser_image_runtime(r#"<img id="swap" src="old.png">"#, move |url: &str| {
            seen.lock().unwrap().push(url.to_string());
            if url.ends_with("/new.png") {
                Some(second.clone())
            } else {
                Some(first.clone())
            }
        });
        rt.execute_script(
            "replace-image-source",
            r#"
                globalThis.__swapEvents = [];
                const swap = document.getElementById("swap");
                swap.addEventListener("load", () => __swapEvents.push(swap.currentSrc));
                swap.src = "new.png";
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[swap.complete, swap.naturalWidth, swap.naturalHeight, \
                  swap.currentSrc, __swapEvents]"
            )
            .unwrap(),
            serde_json::json!([
                true,
                4,
                5,
                "http://example.com/page/new.png",
                ["http://example.com/page/new.png"]
            ])
        );
        assert_eq!(
            *requests.lock().unwrap(),
            vec!["http://example.com/page/new.png".to_string()]
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn responsive_picture_lifecycle_tracks_viewport_density_and_source_media() {
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen = requests.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"
                <picture>
                    <source type="image/avif" srcset="unsupported.avif">
                    <source id="wide-source" media="(min-width: 800px)"
                            srcset="wide.png 2x">
                    <source media="(max-width: 799px)" srcset="narrow.png">
                    <img id="responsive-picture" src="fallback.png">
                </picture>
            "#,
            move |url: &str| {
                seen.lock().unwrap().push(url.to_string());
                Some(png.clone())
            },
        );
        rt.set_viewport(1000.0, 600.0);
        rt.execute_script(
            "observe-responsive-picture",
            r#"
                globalThis.__pictureLoads = [];
                const pictureImage = document.getElementById("responsive-picture");
                pictureImage.addEventListener("load", () => {
                    __pictureLoads.push(pictureImage.currentSrc);
                });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[pictureImage.currentSrc, pictureImage.naturalWidth, \
                  pictureImage.naturalHeight, __pictureLoads]"
            )
            .unwrap(),
            serde_json::json!([
                "http://example.com/page/wide.png",
                1,
                2,
                ["http://example.com/page/wide.png"]
            ])
        );

        // A live viewport change re-runs the renderer's media/source
        // selection. The cache-only complete getter must report pending but
        // must not perform the load itself.
        rt.set_viewport(600.0, 600.0);
        assert_eq!(
            rt.evaluate("pictureImage.complete").unwrap(),
            serde_json::json!(false)
        );
        assert_eq!(requests.lock().unwrap().len(), 1);
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate(
                "[pictureImage.currentSrc, pictureImage.naturalWidth, \
                  pictureImage.naturalHeight, __pictureLoads]"
            )
            .unwrap(),
            serde_json::json!([
                "http://example.com/page/narrow.png",
                2,
                3,
                [
                    "http://example.com/page/wide.png",
                    "http://example.com/page/narrow.png"
                ]
            ])
        );

        // Mutating a <source> selection input invalidates its associated img.
        // The wide bytes are already shared in the render cache, but lifecycle
        // completion remains task-queued and emits one new load event.
        rt.execute_script(
            "mutate-picture-source",
            r#"
                document.getElementById("wide-source").setAttribute("media", "all");
                globalThis.__pictureCompleteAfterSourceMutation = pictureImage.complete;
            "#,
        )
        .unwrap();
        assert_eq!(
            rt.evaluate("__pictureCompleteAfterSourceMutation").unwrap(),
            serde_json::json!(false)
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[pictureImage.currentSrc, __pictureLoads]")
                .unwrap(),
            serde_json::json!([
                "http://example.com/page/wide.png",
                [
                    "http://example.com/page/wide.png",
                    "http://example.com/page/narrow.png",
                    "http://example.com/page/wide.png"
                ]
            ])
        );
        assert_eq!(
            *requests.lock().unwrap(),
            vec![
                "http://example.com/page/wide.png".to_string(),
                "http://example.com/page/narrow.png".to_string(),
            ]
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn responsive_srcset_sizes_uses_renderer_selected_current_src() {
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let seen = requests.clone();
        let png = two_by_three_png();
        let mut rt = parser_image_runtime(
            r#"<img id="responsive-srcset" src="fallback.png"
                     srcset="small.png 400w, large.png 800w" sizes="400px">"#,
            move |url: &str| {
                seen.lock().unwrap().push(url.to_string());
                Some(png.clone())
            },
        );
        rt.execute_script(
            "observe-responsive-srcset",
            r#"
                globalThis.__srcsetLoads = [];
                const srcsetImage = document.getElementById("responsive-srcset");
                srcsetImage.addEventListener("load", () => {
                    __srcsetLoads.push(srcsetImage.currentSrc);
                });
            "#,
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[srcsetImage.currentSrc, __srcsetLoads]")
                .unwrap(),
            serde_json::json!([
                "http://example.com/page/small.png",
                ["http://example.com/page/small.png"]
            ])
        );

        change_srcset_image_sizes(&mut rt);
        assert_eq!(
            rt.evaluate("srcsetImage.complete").unwrap(),
            serde_json::json!(false)
        );
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("[srcsetImage.currentSrc, __srcsetLoads]")
                .unwrap(),
            serde_json::json!([
                "http://example.com/page/large.png",
                [
                    "http://example.com/page/small.png",
                    "http://example.com/page/large.png"
                ]
            ])
        );
        assert_eq!(
            *requests.lock().unwrap(),
            vec![
                "http://example.com/page/small.png".to_string(),
                "http://example.com/page/large.png".to_string(),
            ]
        );
    }

    #[cfg(feature = "render")]
    fn change_srcset_image_sizes(rt: &mut ObscuraJsRuntime) {
        rt.execute_script("change-responsive-sizes", r#"srcsetImage.sizes = "800px";"#)
            .unwrap();
    }

    /// Regression for #105: `HTMLFormElement` must expose `.elements` so
    /// frameworks that probe form field collections work.
    #[test]
    fn html_form_element_exposes_elements_collection() {
        let mut rt = setup_runtime(
            r#"<form id="f"><input name=a><input name=b><textarea></textarea></form>"#,
        );
        let n = rt
            .evaluate("document.getElementById('f').elements.length")
            .unwrap();
        assert_eq!(n.as_f64().unwrap() as i64, 3);
        let is_form = rt
            .evaluate("document.getElementById('f') instanceof HTMLFormElement")
            .unwrap();
        assert_eq!(is_form, serde_json::json!(true));
    }

    /// Regression for #105: `Element.prepend` must actually insert at the
    /// start, not silently no-op.
    #[test]
    fn element_prepend_inserts_at_start() {
        let mut rt = setup_runtime(r#"<div id="c"><span>existing</span></div>"#);
        rt.evaluate(
            r#"
            const c = document.getElementById('c');
            const n = document.createElement('span');
            n.id = 'first';
            c.prepend(n);
            "#,
        )
        .unwrap();
        let first_id = rt
            .evaluate("document.getElementById('c').firstChild.id")
            .unwrap();
        assert_eq!(first_id, serde_json::json!("first"));
        let count = rt
            .evaluate("document.getElementById('c').childNodes.length")
            .unwrap();
        assert_eq!(count.as_f64().unwrap() as i64, 2);
    }

    /// Regression for #105: `isEqualNode` compares structure, not identity.
    /// Framework diff algorithms rely on this.
    #[test]
    fn is_equal_node_does_structural_compare() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate(
                r#"
                const a = document.createElement('div'); a.setAttribute('class', 'x'); a.innerHTML = '<span>hi</span>';
                const b = document.createElement('div'); b.setAttribute('class', 'x'); b.innerHTML = '<span>hi</span>';
                const c = document.createElement('div'); c.innerHTML = '<span>bye</span>';
                return [a.isEqualNode(b), a.isEqualNode(c), a.isSameNode(b)];
                "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, false, false]));
    }

    /// Regression for the long-standing insert_before arg-order bug noted
    /// in CLAUDE.md: bootstrap.js was passing (parent, new, ref) but `_dom`
    /// forwards only two args, silently dropping `ref`. With the fix,
    /// `insertBefore` actually inserts.
    #[test]
    fn insert_before_inserts_node_at_correct_position() {
        let mut rt =
            setup_runtime(r#"<div id="p"><span id="b">b</span><span id="c">c</span></div>"#);
        let order = rt
            .evaluate(
                r#"
                const p = document.getElementById('p');
                const a = document.createElement('span');
                a.id = 'a';
                p.insertBefore(a, document.getElementById('b'));
                return Array.from(p.children).map(e => e.id).join(',');
                "#,
            )
            .unwrap();
        assert_eq!(order, serde_json::json!("a,b,c"));
    }

    #[test]
    fn test_console_log() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("test", "console.log('Hello from V8!')")
            .unwrap();
    }

    #[test]
    fn test_location() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let href = rt.evaluate("location.href").unwrap();
        assert_eq!(href, serde_json::json!("http://example.com/test"));
    }

    #[test]
    fn window_origin_is_replaceable_without_changing_the_document_origin() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const descriptor = Object.getOwnPropertyDescriptor(window, 'origin');
            const initial = origin;
            const value = { replaced: true };
            origin = value;
            const replaced = Object.getOwnPropertyDescriptor(window, 'origin');
            const errors = [];
            for (const member of [descriptor.get, descriptor.set]) {
                try { member.call({}, 'fake'); errors.push('allowed'); }
                catch (error) { errors.push(error.name); }
            }
            location.href = 'https://destination.example/next';
            return [initial, descriptor.configurable, descriptor.enumerable,
                descriptor.get.name, descriptor.set.name,
                descriptor.get.length, descriptor.set.length,
                origin === value, replaced.writable, replaced.configurable,
                replaced.enumerable, descriptor.get.call(window), location.origin, errors];
        })()"#).unwrap(), serde_json::json!([
            "http://example.com", true, true, "get origin", "set origin", 0, 1,
            true, true, true, true, "http://example.com", "https://destination.example",
            ["TypeError", "TypeError"]
        ]));
    }

    #[test]
    fn window_origin_uses_the_receiver_realm_and_inherits_blank_frame_origins() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const frame = document.createElement('iframe');
            document.body.append(frame);
            const child = frame.contentWindow;
            const descriptor = Object.getOwnPropertyDescriptor(window, 'origin');
            const initial = [origin, child.origin, child.location.origin,
                descriptor.get.call(child)];
            const value = { child: true };
            descriptor.set.call(child, value);
            const replaced = child.origin === value;
            const parentUnchanged = origin === 'http://example.com';
            const deleted = delete child.origin;
            return [initial, replaced, parentUnchanged, deleted,
                descriptor.get.call(child), Object.hasOwn(child, 'origin')];
        })()"#).unwrap(), serde_json::json!([
            ["http://example.com", "http://example.com", "null", "http://example.com"],
            true, true, true, "http://example.com", false
        ]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn pbkdf2_derivation_does_not_block_page_timers() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.call_function_on_for_cdp(r#"async () => {
            const key = await crypto.subtle.importKey(
                'raw', new TextEncoder().encode('password'), 'PBKDF2', false, ['deriveBits']);
            const derivation = crypto.subtle.deriveBits({
                name: 'PBKDF2', hash: 'SHA-256',
                salt: new TextEncoder().encode('salt'), iterations: 1000000,
            }, key, 256);
            const first = await Promise.race([
                derivation.then(() => 'derivation'),
                new Promise(resolve => setTimeout(() => resolve('timer'), 0)),
            ]);
            return [first, (await derivation).byteLength];
        }"#, None, &[], true, true).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!(["timer", 32])));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn pbkdf2_async_derivation_snapshots_buffers_and_reports_operation_errors() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.call_function_on_for_cdp(r#"async () => {
            const key = await crypto.subtle.importKey(
                'raw', new TextEncoder().encode('password'), 'PBKDF2', false, ['deriveBits']);
            const salt = new TextEncoder().encode('salt');
            const derivation = crypto.subtle.deriveBits({
                name: 'PBKDF2', hash: 'SHA-1', salt, iterations: 4096,
            }, key, 160);
            salt.fill(0);
            const hex = Array.from(new Uint8Array(await derivation),
                byte => byte.toString(16).padStart(2, '0')).join('');
            const errors = [];
            for (const [iterations, bits] of [[0, 256], [10000001, 256], [10000000, 8388608]]) {
                try {
                    await crypto.subtle.deriveBits({
                        name: 'PBKDF2', hash: 'SHA-1', salt, iterations,
                    }, key, bits);
                    errors.push('allowed');
                } catch (error) {
                    errors.push([error instanceof DOMException, error.name]);
                }
            }
            return [hex, errors];
        }"#, None, &[], true, true).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!([
            "4b007901b765489abead49d926f721d065a429c1",
            [[true, "OperationError"], [true, "OperationError"], [true, "OperationError"]]
        ])));
    }

    #[test]
    fn test_button_click_dispatches_listener() {
        let mut rt = setup_runtime(r#"<button id="go">Go</button>"#);
        let result = rt
            .evaluate(
                r#"
            const button = document.getElementById('go');
            button.addEventListener('click', () => { button.dataset.clicked = 'yes'; });
            button.click();
            return button.dataset.clicked;
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!("yes"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_summary_activation_toggles_details() {
        let mut rt = setup_runtime(
            r#"<details id="panel"><summary id="first"><span id="text">More</span><button id="nested">Button</button></summary>
               <summary id="second">Other</summary><p>Content</p></details>
               <details id="cancel"><summary id="blocked">Blocked</summary></details>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const panel = document.getElementById('panel');
            const cancel = document.getElementById('cancel');
            globalThis.summaryToggles = [];
            panel.addEventListener('toggle', event => summaryToggles.push([event.oldState, event.newState]));
            document.getElementById('text').click();
            const opened = panel.open;
            document.getElementById('second').click();
            const stillOpen = panel.open;
            document.getElementById('first').click();
            const closed = panel.open;
            document.getElementById('nested').click();
            const afterNested = panel.open;
            document.getElementById('blocked').addEventListener('click', event => event.preventDefault());
            document.getElementById('blocked').click();
            return [opened, stillOpen, closed, afterNested, cancel.open, summaryToggles.length];
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true, false, false, false, 0]));
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("summaryToggles").unwrap(),
            serde_json::json!([["closed", "closed"]])
        );
        rt.evaluate("document.getElementById('first').click()")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("summaryToggles").unwrap(),
            serde_json::json!([["closed", "closed"], ["closed", "open"]])
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_details_toggle_tracks_open_attribute_changes() {
        let mut rt = setup_runtime(r#"<details id="panel"><summary>More</summary></details>"#);
        let protected = rt
            .evaluate(
                r#"
            const helper = globalThis.__obscura_activateSummary;
            globalThis.toggleStates = [];
            document.getElementById('panel').addEventListener('toggle', event => {
                toggleStates.push([event.oldState, event.newState]);
            });
            return [!Reflect.set(globalThis, '__obscura_activateSummary', () => false),
             !Reflect.deleteProperty(globalThis, '__obscura_activateSummary'),
             globalThis.__obscura_activateSummary === helper];
        "#,
            )
            .unwrap();
        assert_eq!(protected, serde_json::json!([true, true, true]));

        rt.evaluate("document.getElementById('panel').open = true")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("toggleStates").unwrap(),
            serde_json::json!([["closed", "open"]])
        );

        rt.evaluate("document.getElementById('panel').setAttribute('open', '')")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("toggleStates").unwrap(),
            serde_json::json!([["closed", "open"]])
        );

        rt.evaluate("document.getElementById('panel').toggleAttribute('open')")
            .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("toggleStates").unwrap(),
            serde_json::json!([["closed", "open"], ["open", "closed"]])
        );

        rt.evaluate(
            "const panel = document.getElementById('panel'); panel.setAttributeNS(null, 'open', ''); panel.removeAttributeNS(null, 'open')",
        )
        .unwrap();
        rt.run_event_loop_bounded(100).await.unwrap();
        assert_eq!(
            rt.evaluate("toggleStates").unwrap(),
            serde_json::json!([
                ["closed", "open"],
                ["open", "closed"],
                ["closed", "closed"]
            ])
        );
    }

    #[test]
    fn test_label_click_activates_its_labeled_control() {
        let mut rt = setup_runtime(
            r#"<label id="explicit" for="a">a</label><input type="checkbox" id="a">
               <label id="implicit">b <input type="checkbox" id="b"></label>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const ids = ['explicit', 'implicit'];
            for (const id of ids) { document.getElementById(id).click(); }
            return [document.getElementById('a').checked, document.getElementById('b').checked];
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true]));
    }

    #[test]
    fn test_label_click_honors_the_association_rules() {
        // A present `for` associates by id alone: an empty value associates
        // nothing and must not fall back to the nested control, and a dangling
        // id activates nothing. A disabled control has no activation behavior.
        let mut rt = setup_runtime(
            r#"<label id="empty" for="">a <input type="checkbox" id="a"></label>
               <label id="dangling" for="missing">b</label><input type="checkbox" id="b">
               <label id="disabled" for="c">c</label><input type="checkbox" id="c" disabled>
               <label id="both" for="d">d <input type="checkbox" id="e"></label>
               <input type="checkbox" id="d">"#,
        );
        let result = rt
            .evaluate(
                r#"
            for (const id of ['empty', 'dangling', 'disabled', 'both']) {
                document.getElementById(id).click();
            }
            return ['a', 'b', 'c', 'd', 'e'].map(id => document.getElementById(id).checked);
        "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([false, false, false, true, false])
        );
    }

    #[test]
    fn test_label_activation_does_not_double_fire_or_recurse() {
        // Clicking the control inside its own label toggles once, and a click
        // handler that clicks that label back cannot re-enter the forwarding.
        let mut rt = setup_runtime(
            r#"<label id="wrapper"><input type="checkbox" id="nested"></label>
               <label id="host" for="reentrant">r</label>
               <input type="checkbox" id="reentrant">"#,
        );
        let result = rt
            .evaluate(
                r#"
            const reentrant = document.getElementById('reentrant');
            document.getElementById('nested').click();
            let bounces = 0;
            reentrant.addEventListener('click', () => {
                if (bounces++ < 1) { document.getElementById('host').click(); }
            });
            document.getElementById('host').click();
            return [document.getElementById('nested').checked, reentrant.checked, bounces];
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true, 1]));
    }

    #[test]
    fn test_click_respects_disabled_controls_and_interactive_content() {
        // A disabled control has no activation behaviour, whether it is clicked
        // directly, reached through its label, or disabled by an ancestor
        // fieldset. Interactive content inside a label swallows the label's
        // activation, but an <a> without href is not interactive content.
        let mut rt = setup_runtime(
            r#"<input type="checkbox" id="direct" disabled>
               <fieldset disabled><label id="in-set" for="set-box">s</label>
                 <input type="checkbox" id="set-box"></fieldset>
               <label id="link"><a href="/x"><span id="in-link">go</span></a>
                 <input type="checkbox" id="link-box"></label>
               <label id="plain"><a><span id="in-plain">go</span></a>
                 <input type="checkbox" id="plain-box"></label>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const ids = ['direct', 'in-set', 'in-link', 'in-plain'];
            for (const id of ids) { document.getElementById(id).click(); }
            return ['direct', 'set-box', 'link-box', 'plain-box']
                .map(id => document.getElementById(id).checked);
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([false, false, false, true]));
    }

    #[test]
    fn test_checkbox_indeterminate_is_idl_only_and_cleared_by_activation() {
        // `indeterminate` has no content attribute, so it exists only if the
        // prototype defines it -- `'indeterminate' in el` is the check that
        // fails when it is missing. Activation clears it as well as toggling
        // checkedness (HTML legacy-pre-activation behaviour), and a cancelled
        // click puts both back, so a script-set flag is never left stuck.
        let mut rt = setup_runtime(
            r#"<input type="checkbox" id="fresh">
               <input type="checkbox" id="click">
               <input type="checkbox" id="cancel">"#,
        );
        let result = rt
            .evaluate(
                r#"
            const fresh = document.getElementById('fresh');
            const present = 'indeterminate' in fresh;
            const initial = fresh.indeterminate;
            fresh.indeterminate = true;
            const roundTrip = fresh.indeterminate;

            const clicked = document.getElementById('click');
            clicked.indeterminate = true;
            clicked.click();

            const cancelled = document.getElementById('cancel');
            cancelled.indeterminate = true;
            cancelled.addEventListener('click', e => e.preventDefault());
            cancelled.click();

            return [present, initial, roundTrip,
                    clicked.checked, clicked.indeterminate,
                    cancelled.checked, cancelled.indeterminate];
        "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, false, true, true, false, false, true])
        );
    }

    #[test]
    fn test_disabled_only_applies_to_disableable_elements() {
        // A `disabled` attribute is meaningless on anything that cannot be
        // disabled, and only listed form controls inherit it from a fieldset.
        // Component libraries do put `disabled` on plain <div>s, so treating
        // that as disabled would silently stop their clicks.
        let mut rt = setup_runtime(
            r#"<div id="plain" disabled>x</div>
               <fieldset disabled><a id="link" href="x">l</a>
                 <input type="checkbox" id="control"></fieldset>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const seen = [];
            for (const id of ['plain', 'link']) {
                const el = document.getElementById(id);
                el.addEventListener('click', e => { seen.push(id); e.preventDefault(); });
                el.click();
            }
            document.getElementById('control').click();
            return [seen.join(','), document.getElementById('control').checked];
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!(["plain,link", false]));
    }

    #[test]
    fn test_label_forwarding_uses_interactive_content_not_labelable() {
        // meter, output and progress are labelable but not interactive, so a
        // click on one still activates the label. An <a> counts only with href.
        let mut rt = setup_runtime(
            r#"<label id="l1" for="c1"><output id="o">v</output></label>
               <input type="checkbox" id="c1">
               <label id="l2" for="c2"><a id="bare">t</a></label>
               <input type="checkbox" id="c2">
               <label id="l3" for="c3"><a id="linked" href="x">t</a></label>
               <input type="checkbox" id="c3">
               <label id="l4" for="c4"><button id="btn" type="button">b</button></label>
               <input type="checkbox" id="c4">"#,
        );
        let result = rt
            .evaluate(
                r#"
            const ids = ['o', 'bare', 'linked', 'btn'];
            for (const id of ids) { document.getElementById(id).click(); }
            return ['c1', 'c2', 'c3', 'c4'].map(id => document.getElementById(id).checked);
        "#,
            )
            .unwrap();
        assert_eq!(result, serde_json::json!([true, true, false, false]));
    }

    #[test]
    fn test_radio_activation_moves_the_checked_peer_and_reverts_on_cancel() {
        let mut rt = setup_runtime(
            r#"<form><label id="pick" for="b">b</label>
                 <input type="radio" name="g" id="a" checked>
                 <input type="radio" name="g" id="b"></form>
               <form><label id="veto" for="d">d</label>
                 <input type="radio" name="h" id="c" checked>
                 <input type="radio" name="h" id="d"></form>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const seen = [];
            document.getElementById('b').addEventListener('change', () => seen.push('change'));
            document.getElementById('pick').click();
            document.getElementById('d').addEventListener('click', e => e.preventDefault());
            document.getElementById('veto').click();
            return [
                document.getElementById('a').checked, document.getElementById('b').checked,
                document.getElementById('c').checked, document.getElementById('d').checked,
                seen.join(','),
            ];
        "#,
            )
            .unwrap();
        // Activating b unchecks its peer a; the cancelled activation of d
        // restores c.
        assert_eq!(
            result,
            serde_json::json!([false, true, true, false, "change"])
        );
    }

    #[test]
    fn test_disabled_fieldset_exemption_is_the_first_legend_child_only() {
        // Every disabled fieldset ancestor counts, and only descendants of that
        // fieldset's first <legend> child escape it. A legend wrapped in a div
        // is not the fieldset's legend, a second legend does not exempt, and an
        // inner fieldset's legend does not escape an outer disabled fieldset.
        let mut rt = setup_runtime(
            r#"<fieldset disabled><legend><input type="checkbox" id="a"></legend>
                 <input type="checkbox" id="b"></fieldset>
               <fieldset disabled><legend>x</legend>
                 <legend><input type="checkbox" id="c"></legend></fieldset>
               <fieldset disabled><div><legend>
                 <input type="checkbox" id="d"></legend></div></fieldset>
               <fieldset disabled><div><fieldset disabled><legend>
                 <input type="checkbox" id="e"></legend></fieldset></div></fieldset>
               <fieldset disabled><fieldset><legend>
                 <input type="checkbox" id="f"></legend></fieldset></fieldset>"#,
        );
        let result = rt
            .evaluate(
                r#"
            const ids = ['a', 'b', 'c', 'd', 'e', 'f'];
            for (const id of ids) { document.getElementById(id).click(); }
            return ids.map(id => document.getElementById(id).checked);
        "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([true, false, false, false, false, false])
        );
    }

    #[test]
    fn test_label_click_runs_checkbox_pre_click_activation() {
        // The control flips before the click event dispatches, so listeners
        // observe the new state, `input` and `change` follow, and a cancelled
        // event restores the old state.
        let mut rt = setup_runtime(
            r#"<label id="live" for="live-box">a</label><input type="checkbox" id="live-box">
               <label id="cancel" for="cancel-box">b</label>
               <input type="checkbox" id="cancel-box">"#,
        );
        let result = rt
            .evaluate(
                r#"
            const events = [];
            const live = document.getElementById('live-box');
            for (const type of ['click', 'input', 'change']) {
                live.addEventListener(type, () => events.push(type + ':' + live.checked));
            }
            document.getElementById('live').click();
            const cancelled = document.getElementById('cancel-box');
            cancelled.addEventListener('click', event => event.preventDefault());
            document.getElementById('cancel').click();
            return [events.join(','), live.checked, cancelled.checked];
        "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!(["click:true,input:true,change:true", true, false])
        );
    }

    #[test]
    fn test_dispatch_mouse_event_runs_listener() {
        let mut rt = setup_runtime(r#"<button id="go">Go</button>"#);
        let result = rt
            .evaluate(
                r#"
            const button = document.getElementById('go');
            let count = 0;
            button.addEventListener('click', () => { count += 1; });
            button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
            return count;
        "#,
            )
            .unwrap();
        assert_eq!(result.as_f64().unwrap() as i64, 1);
    }

    #[test]
    fn test_location_href_assignment_updates_navigation_state() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let href = rt
            .evaluate("const next = '/next'; location.href = next; return location.href;")
            .unwrap();
        assert_eq!(href, serde_json::json!("http://example.com/next"));
        assert_eq!(
            rt.take_pending_navigation(),
            Some((
                "http://example.com/next".to_string(),
                "GET".to_string(),
                "".to_string()
            ))
        );
    }

    #[test]
    fn test_location_navigation_coerces_url_objects() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let hrefs = rt
            .evaluate(
                r#"(() => {
                    location.href = new URL('/from-href', location.href);
                    const href = location.href;
                    location.assign(new URL('/from-assign', location.href));
                    const assigned = location.href;
                    location.replace(new URL('/from-replace', location.href));
                    return [href, assigned, location.href];
                })()"#,
            )
            .unwrap();
        assert_eq!(
            hrefs,
            serde_json::json!([
                "http://example.com/from-href",
                "http://example.com/from-assign",
                "http://example.com/from-replace"
            ])
        );
        assert_eq!(
            rt.take_pending_navigation(),
            Some((
                "http://example.com/from-replace".to_string(),
                "GET".to_string(),
                "".to_string()
            ))
        );
    }

    #[test]
    fn test_submit_button_click_handler_can_prevent_default_and_navigate() {
        let mut rt =
            setup_runtime(r#"<form><button type="submit" id="submit">Submit</button></form>"#);
        let href = rt
            .evaluate(
                r#"
            const form = document.querySelector('form');
            form.addEventListener('submit', (event) => {
                event.preventDefault();
                location.href = '/submitted';
            });
            document.getElementById('submit').click();
            return location.href;
        "#,
            )
            .unwrap();
        assert_eq!(href, serde_json::json!("http://example.com/submitted"));
        assert_eq!(
            rt.take_pending_navigation(),
            Some((
                "http://example.com/submitted".to_string(),
                "GET".to_string(),
                "".to_string()
            ))
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_evaluation_does_not_call_the_pages_eval() {
        let mut rt = ObscuraJsRuntime::new();
        rt.evaluate_script("globalThis.eval = () => { throw new Error('page eval called'); };").unwrap();
        for await_promise in [false, true] {
            let result = rt.evaluate_for_cdp("6 * 7", true, await_promise).await.unwrap();
            assert!(!result.thrown);
            assert_eq!(result.value, Some(serde_json::json!(42.0)));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_evaluation_preserves_global_lexical_bindings() {
        let mut rt = ObscuraJsRuntime::new();
        for (name, await_promise) in [("syncLexical", false), ("asyncLexical", true)] {
            let declaration = format!("let {name} = 40; {name}");
            let first = rt.evaluate_for_cdp(&declaration, true, await_promise).await.unwrap();
            assert_eq!(first.value, Some(serde_json::json!(40.0)));
            let second = rt.evaluate_for_cdp(&format!("{name} += 2; {name}"), true, await_promise).await.unwrap();
            assert!(!second.thrown);
            assert_eq!(second.value, Some(serde_json::json!(42.0)));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_by_value_results_do_not_retain_unreleasable_objects() {
        let mut rt = ObscuraJsRuntime::new();
        // A real remote handle must survive by-value calls until released.
        let handle = rt.evaluate_for_cdp("({kept: 42})", false, true).await.unwrap();
        let oid = handle.object_id.unwrap();
        for await_promise in [false, true] {
            for call_function in [false, true] {
                for _ in 0..32 {
                    let result = if call_function {
                        rt.call_function_on_for_cdp(
                            "function() { return {payload: Array(1024).fill(7)}; }",
                            None, &[], true, await_promise,
                        ).await.unwrap()
                    } else {
                        rt.evaluate_for_cdp(
                            "({payload: Array(1024).fill(7)})", true, await_promise,
                        ).await.unwrap()
                    };
                    assert!(result.object_id.is_none());
                    assert_eq!(result.value.unwrap()["payload"].as_array().unwrap().len(), 1024);
                }
                assert_eq!(
                    rt.evaluate("Object.keys(globalThis.__obscura_objects).length").unwrap(),
                    serde_json::json!(1.0),
                    "unreleasable JS results: call_function={call_function}, await_promise={await_promise}",
                );
                assert_eq!(rt.object_store.len(), 1, "unreleasable Rust handles");
            }
        }
        let kept = rt.call_function_on_for_cdp(
            "function() { return this.kept; }", Some(&oid), &[], true, false,
        ).await.unwrap();
        assert_eq!(kept.value, Some(serde_json::json!(42.0)));
        rt.release_object(&oid);
        assert_eq!(
            rt.evaluate("Object.keys(globalThis.__obscura_objects).length").unwrap(),
            serde_json::json!(0.0),
        );
        assert!(rt.object_store.is_empty());
        assert_eq!(
            rt.evaluate("Object.keys(globalThis).filter(key => key.startsWith('__obscura_done_')).length").unwrap(),
            serde_json::json!(0.0),
            "completed calls must not retain per-call completion globals",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn response_constructor_validates_public_init_without_forging_network_metadata() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const error = callback => { try { callback(); return null; } catch (e) { return e.name; } };
            const response = new Response(null, {type:'opaque',url:'https://example.com/',redirected:true});
            let statusReads = 0;
            const singleRead = new Response(null, {get status(){statusReads++;return 201;}});
            return {
                ordinary:[response.type,response.url,response.redirected,String(response.status)],
                invalidStatus:[0,100,199,600,1000].map(status=>error(()=>new Response('',{status}))),
                conversion:[65736,200.9,'201'].map(status=>String(new Response(null,{status}).status)),
                invalidStatusText:['\n','\r','\0','\u0100'].map(statusText=>error(()=>new Response(null,{statusText}))),
                validStatusText:['\tOK','\u0080'].map(statusText=>new Response(null,{statusText}).statusText),
                nullBodyStatus:[204,205,304].map(status=>error(()=>new Response('',{status}))),
                nullBodyAllowed:[204,205,304].map(status=>new Response(null,{status}).body),
                nullInit:String(new Response(null,null).status),
                getter:[String(singleRead.status),String(statusReads)]
            };
        "#).unwrap();
        assert_eq!(result, serde_json::json!({
            "ordinary":["default","",false,"200"],
            "invalidStatus":["RangeError","RangeError","RangeError","RangeError","RangeError"],
            "conversion":["200","200","201"],
            "invalidStatusText":["TypeError","TypeError","TypeError","TypeError"],
            "validStatusText":["\tOK","\u{0080}"],
            "nullBodyStatus":["TypeError","TypeError","TypeError"],
            "nullBodyAllowed":[null,null,null],
            "nullInit":"200",
            "getter":["201","1"]
        }));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn response_factories_validate_redirects_and_json_and_preserve_error_clones() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"
            const error = callback => { try { callback(); return null; } catch (e) { return e.name; } };
            const networkError = Response.error();
            const copy = networkError.clone();
            const redirect = Response.redirect('https://example.com/a/../b');
            const json = Response.json({ok:true},{headers:new Headers({'x-check':'preserved'})});
            return {
                error:[networkError.type,String(networkError.status),networkError.body],
                clone:[copy.type,String(copy.status),copy.body],
                redirect:[redirect.type,String(redirect.status),redirect.headers.get('location')],
                invalidRedirectStatus:[0,200,309,400,500].map(status=>error(()=>Response.redirect('https://example.com/',status))),
                invalidRedirectUrl:error(()=>Response.redirect('https://[invalid')),
                json:[json.type,json.headers.get('content-type'),json.headers.get('x-check')],
                jsonUndefined:error(()=>Response.json(undefined)),
                jsonSymbol:error(()=>Response.json(Symbol('value'))),
                jsonNullBodyStatus:[204,205,304].map(status=>error(()=>Response.json('body',{status})))
            };
        "#).unwrap();
        assert_eq!(result, serde_json::json!({
            "error":["error","0",null], "clone":["error","0",null],
            "redirect":["default","302","https://example.com/b"],
            "invalidRedirectStatus":["RangeError","RangeError","RangeError","RangeError","RangeError"],
            "invalidRedirectUrl":"TypeError", "json":["default","application/json","preserved"],
            "jsonUndefined":"TypeError", "jsonSymbol":"TypeError",
            "jsonNullBodyStatus":["TypeError","TypeError","TypeError"]
        }));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn response_body_exposes_stream_and_consumption_state() {
        // #818: a non-null Response body must expose a ReadableStream through
        // .body, a boolean .bodyUsed, and a working getReader(); consuming
        // the body marks it used and a second consumption throws.
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate_for_cdp(
                r#"(async () => {
                    const r = new Response("hello");
                    const meta = {
                        bodyType: r.body === null ? "null" : typeof r.body,
                        bodyUsed: r.bodyUsed,
                        hasReader: !!(r.body && r.body.getReader),
                    };
                    const reader = r.body.getReader();
                    const first = await reader.read();
                    const second = await reader.read();
                    const chunkText = first.value ? new TextDecoder().decode(first.value) : "";
                    const consumed = r.bodyUsed;
                    let doubleThrew = false;
                    try { await r.text(); } catch (e) { doubleThrew = true; }
                    return { meta, chunkText, done: second.done, consumed, doubleThrew, nullBody: new Response(null).body === null };
                })()"#,
                true,
                true,
            )
            .await
            .expect("evaluation must succeed");
        let out = result.value.unwrap();
        assert_eq!(out["meta"]["bodyType"], "object");
        assert_eq!(out["meta"]["bodyUsed"], false);
        assert_eq!(out["meta"]["hasReader"], true);
        assert_eq!(out["chunkText"], "hello");
        assert_eq!(out["done"], true);
        assert_eq!(out["consumed"], true);
        assert_eq!(out["doubleThrew"], true);
        assert_eq!(out["nullBody"], true);
    }

    #[test]
    fn test_navigator() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let ua = rt.evaluate("navigator.userAgent").unwrap();
        assert!(
            ua.as_str().unwrap().contains("Chrome"),
            "UA should contain Chrome: {}",
            ua
        );
        let wd = rt.evaluate("navigator.webdriver").unwrap();
        assert_eq!(wd, serde_json::json!(false));
        let plugins = rt.evaluate("navigator.plugins.length").unwrap();
        assert!(plugins.as_f64().unwrap() > 0.0, "Should have plugins");
        let plugin_interfaces = rt
            .evaluate(
                r#"({
                    Navigator: typeof Navigator,
                    PluginArray: typeof PluginArray,
                    Plugin: typeof Plugin,
                    MimeType: typeof MimeType,
                    MimeTypeArray: typeof MimeTypeArray,
                    pluginsMatch: navigator.plugins instanceof PluginArray,
                    enumerable: Object.getOwnPropertyDescriptor(window, "PluginArray").enumerable,
                })"#,
            )
            .unwrap();
        assert_eq!(plugin_interfaces["Navigator"], "function");
        assert_eq!(plugin_interfaces["PluginArray"], "function");
        assert_eq!(plugin_interfaces["Plugin"], "function");
        assert_eq!(plugin_interfaces["MimeType"], "function");
        assert_eq!(plugin_interfaces["MimeTypeArray"], "function");
        assert_eq!(plugin_interfaces["pluginsMatch"], true);
        assert_eq!(plugin_interfaces["enumerable"], false);
        let chrome = rt.evaluate("typeof window.chrome").unwrap();
        assert_eq!(chrome, serde_json::json!("object"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn unserializable_value_arguments_are_limited_to_the_cdp_set() {
        // CDP's UnserializableValue is a closed set. Anything else is source
        // text that must not be evaluated just because it arrived in that field.
        let mut rt = setup_runtime("<html><body></body></html>");
        let args = vec![serde_json::json!({
            "unserializableValue": "(globalThis.__pwned = 1)"
        })];
        let result = rt
            .call_function_on("(a) => typeof a", None, &args, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!("undefined"));
        assert_eq!(
            rt.evaluate("globalThis.__pwned").unwrap(),
            serde_json::Value::Null
        );

        for (unser, expected) in [
            ("Infinity", "Infinity"),
            ("-Infinity", "-Infinity"),
            ("NaN", "NaN"),
            ("-0", "-0"),
            ("12n", "12n"),
            ("-7n", "-7n"),
        ] {
            let args = vec![serde_json::json!({ "unserializableValue": unser })];
            let result = rt
                .call_function_on(
                    "(a) => Object.is(a, -0) ? '-0' : (typeof a === 'bigint' ? a + 'n' : String(a))",
                    None,
                    &args,
                    true,
                )
                .await
                .unwrap();
            assert_eq!(result.value.unwrap(), serde_json::json!(expected), "{unser}");
        }
    }

    #[test]
    fn release_object_never_interpolates_the_object_id_as_source() {
        let mut rt = setup_runtime("<html><body></body></html>");
        // A key the CDP client controls only reaches release_object when the
        // store holds it; simulate a store entry whose id carries source text.
        let hostile = "x'];globalThis.__pwned=1;//";
        rt.object_store
            .insert(hostile.to_string(), CdpObjectRecord { retrieval: "undefined".to_string(), frame: None });
        rt.release_object(hostile);
        assert_eq!(
            rt.evaluate("globalThis.__pwned").unwrap(),
            serde_json::Value::Null,
            "the object id must be embedded as a string literal, never as source"
        );
    }

    #[test]
    fn replacing_a_subtree_releases_its_linked_stylesheets() {
        // innerHTML and subtree removal bypass Node.removeChild, which was the
        // only path that released native external stylesheet bytes. On an SPA
        // that swaps sections holding <link rel=stylesheet>, the native map
        // grew without bound and a recycled node id could inherit stale CSS.
        let mut rt = setup_runtime(
            "<html><body><div id=\"outer\"><div id=\"inner\">\
             <link rel=\"stylesheet\" href=\"a.css\"></div></div>\
             <div id=\"other\"><link rel=\"stylesheet\" href=\"b.css\"></div></body></html>",
        );
        rt.with_dom(|dom| {
            for link in dom.query_selector_all("link").unwrap() {
                dom.append_external_stylesheet(link, "p{color:red}".to_string(), true);
            }
        });
        rt.execute_script(
            "<register>",
            "for (const l of document.querySelectorAll('link')) \
                 globalThis.__obscura_registerLinkedStylesheet(l, 'http://x/' + l.getAttribute('href'));",
        )
        .unwrap();
        assert_eq!(rt.with_dom(|dom| dom.external_stylesheets().len()).unwrap(), 2);

        // innerHTML replacement of an ancestor.
        rt.evaluate("document.getElementById('outer').innerHTML = '<p>gone</p>'")
            .unwrap();
        assert_eq!(
            rt.with_dom(|dom| dom.external_stylesheets().len()).unwrap(),
            1,
            "innerHTML must release the linked stylesheet of a removed descendant"
        );
        // removeChild of an ancestor (the link is a grandchild, not the child).
        rt.evaluate("document.body.removeChild(document.getElementById('other'))")
            .unwrap();
        assert_eq!(
            rt.with_dom(|dom| dom.external_stylesheets().len()).unwrap(),
            0,
            "removing an ancestor must release the linked stylesheets below it"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_calls_do_not_use_a_page_overridden_function_call() {
        for await_promise in [false, true] {
            let mut rt = setup_runtime("<body></body>");
            let receiver = rt.evaluate_for_cdp("({base:40})", false, false).await.unwrap();
            rt.execute_script("<override-call>",
                "Function.prototype.call=function(){throw new Error('page call override');};").unwrap();
            for declaration in [
                "function(value){return this.base+value;}",
                "function(value){return this.base+value;}\n//# sourceURL=cdp-function.js",
            ] {
                let result = rt.call_function_on_for_cdp(
                    declaration, receiver.object_id.as_deref(),
                    &[serde_json::json!({"value":2})], true, await_promise,
                ).await.unwrap();
                assert!(!result.thrown);
                assert_eq!(result.value.as_ref().and_then(serde_json::Value::as_f64), Some(42.0));
            }
            let thrown = rt.call_function_on_for_cdp(
                "function(){throw new Error('native call error');}", None, &[], true, await_promise,
            ).await.unwrap();
            assert!(thrown.thrown);
            assert_eq!(thrown.subtype.as_deref(), Some("error"));
            assert!(thrown.description.contains("native call error"));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_call_json_arguments_preserve_proto_data_properties() {
        for await_promise in [false, true] {
            let mut rt = setup_runtime("<body></body>");
            rt.execute_script("<override-json>",
                "JSON.parse=function(){throw new Error('page JSON override');};").unwrap();
            let argument = serde_json::from_str(r#"{"value":{"__proto__":{"sentinel":42},"marker":7,"nested":[{"__proto__":null}]}}"#).unwrap();
            let result = rt.call_function_on_for_cdp(r#"function(value){
                const child=value.nested[0];
                return [Object.hasOwn(value,'__proto__'), Object.getPrototypeOf(value)===Object.prototype,
                    value.__proto__.sentinel, value.marker, Object.hasOwn(child,'__proto__'),
                    Object.getPrototypeOf(child)===Object.prototype, child.__proto__===null];
            }"#, None, &[argument], true, await_promise).await.unwrap();
            assert!(!result.thrown);
            assert_eq!(result.value, Some(serde_json::json!([true,true,42,7,true,true,true])));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_no_args() {
        let mut rt = setup_runtime("<html><head><title>Test</title></head><body></body></html>");
        let result = rt
            .call_function_on("() => document.title", None, &[], true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!("Test"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_with_args() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let args = vec![
            serde_json::json!({"value": 10}),
            serde_json::json!({"value": 20}),
        ];
        let result = rt
            .call_function_on("(a, b) => a + b", None, &args, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_f64().unwrap() as i64, 30);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_with_string_args() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let args = vec![
            serde_json::json!({"value": "hello"}),
            serde_json::json!({"value": " world"}),
        ];
        let result = rt
            .call_function_on("(a, b) => a + b", None, &args, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!("hello world"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_with_object_args() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let args = vec![serde_json::json!({"value": {"name": "test", "count": 5}})];
        let result = rt
            .call_function_on("(obj) => obj.name + ':' + obj.count", None, &args, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!("test:5"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_return_object() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .call_function_on("() => ({a: 1, b: 2})", None, &[], true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!({"a": 1, "b": 2}));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_object_ref_preserves_methods() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .call_function_on(
                "() => ({ items: [1,2,3], getLen: function() { return this.items.length; } })",
                None,
                &[],
                false,
            )
            .await
            .unwrap();
        let oid = result.object_id.unwrap();

        let result2 = rt
            .call_function_on(
                "function() { return this.getLen(); }",
                Some(&oid),
                &[],
                true,
            )
            .await
            .unwrap();
        assert_eq!(result2.value.unwrap().as_f64().unwrap() as i64, 3);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_detects_node() {
        let mut rt = setup_runtime("<html><body><h1>Hello</h1></body></html>");
        let result = rt
            .evaluate_for_cdp("document.querySelector('h1')", false, false)
            .await
            .unwrap();
        assert_eq!(result.subtype.as_deref(), Some("node"));
        assert_eq!(result.js_type, "object");
        assert!(result.object_id.is_some());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_detects_document() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate_for_cdp("document", false, false).await.unwrap();
        assert_eq!(result.subtype.as_deref(), Some("node"));
        assert_eq!(result.class_name, "HTMLDocument");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_awaits_resolved_promise() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate_for_cdp("Promise.resolve(42)", true, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_f64().unwrap() as i64, 42);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn pending_promise_wait_yields_to_other_tasks() {
        use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};

        let mut rt = setup_runtime("<html><body></body></html>");
        let turns = Arc::new(AtomicUsize::new(0));
        let observed = turns.clone();
        let heartbeat = tokio::spawn(async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                observed.fetch_add(1, Ordering::Relaxed);
            }
        });
        tokio::task::yield_now().await;
        assert!(!rt.resolve_promises_until(|_| false, 80).await);
        heartbeat.abort();
        assert!(turns.load(Ordering::Relaxed) > 1,
            "an idle promise wait must yield instead of spinning until its deadline");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn awaited_fetch_progresses_while_posted_tasks_remain_ready() {
        let (mut rt, accepted) = delayed_fetch_runtime(std::time::Duration::from_millis(20));
        let started = std::time::Instant::now();
        let result = rt.evaluate_for_cdp(
            r#"(async () => {
                const channel = new MessageChannel();
                const deadline = Date.now() + 2000;
                let turns = 0;
                channel.port1.onmessage = () => {
                    turns++;
                    const taskEnd = Date.now() + 60;
                    while (Date.now() < taskEnd) {}
                    if (Date.now() < deadline) channel.port2.postMessage(null);
                };
                channel.port2.postMessage(null);
                const text = await (await fetch('/hydrate')).text();
                channel.port1.close();
                channel.port2.close();
                return { text, turns };
            })()"#,
            true, true,
        ).await.unwrap();
        let elapsed = started.elapsed();
        accepted.recv_timeout(std::time::Duration::from_millis(100)).unwrap();
        let value = result.value.unwrap();
        assert_eq!(value["text"], "hydrated");
        assert!(value["turns"].as_f64().unwrap() > 0.0);
        assert!(elapsed < std::time::Duration::from_millis(1000),
            "network progress waited for the posted-task queue to drain: {elapsed:?}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn resolved_cdp_promise_does_not_run_unrelated_ready_timer() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.execute_script("ready-timer", "globalThis.timerRan = false; setTimeout(() => timerRan = true, 0);").unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        let result = rt.evaluate_for_cdp("Promise.resolve(42)", true, true).await.unwrap();
        assert_eq!(result.value.unwrap(), serde_json::json!(42.0));
        assert_eq!(rt.evaluate("timerRan").unwrap(), serde_json::json!(false),
            "an already-resolved CDP promise must not drain unrelated tasks");
        rt.run_autonomous_event_loop_turn().await.unwrap();
        assert_eq!(rt.evaluate("timerRan").unwrap(), serde_json::json!(true),
            "the timer must still run on the autonomous pump");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_awaits_timer_promise() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate_for_cdp(
                "new Promise(resolve => setTimeout(() => resolve('done'), 1))",
                true,
                true,
            )
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_str().unwrap(), "done");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_settled_promise_does_not_wait_for_unrelated_timer() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let expression = "(() => {
            globalThis.unrelatedTimerFinished = false;
            setTimeout(() => { globalThis.unrelatedTimerFinished = true; }, 0);
            return Promise.resolve(42);
        })()";
        for call_function in [false, true] {
            let result = if call_function {
                rt.call_function_on_for_cdp_with_timeout(
                    &format!("() => {expression}"), None, &[], true, true, 1000,
                ).await
            } else {
                rt.evaluate_for_cdp_with_timeout(expression, true, true, 1000).await
            }.unwrap();
            assert_eq!(result.value.and_then(|value| value.as_f64()), Some(42.0));
            let timer = rt.evaluate_for_cdp("globalThis.unrelatedTimerFinished", true, false)
                .await.unwrap();
            assert_eq!(timer.value, Some(serde_json::json!(false)),
                "an already-settled promise must not drain unrelated timers (callFunctionOn={call_function})");
            rt.evaluate_for_cdp("new Promise(resolve => setTimeout(resolve, 10))", true, true)
                .await.unwrap();
            let timer = rt.evaluate_for_cdp("globalThis.unrelatedTimerFinished", true, false)
                .await.unwrap();
            assert_eq!(timer.value, Some(serde_json::json!(true)), "the timer must still run");
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_can_await_beyond_legacy_five_second_cap() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let started = std::time::Instant::now();
        let result = rt
            .evaluate_for_cdp_with_timeout(
                "new Promise(resolve => setTimeout(() => resolve('after-five'), 5100))",
                true,
                true,
                6000,
            )
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_str(), Some("after-five"));
        assert!(
            started.elapsed() >= std::time::Duration::from_secs(5),
            "long promise resolved before its timer deadline"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_for_cdp_reports_unsettled_promise_timeout() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let error = rt
            .call_function_on_for_cdp_with_timeout(
                "() => new Promise(() => {})",
                None,
                &[],
                true,
                true,
                25,
            )
            .await
            .unwrap_err();
        assert!(
            error.contains("did not settle within 25ms"),
            "unexpected timeout error: {error}"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_awaits_async_function() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate_for_cdp("(async () => 'async-ok')()", true, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_str().unwrap(), "async-ok");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn releasing_remote_objects_keeps_inflight_evaluations_alive() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let first = rt.start_cdp_evaluation(
            "new Promise(resolve=>{globalThis.finishFirst=resolve})", true, true,
        ).unwrap();
        let second = rt.start_cdp_call(
            "()=>new Promise(resolve=>setTimeout(()=>{finishFirst(42);resolve({answer:7})},1))",
            None, &[], false, true,
        ).unwrap();
        let CdpEvaluation::Pending(first) = first else { panic!("expected pending evaluation"); };
        let CdpEvaluation::Pending(second) = second else { panic!("expected pending evaluation"); };
        rt.release_object_group();
        assert!(rt.resolve_promises_until(|rt| rt.cdp_evaluation_ready(&first) && rt.cdp_evaluation_ready(&second), 100).await,
            "releasing client object handles must not discard an inflight evaluation");
        let result = rt.finish_cdp_evaluation(second, false).unwrap();
        let answer = rt.call_function_on_for_cdp("function(){return this.answer}", result.object_id.as_deref(), &[], true, false).await.unwrap();
        assert_eq!(answer.value.as_ref().and_then(serde_json::Value::as_f64), Some(7.0));
        rt.release_object_group();
        let result = rt.finish_cdp_evaluation(first, true).unwrap();
        assert_eq!(result.value.as_ref().and_then(serde_json::Value::as_f64), Some(42.0));
        assert!(rt.pending_cdp_evaluations.is_empty(), "completed commands must release their native roots");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_timed_out_rejection_cannot_poison_a_later_success() {
        for call_function in [false, true] {
            let mut rt = setup_runtime("<html><body></body></html>");
            assert!(rt.evaluate_for_cdp_with_timeout(
                "new Promise((resolve,reject)=>{globalThis.rejectOld=reject})", true, true, 10,
            ).await.is_err());
            assert!(rt.pending_cdp_evaluations.is_empty(), "timed-out commands must release their native roots");
            rt.release_object_group();
            let body = "Promise.resolve().then(()=>queueMicrotask(()=>rejectOld(new Error('old-rejection'))));return 42;";
            let result = if call_function {
                rt.call_function_on_for_cdp(&format!("function(){{{body}}}"), None, &[], true, true).await
            } else {
                rt.evaluate_for_cdp(&format!("(function(){{{body}}})()"), true, true).await
            }.unwrap();
            assert!(!result.thrown, "an older rejected callback contaminated this call: {}", result.description);
            assert_eq!(result.value.as_ref().and_then(serde_json::Value::as_f64), Some(42.0));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cdp_timed_out_success_cannot_hide_a_later_rejection() {
        for call_function in [false, true] {
            let mut rt = setup_runtime("<html><body></body></html>");
            assert!(rt.evaluate_for_cdp_with_timeout(
                "new Promise(resolve=>{globalThis.resolveOld=resolve})", true, true, 10,
            ).await.is_err());
            rt.release_object_group();
            let body = "Promise.resolve().then(()=>queueMicrotask(()=>resolveOld(99)));return Promise.reject(new Error('current-failure'));";
            let result = if call_function {
                rt.call_function_on_for_cdp(&format!("function(){{{body}}}"), None, &[], true, true).await
            } else {
                rt.evaluate_for_cdp(&format!("(function(){{{body}}})()"), true, true).await
            }.unwrap();
            assert!(result.thrown, "an older resolved callback hid this call's rejection: {:?}", result.value);
            assert!(result.description.contains("current-failure"), "{}", result.description);
        }
    }

    // CDP answers the command and reports rejections through exceptionDetails.
    #[tokio::test(flavor = "current_thread")]
    async fn test_evaluate_for_cdp_reports_promise_rejection() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("Promise.reject(new Error('boom'))", true, true)
            .await
            .expect("a rejection is answered, not failed");
        assert!(info.thrown, "the rejected value must be marked as thrown");
        assert_eq!(info.js_type, "object");
        assert_eq!(info.subtype.as_deref(), Some("error"));
        assert_eq!(info.class_name, "Error");
        assert!(
            info.description.contains("boom"),
            "the description is what a client rebuilds the error from: {}",
            info.description
        );
        // Reported by reference, never serialized: an Error has no own
        // enumerable properties, so by value it would be `{}`.
        assert!(info.value.is_none());
        assert!(info.object_id.is_some());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn call_function_on_marks_a_rejection_instead_of_returning_it() {
        // The reported shape: returnByValue on a rejected call answered
        // successfully with `{}`, because the wrapper stored the error under
        // the object id a success uses and nothing said which branch ran.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .call_function_on_for_cdp(
                "() => Promise.reject(new Error('boom'))",
                None,
                &[],
                true,
                true,
            )
            .await
            .expect("a rejection is answered, not failed");
        assert!(info.thrown, "expected a thrown value, got {:?}", info.value);
        assert_eq!(info.subtype.as_deref(), Some("error"));
        assert!(info.description.contains("boom"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn call_function_on_separates_a_rejected_object_from_a_resolved_one() {
        // The sharper half of the same defect: rejecting with a plain object
        // produced a reply byte-identical to resolving with it, so no client
        // could tell the two apart.
        let mut rt = setup_runtime("<html><body></body></html>");
        let resolved = rt
            .call_function_on_for_cdp("() => Promise.resolve({code: 42})", None, &[], true, true)
            .await
            .unwrap();
        let rejected = rt
            .call_function_on_for_cdp("() => Promise.reject({code: 42})", None, &[], true, true)
            .await
            .unwrap();
        assert!(!resolved.thrown);
        assert!(rejected.thrown);
        assert_eq!(resolved.value, Some(serde_json::json!({"code": 42})));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn a_synchronous_throw_is_reported_instead_of_swallowed() {
        // The sync wrapper answered a throw with `__result = undefined`, so the
        // command succeeded and the page error vanished. A client cannot tell
        // that from an expression that genuinely has no value.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("undefined_variable_xyz", false, false)
            .await
            .expect("a page error is not a protocol failure");
        assert!(
            info.thrown,
            "a ReferenceError must come back flagged thrown"
        );
        assert_eq!(info.subtype.as_deref(), Some("error"));
        assert!(
            info.description.contains("ReferenceError"),
            "the description is what a client rebuilds the error from: {:?}",
            info.description
        );
    }
    
    #[tokio::test(flavor = "current_thread")]
    async fn a_synchronous_throw_is_reported_when_a_value_was_asked_for() {
        // returnByValue took a different route entirely, through `evaluate`,
        // whose wrapper answers an exception with null. That is the shape a
        // Puppeteer `page.evaluate` uses most, and it reported success.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("undefined_variable_xyz", true, false)
            .await
            .expect("a page error is not a protocol failure");
        assert!(info.thrown, "a ReferenceError must not serialize to null");
        assert!(info.description.contains("ReferenceError"));
    }
    
    #[tokio::test(flavor = "current_thread")]
    async fn a_throw_statement_is_run_as_a_script_not_wrapped_in_parentheses() {
        // `Runtime.evaluate` takes a script. Pasted into `(...)` a throw is a
        // parse-time SyntaxError, which no catch can see, so the whole command
        // failed at the protocol level instead of reporting the page's error.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("throw new Error('boom')", false, false)
            .await
            .expect("a throw statement must be evaluated, not rejected as invalid");
        assert!(info.thrown);
        assert!(
            info.description.contains("boom"),
            "the thrown error must survive: {:?}",
            info.description
        );
    }
    
    #[tokio::test(flavor = "current_thread")]
    async fn a_statement_bundle_yields_its_completion_value() {
        // Chrome reports the completion value of the script. The old wrapper
        // put statement bundles in a function body with no `return`, so every
        // one of them evaluated to the wrapper's own undefined.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("var completion_x = 1; completion_x * 2", true, false)
            .await
            .expect("statement bundles are valid input");
        assert!(!info.thrown);
        // Compared as a number rather than against a literal: the engine
        // boxes every number as f64, so `json!(2)` would not match `2.0`.
        // That spelling is its own defect and does not belong to this test.
        assert_eq!(
            info.value.as_ref().and_then(serde_json::Value::as_f64),
            Some(2.0),
            "the bundle's completion value, not the wrapper's undefined"
        );
    }
    
    #[tokio::test(flavor = "current_thread")]
    async fn a_trailing_semicolon_and_source_url_still_parse() {
        // Both were handled by hand before: the semicolon had to be trimmed or
        // `(expr;)` failed to parse, and the sourceURL comment had to be closed
        // by a newline or it swallowed the wrapper's own paren. Passing the
        // script as a string removes the class, so these pin that it stays gone.
        let mut rt = setup_runtime("<html><body></body></html>");
        let info = rt
            .evaluate_for_cdp("(() => 7)();", true, false)
            .await
            .expect("a trailing semicolon is legal");
        assert_eq!(
            info.value.as_ref().and_then(serde_json::Value::as_f64),
            Some(7.0)
        );
    
        let info = rt
            .evaluate_for_cdp(
                "(() => 8)()\n//# sourceURL=__puppeteer_evaluation_script__",
                true,
                false,
            )
            .await
            .expect("a trailing sourceURL comment is legal");
        assert_eq!(
            info.value.as_ref().and_then(serde_json::Value::as_f64),
            Some(8.0)
        );
    }
    
    #[tokio::test(flavor = "current_thread")]
    async fn a_rejection_does_not_leak_into_the_next_call() {
        // Completed calls must not carry rejection state into either API entrypoint.
        let mut rt = setup_runtime("<html><body></body></html>");
        let rejected = rt
            .call_function_on_for_cdp(
                "() => Promise.reject(new Error('first'))",
                None,
                &[],
                true,
                true,
            )
            .await
            .unwrap();
        assert!(rejected.thrown);
        let after = rt
            .call_function_on_for_cdp("() => Promise.resolve(7)", None, &[], true, true)
            .await
            .unwrap();
        assert!(!after.thrown, "a later success was still marked as thrown");
        assert_eq!(after.value.unwrap().as_f64(), Some(7.0));

        let evaluated = rt
            .evaluate_for_cdp("Promise.resolve(8)", true, true)
            .await
            .unwrap();
        assert!(!evaluated.thrown);
        assert_eq!(evaluated.value.unwrap().as_f64(), Some(8.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_call_function_on_dom_interaction() {
        let mut rt = setup_runtime(r#"<div id="items"><span>A</span><span>B</span></div>"#);
        let args = vec![serde_json::json!({"value": "span"})];
        let result = rt
            .call_function_on(
                "(sel) => document.querySelectorAll(sel).length",
                None,
                &args,
                true,
            )
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_f64().unwrap() as i64, 2);
    }

    #[test]
    fn test_inner_html_setter() {
        let mut rt = setup_runtime(r#"<div id="target"><p>Old</p></div>"#);
        rt.execute_script(
            "test",
            r#"
            var el = document.getElementById('target');
            el.innerHTML = '<strong>Bold</strong><em>Italic</em>';
        "#,
        )
        .unwrap();
        let result = rt
            .evaluate("document.getElementById('target').innerHTML")
            .unwrap();
        let html = result.as_str().unwrap();
        assert!(
            html.contains("<strong>"),
            "innerHTML should contain <strong>, got: {}",
            html
        );
        assert!(
            html.contains("<em>"),
            "innerHTML should contain <em>, got: {}",
            html
        );
        assert!(
            !html.contains("Old"),
            "innerHTML should not contain old content, got: {}",
            html
        );
    }

    #[test]
    fn test_inner_html_with_nested() {
        let mut rt = setup_runtime(r#"<div id="root"></div>"#);
        rt.execute_script(
            "test",
            r#"
            var el = document.getElementById('root');
            el.innerHTML = '<ul><li>A</li><li>B</li><li>C</li></ul>';
        "#,
        )
        .unwrap();
        let count = rt
            .evaluate("document.querySelectorAll('li').length")
            .unwrap();
        assert_eq!(
            count.as_f64().unwrap() as i64,
            3,
            "Should find 3 li elements after innerHTML set"
        );

        let text = rt
            .evaluate("document.querySelector('li').textContent")
            .unwrap();
        assert_eq!(text, serde_json::json!("A"));
    }

    #[test]
    fn test_input_value() {
        let mut rt = setup_runtime(
            r#"<form><input id="name" type="text" value="initial"><textarea id="bio">old text</textarea></form>"#,
        );
        let val = rt
            .evaluate("document.getElementById('name').value")
            .unwrap();
        assert_eq!(val, serde_json::json!("initial"));
        rt.execute_script(
            "test",
            "document.getElementById('name').value = 'new value';",
        )
        .unwrap();
        let val2 = rt
            .evaluate("document.getElementById('name').value")
            .unwrap();
        assert_eq!(val2, serde_json::json!("new value"));
        let bio = rt.evaluate("document.getElementById('bio').value").unwrap();
        assert_eq!(bio, serde_json::json!("old text"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_sequential_runtime_swap() {
        let mut rt1 = setup_runtime("<html><body><h1>Page1</h1></body></html>");
        let title1 = rt1
            .evaluate("document.querySelector('h1').textContent")
            .unwrap();
        assert_eq!(title1, serde_json::json!("Page1"));

        let dom1 = rt1.take_dom();
        drop(rt1);

        let mut rt2 = setup_runtime("<html><body><h1>Page2</h1></body></html>");
        let title2 = rt2
            .evaluate("document.querySelector('h1').textContent")
            .unwrap();
        assert_eq!(title2, serde_json::json!("Page2"));
        drop(rt2);

        if let Some(dom) = dom1 {
            let mut rt1b = ObscuraJsRuntime::new();
            rt1b.set_dom(dom);
            rt1b.set_url("http://example.com");
            rt1b.set_title("Page1");
            rt1b.run_page_init();
            let title1b = rt1b
                .evaluate("document.querySelector('h1').textContent")
                .unwrap();
            assert_eq!(title1b, serde_json::json!("Page1"));
        }
    }

    #[test]
    fn test_checkbox_checked() {
        let mut rt = setup_runtime(r#"<input id="cb" type="checkbox" checked>"#);
        let checked = rt
            .evaluate("document.getElementById('cb').checked")
            .unwrap();
        assert_eq!(checked, serde_json::json!(true));
        rt.execute_script("test", "document.getElementById('cb').checked = false;")
            .unwrap();
        let checked2 = rt
            .evaluate("document.getElementById('cb').checked")
            .unwrap();
        assert_eq!(checked2, serde_json::json!(false));
    }

    // Issue #324: React/Preact/Vue install a value tracker by redefining `value`
    // on the element instance so they can tell a real edit from their own
    // controlled write. __obscura_setFieldValue must write through the prototype
    // setter, leaving that per-instance tracker stale, so the following input
    // event reads as a genuine change and onChange fires. A plain assignment
    // keeps the tracker in sync and suppresses onChange.
    #[test]
    fn set_field_value_bypasses_instance_value_wrapper() {
        let mut rt = setup_runtime(r#"<input id="i">"#);
        let result = rt
            .evaluate(
                r#"
                (function(){
                    var el = document.getElementById('i');
                    var d = Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value');
                    var set = d.set, get = d.get, tracked = '' + el.value;
                    Object.defineProperty(el, 'value', {
                        configurable: true,
                        get: function(){ return get.call(this); },
                        set: function(v){ tracked = '' + v; set.call(this, v); },
                    });
                    el.value = 'wrapped';
                    var afterDirect = { value: el.value, tracked: tracked };
                    globalThis.__obscura_setFieldValue(el, 'value', 'native');
                    var afterHelper = { value: el.value, tracked: tracked };
                    return JSON.stringify({ afterDirect: afterDirect, afterHelper: afterHelper });
                })()
                "#,
            )
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        // Direct assignment keeps tracker == value (the change that suppresses onChange).
        assert_eq!(parsed["afterDirect"]["value"], "wrapped");
        assert_eq!(parsed["afterDirect"]["tracked"], "wrapped");
        // The helper updates the value but leaves the tracker stale, so onChange fires.
        assert_eq!(parsed["afterHelper"]["value"], "native");
        assert_eq!(parsed["afterHelper"]["tracked"], "wrapped");
    }

    // Issue #324: React feature-detects the modern input-event path with
    // `('oninput' in document)`. If the GlobalEventHandlers on* attributes are
    // only on window (not Document/Element), that check fails and React falls
    // back to a legacy change-detection path, so controlled-input onChange never
    // fires. These must be present on document and Element.prototype too.
    #[test]
    fn global_event_handlers_present_on_document_and_element() {
        let mut rt = setup_runtime("<div></div>");
        let result = rt
            .evaluate(
                r#"JSON.stringify({
                    docInput: ('oninput' in document),
                    docChange: ('onchange' in document),
                    docClick: ('onclick' in document),
                    elProtoInput: ('oninput' in Element.prototype),
                    winInput: ('oninput' in window)
                })"#,
            )
            .unwrap();
        let p: serde_json::Value = serde_json::from_str(result.as_str().unwrap()).unwrap();
        assert_eq!(p["docInput"], true);
        assert_eq!(p["docChange"], true);
        assert_eq!(p["docClick"], true);
        assert_eq!(p["elProtoInput"], true);
        assert_eq!(p["winInput"], true);
    }

    #[test]
    fn test_matches_and_closest() {
        let mut rt = setup_runtime(
            r#"<div class="outer"><div class="inner"><span id="target">Hi</span></div></div>"#,
        );
        let matches = rt
            .evaluate("document.getElementById('target').matches('span')")
            .unwrap();
        assert_eq!(matches, serde_json::json!(true));
        let closest = rt
            .evaluate("document.getElementById('target').closest('.outer').className")
            .unwrap();
        assert_eq!(closest, serde_json::json!("outer"));
        let no_match = rt
            .evaluate("document.getElementById('target').closest('.nonexistent')")
            .unwrap();
        assert_eq!(no_match, serde_json::Value::Null);
    }

    #[test]
    fn shallow_element_clone_preserves_interface_attributes_and_isolation() {
        let mut rt = setup_runtime(
            r#"<section id="src" class="source" data-token="original"><span>child</span></section>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const source = document.getElementById('src');
                const clone = source.cloneNode(false);
                clone.className = 'clone';
                source.setAttribute('data-token', 'changed');
                return [
                    clone instanceof Node,
                    clone instanceof Element,
                    clone instanceof HTMLElement,
                    typeof clone.outerHTML,
                    typeof clone.querySelectorAll,
                    clone.tagName,
                    clone.id,
                    clone.className,
                    clone.getAttribute('data-token'),
                    clone.childNodes.length,
                    clone.ownerDocument === document,
                    clone.parentNode === null,
                    clone !== source,
                    source.className,
                    source.getAttribute('data-token'),
                    source.childNodes.length,
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true, true, true, "string", "function", "SECTION", "src", "clone", "original", 0,
                true, true, true, "source", "changed", 1
            ])
        );
    }

    #[test]
    fn document_clones_preserve_metadata_and_native_control_state() {
        let mut rt = setup_runtime("<!doctype html><!--before--><html lang=en><head><base href='http://example.com/articles/'><title>Article</title></head><body><input id=field value=initial><template id=t><p>Template</p></template><p id=copy>Original</p></body></html><!--after-->");
        assert_eq!(rt.evaluate(r#"(() => {
            document.getElementById('field').value='edited';
            const shallow=document.cloneNode(false), clone=document.cloneNode(true);
            if (!shallow || !clone) return 'missing document clone';
            clone.getElementById('copy').textContent='Changed';
            return [clone instanceof Document, clone.nodeType, clone.ownerDocument, clone.defaultView,
                clone.URL, clone.documentURI, clone.baseURI, clone.contentType, clone.compatMode,
                clone.characterSet, shallow.childNodes.length, shallow.URL, shallow.compatMode,
                Array.from(clone.childNodes,n=>n.nodeType), clone.doctype.name,
                clone.documentElement.ownerDocument===clone, clone.body.ownerDocument===clone,
                clone.getElementById('field').value, clone.getElementById('field').getAttribute('value'),
                clone.getElementById('t').content.textContent, document.getElementById('copy').textContent];
        })()"#).unwrap(), serde_json::json!([true,9,null,null,"http://example.com/test","http://example.com/test","http://example.com/articles/","text/html","CSS1Compat","UTF-8",0,"http://example.com/test","CSS1Compat",[10,8,1,8],"html",true,true,"edited","initial","Template","Original"]));
    }

    #[test]
    fn document_clones_preserve_xml_interfaces_namespaces_and_quirks_mode() {
        let mut rt = setup_runtime("<p>Quirks</p>");
        assert_eq!(rt.evaluate(r#"(() => {
            const source=document.implementation.createDocument('urn:article','p:article',null);
            source.documentElement.setAttributeNS('urn:meta','m:kind','article');
            const clone=source.cloneNode(true), quirks=document.cloneNode(false);
            if (!clone || !quirks) return 'missing document clone';
            return [clone instanceof XMLDocument, clone.contentType, clone.documentElement.nodeName,
                clone.documentElement.namespaceURI, clone.documentElement.getAttributeNS('urn:meta','kind'),
                clone.documentElement.ownerDocument===clone, clone.defaultView, quirks.compatMode];
        })()"#).unwrap(), serde_json::json!([true,"application/xml","p:article","urn:article","article",true,null,"BackCompat"]));
    }

    #[test]
    fn attribute_clones_are_independent_nodes_with_the_original_namespace_and_owner() {
        let mut rt = setup_runtime("<div id=source data-value=old></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const source=document.getElementById('source');
            source.setAttributeNS('urn:meta','m:kind','article');
            const attr=source.attributes.getNamedItem('m:kind');
            if (typeof attr.cloneNode!=='function') return 'missing attribute clone';
            const clone=attr.cloneNode(true);
            clone.value='copy';
            const foreign=document.implementation.createHTMLDocument('Foreign');
            const detached=foreign.createAttributeNS('urn:meta','m:kind');
            detached.value='detached';
            const detachedClone=detached.cloneNode(false);
            return [attr instanceof Attr, attr instanceof Node, Object.prototype.toString.call(attr),
                clone.nodeType, clone.name, clone.localName, clone.namespaceURI, clone.prefix,
                clone.ownerElement, clone.ownerDocument===document, clone.parentNode,
                clone.childNodes.length, clone.getRootNode()===clone, clone.isConnected,
                clone.value, clone.nodeValue, clone.textContent, source.getAttributeNS('urn:meta','kind'),
                clone!==attr, !clone.isSameNode(attr), !clone.isEqualNode(attr),
                detachedClone.ownerDocument===foreign, detachedClone.value, detachedClone.namespaceURI];
        })()"#).unwrap(), serde_json::json!([true,true,"[object Attr]",2,"m:kind","kind","urn:meta","m",null,true,null,0,true,false,"copy","copy","copy","article",true,true,true,true,"detached","urn:meta"]));
    }

    #[test]
    fn parsed_document_clones_keep_the_url_and_do_not_reparse_or_run_scripts() {
        let mut rt = setup_runtime("<!doctype html><title>Live</title><p>Live body</p>");
        assert_eq!(rt.evaluate(r#"(() => {
            const parsed=new DOMParser().parseFromString('<title>Inert</title><script>window.executed=true</script><input id=field value=initial>','text/html');
            parsed.getElementById('field').value='edited';
            const clone=parsed.cloneNode(true), shallow=parsed.cloneNode(false);
            return [parsed.URL, clone.URL, clone instanceof Document, clone.defaultView,
                clone.getElementById('field').value, clone.getElementById('field').getAttribute('value'),
                clone.getElementById('field').ownerDocument===clone, shallow.childNodes.length,
                document.title, typeof window.executed];
        })()"#).unwrap(), serde_json::json!(["http://example.com/test","http://example.com/test",true,null,"edited","initial",true,0,"Live","undefined"]));
    }

    #[test]
    fn attribute_node_positions_do_not_alias_missing_arena_ids() {
        let mut rt = setup_runtime("<div id=x a=1 b=2></div>");
        assert_eq!(rt.evaluate(r#"(() => {
            const el=document.getElementById('x'), a=el.attributes[1], b=el.attributes[2];
            const clone=a.cloneNode(), forward=clone.compareDocumentPosition(a), reverse=a.compareDocumentPosition(clone);
            return [a.compareDocumentPosition(el),el.compareDocumentPosition(a),
                a.compareDocumentPosition(b),b.compareDocumentPosition(a),
                (forward & 33)===33,(reverse & 33)===33,
                (forward & 6)===(reverse & 4 ? 2 : 4),clone.compareDocumentPosition(clone)];
        })()"#).unwrap(), serde_json::json!([10,20,36,34,true,true,true,0]));
    }

    #[test]
    fn inert_html_parsing_preserves_document_root_attributes_and_structure() {
        let mut rt = setup_runtime("<title>Live page</title><p>Live content</p>");
        assert_eq!(rt.evaluate(r#"(() => {
            const parsed=new DOMParser().parseFromString('<!doctype html><!--before--><html lang=fr dir=rtl data-root=article><head><title>Parsed</title></head><body><template id=t><p>Template</p></template><script>window.executed=true</script><noscript><img src=fallback.jpg></noscript><p id=content>Article</p></body></html><!--after-->','text/html');
            return [parsed instanceof Document, parsed.URL, parsed.documentElement.lang,
                parsed.documentElement.dir, parsed.documentElement.getAttribute('data-root'),
                Array.from(parsed.childNodes,n=>n.nodeType), parsed.doctype?.name,
                parsed.body.ownerDocument===parsed, parsed.getElementById('t').content.textContent,
                parsed.title, parsed.compatMode, parsed.defaultView, document.title, typeof window.executed,
                parsed.querySelector('noscript img')?.getAttribute('src')];
        })()"#).unwrap(), serde_json::json!([true,"http://example.com/test","fr","rtl","article",[10,8,1,8],"html",true,"Template","Parsed","CSS1Compat",null,"Live page","undefined","fallback.jpg"]));
    }

    #[test]
    fn deep_document_element_clone_stays_an_independent_html_element() {
        let mut rt = setup_runtime(
            r#"<html lang="en" data-root="original"><head><title>Clone</title></head><body><main id="app" data-state="source"><p class="item">original text</p></main></body></html>"#,
        );
        let result = rt
            .evaluate(
                r#"
                const source = document.documentElement;
                const clone = source.cloneNode(true);
                const cloneItem = clone.querySelector('.item');
                const sourceItem = source.querySelector('.item');
                cloneItem.textContent = 'clone text';
                source.querySelector('#app').setAttribute('data-state', 'changed');
                clone.setAttribute('lang', 'fr');
                return [
                    clone instanceof Element,
                    clone instanceof HTMLElement,
                    clone.tagName,
                    typeof clone.outerHTML,
                    typeof clone.querySelectorAll,
                    clone.querySelectorAll('head, body, main, p').length,
                    clone.ownerDocument === document,
                    clone.parentNode === null,
                    clone !== source,
                    clone.querySelector('body') !== document.body,
                    clone.getAttribute('data-root'),
                    clone.getAttribute('lang'),
                    source.getAttribute('lang'),
                    cloneItem.textContent,
                    sourceItem.textContent,
                    clone.querySelector('#app').getAttribute('data-state'),
                    source.querySelector('#app').getAttribute('data-state'),
                ];
                "#,
            )
            .unwrap();
        assert_eq!(
            result,
            serde_json::json!([
                true,
                true,
                "HTML",
                "string",
                "function",
                4,
                true,
                true,
                true,
                true,
                "original",
                "fr",
                "en",
                "clone text",
                "original text",
                "source",
                "changed"
            ])
        );
    }

    #[test]
    fn test_evaluate_multistatement() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate("var x = 5; var y = 10; return x + y;").unwrap();
        assert_eq!(result.as_f64().unwrap() as i64, 15);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_object_ref_as_argument() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let obj = rt
            .call_function_on("() => ({ x: 42 })", None, &[], false)
            .await
            .unwrap();
        let oid = obj.object_id.unwrap();

        let args = vec![serde_json::json!({"objectId": oid})];
        let result = rt
            .call_function_on("(obj) => obj.x * 2", None, &args, true)
            .await
            .unwrap();
        assert_eq!(result.value.unwrap().as_f64().unwrap() as i64, 84);
    }

    fn setup_runtime_with_cookies(
        html: &str,
    ) -> (ObscuraJsRuntime, std::sync::Arc<obscura_net::CookieJar>) {
        let dom = obscura_dom::parse_html(html);
        let jar = std::sync::Arc::new(obscura_net::CookieJar::new());
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.com/test");
        rt.set_title("Test Page");
        rt.set_cookie_jar(jar.clone());
        rt.run_page_init();
        (rt, jar)
    }

    #[test]
    fn test_document_cookie_reads_http_cookies() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        let url = url::Url::parse("http://example.com/test").unwrap();
        jar.set_cookie("session=abc123; Path=/", &url);
        jar.set_cookie("theme=dark; Path=/", &url);
        let result = rt.evaluate("document.cookie").unwrap();
        let cookie_str = result.as_str().unwrap();
        assert!(
            cookie_str.contains("session=abc123"),
            "expected session cookie, got: {}",
            cookie_str
        );
        assert!(
            cookie_str.contains("theme=dark"),
            "expected theme cookie, got: {}",
            cookie_str
        );
    }

    #[test]
    fn test_document_cookie_excludes_httponly() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        let url = url::Url::parse("http://example.com/test").unwrap();
        jar.set_cookie("visible=yes; Path=/", &url);
        jar.set_cookie("secret=token; Path=/; HttpOnly", &url);
        let result = rt.evaluate("document.cookie").unwrap();
        let cookie_str = result.as_str().unwrap();
        assert!(
            cookie_str.contains("visible=yes"),
            "expected visible cookie, got: {}",
            cookie_str
        );
        assert!(
            !cookie_str.contains("secret"),
            "httpOnly cookie should not be visible to JS, got: {}",
            cookie_str
        );
    }

    #[test]
    fn test_document_cookie_setter_stores_in_jar() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        rt.evaluate("document.cookie = 'foo=bar; Path=/'").unwrap();
        let url = url::Url::parse("http://example.com/test").unwrap();
        let result = rt.evaluate("document.cookie").unwrap();
        assert!(result.as_str().unwrap().contains("foo=bar"));
        let header = jar.get_cookie_header_same_site(&url);
        assert!(
            header.contains("foo=bar"),
            "cookie should be in jar, got: {}",
            header
        );
    }

    #[test]
    fn global_document_cannot_be_replaced_by_page_script() {
        let mut rt = setup_runtime(r#"<html><body id="live"></body></html>"#);

        let descriptor = rt
            .evaluate(
                "(() => { \
                   const d = Object.getOwnPropertyDescriptor(globalThis, 'document'); \
                   return [typeof d.get, d.set === undefined, d.configurable, d.enumerable]; \
                 })()",
            )
            .unwrap();
        assert_eq!(
            descriptor,
            serde_json::json!(["function", true, false, true])
        );

        rt.evaluate("document = { probe: true };").unwrap();
        let after_assignment = rt
            .evaluate(
                "[ \
                   document === globalThis.document, \
                   document instanceof Document, \
                   document.body.tagName, \
                   typeof document.cookie \
                 ]",
            )
            .unwrap();
        assert_eq!(
            after_assignment,
            serde_json::json!([true, true, "BODY", "string"])
        );

        let strict_error = rt
            .execute_script(
                "strict-document-assignment",
                "'use strict'; document = {};",
            )
            .unwrap_err();
        assert!(strict_error.contains("TypeError"), "{strict_error}");
    }

    // #940: op_navigate must not move the document's cookie context before the
    // navigation actually commits. A queued navigation to another origin must
    // not let document.cookie read that origin's cookies (SOP bypass).
    #[test]
    fn queued_navigation_does_not_expose_another_origins_cookies() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        // A cookie belonging to a different origin than the current page
        // (the harness page is http://example.com/test).
        let victim = url::Url::parse("https://victim.example/").unwrap();
        jar.set_cookie("secret=victimtoken; Path=/", &victim);

        // Start navigating to the victim origin. This only *queues* the
        // navigation; it must not retroactively move the cookie context.
        rt.evaluate("location.href = 'https://victim.example/'")
            .unwrap();

        let result = rt.evaluate("document.cookie").unwrap();
        let cookie_str = result.as_str().unwrap();
        assert!(
            !cookie_str.contains("victimtoken"),
            "document.cookie must not expose another origin's cookies after a queued navigation, got: {}",
            cookie_str
        );
    }

    #[test]
    fn test_document_cookie_delete_via_max_age() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        let url = url::Url::parse("http://example.com/test").unwrap();
        rt.evaluate("document.cookie = 'temp=val; Path=/'").unwrap();
        assert!(
            rt.evaluate("document.cookie")
            .unwrap()
            .as_str()
            .unwrap()
                .contains("temp=val")
        );
        rt.evaluate("document.cookie = 'temp=; Max-Age=0'").unwrap();
        let result = rt.evaluate("document.cookie").unwrap();
        assert!(
            !result.as_str().unwrap().contains("temp="),
            "cookie should be deleted, got: {}",
            result
        );
        assert!(!jar.get_cookie_header_same_site(&url).contains("temp="));
    }

    #[test]
    fn test_document_cookie_js_and_http_merge() {
        let (mut rt, jar) = setup_runtime_with_cookies("<html><body></body></html>");
        let url = url::Url::parse("http://example.com/test").unwrap();
        jar.set_cookie("server_sid=xyz; Path=/", &url);
        rt.evaluate("document.cookie = 'client_pref=light'")
            .unwrap();
        let result = rt.evaluate("document.cookie").unwrap();
        let cookie_str = result.as_str().unwrap();
        assert!(
            cookie_str.contains("server_sid=xyz"),
            "expected server cookie, got: {}",
            cookie_str
        );
        assert!(
            cookie_str.contains("client_pref=light"),
            "expected client cookie, got: {}",
            cookie_str
        );
    }

    #[test]
    fn test_document_cookie_empty_when_no_cookies() {
        let (mut rt, _jar) = setup_runtime_with_cookies("<html><body></body></html>");
        let result = rt.evaluate("document.cookie").unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_document_cookie_no_jar_returns_empty() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate("document.cookie").unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_document_write_appends_to_body() {
        let mut rt = setup_runtime("<html><body><p>Existing</p></body></html>");
        rt.evaluate("document.write('<div>Added</div>')").unwrap();
        let html = rt.evaluate("document.body.innerHTML").unwrap();
        let body = html.as_str().unwrap();
        assert!(
            body.contains("Existing"),
            "existing content should remain, got: {}",
            body
        );
        assert!(
            body.contains("Added"),
            "written content should appear, got: {}",
            body
        );
    }

    #[test]
    fn test_document_writeln() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("document.writeln('Hello')").unwrap();
        let html = rt.evaluate("document.body.innerHTML").unwrap();
        assert!(html.as_str().unwrap().contains("Hello"));
    }

    #[test]
    fn test_document_write_multiple_args() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate("document.write('Hello', ' ', 'World')")
            .unwrap();
        let text = rt.evaluate("document.body.textContent").unwrap();
        assert_eq!(text.as_str().unwrap().trim(), "Hello World");
    }

    #[test]
    fn document_open_removes_old_document_tree_before_writing() {
        let mut rt = setup_runtime("<!doctype html><html><body><p>Old content</p></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const oldRoot = document.documentElement, oldType = document.doctype;
            const opened = document.open();
            return [opened === document, document.documentElement, document.head,
                document.body, document.doctype, document.childNodes.length,
                oldRoot.isConnected, oldType.isConnected];
        })()"#).unwrap(), serde_json::json!([true, null, null, null, null, 0, false, false]));
    }

    #[test]
    fn document_open_close_emits_the_empty_document_at_eof() {
        let mut rt = setup_runtime("<html><body>old</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            document.open();
            const emptyBeforeClose = document.childNodes.length === 0;
            document.close();
            return [emptyBeforeClose, document.documentElement.nodeName,
                document.head.nodeName, document.body.nodeName, document.body.childNodes.length];
        })()"#).unwrap(), serde_json::json!([true, "HTML", "HEAD", "BODY", 0]));
    }

    #[test]
    fn document_open_close_retains_unclosed_script_without_running_it() {
        let mut rt = setup_runtime("<html><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            globalThis.unclosedWriteRan = false;
            document.open();
            document.write('<script id="unclosed">globalThis.unclosedWriteRan = true;');
            document.close();
            return [document.getElementById('unclosed').parentNode.nodeName,
                document.getElementById('unclosed').textContent, globalThis.unclosedWriteRan];
        })()"#).unwrap(), serde_json::json!([
            "HEAD", "globalThis.unclosedWriteRan = true;", false
        ]));
    }

    #[test]
    fn document_open_write_borrowed_methods_use_the_receiver_parser() {
        let mut rt = setup_runtime("<html><body id='parent'>parent</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const childDocument = iframe.contentDocument;
            Document.prototype.open.call(childDocument);
            Document.prototype.write.call(childDocument, '<title>child</title><p id="written">value</p>');
            Document.prototype.close.call(childDocument);
            return [document.body.id, document.getElementById('written'),
                childDocument.title, childDocument.getElementById('written').textContent,
                childDocument.querySelector('title').parentNode.nodeName];
        })()"#).unwrap(), serde_json::json!(["parent", null, "child", "value", "HEAD"]));
    }

    #[test]
    fn document_open_write_uses_document_insertion_modes_across_calls() {
        let mut rt = setup_runtime("<html><head><meta id='old'></head><body>old</body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            document.open();
            document.write('<sty');
            document.write('le id="written-style">body{margin:0}');
            document.write('</style>\n      <input id="widget">');
            document.close();
            const widget = document.getElementById('widget');
            const range = document.createRange(); range.selectNode(widget);
            return [document.getElementById('written-style').parentNode.nodeName,
                Array.from(document.head.children, n => n.nodeName),
                Array.from(document.body.childNodes, n => n.nodeName),
                range.startContainer.nodeName, range.startOffset,
                document.getElementById('old') === null];
        })()"#).unwrap(), serde_json::json!(["HEAD", ["STYLE"], ["INPUT"], "BODY", 0, true]));
    }

    #[test]
    fn document_open_write_preserves_explicit_document_structure() {
        let mut rt = setup_runtime("<html><head></head><body></body></html>");
        assert_eq!(rt.evaluate(r#"(() => {
            document.open();
            document.write('<!doctype html><html lang="fr"><head><title>Written</title></head>');
            document.write('<body id="written-body"><table><tr><td id="cell">value</td></tr></table></body></html>');
            document.close();
            return [document.querySelectorAll('html').length, document.querySelectorAll('head').length,
                document.querySelectorAll('body').length, document.documentElement.lang,
                document.body.id, document.querySelector('title').parentNode.nodeName,
                document.getElementById('cell').parentNode.parentNode.nodeName,
                Array.from(document.childNodes, n => n.nodeType)];
        })()"#).unwrap(), serde_json::json!([1, 1, 1, "fr", "written-body", "HEAD", "TBODY", [10, 1]]));
    }

    #[test]
    fn document_compat_mode_reads_the_parsed_document_mode() {
        for (html, expected) in [
            ("<p>quirks</p>", "BackCompat"),
            ("<!doctype html><p>standards</p>", "CSS1Compat"),
            ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><p>limited</p>", "CSS1Compat"),
        ] {
            let mut rt = setup_runtime(html);
            assert_eq!(rt.evaluate("document.compatMode").unwrap(), serde_json::json!(expected), "{html}");
        }
    }

    #[test]
    fn document_open_write_updates_quirks_mode_without_fragment_leaks() {
        let mut rt = setup_runtime("<!doctype html><p>old</p>");
        assert_eq!(rt.evaluate(r#"(() => {
            const modes = [document.compatMode];
            document.open(); modes.push(document.compatMode);
            document.write('<p>new</p>'); modes.push(document.compatMode);
            document.close(); modes.push(document.compatMode);
            document.open(); modes.push(document.compatMode);
            document.write('<!doctype html><p>standards</p>'); modes.push(document.compatMode);
            document.close();
            document.body.innerHTML = '<p>fragment</p>';
            document.write('<span>fragment write</span>'); modes.push(document.compatMode);
            return modes;
        })()"#).unwrap(), serde_json::json!([
            "CSS1Compat", "CSS1Compat", "BackCompat", "BackCompat",
            "CSS1Compat", "CSS1Compat", "CSS1Compat"
        ]));
    }

    #[test]
    fn document_open_close_sets_quirks_mode_at_eof() {
        let mut rt = setup_runtime("<!doctype html><p>old</p>");
        assert_eq!(rt.evaluate(r#"(() => {
            document.open();
            const before = document.compatMode;
            document.close();
            return [before, document.compatMode];
        })()"#).unwrap(), serde_json::json!(["CSS1Compat", "BackCompat"]));
    }

    #[test]
    fn document_compat_mode_borrowed_getter_uses_the_receiver_realm() {
        let mut rt = setup_runtime("<!doctype html><body></body>");
        assert_eq!(rt.evaluate(r#"(() => {
            const iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            const child = iframe.contentDocument;
            Document.prototype.open.call(child);
            Document.prototype.write.call(child, '<p>quirks</p>');
            Document.prototype.close.call(child);
            const getMode = Object.getOwnPropertyDescriptor(Document.prototype, 'compatMode').get;
            return [getMode.call(child), document.compatMode];
        })()"#).unwrap(), serde_json::json!(["BackCompat", "CSS1Compat"]));
    }

    #[test]
    fn test_document_write_html_elements() {
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.evaluate(r#"document.write('<h1 id="title">Test</h1><p>Para</p>')"#)
            .unwrap();
        let h1 = rt
            .evaluate("document.querySelector('h1').textContent")
            .unwrap();
        assert_eq!(h1.as_str().unwrap(), "Test");
        let p = rt
            .evaluate("document.querySelector('p').textContent")
            .unwrap();
        assert_eq!(p.as_str().unwrap(), "Para");
    }

    #[test]
    fn test_url_relative_resolution() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .evaluate("new URL('data.json', 'http://example.com/path/page.html').href")
            .unwrap();
        assert_eq!(
            result.as_str().unwrap(),
            "http://example.com/path/data.json"
        );

        let result = rt
            .evaluate("new URL('/api/data', 'http://example.com/path/page.html').href")
            .unwrap();
        assert_eq!(result.as_str().unwrap(), "http://example.com/api/data");

        let result = rt
            .evaluate("new URL('https://other.com/foo', 'http://example.com/bar').href")
            .unwrap();
        assert_eq!(result.as_str().unwrap(), "https://other.com/foo");

        let result = rt
            .evaluate("new URL('sub/file.js', 'http://example.com/a/b/c.html').href")
            .unwrap();
        assert_eq!(
            result.as_str().unwrap(),
            "http://example.com/a/b/sub/file.js"
        );

        let result = rt
            .evaluate("new URL('api.json', 'http://localhost:8080/dir/index.html').href")
            .unwrap();
        assert_eq!(
            result.as_str().unwrap(),
            "http://localhost:8080/dir/api.json"
        );
    }

    /// Document URL two levels deep, base one level deep and the origin root on neither of the
    /// two. The three possible bases land on three different paths, and one assert keeps them
    /// apart:
    ///   document base URL  ->  /app/data/x.json   (the spec)
    ///   document URL       ->  /deep/data/x.json  (the bug)
    ///   origin root        ->  /data/x.json       (a base "/" would hide this one)
    fn setup_runtime_at_deep_url(html: &str) -> ObscuraJsRuntime {
        let dom = parse_html(html);
        let mut rt = ObscuraJsRuntime::new();
        rt.set_dom(dom);
        rt.set_url("http://example.com/deep/page");
        rt.run_page_init();
        rt
    }

    const BASE_HREF_PAGE: &str = r#"<html><head><base href="/app/"></head><body>
            <a id="link" href="data/x.json"></a>
            <form id="form" action="submit"></form>
            <script id="script" src="chunk.js"></script>
        </body></html>"#;

    #[test]
    fn base_href_governs_dom_url_reflection() {
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);

        // One evaluate, one assert: a bundle of assert_eq! aborts at the first failure and
        // reports one broken path while hiding the others.
        let seen = rt
            .evaluate(
                r#"return [
                    document.baseURI,
                    document.getElementById('link').href,
                    document.getElementById('form').action,
                    document.getElementById('script').src,
                ]"#,
            )
            .unwrap();
        assert_eq!(
            seen.as_array().unwrap(),
            &vec![
                serde_json::json!("http://example.com/app/"),
                serde_json::json!("http://example.com/app/data/x.json"),
                serde_json::json!("http://example.com/app/submit"),
                serde_json::json!("http://example.com/app/chunk.js"),
            ]
        );
    }

    #[test]
    fn a_relative_location_assignment_follows_the_base() {
        // _resolveUrl serves location.href=, assign, replace and window.location=. Of the six
        // call sites it has the largest external effect, so it gets its own test.
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        rt.evaluate("location.href = 'users/42'").unwrap();

        let landed = rt.evaluate("location.href").unwrap();
        assert_eq!(landed.as_str().unwrap(), "http://example.com/app/users/42");
    }

    #[test]
    fn without_base_href_resolution_stays_on_the_document_url() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head></head><body>
                <a id="link" href="data/x.json"></a>
                <form id="form" action="submit"></form>
                <script id="script" src="chunk.js"></script>
            </body></html>"#,
        );

        // Every call site, not just the anchor: a site that resolves to the origin root instead
        // of the document URL slips through on a page without a base only when nobody is looking.
        let seen = rt
            .evaluate(
                r#"return [
                    document.baseURI,
                    document.getElementById('link').href,
                    document.getElementById('form').action,
                    document.getElementById('script').src,
                ]"#,
            )
            .unwrap();
        assert_eq!(
            seen.as_array().unwrap(),
            &vec![
                serde_json::json!("http://example.com/deep/page"),
                serde_json::json!("http://example.com/deep/data/x.json"),
                serde_json::json!("http://example.com/deep/submit"),
                serde_json::json!("http://example.com/deep/chunk.js"),
            ]
        );
    }

    #[test]
    fn base_element_href_reflects_the_resolved_url() {
        // Resolved against the fallback base URL, i.e. the document URL and not /app/.
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        let href = rt.evaluate("document.querySelector('base').href").unwrap();
        assert_eq!(href.as_str().unwrap(), "http://example.com/app/");

        let mut relative = setup_runtime_at_deep_url(
            r#"<html><head><base href="assets/"></head><body></body></html>"#,
        );
        let href = relative
            .evaluate("document.querySelector('base').href")
            .unwrap();
        assert_eq!(href.as_str().unwrap(), "http://example.com/deep/assets/");
    }

    #[test]
    fn the_first_base_with_an_href_wins() {
        // Tree order, and a <base> without href does not count.
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base><base href="/a/"><base href="/b/"></head><body>
                <a id="link" href="x.json"></a>
            </body></html>"#,
        );
        let link = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(link.as_str().unwrap(), "http://example.com/a/x.json");
    }

    #[test]
    fn an_empty_base_href_resolves_to_the_document_url() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base href=""></head><body>
                <a id="link" href="x.json"></a>
            </body></html>"#,
        );
        let link = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(link.as_str().unwrap(), "http://example.com/deep/x.json");
    }

    #[test]
    fn a_cross_origin_base_moves_the_target_but_not_the_page_origin() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base href="https://cdn.example.net/v2/"></head><body>
                <a id="link" href="x.json"></a>
            </body></html>"#,
        );
        let seen = rt
            .evaluate("return [document.getElementById('link').href, location.origin]")
            .unwrap();
        assert_eq!(
            seen.as_array().unwrap(),
            &vec![
                serde_json::json!("https://cdn.example.net/v2/x.json"),
                serde_json::json!("http://example.com"),
            ]
        );
    }

    #[test]
    fn base_href_rejects_a_data_url_base() {
        // https://html.spec.whatwg.org/multipage/semantics.html#set-the-frozen-base-url
        // Accepting it would make every later relative resolution fail instead of falling back.
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base href="data:text/html,x"></head><body>
                <a id="link" href="data/x.json"></a>
            </body></html>"#,
        );

        let base_uri = rt.evaluate("document.baseURI").unwrap();
        assert_eq!(base_uri.as_str().unwrap(), "http://example.com/deep/page");

        let link = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(
            link.as_str().unwrap(),
            "http://example.com/deep/data/x.json"
        );
    }

    #[test]
    fn base_resolution_follows_the_url_set_by_push_state() {
        // pushState changes the document URL, and without <base> that very URL is the base.
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head></head><body><a id="link" href="x.json"></a></body></html>"#,
        );
        rt.evaluate("history.pushState({}, '', '/other/route')")
            .unwrap();

        let link = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(link.as_str().unwrap(), "http://example.com/other/x.json");
    }

    #[test]
    fn a_relative_base_href_resolves_against_the_push_state_url() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base href="assets/"></head><body>
                <a id="link" href="x.json"></a>
            </body></html>"#,
        );
        rt.evaluate("history.pushState({}, '', '/other/route')")
            .unwrap();

        let link = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(
            link.as_str().unwrap(),
            "http://example.com/other/assets/x.json"
        );
    }

    /// Base resolution is shared by URL reflection and retained geometry reads.
    /// Neither may walk the document again for every read in a snapshot.
    /// The bound is deliberately loose: it should catch the regression, not watch the allocator.
    #[test]
    fn base_dependent_reads_do_not_scale_with_document_size() {
        let mut body = String::from(r#"<html><head></head><body><a id="link" href="x.json"></a>"#);
        for i in 0..4000 {
            body.push_str(&format!("<div id=\"n{i}\"><span>text</span></div>"));
        }
        body.push_str("</body></html>");
        let mut rt = setup_runtime_at_deep_url(&body);
        // Build layout before timing reads, so the bound measures reuse rather
        // than font loading or the initial layout of the large document.
        rt.evaluate("document.getElementById('n0').getBoundingClientRect()").unwrap();

        let elapsed = rt
            .evaluate(
                r#"
                const link = document.getElementById('link');
                const box = document.getElementById('n0');
                const started = Date.now();
                for (let i = 0; i < 2000; i++) {
                    link.href; box.scrollTop; box.scrollLeft;
                    getComputedStyle(box, '::before').content;
                }
                return Date.now() - started;
                "#,
            )
            .unwrap();
        let ms = elapsed.as_f64().expect("elapsed ms");
        assert!(
            ms < 500.0,
            "2000 URL/scroll/style reads on a document with 12000 nodes took {ms} ms, the base query is not cached"
        );
    }

    #[cfg(feature = "render")]
    #[test]
    fn render_reads_track_base_mutations_and_document_replacement() {
        let mut rt = setup_runtime_at_deep_url("<html><head></head><body><div>box</div></body></html>");
        for (mutation, expected) in [
            ("", "http://example.com/deep/page"),
            ("document.head.innerHTML = '<base href=\"/assets/\">';", "http://example.com/assets/"),
            ("document.querySelector('base').setAttribute('href', 'relative/');", "http://example.com/deep/relative/"),
            ("document.querySelector('base').remove();", "http://example.com/deep/page"),
        ] {
            rt.evaluate(&format!("(() => {{ {mutation} return document.body.scrollTop; }})()")).unwrap();
            assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some(expected));
        }
        rt.set_url("http://example.com/other/page");
        rt.evaluate("document.body.scrollTop").unwrap();
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/other/page"));
        rt.set_dom(parse_html("<html><head><base href='/replacement/'></head><body></body></html>"));
        rt.run_page_init();
        rt.evaluate("document.body.scrollTop").unwrap();
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/replacement/"));
        // Embedders can mutate DomTree directly between JavaScript tasks,
        // without going through the JS mutation/activity counter.
        rt.with_dom(|dom| {
            let base = dom.query_selector("base").unwrap().unwrap();
            dom.with_node_mut(base, |node| node.set_attribute("href", "/native/".into()));
        });
        rt.evaluate("document.body.scrollTop").unwrap();
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/native/"));
        rt.with_dom(|dom| {
            let base = dom.query_selector("base").unwrap().unwrap();
            dom.with_node_mut(base, |node| node.set_attribute("href", "/native-style/".into()));
        });
        rt.evaluate("getComputedStyle(document.body, '::before').content").unwrap();
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/native-style/"));
        rt.evaluate(r#"(() => {
            getComputedStyle(document.body, '::before').content;
            document.querySelector('base').setAttribute('href', '/script-style/');
            return getComputedStyle(document.body, '::before').content;
        })()"#).unwrap();
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/script-style/"));
        // Native paint can run without starting another JS task. It must not
        // reuse the task's base after a host-side edit.
        rt.with_dom(|dom| {
            let base = dom.query_selector("base").unwrap().unwrap();
            dom.with_node_mut(base, |node| node.set_attribute("href", "/native-paint/".into()));
        });
        crate::ops::ensure_prepared_render(&mut rt.state.borrow_mut());
        assert_eq!(rt.state.borrow().prepared_render.as_ref().unwrap().base_url(), Some("http://example.com/native-paint/"));
    }

    #[test]
    fn the_base_memo_still_sees_a_base_element_added_later() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head></head><body><a id="link" href="x.json"></a></body></html>"#,
        );
        let before = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(before.as_str().unwrap(), "http://example.com/deep/x.json");

        rt.evaluate(
            r#"
            const base = document.createElement('base');
            base.setAttribute('href', '/');
            document.head.appendChild(base);
            "#,
        )
        .unwrap();

        let after = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(after.as_str().unwrap(), "http://example.com/x.json");
    }

    #[test]
    fn the_base_memo_notices_a_changed_href_attribute() {
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        let before = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(
            before.as_str().unwrap(),
            "http://example.com/app/data/x.json"
        );

        rt.evaluate("document.querySelector('base').setAttribute('href', '/other/')")
            .unwrap();

        let after = rt.evaluate("document.getElementById('link').href").unwrap();
        assert_eq!(
            after.as_str().unwrap(),
            "http://example.com/other/data/x.json"
        );
    }

    #[cfg(not(feature = "render"))]
    #[test]
    fn native_dom_reads_keep_base_cache_without_rendering() {
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str(), Some("http://example.com/app/"));
        assert!(rt.state.borrow().base_url_cache.borrow().is_some());
        rt.with_dom(|dom| dom.document());
        assert!(rt.state.borrow().base_url_cache.borrow().is_some());
        drop(rt.dom_ref());
        assert!(rt.state.borrow().base_url_cache.borrow().is_some());
        assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str(), Some("http://example.com/app/"));
    }

    #[cfg(feature = "render")]
    #[test]
    fn render_base_cache_tracks_dom_url_and_document_replacement() {
        let mut rt = setup_runtime_at_deep_url(
            r#"<html><head><base id="a" href="/a/"><base id="b" href="/b/"></head>
            <body><img id="image" src="picture.svg"><p>geometry</p></body></html>"#,
        );
        let check = |rt: &mut ObscuraJsRuntime, expected: &str| {
            let base = {
                let mut state = rt.state.borrow_mut();
                ensure_prepared_render(&mut state).unwrap().base_url().unwrap().to_string()
            };
            assert_eq!(base, expected);
            let image = rt.evaluate("document.getElementById('image').currentSrc").unwrap();
            assert_eq!(image.as_str().unwrap(), url::Url::parse(expected).unwrap().join("picture.svg").unwrap().as_str());
            assert_eq!(rt.evaluate("document.baseURI").unwrap().as_str().unwrap(), expected);
        };
        check(&mut rt, "http://example.com/a/");
        // Warm both geometry and image metadata, then change which base wins.
        check(&mut rt, "http://example.com/a/");
        for (script, expected) in [
            ("document.head.insertBefore(document.getElementById('b'),document.getElementById('a'))", "http://example.com/b/"),
            ("document.getElementById('b').removeAttribute('href')", "http://example.com/a/"),
            ("document.getElementById('a').setAttribute('href','assets/')", "http://example.com/deep/assets/"),
            ("document.getElementById('a').remove()", "http://example.com/deep/page"),
            ("document.getElementById('b').setAttribute('href','javascript:bad')", "http://example.com/deep/page"),
            ("document.getElementById('b').setAttribute('href','https://cdn.example.net/v2/')", "https://cdn.example.net/v2/"),
        ] {
            rt.evaluate(script).unwrap();
            check(&mut rt, expected);
        }
        // The embedder updates the native document URL separately from JS history.
        rt.evaluate("document.getElementById('b').setAttribute('href','assets/')").unwrap();
        rt.set_url("http://example.com/other/page");
        rt.run_page_init();
        check(&mut rt, "http://example.com/other/assets/");
        rt.set_dom(parse_html("<html><head><base href='/replacement/'></head><body></body></html>"));
        let mut state = rt.state.borrow_mut();
        assert_eq!(ensure_prepared_render(&mut state).unwrap().base_url(), Some("http://example.com/replacement/"));
    }

    #[cfg(feature = "render")]
    #[test]
    fn render_base_cache_sees_native_dom_access_and_removal() {
        let rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        let base = |rt: &ObscuraJsRuntime| {
            let mut state = rt.state.borrow_mut();
            ensure_prepared_render(&mut state).unwrap().base_url().unwrap().to_string()
        };
        assert_eq!(base(&rt), "http://example.com/app/");
        rt.with_dom(|dom| {
            let node = dom.query_selector("base").unwrap().unwrap();
            dom.with_node_mut(node, |node| node.set_attribute("href", "/native/".into()));
        });
        assert_eq!(base(&rt), "http://example.com/native/");
        {
            let dom = rt.dom_ref().unwrap();
            let dom = dom.as_ref().unwrap();
            let node = dom.query_selector("base").unwrap().unwrap();
            dom.remove(node);
        }
        assert_eq!(base(&rt), "http://example.com/deep/page");
        rt.set_dom(parse_html(BASE_HREF_PAGE));
        assert_eq!(base(&rt), "http://example.com/app/");
        rt.take_dom();
        assert_eq!(crate::ops::document_base_url(&rt.state.borrow()).as_deref(), Some("http://example.com/deep/page"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn base_href_governs_fetch_and_xhr_targets() {
        let mut rt = setup_runtime_at_deep_url(BASE_HREF_PAGE);
        let result = rt
            .call_function_on_for_cdp(
                r#"async () => {
                const originalFetchOp = __obscura_test_ops.op_fetch_url;
                const seen = [];
                try {
                    __obscura_test_ops.op_fetch_url = (url) => {
                        seen.push(url);
                        return JSON.stringify({ status: 200, headers: {}, body: "{}", url });
                    };
                    await fetch("data/x.json");
                    const xhr = new XMLHttpRequest();
                    xhr.open("GET", "data/y.json");
                    xhr.send();
                    await new Promise((r) => setTimeout(r, 0));
                    return seen;
                } finally {
                    __obscura_test_ops.op_fetch_url = originalFetchOp;
                }
            }"#,
                None,
                &[],
                true,
                true,
            )
            .await
            .unwrap();

        let value = result.value.expect("captured URLs");
        let seen = value.as_array().expect("captured URLs");
        // The XHR entry cannot isolate its own layer: send() passes the already absolute URL on
        // to fetch, so fetch takes over the resolution if it is removed from send, and the assert
        // still holds. It pins the result, not the layer.
        assert_eq!(seen.len(), 2, "one fetch, one XHR");
        assert_eq!(
            seen[0].as_str().unwrap(),
            "http://example.com/app/data/x.json"
        );
        assert_eq!(
            seen[1].as_str().unwrap(),
            "http://example.com/app/data/y.json"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_fetch_url_input_decodes_binary_body_base64() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .call_function_on_for_cdp(
                r#"async () => {
                const originalFetchOp = __obscura_test_ops.op_fetch_url;
                try {
                    __obscura_test_ops.op_fetch_url = (url) => {
                        globalThis.__capturedFetchUrl = url;
                        return JSON.stringify({
                            status: 200,
                            headers: { "content-type": "application/wasm" },
                            bodyBase64: "AGFzbQEAAAA=",
                            url,
                        });
                    };
                    const response = await fetch(new URL("/pkg/app_bg.wasm", document.URL));
                    const bytes = Array.from(new Uint8Array(await response.arrayBuffer()));
                    return { url: globalThis.__capturedFetchUrl, bytes };
                } finally {
                    __obscura_test_ops.op_fetch_url = originalFetchOp;
                }
            }"#,
                None,
                &[],
                true,
                true,
            )
            .await
            .unwrap();

        assert_eq!(
            result.value.unwrap(),
            serde_json::json!({
                "url": "http://example.com/pkg/app_bg.wasm",
                "bytes": [0, 97, 115, 109, 1, 0, 0, 0],
            })
        );
    }

    // #969: fetch() must normalize the request method to uppercase, matching the
    // Request constructor, so a lowercase standard method is not wrongly
    // rejected by the case-sensitive CORS checks.
    #[tokio::test(flavor = "current_thread")]
    async fn fetch_normalizes_request_method_to_uppercase() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .call_function_on_for_cdp(
                r#"async () => {
                const original = __obscura_test_ops.op_fetch_url;
                let captured = null;
                try {
                    __obscura_test_ops.op_fetch_url = (url, method) => {
                        captured = method;
                        return JSON.stringify({ status: 200, headers: {}, body: "ok", url });
                    };
                    await fetch(new URL("/api", document.URL), { method: "delete" });
                    return captured;
                } finally {
                    __obscura_test_ops.op_fetch_url = original;
                }
            }"#,
                None,
                &[],
                true,
                true,
            )
            .await
            .unwrap();

        assert_eq!(
            result.value.unwrap(),
            serde_json::json!("DELETE"),
            "fetch() must uppercase the method like the Request constructor"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_and_xhr_forward_browser_credentials_modes() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt
            .call_function_on_for_cdp(
                r#"async () => {
                    const originalFetchOp = __obscura_test_ops.op_fetch_url;
                    const calls = [];
                    try {
                        __obscura_test_ops.op_fetch_url =
                            (url, method, headers, body, origin, mode, credentials) => {
                                calls.push({ url, credentials });
                                return JSON.stringify({
                                    status: 200,
                                    headers: {},
                                    body: "ok",
                                    url,
                                });
                            };

                        await fetch("/default");
                        await fetch("/omit", { credentials: "omit" });
                        const request = new Request("/included", { credentials: "include" });
                        await fetch(request);
                        await fetch(request.clone());
                        await fetch(request, { credentials: "same-origin" });

                        const sendXhr = (path, withCredentials) => new Promise((resolve, reject) => {
                            const xhr = new XMLHttpRequest();
                            xhr.open("GET", path);
                            xhr.withCredentials = withCredentials;
                            xhr.onload = resolve;
                            xhr.onerror = reject;
                            xhr.send();
                        });
                        await sendXhr("/xhr-default", false);
                        await sendXhr("/xhr-credentialed", true);

                        let invalidFetchRejected = false;
                        try {
                            await fetch("/bad", { credentials: "invalid" });
                        } catch (error) {
                            invalidFetchRejected = error instanceof TypeError;
                        }

                        return { calls, invalidFetchRejected };
                    } finally {
                        __obscura_test_ops.op_fetch_url = originalFetchOp;
                    }
                }"#,
                None,
                &[],
                true,
                true,
            )
            .await
            .unwrap();

        assert_eq!(
            result.value.unwrap(),
            serde_json::json!({
                "calls": [
                    { "url": "http://example.com/default", "credentials": "same-origin" },
                    { "url": "http://example.com/omit", "credentials": "omit" },
                    { "url": "http://example.com/included", "credentials": "include" },
                    { "url": "http://example.com/included", "credentials": "include" },
                    { "url": "http://example.com/included", "credentials": "same-origin" },
                    { "url": "http://example.com/xhr-default", "credentials": "same-origin" },
                    { "url": "http://example.com/xhr-credentialed", "credentials": "include" },
                ],
                "invalidFetchRejected": true,
            })
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_abort_prevents_pre_aborted_requests_from_reaching_transport() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let target = format!("http://{}/resource", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let mut requests = 0;
            while let Ok(Ok((mut stream, _))) = tokio::time::timeout(
                std::time::Duration::from_millis(500), listener.accept(),
            ).await {
                let mut buffer = [0u8; 4096];
                stream.read(&mut buffer).await.unwrap();
                stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\
                    Access-Control-Allow-Origin: *\r\nConnection: close\r\n\r\nok").await.unwrap();
                requests += 1;
            }
            requests
        });
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::with_full_options(
            std::sync::Arc::new(obscura_net::CookieJar::new()), None, true,
        )));
        let result = rt.call_function_on_for_cdp(&format!(r#"async () => {{
            const reason = {{ why: 'cancelled' }};
            const controller = new AbortController(); controller.abort(reason);
            const inherited = new Request({target:?}, {{ signal: controller.signal }});
            const results = [];
            for (const [input, init] of [[{target:?}, {{signal:controller.signal}}], [inherited, {{}}]]) {{
                results.push(await fetch(input, init).then(() => false, error => error === reason));
            }}
            // An explicit null overrides an inherited aborted signal.
            results.push(await fetch(inherited, {{signal:null}}).then(r => r.text()) === 'ok');
            return results;
        }}"#), None, &[], true, true).await.unwrap();
        let requests = server.await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!([true, true, true])));
        assert_eq!(requests, 1, "only the explicit signal override may reach the server");
        assert!(!rt.has_pending_network_requests());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_abort_accepts_cross_realm_signals_but_rejects_forged_prototypes() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.call_function_on_for_cdp(r#"async () => {
            const frame = document.createElement('iframe'); document.body.appendChild(frame);
            const controller = new frame.contentWindow.AbortController();
            const reason = { cancelled: true }; controller.abort(reason);
            const outcomes = [];
            outcomes.push(await fetch('https://example.com/', {signal:controller.signal})
                .then(() => false, error => error === reason));
            try {
                const request = new Request('https://example.com/', {signal:controller.signal});
                outcomes.push(await fetch(request).then(() => false, error => error === reason));
            } catch (_) { outcomes.push(false); }
            const forged = Object.create(AbortSignal.prototype);
            outcomes.push(await fetch('https://example.com/', {signal:forged})
                .then(() => false, error => error instanceof TypeError));
            try { new Request('https://example.com/', {signal:forged}); outcomes.push(false); }
            catch (error) { outcomes.push(error instanceof TypeError); }
            return outcomes;
        }"#, None, &[], true, true).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!([true, true, true, true])));
        assert!(!rt.has_pending_network_requests());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_abort_reads_signal_getters_once() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.call_function_on_for_cdp(r#"async () => {
            const reason = { cancelled: true };
            const signal = AbortSignal.abort(reason);
            let fetchReads = 0, requestReads = 0;
            const rejected = await fetch('https://example.com/', {
                get signal() { fetchReads++; return signal; }
            }).then(() => false, error => error === reason);
            const request = new Request('https://example.com/', {
                get signal() { requestReads++; return signal; }
            });
            return [rejected, request.signal.aborted, fetchReads, requestReads];
        }"#, None, &[], true, true).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!([true, true, 1, 1])));
    }

    #[test]
    fn request_signals_follow_sources_without_aliasing_or_reordering_abort_events() {
        let mut rt = setup_runtime("<html><body></body></html>");
        let result = rt.evaluate(r#"(() => {
            const controller = new AbortController();
            const request = new Request('https://example.com/', {signal:controller.signal});
            const clone = request.clone();
            const nested = AbortSignal.any([request.signal,clone.signal]);
            const reason = {cancelled:true};
            const order = [];
            controller.signal.addEventListener('abort', () => {
                order.push(['parent',request.signal.aborted,clone.signal.aborted,nested.aborted]);
            });
            request.signal.addEventListener('abort',()=>order.push(['request']));
            clone.signal.addEventListener('abort',()=>order.push(['clone']));
            nested.addEventListener('abort',()=>order.push(['nested']));
            const distinct = request.signal !== controller.signal && clone.signal !== request.signal;
            controller.abort(reason);
            return {distinct,order,reasons:request.signal.reason===reason &&
                clone.signal.reason===reason && nested.reason===reason};
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!({
            "distinct": true,
            "order": [["parent",true,true,true],["request"],["clone"],["nested"]],
            "reasons": true,
        }));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_abort_errors_completed_unread_response_streams() {
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let target = format!("http://{}/resource", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut request = [0u8; 4096];
            stream.read(&mut request).await.unwrap();
            stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\
                Access-Control-Allow-Origin: *\r\nConnection: close\r\n\r\ntail").await.unwrap();
        });
        let mut rt = setup_runtime("<html><body></body></html>");
        rt.set_http_client(std::sync::Arc::new(obscura_net::ObscuraHttpClient::with_full_options(
            std::sync::Arc::new(obscura_net::CookieJar::new()), None, true,
        )));
        rt.execute_script("completed-abort-fetch", &format!(r#"
            globalThis.completedController = new AbortController();
            globalThis.completedReader = null;
            fetch({target:?}, {{signal:completedController.signal}}).then(response => {{
                completedReader = response.body.getReader();
                globalThis.completedClosed = completedReader.closed.then(
                    () => false, error => error.name === 'AbortError');
            }});
        "#)).unwrap();
        assert!(rt.resolve_promises_until(|rt| {
            rt.evaluate("completedReader !== null").unwrap() == serde_json::json!(true)
                && !rt.has_pending_network_requests()
        }, 2_000).await, "the body must complete before abort");
        server.await.unwrap();
        let result = rt.call_function_on_for_cdp(r#"async () => {
            completedController.abort();
            return [await completedReader.read().then(
                () => false, error => error.name === 'AbortError'), await completedClosed];
        }"#, None, &[], true, true).await.unwrap();
        assert_eq!(result.value, Some(serde_json::json!([true,true])));
        assert!(!rt.has_pending_network_requests());
    }

    #[test]
    fn request_following_signals_are_collectible_without_observers() {
        let mut rt = setup_runtime("<html>

File truncated at 1 MB.