Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(dom): expose native NodeList snapshots in mutation records
ldm053121ae26b52
diff --git a/moli-renderer-v8/src/native_bridge/bridge/live_collections.rs b/moli-renderer-v8/src/native_bridge/bridge/live_collections.rsindex a6355d204..6f1446578 100644--- a/moli-renderer-v8/src/native_bridge/bridge/live_collections.rs+++ b/moli-renderer-v8/src/native_bridge/bridge/live_collections.rs@@ -1,4 +1,6 @@-use super::super::LiveCollectionDescriptor;+use std::{cell::RefCell, rc::Rc};++use super::super::{LiveCollectionDescriptor, identity::StaticHandleCollectionStore};use super::NativeDomBridge;impl NativeDomBridge {@@ -35,11 +37,10 @@ impl NativeDomBridge {.cache_live_collection_wrapper(scope, descriptor, wrapper);}- pub(in crate::native_bridge) fn register_static_handle_collection(- &mut self,- handles: Vec<crate::document_runtime::DomHandle>,- ) -> u32 {- self.identity.register_static_handle_collection(handles)+ pub(in crate::native_bridge) fn static_handle_collection_store(+ &self,+ ) -> Rc<RefCell<StaticHandleCollectionStore>> {+ self.identity.static_handle_collection_store()}pub(in crate::native_bridge) fn static_handle_collection_len(diff --git a/moli-renderer-v8/src/native_bridge/collections.rs b/moli-renderer-v8/src/native_bridge/collections.rsindex 4aabe8fc9..d56262609 100644--- a/moli-renderer-v8/src/native_bridge/collections.rs+++ b/moli-renderer-v8/src/native_bridge/collections.rs@@ -42,7 +42,6 @@ pub(super) use bridge_callbacks::{bridge_resolve_live_collection_callback,};pub(in crate::native_bridge::collections) use builders::STATIC_HANDLE_COLLECTION_ID_INTERNAL_FIELD;-pub(crate) use builders::install_collection_template_bindings;pub(in crate::native_bridge) use builders::{STATIC_COLLECTION_LENGTH_SLOT, build_fresh_document_all_named_collection_value,is_document_all_named_collection_value,@@ -52,6 +51,9 @@ pub(super) use builders::{build_live_collection_wrapper, build_live_collection_wrapper_for_receiver,build_live_html_children_collection_for_node, build_node_list_from_handles,};+pub(crate) use builders::{+ build_static_handle_node_list_wrapper, install_collection_template_bindings,+};pub(in crate::native_bridge) use shared::array_index_property_name;// Keep these re-exports visible only inside `collections`; sibling modules use `super::*`// without leaking collection-private helpers to the broader native_bridge surface.diff --git a/moli-renderer-v8/src/native_bridge/collections/builders.rs b/moli-renderer-v8/src/native_bridge/collections/builders.rsindex 1f80e97c9..38d8167d2 100644--- a/moli-renderer-v8/src/native_bridge/collections/builders.rs+++ b/moli-renderer-v8/src/native_bridge/collections/builders.rs@@ -303,7 +303,7 @@ pub(in crate::native_bridge) fn build_collection_wrapper<'s>(wrapper}-fn build_static_handle_node_list_wrapper<'s>(+pub(crate) fn build_static_handle_node_list_wrapper<'s>(scope: &mut v8::PinScope<'s, '_>,runtime_ptr: *mut JsContextHost,handles: &[DomHandle],@@ -334,11 +334,16 @@ fn build_static_handle_node_list_wrapper<'s>();set_collection_prototype(scope, wrapper, CollectionKind::NodeList);- let collection_id = {+ let collections = {let host = unsafe { &mut *runtime_ptr };- host.native_bridge_mut()- .register_static_handle_collection(handles.to_vec())+ host.native_bridge_mut().static_handle_collection_store()};+ let collection_id = collections.borrow_mut().register(handles.to_vec());+ // Mutation records create short-lived snapshots frequently. Release the+ // native handle vector when its wrapper dies, without retaining the host.+ crate::v8_finalizer::track_context_owned_v8_finalizer(scope, wrapper, move || {+ collections.borrow_mut().remove(collection_id);+ });assert!(wrapper.set_internal_field(STATIC_HANDLE_COLLECTION_ID_INTERNAL_FIELD,diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rsindex 95c37c70c..f0d4e17ba 100644--- a/moli-renderer-v8/src/native_bridge/identity.rs+++ b/moli-renderer-v8/src/native_bridge/identity.rs@@ -378,7 +378,7 @@ impl LiveCollectionStore {}#[derive(Debug)]-struct StaticHandleCollectionStore {+pub(in crate::native_bridge) struct StaticHandleCollectionStore {next_id: u32,handles: HashMap<u32, Vec<DomHandle>>,}@@ -393,7 +393,7 @@ impl Default for StaticHandleCollectionStore {}impl StaticHandleCollectionStore {- fn register(&mut self, handles: Vec<DomHandle>) -> u32 {+ pub(in crate::native_bridge) fn register(&mut self, handles: Vec<DomHandle>) -> u32 {let collection_id = self.next_id;self.next_id = self.next_id@@ -407,6 +407,10 @@ impl StaticHandleCollectionStore {collection_id}+ pub(in crate::native_bridge) fn remove(&mut self, collection_id: u32) {+ self.handles.remove(&collection_id);+ }+fn len(&self, collection_id: u32) -> Option<usize> {self.handles.get(&collection_id).map(Vec::len)}@@ -555,7 +559,7 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown(pub(super) struct BridgeIdentityStore {reflector_handles: IndexSet<BridgeHandle>,live_collections: LiveCollectionStore,- static_handle_collections: StaticHandleCollectionStore,+ static_handle_collections: Rc<RefCell<StaticHandleCollectionStore>>,default_world_wrapper_cache: Rc<RefCell<BridgeContextWrapperCache>>,}@@ -666,12 +670,14 @@ impl BridgeIdentityStore {});}- pub(super) fn register_static_handle_collection(&mut self, handles: Vec<DomHandle>) -> u32 {- self.static_handle_collections.register(handles)+ pub(super) fn static_handle_collection_store(+ &self,+ ) -> Rc<RefCell<StaticHandleCollectionStore>> {+ self.static_handle_collections.clone()}pub(super) fn static_handle_collection_len(&self, collection_id: u32) -> Option<usize> {- self.static_handle_collections.len(collection_id)+ self.static_handle_collections.borrow().len(collection_id)}pub(super) fn static_handle_collection_handle_at(@@ -680,16 +686,60 @@ impl BridgeIdentityStore {index: usize,) -> Option<DomHandle> {self.static_handle_collections+ .borrow().handle_at(collection_id, index)}}#[cfg(test)]mod tests {- use std::mem::size_of;+ use std::{cell::RefCell, mem::size_of, rc::Rc};use super::{BridgeCachedWrapper, BridgeHandle, BridgeIdentityStore, ReflectorId};+ #[test]+ fn static_handle_collection_releases_its_snapshot_on_wrapper_gc() {+ crate::ensure_v8_for_test();+ let store = Rc::new(RefCell::new(super::StaticHandleCollectionStore::default()));+ let mut isolate = v8::Isolate::new(Default::default());+ let (wrapper, finalizer, id) = {+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let wrapper = v8::Object::new(scope);+ let id = store+ .borrow_mut()+ .register(vec![super::DomHandle::new(0), super::DomHandle::new(1)]);+ let finalizer_store = store.clone();+ let finalizer = v8::Weak::with_guaranteed_finalizer(+ scope,+ wrapper,+ Box::new(move || finalizer_store.borrow_mut().remove(id)),+ );+ (v8::Global::new(scope, wrapper), finalizer, id)+ };+ isolate.low_memory_notification();+ assert_eq!(+ store.borrow().len(id),+ Some(2),+ "live wrapper retains its snapshot"+ );+ assert_eq!(+ store.borrow().handle_at(id, 1),+ Some(super::DomHandle::new(1))+ );+ drop(wrapper);+ isolate.low_memory_notification();+ assert_eq!(+ store.borrow().len(id),+ None,+ "GC releases the handle vector"+ );+ assert!(store.borrow().handles.is_empty());+ drop(finalizer);+ }+#[test]fn bridge_handle_stays_compact_for_per_wrapper_identity_tables() {#[cfg(target_pointer_width = "64")]diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rsindex e554107bc..d858708d2 100644--- a/moli-renderer-v8/src/native_bridge/mod.rs+++ b/moli-renderer-v8/src/native_bridge/mod.rs@@ -49,7 +49,9 @@ pub(crate) use active_child_window::{restore_deferred_active_child_window_scope_if_present,};pub(crate) use child_window_surface::CALLBACK_ERROR_WINDOW_HANDLE_SLOT;-pub(crate) use collections::install_collection_template_bindings;+pub(crate) use collections::{+ build_static_handle_node_list_wrapper, install_collection_template_bindings,+};pub(crate) use context_host::{DetachedChildBrowsingContextDocumentSnapshot, ImageDecodeRequestId,RuntimeObservableContextToken, cross_origin_lightweight_popup_id,diff --git a/moli-renderer-v8/src/observer_runtime/mod.rs b/moli-renderer-v8/src/observer_runtime/mod.rsindex 9526a9948..28f97c228 100644--- a/moli-renderer-v8/src/observer_runtime/mod.rs+++ b/moli-renderer-v8/src/observer_runtime/mod.rs@@ -39,14 +39,17 @@ use super::{context_bootstrap::build_dom_rect_object,host::report_event_callback_exception,native_bridge::document::{DETACHED_STATE_SLOT, detached_native_handle_for_runtime},- native_bridge::{JsContextHost, callback_value_dom_handle, wrapped_handle_value},+ native_bridge::{+ JsContextHost, build_static_handle_node_list_wrapper, callback_value_dom_handle,+ wrapped_handle_value,+ },native_bridge::{compute_mock_intersection_client_rect, compute_mock_intersection_scrollport_client_rect,},util::{callback_data_index_value, callback_data_item, context_host_ptr_from_global_bridge,- get_private_object, get_private_value, global_constructor_prototype, serialize_v8_array,- serialize_v8_iter_array, throw_range_error, throw_type_error, v8_string, v8str,+ get_private_object, get_private_value, serialize_v8_array, serialize_v8_iter_array,+ throw_range_error, throw_type_error, v8_string, v8str,},window_webidl_callback::WindowWebIdlCallbackFunctionOutcome,};@@ -1338,8 +1341,8 @@ fn build_mutation_record_object<'s>(.and_then(|namespace| v8_string(scope, namespace)).map(v8::Local::<v8::Value>::from).unwrap_or_else(|| v8::null(scope).into());- let added_nodes = empty_node_list_like(scope);- let removed_nodes = empty_node_list_like(scope);+ let added_nodes = build_static_handle_node_list_wrapper(scope, host_ptr, &[]);+ let removed_nodes = build_static_handle_node_list_wrapper(scope, host_ptr, &[]);(v8str(scope, "attributes").into(),v8_string(scope, attribute_name)?.into(),@@ -1356,8 +1359,8 @@ fn build_mutation_record_object<'s>()}QueuedMutationRecordKind::CharacterData { old_value } => {- let added_nodes = empty_node_list_like(scope);- let removed_nodes = empty_node_list_like(scope);+ let added_nodes = build_static_handle_node_list_wrapper(scope, host_ptr, &[]);+ let removed_nodes = build_static_handle_node_list_wrapper(scope, host_ptr, &[]);(v8str(scope, "characterData").into(),v8::null(scope).into(),@@ -1379,8 +1382,9 @@ fn build_mutation_record_object<'s>(previous_sibling,next_sibling,} => {- let added_nodes = build_node_array(scope, host_ptr, added_nodes);- let removed_nodes = build_node_array(scope, host_ptr, removed_nodes);+ let added_nodes = build_static_handle_node_list_wrapper(scope, host_ptr, added_nodes);+ let removed_nodes =+ build_static_handle_node_list_wrapper(scope, host_ptr, removed_nodes);let previous_sibling = previous_sibling.and_then(|handle| wrap_node_handle(scope, host_ptr, handle)).map(v8::Local::<v8::Value>::from)@@ -1508,36 +1512,6 @@ fn create_rect_object<'s>(build_dom_rect_object(scope, x, y, width, height)}-fn build_node_array<'s>(- scope: &mut v8::PinScope<'s, '_>,- host_ptr: *mut JsContextHost,- handles: &[NativeNodeId],-) -> v8::Local<'s, v8::Array> {- let values = handles- .iter()- .copied()- .map(|handle| {- wrap_node_handle(scope, host_ptr, handle)- .map(v8::Local::<v8::Value>::from)- .unwrap_or_else(|| v8::null(scope).into())- })- .collect::<Vec<_>>();- let array =- serialize_v8_array(scope, values.as_slice()).unwrap_or_else(|| v8::Array::new(scope, 0));- if let Some(prototype) = global_constructor_prototype(scope, "NodeList") {- let _ = array.set_prototype(scope, prototype.into());- }- array-}--fn empty_node_list_like<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Array> {- let array = v8::Array::new(scope, 0);- if let Some(prototype) = global_constructor_prototype(scope, "NodeList") {- let _ = array.set_prototype(scope, prototype.into());- }- array-}-fn wrap_node_handle<'s>(scope: &mut v8::PinScope<'s, '_>,host_ptr: *mut JsContextHost,diff --git a/moli-renderer-v8/src/script_vm/tests/mutation_record_node_lists.js b/moli-renderer-v8/src/script_vm/tests/mutation_record_node_lists.jsnew file mode 100644index 000000000..8e873bf65--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/mutation_record_node_lists.js@@ -0,0 +1,173 @@+globalThis.__mutationRecordNodeListResult = "pending";+(async () => {+ const check = (value, message) => {+ if (!value) throw new Error(message);+ };+ const NodeListConstructor = NodeList;+ const item = NodeList.prototype.item;+ const length = Object.getOwnPropertyDescriptor(NodeList.prototype, "length").get;+ const frame = globalThis.__observerCallbackFrame || document.querySelector("iframe");+ const child = frame.contentWindow;+ const childItem = child.NodeList.prototype.item;+ let label = "";+ function checkList(list, nodes) {+ check(!Array.isArray(list), label + ": NodeList must not be an Array");+ check(Object.prototype.toString.call(list) === "[object NodeList]", label + ": tag");+ check(length.call(list) === nodes.length, label + ": native length");+ check(item.call(list, nodes.length) === null, label + ": out-of-bounds item");+ check(list[nodes.length] === undefined, label + ": out-of-bounds index");+ check(childItem.call(list, nodes.length) === null, label + ": cross-realm item");+ const values = [...list];+ const entries = [...list.entries()];+ check(values.length === nodes.length, label + ": iterator length");+ check([...list.keys()].every((key, i) => key === i), label + ": keys");+ check([...list.values()].every((node, i) => node === nodes[i]), label + ": values");+ const receiver = {};+ let visited = 0;+ list.forEach(function (node, index, collection) {+ check(this === receiver && collection === list, label + ": forEach arguments");+ check(node === nodes[index], label + ": forEach node");+ visited++;+ }, receiver);+ check(visited === nodes.length, label + ": forEach count");+ for (let i = 0; i < nodes.length; i++) {+ check(list[i] === nodes[i] && item.call(list, i) === nodes[i], label + ": identity");+ check(values[i] === nodes[i], label + ": iterator identity");+ check(entries[i][0] === i && entries[i][1] === nodes[i], label + ": entries");+ }+ Reflect.set(list, nodes.length, null);+ check(list[nodes.length] === undefined, label + ": unsupported index write");+ Reflect.defineProperty(list, nodes.length, {value: null});+ check(list[nodes.length] === undefined, label + ": unsupported index definition");+ if (nodes.length) {+ const descriptor = Object.getOwnPropertyDescriptor(list, "0");+ check(descriptor.value === nodes[0] && !descriptor.writable &&+ descriptor.enumerable && descriptor.configurable, label + ": indexed descriptor");+ Reflect.set(list, 0, null);+ check(list[0] === nodes[0], label + ": indexed write");+ check(Reflect.deleteProperty(list, 0) === false, label + ": indexed delete");+ Reflect.defineProperty(list, 0, {value: null});+ check(list[0] === nodes[0], label + ": mutations preserve snapshot");+ }+ list.extra = 42;+ check(list.extra === 42, label + ": expando");+ delete list.extra;+ }+ function checkRecord(record, added, removed) {+ check(record.addedNodes === record.addedNodes && record.removedNodes === record.removedNodes,+ label + ": stable list identity");+ checkList(record.addedNodes, added);+ checkList(record.removedNodes, removed);+ }+ const documents = [document, document.implementation.createHTMLDocument(""),+ document.implementation.createDocument(null, "root"), child.document];+ for (const [index, owner] of documents.entries()) {+ label = "document " + index;+ const host = owner.createElement("div");+ const text = owner.createTextNode("before");+ host.appendChild(text);+ const observer = new MutationObserver(() => {});+ observer.observe(host, {attributes: true, characterData: true, childList: true, subtree: true});+ host.setAttribute("data-test", "value");+ text.data = "after";+ const scalarRecords = observer.takeRecords();+ check(Array.isArray(scalarRecords) && scalarRecords.length === 2, label + ": record sequence");+ check(scalarRecords[0].type === "attributes" && scalarRecords[1].type === "characterData",+ label + ": record types");+ scalarRecords.forEach(record => checkRecord(record, [], []));+ const node = owner.createElement("span");+ host.appendChild(node);+ const added = observer.takeRecords();+ check(added.length === 1 && added[0].type === "childList", label + ": insertion");+ checkRecord(added[0], [node], []);+ host.removeChild(node);+ const removed = observer.takeRecords();+ check(removed.length === 1, label + ": removal record");+ checkRecord(removed[0], [], [node]);+ host.appendChild(owner.createElement("other"));+ observer.disconnect();+ checkRecord(added[0], [node], []);+ checkRecord(removed[0], [], [node]);+ }++ label = "large fragment snapshot";+ {+ const host = document.createElement("div");+ const fragment = document.createDocumentFragment();+ const nodes = Array.from({length: 1002}, () => document.createElement("span"));+ nodes.forEach(node => fragment.appendChild(node));+ const observer = new MutationObserver(() => {});+ observer.observe(fragment, {childList: true});+ observer.observe(host, {childList: true});+ host.appendChild(fragment);+ const records = observer.takeRecords();+ check(records.length === 2, label + ": fragment removal and host insertion records");+ const [removed, added] = records;+ check(removed.target === fragment && added.target === host, label + ": record targets");+ checkRecord(removed, [], nodes);+ checkRecord(added, nodes, []);+ observer.disconnect();+ host.removeChild(nodes[0]);+ checkRecord(added, nodes, []);+ checkRecord(removed, [], nodes);+ }++ label = "intrinsic prototype";+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "NodeList");+ const host = document.createElement("div");+ const node = document.createElement("span");+ const observer = new MutationObserver(() => {});+ observer.observe(host, {attributes: true, childList: true});+ let list;+ try {+ Object.defineProperty(globalThis, "NodeList", {+ configurable: true, get() { throw new Error("author NodeList getter must not run"); }+ });+ host.setAttribute("data-test", "value");+ host.appendChild(node);+ const records = observer.takeRecords();+ checkRecord(records[0], [], []);+ checkRecord(records[1], [node], []);+ for (const record of records) {+ for (const value of [record.addedNodes, record.removedNodes]) {+ check(Object.getPrototypeOf(value) === NodeListConstructor.prototype,+ label + ": native prototype survives global replacement");+ }+ }+ list = records[1].addedNodes;+ } finally {+ Object.defineProperty(globalThis, "NodeList", descriptor);+ observer.disconnect();+ }+ const revoked = Proxy.revocable(list, {});+ revoked.revoke();+ let conversions = 0, traps = 0;+ const authorProxy = new Proxy(list, {get() { traps++; }});+ for (const fake of [{}, Object.create(list), authorProxy, revoked.proxy]) {+ let error;+ try { childItem.call(fake, {valueOf() { conversions++; return 0; }}); }+ catch (caught) { error = caught; }+ check(error instanceof child.TypeError, "invalid receiver uses callee TypeError");+ }+ check(conversions === 0 && traps === 0, "brand check precedes conversion and Proxy traps");++ label = "callback delivery";+ await new Promise((resolve, reject) => {+ const observer = new MutationObserver(function (records, deliveredObserver) {+ try {+ check(this === observer && deliveredObserver === observer, label + ": callback receiver");+ check(Array.isArray(records) && records.length === 1, label + ": record sequence");+ checkRecord(records[0], [], [node]);+ resolve();+ } catch (error) { reject(error); }+ finally { observer.disconnect(); }+ });+ observer.observe(host, {childList: true});+ host.removeChild(node);+ });+ globalThis.__mutationRecordNodeListResult = true;+ return true;+})().catch(error => {+ globalThis.__mutationRecordNodeListResult = String(error);+ throw error;+})diff --git a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rsindex 5f857de6a..eb851c064 100644--- a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs+++ b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs@@ -342,3 +342,19 @@ fn performance_observer_disconnect_retires_and_reobserve_restores_delivery() {.expect("PerformanceObserver re-observe workflow should flush");assert_eq!(delivered, r#"["delivered-after-reobserve"]"#);}++#[tokio::test(flavor = "current_thread")]+async fn mutation_record_node_lists_are_native_readonly_snapshots() {+ let mut vm = observer_callback_test_vm("https://mutation-record-node-lists.test/");+ vm.eval(include_str!("mutation_record_node_lists.js"))+ .expect("MutationRecord NodeList fixture should evaluate");+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ vm.advance_timers_until_deadline_for_test(&loader)+ .await+ .expect("deliver mutation records");+ assert_eq!(+ vm.eval("String(globalThis.__mutationRecordNodeListResult)")+ .unwrap(),+ "true"+ );+}