Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(custom-elements): preserve constructor-selected prototypes

ldm0f6b833d28836
diff --git a/moli-renderer-v8/src/custom_elements/construction_result.rs b/moli-renderer-v8/src/custom_elements/construction_result.rs
index 8223876da..c346c5a3c 100644
--- a/moli-renderer-v8/src/custom_elements/construction_result.rs
+++ b/moli-renderer-v8/src/custom_elements/construction_result.rs
@@ -107,9 +107,25 @@ pub(crate) fn set_wrapper_custom_element_constructor_prototype<'s>(
let Ok(prototype) = custom_element_constructor_prototype(scope, constructor) else {
return;
};
- set_wrapper_custom_element_prototype(scope, wrapper, prototype);
+ set_wrapper_custom_element_prototype(scope, wrapper, prototype.into());
if let Some(foreign) = get_private_object(scope, wrapper, DOM_PARSER_FOREIGN_NODE_SLOT) {
- set_wrapper_custom_element_prototype(scope, foreign, prototype);
+ set_wrapper_custom_element_prototype(scope, foreign, prototype.into());
+ }
+}
+
+pub(super) fn synchronize_custom_element_prototype_for_handle<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ source: v8::Local<'s, v8::Object>,
+) {
+ synchronize_wrapper_custom_element_prototype(scope, source);
+ if let Some(canonical) = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)
+ && !canonical.strict_equals(source.into())
+ {
+ synchronize_custom_element_prototype_between_wrappers(scope, source, canonical);
}
}
@@ -120,62 +136,29 @@ pub(super) fn synchronize_wrapper_custom_element_prototype<'s>(
synchronize_custom_element_prototype_between_wrappers(scope, wrapper, wrapper);
}
-pub(super) fn synchronize_custom_element_prototype_between_wrappers<'s>(
+fn synchronize_custom_element_prototype_between_wrappers<'s>(
scope: &mut v8::PinScope<'s, '_>,
source: v8::Local<'s, v8::Object>,
target: v8::Local<'s, v8::Object>,
) {
- let Some(prototype) = source
- .get_prototype(scope)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
+ let Some(prototype) = source.get_prototype(scope) else {
return;
};
- set_wrapper_custom_element_prototype(scope, target, prototype);
+ if !source.strict_equals(target.into()) {
+ set_wrapper_custom_element_prototype(scope, target, prototype);
+ }
if let Some(foreign) = get_private_object(scope, target, DOM_PARSER_FOREIGN_NODE_SLOT) {
set_wrapper_custom_element_prototype(scope, foreign, prototype);
}
}
-pub(super) fn finalize_wrapper_custom_element_prototype<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- wrapper: v8::Local<'s, v8::Object>,
- constructor: v8::Local<'s, v8::Function>,
-) {
- let current = wrapper.get_prototype(scope);
- let definition_prototype = custom_element_constructor_prototype(scope, constructor).ok();
- let definition_parent =
- definition_prototype.and_then(|prototype| prototype.get_prototype(scope));
- let uses_definition_chain = current.is_some_and(|current| {
- definition_prototype.is_some_and(|prototype| current.strict_equals(prototype.into()))
- || definition_parent.is_some_and(|parent| current.strict_equals(parent))
- });
- let prototype_constructor_name = current
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|prototype| prototype.get(scope, crate::util::v8str(scope, "constructor").into()))
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- .map(|function| function.get_name(scope).to_rust_string_lossy(scope));
- let constructor_name = constructor.get_name(scope).to_rust_string_lossy(scope);
- let uses_native_fallback = prototype_constructor_name.as_deref().is_none_or(|name| {
- name.is_empty()
- || name == "undefined"
- || name == "Object"
- || (name.starts_with("HTML") && name.ends_with("Element"))
- });
- let uses_definition_prototype =
- prototype_constructor_name.as_deref() == Some(constructor_name.as_str());
- if uses_definition_chain || uses_definition_prototype || uses_native_fallback {
- set_wrapper_custom_element_constructor_prototype(scope, wrapper, constructor);
- } else {
- synchronize_wrapper_custom_element_prototype(scope, wrapper);
- }
-}
-
fn set_wrapper_custom_element_prototype<'s>(
scope: &mut v8::PinScope<'s, '_>,
wrapper: v8::Local<'s, v8::Object>,
- prototype: v8::Local<'s, v8::Object>,
+ prototype: v8::Local<'s, v8::Value>,
) {
- preserve_detached_element_bridge_for_custom_prototype(scope, wrapper, prototype);
- let _ = wrapper.set_prototype(scope, prototype.into());
+ if let Ok(object) = v8::Local::<v8::Object>::try_from(prototype) {
+ preserve_detached_element_bridge_for_custom_prototype(scope, wrapper, object);
+ }
+ let _ = wrapper.set_prototype(scope, prototype);
}
diff --git a/moli-renderer-v8/src/custom_elements/construction_runtime.rs b/moli-renderer-v8/src/custom_elements/construction_runtime.rs
index febfbe446..d2d88f5fa 100644
--- a/moli-renderer-v8/src/custom_elements/construction_runtime.rs
+++ b/moli-renderer-v8/src/custom_elements/construction_runtime.rs
@@ -4,9 +4,7 @@ use super::construction_invocation::{
CustomElementConstructorInvocation, invoke_custom_element_constructor,
};
use super::construction_result::{
- finalize_wrapper_custom_element_prototype,
- synchronize_custom_element_prototype_between_wrappers,
- validate_custom_element_construction_result,
+ synchronize_custom_element_prototype_for_handle, validate_custom_element_construction_result,
};
use super::element_state::{
create_element_with_owner_document, set_dom_custom_element_is_name,
@@ -80,23 +78,7 @@ pub(super) fn create_custom_element_for_registry_key<'s>(
if let Some(prefix) = post_construction_prefix {
set_dom_element_prefix(host_ptr, handle, Some(prefix.to_owned()));
}
- finalize_wrapper_custom_element_prototype(scope, created, constructor);
- if let Some(canonical) = unsafe { &mut *host_ptr }
- .native_bridge_mut()
- .wrap_handle(scope, host_ptr, handle)
- {
- if canonical.strict_equals(created.into()) {
- synchronize_custom_element_prototype_between_wrappers(
- scope, created, canonical,
- );
- } else {
- super::construction_result::set_wrapper_custom_element_constructor_prototype(
- scope,
- canonical,
- constructor,
- );
- }
- }
+ synchronize_custom_element_prototype_for_handle(scope, host_ptr, handle, created);
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.mark_upgraded_handle(handle, definition_name);
@@ -104,18 +86,6 @@ pub(super) fn create_custom_element_for_registry_key<'s>(
unsafe { &mut *host_ptr }
.custom_elements_mut_for_registry_key(registry_key)
.finish_construction(handle);
- finalize_wrapper_custom_element_prototype(scope, created, constructor);
- if let Some(canonical) = unsafe { &mut *host_ptr }
- .native_bridge_mut()
- .wrap_handle(scope, host_ptr, handle)
- && !canonical.strict_equals(created.into())
- {
- super::construction_result::set_wrapper_custom_element_constructor_prototype(
- scope,
- canonical,
- constructor,
- );
- }
dispatch_form_association_callback_if_needed(scope, host_ptr, handle);
dispatch_form_disabled_callback_if_needed(scope, host_ptr, handle);
Some(created)
diff --git a/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs b/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
index df8769877..c5edda923 100644
--- a/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
+++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_failure.rs
@@ -36,7 +36,7 @@ pub(super) fn fail_existing_custom_element_construction<'s>(
if let Some(wrapper) = wrapper {
match failure_prototype {
FailedExistingConstructionPrototype::ResetToUnknown => {
- set_wrapper_failed_custom_element_prototype(scope, wrapper);
+ set_wrapper_failed_custom_element_prototype(scope, host_ptr, handle, wrapper);
}
FailedExistingConstructionPrototype::PreserveCurrent => {}
}
@@ -46,12 +46,23 @@ pub(super) fn fail_existing_custom_element_construction<'s>(
fn set_wrapper_failed_custom_element_prototype<'s>(
scope: &mut v8::PinScope<'s, '_>,
+ host_ptr: *mut JsContextHost,
+ handle: DomHandle,
wrapper: v8::Local<'s, v8::Object>,
) {
- let Some(prototype) = global_constructor_prototype(scope, "HTMLUnknownElement") else {
+ let host = unsafe { &mut *host_ptr };
+ let child = host
+ .dom_host()
+ .owner_document_handle(handle)
+ .and_then(|document| host.child_browsing_context_host_for_document_handle(document));
+ let prototype = child
+ .and_then(|child| {
+ host.child_browsing_context_constructor_prototype(scope, child, "HTMLUnknownElement")
+ })
+ .or_else(|| global_constructor_prototype(scope, "HTMLUnknownElement").map(Into::into));
+ let Some(prototype) = prototype else {
return;
};
- let prototype = prototype.into();
let _ = wrapper.set_prototype(scope, prototype);
if let Some(foreign) = get_private_object(scope, wrapper, DOM_PARSER_FOREIGN_NODE_SLOT) {
let _ = foreign.set_prototype(scope, prototype);
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 509c61a13..5313e9a8b 100644
--- a/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs
+++ b/moli-renderer-v8/src/custom_elements/existing_upgrade_invocation.rs
@@ -4,8 +4,7 @@ use super::construction_invocation::{
CustomElementConstructorInvocation, invoke_custom_element_constructor,
};
use super::construction_result::{
- FailedExistingConstructionPrototype, finalize_wrapper_custom_element_prototype,
- synchronize_custom_element_prototype_between_wrappers,
+ FailedExistingConstructionPrototype, synchronize_custom_element_prototype_for_handle,
};
use super::existing_upgrade_completion::{
complete_existing_custom_element_upgrade, enqueue_existing_upgrade_callbacks,
@@ -32,12 +31,10 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
.begin_construction(scope, constructor, wrapper, handle);
let _dynamic_markup = enter_upgrade_dynamic_markup_insertion(host_ptr, handle);
let invocation = invoke_custom_element_constructor(scope, host_ptr, constructor);
- let consumed_pending_wrapper = unsafe { &*host_ptr }
- .custom_elements_for_node_handle(handle)
- .is_some_and(|store| store.pending_construction_is_already_constructed(handle));
match invocation {
CustomElementConstructorInvocation::Created(created) => {
let created = v8::Local::new(scope, &created);
+ synchronize_custom_element_prototype_for_handle(scope, host_ptr, handle, wrapper);
if !validate_existing_custom_element_upgrade_result(wrapper, created) {
fail_existing_custom_element_construction(
scope,
@@ -49,36 +46,13 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
),
failure_prototype,
);
- if consumed_pending_wrapper {
- finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
- }
return true;
}
- finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
complete_existing_custom_element_upgrade(scope, host_ptr, handle, definition_name);
true
}
CustomElementConstructorInvocation::Exception(exception) => {
- if consumed_pending_wrapper {
- finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
- }
- if consumed_pending_wrapper
- && let Some(canonical) = unsafe { &mut *host_ptr }
- .native_bridge_mut()
- .wrap_handle(scope, host_ptr, handle)
- {
- if canonical.strict_equals(wrapper.into()) {
- synchronize_custom_element_prototype_between_wrappers(
- scope, wrapper, canonical,
- );
- } else {
- super::construction_result::set_wrapper_custom_element_constructor_prototype(
- scope,
- canonical,
- constructor,
- );
- }
- }
+ synchronize_custom_element_prototype_for_handle(scope, host_ptr, handle, wrapper);
let exception = v8::Local::new(scope, &exception);
if already_constructed_reentry_consumed_pending_handle(
scope,
@@ -99,9 +73,6 @@ pub(super) fn upgrade_existing_custom_element_with_constructor<'s>(
ConstructionFailure::Exception(exception),
failure_prototype,
);
- if consumed_pending_wrapper {
- finalize_wrapper_custom_element_prototype(scope, wrapper, constructor);
- }
true
}
CustomElementConstructorInvocation::Empty => {
diff --git a/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs b/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs
index 6de7b49d8..88df06338 100644
--- a/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs
+++ b/moli-renderer-v8/src/native_bridge/bridge/wrappers.rs
@@ -51,7 +51,16 @@ impl NativeDomBridge {
) -> Option<v8::Local<'s, v8::Object>> {
let reflector_id = self.identity.reflector_id(&handle);
if let Some(wrapper) = self.identity.cached_wrapper(scope, reflector_id) {
- if !matches!(&handle, BridgeHandle::Window) {
+ // Once custom element construction starts, preserve the prototype
+ // chosen by JavaScript, including when an upgrade fails.
+ let preserve_prototype = match &handle {
+ BridgeHandle::Window => true,
+ BridgeHandle::Node(handle) => {
+ unsafe { &*host_ptr }.custom_element_handle_preserves_wrapper_prototype(*handle)
+ }
+ _ => false,
+ };
+ if !preserve_prototype {
self.bindings
.sync_wrapper_owner_realm_prototype(scope, host_ptr, &handle, wrapper);
}
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 9742b72df..26cad85c4 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -2209,6 +2209,28 @@ impl JsContextHost {
.is_some_and(|store| store.is_upgraded_handle(handle))
}
+ pub(crate) fn custom_element_handle_preserves_wrapper_prototype(
+ &self,
+ handle: DomHandle,
+ ) -> bool {
+ let Some(element) = self
+ .dom_host()
+ .node(handle)
+ .and_then(|node| node.as_element())
+ else {
+ return false;
+ };
+ if element.custom_element_state() == crate::dom::native::CustomElementState::Uncustomized {
+ return false;
+ }
+ self.custom_elements_for_node_handle(handle)
+ .is_some_and(|store| {
+ store.is_upgraded_handle(handle)
+ || store.is_pending_construction_handle(handle)
+ || store.is_failed_construction_handle(handle)
+ })
+ }
+
pub(crate) fn custom_elements_mut_for_node_handle(
&mut self,
handle: DomHandle,
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
index 1884c3a44..d6bd940d3 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
@@ -1471,6 +1471,123 @@ fn child_custom_elements_upgrade_accepts_child_document_node_root() {
);
}
+#[test]
+fn custom_element_constructor_selected_prototypes_survive_wrapper_lookup() {
+ let mut vm = new_storage_test_vm("https://ce-selected-prototypes.test/");
+ let result = vm.eval(r#"
+ (() => {
+ window.addEventListener("error", event => event.preventDefault());
+ const html = document.documentElement || document.appendChild(document.createElement("html"));
+ const body = document.body || html.appendChild(document.createElement("body"));
+ const frame = body.appendChild(document.createElement("iframe"));
+ const failures = [];
+ let cases = 0;
+ for (const [realm, w] of [["main", window], ["child", frame.contentWindow]]) {
+ const doc = w.document;
+ const root = doc.body || doc.documentElement || doc;
+ for (const mode of ["create", "upgrade", "failed-upgrade"]) {
+ for (const kind of ["null", "object", "inherited", "base", "same-name", "html-name", "getter"]) {
+ const name = `selected-${mode}-${kind}`;
+ let selected;
+ let constructorReads = 0;
+ let sameDuring = false;
+ let prototypeDuring = false;
+ const callbacks = [];
+ class SelectedElement extends w.HTMLElement {
+ constructor() {
+ super();
+ Object.setPrototypeOf(this, selected);
+ const lookedUp = mode === "create" ? doc.adoptNode(this) : doc.querySelector(name);
+ sameDuring = lookedUp === this;
+ prototypeDuring = Object.getPrototypeOf(lookedUp) === selected;
+ if (mode === "failed-upgrade") throw new Error("after super");
+ }
+ connectedCallback() { callbacks.push(Object.getPrototypeOf(this) === selected); }
+ }
+ switch (kind) {
+ case "null": selected = null; break;
+ case "object": selected = {}; break;
+ case "inherited": selected = Object.create(SelectedElement.prototype); break;
+ case "base": selected = w.HTMLElement.prototype; break;
+ case "same-name": selected = (class SelectedElement extends w.HTMLElement {}).prototype; break;
+ case "html-name": selected = (class HTMLReplacementElement extends w.HTMLElement {}).prototype; break;
+ case "getter":
+ selected = Object.create(w.HTMLElement.prototype);
+ Object.defineProperty(selected, "constructor", {get() {
+ constructorReads++;
+ throw new Error("prototype.constructor must not be read");
+ }});
+ break;
+ }
+ let element;
+ if (mode !== "create") {
+ element = doc.createElement(name);
+ root.appendChild(element);
+ }
+ w.customElements.define(name, SelectedElement);
+ if (mode === "create") {
+ element = doc.createElement(name);
+ root.appendChild(element);
+ }
+ const lookedUp = doc.querySelector(name);
+ const after = Object.getPrototypeOf(element) === selected;
+ const afterLookup = Object.getPrototypeOf(lookedUp) === selected;
+ const sameAfter = lookedUp === element;
+ const callbacksCorrect = JSON.stringify(callbacks) ===
+ (mode === "failed-upgrade" ? "[]" : "[true]");
+ if (!sameDuring || !prototypeDuring || !after || !afterLookup || !sameAfter ||
+ constructorReads !== 0 || !callbacksCorrect) {
+ failures.push({realm, mode, kind, sameDuring, prototypeDuring, after, afterLookup,
+ sameAfter, constructorReads, callbacks});
+ }
+ cases++;
+ }
+ }
+ }
+ return JSON.stringify({cases, failures});
+ })()
+ "#).expect("constructor-selected prototypes should remain observable");
+ assert_eq!(result, r#"{"cases":42,"failures":[]}"#);
+}
+
+#[test]
+fn child_failed_custom_element_creation_preserves_original_and_fallback_prototypes() {
+ let mut vm = new_storage_test_vm("https://ce-fallback-prototype.test/");
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ window.addEventListener("error", event => event.preventDefault());
+ const html = document.documentElement || document.appendChild(document.createElement("html"));
+ const body = document.body || html.appendChild(document.createElement("body"));
+ const frame = body.appendChild(document.createElement("iframe"));
+ const w = frame.contentWindow;
+ let constructed;
+ class InvalidElement extends w.HTMLElement {
+ constructor() {
+ super();
+ constructed = this;
+ this.setAttribute("invalid", "yes");
+ Object.setPrototypeOf(this, null);
+ }
+ }
+ w.customElements.define("invalid-created-element", InvalidElement);
+ const element = w.document.createElement("invalid-created-element");
+ (w.document.body || w.document.documentElement).appendChild(element);
+ const lookedUp = w.document.querySelector("invalid-created-element");
+ const original = w.document.adoptNode(constructed);
+ return [element instanceof w.HTMLUnknownElement,
+ Object.getPrototypeOf(element) === w.HTMLUnknownElement.prototype,
+ element instanceof InvalidElement, element.hasAttribute("invalid"),
+ lookedUp === element, element !== constructed, original === constructed,
+ Object.getPrototypeOf(original) === null].join(":");
+ })()
+ "#,
+ )
+ .expect("failed construction should preserve the original and initialize its fallback");
+ assert_eq!(result, "true:true:false:false:true:true:true:true");
+}
+
#[test]
fn existing_upgrade_preserves_prototype_selected_by_wrapping_constructor() {
let mut vm = new_storage_test_vm("https://example.com/");