Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(navigation): share interception settlement lifecycle (#770)
Donough Liu13a1d7d15f2e
diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rsindex 100a9a6e7..8f5e461be 100644--- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs@@ -2,7 +2,7 @@ use super::location_runtime::{is_same_document_fragment_navigation, location_href_slot, resolve_location_navigation_target,sync_location_object,};-use super::navigation_activation::{clear_navigation_transition, install_navigation_transition};+use super::navigation_activation::install_navigation_transition;use super::navigation_callbacks::cancel_active_intercepted_same_document_navigation;use super::navigation_entry::history_state_value;use super::navigation_entry::{@@ -13,15 +13,10 @@ use super::navigation_events::{NavigationDispatchOutcome, cancel_active_navigation_event,dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data,dispatch_navigation_navigate_event_with_form_data_and_outcome,- dispatch_navigation_navigate_event_with_outcome, dispatch_navigation_success,- dispatch_popstate_event, queue_hash_change_for_runtime_owner,- run_navigation_precommit_deferred_handlers,-};-use super::navigation_lifecycle::{- begin_navigation_attempt, cancel_navigation_attempt, complete_navigation_attempt,- finish_navigation_error_events, navigation_attempt_id_from_slot, navigation_attempt_is_active,- settle_navigation_transition_finished_local,+ dispatch_navigation_navigate_event_with_outcome, dispatch_popstate_event,+ queue_hash_change_for_runtime_owner,};+use super::navigation_lifecycle::finish_navigation_error_events;use super::navigation_mutation::{apply_local_window_location_navigation, apply_navigation_navigate_same_document,sync_local_document_front_from_window, update_navigation_current_entry_for_same_document,@@ -42,12 +37,11 @@ use super::navigation_window::{};use super::*;use crate::native_bridge::NavigationHistoryEntrySeed;-use crate::util::{context_host_ptr_from_window_object, get_private_value, set_private_value};+use crate::util::context_host_ptr_from_window_object;use crate::webidl;use moli_page_types::{NavigationHistoryMutation, SameDocumentHistoryUpdate, cross_document_navigation_seed,};-use moli_webapi_declare::WebApiObject;#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum LocationNavigationKind {@@ -343,7 +337,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(let mut navigate_outcome = navigation.map(|navigation| {let _ = cancel_active_navigation_event(scope, navigation);cancel_active_intercepted_same_document_navigation(scope, navigation);- cancel_active_location_intercepted_same_document_navigation(scope, navigation);cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation);dispatch_navigation_navigate_event_with_outcome(scope,@@ -447,15 +440,9 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(.as_ref().is_some_and(|outcome| outcome.intercepted){- let mut outcome = navigate_outcome+ let outcome = navigate_outcome.take().expect("checked intercepted outcome");- if let Some(precommit_event) = outcome.precommit_event {- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, precommit_event);- outcome.intercept_error = intercept_error;- outcome.intercept_result = intercept_result.or(outcome.intercept_result);- }settle_location_intercepted_same_document_navigation(scope,navigation,@@ -486,7 +473,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>({let _ = cancel_active_navigation_event(scope, navigation);cancel_active_intercepted_same_document_navigation(scope, navigation);- cancel_active_location_intercepted_same_document_navigation(scope, navigation);cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation);let navigation_type = match kind {LocationNavigationKind::Assign if source_element.is_some() && exact_same_href => {@@ -502,7 +488,7 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(} else {None};- let mut outcome = dispatch_navigation_navigate_event_with_outcome(+ let outcome = dispatch_navigation_navigate_event_with_outcome(scope,navigation,resolved.as_str(),@@ -571,12 +557,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(};host.record_same_document_navigation(&url, "fragment", history_update);}- if let Some(precommit_event) = outcome.precommit_event {- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, precommit_event);- outcome.intercept_error = intercept_error;- outcome.intercept_result = intercept_result.or(outcome.intercept_result);- }settle_location_intercepted_same_document_navigation(scope,navigation,@@ -748,7 +728,6 @@ pub(crate) fn dispatch_top_level_navigation_event_with_source_element<'s>(.unwrap_or_default();let _ = cancel_active_navigation_event(scope, navigation);cancel_active_intercepted_same_document_navigation(scope, navigation);- cancel_active_location_intercepted_same_document_navigation(scope, navigation);cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation);let outcome = dispatch_navigation_navigate_event_with_outcome(scope,@@ -795,7 +774,6 @@ pub(crate) fn dispatch_top_level_form_navigation_event<'s>(.unwrap_or_default();let _ = cancel_active_navigation_event(scope, navigation);cancel_active_intercepted_same_document_navigation(scope, navigation);- cancel_active_location_intercepted_same_document_navigation(scope, navigation);cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation);let outcome = dispatch_navigation_navigate_event_with_form_data_and_outcome(scope,@@ -830,79 +808,6 @@ fn top_level_document_is_before_load_complete(scope: &mut v8::PinScope<'_, '_>)})}-const LOCATION_INTERCEPT_SETTLEMENT_NAVIGATION_SLOT: &str = "__lmLocationInterceptNavigation";-const LOCATION_INTERCEPT_SETTLEMENT_SIGNAL_SLOT: &str = "__lmLocationInterceptSignal";-const LOCATION_INTERCEPT_SETTLEMENT_FILENAME_SLOT: &str = "__lmLocationInterceptFilename";-const LOCATION_INTERCEPT_SETTLEMENT_PROMISE_SLOT: &str = "__lmLocationInterceptPromise";-const LOCATION_INTERCEPT_SETTLEMENT_TRANSITION_RESOLVER_SLOT: &str =- "__lmLocationInterceptTransitionResolver";-const LOCATION_INTERCEPT_SETTLEMENT_ACTIVE_SLOT: &str = "__lmLocationInterceptActive";-const LOCATION_INTERCEPT_SETTLEMENT_ATTEMPT_ID_SLOT: &str = "__lmLocationInterceptAttemptId";-const NAVIGATION_ACTIVE_LOCATION_INTERCEPT_SETTLEMENT_SLOT: &str =- "__lmNavigationActiveLocationInterceptSettlement";--#[derive(WebApiObject)]-#[webapi(plain)]-struct LocationInterceptSettlementDataDeclaration<'scope> {- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_ACTIVE_SLOT)]- active: bool,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_ATTEMPT_ID_SLOT)]- attempt_id: Option<v8::Local<'scope, v8::BigInt>>,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_PROMISE_SLOT)]- promise: Option<v8::Local<'scope, v8::Value>>,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_NAVIGATION_SLOT)]- navigation: v8::Local<'scope, v8::Object>,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_SIGNAL_SLOT)]- signal: Option<v8::Local<'scope, v8::Object>>,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_TRANSITION_RESOLVER_SLOT)]- transition_resolver: Option<v8::Local<'scope, v8::PromiseResolver>>,-- #[webapi(slot = LOCATION_INTERCEPT_SETTLEMENT_FILENAME_SLOT)]- filename: v8::Local<'scope, v8::String>,-}--fn navigation_active_location_intercept_settlement<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Object>> {- get_private_value(- scope,- navigation,- NAVIGATION_ACTIVE_LOCATION_INTERCEPT_SETTLEMENT_SLOT,- )- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())-}--fn set_navigation_active_location_intercept_settlement<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,- data: v8::Local<'s, v8::Object>,-) {- set_private_value(- scope,- navigation,- NAVIGATION_ACTIVE_LOCATION_INTERCEPT_SETTLEMENT_SLOT,- data.into(),- );-}--fn clear_navigation_active_location_intercept_settlement<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,-) {- set_private_value(- scope,- navigation,- NAVIGATION_ACTIVE_LOCATION_INTERCEPT_SETTLEMENT_SLOT,- v8::undefined(scope).into(),- );-}-fn finish_location_navigation_canceled<'s>(scope: &mut v8::PinScope<'s, '_>,navigation: v8::Local<'s, v8::Object>,@@ -925,283 +830,21 @@ fn settle_location_intercepted_same_document_navigation<'s>(transition_resolver: Option<v8::Local<'s, v8::PromiseResolver>>,filename: &str,) {- if let Some(error) = outcome.intercept_error {- finish_location_intercepted_navigation_rejected(- scope,- navigation,- outcome.signal,- transition_resolver,- error,- filename,- );- return;- }- let Some(result) = outcome.intercept_result else {- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);- return;- };- let Some(result_object) = v8::Local::<v8::Object>::try_from(result).ok() else {- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);- return;- };- let Some(then) = result_object- .get(scope, v8str(scope, "then").into())- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())- else {- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);- return;- };- let attempt_id = begin_navigation_attempt(scope, "location-intercept-settlement")- .map(|attempt_id| v8::BigInt::new_from_u64(scope, attempt_id.raw()));- let promise = v8::Local::<v8::Promise>::try_from(result)- .is_ok()- .then_some(result);- let filename = v8_string(scope, filename).unwrap_or_else(|| v8::String::empty(scope));- let data = LocationInterceptSettlementDataDeclaration::new(- true,- attempt_id,- promise,- navigation,- outcome.signal,- transition_resolver,- filename,- )- .bind(scope)- .expect("location intercept settlement data should bind");- set_navigation_active_location_intercept_settlement(scope, navigation, data);- let Some(on_fulfilled) =- v8::Function::builder(location_intercept_settlement_fulfilled_callback)- .data(data.into())- .build(scope)- else {- complete_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);- return;- };- let Some(on_rejected) = v8::Function::builder(location_intercept_settlement_rejected_callback)- .data(data.into())- .build(scope)- else {- complete_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);- return;- };- if then- .call(scope, result, &[on_fulfilled.into(), on_rejected.into()])- .is_none()- {- cancel_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- }-}--fn location_intercept_settlement_data<'s>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Value>,-) -> Option<(- v8::Local<'s, v8::Object>,- Option<v8::Local<'s, v8::Object>>,- Option<v8::Local<'s, v8::Promise>>,- Option<v8::Local<'s, v8::PromiseResolver>>,- String,-)> {- let data = v8::Local::<v8::Object>::try_from(data).ok()?;- let navigation = get_private_value(scope, data, LOCATION_INTERCEPT_SETTLEMENT_NAVIGATION_SLOT)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;- let signal = get_private_value(scope, data, LOCATION_INTERCEPT_SETTLEMENT_SIGNAL_SLOT)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());- let promise = get_private_value(scope, data, LOCATION_INTERCEPT_SETTLEMENT_PROMISE_SLOT)- .and_then(|value| v8::Local::<v8::Promise>::try_from(value).ok());- let transition_resolver = get_private_value(- scope,- data,- LOCATION_INTERCEPT_SETTLEMENT_TRANSITION_RESOLVER_SLOT,- )- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- .map(|object| unsafe { v8::Local::<v8::PromiseResolver>::cast_unchecked(object) });- let filename = get_private_value(scope, data, LOCATION_INTERCEPT_SETTLEMENT_FILENAME_SLOT)- .and_then(|value| value.to_string(scope))- .map(|value| value.to_rust_string_lossy(scope))- .unwrap_or_default();- Some((navigation, signal, promise, transition_resolver, filename))-}--fn location_intercept_settlement_fulfilled_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- _rv: v8::ReturnValue<'_, v8::Value>,-) {- if !location_intercept_settlement_is_active(scope, args.data()) {- return;- }- let Some((navigation, _, _, transition_resolver, _)) =- location_intercept_settlement_data(scope, args.data())- else {- return;- };- if let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) {- complete_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- }- dispatch_navigation_success(scope, navigation);- settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);-}--fn location_intercept_settlement_rejected_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- _rv: v8::ReturnValue<'_, v8::Value>,-) {- if !location_intercept_settlement_is_active(scope, args.data()) {- return;- }- let Some((navigation, signal, promise, transition_resolver, filename)) =- location_intercept_settlement_data(scope, args.data())- else {- return;- };- if let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) {- complete_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- }- let error = promise- .filter(|promise| promise.state() == v8::PromiseState::Rejected)- .map(|promise| promise.result(scope))- .unwrap_or_else(|| args.get(0));- finish_location_intercepted_navigation_rejected(- scope,- navigation,- signal,- transition_resolver,- error,- &filename,- );-}--fn finish_location_intercepted_navigation_rejected<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,- signal: Option<v8::Local<'s, v8::Object>>,- transition_resolver: Option<v8::Local<'s, v8::PromiseResolver>>,- error: v8::Local<'s, v8::Value>,- filename: &str,-) {- if let Some(signal) = signal- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)- {- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);- }- finish_navigation_error_events(scope, navigation, error, filename);- settle_navigation_transition_finished_local(+ let owner = runtime_window_owner(scope, navigation);+ let resolved_value = navigation_current_entry(scope, owner)+ .map(v8::Local::<v8::Value>::from)+ .unwrap_or_else(|| v8::undefined(scope).into());+ super::navigation_callbacks::settle_intercepted_same_document_navigation(scope,navigation,+ outcome,+ None,+ None,+ None,transition_resolver,- Some(error),- );-}--fn cancel_active_location_intercepted_same_document_navigation<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,-) -> bool {- let Some(data) = navigation_active_location_intercept_settlement(scope, navigation) else {- return false;- };- if !location_intercept_settlement_is_active(scope, data.into()) {- return false;- }- cancel_location_intercept_settlement_attempt(scope, data);- set_location_intercept_settlement_active(scope, navigation, data, false);- let Some((navigation, signal, _, transition_resolver, filename)) =- location_intercept_settlement_data(scope, data.into())- else {- return false;- };- let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");- if let Some(signal) = signal- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)- {- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);- }- finish_navigation_error_events(scope, navigation, error, &filename);- if transition_resolver.is_some() {- clear_navigation_transition(scope, navigation);- }- if let Some(transition_resolver) = transition_resolver {- let _ = transition_resolver.reject(scope, error);- }- true-}--fn location_intercept_settlement_is_active<'s>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Value>,-) -> bool {- v8::Local::<v8::Object>::try_from(data)- .ok()- .is_some_and(|data| {- location_intercept_settlement_active(scope, data)- && navigation_attempt_id_from_slot(- scope,- data,- LOCATION_INTERCEPT_SETTLEMENT_ATTEMPT_ID_SLOT,- )- .is_some_and(|attempt_id| navigation_attempt_is_active(scope, attempt_id))- })-}--fn location_intercept_settlement_active<'s>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Object>,-) -> bool {- get_private_value(scope, data, LOCATION_INTERCEPT_SETTLEMENT_ACTIVE_SLOT)- .is_some_and(|value| value.is_boolean() && value.boolean_value(scope))-}--fn complete_location_intercept_settlement_attempt<'s>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Object>,-) {- if let Some(attempt_id) =- navigation_attempt_id_from_slot(scope, data, LOCATION_INTERCEPT_SETTLEMENT_ATTEMPT_ID_SLOT)- {- complete_navigation_attempt(scope, attempt_id);- }-}--fn cancel_location_intercept_settlement_attempt<'s>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Object>,-) {- if let Some(attempt_id) =- navigation_attempt_id_from_slot(scope, data, LOCATION_INTERCEPT_SETTLEMENT_ATTEMPT_ID_SLOT)- {- cancel_navigation_attempt(scope, attempt_id);- }-}--fn set_location_intercept_settlement_active<'s>(- scope: &mut v8::PinScope<'s, '_>,- navigation: v8::Local<'s, v8::Object>,- data: v8::Local<'s, v8::Object>,- active: bool,-) {- set_private_value(- scope,- data,- LOCATION_INTERCEPT_SETTLEMENT_ACTIVE_SLOT,- v8::Boolean::new(scope, active).into(),+ resolved_value,+ filename,);- if !active {- clear_navigation_active_location_intercept_settlement(scope, navigation);- }}fn history_entry_seed_for_cross_document_location<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/methods.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/methods.rsindex a3db07e97..e5ef4a25a 100644--- a/moli-renderer-v8/src/context_bootstrap/location_runtime/methods.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/methods.rs@@ -46,7 +46,7 @@ pub(super) fn location_replace_callback<'s>(if require_location_href_slot(scope, args.this()).is_none() {return;}- navigate_location_object(+ navigate_location_object_with_child_navigate_event(scope,args.this(),LocationNavigationKind::Replace,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rsindex 4346907dc..af2ecf844 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs@@ -348,7 +348,7 @@ fn settle_navigation_transition_callback<'s>(}}-fn navigation_transition_matches_resolver<'s>(+pub(super) fn navigation_transition_matches_resolver<'s>(scope: &mut v8::PinScope<'s, '_>,navigation: v8::Local<'s, v8::Object>,resolver: v8::Local<'s, v8::PromiseResolver>,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rsindex 5c4a4f828..153f0d205 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs@@ -26,7 +26,7 @@ use super::navigation_result::{navigation_immediate_result_with_value, navigation_pending_result,navigation_rejected_dom_exception_result, navigation_rejected_invalid_state_result,navigation_rejected_value_result, navigation_result_with_pending_commit,- queue_same_document_navigation_finished,+ queue_same_document_navigation_finished, suppress_unhandled_rejection,};use super::navigation_serialize::sync_child_navigation_entry_seed_from_owner;use super::navigation_window::{diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rsindex 9d9df4973..0cfae2ee0 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs@@ -1,12 +1,15 @@use super::super::navigation_activation::{clear_navigation_transition, install_navigation_transition,- reject_navigation_transition_committed, resolve_navigation_transition_committed,+ navigation_transition_matches_resolver, reject_navigation_transition_committed,+ resolve_navigation_transition_committed,};use super::super::navigation_events::dispatch_popstate_event;use super::super::navigation_lifecycle::{begin_navigation_attempt, cancel_navigation_attempt, complete_navigation_attempt,- finish_navigation_error_events, navigation_attempt_id_from_slot, navigation_attempt_is_active,+ finish_navigation_error_events, finish_navigation_success_events,+ navigation_attempt_id_from_slot, navigation_attempt_is_active, settle_navigation_committed,settle_navigation_finished_rejected_after_reactions,+ settle_navigation_finished_resolved_after_reactions,settle_navigation_transition_finished_local,};use super::super::navigation_window::{@@ -249,7 +252,7 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(} else {false};- let mut navigate_outcome = navigation_for_event.map(|navigation| {+ let navigate_outcome = navigation_for_event.map(|navigation| {dispatch_navigation_navigate_event_with_outcome(scope,navigation,@@ -409,6 +412,9 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(rv.set(pending.object.into());return;}+ let intercepted = navigate_outcome+ .as_ref()+ .is_some_and(|outcome| outcome.intercepted);let transition_from = navigate_outcome.as_ref().is_some_and(|outcome| outcome.intercepted)@@ -443,17 +449,6 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(effective_kind,effective_state,);- if let Some(outcome) = navigate_outcome.as_mut()- && let Some(precommit_event) = outcome.precommit_event- {- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, precommit_event);- outcome.intercept_error = intercept_error;- outcome.intercept_result = intercept_result.or(outcome.intercept_result);- }- let intercepted = navigate_outcome- .as_ref()- .is_some_and(|outcome| outcome.intercepted);let result = if intercepted {let Some(pending) = navigation_current_entry_result_with_pending_finished(scope, owner)else {@@ -469,8 +464,8 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(navigation,outcome,Some(pending.committed_resolve),- pending.finished_resolve,- pending.finished_reject,+ Some(pending.finished_resolve),+ Some(pending.finished_reject),transition_resolver,pending.resolved_value,¤t_href,@@ -519,7 +514,7 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(LocationNavigationKind::Assign}};- let mut outcome = dispatch_navigation_navigate_event_with_outcome(+ let outcome = dispatch_navigation_navigate_event_with_outcome(scope,navigation,next_url.as_str(),@@ -635,12 +630,6 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(effective_kind,effective_state,);- if let Some(precommit_event) = outcome.precommit_event {- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, precommit_event);- outcome.intercept_error = intercept_error;- outcome.intercept_result = intercept_result.or(outcome.intercept_result);- }let Some(pending) = navigation_current_entry_result_with_pending_finished(scope, owner)else {let result = navigation_immediate_result_with_value(scope, resolved_value);@@ -652,8 +641,8 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(navigation,outcome,Some(pending.committed_resolve),- pending.finished_resolve,- pending.finished_reject,+ Some(pending.finished_resolve),+ Some(pending.finished_reject),transition_resolver,pending.resolved_value,¤t_href,@@ -1254,8 +1243,6 @@ fn precommit_commit_fulfilled_callback<'s>(.committed_resolve.call(scope, receiver, &[resolved_value]);resolve_navigation_transition_committed(scope, data.navigation, resolved_value);- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, data.event);let outcome = NavigationDispatchOutcome {proceed: true,intercepted: true,@@ -1267,11 +1254,11 @@ fn precommit_commit_fulfilled_callback<'s>(redirected_url: None,redirected_history: None,redirected_state: None,- precommit_event: None,+ precommit_event: Some(data.event),precommit_error: None,precommit_result: None,- intercept_error,- intercept_result,+ intercept_error: None,+ intercept_result: None,abort_error: None,};settle_intercepted_same_document_navigation(@@ -1279,8 +1266,8 @@ fn precommit_commit_fulfilled_callback<'s>(data.navigation,outcome,None,- data.finished_resolve,- data.finished_reject,+ Some(data.finished_resolve),+ Some(data.finished_reject),data.transition_resolver,resolved_value,&data.current_href,@@ -1361,10 +1348,10 @@ struct InterceptSettlementDataDeclaration<'scope> {signal: Option<v8::Local<'scope, v8::Object>>,#[webapi(slot = INTERCEPT_SETTLEMENT_RESOLVE_SLOT)]- resolve: v8::Local<'scope, v8::Function>,+ resolve: Option<v8::Local<'scope, v8::Function>>,#[webapi(slot = INTERCEPT_SETTLEMENT_REJECT_SLOT)]- reject: v8::Local<'scope, v8::Function>,+ reject: Option<v8::Local<'scope, v8::Function>>,#[webapi(slot = INTERCEPT_SETTLEMENT_TRANSITION_RESOLVER_SLOT)]transition_resolver: Option<v8::Local<'scope, v8::PromiseResolver>>,@@ -1416,22 +1403,61 @@ fn clear_navigation_active_intercept_settlement<'s>(pub(in crate::context_bootstrap) fn settle_intercepted_same_document_navigation<'s>(scope: &mut v8::PinScope<'s, '_>,navigation: v8::Local<'s, v8::Object>,- outcome: NavigationDispatchOutcome<'s>,+ mut outcome: NavigationDispatchOutcome<'s>,mut committed_resolve: Option<v8::Local<'s, v8::Function>>,- finished_resolve: v8::Local<'s, v8::Function>,- finished_reject: v8::Local<'s, v8::Function>,+ finished_resolve: Option<v8::Local<'s, v8::Function>>,+ finished_reject: Option<v8::Local<'s, v8::Function>>,transition_resolver: Option<v8::Local<'s, v8::PromiseResolver>>,resolved_value: v8::Local<'s, v8::Value>,filename: &str,) {- if (outcome.intercept_error.is_some() || outcome.intercept_result.is_some())- && let Some(resolve) = committed_resolve.take()- {+ let attempt_id = begin_navigation_attempt(scope, "intercept-settlement")+ .map(|attempt_id| v8::BigInt::new_from_u64(scope, attempt_id.raw()));+ let filename_value = v8_string(scope, filename).unwrap_or_else(|| v8::String::empty(scope));+ let data = InterceptSettlementDataDeclaration {+ active: true,+ attempt_id,+ promise: None,+ navigation,+ committed_resolve: None,+ signal: outcome.signal,+ resolve: finished_resolve,+ reject: finished_reject,+ transition_resolver,+ value: resolved_value,+ filename: filename_value,+ }+ .bind(scope)+ .expect("intercept settlement data should bind");+ // Handlers can stop, detach, or supersede this navigation synchronously.+ // Register its settlement before invoking any of them, and keep the+ // committed entry captured before a reentrant navigation can replace it.+ set_navigation_active_intercept_settlement(scope, navigation, data);+ if let Some(resolve) = committed_resolve.take() {let receiver = v8::undefined(scope).into();let _ = resolve.call(scope, receiver, &[resolved_value]);+ }+ if transition_resolver+ .is_some_and(|resolver| navigation_transition_matches_resolver(scope, navigation, resolver))+ {resolve_navigation_transition_committed(scope, navigation, resolved_value);}+ if let Some(event) = outcome.precommit_event {+ let (error, result) = run_navigation_precommit_deferred_handlers(scope, event);+ outcome.intercept_error = error.or(outcome.intercept_error);+ outcome.intercept_result = result.or(outcome.intercept_result);+ }+ if !intercept_settlement_is_active(scope, data.into()) {+ if let Some(result) = outcome.intercept_result+ && let Ok(promise) = v8::Local::<v8::Promise>::try_from(result)+ {+ suppress_unhandled_rejection(scope, promise);+ }+ return;+ }if let Some(error) = outcome.intercept_error {+ complete_intercept_settlement_attempt(scope, data);+ set_intercept_settlement_active(scope, navigation, data, false);finish_intercepted_navigation_rejected(scope,navigation,@@ -1446,6 +1472,8 @@ pub(in crate::context_bootstrap) fn settle_intercepted_same_document_navigation<return;}let Some(result) = outcome.intercept_result else {+ complete_intercept_settlement_attempt(scope, data);+ set_intercept_settlement_active(scope, navigation, data, false);finish_intercepted_navigation_fulfilled(scope,navigation,@@ -1459,6 +1487,8 @@ pub(in crate::context_bootstrap) fn settle_intercepted_same_document_navigation<return;};let Some(result_object) = v8::Local::<v8::Object>::try_from(result).ok() else {+ complete_intercept_settlement_attempt(scope, data);+ set_intercept_settlement_active(scope, navigation, data, false);finish_intercepted_navigation_fulfilled(scope,navigation,@@ -1475,6 +1505,8 @@ pub(in crate::context_bootstrap) fn settle_intercepted_same_document_navigation<.get(scope, v8str(scope, "then").into()).and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())else {+ complete_intercept_settlement_attempt(scope, data);+ set_intercept_settlement_active(scope, navigation, data, false);finish_intercepted_navigation_fulfilled(scope,navigation,@@ -1487,28 +1519,9 @@ pub(in crate::context_bootstrap) fn settle_intercepted_same_document_navigation<);return;};- let attempt_id = begin_navigation_attempt(scope, "intercept-settlement")- .map(|attempt_id| v8::BigInt::new_from_u64(scope, attempt_id.raw()));- let promise = v8::Local::<v8::Promise>::try_from(result)- .is_ok()- .then_some(result);- let filename = v8_string(scope, filename).unwrap_or_else(|| v8::String::empty(scope));- let data = InterceptSettlementDataDeclaration {- active: true,- attempt_id,- promise,- navigation,- committed_resolve,- signal: outcome.signal,- resolve: finished_resolve,- reject: finished_reject,- transition_resolver,- value: resolved_value,- filename,+ if v8::Local::<v8::Promise>::try_from(result).is_ok() {+ set_private_value(scope, data, INTERCEPT_SETTLEMENT_PROMISE_SLOT, result);}- .bind(scope)- .expect("intercept settlement data should bind");- set_navigation_active_intercept_settlement(scope, navigation, data);let Some(on_fulfilled) = v8::Function::builder(intercept_settlement_fulfilled_callback).data(data.into()).build(scope)@@ -1592,11 +1605,13 @@ pub(in crate::context_bootstrap) fn cancel_active_intercepted_same_document_navilet _ = committed_resolve.call(scope, receiver, &[resolved_value]);resolve_navigation_transition_committed(scope, navigation, resolved_value);}- let _ = reject.call(scope, receiver, &[error]);- if transition_resolver.is_some() {- clear_navigation_transition(scope, navigation);+ if let Some(reject) = reject {+ let _ = reject.call(scope, receiver, &[error]);}if let Some(transition_resolver) = transition_resolver {+ if navigation_transition_matches_resolver(scope, navigation, transition_resolver) {+ clear_navigation_transition(scope, navigation);+ }let _ = transition_resolver.reject(scope, error);}true@@ -1661,7 +1676,10 @@ fn set_intercept_settlement_active<'s>(INTERCEPT_SETTLEMENT_ACTIVE_SLOT,v8::Boolean::new(scope, active).into(),);- if !active {+ if !active+ && navigation_active_intercept_settlement(scope, navigation)+ .is_some_and(|current| current.strict_equals(data.into()))+ {clear_navigation_active_intercept_settlement(scope, navigation);}}@@ -1673,8 +1691,8 @@ fn intercept_settlement_data<'s>(v8::Local<'s, v8::Object>,Option<v8::Local<'s, v8::Object>>,Option<v8::Local<'s, v8::Function>>,- v8::Local<'s, v8::Function>,- v8::Local<'s, v8::Function>,+ Option<v8::Local<'s, v8::Function>>,+ Option<v8::Local<'s, v8::Function>>,v8::Local<'s, v8::Value>,Option<v8::Local<'s, v8::Promise>>,Option<v8::Local<'s, v8::PromiseResolver>>,@@ -1690,9 +1708,8 @@ fn intercept_settlement_data<'s>(.and_then(|value| v8::Local::<v8::Function>::try_from(value).ok());let resolve = get_private_value(scope, data, INTERCEPT_SETTLEMENT_RESOLVE_SLOT).and_then(|value| v8::Local::<v8::Function>::try_from(value).ok());- let resolve = resolve?;let reject = get_private_value(scope, data, INTERCEPT_SETTLEMENT_REJECT_SLOT)- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())?;+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok());let resolved_value = get_private_value(scope, data, INTERCEPT_SETTLEMENT_VALUE_SLOT).unwrap_or_else(|| v8::undefined(scope).into());let promise = get_private_value(scope, data, INTERCEPT_SETTLEMENT_PROMISE_SLOT)@@ -1728,10 +1745,10 @@ fn intercept_settlement_fulfilled_callback<'s>(}let Some((navigation,- signal,+ _,committed_resolve,resolve,- reject,+ _,resolved_value,_,transition_resolver,@@ -1744,16 +1761,16 @@ fn intercept_settlement_fulfilled_callback<'s>(complete_intercept_settlement_attempt(scope, data);set_intercept_settlement_active(scope, navigation, data, false);}- finish_intercepted_navigation_fulfilled(- scope,- navigation,- signal,- committed_resolve,- resolve,- reject,- transition_resolver,- resolved_value,- );+ // This callback already runs as the handler promise's fulfillment reaction.+ // Another queued completion would put navigatesuccess after author microtasks.+ finish_navigation_success_events(scope, navigation, "");+ if let Some(resolve) = committed_resolve {+ settle_navigation_committed(scope, navigation, resolve, resolved_value);+ }+ if let Some(resolve) = resolve {+ settle_navigation_finished_resolved_after_reactions(scope, resolve, resolved_value);+ }+ settle_navigation_transition_finished_local(scope, navigation, transition_resolver, None);}fn intercept_settlement_rejected_callback<'s>(@@ -1804,8 +1821,8 @@ fn finish_intercepted_navigation_fulfilled<'s>(navigation: v8::Local<'s, v8::Object>,signal: Option<v8::Local<'s, v8::Object>>,committed_resolve: Option<v8::Local<'s, v8::Function>>,- finished_resolve: v8::Local<'s, v8::Function>,- finished_reject: v8::Local<'s, v8::Function>,+ finished_resolve: Option<v8::Local<'s, v8::Function>>,+ finished_reject: Option<v8::Local<'s, v8::Function>>,transition_resolver: Option<v8::Local<'s, v8::PromiseResolver>>,resolved_value: v8::Local<'s, v8::Value>,) {@@ -1814,8 +1831,8 @@ fn finish_intercepted_navigation_fulfilled<'s>(navigation,signal,committed_resolve,- Some(finished_resolve),- Some(finished_reject),+ finished_resolve,+ finished_reject,Some(resolved_value),transition_resolver,"",@@ -1828,7 +1845,7 @@ fn finish_intercepted_navigation_rejected<'s>(signal: Option<v8::Local<'s, v8::Object>>,committed_resolve: Option<v8::Local<'s, v8::Function>>,resolved_value: v8::Local<'s, v8::Value>,- finished_reject: v8::Local<'s, v8::Function>,+ finished_reject: Option<v8::Local<'s, v8::Function>>,transition_resolver: Option<v8::Local<'s, v8::PromiseResolver>>,error: v8::Local<'s, v8::Value>,filename: &str,@@ -1844,7 +1861,9 @@ fn finish_intercepted_navigation_rejected<'s>(let _ = committed_resolve.call(scope, receiver, &[resolved_value]);resolve_navigation_transition_committed(scope, navigation, resolved_value);}- settle_navigation_finished_rejected_after_reactions(scope, finished_reject, error);+ if let Some(reject) = finished_reject {+ settle_navigation_finished_rejected_after_reactions(scope, reject, error);+ }settle_navigation_transition_finished_local(scope,navigation,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rsindex c542a4b76..8670589b2 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs@@ -21,7 +21,6 @@ use super::navigation_entry_state::{use super::navigation_events::cancel_active_navigation_event;use super::navigation_events::{dispatch_navigation_currententrychange, dispatch_navigation_navigate_event_with_outcome,- run_navigation_precommit_deferred_handlers,};use super::navigation_lifecycle::finish_navigation_error_events;use super::navigation_projection::visible_navigation_entries_len;@@ -283,7 +282,7 @@ pub(super) fn navigation_reload_callback<'s>(let current_href = super::location_runtime::location_href_slot(scope, location).unwrap_or_else(|| "about:blank".to_owned());let destination_state = reload_destination_state(scope, owner, cloned_navigation_state);- let mut outcome = dispatch_navigation_navigate_event_with_outcome(+ let outcome = dispatch_navigation_navigate_event_with_outcome(scope,navigation,¤t_href,@@ -363,12 +362,6 @@ pub(super) fn navigation_reload_callback<'s>(if let Some(state) = cloned_navigation_state {set_reload_current_entry_state(scope, owner, state);}- if let Some(precommit_event) = outcome.precommit_event {- let (intercept_error, intercept_result) =- run_navigation_precommit_deferred_handlers(scope, precommit_event);- outcome.intercept_error = intercept_error;- outcome.intercept_result = intercept_result.or(outcome.intercept_result);- }let Some(pending) = navigation_current_entry_result_with_pending_finished(scope, owner)else {rv.set(navigation_immediate_current_entry_result(scope, owner).into());@@ -379,8 +372,8 @@ pub(super) fn navigation_reload_callback<'s>(navigation,outcome,Some(pending.committed_resolve),- pending.finished_resolve,- pending.finished_reject,+ Some(pending.finished_resolve),+ Some(pending.finished_reject),transition_resolver,pending.resolved_value,¤t_href,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rsindex 6627b1edf..c521be609 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs@@ -2995,6 +2995,146 @@ async fn pending_precommit_navigation_slot_is_not_script_writable() {"#two:precommitSpoof:false:reload|navigate:|precommit:|exposed:false|abort:AbortError:|navigate:|precommit:|handler:#two|firstCommittedRejected:AbortError|firstFinishedRejected:AbortError|secondCommitted:#two|secondFinished:#two");}+#[tokio::test]+async fn navigation_intercept_handlers_preserve_cancellation_and_committed_entry() {+ for api in [+ "location-fragment",+ "navigate-fragment",+ "navigate-cross-document",+ "reload",+ "precommit",+ ] {+ for cause in ["none", "stop", "detach", "throw"] {+ let server = StaticHttpServer::spawn(1).await;+ let parent_url = server.base_url().join("parent").unwrap();+ let loader = static_http_loader([]);+ let mut vm =+ new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);+ let script = include_str!("../../../../tests/fixtures/navigation-interception.js");+ vm.eval(&format!(+ "{script}\n\+ globalThis.interceptionResult = 'pending';\n\+ navigationInterceptionProbe({api:?}, {cause:?}).then(\n\+ value => interceptionResult = value,\n\+ error => interceptionResult = String(error));"+ ))+ .unwrap();+ let context = format!("{api}/{cause}");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(interceptionResult !== 'pending')",+ "true",+ &context,+ )+ .await;+ let result: serde_json::Value =+ serde_json::from_str(&vm.eval("JSON.stringify(interceptionResult)").unwrap())+ .unwrap();+ let (log, settlement) = match cause {+ "none" => (+ vec!["navigate", "first", "first-after", "second", "success"],+ "fulfilled",+ ),+ "throw" => (+ vec!["navigate", "first", "second", "abort", "error:Error"],+ "Error",+ ),+ _ => (+ vec![+ "navigate",+ "first",+ "abort",+ "error:AbortError",+ "first-after",+ "second",+ ],+ "AbortError",+ ),+ };+ let promises = if api.starts_with("location-") {+ serde_json::json!([])+ } else {+ serde_json::json!(["fulfilled", settlement])+ };+ assert_eq!(+ result,+ serde_json::json!({+ "log": log,+ "entryChanges": 1,+ "defaultPrevented": false,+ "aborted": cause != "none",+ "transition": ["fulfilled", settlement],+ "promises": promises,+ "committedEntry": true,+ "sameReason": true,+ "errorKind": true,+ "transitionCleared": true+ }),+ "{context}"+ );+ assert_eq!(server.finish_targets().await, ["/child"], "{context}");+ }+ }+}++#[tokio::test]+async fn navigation_intercept_reentrant_handlers_preserve_replacement_navigation() {+ for throws_after_replacement in [false, true] {+ let server = StaticHttpServer::spawn(1).await;+ let parent_url = server.base_url().join("parent").unwrap();+ let loader = static_http_loader([]);+ let mut vm =+ new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);+ let script = include_str!("../../../../tests/fixtures/navigation-interception.js");+ vm.eval(&format!(+ "{script}\n\+ globalThis.interceptionResult = 'pending';\n\+ navigationReentrantInterceptionProbe({throws_after_replacement}).then(\n\+ value => interceptionResult = value,\n\+ error => interceptionResult = String(error));"+ ))+ .unwrap();+ let context = format!("throws after replacement: {throws_after_replacement}");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(interceptionResult !== 'pending')",+ "true",+ &context,+ )+ .await;+ let result: serde_json::Value =+ serde_json::from_str(&vm.eval("JSON.stringify(interceptionResult)").unwrap()).unwrap();+ let mut log = vec!["first", "abort", "replacement-handler"];+ if !throws_after_replacement {+ log.push("first-after");+ }+ log.push("second");+ assert_eq!(+ result,+ serde_json::json!({+ "before": {+ "activeTransition": true,+ "promises": ["fulfilled", "AbortError"],+ "transition": ["fulfilled", "AbortError"],+ "committedEntry": true,+ "sameReason": true,+ "errors": 1,+ "successes": 0+ },+ "log": log,+ "replacementEntry": true,+ "transitionCleared": true,+ "errors": 1,+ "successes": 1+ }),+ "{context}"+ );+ assert_eq!(server.finish_targets().await, ["/child"], "{context}");+ }+}+#[tokio::test]async fn nested_same_document_navigation_marks_outer_event_canceled() {let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rsindex cf410770c..be6594dfa 100644--- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs+++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs@@ -88,11 +88,6 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[2,DirectCallOwner::BrowserAlgorithm,),- allowed(- "context_bootstrap/location_navigation.rs",- 1,- DirectCallOwner::BrowserAlgorithm,- ),allowed("context_bootstrap/navigation_callbacks/navigation.rs",11,diff --git a/moli-renderer-v8/tests/fixtures/navigation-interception.js b/moli-renderer-v8/tests/fixtures/navigation-interception.jsnew file mode 100644index 000000000..e9f896023--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/navigation-interception.js@@ -0,0 +1,144 @@+globalThis.navigationInterceptionProbe = async function(api, cause) {+ const frame = document.createElement('iframe');+ frame.src = new URL('/child', location.href).href;+ const loaded = new Promise(resolve => frame.onload = resolve);+ (document.body || document.documentElement || document).appendChild(frame);+ await loaded;+ const child = frame.contentWindow;+ const nav = child.navigation;+ const url = child.location.href;+ const Exception = child.DOMException;+ const failure = new child.Error('handler failure');+ const log = [];+ const done = Promise.withResolvers();+ let event;+ let transition;+ let observedTransition;+ let committedEntry = nav.currentEntry;+ let entryChanges = 0;+ let error;+ nav.addEventListener('currententrychange', () => {+ committedEntry = nav.currentEntry;+ entryChanges++;+ });+ nav.addEventListener('navigateerror', e => {+ error = e.error;+ log.push('error:' + error.name);+ done.resolve();+ });+ nav.addEventListener('navigatesuccess', () => {+ log.push('success');+ done.resolve();+ });+ nav.addEventListener('navigate', e => {+ event = e;+ log.push('navigate');+ e.signal.addEventListener('abort', () => log.push('abort'));+ const options = {handler() {+ transition = nav.transition;+ observedTransition = Promise.allSettled([transition.committed, transition.finished]);+ log.push('first');+ if(cause === 'detach') frame.remove();+ if(cause === 'stop') child.stop();+ if(cause === 'throw') throw failure;+ log.push('first-after');+ }};+ if(api === 'precommit') options.precommitHandler = () => Promise.resolve();+ e.intercept(options);+ e.intercept({handler() {log.push('second');}});+ }, {once: true});+ let result;+ if(api === 'location-fragment') child.location.href = url + '#destination';+ else if(api === 'location-cross-document') child.location.href = '/intercepted';+ else if(api === 'location-replace') child.location.replace('/intercepted');+ else if(api === 'location-reload') child.location.reload();+ else if(api === 'reload') result = nav.reload();+ else result = nav.navigate(api === 'navigate-cross-document' ? '/intercepted' : url + '#destination');+ if(result) {+ result.committed.catch(() => {});+ result.finished.catch(() => {});+ }+ await done.promise;+ const transitionResults = await observedTransition;+ const apiResults = result ? await Promise.allSettled([result.committed, result.finished]) : [];+ const rejected = [...transitionResults, ...apiResults].filter(value => value.status === 'rejected');+ const record = {+ log,+ entryChanges,+ defaultPrevented: event.defaultPrevented,+ aborted: event.signal.aborted,+ transition: transitionResults.map(value => value.status === 'fulfilled' ? 'fulfilled' : value.reason.name),+ promises: apiResults.map(value => value.status === 'fulfilled' ? 'fulfilled' : value.reason.name),+ committedEntry: !result || apiResults[0].value === committedEntry,+ sameReason: rejected.every(value => value.reason === error && value.reason === event.signal.reason),+ errorKind: error === undefined || (cause === 'throw' ? error === failure : error instanceof Exception),+ transitionCleared: nav.transition === null+ };+ frame.remove();+ return record;+};++globalThis.navigationReentrantInterceptionProbe = async function(throwsAfterReplacement) {+ const frame = document.createElement('iframe');+ frame.src = new URL('/child', location.href).href;+ const loaded = new Promise(resolve => frame.onload = resolve);+ (document.body || document.documentElement || document).appendChild(frame);+ await loaded;+ const child = frame.contentWindow;+ const nav = child.navigation;+ const url = child.location.href;+ const gate = Promise.withResolvers();+ const log = [];+ let firstEvent, firstEntry, firstTransitionResults, replacement, replacementTransition;+ let successes = 0;+ const errors = [];+ nav.addEventListener('navigatesuccess', () => successes++);+ nav.addEventListener('navigateerror', e => errors.push(e.error));+ nav.addEventListener('navigate', e => {+ if(firstEvent) {+ e.intercept({handler() {+ log.push('replacement-handler');+ replacementTransition = nav.transition;+ return gate.promise;+ }});+ return;+ }+ firstEvent = e;+ e.signal.addEventListener('abort', () => log.push('abort'));+ e.intercept({handler() {+ firstEntry = nav.currentEntry;+ const transition = nav.transition;+ firstTransitionResults = Promise.allSettled([transition.committed, transition.finished]);+ log.push('first');+ replacement = nav.navigate(url + '#replacement');+ replacement.committed.catch(() => {});+ replacement.finished.catch(() => {});+ if(throwsAfterReplacement) throw new Error('old handler rejection');+ log.push('first-after');+ }});+ e.intercept({handler() {log.push('second');}});+ });+ const first = nav.navigate(url + '#first');+ const results = await Promise.allSettled([first.committed, first.finished]);+ const transitions = await firstTransitionResults;+ const before = {+ activeTransition: nav.transition === replacementTransition && replacementTransition !== null,+ promises: results.map(value => value.status === 'fulfilled' ? 'fulfilled' : value.reason.name),+ transition: transitions.map(value => value.status === 'fulfilled' ? 'fulfilled' : value.reason.name),+ committedEntry: results[0].value === firstEntry,+ sameReason: results[1].reason === firstEvent.signal.reason && transitions[1].reason === firstEvent.signal.reason,+ errors: errors.length,+ successes+ };+ gate.resolve();+ const entry = await replacement.finished;+ const record = {+ before, log,+ replacementEntry: entry === nav.currentEntry && entry.url === url + '#replacement',+ transitionCleared: nav.transition === null,+ errors: errors.length,+ successes+ };+ frame.remove();+ return record;+};