Skip to content

armgit / moli

Public Imported from GitHub
0

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

feat(webapi): generate private platform object identity

ldm025d7b63e0676
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index ac546e4eb..cc71f863c 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -779,7 +779,7 @@ struct WorkerAbortControllerTemplateDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "WorkerGlobalScope", enumerable)]
+#[webapi(unbranded, interface = "WorkerGlobalScope", enumerable)]
struct WorkerGlobalScopeCryptoPrototypeDeclaration {
#[webapi(accessor_property, getter = worker_crypto_getter_callback)]
crypto: (),
diff --git a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs
index c7c4d7524..688331464 100644
--- a/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs
+++ b/moli-renderer-v8/src/context_bootstrap/canvas/helpers.rs
@@ -4,7 +4,7 @@ use moli_canvas::{DEFAULT_FILL_STYLE, DEFAULT_FONT};
use moli_webapi_declare::WebApiObject;
#[derive(WebApiObject)]
-#[webapi(interface = "CanvasRenderingContext2D")]
+#[webapi(unbranded, interface = "CanvasRenderingContext2D")]
struct CanvasLikeContextObjectDeclaration {
#[webapi(
slot = CANVAS_CONTEXT_FILL_STYLE_SLOT,
diff --git a/moli-renderer-v8/src/context_bootstrap/crypto/install.rs b/moli-renderer-v8/src/context_bootstrap/crypto/install.rs
index 8cf31370d..9007a1be7 100644
--- a/moli-renderer-v8/src/context_bootstrap/crypto/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/crypto/install.rs
@@ -34,7 +34,7 @@ struct SubtleCryptoObjectDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Crypto")]
+#[webapi(unbranded, interface = "Crypto")]
struct CryptoPrototypeAccessorsDeclaration {
#[webapi(
accessor_property,
@@ -58,7 +58,7 @@ struct CryptoPrototypeOperationsDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Crypto")]
+#[webapi(unbranded, interface = "Crypto")]
struct CryptoSecurePrototypeOperationsDeclaration {
#[webapi(
method = "randomUUID",
diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
index 16657fad0..706d94efe 100644
--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
@@ -11,7 +11,7 @@ const ORIGINAL_INTL_DATETIME_FORMAT_RESOLVED_OPTIONS_SLOT: &str =
"__moliOriginalIntlDateTimeFormatResolvedOptions";
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Date")]
+#[webapi(unbranded, interface = "Date")]
struct DateLocalePrototypeDeclaration {
#[webapi(method, length = 0, callback = date_to_locale_string_callback)]
to_locale_string: (),
@@ -22,7 +22,7 @@ struct DateLocalePrototypeDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Intl.DateTimeFormat")]
+#[webapi(unbranded, interface = "Intl.DateTimeFormat")]
struct IntlDateTimeFormatPrototypeDeclaration {
#[webapi(
method = "resolvedOptions",
diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs
index 902540437..b506ab6d4 100644
--- a/moli-renderer-v8/src/context_bootstrap/events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events.rs
@@ -38,7 +38,7 @@ struct StorageEventStateDeclaration<'scope> {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "PointerEvent", enumerable)]
+#[webapi(unbranded, interface = "PointerEvent", enumerable)]
struct SecurePointerEventPrototypeRuntimeDeclaration {
#[webapi(
method = "getCoalescedEvents",
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/template_registry.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/template_registry.rs
index 48fe0a2ba..c58a71ab6 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/template_registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/template_registry.rs
@@ -59,6 +59,10 @@ impl ExposedInterfaceTemplateRegistry {
profile: TemplateBuildProfile,
) -> Result<Rc<Self>> {
let metadata = ExposedInterfaceMetadataTable::from_constructor_specs(&specs)?;
+ moli_webapi_declare::register_web_api_interfaces(
+ scope,
+ specs.iter().map(|spec| (spec.name, spec.parent)),
+ )?;
let templates = (0..metadata.len())
.map(|_| ExposedInterfaceTemplateEntry::new())
.collect();
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface/accessors.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface/accessors.rs
index 5c461a61b..520e9eb80 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/accessors.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/accessors.rs
@@ -27,7 +27,7 @@ impl ScrollRestoration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "History")]
+#[webapi(unbranded, interface = "History")]
struct HistoryPrototypeAccessorsDeclaration {
#[webapi(accessor_property, getter = history_length_getter_function, enumerable)]
length: (),
@@ -45,7 +45,7 @@ struct HistoryPrototypeAccessorsDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Navigation")]
+#[webapi(unbranded, interface = "Navigation")]
struct NavigationPrototypeAccessorsDeclaration {
#[webapi(accessor_property = "canGoBack", getter = navigation_can_go_back_getter_function, enumerable)]
can_go_back: (),
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
index 2a010678c..3912f2ded 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
@@ -85,7 +85,7 @@ struct PerformanceJsonSnapshotDeclaration<'scope> {
}
#[derive(WebApiObject)]
-#[webapi(interface = "PerformanceObserver")]
+#[webapi(unbranded, interface = "PerformanceObserver")]
struct PerformanceObserverConstructorDeclaration {
#[webapi(data_property = "supportedEntryTypes")]
supported_entry_types: &'static [&'static str],
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index e51459d47..f1caed23c 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -69,14 +69,14 @@ struct HtmlScriptElementSupportsArgs {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "HTMLScriptElement", enumerable)]
+#[webapi(unbranded, interface = "HTMLScriptElement", enumerable)]
struct HtmlScriptElementStaticMethodsDeclaration {
#[webapi(method, length = 1, callback = html_script_element_supports_callback)]
supports: (),
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Document", enumerable)]
+#[webapi(unbranded, interface = "Document", enumerable)]
struct DocumentStaticMethodsDeclaration {
#[webapi(
method = "parseHTMLUnsafe",
@@ -87,7 +87,7 @@ struct DocumentStaticMethodsDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Document", enumerable)]
+#[webapi(unbranded, interface = "Document", enumerable)]
struct DocumentPrototypeRuntimeDeclaration {
#[webapi(
accessor_property = "designMode",
@@ -288,7 +288,7 @@ struct WindowLegacyAliasAccessorsDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "Window", enumerable)]
+#[webapi(unbranded, interface = "Window", enumerable)]
struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> {
origin_name: v8::Local<'scope, v8::Value>,
inner_width_name: v8::Local<'scope, v8::Value>,
diff --git a/moli-renderer-v8/src/context_bootstrap/shared_installers/constants.rs b/moli-renderer-v8/src/context_bootstrap/shared_installers/constants.rs
index d5eceb34b..90b74b6e9 100644
--- a/moli-renderer-v8/src/context_bootstrap/shared_installers/constants.rs
+++ b/moli-renderer-v8/src/context_bootstrap/shared_installers/constants.rs
@@ -39,7 +39,7 @@ struct NodeFilterConstantsObjectDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "Window")]
+#[webapi(unbranded, interface = "Window")]
struct NodeFilterGlobalDeclaration<'scope> {
#[webapi(data_property = "NodeFilter")]
node_filter: v8::Local<'scope, v8::Function>,
diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/construction.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/construction.rs
index 8dc26d568..b52eceb35 100644
--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/construction.rs
+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/construction.rs
@@ -145,7 +145,7 @@ struct WritableStreamObjectDeclaration<'scope, 'value> {
}
#[derive(WebApiObject)]
-#[webapi(interface = "TransformStream")]
+#[webapi(interface = "TransformStream", unbranded)]
struct TransformStreamObjectDeclaration<'scope> {
#[webapi(slot = TRANSFORM_STREAM_READABLE_SLOT)]
readable: v8::Local<'scope, v8::Object>,
@@ -213,6 +213,14 @@ pub(in crate::context_bootstrap) fn initialize_transform_stream_object<'s>(
TransformStreamObjectDeclaration::new(readable, writable)
.initialize(scope, stream)
.expect("TransformStream declaration should initialize object");
+ // Encoding wrappers share endpoint storage, but are separate interfaces.
+ let interface = match mode {
+ Some("text-encoder") => "TextEncoderStream",
+ Some("text-decoder") => "TextDecoderStream",
+ _ => "TransformStream",
+ };
+ moli_webapi_declare::initialize_web_api_object(scope, stream, interface)
+ .expect("stream identity should initialize");
}
pub(in crate::context_bootstrap) fn initialize_webidl_transform_stream_object<'s>(
@@ -314,6 +322,8 @@ pub(in crate::context_bootstrap) fn initialize_webidl_transform_stream_object<'s
TransformStreamObjectDeclaration::new(readable, writable)
.initialize(scope, stream)
.expect("TransformStream declaration should initialize object");
+ moli_webapi_declare::initialize_web_api_object(scope, stream, "TransformStream")
+ .expect("TransformStream identity should initialize");
}
fn install_transform_stream_readable_pull_algorithm<'s>(
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 da85c06e0..95b609a74 100644
--- a/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs
@@ -37,7 +37,7 @@ struct StoragePrototypeMethodsDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Storage")]
+#[webapi(unbranded, interface = "Storage")]
struct StoragePrototypeMetadataDeclaration {
#[webapi(to_string_tag, init = string("Storage"))]
to_string_tag: (),
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 8685ea233..08a3a0c64 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_events/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_events/install.rs
@@ -11,7 +11,7 @@ use crate::util::v8str;
use moli_webapi_declare::WebApiObject;
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Window")]
+#[webapi(unbranded, interface = "Window")]
struct WindowGlobalEventHandlerAccessorsDeclaration {
#[webapi(
accessor_property,
diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
index e54d19ccf..b01ad2dba 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs
@@ -248,7 +248,7 @@ struct NavigatorUaDataHighEntropySnapshotDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "StorageEstimate")]
+#[webapi(unbranded, interface = "StorageEstimate")]
struct StorageEstimateObjectDeclaration<'scope> {
#[webapi(data_property, enumerable)]
quota: f64,
diff --git a/moli-renderer-v8/src/context_bootstrap/worker_location_runtime.rs b/moli-renderer-v8/src/context_bootstrap/worker_location_runtime.rs
index 9129e75d9..4fde3c647 100644
--- a/moli-renderer-v8/src/context_bootstrap/worker_location_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/worker_location_runtime.rs
@@ -23,7 +23,7 @@ struct WorkerLocationGlobalDeclaration<'scope> {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "WorkerLocation", enumerable)]
+#[webapi(unbranded, interface = "WorkerLocation", enumerable)]
struct WorkerLocationPrototypeDeclaration {
#[webapi(
accessor_property,
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods.rs b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods.rs
index 0804cf949..31e4fb9b3 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods.rs
@@ -13,7 +13,7 @@ use live_attribute_bridge::install_live_attribute_bridge_methods;
use node::{install_detached_node_methods, install_detached_parent_node_move_before};
#[derive(WebApiObject)]
-#[webapi(interface = "ParentNode")]
+#[webapi(unbranded, interface = "ParentNode")]
struct DocumentFragmentParentNodeQueryMethodsDeclaration {
#[webapi(method, callback = node_query_selector_callback)]
query_selector: (),
@@ -23,7 +23,7 @@ struct DocumentFragmentParentNodeQueryMethodsDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "DocumentFragment")]
+#[webapi(unbranded, interface = "DocumentFragment")]
struct DocumentFragmentGetElementByIdDeclaration {
#[webapi(method, length = 1, callback = document_fragment_get_element_by_id_callback)]
get_element_by_id: (),
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/document.rs b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/document.rs
index b30e85082..63fb489e6 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/document.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/document.rs
@@ -2,7 +2,7 @@ use super::*;
use moli_webapi_declare::WebApiObject;
#[derive(WebApiObject)]
-#[webapi(interface = "Document")]
+#[webapi(unbranded, interface = "Document")]
struct DetachedDocumentStateAccessorsDeclaration {
#[webapi(
accessor_property,
@@ -15,7 +15,7 @@ struct DetachedDocumentStateAccessorsDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "HTMLDocument")]
+#[webapi(unbranded, interface = "HTMLDocument")]
struct DetachedHtmlDocumentCreationMethodsDeclaration {
#[webapi(method, callback = detached_create_html_element_method_callback)]
create_element: (),
@@ -37,7 +37,7 @@ struct DetachedHtmlDocumentCreationMethodsDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "XMLDocument")]
+#[webapi(unbranded, interface = "XMLDocument")]
struct DetachedXmlDocumentCreationMethodsDeclaration {
#[webapi(method, callback = detached_create_xml_element_method_callback)]
create_element: (),
@@ -56,7 +56,7 @@ struct DetachedXmlDocumentCreationMethodsDeclaration {
}
#[derive(WebApiObject)]
-#[webapi(interface = "Document")]
+#[webapi(unbranded, interface = "Document")]
struct DetachedDocumentCommonMethodsDeclaration {
#[webapi(method, callback = detached_create_attribute_method_callback)]
create_attribute: (),
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/node.rs b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/node.rs
index 8491e1ba2..1486f4b5d 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/node.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_install/bridge_methods/node.rs
@@ -2,7 +2,7 @@ use super::*;
use moli_webapi_declare::WebApiObject;
#[derive(Default, WebApiObject)]
-#[webapi(interface = "Node")]
+#[webapi(unbranded, interface = "Node")]
struct DetachedNodeMethodsDeclaration {
#[webapi(method, callback = detached_append_child_method_callback)]
append_child: (),
@@ -73,7 +73,7 @@ pub(super) fn install_detached_parent_node_move_before<'s>(
prototype: v8::Local<'s, v8::Object>,
) {
#[derive(Default, WebApiObject)]
- #[webapi(interface = "ParentNode")]
+ #[webapi(unbranded, interface = "ParentNode")]
struct DetachedParentNodeMoveBeforeDeclaration {
#[webapi(method, length = 2, callback = detached_move_before_method_callback)]
move_before: (),
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs
index 4f1f4188c..871fef123 100644
--- a/moli-renderer-v8/src/network_host.rs
+++ b/moli-renderer-v8/src/network_host.rs
@@ -198,7 +198,7 @@ pub(crate) use crate::protocol_types::extract_subresource_auth_challenge;
pub(crate) use moli_fetch::NET_ERR_ABORTED_ERROR_TEXT as ABORTED_ERROR_TEXT;
#[derive(WebApiObject)]
-#[webapi(interface = "Response")]
+#[webapi(unbranded, interface = "Response")]
struct ChildResponseConstructorDeclaration<'scope> {
data: v8::Local<'scope, v8::Value>,
diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rs
index 53131ad6f..e6c473d22 100644
--- a/moli-renderer-v8/src/worker/global_scope/mod.rs
+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs
@@ -374,7 +374,7 @@ struct SharedWorkerGlobalEventHandlerStateDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "DedicatedWorkerGlobalScope", enumerable)]
+#[webapi(unbranded, interface = "DedicatedWorkerGlobalScope", enumerable)]
struct DedicatedWorkerGlobalMethodsDeclaration {
#[webapi(method, callback = worker_close_callback, length = 0)]
close: (),
@@ -388,7 +388,7 @@ struct DedicatedWorkerGlobalPostMessageDeclaration {
}
#[derive(Default, WebApiObject)]
-#[webapi(interface = "SharedWorkerGlobalScope", enumerable)]
+#[webapi(unbranded, interface = "SharedWorkerGlobalScope", enumerable)]
struct SharedWorkerGlobalMethodsDeclaration {
#[webapi(method, callback = worker_close_callback, length = 0)]
close: (),
@@ -5598,6 +5598,10 @@ fn install_service_worker_extendable_event_constructors<'s>(
.map_err(|error| anyhow!("failed to initialize ExtendableMessageEvent global: {error}"))?;
ensure_worker_interface_constructor(scope, "ServiceWorker")?;
+ moli_webapi_declare::register_web_api_interfaces(
+ scope,
+ [("Client", None), ("WindowClient", Some("Client"))],
+ )?;
ensure_worker_interface_constructor(scope, "Client")?;
ensure_worker_interface_constructor(scope, "WindowClient")?;
if let Some(client_ctor) = global_constructor_object(scope, "Client")
diff --git a/moli-webapi-declare-derive/src/attrs.rs b/moli-webapi-declare-derive/src/attrs.rs
index c79e820f9..95fe1630c 100644
--- a/moli-webapi-declare-derive/src/attrs.rs
+++ b/moli-webapi-declare-derive/src/attrs.rs
@@ -59,6 +59,7 @@ pub(crate) struct ObjectAttrs {
pub(crate) default_data_properties: bool,
pub(crate) default_enumerable: bool,
pub(crate) no_dynamic_constructor: bool,
+ pub(crate) unbranded: bool,
}
#[derive(Default)]
@@ -209,6 +210,10 @@ pub(crate) fn parse_object_attrs(attrs: &[syn::Attribute]) -> Result<ObjectAttrs
let mut parsed = ObjectAttrs::default();
for attr in attrs.iter().filter(|attr| attr.path().is_ident("webapi")) {
attr.parse_nested_meta(|meta| {
+ if meta.path.is_ident("unbranded") {
+ parsed.unbranded = true;
+ return Ok(());
+ }
if meta.path.is_ident("receiver") {
parsed.receiver = Some(meta.value()?.parse()?);
return Ok(());
diff --git a/moli-webapi-declare-derive/src/expand.rs b/moli-webapi-declare-derive/src/expand.rs
index 0705e5f94..22fed9e6b 100644
--- a/moli-webapi-declare-derive/src/expand.rs
+++ b/moli-webapi-declare-derive/src/expand.rs
@@ -55,6 +55,10 @@ pub(crate) fn expand_webapi_interface(
const INTERFACE_NAME: &'static str = #interface_name;
const PARENT_INTERFACE: ::std::option::Option<&'static str> = #parent;
+ ::moli_webapi_declare::register_web_api_interfaces(
+ scope, [(INTERFACE_NAME, PARENT_INTERFACE)],
+ )?;
+
let prototype = ::moli_webapi_declare::v8::Object::new(scope);
if let ::std::option::Option::Some(parent) = PARENT_INTERFACE {
if let ::std::option::Option::Some(parent_prototype) =
@@ -355,8 +359,14 @@ pub(crate) fn expand_webapi_object(input: DeriveInput) -> Result<proc_macro2::To
));
}
+ let initialize_brand = (!attrs.unbranded && interface.value() != "Object").then(|| {
+ quote! {
+ ::moli_webapi_declare::initialize_web_api_object(scope, object, #interface)?;
+ }
+ });
let initialize_body = quote! {
#(#fields)*
+ #initialize_brand
::std::result::Result::Ok(())
};
let trait_impl = match scope_lifetime {
diff --git a/moli-webapi-declare/src/brand.rs b/moli-webapi-declare/src/brand.rs
new file mode 100644
index 000000000..c5c2bc49d
--- /dev/null
+++ b/moli-webapi-declare/src/brand.rs
@@ -0,0 +1,218 @@
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use moli_v8_util::v8str;
+
+use crate::{BindError, v8};
+
+/// The primary Web IDL interface of a native platform object.
+///
+/// Names come from Rust declarations, never from JavaScript constructors or
+/// prototypes. The numeric representation in V8 is isolate-local and must not
+/// be persisted or used as a structured-clone wire tag.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub struct WebApiType {
+ name: &'static str,
+}
+
+impl WebApiType {
+ pub const fn name(self) -> &'static str {
+ self.name
+ }
+}
+
+#[derive(Clone)]
+struct TypeEntry {
+ name: &'static str,
+ parent: Option<usize>,
+ declared: bool,
+}
+
+struct TypeRegistry {
+ key: v8::Global<v8::Private>,
+ entries: Vec<TypeEntry>,
+ names: HashMap<&'static str, usize>,
+}
+
+impl TypeRegistry {
+ fn intern(&mut self, name: &'static str) -> usize {
+ if let Some(id) = self.names.get(name) {
+ return *id;
+ }
+ let id = self.entries.len();
+ self.entries.push(TypeEntry {
+ name,
+ parent: None,
+ declared: false,
+ });
+ self.names.insert(name, id);
+ id
+ }
+
+ fn implements(&self, mut id: usize, expected: usize) -> bool {
+ // Registration rejects cycles. The bound also makes incomplete native
+ // metadata harmless while a batch of interfaces is being registered.
+ for _ in 0..self.entries.len() {
+ if id == expected {
+ return true;
+ }
+ let Some(parent) = self.entries.get(id).and_then(|entry| entry.parent) else {
+ return false;
+ };
+ id = parent;
+ }
+ false
+ }
+}
+
+fn registry(scope: &mut v8::PinScope<'_, '_, ()>) -> Rc<RefCell<TypeRegistry>> {
+ if let Some(registry) = scope.get_slot::<Rc<RefCell<TypeRegistry>>>() {
+ return registry.clone();
+ }
+ let name = v8str(scope, "__moliWebApiType");
+ let key = v8::Private::new(scope, Some(name));
+ let registry = Rc::new(RefCell::new(TypeRegistry {
+ key: v8::Global::new(scope, key),
+ entries: Vec::new(),
+ names: HashMap::new(),
+ }));
+ scope.as_mut().set_slot(registry.clone());
+ registry
+}
+
+/// Registers interface inheritance from the same metadata used to declare
+/// interfaces. This does not materialize constructors or depend on exposure in
+/// the current realm. Repeated declarations must agree.
+pub fn register_web_api_interfaces<C>(
+ scope: &mut v8::PinScope<'_, '_, C>,
+ interfaces: impl IntoIterator<Item = (&'static str, Option<&'static str>)>,
+) -> Result<(), BindError> {
+ v8::scope!(let scope, scope.as_mut());
+ let registry = registry(scope);
+ let mut registry = registry.borrow_mut();
+ // Validate the whole batch before publishing any inheritance changes.
+ let mut entries = registry.entries.clone();
+ let mut names = registry.names.clone();
+ for (name, parent) in interfaces {
+ if name == "Object" || parent == Some("Object") {
+ return Err(BindError::new("Object is not a Web IDL interface"));
+ }
+ let mut intern = |name| {
+ *names.entry(name).or_insert_with(|| {
+ let id = entries.len();
+ entries.push(TypeEntry {
+ name,
+ parent: None,
+ declared: false,
+ });
+ id
+ })
+ };
+ let id = intern(name);
+ let parent = parent.map(intern);
+ let entry = &mut entries[id];
+ if entry.declared && entry.parent != parent {
+ return Err(BindError::new(format!("conflicting parents for `{name}`")));
+ }
+ entry.parent = parent;
+ entry.declared = true;
+ }
+ for entry in &entries {
+ let mut parent = entry.parent;
+ for depth in 0..=entries.len() {
+ let Some(id) = parent else { break };
+ if depth == entries.len() {
+ return Err(BindError::new(format!(
+ "interface inheritance cycle at `{}`",
+ entry.name
+ )));
+ }
+ parent = entries[id].parent;
+ }
+ }
+ registry.entries = entries;
+ registry.names = names;
+ Ok(())
+}
+
+fn object_type_id<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ registry: &Rc<RefCell<TypeRegistry>>,
+) -> Option<usize> {
+ // In particular, do not forward identity checks through Proxy traps.
+ if object.is_proxy() {
+ return None;
+ }
+ let key = v8::Local::new(scope, &registry.borrow().key);
+ let value = object.get_private(scope, key)?;
+ let id = v8::Local::<v8::Uint32>::try_from(value).ok()?.value() as usize;
+ (id < registry.borrow().entries.len()).then_some(id)
+}
+
+/// Reads only the object's own native identity. Prototype inheritance and
+/// JavaScript properties (including symbols) cannot supply this identity.
+pub fn web_api_object_type<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+) -> Option<WebApiType> {
+ let registry = registry(scope);
+ let id = object_type_id(scope, object, &registry)?;
+ Some(WebApiType {
+ name: registry.borrow().entries[id].name,
+ })
+}
+
+pub fn implements_interface<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ expected: &str,
+) -> bool {
+ let registry = registry(scope);
+ let Some(id) = object_type_id(scope, object, &registry) else {
+ return false;
+ };
+ let registry = registry.borrow();
+ registry
+ .names
+ .get(expected)
+ .is_some_and(|expected| registry.implements(id, *expected))
+}
+
+/// Attaches identity to an initialized native instance. Generated declarations
+/// call this automatically; native wrapper factories use the same entry point.
+/// Base initialization preserves a derived type, and derived initialization can
+/// refine a base type. Unrelated declarations cannot rebrand an existing object.
+pub fn initialize_web_api_object<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ interface: &'static str,
+) -> Result<(), BindError> {
+ if interface == "Object" || object.is_proxy() {
+ return Err(BindError::new(
+ "platform identity requires a native interface instance",
+ ));
+ }
+ let registry = registry(scope);
+ let id = registry.borrow_mut().intern(interface);
+ if let Some(existing) = object_type_id(scope, object, &registry) {
+ let registry = registry.borrow();
+ if registry.implements(existing, id) {
+ return Ok(());
+ }
+ if !registry.implements(id, existing) {
+ return Err(BindError::new(format!(
+ "cannot change `{}` identity to `{interface}`",
+ registry.entries[existing].name
+ )));
+ }
+ }
+ let id = u32::try_from(id).map_err(|_| BindError::new("too many Web API types"))?;
+ let key = v8::Local::new(scope, &registry.borrow().key);
+ let value = v8::Integer::new_from_unsigned(scope, id);
+ if object.set_private(scope, key, value.into()) != Some(true) {
+ return Err(BindError::new(format!(
+ "failed to initialize `{interface}` identity"
+ )));
+ }
+ Ok(())
+}
diff --git a/moli-webapi-declare/src/lib.rs b/moli-webapi-declare/src/lib.rs
index e8c89659e..e874792ab 100644
--- a/moli-webapi-declare/src/lib.rs
+++ b/moli-webapi-declare/src/lib.rs
@@ -84,6 +84,20 @@
//! `data = self.some_field`, which lets a declaration carry callback data
//! without expanding the object reflection surface.
//!
+//! Named interface instances automatically receive a private Web API type after
+//! their fields initialize successfully. `bind`, `bind_into`, and `initialize`
+//! all use this path. `interface = "Object"` describes an unbranded record;
+//! `#[webapi(unbranded)]` explicitly opts named prototype/constructor installers,
+//! dictionaries, and shared initialization fragments out of instance branding.
+//! These fragments never erase an identity already present on their target.
+//!
+//! Register inheritance with `register_web_api_interfaces` using the same
+//! interface metadata that drives constructor installation. `WebApiInterface`
+//! registers its own name and parent automatically. Identity is independent of
+//! realm exposure and mutable JavaScript prototypes. Use `web_api_object_type`
+//! for the primary interface and `implements_interface` for inherited receiver
+//! checks. Native factories can call `initialize_web_api_object` directly.
+//!
//! The derive generates a Rust-side `new(...)` constructor by default. The
//! generated constructor takes every non-`()` declaration field as a named
//! argument and fills `()` declaration fields with `()`. If every field is
@@ -163,6 +177,7 @@
extern crate self as moli_webapi_declare;
+mod brand;
mod callback;
mod declaration;
mod error;
@@ -175,6 +190,11 @@ pub mod __private;
pub use moli_webapi_declare_derive::{WebApiFunctionTemplate, WebApiInterface, WebApiObject};
pub use v8;
+pub use brand::{
+ WebApiType, implements_interface, initialize_web_api_object, register_web_api_interfaces,
+ web_api_object_type,
+};
+
pub use declaration::{
DataPropertyDescriptorDeclaration, ObjectLiteralDeclaration, WebApiFunctionTemplateDeclaration,
WebApiInterfaceDeclaration, WebApiObjectDeclaration,
diff --git a/moli-webapi-declare/tests/brand.rs b/moli-webapi-declare/tests/brand.rs
new file mode 100644
index 000000000..21252a532
--- /dev/null
+++ b/moli-webapi-declare/tests/brand.rs
@@ -0,0 +1,137 @@
+use std::pin::pin;
+
+use moli_v8_test_util::ensure_v8;
+use moli_webapi_declare::{
+ WebApiObject, implements_interface, initialize_web_api_object, register_web_api_interfaces,
+ web_api_object_type,
+};
+
+#[derive(WebApiObject)]
+#[webapi(interface = "TestBase", allow_empty)]
+struct Base {}
+
+#[derive(WebApiObject)]
+#[webapi(interface = "TestDerived", allow_empty)]
+struct Derived {}
+
+#[derive(WebApiObject)]
+#[webapi(interface = "Object", data_properties, enumerable)]
+struct Record {
+ value: u32,
+}
+
+#[derive(WebApiObject)]
+#[webapi(interface = "TestBase", unbranded, allow_empty)]
+struct PrototypeMembers {}
+
+fn eval<'s>(scope: &mut v8::PinScope<'s, '_>, source: &str) -> v8::Local<'s, v8::Value> {
+ let source = v8::String::new(scope, source).unwrap();
+ v8::Script::compile(scope, source, None)
+ .unwrap()
+ .run(scope)
+ .unwrap()
+}
+
+#[test]
+fn declarations_brand_instances_and_preserve_derived_identity_across_realms() {
+ ensure_v8();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ register_web_api_interfaces(
+ scope,
+ [("TestBase", None), ("TestDerived", Some("TestBase"))],
+ )
+ .unwrap();
+ let first = v8::Context::new(scope, Default::default());
+ let second = v8::Context::new(scope, Default::default());
+ let object = {
+ let scope = &mut v8::ContextScope::new(scope, first);
+ let object = Base::new().bind(scope).unwrap();
+ Derived::new().initialize(scope, object).unwrap();
+ Base::new().initialize(scope, object).unwrap();
+ Record::new(7).initialize(scope, object).unwrap();
+ assert_eq!(
+ web_api_object_type(scope, object).unwrap().name(),
+ "TestDerived"
+ );
+ assert!(implements_interface(scope, object, "TestBase"));
+ assert!(implements_interface(scope, object, "TestDerived"));
+ assert!(!implements_interface(scope, object, "Unrelated"));
+ assert!(initialize_web_api_object(scope, object, "Unrelated").is_err());
+ object
+ };
+ let scope = &mut v8::ContextScope::new(scope, second);
+ assert!(implements_interface(scope, object, "TestBase"));
+ let key = v8::String::new(scope, "real").unwrap();
+ second
+ .global(scope)
+ .set(scope, key.into(), object.into())
+ .unwrap();
+ eval(
+ scope,
+ "Object.setPrototypeOf(real, null); real.__moliWebApiType = 'Unrelated'",
+ );
+ assert_eq!(
+ web_api_object_type(scope, object).unwrap().name(),
+ "TestDerived"
+ );
+ assert!(implements_interface(scope, object, "TestBase"));
+}
+
+#[test]
+fn identity_is_own_private_and_never_invokes_author_code() {
+ ensure_v8();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let real = Base::new().bind(scope).unwrap();
+ let key = v8::String::new(scope, "real").unwrap();
+ context
+ .global(scope)
+ .set(scope, key.into(), real.into())
+ .unwrap();
+ assert_eq!(
+ eval(scope, "Reflect.ownKeys(real).length").uint32_value(scope),
+ Some(0)
+ );
+ for source in [
+ "({__moliWebApiType: 0})",
+ "({[Symbol('__moliWebApiType')]: 0})",
+ "Object.create(real)",
+ "new Proxy(real, {get() { throw Error('trap'); }, getPrototypeOf() { throw Error('trap'); }})",
+ "(() => { const {proxy, revoke} = Proxy.revocable(real, {}); revoke(); return proxy; })()",
+ ] {
+ let object = v8::Local::<v8::Object>::try_from(eval(scope, source)).unwrap();
+ assert_eq!(web_api_object_type(scope, object), None, "{source}");
+ assert!(!implements_interface(scope, object, "TestBase"), "{source}");
+ }
+ let record = Record::new(7).bind(scope).unwrap();
+ let prototype = PrototypeMembers::new().bind(scope).unwrap();
+ assert_eq!(web_api_object_type(scope, record), None);
+ assert_eq!(web_api_object_type(scope, prototype), None);
+}
+
+#[test]
+fn inheritance_registration_is_atomic_and_rejects_conflicts_and_cycles() {
+ ensure_v8();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let scope = pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let object = Derived::new().bind(scope).unwrap();
+ register_web_api_interfaces(
+ scope,
+ [("TestDerived", Some("TestBase")), ("TestBase", None)],
+ )
+ .unwrap();
+ register_web_api_interfaces(scope, [("TestDerived", Some("TestBase"))]).unwrap();
+ assert!(register_web_api_interfaces(scope, [("TestDerived", None)]).is_err());
+ assert!(register_web_api_interfaces(scope, [("A", Some("B")), ("B", Some("A"))]).is_err());
+ assert!(implements_interface(scope, object, "TestBase"));
+ // A rejected batch has not left conflicting declarations behind.
+ register_web_api_interfaces(scope, [("A", None), ("B", Some("A"))]).unwrap();
+}