From dead4b1585ce3e95ce7fc4e623f5032be2561871 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Wed, 28 Oct 2026 19:06:20 +0800 Subject: [PATCH] fix(dom): share scoped registries across native owners --- moli-renderer-v8/src/custom_elements.rs | 2 + .../src/custom_elements/construction.rs | 240 +++++++++++++--- .../custom_elements/construction_failure.rs | 14 +- .../custom_elements/construction_runtime.rs | 3 +- .../src/custom_elements/definition.rs | 38 +++ .../definition_registry/tests.rs | 8 +- .../src/custom_elements/definition_state.rs | 16 +- .../src/custom_elements/definition_upgrade.rs | 106 ++++---- .../existing_upgrade_invocation.rs | 3 +- .../existing_upgrade_reentry.rs | 13 +- .../custom_elements/parser_handoff_direct.rs | 3 +- .../src/custom_elements/reaction_guards.rs | 3 + .../registry_adoption_retarget.rs | 9 +- .../src/custom_elements/registry_bindings.rs | 118 ++++++++ .../src/custom_elements/registry_runtime.rs | 2 + .../src/custom_elements/registry_tracing.rs | 12 + .../src/document_runtime/document_write.rs | 26 +- .../src/native_bridge/bridge/wrappers.rs | 18 +- .../context_host/bridge_install.rs | 6 + .../src/native_bridge/context_host/core.rs | 114 +++++++- .../src/native_bridge/context_host/mod.rs | 5 + .../context_host/runtime_observable.rs | 4 +- .../src/native_bridge/identity.rs | 7 + .../native_bridge/identity/node_ownership.rs | 98 +++++++ .../identity/registry_references.rs | 135 +++++++++ .../src/runtime/tests/auxiliary_pages.rs | 257 ++++++++++++++++++ .../custom_element_registry_cross_owner.js | 45 +++ ...nt_registry_cross_owner_explicit_realms.js | 39 +++ .../custom_element_registry_cross_owner_gc.js | 34 +++ ...tom_element_registry_cross_owner_realms.js | 39 +++ .../registry_reactions_and_builtins.rs | 2 +- .../registry_scoping_and_fragments.rs | 10 +- 32 files changed, 1311 insertions(+), 118 deletions(-) create mode 100644 moli-renderer-v8/src/custom_elements/registry_bindings.rs create mode 100644 moli-renderer-v8/src/native_bridge/identity/registry_references.rs create mode 100644 moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner.js create mode 100644 moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_explicit_realms.js create mode 100644 moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_gc.js create mode 100644 moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_realms.js diff --git a/moli-renderer-v8/src/custom_elements.rs b/moli-renderer-v8/src/custom_elements.rs index 4c8efba2930..19ddf3241c3 100644 --- a/moli-renderer-v8/src/custom_elements.rs +++ b/moli-renderer-v8/src/custom_elements.rs @@ -124,7 +124,9 @@ mod registry_clone_retarget; pub(crate) use registry_clone_retarget::{ registry_association_retargets_for_clone, registry_association_retargets_for_import_clone, }; +mod registry_bindings; mod registry_install; +pub(crate) use registry_bindings::CustomElementRegistryBindings; pub(crate) use registry_install::{ build_custom_elements_registry_for_window, custom_elements_registry_for_current_realm, rebind_materialized_child_custom_elements_registry, diff --git a/moli-renderer-v8/src/custom_elements/construction.rs b/moli-renderer-v8/src/custom_elements/construction.rs index 6cd2e116f38..a20af32e692 100644 --- a/moli-renderer-v8/src/custom_elements/construction.rs +++ b/moli-renderer-v8/src/custom_elements/construction.rs @@ -1,11 +1,10 @@ -use crate::document_runtime::DomHandle; -use std::collections::HashSet; +use crate::{document_runtime::DomHandle, native_bridge::NativeDomHostId}; +use std::{cell::Cell, collections::HashSet, rc::Rc}; struct PendingConstruction { constructor: v8::Global, wrapper: Option>, - handle: DomHandle, - kind: PendingConstructionKind, + view: Rc, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -14,9 +13,69 @@ enum PendingConstructionKind { SynchronousCreateElement, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum ConstructionState { + Available, + Consumed, + Finished, +} + +#[derive(Clone, Copy)] +pub(crate) struct CustomElementConstructionId { + pub(crate) owner: NativeDomHostId, + pub(crate) handle: DomHandle, +} + +/// A weak view of a construction owned by one native DOM host. The isolate +/// may locate this view while calling super() in another realm; only the +/// owning stack roots values and stores unqualified node state. +pub(super) struct SharedPendingConstruction { + id: CustomElementConstructionId, + constructor: v8::Weak, + registry_realm: v8::Weak, + wrapper: v8::Weak, + kind: PendingConstructionKind, + state: Cell, +} + pub(crate) enum PendingCustomElementConstruction<'s> { - Wrapper(v8::Local<'s, v8::Object>, DomHandle), - AlreadyConstructed(DomHandle), + Wrapper(v8::Local<'s, v8::Object>, CustomElementConstructionId), + AlreadyConstructed(CustomElementConstructionId), +} + +impl SharedPendingConstruction { + pub(super) fn matches( + &self, + scope: &mut v8::PinScope<'_, '_>, + new_target: v8::Local<'_, v8::Function>, + ) -> bool { + self.state.get() != ConstructionState::Finished + && self.registry_realm.to_local(scope) == Some(scope.get_current_context()) + && self + .constructor + .to_local(scope) + .is_some_and(|constructor| constructor.strict_equals(new_target.into())) + } + + pub(super) fn take<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + ) -> Option> { + if self.state.get() == ConstructionState::Consumed { + return Some(PendingCustomElementConstruction::AlreadyConstructed( + self.id, + )); + } + if self.state.get() == ConstructionState::Finished { + return None; + } + let wrapper = self.wrapper.to_local(scope)?; + self.state.set(match self.kind { + PendingConstructionKind::ExistingElementUpgrade => ConstructionState::Consumed, + PendingConstructionKind::SynchronousCreateElement => ConstructionState::Finished, + }); + Some(PendingCustomElementConstruction::Wrapper(wrapper, self.id)) + } } #[derive(Default)] @@ -30,15 +89,18 @@ impl CustomElementConstructionStack { pub(super) fn begin_existing_element_upgrade( &mut self, scope: &mut v8::PinScope<'_, '_>, + owner: NativeDomHostId, + registry_realm: v8::Local<'_, v8::Context>, constructor: v8::Local<'_, v8::Function>, wrapper: v8::Local<'_, v8::Object>, handle: DomHandle, ) { self.begin_with_kind( scope, + CustomElementConstructionId { owner, handle }, + registry_realm, constructor, wrapper, - handle, PendingConstructionKind::ExistingElementUpgrade, ); } @@ -46,15 +108,18 @@ impl CustomElementConstructionStack { pub(super) fn begin_synchronous_create_element( &mut self, scope: &mut v8::PinScope<'_, '_>, + owner: NativeDomHostId, + registry_realm: v8::Local<'_, v8::Context>, constructor: v8::Local<'_, v8::Function>, wrapper: v8::Local<'_, v8::Object>, handle: DomHandle, ) { self.begin_with_kind( scope, + CustomElementConstructionId { owner, handle }, + registry_realm, constructor, wrapper, - handle, PendingConstructionKind::SynchronousCreateElement, ); } @@ -62,17 +127,26 @@ impl CustomElementConstructionStack { fn begin_with_kind( &mut self, scope: &mut v8::PinScope<'_, '_>, + id: CustomElementConstructionId, + registry_realm: v8::Local<'_, v8::Context>, constructor: v8::Local<'_, v8::Function>, wrapper: v8::Local<'_, v8::Object>, - handle: DomHandle, kind: PendingConstructionKind, ) { - self.constructing_handles.insert(handle); + let view = Rc::new(SharedPendingConstruction { + id, + constructor: v8::Weak::new(scope, constructor), + registry_realm: v8::Weak::new(scope, registry_realm), + wrapper: v8::Weak::new(scope, wrapper), + kind, + state: Cell::new(ConstructionState::Available), + }); + super::CustomElementRegistryBindings::for_isolate(scope).register_construction(&view); + self.constructing_handles.insert(id.handle); self.stack.push(PendingConstruction { constructor: v8::Global::new(scope, constructor), wrapper: Some(v8::Global::new(scope, wrapper)), - handle, - kind, + view, }); } @@ -81,9 +155,10 @@ impl CustomElementConstructionStack { if let Some(index) = self .stack .iter() - .rposition(|pending| pending.handle == handle) + .rposition(|pending| pending.view.id.handle == handle) { - self.stack.remove(index); + let pending = self.stack.remove(index); + pending.view.state.set(ConstructionState::Finished); } } @@ -93,21 +168,16 @@ impl CustomElementConstructionStack { new_target: v8::Local<'_, v8::Function>, ) -> Option> { let index = self.stack.iter().rposition(|pending| { - let constructor = v8::Local::new(scope, &pending.constructor); - constructor.strict_equals(new_target.into()) + pending.view.state.get() != ConstructionState::Finished + && v8::Local::new(scope, &pending.constructor).strict_equals(new_target.into()) })?; let pending = &mut self.stack[index]; - let Some(wrapper) = pending.wrapper.take() else { - return Some(PendingCustomElementConstruction::AlreadyConstructed( - pending.handle, - )); - }; - let wrapper = v8::Local::new(scope, &wrapper); - let handle = pending.handle; - if pending.kind == PendingConstructionKind::SynchronousCreateElement { + let result = pending.view.take(scope); + pending.wrapper.take(); + if pending.view.kind == PendingConstructionKind::SynchronousCreateElement { self.stack.remove(index); } - Some(PendingCustomElementConstruction::Wrapper(wrapper, handle)) + result } pub(super) fn has_pending_wrapper_for( @@ -116,36 +186,134 @@ impl CustomElementConstructionStack { new_target: v8::Local<'_, v8::Function>, ) -> bool { self.stack.iter().any(|pending| { - let constructor = v8::Local::new(scope, &pending.constructor); - constructor.strict_equals(new_target.into()) + pending.view.state.get() != ConstructionState::Finished + && v8::Local::new(scope, &pending.constructor).strict_equals(new_target.into()) }) } pub(super) fn is_pending_handle(&self, handle: DomHandle) -> bool { self.constructing_handles.contains(&handle) } - pub(super) fn is_already_constructed(&self, handle: DomHandle) -> bool { - self.stack - .iter() - .any(|pending| pending.handle == handle && pending.wrapper.is_none()) + self.stack.iter().any(|pending| { + pending.view.id.handle == handle + && pending.view.state.get() == ConstructionState::Consumed + }) } - pub(super) fn mark_failed(&mut self, handle: DomHandle) { self.failed_handles.insert(handle); } - pub(super) fn clear_failed(&mut self, handle: DomHandle) { self.failed_handles.remove(&handle); } - pub(super) fn is_failed(&self, handle: DomHandle) -> bool { self.failed_handles.contains(&handle) } - pub(super) fn owns_handle(&self, handle: DomHandle) -> bool { self.constructing_handles.contains(&handle) || self.failed_handles.contains(&handle) - || self.stack.iter().any(|pending| pending.handle == handle) + || self + .stack + .iter() + .any(|pending| pending.view.id.handle == handle) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn constructor<'s>( + _scope: &mut v8::PinScope<'s, '_>, + _args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'s>, + ) { + } + + #[test] + fn shared_construction_views_keep_native_ids_qualified_and_follow_nested_order() { + crate::ensure_v8_for_test(); + let mut isolate = v8::Isolate::new(Default::default()); + let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let other_context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let function = v8::Function::new(scope, constructor).unwrap(); + let wrapper = v8::Object::new(scope); + let source_owner = NativeDomHostId::default(); + let target_owner = NativeDomHostId::default(); + let handle = DomHandle::new(7); + let mut source = CustomElementConstructionStack::default(); + let mut target = CustomElementConstructionStack::default(); + target.begin_existing_element_upgrade( + scope, + target_owner, + context, + function, + wrapper, + handle, + ); + assert!(!source.has_pending_wrapper_for(scope, function)); + let bindings = super::super::CustomElementRegistryBindings::for_isolate(scope); + { + let scope = &mut v8::ContextScope::new(scope, other_context); + assert!( + !bindings.has_pending_construction(scope, function), + "a foreign super constructor must not consume another realm's construction" + ); + } + source.begin_existing_element_upgrade( + scope, + source_owner, + context, + function, + wrapper, + handle, + ); + let Some(PendingCustomElementConstruction::Wrapper(_, id)) = + bindings.take_pending_construction(scope, function) + else { + panic!("nested source construction"); + }; + assert_eq!(id.owner, source_owner); + assert_eq!(id.handle, handle); + assert!(source.is_already_constructed(handle)); + assert!(!target.is_already_constructed(handle)); + source.discard(handle); + let Some(PendingCustomElementConstruction::Wrapper(value, id)) = + bindings.take_pending_construction(scope, function) + else { + panic!("foreign target construction"); + }; + assert_eq!(value, wrapper); + assert_eq!(id.owner, target_owner); + assert_eq!(id.handle, handle); + assert!(target.is_already_constructed(handle)); + assert!(!source.owns_handle(handle)); + assert!(matches!( + bindings.take_pending_construction(scope, function), + Some(PendingCustomElementConstruction::AlreadyConstructed(_)) + )); + target.discard(handle); + assert!(!bindings.has_pending_construction(scope, function)); + target.begin_synchronous_create_element( + scope, + target_owner, + other_context, + function, + wrapper, + handle, + ); + assert!(!bindings.has_pending_construction(scope, function)); + { + let scope = &mut v8::ContextScope::new(scope, other_context); + assert!(bindings.has_pending_construction(scope, function)); + assert!(matches!( + bindings.take_pending_construction(scope, function), + Some(PendingCustomElementConstruction::Wrapper(_, _)) + )); + } + target.discard(handle); } } diff --git a/moli-renderer-v8/src/custom_elements/construction_failure.rs b/moli-renderer-v8/src/custom_elements/construction_failure.rs index 09a5db69d15..4755b3f357e 100644 --- a/moli-renderer-v8/src/custom_elements/construction_failure.rs +++ b/moli-renderer-v8/src/custom_elements/construction_failure.rs @@ -4,7 +4,6 @@ use super::super::{ context_bootstrap::{ dispatch_window_error_event_with_details, new_most_derived_dom_exception_value, }, - document_runtime::DomHandle, exception_reporting::V8ExceptionReport, host::report_event_listener_exception, util::{set_private_value, v8_string, v8str}, @@ -12,6 +11,8 @@ use super::super::{ pub(super) const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT: &str = "__moliCustomElementAlreadyConstructedHandle"; +pub(super) const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT: &str = + "__moliCustomElementAlreadyConstructedOwner"; const CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_MESSAGE: &str = "Custom element constructor already consumed this element"; @@ -96,19 +97,26 @@ fn error_message_for_value( pub(crate) fn throw_already_constructed_custom_element_error( scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, + id: super::construction::CustomElementConstructionId, ) { let message = v8_string(scope, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_MESSAGE) .unwrap_or_else(|| v8::String::empty(scope)); let exception = v8::Exception::type_error(scope, message); if let Ok(object) = v8::Local::::try_from(exception) { - let handle_value = v8::BigInt::new_from_u64(scope, handle.index() as u64); + let handle_value = v8::BigInt::new_from_u64(scope, id.handle.index() as u64); set_private_value( scope, object, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT, handle_value.into(), ); + let owner_value = v8::BigInt::new_from_u64(scope, id.owner.get()); + set_private_value( + scope, + object, + CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT, + owner_value.into(), + ); } scope.throw_exception(exception); } diff --git a/moli-renderer-v8/src/custom_elements/construction_runtime.rs b/moli-renderer-v8/src/custom_elements/construction_runtime.rs index 593107219f3..35d9515ed3e 100644 --- a/moli-renderer-v8/src/custom_elements/construction_runtime.rs +++ b/moli-renderer-v8/src/custom_elements/construction_runtime.rs @@ -43,9 +43,10 @@ pub(super) fn create_custom_element_for_registry_key<'s>( let wrapper = unsafe { &mut *host_ptr } .native_bridge_mut() .wrap_handle(scope, host_ptr, handle)?; + let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id(); unsafe { &mut *host_ptr } .custom_elements_mut_for_registry_key(registry_key) - .begin_create_element_construction(scope, constructor, wrapper, handle); + .begin_create_element_construction(scope, construction_owner, constructor, wrapper, handle); let initial_owner_document = unsafe { &*host_ptr } .dom_host() diff --git a/moli-renderer-v8/src/custom_elements/definition.rs b/moli-renderer-v8/src/custom_elements/definition.rs index e3f45c81ca9..bf32c14d3b9 100644 --- a/moli-renderer-v8/src/custom_elements/definition.rs +++ b/moli-renderer-v8/src/custom_elements/definition.rs @@ -2,6 +2,7 @@ use super::super::document_runtime::DomHandle; use super::construction::CustomElementConstructionStack; pub(crate) use super::definition_error::CustomElementDefineError; use crate::dom::custom_elements::is_valid_custom_element_name as is_valid_dom_custom_element_name; +use crate::native_bridge::NativeDomHostId; use moli_dom::native::DomStringValue; use std::{ cell::{Cell, RefCell}, @@ -51,6 +52,39 @@ pub(crate) struct CustomElementRegistryData { pub(super) definition_is_running: Cell, pub(super) roots: RefCell>, pub(super) retired: Cell, + associated_documents: RefCell>, + shared_native_owners: Cell, +} + +#[derive(Clone, Copy, Eq, PartialEq, Hash)] +pub(crate) struct RegistryAssociatedDocument { + pub(crate) owner: NativeDomHostId, + pub(crate) document: DomHandle, +} + +impl CustomElementRegistryData { + pub(crate) fn mark_shared_native_owners(&self) { + self.shared_native_owners.set(true); + } + pub(crate) fn has_shared_native_owners(&self) -> bool { + self.shared_native_owners.get() + } + pub(crate) fn associate_document( + &self, + owner: NativeDomHostId, + document: DomHandle, + retarget: bool, + ) { + let key = RegistryAssociatedDocument { owner, document }; + let mut documents = self.associated_documents.borrow_mut(); + if retarget || !documents.contains_key(&key) { + documents.insert(key, ()); + } + } + + pub(crate) fn associated_documents(&self) -> Vec { + self.associated_documents.borrow().keys().copied().collect() + } } // A registry's definitions and promises can be shared by different native DOM @@ -88,6 +122,10 @@ impl CustomElementStore { pub(crate) fn retire_execution_state(&mut self) { self.registry.retire(); + self.retire_native_construction_state(); + } + + pub(crate) fn retire_native_construction_state(&mut self) { self.construction_stack = CustomElementConstructionStack::default(); } diff --git a/moli-renderer-v8/src/custom_elements/definition_registry/tests.rs b/moli-renderer-v8/src/custom_elements/definition_registry/tests.rs index 52bb7d95383..e16b3a0bf87 100644 --- a/moli-renderer-v8/src/custom_elements/definition_registry/tests.rs +++ b/moli-renderer-v8/src/custom_elements/definition_registry/tests.rs @@ -56,7 +56,13 @@ fn registry_data_shares_definitions_and_promises_without_sharing_native_handles( let pending_handle = DomHandle::new(9); let wrapper = v8::Object::new(scope); - source.begin_construction(scope, constructor, wrapper, pending_handle); + source.begin_construction( + scope, + crate::native_bridge::NativeDomHostId::default(), + constructor, + wrapper, + pending_handle, + ); assert!(source.has_pending_wrapper_for(scope, constructor)); assert!(!target.has_pending_wrapper_for(scope, constructor)); source.mark_failed_construction_handle(pending_handle); diff --git a/moli-renderer-v8/src/custom_elements/definition_state.rs b/moli-renderer-v8/src/custom_elements/definition_state.rs index 6e2aa51db37..c462b3dbab6 100644 --- a/moli-renderer-v8/src/custom_elements/definition_state.rs +++ b/moli-renderer-v8/src/custom_elements/definition_state.rs @@ -15,23 +15,35 @@ impl CustomElementStore { pub(crate) fn begin_construction( &mut self, scope: &mut v8::PinScope<'_, '_>, + owner: crate::native_bridge::NativeDomHostId, constructor: v8::Local<'_, v8::Function>, wrapper: v8::Local<'_, v8::Object>, handle: DomHandle, ) { - self.construction_stack - .begin_existing_element_upgrade(scope, constructor, wrapper, handle); + let realm = self.registry.construction_realm(scope); + self.construction_stack.begin_existing_element_upgrade( + scope, + owner, + realm, + constructor, + wrapper, + handle, + ); } pub(crate) fn begin_create_element_construction( &mut self, scope: &mut v8::PinScope<'_, '_>, + owner: crate::native_bridge::NativeDomHostId, constructor: v8::Local<'_, v8::Function>, wrapper: v8::Local<'_, v8::Object>, handle: DomHandle, ) { + let realm = self.registry.construction_realm(scope); self.construction_stack.begin_synchronous_create_element( scope, + owner, + realm, constructor, wrapper, handle, diff --git a/moli-renderer-v8/src/custom_elements/definition_upgrade.rs b/moli-renderer-v8/src/custom_elements/definition_upgrade.rs index 3f8c86ed81b..8adf44e26bb 100644 --- a/moli-renderer-v8/src/custom_elements/definition_upgrade.rs +++ b/moli-renderer-v8/src/custom_elements/definition_upgrade.rs @@ -1,13 +1,10 @@ use super::element_state::definition_name_for_handle; use super::reactions::{CustomElementReaction, enqueue_custom_element_reaction}; -use super::registry_roots::{ - is_shadow_including_rooted_in_browsing_context_document, shadow_including_root_document_handle, -}; +use super::registry_roots::is_shadow_including_rooted_in_browsing_context_document; use super::traversal::shadow_including_subtree_handles; use super::with_custom_element_reaction_scope; use super::{CustomElementRegistryAssociation, CustomElementRegistryKey}; use crate::{document_runtime::DomHandle, native_bridge::PageScriptHost}; -use std::collections::HashSet; pub(crate) fn upgrade_existing_definition_for_child( scope: &mut v8::PinScope<'_, '_>, @@ -46,65 +43,64 @@ pub(crate) fn upgrade_existing_definition_for_registry( registry_key: CustomElementRegistryKey, definition_name: &str, ) { - let handles = matching_definition_handles_for_registry_in_upgrade_order( - host_ptr, - registry_key, - definition_name, - ); - with_custom_element_reaction_scope(scope, host_ptr, |scope| { - for handle in handles { - enqueue_custom_element_reaction( - scope, - host_ptr, - handle, - CustomElementReaction::Upgrade, - ); - } - }); -} - -fn matching_definition_handles_for_registry_in_upgrade_order( - host_ptr: *mut PageScriptHost, - registry_key: CustomElementRegistryKey, - definition_name: &str, -) -> Vec { let host = unsafe { &*host_ptr }; - let target_association = CustomElementRegistryAssociation::Registry(registry_key); - let mut documents = Vec::new(); - let mut seen_documents = HashSet::new(); - for (handle, association) in host.custom_element_registry_associations_in_order() { - if association != target_association { - continue; - } - let Some(document) = shadow_including_root_document_handle(host.dom_host(), handle) else { + let Some(data) = host + .custom_elements_for_registry_key(registry_key) + .map(|store| store.registry_data()) + else { + return; + }; + let bindings = host.custom_element_registry_bindings.clone(); + let mut candidates = Vec::new(); + for associated in data.associated_documents() { + let Some(owner) = bindings + .as_ref() + .and_then(|bindings| bindings.host(associated.owner)) + else { continue; }; - if !is_shadow_including_rooted_in_browsing_context_document(host, document) { + let target = owner.as_ptr(); + let target_host = unsafe { &*target }; + if target_host.browsing_context_is_closed() + || target_host.context_host_lifecycle_handle().get() + != crate::util::ContextHostLifecycle::Active + || !is_shadow_including_rooted_in_browsing_context_document( + target_host, + associated.document, + ) + { continue; } - if seen_documents.insert(document) { - documents.push(document); - } + let handles = shadow_including_subtree_handles(target, associated.document) + .into_iter() + .filter(|handle| { + target_host.effective_custom_element_registry_association(*handle) + == CustomElementRegistryAssociation::Registry(registry_key) + }) + .filter(|handle| { + definition_name_for_handle(target, *handle).as_deref() == Some(definition_name) + }) + .collect::>(); + candidates.push((owner, handles)); } - - let mut handles = Vec::new(); - let mut seen_handles = HashSet::new(); - for document in documents { - for handle in shadow_including_subtree_handles(host_ptr, document) { - if !seen_handles.insert(handle) { - continue; - } - if unsafe { &*host_ptr }.effective_custom_element_registry_association(handle) - != target_association - { - continue; - } - if definition_name_for_handle(host_ptr, handle).as_deref() == Some(definition_name) { - handles.push(handle); - } + // Keep native owners pinned for this reaction turn. Their local handles + // never enter another owner's store or reaction queue. + for (owner, handles) in candidates { + let target = owner.as_ptr(); + if unsafe { &*target }.browsing_context_is_closed() { + continue; } + with_custom_element_reaction_scope(scope, target, |scope| { + for handle in handles { + enqueue_custom_element_reaction( + scope, + target, + handle, + CustomElementReaction::Upgrade, + ); + } + }); } - handles } fn collect_matching_definition_handles( diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs index e02693dbe36..37816528ddc 100644 --- a/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs +++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs @@ -26,9 +26,10 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>( let initial_attributes = observed_attributes_with_current_values(host_ptr, handle, definition_name); enqueue_existing_upgrade_callbacks(scope, host_ptr, handle, initial_attributes); + let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id(); unsafe { &mut *host_ptr } .custom_elements_mut_for_node_handle(handle) - .begin_construction(scope, constructor, wrapper, handle); + .begin_construction(scope, construction_owner, constructor, wrapper, handle); let _dynamic_markup = enter_upgrade_dynamic_markup_insertion(host_ptr, handle); let invocation = invoke_custom_element_constructor(scope, host_ptr, constructor); match invocation { diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_reentry.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_reentry.rs index cc33ffbdf06..0935f86164e 100644 --- a/moli-renderer-v8/src/custom_elements/existing_upgrade_reentry.rs +++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_reentry.rs @@ -1,4 +1,6 @@ -use super::construction_failure::CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT; +use super::construction_failure::{ + CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_HANDLE_SLOT, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT, +}; use super::super::{ document_runtime::DomHandle, native_bridge::PageScriptHost, util::get_private_value, @@ -14,7 +16,8 @@ pub(super) fn already_constructed_reentry_consumed_pending_handle<'s>( ) -> bool { let host = unsafe { &*host_ptr }; let current_registry_key = host.custom_element_registry_key_for_owned_handle(handle); - already_constructed_error_handle(scope, exception) == Some(handle) + already_constructed_error_handle(scope, exception, host.custom_element_registry_owner_id()) + == Some(handle) && host .custom_elements_for_node_handle(handle) .is_some_and(|store| store.pending_construction_is_already_constructed(handle)) @@ -29,8 +32,14 @@ pub(super) fn already_constructed_reentry_consumed_pending_handle<'s>( fn already_constructed_error_handle<'s>( scope: &mut v8::PinScope<'s, '_>, exception: v8::Local<'s, v8::Value>, + owner: crate::native_bridge::NativeDomHostId, ) -> Option { let object = v8::Local::::try_from(exception).ok()?; + let marker = get_private_value(scope, object, CUSTOM_ELEMENT_ALREADY_CONSTRUCTED_OWNER_SLOT)?; + let marker = v8::Local::::try_from(marker).ok()?.u64_value(); + if marker != (owner.get(), true) { + return None; + } let value = get_private_value( scope, object, diff --git a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs index ac7cc7c9615..3fac997d312 100644 --- a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs +++ b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs @@ -64,9 +64,10 @@ pub(super) fn construct_parser_created_custom_element_direct( return Some(handle); }; + let construction_owner = unsafe { &*host_ptr }.custom_element_registry_owner_id(); unsafe { &mut *host_ptr } .custom_elements_mut_for_registry_key(registry_key) - .begin_create_element_construction(scope, constructor, wrapper, handle); + .begin_create_element_construction(scope, construction_owner, constructor, wrapper, handle); let initial_owner_document = unsafe { &*host_ptr } .dom_host() diff --git a/moli-renderer-v8/src/custom_elements/reaction_guards.rs b/moli-renderer-v8/src/custom_elements/reaction_guards.rs index d91744fad09..830aae63ed3 100644 --- a/moli-renderer-v8/src/custom_elements/reaction_guards.rs +++ b/moli-renderer-v8/src/custom_elements/reaction_guards.rs @@ -22,6 +22,9 @@ impl Drop for CustomElementReactionGuard { impl Drop for CustomElementReactionScope<'_, '_, '_> { fn drop(&mut self) { + unsafe { &mut *self.host_ptr } + .native_bridge_mut() + .synchronize_custom_element_registry_references(self.scope, self.host_ptr); super::reactions::flush_current_custom_element_reaction_queue(self.scope, self.host_ptr); } } diff --git a/moli-renderer-v8/src/custom_elements/registry_adoption_retarget.rs b/moli-renderer-v8/src/custom_elements/registry_adoption_retarget.rs index 6eca61906c7..2692de83546 100644 --- a/moli-renderer-v8/src/custom_elements/registry_adoption_retarget.rs +++ b/moli-renderer-v8/src/custom_elements/registry_adoption_retarget.rs @@ -80,7 +80,14 @@ fn should_preserve_same_document_registry_association( host_ptr: *mut PageScriptHost, root: DomHandle, ) -> bool { - let host = unsafe { &*host_ptr }.dom_host(); + let runtime = unsafe { &*host_ptr }; + let host = runtime.dom_host(); + if host + .owner_document_handle(root) + .is_some_and(|document| runtime.document_uses_scoped_custom_element_registries(document)) + { + return true; + } host.node(root) .and_then(Node::parent_node) .is_some_and(|parent| { diff --git a/moli-renderer-v8/src/custom_elements/registry_bindings.rs b/moli-renderer-v8/src/custom_elements/registry_bindings.rs new file mode 100644 index 00000000000..05ce938f4a1 --- /dev/null +++ b/moli-renderer-v8/src/custom_elements/registry_bindings.rs @@ -0,0 +1,118 @@ +use std::{ + cell::RefCell, + collections::HashMap, + rc::{Rc, Weak}, +}; + +use super::{CustomElementRegistryKey, definition::CustomElementRegistryData}; +use crate::native_bridge::{NativeDomHostId, PageScriptHost}; + +struct RegistryBinding { + wrapper: v8::Weak, + data: Weak, +} + +/// Isolate-local discovery only. Neither the native owner nor any JS realm is +/// kept alive by this index. DOM associations own their V8-traced references. +#[derive(Default)] +pub(crate) struct CustomElementRegistryBindings { + registries: RefCell>, + hosts: RefCell>>>, + constructions: RefCell>>, +} + +impl CustomElementRegistryBindings { + pub(super) fn register_construction( + &self, + view: &Rc, + ) { + let mut constructions = self.constructions.borrow_mut(); + constructions.retain(|view| view.strong_count() != 0); + constructions.push(Rc::downgrade(view)); + } + + pub(crate) fn has_pending_construction( + &self, + scope: &mut v8::PinScope<'_, '_>, + constructor: v8::Local<'_, v8::Function>, + ) -> bool { + self.constructions + .borrow() + .iter() + .rev() + .filter_map(Weak::upgrade) + .any(|view| view.matches(scope, constructor)) + } + + pub(crate) fn take_pending_construction<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + constructor: v8::Local<'_, v8::Function>, + ) -> Option> { + let view = self + .constructions + .borrow() + .iter() + .rev() + .filter_map(Weak::upgrade) + .find(|view| view.matches(scope, constructor))?; + view.take(scope) + } + + pub(crate) fn for_isolate(scope: &mut v8::PinScope<'_, '_>) -> Rc { + type Store = Rc; + if let Some(store) = scope.get_slot::() { + return store.clone(); + } + let store = Store::default(); + scope.set_slot(store.clone()); + store + } + + pub(crate) fn register_host(&self, id: NativeDomHostId, host: &Rc>) { + let mut hosts = self.hosts.borrow_mut(); + hosts.retain(|_, owner| owner.strong_count() != 0); + hosts.insert(id, Rc::downgrade(host)); + } + + pub(crate) fn host(&self, id: NativeDomHostId) -> Option>> { + self.hosts.borrow().get(&id)?.upgrade() + } + + pub(crate) fn register( + &self, + scope: &mut v8::PinScope<'_, '_>, + key: CustomElementRegistryKey, + wrapper: v8::Local<'_, v8::Object>, + data: &Rc, + ) { + let mut registries = self.registries.borrow_mut(); + if registries.len().is_multiple_of(64) { + registries.retain(|_, binding| { + !binding.wrapper.is_empty() && binding.data.strong_count() != 0 + }); + } + registries.insert( + key, + RegistryBinding { + wrapper: v8::Weak::new(scope, wrapper), + data: Rc::downgrade(data), + }, + ); + } + + pub(crate) fn data( + &self, + key: CustomElementRegistryKey, + ) -> Option> { + self.registries.borrow().get(&key)?.data.upgrade() + } + + pub(crate) fn wrapper<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + key: CustomElementRegistryKey, + ) -> Option> { + self.registries.borrow().get(&key)?.wrapper.to_local(scope) + } +} diff --git a/moli-renderer-v8/src/custom_elements/registry_runtime.rs b/moli-renderer-v8/src/custom_elements/registry_runtime.rs index eb1ef131e4d..eb06adf2ed4 100644 --- a/moli-renderer-v8/src/custom_elements/registry_runtime.rs +++ b/moli-renderer-v8/src/custom_elements/registry_runtime.rs @@ -73,6 +73,8 @@ pub(crate) fn bind_custom_elements_registry_data<'s>( } let scope = &mut v8::ContextScope::new(scope, owner); data.bind_wrapper(scope, registry); + let bindings = super::CustomElementRegistryBindings::for_isolate(scope); + bindings.register(scope, key, registry, &data); } pub(crate) fn mark_scoped_custom_elements_registry( diff --git a/moli-renderer-v8/src/custom_elements/registry_tracing.rs b/moli-renderer-v8/src/custom_elements/registry_tracing.rs index 9b33fb54220..d86fa6184a9 100644 --- a/moli-renderer-v8/src/custom_elements/registry_tracing.rs +++ b/moli-renderer-v8/src/custom_elements/registry_tracing.rs @@ -50,6 +50,18 @@ impl CustomElementRegistryData { set_private_value(scope, registry, ROOTS_SLOT, anchor.into()); } + pub(super) fn construction_realm<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + ) -> v8::Local<'s, v8::Context> { + self.roots + .borrow() + .as_ref() + .and_then(|roots| roots.anchor.to_local(scope)) + .and_then(|anchor| anchor.get_creation_context(scope)) + .unwrap_or_else(|| scope.get_current_context()) + } + pub(super) fn belongs_to_realm(&self, realm_token: RuntimeObservableContextToken) -> bool { self.roots .borrow() diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs index d4bcdc2a960..e910639994a 100644 --- a/moli-renderer-v8/src/document_runtime/document_write.rs +++ b/moli-renderer-v8/src/document_runtime/document_write.rs @@ -608,7 +608,11 @@ impl DocumentRuntime { ) -> Option { let first_node_index = self.dom_host().dom().len(); let parser = HtmlParser::with_scripting_enabled(scripting_enabled); - let context_node = context_handle.and_then(|element| self.dom_host().node(element)); + // Tokenization uses the host of a ShadowRoot, while the registry + // comes from the actual fragment context. + let parsing_context = context_handle + .map(|context| self.dom_host().shadow_root_host(context).unwrap_or(context)); + let context_node = parsing_context.and_then(|element| self.dom_host().node(element)); let context_namespace = context_node .and_then(Node::namespace) .unwrap_or("http://www.w3.org/1999/xhtml") @@ -618,7 +622,7 @@ impl DocumentRuntime { .unwrap_or("body") .to_owned(); let context = - HtmlFragmentContext::new(context_handle, &context_namespace, &context_local_name); + HtmlFragmentContext::new(parsing_context, &context_namespace, &context_local_name); let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml" && context_local_name.eq_ignore_ascii_case("frameset"); let registry_association = match context_handle { @@ -796,7 +800,11 @@ impl DocumentRuntime { markup: &DomStringValue, custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming, ) -> Result, XmlFragmentParseError> { - let parsed = XmlParser.parse_fragment(self.dom_host(), context_handle, markup)?; + let parsing_context = self + .dom_host() + .shadow_root_host(context_handle) + .unwrap_or(context_handle); + let parsed = XmlParser.parse_fragment(self.dom_host(), parsing_context, markup)?; let first_node_index = self.dom_host().dom().len(); let registry_association = self.fragment_context_custom_element_registry_association(host_ptr, context_handle); @@ -904,7 +912,7 @@ impl DocumentRuntime { handle: DomHandle, html: &DomStringValue, ) -> Result { - let context = self.dom_host().shadow_root_host(handle).unwrap_or(handle); + let context = handle; let target = self .dom_host() .node(handle) @@ -1104,6 +1112,8 @@ impl DocumentRuntime { DomHandle, ) -> bool, ) -> Result { + let registry_association = + self.fragment_context_custom_element_registry_association(host_ptr, context_handle); let context_is_element = self .dom_host() .node(context_handle) @@ -1117,7 +1127,13 @@ impl DocumentRuntime { .node(context_handle) .is_some_and(|node| node.is_html_element_named("html")); let context_handle = if !context_is_element || context_is_html_root { - self.create_fragment_body_context(document_handle) + let body = self.create_fragment_body_context(document_handle); + self.set_fragment_root_custom_element_registry_association( + host_ptr, + body, + registry_association, + ); + body } else { context_handle }; diff --git a/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs b/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs index 5b3537ab6bb..1a5311f2ecc 100644 --- a/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs +++ b/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs @@ -41,6 +41,15 @@ impl NativeDomBridge { self.wrap_bridge_handle(scope, host_ptr, BridgeHandle::Node(handle)) } + pub(crate) fn synchronize_custom_element_registry_references( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + ) { + self.identity + .synchronize_registry_references(scope, host_ptr); + } + pub(crate) fn cached_handle_wrapper<'s>( &self, scope: &mut v8::PinScope<'s, '_>, @@ -74,7 +83,14 @@ impl NativeDomBridge { host_ptr: *mut PageScriptHost, handle: BridgeHandle, ) -> Option> { - self.materialize_bridge_wrapper(scope, host_ptr, handle, BridgeWrapperIdentity::Canonical) + let result = self.materialize_bridge_wrapper( + scope, + host_ptr, + handle, + BridgeWrapperIdentity::Canonical, + ); + self.synchronize_custom_element_registry_references(scope, host_ptr); + result } fn materialize_bridge_wrapper<'s, 'i>( diff --git a/moli-renderer-v8/src/native_bridge/context_host/bridge_install.rs b/moli-renderer-v8/src/native_bridge/context_host/bridge_install.rs index 7c81a800a45..733d4732960 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/bridge_install.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/bridge_install.rs @@ -80,6 +80,12 @@ impl PageScriptHost { global: v8::Local<'s, v8::Object>, ) -> Result { let host_ptr: *mut PageScriptHost = (*host_rc).as_ptr(); + let bindings = crate::custom_elements::CustomElementRegistryBindings::for_isolate(scope); + bindings.register_host( + unsafe { &*host_ptr }.custom_element_registry_owner_id(), + host_rc, + ); + unsafe { &mut *host_ptr }.custom_element_registry_bindings = Some(bindings); #[cfg(test)] let bridge_ref_count = unsafe { &*host_ptr }.bridge_ref_count.clone(); #[cfg(not(test))] diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index 7791b6107be..fe6ff3663ad 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -422,10 +422,14 @@ impl PageScriptHost { child_custom_elements: HashMap::new(), scoped_custom_elements: HashMap::new(), foreign_custom_elements: HashMap::new(), + custom_element_registry_bindings: None, + custom_element_registry_references_enabled: Cell::new(false), + custom_element_registry_references_version: Cell::new(None), parser_defined_autonomous_custom_elements: VecDeque::new(), parser_custom_element_handoff_replacements: HashMap::new(), scoped_custom_element_registry_wrappers: HashMap::new(), custom_element_registry_associations: LinkedHashMap::new(), + scoped_custom_element_registry_documents: HashSet::new(), next_scoped_custom_elements_registry_id: 1, observers: ObserverStore::default(), child_browsing_contexts: IndexMap::new(), @@ -2156,9 +2160,30 @@ impl PageScriptHost { if id.is_multiple_of(64) { self.compact_scoped_custom_element_registry_wrappers(); } + let document = self + .current_runtime_window_execution_context_identity(scope) + .and_then(|identity| match identity.dispatch_scope() { + OwnerDispatchScope::Child(handle) => { + self.child_browsing_context_document_handle(handle) + } + OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => { + Some(self.document_handle()) + } + }) + .unwrap_or_else(|| self.document_handle()); + self.scoped_custom_element_registry_documents + .insert(document); Some(id) } + pub(crate) fn document_uses_scoped_custom_element_registries( + &self, + document: DomHandle, + ) -> bool { + self.scoped_custom_element_registry_documents + .contains(&document) + } + fn compact_scoped_custom_element_registry_wrappers(&mut self) { self.scoped_custom_element_registry_wrappers .retain(|_, registry| !registry.is_empty()); @@ -2172,6 +2197,61 @@ impl PageScriptHost { self.scoped_custom_elements.remove(&id); } + fn bind_custom_element_registry_association( + &mut self, + handle: DomHandle, + association: CustomElementRegistryAssociation, + retarget: bool, + ) { + let CustomElementRegistryAssociation::Registry(key) = association else { + return; + }; + let document = if self + .dom_host() + .node(handle) + .is_some_and(|node| node.is_document()) + { + handle + } else { + let Some(document) = self.dom_host().owner_document_handle(handle) else { + return; + }; + document + }; + if key.is_scoped() + && self + .dom_host() + .node(handle) + .is_some_and(|node| node.is_element()) + && association + != self.default_custom_element_registry_association_for_document(document) + { + self.scoped_custom_element_registry_documents + .insert(document); + } + let owner = self.custom_element_registry_owner_id(); + let data = self + .custom_elements_mut_for_registry_key(key) + .registry_data(); + data.associate_document(owner, document, retarget); + if key.owner() != owner { + data.mark_shared_native_owners(); + if let Some(source) = self + .custom_element_registry_bindings + .as_ref() + .and_then(|bindings| bindings.host(key.owner())) + { + let source = unsafe { &*source.as_ptr() }; + source.custom_element_registry_references_enabled.set(true); + source.custom_element_registry_references_version.set(None); + } + } + if data.has_shared_native_owners() { + self.custom_element_registry_references_enabled.set(true); + } + self.custom_element_registry_references_version.set(None); + } + pub(crate) fn set_custom_element_registry_association( &mut self, handle: DomHandle, @@ -2180,6 +2260,7 @@ impl PageScriptHost { if self.custom_element_registry_associations.get(&handle) == Some(&association) { return; } + self.bind_custom_element_registry_association(handle, association, false); self.custom_element_registry_associations .insert(handle, association); } @@ -2194,6 +2275,11 @@ impl PageScriptHost { // LinkedHashMap::insert moves existing entries to the back in O(1), // preserving last-retarget order without scanning unrelated entries. for retarget in retargets { + self.bind_custom_element_registry_association( + retarget.handle, + retarget.association, + true, + ); self.custom_element_registry_associations .insert(retarget.handle, retarget.association); } @@ -2220,10 +2306,15 @@ impl PageScriptHost { &mut self, child_handle: DomHandle, ) { + self.custom_element_registry_references_version.set(None); let document_handle = self .child_browsing_context_document_handles .get(&child_handle) .copied(); + if let Some(document) = document_handle { + self.scoped_custom_element_registry_documents + .remove(&document); + } let stale_handles = self .custom_element_registry_associations .iter() @@ -2258,6 +2349,9 @@ impl PageScriptHost { &mut self, document_handle: DomHandle, ) { + self.scoped_custom_element_registry_documents + .remove(&document_handle); + self.custom_element_registry_references_version.set(None); let stale_handles = self .custom_element_registry_associations .keys() @@ -2455,7 +2549,10 @@ impl PageScriptHost { key: CustomElementRegistryKey, ) -> Option> { if key.owner() != self.custom_element_registry_owner_id() { - return None; + return self + .custom_element_registry_bindings + .as_ref()? + .wrapper(scope, key); } match key.kind() { CustomElementRegistryKind::Global => { @@ -2522,7 +2619,14 @@ impl PageScriptHost { key: CustomElementRegistryKey, ) -> &mut CustomElementStore { if key.owner() != self.custom_element_registry_owner_id() { - return self.foreign_custom_elements.entry(key).or_default(); + let data = self + .custom_element_registry_bindings + .as_ref() + .and_then(|bindings| bindings.data(key)); + return self.foreign_custom_elements.entry(key).or_insert_with(|| { + data.map(CustomElementStore::for_registry) + .unwrap_or_default() + }); } match key.kind() { CustomElementRegistryKind::Global => &mut self.custom_elements, @@ -2740,6 +2844,9 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, new_target: v8::Local<'_, v8::Function>, ) -> Option> { + if let Some(bindings) = &self.custom_element_registry_bindings { + return bindings.take_pending_construction(scope, new_target); + } self.custom_element_store_entries_mut() .find_map(|store| store.take_pending_wrapper_for(scope, new_target)) } @@ -2749,6 +2856,9 @@ impl PageScriptHost { scope: &mut v8::PinScope<'_, '_>, new_target: v8::Local<'_, v8::Function>, ) -> bool { + if let Some(bindings) = &self.custom_element_registry_bindings { + return bindings.has_pending_construction(scope, new_target); + } if self .custom_elements .has_pending_wrapper_for(scope, new_target) diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index a8ee6f4dce8..03ebd615119 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -937,6 +937,10 @@ pub(crate) struct PageScriptHost { child_custom_elements: HashMap, scoped_custom_elements: HashMap, foreign_custom_elements: HashMap, + pub(crate) custom_element_registry_bindings: + Option>, + pub(in crate::native_bridge) custom_element_registry_references_enabled: Cell, + pub(in crate::native_bridge) custom_element_registry_references_version: Cell>, parser_defined_autonomous_custom_elements: VecDeque, // Parser-created direct construction leaves html5ever's open-stack // placeholder alive but detached. The runtime-visible element is the @@ -944,6 +948,7 @@ pub(crate) struct PageScriptHost { // that result before the next script observes the DOM. parser_custom_element_handoff_replacements: HashMap, scoped_custom_element_registry_wrappers: HashMap>, + scoped_custom_element_registry_documents: HashSet, custom_element_registry_associations: LinkedHashMap, next_scoped_custom_elements_registry_id: u32, diff --git a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs index 1adf4197d93..fcf7cc14da9 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs @@ -225,10 +225,12 @@ impl PageScriptHost { for store in std::iter::once(&mut self.custom_elements) .chain(self.child_custom_elements.values_mut()) .chain(self.scoped_custom_elements.values_mut()) - .chain(self.foreign_custom_elements.values_mut()) { store.retire_execution_state(); } + for store in self.foreign_custom_elements.values_mut() { + store.retire_native_construction_state(); + } drop(std::mem::take(&mut self.custom_element_reactions)); drop(std::mem::take(&mut self.observers)); drop(std::mem::take(&mut self.child_window_proxy_records)); diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs index 4aed8bbbfd6..9056a962c97 100644 --- a/moli-renderer-v8/src/native_bridge/identity.rs +++ b/moli-renderer-v8/src/native_bridge/identity.rs @@ -20,6 +20,7 @@ use dense_reflector_map::DenseReflectorMap; mod dense_reflector_map; mod node_ownership; +mod registry_references; #[cfg(test)] mod wrapper_cache_tests; pub(in crate::native_bridge) use node_ownership::resolve_object_node_ownership; @@ -582,6 +583,12 @@ struct IsolatedWorldWrapperCaches { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) struct NativeDomHostId(NonZeroU64); +impl NativeDomHostId { + pub(crate) fn get(self) -> u64 { + self.0.get() + } +} + impl Default for NativeDomHostId { fn default() -> Self { static NEXT: AtomicU64 = AtomicU64::new(1); diff --git a/moli-renderer-v8/src/native_bridge/identity/node_ownership.rs b/moli-renderer-v8/src/native_bridge/identity/node_ownership.rs index 0f10392b638..b9966113c09 100644 --- a/moli-renderer-v8/src/native_bridge/identity/node_ownership.rs +++ b/moli-renderer-v8/src/native_bridge/identity/node_ownership.rs @@ -6,6 +6,8 @@ use crate::{document_runtime::DomHandle, util}; const ANCHOR_SLOT: &str = "__moliNativeNodeOwnership"; const OWNER_SLOT: &str = "__moliNativeNodeCurrentOwner"; const HANDLE_SLOT: &str = "__moliNativeNodeCurrentHandle"; +const DOCUMENT_SLOT: &str = "__moliNativeNodeOwnerDocument"; +const REGISTRIES_SLOT: &str = "__moliNativeNodeRegistryReferences"; pub(in crate::native_bridge) fn resolve_object_node_ownership( scope: &mut v8::PinScope<'_, '_>, @@ -43,6 +45,38 @@ struct NodeLocation { } impl NodeOwnership { + pub(super) fn existing_anchor<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + ) -> Option> { + self.location.borrow().anchor.to_local(scope) + } + + pub(super) fn trace_document(&self, scope: &mut v8::PinScope<'_, '_>, document: &Self) { + let anchor = self + .anchor(scope) + .expect("live node has an ownership anchor"); + let document = document + .anchor(scope) + .expect("live Document has an ownership anchor"); + util::set_private_value(scope, anchor, DOCUMENT_SLOT, document.into()); + } + + pub(super) fn trace_registries( + &self, + scope: &mut v8::PinScope<'_, '_>, + values: &[v8::Local<'_, v8::Value>], + ) { + let Some(anchor) = self.existing_anchor(scope) else { + return; + }; + let value = if values.is_empty() { + v8::undefined(scope).into() + } else { + v8::Array::new_with_elements(scope, values).into() + }; + util::set_private_value(scope, anchor, REGISTRIES_SLOT, value); + } fn new( scope: &mut v8::PinScope<'_, '_>, owner: v8::Local<'_, v8::Context>, @@ -85,6 +119,39 @@ impl NodeOwnership { let value = v8::BigInt::new_from_u64(scope, location.handle.index() as u64); util::set_private_value(scope, anchor, HANDLE_SLOT, value.into()); location.anchor = v8::Weak::new(scope, anchor); + let handle = location.handle; + drop(location); + if let Some(host) = util::context_host_ptr_from_context_slot(owner) { + unsafe { &*host } + .custom_element_registry_references_version + .set(None); + if unsafe { &*host } + .custom_element_registry_references_enabled + .get() + { + let document = unsafe { &*host } + .dom_host() + .owner_document_handle(handle) + .filter(|document| *document != handle) + .and_then(|document| { + unsafe { &*host } + .bridge + .identity + .node_ownership + .get(&document) + .cloned() + }); + if let Some(document) = document.and_then(|document| document.anchor(scope)) { + util::set_private_value(scope, anchor, DOCUMENT_SLOT, document.into()); + } + let values = + super::registry_references::registry_values_for_subtree(scope, host, handle); + if !values.is_empty() { + let values = v8::Array::new_with_elements(scope, &values); + util::set_private_value(scope, anchor, REGISTRIES_SLOT, values.into()); + } + } + } Some(anchor) } @@ -109,6 +176,19 @@ impl NodeOwnership { // a V8-traced edge to the new owner before replacing the weak location. let mut location = self.location.borrow_mut(); if let Some(anchor) = location.anchor.to_local(scope) { + // The new native tree determines registry and Document edges. + // Do not retain the previous Document through a transferred view. + if util::get_private_object(scope, anchor, DOCUMENT_SLOT).is_some() + || util::get_private_object(scope, anchor, REGISTRIES_SLOT).is_some() + { + util::set_private_value(scope, anchor, DOCUMENT_SLOT, v8::undefined(scope).into()); + util::set_private_value( + scope, + anchor, + REGISTRIES_SLOT, + v8::undefined(scope).into(), + ); + } let scope = &mut v8::ContextScope::new(scope, owner); let owner_anchor = util::new_null_prototype_object(scope); util::set_private_value(scope, anchor, OWNER_SLOT, owner_anchor.into()); @@ -227,6 +307,10 @@ impl BridgeIdentityStore { *descriptor.resolution_cache.0.borrow_mut() = None; } } + unsafe { &*source_host } + .custom_element_registry_references_version + .set(None); + source.synchronize_registry_references(scope, source_host); } pub(in crate::native_bridge) fn node_ownership( @@ -244,6 +328,20 @@ impl BridgeIdentityStore { self.node_owner_realm = Some(v8::Weak::new(scope, owner)); let ownership = Rc::new(NodeOwnership::new(scope, owner, handle)); self.node_ownership.insert(handle, ownership.clone()); + if unsafe { &*host } + .custom_element_registry_references_enabled + .get() + { + if let Some(document) = unsafe { &*host }.dom_host().owner_document_handle(handle) + && document != handle + { + let document = self.node_ownership(scope, host, document); + ownership.trace_document(scope, &document); + } + let values = + super::registry_references::registry_values_for_subtree(scope, host, handle); + ownership.trace_registries(scope, &values); + } ownership } diff --git a/moli-renderer-v8/src/native_bridge/identity/registry_references.rs b/moli-renderer-v8/src/native_bridge/identity/registry_references.rs new file mode 100644 index 00000000000..5ddcad92db7 --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/identity/registry_references.rs @@ -0,0 +1,135 @@ +use std::collections::{HashMap, HashSet}; + +use super::{BridgeIdentityStore, PageScriptHost}; +use crate::{ + custom_elements::{CustomElementRegistryAssociation, CustomElementRegistryKey}, + document_runtime::DomHandle, +}; + +fn registry_for_node(host: &PageScriptHost, node: DomHandle) -> Option { + let CustomElementRegistryAssociation::Registry(key) = + host.effective_custom_element_registry_association(node) + else { + return None; + }; + host.custom_elements_for_registry_key(key) + .is_some_and(|store| store.registry_data().has_shared_native_owners()) + .then_some(key) +} + +fn parent(host: &PageScriptHost, node: DomHandle) -> Option { + host.dom_host() + .node(node) + .and_then(|node| node.parent_node()) + .or_else(|| host.dom_host().shadow_root_host(node)) +} + +pub(super) fn registry_values_for_subtree<'s>( + scope: &mut v8::PinScope<'s, '_>, + host: *mut PageScriptHost, + root: DomHandle, +) -> Vec> { + let host = unsafe { &*host }; + let Some(bindings) = &host.custom_element_registry_bindings else { + return Vec::new(); + }; + let mut keys = HashSet::new(); + if let Some(key) = registry_for_node(host, root) { + keys.insert(key); + } + for (handle, _) in host.custom_element_registry_associations_in_order() { + let Some(key) = registry_for_node(host, handle) else { + continue; + }; + let mut current = Some(handle); + while let Some(handle) = current { + if handle == root { + keys.insert(key); + break; + } + current = parent(host, handle); + } + } + keys.into_iter() + .filter_map(|key| bindings.wrapper(scope, key).map(Into::into)) + .collect() +} + +impl BridgeIdentityStore { + /// Mirrors only registry references into the V8 graph. Connected trees + /// trace through their Document anchor; detached subtrees through retained + /// ancestor/node anchors. The native index and ownership records stay weak. + pub(in crate::native_bridge) fn synchronize_registry_references( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + ) { + let host = unsafe { &*host_ptr }; + if !host.custom_element_registry_references_enabled.get() { + return; + } + let version = host.dom_host().query_version(); + if host.custom_element_registry_references_version.get() == Some(version) { + return; + } + host.custom_element_registry_references_version + .set(Some(version)); + let Some(bindings) = host.custom_element_registry_bindings.clone() else { + return; + }; + let associations = host + .custom_element_registry_associations_in_order() + .collect::>(); + let mut nodes = self + .node_ownership + .iter() + .map(|(&handle, ownership)| (handle, ownership.clone())) + .collect::>(); + let mut roots: HashMap> = HashMap::new(); + // A retained non-element also traces its owner Document and the + // registry of its containing shadow tree. + for (handle, ownership) in &nodes { + if ownership.existing_anchor(scope).is_none() { + continue; + } + if let Some(key) = registry_for_node(host, *handle) { + roots.entry(*handle).or_default().insert(key); + } + if let Some(document) = host.dom_host().owner_document_handle(*handle) + && document != *handle + { + let document = self.node_ownership(scope, host_ptr, document); + ownership.trace_document(scope, &document); + } + } + // Include Document records first materialized by the loop above. + nodes = self + .node_ownership + .iter() + .map(|(&handle, ownership)| (handle, ownership.clone())) + .collect(); + for (handle, _) in associations { + let Some(key) = registry_for_node(host, handle) else { + continue; + }; + let mut current = Some(handle); + while let Some(handle) = current { + if self.node_ownership.contains_key(&handle) { + roots.entry(handle).or_default().insert(key); + } + current = parent(host, handle); + } + } + for (handle, ownership) in nodes { + let values = roots + .remove(&handle) + .into_iter() + .flatten() + .filter_map(|key| bindings.wrapper(scope, key).map(Into::into)) + .collect::>(); + ownership.trace_registries(scope, &values); + } + host.custom_element_registry_references_version + .set(Some(version)); + } +} diff --git a/moli-renderer-v8/src/runtime/tests/auxiliary_pages.rs b/moli-renderer-v8/src/runtime/tests/auxiliary_pages.rs index 9608862e5cf..f315756a2b2 100644 --- a/moli-renderer-v8/src/runtime/tests/auxiliary_pages.rs +++ b/moli-renderer-v8/src/runtime/tests/auxiliary_pages.rs @@ -4,6 +4,263 @@ mod split30_registry_native_owner; use super::*; use crate::RendererPopupActivationSource; +#[tokio::test] +async fn cross_owner_construction_matches_registry_window_with_implicit_associations() { + let runtime = JsRuntime::initialize(); + runtime + .browser_context_runtime() + .delegate_auxiliary_document_responses_to_browser(); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut page = create_test_html_page_with_navigation_dispatch( + &runtime, + &loader, + url::Url::parse("https://registry-realms.test/").unwrap(), + "", + RendererTopLevelNavigationDispatch::DelegateToBrowser, + ) + .await; + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: include_str!("custom_element_registry_cross_owner_realms.js").to_owned(), + await_promise: true, + }) + .await + .unwrap(); + let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else { + panic!("cross-owner realm matrix must return all observations"); + }; + let facts: serde_json::Value = serde_json::from_str(&result).unwrap(); + let expected = serde_json::json!([ + { + "case": "main-registry-main-super", + "upgraded": true, + "created": true, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 2, + "exception": null + }, + { + "case": "main-registry-popup-super", + "upgraded": false, + "created": false, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 0, + "exception": null + }, + { + "case": "popup-registry-main-super", + "upgraded": false, + "created": false, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 0, + "exception": null + }, + { + "case": "popup-registry-popup-super", + "upgraded": false, + "created": true, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 1, + "exception": null + } + ]); + assert_eq!(facts["rows"], expected); + page.close_async().await.unwrap(); +} + +#[tokio::test] +async fn cross_owner_construction_matches_registry_window_with_explicit_associations() { + let runtime = JsRuntime::initialize(); + runtime + .browser_context_runtime() + .delegate_auxiliary_document_responses_to_browser(); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut page = create_test_html_page_with_navigation_dispatch( + &runtime, + &loader, + url::Url::parse("https://registry-realms.test/").unwrap(), + "", + RendererTopLevelNavigationDispatch::DelegateToBrowser, + ) + .await; + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: include_str!("custom_element_registry_cross_owner_explicit_realms.js") + .to_owned(), + await_promise: true, + }) + .await + .unwrap(); + let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else { + panic!("cross-owner realm matrix must return all observations"); + }; + let facts: serde_json::Value = serde_json::from_str(&result).unwrap(); + let expected = serde_json::json!([ + { + "case": "main-registry-main-super", + "upgraded": true, + "created": true, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 2, + "exception": null, + "association": true + }, + { + "case": "main-registry-popup-super", + "upgraded": false, + "created": false, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 0, + "exception": null, + "association": true + }, + { + "case": "popup-registry-main-super", + "upgraded": false, + "created": false, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 0, + "exception": null, + "association": true + }, + { + "case": "popup-registry-popup-super", + "upgraded": true, + "created": true, + "existingOwner": true, + "createdOwner": true, + "constructorCalls": 2, + "exception": null, + "association": true + } + ]); + assert_eq!(facts["rows"], expected); + page.close_async().await.unwrap(); +} + +#[cfg(feature = "devtools")] +#[tokio::test] +async fn cross_owner_registry_references_follow_retained_documents_and_detached_trees() { + let runtime = JsRuntime::initialize(); + runtime + .browser_context_runtime() + .delegate_auxiliary_document_responses_to_browser(); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut page = create_test_html_page_with_navigation_dispatch( + &runtime, + &loader, + url::Url::parse("https://cross-owner-registry-gc.test/").unwrap(), + "", + RendererTopLevelNavigationDispatch::DelegateToBrowser, + ) + .await; + page.run_async_command(RendererPageCommand::EvaluateExpression { + expression: include_str!("custom_element_registry_cross_owner_gc.js").to_owned(), + await_promise: false, + }) + .await + .unwrap(); + for detached in [false, true] { + page.run_async_command(RendererPageCommand::EvaluateExpression { + expression: format!("crossOwnerRegistryGc.setup({detached})"), + await_promise: true, + }) + .await + .unwrap(); + page.run_async_command(RendererPageCommand::DevTools( + RendererDevToolsPageCommand::RuntimeCollectGarbage, + )) + .await + .unwrap(); + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: "crossOwnerRegistryGc.retained()".to_owned(), + await_promise: false, + }) + .await + .unwrap(); + assert_eq!( + renderer_json_value(reply), + Some(serde_json::Value::String( + r#"{"alive":true,"identity":true}"#.to_owned() + )), + "detached={detached}" + ); + page.run_async_command(RendererPageCommand::EvaluateExpression { + expression: "crossOwnerRegistryGc.release()".to_owned(), + await_promise: true, + }) + .await + .unwrap(); + page.run_async_command(RendererPageCommand::DevTools( + RendererDevToolsPageCommand::RuntimeCollectGarbage, + )) + .await + .unwrap(); + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: "crossOwnerRegistryGc.collected()".to_owned(), + await_promise: false, + }) + .await + .unwrap(); + assert_eq!( + renderer_json_value(reply), + Some(serde_json::Value::Bool(true)), + "released detached={detached}" + ); + } + page.close_async().await.unwrap(); +} + +#[tokio::test] +async fn scoped_registry_upgrades_and_creates_elements_in_another_native_owner() { + let runtime = JsRuntime::initialize(); + runtime + .browser_context_runtime() + .delegate_auxiliary_document_responses_to_browser(); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut page = create_test_html_page_with_navigation_dispatch( + &runtime, + &loader, + url::Url::parse("https://cross-owner-registry.test/").unwrap(), + "", + RendererTopLevelNavigationDispatch::DelegateToBrowser, + ) + .await; + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: include_str!("custom_element_registry_cross_owner.js").to_owned(), + await_promise: true, + }) + .await + .unwrap(); + let Some(serde_json::Value::String(result)) = renderer_json_value(reply) else { + panic!("cross-owner registry probe must return all observations"); + }; + let facts: serde_json::Value = serde_json::from_str(&result).unwrap(); + let rows = facts["rows"].as_array().unwrap(); + assert_eq!(rows.len(), 4); + for row in rows { + for (name, value) in row.as_object().unwrap() { + match name.as_str() { + "case" => {} + "constructorCalls" => assert_eq!(value, 1, "{row}"), + "totalConstructorCalls" => assert_eq!(value, 2, "{row}"), + _ => assert_eq!(value, true, "{row}: {name}"), + } + } + } + page.close_async().await.unwrap(); +} + #[tokio::test] async fn retained_popup_registries_preserve_definitions_without_resuming_definition_installation() { let runtime = JsRuntime::initialize(); diff --git a/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner.js b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner.js new file mode 100644 index 00000000000..90ba21a379e --- /dev/null +++ b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner.js @@ -0,0 +1,45 @@ +(async () => { + const popup = open('about:blank'); + const rows = []; + const registry = new CustomElementRegistry(); + const doc = popup.document; + const host = doc.createElement('div'); + const root = host.attachShadow({mode: 'open', customElementRegistry: registry}); + const name = 'cross-popup-late-upgrade'; + const node = doc.createElement(name); + root.append(node); + doc.body.append(host); + const calls = []; + class Element extends HTMLElement { + constructor() { super(); calls.push(this.ownerDocument === doc); } + } + try { + rows.push({case: 'association', rootRegistry: root.customElementRegistry === registry, + inheritedRegistry: node.customElementRegistry === registry, + ownerDocument: node.ownerDocument === doc}); + registry.define(name, Element); + rows.push({case: 'late-upgrade', instance: node instanceof Element, + ownerDocument: node.ownerDocument === doc, + constructorCalls: calls.length, correctDocuments: calls.every(Boolean), + sourceLookup: registry.get(name) === Element}); + const created = doc.createElement(name, {customElementRegistry: registry}); + root.append(created); + rows.push({case: 'create', instance: created instanceof Element, + ownerDocument: created.ownerDocument === doc, + registry: created.customElementRegistry === registry, + totalConstructorCalls: calls.length, correctDocuments: calls.every(Boolean)}); + popup.close(); + await new Promise(resolve => setTimeout(resolve, 500)); + class AfterClose extends HTMLElement {} + const afterName = 'cross-popup-source-still-active'; + let resolved; + registry.whenDefined(afterName).then(value => { resolved = value; }); + registry.define(afterName, AfterClose); + await Promise.resolve(); + rows.push({case: 'target-retirement', oldDefinition: registry.get(name) === Element, + newDefinition: registry.get(afterName) === AfterClose, + whenDefined: resolved === AfterClose, + rootRegistry: root.customElementRegistry === registry}); + return JSON.stringify({rows}); + } finally { popup.close(); } +})() diff --git a/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_explicit_realms.js b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_explicit_realms.js new file mode 100644 index 00000000000..874bf7789f9 --- /dev/null +++ b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_explicit_realms.js @@ -0,0 +1,39 @@ +(async () => { + const rows = []; + for (const registryRealm of ['main', 'popup']) { + for (const superRealm of ['main', 'popup']) { + const popup = open('about:blank'); + try { + popup.addEventListener('error', event => event.preventDefault()); + const owner = registryRealm === 'main' ? window : popup; + const target = registryRealm === 'main' ? popup : window; + const doc = target.document; + const registry = new owner.CustomElementRegistry(); + const base = superRealm === 'main' ? HTMLElement : popup.HTMLElement; + const name = `cross-super-${registryRealm}-${superRealm}`; + let calls = 0; + const Constructor = class extends base { + constructor() { super(); ++calls; } + }; + const host = doc.createElement('div'); + const shadow = host.attachShadow({mode: 'open', customElementRegistry: registry}); + const existing = doc.createElement(name, {customElementRegistry: registry}); + shadow.append(existing); + doc.body.append(host); + registry.define(name, Constructor); + let created; + let exception = null; + try { created = doc.createElement(name, {customElementRegistry: registry}); } + catch (error) { exception = error.name; } + rows.push({case: `${registryRealm}-registry-${superRealm}-super`, + upgraded: existing instanceof Constructor, + created: created instanceof Constructor, + existingOwner: existing.ownerDocument === doc, + createdOwner: created?.ownerDocument === doc, + constructorCalls: calls, association: existing.customElementRegistry === registry, exception}); + host.remove(); + } finally { popup.close(); } + } + } + return JSON.stringify({rows}); +})() diff --git a/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_gc.js b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_gc.js new file mode 100644 index 00000000000..4aea3544611 --- /dev/null +++ b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_gc.js @@ -0,0 +1,34 @@ +(() => { + let state; + globalThis.crossOwnerRegistryGc = { + async setup(detached) { + const popup = open('about:blank'); + const doc = popup.document; + const registry = new CustomElementRegistry(); + const host = doc.createElement('div'); + host.attachShadow({mode: 'open', customElementRegistry: registry}); + doc.body.append(host); + state = {popup, retained: detached ? host : doc, reference: new WeakRef(registry), detached}; + if (detached) { + host.remove(); + popup.close(); + await new Promise(resolve => setTimeout(resolve, 500)); + } + return 'ready'; + }, + retained() { + const registry = state.reference.deref(); + const host = state.detached ? state.retained : state.retained.body.firstElementChild; + return JSON.stringify({alive: registry !== undefined, + identity: registry !== undefined && host.shadowRoot.customElementRegistry === registry}); + }, + release() { + state.popup.close(); + state.popup = null; + state.retained = null; + return new Promise(resolve => setTimeout(resolve, 500)); + }, + collected() { return state.reference.deref() === undefined; }, + }; + return 'ready'; +})() diff --git a/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_realms.js b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_realms.js new file mode 100644 index 00000000000..37ee880cd68 --- /dev/null +++ b/moli-renderer-v8/src/runtime/tests/custom_element_registry_cross_owner_realms.js @@ -0,0 +1,39 @@ +(async () => { + const rows = []; + for (const registryRealm of ['main', 'popup']) { + for (const superRealm of ['main', 'popup']) { + const popup = open('about:blank'); + try { + popup.addEventListener('error', event => event.preventDefault()); + const owner = registryRealm === 'main' ? window : popup; + const target = registryRealm === 'main' ? popup : window; + const doc = target.document; + const registry = new owner.CustomElementRegistry(); + const base = superRealm === 'main' ? HTMLElement : popup.HTMLElement; + const name = `cross-super-${registryRealm}-${superRealm}`; + let calls = 0; + const Constructor = class extends base { + constructor() { super(); ++calls; } + }; + const host = doc.createElement('div'); + const shadow = host.attachShadow({mode: 'open', customElementRegistry: registry}); + const existing = doc.createElement(name); + shadow.append(existing); + doc.body.append(host); + registry.define(name, Constructor); + let created; + let exception = null; + try { created = doc.createElement(name, {customElementRegistry: registry}); } + catch (error) { exception = error.name; } + rows.push({case: `${registryRealm}-registry-${superRealm}-super`, + upgraded: existing instanceof Constructor, + created: created instanceof Constructor, + existingOwner: existing.ownerDocument === doc, + createdOwner: created?.ownerDocument === doc, + constructorCalls: calls, exception}); + host.remove(); + } finally { popup.close(); } + } + } + return JSON.stringify({rows}); +})() diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_reactions_and_builtins.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_reactions_and_builtins.rs index 558a65d06c6..4c7dc25b080 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_reactions_and_builtins.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_reactions_and_builtins.rs @@ -209,7 +209,7 @@ fn fragment_html_uses_context_custom_element_registry_association() { mode: "open", customElementRegistry: null }); - const nullContainer = document.createElement("div"); + const nullContainer = document.createElement("div", { customElementRegistry: null }); nullShadow.appendChild(nullContainer); nullContainer.innerHTML = "" + diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_scoping_and_fragments.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_scoping_and_fragments.rs index 5a933160c2d..1107a7922f1 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_scoping_and_fragments.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/registry_scoping_and_fragments.rs @@ -1474,7 +1474,7 @@ fn attach_shadow_default_registry_uses_owner_document_default() { const nullRoot = document .createElement("wpt-null-host") .attachShadow({ mode: "open", customElementRegistry: null }); - const nestedHost = document.createElement("wpt-nested-host"); + const nestedHost = document.createElement("wpt-nested-host", { customElementRegistry: null }); nullRoot.appendChild(nestedHost); const nestedDefaultRoot = nestedHost.attachShadow({ mode: "open" }); @@ -1513,16 +1513,16 @@ fn removing_from_shadow_tree_preserves_non_default_registry_association() { const scopedRoot = document .createElement("wpt-scoped-root") .attachShadow({ mode: "open", customElementRegistry: registry }); - const scopedWrapper = document.createElement("div"); - const scopedChild = document.createElement("wpt-scoped-child"); + const scopedWrapper = document.createElement("div", { customElementRegistry: registry }); + const scopedChild = document.createElement("wpt-scoped-child", { customElementRegistry: registry }); scopedWrapper.appendChild(scopedChild); scopedRoot.appendChild(scopedWrapper); const nullRoot = document .createElement("wpt-null-root") .attachShadow({ mode: "open", customElementRegistry: null }); - const nullWrapper = document.createElement("section"); - const nullChild = document.createElement("wpt-null-child"); + const nullWrapper = document.createElement("section", { customElementRegistry: null }); + const nullChild = document.createElement("wpt-null-child", { customElementRegistry: null }); nullWrapper.appendChild(nullChild); nullRoot.appendChild(nullWrapper);