diff --git a/moli-html2md/src/machine.rs b/moli-html2md/src/machine.rs
index 62ff7cd9ee6..9bb1765c589 100644
--- a/moli-html2md/src/machine.rs
+++ b/moli-html2md/src/machine.rs
@@ -9,7 +9,7 @@ enum Task<'a, Id> {
Children(Option, usize),
Boundary,
PopStyle,
- EndLink(usize),
+ EndLink(usize, Option<&'a str>),
EndQuote,
EndHeading(usize),
EndList(usize),
@@ -70,7 +70,9 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
Task::Children(None, _) | Task::RawChildren(None, _, _) => {}
Task::Boundary => self.writer().boundary(2),
Task::PopStyle => self.writer().pop_style(),
- Task::EndLink(serial) => self.writer().end_link(serial),
+ Task::EndLink(serial, fallback_label) => {
+ self.writer().end_link(serial, fallback_label)
+ }
Task::EndQuote => {
let content = self.take_writer().into_string();
let mut quote = String::new();
@@ -166,6 +168,7 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
let writer = self.writers.pop().expect("capture has an output");
if let Some(parent) = self.writers.last_mut() {
parent.last_link = parent.last_link.max(writer.last_link);
+ parent.last_link_content = parent.last_link_content.max(writer.last_link_content);
}
writer.finish()
}
@@ -232,7 +235,10 @@ impl<'a, D: Dom + ?Sized> Machine<'a, D> {
title: self.dom.attribute(node, "title"),
};
if self.writer().push_style(style) {
- self.tasks.push(Task::EndLink(serial));
+ self.tasks.push(Task::EndLink(
+ serial,
+ self.dom.attribute(node, "aria-label"),
+ ));
}
}
}
diff --git a/moli-html2md/src/writer.rs b/moli-html2md/src/writer.rs
index 7417fdf72c5..df7fb9e5ed7 100644
--- a/moli-html2md/src/writer.rs
+++ b/moli-html2md/src/writer.rs
@@ -40,6 +40,7 @@ pub(crate) struct Writer<'a> {
heading: bool,
single_line_attributes: bool,
pub(crate) last_link: usize,
+ pub(crate) last_link_content: usize,
// Block events in this output buffer, used when finalizing a list item.
pub(crate) has_blocks: bool,
}
@@ -86,12 +87,21 @@ impl<'a> Writer<'a> {
self.desired.pop();
}
- pub(crate) fn end_link(&mut self, serial: usize) {
+ pub(crate) fn end_link(&mut self, serial: usize, fallback_label: Option<&str>) {
self.flush_code();
if self.last_link < serial {
- // Empty anchors still carry a destination. Materialize the link
- // after its leading whitespace, even without a text event.
- self.prepare_inline('[');
+ if let Some(label) = fallback_label
+ .filter(|label| self.last_link_content < serial && !label.trim().is_empty())
+ {
+ // An empty anchor can still have an author-provided accessible
+ // name. Preserve that name inside the link instead of emitting
+ // an unusable empty label. Visible descendants remain primary.
+ self.text(label);
+ } else {
+ // Empty anchors still carry a destination. Materialize the link
+ // after its leading whitespace, even without a text event.
+ self.prepare_inline('[');
+ }
}
self.pop_style();
}
@@ -250,6 +260,11 @@ impl<'a> Writer<'a> {
self.boundary(before.max(after));
return;
}
+ for style in &self.desired {
+ if let Style::Link { serial, .. } = style {
+ self.last_link_content = self.last_link_content.max(*serial);
+ }
+ }
// Closing styles before detaching the tail keeps all inline edit
// offsets local to the current String, never inside a finished block.
self.boundary(before);
@@ -320,6 +335,7 @@ impl<'a> Writer<'a> {
Style::Strike => self.output.push_str(if html { "" } else { "~~" }),
Style::Link { serial, .. } => {
self.last_link = self.last_link.max(serial);
+ self.last_link_content = self.last_link_content.max(serial);
if self.output.ends_with('!') {
self.output.insert(self.output.len() - 1, '\\');
}
diff --git a/moli-html2md/tests/regressions.rs b/moli-html2md/tests/regressions.rs
index f5e12486a8b..8c90bc535bb 100644
--- a/moli-html2md/tests/regressions.rs
+++ b/moli-html2md/tests/regressions.rs
@@ -57,6 +57,40 @@ fn empty_links_keep_destinations_across_adjacent_and_nested_elements() {
}
}
+#[test]
+fn empty_links_use_their_own_accessible_label_without_replacing_visible_text() {
+ for (html, expected) in [
+ (
+ "",
+ "[Open report](/report)",
+ ),
+ (
+ "Visible report",
+ "[Visible report](/report)",
+ ),
+ (
+ " ",
+ "[Open report](/report)",
+ ),
+ ("", "[](/report)"),
+ (
+ "",
+ r"[\[Open\] \*report\*](/report)",
+ ),
+ (
+ "",
+ "[One](/one)[Two](/two)",
+ ),
+ (
+ "
",
+ "[](/report)",
+ ),
+ ("", ""),
+ ] {
+ assert_eq!(markdown(html, false), expected, "{html}");
+ }
+}
+
#[test]
fn href_without_a_destination_does_not_create_an_empty_markdown_link() {
for html in [
@@ -488,3 +522,45 @@ fn fallback_block_elements_separate_neighboring_words() {
);
}
}
+
+#[test]
+fn accessible_link_fallback_never_duplicates_visible_inline_or_block_descendants() {
+ for content in [
+ "Visible",
+ "
",
+ "code",
+ "preformatted
",
+ "nested code
",
+ "Paragraph
",
+ "Heading
",
+ "",
+ "Quotation
",
+ "",
+ ] {
+ let plain = format!("{content}");
+ let labeled = format!("{content}");
+ assert_eq!(
+ markdown(&labeled, false),
+ markdown(&plain, false),
+ "{content}"
+ );
+ }
+}
+
+#[test]
+fn empty_link_fallback_belongs_only_to_that_anchor() {
+ assert_eq!(
+ markdown(
+ "",
+ false
+ ),
+ "[](/one)[Own](/two)"
+ );
+ assert_eq!(
+ markdown(
+ "",
+ false
+ ),
+ "[Own](/target)"
+ );
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/cross_origin_cache.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/cross_origin_cache.rs
index 0016d0298af..defc6042edf 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/cross_origin_cache.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/cross_origin_cache.rs
@@ -43,7 +43,10 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
target: v8::Local<'s, v8::Context>,
accessing: v8::Local<'s, v8::Context>,
build: impl FnOnce(&mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object>,
-) -> v8::Local<'s, v8::Object> {
+) -> Option> {
+ if scope.is_execution_terminating() {
+ return None;
+ }
let (map, get, set) = {
let scope = &mut v8::ContextScope::new(scope, target);
let anchor = target.get_extras_binding_object(scope);
@@ -52,9 +55,9 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
.expect("Window cross-origin cache initialized during bootstrap");
let value = cache.get_index(scope, 0).expect("Window cache slot");
let map = if let Ok(constructor) = v8::Local::::try_from(value) {
- let map = constructor
- .new_instance(scope, &[])
- .expect("intrinsic WeakMap construction");
+ let map = intrinsic_or_termination(scope, "intrinsic WeakMap construction", |scope| {
+ constructor.new_instance(scope, &[])
+ })?;
assert_eq!(cache.set_index(scope, 0, map.into()), Some(true));
map
} else {
@@ -70,14 +73,136 @@ pub(crate) fn cached_cross_origin_window_surface<'s>(
};
let scope = &mut v8::ContextScope::new(scope, accessing);
let key = accessing.get_extras_binding_object(scope);
- let existing = get
- .call(scope, map.into(), &[key.into()])
- .expect("intrinsic WeakMap.get");
+ let existing = intrinsic_or_termination(scope, "intrinsic WeakMap.get", |scope| {
+ get.call(scope, map.into(), &[key.into()])
+ })?;
if let Ok(surface) = v8::Local::::try_from(existing) {
- return surface;
+ return Some(surface);
}
let surface = build(scope);
- set.call(scope, map.into(), &[key.into(), surface.into()])
- .expect("intrinsic WeakMap.set");
- surface
+ intrinsic_or_termination(scope, "intrinsic WeakMap.set", |scope| {
+ set.call(scope, map.into(), &[key.into(), surface.into()])
+ })?;
+ Some(surface)
+}
+
+fn intrinsic_or_termination<'s, T>(
+ scope: &mut v8::PinScope<'s, '_>,
+ operation: &str,
+ invoke: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Option,
+) -> Option {
+ let scope = std::pin::pin!(v8::TryCatch::new(scope));
+ let scope = &mut scope.init();
+ match invoke(scope) {
+ Some(value) => Some(value),
+ // The isolate flag can reset at the V8 call boundary; TryCatch retains
+ // the termination reason. Keep the interruption visible to its caller.
+ None if scope.has_terminated() || scope.is_execution_terminating() => {
+ let _ = scope.rethrow();
+ None
+ }
+ None => panic!("{operation}"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{cell::Cell, pin::pin};
+
+ use super::*;
+
+ #[test]
+ fn terminated_execution_stops_cross_origin_cache_lookup_without_building() {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let isolate_handle = isolate.thread_safe_handle();
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let target = v8::Context::new(scope, Default::default());
+ let accessing = v8::Context::new(scope, Default::default());
+ {
+ let scope = &mut v8::ContextScope::new(scope, target);
+ initialize_cross_origin_window_cache(scope).unwrap();
+ }
+
+ let scope = &mut v8::ContextScope::new(scope, accessing);
+ assert!(isolate_handle.terminate_execution());
+ let built = Cell::new(false);
+ let surface = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
+ built.set(true);
+ v8::Object::new(scope)
+ });
+ assert!(surface.is_none());
+ assert!(!built.get());
+ assert!(scope.is_execution_terminating());
+ assert!(isolate_handle.cancel_terminate_execution());
+ }
+
+ #[test]
+ fn termination_during_surface_creation_does_not_cache_and_can_recover() {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let handle = isolate.thread_safe_handle();
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let target = v8::Context::new(scope, Default::default());
+ let accessing = v8::Context::new(scope, Default::default());
+ let other = v8::Context::new(scope, Default::default());
+ {
+ let scope = &mut v8::ContextScope::new(scope, target);
+ initialize_cross_origin_window_cache(scope).unwrap();
+ }
+ let scope = &mut v8::ContextScope::new(scope, accessing);
+ assert!(
+ cached_cross_origin_window_surface(scope, target, accessing, |scope| {
+ let surface = v8::Object::new(scope);
+ assert!(handle.terminate_execution());
+ surface
+ })
+ .is_none()
+ );
+ assert!(handle.cancel_terminate_execution());
+ let surface = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
+ v8::Object::new(scope)
+ })
+ .unwrap();
+ let cached = cached_cross_origin_window_surface(scope, target, accessing, |_| {
+ panic!("the same observer must reuse its surface")
+ })
+ .unwrap();
+ assert!(surface.strict_equals(cached.into()));
+ let distinct = cached_cross_origin_window_surface(scope, target, other, |scope| {
+ v8::Object::new(scope)
+ })
+ .unwrap();
+ assert!(!surface.strict_equals(distinct.into()));
+ }
+
+ #[test]
+ #[should_panic(expected = "intrinsic WeakMap.get")]
+ fn non_termination_cache_errors_are_not_silenced() {
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let target = v8::Context::new(scope, Default::default());
+ let accessing = v8::Context::new(scope, Default::default());
+ {
+ let scope = &mut v8::ContextScope::new(scope, target);
+ initialize_cross_origin_window_cache(scope).unwrap();
+ let anchor = target.get_extras_binding_object(scope);
+ let cache = get_private_value(scope, anchor, CACHE).unwrap();
+ let cache = v8::Local::::try_from(cache).unwrap();
+ let source = v8str(scope, "(function () { throw new Error('broken cache'); })");
+ let script = v8::Script::compile(scope, source, None).unwrap();
+ let throwing = script.run(scope).unwrap();
+ assert_eq!(cache.set_index(scope, 1, throwing), Some(true));
+ }
+ let scope = &mut v8::ContextScope::new(scope, accessing);
+ let scope = pin!(v8::TryCatch::new(scope));
+ let scope = &mut scope.init();
+ let _ = cached_cross_origin_window_surface(scope, target, accessing, |scope| {
+ v8::Object::new(scope)
+ });
+ }
}
diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
index 6b65b706df8..fd78d364a54 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
@@ -651,9 +651,11 @@ fn build_permission_status_object<'s>(
name: &str,
state: &str,
) -> v8::Local<'s, v8::Object> {
- PermissionStatusObjectDeclaration::new(name.to_owned(), state.to_owned())
+ let status = PermissionStatusObjectDeclaration::new(name.to_owned(), state.to_owned())
.bind(scope)
- .expect("PermissionStatus declaration should bind")
+ .expect("PermissionStatus declaration should bind");
+ mark_simple_event_target_slot(scope, status, "__moliPermissionStatusListeners");
+ status
}
pub(in crate::context_bootstrap) fn permission_status_name_getter_callback<'s>(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
index 79f966e1605..edc639f55d2 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
@@ -2221,7 +2221,7 @@ fn child_window_cross_origin_handler_data<'s>(
&& host.browsing_context_is_closed()
{
return Some((
- main_page::access_surface(scope, holder_context),
+ main_page::access_surface(scope, holder_context)?,
holder_context.global(scope),
));
}
@@ -2233,7 +2233,7 @@ fn child_window_cross_origin_handler_data<'s>(
}
if identity.dispatch_scope() == super::super::OwnerDispatchScope::Top {
let window = holder_context.global(scope);
- return Some((main_page::access_surface(scope, holder_context), window));
+ return Some((main_page::access_surface(scope, holder_context)?, window));
}
let super::super::OwnerDispatchScope::Child(handle) = identity.dispatch_scope() else {
return None;
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
index 75e5cbef936..93eeb4dc326 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
@@ -38,16 +38,16 @@ struct MainWindowCrossOriginSurface {
pub(super) fn access_surface<'s>(
scope: &mut v8::PinScope<'s, '_>,
target_context: v8::Local<'s, v8::Context>,
-) -> v8::Local<'s, v8::Object> {
- let surface = cached_access_surface(scope, target_context);
+) -> Option> {
+ let surface = cached_access_surface(scope, target_context)?;
refresh_indexed_children(scope, target_context, surface);
- surface
+ Some(surface)
}
fn cached_access_surface<'s>(
scope: &mut v8::PinScope<'s, '_>,
target_context: v8::Local<'s, v8::Context>,
-) -> v8::Local<'s, v8::Object> {
+) -> Option> {
let accessing_context = cross_origin_accessing_context(scope);
cached_cross_origin_window_surface(scope, target_context, accessing_context, |scope| {
let window = target_context.global(scope);
@@ -165,7 +165,7 @@ pub(super) fn location_access_surface<'s>(
) -> Option> {
let window = main_location_window(scope, receiver)?;
let context = window.get_creation_context(scope)?;
- let surface = cached_access_surface(scope, context);
+ let surface = cached_access_surface(scope, context)?;
get_private_value(scope, surface, LOCATION_SURFACE)
.and_then(|value| v8::Local::::try_from(value).ok())
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs
index b9c82e4fcba..ad4a700c8ec 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs
@@ -870,3 +870,48 @@ async fn request_relative_urls_follow_live_http_iframe_base_urls() {
assert_retained_request_uses_child_document(&mut vm, child_url.as_str());
server.await.expect("iframe response server should finish");
}
+
+#[test]
+fn permission_status_supports_inherited_event_target_listeners() {
+ let mut vm = new_storage_test_vm("https://permission-status-events.test/");
+ vm.eval(
+ r#"
+ globalThis.permissionEvents = "pending";
+ Promise.all([
+ navigator.permissions.query({name: "geolocation"}),
+ navigator.permissions.query({name: "clipboard-write"})
+ ]).then(([first, second]) => {
+ const checks = [
+ first instanceof PermissionStatus,
+ first instanceof EventTarget,
+ Object.getPrototypeOf(PermissionStatus.prototype) === EventTarget.prototype,
+ first.addEventListener === EventTarget.prototype.addEventListener
+ ];
+ let calls = 0;
+ let otherCalls = 0;
+ const listener = event => {
+ checks.push(event.target === first, event.currentTarget === first);
+ calls++;
+ };
+ first.addEventListener("change", listener);
+ second.addEventListener("change", () => otherCalls++);
+ first.dispatchEvent(new Event("change"));
+ first.removeEventListener("change", listener);
+ first.dispatchEvent(new Event("change"));
+ let once = 0;
+ first.addEventListener("change", () => once++, {once: true});
+ first.dispatchEvent(new Event("change"));
+ first.dispatchEvent(new Event("change"));
+ checks.push(calls === 1, otherCalls === 0, once === 1);
+ try { new PermissionStatus(); checks.push(false); }
+ catch (error) { checks.push(error instanceof TypeError); }
+ globalThis.permissionEvents = checks.join(",");
+ }).catch(error => { globalThis.permissionEvents = String(error); });
+ "#,
+ )
+ .expect("permission listener scenario should evaluate");
+ let result = vm
+ .eval("String(globalThis.permissionEvents)")
+ .expect("permission queries should settle");
+ assert_eq!(result, "true,true,true,true,true,true,true,true,true,true");
+}
diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rs
index d04e5b25285..e17f7df729e 100644
--- a/moli-renderer-v8/src/web_api_interfaces.rs
+++ b/moli-renderer-v8/src/web_api_interfaces.rs
@@ -379,7 +379,7 @@ interfaces! {
PerformanceTiming;
PeriodicSyncEvent: ExtendableEvent;
PeriodicSyncManager;
- PermissionStatus;
+ PermissionStatus: EventTarget;
Permissions;
Plugin;
PluginArray;