Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
perf(events): reuse realm-local field getters
ldm0bc25227a5c8f
diff --git a/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs b/moli-renderer-v8/src/context_bootstrap/events/wrappers.rsindex 941a7fce5..2bd1bac19 100644--- a/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/wrappers.rs@@ -8,6 +8,74 @@use super::*;use crate::context_bootstrap::{exposed_interfaces, world_wrappers};+const EVENT_ATTRIBUTE_GETTERS_SLOT: &str = "__moliEventAttributeGetters";++// The callback carries the original V8 key. Its projection is chosen once when+// the realm's getter is created, so reads never convert field names to Rust.+#[derive(Clone, Copy)]+enum AttributeProjection {+ Value,+ Target,+ PlatformObject,+ NavigationEntry,+ NavigationDestination,+}++impl AttributeProjection {+ fn for_property(property: &str) -> Self {+ match property {+ "target" | "srcElement" | "currentTarget" => Self::Target,+ "signal" | "formData" | "sourceElement" | "relatedTarget" | "submitter" | "source" => {+ Self::PlatformObject+ }+ "from" => Self::NavigationEntry,+ "destination" => Self::NavigationDestination,+ // Arbitrary JS payloads (detail, data, reason, info, error, state)+ // retain their identity; they are not platform-object projections.+ _ => Self::Value,+ }+ }++ fn project<'s>(+ self,+ scope: &mut v8::PinScope<'s, '_>,+ wrapper: v8::Local<'s, v8::Object>,+ value: v8::Local<'s, v8::Value>,+ ) -> Option<v8::Local<'s, v8::Value>> {+ if matches!(self, Self::Value) {+ return Some(value);+ }+ let context = wrapper.get_creation_context(scope)?;+ match self {+ Self::Value => Some(value),+ Self::Target => Some(match v8::Local::<v8::Object>::try_from(value) {+ Ok(target) => crate::context_bootstrap::shared_event_targets::target_in_realm(+ scope, target, context,+ )+ .into(),+ Err(_) => value,+ }),+ Self::PlatformObject => {+ crate::context_bootstrap::platform_object_worlds::in_realm(scope, value, context)+ }+ Self::NavigationEntry => Some(+ crate::context_bootstrap::history_runtime::native::entry_value_in_realm(+ scope, value, context,+ ),+ ),+ Self::NavigationDestination => {+ let destination = v8::Local::<v8::Object>::try_from(value).ok()?;+ let scope = &mut v8::ContextScope::new(scope, context);+ crate::context_bootstrap::navigation_events::navigation_destination_for_realm(+ scope,+ destination,+ )+ .map(Into::into)+ }+ }+ }+}+pub(crate) fn new_event_state<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> {crate::util::new_null_prototype_object(scope)}@@ -27,6 +95,25 @@ pub(crate) fn initialize_event_wrapper<'s>(super::base::EVENT_BACKING_SLOT,state.into(),);+ // Keep the cache on the existing intrinsic, in V8's heap. It contains only+ // field getters, never an instance/backing or a native persistent root.+ let constructor =+ exposed_interfaces::ensure_intrinsic_interface_constructor(scope, "Event").ok()?;+ let getters =+ crate::util::get_private_object(scope, constructor.into(), EVENT_ATTRIBUTE_GETTERS_SLOT)+ .unwrap_or_else(|| {+ let getters = crate::util::new_null_prototype_object(scope);+ set_private_value(+ scope,+ constructor.into(),+ EVENT_ATTRIBUTE_GETTERS_SLOT,+ getters.into(),+ );+ getters+ });+ let trusted_key = v8str(scope, "isTrusted");+ // Some native events and optional dictionary members have different own+ // fields. Preserve the actual state shape and descriptor order.let names = state.get_own_property_names(scope,v8::GetPropertyNamesArgs {@@ -36,11 +123,11 @@ pub(crate) fn initialize_event_wrapper<'s>()?;for index in 0..names.length() {let property = names.get_index(scope, index)?;- if property.to_rust_string_lossy(scope) == "isTrusted" {+ if property.strict_equals(trusted_key.into()) {super::base::define_event_is_trusted_accessor(scope, wrapper);} else {let attributes = state.get_property_attributes(scope, property)?;- bind_attribute(scope, wrapper, property, attributes)?;+ bind_attribute(scope, getters, wrapper, property, attributes)?;}}if interface == "NavigateEvent" {@@ -68,16 +155,46 @@ pub(crate) fn new_event_wrapper<'s>(fn bind_attribute<'s>(scope: &mut v8::PinScope<'s, '_>,+ getters: v8::Local<'s, v8::Object>,wrapper: v8::Local<'s, v8::Object>,property: v8::Local<'s, v8::Value>,attributes: v8::PropertyAttribute,) -> Option<()> {let name = v8::Local::<v8::Name>::try_from(property).ok()?;- let getter = v8::Function::builder(event_attribute_getter)- .data(property)- .build(scope)?;- let getter_name = format!("get {}", property.to_rust_string_lossy(scope));- getter.set_name(v8_string(scope, &getter_name)?);+ let getter = if let Some(getter) = getters+ .get(scope, property)+ .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())+ {+ getter+ } else {+ let field = property.to_rust_string_lossy(scope);+ let getter = match AttributeProjection::for_property(&field) {+ AttributeProjection::Value => v8::Function::builder(event_attribute_getter::<0>)+ .data(property)+ .build(scope),+ AttributeProjection::Target => v8::Function::builder(event_attribute_getter::<1>)+ .data(property)+ .build(scope),+ AttributeProjection::PlatformObject => {+ v8::Function::builder(event_attribute_getter::<2>)+ .data(property)+ .build(scope)+ }+ AttributeProjection::NavigationEntry => {+ v8::Function::builder(event_attribute_getter::<3>)+ .data(property)+ .build(scope)+ }+ AttributeProjection::NavigationDestination => {+ v8::Function::builder(event_attribute_getter::<4>)+ .data(property)+ .build(scope)+ }+ }?;+ getter.set_name(v8_string(scope, &format!("get {field}"))?);+ getters.create_data_property(scope, name, getter.into())?;+ getter+ };let mut accessor_attributes = v8::PropertyAttribute::NONE;if attributes.is_dont_enum() {accessor_attributes = accessor_attributes | v8::PropertyAttribute::DONT_ENUM;@@ -97,7 +214,7 @@ fn bind_attribute<'s>(.ok()}-fn event_attribute_getter<'s>(+fn event_attribute_getter<'s, const PROJECTION: u8>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,@@ -106,8 +223,19 @@ fn event_attribute_getter<'s>(throw_type_error(scope, "Illegal invocation");return;}- let property = args.data().to_rust_string_lossy(scope);- if let Some(value) = event_attribute_in_wrapper(scope, args.this(), &property) {+ let state = event_backing(scope, args.this());+ let Some(value) = state.get(scope, args.data()) else {+ return;+ };+ let projection = match PROJECTION {+ 0 => AttributeProjection::Value,+ 1 => AttributeProjection::Target,+ 2 => AttributeProjection::PlatformObject,+ 3 => AttributeProjection::NavigationEntry,+ 4 => AttributeProjection::NavigationDestination,+ _ => unreachable!("Event getter projection"),+ };+ if let Some(value) = projection.project(scope, args.this(), value) {rv.set(value);}}@@ -118,18 +246,7 @@ pub(super) fn event_attribute_in_wrapper<'s>(property: &str,) -> Option<v8::Local<'s, v8::Value>> {let value = event_attribute(scope, wrapper, property)?;- let context = wrapper.get_creation_context(scope)?;- if matches!(property, "target" | "srcElement" | "currentTarget")- && let Ok(target) = v8::Local::<v8::Object>::try_from(value)- {- return Some(- crate::context_bootstrap::shared_event_targets::target_in_realm(scope, target, context)- .into(),- );- }- crate::context_bootstrap::navigation_event_worlds::attribute_in_realm(- scope, property, value, context,- )+ AttributeProjection::for_property(property).project(scope, wrapper, value)}/// Engine reads must bypass the public wrapper, including own shadows anddiff --git a/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rsindex f79b8443d..7455a235a 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs@@ -1,7 +1,7 @@//! Event views for one Navigation dispatch. User callbacks never receive the//! internal control object, so page expandos cannot cross into another world.-use super::{events, history_runtime::native, shared_event_targets, world_wrappers};+use super::{events, shared_event_targets, world_wrappers};pub(super) fn event_in_realm<'s>(scope: &mut v8::PinScope<'s, '_>,@@ -23,26 +23,3 @@ pub(super) fn event_in_realm<'s>(let scope = &mut v8::ContextScope::new(scope, context);events::new_event_wrapper(scope, backing)}--pub(super) fn attribute_in_realm<'s>(- scope: &mut v8::PinScope<'s, '_>,- property: &str,- value: v8::Local<'s, v8::Value>,- context: v8::Local<'s, v8::Context>,-) -> Option<v8::Local<'s, v8::Value>> {- match property {- "from" => Some(native::entry_value_in_realm(scope, value, context)),- "destination" => {- let destination = v8::Local::<v8::Object>::try_from(value).ok()?;- let scope = &mut v8::ContextScope::new(scope, context);- super::navigation_events::navigation_destination_for_realm(scope, destination)- .map(Into::into)- }- "signal" | "formData" | "sourceElement" | "relatedTarget" | "submitter" | "source" => {- super::platform_object_worlds::in_realm(scope, value, context)- }- // info, error, detail, data, reason, and state can contain arbitrary JS- // values. They are not platform wrappers or storage-serialized payloads.- _ => Some(value),- }-}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rsindex ca9832efa..4e9f923c3 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs@@ -1,5 +1,65 @@use super::*;+#[test]+fn event_field_getters_are_shared_within_a_realm_without_capturing_instances() {+ let mut vm = new_storage_test_vm("https://event-field-getters.test/");+ let result = vm.eval(r#"+(() => {+ const frame = (document.body || document.documentElement || document)+ .appendChild(document.createElement('iframe'));+ const other = frame.contentWindow;+ const getters = new Set();+ const own = (event, name) => Object.getOwnPropertyDescriptor(event, name);+ const first = new CustomEvent('first', { detail: { value: 1 } });+ const child = new other.CustomEvent('child', { detail: { value: 2 } });+ for (let i = 0; i < 200; i++) {+ const event = new CustomEvent(String(i), { detail: { value: i } });+ for (const name of Object.keys(event)) getters.add(own(event, name).get);+ if (event.type !== String(i) || event.detail.value !== i) throw new Error('captured instance');+ }+ const type = own(first, 'type'), detail = own(first, 'detail');+ const childType = own(child, 'type');+ let illegal = false;+ try { childType.get.call({}); }+ catch (error) { illegal = error instanceof other.TypeError; }+ class DerivedEvent extends CustomEvent {+ constructor() { super('derived'); this.original = this; }+ }+ const derived = new DerivedEvent();+ // Optional ErrorEvent.error must not be inferred from the first instance.+ const withoutError = new ErrorEvent('without');+ const withError = new ErrorEvent('with', { error: first });+ const toggle = new ToggleEvent('toggle');+ const source = own(toggle, 'source');+ return JSON.stringify({+ getterCount: getters.size,+ fieldCount: Object.keys(first).length,+ base: type.get === own(new Event('base'), 'type').get,+ realm: type.get instanceof Function && childType.get instanceof other.Function &&+ childType.get !== type.get && !(childType.get instanceof Function),+ borrowed: type.get.call(child) === 'child' && detail.get.call(child) === child.detail,+ descriptor: [type.get.name, type.get.length, type.set === undefined, type.enumerable, type.configurable],+ trusted: own(first, 'isTrusted').configurable === false && first.isTrusted === false,+ optional: !Object.hasOwn(withoutError, 'error') && Object.hasOwn(withError, 'error') && withError.error === first,+ toggle: !source.enumerable && !source.configurable,+ original: derived === derived.original && derived instanceof DerivedEvent,+ illegal+ });+})()+"#).expect("shared field getters should preserve instances, descriptors and realms");+ let result: serde_json::Value = serde_json::from_str(&result).unwrap();+ assert_eq!(result["getterCount"], result["fieldCount"], "{result}");+ assert_eq!(+ result["descriptor"],+ serde_json::json!(["get type", 0, true, true, true])+ );+ for property in [+ "base", "realm", "borrowed", "trusted", "optional", "toggle", "original", "illegal",+ ] {+ assert_eq!(result[property], true, "{property}: {result}");+ }+}+#[test]fn history_worlds_slot_backed_platform_fields_keep_local_wrappers() {let mut vm = new_storage_test_vm("https://example.com/base");