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): allocate opaque document history ids
ldm08164cfd94d70
diff --git a/.config/nextest.toml b/.config/nextest.tomlindex 23ad2e2db..4645eb725 100644--- a/.config/nextest.toml+++ b/.config/nextest.toml@@ -1,6 +1,19 @@+[test-groups.navigation-child-browser-runtime]+max-threads = 1++[[profile.default.overrides]]+filter = 'package(moli-core) & binary(wpt_compat) & test(/navigation_child_browsing_context/)'+test-group = 'navigation-child-browser-runtime'+threads-required = "num-test-threads"+[profile.ci]fail-fast = falseretries = 2status-level = "fail"final-status-level = "fail"success-output = "never"++[[profile.ci.overrides]]+filter = 'package(moli-core) & binary(wpt_compat) & test(/navigation_child_browsing_context/)'+test-group = 'navigation-child-browser-runtime'+threads-required = "num-test-threads"diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rsindex 546733522..7128c7a46 100644--- a/moli-page-types/src/lib.rs+++ b/moli-page-types/src/lib.rs@@ -187,8 +187,9 @@ pub use inspector_state::{renderer_inspector_protocol_configuration_command_from_method,};pub use navigation_history::{- NavigationActivationSeed, NavigationHistoryEntrySeed, NavigationHistoryMutation,- NavigationHistorySerializedEntry, NavigationTraversalSeedCandidate, SameDocumentHistoryUpdate,+ NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntrySeed,+ NavigationHistoryMutation, NavigationHistorySerializedEntry, NavigationTraversalSeedCandidate,+ SameDocumentHistoryUpdate,apply_child_browsing_context_javascript_url_navigation_to_entry_seed,apply_child_browsing_context_navigation_to_entry_seed,child_browsing_context_single_entry_seed, cross_document_navigation_seed,diff --git a/moli-page-types/src/navigation_history.rs b/moli-page-types/src/navigation_history.rsindex 412f348bd..31f69760a 100644--- a/moli-page-types/src/navigation_history.rs+++ b/moli-page-types/src/navigation_history.rs@@ -1,12 +1,49 @@+use std::sync::atomic::{AtomicU64, Ordering};use url::Url;+static NEXT_NAVIGATION_HISTORY_DOCUMENT_ID: AtomicU64 = AtomicU64::new(1);++/// Opaque identity shared by session-history entries that belong to the same+/// `Document`.+///+/// The serialized token is carried through the renderer's hidden Navigation+/// slots, but its contents have no meaning. In particular, callers must not+/// derive a new identity from a URL, a history index, or a previous token.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct NavigationHistoryDocumentId(String);++impl NavigationHistoryDocumentId {+ pub fn allocate() -> Self {+ allocate_navigation_history_document_id(&NEXT_NAVIGATION_HISTORY_DOCUMENT_ID)+ }++ /// Restores an identity previously stored in a renderer-owned runtime+ /// slot. Equality remains opaque; the token is never parsed.+ pub fn from_serialized(token: String) -> Self {+ Self(token)+ }++ pub fn as_str(&self) -> &str {+ &self.0+ }+}++fn allocate_navigation_history_document_id(counter: &AtomicU64) -> NavigationHistoryDocumentId {+ let raw = counter+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ current.checked_add(1)+ })+ .expect("Navigation History Document id allocator exhausted");+ NavigationHistoryDocumentId(format!("document-{raw}"))+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct NavigationHistorySerializedEntry {pub url: String,pub history_state_json: Option<String>,pub navigation_state_json: Option<String>,pub referrer_policy: Option<String>,- pub document_id: String,+ pub document_id: NavigationHistoryDocumentId,pub history_index: u32,pub index: u32,pub id: String,@@ -67,18 +104,29 @@ pub fn initial_navigation_history_seed(href: &str,) -> NavigationHistoryEntrySeed {if is_global_window && href != "about:blank" {+ let initial_document_id = NavigationHistoryDocumentId::allocate();+ let current_document_id = NavigationHistoryDocumentId::allocate();let entries = vec![navigation_history_entry("about:blank",0,0,- "document-0",+ initial_document_id,"entry-0","key-0",None,None,),- navigation_history_entry(href, 1, 0, "document-1", "entry-1", "key-1", None, None),+ navigation_history_entry(+ href,+ 1,+ 0,+ current_document_id,+ "entry-1",+ "key-1",+ None,+ None,+ ),];return NavigationHistoryEntrySeed {current_index: 1,@@ -94,7 +142,7 @@ pub fn initial_navigation_history_seed(href,0,0,- "document-0",+ NavigationHistoryDocumentId::allocate(),"entry-0","key-0",None,@@ -115,34 +163,29 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigationlet url = url.map(|url| url.as_str().to_owned()).unwrap_or_else(|| "about:blank".to_owned());- let mut entries = vec![navigation_history_entry(- &url,- 0,- 0,- "document-0",- "entry-0",- "key-0",- None,- None,- )];- if entries[0].url != "about:blank" {- entries.insert(- 0,+ if url != "about:blank" {+ let entries = vec![navigation_history_entry("about:blank",0,0,- "document-0",+ NavigationHistoryDocumentId::allocate(),"entry-0","key-0",None,None,),- );- entries[1].history_index = 1;- entries[1].id = "entry-1".to_owned();- entries[1].key = "key-1".to_owned();- entries[1].document_id = "document-1".to_owned();+ navigation_history_entry(+ &url,+ 1,+ 0,+ NavigationHistoryDocumentId::allocate(),+ "entry-1",+ "key-1",+ None,+ None,+ ),+ ];return NavigationHistoryEntrySeed {activation: Some(NavigationActivationSeed {entry: entries[1].clone(),@@ -153,12 +196,18 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigationcurrent_index: 1,};}+ let entries = vec![navigation_history_entry(+ &url,+ 0,+ 0,+ NavigationHistoryDocumentId::allocate(),+ "entry-0",+ "key-0",+ None,+ None,+ )];NavigationHistoryEntrySeed {- activation: (entries[0].url != "about:blank").then(|| NavigationActivationSeed {- entry: entries[0].clone(),- from: None,- navigation_type: Some("push".to_owned()),- }),+ activation: None,entries,current_index: 0,}@@ -183,7 +232,7 @@ pub fn apply_child_browsing_context_navigation_to_entry_seed(url.as_str(),next_index,current_navigation_index + 1,- &format!("document-{next_index}"),+ NavigationHistoryDocumentId::allocate(),&format!("entry-{next_index}"),&format!("key-{next_index}"),history_state_json,@@ -239,14 +288,15 @@ pub fn replace_child_browsing_context_navigation_in_entry_seed(.iter().find(|entry| entry.history_index == current_index).cloned();- let next_document_id = child_replace_document_id(current_index, previous_entry.as_ref(), url);+ let next_document_id = NavigationHistoryDocumentId::allocate();let next_key = replacement_entry_key(current_index, previous_entry.as_ref(), url);+ let next_entry_id = next_document_id.as_str().to_owned();let next_entry = navigation_history_entry(url.as_str(),current_index,current_navigation_index,- &next_document_id,- &next_document_id,+ next_document_id,+ &next_entry_id,&next_key,history_state_json,navigation_state_json,@@ -279,10 +329,10 @@ pub fn apply_child_browsing_context_javascript_url_navigation_to_entry_seed(else {return;};- let next_document_id = child_javascript_document_id(current_index, &previous_entry);+ let next_document_id = NavigationHistoryDocumentId::allocate();let mut next_entry = previous_entry.clone();next_entry.document_id = next_document_id.clone();- next_entry.id = next_document_id;+ next_entry.id = next_document_id.as_str().to_owned();if let Some(existing) = seed.entries.iter_mut()@@ -317,7 +367,7 @@ pub fn cross_document_navigation_seed(destination_url.as_str(),next_index,current_navigation_index + 1,- &format!("document-{next_index}-{}", destination_url.as_str()),+ NavigationHistoryDocumentId::allocate(),&format!("entry-{next_index}"),&format!("key-{next_index}"),None,@@ -327,18 +377,19 @@ pub fn cross_document_navigation_seed((entry, next_index)}NavigationHistoryMutation::Replace => {- let next_document_id = format!("document-{current_index}-{}", destination_url.as_str());+ let next_document_id = NavigationHistoryDocumentId::allocate();let next_key = replacement_entry_key(current_index,current_entry_snapshot.as_ref(),destination_url,);+ let next_entry_id = next_document_id.as_str().to_owned();let entry = navigation_history_entry(destination_url.as_str(),current_index,current_navigation_index,- &next_document_id,- &next_document_id,+ next_document_id,+ &next_entry_id,&next_key,None,None,@@ -423,7 +474,7 @@ fn navigation_history_entry(url: &str,history_index: u32,index: u32,- document_id: &str,+ document_id: NavigationHistoryDocumentId,id: &str,key: &str,history_state_json: Option<String>,@@ -434,7 +485,7 @@ fn navigation_history_entry(history_state_json,navigation_state_json,referrer_policy: None,- document_id: document_id.to_owned(),+ document_id,history_index,index,id: id.to_owned(),@@ -442,42 +493,6 @@ fn navigation_history_entry(}}-fn child_replace_document_id(- history_index: u32,- previous_entry: Option<&NavigationHistorySerializedEntry>,- url: &Url,-) -> String {- let prefix = format!("document-{history_index}-replace-");- let previous_generation = previous_entry- .and_then(|entry| entry.document_id.strip_prefix(&prefix))- .and_then(|rest| rest.split_once('-').map(|(generation, _)| generation))- .and_then(|generation| generation.parse::<u32>().ok())- .unwrap_or(0);- format!(- "document-{history_index}-replace-{}-{}",- previous_generation + 1,- url.as_str()- )-}--fn child_javascript_document_id(- history_index: u32,- previous_entry: &NavigationHistorySerializedEntry,-) -> String {- let prefix = format!("document-{history_index}-javascript-");- let previous_generation = previous_entry- .document_id- .strip_prefix(&prefix)- .and_then(|rest| rest.split_once('-').map(|(generation, _)| generation))- .and_then(|generation| generation.parse::<u32>().ok())- .unwrap_or(0);- format!(- "document-{history_index}-javascript-{}-{}",- previous_generation + 1,- previous_entry.url- )-}-fn replacement_entry_key(history_index: u32,previous_entry: Option<&NavigationHistorySerializedEntry>,@@ -505,6 +520,10 @@ fn same_origin(left: &Url, right: &Url) -> bool {mod tests {use super::*;+ fn document_id(token: &str) -> NavigationHistoryDocumentId {+ NavigationHistoryDocumentId::from_serialized(token.to_owned())+ }+#[test]fn initial_navigation_history_seed_preserves_global_about_blank_predecessor() {let seed = initial_navigation_history_seed(true, "https://example.test/page");@@ -512,6 +531,7 @@ mod tests {assert_eq!(seed.entries.len(), 2);assert_eq!(seed.entries[0].url, "about:blank");assert_eq!(seed.entries[1].url, "https://example.test/page");+ assert_ne!(seed.entries[0].document_id, seed.entries[1].document_id);assert_eq!(seed.activation.as_ref()@@ -564,6 +584,55 @@ mod tests {);}+ #[test]+ fn cross_document_replace_same_url_allocates_a_fresh_document_id() {+ let destination = Url::parse("https://example.test/replaced").unwrap();+ let initial = vec![navigation_history_entry(+ "https://example.test/current",+ 4,+ 2,+ document_id("opaque-existing-document"),+ "entry-4",+ "key-4",+ None,+ None,+ )];++ let first = cross_document_navigation_seed(+ initial,+ 4,+ 2,+ &destination,+ NavigationHistoryMutation::Replace,+ );+ let first_document_id = first.entries[0].document_id.clone();+ let second = cross_document_navigation_seed(+ first.entries,+ 4,+ 2,+ &destination,+ NavigationHistoryMutation::Replace,+ );++ assert_ne!(first_document_id, second.entries[0].document_id);+ assert!(+ !second.entries[0]+ .document_id+ .as_str()+ .contains(destination.as_str())+ );+ }++ #[test]+ fn document_id_allocator_rejects_exhaustion_without_wrapping() {+ let counter = AtomicU64::new(u64::MAX);+ let exhausted =+ std::panic::catch_unwind(|| allocate_navigation_history_document_id(&counter));++ assert!(exhausted.is_err());+ assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);+ }+#[test]fn child_activation_omits_from_for_cross_origin_navigation() {let first = Url::parse("http://127.0.0.1:1111/common/blank.html").unwrap();@@ -642,7 +711,7 @@ mod tests {"https://example.test/first",0,0,- "document-0",+ document_id("document-0"),"entry-0","key-0",None,@@ -652,7 +721,7 @@ mod tests {"https://example.test/current",1,1,- "document-1",+ document_id("document-1"),"entry-1","key-1",None,@@ -662,7 +731,7 @@ mod tests {"https://example.test/forward",2,2,- "document-2",+ document_id("document-2"),"entry-2","key-2",None,@@ -698,7 +767,7 @@ mod tests {"https://example.test/current",4,2,- "document-4",+ document_id("document-4"),"entry-4","key-4",None,@@ -732,7 +801,7 @@ mod tests {"https://example.test/current",7,3,- "document-7",+ document_id("document-7"),"entry-7","key-7",None,@@ -757,7 +826,7 @@ mod tests {"https://example.test/current",0,0,- "document-1",+ document_id("document-1"),"entry-0","key-0",None,@@ -767,7 +836,7 @@ mod tests {"https://example.test/target",1,1,- "document-1",+ document_id("document-1"),"entry-1","key-1",None,@@ -785,7 +854,7 @@ mod tests {"https://example.test/current",0,0,- "document-0",+ document_id("document-0"),"entry-0","key-0",None,@@ -795,7 +864,7 @@ mod tests {"https://example.test/target",1,1,- "document-1",+ document_id("document-1"),"entry-1","key-1",None,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rsindex 04a1b2a5e..f27c84234 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs@@ -145,7 +145,7 @@ pub(super) fn navigation_entry_object_from_snapshot<'s>(&snapshot.id,&snapshot.key,);- set_navigation_entry_document_id(scope, entry, &snapshot.document_id);+ set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);entry}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rsindex 86aa949ec..c64a99303 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs@@ -53,11 +53,12 @@ pub(crate) fn install_window_location_history_navigation_runtime_state<'s>(install_location_runtime_state(scope, location, href)?;set_private_value(scope, window, WINDOW_LOCATION_SLOT, location.into());- let history = build_history_runtime_state(scope, window)?;+ let initial_seed = initial_navigation_history_seed(scope, window, href);+ let history = build_history_runtime_state(scope, window, &initial_seed)?;set_runtime_window_owner(scope, history, window);set_private_value(scope, window, WINDOW_HISTORY_SLOT, history.into());- let navigation = build_navigation_runtime_state(scope, window)?;+ let navigation = build_navigation_runtime_state(scope, window, &initial_seed)?;set_runtime_window_owner(scope, navigation, window);set_private_value(scope, window, WINDOW_NAVIGATION_SLOT, navigation.into());if !window.strict_equals(scope.get_current_context().global(scope).into()) {@@ -84,14 +85,14 @@ pub(crate) fn reset_window_location_history_navigation_runtime_state<'s>(.map_err(|error| anyhow::anyhow!("failed to initialize Location object: {error}"))?;install_location_runtime_state(scope, location, href)?;+ let initial_seed = initial_navigation_history_seed(scope, window, href);let history = match window_runtime_object(scope, window, WINDOW_HISTORY_SLOT) {Some(history) => history,- None => build_history_runtime_state(scope, window)?,+ None => build_history_runtime_state(scope, window, &initial_seed)?,};set_runtime_window_owner(scope, history, window);install_history_scroll_restoration_runtime_state(scope, history, "auto");install_history_state_runtime_state(scope, history, v8::null(scope).into());- let initial_seed = initial_navigation_history_seed(scope, window, href);let entries = build_history_entries_array_from_seed(scope, window, &initial_seed);let current_entry = entries.get_index(scope, initial_seed.current_index)@@ -111,7 +112,7 @@ pub(crate) fn reset_window_location_history_navigation_runtime_state<'s>(let navigation = match window_runtime_object(scope, window, WINDOW_NAVIGATION_SLOT) {Some(navigation) => navigation,- None => build_navigation_runtime_state(scope, window)?,+ None => build_navigation_runtime_state(scope, window, &initial_seed)?,};set_runtime_window_owner(scope, navigation, window);set_navigation_current_entry(scope, navigation, current_entry);diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rsindex f967576fb..d4ea83e62 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs@@ -45,7 +45,7 @@ pub(crate) fn install_navigation_bootstrap_entry_for_holder<'s>(&snapshot.id,&snapshot.key,);- set_navigation_entry_document_id(scope, entry, &snapshot.document_id);+ set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);let _ = entries.set_index(scope, snapshot.history_index, entry.into());if snapshot.history_index == entry_seed.current_index {@@ -58,7 +58,8 @@ pub(crate) fn install_navigation_bootstrap_entry_for_holder<'s>(let current_entry = current_entry.unwrap_or_else(|| {current_state = Some(v8::null(scope).into());let entry = create_navigation_entry(scope, "about:blank", None, None, None, 0, "", "");- set_navigation_entry_document_id(scope, entry, "document-0");+ let document_id = moli_page_types::NavigationHistoryDocumentId::allocate();+ set_navigation_entry_document_id(scope, entry, document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);entry});diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rsindex 10d67feb0..c0a090bd9 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs@@ -44,7 +44,7 @@ pub(super) fn build_history_entries_array_from_seed<'s>(&snapshot.id,&snapshot.key,);- set_navigation_entry_document_id(scope, entry, &snapshot.document_id);+ set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);let _ = entries.set_index(scope, snapshot.history_index, entry.into());}@@ -73,7 +73,8 @@ pub(super) fn build_current_navigation_entry_from_seed<'s>("","",);- set_navigation_entry_document_id(scope, entry, "document-0");+ let document_id = moli_page_types::NavigationHistoryDocumentId::allocate();+ set_navigation_entry_document_id(scope, entry, document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);return entry;};@@ -87,7 +88,7 @@ pub(super) fn build_current_navigation_entry_from_seed<'s>(&snapshot.id,&snapshot.key,);- set_navigation_entry_document_id(scope, entry, &snapshot.document_id);+ set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());bind_navigation_entry_runtime_owner(scope, entry, owner);entry}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rsindex 438f91d7c..593ec6380 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs@@ -12,7 +12,8 @@ use super::navigation_window::{};use super::*;use crate::native_bridge::{- NavigationActivationSeed, NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,+ NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntrySeed,+ NavigationHistorySerializedEntry,};use crate::{document_runtime::DomHandle, native_bridge::node_runtime_and_handle_from_object,@@ -124,7 +125,7 @@ pub(super) fn serialize_navigation_entry_object<'s>(history_state_json,navigation_state_json,referrer_policy: navigation_entry_referrer_policy_value(scope, entry),- document_id,+ document_id: NavigationHistoryDocumentId::from_serialized(document_id),history_index: entry_index,index: entry_index,id,@@ -228,7 +229,7 @@ pub(super) fn serialize_history_entries<'s>(history_state_json,navigation_state_json,referrer_policy: navigation_entry_referrer_policy_value(scope, entry),- document_id,+ document_id: NavigationHistoryDocumentId::from_serialized(document_id),history_index: index,index: entry_index,id,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rsindex dbf3ecff6..cdbe7c2ca 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs@@ -3,7 +3,6 @@ use super::location_history_storage::{HISTORY_ENTRIES_SLOT, HISTORY_INDEX_SLOT, HISTORY_LENGTH_SLOT, HISTORY_SCROLL_RESTORATION_SLOT,HISTORY_STATE_SLOT, NAVIGATION_CURRENT_ENTRY_SLOT, NAVIGATION_EVENT_LISTENERS_SLOT,};-use super::location_runtime::location_href_slot;use super::navigation_activation::install_navigation_activation_runtime_state;use super::navigation_callbacks::{navigation_entries_callback, navigation_navigate_callback,@@ -13,7 +12,6 @@ use super::navigation_events::navigation_error_event_active;use super::navigation_projection::set_history_length_from_visible_entries;use super::navigation_seed::{build_current_navigation_entry_from_seed, build_history_entries_array_from_seed,- initial_navigation_history_seed,};use super::navigation_traversal::{history_back_callback, history_forward_callback, history_go_callback, navigation_back_callback,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rsindex 77bd41af3..9562e829c 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs@@ -5,6 +5,7 @@ use super::accessors::{install_history_prototype_accessors, install_navigation_prototype_accessors,};use super::*;+use crate::native_bridge::NavigationHistoryEntrySeed;use crate::util::get_private_value;use moli_webapi_declare::WebApiObject;@@ -49,16 +50,12 @@ struct NavigationRuntimeObjectDeclaration<'scope> {pub(in crate::context_bootstrap) fn build_history_runtime_state<'s>(scope: &mut v8::PinScope<'s, '_>,window: v8::Local<'s, v8::Object>,+ initial_seed: &NavigationHistoryEntrySeed,) -> Result<v8::Local<'s, v8::Object>> {if let Some(prototype) = global_constructor_prototype(scope, "History") {install_history_prototype_accessors(scope, prototype);}- let current_href = window_location_runtime_object(scope, window)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- .and_then(|location| location_href_slot(scope, location))- .unwrap_or_else(|| "about:blank".to_owned());- let initial_seed = initial_navigation_history_seed(scope, window, ¤t_href);- let entries = build_history_entries_array_from_seed(scope, window, &initial_seed);+ let entries = build_history_entries_array_from_seed(scope, window, initial_seed);let history = HistoryRuntimeObjectDeclaration::new(v8::null(scope).into(),"auto",@@ -75,15 +72,11 @@ pub(in crate::context_bootstrap) fn build_history_runtime_state<'s>(pub(in crate::context_bootstrap) fn build_navigation_runtime_state<'s>(scope: &mut v8::PinScope<'s, '_>,window: v8::Local<'s, v8::Object>,+ initial_seed: &NavigationHistoryEntrySeed,) -> Result<v8::Local<'s, v8::Object>> {if let Some(prototype) = global_constructor_prototype(scope, "Navigation") {install_navigation_prototype_accessors(scope, prototype);}- let current_href = window_location_runtime_object(scope, window)- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- .and_then(|location| location_href_slot(scope, location))- .unwrap_or_else(|| "about:blank".to_owned());- let initial_seed = initial_navigation_history_seed(scope, window, ¤t_href);let current_entry = window_runtime_object(scope, window, WINDOW_HISTORY_SLOT).and_then(|value| v8::Local::<v8::Object>::try_from(value).ok()).and_then(|history| {@@ -97,7 +90,7 @@ pub(in crate::context_bootstrap) fn build_navigation_runtime_state<'s>(build_current_navigation_entry_from_seed(scope,window,- &initial_seed,+ initial_seed,v8::null(scope).into(),)});@@ -119,13 +112,6 @@ pub(in crate::context_bootstrap) fn build_navigation_runtime_state<'s>(Ok(navigation)}-fn window_location_runtime_object<'s>(- scope: &mut v8::PinScope<'s, '_>,- window: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Value>> {- window_runtime_object(scope, window, WINDOW_LOCATION_SLOT)-}-fn window_runtime_object<'s>(scope: &mut v8::PinScope<'s, '_>,window: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rsindex 86e804ac2..0a5c679e7 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs@@ -1,7 +1,8 @@use super::{ChildBrowsingContextBootstrap, ChildBrowsingContextSnapshot, ChildFrameAttachmentSnapshot,- JsContextHost, NavigationActivationSeed, NavigationHistoryEntrySeed,- NavigationHistorySerializedEntry, child_documents::CompletedFrameOwnerResourceTiming,+ JsContextHost, NavigationActivationSeed, NavigationHistoryDocumentId,+ NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,+ child_documents::CompletedFrameOwnerResourceTiming,};use crate::{context_bootstrap::set_top_level_history_length_at_least_for_runtime_owner,@@ -622,16 +623,16 @@ impl ChildBrowsingContextEntry {.map(|snapshot| snapshot.document_id.clone());for snapshot in &mut self.navigation_entry_seed.entries {if current_document_id- .as_deref()- .is_some_and(|document_id| snapshot.document_id == document_id)+ .as_ref()+ .is_some_and(|document_id| &snapshot.document_id == document_id){snapshot.referrer_policy = Some(policy.clone());}}if let Some(activation) = self.navigation_entry_seed.activation.as_mut()&& current_document_id- .as_deref()- .is_some_and(|document_id| activation.entry.document_id == document_id)+ .as_ref()+ .is_some_and(|document_id| &activation.entry.document_id == document_id){activation.entry.referrer_policy = Some(policy);}@@ -745,7 +746,7 @@ impl ChildBrowsingContextEntry {history_state_json: None,navigation_state_json: None,referrer_policy: None,- document_id: "document-1".to_owned(),+ document_id: NavigationHistoryDocumentId::allocate(),history_index: 1,index: 0,id: "entry-1".to_owned(),diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rsindex e488d47af..5c0c206fe 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs@@ -158,13 +158,7 @@ impl JsContextHost {existing.as_ref().map(|entry| entry.committed_navigation_entry_seed())- .unwrap_or_else(|| {- if is_new {- Self::child_browsing_context_single_entry_seed(&live_bootstrap)- } else {- navigation_entry_seed.clone()- }- })+ .unwrap_or_else(|| navigation_entry_seed.clone())};let performance_time_origin = if is_new {ChildPerformanceTimeOrigin::now()diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 4871fc914..efc919779 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -196,7 +196,8 @@ pub(crate) use messages::{PendingWindowMessage, PendingWindowMessageEndpoint, PendingWindowMessageSource,};pub(crate) use moli_page_types::{- NavigationActivationSeed, NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,+ NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntrySeed,+ NavigationHistorySerializedEntry,};pub(crate) use navigation::{PendingLocationNavigation, PendingTopLevelNavigation};pub(crate) use popups::{diff --git a/moli-wpt-compat/fixtures/wpt/ported/navigation/navigation-child-browsing-context-forward-result-promises-basic.html b/moli-wpt-compat/fixtures/wpt/ported/navigation/navigation-child-browsing-context-forward-result-promises-basic.htmlindex 68557ce98..337d35db0 100644--- a/moli-wpt-compat/fixtures/wpt/ported/navigation/navigation-child-browsing-context-forward-result-promises-basic.html+++ b/moli-wpt-compat/fixtures/wpt/ported/navigation/navigation-child-browsing-context-forward-result-promises-basic.html@@ -20,6 +20,20 @@ function wait_for(promise, description) {]);}+function wait_for_hashchange(childWindow, expectedHash, action) {+ return new Promise(function (resolve) {+ function onHashchange() {+ if (childWindow.location.hash !== expectedHash) {+ return;+ }+ childWindow.removeEventListener("hashchange", onHashchange);+ resolve();+ }+ childWindow.addEventListener("hashchange", onHashchange);+ action();+ });+}+promise_test(async function () {const iframe = document.getElementById("child");const topOrder = [];@@ -39,7 +53,8 @@ promise_test(async function () {if (childWindow &&childWindow.location.href === childBaseUrl &&- childWindow.navigation.currentEntry?.url === childBaseUrl+ childWindow.navigation.currentEntry?.url === childBaseUrl &&+ childWindow.document.readyState === "complete") {resolve();return;@@ -51,79 +66,67 @@ promise_test(async function () {"child iframe initial navigation commit",);- const snapshot = await wait_for(- new Promise(function (resolve) {- const childWindow = iframe.contentWindow;- const childOrder = [];-- childWindow.history.pushState({ step: 1 }, "", "#one");- childWindow.history.pushState({ step: 2 }, "", "#two");-- childWindow.addEventListener(- "hashchange",- function onHashchange() {- if (childWindow.location.hash !== "#one") {- return;- }+ const childWindow = iframe.contentWindow;+ const childOrder = [];- let committedSettled = false;- let finishedSettled = false;- let committedValue = null;- let finishedValue = null;+ childWindow.history.pushState({ step: 1 }, "", "#one");+ childWindow.history.pushState({ step: 2 }, "", "#two");+ await wait_for_hashchange(+ childWindow,+ "#one",+ function () {+ childWindow.history.back();+ },+ );- const result = childWindow.navigation.forward();- result.committed.then(function (entry) {- committedSettled = true;- committedValue = entry;- childOrder.push("child-committed:" + childWindow.location.hash);- });- result.finished.then(function (entry) {- finishedSettled = true;- finishedValue = entry;- childOrder.push("child-finished:" + childWindow.location.hash);- });+ let committedSettled = false;+ let finishedSettled = false;+ let committedValue = null;+ let finishedValue = null;- const syncHash = childWindow.location.hash;- const syncState = String(childWindow.history.state?.step ?? "null");- const syncCommitted = String(committedSettled);- const syncFinished = String(finishedSettled);- const syncKeys = Object.keys(result).join(",");- const syncProps = Object.getOwnPropertyNames(result).join(",");+ const result = childWindow.navigation.forward();+ result.committed.then(function (entry) {+ committedSettled = true;+ committedValue = entry;+ childOrder.push("child-committed:" + childWindow.location.hash);+ });+ result.finished.then(function (entry) {+ finishedSettled = true;+ finishedValue = entry;+ childOrder.push("child-finished:" + childWindow.location.hash);+ });- childWindow.removeEventListener("hashchange", onHashchange);- setTimeout(function () {- resolve({- syncHash,- syncState,- syncCommitted,- syncFinished,- syncKeys,- syncProps,- timeoutHash: childWindow.location.hash,- timeoutState: String(childWindow.history.state?.step ?? "null"),- timeoutCommitted: String(committedSettled),- timeoutFinished: String(finishedSettled),- timeoutCommittedType: Object.prototype.toString.call(committedValue),- timeoutFinishedType: Object.prototype.toString.call(finishedValue),- timeoutCommittedUrl: committedValue ? committedValue.url : "",- timeoutFinishedUrl: finishedValue ? finishedValue.url : "",- timeoutCurrentSameCommitted: String(- committedValue === childWindow.navigation.currentEntry,- ),- timeoutCurrentSameFinished: String(- finishedValue === childWindow.navigation.currentEntry,- ),- order: childOrder.join(","),- });- }, 50);- },- { once: false },- );+ const syncHash = childWindow.location.hash;+ const syncState = String(childWindow.history.state?.step ?? "null");+ const syncCommitted = String(committedSettled);+ const syncFinished = String(finishedSettled);+ const syncKeys = Object.keys(result).join(",");+ const syncProps = Object.getOwnPropertyNames(result).join(",");- childWindow.history.back();- }),- "child forward result promises",- );+ await Promise.all([result.committed, result.finished]);+ const snapshot = {+ syncHash,+ syncState,+ syncCommitted,+ syncFinished,+ syncKeys,+ syncProps,+ timeoutHash: childWindow.location.hash,+ timeoutState: String(childWindow.history.state?.step ?? "null"),+ timeoutCommitted: String(committedSettled),+ timeoutFinished: String(finishedSettled),+ timeoutCommittedType: Object.prototype.toString.call(committedValue),+ timeoutFinishedType: Object.prototype.toString.call(finishedValue),+ timeoutCommittedUrl: committedValue ? committedValue.url : "",+ timeoutFinishedUrl: finishedValue ? finishedValue.url : "",+ timeoutCurrentSameCommitted: String(+ committedValue === childWindow.navigation.currentEntry,+ ),+ timeoutCurrentSameFinished: String(+ finishedValue === childWindow.navigation.currentEntry,+ ),+ order: childOrder.join(","),+ };assert_array_equals(topOrder, [], "top-level traversal events should stay window-local to the child");assert_equals(snapshot.syncHash, "#one", "child should be back on the first fragment synchronously");diff --git a/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-activation-same-document.js b/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-activation-same-document.jsindex 1e4b8cf10..ad8094a62 100644--- a/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-activation-same-document.js+++ b/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-activation-same-document.js@@ -42,31 +42,31 @@await wait_for_value(function () {return (childWindow.location.href === childUrl &&- childWindow.navigation.currentEntry?.url === childUrl+ childWindow.navigation.currentEntry?.url === childUrl &&+ childWindow.document.readyState === "complete");}, "child initial navigation commit");const initial = snapshotChildActivation(iframe);- childWindow.navigation.navigate("#one", {- history: "push",- state: { step: 1 },+ let pushResult;+ const pushHashchange = wait_for_hashchange(childWindow, "#one", function () {+ pushResult = childWindow.navigation.navigate("#one", {+ history: "push",+ state: { step: 1 },+ });});- await wait_for_value(function () {- return childWindow.location.hash === "#one";- }, "child same-document push");+ await Promise.all([pushResult.finished, pushHashchange]);const afterPush = snapshotChildActivation(iframe);- childWindow.history.back();- await wait_for_value(function () {- return childWindow.location.hash === "";- }, "child history back");+ await wait_for_hashchange(childWindow, "", function () {+ childWindow.history.back();+ });const afterBack = snapshotChildActivation(iframe);- childWindow.history.forward();- await wait_for_value(function () {- return childWindow.location.hash === "#one";- }, "child history forward");+ await wait_for_hashchange(childWindow, "#one", function () {+ childWindow.history.forward();+ });const afterForward = snapshotChildActivation(iframe);assert_equals(@@ -102,4 +102,18 @@String(childWindow.navigation.transition === null),].join("|");}++ function wait_for_hashchange(childWindow, expectedHash, action) {+ return new Promise(function (resolve) {+ function onHashchange() {+ if (childWindow.location.hash !== expectedHash) {+ return;+ }+ childWindow.removeEventListener("hashchange", onHashchange);+ resolve();+ }+ childWindow.addEventListener("hashchange", onHashchange);+ action();+ });+ }})();diff --git a/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-currententrychange.js b/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-currententrychange.jsindex 346ad1013..0dbaeafc9 100644--- a/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-currententrychange.js+++ b/moli-wpt-compat/fixtures/wpt/ported/navigation/resources/navigation-child-browsing-context-currententrychange.js@@ -27,7 +27,8 @@if (childWindow &&childWindow.location.href === childBaseUrl &&- childWindow.navigation.currentEntry?.url === childBaseUrl+ childWindow.navigation.currentEntry?.url === childBaseUrl &&+ childWindow.document.readyState === "complete") {resolve();return;@@ -83,12 +84,11 @@childPropertyNavigationTypes.push(String(event.navigationType));};- childWindow.navigation.navigate("#one", {+ const result = childWindow.navigation.navigate("#one", {history: "push",state: { from: "child" },});-- await wait(0);+ await result.finished;assert_equals(topChanges,@@ -143,60 +143,42 @@childWindow.history.pushState({ n: 1 }, "", "#one");childWindow.history.pushState({ n: 2 }, "", "#two");- await wait(0);+ await wait_for_hashchange(childWindow, "#one", function () {+ childWindow.history.back();+ });- const snapshot = await wait_for(- new Promise(function (resolve) {- childWindow.addEventListener(- "hashchange",- function onHashchange() {- if (childWindow.location.hash !== "#one") {- return;- }-- childWindow.removeEventListener("hashchange", onHashchange);-- const order = [];- let fired = false;- let fromUrl = "null";- let navigationType = "null";- let syncHash = "";- let syncState = "";-- childWindow.navigation.oncurrententrychange = function (event) {- fired = true;- fromUrl = event.from?.url ?? "null";- navigationType = String(event.navigationType);- order.push("currententrychange");- queueMicrotask(function () {- order.push("currententrychange-microtask:" + childWindow.location.hash);- });- setTimeout(function () {- resolve({- fired: String(fired),- topChanges: String(topChanges),- syncHash: syncHash,- syncState: syncState,- timeoutHash: childWindow.location.hash,- timeoutState: JSON.stringify(childWindow.history.state),- fromUrl: fromUrl,- navigationType: navigationType,- order: order.join(","),- });- }, 0);- };-- childWindow.navigation.forward();- syncHash = childWindow.location.hash;- syncState = JSON.stringify(childWindow.history.state);- },- { once: false },- );-- childWindow.history.back();- }),- "child forward currententrychange traverse snapshot",- );+ const order = [];+ let fired = false;+ let fromUrl = "null";+ let navigationType = "null";+ const currentEntryChange = new Promise(function (resolve) {+ childWindow.navigation.oncurrententrychange = function (event) {+ fired = true;+ fromUrl = event.from?.url ?? "null";+ navigationType = String(event.navigationType);+ order.push("currententrychange");+ queueMicrotask(function () {+ order.push("currententrychange-microtask:" + childWindow.location.hash);+ resolve();+ });+ };+ });++ const result = childWindow.navigation.forward();+ const syncHash = childWindow.location.hash;+ const syncState = JSON.stringify(childWindow.history.state);+ await Promise.all([currentEntryChange, result.finished]);+ const snapshot = {+ fired: String(fired),+ topChanges: String(topChanges),+ syncHash,+ syncState,+ timeoutHash: childWindow.location.hash,+ timeoutState: JSON.stringify(childWindow.history.state),+ fromUrl,+ navigationType,+ order: order.join(","),+ };assert_equals(snapshot.topChanges,@@ -244,4 +226,18 @@"child oncurrententrychange should observe the traversed fragment by microtask time",);}++ function wait_for_hashchange(childWindow, expectedHash, action) {+ return new Promise(function (resolve) {+ function onHashchange() {+ if (childWindow.location.hash !== expectedHash) {+ return;+ }+ childWindow.removeEventListener("hashchange", onHashchange);+ resolve();+ }+ childWindow.addEventListener("hashchange", onHashchange);+ action();+ });+ }})();