From 595ea3aa3b8a617ca16ce6287ce01a58b7bedacb Mon Sep 17 00:00:00 2001 From: ldm0 Date: Mon, 19 Oct 2026 18:56:08 +0800 Subject: [PATCH] fix(runtime): integrate typed API state and Window ownership with main Reconcile API dictionary snapshots and data properties with main, and migrate frontend listener state to the shared native EventTarget machinery. Preserve native proxy dispatch identity and validate callbacks in their captured execution context. Use the shared cross-origin Window and Location infrastructure while retaining callee-realm errors, entry and incumbent navigation settings, lazy child contexts and document-order named access. Update regression fixtures for native task ownership and published geometry; retain all matrix assertions and compare video frame pixels directly without stringifying them. --- moli-core/tests/history_child.rs | 8 +- moli-renderer-v8/src/blob.rs | 3 +- moli-renderer-v8/src/context_bootstrap.rs | 4 +- .../src/context_bootstrap/bar_prop.rs | 20 +- .../canvas/blob_serialization.rs | 45 +- .../src/context_bootstrap/close_watchers.rs | 34 +- .../exposed_interfaces/metadata.rs | 4 + .../context_bootstrap/location_navigation.rs | 11 +- .../src/context_bootstrap/location_runtime.rs | 3 +- .../location_runtime/access.rs | 21 +- .../location_runtime/navigation.rs | 13 - .../location_runtime/surface.rs | 7 +- .../src/context_bootstrap/media_queries.rs | 5 +- .../context_bootstrap/media_queries/events.rs | 5 +- .../events/simple_event_target/listeners.rs | 8 +- .../navigation_callbacks/accessors.rs | 16 +- .../context_bootstrap/navigation_download.rs | 7 +- .../navigator_runtime/encrypted_media.rs | 15 +- .../navigator_runtime/midi.rs | 18 +- .../performance_runtime/marks_measures.rs | 4 +- .../src/context_bootstrap/remote_playback.rs | 54 +- .../resize_observer_runtime.rs | 2 +- .../src/context_bootstrap/rtc_rtp/dtmf.rs | 2 +- .../context_bootstrap/rtc_rtp/signaling.rs | 7 +- .../context_bootstrap/rtc_rtp/transports.rs | 15 +- .../src/context_bootstrap/runtime_state.rs | 76 +- .../service_worker_interfaces.rs | 23 +- .../src/context_bootstrap/shared/clone.rs | 4 +- .../src/context_bootstrap/shared/slots.rs | 1 + .../context_bootstrap/shared_event_targets.rs | 2 +- .../context_bootstrap/svg_runtime/filters.rs | 43 - .../context_bootstrap/video_codecs/config.rs | 2 +- .../context_bootstrap/video_color_space.rs | 2 - .../context_bootstrap/web_storage/install.rs | 2 +- .../src/context_bootstrap/window_accessors.rs | 1 + .../window_accessors/child_context.rs | 8 +- .../window_accessors/document.rs | 16 +- .../window_accessors/interceptors.rs | 16 +- .../window_accessors/surface.rs | 36 +- .../window_accessors/values.rs | 6 +- .../window_events/install.rs | 2 +- .../src/context_bootstrap/window_receiver.rs | 6 - .../src/context_bootstrap/window_template.rs | 74 +- moli-renderer-v8/src/definitions.rs | 2 - .../src/module_runtime/fetch_context.rs | 2 +- .../context_host/animation_frames.rs | 26 +- .../context_host/child_frame_runtime.rs | 1 + .../child_frame_runtime/document.rs | 15 +- .../realm_state/initialize.rs | 2 +- .../child_frame_runtime/realm_state/model.rs | 1 - .../child_frame_runtime/window.rs | 82 +- .../window/cross_origin_bindings.rs | 34 +- .../child_frame_runtime/window/location.rs | 40 +- .../child_frame_snapshots/frame_tree.rs | 3 +- .../context_host/child_frames/lookup.rs | 27 +- .../context_host/host_environment.rs | 8 +- .../context_host/media_playback/video.rs | 33 + .../src/native_bridge/context_host/mod.rs | 3 +- .../src/native_bridge/context_host/popups.rs | 9 +- .../context_host/popups/realm.rs | 2 +- .../context_host/window_security_tokens.rs | 28 +- .../document/custom_element_options.rs | 1 - .../src/native_bridge/document/lifecycle.rs | 3 +- .../src/native_bridge/element/styles.rs | 16 - moli-renderer-v8/src/native_bridge/mod.rs | 1 + .../page_vm/tests/canvas_loaded_images.rs | 106 +- .../page_vm/tests/canvas_video_frames.rs | 80 +- .../page_vm/tests/media_element_event.rs | 20 +- .../tests/browser_api/nested_frame_access.rs | 40 + .../tests/cross_origin_named_children.rs | 8 +- .../script_vm/tests/declarative_receivers.rs | 11 +- .../tests/document_import_adopt_webidl.rs | 6 +- .../detached/tables_and_document_surfaces.rs | 26 +- .../stylesheet_and_document_lifecycle.rs | 148 +- .../src/script_vm/tests/encrypted_media.rs | 4 +- .../src/script_vm/tests/midi_frontend.rs | 1 + moli-renderer-v8/src/script_vm/tests/mod.rs | 6 - .../src/script_vm/tests/observer_callbacks.rs | 17 +- .../tests/resize_observer_entries.rs | 24 + .../src/script_vm/tests/rtc_configuration.rs | 12 +- .../script_vm/tests/video_playback_quality.js | 6 +- .../webidl_and_transform_streams.rs | 69 +- moli-renderer-v8/src/util.rs | 20 +- .../src/webidl_callback_execution.rs | 18 +- .../src/worker/global_scope/event_handlers.rs | 2 +- .../worker/global_scope/service_worker_api.rs | 13 +- .../src/worker/thread/tests/wasm_csp.rs | 11 +- .../tests/fixtures/canvas-exif-orientation.js | 1 + .../tests/fixtures/canvas-video-frames.js | 27 +- .../fixtures/frame-content-document-domain.js | 7 +- .../windowless-handler-csp-retirement.js | 3 +- .../tests/fixtures/worker-wasm-csp.js | 10 +- moli-webapi-declare-derive/src/expand.rs | 46 + moli-webapi-declare/src/declaration.rs | 13 + moli-webapi/src/dom_exception/rtc_error.rs | 1 + moli-webapi/src/events/ice_error_event.rs | 5 +- moli-webapi/src/events/value.rs | 3 +- moli-webapi/src/events/webrtc.rs | 5 +- moli-webapi/src/geometry.rs | 13 +- moli-webapi/src/interfaces.rs | 5 - vendor/v8-152.2.0/src/template.rs | 1975 ++++++++--------- 101 files changed, 1800 insertions(+), 1952 deletions(-) diff --git a/moli-core/tests/history_child.rs b/moli-core/tests/history_child.rs index 7f27fb7f13c..c689bf89095 100644 --- a/moli-core/tests/history_child.rs +++ b/moli-core/tests/history_child.rs @@ -5448,13 +5448,7 @@ async fn cross_origin_window_proxy_exposes_named_child_frames() -> Result<()> { hasDocumentCollision: Object.prototype.hasOwnProperty.call(win, 'document'),\ hasFocusCollision: Object.prototype.hasOwnProperty.call(win, 'focus'),\ sameAsIndexed: named === indexed,\ - documentDescriptor: {\ - enumerable: documentDescriptor?.enumerable,\ - configurable: documentDescriptor?.configurable,\ - getterType: typeof documentDescriptor?.get,\ - setterType: typeof documentDescriptor?.set,\ - valueType: typeof documentDescriptor?.value\ - },\ + documentDescriptor,\ focusDescriptor: {\ enumerable: focusDescriptor?.enumerable,\ configurable: focusDescriptor?.configurable,\ diff --git a/moli-renderer-v8/src/blob.rs b/moli-renderer-v8/src/blob.rs index d5587c73010..1919747ba30 100644 --- a/moli-renderer-v8/src/blob.rs +++ b/moli-renderer-v8/src/blob.rs @@ -1,8 +1,7 @@ use crate::context_bootstrap::media_source::{MediaSourceObject, media_source_object}; use crate::native_bridge; -use moli_file_api::{BlobData, BlobId, BlobStore, ObjectUrlData, ObjectUrlEntry, ObjectUrlTarget}; +use moli_file_api::{BlobData, BlobId, BlobStore, ObjectUrlEntry, ObjectUrlTarget}; pub(super) use moli_v8_util::buffer_source_bytes_from_value; -pub(crate) use moli_webapi::blob::{blob_id_from_object, world_wrapper}; use moli_webapi::blob::{BlobReadMode, BlobRuntime}; pub(super) use moli_webapi::blob::{ blob_constructor_callback, blob_data_from_object, blob_mime_type_from_object, diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index cece76ee391..5ef76a71319 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -235,7 +235,7 @@ pub(crate) use css_fontface_runtime::{ pub(crate) use form_navigation::FormNavigationHistory; pub(crate) use history_mutation::update_history_for_document_open; pub(crate) use location_navigation::{ - HyperlinkNavigationOptions, LocationNavigationKind, blocks_ancestor_location_navigation, + HyperlinkNavigationOptions, LocationNavigationKind, dispatch_top_level_navigation_event_with_source_element, history_entry_seed_for_cross_document_location, is_native_location, navigate_borrowed_location, navigate_child_meta_refresh, navigate_location_object_for_element_fragment, @@ -265,8 +265,6 @@ pub(crate) use navigation_traversal_execution::{ apply_authorized_history_traversal_task, reject_canceled_history_traversal_results, resume_pending_history_traversals, }; -pub(crate) use performance_runtime::PERFORMANCE_TIME_ORIGIN_SLOT; -pub(crate) use performance_runtime::performance_slot_number; #[cfg(feature = "devtools")] pub(crate) use selection_surface::window_selection_is_collapsed; pub(crate) use selection::focus_element_selection; diff --git a/moli-renderer-v8/src/context_bootstrap/bar_prop.rs b/moli-renderer-v8/src/context_bootstrap/bar_prop.rs index 9c958ab004a..50ad06e4b43 100644 --- a/moli-renderer-v8/src/context_bootstrap/bar_prop.rs +++ b/moli-renderer-v8/src/context_bootstrap/bar_prop.rs @@ -29,7 +29,7 @@ struct BarPropPrototypeDeclaration { } #[derive(WebApiObject)] -#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowBarPropsDeclaration<'s> { locationbar_data: v8::Local<'s, v8::Value>, menubar_data: v8::Local<'s, v8::Value>, @@ -38,28 +38,22 @@ struct WindowBarPropsDeclaration<'s> { statusbar_data: v8::Local<'s, v8::Value>, toolbar_data: v8::Local<'s, v8::Value>, #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.locationbar_data, setter_data = self.locationbar_data)] - #[webapi(receiver_access_check = "setter")] + data = self.locationbar_data, setter_data = self.locationbar_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] locationbar: (), #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.menubar_data, setter_data = self.menubar_data)] - #[webapi(receiver_access_check = "setter")] + data = self.menubar_data, setter_data = self.menubar_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] menubar: (), #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.personalbar_data, setter_data = self.personalbar_data)] - #[webapi(receiver_access_check = "setter")] + data = self.personalbar_data, setter_data = self.personalbar_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] personalbar: (), #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.scrollbars_data, setter_data = self.scrollbars_data)] - #[webapi(receiver_access_check = "setter")] + data = self.scrollbars_data, setter_data = self.scrollbars_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] scrollbars: (), #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.statusbar_data, setter_data = self.statusbar_data)] - #[webapi(receiver_access_check = "setter")] + data = self.statusbar_data, setter_data = self.statusbar_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] statusbar: (), #[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter, - data = self.toolbar_data, setter_data = self.toolbar_data)] - #[webapi(receiver_access_check = "setter")] + data = self.toolbar_data, setter_data = self.toolbar_data, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] toolbar: (), } diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/blob_serialization.rs b/moli-renderer-v8/src/context_bootstrap/canvas/blob_serialization.rs index 6e642c1909d..67ff5d142c2 100644 --- a/moli-renderer-v8/src/context_bootstrap/canvas/blob_serialization.rs +++ b/moli-renderer-v8/src/context_bootstrap/canvas/blob_serialization.rs @@ -2,16 +2,9 @@ use moli_webidl_callback::WebIdlCallbackFunction; use tokio::sync::oneshot; use crate::{ - blob::build_blob_object, - context_bootstrap::new_dom_exception_value, - host::report_event_callback_exception, - native_bridge::PageScriptHost, - util::context_host_ptr_from_global_bridge, - webidl, - window_webidl_callback::{ - WindowWebIdlCallbackFunction, WindowWebIdlCallbackFunctionOutcome, - invoke_window_webidl_callback_function, - }, + blob::build_blob_object, context_bootstrap::new_dom_exception_value, + native_bridge::PageScriptHost, util::context_host_ptr_from_global_bridge, webidl, + window_webidl_callback::WindowWebIdlCallbackFunction, }; use super::backing_store::canvas_like_pixels_copy; @@ -208,32 +201,20 @@ impl CanvasBlobTask { .unwrap_or_else(|| v8::null(scope).into()), None => v8::null(scope).into(), }; - let callback = callback.prepare(scope); - let relevant_identity = callback.relevant_identity(); - let receiver = v8::undefined(scope); - match invoke_window_webidl_callback_function( + let Some(execution) = callback.prepare_execution(scope, host_ptr, None) else { + return CanvasBlobTaskEffect::Retired; + }; + let receiver = v8::undefined(scope).into(); + if execution.invoke_and_report( scope, - host_ptr, - "BlobCallback", - "HTMLCanvasElement.toBlob callback threw", + "canvas", "HTMLCanvasElement.toBlob callback", - &callback, - receiver.into(), + receiver, &[blob], ) { - WindowWebIdlCallbackFunctionOutcome::Returned => CanvasBlobTaskEffect::Completed, - WindowWebIdlCallbackFunctionOutcome::Threw(report) => { - report_event_callback_exception( - scope, - host_ptr, - "canvas", - relevant_identity, - None, - &report, - ); - CanvasBlobTaskEffect::Completed - } - WindowWebIdlCallbackFunctionOutcome::Retired => CanvasBlobTaskEffect::Retired, + CanvasBlobTaskEffect::Completed + } else { + CanvasBlobTaskEffect::Retired } } } diff --git a/moli-renderer-v8/src/context_bootstrap/close_watchers.rs b/moli-renderer-v8/src/context_bootstrap/close_watchers.rs index 0a908fc781c..a20fce039c1 100644 --- a/moli-renderer-v8/src/context_bootstrap/close_watchers.rs +++ b/moli-renderer-v8/src/context_bootstrap/close_watchers.rs @@ -1,8 +1,7 @@ use super::{ - SIMPLE_EVENT_TARGET_SLOT, dispatch_simple_event_target_event, - ensure_intrinsic_interface_prototype, events::initialize_event_object, - install_simple_event_target_ordered_handlers, mark_event_trusted, - simple_object_event_set_ordered_handler, throw_dom_exception_value, + SIMPLE_EVENT_TARGET_LISTENERS_SLOT, dispatch_simple_event_target_event, + ensure_intrinsic_interface_prototype, events::initialize_event_object, mark_event_trusted, + simple_object_event_set_handler, throw_dom_exception_value, }; use crate::{ abort_signal_route::ResolvedAbortSignal, @@ -17,7 +16,6 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; const REALM_ANCHOR_SLOT: &str = "__moliCloseWatcherRealmAnchor"; const ACTIVE_SLOT: &str = "__moliCloseWatcherActive"; const RUNNING_CANCEL_SLOT: &str = "__moliCloseWatcherRunningCancel"; -const LISTENERS_SLOT: &str = "__moliCloseWatcherListeners"; const ONCANCEL_SLOT: &str = "__moliCloseWatcherOncancel"; const ONCLOSE_SLOT: &str = "__moliCloseWatcherOnclose"; const SIGNAL_SLOT: &str = "__moliCloseWatcherSignal"; @@ -32,7 +30,7 @@ struct CloseWatcherObjectDeclaration<'scope> { active: (), #[webapi(slot = RUNNING_CANCEL_SLOT, init = false)] running_cancel: (), - #[webapi(slot = SIMPLE_EVENT_TARGET_SLOT, value = LISTENERS_SLOT)] + #[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")] event_target_slot: (), #[webapi(slot = ONCANCEL_SLOT, init = "null")] oncancel: (), @@ -124,7 +122,6 @@ pub(in crate::context_bootstrap) fn close_watcher_constructor_callback<'s>( { return; } - install_simple_event_target_ordered_handlers(scope, watcher); let Some(host_ptr) = context_host_ptr_from_context_slot(context) else { return; }; @@ -248,7 +245,7 @@ fn fire_event<'s>( let _ = event.set_prototype(scope, prototype.into()); initialize_event_object(scope, event, event_type, false, cancelable); mark_event_trusted(scope, event); - dispatch_simple_event_target_event(scope, watcher, LISTENERS_SLOT, event_type, event) + dispatch_simple_event_target_event(scope, watcher, event_type, event) } fn close<'s>(scope: &mut v8::PinScope<'s, '_>, watcher: v8::Local<'s, v8::Object>) { @@ -381,26 +378,7 @@ fn set_handler<'s>( event_type: &str, ) { let watcher = args.this(); - let value = args.get(0); - let active = value.is_object(); - set_private_value( - scope, - watcher, - slot, - if active { - value - } else { - v8::null(scope).into() - }, - ); - simple_object_event_set_ordered_handler( - scope, - watcher, - LISTENERS_SLOT, - event_type, - slot, - active, - ); + simple_object_event_set_handler(scope, watcher, event_type, slot, args.get(0)); } fn oncancel_getter<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs index 5b7ac09f3dc..11b8dd9e909 100644 --- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs +++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs @@ -224,6 +224,10 @@ const SECURE_CONTEXT_ONLY_INTERFACE_NAMES: &[&str] = &[ "MIDIConnectionEvent", "MIDIMessageEvent", "MediaKeyMessageEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", "PaymentRequest", "PaymentResponse", "VideoDecoder", diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs index f1d85c8e4c0..898ede962ee 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs @@ -1078,6 +1078,10 @@ pub(crate) fn navigate_borrowed_location<'s>( if !is_native_location(scope, receiver) { return false; } + if kind == LocationNavigationKind::Assign { + let _ = super::location_runtime::set_location_href(scope, receiver, value); + return true; + } let raw = match crate::webidl::convert::( scope, value, @@ -1089,10 +1093,9 @@ pub(crate) fn navigate_borrowed_location<'s>( return true; } }; - let Some(context) = receiver.get_creation_context(scope) else { - return true; - }; - let scope = &mut v8::ContextScope::new(scope, context); + // The navigation algorithm resolves the native receiver's owner itself. + // Preserve the caller's entry/incumbent settings and exception Realm until + // that boundary has captured them. navigate_location_object_with_child_navigate_event(scope, receiver, kind, Some(raw)); true } diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime.rs index 3cb8487274b..9fe3dea3ef0 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime.rs @@ -14,6 +14,7 @@ mod origin; mod slots; mod surface; +pub(super) use access::set_location_href; pub(in crate::context_bootstrap) use access::wrap_location_object; pub(super) use install::{ @@ -23,7 +24,7 @@ pub(super) use install::{ }; pub(super) use navigation::{ is_same_document_fragment_navigation, resolve_location_navigation_target, - urls_equal_ignoring_fragment, urls_refer_to_same_document, + urls_equal_ignoring_fragment, }; pub(super) use slots::{location_href_slot, sync_location_object}; pub(crate) use surface::refresh_global_location_security_origin; diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs index 2bf6bae358f..47b428b8455 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs @@ -115,7 +115,7 @@ fn location_proxy_set<'s>( } } -pub(super) fn set_location_href<'s>( +pub(in crate::context_bootstrap) fn set_location_href<'s>( scope: &mut v8::PinScope<'s, '_>, location: v8::Local<'s, v8::Object>, value: v8::Local<'s, v8::Value>, @@ -212,8 +212,6 @@ struct CrossOriginSurfaceDeclaration<'s> { surface: v8::Local<'s, v8::Object>, #[webapi(method = "set href", callback = cross_origin_href_setter, data = self.surface, length = 1)] href: (), - #[webapi(method, callback = super::methods::location_replace_callback, data = self.surface, length = 1, readonly)] - replace: (), } pub(super) fn install_access_check(template: v8::Local<'_, v8::ObjectTemplate>) { @@ -310,13 +308,16 @@ fn surface_for<'s>( } let surface = new_null_prototype_object(scope); set_private_value(scope, surface, SURFACE_TARGET_SLOT, target.into()); - CrossOriginSurfaceDeclaration { - surface, - href: (), - replace: (), - } - .initialize(scope, surface) - .ok()?; + CrossOriginSurfaceDeclaration { surface, href: () } + .initialize(scope, surface) + .ok()?; + let replace = crate::native_bridge::cross_origin_location_replace_function(scope)?; + surface.define_own_property( + scope, + v8str(scope, "replace").into(), + replace.into(), + v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_ENUM, + )?; let setter_name = v8str(scope, "set href"); let setter = surface.get(scope, setter_name.into())?; surface.delete(scope, setter_name.into())?; diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs index b168eea3e35..c04fed9c1ec 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs @@ -61,16 +61,3 @@ pub(in crate::context_bootstrap) fn urls_equal_ignoring_fragment( target_without_fragment.set_fragment(None); current_without_fragment == target_without_fragment } - -pub(in crate::context_bootstrap) fn urls_refer_to_same_document( - current_href: &str, - target_href: &str, -) -> bool { - let Ok(current) = url::Url::parse(current_href) else { - return false; - }; - let Ok(target) = url::Url::parse(target_href) else { - return false; - }; - urls_equal_ignoring_fragment(¤t, &target) -} diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs index b25079e1db8..a9182ca5a24 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs @@ -17,13 +17,12 @@ struct WindowLocationAccessorDeclaration { } #[derive(Default, WebApiObject)] -#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowHistoryAccessorDeclaration { #[webapi( accessor_property, getter = window_history_getter, - enumerable - )] + enumerable, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] history: (), } @@ -34,7 +33,7 @@ struct WindowNavigationAccessorDeclaration { accessor_property, getter = window_navigation_getter, setter = window_navigation_setter, - enumerable, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] + enumerable, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] navigation: (), } diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries.rs b/moli-renderer-v8/src/context_bootstrap/media_queries.rs index e90605ffc71..9ea018149c4 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_queries.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_queries.rs @@ -27,7 +27,4 @@ pub(super) use self::events::{ media_query_list_add_listener_callback, media_query_list_remove_listener_callback, }; -use super::{ - SIMPLE_EVENT_TARGET_LISTENERS_SLOT, object_property_as_array, object_string_property_defined, - v8str, -}; +use super::{SIMPLE_EVENT_TARGET_LISTENERS_SLOT, object_string_property_defined, v8str}; diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/events.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/events.rs index 76db74b9e56..104d476d7a4 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_queries/events.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_queries/events.rs @@ -1,7 +1,4 @@ -use super::{ - SIMPLE_EVENT_TARGET_LISTENERS_SLOT, object_property_as_array, object_string_property_defined, - v8str, -}; +use super::{SIMPLE_EVENT_TARGET_LISTENERS_SLOT, object_string_property_defined, v8str}; const SIMPLE_EVENT_TARGET_HANDLER_SLOT_FIELD: &str = "handlerSlot"; mod media_query_list; diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs index 647d13d7770..0a983f632dd 100644 --- a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs +++ b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs @@ -738,10 +738,16 @@ fn handler_belongs_to_target<'s>( candidate: v8::Local<'s, v8::Value>, target: v8::Local<'s, v8::Object>, ) -> bool { + let target = moli_webapi_declare::web_api_object_target(scope, target).unwrap_or(target); v8::Local::::try_from(candidate) .ok() .and_then(|entry| get_private_value(scope, entry, HANDLER_TARGET_SLOT)) - .is_some_and(|owner| owner.strict_equals(target.into())) + .and_then(|owner| v8::Local::::try_from(owner).ok()) + .is_some_and(|owner| { + moli_webapi_declare::web_api_object_target(scope, owner) + .unwrap_or(owner) + .strict_equals(target.into()) + }) } pub(crate) fn simple_object_event_remove_listener_value_for_type<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/accessors.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/accessors.rs index 446ee7559f3..94c9d59ab7a 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/accessors.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/accessors.rs @@ -1,5 +1,5 @@ use super::*; -use crate::util::{context_host_ptr_from_window_object, get_private_value}; +use crate::util::get_private_value; use crate::webidl; fn window_receiver<'s>( @@ -8,7 +8,7 @@ fn window_receiver<'s>( member: &'static str, ) -> Option> { let receiver = args.this(); - if context_host_ptr_from_window_object(scope, receiver).is_some() { + if super::super::is_window_receiver(scope, receiver) { return Some(receiver); } webidl::throw_type_error( @@ -58,8 +58,7 @@ pub(in crate::context_bootstrap) fn window_location_getter<'s>( let Some(receiver) = window_receiver(scope, &args, "location") else { return; }; - let Some(value) = get_private_value(scope, receiver, WINDOW_LOCATION_SLOT) - .filter(|v| !v.is_undefined()) + let Some(value) = object_window_slot_value(scope, receiver, WINDOW_LOCATION_SLOT) .or_else(|| global_location_slot_value(scope)) else { webidl::throw_type_error( @@ -136,18 +135,13 @@ pub(in crate::context_bootstrap) fn document_location_setter<'s>( rv.set_undefined(); } -fn object_location_slot_value<'s>( - scope: &mut v8::PinScope<'s, '_>, - object: v8::Local<'s, v8::Object>, -) -> Option> { - object_window_slot_value(scope, object, WINDOW_LOCATION_SLOT) -} - fn object_window_slot_value<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, slot: &'static str, ) -> Option> { + let context = object.get_creation_context(scope)?; + let scope = &mut v8::ContextScope::new(scope, context); get_private_value(scope, object, slot).filter(|value| !value.is_undefined()) } diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_download.rs b/moli-renderer-v8/src/context_bootstrap/navigation_download.rs index 2d541aaa20d..0dcf49f2bd2 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_download.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_download.rs @@ -29,7 +29,6 @@ use super::navigation_window::{ navigation_document_has_disabled_entries, navigation_document_is_active, window_location_for_holder, window_navigation_for_holder, }; -use super::*; use crate::script_cleanup::ScriptExecutionScope; pub(super) fn dispatch_download_navigation_event<'s>( @@ -187,10 +186,8 @@ fn finish_download_navigation_error<'s>( let committed_resolver = transition_resolver .filter(|resolver| navigation_transition_matches_resolver(scope, navigation, *resolver)) .and_then(|_| take_navigation_transition_committed_resolver(scope, navigation)); - if let Some(signal) = outcome.signal - && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) - { - unsafe { &mut *host_ptr }.abort_signal(scope, signal, error); + if let Some(signal) = outcome.signal { + crate::native_bridge::abort::abort_signal(scope, signal, error); } finish_navigation_error_events(scope, navigation, error, href); if let Some(resolver) = committed_resolver { diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/encrypted_media.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/encrypted_media.rs index d227230e637..14d3220db3e 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/encrypted_media.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/encrypted_media.rs @@ -10,14 +10,12 @@ use crate::{ PageScriptHost, element::{node_event_handler_getter_function, node_event_handler_setter_function}, }, - util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value, v8str}, + util::{context_host_ptr_from_global_bridge, get_private_value, v8str}, web_api_interfaces, webidl, }; mod schema; - -const LISTENERS: &str = "__moliMediaKeySessionListeners"; const MESSAGE_HANDLER: &str = "__moliMediaKeySessionOnmessage"; const STATUS_HANDLER: &str = "__moliMediaKeySessionOnkeystatuseschange"; const UNAVAILABLE: &str = "No content decryption module backend is available."; @@ -329,14 +327,5 @@ fn set_handler<'s>( ) { let receiver = target(scope, args.this()); let (slot, event) = handler_metadata(&args.data().to_rust_string_lossy(scope)); - let active = args.get(0).is_object(); - let value = if active { - args.get(0) - } else { - v8::null(scope).into() - }; - set_private_value(scope, receiver, slot, value); - media_queries::simple_object_event_set_ordered_handler( - scope, receiver, LISTENERS, event, slot, active, - ); + media_queries::simple_object_event_set_handler(scope, receiver, event, slot, args.get(0)); } diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/midi.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/midi.rs index c95484edd80..d5518514aaa 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/midi.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/midi.rs @@ -3,7 +3,7 @@ use super::super::{context_host_ptr_from_global_bridge, media_queries}; use crate::{ - util::{get_private_object, get_private_value, set_private_value, v8str}, + util::{get_private_object, get_private_value, v8str}, web_api_interfaces, webidl, webidl_iterator::{ MaplikeWebIdlIteratorMethod, call_live_maplike_webidl_for_each, @@ -13,7 +13,6 @@ use crate::{ use moli_webapi_declare::WebApiFunctionTemplate; const BACKING: &str = "__moliMidiMapBacking"; -const LISTENERS: &str = "__moliMidiListeners"; const STATE_HANDLER: &str = "__moliMidiStateChangeHandler"; const MESSAGE_HANDLER: &str = "__moliMidiMessageHandler"; @@ -276,18 +275,7 @@ fn handler_setter<'s>( ) { let object = target(scope, args.this()); let (slot, event) = handler_slot(scope, args.data()); - media_queries::mark_simple_event_target_slot(scope, object, LISTENERS); - media_queries::install_simple_event_target_ordered_handlers(scope, object); - let active = args.get(0).is_object(); - let value = if active { - args.get(0) - } else { - v8::null(scope).into() - }; - set_private_value(scope, object, slot, value); - media_queries::simple_object_event_set_ordered_handler( - scope, object, LISTENERS, event, slot, active, - ); + media_queries::simple_object_event_set_handler(scope, object, event, slot, args.get(0)); } fn backing<'s>( @@ -429,6 +417,6 @@ pub(crate) fn map_for_test<'s>( let object = v8::Object::new(scope); web_api_interfaces::initialize(scope, object, interface).unwrap(); assert_eq!(object.set_prototype(scope, prototype.into()), Some(true)); - set_private_value(scope, object, BACKING, map.into()); + crate::util::set_private_value(scope, object, BACKING, map.into()); object } diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs index aedbfe35f90..3f9122d3c8b 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs @@ -366,7 +366,7 @@ fn resolve_named_measure_boundary<'s>( ); return Err(()); } - if name == "navigationStart" { + if timing_name == "navigationStart" { return Ok(0.0); } let timing = match super::lazy_subobjects::ensure_performance_subobject( @@ -386,7 +386,7 @@ fn resolve_named_measure_boundary<'s>( return Err(()); } }; - let value = install::performance_timing_value(scope, timing, name) + let value = install::performance_timing_value(scope, timing, timing_name) .number_value(scope) .expect("native PerformanceTiming attributes should be numeric"); if value == 0.0 { diff --git a/moli-renderer-v8/src/context_bootstrap/remote_playback.rs b/moli-renderer-v8/src/context_bootstrap/remote_playback.rs index dfd54e54d96..2a487926f40 100644 --- a/moli-renderer-v8/src/context_bootstrap/remote_playback.rs +++ b/moli-renderer-v8/src/context_bootstrap/remote_playback.rs @@ -5,33 +5,26 @@ use super::{media_queries, shared}; use crate::{ document_runtime::DomHandle, - host::report_event_callback_exception, native_bridge::{ PageScriptHost, document::document_is_fully_active, node_runtime_and_handle_from_object_or_detached, throw_dom_exception, }, util::{get_private_object, get_private_value, set_private_value, v8str}, web_api_interfaces, webidl, - window_webidl_callback::{ - WindowWebIdlCallbackFunction, WindowWebIdlCallbackFunctionOutcome, - invoke_window_webidl_callback_function, - }, + window_webidl_callback::WindowWebIdlCallbackFunction, }; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; const ASSOCIATED: &str = "__moliMediaRemotePlayback"; const MEDIA: &str = "__moliRemotePlaybackMedia"; -const LISTENERS: &str = "__moliRemotePlaybackListeners"; #[derive(WebApiObject)] #[webapi(interface = web_api_interfaces::RemotePlayback, require_prototype)] struct RemotePlaybackObject<'s> { #[webapi(slot = MEDIA)] media: v8::Local<'s, v8::Object>, - #[webapi(slot = shared::SIMPLE_EVENT_TARGET_SLOT, value = LISTENERS)] + #[webapi(slot = shared::SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")] event_target: (), - #[webapi(slot = shared::SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT, init = true)] - ordered_handlers: (), } #[derive(WebApiFunctionTemplate)] @@ -264,15 +257,12 @@ fn handler_setter<'s>( let remote = target(scope, args.this()); let event = args.data().to_rust_string_lossy(scope); let slot = handler_slot(&event); - let active = args.get(0).is_object(); - let handler = if active { - args.get(0) - } else { - v8::null(scope).into() - }; - set_private_value(scope, remote, slot, handler); - media_queries::simple_object_event_set_ordered_handler( - scope, remote, LISTENERS, &event, slot, active, + media_queries::simple_object_event_set_handler( + scope, + remote, + event.as_str(), + slot, + args.get(0), ); } @@ -298,33 +288,17 @@ impl RemotePlaybackAvailabilityTask { scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, ) -> bool { - let callback = self.callback.prepare(scope); - let relevant_identity = callback.relevant_identity(); + let Some(execution) = self.callback.prepare_execution(scope, host_ptr, None) else { + return false; + }; let receiver = v8::undefined(scope).into(); let available = v8::Boolean::new(scope, false).into(); - match invoke_window_webidl_callback_function( + execution.invoke_and_report( scope, - host_ptr, - "RemotePlaybackAvailabilityCallback", - "RemotePlayback availability callback threw", + "remoteplayback", "RemotePlayback availability callback", - &callback, receiver, &[available], - ) { - WindowWebIdlCallbackFunctionOutcome::Returned => true, - WindowWebIdlCallbackFunctionOutcome::Threw(report) => { - report_event_callback_exception( - scope, - host_ptr, - "remoteplayback", - relevant_identity, - None, - &report, - ); - true - } - WindowWebIdlCallbackFunctionOutcome::Retired => false, - } + ) } } diff --git a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs index faee65c586d..505e433699f 100644 --- a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs +++ b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs @@ -407,7 +407,7 @@ fn sample_resize_observations<'s>( for entry in pending { let (metrics, dpr) = entry .handle - .and_then(|handle| geometry.get(&handle).copied()) + .and_then(|handle| geometry.get(&handle).cloned()) .and_then(|(metrics, dpr)| metrics.map(|metrics| (metrics, dpr))) .map(|(metrics, dpr)| (Some(metrics), dpr)) .unwrap_or((None, 1.0)); diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/dtmf.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/dtmf.rs index eaa7b0cd10c..8e0edaaceb0 100644 --- a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/dtmf.rs +++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/dtmf.rs @@ -5,7 +5,7 @@ use crate::{ context_bootstrap::{exposed_interfaces, media_queries}, native_bridge::throw_dom_exception, - util::{get_private_value, set_private_value}, + util::get_private_value, web_api_interfaces, webidl, }; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/signaling.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/signaling.rs index e8416607d76..b6b4e9e187f 100644 --- a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/signaling.rs +++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/signaling.rs @@ -3,12 +3,13 @@ use crate::{ context_bootstrap::{events, exposed_interfaces, media_queries}, - util::{callback_data_index_value, callback_data_item, get_private_value, set_private_value}, + util::{callback_data_index_value, callback_data_item, get_private_value}, web_api_interfaces, }; +use moli_webapi::rtc::peer_connection::signaling::{ + CURRENT_LOCAL, CURRENT_REMOTE, HANDLER, PENDING_LOCAL, PENDING_REMOTE, +}; use moli_webapi_declare::WebApiFunctionTemplate; -use moli_webapi::rtc::peer_connection::signaling::{CURRENT_LOCAL, PENDING_LOCAL, CURRENT_REMOTE, PENDING_REMOTE, HANDLER}; - const DESCRIPTIONS: &[(&str, Option<&str>)] = &[ (PENDING_LOCAL, Some(CURRENT_LOCAL)), diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/transports.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/transports.rs index bccb6eafd53..a01070613fb 100644 --- a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/transports.rs +++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/transports.rs @@ -1,17 +1,17 @@ //! Native local transports. Applying an offer exposes the planned ICE/DTLS //! objects; only a transport backend may supply candidates or advance them. -use super::{operations, rtp_transceivers, signaling, SIMPLE_EVENT_TARGET_LISTENERS_SLOT}; -use moli_webapi::rtc::peer_connection::{configuration, set_string_slot}; +use super::{SIMPLE_EVENT_TARGET_LISTENERS_SLOT, operations, rtp_transceivers, signaling}; +use crate::page_task_queue::RendererPageWebRtcTaskKind; +use crate::util::get_private_object; use crate::{ context_bootstrap::media_queries, util::{get_private_value, set_private_value, v8_string, v8str}, web_api_interfaces, }; -use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; -use crate::page_task_queue::RendererPageWebRtcTaskKind; -use crate::util::get_private_object; use base64::Engine as _; +use moli_webapi::rtc::peer_connection::{configuration, set_string_slot}; +use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; #[derive(WebApiFunctionTemplate)] #[webapi(interface = web_api_interfaces::RTCPeerConnection, enumerable)] @@ -21,7 +21,8 @@ struct PeerPrototype { } pub(super) fn install_peer<'s>( - scope: &mut v8::PinScope<'s, '_, ()>, prototype: v8::Local<'s, v8::ObjectTemplate>, + scope: &mut v8::PinScope<'s, '_, ()>, + prototype: v8::Local<'s, v8::ObjectTemplate>, ) { PeerPrototype::initialize_prototype_template(scope, prototype); } @@ -257,7 +258,7 @@ pub(super) fn close_sctp<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, // Unlike rollback, close retains pc.sctp. Notify within the SCTP shutdown // step; the following steps of PC.close() shut down DTLS and ICE. set_string_slot(scope, sctp, STATE, "closed"); - signaling::dispatch_event(scope, sctp, LISTENERS, "statechange"); + signaling::dispatch_event(scope, sctp, "statechange"); } } diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs index 212e8462c13..e318f3acdf5 100644 --- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs @@ -138,7 +138,7 @@ struct DocumentPrototypeRuntimeDeclaration { } #[derive(Default, WebApiObject)] -#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowComputedStyleMethodDeclaration { #[webapi( method, @@ -149,7 +149,7 @@ struct WindowComputedStyleMethodDeclaration { } #[derive(WebApiObject)] -#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowLegacySurfaceAccessorsDeclaration<'scope> { navigator_slot: v8::Local<'scope, v8::Value>, external_slot: v8::Local<'scope, v8::Value>, @@ -159,8 +159,7 @@ struct WindowLegacySurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.navigator_slot, - setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("clientInformation").unwrap()), setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("clientInformation").unwrap()), access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] client_information: (), #[webapi( accessor_property, @@ -168,16 +167,15 @@ struct WindowLegacySurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.external_slot, - setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("external").unwrap()), setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("external").unwrap()), access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] external: (), } -// SameObject getters authorize in bound_callback_data_item so an original -// getter can return its captured object after Realm retirement. Setters use -// V8's receiver check; live WindowProxy receivers always require authorization. +// Generated access policies run before reading callback data. The native +// Window predicate admits a retired function's own global, allowing its +// SameObject getter to return the captured object after Realm retirement. #[derive(WebApiObject)] -#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowPublicSurfaceAccessorsDeclaration<'scope> { history_slot: v8::Local<'scope, v8::Value>, navigation_slot: v8::Local<'scope, v8::Value>, @@ -198,9 +196,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { accessor_property, enumerable, getter = window_surface_slot_getter, - data = self.history_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.history_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] history: (), #[webapi( accessor_property, @@ -208,16 +204,13 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.navigation_slot, - setter_data = self.navigation_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = self.navigation_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] navigation: (), #[webapi( accessor_property, enumerable, getter = window_surface_slot_getter, - data = self.navigator_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.navigator_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] navigator: (), #[webapi( accessor_property, @@ -225,32 +218,25 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.screen_slot, - setter_data = self.screen_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = self.screen_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] screen: (), #[webapi( accessor_property = "speechSynthesis", enumerable, getter = window_surface_slot_getter, - data = self.speech_synthesis_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.speech_synthesis_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] speech_synthesis: (), #[webapi( accessor_property = "customElements", enumerable, getter = window_surface_slot_getter, - data = self.custom_elements_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.custom_elements_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] custom_elements: (), #[webapi( accessor_property, enumerable, getter = window_surface_slot_getter, - data = self.crypto_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.crypto_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] crypto: (), #[webapi( accessor_property, @@ -258,8 +244,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.performance_slot, - setter_data = self.performance_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = self.performance_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] performance: (), #[webapi( accessor_property = "visualViewport", @@ -267,8 +252,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { getter = window_surface_slot_getter, setter = window_surface_replaceable_setter, data = self.visual_viewport_slot, - setter_data = self.visual_viewport_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] + setter_data = self.visual_viewport_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] visual_viewport: (), #[webapi( accessor_property = "localStorage", @@ -284,9 +268,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { accessor_property = "indexedDB", enumerable, getter = window_surface_slot_getter, - data = self.indexed_db_slot - )] - #[webapi(receiver_access_check = "setter")] + data = self.indexed_db_slot, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] indexed_db: (), #[webapi( accessor_property, @@ -303,36 +285,29 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> { } #[derive(Default, WebApiObject)] -#[webapi(plain, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowLegacyAliasAccessorsDeclaration { #[webapi( accessor_property, getter = legacy_unforgeable_self_getter, - setter = replaceable_self_setter - )] - #[webapi(receiver_access_check = "setter")] + setter = replaceable_self_setter, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] self_: (), #[webapi( accessor_property, getter = legacy_unforgeable_parent_getter, - setter = replaceable_parent_setter - )] - #[webapi(receiver_access_check = "setter")] + setter = replaceable_parent_setter, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] parent: (), #[webapi(accessor_property, dont_delete, getter = legacy_unforgeable_top_getter)] - #[webapi(receiver_access_check = "setter")] top: (), #[webapi( accessor_property, getter = legacy_unforgeable_frames_getter, - setter = replaceable_frames_setter - )] - #[webapi(receiver_access_check = "setter")] + setter = replaceable_frames_setter, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] frames: (), } #[derive(WebApiObject)] -#[webapi(fragment, prototype = "Window", enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(fragment, prototype = "Window", enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> { origin_name: v8::Local<'scope, v8::Value>, inner_width_name: v8::Local<'scope, v8::Value>, @@ -354,14 +329,13 @@ struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> { accessor_property = "innerWidth", getter = window_inner_width_getter, setter = window_surface_replaceable_setter, - setter_data = self.inner_width_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] + setter_data = self.inner_width_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] inner_width: (), #[webapi( accessor_property, getter = window_length_getter, setter = window_surface_replaceable_setter, setter_data = self.length_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] - #[webapi(receiver_access_check = "setter")] length: (), #[webapi( accessor_property, @@ -373,7 +347,7 @@ struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> { accessor_property = "outerHeight", getter = window_outer_height_getter, setter = window_surface_replaceable_setter, - setter_data = self.outer_height_name, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] + setter_data = self.outer_height_name, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] outer_height: (), #[webapi( accessor_property = "scrollX", diff --git a/moli-renderer-v8/src/context_bootstrap/service_worker_interfaces.rs b/moli-renderer-v8/src/context_bootstrap/service_worker_interfaces.rs index 828b7c48835..824b284c99b 100644 --- a/moli-renderer-v8/src/context_bootstrap/service_worker_interfaces.rs +++ b/moli-renderer-v8/src/context_bootstrap/service_worker_interfaces.rs @@ -1,9 +1,7 @@ //! Shared native identity, state and attributes for Window and Worker bindings. use super::*; -use crate::util::{ - callback_data_index_value, callback_data_item, get_private_value, set_private_value, -}; +use crate::util::{callback_data_index_value, callback_data_item, get_private_value}; use crate::web_api_interfaces; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; @@ -144,24 +142,7 @@ fn handler_setter<'s>( else { return; }; - let value = args.get(0); - let active = value.is_object(); - let value = if active { - value - } else { - v8::null(scope).into() - }; - set_private_value(scope, args.this(), slot, value); - if let Some(listeners) = simple_event_target_slot_name(scope, args.this()) { - simple_object_event_set_ordered_handler( - scope, - args.this(), - &listeners, - event_type, - slot, - active, - ); - } + simple_object_event_set_handler(scope, args.this(), event_type, slot, args.get(0)); } /// The generated binding rejects invalid receivers in the callee realm. Native diff --git a/moli-renderer-v8/src/context_bootstrap/shared/clone.rs b/moli-renderer-v8/src/context_bootstrap/shared/clone.rs index 5d66b4e5f6f..dbaf7221f99 100644 --- a/moli-renderer-v8/src/context_bootstrap/shared/clone.rs +++ b/moli-renderer-v8/src/context_bootstrap/shared/clone.rs @@ -17,8 +17,8 @@ pub(in crate::context_bootstrap) struct PostMessageTransferList<'s> { } impl<'s> PostMessageTransferList<'s> { - fn wire_transfers(&self) -> WireTransfers<'_, 's> { - WireTransfers { + fn wire_transfers(&self) -> crate::structured_clone::WireTransfers<'_, 's> { + crate::structured_clone::WireTransfers { entries: &self.entries, } } diff --git a/moli-renderer-v8/src/context_bootstrap/shared/slots.rs b/moli-renderer-v8/src/context_bootstrap/shared/slots.rs index 01f42165215..b711d4ecad6 100644 --- a/moli-renderer-v8/src/context_bootstrap/shared/slots.rs +++ b/moli-renderer-v8/src/context_bootstrap/shared/slots.rs @@ -1,3 +1,4 @@ +pub(crate) const WINDOW_DOCUMENT_SLOT: &str = "__moliWindowAssociatedDocument"; pub(in crate::context_bootstrap) const WINDOW_LOCATION_SLOT: &str = "__moliWindowLocation"; pub(in crate::context_bootstrap) const WINDOW_LOCATION_HREF_SLOT: &str = "__moliWindowLocationHref"; pub(in crate::context_bootstrap) const WINDOW_CONSOLE_SLOT: &str = "__moliWindowConsole"; 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 7f1315ce915..bfce5f85b65 100644 --- a/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs +++ b/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs @@ -259,5 +259,5 @@ fn handler_setter<'s>( }; let target = resolve_event_target(scope, args.this()).map_or(args.this(), |target| target.handler_owner); - media_queries::simple_object_event_set_handler(scope, target, event_type, slot, args.get(0)); + media_queries::simple_object_event_set_handler(scope, target, *event_type, slot, args.get(0)); } diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/filters.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/filters.rs index 6e999bb691e..caccc699840 100644 --- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/filters.rs +++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/filters.rs @@ -148,49 +148,6 @@ struct ComponentTransferFunctionDeclaration { table_values: (), } -#[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::SVGFEDropShadowElement, enumerable)] -struct DropShadowMethodsDeclaration { - #[webapi(method = "setStdDeviation", length = 2, callback = set_std_deviation)] - set_std_deviation: (), -} - -#[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::SVGFEGaussianBlurElement, enumerable)] -struct GaussianBlurMethodsDeclaration { - #[webapi(method = "setStdDeviation", length = 2, callback = set_std_deviation)] - set_std_deviation: (), -} - -#[derive(webidl::WebIdlArgs)] -#[webidl(prefix = "setStdDeviation")] -struct SetStdDeviationArgs { - #[webidl(required, converter = "raw")] - x: webidl::Float, - #[webidl(required, converter = "raw")] - y: webidl::Float, -} - -fn set_std_deviation<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'_, v8::Value>, -) { - let Some(parsed) = webidl::parse_args::(scope, &args) else { - return; - }; - // Both float conversions complete before a single native mutation. The - // f64 text view preserves the exact f32 values for existing live tear-offs. - let value = format!("{} {}", f64::from(parsed.x.0), f64::from(parsed.y.0)); - let Ok((runtime_ptr, handle)) = - node_runtime_and_handle_from_object_or_detached(scope, args.this()) - else { - return; - }; - let runtime = unsafe { &mut *runtime_ptr }; - let _ = runtime.set_attribute(scope, runtime_ptr, handle, "stdDeviation", &value); -} - pub(super) fn install_bindings<'s>( scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::FunctionTemplate>, diff --git a/moli-renderer-v8/src/context_bootstrap/video_codecs/config.rs b/moli-renderer-v8/src/context_bootstrap/video_codecs/config.rs index f60cf7bf765..1c185004602 100644 --- a/moli-renderer-v8/src/context_bootstrap/video_codecs/config.rs +++ b/moli-renderer-v8/src/context_bootstrap/video_codecs/config.rs @@ -4,7 +4,7 @@ use super::super::video_color_space::VideoColorSpaceInit; use crate::{blob::array_buffer_from_bytes, webidl}; -use webidl::{SnapshotPrototype, WebIdlDictionarySerialize}; +use webidl::SnapshotPrototype; fn codec_is_empty(codec: &webidl::DomString16) -> bool { codec diff --git a/moli-renderer-v8/src/context_bootstrap/video_color_space.rs b/moli-renderer-v8/src/context_bootstrap/video_color_space.rs index d901014cb88..14a8f71d035 100644 --- a/moli-renderer-v8/src/context_bootstrap/video_color_space.rs +++ b/moli-renderer-v8/src/context_bootstrap/video_color_space.rs @@ -1,7 +1,5 @@ //! Immutable color metadata, independent of video decoding and rendering. -use webidl::{SnapshotPrototype, WebIdlDictionarySerialize}; - use crate::{ util::{get_private_value, throw_type_error, v8str}, web_api_interfaces, webidl, diff --git a/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs b/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs index a8effd2d9d6..629ea43735e 100644 --- a/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs +++ b/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs @@ -45,7 +45,7 @@ struct StoragePrototypeMetadataDeclaration { } #[derive(Default, WebApiObject)] -#[webapi(plain, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(plain, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct StorageAliasesDeclaration { #[webapi(accessor_property = "localStorage", getter = window_local_storage_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] local_storage: (), diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors.rs index 0ba2d9b5678..435ea583e39 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors.rs @@ -51,6 +51,7 @@ pub(super) use surface::{ window_screen_getter, window_scroll_x_getter, window_scroll_y_getter, window_self_getter, window_speech_synthesis_getter, window_visual_viewport_getter, window_window_getter, }; + pub(crate) use values::{ window_closed_value, window_frames_value, window_length_value, window_opener_value, window_parent_value, window_self_value, window_top_value, diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs index 652856ae4a7..d13d3970734 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs @@ -67,9 +67,7 @@ pub(in crate::context_bootstrap) fn window_credentialless_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let Some(handle) = window_child_context_handle(scope, receiver) else { rv.set_bool(false); return; @@ -86,9 +84,7 @@ pub(in crate::context_bootstrap) fn window_cross_origin_isolated_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let Some(host_ptr) = window_host_ptr(scope, receiver) else { rv.set_bool(false); return; diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs index 5ff7ee74b93..cb58befe3f1 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs @@ -1,4 +1,4 @@ -use super::helpers::{window_child_context_handle, window_host_ptr, window_receiver}; +use super::helpers::{window_child_context_handle, window_host_ptr}; use crate::{ document_runtime::DomHandle, native_bridge::{PageScriptHost, WindowEnvironmentSettings}, @@ -20,16 +20,16 @@ pub(in crate::context_bootstrap) fn window_document_getter_template<'s>( scope: &mut v8::PinScope<'s, '_, ()>, cache_property: Option>, ) -> v8::Local<'s, v8::FunctionTemplate> { + let callback = ::accessor_getter_callback("document") + .expect("declared Window.document getter"); let template = match cache_property { Some(cache_property) => { - v8::FunctionTemplate::new_with_cache(scope, window_document_getter, cache_property) + v8::FunctionTemplate::new_with_cache_raw(scope, callback, cache_property) } - None => v8::FunctionTemplate::new(scope, window_document_getter), + None => v8::FunctionTemplate::new_raw(scope, callback), }; template.remove_prototype(); - // WindowProxy checks ordinary property reads before using the cache. - // Explicit getter calls must reach our receiver check in the callee's - // realm so a borrowed getter creates errors with the correct intrinsic. template } @@ -82,9 +82,7 @@ pub(in crate::context_bootstrap) fn window_document_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let Some(context) = receiver.get_creation_context(scope) else { rv.set_null(); return; diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs index bdd63a5747f..9f4a5bad30d 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs @@ -242,15 +242,16 @@ fn window_named_access_value<'s>( } let host_ptr = window_host_ptr(scope, holder)?; let host = unsafe { &*host_ptr }; - let child_handle = window_current_dispatch_scope(scope, holder, host)?.child_window(); + let dispatch_scope = window_current_dispatch_scope(scope, holder, host)?; + let child_handle = dispatch_scope.child_window(); // Browsing-context names win over document id/name exposure, matching the // Window named access ordering. Both paths are fast miss paths now: child // contexts return immediately when empty, and document name lookup is indexed. let named_child = host.child_browsing_context_named_object_handle(child_handle, &key_name); - if let Some(handle) = named_child - && host.child_browsing_context_child_is_same_origin(child_handle, handle) - && let Some(window) = - unsafe { &mut *host_ptr }.child_browsing_context_window_wrapper(scope, handle) + if let Some(handle) = + host.child_browsing_context_named_child_handle_for_scope(dispatch_scope, &key_name) + && let Some(window) = unsafe { &mut *host_ptr } + .child_browsing_context_window_proxy_for_accessing_context(scope, handle) { let context = scope.get_current_context(); let window = @@ -259,10 +260,7 @@ fn window_named_access_value<'s>( return Some(window.into()); } let host = unsafe { &*host_ptr }; - let document = match child_handle { - Some(handle) => host.child_browsing_context_document_handle(handle)?, - None => host.document_handle(), - }; + let document = super::helpers::window_document_handle(scope, holder, host)?; let handles = window_named_item_handles(host.dom_host(), document, &key_name); if !handles.is_empty() && let Some(handle) = named_child diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/surface.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/surface.rs index 942307a1cb4..159d1c95968 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/surface.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/surface.rs @@ -60,9 +60,7 @@ fn set_receiver_slot_or_undefined<'s>( slot: &'static str, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, args) else { - return; - }; + let receiver = args.this(); let value = if let Some(value) = window_hidden_value(scope, receiver, slot) { Some(value) } else { @@ -117,9 +115,7 @@ pub(in crate::context_bootstrap) fn window_opener_setter<'s>( args: v8::FunctionCallbackArguments<'s>, _rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = args.get(0); if value.is_null() { if let Some(host_ptr) = window_host_ptr(scope, receiver) { @@ -156,9 +152,7 @@ pub(in crate::context_bootstrap) fn window_inner_width_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let width = window_inner_surface_width(scope, receiver); rv.set(v8::Number::new(scope, width).into()); } @@ -168,9 +162,7 @@ pub(in crate::context_bootstrap) fn window_inner_height_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let height = window_inner_surface_height(scope, receiver); rv.set(v8::Number::new(scope, height).into()); } @@ -180,9 +172,7 @@ pub(in crate::context_bootstrap) fn window_outer_width_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = window_host_ptr(scope, receiver) .and_then(|host_ptr| unsafe { &*host_ptr }.viewport_surface()) .map_or(DEFAULT_WINDOW_SURFACE_PROFILE.inner_width, |v| { @@ -196,9 +186,7 @@ pub(in crate::context_bootstrap) fn window_outer_height_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = window_host_ptr(scope, receiver) .and_then(|host_ptr| unsafe { &*host_ptr }.viewport_surface()) .map_or(DEFAULT_WINDOW_SURFACE_PROFILE.inner_height, |v| { @@ -212,9 +200,7 @@ pub(in crate::context_bootstrap) fn window_device_pixel_ratio_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = window_host_ptr(scope, receiver) .and_then(|host_ptr| unsafe { &*host_ptr }.viewport_surface()) .map_or(DEFAULT_WINDOW_SURFACE_PROFILE.device_pixel_ratio, |v| { @@ -228,9 +214,7 @@ pub(in crate::context_bootstrap) fn window_scroll_x_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = window_hidden_value(scope, receiver, WINDOW_SCROLL_X_SLOT) .and_then(|value| value.number_value(scope)) .unwrap_or(0.0); @@ -242,9 +226,7 @@ pub(in crate::context_bootstrap) fn window_scroll_y_getter<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(receiver) = window_receiver(scope, &args) else { - return; - }; + let receiver = args.this(); let value = window_hidden_value(scope, receiver, WINDOW_SCROLL_Y_SLOT) .and_then(|value| value.number_value(scope)) .unwrap_or(0.0); diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/values.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/values.rs index 28e721c7e4e..822176d2072 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/values.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/values.rs @@ -1,9 +1,7 @@ -use super::helpers::{ - window_current_dispatch_scope, window_hidden_value, window_host_ptr, window_is_closed, -}; +use super::helpers::{window_hidden_value, window_host_ptr, window_is_closed}; use super::*; -pub(super) fn window_alias_value<'s>( +pub(in crate::context_bootstrap) fn window_alias_value<'s>( scope: &mut v8::PinScope<'s, '_>, receiver: v8::Local<'s, v8::Object>, slot: &'static str, diff --git a/moli-renderer-v8/src/context_bootstrap/window_events/install.rs b/moli-renderer-v8/src/context_bootstrap/window_events/install.rs index e1383f02a6f..8100a506047 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_events/install.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_events/install.rs @@ -85,7 +85,7 @@ pub(crate) fn clear_simple_window_event_handler_values<'s>( } #[derive(Default, WebApiObject)] -#[webapi(fragment, prototype = "Window", receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(fragment, prototype = "Window", receiver = crate::context_bootstrap::is_window_receiver)] struct WindowGlobalEventHandlerAccessorsDeclaration { #[webapi( accessor_property, diff --git a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs index b0af08c1485..4b929c0158f 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs @@ -161,12 +161,6 @@ pub(in crate::context_bootstrap) fn bound_callback_data_item<'s>( // The original getter can return its captured SameObject after retirement. // A live receiver, including a reused WindowProxy, must pass authorization // before any private cache read or entry into its relevant Realm. - if !original_retired_receiver - && !crate::native_bridge::caller_can_access_window(scope, args.this()) - { - crate::native_bridge::throw_cross_origin_location_security_error(scope); - return None; - } let Some(item) = index.and_then(|index| items.get(index)).copied() else { throw_type_error(scope, &format!("Invalid callback data for {context}.")); return None; diff --git a/moli-renderer-v8/src/context_bootstrap/window_template.rs b/moli-renderer-v8/src/context_bootstrap/window_template.rs index 782324cbb85..236d7245663 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_template.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_template.rs @@ -39,7 +39,7 @@ pub(in crate::context_bootstrap) fn is_window_named_properties_object<'s>( } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowEarlyTemplateMethodsDeclaration { #[webapi( method, @@ -74,7 +74,6 @@ struct WindowEarlyTemplateMethodsDeclaration { clear_interval: (), #[webapi(method, length = 1, callback = window_host::window_post_message_callback)] - #[webapi(receiver_access_check = false)] post_message: (), #[webapi( @@ -107,15 +106,12 @@ struct WindowEarlyTemplateMethodsDeclaration { open: (), #[webapi(method, length = 0, callback = window_close_callback)] - #[webapi(receiver_access_check = false)] close: (), #[webapi(method, length = 0, callback = window_focus_callback)] - #[webapi(receiver_access_check = false)] focus: (), #[webapi(method, length = 0, callback = window_blur_callback)] - #[webapi(receiver_access_check = false)] blur: (), #[webapi(method, length = 0, callback = window_const_false_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] @@ -123,7 +119,7 @@ struct WindowEarlyTemplateMethodsDeclaration { } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowObsoleteTemplateMethodsDeclaration { #[webapi(method, length = 0, callback = window_obsolete_noop_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] capture_events: (), @@ -133,13 +129,14 @@ struct WindowObsoleteTemplateMethodsDeclaration { } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowPostNetworkTemplateMethodsDeclaration { #[webapi( method = "createImageBitmap", length = 1, callback = window_create_image_bitmap_callback, - returns_promise, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] + returns_promise, + access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] create_image_bitmap: (), #[webapi(method, length = 0, callback = window_alert_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] @@ -203,43 +200,37 @@ struct WindowPostNetworkTemplateMethodsDeclaration { } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowSelectionTemplateMethodsDeclaration { #[webapi(method, length = 0, callback = window_get_selection_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] get_selection: (), } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowMediaTemplateMethodsDeclaration { #[webapi(method, length = 1, callback = window_match_media_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] match_media: (), } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowIdentityAccessorsDeclaration { #[webapi(accessor_property, getter = window_closed_getter)] - #[webapi(receiver_access_check = false)] closed: (), #[webapi(accessor_property, getter = window_window_getter)] - #[webapi(receiver_access_check = false)] window: (), #[webapi(accessor_property = "self", getter = window_self_getter)] - #[webapi(receiver_access_check = false)] self_: (), #[webapi(accessor_property, getter = window_top_getter)] - #[webapi(receiver_access_check = false)] top: (), #[webapi(accessor_property, getter = window_parent_getter)] - #[webapi(receiver_access_check = false)] parent: (), #[webapi(accessor_property, getter = window_frames_getter)] - #[webapi(receiver_access_check = false)] frames: (), #[webapi( @@ -255,7 +246,6 @@ struct WindowIdentityAccessorsDeclaration { getter = window_location_getter, setter = window_location_setter )] - #[webapi(receiver_access_check = false)] location: (), #[webapi(accessor_property, getter = window_console_getter)] @@ -291,78 +281,75 @@ struct WindowIdentityAccessorsDeclaration { } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowPostRuntimeAccessorsDeclaration { - #[webapi(accessor_property, getter = window_opener_getter, setter = window_opener_setter)] - #[webapi(receiver_access_check = "setter")] + #[webapi(accessor_property, getter = window_opener_getter, setter = window_opener_setter, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] opener: (), - #[webapi(accessor_property, getter = window_inner_width_getter)] + #[webapi(accessor_property, getter = window_inner_width_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] inner_width: (), - #[webapi(accessor_property, getter = window_inner_height_getter)] + #[webapi(accessor_property, getter = window_inner_height_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] inner_height: (), - #[webapi(accessor_property, getter = window_outer_width_getter)] + #[webapi(accessor_property, getter = window_outer_width_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] outer_width: (), - #[webapi(accessor_property, getter = window_outer_height_getter)] + #[webapi(accessor_property, getter = window_outer_height_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] outer_height: (), - #[webapi(accessor_property, getter = window_device_pixel_ratio_getter)] + #[webapi(accessor_property, getter = window_device_pixel_ratio_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] device_pixel_ratio: (), - #[webapi(accessor_property, getter = window_credentialless_getter)] + #[webapi(accessor_property, getter = window_credentialless_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] credentialless: (), #[webapi( accessor_property = "crossOriginIsolated", - getter = window_cross_origin_isolated_getter - )] + getter = window_cross_origin_isolated_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] cross_origin_isolated: (), - #[webapi(accessor_property, getter = window_navigator_getter)] + #[webapi(accessor_property, getter = window_navigator_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] navigator: (), - #[webapi(accessor_property, getter = window_history_getter)] + #[webapi(accessor_property, getter = window_history_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] history: (), #[webapi( accessor_property, getter = window_navigation_getter, - setter = window_navigation_setter, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] + setter = window_navigation_setter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] navigation: (), - #[webapi(accessor_property, getter = window_screen_getter)] + #[webapi(accessor_property, getter = window_screen_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] screen: (), #[webapi( accessor_property = "speechSynthesis", - getter = window_speech_synthesis_getter - )] + getter = window_speech_synthesis_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] speech_synthesis: (), - #[webapi(accessor_property, getter = window_performance_getter)] + #[webapi(accessor_property, getter = window_performance_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] performance: (), - #[webapi(accessor_property, getter = window_visual_viewport_getter)] + #[webapi(accessor_property, getter = window_visual_viewport_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] visual_viewport: (), - #[webapi(accessor_property, getter = window_scroll_x_getter)] + #[webapi(accessor_property, getter = window_scroll_x_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] scroll_x: (), - #[webapi(accessor_property, getter = window_scroll_y_getter)] + #[webapi(accessor_property, getter = window_scroll_y_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] scroll_y: (), - #[webapi(accessor_property, getter = window_scroll_x_getter)] + #[webapi(accessor_property, getter = window_scroll_x_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] page_x_offset: (), - #[webapi(accessor_property, getter = window_scroll_y_getter)] + #[webapi(accessor_property, getter = window_scroll_y_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] page_y_offset: (), } #[derive(WebApiFunctionTemplate)] -#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)] +#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)] struct WindowStorageAccessorsDeclaration { #[webapi(accessor_property, getter = window_local_storage_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] local_storage: (), @@ -376,11 +363,10 @@ struct WindowStorageAccessorsDeclaration { )] indexed_db: (), - #[webapi(accessor_property, getter = window_custom_elements_getter)] + #[webapi(accessor_property, getter = window_custom_elements_getter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] custom_elements: (), #[webapi(accessor_property, getter = window_length_getter)] - #[webapi(receiver_access_check = false)] length: (), } diff --git a/moli-renderer-v8/src/definitions.rs b/moli-renderer-v8/src/definitions.rs index 0b157b934b0..38947947b94 100644 --- a/moli-renderer-v8/src/definitions.rs +++ b/moli-renderer-v8/src/definitions.rs @@ -1,6 +1,4 @@ pub(crate) use crate::util::{ - define_non_enumerable_static_bool_property as define_non_enumerable_bool_property, - define_non_enumerable_static_number_property as define_non_enumerable_number_property, define_non_enumerable_static_property as define_non_enumerable_value_property, define_non_enumerable_static_string_property as define_non_enumerable_string_property, }; diff --git a/moli-renderer-v8/src/module_runtime/fetch_context.rs b/moli-renderer-v8/src/module_runtime/fetch_context.rs index 695c9210e1b..6b8d5c11d68 100644 --- a/moli-renderer-v8/src/module_runtime/fetch_context.rs +++ b/moli-renderer-v8/src/module_runtime/fetch_context.rs @@ -161,7 +161,7 @@ impl NativeModuleFetchContext { crate::network_host::FetchResponseRequest { method: "GET", mode: request.request_mode, - redirect_mode: request.redirect_mode, + redirect_mode: request.redirect_mode(), } .network_response_filter( &self.request_origin, diff --git a/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs index 413fea667df..5e87a666bf8 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/animation_frames.rs @@ -13,10 +13,7 @@ use crate::{ v8_execution_watchdog::{ V8ExecutionWatchdog, V8ExecutionWatchdogKind, V8ExecutionWatchdogOutcome, }, - window_webidl_callback::{ - WindowWebIdlCallbackFunction, WindowWebIdlCallbackFunctionOutcome, - invoke_window_webidl_callback_function, - }, + window_webidl_callback::WindowWebIdlCallbackFunction, }; use super::rendering_updates::PendingRenderingUpdatePayload; @@ -382,7 +379,9 @@ impl PageScriptHost { let Some(callback) = callback else { continue; }; - let prepared = callback.prepare(scope); + let Some(prepared) = callback.prepare_execution(scope, host_ptr, None) else { + continue; + }; let watchdog = V8ExecutionWatchdog::arm( V8ExecutionWatchdogKind::AnimationFrameCallback, scope.thread_safe_handle(), @@ -391,18 +390,22 @@ impl PageScriptHost { let execution_scope = crate::script_cleanup::ScriptExecutionScope::enter(scope); let receiver = v8::undefined(scope).into(); let argument = v8::Number::new(scope, timestamp).into(); - let result = invoke_window_webidl_callback_function( + let result = prepared.invoke_with_report( scope, - host_ptr, "requestAnimationFrame callback", "animation frame callback threw", "requestAnimationFrame callback", - &prepared, receiver, &[argument], ); + let attempted = !matches!( + result, + crate::webidl_callback_execution::WebIdlCallbackExecutionOutcome::Unavailable + ); if !scope.is_execution_terminating() - && let WindowWebIdlCallbackFunctionOutcome::Threw(report) = result + && let crate::webidl_callback_execution::WebIdlCallbackExecutionOutcome::Failed( + report, + ) = result { crate::host::report_window_timer_exception( scope, @@ -413,10 +416,11 @@ impl PageScriptHost { } drop(execution_scope); crate::script_cleanup::perform_callback_cleanup_checkpoint(scope); - if watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut { + let watchdog_outcome = watchdog.disarm(); + if watchdog_outcome == V8ExecutionWatchdogOutcome::TimedOut { tracing::warn!("animation frame callback exceeded its execution deadline"); } - invoked = true; + invoked |= attempted; } dispatch_scope.restore(scope, previous_scope); invoked diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs index a594bddb100..3202d0023fc 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs @@ -1,3 +1,4 @@ +pub(crate) use window::cross_origin_location_replace_function; mod document; pub(in crate::native_bridge::context_host) mod document_slots; mod isolated_world; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs index b01f06c2eff..77d19cec882 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs @@ -46,7 +46,11 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, handle: DomHandle, ) -> Option> { - self.refresh_child_browsing_context(scope, handle); + // Child navigables belong to insertion/parser lifecycle. A read must + // not create an unprocessed sibling during another frame's load event. + if !self.child_browsing_contexts.contains_key(&handle) { + return None; + } if !self.frame_owner_can_access_content_document(handle) { return None; } @@ -230,15 +234,6 @@ impl PageScriptHost { .set_detached_content_document(scope, handle, document); } - pub(crate) fn cached_detached_iframe_content_window<'s>( - &self, - scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, - ) -> Option> { - self.child_window_proxy_records - .detached_content_window(scope, handle) - } - pub(crate) fn set_cached_detached_iframe_content_window( &mut self, scope: &mut v8::PinScope<'_, '_>, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs index aa28f4d9fa8..ddde74c4383 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs @@ -67,7 +67,7 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn initialize_ch validate_child_window_realm_snapshot(host, &snapshot)?; bind_document(host, scope, &snapshot, document)?; - Ok(ChildWindowRealmProjection { top, document }) + Ok(ChildWindowRealmProjection { document }) } pub(in crate::native_bridge::context_host::child_frame_runtime) fn rebind_child_window_realm_document_state< diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/model.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/model.rs index 5b3f0cb6ac1..a1f1bbb6a16 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/model.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/model.rs @@ -55,7 +55,6 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) struct ChildWind pub(in crate::native_bridge::context_host::child_frame_runtime) struct ChildWindowRealmProjection< 's, > { - pub(in crate::native_bridge::context_host::child_frame_runtime) top: v8::Local<'s, v8::Object>, pub(in crate::native_bridge::context_host::child_frame_runtime) document: v8::Local<'s, v8::Object>, } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs index 4a50284ad08..7f61d821463 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs @@ -26,6 +26,7 @@ use std::{ }; mod cross_origin_bindings; +pub(crate) use cross_origin_bindings::cross_origin_location_replace_function; mod location; use cross_origin_bindings::*; @@ -116,14 +117,6 @@ impl ChildWindowProxyRecords { self.records.get_mut(&handle)?.facade_context.take() } - fn clear_retired_realm_projections(&mut self, handle: DomHandle) { - let Some(record) = self.records.get_mut(&handle) else { - return; - }; - record.cross_origin_endpoint_projections.clear(); - record.realm_top_window_wrapper = None; - } - pub(in crate::native_bridge::context_host) fn promote_shell_to_live( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -321,16 +314,6 @@ impl ChildWindowProxyRecords { .insert(handle, v8::Weak::new(scope, document)); } - pub(in crate::native_bridge::context_host) fn detached_content_window<'s>( - &self, - scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, - ) -> Option> { - self.detached_content_window_wrappers - .get(&handle) - .and_then(|wrapper| wrapper.to_local(scope)) - } - pub(in crate::native_bridge::context_host) fn set_detached_content_window( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -634,7 +617,11 @@ pub(crate) fn synthetic_window_context_can_access<'s>( else { return true; }; - let Ok(host_ptr) = crate::native_bridge::runtime_ptr_from_object(scope, window) else { + let Some(host_ptr) = window + .get_creation_context(scope) + .and_then(crate::util::context_host_ptr_from_context_slot) + .or_else(|| crate::native_bridge::runtime_ptr_from_object(scope, window).ok()) + else { return false; }; if crate::util::context_host_ptr_from_context_slot(accessing_context) != Some(host_ptr) { @@ -671,17 +658,19 @@ pub(crate) fn caller_can_access_window<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, ) -> bool { + let accessing = cross_origin_accessing_context(scope); + if let Some(accessed) = window.get_creation_context(scope) + && window.strict_equals(accessed.global(scope).into()) + && crate::util::context_host_ptr_from_context_slot(accessed).is_some() + { + return contexts_can_script_access(scope, accessing, accessed); + } if crate::native_bridge::lightweight_popup_id_from_window(scope, window).is_some() { - return synthetic_window_context_can_access( - scope, - cross_origin_accessing_context(scope), - window, - ); + return synthetic_window_context_can_access(scope, accessing, window); } let Some(accessed) = window.get_creation_context(scope) else { return false; }; - let accessing = cross_origin_accessing_context(scope); contexts_can_script_access(scope, accessing, accessed) } @@ -998,12 +987,6 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_, ()>, handle: DomHandle, ) -> bool { - // Endpoint projections contain functions from the outgoing Realm. - // Clear them for both same-origin and cross-origin navigation; a - // successor must not reuse a parent's postMessage function whose - // creating child Realm has already retired. - self.child_window_proxy_records - .clear_retired_realm_projections(handle); // A same-origin caller can retain functions from the retired inner // global. Keep that proxy detached until the replacement LocalWindow // takes it over so those closures continue to resolve against their @@ -1570,28 +1553,6 @@ impl PageScriptHost { ) -> Option> { self.lightweight_popup_window(scope, popup_id) } - - fn cross_origin_window_endpoint_projection_for_child<'s>( - &mut self, - scope: &mut v8::PinScope<'s, '_>, - _accessing_handle: DomHandle, - endpoint: PendingWindowMessageEndpoint, - ) -> Option> { - match endpoint { - PendingWindowMessageEndpoint::TopWindow => { - let dispatch = super::super::OwnerDispatchScope::Top; - let owner = self.current_window_execution_context_owner(dispatch)?; - let (_, context) = self.window_execution_context(scope, owner, dispatch)?; - Some(context.global(scope)) - } - PendingWindowMessageEndpoint::ChildWindow(handle) => { - self.child_browsing_context_cross_origin_window_proxy(scope, handle) - } - PendingWindowMessageEndpoint::LightweightPopup(popup_id) => { - self.lightweight_popup_window(scope, popup_id) - } - } - } } impl PageScriptHost { @@ -1895,19 +1856,6 @@ fn get_cross_origin_proxy_private_value<'s>( get_private_value(scope, storage, slot) } -fn set_cross_origin_window_self_identity_slots( - scope: &mut v8::PinScope<'_, '_>, - window: v8::Local<'_, v8::Object>, - identity: v8::Local<'_, v8::Object>, -) { - set_cross_origin_object_slot(scope, window, "self", identity.into()); - set_cross_origin_object_slot(scope, window, "window", identity.into()); - set_cross_origin_object_slot(scope, window, "globalThis", identity.into()); - set_cross_origin_object_slot(scope, window, "parent", identity.into()); - set_cross_origin_object_slot(scope, window, "top", identity.into()); - set_cross_origin_object_slot(scope, window, "frames", identity.into()); -} - fn wrap_cross_origin_window_with_has_trap<'s>( scope: &mut v8::PinScope<'s, '_>, target: v8::Local<'s, v8::Object>, @@ -2368,7 +2316,7 @@ fn cross_origin_location_proxy_set_callback<'s>( fn cross_origin_window_close_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, - rv: v8::ReturnValue<'_, v8::Value>, + rv: v8::ReturnValue<'s, v8::Value>, ) { if crate::native_bridge::lightweight_popup_id_from_window(scope, args.this()).is_some() { super::super::popups::lightweight_popup_close_callback(scope, args, rv); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs index bfc65cd23b3..4b50569e016 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs @@ -49,6 +49,17 @@ pub(super) struct LocationMembers { replace: (), } +pub(crate) fn cross_origin_location_replace_function<'s>( + scope: &mut v8::PinScope<'s, '_>, +) -> Option> { + let moli_webapi_declare::CrossOriginProperty::Method { function, .. } = + LocationMembers::cross_origin_property("replace")? + else { + return None; + }; + function.get(scope) +} + fn is_location_receiver<'s>( scope: &mut v8::PinScope<'s, '_>, receiver: v8::Local<'s, v8::Object>, @@ -77,7 +88,6 @@ fn set_href_value<'s>( /// supplies parent/top and children while a replacement document is pending. struct WindowTarget<'s> { window: v8::Local<'s, v8::Object>, - context: v8::Local<'s, v8::Context>, host: *mut PageScriptHost, child: Option, popup: Option, @@ -96,7 +106,6 @@ impl<'s> WindowTarget<'s> { { return Some(Self { window: receiver, - context, host, child: None, popup: Some(popup), @@ -128,7 +137,6 @@ impl<'s> WindowTarget<'s> { }; Some(Self { window: context.global(scope), - context, host, child, popup: None, @@ -136,27 +144,10 @@ impl<'s> WindowTarget<'s> { }) } - fn sync_children(&self, scope: &mut v8::PinScope<'s, '_>) { - let host = unsafe { &mut *self.host }; - let document = if let Some(popup) = self.popup { - host.lightweight_popup_document_handle(popup) - } else { - match self.child { - Some(handle) => host.child_browsing_context_document_handle(handle), - None => Some(host.document_handle()), - } - }; - let scope = &mut v8::ContextScope::new(scope, self.context); - if let Some(document) = document { - host.sync_child_browsing_context_subtree(scope, document); - } - } - - fn children(&self, scope: &mut v8::PinScope<'s, '_>) -> Vec { + fn children(&self, _scope: &mut v8::PinScope<'s, '_>) -> Vec { if self.closed { return Vec::new(); } - self.sync_children(scope); let host = unsafe { &*self.host }; if let Some(popup) = self.popup { return host @@ -192,7 +183,6 @@ impl<'s> WindowTarget<'s> { if self.closed || name.is_empty() { return None; } - self.sync_children(scope); let host = unsafe { &mut *self.host }; let handle = if let Some(popup) = self.popup { host.child_browsing_context_named_child_handle_for_scope( diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs index 0b31f4e6d65..7becdc9cfaa 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs @@ -151,6 +151,10 @@ fn navigate_cross_origin_child<'s>( { return None; } + let initiator_context = scope + .get_incumbent_context() + .unwrap_or_else(|| scope.get_current_context()); + let initiator = host.window_dispatch_scope_for_context(scope, initiator_context); // A foreign initiator navigates the browsing context, without firing a // destination navigate event or editing the outgoing Window's local history. Some(match kind { @@ -163,9 +167,16 @@ fn navigate_cross_origin_child<'s>( handle, target.as_str(), true, + initiator, ), crate::context_bootstrap::LocationNavigationKind::Reload => host - .queue_child_browsing_context_reload_from_existing_seed(scope, handle, target.as_str()), + .queue_child_browsing_context_navigation_without_seed_update( + scope, + handle, + target.as_str(), + None, + initiator, + ), }) } @@ -184,17 +195,40 @@ pub(super) fn window_location<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, ) -> Option> { - if caller_can_access_window(scope, window) { - return get_private_value(scope, window, WINDOW_LOCATION_SLOT); + if let Some(location) = native_window_location(scope, window) { + return Some(location.into()); } shared_cross_origin_location(scope, window).map(Into::into) } +fn native_window_location<'s>( + scope: &mut v8::PinScope<'s, '_>, + window: v8::Local<'s, v8::Object>, +) -> Option> { + let context = window.get_creation_context(scope)?; + let scope = &mut v8::ContextScope::new(scope, context); + let global = context.global(scope); + get_private_value(scope, global, WINDOW_LOCATION_SLOT) + .and_then(|value| v8::Local::::try_from(value).ok()) +} + pub(super) fn set_window_location<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, value: v8::Local<'s, v8::Value>, ) -> Option<()> { + // Keep the native Location's identity and checked exotic surface across + // origins. Its setter preserves entry/incumbent settings and validates + // the exact Document again after argument conversion. + if let Some(location) = native_window_location(scope, window) { + crate::context_bootstrap::navigate_borrowed_location( + scope, + location, + value, + crate::context_bootstrap::LocationNavigationKind::Assign, + ); + return Some(()); + } let block_javascript = !caller_can_access_window(scope, window); navigate_window( scope, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs index f99239c4f07..457da88b8d1 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs @@ -58,7 +58,8 @@ impl PageScriptHost { .window_name(); if name.is_empty() || !seen.insert(name.to_owned()) - || !self.child_browsing_context_child_is_same_origin(Some(handle), child_handle) + || self.child_browsing_context_named_child_handle(Some(handle), name) + != Some(child_handle) { return None; } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs index 6ccff557790..d20c4815d31 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs @@ -140,7 +140,7 @@ impl PageScriptHost { .collect() } - fn window_child_browsing_context_handles_for_document( + pub(in crate::native_bridge::context_host) fn window_child_browsing_context_handles_for_document( &self, document: DomHandle, ) -> Vec { @@ -243,25 +243,10 @@ impl PageScriptHost { parent: Option, key: &str, ) -> Option { - let handle = self.child_browsing_context_named_object_handle(parent, key)?; - // Deduplicate before filtering by origin: a cross-origin first match - // must not expose a later same-origin child with the same target name. - self.child_browsing_context_child_is_same_origin(parent, handle) - .then_some(handle) - } - - pub(crate) fn child_browsing_context_child_is_same_origin( - &self, - parent: Option, - child: DomHandle, - ) -> bool { - let parent = match parent { - Some(parent) => self.child_window_access_origin(parent), - None => self.main_window_access_origin(), - }; - parent - .zip(self.child_window_access_origin(child)) - .is_some_and(|(parent, child)| parent.is_same_origin(&child)) + self.child_browsing_context_named_child_handle_for_scope( + parent.map_or(OwnerDispatchScope::Top, OwnerDispatchScope::Child), + key, + ) } // Named objects also include cross-origin children when a Document's @@ -305,7 +290,7 @@ impl PageScriptHost { self.child_browsing_context_direct_host_handles(parent) } OwnerDispatchScope::Top => { - self.top_level_child_browsing_context_handles_in_frame_tree_order() + self.top_level_child_browsing_context_handles_in_document_order() } OwnerDispatchScope::LightweightPopup(id) => self .window_child_browsing_context_handles_for_document( diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs index aa19d71839a..c76a8b04de5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs @@ -2311,7 +2311,13 @@ impl PageScriptHost { .retained_current_element_state(unsafe { &*dom_host }, element) } - pub(crate) fn set_select_value(&mut self, handle: DomHandle, value: &str) -> bool { + pub(crate) fn set_select_value( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + handle: DomHandle, + value: impl Into, + ) -> bool { // Capture selected peers before the native multi-option commit. The // same wrapper serves the Web setter and native autofill. let old_states = self diff --git a/moli-renderer-v8/src/native_bridge/context_host/media_playback/video.rs b/moli-renderer-v8/src/native_bridge/context_host/media_playback/video.rs index 6221048d341..95382f8fd2c 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/media_playback/video.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/media_playback/video.rs @@ -228,6 +228,39 @@ pub(in crate::native_bridge::context_host) struct MediaVideoDecodeTask { } impl PageScriptHost { + #[cfg(test)] + pub(crate) fn media_video_state_for_test(&self, media: DomHandle) -> serde_json::Value { + let Some(state) = self.media_playback.elements.get(&media) else { + return serde_json::json!({"state": "absent"}); + }; + let Some(video) = state.video.as_ref() else { + return serde_json::json!({"video": "absent", "epoch": state.epoch}); + }; + let completion_ready = video.pending.as_ref().and_then(|pending| { + let task = self.media_element_events.pending(pending.id)?; + match task.payload() { + PendingMediaElementEventPayload::VideoDecode(task) => { + Some(task.completion.lock().is_some()) + } + _ => None, + } + }); + serde_json::json!({ + "current": self.playback_is_current(media, state.document, state.epoch), + "target": format!("{:?}", state.target), + "currentTarget": state.target.map(|target| format!("{:?}", self.current_media_window_task_target(target.dispatch_scope()))), + "desired": video.desired_position, + "decoded": video.decoded_position, + "pending": video.pending.as_ref().map(|pending| format!("{:?}", pending.id)), + "completionReady": completion_ready, + "workerClosed": video.worker.wake.is_closed(), + "workerFinished": video.worker.task.is_finished(), + "requestQueued": video.worker.request.lock().is_some(), + "seekToken": video.seek_token, + "failed": video.failed, + }) + } + #[cfg(test)] pub(crate) fn video_decode_budget_probe_for_test(&self) -> VideoDecodeBudgetProbe { VideoDecodeBudgetProbe { diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index 0efbd0abf44..2a8bb9a2ea1 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -81,7 +81,8 @@ mod document_parser_owner; mod svg_smil; pub(crate) use child_frame_runtime::install_child_window_proxy_access_check_handlers; pub(crate) use child_frame_runtime::{ - install_synthetic_window_access_check_handlers, synthetic_window_context_can_access, + cross_origin_location_replace_function, install_synthetic_window_access_check_handlers, + synthetic_window_context_can_access, }; mod child_frame_snapshots; mod child_frames; diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index f53146f4b3f..a6b2fc163c3 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -10,12 +10,10 @@ use crate::navigation_document::{ use crate::{ content_security_policy::content_security_policy_forces_opaque_origin, context_bootstrap::{ - SIMPLE_EVENT_TARGET_LISTENERS_SLOT, SharedWebStorageStore, WINDOW_NAME_SLOT, - apply_local_window_location_navigation, clear_simple_window_event_handler_values, + SharedWebStorageStore, WINDOW_NAME_SLOT, apply_local_window_location_navigation, construct_original_event, construct_original_page_transition_event, - deep_clone_shared_web_storage_store, dispatch_beforeunload_for_runtime_owner, - dispatch_pagehide_for_runtime_owner, - dispatch_simple_event_target_event_with_original_target, dispatch_unload_for_runtime_owner, + deep_clone_shared_web_storage_store, + dispatch_simple_event_target_event_with_original_target, finish_cross_document_navigation_for_window, history_entry_seed_for_cross_document_location, initialize_simple_event_target, install_navigation_bootstrap_entry_for_holder, install_simple_window_event_handlers, @@ -3750,7 +3748,6 @@ impl PageScriptHost { crate::context_bootstrap::invoke_simple_event_target_listeners( scope, window, - LIGHTWEIGHT_POPUP_EVENT_LISTENERS_SLOT, event_type, event, capture, diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs b/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs index c1aa969da78..3178ceb55a6 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs @@ -164,7 +164,7 @@ impl PageScriptHost { opener: (), } .initialize(scope, window)?; - install_simple_event_target_methods(scope, window); + initialize_simple_event_target(scope, window); install_simple_window_event_handlers(scope, window); crate::context_bootstrap::install_secure_window_event_handler_accessors( scope, window, secure, diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index 5aba47111d6..40d03ed633a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -964,20 +964,6 @@ impl PageScriptHost { accessing_origin.can_access(&accessed_origin) } - pub(crate) fn current_realm_can_access_child_window( - &self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - ) -> bool { - self.current_runtime_window_execution_context_identity(scope) - .is_some_and(|accessing| { - self.window_execution_context_can_access_dispatch_scope( - accessing, - OwnerDispatchScope::Child(handle), - ) - }) - } - fn window_access_origin( &self, identity: WindowExecutionContextIdentity, @@ -1401,9 +1387,9 @@ mod tests { assert!(inherited.can_access(&WindowAccessOrigin::opaque(inherited_identity))); assert!(!inherited.can_access(&WindowAccessOrigin::opaque(distinct_identity))); assert!(!inherited.can_access(&WindowAccessOrigin::Opaque { identity: None })); - assert!(inherited.is_same_origin(&WindowAccessOrigin::opaque(inherited_identity))); - assert!(!inherited.is_same_origin(&WindowAccessOrigin::opaque(distinct_identity))); - assert!(!inherited.is_same_origin(&WindowAccessOrigin::Opaque { identity: None })); + assert!(inherited.has_same_origin(&WindowAccessOrigin::opaque(inherited_identity))); + assert!(!inherited.has_same_origin(&WindowAccessOrigin::opaque(distinct_identity))); + assert!(!inherited.has_same_origin(&WindowAccessOrigin::Opaque { identity: None })); } #[test] @@ -1415,11 +1401,11 @@ mod tests { let parent = origin("https://a.example.test:8443", Some("example.test")); let same = origin("https://a.example.test:8443", None); let relaxed = origin("https://b.example.test:9443", Some("example.test")); - assert!(parent.is_same_origin(&same)); + assert!(parent.has_same_origin(&same)); assert!(parent.can_access(&relaxed)); - assert!(!parent.is_same_origin(&relaxed)); - assert!(!parent.is_same_origin(&origin("http://a.example.test:8443", None))); - assert!(!parent.is_same_origin(&origin("https://a.example.test:9443", None))); + assert!(!parent.has_same_origin(&relaxed)); + assert!(!parent.has_same_origin(&origin("http://a.example.test:8443", None))); + assert!(!parent.has_same_origin(&origin("https://a.example.test:9443", None))); } #[test] diff --git a/moli-renderer-v8/src/native_bridge/document/custom_element_options.rs b/moli-renderer-v8/src/native_bridge/document/custom_element_options.rs index ecb3c2d5547..2686f194cb2 100644 --- a/moli-renderer-v8/src/native_bridge/document/custom_element_options.rs +++ b/moli-renderer-v8/src/native_bridge/document/custom_element_options.rs @@ -1,7 +1,6 @@ use crate::custom_elements; use crate::document_runtime::DomHandle; use crate::native_bridge::{PageScriptHost, throw_dom_exception}; -use crate::util::{throw_type_error, v8str}; use crate::web_api_interfaces; use crate::webidl; diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs index e35fb62c314..01db57ad3d2 100644 --- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs @@ -15,8 +15,7 @@ use crate::native_bridge::element::{ use crate::{ custom_elements, document_runtime::{DomHandle, EventTargetHandle}, - dom::native::{DocumentReadyState, NativeDom, Node, NodeData}, - parser::HtmlParser, + dom::native::{DocumentReadyState, Node}, util::{ call_object_method, node_wrapper_from_handle, utf16_next_scalar_boundary, utf16_previous_scalar_boundary, utf16_scalar_boundary_at_or_after, v8_string, v8str, diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rs index 24c672d018c..c2a1437e8cb 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles.rs @@ -167,22 +167,6 @@ fn popup_document_target_is_active( .is_some_and(|popup_id| runtime.lightweight_popup_is_open(popup_id)) } -fn target_context_epoch_is_current<'s>( - scope: &mut v8::PinScope<'s, '_>, - runtime: &PageScriptHost, - style: v8::Local<'s, v8::Object>, -) -> bool { - let Some(value) = get_private_value(scope, style, STYLE_DECLARATION_TARGET_CONTEXT_EPOCH_SLOT) - else { - return false; - }; - let Ok(value) = v8::Local::::try_from(value) else { - return false; - }; - let (epoch, lossless) = value.u64_value(); - lossless && epoch == runtime.style_target_context_epoch() -} - fn cache_target_empty_context<'s>( scope: &mut v8::PinScope<'s, '_>, runtime: &PageScriptHost, diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs index 3aae5432797..24273e5f99d 100644 --- a/moli-renderer-v8/src/native_bridge/mod.rs +++ b/moli-renderer-v8/src/native_bridge/mod.rs @@ -1,3 +1,4 @@ +pub(crate) use context_host::cross_origin_location_replace_function; pub(crate) mod abort; mod active_child_window; pub(super) mod bindings; diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/canvas_loaded_images.rs b/moli-renderer-v8/src/runtime/page_vm/tests/canvas_loaded_images.rs index 3518e41f7c6..cd6cac651de 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/canvas_loaded_images.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/canvas_loaded_images.rs @@ -6,56 +6,66 @@ async fn canvas_exif_orientation_survives_sources_realms_and_bitmap_copies() { let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); loader.set_image_fetch_enabled(true); - let (mut page, _resource_source, _owner_wake) = - page_vm_with_bound_task_sources_and_owner_wake( - &loader, - Url::parse("https://canvas-exif.test/")?, - ); - page.vm_mut() - .set_layout_policy(moli_page_types::LayoutPolicy::Mock); - page.vm_mut().eval(&format!( - "document.body.innerHTML='';globalThis.__exifSources={};", - include_str!("../../../../tests/fixtures/canvas-exif-sources.json"), - ))?; - page.vm_mut().eval(include_str!( - "../../../../tests/fixtures/canvas-exif-orientation.js" - ))?; - let deadline = Instant::now() + Duration::from_secs(30); - while page.vm_mut().eval("typeof __uiEventResults")? == "undefined" { - let _ = page - .run_next_child_frame_task_source_for_semantic_test() - .await; - for selector in [ - PageSelectedTaskTestSelector::ResourceCompletion, - PageSelectedTaskTestSelector::BitmapTask, - PageSelectedTaskTestSelector::DomManipulation( - PageDomManipulationTestFamily::ImageLoadEvent, - ), - ] { - let _ = page - .run_exact_selected_page_task_for_test(selector, &loader) - .await?; + let mut names = std::collections::BTreeSet::new(); + // Each scenario retains all eight orientations and all source/copy + // assertions. The shared browser fixture remains unfiltered by default. + for owner in ["main", "iframe"] { + for callee in ["main", "iframe"] { + for format in ["png", "jpg", "webp"] { + let scenario = format!("{owner}/{callee}/{format}"); + let (mut page, _resource_source, _owner_wake) = + page_vm_with_bound_task_sources_and_owner_wake( + &loader, + Url::parse("https://canvas-exif.test/")?, + ); + page.vm_mut() + .set_layout_policy(moli_page_types::LayoutPolicy::Mock); + page.vm_mut().eval(&format!( + "document.body.innerHTML='';globalThis.__exifScenario={scenario:?};globalThis.__exifSources={};", + include_str!("../../../../tests/fixtures/canvas-exif-sources.json"), + ))?; + page.vm_mut().eval(include_str!( + "../../../../tests/fixtures/canvas-exif-orientation.js" + ))?; + let deadline = Instant::now() + Duration::from_secs(30); + while page.vm_mut().eval("typeof __uiEventResults")? == "undefined" { + let _ = page + .run_next_child_frame_task_source_for_semantic_test() + .await; + for selector in [ + PageSelectedTaskTestSelector::ResourceCompletion, + PageSelectedTaskTestSelector::BitmapTask, + PageSelectedTaskTestSelector::DomManipulation( + PageDomManipulationTestFamily::ImageLoadEvent, + ), + ] { + let _ = page + .run_exact_selected_page_task_for_test(selector, &loader) + .await?; + } + anyhow::ensure!( + Instant::now() < deadline, + "EXIF scenario {scenario} did not finish: {}", + page.vm_mut().eval("__exifProgress.stage")? + ); + tokio::time::sleep(Duration::from_millis(1)).await; + } + let result: serde_json::Value = serde_json::from_str( + &page.vm_mut().eval("JSON.stringify(__uiEventResults)")?, + )?; + let checks = result["checks"].as_array().unwrap(); + let failures: Vec<_> = checks.iter().filter(|row| row["passed"] != true).collect(); + assert!(failures.is_empty(), "{scenario}: {failures:#?}"); + assert_eq!(result["total"], 200, "all orientations and sources: {scenario}"); + for check in checks { + let name = check["name"].as_str().unwrap(); + assert!(name.starts_with(&format!("{scenario}/")), "{name}"); + assert!(names.insert(name.to_owned()), "duplicate check {name}"); + } + } } - anyhow::ensure!( - Instant::now() < deadline, - "EXIF fixture did not finish: {}", - page.vm_mut().eval("__exifProgress.stage")? - ); - tokio::time::sleep(Duration::from_millis(1)).await; } - let result: serde_json::Value = - serde_json::from_str(&page.vm_mut().eval("JSON.stringify(__uiEventResults)")?)?; - let failures: Vec<_> = result["checks"] - .as_array() - .unwrap() - .iter() - .filter(|row| row["passed"] != true) - .collect(); - assert!(failures.is_empty(), "{failures:#?}"); - assert_eq!( - result["total"], 2400, - "all codecs, orientations, sources and realm pairs must run" - ); + assert_eq!(names.len(), 2400, "all codecs, orientations, sources and realm pairs must run"); Ok::<_, anyhow::Error>(()) }) .await diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/canvas_video_frames.rs b/moli-renderer-v8/src/runtime/page_vm/tests/canvas_video_frames.rs index 5c7afb5f28f..55aa072ee5c 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/canvas_video_frames.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/canvas_video_frames.rs @@ -1,6 +1,23 @@ use super::*; use base64::Engine; +fn video_frame_native_state_for_test<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let object = v8::Local::::try_from(args.get(0)).unwrap(); + let (host, handle) = + crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, object) + .unwrap(); + let state = unsafe { &*host }.media_video_state_for_test(handle); + rv.set( + crate::util::v8_string(scope, &state.to_string()) + .unwrap() + .into(), + ); +} + #[tokio::test(flavor = "current_thread")] async fn canvas_video_sources_decode_real_frames_and_follow_media_ownership() { run_page_vm_async_test(async move { @@ -23,8 +40,6 @@ async fn canvas_video_sources_decode_real_frames_and_follow_media_ownership() { }); let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; loader.set_optional_resource_fetch_enabled(crate::types::SubresourceResourceType::Video, true); - let (mut page, _source, _wake) = page_vm_with_bound_task_sources_and_owner_wake(&loader, Url::parse(&base)?); - page.vm_mut().set_layout_policy(moli_page_types::LayoutPolicy::Mock); let sources = serde_json::json!({ "data": { "pattern": format!("data:video/webm;base64,{}", base64::engine::general_purpose::STANDARD.encode(pattern)), @@ -33,23 +48,56 @@ async fn canvas_video_sources_decode_real_frames_and_follow_media_ownership() { }, "http": { "pattern": format!("{base}/pattern"), "counting": format!("{base}/counting"), "vp9": format!("{base}/vp9") }, }); - page.vm_mut().eval(&format!("document.body.innerHTML='';globalThis.__videoFrameSources={sources};"))?; - page.vm_mut().eval(include_str!("../../../../tests/fixtures/canvas-video-frames.js"))?; - let deadline = Instant::now() + Duration::from_secs(120); - while page.vm_mut().eval("typeof __uiEventResults")? == "undefined" { - let _ = page.run_next_child_frame_task_source_for_semantic_test().await; - for selector in [PageSelectedTaskTestSelector::ResourceCompletion, PageSelectedTaskTestSelector::MediaElementEvent, PageSelectedTaskTestSelector::BitmapTask] { - let _ = page.run_exact_selected_page_task_for_test(selector, &loader).await?; + let mut names = std::collections::BTreeSet::new(); + for owner in ["main", "iframe"] { + for callee in ["main", "iframe"] { + for transport in ["data", "http"] { + for residence in ["live", "windowless"] { + for canvas in ["html", "offscreen"] { + let scenario = format!("{owner}/{callee}/{transport}/{residence}/{canvas}"); + let (mut page, _source, _wake) = page_vm_with_bound_task_sources_and_owner_wake(&loader, Url::parse(&base)?); + page.vm_mut().set_layout_policy(moli_page_types::LayoutPolicy::Mock); + page.vm_mut().with_default_context_scope_for_test(|scope, _| { + let function = v8::FunctionTemplate::new(scope, video_frame_native_state_for_test).get_function(scope).unwrap(); + let global = scope.get_current_context().global(scope); + global.create_data_property(scope, crate::util::v8str(scope, "__videoFrameNativeState").into(), function.into()); + Ok(()) + })?; + page.vm_mut().eval(&format!("document.body.innerHTML='';globalThis.__videoFrameScenario={scenario:?};globalThis.__videoFrameSources={sources};"))?; + page.vm_mut().eval(include_str!("../../../../tests/fixtures/canvas-video-frames.js"))?; + let deadline = Instant::now() + Duration::from_secs(120); + while page.vm_mut().eval("typeof __uiEventResults")? == "undefined" { + let _ = page.run_next_child_frame_task_source_for_semantic_test().await; + // Complete already-ready source work before selecting a due timer. + // Keep a bounded turn so decoding cannot starve timer delivery. + for _ in 0..64 { + let mut advanced = false; + for selector in [PageSelectedTaskTestSelector::ResourceCompletion, PageSelectedTaskTestSelector::MediaElementEvent, PageSelectedTaskTestSelector::BitmapTask] { + advanced |= page.run_exact_selected_page_task_for_test(selector, &loader).await?; + } + if !advanced { break; } + } + let _ = page.run_one_due_timer_selected_task_for_test(&loader).await?; + anyhow::ensure!(Instant::now() < deadline, "video scenario {scenario} did not finish: {}", page.vm_mut().eval("__videoFrameProgress.stage")?); + tokio::time::sleep(Duration::from_millis(1)).await; + } + let result: serde_json::Value = serde_json::from_str(&page.vm_mut().eval("JSON.stringify(__uiEventResults)")?)?; + let checks = result["checks"].as_array().unwrap(); + let failures: Vec<_> = checks.iter().filter(|check| check["passed"] != true).collect(); + assert!(failures.is_empty(), "{scenario}: {failures:#?}"); + assert_eq!(result["total"], 6, "all video operations: {scenario}"); + for check in checks { + let name = check["name"].as_str().unwrap(); + assert!(name.starts_with(&format!("{scenario}/")), "{name}"); + assert!(names.insert(name.to_owned()), "duplicate check {name}"); + } + } + } + } } - let _ = page.run_one_due_timer_selected_task_for_test(&loader).await?; - anyhow::ensure!(Instant::now() < deadline, "video fixture did not finish: {}", page.vm_mut().eval("__videoFrameProgress.stage")?); - tokio::time::sleep(Duration::from_millis(1)).await; } server.abort(); - let result: serde_json::Value = serde_json::from_str(&page.vm_mut().eval("JSON.stringify(__uiEventResults)")?)?; - let failures: Vec<_> = result["checks"].as_array().unwrap().iter().filter(|check| check["passed"] != true).collect(); - assert!(failures.is_empty(), "{failures:#?}"); - assert_eq!(result["total"], 192); + assert_eq!(names.len(), 192); Ok::<_, anyhow::Error>(()) }).await.expect("decoded video sources across realms and transport paths"); } diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/media_element_event.rs b/moli-renderer-v8/src/runtime/page_vm/tests/media_element_event.rs index 58fadface2e..e34d9ead045 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/media_element_event.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/media_element_event.rs @@ -1252,13 +1252,19 @@ async fn media_canplaythrough_from_a_retired_document_does_not_checkpoint_the_re page.vm_mut().eval( r#" globalThis.retiredMediaEvents = []; -const media = document.createElement('video'); +globalThis.retiredMediaPhases = []; +const retiringFrame = document.createElement('iframe'); +document.body.append(retiringFrame); +const media = retiringFrame.contentDocument.createElement('video'); +for (const type of ['loadstart','durationchange','resize','loadedmetadata','loadeddata','canplay']) { + media.addEventListener(type, () => retiredMediaPhases.push(type)); +} media.oncanplaythrough = () => retiredMediaEvents.push('stale canplaythrough'); -document.body.append(media); +retiringFrame.contentDocument.body.append(media); media.src = 'data:video/mp4;base64,AAAAGGZ0eXBtcDQyAAAAAG1wNDJtcDQx'; "#, )?; - for _ in 0..4 { + for _ in 0..6 { let turn = page .claim_exact_selected_page_task_for_test( PageSelectedTaskTestSelector::MediaElementEvent, @@ -1267,14 +1273,20 @@ media.src = 'data:video/mp4;base64,AAAAGGZ0eXBtcDQyAAAAAG1wNDJtcDQx'; page.run_claimed_selected_page_task_for_test(turn, &loader) .await?; } + assert_eq!( + page.vm_mut().eval("retiredMediaPhases.join('|')")?, + "loadstart|durationchange|resize|loadedmetadata|loadeddata|canplay", + ); let retired = page .claim_exact_selected_page_task_for_test( PageSelectedTaskTestSelector::MediaElementEvent, ) .expect("capture the terminal task before its Document is retired"); page.vm_mut().eval( - "document.open();document.write('replacement');document.close();", + "retiringFrame.remove();document.open();document.write('replacement');document.close();", )?; + // Removing the frame retires its real LocalWindow. document.open alone + // preserves ongoing media in the same Window and is not retirement. page.vm_mut().eval_without_microtask_checkpoint_for_test( r#" globalThis.replacementMediaEvents = []; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/nested_frame_access.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/nested_frame_access.rs index cc16626b6ca..a22825e4c89 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/nested_frame_access.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/nested_frame_access.rs @@ -49,6 +49,46 @@ async fn nested_frame_windows_use_accessing_realm_without_granting_top_access() assert_eq!(server.finish_targets().await, vec!["/child"]); } +#[tokio::test] +async fn frame_content_document_uses_node_document_origin_after_document_domain_changes() { + let server = StaticHttpServer::spawn_with_bodies(vec![ + "".to_owned(), + "nested loaded".to_owned(), + ]) + .await; + let origin = server.base_url().origin().ascii_serialization(); + let loader = static_http_loader([]); + let mut vm = new_parsed_page_task_executor_test_vm( + &format!("{origin}/top"), + "top", + &loader, + ); + vm.eval(&format!( + r#" + const frame = document.createElement('iframe'); frame.id = 'outer'; + frame.src = '{origin}/outer'; document.body.append(frame); + "# + )) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(document.getElementById('outer').contentDocument?.getElementById('nested')?.contentDocument?.body?.textContent === 'nested loaded')", + "true", + "loaded independent-origin nested documents", + ) + .await; + assert_eq!( + vm.eval(&format!( + "JSON.stringify({})", + include_str!("../../../../tests/fixtures/frame-content-document-domain.js") + )) + .unwrap(), + "[true,true,true,true,true,true,true,true,true,true]", + ); + assert_eq!(server.finish_targets().await, vec!["/outer", "/nested"]); +} + #[tokio::test] async fn frame_content_document_uses_getter_realm_after_document_domain_changes() { let server = StaticHttpServer::spawn_with_bodies(vec![ diff --git a/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs b/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs index bdba3f7babd..667e87dca26 100644 --- a/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs +++ b/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs @@ -64,7 +64,11 @@ async fn cross_origin_named_children_use_the_parent_origin_and_first_document_tr ]; for (const [id, name, src] of definitions) {{ const frame = document.createElement('iframe'); - Object.assign(frame, {{id, name, src}}); + // Loaded documents publish window.name themselves. Leave their + // container name unset so embedder authorization cannot mask the + // parent-origin filtering and first-match checks below. + Object.assign(frame, {{id, src}}); + if (src === 'about:blank') frame.name = name; body.appendChild(frame); }} "#, @@ -143,7 +147,7 @@ async fn cross_origin_named_children_use_the_parent_origin_and_first_document_tr // Reordering must select the first name in the current document tree, // rather than preserving insertion order or skipping a cross-origin first. - vm.eval("document.body.appendChild(document.getElementById('duplicate-first'))") + vm.eval("document.body.moveBefore(document.getElementById('duplicate-first'), null)") .unwrap(); assert_eq!( vm.eval_in_child_default_context(observer, "top.duplicate === allowedDuplicate") diff --git a/moli-renderer-v8/src/script_vm/tests/declarative_receivers.rs b/moli-renderer-v8/src/script_vm/tests/declarative_receivers.rs index c312e9e4643..8e0f3ab8ff7 100644 --- a/moli-renderer-v8/src/script_vm/tests/declarative_receivers.rs +++ b/moli-renderer-v8/src/script_vm/tests/declarative_receivers.rs @@ -134,7 +134,7 @@ fn canvas_declarations_check_setters_before_conversion_and_keep_foreign_backing_ setter.call(canvas, 4); assert(canvas[name] === 4, 'foreign canvas setter updates receiver'); } - for (const name of ['getContext', 'convertToBlob', 'transferToImageBitmap']) check(realm, canvas, realm.OffscreenCanvas.prototype[name]); + for (const name of ['getContext', 'convertToBlob', 'transferToImageBitmap']) check(realm, canvas, realm.OffscreenCanvas.prototype[name], name === 'convertToBlob'); assert(realm.OffscreenCanvas.prototype.getContext.call(canvas, '2d') === canvas.getContext('2d'), 'foreign canvas context identity'); const bitmap = await other.createImageBitmap(canvas); getters(realm, 'ImageBitmap', bitmap, ['width', 'height']); @@ -144,12 +144,17 @@ fn canvas_declarations_check_setters_before_conversion_and_keep_foreign_backing_ const data = new other.ImageData(2, 3); getters(realm, 'ImageData', data, ['width', 'height', 'colorSpace', 'pixelFormat', 'data']); let error; - try {realm.createImageBitmap(new Proxy(canvas, {}));} catch (caught) {error = caught;} + const invalidSource = realm.createImageBitmap(new Proxy(canvas, {})); + assert(Object.getPrototypeOf(invalidSource) === realm.Promise.prototype, 'image source rejection Promise realm'); + try {await invalidSource;} catch (caught) {error = caught;} assert(Object.getPrototypeOf(error) === realm.TypeError.prototype, 'image source parameter keeps native interface check'); } return 'ok'; })().then(result => {globalThis.receiverSetup = result;}, error => {globalThis.receiverSetup = String(error);})"#).unwrap(); - assert_eq!(vm.eval("receiverSetup").unwrap(), "ok"); + assert_eq!( + vm.eval_after_selected_page_tasks("receiverSetup").unwrap(), + "ok" + ); finish_receiver_checks(&mut vm); } diff --git a/moli-renderer-v8/src/script_vm/tests/document_import_adopt_webidl.rs b/moli-renderer-v8/src/script_vm/tests/document_import_adopt_webidl.rs index 5b3d2f5df2c..7c0756d9625 100644 --- a/moli-renderer-v8/src/script_vm/tests/document_import_adopt_webidl.rs +++ b/moli-renderer-v8/src/script_vm/tests/document_import_adopt_webidl.rs @@ -23,8 +23,10 @@ fn document_import_and_adopt_use_webidl_node_and_dictionary_conversion() { vm.eval(include_str!("document_import_adopt_webidl.js")) .expect("Document import/adopt WebIDL matrix should evaluate"); assert_eq!( - vm.eval("JSON.stringify(__documentImportAdoptResults.checks.filter(row => !row.passed))") - .unwrap(), + vm.eval_after_selected_page_tasks( + "JSON.stringify(__documentImportAdoptResults.checks.filter(row => !row.passed))" + ) + .unwrap(), "[]" ); assert_eq!( diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/tables_and_document_surfaces.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/tables_and_document_surfaces.rs index 8cb6f9c490c..a6f7795999f 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/tables_and_document_surfaces.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/tables_and_document_surfaces.rs @@ -1663,26 +1663,18 @@ fn detached_iframe_windows_do_not_create_document_browsing_contexts() { outer.documentElement.appendChild(frame); const label = `${name}/${first}`; check(outer.defaultView === null, `${label}: windowless owner`); - let child; if (first === "document") { - child = frame.contentDocument; - check(child.hidden && child.visibilityState === "hidden", `${label}: before contentWindow`); + check(frame.contentDocument === null, `${label}: no child Document before contentWindow`); } - const view = frame.contentWindow; - child ||= frame.contentDocument; - check(view !== null && view.document === child, `${label}: synthetic window`); - check(child.defaultView === null, `${label}: synthetic window has no browsing context`); - check(child.hidden && child.visibilityState === "hidden", `${label}: after contentWindow`); + check(frame.contentWindow === null, `${label}: no child Window`); + check(frame.contentDocument === null, `${label}: no child Document after contentWindow`); + check(outer.defaultView === null, `${label}: getter cannot create a browsing context`); check(outer.hidden && outer.visibilityState === "hidden", `${label}: owner stays hidden`); - const nested = child.createElement("iframe"); - nested.srcdoc = "

nested

"; - child.body.appendChild(nested); - const nestedChild = nested.contentDocument; - check(nestedChild.hidden && nestedChild.visibilityState === "hidden", `${label}: nested before contentWindow`); - check(nested.contentWindow.document === nestedChild, `${label}: nested window`); - check(nested.contentWindow.parent === view, `${label}: nested compatibility parent`); - check(nestedChild.defaultView === null, `${label}: nested synthetic window has no browsing context`); - check(nestedChild.hidden && nestedChild.visibilityState === "hidden", `${label}: nested after contentWindow`); + const nested = outer.createElementNS("http://www.w3.org/1999/xhtml", "iframe"); + frame.appendChild(nested); + check(nested.contentDocument === null, `${label}: nested has no child Document`); + check(nested.contentWindow === null, `${label}: nested has no child Window`); + check(outer.hidden && outer.visibilityState === "hidden", `${label}: nested getters keep owner hidden`); } } return JSON.stringify(errors); diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/stylesheet_and_document_lifecycle.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/stylesheet_and_document_lifecycle.rs index e92408d26e6..0c95ba75a8a 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/stylesheet_and_document_lifecycle.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/stylesheet_and_document_lifecycle.rs @@ -1412,7 +1412,7 @@ yield; // Publish this scene before reading its geometry. } #[test] -fn nested_iframe_cached_viewport_units_follow_recursive_frame_resizes() { +fn nested_iframe_cached_viewport_units_follow_published_recursive_frame_resizes() { let mut vm = new_storage_test_vm("https://nested-cached-viewport-units.test/"); let before = vm @@ -1514,22 +1514,29 @@ fn nested_iframe_cached_viewport_units_follow_recursive_frame_resizes() { "#; let after = vm .eval(query) - .expect("warm queries refresh invalidated frame viewports"); - assert_eq!(after, "100|80|50|40|5px|4px|2px|5px|4px"); + .expect("warm queries reuse the published frame viewports"); + assert_eq!(after, "200|160|100|80|10px|8px|4px|10px|8px"); assert_eq!( vm.retained_style_system_update_count_for_document_for_test(inner_document), - updates + 1, - "warm observation must consume the changed viewport once" + updates, + "ordinary reads must not publish a new recursive layout" ); publish_layout_for_test(&mut vm); let refreshed = vm .eval(query) - .expect("explicit refresh retains the already current recursive frame viewports"); + .expect("explicit refresh publishes the changed recursive frame viewports"); assert_eq!(refreshed, "100|80|50|40|5px|4px|2px|5px|4px"); assert_eq!( vm.retained_style_system_update_count_for_document_for_test(inner_document), updates + 1, - "explicit refresh must not consume the viewport transition a second time", + "the published viewport transition must update the retained style world once", + ); + publish_layout_for_test(&mut vm); + assert_eq!(vm.eval(query).unwrap(), refreshed); + assert_eq!( + vm.retained_style_system_update_count_for_document_for_test(inner_document), + updates + 1, + "republication must not consume the same viewport transition twice", ); assert_eq!( vm.retained_stylist_identity_for_document_for_test(inner_document), @@ -2044,3 +2051,130 @@ fn child_parser_quirks_mode_does_not_mutate_the_top_document() { assert_eq!(result, "CSS1Compat|BackCompat"); } + +#[test] +fn nested_iframe_cached_viewport_units_follow_recursive_frame_resizes() { + let mut vm = new_storage_test_vm("https://nested-cached-viewport-units.test/"); + + let before = vm + .eval( + r#" +(() => { + const outerFrame = document.createElement('iframe'); + outerFrame.id = 'nested-viewport-outer-frame'; + outerFrame.style.cssText = 'width:200px;height:160px;border:0'; + (document.body || document.documentElement || document).appendChild(outerFrame); + + const outerWindow = outerFrame.contentWindow; + const outerDocument = outerWindow.document; + outerDocument.open(); + outerDocument.write(` + + `); + outerDocument.close(); + + const innerFrame = outerDocument.getElementById('nested-viewport-inner-frame'); + const innerWindow = innerFrame.contentWindow; + const innerDocument = innerWindow.document; + innerDocument.open(); + innerDocument.write(` + +
`); + innerDocument.close(); + + outerFrame.getBoundingClientRect(); + innerFrame.getBoundingClientRect(); + const target = innerDocument.getElementById('nested-viewport-target'); + const held = innerWindow.getComputedStyle(target); + globalThis.__nestedViewportUnitFixture = { + outerFrame, + innerFrame, + outerWindow, + innerWindow, + target, + held + }; + return [ + outerWindow.innerWidth, + outerWindow.innerHeight, + innerWindow.innerWidth, + innerWindow.innerHeight, + held.width, + held.height, + held.paddingLeft + ].join('|'); +})() +"#, + ) + .expect("nested viewport-unit styles should be cached"); + assert_eq!(before, "200|160|100|80|10px|8px|4px"); + let inner_document = child_document_handle_for_frame_id(&vm, "nested-viewport-inner-frame"); + let updates = vm.retained_style_system_update_count_for_document_for_test(inner_document); + let stylist = vm.retained_stylist_identity_for_document_for_test(inner_document); + + let query = r#" +(() => { + const { + outerFrame, + innerFrame, + outerWindow, + innerWindow, + target, + held + } = __nestedViewportUnitFixture; + outerFrame.style.width = '100px'; + outerFrame.style.height = '80px'; + outerFrame.getBoundingClientRect(); + innerFrame.getBoundingClientRect(); + const heldValues = [held.width, held.height, held.paddingLeft]; + const fresh = innerWindow.getComputedStyle(target); + return [ + outerWindow.innerWidth, + outerWindow.innerHeight, + innerWindow.innerWidth, + innerWindow.innerHeight, + ...heldValues, + fresh.width, + fresh.height + ].join('|'); +})() +"#; + let after = vm + .eval(query) + .expect("warm queries refresh invalidated frame viewports"); + assert_eq!(after, "100|80|50|40|5px|4px|2px|5px|4px"); + assert_eq!( + vm.retained_style_system_update_count_for_document_for_test(inner_document), + updates + 1, + "warm observation must consume the changed viewport once" + ); + publish_layout_for_test(&mut vm); + let refreshed = vm + .eval(query) + .expect("explicit refresh retains the already current recursive frame viewports"); + assert_eq!(refreshed, "100|80|50|40|5px|4px|2px|5px|4px"); + assert_eq!( + vm.retained_style_system_update_count_for_document_for_test(inner_document), + updates + 1, + "explicit refresh must not consume the viewport transition a second time", + ); + assert_eq!( + vm.retained_stylist_identity_for_document_for_test(inner_document), + stylist, + "recursive iframe resizing must retain the innermost Stylist", + ); +} diff --git a/moli-renderer-v8/src/script_vm/tests/encrypted_media.rs b/moli-renderer-v8/src/script_vm/tests/encrypted_media.rs index 7b58a6f9b6a..51d71b8f5f6 100644 --- a/moli-renderer-v8/src/script_vm/tests/encrypted_media.rs +++ b/moli-renderer-v8/src/script_vm/tests/encrypted_media.rs @@ -109,10 +109,8 @@ fn encrypted_media_session_handlers_use_native_event_targets_and_registered_prox #[derive(WebApiObject)] #[webapi(interface = crate::web_api_interfaces::MediaKeySession, require_prototype)] struct TestSession { - #[webapi(slot = crate::context_bootstrap::SIMPLE_EVENT_TARGET_SLOT, value = "__moliMediaKeySessionListeners")] + #[webapi(slot = crate::context_bootstrap::SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")] target_slot: (), - #[webapi(slot = crate::context_bootstrap::SIMPLE_EVENT_TARGET_ORDERED_HANDLERS_SLOT, init = true)] - ordered_handlers: (), } let mut vm = new_storage_page_task_executor_test_vm("https://eme-events.test/"); diff --git a/moli-renderer-v8/src/script_vm/tests/midi_frontend.rs b/moli-renderer-v8/src/script_vm/tests/midi_frontend.rs index 3c65b362597..e7302b9affe 100644 --- a/moli-renderer-v8/src/script_vm/tests/midi_frontend.rs +++ b/moli-renderer-v8/src/script_vm/tests/midi_frontend.rs @@ -64,6 +64,7 @@ fn native_midi_maps_are_live_lossless_and_support_registered_proxies() { .unwrap(); let port = v8::Object::new(scope); crate::web_api_interfaces::initialize(scope, port, interface).unwrap(); + crate::context_bootstrap::initialize_simple_event_target(scope, port); assert_eq!(port.set_prototype(scope, prototype.into()), Some(true)); assert_eq!( global.create_data_property( diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index 5d2e96bae2d..42de073406d 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2349,7 +2349,6 @@ mod document_svg_root; mod image_bitmap_clone; mod image_bitmap_tasks; mod image_data_native; -mod message_port_transfer; mod payment_events; mod payment_request; mod reporting_observer; @@ -2413,14 +2412,11 @@ mod svg_transform_native_receivers; mod svg_detached_lengths; mod svg_transform_sync_consolidation; -mod cross_origin_named_children; -mod declarative_receivers; mod svg_transform_float_arguments; mod html_constructor_proxy_handler_isolation; mod data_transfer_native_receivers; -mod frame_owner_origin_access; mod encrypted_media; mod hyperlink_null_url_protocol; @@ -2622,8 +2618,6 @@ mod dom_rect_structured_clone; mod domrect_receiver_consolidation; mod resize_observer_entries; -mod encoded_video_chunk; - mod file_value_receivers; mod detached_node_producer_host; diff --git a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs index eb08b1a7fbd..a0dc577ce6e 100644 --- a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs +++ b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs @@ -840,6 +840,7 @@ async fn observer_callbacks_use_webidl_callback_function_realm_receiver_and_prox (() => { const child = __observerCallbackFrame.contentWindow; const target = document.body.appendChild(document.createElement("div")); + target.style.cssText = "width:20px;height:10px"; globalThis.__observerCallbackFacts = []; globalThis.__observerProxyCalls = []; globalThis.__observerCallbackChild = child; @@ -982,9 +983,20 @@ async fn intersection_entries_use_the_borrowed_callback_realm_in_both_layout_mod .unwrap(); let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); + assert_eq!( + vm.layout_pass_observability_for_test().1, + builds, + "registration must not build a layout: {policy:?}" + ); vm.advance_timers_until_deadline_for_test(&loader) .await .expect("deliver Document intersection task"); + let sampled_builds = vm.layout_pass_observability_for_test().1; + assert_eq!( + sampled_builds, + builds + u64::from(policy == moli_page_types::LayoutPolicy::OnDemand), + "one rendering update publishes one real layout and none for Mock: {policy:?}" + ); assert_eq!( vm.eval("JSON.stringify(rows)").unwrap(), r#"[{"callbackRealm":true,"observerRealm":true,"receiver":true,"arrayRealm":true,"entryRealm":true,"rectRealm":true,"target":true,"count":1,"argc":2}]"#, @@ -995,8 +1007,8 @@ async fn intersection_entries_use_the_borrowed_callback_realm_in_both_layout_mod } assert_eq!( vm.layout_pass_observability_for_test().1, - builds, - "observer registration, delivery and record reads must reuse the initial sample: {policy:?}" + sampled_builds, + "delivery and record reads must reuse the rendering update's sample: {policy:?}" ); } } @@ -1072,6 +1084,7 @@ async fn observer_callback_exceptions_are_reported_to_the_callback_relevant_wind (() => { const child = __observerCallbackFrame.contentWindow; const target = document.body.appendChild(document.createElement("div")); + target.style.cssText = "width:20px;height:10px"; globalThis.__observerCallbackErrors = []; child.addEventListener("error", child.Function( "event", diff --git a/moli-renderer-v8/src/script_vm/tests/resize_observer_entries.rs b/moli-renderer-v8/src/script_vm/tests/resize_observer_entries.rs index 311746e193f..d536bce99e1 100644 --- a/moli-renderer-v8/src/script_vm/tests/resize_observer_entries.rs +++ b/moli-renderer-v8/src/script_vm/tests/resize_observer_entries.rs @@ -1,5 +1,25 @@ use super::*; +// These projection tests isolate sampling from the rendering task's layout +// publication. Only already-published geometry may be queried by a broadcast. +fn broadcast_published_resize_observations(vm: &mut StandaloneScriptVmHarness) { + vm.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { + let host = unsafe { &*host_ptr }; + let dispatch = crate::native_bridge::OwnerDispatchScope::Top; + let target = host + .current_window_document_task_target_for_dispatch_scope(dispatch) + .unwrap(); + let owner = host + .current_window_execution_context_owner(dispatch) + .unwrap(); + crate::context_bootstrap::broadcast_document_resize_observers( + scope, host_ptr, target, owner, 0, + )?; + Ok(()) + }) + .unwrap(); +} + #[tokio::test(flavor = "current_thread")] async fn resize_observer_entries_preserve_webidl_snapshots_and_callback_realms() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); @@ -52,6 +72,7 @@ fn ondemand_ro_uses_published_css_box_axes_and_unzoomed_dimensions() { "#, ) .unwrap(); + broadcast_published_resize_observations(&mut vm); assert_eq!( vm.eval("JSON.stringify(samples)").unwrap(), "[[50,100,100,50,104,54]]" @@ -59,6 +80,7 @@ fn ondemand_ro_uses_published_css_box_axes_and_unzoomed_dimensions() { assert_eq!(vm.layout_pass_observability_for_test().1, builds); vm.eval("target.style.writingMode='horizontal-tb'").unwrap(); + broadcast_published_resize_observations(&mut vm); assert_eq!( vm.eval("JSON.stringify(samples)").unwrap(), "[[50,100,100,50,104,54]]", @@ -71,6 +93,7 @@ fn ondemand_ro_uses_published_css_box_axes_and_unzoomed_dimensions() { // This mutation schedules its existing check without requesting layout. vm.eval("target.setAttribute('data-resample','yes')") .unwrap(); + broadcast_published_resize_observations(&mut vm); assert_eq!( vm.eval("JSON.stringify(samples)").unwrap(), "[[50,100,100,50,104,54],[50,100,50,100,54,104]]" @@ -107,6 +130,7 @@ fn real_ro_css_box_projection_excludes_non_replaced_inline_fragments() { "#, ) .unwrap(); + broadcast_published_resize_observations(&mut vm); assert_eq!( vm.eval("JSON.stringify(samples)").unwrap(), r#"[["inline",0,0,0,0,0,0],["atomic",50,100,100,50,104,54]]"#, diff --git a/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs b/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs index 527a7da7119..be608b1c09d 100644 --- a/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs +++ b/moli-renderer-v8/src/script_vm/tests/rtc_configuration.rs @@ -66,12 +66,16 @@ fn rtc_configuration_uses_registered_native_proxy_identity() { #[test] fn rtc_configuration_snapshots_preserve_certificate_identity_and_immutability() { let mut vm = new_storage_page_task_executor_test_vm("https://rtc-configuration.test/"); + vm.eval("RTCPeerConnection.generateCertificate({name:'ECDSA',namedCurve:'P-256'}).then(value=>globalThis.certificate=value)").unwrap(); let context_ptr = &vm.current_main_world().unwrap().context as *const _; vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| { - let certificate = v8::Object::new(scope); - crate::web_api_interfaces::RTCCertificate::DESCRIPTOR - .initialize(scope, certificate) - .unwrap(); + let global = scope.get_current_context().global(scope); + let certificate = v8::Local::::try_from( + global + .get(scope, crate::util::v8str(scope, "certificate").into()) + .unwrap(), + ) + .unwrap(); let handler = crate::util::new_null_prototype_object(scope); let proxy = v8::Proxy::new(scope, certificate, handler).unwrap(); moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap(); diff --git a/moli-renderer-v8/src/script_vm/tests/video_playback_quality.js b/moli-renderer-v8/src/script_vm/tests/video_playback_quality.js index 9790a3772f9..5ab92751349 100644 --- a/moli-renderer-v8/src/script_vm/tests/video_playback_quality.js +++ b/moli-renderer-v8/src/script_vm/tests/video_playback_quality.js @@ -42,9 +42,9 @@ }); run(label + '/synthetic-window-does-not-create-document-clock', () => { const outer = w.document.implementation.createHTMLDocument(''), iframe = outer.createElement('iframe'); - outer.body.appendChild(iframe); const document = iframe.contentDocument; - iframe.contentWindow; - return method.call(document.createElement('video')).creationTime === 0; + outer.body.appendChild(iframe); + return iframe.contentDocument === null && iframe.contentWindow === null && + method.call(outer.createElement('video')).creationTime === 0; }); run(label + '/snapshot-slots', () => { const result = method.call(w.document.createElement('video')); diff --git a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs index 4373becf1d9..d10abd91200 100644 --- a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs +++ b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs @@ -595,7 +595,7 @@ fn text_stream_constructors_preserve_declared_metadata() { fatal: true, ignoreBOM: true, }); - const metadataOrder = Object.getOwnPropertyNames(decoder) + const metadataOrder = Object.getOwnPropertyNames(Object.getPrototypeOf(decoder)) .filter(name => ["encoding", "fatal", "ignoreBOM"].includes(name)); if (metadataOrder.join() !== "encoding,fatal,ignoreBOM") { throw Error("TextDecoderStream metadata property order"); @@ -1861,70 +1861,3 @@ fn transform_stream_caught_enqueue_strategy_error_errors_stream_but_resolves_wri r#"["closed:RangeError","enqueue:RangeError","readable:RangeError","ready:RangeError","write:resolved"]"# ); } - -#[test] -fn text_decoder_snapshots_input_after_options_conversion() { - let mut vm = new_storage_test_vm("https://text-decoder-input-snapshot.test/"); - vm.eval(include_str!( - "../../../../tests/fixtures/text-decoder-input-snapshot.js" - )) - .expect("text decoder input snapshot contract should load"); - vm.eval("runTextDecoderInputSnapshotContract().then(result => globalThis.__textDecoderInputSnapshotResults = result)") - .expect("text decoder input snapshot contract should execute"); - let facts: serde_json::Value = serde_json::from_str( - &vm.eval("JSON.stringify(__textDecoderInputSnapshotResults)") - .expect("text decoder input snapshot results should serialize"), - ) - .expect("text decoder input snapshot results should be valid JSON"); - let checks = facts["checks"].as_array().expect("input snapshot checks"); - let failures = checks - .iter() - .filter(|check| check["passed"] != true) - .collect::>(); - assert!(failures.is_empty(), "{failures:#?}"); - assert_eq!(checks.len(), 33); -} - -#[test] -fn text_decoder_constructors_follow_encoding_label_whitespace_rules() { - let mut vm = new_storage_test_vm("https://text-decoder-labels.test/"); - vm.eval(include_str!( - "../../../../tests/fixtures/text-decoder-labels.js" - )) - .expect("TextDecoder label fixture should execute"); - let facts: serde_json::Value = serde_json::from_str( - &vm.eval("JSON.stringify(__textDecoderLabelResults)") - .expect("TextDecoder label results should serialize"), - ) - .expect("TextDecoder label results should be valid JSON"); - let checks = facts["checks"].as_array().expect("label checks"); - let failures = checks - .iter() - .filter(|check| check["passed"] != true) - .collect::>(); - assert!(failures.is_empty(), "{failures:#?}"); - assert_eq!(checks.len(), 512); -} - -#[test] -fn text_encoder_stream_preserves_utf16_chunk_boundaries() { - let mut vm = new_storage_test_vm("https://text-encoder-boundaries.test/"); - vm.eval(include_str!( - "../../../../tests/fixtures/text-encoder-boundaries.js" - )) - .expect("text encoder boundary contract should load"); - vm.eval("runTextEncoderBoundaryContract().then(result => globalThis.__textEncoderBoundaryResults = result)") - .expect("text encoder boundary contract should execute"); - let facts: serde_json::Value = serde_json::from_str( - &vm.eval("JSON.stringify(__textEncoderBoundaryResults)") - .expect("text encoder boundary results should serialize"), - ) - .expect("text encoder boundary results should be valid JSON"); - let checks = facts["checks"].as_array().expect("boundary checks"); - let failures = checks - .iter() - .filter(|check| check["passed"] != true) - .collect::>(); - assert!(failures.is_empty(), "{failures:#?}"); - assert_eq!(checks.len(), 49); -} diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs index 9025a2147ea..ab5b831f2da 100644 --- a/moli-renderer-v8/src/util.rs +++ b/moli-renderer-v8/src/util.rs @@ -4,7 +4,7 @@ pub(crate) use moli_v8_util::v8_string_from_utf16_units; pub use moli_v8_util::{ array_contains_strict, array_push_value, call_object_method, callable_relevant_context, callback_data_index_value, callback_data_item, constructor_object, constructor_prototype, constructor_prototype_object, - define_non_enumerable_static_bool_property, define_non_enumerable_static_number_property, + define_non_enumerable_static_bool_property, define_non_enumerable_static_property, define_non_enumerable_static_string_property, get_own_static_property, get_private_object, get_private_value, get_property, global_constructor_object, global_constructor_prototype, @@ -311,25 +311,9 @@ pub(crate) use moli_v8_util::materialize_hidden_function_template_prototype; pub(crate) use moli_webapi_declare::{serialize_v8_array, serialize_v8_iter_array}; pub(crate) use moli_v8_util::{ - new_target_realm_constructor_prototype, - receiver_uses_new_target_realm_object_fallback, + new_target_realm_constructor_prototype, receiver_uses_new_target_realm_object_fallback, }; -pub(super) fn create_script_origin_with_base_url<'s>( - scope: &mut v8::PinScope<'s, '_>, - resource_name: &str, - line_offset: i32, - base_url: Option<&Url>, -) -> v8::ScriptOrigin<'s> { - create_script_origin_with_base_url_and_fetch_metadata( - scope, - resource_name, - line_offset, - base_url, - &crate::module_runtime::ModuleFetchMetadata::default(), - ) -} - pub(super) fn create_function_origin_with_base_url<'s>( scope: &mut v8::PinScope<'s, '_>, location: &crate::dom::native::SourceLocation, diff --git a/moli-renderer-v8/src/webidl_callback_execution.rs b/moli-renderer-v8/src/webidl_callback_execution.rs index 94d157e3482..ce65e231d03 100644 --- a/moli-renderer-v8/src/webidl_callback_execution.rs +++ b/moli-renderer-v8/src/webidl_callback_execution.rs @@ -48,6 +48,7 @@ pub(crate) enum WebIdlCallbackExecutionOutcome { enum CallbackExecutionEnvironment { Window { + context: v8::Global, // Some API registrations, including observers, authorize both the // API object's owner and the callback's potentially different Realm. owner_identity: Option, @@ -73,6 +74,7 @@ impl PreparedWebIdlCallbackExecution { Some(Self { callback, environment: CallbackExecutionEnvironment::Window { + context: v8::Global::new(scope, scope.get_current_context()), owner_identity, callback_identity, }, @@ -118,6 +120,7 @@ impl PreparedWebIdlCallbackExecution { let callback_identity = host.window_execution_context_identity_for_v8_context(scope, context)?; CallbackExecutionEnvironment::Window { + context: v8::Global::new(scope, scope.get_current_context()), owner_identity: None, callback_identity, } @@ -150,7 +153,19 @@ impl PreparedWebIdlCallbackExecution { } pub(crate) fn is_current(&self, scope: &mut v8::PinScope<'_, '_>) -> bool { - self.environment.can_invoke(scope, &self.binding) + // Validate the exact preparation Context independently of the caller's + // ambient Realm. The neutral callback layer then enters the relevant + // Realm, which may belong to another Window or Page owner. + match &self.environment { + CallbackExecutionEnvironment::Window { context, .. } => { + let context = v8::Local::new(scope, context); + let scope = &mut v8::ContextScope::new(scope, context); + self.environment.can_invoke(scope, &self.binding) + } + CallbackExecutionEnvironment::Worker { .. } => { + self.environment.can_invoke(scope, &self.binding) + } + } } /// Execute the caller's invocation and return conversion while the Web @@ -258,6 +273,7 @@ impl CallbackExecutionEnvironment { Self::Window { owner_identity, callback_identity, + .. }, Some(RuntimeExecutionContext::Window(host_ptr)), ) => { diff --git a/moli-renderer-v8/src/worker/global_scope/event_handlers.rs b/moli-renderer-v8/src/worker/global_scope/event_handlers.rs index daeadd01926..29ffc874c63 100644 --- a/moli-renderer-v8/src/worker/global_scope/event_handlers.rs +++ b/moli-renderer-v8/src/worker/global_scope/event_handlers.rs @@ -310,7 +310,7 @@ fn worker_global_onrtctransform_setter<'s>( args.this(), args.get(0), WORKER_GLOBAL_ONRTCTRANSFORM_SLOT, - Some("rtctransform"), + "rtctransform", ); } diff --git a/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs b/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs index f1482290e4d..e22771e5746 100644 --- a/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs +++ b/moli-renderer-v8/src/worker/global_scope/service_worker_api.rs @@ -1,7 +1,4 @@ use super::*; -use crate::context_bootstrap::{ - simple_event_target_handler_getter_callback, simple_event_target_handler_setter_callback, -}; pub(super) fn install_service_worker_global_runtime<'s>( scope: &mut v8::PinScope<'s, '_>, @@ -68,12 +65,7 @@ fn build_service_worker_global_registration<'s>( } .bind(scope) .map_err(|error| anyhow!("failed to build service worker registration: {error:?}"))?; - crate::context_bootstrap::mark_simple_event_target_slot( - scope, - registration, - SERVICE_WORKER_REGISTRATION_EVENTS_SLOT, - ); - install_simple_event_target_ordered_handlers(scope, registration); + crate::context_bootstrap::initialize_simple_event_target(scope, registration); let scope_value = v8_string(scope, scope_url.as_str()) .ok_or_else(|| anyhow!("failed to allocate service worker registration scope"))?; set_private_value( @@ -121,7 +113,6 @@ pub(in crate::worker) fn dispatch_service_worker_registration_update_found<'s>( crate::context_bootstrap::dispatch_simple_event_target_event( scope, registration, - SERVICE_WORKER_REGISTRATION_EVENTS_SLOT, "updatefound", event, ); @@ -2223,5 +2214,3 @@ pub(in crate::worker) struct ServiceWorkerWindowClientDeclaration<'scope> { navigate: (), } const SERVICE_WORKER_GLOBAL_REGISTRATION_SLOT: &str = "__moliServiceWorkerGlobalRegistration"; - -const SERVICE_WORKER_REGISTRATION_EVENTS_SLOT: &str = "__moliServiceWorkerRegistrationEvents"; diff --git a/moli-renderer-v8/src/worker/thread/tests/wasm_csp.rs b/moli-renderer-v8/src/worker/thread/tests/wasm_csp.rs index 9473e9c5c36..6b3e1149eec 100644 --- a/moli-renderer-v8/src/worker/thread/tests/wasm_csp.rs +++ b/moli-renderer-v8/src/worker/thread/tests/wasm_csp.rs @@ -1,9 +1,9 @@ use super::*; -fn wasm_csp_options() -> WorkerSpawnOptions { +fn wasm_csp_options(expected_reports: usize) -> WorkerSpawnOptions { WorkerSpawnOptions::new( format!( - "{}.then(value => {{ postMessage(value); close(); }});", + "globalThis.__expectedWasmCspReports = {expected_reports}; {}.then(value => {{ postMessage(value); close(); }});", include_str!("../../../../tests/fixtures/worker-wasm-csp.js"), ), "https://app.test/worker/main.js".to_owned(), @@ -65,7 +65,8 @@ async fn worker_wasm_csp_covers_sync_async_and_streaming_compilation() { ("script-src 'unsafe-eval'\u{000b}", false), ] { let result = wasm_csp_result( - wasm_csp_options().with_content_security_policies(vec![policy.to_owned()]), + wasm_csp_options(if allowed { 0 } else { 5 }) + .with_content_security_policies(vec![policy.to_owned()]), ) .await; assert_wasm_compilation_result(&result, allowed); @@ -88,7 +89,7 @@ async fn worker_wasm_csp_reports_every_policy_without_enforcing_report_only() { let policies = ["script-src 'none'", "default-src 'self'"].map(str::to_owned); for enforce in [false, true] { let result = wasm_csp_result( - wasm_csp_options() + wasm_csp_options(if enforce { 20 } else { 10 }) .with_content_security_policies(if enforce { policies.to_vec() } else { vec![] }) .with_content_security_report_only_policies(policies.to_vec()), ) @@ -118,7 +119,7 @@ async fn worker_wasm_csp_reports_every_policy_without_enforcing_report_only() { #[tokio::test] async fn worker_wasm_csp_uses_inherited_header_meta_and_report_only_policies() { ensure_v8(); - let result = wasm_csp_result(wasm_csp_options().with_content_security_policy_snapshot( + let result = wasm_csp_result(wasm_csp_options(10).with_content_security_policy_snapshot( crate::content_security_policy::InheritedContentSecurityPolicy { self_url: Some(url::Url::parse("https://creator.test/").unwrap()), header_policies: vec!["script-src 'wasm-unsafe-eval'".to_owned()], diff --git a/moli-renderer-v8/tests/fixtures/canvas-exif-orientation.js b/moli-renderer-v8/tests/fixtures/canvas-exif-orientation.js index 240bf8b1cb1..f347340a74b 100644 --- a/moli-renderer-v8/tests/fixtures/canvas-exif-orientation.js +++ b/moli-renderer-v8/tests/fixtures/canvas-exif-orientation.js @@ -62,6 +62,7 @@ const realms=[['main',globalThis],['iframe',document.querySelector('iframe').contentWindow]]; for(const [ownerName,owner] of realms)for(const [calleeName,callee] of realms) for(const format of ['png','jpg','webp'])for(let orientation=1;orientation<=8;orientation++){ + if(globalThis.__exifScenario && globalThis.__exifScenario !== `${ownerName}/${calleeName}/${format}`)continue; const prefix=`${ownerName}/${calleeName}/${format}/${orientation}`; progress.stage=prefix+'/load'; const bytes=orientedBytes(format,orientation),mime=__exifSources[format].mime; diff --git a/moli-renderer-v8/tests/fixtures/canvas-video-frames.js b/moli-renderer-v8/tests/fixtures/canvas-video-frames.js index 0f8cdc1b6a3..c99a72904bd 100644 --- a/moli-renderer-v8/tests/fixtures/canvas-video-frames.js +++ b/moli-renderer-v8/tests/fixtures/canvas-video-frames.js @@ -27,13 +27,18 @@ } function bytes(ctx,source) { ctx.canvas.width=source.width;ctx.canvas.height=source.height;ctx.drawImage(source,0,0); - return Array.from(ctx.getImageData(0,0,source.width,source.height).data).join(','); + return ctx.getImageData(0,0,source.width,source.height).data; + } + function sameBytes(actual,expected) { + if(actual.length!==expected.length)return false; + for(let i=0;i{ - video.onseeked=()=>{video.onseeked=null;try{assert(video.currentTime===time && !video.seeking,'seek position '+video.currentTime+' expected '+time+' seeking '+video.seeking);resolve();}catch(error){reject(error);}}; + video.onseeked=()=>{progress.operation='seeked/'+time;video.onseeked=null;try{assert(video.currentTime===time && !video.seeking,'seek position '+video.currentTime+' expected '+time+' seeking '+video.seeking);resolve();}catch(error){reject(error);}}; set(callee,video,'currentTime',time); - }).then(()=>new Promise(resolve=>callee.setTimeout(resolve,0))); + }).then(()=>new Promise(resolve=>{progress.operation='seek-timer/'+time;callee.setTimeout(resolve,0);})); } const cases=[ ['decoded dimensions and Canvas pixels',async(owner,callee,video,url,ctx)=>{ @@ -76,15 +81,21 @@ ctx.drawImage(bitmap,0,0);corners(ctx);bitmap.close(); }], ['seek selects new frames and rewinds reference state',async(owner,callee,video,url,ctx,transport)=>{ + progress.operation='counting-ready'; await ready(owner,callee,video,__videoFrameSources[transport].counting); + progress.operation='first-bitmap'; const first=await callee.createImageBitmap(video),initial=bytes(ctx,first); + progress.operation='forward-seek'; await seek(callee,video,2.5); + progress.operation='later-bitmap'; const later=await callee.createImageBitmap(video); - assert(bytes(ctx,later)!==initial,'seek must produce a genuinely different decoded frame'); - assert(bytes(ctx,first)===initial,'an earlier bitmap remains immutable'); + assert(!sameBytes(bytes(ctx,later),initial),'seek must produce a genuinely different decoded frame'); + assert(sameBytes(bytes(ctx,first),initial),'an earlier bitmap remains immutable'); + progress.operation='rewind-seek'; await seek(callee,video,0); + progress.operation='rewound-bitmap'; const rewound=await callee.createImageBitmap(video); - assert(bytes(ctx,rewound)===initial,'rewinding replays codec references'); + assert(sameBytes(bytes(ctx,rewound),initial),'rewinding replays codec references'); first.close();later.close();rewound.close(); }], ['VP9 frames share native allocation limits and timestamps',async(owner,callee,video,url,ctx,transport)=>{ @@ -105,13 +116,15 @@ const realms=[['main',globalThis],['iframe',document.querySelector('iframe').contentWindow]]; for(const [ownerName,owner] of realms)for(const [calleeName,callee] of realms) for(const transport of ['data','http'])for(const windowless of [false,true])for(const offscreen of [false,true]) { + const scenario=`${ownerName}/${calleeName}/${transport}/${windowless?'windowless':'live'}/${offscreen?'offscreen':'html'}`; + if(globalThis.__videoFrameScenario && globalThis.__videoFrameScenario !== scenario)continue; const doc=windowless?owner.document.implementation.createHTMLDocument(''):owner.document; for(const [name,body] of cases) { const video=doc.createElement('video');doc.body.appendChild(video); const label=`${ownerName}/${calleeName}/${transport}/${windowless?'windowless':'live'}/${offscreen?'offscreen':'html'}/${name}`; progress.stage=label;let timeout; try { - await Promise.race([body(owner,callee,video,__videoFrameSources[transport].pattern,context(callee,offscreen),transport,offscreen),new Promise((_,reject)=>{timeout=setTimeout(()=>reject(Error('video case timeout')),2500);})]); + await Promise.race([body(owner,callee,video,__videoFrameSources[transport].pattern,context(callee,offscreen),transport,offscreen),new Promise((_,reject)=>{timeout=setTimeout(()=>reject(Error('video case timeout '+JSON.stringify({operation:progress.operation,currentTime:video.currentTime,seeking:video.seeking,readyState:video.readyState,error:video.error?.code,ownerClosed:owner.closed,calleeClosed:callee.closed,native:globalThis.__videoFrameNativeState?.(video)}))),2500);})]); if(windowless)assert(doc.defaultView===null && doc.hidden,'video resources do not create a synthetic Window'); checks.push({name:label,category:windowless?'windowless':'live',passed:true}); }catch(error){checks.push({name:label,category:windowless?'windowless':'live',passed:false,detail:String(error)});} diff --git a/moli-renderer-v8/tests/fixtures/frame-content-document-domain.js b/moli-renderer-v8/tests/fixtures/frame-content-document-domain.js index 790557033b4..5f65ba80ccb 100644 --- a/moli-renderer-v8/tests/fixtures/frame-content-document-domain.js +++ b/moli-renderer-v8/tests/fixtures/frame-content-document-domain.js @@ -1,4 +1,7 @@ (() => { + // https://html.spec.whatwg.org/multipage/document-sequences.html#concept-navigable-container-content-document + // The container's node Document supplies origin-domain, including when its + // native getter is borrowed from another Realm. const outer = document.getElementById('outer'); const container = outer.contentDocument; const nested = container.getElementById('nested'); @@ -8,9 +11,9 @@ document.domain = document.domain; checks.push(outer.contentDocument === null, nested.contentDocument === doc, - get.call(nested) === null); + get.call(nested) === doc); doc.domain = doc.domain; - checks.push(nested.contentDocument === null, get.call(nested) === doc); + checks.push(nested.contentDocument === null, get.call(nested) === null); container.domain = container.domain; checks.push(outer.contentDocument === container, nested.contentDocument === doc, get.call(nested) === doc); diff --git a/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js index 94bacf4bf1b..e7dbf18e1ec 100644 --- a/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js +++ b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js @@ -11,7 +11,8 @@ meta.content = "script-src-attr 'none' 'report-sample'"; creator.document.head.appendChild(meta); const synthetic = inert.createElement('iframe'); inert.body.appendChild(synthetic); -if (synthetic.contentWindow === null) throw Error('missing synthetic Window'); +if (synthetic.contentWindow !== null || synthetic.contentDocument !== null || inert.defaultView !== null) + throw Error('a windowless iframe acquired a browsing context'); const target = inert.createElement('button'); const prior = () => 17; target.onclick = prior; diff --git a/moli-renderer-v8/tests/fixtures/worker-wasm-csp.js b/moli-renderer-v8/tests/fixtures/worker-wasm-csp.js index 720f2409621..ed93c6b9460 100644 --- a/moli-renderer-v8/tests/fixtures/worker-wasm-csp.js +++ b/moli-renderer-v8/tests/fixtures/worker-wasm-csp.js @@ -2,7 +2,9 @@ const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]); const events = []; let microtaskRan = false; - const listener = event => events.push({ + let reportsComplete; + const reportsDone = new Promise(resolve => { reportsComplete = resolve; }); + const listener = event => { events.push({ blocked: event.blockedURI, directive: event.effectiveDirective, policy: event.originalPolicy, @@ -12,6 +14,8 @@ native: event instanceof SecurityPolicyViolationEvent, afterMicrotask: microtaskRan, }); + if (events.length === globalThis.__expectedWasmCspReports) reportsComplete(); + }; addEventListener('securitypolicyviolation', listener); queueMicrotask(() => { microtaskRan = true; }); const response = () => new Response(bytes, { headers: { 'Content-Type': 'application/wasm' } }); @@ -35,7 +39,9 @@ } } const valid = WebAssembly.validate(bytes); - await new Promise(resolve => setTimeout(resolve, 30)); + const observation = new Promise(resolve => setTimeout(resolve, 30)); + if (globalThis.__expectedWasmCspReports > 0) await reportsDone; + await observation; removeEventListener('securitypolicyviolation', listener); return { results, synchronousEvents, valid, events }; })() diff --git a/moli-webapi-declare-derive/src/expand.rs b/moli-webapi-declare-derive/src/expand.rs index edc08db141d..452cb722a04 100644 --- a/moli-webapi-declare-derive/src/expand.rs +++ b/moli-webapi-declare-derive/src/expand.rs @@ -174,6 +174,34 @@ pub(crate) fn expand_webapi_function_template( None } }); + let getter_callbacks = fields.iter().filter_map(|DeclaredField { attrs, .. }| { + if !matches!(attrs.kind, FieldKind::AccessorProperty) { + return None; + } + let name = webapi_field_name_literal(attrs.name.as_ref())?; + let callback = expand_callback(attrs.getter.as_ref()?, attrs, false); + Some(quote! { + #name => ::std::option::Option::Some( + ::moli_webapi_declare::v8::MapFnTo::< + ::moli_webapi_declare::v8::FunctionCallback, + >::map_fn_to(#callback) + ), + }) + }); + let setter_callbacks = fields.iter().filter_map(|DeclaredField { attrs, .. }| { + if !matches!(attrs.kind, FieldKind::AccessorProperty) { + return None; + } + let name = webapi_field_name_literal(attrs.name.as_ref())?; + let callback = expand_callback(attrs.setter.as_ref()?, attrs, true); + Some(quote! { + #name => ::std::option::Option::Some( + ::moli_webapi_declare::v8::MapFnTo::< + ::moli_webapi_declare::v8::FunctionCallback, + >::map_fn_to(#callback) + ), + }) + }); let mut callback_mappings = CallbackMappings::default(); let template_fields = expand_function_template_fields(&fields, &template_name, &mut callback_mappings)?; @@ -227,6 +255,24 @@ pub(crate) fn expand_webapi_function_template( const NAME: &'static str = #template_name; const PROTOTYPE_ATTRIBUTE_NAMES: &'static [&'static str] = &[#(#prototype_attribute_names),*]; + fn accessor_getter_callback(__moli_accessor_name: &str) -> ::std::option::Option<::moli_webapi_declare::v8::FunctionCallback> { + match __moli_accessor_name { + #(#getter_callbacks)* + _ => ::std::option::Option::None, + } + } + + + fn accessor_setter_callback(__moli_accessor_name: &str) -> ::std::option::Option<::moli_webapi_declare::v8::FunctionCallback> { + match __moli_accessor_name { + #(#setter_callbacks)* + _ => ::std::option::Option::None, + } + } + + + + fn build<'s>( scope: &mut ::moli_webapi_declare::v8::PinScope<'s, '_, ()>, ) -> ::moli_webapi_declare::v8::Local<'s, ::moli_webapi_declare::v8::FunctionTemplate> { diff --git a/moli-webapi-declare/src/declaration.rs b/moli-webapi-declare/src/declaration.rs index f59bcbb2fdf..acf633c7091 100644 --- a/moli-webapi-declare/src/declaration.rs +++ b/moli-webapi-declare/src/declaration.rs @@ -20,6 +20,19 @@ pub trait WebApiFunctionTemplateDeclaration { /// prototype objects. Inherited declarations are listed separately. const PROTOTYPE_ATTRIBUTE_NAMES: &'static [&'static str] = &[]; + /// Returns the generated native getter adapter for a statically named + /// accessor. Exotic installers can retain their native V8 cache while + /// using the declaration's receiver and access policies. Callback data, + /// when declared, must still be supplied by the installer. + fn accessor_getter_callback(_name: &str) -> Option { + None + } + + /// The setter counterpart for native installers using declared accessors. + fn accessor_setter_callback(_name: &str) -> Option { + None + } + fn build<'s>(scope: &mut v8::PinScope<'s, '_, ()>) -> v8::Local<'s, v8::FunctionTemplate>; fn initialize_template<'s>( diff --git a/moli-webapi/src/dom_exception/rtc_error.rs b/moli-webapi/src/dom_exception/rtc_error.rs index 3ab8d0c7bc5..642ec286f53 100644 --- a/moli-webapi/src/dom_exception/rtc_error.rs +++ b/moli-webapi/src/dom_exception/rtc_error.rs @@ -141,6 +141,7 @@ pub fn build_rtc_sdp_error<'s>( sent_alert: None, } .initialize_snapshot(scope, object)?; + capture_dom_exception_stack(scope, object); Some(object) } diff --git a/moli-webapi/src/events/ice_error_event.rs b/moli-webapi/src/events/ice_error_event.rs index 30df8066f99..d96ee9658ec 100644 --- a/moli-webapi/src/events/ice_error_event.rs +++ b/moli-webapi/src/events/ice_error_event.rs @@ -3,10 +3,7 @@ use super::{ new_event_state, }; use crate::interfaces as web_api_interfaces; -use moli_v8_util::{ - callback_data_index_value, callback_data_item, - throw_type_error, -}; +use moli_v8_util::{callback_data_index_value, callback_data_item, throw_type_error}; use moli_webapi_declare::WebApiFunctionTemplate; use moli_webidl as webidl; use moli_webapi_declare::initialize_web_api_constructor_receiver; diff --git a/moli-webapi/src/events/value.rs b/moli-webapi/src/events/value.rs index fea7e6f45d9..1013ea4cadd 100644 --- a/moli-webapi/src/events/value.rs +++ b/moli-webapi/src/events/value.rs @@ -47,8 +47,7 @@ pub fn initialize_css_animation_start_event<'s>( elapsed_time, pseudo_element: v8str(scope, ""), } - .initialize_snapshot(scope, state) - .ok()?; + .initialize_own_snapshot(scope, state)?; web_api_interfaces::AnimationEvent::DESCRIPTOR .initialize(scope, state) .ok()?; diff --git a/moli-webapi/src/events/webrtc.rs b/moli-webapi/src/events/webrtc.rs index 74de8ccfb76..d43c30dc289 100644 --- a/moli-webapi/src/events/webrtc.rs +++ b/moli-webapi/src/events/webrtc.rs @@ -3,10 +3,7 @@ use super::{ new_event_state, }; use crate::interfaces as web_api_interfaces; -use moli_v8_util::{ - callback_data_index_value, callback_data_item, - throw_type_error, -}; +use moli_v8_util::{callback_data_index_value, callback_data_item, throw_type_error}; use moli_webapi_declare::{WebApiFunctionTemplate, WebApiInterfaceDescriptor}; use moli_webidl as webidl; use webidl::WebIdlDictionarySerialize; diff --git a/moli-webapi/src/geometry.rs b/moli-webapi/src/geometry.rs index f87f4fe2b11..7b2ec2811b4 100644 --- a/moli-webapi/src/geometry.rs +++ b/moli-webapi/src/geometry.rs @@ -861,7 +861,7 @@ fn build_dom_point_readonly_object<'s>( object } -pub(in crate::context_bootstrap) fn build_dom_matrix_identity_object<'s>( +pub fn build_dom_matrix_identity_object<'s>( scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Object> { build_dom_matrix_object(scope, DomMatrixComponents::identity()) @@ -965,16 +965,7 @@ fn dom_point_setter_callback<'s>( }; let point = moli_webapi_declare::web_api_object_target(scope, args.this()) .expect("validated DOMPoint receiver"); - if get_private_value(scope, point, DOM_POINT_READ_ONLY_SLOT) - .is_some_and(|value| value.boolean_value(scope)) - { - embedding::throw_dom_exception_value( - scope, - "The SVG point is read-only.", - "NoModificationAllowedError", - ); - return; - } + let context = webidl::Context::member("DOMPoint", slot); let value = if get_private_value(scope, point, DOM_POINT_RESTRICTED_NUMBER_SLOT) .is_some_and(|value| value.boolean_value(scope)) diff --git a/moli-webapi/src/interfaces.rs b/moli-webapi/src/interfaces.rs index c5942e1cbc3..011e67d98e0 100644 --- a/moli-webapi/src/interfaces.rs +++ b/moli-webapi/src/interfaces.rs @@ -731,11 +731,6 @@ interfaces! { XMLSerializer; XPathEvaluator; XPathExpression; - - - - - XPathResult; } diff --git a/vendor/v8-152.2.0/src/template.rs b/vendor/v8-152.2.0/src/template.rs index 9991f1658ba..9f482e937f7 100644 --- a/vendor/v8-152.2.0/src/template.rs +++ b/vendor/v8-152.2.0/src/template.rs @@ -40,173 +40,163 @@ use std::convert::TryFrom; use std::ptr::null; unsafe extern "C" { - fn v8__FunctionTemplate__NewWithCache( - isolate: *mut RealIsolate, - callback: FunctionCallback, - cache_property: *const Private, - ) -> *const FunctionTemplate; - fn v8__Template__Set( - this: *const Template, - key: *const Name, - value: *const Data, - attr: PropertyAttribute, - ); - fn v8__Template__SetIntrinsicDataProperty( - this: *const Template, - key: *const Name, - intrinsic: Intrinsic, - attr: PropertyAttribute, - ); - fn v8__Template__SetLazyDataProperty( - this: *const Template, - key: *const Name, - getter: AccessorNameGetterCallback, - data_or_null: *const Value, - attr: PropertyAttribute, - getter_side_effect_type: SideEffectType, - setter_side_effect_type: SideEffectType, - ); + fn v8__FunctionTemplate__NewWithCache( + isolate: *mut RealIsolate, + callback: FunctionCallback, + cache_property: *const Private, + ) -> *const FunctionTemplate; + fn v8__Template__Set( + this: *const Template, + key: *const Name, + value: *const Data, + attr: PropertyAttribute, + ); + fn v8__Template__SetIntrinsicDataProperty( + this: *const Template, + key: *const Name, + intrinsic: Intrinsic, + attr: PropertyAttribute, + ); + fn v8__Template__SetLazyDataProperty( + this: *const Template, + key: *const Name, + getter: AccessorNameGetterCallback, + data_or_null: *const Value, + attr: PropertyAttribute, + getter_side_effect_type: SideEffectType, + setter_side_effect_type: SideEffectType, + ); - fn v8__Signature__New( - isolate: *mut RealIsolate, - templ: *const FunctionTemplate, - ) -> *const Signature; - fn v8__FunctionTemplate__New( - isolate: *mut RealIsolate, - callback: FunctionCallback, - data_or_null: *const Value, - signature_or_null: *const Signature, - length: i32, - constructor_behavior: ConstructorBehavior, - side_effect_type: SideEffectType, - c_functions: *const CFunction, - c_functions_len: usize, - ) -> *const FunctionTemplate; - fn v8__FunctionTemplate__GetFunction( - this: *const FunctionTemplate, - context: *const Context, - ) -> *const Function; - fn v8__FunctionTemplate__PrototypeTemplate( - this: *const FunctionTemplate, - ) -> *const ObjectTemplate; - fn v8__FunctionTemplate__InstanceTemplate( - this: *const FunctionTemplate, - ) -> *const ObjectTemplate; - fn v8__FunctionTemplate__SetClassName( - this: *const FunctionTemplate, - name: *const String, - ); - fn v8__FunctionTemplate__SetAccessorProperty( - this: *const FunctionTemplate, - key: *const Name, - getter: *const FunctionTemplate, - setter: *const FunctionTemplate, - attr: PropertyAttribute, - ); - fn v8__FunctionTemplate__Inherit( - this: *const FunctionTemplate, - parent: *const FunctionTemplate, - ); - fn v8__FunctionTemplate__ReadOnlyPrototype(this: *const FunctionTemplate); - fn v8__FunctionTemplate__RemovePrototype(this: *const FunctionTemplate); - fn v8__FunctionTemplate__SetAcceptAnyReceiver( - this: *const FunctionTemplate, - value: bool, - ); - fn v8__FunctionTemplate__HasInstance( - this: *const FunctionTemplate, - value: *const Value, - ) -> bool; + fn v8__Signature__New( + isolate: *mut RealIsolate, + templ: *const FunctionTemplate, + ) -> *const Signature; + fn v8__FunctionTemplate__New( + isolate: *mut RealIsolate, + callback: FunctionCallback, + data_or_null: *const Value, + signature_or_null: *const Signature, + length: i32, + constructor_behavior: ConstructorBehavior, + side_effect_type: SideEffectType, + c_functions: *const CFunction, + c_functions_len: usize, + ) -> *const FunctionTemplate; + fn v8__FunctionTemplate__GetFunction( + this: *const FunctionTemplate, + context: *const Context, + ) -> *const Function; + fn v8__FunctionTemplate__PrototypeTemplate( + this: *const FunctionTemplate, + ) -> *const ObjectTemplate; + fn v8__FunctionTemplate__InstanceTemplate( + this: *const FunctionTemplate, + ) -> *const ObjectTemplate; + fn v8__FunctionTemplate__SetClassName(this: *const FunctionTemplate, name: *const String); + fn v8__FunctionTemplate__SetAccessorProperty( + this: *const FunctionTemplate, + key: *const Name, + getter: *const FunctionTemplate, + setter: *const FunctionTemplate, + attr: PropertyAttribute, + ); + fn v8__FunctionTemplate__Inherit( + this: *const FunctionTemplate, + parent: *const FunctionTemplate, + ); + fn v8__FunctionTemplate__ReadOnlyPrototype(this: *const FunctionTemplate); + fn v8__FunctionTemplate__RemovePrototype(this: *const FunctionTemplate); + fn v8__FunctionTemplate__SetAcceptAnyReceiver(this: *const FunctionTemplate, value: bool); + fn v8__FunctionTemplate__HasInstance( + this: *const FunctionTemplate, + value: *const Value, + ) -> bool; - fn v8__ObjectTemplate__New( - isolate: *mut RealIsolate, - templ: *const FunctionTemplate, - ) -> *const ObjectTemplate; - fn v8__ObjectTemplate__NewInstance( - this: *const ObjectTemplate, - context: *const Context, - ) -> *const Object; - fn v8__ObjectTemplate__InternalFieldCount(this: *const ObjectTemplate) - -> int; - fn v8__ObjectTemplate__SetInternalFieldCount( - this: *const ObjectTemplate, - value: int, - ); + fn v8__ObjectTemplate__New( + isolate: *mut RealIsolate, + templ: *const FunctionTemplate, + ) -> *const ObjectTemplate; + fn v8__ObjectTemplate__NewInstance( + this: *const ObjectTemplate, + context: *const Context, + ) -> *const Object; + fn v8__ObjectTemplate__InternalFieldCount(this: *const ObjectTemplate) -> int; + fn v8__ObjectTemplate__SetInternalFieldCount(this: *const ObjectTemplate, value: int); - fn v8__ObjectTemplate__SetNativeDataProperty( - this: *const ObjectTemplate, - key: *const Name, - getter: AccessorNameGetterCallback, - setter: Option, - data_or_null: *const Value, - attr: PropertyAttribute, - ); - fn v8__ObjectTemplate__SetAccessorProperty( - this: *const ObjectTemplate, - key: *const Name, - getter: *const FunctionTemplate, - setter: *const FunctionTemplate, - attr: PropertyAttribute, - ); + fn v8__ObjectTemplate__SetNativeDataProperty( + this: *const ObjectTemplate, + key: *const Name, + getter: AccessorNameGetterCallback, + setter: Option, + data_or_null: *const Value, + attr: PropertyAttribute, + ); + fn v8__ObjectTemplate__SetAccessorProperty( + this: *const ObjectTemplate, + key: *const Name, + getter: *const FunctionTemplate, + setter: *const FunctionTemplate, + attr: PropertyAttribute, + ); - fn v8__ObjectTemplate__SetNamedPropertyHandler( - this: *const ObjectTemplate, - getter: Option, - setter: Option, - query: Option, - deleter: Option, - enumerator: Option, - definer: Option, - descriptor: Option, - data_or_null: *const Value, - flags: PropertyHandlerFlags, - ); + fn v8__ObjectTemplate__SetNamedPropertyHandler( + this: *const ObjectTemplate, + getter: Option, + setter: Option, + query: Option, + deleter: Option, + enumerator: Option, + definer: Option, + descriptor: Option, + data_or_null: *const Value, + flags: PropertyHandlerFlags, + ); - fn v8__ObjectTemplate__SetIndexedPropertyHandler( - this: *const ObjectTemplate, - getter: Option, - setter: Option, - query: Option, - deleter: Option, - enumerator: Option, - definer: Option, - descriptor: Option, - data_or_null: *const Value, - flags: PropertyHandlerFlags, - ); + fn v8__ObjectTemplate__SetIndexedPropertyHandler( + this: *const ObjectTemplate, + getter: Option, + setter: Option, + query: Option, + deleter: Option, + enumerator: Option, + definer: Option, + descriptor: Option, + data_or_null: *const Value, + flags: PropertyHandlerFlags, + ); - fn v8__ObjectTemplate__SetImmutableProto(this: *const ObjectTemplate); + fn v8__ObjectTemplate__SetImmutableProto(this: *const ObjectTemplate); - fn v8__ObjectTemplate__SetCallAsFunctionHandler( - this: *const ObjectTemplate, - callback: FunctionCallback, - data_or_null: *const Value, - ); - fn v8__ObjectTemplate__MarkAsUndetectable(this: *const ObjectTemplate); - fn v8__ObjectTemplate__SetCodeLike(this: *const ObjectTemplate); - #[allow(clippy::too_many_arguments)] - fn v8__ObjectTemplate__SetSecurityTokenAccessCheckAndHandlers( - this: *const ObjectTemplate, - access_check: AccessCheckCallback, - named_getter: Option, - named_setter: Option, - named_query: Option, - named_deleter: Option, - named_enumerator: Option, - named_definer: Option, - named_descriptor: Option, - named_data_or_null: *const Value, - named_flags: PropertyHandlerFlags, - indexed_getter: Option, - indexed_setter: Option, - indexed_query: Option, - indexed_deleter: Option, - indexed_enumerator: Option, - indexed_definer: Option, - indexed_descriptor: Option, - indexed_data_or_null: *const Value, - indexed_flags: PropertyHandlerFlags, - ); + fn v8__ObjectTemplate__SetCallAsFunctionHandler( + this: *const ObjectTemplate, + callback: FunctionCallback, + data_or_null: *const Value, + ); + fn v8__ObjectTemplate__MarkAsUndetectable(this: *const ObjectTemplate); + fn v8__ObjectTemplate__SetCodeLike(this: *const ObjectTemplate); + #[allow(clippy::too_many_arguments)] + fn v8__ObjectTemplate__SetSecurityTokenAccessCheckAndHandlers( + this: *const ObjectTemplate, + access_check: AccessCheckCallback, + named_getter: Option, + named_setter: Option, + named_query: Option, + named_deleter: Option, + named_enumerator: Option, + named_definer: Option, + named_descriptor: Option, + named_data_or_null: *const Value, + named_flags: PropertyHandlerFlags, + indexed_getter: Option, + indexed_setter: Option, + indexed_query: Option, + indexed_deleter: Option, + indexed_enumerator: Option, + indexed_definer: Option, + indexed_descriptor: Option, + indexed_data_or_null: *const Value, + indexed_flags: PropertyHandlerFlags, + ); } pub type AccessorNameGetterCallback = NamedGetterCallbackForAccessor; @@ -215,7 +205,7 @@ pub type AccessorNameGetterCallback = NamedGetterCallbackForAccessor; pub type AccessorNameSetterCallback = NamedSetterCallbackForAccessor; pub type AccessCheckCallback = - unsafe extern "C" fn(Local, Local, Local) -> bool; + unsafe extern "C" fn(Local, Local, Local) -> bool; /// Interceptor for get requests on an object. /// @@ -323,563 +313,486 @@ pub type IndexedPropertyDefinerCallback = IndexedDefinerCallback; pub type IndexedPropertyDescriptorCallback = IndexedGetterCallback; pub struct AccessorConfiguration<'s> { - pub(crate) getter: AccessorNameGetterCallback, - pub(crate) setter: Option, - pub(crate) data: Option>, - pub(crate) property_attribute: PropertyAttribute, + pub(crate) getter: AccessorNameGetterCallback, + pub(crate) setter: Option, + pub(crate) data: Option>, + pub(crate) property_attribute: PropertyAttribute, } /// Configuration for a callback-backed V8 native data property. pub type NativeDataPropertyConfiguration<'s> = AccessorConfiguration<'s>; pub struct LazyDataPropertyConfiguration<'s> { - pub(crate) getter: AccessorNameGetterCallback, - pub(crate) data: Option>, - pub(crate) property_attribute: PropertyAttribute, - pub(crate) getter_side_effect_type: SideEffectType, - pub(crate) setter_side_effect_type: SideEffectType, + pub(crate) getter: AccessorNameGetterCallback, + pub(crate) data: Option>, + pub(crate) property_attribute: PropertyAttribute, + pub(crate) getter_side_effect_type: SideEffectType, + pub(crate) setter_side_effect_type: SideEffectType, } impl<'s> LazyDataPropertyConfiguration<'s> { - pub fn new(getter: impl MapFnTo) -> Self { - Self { - getter: getter.map_fn_to(), - data: None, - property_attribute: PropertyAttribute::NONE, - getter_side_effect_type: SideEffectType::HasSideEffect, - setter_side_effect_type: SideEffectType::HasSideEffect, + pub fn new(getter: impl MapFnTo) -> Self { + Self { + getter: getter.map_fn_to(), + data: None, + property_attribute: PropertyAttribute::NONE, + getter_side_effect_type: SideEffectType::HasSideEffect, + setter_side_effect_type: SideEffectType::HasSideEffect, + } } - } - pub fn property_attribute( - mut self, - property_attribute: PropertyAttribute, - ) -> Self { - self.property_attribute = property_attribute; - self - } + pub fn property_attribute(mut self, property_attribute: PropertyAttribute) -> Self { + self.property_attribute = property_attribute; + self + } - pub fn data(mut self, data: Local<'s, Value>) -> Self { - self.data = Some(data); - self - } + pub fn data(mut self, data: Local<'s, Value>) -> Self { + self.data = Some(data); + self + } - pub fn getter_side_effect_type( - mut self, - side_effect_type: SideEffectType, - ) -> Self { - self.getter_side_effect_type = side_effect_type; - self - } + pub fn getter_side_effect_type(mut self, side_effect_type: SideEffectType) -> Self { + self.getter_side_effect_type = side_effect_type; + self + } - pub fn setter_side_effect_type( - mut self, - side_effect_type: SideEffectType, - ) -> Self { - self.setter_side_effect_type = side_effect_type; - self - } + pub fn setter_side_effect_type(mut self, side_effect_type: SideEffectType) -> Self { + self.setter_side_effect_type = side_effect_type; + self + } } impl<'s> AccessorConfiguration<'s> { - pub fn new(getter: impl MapFnTo) -> Self { - Self { - getter: getter.map_fn_to(), - setter: None, - data: None, - property_attribute: PropertyAttribute::NONE, + pub fn new(getter: impl MapFnTo) -> Self { + Self { + getter: getter.map_fn_to(), + setter: None, + data: None, + property_attribute: PropertyAttribute::NONE, + } } - } - pub fn setter( - mut self, - setter: impl MapFnTo, - ) -> Self { - self.setter = Some(setter.map_fn_to()); - self - } + pub fn setter(mut self, setter: impl MapFnTo) -> Self { + self.setter = Some(setter.map_fn_to()); + self + } - pub fn property_attribute( - mut self, - property_attribute: PropertyAttribute, - ) -> Self { - self.property_attribute = property_attribute; - self - } + pub fn property_attribute(mut self, property_attribute: PropertyAttribute) -> Self { + self.property_attribute = property_attribute; + self + } - /// Set the associated data. The default is no associated data. - pub fn data(mut self, data: Local<'s, Value>) -> Self { - self.data = Some(data); - self - } + /// Set the associated data. The default is no associated data. + pub fn data(mut self, data: Local<'s, Value>) -> Self { + self.data = Some(data); + self + } } #[derive(Default)] pub struct NamedPropertyHandlerConfiguration<'s> { - pub(crate) getter: Option, - pub(crate) setter: Option, - pub(crate) query: Option, - pub(crate) deleter: Option, - pub(crate) enumerator: Option, - pub(crate) definer: Option, - pub(crate) descriptor: Option, - pub(crate) data: Option>, - pub(crate) flags: PropertyHandlerFlags, + pub(crate) getter: Option, + pub(crate) setter: Option, + pub(crate) query: Option, + pub(crate) deleter: Option, + pub(crate) enumerator: Option, + pub(crate) definer: Option, + pub(crate) descriptor: Option, + pub(crate) data: Option>, + pub(crate) flags: PropertyHandlerFlags, } impl<'s> NamedPropertyHandlerConfiguration<'s> { - pub fn new() -> Self { - Self { - getter: None, - setter: None, - query: None, - deleter: None, - enumerator: None, - definer: None, - descriptor: None, - data: None, - flags: PropertyHandlerFlags::NONE, + pub fn new() -> Self { + Self { + getter: None, + setter: None, + query: None, + deleter: None, + enumerator: None, + definer: None, + descriptor: None, + data: None, + flags: PropertyHandlerFlags::NONE, + } } - } - pub fn is_some(&self) -> bool { - self.getter.is_some() - || self.setter.is_some() - || self.query.is_some() - || self.deleter.is_some() - || self.enumerator.is_some() - || self.definer.is_some() - || self.descriptor.is_some() - || !self.flags.is_none() - } + pub fn is_some(&self) -> bool { + self.getter.is_some() + || self.setter.is_some() + || self.query.is_some() + || self.deleter.is_some() + || self.enumerator.is_some() + || self.definer.is_some() + || self.descriptor.is_some() + || !self.flags.is_none() + } - pub fn getter( - mut self, - getter: impl MapFnTo, - ) -> Self { - self.getter = Some(getter.map_fn_to()); - self - } + pub fn getter(mut self, getter: impl MapFnTo) -> Self { + self.getter = Some(getter.map_fn_to()); + self + } - pub fn getter_raw(mut self, getter: NamedPropertyGetterCallback) -> Self { - self.getter = Some(getter); - self - } + pub fn getter_raw(mut self, getter: NamedPropertyGetterCallback) -> Self { + self.getter = Some(getter); + self + } - pub fn setter( - mut self, - setter: impl MapFnTo, - ) -> Self { - self.setter = Some(setter.map_fn_to()); - self - } + pub fn setter(mut self, setter: impl MapFnTo) -> Self { + self.setter = Some(setter.map_fn_to()); + self + } - pub fn setter_raw(mut self, setter: NamedPropertySetterCallback) -> Self { - self.setter = Some(setter); - self - } + pub fn setter_raw(mut self, setter: NamedPropertySetterCallback) -> Self { + self.setter = Some(setter); + self + } - pub fn query( - mut self, - query: impl MapFnTo, - ) -> Self { - self.query = Some(query.map_fn_to()); - self - } + pub fn query(mut self, query: impl MapFnTo) -> Self { + self.query = Some(query.map_fn_to()); + self + } - pub fn query_raw(mut self, query: NamedPropertyQueryCallback) -> Self { - self.query = Some(query); - self - } + pub fn query_raw(mut self, query: NamedPropertyQueryCallback) -> Self { + self.query = Some(query); + self + } - pub fn deleter( - mut self, - deleter: impl MapFnTo, - ) -> Self { - self.deleter = Some(deleter.map_fn_to()); - self - } + pub fn deleter(mut self, deleter: impl MapFnTo) -> Self { + self.deleter = Some(deleter.map_fn_to()); + self + } - pub fn deleter_raw(mut self, deleter: NamedPropertyDeleterCallback) -> Self { - self.deleter = Some(deleter); - self - } + pub fn deleter_raw(mut self, deleter: NamedPropertyDeleterCallback) -> Self { + self.deleter = Some(deleter); + self + } - pub fn enumerator( - mut self, - enumerator: impl MapFnTo, - ) -> Self { - self.enumerator = Some(enumerator.map_fn_to()); - self - } + pub fn enumerator(mut self, enumerator: impl MapFnTo) -> Self { + self.enumerator = Some(enumerator.map_fn_to()); + self + } - pub fn enumerator_raw( - mut self, - enumerator: NamedPropertyEnumeratorCallback, - ) -> Self { - self.enumerator = Some(enumerator); - self - } + pub fn enumerator_raw(mut self, enumerator: NamedPropertyEnumeratorCallback) -> Self { + self.enumerator = Some(enumerator); + self + } - pub fn definer( - mut self, - definer: impl MapFnTo, - ) -> Self { - self.definer = Some(definer.map_fn_to()); - self - } + pub fn definer(mut self, definer: impl MapFnTo) -> Self { + self.definer = Some(definer.map_fn_to()); + self + } - pub fn definer_raw(mut self, definer: NamedPropertyDefinerCallback) -> Self { - self.definer = Some(definer); - self - } + pub fn definer_raw(mut self, definer: NamedPropertyDefinerCallback) -> Self { + self.definer = Some(definer); + self + } - pub fn descriptor( - mut self, - descriptor: impl MapFnTo, - ) -> Self { - self.descriptor = Some(descriptor.map_fn_to()); - self - } + pub fn descriptor(mut self, descriptor: impl MapFnTo) -> Self { + self.descriptor = Some(descriptor.map_fn_to()); + self + } - pub fn descriptor_raw( - mut self, - descriptor: NamedPropertyDescriptorCallback, - ) -> Self { - self.descriptor = Some(descriptor); - self - } + pub fn descriptor_raw(mut self, descriptor: NamedPropertyDescriptorCallback) -> Self { + self.descriptor = Some(descriptor); + self + } - /// Set the associated data. The default is no associated data. - pub fn data(mut self, data: Local<'s, Value>) -> Self { - self.data = Some(data); - self - } + /// Set the associated data. The default is no associated data. + pub fn data(mut self, data: Local<'s, Value>) -> Self { + self.data = Some(data); + self + } - /// Set the property handler flags. The default is PropertyHandlerFlags::NONE. - pub fn flags(mut self, flags: PropertyHandlerFlags) -> Self { - self.flags = flags; - self - } + /// Set the property handler flags. The default is PropertyHandlerFlags::NONE. + pub fn flags(mut self, flags: PropertyHandlerFlags) -> Self { + self.flags = flags; + self + } } #[derive(Default)] pub struct IndexedPropertyHandlerConfiguration<'s> { - pub(crate) getter: Option, - pub(crate) setter: Option, - pub(crate) query: Option, - pub(crate) deleter: Option, - pub(crate) enumerator: Option, - pub(crate) definer: Option, - pub(crate) descriptor: Option, - pub(crate) data: Option>, - pub(crate) flags: PropertyHandlerFlags, + pub(crate) getter: Option, + pub(crate) setter: Option, + pub(crate) query: Option, + pub(crate) deleter: Option, + pub(crate) enumerator: Option, + pub(crate) definer: Option, + pub(crate) descriptor: Option, + pub(crate) data: Option>, + pub(crate) flags: PropertyHandlerFlags, } impl<'s> IndexedPropertyHandlerConfiguration<'s> { - pub fn new() -> Self { - Self { - getter: None, - setter: None, - query: None, - deleter: None, - enumerator: None, - definer: None, - descriptor: None, - data: None, - flags: PropertyHandlerFlags::NONE, + pub fn new() -> Self { + Self { + getter: None, + setter: None, + query: None, + deleter: None, + enumerator: None, + definer: None, + descriptor: None, + data: None, + flags: PropertyHandlerFlags::NONE, + } } - } - pub fn is_some(&self) -> bool { - self.getter.is_some() - || self.setter.is_some() - || self.query.is_some() - || self.deleter.is_some() - || self.enumerator.is_some() - || self.definer.is_some() - || self.descriptor.is_some() - || !self.flags.is_none() - } + pub fn is_some(&self) -> bool { + self.getter.is_some() + || self.setter.is_some() + || self.query.is_some() + || self.deleter.is_some() + || self.enumerator.is_some() + || self.definer.is_some() + || self.descriptor.is_some() + || !self.flags.is_none() + } - pub fn getter( - mut self, - getter: impl MapFnTo, - ) -> Self { - self.getter = Some(getter.map_fn_to()); - self - } + pub fn getter(mut self, getter: impl MapFnTo) -> Self { + self.getter = Some(getter.map_fn_to()); + self + } - pub fn getter_raw(mut self, getter: IndexedPropertyGetterCallback) -> Self { - self.getter = Some(getter); - self - } + pub fn getter_raw(mut self, getter: IndexedPropertyGetterCallback) -> Self { + self.getter = Some(getter); + self + } - pub fn setter( - mut self, - setter: impl MapFnTo, - ) -> Self { - self.setter = Some(setter.map_fn_to()); - self - } + pub fn setter(mut self, setter: impl MapFnTo) -> Self { + self.setter = Some(setter.map_fn_to()); + self + } - pub fn setter_raw(mut self, setter: IndexedPropertySetterCallback) -> Self { - self.setter = Some(setter); - self - } + pub fn setter_raw(mut self, setter: IndexedPropertySetterCallback) -> Self { + self.setter = Some(setter); + self + } - pub fn query( - mut self, - query: impl MapFnTo, - ) -> Self { - self.query = Some(query.map_fn_to()); - self - } + pub fn query(mut self, query: impl MapFnTo) -> Self { + self.query = Some(query.map_fn_to()); + self + } - pub fn query_raw(mut self, query: IndexedPropertyQueryCallback) -> Self { - self.query = Some(query); - self - } + pub fn query_raw(mut self, query: IndexedPropertyQueryCallback) -> Self { + self.query = Some(query); + self + } - pub fn deleter( - mut self, - deleter: impl MapFnTo, - ) -> Self { - self.deleter = Some(deleter.map_fn_to()); - self - } + pub fn deleter(mut self, deleter: impl MapFnTo) -> Self { + self.deleter = Some(deleter.map_fn_to()); + self + } - pub fn deleter_raw( - mut self, - deleter: IndexedPropertyDeleterCallback, - ) -> Self { - self.deleter = Some(deleter); - self - } + pub fn deleter_raw(mut self, deleter: IndexedPropertyDeleterCallback) -> Self { + self.deleter = Some(deleter); + self + } - pub fn enumerator( - mut self, - enumerator: impl MapFnTo, - ) -> Self { - self.enumerator = Some(enumerator.map_fn_to()); - self - } + pub fn enumerator( + mut self, + enumerator: impl MapFnTo, + ) -> Self { + self.enumerator = Some(enumerator.map_fn_to()); + self + } - pub fn enumerator_raw( - mut self, - enumerator: IndexedPropertyEnumeratorCallback, - ) -> Self { - self.enumerator = Some(enumerator); - self - } + pub fn enumerator_raw(mut self, enumerator: IndexedPropertyEnumeratorCallback) -> Self { + self.enumerator = Some(enumerator); + self + } - pub fn definer( - mut self, - definer: impl MapFnTo, - ) -> Self { - self.definer = Some(definer.map_fn_to()); - self - } + pub fn definer(mut self, definer: impl MapFnTo) -> Self { + self.definer = Some(definer.map_fn_to()); + self + } - pub fn definer_raw( - mut self, - definer: IndexedPropertyDefinerCallback, - ) -> Self { - self.definer = Some(definer); - self - } + pub fn definer_raw(mut self, definer: IndexedPropertyDefinerCallback) -> Self { + self.definer = Some(definer); + self + } - pub fn descriptor( - mut self, - descriptor: impl MapFnTo, - ) -> Self { - self.descriptor = Some(descriptor.map_fn_to()); - self - } + pub fn descriptor( + mut self, + descriptor: impl MapFnTo, + ) -> Self { + self.descriptor = Some(descriptor.map_fn_to()); + self + } - pub fn descriptor_raw( - mut self, - descriptor: IndexedPropertyDescriptorCallback, - ) -> Self { - self.descriptor = Some(descriptor); - self - } + pub fn descriptor_raw(mut self, descriptor: IndexedPropertyDescriptorCallback) -> Self { + self.descriptor = Some(descriptor); + self + } - /// Set the associated data. The default is no associated data. - pub fn data(mut self, data: Local<'s, Value>) -> Self { - self.data = Some(data); - self - } + /// Set the associated data. The default is no associated data. + pub fn data(mut self, data: Local<'s, Value>) -> Self { + self.data = Some(data); + self + } - /// Set the property handler flags. The default is PropertyHandlerFlags::NONE. - pub fn flags(mut self, flags: PropertyHandlerFlags) -> Self { - self.flags = flags; - self - } + /// Set the property handler flags. The default is PropertyHandlerFlags::NONE. + pub fn flags(mut self, flags: PropertyHandlerFlags) -> Self { + self.flags = flags; + self + } } #[derive(Debug, Clone, Copy)] #[repr(C)] pub enum Intrinsic { - ArrayProtoEntries, - ArrayProtoForEach, - ArrayProtoKeys, - ArrayProtoValues, - ArrayPrototype, - AsyncIteratorPrototype, - ErrorPrototype, - IteratorPrototype, - MapIteratorPrototype, - ObjProtoValueOf, - SetIteratorPrototype, + ArrayProtoEntries, + ArrayProtoForEach, + ArrayProtoKeys, + ArrayProtoValues, + ArrayPrototype, + AsyncIteratorPrototype, + ErrorPrototype, + IteratorPrototype, + MapIteratorPrototype, + ObjProtoValueOf, + SetIteratorPrototype, } impl Template { - /// Adds a property to each instance created by this template. - #[inline(always)] - pub fn set(&self, key: Local, value: Local) { - self.set_with_attr(key, value, PropertyAttribute::NONE); - } - - /// Adds a property to each instance created by this template with - /// the specified property attributes. - #[inline(always)] - pub fn set_with_attr( - &self, - key: Local, - value: Local, - attr: PropertyAttribute, - ) { - unsafe { v8__Template__Set(self, &*key, &*value, attr) } - } - - /// Adds a data-like property whose value is produced on first read. - #[inline(always)] - pub fn set_lazy_data_property( - &self, - key: Local, - getter: impl MapFnTo, - ) { - self.set_lazy_data_property_with_configuration( - key, - LazyDataPropertyConfiguration::new(getter), - ); - } - - #[inline(always)] - pub fn set_lazy_data_property_with_configuration( - &self, - key: Local, - configuration: LazyDataPropertyConfiguration, - ) { - unsafe { - v8__Template__SetLazyDataProperty( - self, - &*key, - configuration.getter, - configuration.data.map_or_else(null, |p| &*p), - configuration.property_attribute, - configuration.getter_side_effect_type, - configuration.setter_side_effect_type, - ); + /// Adds a property to each instance created by this template. + #[inline(always)] + pub fn set(&self, key: Local, value: Local) { + self.set_with_attr(key, value, PropertyAttribute::NONE); } - } - /// During template instantiation, sets the value with the - /// intrinsic property from the correct context. - #[inline(always)] - pub fn set_intrinsic_data_property( - &self, - key: Local, - intrinsic: Intrinsic, - attr: PropertyAttribute, - ) { - unsafe { - v8__Template__SetIntrinsicDataProperty(self, &*key, intrinsic, attr); + /// Adds a property to each instance created by this template with + /// the specified property attributes. + #[inline(always)] + pub fn set_with_attr(&self, key: Local, value: Local, attr: PropertyAttribute) { + unsafe { v8__Template__Set(self, &*key, &*value, attr) } + } + + /// Adds a data-like property whose value is produced on first read. + #[inline(always)] + pub fn set_lazy_data_property( + &self, + key: Local, + getter: impl MapFnTo, + ) { + self.set_lazy_data_property_with_configuration( + key, + LazyDataPropertyConfiguration::new(getter), + ); + } + + #[inline(always)] + pub fn set_lazy_data_property_with_configuration( + &self, + key: Local, + configuration: LazyDataPropertyConfiguration, + ) { + unsafe { + v8__Template__SetLazyDataProperty( + self, + &*key, + configuration.getter, + configuration.data.map_or_else(null, |p| &*p), + configuration.property_attribute, + configuration.getter_side_effect_type, + configuration.setter_side_effect_type, + ); + } + } + + /// During template instantiation, sets the value with the + /// intrinsic property from the correct context. + #[inline(always)] + pub fn set_intrinsic_data_property( + &self, + key: Local, + intrinsic: Intrinsic, + attr: PropertyAttribute, + ) { + unsafe { + v8__Template__SetIntrinsicDataProperty(self, &*key, intrinsic, attr); + } } - } } impl<'s> FunctionBuilder<'s, FunctionTemplate> { - /// Set the function call signature. The default is no signature. - #[inline(always)] - pub fn signature(mut self, signature: Local<'s, Signature>) -> Self { - self.signature = Some(signature); - self - } - - /// Creates the function template. - #[inline(always)] - pub fn build<'i>( - self, - scope: &PinScope<'s, 'i, ()>, - ) -> Local<'s, FunctionTemplate> { - unsafe { - scope.cast_local(|sd| { - v8__FunctionTemplate__New( - sd.get_isolate_ptr(), - self.callback, - self.data.map_or_else(null, |p| &*p), - self.signature.map_or_else(null, |p| &*p), - self.length, - self.constructor_behavior, - self.side_effect_type, - null(), - 0, - ) - }) + /// Set the function call signature. The default is no signature. + #[inline(always)] + pub fn signature(mut self, signature: Local<'s, Signature>) -> Self { + self.signature = Some(signature); + self } - .unwrap() - } - /// It's not required to provide `CFunctionInfo` for the overloads - if they - /// are omitted, then they will be automatically created. In some cases it is - /// useful to pass them explicitly - eg. when you are snapshotting you'd provide - /// the overloads and `CFunctionInfo` that would be placed in the external - /// references array. - /// - /// # Lifetime invariant - /// - /// `overloads` is `&'static [CFunction]` because, since - /// [crrev.com/c/7828135], V8 stores the raw `v8::CFunction` pointers it - /// receives via `NewWithCFunctionOverloads` directly inside - /// `FunctionTemplateInfo` (rather than copying them into a managed heap - /// object). The pointed-to storage must therefore outlive every - /// `FunctionTemplate` that references it. A `FunctionTemplate` may live - /// until isolate disposal, so in practice this requires the slice (and its - /// elements, including the `CFunctionInfo`s they reference) to have - /// `'static` storage. Use a `const` slice such as - /// - /// ```ignore - /// const OVERLOADS: &[v8::fast_api::CFunction] = &[FAST_TEST]; - /// ``` - /// - /// or a `static` item; do **not** synthesize the slice from stack-local - /// data. - /// - /// [crrev.com/c/7828135]: https://chromium-review.googlesource.com/c/v8/v8/+/7828135 - pub fn build_fast<'i>( - self, - scope: &PinScope<'s, 'i>, - overloads: &'static [CFunction], - ) -> Local<'s, FunctionTemplate> { - unsafe { - scope.cast_local(|sd| { - v8__FunctionTemplate__New( - sd.get_isolate_ptr(), - self.callback, - self.data.map_or_else(null, |p| &*p), - self.signature.map_or_else(null, |p| &*p), - self.length, - ConstructorBehavior::Throw, - self.side_effect_type, - overloads.as_ptr(), - overloads.len(), - ) - }) + /// Creates the function template. + #[inline(always)] + pub fn build<'i>(self, scope: &PinScope<'s, 'i, ()>) -> Local<'s, FunctionTemplate> { + unsafe { + scope.cast_local(|sd| { + v8__FunctionTemplate__New( + sd.get_isolate_ptr(), + self.callback, + self.data.map_or_else(null, |p| &*p), + self.signature.map_or_else(null, |p| &*p), + self.length, + self.constructor_behavior, + self.side_effect_type, + null(), + 0, + ) + }) + } + .unwrap() + } + + /// It's not required to provide `CFunctionInfo` for the overloads - if they + /// are omitted, then they will be automatically created. In some cases it is + /// useful to pass them explicitly - eg. when you are snapshotting you'd provide + /// the overloads and `CFunctionInfo` that would be placed in the external + /// references array. + /// + /// # Lifetime invariant + /// + /// `overloads` is `&'static [CFunction]` because, since + /// [crrev.com/c/7828135], V8 stores the raw `v8::CFunction` pointers it + /// receives via `NewWithCFunctionOverloads` directly inside + /// `FunctionTemplateInfo` (rather than copying them into a managed heap + /// object). The pointed-to storage must therefore outlive every + /// `FunctionTemplate` that references it. A `FunctionTemplate` may live + /// until isolate disposal, so in practice this requires the slice (and its + /// elements, including the `CFunctionInfo`s they reference) to have + /// `'static` storage. Use a `const` slice such as + /// + /// ```ignore + /// const OVERLOADS: &[v8::fast_api::CFunction] = &[FAST_TEST]; + /// ``` + /// + /// or a `static` item; do **not** synthesize the slice from stack-local + /// data. + /// + /// [crrev.com/c/7828135]: https://chromium-review.googlesource.com/c/v8/v8/+/7828135 + pub fn build_fast<'i>( + self, + scope: &PinScope<'s, 'i>, + overloads: &'static [CFunction], + ) -> Local<'s, FunctionTemplate> { + unsafe { + scope.cast_local(|sd| { + v8__FunctionTemplate__New( + sd.get_isolate_ptr(), + self.callback, + self.data.map_or_else(null, |p| &*p), + self.signature.map_or_else(null, |p| &*p), + self.length, + ConstructorBehavior::Throw, + self.side_effect_type, + overloads.as_ptr(), + overloads.len(), + ) + }) + } + .unwrap() } - .unwrap() - } } /// A Signature specifies which receiver is valid for a function. @@ -889,460 +802,420 @@ impl<'s> FunctionBuilder<'s, FunctionTemplate> { /// from a FunctionTemplate that inherits directly or indirectly from the /// signature's FunctionTemplate. impl Signature { - #[inline(always)] - pub fn new<'s>( - scope: &PinScope<'s, '_, ()>, - templ: Local, - ) -> Local<'s, Self> { - unsafe { - scope.cast_local(|sd| v8__Signature__New(sd.get_isolate_ptr(), &*templ)) + #[inline(always)] + pub fn new<'s>( + scope: &PinScope<'s, '_, ()>, + templ: Local, + ) -> Local<'s, Self> { + unsafe { scope.cast_local(|sd| v8__Signature__New(sd.get_isolate_ptr(), &*templ)) }.unwrap() } - .unwrap() - } } impl FunctionTemplate { - /// Creates a getter template backed by a private property. Property reads - /// use the holder's cached value; explicit calls invoke the callback. - #[inline(always)] - pub fn new_with_cache<'s>( - scope: &PinScope<'s, '_, ()>, - callback: impl MapFnTo, - cache_property: Local<'s, Private>, - ) -> Local<'s, FunctionTemplate> { - unsafe { - scope.cast_local(|sd| { - v8__FunctionTemplate__NewWithCache( - sd.get_isolate_ptr(), - callback.map_fn_to(), - &*cache_property, - ) - }) + /// Creates a getter template backed by a private property. Property reads + /// use the holder's cached value; explicit calls invoke the callback. + #[inline(always)] + pub fn new_with_cache<'s>( + scope: &PinScope<'s, '_, ()>, + callback: impl MapFnTo, + cache_property: Local<'s, Private>, + ) -> Local<'s, FunctionTemplate> { + Self::new_with_cache_raw(scope, callback.map_fn_to(), cache_property) } - .unwrap() - } - /// Controls whether calls skip the receiver's access check. V8 defaults to - /// accepting any receiver; set this to false before instantiating a function - /// whose receiver must be accessible from the actual calling context. - #[inline(always)] - pub fn set_accept_any_receiver(&self, value: bool) { - unsafe { v8__FunctionTemplate__SetAcceptAnyReceiver(self, value) }; - } - - /// Returns true if `value` was created from this function template or from - /// a function template that inherits from it. - #[inline(always)] - pub fn has_instance(&self, value: Local) -> bool { - unsafe { v8__FunctionTemplate__HasInstance(self, &*value) } - } - - /// Create a FunctionBuilder to configure a FunctionTemplate. - /// This is the same as FunctionBuilder::::new(). - #[inline(always)] - pub fn builder<'s>( - callback: impl MapFnTo, - ) -> FunctionBuilder<'s, Self> { - FunctionBuilder::new(callback) - } - - #[inline(always)] - pub fn builder_raw<'s>( - callback: FunctionCallback, - ) -> FunctionBuilder<'s, Self> { - FunctionBuilder::new_raw(callback) - } - - /// Creates a function template. - #[inline(always)] - pub fn new<'s>( - scope: &PinScope<'s, '_, ()>, - callback: impl MapFnTo, - ) -> Local<'s, FunctionTemplate> { - Self::builder(callback).build(scope) - } - - #[inline(always)] - pub fn new_raw<'s>( - scope: &PinScope<'s, '_, ()>, - callback: FunctionCallback, - ) -> Local<'s, FunctionTemplate> { - Self::builder_raw(callback).build(scope) - } - - /// Returns the unique function instance in the current execution context. - #[inline(always)] - pub fn get_function<'s>( - &self, - scope: &PinScope<'s, '_>, - ) -> Option> { - unsafe { - scope.cast_local(|sd| { - v8__FunctionTemplate__GetFunction(self, sd.get_current_context()) - }) + /// Creates a cached getter template from an already mapped native callback. + #[inline(always)] + pub fn new_with_cache_raw<'s>( + scope: &PinScope<'s, '_, ()>, + callback: FunctionCallback, + cache_property: Local<'s, Private>, + ) -> Local<'s, FunctionTemplate> { + unsafe { + scope.cast_local(|sd| { + v8__FunctionTemplate__NewWithCache(sd.get_isolate_ptr(), callback, &*cache_property) + }) + } + .unwrap() } - } - /// Set the class name of the FunctionTemplate. This is used for - /// printing objects created with the function created from the - /// FunctionTemplate as its constructor. - #[inline(always)] - pub fn set_class_name(&self, name: Local) { - unsafe { v8__FunctionTemplate__SetClassName(self, &*name) }; - } - - /// Returns the ObjectTemplate that is used by this - /// FunctionTemplate as a PrototypeTemplate - #[inline(always)] - pub fn prototype_template<'s>( - &self, - scope: &PinScope<'s, '_, ()>, - ) -> Local<'s, ObjectTemplate> { - unsafe { - scope.cast_local(|_sd| v8__FunctionTemplate__PrototypeTemplate(self)) + /// Controls whether calls skip the receiver's access check. V8 defaults to + /// accepting any receiver; set this to false before instantiating a function + /// whose receiver must be accessible from the actual calling context. + #[inline(always)] + pub fn set_accept_any_receiver(&self, value: bool) { + unsafe { v8__FunctionTemplate__SetAcceptAnyReceiver(self, value) }; } - .unwrap() - } - /// Returns the object template that is used for instances created when this function - /// template is called as a constructor. - #[inline(always)] - pub fn instance_template<'s>( - &self, - scope: &PinScope<'s, '_, ()>, - ) -> Local<'s, ObjectTemplate> { - unsafe { - scope.cast_local(|_sd| v8__FunctionTemplate__InstanceTemplate(self)) + /// Returns true if `value` was created from this function template or from + /// a function template that inherits from it. + #[inline(always)] + pub fn has_instance(&self, value: Local) -> bool { + unsafe { v8__FunctionTemplate__HasInstance(self, &*value) } } - .unwrap() - } - /// Causes the function template to inherit from a parent function template. - /// This means the function's prototype.__proto__ is set to the parent function's prototype. - #[inline(always)] - pub fn inherit(&self, parent: Local) { - unsafe { v8__FunctionTemplate__Inherit(self, &*parent) }; - } - - /// Sets the ReadOnly flag in the attributes of the 'prototype' property - /// of functions created from this FunctionTemplate to true. - #[inline(always)] - pub fn read_only_prototype(&self) { - unsafe { v8__FunctionTemplate__ReadOnlyPrototype(self) }; - } - - /// Removes the prototype property from functions created from this FunctionTemplate. - #[inline(always)] - pub fn remove_prototype(&self) { - unsafe { v8__FunctionTemplate__RemovePrototype(self) }; - } - - /// Sets an [accessor property](https://tc39.es/ecma262/#sec-property-attributes) - /// on the function template (i.e. a static accessor on the constructor). - /// - /// # Panics - /// - /// Panics if both `getter` and `setter` are `None`. - #[inline(always)] - pub fn set_accessor_property( - &self, - key: Local, - getter: Option>, - setter: Option>, - attr: PropertyAttribute, - ) { - assert!(getter.is_some() || setter.is_some()); - - unsafe { - let getter = getter.map_or_else(std::ptr::null, |v| &*v); - let setter = setter.map_or_else(std::ptr::null, |v| &*v); - v8__FunctionTemplate__SetAccessorProperty( - self, &*key, getter, setter, attr, - ); + /// Create a FunctionBuilder to configure a FunctionTemplate. + /// This is the same as FunctionBuilder::::new(). + #[inline(always)] + pub fn builder<'s>(callback: impl MapFnTo) -> FunctionBuilder<'s, Self> { + FunctionBuilder::new(callback) + } + + #[inline(always)] + pub fn builder_raw<'s>(callback: FunctionCallback) -> FunctionBuilder<'s, Self> { + FunctionBuilder::new_raw(callback) + } + + /// Creates a function template. + #[inline(always)] + pub fn new<'s>( + scope: &PinScope<'s, '_, ()>, + callback: impl MapFnTo, + ) -> Local<'s, FunctionTemplate> { + Self::builder(callback).build(scope) + } + + #[inline(always)] + pub fn new_raw<'s>( + scope: &PinScope<'s, '_, ()>, + callback: FunctionCallback, + ) -> Local<'s, FunctionTemplate> { + Self::builder_raw(callback).build(scope) + } + + /// Returns the unique function instance in the current execution context. + #[inline(always)] + pub fn get_function<'s>(&self, scope: &PinScope<'s, '_>) -> Option> { + unsafe { + scope.cast_local(|sd| v8__FunctionTemplate__GetFunction(self, sd.get_current_context())) + } + } + + /// Set the class name of the FunctionTemplate. This is used for + /// printing objects created with the function created from the + /// FunctionTemplate as its constructor. + #[inline(always)] + pub fn set_class_name(&self, name: Local) { + unsafe { v8__FunctionTemplate__SetClassName(self, &*name) }; + } + + /// Returns the ObjectTemplate that is used by this + /// FunctionTemplate as a PrototypeTemplate + #[inline(always)] + pub fn prototype_template<'s>( + &self, + scope: &PinScope<'s, '_, ()>, + ) -> Local<'s, ObjectTemplate> { + unsafe { scope.cast_local(|_sd| v8__FunctionTemplate__PrototypeTemplate(self)) }.unwrap() + } + + /// Returns the object template that is used for instances created when this function + /// template is called as a constructor. + #[inline(always)] + pub fn instance_template<'s>(&self, scope: &PinScope<'s, '_, ()>) -> Local<'s, ObjectTemplate> { + unsafe { scope.cast_local(|_sd| v8__FunctionTemplate__InstanceTemplate(self)) }.unwrap() + } + + /// Causes the function template to inherit from a parent function template. + /// This means the function's prototype.__proto__ is set to the parent function's prototype. + #[inline(always)] + pub fn inherit(&self, parent: Local) { + unsafe { v8__FunctionTemplate__Inherit(self, &*parent) }; + } + + /// Sets the ReadOnly flag in the attributes of the 'prototype' property + /// of functions created from this FunctionTemplate to true. + #[inline(always)] + pub fn read_only_prototype(&self) { + unsafe { v8__FunctionTemplate__ReadOnlyPrototype(self) }; + } + + /// Removes the prototype property from functions created from this FunctionTemplate. + #[inline(always)] + pub fn remove_prototype(&self) { + unsafe { v8__FunctionTemplate__RemovePrototype(self) }; + } + + /// Sets an [accessor property](https://tc39.es/ecma262/#sec-property-attributes) + /// on the function template (i.e. a static accessor on the constructor). + /// + /// # Panics + /// + /// Panics if both `getter` and `setter` are `None`. + #[inline(always)] + pub fn set_accessor_property( + &self, + key: Local, + getter: Option>, + setter: Option>, + attr: PropertyAttribute, + ) { + assert!(getter.is_some() || setter.is_some()); + + unsafe { + let getter = getter.map_or_else(std::ptr::null, |v| &*v); + let setter = setter.map_or_else(std::ptr::null, |v| &*v); + v8__FunctionTemplate__SetAccessorProperty(self, &*key, getter, setter, attr); + } } - } } impl ObjectTemplate { - /// Creates an object template. - #[inline(always)] - pub fn new<'s>(scope: &PinScope<'s, '_, ()>) -> Local<'s, ObjectTemplate> { - unsafe { - scope.cast_local(|sd| { - v8__ObjectTemplate__New(sd.get_isolate_ptr(), std::ptr::null()) - }) + /// Creates an object template. + #[inline(always)] + pub fn new<'s>(scope: &PinScope<'s, '_, ()>) -> Local<'s, ObjectTemplate> { + unsafe { + scope.cast_local(|sd| v8__ObjectTemplate__New(sd.get_isolate_ptr(), std::ptr::null())) + } + .unwrap() } - .unwrap() - } - /// Creates an object template from a function template. - #[inline(always)] - pub fn new_from_template<'s>( - scope: &PinScope<'s, '_, ()>, - templ: Local, - ) -> Local<'s, ObjectTemplate> { - unsafe { - scope - .cast_local(|sd| v8__ObjectTemplate__New(sd.get_isolate_ptr(), &*templ)) + /// Creates an object template from a function template. + #[inline(always)] + pub fn new_from_template<'s>( + scope: &PinScope<'s, '_, ()>, + templ: Local, + ) -> Local<'s, ObjectTemplate> { + unsafe { scope.cast_local(|sd| v8__ObjectTemplate__New(sd.get_isolate_ptr(), &*templ)) } + .unwrap() } - .unwrap() - } - /// Creates a new instance of this object template. - #[inline(always)] - pub fn new_instance<'s>( - &self, - scope: &PinScope<'s, '_>, - ) -> Option> { - unsafe { - scope.cast_local(|sd| { - v8__ObjectTemplate__NewInstance(self, sd.get_current_context()) - }) + /// Creates a new instance of this object template. + #[inline(always)] + pub fn new_instance<'s>(&self, scope: &PinScope<'s, '_>) -> Option> { + unsafe { + scope.cast_local(|sd| v8__ObjectTemplate__NewInstance(self, sd.get_current_context())) + } } - } - /// Gets the number of internal fields for objects generated from - /// this template. - #[inline(always)] - pub fn internal_field_count(&self) -> usize { - let count = unsafe { v8__ObjectTemplate__InternalFieldCount(self) }; - usize::try_from(count).expect("bad internal field count") // Can't happen. - } - - /// Sets the number of internal fields for objects generated from - /// this template. - #[inline(always)] - pub fn set_internal_field_count(&self, value: usize) -> bool { - // The C++ API takes an i32 but trying to set a value < 0 - // results in unpredictable behavior, hence we disallow it. - match int::try_from(value) { - Err(_) => false, - Ok(value) => { - unsafe { v8__ObjectTemplate__SetInternalFieldCount(self, value) }; - true - } + /// Gets the number of internal fields for objects generated from + /// this template. + #[inline(always)] + pub fn internal_field_count(&self) -> usize { + let count = unsafe { v8__ObjectTemplate__InternalFieldCount(self) }; + usize::try_from(count).expect("bad internal field count") // Can't happen. } - } - #[inline(always)] - pub fn set_accessor( - &self, - key: Local, - getter: impl MapFnTo, - ) { - self - .set_accessor_with_configuration(key, AccessorConfiguration::new(getter)); - } - - #[inline(always)] - pub fn set_accessor_with_setter( - &self, - key: Local, - getter: impl MapFnTo, - setter: impl MapFnTo, - ) { - self.set_accessor_with_configuration( - key, - AccessorConfiguration::new(getter).setter(setter), - ); - } - - #[inline(always)] - pub fn set_accessor_with_configuration( - &self, - key: Local, - configuration: AccessorConfiguration, - ) { - unsafe { - v8__ObjectTemplate__SetNativeDataProperty( - self, - &*key, - configuration.getter, - configuration.setter, - configuration.data.map_or_else(null, |p| &*p), - configuration.property_attribute, - ); + /// Sets the number of internal fields for objects generated from + /// this template. + #[inline(always)] + pub fn set_internal_field_count(&self, value: usize) -> bool { + // The C++ API takes an i32 but trying to set a value < 0 + // results in unpredictable behavior, hence we disallow it. + match int::try_from(value) { + Err(_) => false, + Ok(value) => { + unsafe { v8__ObjectTemplate__SetInternalFieldCount(self, value) }; + true + } + } } - } - #[inline(always)] - pub fn set_native_data_property( - &self, - key: Local, - getter: impl MapFnTo, - ) { - self.set_accessor(key, getter); - } - - #[inline(always)] - pub fn set_native_data_property_with_setter( - &self, - key: Local, - getter: impl MapFnTo, - setter: impl MapFnTo, - ) { - self.set_accessor_with_setter(key, getter, setter); - } - - #[inline(always)] - pub fn set_native_data_property_with_configuration( - &self, - key: Local, - configuration: NativeDataPropertyConfiguration, - ) { - self.set_accessor_with_configuration(key, configuration); - } - - //Re uses the AccessorNameGetterCallback to avoid implementation conflicts since the declaration for - //GenericNamedPropertyGetterCallback and AccessorNameGetterCallback are the same - pub fn set_named_property_handler( - &self, - configuration: NamedPropertyHandlerConfiguration, - ) { - assert!(configuration.is_some()); - unsafe { - v8__ObjectTemplate__SetNamedPropertyHandler( - self, - configuration.getter, - configuration.setter, - configuration.query, - configuration.deleter, - configuration.enumerator, - configuration.definer, - configuration.descriptor, - configuration.data.map_or_else(null, |p| &*p), - configuration.flags, - ); + #[inline(always)] + pub fn set_accessor(&self, key: Local, getter: impl MapFnTo) { + self.set_accessor_with_configuration(key, AccessorConfiguration::new(getter)); } - } - pub fn set_indexed_property_handler( - &self, - configuration: IndexedPropertyHandlerConfiguration, - ) { - assert!(configuration.is_some()); - unsafe { - v8__ObjectTemplate__SetIndexedPropertyHandler( - self, - configuration.getter, - configuration.setter, - configuration.query, - configuration.deleter, - configuration.enumerator, - configuration.definer, - configuration.descriptor, - configuration.data.map_or_else(null, |p| &*p), - configuration.flags, - ); + #[inline(always)] + pub fn set_accessor_with_setter( + &self, + key: Local, + getter: impl MapFnTo, + setter: impl MapFnTo, + ) { + self.set_accessor_with_configuration( + key, + AccessorConfiguration::new(getter).setter(setter), + ); } - } - /// Sets an [accessor property](https://tc39.es/ecma262/#sec-property-attributes) - /// on the object template. - /// - /// # Panics - /// - /// Panics if both `getter` and `setter` are `None`. - #[inline(always)] - pub fn set_accessor_property( - &self, - key: Local, - getter: Option>, - setter: Option>, - attr: PropertyAttribute, - ) { - assert!(getter.is_some() || setter.is_some()); - - unsafe { - let getter = getter.map_or_else(std::ptr::null, |v| &*v); - let setter = setter.map_or_else(std::ptr::null, |v| &*v); - v8__ObjectTemplate__SetAccessorProperty( - self, &*key, getter, setter, attr, - ); + #[inline(always)] + pub fn set_accessor_with_configuration( + &self, + key: Local, + configuration: AccessorConfiguration, + ) { + unsafe { + v8__ObjectTemplate__SetNativeDataProperty( + self, + &*key, + configuration.getter, + configuration.setter, + configuration.data.map_or_else(null, |p| &*p), + configuration.property_attribute, + ); + } } - } - /// Makes the ObjectTemplate for an immutable prototype exotic object, - /// with an immutable proto. - #[inline(always)] - pub fn set_immutable_proto(&self) { - unsafe { v8__ObjectTemplate__SetImmutableProto(self) }; - } - - /// Marks object instances created from this template as undetectable. - #[inline(always)] - pub fn mark_as_undetectable(&self) { - unsafe { v8__ObjectTemplate__MarkAsUndetectable(self) }; - } - - /// Marks instances as code-like for string-code-generation policy checks. - #[inline(always)] - pub fn set_code_like(&self) { - unsafe { v8__ObjectTemplate__SetCodeLike(self) }; - } - - /// Sets the callback to be used when calling instances created from this - /// template as a function. - /// - /// If no callback is set, instances behave like normal [`Object`]s that - /// cannot be called like [`Function`]s. - #[inline(always)] - pub fn set_call_as_function_handler( - &self, - callback: impl MapFnTo, - data: Option>, - ) { - unsafe { - v8__ObjectTemplate__SetCallAsFunctionHandler( - self, - callback.map_fn_to(), - data.map_or_else(null, |p| &*p), - ); + #[inline(always)] + pub fn set_native_data_property( + &self, + key: Local, + getter: impl MapFnTo, + ) { + self.set_accessor(key, getter); } - } - /// Sets the callback and optional associated data used when instances are - /// called as functions. - #[inline(always)] - pub fn set_call_as_function_handler_with_data( - &self, - callback: impl MapFnTo, - data: Option>, - ) { - self.set_call_as_function_handler(callback, data); - } - - /// Enables embedder-defined access checks and denied-access handlers. - pub fn set_security_token_access_check_and_handlers( - &self, - access_check: AccessCheckCallback, - named: NamedPropertyHandlerConfiguration, - indexed: IndexedPropertyHandlerConfiguration, - ) { - assert!(named.is_some() || indexed.is_some()); - unsafe { - v8__ObjectTemplate__SetSecurityTokenAccessCheckAndHandlers( - self, - access_check, - named.getter, - named.setter, - named.query, - named.deleter, - named.enumerator, - named.definer, - named.descriptor, - named.data.map_or_else(null, |p| &*p), - named.flags, - indexed.getter, - indexed.setter, - indexed.query, - indexed.deleter, - indexed.enumerator, - indexed.definer, - indexed.descriptor, - indexed.data.map_or_else(null, |p| &*p), - indexed.flags, - ); + #[inline(always)] + pub fn set_native_data_property_with_setter( + &self, + key: Local, + getter: impl MapFnTo, + setter: impl MapFnTo, + ) { + self.set_accessor_with_setter(key, getter, setter); + } + + #[inline(always)] + pub fn set_native_data_property_with_configuration( + &self, + key: Local, + configuration: NativeDataPropertyConfiguration, + ) { + self.set_accessor_with_configuration(key, configuration); + } + + //Re uses the AccessorNameGetterCallback to avoid implementation conflicts since the declaration for + //GenericNamedPropertyGetterCallback and AccessorNameGetterCallback are the same + pub fn set_named_property_handler(&self, configuration: NamedPropertyHandlerConfiguration) { + assert!(configuration.is_some()); + unsafe { + v8__ObjectTemplate__SetNamedPropertyHandler( + self, + configuration.getter, + configuration.setter, + configuration.query, + configuration.deleter, + configuration.enumerator, + configuration.definer, + configuration.descriptor, + configuration.data.map_or_else(null, |p| &*p), + configuration.flags, + ); + } + } + + pub fn set_indexed_property_handler(&self, configuration: IndexedPropertyHandlerConfiguration) { + assert!(configuration.is_some()); + unsafe { + v8__ObjectTemplate__SetIndexedPropertyHandler( + self, + configuration.getter, + configuration.setter, + configuration.query, + configuration.deleter, + configuration.enumerator, + configuration.definer, + configuration.descriptor, + configuration.data.map_or_else(null, |p| &*p), + configuration.flags, + ); + } + } + + /// Sets an [accessor property](https://tc39.es/ecma262/#sec-property-attributes) + /// on the object template. + /// + /// # Panics + /// + /// Panics if both `getter` and `setter` are `None`. + #[inline(always)] + pub fn set_accessor_property( + &self, + key: Local, + getter: Option>, + setter: Option>, + attr: PropertyAttribute, + ) { + assert!(getter.is_some() || setter.is_some()); + + unsafe { + let getter = getter.map_or_else(std::ptr::null, |v| &*v); + let setter = setter.map_or_else(std::ptr::null, |v| &*v); + v8__ObjectTemplate__SetAccessorProperty(self, &*key, getter, setter, attr); + } + } + + /// Makes the ObjectTemplate for an immutable prototype exotic object, + /// with an immutable proto. + #[inline(always)] + pub fn set_immutable_proto(&self) { + unsafe { v8__ObjectTemplate__SetImmutableProto(self) }; + } + + /// Marks object instances created from this template as undetectable. + #[inline(always)] + pub fn mark_as_undetectable(&self) { + unsafe { v8__ObjectTemplate__MarkAsUndetectable(self) }; + } + + /// Marks instances as code-like for string-code-generation policy checks. + #[inline(always)] + pub fn set_code_like(&self) { + unsafe { v8__ObjectTemplate__SetCodeLike(self) }; + } + + /// Sets the callback to be used when calling instances created from this + /// template as a function. + /// + /// If no callback is set, instances behave like normal [`Object`]s that + /// cannot be called like [`Function`]s. + #[inline(always)] + pub fn set_call_as_function_handler( + &self, + callback: impl MapFnTo, + data: Option>, + ) { + unsafe { + v8__ObjectTemplate__SetCallAsFunctionHandler( + self, + callback.map_fn_to(), + data.map_or_else(null, |p| &*p), + ); + } + } + + /// Sets the callback and optional associated data used when instances are + /// called as functions. + #[inline(always)] + pub fn set_call_as_function_handler_with_data( + &self, + callback: impl MapFnTo, + data: Option>, + ) { + self.set_call_as_function_handler(callback, data); + } + + /// Enables embedder-defined access checks and denied-access handlers. + pub fn set_security_token_access_check_and_handlers( + &self, + access_check: AccessCheckCallback, + named: NamedPropertyHandlerConfiguration, + indexed: IndexedPropertyHandlerConfiguration, + ) { + assert!(named.is_some() || indexed.is_some()); + unsafe { + v8__ObjectTemplate__SetSecurityTokenAccessCheckAndHandlers( + self, + access_check, + named.getter, + named.setter, + named.query, + named.deleter, + named.enumerator, + named.definer, + named.descriptor, + named.data.map_or_else(null, |p| &*p), + named.flags, + indexed.getter, + indexed.setter, + indexed.query, + indexed.deleter, + indexed.enumerator, + indexed.definer, + indexed.descriptor, + indexed.data.map_or_else(null, |p| &*p), + indexed.flags, + ); + } } - } }