Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(history): finish world isolation and native entry cleanup

ldm08b57e489e631
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index 79112d9d3..e8ab5de03 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -31,7 +31,12 @@ and `Page.createIsolatedWorld` to cover the PR #818 regressions: entry wrapper
identity and expando/method isolation, one `currententrychange` in each world,
isolated `navigate` cancellation, and the realm of History `SecurityError`s.
It also verifies that a later main-world mutation updates the isolated world's
-structured state and preserves its local state cache. Run it with
+structured state and preserves its local state cache. Event checks cover local
+AbortSignal, FormData, File, and DOM wrappers; live FormData mutations; and
+synthetic Event/CustomEvent identity, interface type, and shared cancellation.
+Abort delivery for a synthetic NavigateEvent is covered by renderer Rust tests:
+Chrome 154 crashes when aborting the signal passed to that synthetic event.
+Run it with
`uv run moli-cdp-smoke --group history-worlds`, or add `--endpoint URL` to use an
existing browser process.
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py b/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py
index bf4c70e16..05ffdbeb4 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py
@@ -125,9 +125,123 @@ async def run_history_worlds_group(
changes]
""", isolated)
assert_equal(state, [3, True, True, True, 2], "native History updates reach existing worlds")
+
+ await evaluate("""
+ navigation.addEventListener('navigate', event => {
+ globalThis.probeDestination = event.destination;
+ event.signal.pageOnly = 'page';
+ event.signal.addEventListener = () => { throw new Error('page override'); };
+ }, {once: true});
+ """)
+ await evaluate("""
+ globalThis.signalViews = [];
+ navigation.addEventListener('navigate', event => {
+ signalViews.push(event instanceof NavigateEvent,
+ event.signal instanceof AbortSignal,
+ Object.getPrototypeOf(event.signal) === AbortSignal.prototype,
+ event.signal.pageOnly === undefined);
+ try { event.signal.addEventListener('abort', () => {}); signalViews.push(true); }
+ catch (_) { signalViews.push(false); }
+ }, {once: true});
+ """, isolated)
+ await evaluate("history.pushState({}, '', '#signal-view')")
+ signal_views = await evaluate("signalViews", isolated)
+ assert_equal(signal_views, [True] * 5, "NavigateEvent signal world wrapper")
+
+ await evaluate("""
+ globalThis.syntheticViews = [];
+ for (const type of ['probe', 'navigate']) {
+ navigation.addEventListener(type, function (event) {
+ syntheticViews.push([event instanceof Event, event.expando === undefined,
+ event.target === navigation, event.currentTarget === navigation,
+ this === navigation, event instanceof CustomEvent,
+ event instanceof NavigateEvent, event.detail ?? null]);
+ event.preventDefault();
+ }, {once: true});
+ }
+ """)
+ original_identity = await evaluate("""
+ (() => {
+ const facts = [];
+ for (const original of [new CustomEvent('probe', {detail: 7, cancelable: true}),
+ new Event('navigate', {cancelable: true})]) {
+ original.expando = 'isolated';
+ navigation.addEventListener(original.type, event => {
+ facts.push(event === original, event.defaultPrevented,
+ event.target === navigation, event.composedPath()[0] === navigation);
+ }, {once: true});
+ facts.push(navigation.dispatchEvent(original), original.defaultPrevented,
+ original.currentTarget === null, original.composedPath().length === 0);
+ }
+ return facts;
+ })()
+ """, isolated)
+ assert_equal(original_identity, [True, True, True, True, False, True, True, True] * 2,
+ "synthetic event identity and shared cancellation")
+ synthetic_views = await evaluate("syntheticViews")
+ assert_equal(synthetic_views, [
+ [True, True, True, True, True, True, False, 7],
+ [True, True, True, True, True, False, False, None],
+ ], "synthetic event interface and expando isolation")
+
+ await evaluate("""
+ globalThis.probeController = new AbortController();
+ globalThis.probeData = new FormData();
+ probeData.set('value', 'page');
+ const file = new File(['bytes'], 'probe.txt', {type: 'text/plain', lastModified: 7});
+ file.pageOnly = true;
+ probeData.set('file', file);
+ const source = document.createElement('button');
+ source.id = 'world-probe-source';
+ document.body.appendChild(source);
+ globalThis.platformProbe = new NavigateEvent('platform-probe', {
+ destination: probeDestination, signal: probeController.signal,
+ formData: probeData, sourceElement: source,
+ });
+ navigation.addEventListener('platform-probe', event => {
+ event.signal.pageOnly = true;
+ event.signal.addEventListener = () => { throw new Error('page signal override'); };
+ event.formData.pageOnly = true;
+ event.formData.get = () => 'page override';
+ event.sourceElement.pageOnly = true;
+ event.sourceElement.getAttribute = () => 'page override';
+ }, {once: true});
+ """)
+ await evaluate("""
+ globalThis.platformViews = [];
+ navigation.addEventListener('platform-probe', event => {
+ globalThis.probeSignal = event.signal;
+ globalThis.probeFormData = event.formData;
+ const file = event.formData.get('file');
+ platformViews.push(event instanceof NavigateEvent,
+ event.signal instanceof AbortSignal, event.signal.pageOnly === undefined,
+ event.formData instanceof FormData, event.formData.pageOnly === undefined,
+ event.formData.get('value') === 'page',
+ event.sourceElement instanceof HTMLButtonElement,
+ event.sourceElement === document.getElementById('world-probe-source'),
+ event.sourceElement.pageOnly === undefined,
+ event.sourceElement.getAttribute('id') === 'world-probe-source',
+ file instanceof File, file.pageOnly === undefined,
+ file === event.formData.get('file'), file.name === 'probe.txt',
+ file.size === 5, file.type === 'text/plain', file.lastModified === 7);
+ event.formData.set('value', 'isolated');
+ }, {once: true});
+ """, isolated)
+ await evaluate("navigation.dispatchEvent(platformProbe)")
+ # Chrome 154 crashes when aborting this synthetic NavigateEvent's signal.
+ # Shared abort state and delivery are covered by history_worlds.rs.
+ platform_views = await evaluate("platformViews", isolated)
+ assert_equal(platform_views, [True] * 17, "nested platform object world wrappers")
+ assert_equal(await evaluate("FormData.prototype.get.call(probeData, 'value')"),
+ "isolated", "FormData writes reach the original object")
+ await evaluate("FormData.prototype.set.call(probeData, 'value', 'updated')")
+ assert_equal(await evaluate("probeFormData.get('value')", isolated),
+ "updated", "FormData views remain live")
record(results, "raw_cdp_history_world_boundaries", {
"wrappers": wrappers, "changes": changes, "cancellation": cancellation,
"errors": errors, "state": state,
+ "signal_views": signal_views, "original_identity": original_identity,
+ "synthetic_views": synthetic_views, "platform_views": platform_views,
})
finally:
session = None
diff --git a/moli-page-types/src/navigation_history.rs b/moli-page-types/src/navigation_history.rs
index 358c4b4d0..6e639652c 100644
--- a/moli-page-types/src/navigation_history.rs
+++ b/moli-page-types/src/navigation_history.rs
@@ -51,10 +51,6 @@ pub struct NavigationHistorySerializedEntry {
pub history_state: Option<moli_history::SerializedScriptValue>,
pub navigation_state: Option<moli_history::SerializedScriptValue>,
pub scroll_restoration: moli_history::ScrollRestoration,
- /// Legacy/bootstrap input only; native snapshots use `history_state`.
- pub history_state_json: Option<String>,
- /// Legacy/bootstrap input only; native snapshots use `navigation_state`.
- pub navigation_state_json: Option<String>,
pub referrer_policy: Option<String>,
pub document_id: NavigationHistoryDocumentId,
pub history_index: u32,
@@ -129,8 +125,6 @@ pub fn initial_navigation_history_seed(
initial_document_id,
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
),
navigation_history_entry(
href,
@@ -139,8 +133,6 @@ pub fn initial_navigation_history_seed(
current_document_id,
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
),
];
return NavigationHistoryEntrySeed {
@@ -161,8 +153,6 @@ pub fn initial_navigation_history_seed(
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
)];
NavigationHistoryEntrySeed {
session_history: Default::default(),
@@ -189,8 +179,6 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigation
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
),
navigation_history_entry(
&url,
@@ -199,8 +187,6 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigation
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
),
];
return NavigationHistoryEntrySeed {
@@ -221,8 +207,6 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigation
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
)];
NavigationHistoryEntrySeed {
session_history: Default::default(),
@@ -235,8 +219,6 @@ pub fn child_browsing_context_single_entry_seed(url: Option<&Url>) -> Navigation
pub fn apply_child_browsing_context_navigation_to_entry_seed(
seed: &mut NavigationHistoryEntrySeed,
url: &Url,
- history_state_json: Option<String>,
- navigation_state_json: Option<String>,
) {
seed.session_history = crate::SessionHistorySeed {
commit: crate::SessionHistoryCommit::Push,
@@ -258,8 +240,6 @@ pub fn apply_child_browsing_context_navigation_to_entry_seed(
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- history_state_json,
- navigation_state_json,
));
seed.current_index = next_index;
seed.activation = Some(NavigationActivationSeed {
@@ -296,8 +276,6 @@ fn visible_activation_from(
pub fn replace_child_browsing_context_navigation_in_entry_seed(
seed: &mut NavigationHistoryEntrySeed,
url: &Url,
- history_state_json: Option<String>,
- navigation_state_json: Option<String>,
) {
seed.session_history = crate::SessionHistorySeed {
commit: crate::SessionHistoryCommit::Replace,
@@ -324,8 +302,6 @@ pub fn replace_child_browsing_context_navigation_in_entry_seed(
next_document_id,
NavigationHistoryEntryId::allocate(),
next_key,
- history_state_json,
- navigation_state_json,
);
if let Some(existing) = seed
.entries
@@ -400,8 +376,6 @@ pub fn cross_document_navigation_seed(
NavigationHistoryDocumentId::allocate(),
NavigationHistoryEntryId::allocate(),
NavigationHistoryEntryKey::allocate(),
- None,
- None,
);
entries.push(entry.clone());
(entry, next_index)
@@ -416,8 +390,6 @@ pub fn cross_document_navigation_seed(
next_document_id,
NavigationHistoryEntryId::allocate(),
next_key,
- None,
- None,
);
if let Some(existing) = entries
.iter_mut()
@@ -517,16 +489,12 @@ fn navigation_history_entry(
document_id: NavigationHistoryDocumentId,
id: NavigationHistoryEntryId,
key: NavigationHistoryEntryKey,
- history_state_json: Option<String>,
- navigation_state_json: Option<String>,
) -> NavigationHistorySerializedEntry {
NavigationHistorySerializedEntry {
url: url.to_owned(),
history_state: None,
navigation_state: None,
scroll_restoration: Default::default(),
- history_state_json,
- navigation_state_json,
referrer_policy: None,
document_id,
history_index,
@@ -614,10 +582,10 @@ mod tests {
let url = Url::parse("https://child.example/frame").unwrap();
let mut seed = child_browsing_context_single_entry_seed(None);
- replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url, None, None);
+ replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url);
let first = seed.entries[0].clone();
- replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url, None, None);
+ replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url);
let second = seed.entries[0].clone();
assert_eq!(first.history_index, second.history_index);
@@ -644,8 +612,6 @@ mod tests {
document_id("opaque-existing-document"),
entry_id("entry-4"),
entry_key("key-4"),
- None,
- None,
)];
let first = cross_document_navigation_seed(
@@ -688,12 +654,12 @@ mod tests {
let second = Url::parse("https://example.test/second").unwrap();
let replacement = Url::parse("https://example.test/replacement").unwrap();
let mut seed = child_browsing_context_single_entry_seed(None);
- apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &first, None, None);
- apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &second, None, None);
+ apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &first);
+ apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &second);
let retired_forward_entry = seed.entries[2].clone();
seed.current_index = 1;
- apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &replacement, None, None);
+ apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &replacement);
let replacement_entry = &seed.entries[2];
assert_eq!(
@@ -716,7 +682,7 @@ mod tests {
let mut seed = child_browsing_context_single_entry_seed(Some(&first));
let previous = seed.entries[1].clone();
- replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &second, None, None);
+ replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &second);
assert_eq!(seed.entries[1].history_index, previous.history_index);
assert_ne!(seed.entries[1].id, previous.id);
@@ -729,7 +695,7 @@ mod tests {
let second = Url::parse("http://127.0.0.1:2222/common/blank.html").unwrap();
let mut seed = child_browsing_context_single_entry_seed(Some(&first));
- apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &second, None, None);
+ apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &second);
assert_eq!(
seed.activation
@@ -744,7 +710,7 @@ mod tests {
.is_none()
);
- replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &first, None, None);
+ replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &first);
assert_eq!(
seed.activation
@@ -765,7 +731,7 @@ mod tests {
let url = Url::parse("http://127.0.0.1:1111/common/blank.html").unwrap();
let mut seed = child_browsing_context_single_entry_seed(None);
- replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url, None, None);
+ replace_child_browsing_context_navigation_in_entry_seed(&mut seed, &url);
assert_eq!(
seed.activation
@@ -780,7 +746,7 @@ mod tests {
fn child_javascript_url_navigation_preserves_current_entry_url_and_key() {
let url = Url::parse("http://127.0.0.1:1111/common/blank.html?1").unwrap();
let mut seed = child_browsing_context_single_entry_seed(None);
- apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &url, None, None);
+ apply_child_browsing_context_navigation_to_entry_seed(&mut seed, &url);
let before = seed.entries[1].clone();
apply_child_browsing_context_javascript_url_navigation_to_entry_seed(&mut seed);
@@ -804,8 +770,6 @@ mod tests {
document_id("document-0"),
entry_id("entry-0"),
entry_key("key-0"),
- None,
- None,
),
navigation_history_entry(
"https://example.test/current",
@@ -814,8 +778,6 @@ mod tests {
document_id("document-1"),
entry_id("entry-1"),
entry_key("key-1"),
- None,
- None,
),
navigation_history_entry(
"https://example.test/forward",
@@ -824,8 +786,6 @@ mod tests {
document_id("document-2"),
entry_id("entry-2"),
entry_key("key-2"),
- None,
- None,
),
];
@@ -860,8 +820,6 @@ mod tests {
document_id("document-4"),
entry_id("entry-4"),
entry_key("key-4"),
- None,
- None,
)];
let seed = cross_document_navigation_seed(
@@ -894,8 +852,6 @@ mod tests {
document_id("document-7"),
entry_id("entry-7"),
entry_key("key-7"),
- None,
- None,
)];
let seed = reload_navigation_seed(entries, 7).expect("reload seed");
@@ -919,8 +875,6 @@ mod tests {
document_id("document-1"),
entry_id("entry-0"),
entry_key("key-0"),
- None,
- None,
),
navigation_history_entry(
"https://example.test/target",
@@ -929,8 +883,6 @@ mod tests {
document_id("document-1"),
entry_id("entry-1"),
entry_key("key-1"),
- None,
- None,
),
];
@@ -947,8 +899,6 @@ mod tests {
document_id("document-0"),
entry_id("entry-0"),
entry_key("key-0"),
- None,
- None,
),
navigation_history_entry(
"https://example.test/target",
@@ -957,8 +907,6 @@ mod tests {
document_id("document-1"),
entry_id("entry-1"),
entry_key("key-1"),
- None,
- None,
),
];
diff --git a/moli-renderer-v8/src/blob.rs b/moli-renderer-v8/src/blob.rs
index ece494132..bcaecfa05 100644
--- a/moli-renderer-v8/src/blob.rs
+++ b/moli-renderer-v8/src/blob.rs
@@ -284,6 +284,23 @@ fn blob_id_from_object<'s>(
blob_id_from_value(scope, value)
}
+pub(crate) fn world_wrapper<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let id = blob_id_from_object(scope, source)?;
+ // The wrapper cache binds this view to source, retaining its native Blob
+ // reference. No payload copy or independent Blob identity is created.
+ let object = BlobInstanceDeclaration::new(v8::BigInt::new_from_u64(scope, id))
+ .bind(scope)
+ .ok()?;
+ let prototype =
+ crate::context_bootstrap::ensure_intrinsic_interface_prototype(scope, "Blob").ok()?;
+ finalize_blob_realm_bindings(scope, prototype);
+ object.set_prototype(scope, prototype.into())?;
+ Some(object)
+}
+
fn blob_id_from_value(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 980e071dd..0caa1ee82 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -75,8 +75,10 @@ mod navigation_traversal_execution;
mod navigation_traversal_plan;
mod navigation_window;
mod navigator_runtime;
+mod platform_object_worlds;
mod session_history;
mod shared_event_targets;
+mod world_wrappers;
#[cfg(test)]
pub(crate) use navigator_runtime::{
materialized_navigator_subobject_keys, navigator_storage_wrapper_diagnostics,
diff --git a/moli-renderer-v8/src/context_bootstrap/event_legacy.rs b/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
index d2a4cb564..da60b46b7 100644
--- a/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
+++ b/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
@@ -316,7 +316,7 @@ pub(super) fn ui_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -341,7 +341,7 @@ pub(super) fn text_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -369,7 +369,7 @@ pub(super) fn mouse_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -415,7 +415,7 @@ pub(super) fn keyboard_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -442,7 +442,7 @@ pub(super) fn composition_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -468,7 +468,7 @@ pub(super) fn custom_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -493,7 +493,7 @@ pub(super) fn storage_event_init_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
@@ -526,7 +526,7 @@ pub(super) fn keyboard_event_get_modifier_state_callback<'s>(
let Some(parsed) = webidl::parse_args::<KeyboardEventGetModifierStateArgs>(scope, &args) else {
return;
};
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
let key_name = match parsed.key_arg.as_str() {
"Alt" | "AltGraph" => "altKey",
"Control" => "ctrlKey",
diff --git a/moli-renderer-v8/src/context_bootstrap/event_target_dispatch.rs b/moli-renderer-v8/src/context_bootstrap/event_target_dispatch.rs
index dde113809..f1942bdab 100644
--- a/moli-renderer-v8/src/context_bootstrap/event_target_dispatch.rs
+++ b/moli-renderer-v8/src/context_bootstrap/event_target_dispatch.rs
@@ -42,6 +42,11 @@ pub(crate) fn begin_dispatch<'s>(
target: v8::Local<'s, v8::Object>,
event: v8::Local<'s, v8::Object>,
) -> bool {
+ let backing = super::events::event_backing(scope, event);
+ let target = backing
+ .get_creation_context(scope)
+ .map(|context| super::shared_event_targets::target_in_realm(scope, target, context))
+ .unwrap_or(target);
set_event_dispatch_fields(scope, target, event);
let path = v8::Array::new_with_elements(scope, &[target.into()]);
set_event_composed_path(scope, event, path);
diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs
index a3814a4b9..2b16ad880 100644
--- a/moli-renderer-v8/src/context_bootstrap/events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events.rs
@@ -228,7 +228,9 @@ pub(crate) use base::{
event_internal_bool_flag, event_is_dispatching, initialize_event_object, mark_event_trusted,
set_event_composed_path, set_event_internal_flag, set_event_trusted,
};
-pub(in crate::context_bootstrap) use base::{bind_event_backing, event_backing, event_trusted};
+pub(in crate::context_bootstrap) use base::{
+ bind_event_attribute, bind_event_backing, event_backing, event_trusted,
+};
fn event_subclass_kind<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/base.rs b/moli-renderer-v8/src/context_bootstrap/events/base.rs
index fc9b3ab18..5bbc941d8 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/base.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/base.rs
@@ -50,23 +50,31 @@ pub(in crate::context_bootstrap) fn bind_event_backing<'s>(
{
continue;
}
- let getter = v8::Function::builder(shared_event_attribute_getter)
- .data(v8str(scope, property).into())
- .build(scope)
- .expect("event attribute getter");
- crate::definitions::define_get_set_property(
- scope,
- wrapper,
- v8str(scope, property).into(),
- getter.into(),
- v8::undefined(scope).into(),
- v8::PropertyAttribute::NONE,
- "shared Event attribute",
- )
- .expect("shared Event attribute");
+ bind_event_attribute(scope, wrapper, property);
}
}
+pub(in crate::context_bootstrap) fn bind_event_attribute<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+ property: &'static str,
+) {
+ let getter = v8::Function::builder(shared_event_attribute_getter)
+ .data(v8str(scope, property).into())
+ .build(scope)
+ .expect("event attribute getter");
+ crate::definitions::define_get_set_property(
+ scope,
+ wrapper,
+ v8str(scope, property).into(),
+ getter.into(),
+ v8::undefined(scope).into(),
+ v8::PropertyAttribute::NONE,
+ "shared Event attribute",
+ )
+ .expect("shared Event attribute");
+}
+
fn shared_event_attribute_getter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -95,7 +103,8 @@ fn shared_event_attribute_value<'s>(
.into(),
);
}
- Some(value)
+ let context = wrapper.get_creation_context(scope)?;
+ super::super::navigation_event_worlds::attribute_in_realm(scope, property, value, context)
}
#[derive(WebApiObject)]
diff --git a/moli-renderer-v8/src/context_bootstrap/file_api.rs b/moli-renderer-v8/src/context_bootstrap/file_api.rs
index 9da4c5b97..1bb0442f3 100644
--- a/moli-renderer-v8/src/context_bootstrap/file_api.rs
+++ b/moli-renderer-v8/src/context_bootstrap/file_api.rs
@@ -29,6 +29,7 @@ pub(crate) use directory_reader::{
DirectoryReaderCallbackAdmission, DirectoryReaderCallbackTask,
DirectoryReaderCallbackTaskEffect, file_system_directory_reader_read_entries_callback,
};
+pub(super) use file::bind_file_world_wrapper;
pub(super) use file::file_constructor_callback;
pub(in crate::context_bootstrap) use file::file_name_from_object;
pub(crate) use file::{build_file_object, selected_file_from_object};
diff --git a/moli-renderer-v8/src/context_bootstrap/file_api/file.rs b/moli-renderer-v8/src/context_bootstrap/file_api/file.rs
index 8505e247a..b483ee62f 100644
--- a/moli-renderer-v8/src/context_bootstrap/file_api/file.rs
+++ b/moli-renderer-v8/src/context_bootstrap/file_api/file.rs
@@ -10,6 +10,20 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
const FILE_NAME_SLOT: &str = "__lmFileName";
const FILE_LAST_MODIFIED_SLOT: &str = "__lmFileLastModified";
+pub(in crate::context_bootstrap) fn bind_file_world_wrapper<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+ wrapper: v8::Local<'s, v8::Object>,
+) -> Option<()> {
+ let name = file_name_from_object(scope, source)?;
+ let modified =
+ get_private_value(scope, source, FILE_LAST_MODIFIED_SLOT)?.number_value(scope)?;
+ initialize_file_metadata(scope, wrapper, &name, modified);
+ let prototype = super::super::ensure_intrinsic_interface_prototype(scope, "File").ok()?;
+ wrapper.set_prototype(scope, prototype.into())?;
+ Some(())
+}
+
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::File)]
struct FileMetadataDeclaration {
diff --git a/moli-renderer-v8/src/context_bootstrap/form_data_runtime.rs b/moli-renderer-v8/src/context_bootstrap/form_data_runtime.rs
index 23443c310..31ec98e81 100644
--- a/moli-renderer-v8/src/context_bootstrap/form_data_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/form_data_runtime.rs
@@ -18,6 +18,15 @@ pub(crate) use serialize::form_data_entries_to_string_pairs;
pub(in crate::context_bootstrap) use storage::form_data_is_object;
pub(super) use template::build_form_data_constructor_template;
+pub(super) fn new_world_wrapper<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let constructor =
+ super::exposed_interfaces::ensure_intrinsic_interface_constructor(scope, "FormData")
+ .ok()?;
+ constructor.new_instance(scope, &[])
+}
+
pub(crate) fn form_data_object_from_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
entries: &[(String, v8::Global<v8::Value>)],
diff --git a/moli-renderer-v8/src/context_bootstrap/form_data_runtime/storage.rs b/moli-renderer-v8/src/context_bootstrap/form_data_runtime/storage.rs
index 77627affe..c0eaf4b1b 100644
--- a/moli-renderer-v8/src/context_bootstrap/form_data_runtime/storage.rs
+++ b/moli-renderer-v8/src/context_bootstrap/form_data_runtime/storage.rs
@@ -43,6 +43,11 @@ pub(in crate::context_bootstrap) fn form_data_entries<'s>(
let value = pair
.get_index(scope, 1)
.unwrap_or_else(|| v8::undefined(scope).into());
+ let context = object
+ .get_creation_context(scope)
+ .unwrap_or_else(|| scope.get_current_context());
+ let value =
+ super::super::platform_object_worlds::in_realm(scope, value, context).unwrap_or(value);
entries.push((key, v8::Global::new(scope, value)));
}
entries
@@ -71,6 +76,7 @@ pub(super) fn set_form_data_entries(
object: v8::Local<'_, v8::Object>,
entries: &[(String, v8::Global<v8::Value>)],
) {
+ let object = super::super::world_wrappers::owner(scope, v8::Local::new(scope, object));
let array = form_data_entries_array(scope, entries);
set_private_value(scope, object, FORM_DATA_ENTRIES_SLOT, array.into());
}
@@ -92,7 +98,13 @@ fn form_data_entries_array<'s>(
) -> v8::Local<'s, v8::Array> {
let pairs: Vec<(&str, v8::Local<'s, v8::Value>)> = entries
.iter()
- .map(|(key, value)| (key.as_str(), v8::Local::new(scope, value)))
+ .map(|(key, value)| {
+ let value = v8::Local::new(scope, value);
+ let value = v8::Local::<v8::Object>::try_from(value)
+ .map(|object| super::super::world_wrappers::owner(scope, object).into())
+ .unwrap_or(value);
+ (key.as_str(), value)
+ })
.collect();
serialize_v8_array(scope, pairs.as_slice()).unwrap_or_else(|| v8::Array::new(scope, 0))
}
@@ -101,6 +113,7 @@ fn form_data_entries_private_array<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Array>> {
+ let object = super::super::world_wrappers::owner(scope, object);
get_private_value(scope, object, FORM_DATA_ENTRIES_SLOT)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
}
diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
index 064a103c4..4edfa9e32 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
@@ -199,8 +199,6 @@ fn mutate_history_object<'s>(
scope,
url.as_str(),
None,
- None,
- None,
next_navigation_index,
&new_navigation_entry_id(),
&new_navigation_entry_key(),
@@ -220,8 +218,6 @@ fn mutate_history_object<'s>(
scope,
url.as_str(),
None,
- None,
- None,
current_navigation_index,
&new_navigation_entry_id(),
&key,
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
index 3750c4724..d15c1f374 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
@@ -3,7 +3,7 @@ use super::super::location_runtime::{
};
use super::super::navigation_entry::{
cache_current_history_state, history_entries, history_index, navigation_current_entry,
- navigation_entries_share_document, navigation_entry_url_value, set_history_index,
+ navigation_entries_share_document, set_history_index,
sync_navigation_current_entry_from_history_entry,
};
use super::super::navigation_events::{
@@ -50,12 +50,16 @@ pub(in crate::context_bootstrap) fn prepare_local_history_entry_commit<'s>(
let old_url = window_location_for_holder(scope, owner)
.and_then(|location| location_href_slot(scope, location));
let entries = history_entries(scope, history)?;
- let entry = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let state = super::super::navigation_entry_state::clone_history_entry_state(scope, entry)
+ let record = entries.get(index as usize)?;
+ let (url, snapshot) = {
+ let record = record.borrow();
+ (record.url.clone(), record.history_state.clone())
+ };
+ let state = snapshot
+ .as_ref()
+ .and_then(|state| crate::structured_clone::deserialize_history_state(scope, state))
.unwrap_or_else(|| v8::null(scope).into());
- let url = navigation_entry_url_value(scope, entry).unwrap_or_else(|| "about:blank".to_owned());
+ let entry = super::native::entry_wrapper(scope, owner, record.clone());
let location = window_location_for_holder(scope, owner)?;
let parsed_url = url::Url::parse(&url).ok()?;
Some(PreparedHistoryEntry {
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
index 001ba8d7c..d5a8a1ddc 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
@@ -187,18 +187,6 @@ pub(in crate::context_bootstrap) fn entry_in_realm<'s>(
wrapper
}
-pub(in crate::context_bootstrap) fn same_entry<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- left: v8::Local<'s, v8::Object>,
- right: v8::Local<'s, v8::Object>,
-) -> bool {
- left.strict_equals(right.into())
- || match (entry(scope, left), entry(scope, right)) {
- (Some(left), Some(right)) => Rc::ptr_eq(&left, &right),
- _ => false,
- }
-}
-
pub(in crate::context_bootstrap) fn entry_value_in_realm<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
@@ -247,12 +235,17 @@ pub(in crate::context_bootstrap) fn entry_wrapper<'s>(
owner: v8::Local<'s, v8::Object>,
entry: HistoryEntryRef,
) -> v8::Local<'s, v8::Object> {
+ let context = owner
+ .get_creation_context(scope)
+ .expect("History Window realm");
+ let scope = &mut v8::ContextScope::new(scope, context);
let id = entry.borrow().id.clone();
let map = wrappers(scope, owner);
if let Some(key) = v8_string(scope, &id)
&& let Some(wrapper) = map
.get(scope, key.into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ && self::entry(scope, wrapper).is_some_and(|record| Rc::ptr_eq(&record, &entry))
{
return wrapper;
}
@@ -266,17 +259,27 @@ pub(in crate::context_bootstrap) fn prune_entry_wrappers<'s>(
owner: v8::Local<'s, v8::Object>,
entries: &[HistoryEntryRef],
) {
- let live: std::collections::HashSet<String> = entries
+ let live: std::collections::HashMap<_, _> = entries
.iter()
- .map(|entry| entry.borrow().id.clone())
+ .map(|entry| (entry.borrow().id.clone(), Rc::as_ptr(entry)))
.collect();
- let map = wrappers(scope, owner);
+ let Some(map) = get_private_value(scope, owner, ENTRY_WRAPPERS)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ else {
+ return;
+ };
let pairs = map.as_array(scope);
for index in (0..pairs.length()).step_by(2) {
- if let Some(key) = pairs.get_index(scope, index)
- && let Some(id) = key.to_string(scope)
- && !live.contains(&id.to_rust_string_lossy(scope))
- {
+ let Some(key) = pairs.get_index(scope, index) else {
+ continue;
+ };
+ let record = pairs
+ .get_index(scope, index + 1)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .and_then(|wrapper| entry(scope, wrapper));
+ let retained = record
+ .is_some_and(|record| live.get(&record.borrow().id) == Some(&Rc::as_ptr(&record)));
+ if !retained {
let _ = map.delete(scope, key);
}
}
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs
index 2bd8e8a81..99267e95e 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs
@@ -4,7 +4,7 @@ use super::super::navigation_window::runtime_window_owner;
use super::native;
use crate::structured_clone::deserialize_history_state;
use crate::util::{get_private_value, private_key, set_private_value, v8_string};
-use moli_history::ScrollRestoration;
+use moli_history::{HistoryEntryRef, ScrollRestoration};
const WINDOW_HISTORY_OWNER_SLOT: &str = "__moliWindowHistoryOwner";
const CACHED_REVISION_SLOT: &str = "__moliHistoryCachedRevision";
@@ -39,46 +39,23 @@ pub(in crate::context_bootstrap) fn window_has_shared_history<'s>(
pub(in crate::context_bootstrap) fn history_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
history: v8::Local<'s, v8::Object>,
-) -> Option<v8::Local<'s, v8::Array>> {
+) -> Option<Vec<HistoryEntryRef>> {
let record = native::history(scope, history)?;
let entries = record.borrow().entries().to_vec();
- let owner = runtime_window_owner(scope, history);
- // This array is a binding projection. The native vector is authoritative.
- let array = v8::Array::new(scope, entries.len() as i32);
- for (index, entry) in entries.into_iter().enumerate() {
- let wrapper = native::entry_wrapper(scope, owner, entry);
- let _ = array.set_index(scope, index as u32, wrapper.into());
- }
- Some(array)
+ Some(entries)
}
pub(in crate::context_bootstrap) fn set_history_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
history: v8::Local<'s, v8::Object>,
- entries: v8::Local<'s, v8::Array>,
+ entries: Vec<HistoryEntryRef>,
) {
let Some(record) = native::history(scope, history) else {
return;
};
let owner = runtime_window_owner(scope, history);
- let mut native_entries = Vec::with_capacity(entries.length() as usize);
- for index in 0..entries.length() {
- let Some(wrapper) = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- let Some(entry) = native::entry(scope, wrapper) else {
- return;
- };
- super::super::navigation_activation::bind_navigation_entry_runtime_owner(
- scope, wrapper, owner,
- );
- native_entries.push(entry);
- }
- native::prune_entry_wrappers(scope, owner, &native_entries);
- record.borrow_mut().restore_entries(native_entries);
+ native::prune_entry_wrappers(scope, owner, &entries);
+ record.borrow_mut().restore_entries(entries);
}
pub(in crate::context_bootstrap) fn push_history_entry<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
index 0adb3df55..84c98753c 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
@@ -1,4 +1,4 @@
-use super::super::navigation_entry::{history_entries, navigation_entry_key_value};
+use super::super::navigation_entry::history_entries;
use super::super::navigation_events::{
NavigationDispatchOutcome, dispatch_navigation_success,
run_navigation_precommit_deferred_handlers,
@@ -137,14 +137,12 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
) {
let plan = history_traversal_target_window(scope, host, traversal.target).and_then(|owner| {
let history = window_history_for_holder(scope, owner)?;
- let entry = history_entries(scope, history)?
- .get_index(scope, traversal.target_index)?
- .try_into()
- .ok()?;
+ let entries = history_entries(scope, history)?;
+ let entry = entries.get(traversal.target_index as usize)?;
if traversal
.target_key
.as_ref()
- .is_some_and(|key| navigation_entry_key_value(scope, entry).as_ref() != Some(key))
+ .is_some_and(|key| entry.borrow().key.as_str() != key)
{
return None;
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
index b90c3e2a0..116ec0886 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
@@ -1,12 +1,11 @@
+use super::history_runtime::native;
use super::location_history_storage::{
NAVIGATION_ACTIVATION_SLOT, NAVIGATION_CURRENT_ENTRY_SLOT, NAVIGATION_TRANSITION_SLOT,
};
-use super::navigation_entry::{
- create_navigation_entry, history_entries, navigation_entry_public_token,
- set_navigation_entry_document_id,
-};
+use super::navigation_entry::{history_entries, navigation_entry_public_token};
use super::navigation_lifecycle::enqueue_navigation_lifecycle_microtask;
use super::navigation_result::suppress_unhandled_rejection;
+use super::navigation_seed::history_entry_from_snapshot;
use super::navigation_window::{
runtime_window_owner, set_runtime_window_owner, window_history_for_holder,
};
@@ -100,16 +99,16 @@ fn navigation_entry_matches_activation_snapshot<'s>(
entry: v8::Local<'s, v8::Object>,
snapshot: &NavigationHistorySerializedEntry,
) -> bool {
- let current_id = get_own_static_property(scope, entry, "id")
- .and_then(|value| value.to_string(scope))
- .map(|value| value.to_rust_string_lossy(scope));
- let current_key = get_own_static_property(scope, entry, "key")
- .and_then(|value| value.to_string(scope))
- .map(|value| value.to_rust_string_lossy(scope));
- let snapshot_id = navigation_entry_public_token(&snapshot.id);
- let snapshot_key = navigation_entry_public_token(&snapshot.key);
- current_id.as_deref() == Some(snapshot_id.as_str())
- && current_key.as_deref() == Some(snapshot_key.as_str())
+ native::entry(scope, entry)
+ .is_some_and(|entry| native_entry_matches_activation_snapshot(&entry.borrow(), snapshot))
+}
+
+fn native_entry_matches_activation_snapshot(
+ entry: &moli_history::HistoryEntry,
+ snapshot: &NavigationHistorySerializedEntry,
+) -> bool {
+ entry.id == navigation_entry_public_token(&snapshot.id)
+ && entry.key.as_str() == navigation_entry_public_token(&snapshot.key)
}
pub(super) fn navigation_entry_object_from_snapshot<'s>(
@@ -124,32 +123,13 @@ pub(super) fn navigation_entry_object_from_snapshot<'s>(
if let Some(history) = window_history_for_holder(scope, owner)
&& let Some(entries) = history_entries(scope, history)
{
- for index in 0..entries.length() {
- let Some(entry) = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- continue;
- };
- if navigation_entry_matches_activation_snapshot(scope, entry, snapshot) {
- return entry;
+ for entry in entries {
+ if native_entry_matches_activation_snapshot(&entry.borrow(), snapshot) {
+ return native::entry_wrapper(scope, owner, entry);
}
}
}
- let entry = create_navigation_entry(
- scope,
- &snapshot.url,
- snapshot.history_state_json.as_deref(),
- snapshot.navigation_state_json.as_deref(),
- snapshot.referrer_policy.as_deref(),
- snapshot.index,
- &snapshot.id,
- &snapshot.key,
- );
- set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());
- super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);
- bind_navigation_entry_runtime_owner(scope, entry, owner);
- entry
+ native::entry_wrapper(scope, owner, history_entry_from_snapshot(snapshot))
}
fn navigation_activation_entry_object<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs
index 5800bec3c..86470b3db 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs
@@ -10,7 +10,7 @@ use super::navigation_activation::{
use super::navigation_entry::{set_history_entries, set_history_index};
use super::navigation_result::clear_active_cross_document_navigation_if_matches;
use super::navigation_seed::{
- build_current_navigation_entry_from_seed, build_history_entries_array_from_seed,
+ build_current_navigation_entry_from_seed, build_history_entries_from_seed,
initial_navigation_history_seed,
};
use super::navigation_surface::{
@@ -79,7 +79,7 @@ pub(crate) fn reset_window_location_history_navigation_runtime_state<'s>(
href: &str,
) -> Result<()> {
// Creating/rebinding an isolated realm must never reset the Window's
- // shared history, including structured-clone state absent from JSON seeds.
+ // shared history or its structured-clone state.
if window_has_shared_history(scope, window) {
return Ok(());
}
@@ -104,10 +104,10 @@ pub(crate) fn reset_window_location_history_navigation_runtime_state<'s>(
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 entries = build_history_entries_array_from_seed(scope, window, &initial_seed);
+ let entries = build_history_entries_from_seed(&initial_seed);
let current_entry = entries
- .get_index(scope, initial_seed.current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .get(initial_seed.current_index as usize)
+ .map(|entry| super::history_runtime::native::entry_wrapper(scope, window, entry.clone()))
.unwrap_or_else(|| {
build_current_navigation_entry_from_seed(
scope,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs
index 153f0d205..e3624fe79 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks.rs
@@ -4,7 +4,7 @@ use super::location_navigation::{
};
use super::location_runtime::{is_same_document_fragment_navigation, location_href_slot};
use super::navigation_cross_document::handle_navigation_navigate_cross_document;
-use super::navigation_entry::{history_entries, history_index, navigation_current_entry};
+use super::navigation_entry::{history_entries, navigation_current_entry};
use super::navigation_entry_state::{
clone_navigation_entry_state, clone_navigation_state_arg_for_result, set_navigation_entry_state,
};
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
index 9c2fd76f1..f12f58c40 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
@@ -68,20 +68,11 @@ pub(in crate::context_bootstrap) fn navigation_entries_callback<'s>(
return;
};
let current_entry = navigation_current_entry(scope, owner);
- let copied = build_visible_navigation_entries_array(scope, entries, current_entry);
let context = navigation
.get_creation_context(scope)
.unwrap_or_else(|| scope.get_current_context());
- for index in 0..copied.length() {
- if let Some(entry) = copied
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- {
- let wrapper =
- super::super::history_runtime::native::entry_in_realm(scope, entry, context);
- let _ = copied.set_index(scope, index, wrapper.into());
- }
- }
+ let copied =
+ build_visible_navigation_entries_array(scope, owner, &entries, current_entry, context);
rv.set(copied.into());
}
@@ -765,23 +756,6 @@ fn set_reload_current_entry_state<'s>(
return;
};
set_navigation_entry_state(scope, current_entry, state);
- let Some(history) = window_history_for_holder(scope, owner) else {
- return;
- };
- let Some(entries) = history_entries(scope, history) else {
- return;
- };
- let current_index = history_index(scope, history);
- let Some(history_entry) = entries
- .get_index(scope, current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- if history_entry.strict_equals(current_entry.into()) {
- return;
- }
- set_navigation_entry_state(scope, history_entry, state);
}
const PRECOMMIT_COMMIT_OWNER_SLOT: &str = "__lmPrecommitCommitOwner";
@@ -1931,19 +1905,6 @@ pub(in crate::context_bootstrap) fn navigation_update_current_entry_callback<'s>
};
set_navigation_entry_state(scope, current_entry, cloned_state);
- if let Some(history) = window_history_for_holder(scope, owner)
- && let Some(entries) = history_entries(scope, history)
- {
- let current_index = history_index(scope, history);
- if let Some(history_entry) = entries
- .get_index(scope, current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- && !history_entry.strict_equals(current_entry.into())
- {
- set_navigation_entry_state(scope, history_entry, cloned_state);
- }
- }
-
dispatch_navigation_currententrychange(scope, navigation, Some(previous_entry), None);
sync_child_navigation_entry_seed_from_owner(scope, owner);
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
index 47bbf6b90..f017bdb53 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
@@ -119,27 +119,18 @@ pub(super) fn restore_current_navigation_entry_scroll_position<'s>(
pub(super) fn create_navigation_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
url: &str,
- history_state_json: Option<&str>,
- navigation_state_json: Option<&str>,
referrer_policy: Option<&str>,
index: u32,
id: &str,
key: &str,
) -> v8::Local<'s, v8::Object> {
- let history_snapshot =
- super::navigation_serialize::parse_history_entry_state(scope, history_state_json);
- let navigation_snapshot =
- super::navigation_serialize::parse_navigation_entry_state(scope, navigation_state_json);
let public_id = navigation_entry_public_token(id);
let public_key = navigation_entry_public_token(key);
let entry = HistoryEntry {
url: url.to_owned(),
referrer_policy: referrer_policy.map(str::to_owned),
- history_state: crate::structured_clone::serialize_history_state(scope, history_snapshot),
- navigation_state: crate::structured_clone::serialize_history_state(
- scope,
- navigation_snapshot,
- ),
+ history_state: None,
+ navigation_state: None,
id: public_id.clone(),
key: NavigationHistoryEntryKey::from_serialized(public_key),
document: NavigationHistoryDocumentId::from_serialized(public_id),
@@ -205,16 +196,6 @@ pub(super) fn navigation_entry_initial_index<'s>(
native::entry(scope, entry).map(|entry| entry.borrow().index)
}
-pub(super) fn set_navigation_entry_initial_index<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entry: v8::Local<'s, v8::Object>,
- index: u32,
-) {
- if let Some(entry) = native::entry(scope, entry) {
- entry.borrow_mut().index = index;
- }
-}
-
pub(super) fn navigation_entry_referrer_policy_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
entry: v8::Local<'s, v8::Object>,
@@ -440,10 +421,11 @@ fn navigation_entry_index_getter<'s>(
let owner = runtime_window_owner(scope, args.this());
if let Some(history) = window_history_for_holder(scope, owner)
&& let Some(entries) = history_entries(scope, history)
+ && let Some(entry) = native::entry(scope, args.this())
{
let current_entry = navigation_current_entry(scope, owner);
if let Some(visible_index) =
- visible_navigation_index_for_entry(scope, entries, current_entry, args.this())
+ visible_navigation_index_for_entry(scope, &entries, current_entry, &entry)
{
rv.set(v8::Number::new(scope, visible_index as f64).into());
return;
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs
index d8f7247b4..8e0f362dc 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs
@@ -38,19 +38,6 @@ pub(super) fn clone_history_entry_state<'s>(
history_entry_state_snapshot(scope, entry)
}
-pub(super) fn set_history_entry_state<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entry: v8::Local<'s, v8::Object>,
- state: v8::Local<'s, v8::Value>,
-) {
- let Some(record) = native::entry(scope, entry) else {
- return;
- };
- if let Some(state) = serialize_history_state(scope, state) {
- record.borrow_mut().history_state = Some(state);
- }
-}
-
pub(super) fn copy_entry_serialized_states<'s>(
scope: &mut v8::PinScope<'s, '_>,
from: v8::Local<'s, v8::Object>,
@@ -84,24 +71,6 @@ pub(super) fn set_navigation_entry_state<'s>(
}
}
-pub(super) fn restore_serialized_entry_state<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entry: v8::Local<'s, v8::Object>,
- snapshot: &moli_page_types::NavigationHistorySerializedEntry,
-) {
- let Some(record) = native::entry(scope, entry) else {
- return;
- };
- let mut record = record.borrow_mut();
- if snapshot.history_state.is_some() {
- record.history_state = snapshot.history_state.clone();
- }
- if snapshot.navigation_state.is_some() {
- record.navigation_state = snapshot.navigation_state.clone();
- }
- record.scroll_restoration = snapshot.scroll_restoration;
-}
-
pub(super) fn clone_navigation_state_arg_for_result<'s>(
scope: &mut v8::PinScope<'s, '_>,
options: Option<v8::Local<'s, v8::Object>>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs
index 855c4372a..c1a560624 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs
@@ -1,10 +1,8 @@
//! Event views for one Navigation dispatch. User callbacks never receive the
//! internal control object, so page expandos cannot cross into another world.
-use super::{events, history_runtime::native, shared_event_targets};
-use crate::util::{get_private_value, set_private_value, v8str};
-
-const WRAPPERS: &str = "__moliNavigationEventWrappers";
+use super::{events, history_runtime::native, shared_event_targets, world_wrappers};
+use crate::util::v8str;
pub(super) fn event_in_realm<'s>(
scope: &mut v8::PinScope<'s, '_>,
@@ -13,75 +11,39 @@ pub(super) fn event_in_realm<'s>(
event_type: &str,
context: v8::Local<'s, v8::Context>,
) -> Option<v8::Local<'s, v8::Object>> {
- // Script-created events retain their dispatchEvent identity. This adapter
- // handles the UA events belonging to the shared Navigation transaction.
- if !shared_event_targets::is_shared_target(scope, target)
- || !events::event_trusted(scope, event)
- {
+ if !shared_event_targets::is_shared_target(scope, target) {
return Some(event);
}
+ let backing = events::event_backing(scope, event);
+ // Register an author's original object in its world; foreign listeners
+ // receive their own wrapper, even when the event is untrusted. A retained
+ // UA view already belongs to the backing object's wrapper cache.
+ if backing.strict_equals(event.into()) && !events::event_trusted(scope, event) {
+ let creation = event.get_creation_context(scope)?;
+ if world_wrappers::get(scope, backing, creation).is_none() {
+ world_wrappers::insert(scope, backing, event);
+ }
+ }
let target = shared_event_targets::target_in_realm(scope, target, context);
// A callback in another same-world Document still receives the owning
// Window's wrapper. Its callback realm is entered separately by the invoker.
let context = target.get_creation_context(scope).unwrap_or(context);
- let wrappers = get_private_value(scope, event, WRAPPERS)
- .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
- .unwrap_or_else(|| {
- let map = v8::Map::new(scope);
- set_private_value(scope, event, WRAPPERS, map.into());
- map
- });
- let global = context.global(scope);
- if let Some(wrapper) = wrappers
- .get(scope, global.into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- {
+ if let Some(wrapper) = world_wrappers::get(scope, backing, context) {
return Some(wrapper);
}
let scope = &mut v8::ContextScope::new(scope, context);
let init = crate::util::new_null_prototype_object(scope);
- let (interface, properties): (&str, &[&'static str]) = match event_type {
- "navigate" => (
- "NavigateEvent",
- &[
- "navigationType",
- "destination",
- "canIntercept",
- "userInitiated",
- "hashChange",
- "signal",
- "formData",
- "downloadRequest",
- "info",
- "sourceElement",
- "hasUAVisualTransition",
- ],
- ),
- "currententrychange" => (
- "NavigationCurrentEntryChangeEvent",
- &["from", "navigationType"],
- ),
- "navigateerror" => (
- "ErrorEvent",
- &["message", "filename", "lineno", "colno", "error"],
- ),
- _ => ("Event", &[]),
- };
+ // Native interface identity survives author prototype/constructor changes
+ // and initEvent(). An event named "navigate" can still be an ordinary Event.
+ let interface = moli_webapi_declare::web_api_object_type(scope, backing)?.name();
+ let properties = init_properties(interface);
for property in properties
.iter()
.copied()
.chain(["bubbles", "cancelable", "composed"])
{
- let mut value = event.get(scope, v8str(scope, property).into())?;
- if property == "from" {
- if let Ok(entry) = v8::Local::<v8::Object>::try_from(value) {
- value = native::entry_in_realm(scope, entry, context).into();
- }
- } else if property == "destination" {
- let destination = v8::Local::<v8::Object>::try_from(value).ok()?;
- value = super::navigation_events::navigation_destination_for_realm(scope, destination)?
- .into();
- }
+ let value = backing.get(scope, v8str(scope, property).into())?;
+ let value = attribute_in_realm(scope, property, value, context)?;
let _ = init.set(scope, v8str(scope, property).into(), value);
}
let constructor =
@@ -91,7 +53,177 @@ pub(super) fn event_in_realm<'s>(
for property in ["target", "srcElement"] {
let _ = wrapper.set(scope, v8str(scope, property).into(), target.into());
}
- events::bind_event_backing(scope, wrapper, event);
- let _ = wrappers.set(scope, global.into(), wrapper.into());
+ events::bind_event_backing(scope, wrapper, backing);
+ for property in properties {
+ events::bind_event_attribute(scope, wrapper, property);
+ }
+ world_wrappers::insert(scope, backing, wrapper);
Some(wrapper)
}
+
+pub(super) fn attribute_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ property: &str,
+ value: v8::Local<'s, v8::Value>,
+ context: v8::Local<'s, v8::Context>,
+) -> Option<v8::Local<'s, v8::Value>> {
+ match property {
+ "from" => Some(native::entry_value_in_realm(scope, value, context)),
+ "destination" => {
+ let destination = v8::Local::<v8::Object>::try_from(value).ok()?;
+ let scope = &mut v8::ContextScope::new(scope, context);
+ super::navigation_events::navigation_destination_for_realm(scope, destination)
+ .map(Into::into)
+ }
+ "signal" | "formData" | "sourceElement" | "relatedTarget" | "submitter" | "source" => {
+ super::platform_object_worlds::in_realm(scope, value, context)
+ }
+ // info, error, detail, data, reason, and state can contain arbitrary JS
+ // values. They are not platform wrappers or storage-serialized payloads.
+ _ => Some(value),
+ }
+}
+
+fn init_properties(interface: &str) -> Vec<&'static str> {
+ let mut properties = Vec::new();
+ if matches!(
+ interface,
+ "UIEvent"
+ | "FocusEvent"
+ | "TextEvent"
+ | "CompositionEvent"
+ | "MouseEvent"
+ | "KeyboardEvent"
+ | "WheelEvent"
+ | "PointerEvent"
+ | "TouchEvent"
+ | "DragEvent"
+ | "InputEvent"
+ | "CapturedMouseEvent"
+ ) {
+ properties.extend(["view", "detail"]);
+ }
+ if matches!(
+ interface,
+ "MouseEvent" | "WheelEvent" | "PointerEvent" | "DragEvent" | "CapturedMouseEvent"
+ ) {
+ properties.extend([
+ "screenX",
+ "screenY",
+ "clientX",
+ "clientY",
+ "ctrlKey",
+ "shiftKey",
+ "altKey",
+ "metaKey",
+ "button",
+ "buttons",
+ "relatedTarget",
+ "movementX",
+ "movementY",
+ ]);
+ }
+ let own: &[&str] = match interface {
+ "CustomEvent" => &["detail"],
+ "FocusEvent" => &["relatedTarget"],
+ "TextEvent" | "CompositionEvent" => &["data"],
+ "KeyboardEvent" => &[
+ "key",
+ "code",
+ "location",
+ "ctrlKey",
+ "shiftKey",
+ "altKey",
+ "metaKey",
+ "repeat",
+ "isComposing",
+ "charCode",
+ "keyCode",
+ "which",
+ ],
+ "WheelEvent" => &["deltaX", "deltaY", "deltaZ", "deltaMode"],
+ "PointerEvent" => &[
+ "pointerId",
+ "width",
+ "height",
+ "pressure",
+ "tangentialPressure",
+ "tiltX",
+ "tiltY",
+ "twist",
+ "altitudeAngle",
+ "azimuthAngle",
+ "pointerType",
+ "isPrimary",
+ "persistentDeviceId",
+ ],
+ "TouchEvent" => &[
+ "touches",
+ "targetTouches",
+ "changedTouches",
+ "ctrlKey",
+ "shiftKey",
+ "altKey",
+ "metaKey",
+ ],
+ "MessageEvent" => &["data", "origin", "lastEventId", "source", "ports"],
+ "ErrorEvent" => &["message", "filename", "lineno", "colno", "error"],
+ "PromiseRejectionEvent" => &["promise", "reason"],
+ "NavigationCurrentEntryChangeEvent" => &["from", "navigationType"],
+ "NavigateEvent" => &[
+ "navigationType",
+ "destination",
+ "canIntercept",
+ "userInitiated",
+ "hashChange",
+ "signal",
+ "formData",
+ "downloadRequest",
+ "info",
+ "sourceElement",
+ "hasUAVisualTransition",
+ ],
+ "CloseEvent" => &["wasClean", "code", "reason"],
+ "DragEvent" => &["dataTransfer"],
+ "ClipboardEvent" => &["clipboardData"],
+ "CapturedMouseEvent" => &["surfaceX", "surfaceY"],
+ "SubmitEvent" => &["submitter"],
+ "FormDataEvent" => &["formData"],
+ "InputEvent" => &[
+ "data",
+ "isComposing",
+ "inputType",
+ "dataTransfer",
+ "targetRanges",
+ ],
+ "PopStateEvent" => &["state", "hasUAVisualTransition"],
+ "PageTransitionEvent" => &["persisted"],
+ "CommandEvent" => &["command", "source"],
+ "ToggleEvent" => &["oldState", "newState", "source"],
+ "TrackEvent" => &["track"],
+ "InterestEvent" => &["source"],
+ "StorageEvent" => &["key", "oldValue", "newValue", "url", "storageArea"],
+ "SecurityPolicyViolationEvent" => &[
+ "documentURI",
+ "referrer",
+ "blockedURI",
+ "violatedDirective",
+ "effectiveDirective",
+ "originalPolicy",
+ "disposition",
+ "sourceFile",
+ "sample",
+ "statusCode",
+ "lineNumber",
+ "columnNumber",
+ ],
+ "FontFaceSetLoadEvent" => &["fontfaces"],
+ "ProgressEvent" => &["lengthComputable", "loaded", "total"],
+ "HashChangeEvent" => &["oldURL", "newURL"],
+ "AnimationEvent" => &["animationName", "elapsedTime", "pseudoElement"],
+ "TransitionEvent" => &["propertyName", "elapsedTime", "pseudoElement"],
+ _ => &[],
+ };
+ properties.extend_from_slice(own);
+ properties
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
index e00c4b72b..8ddd2382b 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
@@ -33,7 +33,6 @@ use moli_webapi_declare::WebApiObject;
const NAVIGATION_DESTINATION_STATE_SLOT: &str = "__lmNavigationDestinationState";
const NAVIGATION_DESTINATION_ENTRY_SLOT: &str = "__lmNavigationDestinationEntry";
const NAVIGATION_DESTINATION_BACKING_SLOT: &str = "__moliNavigationDestinationBacking";
-const NAVIGATION_DESTINATION_WRAPPERS_SLOT: &str = "__moliNavigationDestinationWrappers";
const NAVIGATION_TRACKED_DESTINATIONS_SLOT: &str = "__lmNavigationTrackedDestinations";
const NAVIGATE_EVENT_SYNTHETIC_SLOT: &str = "__lmNavigateEventSynthetic";
const NAVIGATE_EVENT_INTERCEPTED_SLOT: &str = "__lmNavigateEventIntercepted";
@@ -1233,12 +1232,11 @@ pub(super) fn dispatch_navigation_traverse_event_with_outcome<'s>(
let Some(entries) = history_entries(scope, history) else {
return NavigationDispatchOutcome::proceed();
};
- let Some(entry) = entries
- .get_index(scope, target_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
+ let Some(entry) = entries.get(target_index as usize) else {
return NavigationDispatchOutcome::proceed();
};
+ let owner = runtime_window_owner(scope, navigation);
+ let entry = super::history_runtime::native::entry_wrapper(scope, owner, entry.clone());
let destination = create_navigation_destination_for_entry(scope, navigation, entry);
let target_href = destination
.get(scope, v8str(scope, "url").into())
@@ -1369,23 +1367,8 @@ pub(super) fn navigation_destination_for_realm<'s>(
let destination =
crate::util::get_private_object(scope, destination, NAVIGATION_DESTINATION_BACKING_SLOT)
.unwrap_or(destination);
- let global = scope.get_current_context().global(scope);
- let wrappers = get_private_value(scope, destination, NAVIGATION_DESTINATION_WRAPPERS_SLOT)
- .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
- .unwrap_or_else(|| {
- let map = v8::Map::new(scope);
- set_private_value(
- scope,
- destination,
- NAVIGATION_DESTINATION_WRAPPERS_SLOT,
- map.into(),
- );
- map
- });
- if let Some(wrapper) = wrappers
- .get(scope, global.into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- {
+ let context = scope.get_current_context();
+ if let Some(wrapper) = super::world_wrappers::get(scope, destination, context) {
return Some(wrapper);
}
let wrapper = create_navigation_destination(scope, "", false, -1, None);
@@ -1410,7 +1393,7 @@ pub(super) fn navigation_destination_for_realm<'s>(
)
.ok()?;
}
- let _ = wrappers.set(scope, global.into(), wrapper.into());
+ super::world_wrappers::insert(scope, destination, wrapper);
Some(wrapper)
}
@@ -1506,18 +1489,18 @@ fn navigation_destination_live_index<'s>(
let Some(entries) = history_entries(scope, history) else {
return -1;
};
- for index in 0..entries.length() {
- let Some(entry) = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- continue;
- };
- if entry.strict_equals(destination_entry.into()) {
- return navigation_entry_visible_index(scope, entry).unwrap_or(index as i32);
- }
- }
- -1
+ let Some(entry) = super::history_runtime::native::entry(scope, destination_entry) else {
+ return -1;
+ };
+ let owner = runtime_window_owner(scope, history);
+ let current_entry = super::navigation_entry::navigation_current_entry(scope, owner);
+ super::navigation_projection::visible_navigation_index_for_entry(
+ scope,
+ &entries,
+ current_entry,
+ &entry,
+ )
+ .map_or(-1, |index| index as i32)
}
fn navigation_entry_visible_index<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_history_pruning.rs b/moli-renderer-v8/src/context_bootstrap/navigation_history_pruning.rs
index 1ce7808d4..dd57fc50c 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_history_pruning.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_history_pruning.rs
@@ -1,9 +1,11 @@
+use super::history_runtime::native;
use super::navigation_entry::{
history_entries, history_index, navigation_current_entry, navigation_entry_key_value,
- set_history_entries, set_history_index, set_navigation_entry_initial_index,
+ set_history_entries, set_history_index,
};
use super::navigation_events::dispatch_navigation_entry_dispose;
use super::navigation_window::window_history_for_holder;
+use moli_history::HistoryEntryRef;
#[derive(Debug)]
pub(crate) struct NavigationHistoryPrunePlan {
@@ -15,17 +17,14 @@ pub(crate) fn plan_navigation_history_prune(
scope: &mut v8::PinScope<'_, '_>,
) -> Option<NavigationHistoryPrunePlan> {
let (_history, entries, current_index, current_entry) = navigation_history_prune_state(scope)?;
- let retained_entry_key = navigation_entry_key_value(scope, current_entry)?;
- let mut removed_entry_keys = Vec::with_capacity(entries.length().saturating_sub(1) as usize);
- for index in (0..entries.length()).rev() {
- if index == current_index {
- continue;
- }
- let entry = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- removed_entry_keys.push(navigation_entry_key_value(scope, entry)?);
- }
+ let retained_entry_key = current_entry.borrow().key.as_str().to_owned();
+ let removed_entry_keys = entries
+ .iter()
+ .enumerate()
+ .rev()
+ .filter(|(index, _)| *index != current_index as usize)
+ .map(|(_, entry)| entry.borrow().key.as_str().to_owned())
+ .collect();
Some(NavigationHistoryPrunePlan {
retained_entry_key,
removed_entry_keys,
@@ -49,20 +48,12 @@ pub(crate) fn apply_navigation_history_prune_plan(
return false;
};
- let mut retained_entries = Vec::with_capacity(entries.length() as usize);
+ let mut retained_entries = Vec::with_capacity(entries.len());
let mut removed_entries = Vec::with_capacity(plan.removed_entry_keys.len());
- for index in 0..entries.length() {
- let Some(entry) = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return false;
- };
- let Some(key) = navigation_entry_key_value(scope, entry) else {
- return false;
- };
+ for entry in entries {
+ let key = entry.borrow().key.as_str().to_owned();
if plan.removed_entry_keys.contains(&key) {
- removed_entries.push((key, entry));
+ removed_entries.push((key, native::entry_wrapper(scope, owner, entry)));
} else {
retained_entries.push((key, entry));
}
@@ -79,12 +70,15 @@ pub(crate) fn apply_navigation_history_prune_plan(
else {
return false;
};
- let retained_entries_array = v8::Array::new(scope, retained_entries.len() as i32);
- for (index, (_, entry)) in retained_entries.into_iter().enumerate() {
- set_navigation_entry_initial_index(scope, entry, index as u32);
- let _ = retained_entries_array.set_index(scope, index as u32, entry.into());
- }
- set_history_entries(scope, history, retained_entries_array);
+ let retained_entries = retained_entries
+ .into_iter()
+ .enumerate()
+ .map(|(index, (_, entry))| {
+ entry.borrow_mut().index = index as u32;
+ entry
+ })
+ .collect();
+ set_history_entries(scope, history, retained_entries);
set_history_index(scope, history, current_index as u32);
super::navigation_serialize::sync_child_navigation_entry_seed_from_owner(scope, owner);
for removed_key in &plan.removed_entry_keys {
@@ -104,16 +98,14 @@ fn navigation_history_prune_state<'s>(
scope: &mut v8::PinScope<'s, '_>,
) -> Option<(
v8::Local<'s, v8::Object>,
- v8::Local<'s, v8::Array>,
+ Vec<HistoryEntryRef>,
u32,
- v8::Local<'s, v8::Object>,
+ HistoryEntryRef,
)> {
let owner = scope.get_current_context().global(scope);
let history = window_history_for_holder(scope, owner)?;
let entries = history_entries(scope, history)?;
let current_index = history_index(scope, history);
- let current_entry = entries
- .get_index(scope, current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
+ let current_entry = entries.get(current_index as usize)?.clone();
Some((history, entries, current_index, current_entry))
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
index ad18a7504..5e3be4df1 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
@@ -14,7 +14,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
return;
};
let previous_entry = navigation_current_entry(scope, owner);
- let entries = history_entries(scope, history).unwrap_or_else(|| v8::Array::new(scope, 0));
+ let entries = history_entries(scope, history).unwrap_or_default();
let current_index = history_index(scope, history);
let current_navigation_index = navigation_current_entry_index(scope, owner).unwrap_or(0);
@@ -26,8 +26,6 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
scope,
resolved.as_str(),
None,
- None,
- None,
next_navigation_index,
&new_navigation_entry_id(),
&new_navigation_entry_key(),
@@ -62,8 +60,6 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
scope,
resolved.as_str(),
None,
- None,
- None,
current_navigation_index,
&new_navigation_entry_id(),
&key,
@@ -94,10 +90,12 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
);
}
LocationNavigationKind::Reload => {
- if let Some(entry) = entries
- .get_index(scope, current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- {
+ if let Some(record) = entries.get(current_index as usize) {
+ let entry = super::super::history_runtime::native::entry_wrapper(
+ scope,
+ owner,
+ record.clone(),
+ );
let current_entry = previous_entry.unwrap_or(entry);
if previous_entry.is_none() {
sync_navigation_current_entry_from_history_entry(scope, owner, entry);
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs
index ebe7eefbf..31cee1179 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/same_document.rs
@@ -29,8 +29,6 @@ pub(in crate::context_bootstrap) fn update_navigation_current_entry_for_same_doc
scope,
href,
None,
- None,
- None,
next_navigation_index,
&new_navigation_entry_id(),
&new_navigation_entry_key(),
@@ -53,8 +51,6 @@ pub(in crate::context_bootstrap) fn update_navigation_current_entry_for_same_doc
scope,
href,
None,
- None,
- None,
current_navigation_index,
&new_navigation_entry_id(),
&key,
@@ -113,8 +109,6 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(
scope,
href,
None,
- None,
- None,
next_navigation_index,
&new_navigation_entry_id(),
&new_navigation_entry_key(),
@@ -151,8 +145,6 @@ pub(in crate::context_bootstrap) fn apply_navigation_navigate_same_document<'s>(
scope,
href,
None,
- None,
- None,
current_navigation_index,
&new_navigation_entry_id(),
&key,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs b/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
index e9b3b2f5b..8ad181a81 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
@@ -1,24 +1,34 @@
-use super::navigation_entry::{
- navigation_entry_initial_index, navigation_entry_key_value, navigation_entry_url_value,
-};
+use super::history_runtime::native;
use super::navigation_window::{
child_browsing_context_handle_for_runtime_owner, runtime_window_is_global,
runtime_window_owner, runtime_window_uses_top_level_history_model,
};
use crate::util::{context_host_ptr_from_global_bridge, serialize_v8_iter_array};
+use moli_history::HistoryEntryRef;
+use std::rc::Rc;
pub(super) fn build_visible_navigation_entries_array<'s>(
scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
+ owner: v8::Local<'s, v8::Object>,
+ entries: &[HistoryEntryRef],
current_entry: Option<v8::Local<'s, v8::Object>>,
+ context: v8::Local<'s, v8::Context>,
) -> v8::Local<'s, v8::Array> {
let visible_entries = visible_navigation_entries(scope, entries, current_entry);
- serialize_v8_iter_array(scope, visible_entries).unwrap_or_else(|| v8::Array::new(scope, 0))
+ let wrappers: Vec<_> = visible_entries
+ .into_iter()
+ .map(|entry| {
+ let wrapper = native::entry_wrapper(scope, owner, entry);
+ native::entry_in_realm(scope, wrapper, context)
+ })
+ .collect();
+ let scope = &mut v8::ContextScope::new(scope, context);
+ serialize_v8_iter_array(scope, wrappers).unwrap_or_else(|| v8::Array::new(scope, 0))
}
pub(super) fn visible_navigation_entries_len<'s>(
scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
+ entries: &[HistoryEntryRef],
current_entry: Option<v8::Local<'s, v8::Object>>,
) -> u32 {
visible_navigation_entries(scope, entries, current_entry).len() as u32
@@ -26,170 +36,100 @@ pub(super) fn visible_navigation_entries_len<'s>(
pub(super) fn visible_navigation_index_for_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
+ entries: &[HistoryEntryRef],
current_entry: Option<v8::Local<'s, v8::Object>>,
- target_entry: v8::Local<'s, v8::Object>,
+ target_entry: &HistoryEntryRef,
) -> Option<u32> {
visible_navigation_entries(scope, entries, current_entry)
- .into_iter()
- .position(|entry| super::history_runtime::native::same_entry(scope, entry, target_entry))
+ .iter()
+ .position(|entry| Rc::ptr_eq(entry, target_entry))
.map(|index| index as u32)
}
fn visible_navigation_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
+ entries: &[HistoryEntryRef],
current_entry: Option<v8::Local<'s, v8::Object>>,
-) -> Vec<v8::Local<'s, v8::Object>> {
- let Some(current_entry) = current_entry else {
- return all_entries(scope, entries);
+) -> Vec<HistoryEntryRef> {
+ let Some(current_wrapper) = current_entry else {
+ return entries.to_vec();
};
- let Some(current_index) = raw_index_for_entry(scope, entries, current_entry) else {
- return all_entries(scope, entries);
+ let Some(current_entry) = native::entry(scope, current_wrapper) else {
+ return entries.to_vec();
};
- if navigation_entry_url_value(scope, current_entry)
- .and_then(|url| url::Url::parse(&url).ok())
- .is_none()
- {
+ let Some(current_index) = raw_index_for_entry(entries, &current_entry) else {
+ return entries.to_vec();
+ };
+ if url::Url::parse(&current_entry.borrow().url).is_err() {
return vec![current_entry];
}
- let owner = runtime_window_owner(scope, current_entry);
-
+ let owner = runtime_window_owner(scope, current_wrapper);
+ let top_level = runtime_window_uses_top_level_history_model(scope, owner);
+ let current_url = entry_origin_url(scope, owner, &current_entry.borrow().url);
+ let hidden = |entry: &HistoryEntryRef| {
+ top_level
+ && !Rc::ptr_eq(entry, &current_entry)
+ && entry.borrow().url.split('#').next() == Some("about:blank")
+ };
+ let same_origin = |scope: &mut v8::PinScope<'s, '_>, entry: &HistoryEntryRef| {
+ let candidate_url = entry_origin_url(scope, owner, &entry.borrow().url);
+ match (&current_url, candidate_url) {
+ (Some(current), Some(candidate)) => moli_url::same_origin(current, &candidate),
+ _ => false,
+ }
+ };
let mut start = current_index;
while start > 0 {
- let Some(candidate) = entry_at(scope, entries, start - 1) else {
- break;
- };
- if entry_is_hidden_for_owner(scope, owner, current_entry, candidate) {
- start -= 1;
- continue;
- }
- if !entries_are_same_origin(scope, owner, current_entry, candidate) {
+ let candidate = &entries[start - 1];
+ if !hidden(candidate) && !same_origin(scope, candidate) {
break;
}
start -= 1;
}
-
let mut end = current_index;
- while end + 1 < entries.length() {
- let Some(candidate) = entry_at(scope, entries, end + 1) else {
- break;
- };
- if entry_is_hidden_for_owner(scope, owner, current_entry, candidate) {
- end += 1;
- continue;
- }
- if !entries_are_same_origin(scope, owner, current_entry, candidate) {
+ while end + 1 < entries.len() {
+ let candidate = &entries[end + 1];
+ if !hidden(candidate) && !same_origin(scope, candidate) {
break;
}
end += 1;
}
-
- let mut visible = Vec::new();
- for raw_index in start..=end {
- let entry = if raw_index == current_index {
- Some(current_entry)
+ let mut visible: Vec<HistoryEntryRef> = Vec::new();
+ for (offset, entry) in entries[start..=end].iter().enumerate() {
+ let entry = if start + offset == current_index {
+ &current_entry
} else {
- entry_at(scope, entries, raw_index)
+ entry
};
- if let Some(entry) = entry {
- if entry_is_hidden_for_owner(scope, owner, current_entry, entry) {
- continue;
- }
- push_visible_entry(scope, &mut visible, entry);
+ if hidden(entry) {
+ continue;
+ }
+ let index = entry.borrow().index;
+ if let Some(position) = visible
+ .iter()
+ .position(|candidate| candidate.borrow().index == index)
+ {
+ visible[position] = entry.clone();
+ } else {
+ visible.push(entry.clone());
}
}
visible
}
-fn entry_is_hidden_for_owner<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- owner: v8::Local<'s, v8::Object>,
- current_entry: v8::Local<'s, v8::Object>,
- entry: v8::Local<'s, v8::Object>,
-) -> bool {
- if !runtime_window_uses_top_level_history_model(scope, owner) {
- return false;
- }
- if !runtime_window_owner(scope, entry).strict_equals(owner.into()) {
- return true;
- }
- !super::history_runtime::native::same_entry(scope, entry, current_entry)
- && navigation_entry_url_value(scope, entry)
- .is_some_and(|url| url.split('#').next() == Some("about:blank"))
-}
-
-fn push_visible_entry<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- visible: &mut Vec<v8::Local<'s, v8::Object>>,
- entry: v8::Local<'s, v8::Object>,
-) {
- let Some(index) = navigation_entry_initial_index(scope, entry) else {
- visible.push(entry);
- return;
- };
- if let Some(position) = visible.iter().position(|candidate| {
- navigation_entry_initial_index(scope, *candidate)
- .is_some_and(|candidate| candidate == index)
- }) {
- visible[position] = entry;
- } else {
- visible.push(entry);
- }
-}
-
-fn all_entries<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
-) -> Vec<v8::Local<'s, v8::Object>> {
- (0..entries.length())
- .filter_map(|index| entry_at(scope, entries, index))
- .collect()
-}
-
-fn raw_index_for_entry<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
- target_entry: v8::Local<'s, v8::Object>,
-) -> Option<u32> {
- if let Some(index) = (0..entries.length()).find(|index| {
- entry_at(scope, entries, *index)
- .is_some_and(|entry| entry.strict_equals(target_entry.into()))
- }) {
- return Some(index);
- }
- let target_key = navigation_entry_key_value(scope, target_entry)?;
- (0..entries.length()).find(|index| {
- entry_at(scope, entries, *index).is_some_and(|entry| {
- navigation_entry_key_value(scope, entry).as_deref() == Some(target_key.as_str())
- })
- })
-}
-
-fn entry_at<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- entries: v8::Local<'s, v8::Array>,
- index: u32,
-) -> Option<v8::Local<'s, v8::Object>> {
+fn raw_index_for_entry(
+ entries: &[HistoryEntryRef],
+ target_entry: &HistoryEntryRef,
+) -> Option<usize> {
entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
-}
-
-fn entries_are_same_origin<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- owner: v8::Local<'s, v8::Object>,
- current_entry: v8::Local<'s, v8::Object>,
- candidate: v8::Local<'s, v8::Object>,
-) -> bool {
- let current_url = navigation_entry_url_value(scope, current_entry)
- .and_then(|url| entry_origin_url(scope, owner, &url));
- let candidate_url = navigation_entry_url_value(scope, candidate)
- .and_then(|url| entry_origin_url(scope, owner, &url));
- match (current_url, candidate_url) {
- (Some(current), Some(candidate)) => moli_url::same_origin(&current, &candidate),
- _ => false,
- }
+ .iter()
+ .position(|entry| Rc::ptr_eq(entry, target_entry))
+ .or_else(|| {
+ let target = target_entry.borrow();
+ entries
+ .iter()
+ .position(|entry| entry.borrow().key == target.key)
+ })
}
fn entry_origin_url<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
index 6f91e67ea..9a10795a5 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
@@ -1,17 +1,17 @@
+use super::history_runtime::native;
use super::navigation_activation::{
- bind_navigation_entry_runtime_owner, install_navigation_activation_runtime_state,
- set_navigation_current_entry,
+ install_navigation_activation_runtime_state, set_navigation_current_entry,
};
use super::navigation_entry::{
- cache_current_history_state, create_navigation_entry, set_history_entries, set_history_index,
- set_navigation_entry_document_id,
+ cache_current_history_state, set_history_entries, set_history_index,
};
use super::navigation_entry_state::clone_history_entry_state;
use super::navigation_result::clear_active_cross_document_navigation_if_matches;
+use super::navigation_seed::{
+ build_current_navigation_entry_from_seed, build_history_entries_from_seed,
+};
use super::navigation_window::{window_history_for_holder, window_navigation_for_holder};
use crate::native_bridge::NavigationHistoryEntrySeed;
-use moli_page_types::NavigationHistoryEntryId;
-use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
pub(crate) fn install_navigation_bootstrap_entry(
scope: &mut v8::PinScope<'_, '_>,
@@ -62,57 +62,23 @@ pub(crate) fn install_navigation_entry_view_for_holder<'s>(
let Some(navigation) = window_navigation_for_holder(scope, owner) else {
return;
};
- let entries = v8::Array::new(scope, entry_seed.entries.len() as i32);
- let mut current_entry = None;
- let mut current_state: Option<v8::Local<'_, v8::Value>> = None;
- for snapshot in &entry_seed.entries {
- let entry = create_navigation_entry(
- scope,
- &snapshot.url,
- snapshot.history_state_json.as_deref(),
- snapshot.navigation_state_json.as_deref(),
- snapshot.referrer_policy.as_deref(),
- snapshot.index,
- &snapshot.id,
- &snapshot.key,
- );
- set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());
- super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);
- 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 {
- current_entry = Some(entry);
- current_state = Some(
- clone_history_entry_state(scope, entry).unwrap_or_else(|| v8::null(scope).into()),
- );
- }
- }
- let current_entry = current_entry.unwrap_or_else(|| {
- current_state = Some(v8::null(scope).into());
- let entry_id = NavigationHistoryEntryId::allocate();
- let entry_key = NavigationHistoryEntryKey::allocate();
- let entry = create_navigation_entry(
- scope,
- "about:blank",
- None,
- None,
- None,
- 0,
- entry_id.as_str(),
- entry_key.as_str(),
- );
- let document_id = NavigationHistoryDocumentId::allocate();
- set_navigation_entry_document_id(scope, entry, document_id.as_str());
- bind_navigation_entry_runtime_owner(scope, entry, owner);
- entry
- });
+ let entries = build_history_entries_from_seed(entry_seed);
+ let current_entry = entries
+ .get(entry_seed.current_index as usize)
+ .map(|entry| native::entry_wrapper(scope, owner, entry.clone()))
+ .unwrap_or_else(|| {
+ build_current_navigation_entry_from_seed(
+ scope,
+ owner,
+ entry_seed,
+ v8::null(scope).into(),
+ )
+ });
+ let current_state =
+ clone_history_entry_state(scope, current_entry).unwrap_or_else(|| v8::null(scope).into());
set_history_entries(scope, history, entries);
set_history_index(scope, history, entry_seed.current_index);
- cache_current_history_state(
- scope,
- history,
- current_state.unwrap_or_else(|| v8::null(scope).into()),
- );
+ cache_current_history_state(scope, history, current_state);
set_navigation_current_entry(scope, navigation, current_entry);
if let Some(snapshot) = entry_seed
.entries
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
index 416a99674..bdc84fc05 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
@@ -1,16 +1,15 @@
+use super::history_runtime::native;
use super::location_runtime::is_same_document_fragment_navigation;
-use super::navigation_activation::bind_navigation_entry_runtime_owner;
-use super::navigation_entry::{
- create_navigation_entry, history_index, set_navigation_entry_document_id,
-};
-use super::navigation_entry_state::{set_history_entry_state, set_navigation_entry_state};
+use super::navigation_entry::{history_index, navigation_entry_public_token};
use super::navigation_serialize::{
apply_current_document_referrer_policy_to_entry_snapshots, serialize_history_entries,
};
use super::navigation_window::{
runtime_window_uses_top_level_history_model, window_history_for_holder,
};
-use crate::native_bridge::NavigationHistoryEntrySeed;
+use crate::native_bridge::{NavigationHistoryEntrySeed, NavigationHistorySerializedEntry};
+use crate::structured_clone::serialize_history_state;
+use moli_history::{HistoryEntry, HistoryEntryRef, ScrollRestoration};
use moli_page_types::{
NavigationHistoryEntryId,
initial_navigation_history_seed as page_initial_navigation_history_seed,
@@ -29,29 +28,36 @@ pub(super) fn initial_navigation_history_seed<'s>(
)
}
-pub(super) fn build_history_entries_array_from_seed<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- owner: v8::Local<'s, v8::Object>,
- seed: &NavigationHistoryEntrySeed,
-) -> v8::Local<'s, v8::Array> {
- let entries = v8::Array::new(scope, seed.entries.len() as i32);
- for snapshot in &seed.entries {
- let entry = create_navigation_entry(
- scope,
- &snapshot.url,
- snapshot.history_state_json.as_deref(),
- snapshot.navigation_state_json.as_deref(),
- snapshot.referrer_policy.as_deref(),
- snapshot.index,
- &snapshot.id,
+/// Restore the complete native record before exposing any JS wrapper.
+pub(super) fn history_entry_from_snapshot(
+ snapshot: &NavigationHistorySerializedEntry,
+) -> HistoryEntryRef {
+ HistoryEntry {
+ url: snapshot.url.clone(),
+ referrer_policy: snapshot.referrer_policy.clone(),
+ history_state: snapshot.history_state.clone(),
+ navigation_state: snapshot.navigation_state.clone(),
+ id: navigation_entry_public_token(&snapshot.id),
+ key: NavigationHistoryEntryKey::from_serialized(navigation_entry_public_token(
&snapshot.key,
- );
- set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());
- super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);
- bind_navigation_entry_runtime_owner(scope, entry, owner);
- let _ = entries.set_index(scope, snapshot.history_index, entry.into());
+ )),
+ document: snapshot.document_id.clone(),
+ index: snapshot.index,
+ scroll_restoration: snapshot.scroll_restoration,
+ scroll_offset: None,
}
- entries
+ .into_ref()
+}
+
+pub(super) fn build_history_entries_from_seed(
+ seed: &NavigationHistoryEntrySeed,
+) -> Vec<HistoryEntryRef> {
+ let mut snapshots: Vec<_> = seed.entries.iter().collect();
+ snapshots.sort_by_key(|snapshot| snapshot.history_index);
+ snapshots
+ .into_iter()
+ .map(history_entry_from_snapshot)
+ .collect()
}
pub(super) fn build_current_navigation_entry_from_seed<'s>(
@@ -60,44 +66,30 @@ pub(super) fn build_current_navigation_entry_from_seed<'s>(
seed: &NavigationHistoryEntrySeed,
fallback_state: v8::Local<'s, v8::Value>,
) -> v8::Local<'s, v8::Object> {
- let Some(snapshot) = seed
+ let entry = seed
.entries
.iter()
.find(|entry| entry.history_index == seed.current_index)
- else {
- let entry_id = NavigationHistoryEntryId::allocate();
- let entry_key = NavigationHistoryEntryKey::allocate();
- let entry = create_navigation_entry(
- scope,
- "about:blank",
- None,
- None,
- None,
- 0,
- entry_id.as_str(),
- entry_key.as_str(),
- );
- set_history_entry_state(scope, entry, fallback_state);
- set_navigation_entry_state(scope, entry, fallback_state);
- let document_id = NavigationHistoryDocumentId::allocate();
- set_navigation_entry_document_id(scope, entry, document_id.as_str());
- bind_navigation_entry_runtime_owner(scope, entry, owner);
- return entry;
- };
- let entry = create_navigation_entry(
- scope,
- &snapshot.url,
- snapshot.history_state_json.as_deref(),
- snapshot.navigation_state_json.as_deref(),
- snapshot.referrer_policy.as_deref(),
- snapshot.index,
- &snapshot.id,
- &snapshot.key,
- );
- set_navigation_entry_document_id(scope, entry, snapshot.document_id.as_str());
- super::navigation_entry_state::restore_serialized_entry_state(scope, entry, snapshot);
- bind_navigation_entry_runtime_owner(scope, entry, owner);
- entry
+ .map(history_entry_from_snapshot)
+ .unwrap_or_else(|| {
+ let state = serialize_history_state(scope, fallback_state);
+ HistoryEntry {
+ url: "about:blank".to_owned(),
+ referrer_policy: None,
+ history_state: state.clone(),
+ navigation_state: state,
+ id: navigation_entry_public_token(NavigationHistoryEntryId::allocate().as_str()),
+ key: NavigationHistoryEntryKey::from_serialized(navigation_entry_public_token(
+ NavigationHistoryEntryKey::allocate().as_str(),
+ )),
+ document: NavigationHistoryDocumentId::allocate(),
+ index: 0,
+ scroll_restoration: ScrollRestoration::Auto,
+ scroll_offset: None,
+ }
+ .into_ref()
+ });
+ native::entry_wrapper(scope, owner, entry)
}
pub(super) fn history_entry_seed_for_reload<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
index c843f1f37..0c42ce305 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_serialize.rs
@@ -101,8 +101,6 @@ pub(super) fn serialize_navigation_entry_object<'s>(
url: "about:blank".to_owned(),
history_state: None,
navigation_state: None,
- history_state_json: None,
- navigation_state_json: None,
scroll_restoration: Default::default(),
referrer_policy: None,
document_id: NavigationHistoryDocumentId::allocate(),
@@ -130,10 +128,6 @@ fn snapshot_native_entry(
url: entry.url.clone(),
history_state: entry.history_state.clone(),
navigation_state: entry.navigation_state.clone(),
- // JSON is accepted only for legacy/bootstrap seeds. Capturing a native
- // snapshot never deserializes state or invokes script's toJSON hooks.
- history_state_json: None,
- navigation_state_json: None,
scroll_restoration: entry.scroll_restoration,
referrer_policy: entry.referrer_policy.clone(),
document_id: entry.document.clone(),
@@ -170,32 +164,6 @@ fn serialize_navigation_activation_seed<'s>(
})
}
-pub(super) fn parse_history_entry_state<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- state_json: Option<&str>,
-) -> v8::Local<'s, v8::Value> {
- if let Some(state_json) = state_json {
- v8_string(scope, state_json)
- .and_then(|json| v8::json::parse(scope, json))
- .unwrap_or_else(|| v8::null(scope).into())
- } else {
- v8::null(scope).into()
- }
-}
-
-pub(super) fn parse_navigation_entry_state<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- state_json: Option<&str>,
-) -> v8::Local<'s, v8::Value> {
- if let Some(state_json) = state_json {
- v8_string(scope, state_json)
- .and_then(|json| v8::json::parse(scope, json))
- .unwrap_or_else(|| v8::undefined(scope).into())
- } else {
- v8::undefined(scope).into()
- }
-}
-
pub(super) fn serialize_history_entries<'s>(
scope: &mut v8::PinScope<'s, '_>,
history: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs
index d0bd8773c..d50675f29 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs
@@ -9,7 +9,7 @@ use super::navigation_callbacks::{
};
use super::navigation_events::navigation_error_event_active;
use super::navigation_seed::{
- build_current_navigation_entry_from_seed, build_history_entries_array_from_seed,
+ build_current_navigation_entry_from_seed, build_history_entries_from_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.rs
index 88de1a94e..7c7df668c 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs
@@ -53,14 +53,7 @@ pub(in crate::context_bootstrap) fn build_history_runtime_state<'s>(
anyhow::anyhow!("isolated History is missing its native Window history")
})?
} else {
- let entries = build_history_entries_array_from_seed(scope, window, initial_seed);
- let records = (0..entries.length())
- .filter_map(|index| {
- let entry = entries.get_index(scope, index)?;
- let entry = v8::Local::<v8::Object>::try_from(entry).ok()?;
- native::entry(scope, entry)
- })
- .collect();
+ let records = build_history_entries_from_seed(initial_seed);
std::rc::Rc::new(std::cell::RefCell::new(moli_history::WindowHistory::new(
records,
initial_seed.current_index,
@@ -86,9 +79,10 @@ pub(in crate::context_bootstrap) fn build_navigation_runtime_state<'s>(
.and_then(|history| {
let entries = history_entries(scope, history)?;
let index = history_index(scope, history);
+ let owner = history_window_owner(scope, window);
entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .get(index as usize)
+ .map(|entry| native::entry_wrapper(scope, owner, entry.clone()))
})
.unwrap_or_else(|| {
build_current_navigation_entry_from_seed(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs b/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs
index 5f18ffb80..7f805ae17 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs
@@ -1,10 +1,8 @@
-use super::history_runtime::native;
-use crate::util::{get_private_value, set_private_value, v8str};
+use super::{history_runtime::native, world_wrappers};
+use crate::util::v8str;
use crate::web_api_interfaces;
use moli_webapi_declare::WebApiObject;
-const WRAPPERS: &str = "__moliNavigationTransitionWrappers";
-
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::NavigationTransition, own_to_string_tag = "NavigationTransition", readonly_to_string_tag)]
struct TransitionView<'scope> {
@@ -25,18 +23,8 @@ pub(super) fn transition_in_realm<'s>(
transition: v8::Local<'s, v8::Object>,
context: v8::Local<'s, v8::Context>,
) -> Option<v8::Local<'s, v8::Object>> {
- let global = context.global(scope);
- let wrappers = get_private_value(scope, transition, WRAPPERS)
- .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
- .unwrap_or_else(|| {
- let map = v8::Map::new(scope);
- set_private_value(scope, transition, WRAPPERS, map.into());
- map
- });
- if let Some(wrapper) = wrappers
- .get(scope, global.into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- {
+ let transition = world_wrappers::owner(scope, transition);
+ if let Some(wrapper) = world_wrappers::get(scope, transition, context) {
return Some(wrapper);
}
let scope = &mut v8::ContextScope::new(scope, context);
@@ -64,7 +52,7 @@ pub(super) fn transition_in_realm<'s>(
}
.bind(scope)
.ok()?;
- let _ = wrappers.set(scope, global.into(), wrapper.into());
+ world_wrappers::insert(scope, transition, wrapper);
Some(wrapper)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
index 1a6ed3859..1f9abd047 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
@@ -193,17 +193,10 @@ pub(super) fn navigation_traverse_to_callback<'s>(
rv.set(v8::undefined(scope).into());
return;
};
- let target_index = (0..entries.length()).find(|index| {
- entries
- .get_index(scope, *index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| {
- get_own_static_property(scope, entry, "key")
- .and_then(|value| value.to_string(scope))
- .map(|value| value.to_rust_string_lossy(scope))
- })
- .is_some_and(|key| key == target_key)
- });
+ let target_index = entries
+ .iter()
+ .position(|entry| entry.borrow().key.as_str() == target_key)
+ .map(|index| index as u32);
let Some(target_index) = target_index else {
rv.set(navigation_rejected_invalid_state_result(scope, "Invalid key").into());
return;
@@ -417,23 +410,6 @@ fn set_reload_current_entry_state<'s>(
return;
};
super::navigation_entry_state::set_navigation_entry_state(scope, current_entry, state);
- let Some(history) = window_history_for_holder(scope, owner) else {
- return;
- };
- let Some(entries) = history_entries(scope, history) else {
- return;
- };
- let current_index = history_index(scope, history);
- let Some(history_entry) = entries
- .get_index(scope, current_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- if history_entry.strict_equals(current_entry.into()) {
- return;
- }
- super::navigation_entry_state::set_navigation_entry_state(scope, history_entry, state);
}
fn navigation_traverse_result<'s>(
@@ -582,15 +558,16 @@ fn history_entry_navigation_index<'s>(
history: v8::Local<'s, v8::Object>,
history_index: u32,
) -> Option<u32> {
- history_entries(scope, history)?
- .get_index(scope, history_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| {
- get_own_static_property(scope, entry, "index")
- .and_then(|value| value.integer_value(scope))
- })
- .filter(|value| *value >= 0)
- .map(|value| value as u32)
+ let owner = runtime_window_owner(scope, history);
+ let entries = history_entries(scope, history)?;
+ let entry = entries.get(history_index as usize)?;
+ let current_entry = navigation_current_entry(scope, owner);
+ super::navigation_projection::visible_navigation_index_for_entry(
+ scope,
+ &entries,
+ current_entry,
+ entry,
+ )
}
pub(super) fn navigation_entries_len<'s>(
@@ -600,6 +577,6 @@ pub(super) fn navigation_entries_len<'s>(
let owner = runtime_window_owner(scope, history);
let current_entry = navigation_current_entry(scope, owner);
history_entries(scope, history)
- .map(|entries| visible_navigation_entries_len(scope, entries, current_entry))
+ .map(|entries| visible_navigation_entries_len(scope, &entries, current_entry))
.unwrap_or(0)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs
index 6804b582e..6f6a494c1 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs
@@ -54,11 +54,11 @@ fn entry_reference<'s>(
history: v8::Local<'s, v8::Object>,
index: u32,
) -> Option<SessionHistoryEntry> {
- let entry = history_entries(scope, history)?
- .get_index(scope, index)?
- .try_into()
- .ok()?;
- super::session_history::entry_reference(scope, entry)
+ let entries = history_entries(scope, history)?;
+ let entry = entries.get(index as usize)?;
+ Some(super::session_history::native_entry_reference(
+ &entry.borrow(),
+ ))
}
impl TraversalParticipantOutcome {
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
index 2bbc82f9d..b7ba975a0 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
@@ -1,5 +1,5 @@
use super::history_runtime::route_history_traversal_task;
-use super::navigation_entry::{history_entries, navigation_entry_key_value};
+use super::navigation_entry::history_entries;
use super::navigation_result::{
navigation_pending_result, navigation_rejected_dom_exception_result,
};
@@ -11,6 +11,7 @@ use super::navigation_window::{
use super::*;
use crate::document_runtime::DomHandle;
use crate::native_bridge::PendingHistoryTraversalAction;
+use moli_history::HistoryEntryRef;
pub(super) struct TraversalTarget<'s> {
pub(super) owner: v8::Local<'s, v8::Object>,
@@ -27,7 +28,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
) -> Option<v8::Local<'s, v8::Object>> {
target.joint_step = target.joint_step.or_else(|| {
traversal_target_entry(scope, &target)
- .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, entry))
+ .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, &entry))
});
let child_handle = child_browsing_context_handle_for_traversal(scope, target.owner);
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
@@ -72,7 +73,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
return Some(navigation_pending_result(scope));
};
let target_key = traversal_target_entry(scope, &target)
- .and_then(|entry| navigation_entry_key_value(scope, entry));
+ .map(|entry| entry.borrow().key.as_str().to_owned());
let receiver_context = target
.history
.get_creation_context(scope)
@@ -90,14 +91,14 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
return Some(result);
}
let target_entry = traversal_target_entry(scope, &target);
- if !traversal_target_entry_still_available(scope, &target, target_entry) {
+ if !traversal_target_entry_still_available(scope, &target, target_entry.as_ref()) {
return Some(navigation_rejected_dom_exception_result(
scope,
"Navigation was canceled",
"AbortError",
));
}
- let target_key = target_entry.and_then(|entry| navigation_entry_key_value(scope, entry));
+ let target_key = target_entry.map(|entry| entry.borrow().key.as_str().to_owned());
let receiver_context = target
.history
.get_creation_context(scope)
@@ -123,7 +124,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
) {
target.joint_step = target.joint_step.or_else(|| {
traversal_target_entry(scope, &target)
- .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, entry))
+ .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, &entry))
});
let child_handle = child_browsing_context_handle_for_traversal(scope, target.owner);
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
@@ -165,7 +166,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
}
if child_handle.is_some() {
let target_key = traversal_target_entry(scope, &target)
- .and_then(|entry| navigation_entry_key_value(scope, entry));
+ .map(|entry| entry.borrow().key.as_str().to_owned());
let receiver_context = target
.history
.get_creation_context(scope)
@@ -184,7 +185,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
return;
}
let target_entry = traversal_target_entry(scope, &target);
- if !traversal_target_entry_still_available(scope, &target, target_entry) {
+ if !traversal_target_entry_still_available(scope, &target, target_entry.as_ref()) {
return;
}
let receiver_context = target
@@ -192,8 +193,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
.get_creation_context(scope)
.unwrap_or_else(|| scope.get_current_context());
let receiver_scope = &mut v8::ContextScope::new(scope, receiver_context);
- let target_key =
- target_entry.and_then(|entry| navigation_entry_key_value(receiver_scope, entry));
+ let target_key = target_entry.map(|entry| entry.borrow().key.as_str().to_owned());
if let Some(producer) = host.queue_history_traversal(
receiver_scope,
exact_target,
@@ -208,24 +208,22 @@ pub(super) fn queue_history_traversal_without_result<'s>(
fn traversal_target_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
target: &TraversalTarget<'s>,
-) -> Option<v8::Local<'s, v8::Object>> {
+) -> Option<HistoryEntryRef> {
history_entries(scope, target.history)?
- .get_index(scope, target.target_index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .get(target.target_index as usize)
+ .cloned()
}
fn traversal_target_entry_still_available<'s>(
scope: &mut v8::PinScope<'s, '_>,
target: &TraversalTarget<'s>,
- expected_entry: Option<v8::Local<'s, v8::Object>>,
+ expected_entry: Option<&HistoryEntryRef>,
) -> bool {
let Some(expected_entry) = expected_entry else {
return true;
};
- history_entries(scope, target.history)
- .and_then(|entries| entries.get_index(scope, target.target_index))
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .is_some_and(|entry| entry.strict_equals(expected_entry.into()))
+ traversal_target_entry(scope, target)
+ .is_some_and(|entry| std::rc::Rc::ptr_eq(&entry, expected_entry))
}
pub(crate) fn apply_authorized_history_traversal_task(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
index d154ce2df..8a870a5c0 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
@@ -87,10 +87,13 @@ pub(super) fn navigation_delta_traversal_plan<'s>(
let entries = history_entries(scope, history)?;
let current_entry = navigation_current_entry(scope, owner);
let current_navigation_index = current_entry
- .and_then(|entry| visible_navigation_index_for_entry(scope, entries, Some(entry), entry))
+ .and_then(|entry| {
+ let record = super::history_runtime::native::entry(scope, entry)?;
+ visible_navigation_index_for_entry(scope, &entries, Some(entry), &record)
+ })
.or_else(|| navigation_current_entry_index(scope, owner))
.unwrap_or(0) as i64;
- let visible_len = visible_navigation_entries_len(scope, entries, current_entry) as i64;
+ let visible_len = visible_navigation_entries_len(scope, &entries, current_entry) as i64;
if delta < 0 && current_navigation_index <= 0 {
return Some(NavigationTraversalPlan::RejectInvalidState(
"Cannot go back",
@@ -102,7 +105,7 @@ pub(super) fn navigation_delta_traversal_plan<'s>(
));
}
let next_index = current_index + delta;
- if next_index < 0 || next_index >= entries.length() as i64 {
+ if next_index < 0 || next_index >= entries.len() as i64 {
let message = if delta < 0 {
"Cannot go back"
} else {
@@ -137,7 +140,7 @@ pub(super) fn navigation_index_traversal_plan<'s>(
}
let history = window_history_for_holder(scope, owner)?;
let entries = history_entries(scope, history)?;
- if target_index >= entries.length() {
+ if target_index as usize >= entries.len() {
return Some(NavigationTraversalPlan::RejectInvalidState("Invalid key"));
}
let pending_target_index = pending_history_traversal_target_index(scope, history);
diff --git a/moli-renderer-v8/src/context_bootstrap/platform_object_worlds.rs b/moli-renderer-v8/src/context_bootstrap/platform_object_worlds.rs
new file mode 100644
index 000000000..6e0c041ff
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/platform_object_worlds.rs
@@ -0,0 +1,54 @@
+//! Project platform objects, not arbitrary JavaScript values, into a world.
+
+use super::{
+ abort_signal, abort_signal_events, form_data_runtime, shared_event_targets, world_wrappers,
+};
+use crate::web_api_interfaces;
+
+pub(super) fn in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: v8::Local<'s, v8::Context>,
+) -> Option<v8::Local<'s, v8::Value>> {
+ let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {
+ return Some(value);
+ };
+ let object = world_wrappers::owner(scope, object);
+ if world_wrappers::belongs_to_world(scope, object, context) {
+ return Some(object.into());
+ }
+ if let Some(wrapper) = world_wrappers::get(scope, object, context) {
+ return Some(wrapper.into());
+ }
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let wrapper = if web_api_interfaces::AbortSignal::is_instance(scope, object) {
+ let wrapper = abort_signal::new_signal(scope)?;
+ if !crate::native_bridge::abort::bind_signal_wrapper(scope, object, wrapper) {
+ return None;
+ }
+ abort_signal_events::initialize(scope, wrapper);
+ shared_event_targets::bind_shared_target(scope, object, object);
+ shared_event_targets::bind_shared_target(scope, wrapper, object);
+ wrapper
+ } else if web_api_interfaces::FormData::is_instance(scope, object) {
+ form_data_runtime::new_world_wrapper(scope)?
+ } else if web_api_interfaces::Node::is_instance(scope, object) {
+ let (host_ptr, handle) =
+ crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, object)
+ .ok()?;
+ return unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)
+ .map(Into::into);
+ } else if web_api_interfaces::Blob::is_instance(scope, object) {
+ let wrapper = crate::blob::world_wrapper(scope, object)?;
+ if web_api_interfaces::File::is_instance(scope, object) {
+ super::file_api::bind_file_world_wrapper(scope, object, wrapper)?;
+ }
+ wrapper
+ } else {
+ return Some(value);
+ };
+ world_wrappers::insert(scope, object, wrapper);
+ Some(wrapper.into())
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/session_history.rs b/moli-renderer-v8/src/context_bootstrap/session_history.rs
index b080fc578..6cc8ac01a 100644
--- a/moli-renderer-v8/src/context_bootstrap/session_history.rs
+++ b/moli-renderer-v8/src/context_bootstrap/session_history.rs
@@ -1,17 +1,16 @@
use super::navigation_entry::{
- history_entries, history_index, navigation_entry_document_id, navigation_entry_key_value,
- set_history_entries, set_history_index,
+ history_entries, history_index, set_history_entries, set_history_index,
};
use super::navigation_window::{
runtime_top_window_owner, runtime_window_dispatch_scope, window_history_for_holder,
};
use crate::native_bridge::{JsContextHost, NavigationHistoryEntrySeed, OwnerDispatchScope};
use crate::util::context_host_ptr_from_global_bridge;
+use moli_history::{HistoryEntry, HistoryEntryRef};
use moli_page_types::SessionHistoryCommit;
use moli_session_history::{
- JointSessionHistory, NavigationHistoryDocumentId, NavigationHistoryEntryKey,
- SessionHistoryContextId, SessionHistoryEntry, SessionHistoryPosition, SessionHistoryStepId,
- SessionHistoryTraversalPlan,
+ JointSessionHistory, NavigationHistoryEntryKey, SessionHistoryContextId, SessionHistoryEntry,
+ SessionHistoryPosition, SessionHistoryStepId, SessionHistoryTraversalPlan,
};
#[derive(Clone, Copy)]
@@ -39,12 +38,15 @@ pub(super) fn entry_reference<'s>(
scope: &mut v8::PinScope<'s, '_>,
entry: v8::Local<'s, v8::Object>,
) -> Option<SessionHistoryEntry> {
- Some(SessionHistoryEntry {
- key: NavigationHistoryEntryKey::from_serialized(navigation_entry_key_value(scope, entry)?),
- document: NavigationHistoryDocumentId::from_serialized(navigation_entry_document_id(
- scope, entry,
- )?),
- })
+ let entry = super::history_runtime::native::entry(scope, entry)?;
+ Some(native_entry_reference(&entry.borrow()))
+}
+
+pub(super) fn native_entry_reference(entry: &HistoryEntry) -> SessionHistoryEntry {
+ SessionHistoryEntry {
+ key: entry.key.clone(),
+ document: entry.document.clone(),
+ }
}
pub(super) fn initialize<'s>(
@@ -157,9 +159,8 @@ pub(crate) fn install_session_history_position(
let entry = window_history_for_holder(scope, owner).and_then(|history| {
let index = history_index(scope, history);
history_entries(scope, history)?
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| entry_reference(scope, entry))
+ .get(index as usize)
+ .map(|entry| native_entry_reference(&entry.borrow()))
});
let history = unsafe { &mut *host_ptr }.session_histories.get_mut(None);
*history = JointSessionHistory::new(position);
@@ -176,10 +177,11 @@ pub(crate) fn initialize_main_session_history(scope: &mut v8::PinScope<'_, '_>)
return;
};
let index = history_index(scope, history);
- let entry = history_entries(scope, history)
- .and_then(|entries| entries.get_index(scope, index))
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| entry_reference(scope, entry));
+ let entry = history_entries(scope, history).and_then(|entries| {
+ entries
+ .get(index as usize)
+ .map(|entry| native_entry_reference(&entry.borrow()))
+ });
if let Some(entry) = entry
&& let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
{
@@ -314,9 +316,9 @@ pub(super) fn owner_for_context<'s>(
pub(super) fn step_for_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
- entry: v8::Local<'s, v8::Object>,
+ entry: &HistoryEntryRef,
) -> Option<SessionHistoryStepId> {
- let key = entry_reference(scope, entry)?.key;
+ let key = entry.borrow().key.clone();
let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? };
let binding = binding(scope, host, owner);
host.session_histories
@@ -357,35 +359,28 @@ pub(super) fn prune_views<'s>(
let old_current = history_index(scope, history);
let mut retained = Vec::new();
let mut current = 0;
- for index in 0..entries.length() {
- let Some(entry) = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- continue;
- };
- let keep = index <= old_current
- || entry_reference(scope, entry)
- .is_some_and(|entry| model.contains_entry(context, &entry.key));
+ let old_len = entries.len();
+ for (index, entry) in entries.into_iter().enumerate() {
+ let keep =
+ index <= old_current as usize || model.contains_entry(context, &entry.borrow().key);
if keep {
- if index == old_current {
+ if index == old_current as usize {
current = retained.len() as u32;
}
retained.push(entry);
} else {
- removed.push(entry);
+ // Keep observable wrappers alive until dispose delivery, before pruning the cache.
+ removed.push(super::history_runtime::native::entry_wrapper(
+ scope, owner, entry,
+ ));
}
}
- if retained.len() == entries.length() as usize {
+ if retained.len() == old_len {
continue;
}
- let array = v8::Array::new(scope, retained.len() as i32);
- for (index, entry) in retained.into_iter().enumerate() {
- let _ = array.set_index(scope, index as u32, entry.into());
- // Removing a suffix preserves Navigation's filtered indices. Raw
- // history includes hidden entries and cannot supply these indices.
- }
- set_history_entries(scope, history, array);
+ // Removing a suffix preserves Navigation's filtered indices. Raw
+ // history includes hidden entries and cannot supply these indices.
+ set_history_entries(scope, history, retained);
set_history_index(scope, history, current);
super::navigation_serialize::sync_child_navigation_entry_seed_from_owner(scope, owner);
}
@@ -450,13 +445,10 @@ pub(super) fn project_traversal<'s>(
};
let local_entries = history_entries(scope, history)?;
let current_index = history_index(scope, history);
- let index = (0..local_entries.length()).find(|index| {
- local_entries
- .get_index(scope, *index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| navigation_entry_key_value(scope, entry))
- .is_some_and(|key| key == entry.key.as_str())
- });
+ let index = local_entries
+ .iter()
+ .position(|candidate| candidate.borrow().key == entry.key)
+ .map(|index| index as u32);
let Some(target_index) = index else {
if context == SessionHistoryContextId::ROOT {
return None;
@@ -513,16 +505,12 @@ pub(super) fn publish<'s>(
let root_url = window_history_for_holder(scope, top)
.and_then(|history| history_entries(scope, history))
.and_then(|entries| {
- (0..entries.length()).find_map(|index| {
- let entry = entries
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let key = navigation_entry_key_value(scope, entry)?;
- if root_key.as_ref().is_some_and(|root| root.as_str() == key) {
- super::navigation_entry::navigation_entry_url_value(scope, entry)
- } else {
- None
- }
+ entries.iter().find_map(|entry| {
+ let entry = entry.borrow();
+ root_key
+ .as_ref()
+ .filter(|root| *root == &entry.key)
+ .map(|_| entry.url.clone())
})
})
.unwrap_or_else(|| host.document_url().as_str().to_owned());
diff --git a/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs b/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs
index b749179ba..5c17d3457 100644
--- a/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs
+++ b/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs
@@ -36,7 +36,9 @@ pub(super) fn bind_shared_target<'s>(
) {
let owner = shared_target_owner(scope, owner);
set_private_value(scope, wrapper, OWNER, owner.into());
- if native::entry(scope, wrapper).is_none() {
+ if native::entry(scope, wrapper).is_none()
+ && !crate::web_api_interfaces::AbortSignal::is_instance(scope, wrapper)
+ {
let context = wrapper
.get_creation_context(scope)
.expect("Navigation realm");
@@ -60,6 +62,11 @@ pub(super) fn target_in_realm<'s>(
let Some(owner) = get_private_object(scope, target, OWNER) else {
return target;
};
+ if crate::web_api_interfaces::AbortSignal::is_instance(scope, owner) {
+ return super::platform_object_worlds::in_realm(scope, owner.into(), context)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .unwrap_or(target);
+ }
if native::entry(scope, target).is_some() {
let window = super::navigation_window::runtime_window_owner(scope, owner);
let navigation = super::navigation_window::window_navigation_for_holder(scope, window);
diff --git a/moli-renderer-v8/src/context_bootstrap/world_wrappers.rs b/moli-renderer-v8/src/context_bootstrap/world_wrappers.rs
new file mode 100644
index 000000000..5bd335221
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/world_wrappers.rs
@@ -0,0 +1,118 @@
+//! Weak wrapper identities for platform objects exposed by Navigation events.
+//! A retained native object must not keep another world's realm alive merely
+//! because that world once observed it.
+
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use crate::native_bridge::identity::contexts_share_wrapper_world;
+use crate::util::{get_private_object, get_private_value, set_private_value};
+
+const ID: &str = "__moliWorldWrapperIdentity";
+const OWNER: &str = "__moliWorldWrapperOwner";
+type Store = Rc<RefCell<Wrappers>>;
+type WeakWrapper = (u64, Rc<v8::Weak<v8::Object>>);
+
+#[derive(Default)]
+struct Wrappers {
+ next_id: u64,
+ objects: HashMap<u64, Vec<WeakWrapper>>,
+}
+
+fn store(scope: &mut v8::PinScope<'_, '_>) -> Store {
+ if let Some(store) = scope.get_slot::<Store>() {
+ return store.clone();
+ }
+ let store = Store::default();
+ scope.set_slot(store.clone());
+ store
+}
+
+pub(super) fn owner<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+) -> v8::Local<'s, v8::Object> {
+ get_private_object(scope, object, OWNER).unwrap_or(object)
+}
+
+pub(super) fn belongs_to_world<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ context: v8::Local<'s, v8::Context>,
+) -> bool {
+ object
+ .get_creation_context(scope)
+ .is_some_and(|creation| contexts_share_wrapper_world(creation, context))
+}
+
+fn identity<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+) -> Option<u64> {
+ get_private_value(scope, object, ID)
+ .and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())
+ .map(|id| id.u64_value().0)
+}
+
+pub(super) fn get<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ context: v8::Local<'s, v8::Context>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let id = identity(scope, object)?;
+ // Do not hold a RefCell borrow across V8 operations/weak finalizers.
+ let candidates = store(scope).borrow().objects.get(&id)?.clone();
+ candidates.into_iter().find_map(|(_, candidate)| {
+ let wrapper = candidate.to_local(scope)?;
+ belongs_to_world(scope, wrapper, context).then_some(wrapper)
+ })
+}
+
+pub(super) fn insert<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ wrapper: v8::Local<'s, v8::Object>,
+) {
+ let store = store(scope);
+ let wrapper_id = {
+ let mut records = store.borrow_mut();
+ records.next_id = records
+ .next_id
+ .checked_add(1)
+ .expect("wrapper id exhausted");
+ records.next_id
+ };
+ let id = identity(scope, object).unwrap_or_else(|| {
+ set_private_value(
+ scope,
+ object,
+ ID,
+ v8::BigInt::new_from_u64(scope, wrapper_id).into(),
+ );
+ wrapper_id
+ });
+ if !object.strict_equals(wrapper.into()) {
+ set_private_value(scope, wrapper, OWNER, object.into());
+ }
+ let weak_store = Rc::downgrade(&store);
+ let weak = v8::Weak::with_finalizer(
+ scope,
+ wrapper,
+ Box::new(move |_| {
+ if let Some(store) = weak_store.upgrade() {
+ let mut records = store.borrow_mut();
+ if let Some(wrappers) = records.objects.get_mut(&id) {
+ wrappers.retain(|(candidate, _)| *candidate != wrapper_id);
+ if wrappers.is_empty() {
+ records.objects.remove(&id);
+ }
+ }
+ }
+ }),
+ );
+ store
+ .borrow_mut()
+ .objects
+ .entry(id)
+ .or_default()
+ .push((wrapper_id, Rc::new(weak)));
+}
diff --git a/moli-renderer-v8/src/native_bridge/abort.rs b/moli-renderer-v8/src/native_bridge/abort.rs
index d21b70786..df8ae4051 100644
--- a/moli-renderer-v8/src/native_bridge/abort.rs
+++ b/moli-renderer-v8/src/native_bridge/abort.rs
@@ -26,6 +26,18 @@ const ABORT_SIGNAL_ID_SLOT: &str = "__lmAbortSignalId";
const ABORT_CONTROLLER_ID_SLOT: &str = "__lmAbortControllerId";
const ABORT_CONTROLLER_SIGNAL_SLOT: &str = "__lmAbortControllerSignal";
+pub(crate) fn bind_signal_wrapper<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ signal: v8::Local<'s, v8::Object>,
+ wrapper: v8::Local<'s, v8::Object>,
+) -> bool {
+ let Some(id) = get_private_value(scope, signal, ABORT_SIGNAL_ID_SLOT) else {
+ return false;
+ };
+ set_private_value(scope, wrapper, ABORT_SIGNAL_ID_SLOT, id);
+ true
+}
+
#[derive(Default)]
pub(super) struct AbortStore {
next_signal_id: u32,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/history_seed.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/history_seed.rs
index 8ce7c8e0f..2f9845adc 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/history_seed.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/history_seed.rs
@@ -41,15 +41,13 @@ impl JsContextHost {
seed: &mut NavigationHistoryEntrySeed,
url: &Url,
) {
- apply_child_navigation_to_seed(seed, url, None, None);
+ apply_child_navigation_to_seed(seed, url);
}
pub(in crate::native_bridge::context_host) fn replace_child_browsing_context_navigation_in_entry_seed(
seed: &mut NavigationHistoryEntrySeed,
url: &Url,
- history_state_json: Option<String>,
- navigation_state_json: Option<String>,
) {
- replace_child_navigation_in_seed(seed, url, history_state_json, navigation_state_json);
+ replace_child_navigation_in_seed(seed, url);
}
}
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.rs
index d7f806a8a..4555cdb0e 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
@@ -743,11 +743,11 @@ impl ChildBrowsingContextEntry {
}
pub(super) fn apply_navigation_to_entry_seed(&mut self, url: &Url) {
- apply_child_navigation_to_seed(&mut self.navigation_entry_seed, url, None, None);
+ apply_child_navigation_to_seed(&mut self.navigation_entry_seed, url);
}
pub(super) fn replace_navigation_in_entry_seed(&mut self, url: &Url) {
- replace_child_navigation_in_seed(&mut self.navigation_entry_seed, url, None, None);
+ replace_child_navigation_in_seed(&mut self.navigation_entry_seed, url);
}
pub(super) fn apply_javascript_url_navigation_to_entry_seed(&mut self) {
@@ -798,8 +798,6 @@ impl ChildBrowsingContextEntry {
history_state: None,
navigation_state: None,
scroll_restoration: Default::default(),
- history_state_json: None,
- navigation_state_json: None,
referrer_policy: None,
document_id: NavigationHistoryDocumentId::allocate(),
history_index: 1,
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.rs
index 93df2f3f7..20745fa48 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
@@ -161,7 +161,7 @@ impl JsContextHost {
);
} else {
Self::replace_child_browsing_context_navigation_in_entry_seed(
- &mut seed, &url, None, None,
+ &mut seed, &url,
);
}
}
diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs
index b20dd47e5..95fe6daa5 100644
--- a/moli-renderer-v8/src/native_bridge/identity.rs
+++ b/moli-renderer-v8/src/native_bridge/identity.rs
@@ -428,6 +428,20 @@ struct BridgeContextWrapperCache {
#[derive(Debug)]
struct SharedDefaultWorldWrapperCache;
+pub(crate) fn contexts_share_wrapper_world(
+ left: v8::Local<'_, v8::Context>,
+ right: v8::Local<'_, v8::Context>,
+) -> bool {
+ left == right
+ || match (
+ left.get_slot::<RefCell<BridgeContextWrapperCache>>(),
+ right.get_slot::<RefCell<BridgeContextWrapperCache>>(),
+ ) {
+ (Some(left), Some(right)) => Rc::ptr_eq(&left, &right),
+ _ => false,
+ }
+}
+
#[derive(Debug)]
struct BridgeCachedWrapper {
wrapper: v8::Global<v8::Object>,
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
index 9bc5eab4f..289f840e5 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
@@ -1,5 +1,291 @@
use super::*;
+#[test]
+fn history_worlds_retained_page_event_does_not_retain_unobserved_foreign_views() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval("navigation.addEventListener('navigate', event => { globalThis.keptEvent = event; }, {once: true}); 'ready'")
+ .unwrap();
+ let isolated = vm
+ .create_isolated_world("collectible-views", false)
+ .unwrap();
+ vm.eval_in_isolated_context(isolated, "navigation.addEventListener('navigate', event => { globalThis.views = [event, event.destination, event.signal]; }, {once: true}); 'ready'")
+ .unwrap();
+ vm.eval("history.pushState({}, '', '#retained'); 'pushed'")
+ .unwrap();
+ let context_ptr = &vm
+ .page_isolated_world_contexts
+ .context(isolated)
+ .unwrap()
+ .context as *const _;
+ let views = vm
+ .with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ let global = scope.get_current_context().global(scope);
+ let value = global
+ .get(scope, crate::util::v8str(scope, "views").into())
+ .unwrap();
+ let array = v8::Local::<v8::Array>::try_from(value).unwrap();
+ Ok((0..array.length())
+ .map(|index| {
+ let value = array.get_index(scope, index).unwrap();
+ let object = v8::Local::<v8::Object>::try_from(value).unwrap();
+ v8::Weak::new(scope, object)
+ })
+ .collect::<Vec<_>>())
+ })
+ .unwrap();
+ vm.eval_in_isolated_context(isolated, "views = null; 'released'")
+ .unwrap();
+ vm.renderer_document_isolate
+ .with_entered_renderer_document_isolate(|isolate| {
+ isolate.low_memory_notification();
+ Ok(())
+ })
+ .unwrap();
+ vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ assert!(
+ views.iter().all(|view| view.to_local(scope).is_none()),
+ "a retained page event must not root its foreign Event, destination, or signal wrappers"
+ );
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(vm.eval("String(keptEvent.destination.url.endsWith('#retained') && keptEvent.signal instanceof AbortSignal)").unwrap(), "true");
+}
+
+#[test]
+fn history_worlds_navigate_signal_has_a_local_wrapper() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ navigation.addEventListener('navigate', event => {
+ event.signal.pageOnly = 'page';
+ event.signal.addEventListener = () => { throw new Error('page override'); };
+ }, {once: true});
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("signal-view", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ globalThis.facts = [];
+ navigation.addEventListener('navigate', event => {
+ facts.push(event instanceof NavigateEvent,
+ event.signal instanceof AbortSignal,
+ Object.getPrototypeOf(event.signal) === AbortSignal.prototype,
+ event.signal.pageOnly === undefined);
+ try { event.signal.addEventListener('abort', () => {}); facts.push(true); }
+ catch (_) { facts.push(false); }
+ }, {once: true});
+ history.pushState({}, '', '#signal');
+ JSON.stringify(facts)
+ "#
+ )
+ .unwrap(),
+ "[true,true,true,true,true]"
+ );
+}
+
+#[test]
+fn history_worlds_synthetic_events_keep_interface_identity_and_shared_dispatch() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.pageFacts = [];
+ globalThis.pageEvents = [];
+ for (const type of ['probe', 'navigate']) {
+ navigation.addEventListener(type, function (event) {
+ pageEvents.push(event);
+ pageFacts.push([event instanceof Event, event.expando === undefined,
+ event.target === navigation, event.currentTarget === navigation,
+ this === navigation, event instanceof CustomEvent,
+ event instanceof NavigateEvent, event.detail ?? null]);
+ event.preventDefault();
+ });
+ }
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("synthetic-views", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ const facts = [];
+ for (const original of [new CustomEvent('probe', {detail: 7, cancelable: true}),
+ new Event('navigate', {cancelable: true})]) {
+ original.expando = 'isolated';
+ navigation.addEventListener(original.type, event => {
+ facts.push(event === original, event.defaultPrevented,
+ event.target === navigation, event.composedPath()[0] === navigation);
+ }, {once: true});
+ facts.push(navigation.dispatchEvent(original), original.defaultPrevented,
+ original.currentTarget === null, original.composedPath().length === 0);
+ }
+ JSON.stringify(facts)
+ "#
+ )
+ .unwrap(),
+ "[true,true,true,true,false,true,true,true,true,true,true,true,false,true,true,true]"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify(pageFacts)").unwrap(),
+ "[[true,true,true,true,true,true,false,7],[true,true,true,true,true,false,false,null]]"
+ );
+ assert_eq!(vm.eval("String(pageEvents.every(event => event.defaultPrevented && event.currentTarget === null))").unwrap(), "true");
+}
+
+#[test]
+fn history_worlds_nested_platform_objects_share_state_without_sharing_wrappers() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(r#"
+ globalThis.destination = null;
+ navigation.addEventListener('navigate', event => { destination = event.destination; }, {once: true});
+ history.pushState({}, '', '#destination');
+ globalThis.controller = new AbortController();
+ globalThis.data = new FormData();
+ data.set('value', 'page');
+ const file = new File(['bytes'], 'probe.txt', {type: 'text/plain', lastModified: 7});
+ file.pageOnly = true;
+ data.set('file', file);
+ globalThis.source = document.createElement('button');
+ source.id = 'source';
+ if (!document.documentElement) document.appendChild(document.createElement('html'));
+ if (!document.body) document.documentElement.appendChild(document.createElement('body'));
+ document.body.appendChild(source);
+ globalThis.original = new NavigateEvent('probe', {
+ destination, signal: controller.signal, formData: data, sourceElement: source,
+ });
+ navigation.addEventListener('probe', event => {
+ event.signal.pageOnly = true;
+ event.signal.addEventListener = () => { throw new Error('page signal override'); };
+ event.formData.pageOnly = true;
+ event.formData.get = () => 'page override';
+ event.sourceElement.pageOnly = true;
+ event.sourceElement.getAttribute = () => 'page override';
+ });
+ 'ready'
+ "#).unwrap();
+ let isolated = vm.create_isolated_world("platform-views", false).unwrap();
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ globalThis.facts = [];
+ globalThis.abortFacts = [];
+ navigation.addEventListener('probe', event => {
+ globalThis.savedSignal = event.signal;
+ globalThis.savedData = event.formData;
+ const file = event.formData.get('file');
+ facts.push(event instanceof NavigateEvent,
+ event.signal instanceof AbortSignal, event.signal.pageOnly === undefined,
+ event.formData instanceof FormData, event.formData.pageOnly === undefined,
+ event.formData.get('value') === 'page',
+ event.sourceElement instanceof HTMLButtonElement,
+ event.sourceElement === document.getElementById('source'),
+ event.sourceElement.pageOnly === undefined,
+ event.sourceElement.getAttribute('id') === 'source',
+ file instanceof File, file.pageOnly === undefined,
+ file === event.formData.get('file'), file.name === 'probe.txt',
+ file.size === 5, file.type === 'text/plain', file.lastModified === 7);
+ event.formData.set('value', 'isolated');
+ event.signal.addEventListener('abort', function (abort) {
+ abortFacts.push(this === savedSignal, abort.target === savedSignal,
+ abort instanceof Event, savedSignal.aborted, savedSignal.reason === 'stop');
+ }, {once: true});
+ });
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ vm.eval("navigation.dispatchEvent(original); controller.abort('stop'); 'dispatched'")
+ .unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(isolated, "JSON.stringify(facts)")
+ .unwrap(),
+ "[true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true]"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(isolated, "JSON.stringify(abortFacts)")
+ .unwrap(),
+ "[true,true,true,true,true]"
+ );
+ assert_eq!(
+ vm.eval("FormData.prototype.get.call(data, 'value')")
+ .unwrap(),
+ "isolated"
+ );
+ vm.eval("FormData.prototype.set.call(data, 'value', 'updated'); 'updated'")
+ .unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(isolated, "savedData.get('value')")
+ .unwrap(),
+ "updated"
+ );
+}
+
+#[test]
+fn history_worlds_synthetic_event_views_can_be_reinitialized_and_redispatched() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.original = new CustomEvent('probe', {detail: 1, cancelable: true});
+ original.expando = 'page';
+ globalThis.pageFacts = [];
+ navigation.addEventListener('probe', event => {
+ pageFacts.push(event === original, event.target === navigation);
+ });
+ navigation.addEventListener('reused', event => {
+ pageFacts.push(event === original, event.detail === 9, event.expando === 'page',
+ event.target === navigation, event.composedPath()[0] === navigation);
+ event.preventDefault();
+ });
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("redispatch-views", false).unwrap();
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ globalThis.view = null;
+ globalThis.facts = [];
+ navigation.addEventListener('probe', event => {
+ view = event;
+ facts.push(event instanceof CustomEvent, event.expando === undefined,
+ event.target === navigation, event.detail === 1);
+ });
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ vm.eval("navigation.dispatchEvent(original); 'dispatched'")
+ .unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ view.initCustomEvent('reused', false, true, 9);
+ view.expando = 'isolated';
+ navigation.addEventListener('reused', event => {
+ facts.push(event === view, event.defaultPrevented,
+ event.target === navigation, event.detail === 9);
+ }, {once: true});
+ facts.push(navigation.dispatchEvent(view));
+ JSON.stringify(facts)
+ "#
+ )
+ .unwrap(),
+ "[true,true,true,true,true,true,true,true,false]"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify(pageFacts)").unwrap(),
+ "[true,true,true,true,true,true,true]"
+ );
+}
+
#[test]
fn history_worlds_navigation_entries_keep_their_own_wrappers() {
let mut vm = new_storage_test_vm("https://example.com/base");
@@ -717,6 +1003,113 @@ fn history_native_snapshot_survives_isolate_replacement_with_structured_values()
);
}
+#[test]
+fn history_restored_entries_keep_world_identity_and_refresh_reused_ids() {
+ const ENTRIES: &str = r#"JSON.stringify(navigation.entries()
+ .filter(entry => entry.url.includes('#'))
+ .map(entry => [entry.url, entry.id, entry.key, entry.index, entry.sameDocument,
+ entry instanceof NavigationHistoryEntry, entry.getState() instanceof Map,
+ String(entry.getState().get('value'))]))"#;
+ let (mut seed, expected) = {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r##"
+ history.replaceState({value: 1n}, '', '#one');
+ history.scrollRestoration = 'manual';
+ navigation.updateCurrentEntry({state: new Map([['value', 1n]])});
+ history.pushState({value: 2n}, '', '#two');
+ navigation.updateCurrentEntry({state: new Map([['value', 2n]])});
+ 'ready'
+ "##,
+ )
+ .unwrap();
+ let expected = vm.eval(ENTRIES).unwrap();
+ vm.eval("location.href = '/next'; 'queued'").unwrap();
+ let mut seed = vm
+ .take_pending_location_navigation_with_seed()
+ .unwrap()
+ .entry_seed
+ .unwrap();
+ seed.current_index = seed
+ .entries
+ .iter()
+ .find(|entry| entry.url.ends_with("#one"))
+ .unwrap()
+ .history_index;
+ seed.activation = None;
+ // Snapshot order is not the history position stored in each snapshot.
+ seed.entries.reverse();
+ (seed, expected)
+ };
+ let mut restored = new_storage_test_vm("https://example.com/base#one");
+ restored.install_navigation_bootstrap_entry(Some(seed.clone()));
+ let isolated = restored
+ .create_isolated_world("lazy-history-entries", false)
+ .unwrap();
+ // The first observation of non-current entries is in the isolated world.
+ assert_eq!(
+ restored
+ .eval_in_isolated_context(isolated, ENTRIES)
+ .unwrap(),
+ expected
+ );
+ restored
+ .eval_in_isolated_context(
+ isolated,
+ r#"
+ navigation.entries().find(entry => entry.url.endsWith('#two')).worldOnly = 'isolated';
+ globalThis.retained = navigation.currentEntry;
+ 'observed'
+ "#,
+ )
+ .unwrap();
+ assert_eq!(restored.eval(ENTRIES).unwrap(), expected);
+ assert_eq!(
+ restored
+ .eval(r#"String(navigation.entries().every(entry => entry.worldOnly === undefined))"#)
+ .unwrap(),
+ "true"
+ );
+ restored
+ .eval("globalThis.retained = navigation.currentEntry; 'retained'")
+ .unwrap();
+ let replacement = seed
+ .entries
+ .iter()
+ .find(|entry| entry.url.ends_with("#two"))
+ .unwrap()
+ .clone();
+ let current = seed
+ .entries
+ .iter_mut()
+ .find(|entry| entry.url.ends_with("#one"))
+ .unwrap();
+ current.history_state = replacement.history_state;
+ current.navigation_state = replacement.navigation_state;
+ current.scroll_restoration = moli_history::ScrollRestoration::Auto;
+ // Reusing serialized IDs must not return wrappers for the previous native records.
+ restored.install_navigation_bootstrap_entry(Some(seed));
+ const REFRESHED: &str = r#"JSON.stringify([
+ navigation.currentEntry !== retained,
+ navigation.currentEntry.id === retained.id,
+ navigation.currentEntry instanceof NavigationHistoryEntry,
+ navigation.entries().includes(navigation.currentEntry),
+ history.state.value === 2n,
+ navigation.currentEntry.getState().get('value') === 2n,
+ retained.getState().get('value') === 1n,
+ history.scrollRestoration
+ ])"#;
+ for result in [
+ restored.eval(REFRESHED),
+ restored.eval_in_isolated_context(isolated, REFRESHED),
+ ] {
+ assert_eq!(
+ result.unwrap(),
+ r#"[true,true,true,true,true,true,true,"auto"]"#
+ );
+ }
+}
+
#[test]
fn history_native_fragment_navigation_preserves_structured_navigation_state() {
let mut vm = new_storage_test_vm("https://example.com/base");