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(renderer): align legacy named access collections
ldm08eab95a494aa
diff --git a/moli-benchmark/wpt-cross-current/failed-cases.txt b/moli-benchmark/wpt-cross-current/failed-cases.txtindex 169879d67..adccb9740 100644--- a/moli-benchmark/wpt-cross-current/failed-cases.txt+++ b/moli-benchmark/wpt-cross-current/failed-cases.txt@@ -3048,10 +3048,6 @@ html/browsers/the-window-object/garbage-collection-and-browsing-contexts/discardhtml/browsers/the-window-object/garbage-collection-and-browsing-contexts/discard_iframe_history_2.htmlhtml/browsers/the-window-object/garbage-collection-and-browsing-contexts/discard_iframe_history_3.htmlhtml/browsers/the-window-object/garbage-collection-and-browsing-contexts/discard_iframe_history_4.html-html/browsers/the-window-object/named-access-on-the-window-object/basics.html-html/browsers/the-window-object/named-access-on-the-window-object/multi-match.html-html/browsers/the-window-object/named-access-on-the-window-object/name-attribute-elements.html-html/browsers/the-window-object/named-access-on-the-window-object/named-objects.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/window-named-properties.htmlhtml/browsers/the-window-object/open-close/close_script_defer.htmlhtml/browsers/the-window-object/open-close/closed-after-close.html@@ -3103,7 +3099,6 @@ html/dom/elements/the-innertext-and-outertext-properties/innertext-with-white-sphtml/dom/elements/the-innertext-and-outertext-properties/innertext-with-white-spaces.html?white-space=pre-wrap&contenteditable=plaintext-onlyhtml/dom/elements/the-innertext-and-outertext-properties/innertext-with-white-spaces.html?white-space=pre-wrap&contenteditable=truehtml/dom/elements/the-innertext-and-outertext-properties/outertext-setter.html-html/dom/historical.htmlhtml/dom/partial-updates/tentative/processing-instruction-attributes.htmlhtml/dom/partial-updates/tentative/stream-append-has-invalidation.htmlhtml/dom/partial-updates/tentative/stream-append-positional-pseudo-class-invalidation.htmldiff --git a/moli-benchmark/wpt-cross-current/passed-cases.txt b/moli-benchmark/wpt-cross-current/passed-cases.txtindex 94fdb948c..ba909d7b4 100644--- a/moli-benchmark/wpt-cross-current/passed-cases.txt+++ b/moli-benchmark/wpt-cross-current/passed-cases.txt@@ -5086,10 +5086,14 @@ html/browsers/the-window-object/Window-document.htmlhtml/browsers/the-window-object/accessing-other-browsing-contexts/iterator.htmlhtml/browsers/the-window-object/accessing-other-browsing-contexts/window_length.htmlhtml/browsers/the-window-object/defaultstatus.html+html/browsers/the-window-object/named-access-on-the-window-object/basics.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/changing.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/cross-global-npo.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/doc-no-window.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/existing-prop.html+html/browsers/the-window-object/named-access-on-the-window-object/multi-match.html+html/browsers/the-window-object/named-access-on-the-window-object/name-attribute-elements.html+html/browsers/the-window-object/named-access-on-the-window-object/named-objects.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/nested-context.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/prototype.htmlhtml/browsers/the-window-object/named-access-on-the-window-object/removing.html@@ -5194,6 +5198,7 @@ html/dom/elements/global-attributes/translate-non-html-translation-mode.htmlhtml/dom/elements/name-content-attribute-and-property.htmlhtml/dom/elements/the-innertext-and-outertext-properties/getter-first-letter-marker-multicol.htmlhtml/dom/elements/the-innertext-and-outertext-properties/innertext-whitespace-pre-line.html+html/dom/historical.htmlhtml/dom/partial-updates/tentative/template-for-innerHTML-outside.htmlhtml/dom/partial-updates/tentative/template-for-invalid.htmlhtml/dom/partial-updates/tentative/template-for-only-html-001.htmldiff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rsindex 697675260..ae5c68f13 100644--- a/moli-dom/src/native/host/document.rs+++ b/moli-dom/src/native/host/document.rs@@ -809,6 +809,79 @@ impl DomHost {})}+ pub fn element_handles_by_id_or_name_matching(+ &self,+ key: &str,+ mut accepts_name: impl FnMut(DomHandle) -> bool,+ ) -> Vec<DomHandle> {+ self.ensure_id_index();+ self.ensure_name_index();++ let mut candidates = IndexSet::new();+ if let Some(handles) = self+ .id_index+ .borrow()+ .as_ref()+ .and_then(|index| index.handles_by_value.get(key))+ {+ candidates.extend(handles.iter().copied());+ }+ if let Some(handles) = self+ .name_index+ .borrow()+ .as_ref()+ .and_then(|index| index.handles_by_value.get(key))+ {+ candidates.extend(handles.iter().copied());+ }++ let document_handle = self.document_handle();+ let mut matches = candidates+ .into_iter()+ .filter(|handle| {+ self.node(*handle).is_some_and(|node| {+ node.flags().in_document_tree()+ && node.owner_document() == Some(document_handle)+ && node.as_element().is_some_and(|element| {+ element.id() == Some(key)+ || (element.name_attribute() == Some(key) && accepts_name(*handle))+ })+ })+ })+ .collect::<Vec<_>>();+ matches.sort_by(|left, right| self.compare_handles_in_document_order(*left, *right));+ matches+ }++ pub fn element_handles_by_id_or_name_matching_in_subtree(+ &self,+ root: DomHandle,+ key: &str,+ mut accepts_name: impl FnMut(DomHandle) -> bool,+ ) -> Vec<DomHandle> {+ if root == self.document_handle() {+ return self.element_handles_by_id_or_name_matching(key, accepts_name);+ }++ let mut matches = Vec::new();+ let mut stack = vec![root];+ while let Some(handle) = stack.pop() {+ if self+ .node(handle)+ .and_then(Node::as_element)+ .is_some_and(|element| {+ element.id() == Some(key)+ || (element.name_attribute() == Some(key) && accepts_name(handle))+ })+ {+ matches.push(handle);+ }+ let children = self.child_handles(handle).collect::<Vec<_>>();+ stack.extend(children.into_iter().rev());+ }+ matches+ }+pub fn element_handle_by_id_in_subtree(&self, root: DomHandle, id: &str) -> Option<DomHandle> {if root == self.document_handle() {return self.element_handle_by_id(id);diff --git a/moli-dom/src/native/host/query_index.rs b/moli-dom/src/native/host/query_index.rsindex b484c56e3..dca654758 100644--- a/moli-dom/src/native/host/query_index.rs+++ b/moli-dom/src/native/host/query_index.rs@@ -1017,6 +1017,67 @@ mod tests {assert_eq!(host.element_handle_by_id("target"), Some(second));}+ #[test]+ fn combined_named_candidates_are_deduplicated_filtered_and_document_ordered() {+ let mut host = test_host();+ let document = host.document_handle();+ let id_only = host.create_element("div");+ let id_and_name = host.create_element("span");+ let accepted_name = host.create_element("form");++ assert!(host.set_attribute(id_only, "id", "target"));+ assert!(host.set_attribute(id_and_name, "id", "target"));+ assert!(host.set_attribute(id_and_name, "name", "target"));+ assert!(host.set_attribute(accepted_name, "name", "target"));+ assert!(host.append_child(document, id_only));+ assert!(host.append_child(document, id_and_name));+ assert!(host.append_child(document, accepted_name));++ assert_eq!(+ host.element_handles_by_id_or_name_matching("target", |handle| {+ handle == accepted_name+ }),+ vec![id_only, id_and_name, accepted_name]+ );++ assert!(host.insert_before(document, accepted_name, Some(id_only)));+ assert_eq!(+ host.element_handles_by_id_or_name_matching("target", |handle| {+ handle == accepted_name+ }),+ vec![accepted_name, id_only, id_and_name]+ );++ assert!(host.remove_attribute(id_and_name, "id"));+ assert_eq!(+ host.element_handles_by_id_or_name_matching("target", |handle| {+ handle == accepted_name+ }),+ vec![accepted_name, id_only]+ );++ let nested_root = host.create_element("section");+ let nested_id = host.create_element("div");+ let rejected_nested_name = host.create_element("span");+ let accepted_nested_name = host.create_element("form");+ assert!(host.set_attribute(nested_id, "id", "target"));+ assert!(host.set_attribute(rejected_nested_name, "name", "target"));+ assert!(host.set_attribute(accepted_nested_name, "name", "target"));+ assert!(host.append_child(document, nested_root));+ assert!(host.append_child(nested_root, nested_id));+ assert!(host.append_child(nested_root, rejected_nested_name));+ assert!(host.append_child(nested_root, accepted_nested_name));++ assert_eq!(+ host.element_handles_by_id_or_name_matching_in_subtree(+ nested_root,+ "target",+ |handle| handle == accepted_nested_name,+ ),+ vec![nested_id, accepted_nested_name]+ );+ }+#[test]fn named_candidate_index_tracks_deep_subtree_connectivity_without_rebuild() {let mut host = test_host();diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rsindex 03da30680..4a416ab65 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs@@ -1,4 +1,7 @@use super::helpers::{window_child_context_handle, window_host_ptr};+use crate::native_bridge::named_access::{+ build_window_named_items_collection, window_named_item_handles,+};use crate::util::serialize_v8_iter_array;use moli_webapi_declare::DataPropertyDescriptorDeclaration;@@ -199,28 +202,27 @@ fn window_named_access_value<'s>(let document = child_handle.and_then(|child_handle| host.child_browsing_context_document_handle(child_handle)).unwrap_or_else(|| host.document_handle());- let handle = host- .dom_host()- .element_handle_by_id_in_subtree(document, &key_name)- .or_else(|| {- host.dom_host()- .element_handle_by_name_in_subtree(document, &key_name)- });+ let handles = window_named_item_handles(host.dom_host(), document, &key_name);if moli_trace::window_message_trace_enabled() {tracing::info!(target: "moli_window_message_trace",property = %key_name,child_handle = child_handle.map(|handle| handle.index()),document_handle = document.index(),- matched_handle = handle.map(|handle| handle.index()),+ matched_handle = handles.first().map(|handle| handle.index()),+ match_count = handles.len(),receiver_is_current_global = holder.strict_equals(scope.get_current_context().global(scope).into()),stage = "window_named_property_lookup",);}- let handle = handle?;- unsafe { &mut *host_ptr }- .native_bridge_mut()- .wrap_handle(scope, host_ptr, handle)- .map(Into::into)+ match handles.as_slice() {+ [] => None,+ [handle] => unsafe { &mut *host_ptr }+ .native_bridge_mut()+ .wrap_handle(scope, host_ptr, *handle)+ .map(Into::into),+ _ => build_window_named_items_collection(scope, host_ptr, document, &key_name)+ .map(Into::into),+ }}diff --git a/moli-renderer-v8/src/native_bridge/collections.rs b/moli-renderer-v8/src/native_bridge/collections.rsindex 6a6a0fea5..f84fc7f9a 100644--- a/moli-renderer-v8/src/native_bridge/collections.rs+++ b/moli-renderer-v8/src/native_bridge/collections.rs@@ -42,14 +42,18 @@ pub(super) use bridge_callbacks::{bridge_get_elements_by_tag_name_callback, bridge_get_elements_by_tag_name_ns_callback,bridge_resolve_live_collection_callback,};-pub(in crate::native_bridge) use builders::STATIC_COLLECTION_LENGTH_SLOT;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,+};pub(super) use builders::{build_collection_wrapper, build_live_child_node_list_for_node, build_live_collection_for_node,build_live_collection_wrapper, build_live_html_children_collection_for_node,build_node_list_from_handles,};+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.pub(in crate::native_bridge::collections) use iteration::*;diff --git a/moli-renderer-v8/src/native_bridge/collections/builders.rs b/moli-renderer-v8/src/native_bridge/collections/builders.rsindex c6cc1cc00..f7ec577ab 100644--- a/moli-renderer-v8/src/native_bridge/collections/builders.rs+++ b/moli-renderer-v8/src/native_bridge/collections/builders.rs@@ -375,6 +375,26 @@ pub(in crate::native_bridge) fn build_live_collection_wrapper<'s>(host.native_bridge_mut().register_live_collection(descriptor.clone())};+ let wrapper = instantiate_live_collection_wrapper(+ scope,+ runtime_ptr,+ collection_id,+ descriptor.collection_kind,+ );+ {+ let host = unsafe { &mut *runtime_ptr };+ host.native_bridge_mut()+ .cache_live_collection_wrapper(scope, descriptor, wrapper);+ }+ wrapper+}++fn instantiate_live_collection_wrapper<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ runtime_ptr: *mut JsContextHost,+ collection_id: u32,+ collection_kind: CollectionKind,+) -> v8::Local<'s, v8::Object> {let template = {let host = unsafe { &mut *runtime_ptr };host.native_bridge_mut().live_collection_wrapper_template()@@ -391,13 +411,45 @@ pub(in crate::native_bridge) fn build_live_collection_wrapper<'s>(wrapper.set_internal_field(1, v8::Number::new(scope, collection_id as f64).into()),"live collection wrapper must expose its descriptor id field");- set_collection_prototype(scope, wrapper, descriptor.collection_kind);+ set_collection_prototype(scope, wrapper, collection_kind);+ wrapper+}++fn document_all_named_collection_parts(+ scope: &mut v8::PinScope<'_, '_>,+ value: v8::Local<'_, v8::Value>,+) -> Option<(*mut JsContextHost, u32)> {+ let object = v8::Local::<v8::Object>::try_from(value).ok()?;+ let (runtime_ptr, descriptor) = live_collection_descriptor_from_object(scope, object).ok()?;+ if descriptor.collection_kind != CollectionKind::HtmlCollection+ || descriptor.query_kind != LiveCollectionQueryKind::DocumentAllNamedItems{- let host = unsafe { &mut *runtime_ptr };- host.native_bridge_mut()- .cache_live_collection_wrapper(scope, descriptor, wrapper);+ return None;}- wrapper+ Some((runtime_ptr, object_collection_id(scope, object).ok()?))+}++pub(in crate::native_bridge) fn is_document_all_named_collection_value(+ scope: &mut v8::PinScope<'_, '_>,+ value: v8::Local<'_, v8::Value>,+) -> bool {+ document_all_named_collection_parts(scope, value).is_some()+}++pub(in crate::native_bridge) fn build_fresh_document_all_named_collection_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+) -> Option<v8::Local<'s, v8::Value>> {+ let (runtime_ptr, collection_id) = document_all_named_collection_parts(scope, value)?;+ Some(+ instantiate_live_collection_wrapper(+ scope,+ runtime_ptr,+ collection_id,+ CollectionKind::HtmlCollection,+ )+ .into(),+ )}fn define_html_collection_named_properties(diff --git a/moli-renderer-v8/src/native_bridge/collections/shared.rs b/moli-renderer-v8/src/native_bridge/collections/shared.rsindex c8d942d11..b52008a61 100644--- a/moli-renderer-v8/src/native_bridge/collections/shared.rs+++ b/moli-renderer-v8/src/native_bridge/collections/shared.rs@@ -78,7 +78,7 @@ pub(in crate::native_bridge::collections) fn static_handle_collection_handle_at(.static_handle_collection_handle_at(collection_id, index)}-fn object_collection_id(+pub(in crate::native_bridge::collections) fn object_collection_id(scope: &mut v8::PinScope<'_, '_>,object: v8::Local<'_, v8::Object>,) -> std::result::Result<u32, String> {@@ -159,14 +159,20 @@ pub(in crate::native_bridge::collections) fn named_item_property_names(names.into_iter().collect()}-pub(in crate::native_bridge::collections) fn is_array_index_property_name(value: &str) -> bool {+pub(in crate::native_bridge) fn array_index_property_name(value: &str) -> Option<u32> {if value.is_empty() || (value.len() > 1 && value.starts_with('0')) {- return false;+ return None;}if !value.bytes().all(|byte| byte.is_ascii_digit()) {- return false;+ return None;+ }+ let index = value.parse::<u64>().ok()?;+ if index >= u64::from(u32::MAX) {+ return None;}- value- .parse::<u64>()- .is_ok_and(|index| index < u64::from(u32::MAX))+ u32::try_from(index).ok()+}++pub(in crate::native_bridge::collections) fn is_array_index_property_name(value: &str) -> bool {+ array_index_property_name(value).is_some()}diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rsindex d9b4035b4..ca71b055b 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs@@ -1,6 +1,9 @@use crate::native_bridge::collections::{STATIC_COLLECTION_LENGTH_SLOT, mark_collection_kind};use crate::native_bridge::document::DETACHED_NATIVE_NODE_LIST_HANDLES_SLOT;use crate::native_bridge::identity::CollectionKind;+use crate::native_bridge::named_access::{+ LegacyNamedAccessKind, html_element_name_attribute_is_exposed,+};use crate::util::{context_host_ptr_from_global_bridge, get_private_value, serialize_v8_iter_array,set_private_value,@@ -259,16 +262,25 @@ pub(in crate::native_bridge::document) fn detached_html_collection_named_item_cafn detached_collection_named_lookup<'s>(scope: &mut v8::PinScope<'s, '_>,values: &[v8::Local<'s, v8::Object>],+ name_access_kind: Option<LegacyNamedAccessKind>,) -> v8::Local<'s, v8::Object> {let lookup = ObjectLiteralDeclaration::bind(scope);for value in values {- for key_text in [- detached_collection_attribute_value(scope, *value, "id"),- detached_collection_attribute_value(scope, *value, "name"),- ]- .into_iter()- .flatten()- {+ for attribute_name in ["id", "name"] {+ if attribute_name == "name"+ && name_access_kind.is_some_and(|kind| {+ detached_element_namespace_uri(scope, *value).as_deref() != Some(XHTML_NS)+ || !detached_element_local_name(scope, *value).is_some_and(|local_name| {+ html_element_name_attribute_is_exposed(&local_name, kind)+ })+ })+ {+ continue;+ }+ let Some(key_text) = detached_collection_attribute_value(scope, *value, attribute_name)+ else {+ continue;+ };if key_text.is_empty() {continue;}@@ -401,7 +413,7 @@ pub(in crate::native_bridge::document) fn build_detached_html_collection<'s>(scope: &mut v8::PinScope<'s, '_>,values: &[v8::Local<'s, v8::Object>],) -> Option<v8::Local<'s, v8::Object>> {- let named = detached_collection_named_lookup(scope, values);+ let named = detached_collection_named_lookup(scope, values, None);let wrapper = DetachedHtmlCollectionDeclaration::new().bind(scope).ok()?;install_detached_collection_state(scope, wrapper, CollectionKind::HtmlCollection, values.len());install_detached_collection_members(scope, wrapper, values, Some(named))?;@@ -465,7 +477,8 @@ pub(in crate::native_bridge::document) fn build_detached_document_all<'s>(let prototype = v8::Local::<v8::Object>::try_from(prototype).ok()?;let items = build_object_array(scope, &values);- let named = detached_collection_named_lookup(scope, &values);+ let named =+ detached_collection_named_lookup(scope, &values, Some(LegacyNamedAccessKind::DocumentAll));let data = DetachedCollectionItemsAndNamedDataDeclaration::new(items.into(), named).bind(scope).ok()?;diff --git a/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs b/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rsindex 011aa0b63..79d482968 100644--- a/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs+++ b/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs@@ -1,11 +1,13 @@use crate::document_runtime::DomHandle;+use crate::native_bridge::collections;use crate::util::v8str;use moli_webapi_declare::WebApiObject;use super::super::super::super::JsContextHost;use super::super::super::define_collection_value_property;use super::callbacks::{- document_all_call_callback, document_all_item_callback, document_all_named_item_callback,+ document_all_call_callback, document_all_item_callback, document_all_named_collection_getter,+ document_all_named_item_callback,};use super::items::{document_all_items_array, document_all_named_lookup};@@ -31,7 +33,12 @@ struct DocumentAllCollectionSurfaceDeclaration<'scope> {length: f64,#[webapi(method, callback = document_all_item_callback, data = self.data)]item: (),- #[webapi(method, callback = document_all_named_item_callback, data = self.data)]+ #[webapi(+ method,+ length = 1,+ callback = document_all_named_item_callback,+ data = self.data+ )]named_item: (),}@@ -41,7 +48,7 @@ pub(super) fn build_document_all_collection<'s>(document_handle: DomHandle,) -> Option<v8::Local<'s, v8::Object>> {let items = document_all_items_array(scope, runtime_ptr, document_handle)?;- let named = document_all_named_lookup(scope, items);+ let named = document_all_named_lookup(scope, runtime_ptr, document_handle, items);let data = DocumentAllCollectionDataDeclaration::new(items, named).bind(scope).ok()?;@@ -81,6 +88,26 @@ pub(super) fn build_document_all_collection<'s>(let Some(value) = named.get(scope, key) else {continue;};+ let Ok(key_name) = v8::Local::<v8::Name>::try_from(key) else {+ continue;+ };+ let Ok(key_string) = v8::Local::<v8::String>::try_from(key) else {+ continue;+ };+ if collections::array_index_property_name(&key_string.to_rust_string_lossy(scope)).is_some()+ {+ continue;+ }+ if collections::is_document_all_named_collection_value(scope, value) {+ let _ = collection.set_native_data_property_with_configuration(+ scope,+ key_name,+ v8::NativeDataPropertyConfiguration::new(document_all_named_collection_getter)+ .data(value)+ .property_attribute(v8::PropertyAttribute::DONT_ENUM),+ );+ continue;+ }define_collection_value_property(scope,collection,diff --git a/moli-renderer-v8/src/native_bridge/document/live_collections/all/callbacks.rs b/moli-renderer-v8/src/native_bridge/document/live_collections/all/callbacks.rsindex 3d498a088..38256a894 100644--- a/moli-renderer-v8/src/native_bridge/document/live_collections/all/callbacks.rs+++ b/moli-renderer-v8/src/native_bridge/document/live_collections/all/callbacks.rs@@ -1,24 +1,33 @@+use crate::native_bridge::collections;use crate::util::{v8_string, v8str};+use crate::webidl;use super::super::super::super::callback_arg_string;+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "HTMLAllCollection.namedItem")]+struct HtmlAllCollectionNamedItemArgs {+ #[webidl(required)]+ name: String,+}+enum HtmlAllNameOrIndex {Index(u32),Name(String),}fn array_index_property_name(value: &str) -> Option<u32> {- if value.is_empty() || (value.len() > 1 && value.starts_with('0')) {- return None;- }- if !value.bytes().all(|byte| byte.is_ascii_digit()) {- return None;- }- let index = value.parse::<u64>().ok()?;- if index >= u64::from(u32::MAX) {- return None;+ collections::array_index_property_name(value)+}++fn fresh_named_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+) -> Option<v8::Local<'s, v8::Value>> {+ if collections::is_document_all_named_collection_value(scope, value) {+ return collections::build_fresh_document_all_named_collection_value(scope, value);}- u32::try_from(index).ok()+ Some(value)}fn document_all_name_or_index(@@ -47,9 +56,10 @@ fn resolve_document_all_value<'s>(.filter(|value| !value.is_null_or_undefined()),HtmlAllNameOrIndex::Name(key) => {let key = v8_string(scope, &key)?;- named+ let value = named.get(scope, key.into())- .filter(|value| !value.is_null_or_undefined())+ .filter(|value| !value.is_null_or_undefined())?;+ fresh_named_value(scope, value)}}}@@ -120,9 +130,9 @@ pub(super) fn document_all_item_callback(}}-pub(super) fn document_all_named_item_callback(- scope: &mut v8::PinScope<'_, '_>,- args: v8::FunctionCallbackArguments<'_>,+pub(super) fn document_all_named_item_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) else {@@ -136,16 +146,30 @@ pub(super) fn document_all_named_item_callback(rv.set_null();return;};- let Some(key) = callback_arg_string(scope, &args, 0) else {- rv.set_null();+ let Some(parsed) = webidl::parse_args::<HtmlAllCollectionNamedItemArgs>(scope, &args) else {return;};- let Some(key) = v8_string(scope, &key) else {+ let Some(key) = v8_string(scope, &parsed.name) else {rv.set_null();return;};match named.get(scope, key.into()) {- Some(value) if !value.is_null_or_undefined() => rv.set(value),+ Some(value) if !value.is_null_or_undefined() => match fresh_named_value(scope, value) {+ Some(value) => rv.set(value),+ None => rv.set_null(),+ },_ => rv.set_null(),}}+pub(super) fn document_all_named_collection_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ _key: v8::Local<'s, v8::Name>,+ args: v8::PropertyCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ if let Some(value) =+ collections::build_fresh_document_all_named_collection_value(scope, args.data())+ {+ rv.set(value);+ }+}diff --git a/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs b/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rsindex 3ca89c837..2f8faab77 100644--- a/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs+++ b/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs@@ -1,5 +1,11 @@use crate::document_runtime::DomHandle;+use crate::native_bridge::collections;use crate::native_bridge::element::element_attribute_for_object;+use crate::native_bridge::identity::{CollectionKind, LiveCollectionQueryKind};+use crate::native_bridge::named_access::{+ LegacyNamedAccessKind, dom_element_name_attribute_is_exposed,+};+use crate::native_bridge::node::node_runtime_and_handle_from_object;use crate::util::v8_string;use moli_webapi_declare::ObjectLiteralDeclaration;@@ -33,6 +39,8 @@ pub(super) fn document_all_items_array<'s>(pub(super) fn document_all_named_lookup<'s>(scope: &mut v8::PinScope<'s, '_>,+ runtime_ptr: *mut JsContextHost,+ document_handle: DomHandle,items: v8::Local<'s, v8::Array>,) -> v8::Local<'s, v8::Object> {let lookup = ObjectLiteralDeclaration::bind(scope);@@ -45,6 +53,20 @@ pub(super) fn document_all_named_lookup<'s>(continue;};for attribute_name in ["id", "name"] {+ if attribute_name == "name"+ && !node_runtime_and_handle_from_object(scope, item)+ .ok()+ .is_some_and(|(runtime_ptr, handle)| {+ let dom = unsafe { &*runtime_ptr }.dom_host();+ dom_element_name_attribute_is_exposed(+ dom,+ handle,+ LegacyNamedAccessKind::DocumentAll,+ )+ })+ {+ continue;+ }let Some(key_text) = element_attribute_for_object(scope, item, attribute_name) else {continue;};@@ -54,14 +76,36 @@ pub(super) fn document_all_named_lookup<'s>(let Some(key) = v8_string(scope, &key_text) else {continue;};- if lookup- .as_object()+ let lookup_object = lookup.as_object();+ let existing = lookup_object.get(scope, key.into())- .is_some_and(|existing| !existing.is_null_or_undefined())+ .filter(|existing| !existing.is_null_or_undefined());+ if !lookup_object+ .has_own_property(scope, key.into())+ .unwrap_or(false)+ && existing.is_some(){+ // Prototype members are not entries in the backing named+ // table; only own properties represent earlier matches.+ continue;+ }+ let Some(existing) = existing else {+ lookup.set_value_property(scope, key.into(), item.into());+ continue;+ };+ if existing.strict_equals(item.into()) {continue;}- lookup.set_value_property(scope, key.into(), item.into());+ let collection = collections::build_live_collection_for_node(+ scope,+ runtime_ptr,+ document_handle,+ CollectionKind::HtmlCollection,+ LiveCollectionQueryKind::DocumentAllNamedItems,+ Some(key_text),+ false,+ );+ lookup.set_value_property(scope, key.into(), collection.into());}}lookup.into_object()diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rsindex 86289d510..4b389f355 100644--- a/moli-renderer-v8/src/native_bridge/identity.rs+++ b/moli-renderer-v8/src/native_bridge/identity.rs@@ -144,6 +144,8 @@ pub(super) enum LiveCollectionQueryKind {TagNameNs,ClassName,Name,+ WindowNamedItems,+ DocumentAllNamedItems,FormControlsByName,Forms,Images,@@ -169,6 +171,8 @@ impl LiveCollectionQueryKind {Self::TagNameNs => "tagNameNs",Self::ClassName => "className",Self::Name => "name",+ Self::WindowNamedItems => "windowNamedItems",+ Self::DocumentAllNamedItems => "documentAllNamedItems",Self::FormControlsByName => "formControlsByName",Self::Forms => "forms",Self::Images => "images",@@ -276,6 +280,17 @@ impl LiveCollectionDescriptor {.is_some_and(|element| element.matches_named_item_key(query))}).collect()+ } else if self.query_kind == LiveCollectionQueryKind::WindowNamedItems {+ crate::native_bridge::named_access::window_named_item_handles(+ host.dom_host(),+ self.root,+ self.query.as_deref().unwrap_or_default(),+ )+ } else if self.query_kind == LiveCollectionQueryKind::DocumentAllNamedItems {+ crate::native_bridge::named_access::document_all_named_item_handles(+ host.dom_host(),+ self.query.as_deref().unwrap_or_default(),+ )} else {host.dom_host().resolve_live_collection(diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rsindex 8812f993c..b5888fb54 100644--- a/moli-renderer-v8/src/native_bridge/mod.rs+++ b/moli-renderer-v8/src/native_bridge/mod.rs@@ -18,6 +18,7 @@ pub(crate) mod element;mod helpers;mod history_queue;pub(super) mod identity;+pub(crate) mod named_access;mod node;pub(crate) mod pointer_lock;mod traversal;diff --git a/moli-renderer-v8/src/native_bridge/named_access.rs b/moli-renderer-v8/src/native_bridge/named_access.rsnew file mode 100644index 000000000..1d2d4d085--- /dev/null+++ b/moli-renderer-v8/src/native_bridge/named_access.rs@@ -0,0 +1,112 @@+use crate::document_runtime::DomHandle;+use moli_dom::native::DomHost;++use super::{+ JsContextHost, collections,+ identity::{CollectionKind, LiveCollectionQueryKind},+};++const WINDOW_NAME_ELEMENTS: &[&str] = &["img", "form", "embed", "object"];+const DOCUMENT_ALL_NAME_ELEMENTS: &[&str] = &[+ "a", "button", "embed", "form", "frame", "frameset", "iframe", "img", "input", "map", "meta",+ "object", "select", "textarea",+];++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub(crate) enum LegacyNamedAccessKind {+ Window,+ DocumentAll,+}++pub(crate) fn html_element_name_attribute_is_exposed(+ local_name: &str,+ kind: LegacyNamedAccessKind,+) -> bool {+ name_elements(kind).contains(&local_name)+}++pub(crate) fn dom_element_name_attribute_is_exposed(+ dom: &DomHost,+ handle: DomHandle,+ kind: LegacyNamedAccessKind,+) -> bool {+ name_elements(kind)+ .iter()+ .any(|local_name| dom.is_html_element_named(handle, local_name))+}++pub(crate) fn window_named_item_handles(+ dom: &DomHost,+ root: DomHandle,+ name: &str,+) -> Vec<DomHandle> {+ dom.element_handles_by_id_or_name_matching_in_subtree(root, name, |handle| {+ dom_element_name_attribute_is_exposed(dom, handle, LegacyNamedAccessKind::Window)+ })+}++pub(crate) fn document_all_named_item_handles(dom: &DomHost, name: &str) -> Vec<DomHandle> {+ dom.element_handles_by_id_or_name_matching(name, |handle| {+ dom_element_name_attribute_is_exposed(dom, handle, LegacyNamedAccessKind::DocumentAll)+ })+}++pub(crate) fn build_window_named_items_collection<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ runtime_ptr: *mut JsContextHost,+ root: DomHandle,+ name: &str,+) -> Option<v8::Local<'s, v8::Object>> {+ Some(collections::build_live_collection_for_node(+ scope,+ runtime_ptr,+ root,+ CollectionKind::HtmlCollection,+ LiveCollectionQueryKind::WindowNamedItems,+ Some(name.to_owned()),+ false,+ ))+}++fn name_elements(kind: LegacyNamedAccessKind) -> &'static [&'static str] {+ match kind {+ LegacyNamedAccessKind::Window => WINDOW_NAME_ELEMENTS,+ LegacyNamedAccessKind::DocumentAll => DOCUMENT_ALL_NAME_ELEMENTS,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn legacy_name_attribute_candidates_are_scoped_by_consumer() {+ for local_name in ["img", "form", "embed", "object"] {+ assert!(html_element_name_attribute_is_exposed(+ local_name,+ LegacyNamedAccessKind::Window+ ));+ }+ for local_name in ["a", "button", "iframe", "input", "meta", "applet", "div"] {+ assert!(!html_element_name_attribute_is_exposed(+ local_name,+ LegacyNamedAccessKind::Window+ ));+ }+ for local_name in [+ "a", "button", "embed", "form", "frame", "frameset", "iframe", "img", "input", "map",+ "meta", "object", "select", "textarea",+ ] {+ assert!(html_element_name_attribute_is_exposed(+ local_name,+ LegacyNamedAccessKind::DocumentAll+ ));+ }+ for local_name in ["applet", "div", "svg"] {+ assert!(!html_element_name_attribute_is_exposed(+ local_name,+ LegacyNamedAccessKind::DocumentAll+ ));+ }+ }+}diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rsindex 54f4f9102..51666c8d6 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs@@ -5237,6 +5237,211 @@ fn live_document_all_matches_chromium_htmldda_surface() {);}+#[test]+fn live_document_all_obeys_legacy_named_and_indexed_semantics() {+ let mut vm = new_parsed_test_vm(+ "https://example.com/",+ r#"<!doctype html><html><body>+ <div id="dupe"></div><div id="dupe"></div>+ <form id="same" name="same"></form>+ <span id="42"></span>+ <span id="043"></span>+ <span id="4294967294"></span>+ <span id="4294967295"></span>+ <span id="undefined"></span>+ </body></html>"#,+ );++ let result = vm+ .eval(+ r##"+ (() => {+ const all = document.all;+ const collections = [+ all.dupe,+ all.namedItem("dupe"),+ all("dupe", 0),+ all.item("dupe"),+ ];+ const matches = collections[0];+ const first = document.querySelectorAll("#dupe")[0];+ const second = document.querySelectorAll("#dupe")[1];+ const initial = [+ collections.every(collection => collection instanceof HTMLCollection),+ collections.every((collection, index) =>+ collections.slice(index + 1).every(other => collection !== other)),+ matches.length,+ matches[0] === first,+ matches[1] === second,+ all("same") === document.getElementById("same")+ ];+ const numericNames = [+ all[42] === undefined,+ all[4294967294] === undefined,+ all["043"] === document.getElementById("043"),+ all[4294967295] === document.getElementById("4294967295"),+ ];+ let namedItemMissingThrows = false;+ try {+ all.namedItem();+ } catch (error) {+ namedItemMissingThrows = error instanceof TypeError;+ }+ const explicitUndefined =+ all.namedItem(undefined) === document.getElementById("undefined");+ const namedItemLength = all.namedItem.length;+ const third = document.createElement("div");+ third.id = "dupe";+ document.body.appendChild(third);+ const appended = collections.every(collection =>+ collection.length === 3 && collection[2] === third);+ second.remove();+ const removed = collections.every(collection =>+ collection.length === 2 && collection[0] === first && collection[1] === third);+ return JSON.stringify({+ initial,+ numericNames,+ namedItemMissingThrows,+ explicitUndefined,+ namedItemLength,+ appended,+ removed,+ });+ })()+ "##,+ )+ .expect("document.all multiple named matches should evaluate");++ assert_eq!(+ result,+ r#"{"initial":[true,true,2,true,true,true],"numericNames":[true,true,true,true],"namedItemMissingThrows":true,"explicitUndefined":true,"namedItemLength":1,"appended":true,"removed":true}"#+ );+}++#[test]+fn legacy_named_access_filters_name_candidates_by_consumer() {+ let mut vm = new_parsed_test_vm(+ "https://example.com/",+ r#"<!doctype html><html><body>+ <applet id="appletId" name="appletOnly"></applet>+ <applet name="shared"></applet>+ <form id="form" name="shared"></form>+ <div id="divId" name="divOnly"></div>+ <a id="anchor" name="allOnly"></a>+ <img id="image" name="windowAllowed">+ <svg><a id="svgId" name="svgOnly"></a></svg>+ </body></html>"#,+ );++ let result = vm+ .eval(+ r#"+ (() => {+ const detached = new DOMParser().parseFromString(+ '<html><body><applet id="detachedAppletId" name="detachedApplet"></applet>' ++ '<form id="detachedFormId" name="detachedForm"></form></body></html>',+ 'text/html'+ );+ return JSON.stringify({+ windowAppletNameAbsent: window.appletOnly === undefined,+ allAppletNameAbsent: document.all.appletOnly === undefined,+ windowSharedUsesEligibleForm: window.shared === document.getElementById("form"),+ allSharedUsesEligibleForm: document.all.shared === document.getElementById("form"),+ windowAnchorNameAbsent: window.allOnly === undefined,+ allAnchorNamePresent: document.all.allOnly === document.getElementById("anchor"),+ windowImageNamePresent:+ window.windowAllowed === document.getElementById("image"),+ allImageNamePresent:+ document.all.windowAllowed === document.getElementById("image"),+ windowDivNameAbsent: window.divOnly === undefined,+ allDivNameAbsent: document.all.divOnly === undefined,+ windowSvgNameAbsent: window.svgOnly === undefined,+ allSvgNameAbsent: document.all.svgOnly === undefined,+ windowAppletIdPresent: window.appletId === document.getElementById("appletId"),+ allAppletIdPresent: document.all.appletId === document.getElementById("appletId"),+ windowSvgIdPresent: window.svgId === document.getElementById("svgId"),+ allSvgIdPresent: document.all.svgId === document.getElementById("svgId"),+ detachedAppletNameAbsent: detached.all.detachedApplet === undefined,+ detachedAppletIdPresent:+ detached.all.detachedAppletId === detached.getElementById("detachedAppletId"),+ detachedFormNamePresent:+ detached.all.detachedForm === detached.getElementById("detachedFormId")+ });+ })()+ "#,+ )+ .expect("legacy named access candidate filtering should evaluate");++ assert_eq!(+ result,+ r#"{"windowAppletNameAbsent":true,"allAppletNameAbsent":true,"windowSharedUsesEligibleForm":true,"allSharedUsesEligibleForm":true,"windowAnchorNameAbsent":true,"allAnchorNamePresent":true,"windowImageNamePresent":true,"allImageNamePresent":true,"windowDivNameAbsent":true,"allDivNameAbsent":true,"windowSvgNameAbsent":true,"allSvgNameAbsent":true,"windowAppletIdPresent":true,"allAppletIdPresent":true,"windowSvgIdPresent":true,"allSvgIdPresent":true,"detachedAppletNameAbsent":true,"detachedAppletIdPresent":true,"detachedFormNamePresent":true}"#+ );+}++#[test]+fn window_named_access_returns_a_live_deduplicated_collection_for_multiple_matches() {+ let mut vm = new_parsed_test_vm(+ "https://example.com/",+ "<!doctype html><html><body></body></html>",+ );++ let result = vm+ .eval(+ r#"+ (() => {+ const first = document.createElement("img");+ first.name = "multi";+ const duplicate = document.createElement("form");+ duplicate.id = "multi";+ duplicate.name = "multi";+ const rejected = document.createElement("span");+ rejected.setAttribute("name", "multi");+ const idOnly = document.createElement("div");+ idOnly.id = "multi";+ document.body.append(first, duplicate, rejected, idOnly);++ const collection = window.multi;+ const initial = {+ isCollection: collection instanceof HTMLCollection,+ cachedIdentity: window.multi === collection,+ deduplicatedAndFiltered:+ collection.length === 3 &&+ collection[0] === first &&+ collection[1] === duplicate &&+ collection[2] === idOnly+ };++ const inserted = document.createElement("object");+ inserted.name = "multi";+ document.body.insertBefore(inserted, first);+ const liveAfterInsert =+ collection.length === 4 &&+ collection[0] === inserted &&+ collection[1] === first &&+ collection[2] === duplicate &&+ collection[3] === idOnly;++ first.remove();+ idOnly.id = "";+ inserted.name = "";+ return JSON.stringify({+ ...initial,+ liveAfterInsert,+ liveAfterRemoval:+ collection.length === 1 && collection[0] === duplicate,+ getterCollapsesToElement: window.multi === duplicate+ });+ })()+ "#,+ )+ .expect("window named multi-match collection should evaluate");++ assert_eq!(+ result,+ r#"{"isCollection":true,"cachedIdentity":true,"deduplicatedAndFiltered":true,"liveAfterInsert":true,"liveAfterRemoval":true,"getterCollapsesToElement":true}"#+ );+}+#[test]fn live_html_collection_enforces_brand_and_legacy_named_property_semantics() {let mut vm = new_parsed_test_vm(