Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(webidl): derive dictionary output and backing state
ldm0b165771974f3
diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rsindex 79cbad7c5..397131bcf 100644--- a/moli-renderer-v8/src/content_security_policy.rs+++ b/moli-renderer-v8/src/content_security_policy.rs@@ -1,16 +1,13 @@-use crate::web_api_interfaces;use std::collections::BTreeMap;use crate::context_bootstrap::{initialize_event_object, mark_event_trusted};use crate::network::ResourceRequestClient;use crate::subresource_integrity::integrity_metadata_hashes;-use crate::util::v8_string;use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};use moli_crypto::DigestAlgorithm;use moli_fetch::{Request, RequestCredentialsMode, RequestMode, RequestRedirectMode, RequestResourceType,};-use moli_webapi_declare::WebApiObject;use percent_encoding::percent_decode_str;use serde_json::json;use url::Url;@@ -191,29 +188,6 @@ pub(crate) struct ContentSecurityPolicyViolationEventFields<'a> {pub(crate) status_code: i32,}-#[derive(WebApiObject)]-#[webapi(- interface = web_api_interfaces::SecurityPolicyViolationEvent,- data_properties,- enumerable-)]-pub(crate) struct ContentSecurityPolicyViolationEventDeclaration<'scope> {- #[webapi(data_property = "documentURI")]- document_uri: v8::Local<'scope, v8::String>,- referrer: v8::Local<'scope, v8::String>,- #[webapi(data_property = "blockedURI")]- blocked_uri: v8::Local<'scope, v8::String>,- effective_directive: v8::Local<'scope, v8::String>,- violated_directive: v8::Local<'scope, v8::String>,- original_policy: v8::Local<'scope, v8::String>,- disposition: v8::Local<'scope, v8::String>,- source_file: v8::Local<'scope, v8::String>,- sample: v8::Local<'scope, v8::String>,- line_number: u32,- column_number: u32,- status_code: u16,-}-impl<'a> ContentSecurityPolicyViolationEventFields<'a> {pub(crate) fn from_url_violation(violation: &'a ContentSecurityPolicyUrlViolation) -> Self {Self {@@ -237,7 +211,6 @@ pub(crate) fn create_security_policy_violation_event<'s>(scope: &mut v8::PinScope<'s, '_>,fields: &ContentSecurityPolicyViolationEventFields<'_>,) -> Option<v8::Local<'s, v8::Object>> {- let declaration = security_policy_violation_event_declaration(scope, fields)?;let event = crate::context_bootstrap::new_event_state(scope);initialize_event_object(scope, event, "securitypolicyviolation", true, false);event.set(@@ -245,42 +218,13 @@ pub(crate) fn create_security_policy_violation_event<'s>(crate::util::v8str(scope, "composed").into(),v8::Boolean::new(scope, true).into(),)?;- declaration.initialize(scope, event).ok()?;+ crate::context_bootstrap::initialize_native_security_policy_violation_event(+ scope, event, fields,+ )?;mark_event_trusted(scope, event);crate::context_bootstrap::new_event_wrapper(scope, event)}-fn security_policy_violation_event_declaration<'s>(- scope: &mut v8::PinScope<'s, '_>,- fields: &ContentSecurityPolicyViolationEventFields<'_>,-) -> Option<ContentSecurityPolicyViolationEventDeclaration<'s>> {- let document_uri = v8_string(scope, fields.document_uri)?;- let referrer = v8_string(scope, fields.referrer)?;- let blocked_uri = v8_string(scope, fields.blocked_uri)?;- let effective_directive = v8_string(scope, fields.effective_directive)?;- let violated_directive = v8_string(scope, fields.violated_directive)?;- let original_policy = v8_string(scope, fields.original_policy)?;- let disposition = v8_string(scope, fields.disposition.as_str())?;- let source_file = v8_string(scope, fields.source_file)?;- let sample = v8_string(scope, fields.sample)?;- Some(ContentSecurityPolicyViolationEventDeclaration {- document_uri,- referrer,- blocked_uri,- effective_directive,- violated_directive,- original_policy,- disposition,- source_file,- sample,- // Native locations use zero when unavailable. Synthetic events enter- // this shared state with their already converted unsigned IDL values.- line_number: fields.line_number.try_into().unwrap_or_default(),- column_number: fields.column_number.try_into().unwrap_or_default(),- status_code: fields.status_code.try_into().unwrap_or_default(),- })-}-pub(crate) fn content_security_policy_headers(headers: &[(String, Vec<u8>)]) -> Vec<String> {content_security_policy_header_values(headers, "content-security-policy")}diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex eeed7a17a..98b552fb3 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -278,9 +278,10 @@ pub(crate) use self::events::{construct_original_message_event, event_attribute, event_backing, event_bool_attribute,event_callback_values, event_initialized, event_internal_bool_flag, event_is_dispatching,event_is_error_event, event_is_mouse_event, event_private_value, initialize_event_object,- initialize_event_wrapper, mark_agent_submit_event, mark_event_trusted, new_event_state,- new_event_wrapper, set_event_composed_path, set_event_internal_flag, set_event_private_value,- set_event_trusted, submit_event_submitter_value,+ initialize_event_wrapper, initialize_native_security_policy_violation_event,+ mark_agent_submit_event, mark_event_trusted, new_event_state, new_event_wrapper,+ set_event_composed_path, set_event_internal_flag, set_event_private_value, set_event_trusted,+ submit_event_submitter_value,};pub(crate) use self::file_api::{DataTransferStringCallbackTask, DataTransferStringCallbackTaskEffect,diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rsindex 9abee3965..03afbd45a 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs@@ -3,6 +3,7 @@ use crate::web_api_interfaces;use crate::{util::get_private_value, webidl};use moli_web_errors::{DOM_EXCEPTION_CONSTANTS, dom_exception_legacy_code};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject, WebApiTemplateValue};+use webidl::WebIdlDictionarySerialize;mod rtc_error;pub(crate) use rtc_error::rtc_error_constructor_callback;@@ -36,11 +37,13 @@ struct DomErrorConstructorArgs {}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "QuotaExceededErrorOptions")]+#[webidl(prefix = "QuotaExceededErrorOptions", snapshot)]struct QuotaExceededErrorOptions {#[webidl(converter = "double")]+ #[webidl(snapshot_slot = QUOTA_EXCEEDED_ERROR_QUOTA_SLOT, snapshot_default = v8::null(scope).into())]quota: Option<f64>,#[webidl(converter = "double")]+ #[webidl(snapshot_slot = QUOTA_EXCEEDED_ERROR_REQUESTED_SLOT, snapshot_default = v8::null(scope).into())]requested: Option<f64>,}@@ -105,10 +108,6 @@ struct QuotaExceededErrorObjectDeclaration<'scope> {name: (),#[webapi(slot = DOM_EXCEPTION_CODE_SLOT, value = f64::from(dom_exception_legacy_code("QuotaExceededError")))]code: (),- #[webapi(slot = QUOTA_EXCEEDED_ERROR_QUOTA_SLOT)]- quota: v8::Local<'scope, v8::Value>,- #[webapi(slot = QUOTA_EXCEEDED_ERROR_REQUESTED_SLOT)]- requested: v8::Local<'scope, v8::Value>,}#[derive(WebApiFunctionTemplate)]@@ -498,17 +497,6 @@ fn nullable_double_slot_value<'s>(}}-fn quota_exceeded_error_declaration<'s>(- scope: &mut v8::PinScope<'s, '_>,- message: &str,- quota: Option<f64>,- requested: Option<f64>,-) -> QuotaExceededErrorObjectDeclaration<'s> {- let quota = nullable_double_slot_value(scope, quota);- let requested = nullable_double_slot_value(scope, requested);- QuotaExceededErrorObjectDeclaration::new(v8_string(scope, message), quota, requested)-}-fn initialize_quota_exceeded_error<'s>(scope: &mut v8::PinScope<'s, '_>,exception: v8::Local<'s, v8::Object>,@@ -516,9 +504,12 @@ fn initialize_quota_exceeded_error<'s>(quota: Option<f64>,requested: Option<f64>,) {- quota_exceeded_error_declaration(scope, message, quota, requested)+ QuotaExceededErrorObjectDeclaration::new(v8_string(scope, message)).initialize(scope, exception).expect("QuotaExceededError declaration should initialize");+ QuotaExceededErrorOptions { quota, requested }+ .initialize_snapshot(scope, exception)+ .expect("QuotaExceededError options");capture_dom_exception_stack(scope, exception);}@@ -684,9 +675,12 @@ pub(crate) fn new_quota_exceeded_error_value<'s>(quota: Option<f64>,requested: Option<f64>,) -> v8::Local<'s, v8::Value> {- let exception = quota_exceeded_error_declaration(scope, message, quota, requested)+ let exception = QuotaExceededErrorObjectDeclaration::new(v8_string(scope, message)).bind(scope).expect("QuotaExceededError declaration should bind");+ QuotaExceededErrorOptions { quota, requested }+ .initialize_snapshot(scope, exception)+ .expect("QuotaExceededError options");capture_dom_exception_stack(scope, exception);exception.into()}diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception/rtc_error.rs b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception/rtc_error.rsindex 72b6239e6..8e9d37935 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception/rtc_error.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception/rtc_error.rs@@ -1,6 +1,6 @@use super::*;use crate::util::apply_webidl_constructor_prototype_fallback;-use webidl::WebIdlDictionary;+use webidl::{WebIdlDictionary, WebIdlDictionarySerialize};const ERROR_DETAIL: &str = "__moliRtcErrorDetail";const SDP_LINE_NUMBER: &str = "__moliRtcErrorSdpLineNumber";@@ -20,29 +20,20 @@ enum ErrorDetail {HardwareEncoderError,}-impl ErrorDetail {- fn token(self) -> &'static str {- match self {- Self::DataChannelFailure => "data-channel-failure",- Self::DtlsFailure => "dtls-failure",- Self::FingerprintFailure => "fingerprint-failure",- Self::SctpFailure => "sctp-failure",- Self::SdpSyntaxError => "sdp-syntax-error",- Self::HardwareEncoderNotAvailable => "hardware-encoder-not-available",- Self::HardwareEncoderError => "hardware-encoder-error",- }- }-}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "RTCErrorInit")]+#[webidl(prefix = "RTCErrorInit", snapshot)]struct ErrorInit {// Dictionary members are visited lexically, before the message argument.#[webidl(required, converter = "enum")]+ #[webidl(snapshot_slot = ERROR_DETAIL)]error_detail: ErrorDetail,+ #[webidl(snapshot_slot = RECEIVED_ALERT, snapshot_default = v8::null(scope).into())]received_alert: Option<u32>,+ #[webidl(snapshot_slot = SCTP_CAUSE_CODE, snapshot_default = v8::null(scope).into())]sctp_cause_code: Option<i32>,+ #[webidl(snapshot_slot = SDP_LINE_NUMBER, snapshot_default = v8::null(scope).into())]sdp_line_number: Option<i32>,+ #[webidl(snapshot_slot = SENT_ALERT, snapshot_default = v8::null(scope).into())]sent_alert: Option<u32>,}@@ -82,16 +73,6 @@ struct ObjectDeclaration<'s> {name: (),#[webapi(slot = DOM_EXCEPTION_CODE_SLOT, init = 0)]code: (),- #[webapi(slot = ERROR_DETAIL)]- error_detail: v8::Local<'s, v8::String>,- #[webapi(slot = RECEIVED_ALERT)]- received_alert: v8::Local<'s, v8::Value>,- #[webapi(slot = SCTP_CAUSE_CODE)]- sctp_cause_code: v8::Local<'s, v8::Value>,- #[webapi(slot = SDP_LINE_NUMBER)]- sdp_line_number: v8::Local<'s, v8::Value>,- #[webapi(slot = SENT_ALERT)]- sent_alert: v8::Local<'s, v8::Value>,}#[derive(WebApiFunctionTemplate)]@@ -133,15 +114,13 @@ pub(crate) fn rtc_error_constructor_callback<'s>(else {return;};- let declaration = ObjectDeclaration::new(- message,- v8str(scope, parsed.init.error_detail.token()),- nullable_double_slot_value(scope, parsed.init.received_alert.map(f64::from)),- nullable_double_slot_value(scope, parsed.init.sctp_cause_code.map(f64::from)),- nullable_double_slot_value(scope, parsed.init.sdp_line_number.map(f64::from)),- nullable_double_slot_value(scope, parsed.init.sent_alert.map(f64::from)),- );- if declaration.initialize(scope, args.this()).is_ok() {+ let declaration = ObjectDeclaration::new(message);+ if parsed+ .init+ .initialize_snapshot(scope, args.this())+ .is_some()+ && declaration.initialize(scope, args.this()).is_ok()+ {capture_dom_exception_stack(scope, args.this());apply_webidl_constructor_prototype_fallback(scope,diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs b/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rsindex b8093a53d..aa24bc85b 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs@@ -5,6 +5,7 @@ use crate::{webidl,};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionarySerialize;const TEXT_ENCODER_ENCODING_SLOT: &str = "__lmTextEncoderEncoding";const TEXT_DECODER_ENCODING_SLOT: &str = "__lmTextDecoderEncoding";@@ -43,10 +44,6 @@ struct TextEncoderPrototypeDeclaration {struct TextDecoderObjectDeclaration {#[webapi(slot = TEXT_DECODER_ENCODING_SLOT)]encoding: String,- #[webapi(slot = TEXT_DECODER_FATAL_SLOT)]- fatal: bool,- #[webapi(slot = TEXT_DECODER_IGNORE_BOM_SLOT)]- ignore_bom: bool,}#[derive(WebApiFunctionTemplate)]@@ -113,11 +110,13 @@ struct TextDecoderConstructorArgs {}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "TextDecoderOptions")]+#[webidl(prefix = "TextDecoderOptions", snapshot)]struct TextDecoderOptions {#[webidl(default = false)]+ #[webidl(snapshot_slot = TEXT_DECODER_FATAL_SLOT)]fatal: bool,#[webidl(name = "ignoreBOM", default = false)]+ #[webidl(snapshot_slot = TEXT_DECODER_IGNORE_BOM_SLOT)]ignore_bom: bool,}@@ -315,7 +314,11 @@ pub(in crate::context_bootstrap) fn text_decoder_constructor_callback<'s>(let fatal = parsed.options.fatal;let ignore_bom = parsed.options.ignore_bom;init_text_decoder_state(scope, args.this(), encoding, fatal, ignore_bom);- TextDecoderObjectDeclaration::new(encoding_name, fatal, ignore_bom)+ parsed+ .options+ .initialize_snapshot(scope, args.this())+ .expect("TextDecoder options");+ TextDecoderObjectDeclaration::new(encoding_name).initialize(scope, args.this()).expect("TextDecoder declaration should initialize object");rv.set(args.this().into());diff --git a/moli-renderer-v8/src/context_bootstrap/dom_rect.rs b/moli-renderer-v8/src/context_bootstrap/dom_rect.rsindex 3b465ce82..e5b0a904d 100644--- a/moli-renderer-v8/src/context_bootstrap/dom_rect.rs+++ b/moli-renderer-v8/src/context_bootstrap/dom_rect.rs@@ -3,6 +3,7 @@ use crate::util::{callback_data_index_value, get_private_value, set_private_valuuse crate::web_api_interfaces;use crate::webidl;use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionarySerialize;const DOM_RECT_X_SLOT: &str = "__moliDomRectX";const DOM_RECT_Y_SLOT: &str = "__moliDomRectY";@@ -11,29 +12,11 @@ const DOM_RECT_HEIGHT_SLOT: &str = "__moliDomRectHeight";#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::DOMRect)]-struct DomRectObjectDeclaration {- #[webapi(slot = DOM_RECT_X_SLOT)]- x: f64,- #[webapi(slot = DOM_RECT_Y_SLOT)]- y: f64,- #[webapi(slot = DOM_RECT_WIDTH_SLOT)]- width: f64,- #[webapi(slot = DOM_RECT_HEIGHT_SLOT)]- height: f64,-}+struct DomRectObjectDeclaration {}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::DOMRectReadOnly)]-struct DomRectReadOnlyObjectDeclaration {- #[webapi(slot = DOM_RECT_X_SLOT)]- x: f64,- #[webapi(slot = DOM_RECT_Y_SLOT)]- y: f64,- #[webapi(slot = DOM_RECT_WIDTH_SLOT)]- width: f64,- #[webapi(slot = DOM_RECT_HEIGHT_SLOT)]- height: f64,-}+struct DomRectReadOnlyObjectDeclaration {}#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::DOMRectReadOnly, receiver)]@@ -213,15 +196,19 @@ struct DomRectReadOnlyConstructorArgs {}#[derive(Clone, Copy, Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "DOMRectInit")]+#[webidl(prefix = "DOMRectInit", snapshot)]struct DomRectInit {#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_RECT_HEIGHT_SLOT)]height: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_RECT_WIDTH_SLOT)]width: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_RECT_X_SLOT)]x: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_RECT_Y_SLOT)]y: f64,}@@ -284,9 +271,9 @@ pub(crate) fn build_dom_rect_object<'s>(width: f64,height: f64,) -> v8::Local<'s, v8::Object> {- DomRectObjectDeclaration::new(x, y, width, height)- .bind(scope)- .expect("DOMRect declaration should bind")+ let object = v8::Object::new(scope);+ initialize_dom_rect_object(scope, object, x, y, width, height);+ object}pub(super) fn build_dom_rect_readonly_object<'s>(@@ -296,9 +283,9 @@ pub(super) fn build_dom_rect_readonly_object<'s>(width: f64,height: f64,) -> v8::Local<'s, v8::Object> {- DomRectReadOnlyObjectDeclaration::new(x, y, width, height)- .bind(scope)- .expect("DOMRectReadOnly declaration should bind")+ let object = v8::Object::new(scope);+ initialize_dom_rect_readonly_object(scope, object, x, y, width, height);+ object}fn initialize_dom_rect_object<'s>(@@ -309,7 +296,15 @@ fn initialize_dom_rect_object<'s>(width: f64,height: f64,) {- DomRectObjectDeclaration::new(x, y, width, height)+ DomRectInit {+ x,+ y,+ width,+ height,+ }+ .initialize_snapshot(scope, object)+ .expect("DOMRect state");+ DomRectObjectDeclaration::new().bind_into(scope, object).expect("DOMRect declaration should initialize object");}@@ -322,7 +317,15 @@ fn initialize_dom_rect_readonly_object<'s>(width: f64,height: f64,) {- DomRectReadOnlyObjectDeclaration::new(x, y, width, height)+ DomRectInit {+ x,+ y,+ width,+ height,+ }+ .initialize_snapshot(scope, object)+ .expect("DOMRect state");+ DomRectReadOnlyObjectDeclaration::new().bind_into(scope, object).expect("DOMRectReadOnly declaration should initialize object");}diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rsindex 33484e5d7..17ca0736f 100644--- a/moli-renderer-v8/src/context_bootstrap/events.rs+++ b/moli-renderer-v8/src/context_bootstrap/events.rs@@ -1,6 +1,7 @@use super::*;use crate::util::{get_private_value, v8_string, v8_string_from_utf16_units, v8str};-use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiObject};+use crate::webidl::{SnapshotPrototype, WebIdlDictionarySerialize};+use moli_webapi_declare::WebApiObject;mod base;mod device;@@ -11,6 +12,7 @@ pub(crate) use message::construct_original_message_event;mod methods;mod modifiers;mod subclasses;+pub(crate) use subclasses::initialize_native_security_policy_violation_event;mod submit;mod ui;mod value;@@ -52,21 +54,6 @@ struct PageTransitionEventInitDeclaration {persisted: bool,}-#[derive(WebApiObject)]-#[webapi(plain, enumerable)]-struct StorageEventStateDeclaration<'scope> {- #[webapi(data_property)]- key: v8::Local<'scope, v8::Value>,- #[webapi(data_property = "oldValue")]- old_value: v8::Local<'scope, v8::Value>,- #[webapi(data_property = "newValue")]- new_value: v8::Local<'scope, v8::Value>,- #[webapi(data_property)]- url: v8::Local<'scope, v8::Value>,- #[webapi(data_property = "storageArea")]- storage_area: v8::Local<'scope, v8::Value>,-}-#[derive(Default, WebApiObject)]#[webapi(fragment, prototype = "PointerEvent", enumerable)]struct SecurePointerEventPrototypeRuntimeDeclaration {@@ -156,17 +143,14 @@ pub(crate) fn construct_original_storage_event_utf16<'s>(super::exposed_interfaces::ensure_intrinsic_interface_constructor(scope, "StorageEvent").ok()?;let event_type = v8_string(scope, event_type)?;- let init = ObjectLiteralDeclaration::bind(scope);- define_storage_event_init_properties_utf16(- scope,- &init,+ let parsed = subclasses::StorageEventInitMembers::from_native(key,old_value,new_value,url,storage_area,);- let init = init.into_object();+ let init = parsed.to_js_snapshot(scope, SnapshotPrototype::Null)?;let event = {let try_catch = std::pin::pin!(v8::TryCatch::new(scope));let scope = try_catch.init();@@ -194,48 +178,9 @@ pub(in crate::context_bootstrap) fn define_storage_event_properties_utf16<'s>(storage_area: Option<v8::Local<'s, v8::Value>>,) {let event = event_backing(scope, event);- let key_value = storage_event_nullable_string_value_utf16(scope, key);- let old_value = storage_event_nullable_string_value_utf16(scope, old_value);- let new_value = storage_event_nullable_string_value_utf16(scope, new_value);- let url_value = v8_string(scope, url).expect("storage event url").into();- let storage_area = storage_area.unwrap_or_else(|| v8::null(scope).into());- let _ =- StorageEventStateDeclaration::new(key_value, old_value, new_value, url_value, storage_area)- .initialize(scope, event);-}--fn define_storage_event_init_properties_utf16<'s>(- scope: &mut v8::PinScope<'s, '_>,- init: &ObjectLiteralDeclaration<'s>,- key: Option<&[u16]>,- old_value: Option<&[u16]>,- new_value: Option<&[u16]>,- url: &str,- storage_area: Option<v8::Local<'s, v8::Value>>,-) {- let key_value = storage_event_nullable_string_value_utf16(scope, key);- init.set_string_property(scope, "key", key_value);- let old_value = storage_event_nullable_string_value_utf16(scope, old_value);- init.set_string_property(scope, "oldValue", old_value);- let new_value = storage_event_nullable_string_value_utf16(scope, new_value);- init.set_string_property(scope, "newValue", new_value);- let url_value = v8_string(scope, url).expect("storage event url").into();- init.set_string_property(scope, "url", url_value);- let storage_area = storage_area.unwrap_or_else(|| v8::null(scope).into());- init.set_string_property(scope, "storageArea", storage_area);-}--fn storage_event_nullable_string_value_utf16<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: Option<&[u16]>,-) -> v8::Local<'s, v8::Value> {- value- .map(|value| {- v8_string_from_utf16_units(scope, value)- .expect("storage event string")- .into()- })- .unwrap_or_else(|| v8::null(scope).into())+ subclasses::StorageEventInitMembers::from_native(key, old_value, new_value, url, storage_area)+ .initialize_own_snapshot(scope, event)+ .expect("StorageEvent native payload");}pub(crate) use base::{diff --git a/moli-renderer-v8/src/context_bootstrap/events/audio.rs b/moli-renderer-v8/src/context_bootstrap/events/audio.rsindex e409243e9..6cd135c0a 100644--- a/moli-renderer-v8/src/context_bootstrap/events/audio.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/audio.rs@@ -2,7 +2,7 @@use super::{define_event_property, event_private_value, initialize_event_object_with_type,- initialize_event_wrapper, new_event_state, set_event_private_value,+ initialize_event_wrapper, new_event_state,};use crate::context_bootstrap::events::EventInit;use crate::{@@ -10,6 +10,7 @@ use crate::{web_api_interfaces, webidl,};use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::WebIdlDictionarySerialize;const RENDERED_BUFFER_SLOT: &str = "__moliAudioCompletionRenderedBuffer";const INPUT_BUFFER_SLOT: &str = "__moliAudioProcessingInputBuffer";@@ -51,24 +52,28 @@ struct OfflineAudioCompletionEventPrototypeDeclaration {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AudioProcessingEventInit")]+#[webidl(prefix = "AudioProcessingEventInit", snapshot)]struct AudioProcessingEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(required, interface = web_api_interfaces::AudioBuffer)]+ #[webidl(snapshot_slot = INPUT_BUFFER_SLOT)]input_buffer: v8::Local<'s, v8::Object>,#[webidl(required, interface = web_api_interfaces::AudioBuffer)]+ #[webidl(snapshot_slot = OUTPUT_BUFFER_SLOT)]output_buffer: v8::Local<'s, v8::Object>,#[webidl(required, converter = "double")]+ #[webidl(snapshot_slot = PLAYBACK_TIME_SLOT)]playback_time: f64,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "OfflineAudioCompletionEventInit")]+#[webidl(prefix = "OfflineAudioCompletionEventInit", snapshot)]struct OfflineAudioCompletionEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(required, interface = web_api_interfaces::AudioBuffer)]+ #[webidl(snapshot_slot = RENDERED_BUFFER_SLOT)]rendered_buffer: v8::Local<'s, v8::Object>,}@@ -139,24 +144,9 @@ fn audio_event_constructor<'s>(AudioEventKind::Processing => {let parsed =webidl::parse_dictionary_object::<AudioProcessingEventInit>(scope, dictionary)?;- set_event_private_value(- scope,- state,- INPUT_BUFFER_SLOT,- parsed.input_buffer.into(),- );- set_event_private_value(- scope,- state,- OUTPUT_BUFFER_SLOT,- parsed.output_buffer.into(),- );- set_event_private_value(- scope,- state,- PLAYBACK_TIME_SLOT,- v8::Number::new(scope, parsed.playback_time).into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("audio event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -167,12 +157,9 @@ fn audio_event_constructor<'s>(let parsed = webidl::parse_dictionary_object::<OfflineAudioCompletionEventInit>(scope, dictionary,)?;- set_event_private_value(- scope,- state,- RENDERED_BUFFER_SLOT,- parsed.rendered_buffer.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("audio event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -214,7 +201,11 @@ pub(in crate::context_bootstrap) fn new_offline_audio_completion_event<'s>(.ok()?;let state = new_event_state(scope);super::initialize_event_object(scope, state, "complete", false, false);- set_event_private_value(scope, state, RENDERED_BUFFER_SLOT, rendered_buffer.into());+ OfflineAudioCompletionEventInit {+ base: EventInit::default(),+ rendered_buffer,+ }+ .initialize_snapshot(scope, state)?;web_api_interfaces::initialize(scope, state, "OfflineAudioCompletionEvent").ok()?;let event = v8::Object::new(scope);if event.set_prototype(scope, prototype.into()) != Some(true) {diff --git a/moli-renderer-v8/src/context_bootstrap/events/device.rs b/moli-renderer-v8/src/context_bootstrap/events/device.rsindex b868cb6c2..8be6e1aa6 100644--- a/moli-renderer-v8/src/context_bootstrap/events/device.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/device.rs@@ -3,7 +3,7 @@use super::{define_event_property, event_private_value, initialize_event_object_with_type,- initialize_event_wrapper, new_event_state, set_event_private_value,+ initialize_event_wrapper, new_event_state,};use crate::context_bootstrap::events::EventInit;use crate::{@@ -11,6 +11,7 @@ use crate::{web_api_interfaces, webidl,};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::{SnapshotPrototype, WebIdlDictionarySerialize};const ALPHA: &str = "__moliDeviceAlpha";const BETA: &str = "__moliDeviceBeta";@@ -55,12 +56,6 @@ struct MotionPrototype {struct AccelerationObject<'s> {#[webapi(prototype)]prototype: v8::Local<'s, v8::Object>,- #[webapi(slot = X)]- x: v8::Local<'s, v8::Value>,- #[webapi(slot = Y)]- y: v8::Local<'s, v8::Value>,- #[webapi(slot = Z)]- z: v8::Local<'s, v8::Value>,}#[derive(WebApiFunctionTemplate)]@@ -79,12 +74,6 @@ struct AccelerationPrototype {struct RotationRateObject<'s> {#[webapi(prototype)]prototype: v8::Local<'s, v8::Object>,- #[webapi(slot = ALPHA)]- alpha: v8::Local<'s, v8::Value>,- #[webapi(slot = BETA)]- beta: v8::Local<'s, v8::Value>,- #[webapi(slot = GAMMA)]- gamma: v8::Local<'s, v8::Value>,}#[derive(WebApiFunctionTemplate)]@@ -101,54 +90,68 @@ struct RotationRatePrototype {// Convert inherited EventInit members first, followed by the derived members// in Web IDL's lexicographic order, including each nested dictionary in place.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "DeviceOrientationEventInit")]+#[webidl(prefix = "DeviceOrientationEventInit", snapshot)]struct OrientationInit {#[webidl(inherit)]base: EventInit,#[webidl(default = false)]+ #[webidl(snapshot_slot = ABSOLUTE)]absolute: bool,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = ALPHA)]alpha: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = BETA)]beta: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = GAMMA)]gamma: Option<f64>,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "DeviceMotionEventInit")]+#[webidl(prefix = "DeviceMotionEventInit", snapshot)]struct MotionInit {#[webidl(inherit)]base: EventInit,#[webidl(dictionary)]+ #[webidl(snapshot_slot = ACCELERATION, snapshot_with = acceleration_value, snapshot_kind = webidl::SnapshotKind::Identity, snapshot_default = v8::null(scope).into())]acceleration: Option<AccelerationInit>,#[webidl(name = "accelerationIncludingGravity", dictionary)]+ #[webidl(snapshot_slot = ACCELERATION_WITH_GRAVITY, snapshot_with = acceleration_value, snapshot_kind = webidl::SnapshotKind::Identity, snapshot_default = v8::null(scope).into())]acceleration_including_gravity: Option<AccelerationInit>,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = INTERVAL)]interval: f64,#[webidl(name = "rotationRate", dictionary)]+ #[webidl(snapshot_slot = ROTATION_RATE, snapshot_with = rotation_rate_value, snapshot_kind = webidl::SnapshotKind::Identity, snapshot_default = v8::null(scope).into())]rotation_rate: Option<RotationRateInit>,}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "DeviceMotionEventAccelerationInit")]+#[webidl(prefix = "DeviceMotionEventAccelerationInit", snapshot)]struct AccelerationInit {#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = X)]x: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = Y)]y: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = Z)]z: Option<f64>,}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "DeviceMotionEventRotationRateInit")]+#[webidl(prefix = "DeviceMotionEventRotationRateInit", snapshot)]struct RotationRateInit {#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = ALPHA)]alpha: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = BETA)]beta: Option<f64>,#[webidl(nullable, converter = "double")]+ #[webidl(snapshot_slot = GAMMA)]gamma: Option<f64>,}@@ -195,60 +198,36 @@ fn vector_getter<'s>(}}-fn nullable_number<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: Option<f64>,-) -> v8::Local<'s, v8::Value> {- match value {- Some(value) => v8::Number::new(scope, value).into(),- None => v8::null(scope).into(),- }-}-+// Nested motion dictionaries produce platform objects, retaining their intrinsic+// prototypes and native brands while their payload slots come from the schema.fn acceleration_value<'s>(scope: &mut v8::PinScope<'s, '_>,- value: Option<AccelerationInit>,-) -> v8::Local<'s, v8::Value> {- let Some(value) = value else {- return v8::null(scope).into();- };+ value: &AccelerationInit,+ _: SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {let prototype = super::super::exposed_interfaces::ensure_intrinsic_interface_prototype(scope,"DeviceMotionEventAcceleration",)- .expect("DeviceMotionEventAcceleration intrinsic prototype should initialize");- AccelerationObject::new(- prototype,- nullable_number(scope, value.x),- nullable_number(scope, value.y),- nullable_number(scope, value.z),- )- .bind(scope)- .expect("DeviceMotionEventAcceleration should initialize")- .into()+ .ok()?;+ let object = AccelerationObject::new(prototype).bind(scope).ok()?;+ value.initialize_snapshot(scope, object)?;+ Some(object.into())}fn rotation_rate_value<'s>(scope: &mut v8::PinScope<'s, '_>,- value: Option<RotationRateInit>,-) -> v8::Local<'s, v8::Value> {- let Some(value) = value else {- return v8::null(scope).into();- };+ value: &RotationRateInit,+ _: SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {let prototype = super::super::exposed_interfaces::ensure_intrinsic_interface_prototype(scope,"DeviceMotionEventRotationRate",)- .expect("DeviceMotionEventRotationRate intrinsic prototype should initialize");- RotationRateObject::new(- prototype,- nullable_number(scope, value.alpha),- nullable_number(scope, value.beta),- nullable_number(scope, value.gamma),- )- .bind(scope)- .expect("DeviceMotionEventRotationRate should initialize")- .into()+ .ok()?;+ let object = RotationRateObject::new(prototype).bind(scope).ok()?;+ value.initialize_snapshot(scope, object)?;+ Some(object.into())}#[derive(Clone, Copy)]@@ -275,20 +254,9 @@ fn initialize_payload<'s>(match kind {DeviceEventKind::Orientation => {let parsed = webidl::parse_dictionary_object::<OrientationInit>(scope, dictionary)?;- for (slot, value) in [- (ALPHA, parsed.alpha),- (BETA, parsed.beta),- (GAMMA, parsed.gamma),- ] {- let value = nullable_number(scope, value);- set_event_private_value(scope, state, slot, value);- }- set_event_private_value(- scope,- state,- ABSOLUTE,- v8::Boolean::new(scope, parsed.absolute).into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("orientation event state");Ok((parsed.base.bubbles,parsed.base.cancelable,@@ -297,24 +265,9 @@ fn initialize_payload<'s>(}DeviceEventKind::Motion => {let parsed = webidl::parse_dictionary_object::<MotionInit>(scope, dictionary)?;- let acceleration = acceleration_value(scope, parsed.acceleration);- let acceleration_with_gravity =- acceleration_value(scope, parsed.acceleration_including_gravity);- let rotation_rate = rotation_rate_value(scope, parsed.rotation_rate);- set_event_private_value(scope, state, ACCELERATION, acceleration);- set_event_private_value(- scope,- state,- ACCELERATION_WITH_GRAVITY,- acceleration_with_gravity,- );- set_event_private_value(scope, state, ROTATION_RATE, rotation_rate);- set_event_private_value(- scope,- state,- INTERVAL,- v8::Number::new(scope, parsed.interval).into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("motion event state");Ok((parsed.base.bubbles,parsed.base.cancelable,diff --git a/moli-renderer-v8/src/context_bootstrap/events/init.rs b/moli-renderer-v8/src/context_bootstrap/events/init.rsindex 31ee84aab..8e698afeb 100644--- a/moli-renderer-v8/src/context_bootstrap/events/init.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/init.rs@@ -4,7 +4,7 @@ use crate::{};#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "EventInit")]+#[webidl(prefix = "EventInit", snapshot)]pub(in crate::context_bootstrap) struct EventInit {#[webidl(default = false)]pub(in crate::context_bootstrap) bubbles: bool,diff --git a/moli-renderer-v8/src/context_bootstrap/events/message.rs b/moli-renderer-v8/src/context_bootstrap/events/message.rsindex c1ffbaa1e..80f488196 100644--- a/moli-renderer-v8/src/context_bootstrap/events/message.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/message.rs@@ -1,8 +1,8 @@use super::{event_backing, reinitialize_event_object};use crate::context_bootstrap::events::EventInit;-use crate::util::{v8_string, v8_string_from_utf16_units};+use crate::util::v8_string;use crate::{web_api_interfaces, webidl};-use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;// Interface metadata for the Window | MessagePort | ServiceWorker union.// The derives handle nullable conversion and retain the original object.@@ -24,17 +24,17 @@ impl MessageEventSource {/// Inherited EventInit members precede the lexicographically ordered own/// members. Conversion finishes before either base or payload state is set.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "MessageEventInit")]+#[webidl(prefix = "MessageEventInit", snapshot)]pub(super) struct MessageEventInit<'s> {#[webidl(inherit)]base: EventInit,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_default = v8::null(scope).into())]data: Option<v8::Local<'s, v8::Value>>,#[webidl(name = "lastEventId", default = webidl::DomString16(Vec::new()), converter = "raw")]last_event_id: webidl::DomString16,#[webidl(default = "", converter = "usv_string")]origin: String,- #[webidl(sequence, interface = crate::web_api_interfaces::MessagePort, default = Vec::new())]+ #[webidl(sequence, interface = crate::web_api_interfaces::MessagePort, default = Vec::new(), snapshot_frozen)]ports: Vec<v8::Local<'s, v8::Object>>,#[webidl(nullable, interface = MessageEventSource)]source: Option<v8::Local<'s, v8::Object>>,@@ -96,49 +96,10 @@ struct InitMessageEventArgs<'s> {ports: Vec<v8::Local<'s, v8::Object>>,}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct MessageEventState<'s> {- data: v8::Local<'s, v8::Value>,- origin: v8::Local<'s, v8::String>,- last_event_id: v8::Local<'s, v8::String>,- source: v8::Local<'s, v8::Value>,- ports: v8::Local<'s, v8::Array>,-}-pub(super) fn initialize_message_event<'s>(scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,init: MessageEventInit<'s>,-) {- let ports = init- .ports- .iter()- .map(|port| (*port).into())- .collect::<Vec<_>>();- let data = init.data.unwrap_or_else(|| v8::null(scope).into());- let source = init- .source- .map_or_else(|| v8::null(scope).into(), |source| source.into());- initialize_message_event_state(- scope,- event,- data,- &init.origin,- &init.last_event_id.0,- source,- &ports,- );-}--fn initialize_message_event_state<'s>(- scope: &mut v8::PinScope<'s, '_>,- event: v8::Local<'s, v8::Object>,- data: v8::Local<'s, v8::Value>,- origin: &str,- last_event_id: &[u16],- source: v8::Local<'s, v8::Value>,- ports: &[v8::Local<'s, v8::Value>],) {let event = event_backing(scope, event);// A borrowed initializer still creates the FrozenArray in the event's@@ -147,13 +108,9 @@ fn initialize_message_event_state<'s>(.get_creation_context(scope).unwrap_or_else(|| scope.get_current_context());let scope = &mut v8::ContextScope::new(scope, context);- let ports = v8::Array::new_with_elements(scope, ports);- let _ = ports.set_integrity_level(scope, v8::IntegrityLevel::Frozen);- let origin = v8_string(scope, origin).expect("MessageEvent origin");- let last_event_id =- v8_string_from_utf16_units(scope, last_event_id).expect("MessageEvent lastEventId");- MessageEventState::new(data, origin, last_event_id, source, ports)- .initialize(scope, event)+ // Event construction and legacy reinitialization own the inherited flags.+ // In particular, initMessageEvent preserves the existing composed value.+ init.initialize_own_snapshot(scope, event).expect("MessageEvent state should initialize");}@@ -176,9 +133,24 @@ pub(crate) fn construct_original_message_event<'s>(let event_type = v8_string(scope, event_type)?;let event = constructor.new_instance(scope, &[event_type.into()])?;let ports = (0..ports.length())- .map(|index| ports.get_index(scope, index))+ .map(|index| ports.get_index(scope, index)?.try_into().ok()).collect::<Option<Vec<_>>>()?;- initialize_message_event_state(scope, event, data, origin, last_event_id, source, &ports);+ initialize_message_event(+ scope,+ event,+ MessageEventInit {+ base: EventInit::default(),+ data: Some(data),+ origin: origin.to_owned(),+ last_event_id: webidl::DomString16(last_event_id.to_vec()),+ source: if source.is_null_or_undefined() {+ None+ } else {+ Some(source.try_into().ok()?)+ },+ ports,+ },+ );Some(event)}diff --git a/moli-renderer-v8/src/context_bootstrap/events/speech.rs b/moli-renderer-v8/src/context_bootstrap/events/speech.rsindex 3f2ea5156..82e52ba5f 100644--- a/moli-renderer-v8/src/context_bootstrap/events/speech.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/speech.rs@@ -2,13 +2,14 @@use super::{EventInit, define_event_property, event_private_value, initialize_event_object_with_type,- initialize_event_wrapper, new_event_state, set_event_private_value,+ initialize_event_wrapper, new_event_state,};use crate::{- util::{new_null_prototype_object, throw_type_error, v8_string_from_utf16_units, v8str},+ util::{new_null_prototype_object, throw_type_error, v8str},web_api_interfaces, webidl,};use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::WebIdlDictionarySerialize;const UTTERANCE: &str = "__moliSpeechEventUtterance";const CHAR_INDEX: &str = "__moliSpeechEventCharIndex";@@ -49,48 +50,35 @@ enum SpeechSynthesisErrorCode {NotAllowed,}-impl SpeechSynthesisErrorCode {- fn token(self) -> &'static str {- match self {- Self::Canceled => "canceled",- Self::Interrupted => "interrupted",- Self::AudioBusy => "audio-busy",- Self::AudioHardware => "audio-hardware",- Self::Network => "network",- Self::SynthesisUnavailable => "synthesis-unavailable",- Self::SynthesisFailed => "synthesis-failed",- Self::LanguageUnavailable => "language-unavailable",- Self::VoiceUnavailable => "voice-unavailable",- Self::TextTooLong => "text-too-long",- Self::InvalidArgument => "invalid-argument",- Self::NotAllowed => "not-allowed",- }- }-}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "SpeechSynthesisEventInit")]+#[webidl(prefix = "SpeechSynthesisEventInit", snapshot)]struct SpeechSynthesisEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(required, interface = web_api_interfaces::SpeechSynthesisUtterance)]+ #[webidl(snapshot_slot = UTTERANCE)]utterance: v8::Local<'s, v8::Object>,#[webidl(default = 0)]+ #[webidl(snapshot_slot = CHAR_INDEX)]char_index: u32,#[webidl(default = 0)]+ #[webidl(snapshot_slot = CHAR_LENGTH)]char_length: u32,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = ELAPSED_TIME)]elapsed_time: f32,#[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")]+ #[webidl(snapshot_slot = NAME)]name: webidl::DomString16,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "SpeechSynthesisErrorEventInit")]+#[webidl(prefix = "SpeechSynthesisErrorEventInit", snapshot)]struct SpeechSynthesisErrorEventInit<'s> {#[webidl(inherit)]base: SpeechSynthesisEventInit<'s>,#[webidl(required, converter = "enum")]+ #[webidl(snapshot_slot = ERROR)]error: SpeechSynthesisErrorCode,}@@ -179,66 +167,45 @@ fn constructor<'s>(let Some(event_type) = args.get(0).to_string(scope) else {return;};+ let state = new_event_state(scope);let parsed = (|| {let dictionary =webidl::dictionary_arg(&args, 1, webidl::Context::argument(kind.name(), 2))?.unwrap_or_else(|| new_null_prototype_object(scope));match kind {SpeechEventKind::Synthesis => {- webidl::parse_dictionary_object::<SpeechSynthesisEventInit>(scope, dictionary)- .map(|init| (init, None))+ webidl::parse_dictionary_object::<SpeechSynthesisEventInit>(scope, dictionary).map(+ |init| {+ init.initialize_snapshot(scope, state)+ .expect("speech event state");+ init.base+ },+ )}SpeechEventKind::Error => {webidl::parse_dictionary_object::<SpeechSynthesisErrorEventInit>(scope, dictionary)- .map(|init| (init.base, Some(init.error)))+ .map(|init| {+ init.initialize_snapshot(scope, state)+ .expect("speech error event state");+ init.base.base+ })}}})();- let (init, error) = match parsed {+ let init = match parsed {Ok(parsed) => parsed,Err(error) => {webidl::throw_error(scope, &error);return;}};- let state = new_event_state(scope);- initialize_event_object_with_type(- scope,- state,- event_type,- init.base.bubbles,- init.base.cancelable,- );+ initialize_event_object_with_type(scope, state, event_type, init.bubbles, init.cancelable);define_event_property(scope,state,"composed",- v8::Boolean::new(scope, init.base.composed).into(),+ v8::Boolean::new(scope, init.composed).into(),);- set_event_private_value(scope, state, UTTERANCE, init.utterance.into());- set_event_private_value(- scope,- state,- CHAR_INDEX,- v8::Integer::new_from_unsigned(scope, init.char_index).into(),- );- set_event_private_value(- scope,- state,- CHAR_LENGTH,- v8::Integer::new_from_unsigned(scope, init.char_length).into(),- );- set_event_private_value(- scope,- state,- ELAPSED_TIME,- v8::Number::new(scope, f64::from(init.elapsed_time)).into(),- );- let name = v8_string_from_utf16_units(scope, &init.name.0).expect("speech event name");- set_event_private_value(scope, state, NAME, name.into());- if let Some(error) = error {- set_event_private_value(scope, state, ERROR, v8str(scope, error.token()).into());- }web_api_interfaces::initialize(scope, state, kind.name()).expect("speech event brand should initialize");if initialize_event_wrapper(scope, args.this(), state).is_some() {diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rsindex 456d87202..a7bfaf77f 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs@@ -23,7 +23,10 @@ pub(in crate::context_bootstrap) use pointer::{pointer_event_get_coalesced_events_callback, pointer_event_get_predicted_events_callback,};-pub(in crate::context_bootstrap::events) use data::initialize_navigate_event_methods;+pub(in crate::context_bootstrap::events) use data::{+ StorageEventInitMembers, initialize_navigate_event_methods,+};pub(crate) use error::construct_original_error_event;pub(in crate::context_bootstrap) use keyboard::keyboard_event_init_callback;+pub(crate) use security_policy::initialize_native_security_policy_violation_event;diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rsindex 87cc937dc..73d82a4dc 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs@@ -20,6 +20,7 @@ use crate::web_api_interfaces;use crate::webidl;use moli_webapi_declare::WebApiObject;use url::Url;+use webidl::WebIdlDictionarySerialize;const NAVIGATE_EVENT_SYNTHETIC_SLOT: &str = "__lmNavigateEventSynthetic";const NAVIGATE_EVENT_INTERCEPTED_SLOT: &str = "__lmNavigateEventIntercepted";@@ -170,17 +171,6 @@ struct InterestEventInitDeclaration<'scope> {source: v8::Local<'scope, v8::Value>,}-#[derive(WebApiObject)]-#[webapi(plain)]-struct ToggleEventStateDeclaration<'scope> {- #[webapi(data_property = "oldState", readonly, dont_delete)]- old_state: String,- #[webapi(data_property = "newState", readonly, dont_delete)]- new_state: String,- #[webapi(data_property, readonly, dont_delete)]- source: v8::Local<'scope, v8::Value>,-}-#[derive(WebApiObject)]#[webapi(plain, data_properties, enumerable)]struct PopStateEventInitDeclaration<'scope> {@@ -189,18 +179,9 @@ struct PopStateEventInitDeclaration<'scope> {has_ua_visual_transition: bool,}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct HashChangeEventInitDeclaration {- #[webapi(data_property = "oldURL")]- old_url: String,- #[webapi(data_property = "newURL")]- new_url: String,-}-/// Members are declared in Web IDL lexicographic order.#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "HashChangeEventInit")]+#[webidl(prefix = "HashChangeEventInit", snapshot)]struct HashChangeEventInitMembers {#[webidl(name = "newURL", default = "", converter = "usv_string")]new_url: String,@@ -214,19 +195,12 @@ struct PageTransitionEventOwnInitDeclaration {persisted: bool,}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct PromiseRejectionEventInitDeclaration<'scope> {- promise: v8::Local<'scope, v8::Value>,- reason: v8::Local<'scope, v8::Value>,-}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PromiseRejectionEventInit")]+#[webidl(prefix = "PromiseRejectionEventInit", snapshot)]struct PromiseRejectionEventInitMembers<'s> {#[webidl(required)]promise: v8::Local<'s, v8::Object>,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_default = v8::undefined(scope).into())]reason: Option<v8::Local<'s, v8::Value>>,}@@ -255,19 +229,22 @@ struct NavigateEventInitDeclaration<'scope> {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "ToggleEventInit")]+#[webidl(prefix = "ToggleEventInit", snapshot)]struct ToggleEventInitMembers<'s> {#[webidl(default = "")]+ #[webidl(snapshot_attributes = v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE | v8::PropertyAttribute::DONT_ENUM)]old_state: String,#[webidl(default = "")]+ #[webidl(snapshot_attributes = v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE | v8::PropertyAttribute::DONT_ENUM)]new_state: String,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_default = v8::null(scope).into())]+ #[webidl(snapshot_attributes = v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE | v8::PropertyAttribute::DONT_ENUM)]source: Option<v8::Local<'s, v8::Value>>,}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "StorageEventInit")]-pub(super) struct StorageEventInitMembers<'s> {+#[webidl(prefix = "StorageEventInit", snapshot)]+pub(in crate::context_bootstrap::events) struct StorageEventInitMembers<'s> {#[webidl(inherit)]base: EventInit,#[webidl(nullable, converter = "raw")]@@ -282,6 +259,27 @@ pub(super) struct StorageEventInitMembers<'s> {url: String,}+impl<'s> StorageEventInitMembers<'s> {+ pub(in crate::context_bootstrap::events) fn from_native(+ key: Option<&[u16]>,+ old_value: Option<&[u16]>,+ new_value: Option<&[u16]>,+ url: &str,+ storage_area: Option<v8::Local<'s, v8::Value>>,+ ) -> Self {+ Self {+ base: EventInit::default(),+ key: key.map(|value| webidl::DomString16(value.to_vec())),+ old_value: old_value.map(|value| webidl::DomString16(value.to_vec())),+ new_value: new_value.map(|value| webidl::DomString16(value.to_vec())),+ url: url.to_owned(),+ storage_area: storage_area+ .and_then(|value| value.try_into().ok())+ .map(StorageReference),+ }+ }+}+impl StorageEventInitMembers<'_> {pub(super) fn event_flags(&self) -> (bool, bool, bool) {(self.base.bubbles, self.base.cancelable, self.base.composed)@@ -429,15 +427,9 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_storage_eventevent: v8::Local<'s, v8::Object>,parsed: StorageEventInitMembers<'s>,) {- crate::context_bootstrap::events::define_storage_event_properties_utf16(- scope,- event,- parsed.key.as_ref().map(|value| value.0.as_slice()),- parsed.old_value.as_ref().map(|value| value.0.as_slice()),- parsed.new_value.as_ref().map(|value| value.0.as_slice()),- &parsed.url,- parsed.storage_area.map(|value| value.0.into()),- );+ parsed+ .initialize_snapshot(scope, event)+ .expect("StorageEvent state");}pub(in crate::context_bootstrap::events::subclasses) fn initialize_input_event<'s>(@@ -483,8 +475,8 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_hash_change_e}None => HashChangeEventInitMembers::default(),};- HashChangeEventInitDeclaration::new(parsed.old_url, parsed.new_url)- .initialize(scope, event)+ parsed+ .initialize_snapshot(scope, event).expect("HashChangeEvent init declaration should initialize");true}@@ -521,9 +513,7 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_toggle_event<source: None,},};- let source = parsed.source.unwrap_or_else(|| v8::null(scope).into());- let _ = ToggleEventStateDeclaration::new(parsed.old_state, parsed.new_state, source)- .initialize(scope, event);+ let _ = parsed.initialize_snapshot(scope, event);true}@@ -551,9 +541,8 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_promise_rejecreturn false;}};- let reason = parsed.reason.unwrap_or_else(|| v8::undefined(scope).into());- PromiseRejectionEventInitDeclaration::new(parsed.promise.into(), reason)- .initialize(scope, event)+ parsed+ .initialize_snapshot(scope, event).expect("PromiseRejectionEvent init declaration should initialize");true}diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/error.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/error.rsindex aa063018b..70a1dc363 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/error.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/error.rs@@ -1,18 +1,18 @@use crate::context_bootstrap::events::EventInit;-use crate::util::{v8_string, v8_string_from_utf16_units};+use crate::util::v8_string;use crate::webidl;-use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;/// Convert EventInit first, followed by ErrorEventInit's own members in lexical/// order. All conversion completes before either base or payload state is set.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "ErrorEventInit")]+#[webidl(prefix = "ErrorEventInit", snapshot)]pub(super) struct ErrorEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(default = 0)]colno: u32,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_default = v8::undefined(scope).into())]error: Option<v8::Local<'s, v8::Value>>,#[webidl(default = "", converter = "usv_string")]filename: String,@@ -53,16 +53,6 @@ pub(super) fn parse_error_event_init<'s>(}}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct ErrorEventState<'s> {- message: v8::Local<'s, v8::String>,- filename: v8::Local<'s, v8::String>,- lineno: u32,- colno: u32,- error: v8::Local<'s, v8::Value>,-}-impl<'s> ErrorEventInit<'s> {pub(super) fn event_flags(&self) -> (bool, bool, bool) {(self.base.bubbles, self.base.cancelable, self.base.composed)@@ -73,12 +63,7 @@ impl<'s> ErrorEventInit<'s> {scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,) {- let message = v8_string_from_utf16_units(scope, &self.message.0)- .expect("ErrorEvent DOMString message");- let filename = v8_string(scope, &self.filename).expect("ErrorEvent USVString filename");- let error = self.error.unwrap_or_else(|| v8::undefined(scope).into());- ErrorEventState::new(message, filename, self.lineno, self.colno, error)- .initialize(scope, event)+ self.initialize_snapshot(scope, event).expect("ErrorEvent state should initialize");// Existing onerror dispatch reads this native backing, bypassing public getters.}@@ -104,16 +89,17 @@ pub(crate) fn construct_original_error_event<'s>(let event_type = v8_string(scope, "error")?;let event = constructor.new_instance(scope, &[event_type.into()])?;let state = super::super::event_backing(scope, event);- let message = v8_string(scope, message)?;- let filename = v8_string(scope, filename)?;- ErrorEventState::new(message, filename, lineno, colno, error)- .initialize(scope, state)- .ok()?;- super::super::define_event_property(- scope,- state,- "cancelable",- v8::Boolean::new(scope, true).into(),- );+ ErrorEventInit {+ base: EventInit {+ cancelable: true,+ ..EventInit::default()+ },+ message: webidl::DomString16(message.encode_utf16().collect()),+ filename: filename.to_owned(),+ lineno,+ colno,+ error: Some(error),+ }+ .initialize_snapshot(scope, state)?;Some(event)}diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/keyboard.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/keyboard.rsindex f143d0a61..04a9689d0 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/keyboard.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/keyboard.rs@@ -2,10 +2,11 @@ use super::super::ui::{UiEventInit, initialize_legacy_ui_event};use super::*;use crate::webidl;use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;/// Own KeyboardEventInit members, including the legacy code members.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "KeyboardEventInit")]+#[webidl(prefix = "KeyboardEventInit", snapshot)]struct KeyboardEventInitMembers {#[webidl(default = 0)]char_code: u32,@@ -76,39 +77,17 @@ pub(super) fn parse_keyboard_event_init<'s>(}}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct KeyboardEventInitDeclaration<'scope> {- key: v8::Local<'scope, v8::String>,- code: v8::Local<'scope, v8::String>,- location: u32,- char_code: u32,- key_code: u32,- repeat: bool,- is_composing: bool,-}-pub(super) fn initialize_keyboard_event<'s>(scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,parsed: KeyboardEventInit<'s>,) {parsed.ui.initialize(scope, event);- let key = v8_string_from_utf16_units(scope, &parsed.keyboard.key.0).expect("KeyboardEvent key");- let code =- v8_string_from_utf16_units(scope, &parsed.keyboard.code.0).expect("KeyboardEvent code");parsed.modifiers.initialize(scope, event);- KeyboardEventInitDeclaration::new(- key,- code,- parsed.keyboard.location,- parsed.keyboard.char_code,- parsed.keyboard.key_code,- parsed.keyboard.repeat,- parsed.keyboard.is_composing,- )- .initialize(scope, event)- .expect("KeyboardEvent init declaration should initialize");+ parsed+ .keyboard+ .initialize_snapshot(scope, event)+ .expect("KeyboardEvent state should initialize");}#[derive(webidl::WebIdlArgs)]diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/pointer.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/pointer.rsindex 1caa168d8..f97ca961f 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/pointer.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/pointer.rs@@ -2,16 +2,19 @@ use super::*;use moli_webapi_declare::WebApiObject;use crate::webidl;+use webidl::WebIdlDictionarySerialize;const POINTER_EVENT_COALESCED_EVENTS_SLOT: &str = "__moliPointerEventCoalescedEvents";const POINTER_EVENT_PREDICTED_EVENTS_SLOT: &str = "__moliPointerEventPredictedEvents";#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "PointerEventInit")]+#[webidl(prefix = "PointerEventInit", snapshot)]struct PointerEventSequences<'scope> {#[webidl(sequence, interface = crate::web_api_interfaces::PointerEvent, brand_check = is_pointer_event_sequence_item, default = Vec::new())]+ #[webidl(snapshot_slot = POINTER_EVENT_COALESCED_EVENTS_SLOT)]coalesced_events: Vec<v8::Local<'scope, v8::Object>>,#[webidl(sequence, interface = crate::web_api_interfaces::PointerEvent, brand_check = is_pointer_event_sequence_item, default = Vec::new())]+ #[webidl(snapshot_slot = POINTER_EVENT_PREDICTED_EVENTS_SLOT)]predicted_events: Vec<v8::Local<'scope, v8::Object>>,}@@ -279,20 +282,6 @@ fn pointer_event_angle_init<'s>(Ok(angles)}-fn store_pointer_event_sequence<'s>(- scope: &mut v8::PinScope<'s, '_>,- event: v8::Local<'s, v8::Object>,- slot: &'static str,- entries: &[v8::Local<'s, v8::Object>],-) {- let entries = entries- .iter()- .map(|entry| v8::Local::<v8::Value>::from(*entry))- .collect::<Vec<_>>();- let values = v8::Array::new_with_elements(scope, &entries);- set_private_value(scope, event, slot, values.into());-}-fn pointer_event_sequence_copy<'s>(scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,@@ -503,17 +492,8 @@ pub(in crate::context_bootstrap::events::subclasses) fn initialize_pointer_event.initialize(scope, event).expect("PointerEvent tail init declaration should initialize");define_mouse_event_related_target(scope, event, related_target);- store_pointer_event_sequence(- scope,- event,- POINTER_EVENT_COALESCED_EVENTS_SLOT,- &sequences.coalesced_events,- );- store_pointer_event_sequence(- scope,- event,- POINTER_EVENT_PREDICTED_EVENTS_SLOT,- &sequences.predicted_events,- );+ sequences+ .initialize_snapshot(scope, event)+ .expect("PointerEvent sequences");true}diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rsindex cbc93e66a..61755bd0c 100644--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/security_policy.rs@@ -1,14 +1,14 @@use crate::content_security_policy::{- ContentSecurityPolicyDisposition, ContentSecurityPolicyViolationEventDeclaration,+ ContentSecurityPolicyDisposition, ContentSecurityPolicyViolationEventFields,};use crate::context_bootstrap::events::EventInit;-use crate::util::{v8_string, v8_string_from_utf16_units};use crate::webidl;+use webidl::WebIdlDictionarySerialize;// Convert EventInit first, then the derived members in lexical order. Keep// DOMString code units distinct from the four USVString URL fields.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "SecurityPolicyViolationEventInit")]+#[webidl(prefix = "SecurityPolicyViolationEventInit", snapshot)]pub(super) struct SecurityPolicyViolationEventInit {#[webidl(inherit)]base: EventInit,@@ -90,33 +90,40 @@ impl SecurityPolicyViolationEventInit {scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,) {- let document_uri = v8_string(scope, &self.document_uri).expect("USVString documentURI");- let referrer = v8_string(scope, &self.referrer).expect("USVString referrer");- let blocked_uri = v8_string(scope, &self.blocked_uri).expect("USVString blockedURI");- let effective_directive = v8_string_from_utf16_units(scope, &self.effective_directive.0)- .expect("DOMString effectiveDirective");- let violated_directive = v8_string_from_utf16_units(scope, &self.violated_directive.0)- .expect("DOMString violatedDirective");- let original_policy = v8_string_from_utf16_units(scope, &self.original_policy.0)- .expect("DOMString originalPolicy");- let disposition = v8_string(scope, self.disposition.as_str()).expect("disposition enum");- let source_file = v8_string(scope, &self.source_file).expect("USVString sourceFile");- let sample = v8_string_from_utf16_units(scope, &self.sample.0).expect("DOMString sample");- ContentSecurityPolicyViolationEventDeclaration::new(- document_uri,- referrer,- blocked_uri,- effective_directive,- violated_directive,- original_policy,- disposition,- source_file,- sample,- self.line_number,- self.column_number,- self.status_code,- )- .initialize(scope, event)- .expect("SecurityPolicyViolationEvent state should initialize");+ self.initialize_snapshot(scope, event)+ .expect("SecurityPolicyViolationEvent state should initialize");+ crate::web_api_interfaces::initialize(scope, event, "SecurityPolicyViolationEvent")+ .expect("SecurityPolicyViolationEvent brand");}}++/// Native reports use the same dictionary schema, without converting an author+/// object or consulting a public constructor.+pub(crate) fn initialize_native_security_policy_violation_event<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ event: v8::Local<'s, v8::Object>,+ fields: &ContentSecurityPolicyViolationEventFields<'_>,+) -> Option<()> {+ let text = |value: &str| webidl::DomString16(value.encode_utf16().collect());+ SecurityPolicyViolationEventInit {+ base: EventInit {+ bubbles: true,+ cancelable: false,+ composed: true,+ },+ blocked_uri: fields.blocked_uri.to_owned(),+ column_number: fields.column_number.try_into().unwrap_or_default(),+ disposition: fields.disposition,+ document_uri: fields.document_uri.to_owned(),+ effective_directive: text(fields.effective_directive),+ line_number: fields.line_number.try_into().unwrap_or_default(),+ original_policy: text(fields.original_policy),+ referrer: fields.referrer.to_owned(),+ sample: text(fields.sample),+ source_file: fields.source_file.to_owned(),+ status_code: fields.status_code.try_into().unwrap_or_default(),+ violated_directive: text(fields.violated_directive),+ }+ .initialize_snapshot(scope, event)?;+ crate::web_api_interfaces::initialize(scope, event, "SecurityPolicyViolationEvent").ok()+}diff --git a/moli-renderer-v8/src/context_bootstrap/events/ui.rs b/moli-renderer-v8/src/context_bootstrap/events/ui.rsindex 2c20f71fb..77e7f1616 100644--- a/moli-renderer-v8/src/context_bootstrap/events/ui.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/ui.rs@@ -1,5 +1,6 @@use crate::webidl;use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;fn nullable_window_value<'s>(scope: &mut v8::PinScope<'s, '_>,@@ -12,8 +13,10 @@ fn nullable_window_value<'s>(/// Own UIEventInit members, including legacy which, in dictionary order.#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "UIEventInit")]-struct UiEventInitMembers<'s> {+#[webidl(prefix = "UIEventInit", snapshot)]+pub(super) struct UiEventInit<'s> {+ #[webidl(inherit)]+ base: super::EventInit,#[webidl(default = 0)]detail: i32,#[webidl(nullable, interface = crate::web_api_interfaces::Window, brand_check = crate::context_bootstrap::is_window_receiver)]@@ -22,29 +25,9 @@ struct UiEventInitMembers<'s> {which: u32,}-#[derive(Default)]-pub(super) struct UiEventInit<'s> {- flags: (bool, bool, bool),- members: UiEventInitMembers<'s>,-}--impl<'s> webidl::WebIdlDictionary<'s> for UiEventInit<'s> {- fn parse_dictionary(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- ) -> Result<Self, webidl::WebIdlError> {- // Read inherited members before own members. Derived dictionaries- // delegate here so each observable getter runs once, base-first.- Ok(Self {- flags: super::init::parse_event_init(scope, Some(object))?,- members: webidl::parse_dictionary_object(scope, object)?,- })- }-}-impl<'s> UiEventInit<'s> {pub(super) fn event_flags(&self) -> (bool, bool, bool) {- self.flags+ (self.base.bubbles, self.base.cancelable, self.base.composed)}pub(super) fn initialize(@@ -52,21 +35,11 @@ impl<'s> UiEventInit<'s> {scope: &mut v8::PinScope<'s, '_>,event: v8::Local<'s, v8::Object>,) {- let view = nullable_window_value(scope, self.members.view);- UiEventState::new(view, self.members.detail, self.members.which)- .initialize(scope, event)+ self.initialize_snapshot(scope, event).expect("UIEvent state should initialize");}}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct UiEventState<'s> {- view: v8::Local<'s, v8::Value>,- detail: i32,- which: u32,-}-#[derive(WebApiObject)]#[webapi(plain, data_properties, enumerable)]struct LegacyUiEventState<'s> {diff --git a/moli-renderer-v8/src/context_bootstrap/events/value.rs b/moli-renderer-v8/src/context_bootstrap/events/value.rsindex cc768dfa6..47703880a 100644--- a/moli-renderer-v8/src/context_bootstrap/events/value.rs+++ b/moli-renderer-v8/src/context_bootstrap/events/value.rs@@ -2,7 +2,7 @@use super::{define_event_property, event_private_value, initialize_event_object_with_type,- initialize_event_wrapper, new_event_state, set_event_private_value,+ initialize_event_wrapper, new_event_state,};use crate::context_bootstrap::events::EventInit;use crate::{@@ -10,6 +10,7 @@ use crate::{web_api_interfaces, webidl,};use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::WebIdlDictionarySerialize;const NAME_SLOT: &str = "__moliValueEventName";const ELAPSED_TIME_SLOT: &str = "__moliValueEventElapsedTime";@@ -115,48 +116,56 @@ struct ToolCancelEventPrototypeDeclaration {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "ToolEventInit")]+#[webidl(prefix = "ToolEventInit", snapshot)]struct ToolEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(name = "toolName", with = string_member)]+ #[webidl(snapshot_slot = TOOL_NAME_SLOT)]tool_name: v8::Local<'s, v8::String>,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "WebGLContextEventInit")]+#[webidl(prefix = "WebGLContextEventInit", snapshot)]struct WebGlContextEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(with = string_member)]+ #[webidl(snapshot_slot = STATUS_MESSAGE_SLOT)]status_message: v8::Local<'s, v8::String>,}// Inherited dictionary members precede derived members, whose declaration order// follows Web IDL's lexicographic conversion order. Preserve DOMString code units.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AnimationEventInit")]+#[webidl(prefix = "AnimationEventInit", snapshot)]struct AnimationEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(name = "animationName", with = string_member)]+ #[webidl(snapshot_slot = NAME_SLOT)]animation_name: v8::Local<'s, v8::String>,#[webidl(name = "elapsedTime", converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = ELAPSED_TIME_SLOT)]elapsed_time: f64,#[webidl(name = "pseudoElement", with = string_member)]+ #[webidl(snapshot_slot = PSEUDO_ELEMENT_SLOT)]pseudo_element: v8::Local<'s, v8::String>,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "TransitionEventInit")]+#[webidl(prefix = "TransitionEventInit", snapshot)]struct TransitionEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(name = "elapsedTime", converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = ELAPSED_TIME_SLOT)]elapsed_time: f64,#[webidl(name = "propertyName", with = string_member)]+ #[webidl(snapshot_slot = NAME_SLOT)]property_name: v8::Local<'s, v8::String>,#[webidl(name = "pseudoElement", with = string_member)]+ #[webidl(snapshot_slot = PSEUDO_ELEMENT_SLOT)]pseudo_element: v8::Local<'s, v8::String>,}@@ -168,7 +177,7 @@ struct GamepadEventPrototypeDeclaration {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "GamepadEventInit")]+#[webidl(prefix = "GamepadEventInit", snapshot)]struct GamepadEventInit<'s> {#[webidl(default = false)]bubbles: bool,@@ -177,6 +186,7 @@ struct GamepadEventInit<'s> {#[webidl(default = false)]composed: bool,#[webidl(with = gamepad_member)]+ #[webidl(snapshot_slot = GAMEPAD_SLOT, snapshot_default = v8::null(scope).into())]gamepad: Option<v8::Local<'s, v8::Object>>,}@@ -200,13 +210,15 @@ fn gamepad_member<'s>(}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "BlobEventInit")]+#[webidl(prefix = "BlobEventInit", snapshot)]struct BlobEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(required, interface = web_api_interfaces::Blob)]+ #[webidl(snapshot_slot = BLOB_SLOT)]data: v8::Local<'s, v8::Object>,#[webidl(converter = "double")]+ #[webidl(snapshot_slot = TIMECODE_SLOT, snapshot_default = v8::Number::new(scope, f64::NAN).into())]timecode: Option<f64>,}@@ -218,11 +230,12 @@ struct PictureInPictureEventPrototype {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PictureInPictureEventInit")]+#[webidl(prefix = "PictureInPictureEventInit", snapshot)]struct PictureInPictureEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(required, interface = web_api_interfaces::PictureInPictureWindow)]+ #[webidl(snapshot_slot = PICTURE_IN_PICTURE_WINDOW_SLOT)]picture_in_picture_window: v8::Local<'s, v8::Object>,}@@ -236,13 +249,15 @@ struct PaymentMethodChangeEventPrototypeDeclaration {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PaymentMethodChangeEventInit")]+#[webidl(prefix = "PaymentMethodChangeEventInit", snapshot)]struct PaymentMethodChangeEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(nullable)]+ #[webidl(snapshot_slot = PAYMENT_METHOD_DETAILS_SLOT)]method_details: Option<v8::Local<'s, v8::Object>>,#[webidl(with = string_member)]+ #[webidl(snapshot_slot = PAYMENT_METHOD_NAME_SLOT)]method_name: v8::Local<'s, v8::String>,}@@ -403,19 +418,9 @@ fn value_event_constructor<'s>(ValueEventKind::Animation => {let parsed =webidl::parse_dictionary_object::<AnimationEventInit>(scope, dictionary)?;- set_event_private_value(scope, state, NAME_SLOT, parsed.animation_name.into());- set_event_private_value(- scope,- state,- ELAPSED_TIME_SLOT,- v8::Number::new(scope, parsed.elapsed_time).into(),- );- set_event_private_value(- scope,- state,- PSEUDO_ELEMENT_SLOT,- parsed.pseudo_element.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -425,19 +430,9 @@ fn value_event_constructor<'s>(ValueEventKind::Transition => {let parsed =webidl::parse_dictionary_object::<TransitionEventInit>(scope, dictionary)?;- set_event_private_value(scope, state, NAME_SLOT, parsed.property_name.into());- set_event_private_value(- scope,- state,- ELAPSED_TIME_SLOT,- v8::Number::new(scope, parsed.elapsed_time).into(),- );- set_event_private_value(- scope,- state,- PSEUDO_ELEMENT_SLOT,- parsed.pseudo_element.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -447,12 +442,9 @@ fn value_event_constructor<'s>(ValueEventKind::WebGlContext => {let parsed =webidl::parse_dictionary_object::<WebGlContextEventInit>(scope, dictionary)?;- set_event_private_value(- scope,- state,- STATUS_MESSAGE_SLOT,- parsed.status_message.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -461,13 +453,9 @@ fn value_event_constructor<'s>(}ValueEventKind::Blob => {let parsed = webidl::parse_dictionary_object::<BlobEventInit>(scope, dictionary)?;- set_event_private_value(scope, state, BLOB_SLOT, parsed.data.into());- set_event_private_value(- scope,- state,- TIMECODE_SLOT,- v8::Number::new(scope, parsed.timecode.unwrap_or(f64::NAN)).into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -476,7 +464,9 @@ fn value_event_constructor<'s>(}ValueEventKind::ToolActivated | ValueEventKind::ToolCancel => {let parsed = webidl::parse_dictionary_object::<ToolEventInit>(scope, dictionary)?;- set_event_private_value(scope, state, TOOL_NAME_SLOT, parsed.tool_name.into());+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -487,12 +477,9 @@ fn value_event_constructor<'s>(let parsed = webidl::parse_dictionary_object::<PictureInPictureEventInit>(scope, dictionary,)?;- set_event_private_value(- scope,- state,- PICTURE_IN_PICTURE_WINDOW_SLOT,- parsed.picture_in_picture_window.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -500,25 +487,19 @@ fn value_event_constructor<'s>()}ValueEventKind::PaymentRequestUpdate => {- // PaymentRequestUpdateEventInit adds no members to EventInit.let parsed = webidl::parse_dictionary_object::<EventInit>(scope, dictionary)?;+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.bubbles, parsed.cancelable, parsed.composed)}ValueEventKind::PaymentMethodChange => {let parsed = webidl::parse_dictionary_object::<PaymentMethodChangeEventInit>(scope, dictionary,)?;- let details = parsed- .method_details- .map(Into::into)- .unwrap_or_else(|| v8::null(scope).into());- set_event_private_value(scope, state, PAYMENT_METHOD_DETAILS_SLOT, details);- set_event_private_value(- scope,- state,- PAYMENT_METHOD_NAME_SLOT,- parsed.method_name.into(),- );+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.base.bubbles,parsed.base.cancelable,@@ -528,11 +509,9 @@ fn value_event_constructor<'s>(ValueEventKind::Gamepad => {let parsed =webidl::parse_dictionary_object::<GamepadEventInit>(scope, dictionary)?;- let gamepad = parsed- .gamepad- .map(Into::into)- .unwrap_or_else(|| v8::null(scope).into());- set_event_private_value(scope, state, GAMEPAD_SLOT, gamepad);+ parsed+ .initialize_snapshot(scope, state)+ .expect("value event state");(parsed.bubbles, parsed.cancelable, parsed.composed)}};diff --git a/moli-renderer-v8/src/context_bootstrap/geometry_runtime.rs b/moli-renderer-v8/src/context_bootstrap/geometry_runtime.rsindex d626ec5c6..8fa938624 100644--- a/moli-renderer-v8/src/context_bootstrap/geometry_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/geometry_runtime.rs@@ -8,6 +8,7 @@ use moli_geometry::{parse_dom_matrix_value,};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::{SnapshotPrototype, WebIdlDictionarySerialize};const DOM_POINT_X_SLOT: &str = "__moliDomPointX";const DOM_POINT_Y_SLOT: &str = "__moliDomPointY";@@ -36,16 +37,7 @@ const DOM_MATRIX_TYPED_ARRAY_LENGTH: usize = DOM_MATRIX_COMPONENT_COUNT;#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::DOMPoint, fallback_to_string_tag = "DOMPoint")]-struct DomPointObjectDeclaration {- #[webapi(slot = DOM_POINT_X_SLOT)]- x: f64,- #[webapi(slot = DOM_POINT_Y_SLOT)]- y: f64,- #[webapi(slot = DOM_POINT_Z_SLOT)]- z: f64,- #[webapi(slot = DOM_POINT_W_SLOT)]- w: f64,-}+struct DomPointObjectDeclaration {}macro_rules! dom_matrix_object_declaration {($name:ident, $interface:ident) => {@@ -118,15 +110,6 @@ macro_rules! dom_matrix_object_declaration {dom_matrix_object_declaration!(DomMatrixObjectDeclaration, DOMMatrix);dom_matrix_object_declaration!(DomMatrixReadOnlyObjectDeclaration, DOMMatrixReadOnly);-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct DomPointJsonDeclaration {- x: f64,- y: f64,- z: f64,- w: f64,-}-#[derive(WebApiObject)]#[webapi(plain, data_properties, enumerable)]struct DomMatrixJsonDeclaration {@@ -464,16 +447,20 @@ struct DomMatrixConstructorDeclaration {}#[derive(Clone, Copy, webidl::WebIdlDictionary)]-#[webidl(prefix = "DOMPointInit")]+#[webidl(prefix = "DOMPointInit", snapshot)]pub(super) struct DomPointInit {// WebIDL converts dictionary members in lexicographic order.#[webidl(default = 1.0)]+ #[webidl(snapshot_slot = DOM_POINT_W_SLOT, snapshot_order = 3)]pub(super) w: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_POINT_X_SLOT, snapshot_order = 0)]pub(super) x: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_POINT_Y_SLOT, snapshot_order = 1)]pub(super) y: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = DOM_POINT_Z_SLOT, snapshot_order = 2)]pub(super) z: f64,}@@ -546,7 +533,10 @@ pub(in crate::context_bootstrap) fn initialize_dom_point_object<'s>(z: f64,w: f64,) {- DomPointObjectDeclaration::new(x, y, z, w)+ DomPointInit { x, y, z, w }+ .initialize_snapshot(scope, object)+ .expect("DOMPoint state");+ DomPointObjectDeclaration::new().initialize(scope, object).expect("DOMPoint declaration should initialize object");}@@ -558,9 +548,13 @@ pub(in crate::context_bootstrap) fn build_dom_point_object<'s>(z: f64,w: f64,) -> v8::Local<'s, v8::Object> {- DomPointObjectDeclaration::new(x, y, z, w)+ let object = DomPointObjectDeclaration::new().bind(scope)- .expect("DOMPoint declaration should bind")+ .expect("DOMPoint declaration should bind");+ DomPointInit { x, y, z, w }+ .initialize_snapshot(scope, object)+ .expect("DOMPoint state");+ object}pub(super) fn dom_point_init_from_object<'s>(@@ -918,13 +912,8 @@ fn dom_point_to_json_callback<'s>(mut rv: v8::ReturnValue<'_, v8::Value>,) {let this = args.this();- let declaration = DomPointJsonDeclaration {- x: dom_point_slot(scope, this, DOM_POINT_X_SLOT, 0.0),- y: dom_point_slot(scope, this, DOM_POINT_Y_SLOT, 0.0),- z: dom_point_slot(scope, this, DOM_POINT_Z_SLOT, 0.0),- w: dom_point_slot(scope, this, DOM_POINT_W_SLOT, 1.0),- };- let Ok(object) = declaration.bind(scope) else {+ let point = dom_point_init_from_object(scope, this);+ let Some(object) = point.to_js_snapshot(scope, SnapshotPrototype::Ordinary) else {return;};rv.set(object.into());diff --git a/moli-renderer-v8/src/context_bootstrap/image_data.rs b/moli-renderer-v8/src/context_bootstrap/image_data.rsindex 96cf19eb1..36044fb24 100644--- a/moli-renderer-v8/src/context_bootstrap/image_data.rs+++ b/moli-renderer-v8/src/context_bootstrap/image_data.rs@@ -5,6 +5,7 @@ use crate::webidl;use moli_canvas::byte_len as rgba8_byte_len;use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};use std::str::FromStr;+use webidl::{SnapshotPrototype, WebIdlDictionarySerialize};const IMAGE_DATA_WIDTH_SLOT: &str = "__moliImageDataWidth";const IMAGE_DATA_HEIGHT_SLOT: &str = "__moliImageDataHeight";@@ -19,8 +20,6 @@ struct ImageDataObjectDeclaration<'s> {width: u32,#[webapi(slot = IMAGE_DATA_HEIGHT_SLOT)]height: u32,- #[webapi(slot = IMAGE_DATA_COLOR_SPACE_SLOT)]- color_space: String,#[webapi(slot = IMAGE_DATA_PIXEL_FORMAT_SLOT)]pixel_format: &'static str,#[webapi(slot = IMAGE_DATA_DATA_SLOT)]@@ -67,12 +66,6 @@ struct ImageDataPrototypeDeclaration {pixel_format: (),}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct ImageDataSettingsDeclaration<'scope> {- color_space: v8::Local<'scope, v8::String>,-}-#[derive(Clone, Debug)]pub(crate) struct ImageDataClonePayload {pub(crate) width: u32,@@ -103,12 +96,21 @@ impl ImageDataColorSpace {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "ImageDataSettings")]+#[webidl(prefix = "ImageDataSettings", snapshot)]struct ImageDataSettingsMembers {#[webidl(converter = "enum", default = ImageDataColorSpace::Srgb)]+ #[webidl(snapshot_slot = IMAGE_DATA_COLOR_SPACE_SLOT, snapshot_with = color_space_snapshot)]color_space: ImageDataColorSpace,}+fn color_space_snapshot<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: &ImageDataColorSpace,+ _: SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {+ v8_string(scope, value.label()).map(Into::into)+}+pub(super) fn image_data_constructor_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -127,7 +129,10 @@ pub(super) fn image_data_constructor_callback<'s>(return;};- ImageDataObjectDeclaration::new(width, height, color_space, "rgba-unorm8", data)+ color_space+ .initialize_snapshot(scope, args.this())+ .expect("ImageData settings");+ ImageDataObjectDeclaration::new(width, height, "rgba-unorm8", data).initialize(scope, args.this()).expect("ImageData declaration should initialize object");rv.set(args.this().into());@@ -163,7 +168,12 @@ fn image_data_getter_callback<'s>(fn image_data_constructor_parts<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,-) -> Option<(v8::Local<'s, v8::Uint8ClampedArray>, u32, u32, String)> {+) -> Option<(+ v8::Local<'s, v8::Uint8ClampedArray>,+ u32,+ u32,+ ImageDataSettingsMembers,+)> {if let Ok(data) = v8::Local::<v8::Uint8ClampedArray>::try_from(args.get(0)) {let width = image_data_dimension_arg(scope, args.get(1))?;let height = if args.length() > 2 && !args.get(2).is_undefined() {@@ -208,9 +218,11 @@ fn image_data_dimension_arg(fn image_data_color_space_arg<'s>(scope: &mut v8::PinScope<'s, '_>,value: v8::Local<'s, v8::Value>,-) -> Option<String> {+) -> Option<ImageDataSettingsMembers> {if webidl::is_nullish(value) {- return Some("srgb".to_owned());+ return Some(ImageDataSettingsMembers {+ color_space: ImageDataColorSpace::Srgb,+ });}let object = match v8::Local::<v8::Object>::try_from(value) {Ok(object) => object,@@ -224,13 +236,13 @@ fn image_data_color_space_arg<'s>(};let color_space =match webidl::parse_dictionary_object::<ImageDataSettingsMembers>(scope, object) {- Ok(value) => value.color_space,+ Ok(value) => value,Err(error) => {throw_type_error(scope, &error.to_string());return None;}};- Some(color_space.label().to_owned())+ Some(color_space)}const IMAGE_DATA_ATTRIBUTE_SLOTS: &[&str] = &[@@ -310,10 +322,10 @@ pub(crate) fn build_image_data_object_from_clone_payload<'s>(payload: ImageDataClonePayload,) -> Option<v8::Local<'s, v8::Object>> {let data = new_uint8_clamped_array_from_bytes(scope, payload.bytes)?;- let color_space = v8_string(scope, &payload.color_space)?;- let settings = ImageDataSettingsDeclaration::new(color_space)- .bind(scope)- .expect("ImageData settings declaration should bind");+ let settings = ImageDataSettingsMembers {+ color_space: ImageDataColorSpace::parse(&payload.color_space)?,+ }+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)?;let ctor = v8::Local::<v8::Function>::try_from(super::shared::global_constructor_object(scope,"ImageData",diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/event_target/version_change.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/event_target/version_change.rsindex 75c0884d5..403dd25cf 100644--- a/moli-renderer-v8/src/context_bootstrap/indexed_db/event_target/version_change.rs+++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/event_target/version_change.rs@@ -3,20 +3,12 @@ use super::*;use crate::context_bootstrap::events::EventInit;use crate::web_api_interfaces;use crate::webidl;-use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::WebIdlDictionarySerialize;const OLD_VERSION_SLOT: &str = "__moli_idb_event_old_version";const NEW_VERSION_SLOT: &str = "__moli_idb_event_new_version";-#[derive(WebApiObject)]-#[webapi(fragment)]-struct IdbVersionChangeEventFieldsDeclaration<'scope> {- #[webapi(slot = OLD_VERSION_SLOT)]- old_version: u64,- #[webapi(slot = NEW_VERSION_SLOT)]- new_version: v8::Local<'scope, v8::Value>,-}-#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::IDBVersionChangeEvent, enumerable, receiver)]struct IdbVersionChangeEventPrototypeDeclaration {@@ -68,15 +60,17 @@ struct IdbVersionChangeEventConstructorArgs {}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "IDBVersionChangeEventInit")]+#[webidl(prefix = "IDBVersionChangeEventInit", snapshot)]struct IdbVersionChangeEventInit {#[webidl(inherit)]base: EventInit,// WebIDL reads inherited EventInit members first, then this dictionary's// members in lexicographic order. The derive preserves inheritance order.#[webidl(nullable)]+ #[webidl(snapshot_slot = NEW_VERSION_SLOT)]new_version: Option<u64>,#[webidl(default = 0)]+ #[webidl(snapshot_slot = OLD_VERSION_SLOT)]old_version: u64,}@@ -111,12 +105,10 @@ pub(in crate::context_bootstrap) fn idb_version_change_event_constructor_callbac"composed",v8::Boolean::new(scope, parsed.init.base.composed).into(),);- IdbVersionChangeEventFieldsDeclaration::new(- parsed.init.old_version,- version_change_nullable_version_value(scope, parsed.init.new_version),- )- .initialize(scope, event)- .expect("IDBVersionChangeEvent fields declaration should initialize");+ parsed+ .init+ .initialize_snapshot(scope, event)+ .expect("IDBVersionChangeEvent state");crate::web_api_interfaces::initialize(scope, event, "IDBVersionChangeEvent").expect("IDBVersionChangeEvent brand");if events::initialize_event_wrapper(scope, wrapper, event).is_some() {@@ -133,11 +125,12 @@ pub(in crate::context_bootstrap::indexed_db) fn dispatch_version_change_event<'s) -> bool {let state = events::new_event_state(scope);events::initialize_event_object(scope, state, event_type, false, false);- IdbVersionChangeEventFieldsDeclaration::new(+ IdbVersionChangeEventInit {+ base: EventInit::default(),old_version,- version_change_nullable_version_value(scope, new_version),- )- .initialize(scope, state)+ new_version,+ }+ .initialize_snapshot(scope, state).expect("IDBVersionChangeEvent state");crate::web_api_interfaces::initialize(scope, state, "IDBVersionChangeEvent").expect("IDBVersionChangeEvent brand");@@ -147,12 +140,3 @@ pub(in crate::context_bootstrap::indexed_db) fn dispatch_version_change_event<'sevents::mark_event_trusted(scope, event);dispatch_idb_event_object(scope, target, event)}--fn version_change_nullable_version_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- version: Option<u64>,-) -> v8::Local<'s, v8::Value> {- version- .map(|value| v8::Number::new(scope, value as f64).into())- .unwrap_or_else(|| v8::null(scope).into())-}diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/event.rsindex f4b28775f..ba072919b 100644--- a/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs+++ b/moli-renderer-v8/src/context_bootstrap/media_queries/event.rs@@ -4,20 +4,12 @@ use crate::{util::{throw_type_error, v8str},web_api_interfaces, webidl,};-use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::WebIdlDictionarySerialize;const MEDIA_SLOT: &str = "__moliMediaQueryListEventMedia";const MATCHES_SLOT: &str = "__moliMediaQueryListEventMatches";-#[derive(WebApiObject)]-#[webapi(interface = web_api_interfaces::MediaQueryListEvent)]-struct MediaQueryListEventState<'scope> {- #[webapi(slot = MEDIA_SLOT)]- media: v8::Local<'scope, v8::String>,- #[webapi(slot = MATCHES_SLOT)]- matches: bool,-}-#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::MediaQueryListEvent, enumerable, receiver)]struct MediaQueryListEventPrototype {@@ -30,13 +22,15 @@ struct MediaQueryListEventPrototype {// Inherited EventInit members precede this dictionary's own members, each// group in lexicographic order. Convert the complete dictionary only once.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "MediaQueryListEventInit")]+#[webidl(prefix = "MediaQueryListEventInit", snapshot)]struct MediaQueryListEventInit<'s> {#[webidl(inherit)]base: EventInit,#[webidl(default = false)]+ #[webidl(snapshot_slot = MATCHES_SLOT)]matches: bool,#[webidl(with = media_member)]+ #[webidl(snapshot_slot = MEDIA_SLOT)]media: v8::Local<'s, v8::String>,}@@ -102,8 +96,7 @@ fn constructor<'s>(v8str(scope, "composed").into(),v8::Boolean::new(scope, init.base.composed).into(),);- MediaQueryListEventState::new(init.media, init.matches)- .initialize(scope, event)+ init.initialize_snapshot(scope, event).expect("MediaQueryListEvent state should initialize");web_api_interfaces::initialize(scope, event, "MediaQueryListEvent").expect("MediaQueryListEvent brand");@@ -134,9 +127,15 @@ pub(super) fn create_media_query_list_event<'s>(let media = v8::String::new(scope, media).expect("media query string");let event = crate::context_bootstrap::new_event_state(scope);initialize_event_object(scope, event, "change", false, false);- MediaQueryListEventState::new(media, matches)- .initialize(scope, event)- .expect("MediaQueryListEvent state");+ MediaQueryListEventInit {+ base: EventInit::default(),+ media,+ matches,+ }+ .initialize_snapshot(scope, event)+ .expect("MediaQueryListEvent state");+ web_api_interfaces::initialize(scope, event, "MediaQueryListEvent")+ .expect("MediaQueryListEvent brand");mark_event_trusted(scope, event);crate::context_bootstrap::new_event_wrapper(scope, event).expect("MediaQueryListEvent wrapper")}diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rsindex 21d27823f..7b37b75cd 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/clipboard.rs@@ -8,6 +8,7 @@ use crate::{};use anyhow::{Result, anyhow};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionarySerialize;const CLIPBOARD_ITEM_DATA_SLOT: &str = "__moliClipboardItemData";const CLIPBOARD_ITEM_RAW_DATA_SLOT: &str = "__moliClipboardItemRawData";@@ -48,9 +49,6 @@ struct ClipboardItemObjectDeclaration<'scope> {#[webapi(slot = CLIPBOARD_ITEM_TYPES_SLOT)]types: v8::Local<'scope, v8::Array>,-- #[webapi(slot = CLIPBOARD_ITEM_PRESENTATION_STYLE_SLOT)]- presentation_style: String,}#[derive(Default, WebApiFunctionTemplate)]@@ -74,9 +72,10 @@ struct ClipboardItemConstructorDeclaration {}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "ClipboardItemOptions")]+#[webidl(prefix = "ClipboardItemOptions", snapshot)]struct ClipboardItemOptions {#[webidl(converter = "enum", default = PresentationStyle::Unspecified)]+ #[webidl(snapshot_slot = CLIPBOARD_ITEM_PRESENTATION_STYLE_SLOT)]presentation_style: PresentationStyle,}@@ -230,14 +229,12 @@ fn initialize_clipboard_item<'s>(}}let _ = types.set_integrity_level(scope, v8::IntegrityLevel::Frozen);- ClipboardItemObjectDeclaration::new(- data,- raw_data,- types,- presentation_style.as_str().to_owned(),- )- .initialize(scope, object)- .is_ok()+ ClipboardItemOptions { presentation_style }+ .initialize_snapshot(scope, object)+ .is_some()+ && ClipboardItemObjectDeclaration::new(data, raw_data, types)+ .initialize(scope, object)+ .is_ok()}fn build_clipboard_item<'s>(@@ -249,7 +246,6 @@ fn build_clipboard_item<'s>(v8::Object::new(scope),v8::Object::new(scope),v8::Array::new(scope, 0),- presentation_style.as_str().to_owned(),).bind(scope).ok()?;diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options.rsindex 2d3896892..7d8575e5e 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options.rs@@ -8,6 +8,7 @@ mod encode;mod schema;use crate::webidl;+use webidl::{SnapshotPrototype, WebIdlDictionarySerialize};use super::value::Dictionary;use schema::{CreationJson, RequestJson};@@ -34,7 +35,11 @@ pub(super) fn parse_creation<'s>(let Some(parsed) = webidl::parse_args::<CreationArgs>(scope, &args) else {return;};- if let Some(result) = encode::creation(scope, &parsed.options.0) {+ if let Some(result) = parsed+ .options+ .0+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ {rv.set(result.into());}}@@ -47,7 +52,11 @@ pub(super) fn parse_request<'s>(let Some(parsed) = webidl::parse_args::<RequestArgs>(scope, &args) else {return;};- if let Some(result) = encode::request(scope, &parsed.options.0) {+ if let Some(result) = parsed+ .options+ .0+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ {rv.set(result.into());}}diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/encode.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/encode.rsindex 17ab248a1..396137d19 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/encode.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/encode.rs@@ -1,292 +1,16 @@-use moli_webapi_declare::WebApiValue;-+//! Binary member conversion after the entire WebIDL dictionary has parsed.+use super::super::{base64url, value::Text};use crate::{native_bridge::throw_dom_exception, webidl};-use super::super::{- base64url,- value::{Dictionary, Text},-};-use super::schema::{- CreationJson, DescriptorJson, ExtensionsJson, LargeBlobJson, Parameters, PrfJson,- PrfValuesJson, RelyingParty, RequestJson, Selection, UserJson,-};--fn member<'s, T: WebApiValue<'s> + ?Sized>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &str,- value: &T,-) -> Option<()> {- let name = v8::String::new(scope, name)?;- let value = value.to_v8_value(scope)?;- object- .create_data_property(scope, name.into(), value)?- .then_some(())-}--fn optional<'s, T: WebApiValue<'s>>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &str,- value: &Option<T>,-) -> Option<()> {- if let Some(value) = value {- member(scope, object, name, value)?;- }- Some(())-}--fn invalid_base64url<'s>(- scope: &mut v8::PinScope<'s, '_>,-) -> Option<v8::Local<'s, v8::ArrayBuffer>> {- throw_dom_exception(scope, "EncodingError", 0, "Invalid base64url data.");- None-}--fn buffer<'s>(+pub(super) fn decode_buffer<'s>(scope: &mut v8::PinScope<'s, '_>,text: &Text,-) -> Option<v8::Local<'s, v8::ArrayBuffer>> {+ _: webidl::SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {let Some(bytes) = base64url::decode(text) else {- return invalid_base64url(scope);+ throw_dom_exception(scope, "EncodingError", 0, "Invalid base64url data.");+ return None;};- let backing_store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();- Some(v8::ArrayBuffer::with_backing_store(scope, &backing_store))-}--fn optional_buffer<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &str,- value: &Option<Text>,-) -> Option<()> {- if let Some(value) = value {- let decoded = buffer(scope, value)?;- member(scope, object, name, &decoded)?;- }- Some(())-}--fn sequence<'s, T>(- scope: &mut v8::PinScope<'s, '_>,- values: &webidl::Sequence<Dictionary<T>>,- encode: fn(&mut v8::PinScope<'s, '_>, &T) -> Option<v8::Local<'s, v8::Object>>,-) -> Option<v8::Local<'s, v8::Value>> {- let mut result = Vec::with_capacity(values.0.len());- for value in &values.0 {- result.push(encode(scope, &value.0)?);- }- result.to_v8_value(scope)-}--pub(super) fn creation<'s>(- scope: &mut v8::PinScope<'s, '_>,- options: &CreationJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- member(scope, result, "attestation", &options.attestation)?;- member(- scope,- result,- "attestationFormats",- &options.attestation_formats.0,- )?;- if let Some(value) = &options.authenticator_selection {- let value = selection(scope, &value.0)?;- member(scope, result, "authenticatorSelection", &value)?;- }- let challenge = buffer(scope, &options.challenge)?;- member(scope, result, "challenge", &challenge)?;- let excluded = sequence(scope, &options.exclude_credentials, descriptor)?;- member(scope, result, "excludeCredentials", &excluded)?;- if let Some(value) = &options.extensions {- let value = extensions(scope, &value.0)?;- member(scope, result, "extensions", &value)?;- }- member(scope, result, "hints", &options.hints.0)?;- let parameters = sequence(scope, &options.pub_key_cred_params, parameters)?;- member(scope, result, "pubKeyCredParams", ¶meters)?;- let rp = relying_party(scope, &options.rp.0)?;- member(scope, result, "rp", &rp)?;- optional(scope, result, "timeout", &options.timeout)?;- let user = user(scope, &options.user.0)?;- member(scope, result, "user", &user)?;- Some(result)-}--pub(super) fn request<'s>(- scope: &mut v8::PinScope<'s, '_>,- options: &RequestJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- let allowed = sequence(scope, &options.allow_credentials, descriptor)?;- member(scope, result, "allowCredentials", &allowed)?;- let challenge = buffer(scope, &options.challenge)?;- member(scope, result, "challenge", &challenge)?;- if let Some(value) = &options.extensions {- let value = extensions(scope, &value.0)?;- member(scope, result, "extensions", &value)?;- }- member(scope, result, "hints", &options.hints.0)?;- optional(scope, result, "rpId", &options.rp_id)?;- optional(scope, result, "timeout", &options.timeout)?;- member(- scope,- result,- "userVerification",- &options.user_verification,- )?;- Some(result)-}--fn relying_party<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &RelyingParty,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- member(scope, result, "name", &value.base.name)?;- optional(scope, result, "id", &value.id)?;- Some(result)-}--fn user<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &UserJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- // The output is PublicKeyCredentialUserEntity, whose name is inherited.- member(scope, result, "name", &value.name)?;- member(scope, result, "displayName", &value.display_name)?;- let id = buffer(scope, &value.id)?;- member(scope, result, "id", &id)?;- Some(result)-}--fn parameters<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &Parameters,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- member(scope, result, "alg", &value.alg)?;- member(scope, result, "type", &value.credential_type)?;- Some(result)-}--fn descriptor<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &DescriptorJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- let id = buffer(scope, &value.id)?;- member(scope, result, "id", &id)?;- if let Some(transports) = &value.transports {- member(scope, result, "transports", &transports.0)?;- }- member(scope, result, "type", &value.credential_type)?;- Some(result)-}--fn selection<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &Selection,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- optional(- scope,- result,- "authenticatorAttachment",- &value.authenticator_attachment,- )?;- member(- scope,- result,- "requireResidentKey",- &value.require_resident_key,- )?;- optional(scope, result, "residentKey", &value.resident_key)?;- member(scope, result, "userVerification", &value.user_verification)?;- Some(result)-}--fn extensions<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &ExtensionsJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- optional(scope, result, "appid", &value.appid)?;- optional(scope, result, "appidExclude", &value.appid_exclude)?;- optional_buffer(scope, result, "credBlob", &value.cred_blob)?;- optional(scope, result, "credProps", &value.cred_props)?;- optional(- scope,- result,- "credentialProtectionPolicy",- &value.credential_protection_policy,- )?;- member(- scope,- result,- "enforceCredentialProtectionPolicy",- &value.enforce_credential_protection_policy,- )?;- optional(scope, result, "getCredBlob", &value.get_cred_blob)?;- optional(scope, result, "hmacCreateSecret", &value.hmac_create_secret)?;- if let Some(value) = &value.large_blob {- let value = large_blob(scope, &value.0)?;- member(scope, result, "largeBlob", &value)?;- }- optional(scope, result, "minPinLength", &value.min_pin_length)?;- if let Some(value) = &value.prf {- let value = prf(scope, &value.0)?;- member(scope, result, "prf", &value)?;- }- optional(- scope,- result,- "remoteClientDataJSON",- &value.remote_client_data_json,- )?;- Some(result)-}--fn large_blob<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &LargeBlobJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- optional(scope, result, "read", &value.read)?;- optional(scope, result, "support", &value.support)?;- optional_buffer(scope, result, "write", &value.write)?;- Some(result)-}--fn prf<'s>(scope: &mut v8::PinScope<'s, '_>, value: &PrfJson) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- if let Some(value) = &value.eval {- let value = prf_values(scope, &value.0)?;- member(scope, result, "eval", &value)?;- }- if let Some(record) = &value.eval_by_credential {- let entries = v8::Object::new(scope);- for (key, value) in &record.0 {- let key = v8::Local::<v8::Name>::try_from(key.to_v8_value(scope)?).ok()?;- let value = prf_values(scope, &value.0)?;- if entries.create_data_property(scope, key, value.into()) != Some(true) {- return None;- }- }- member(scope, result, "evalByCredential", &entries)?;- }- Some(result)-}--fn prf_values<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: &PrfValuesJson,-) -> Option<v8::Local<'s, v8::Object>> {- let result = v8::Object::new(scope);- let first = buffer(scope, &value.first)?;- member(scope, result, "first", &first)?;- optional_buffer(scope, result, "second", &value.second)?;- Some(result)+ let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();+ Some(v8::ArrayBuffer::with_backing_store(scope, &store).into())}diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/schema.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/schema.rsindex 756b42109..57e5d94d8 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/schema.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/json_options/schema.rs@@ -6,7 +6,7 @@ use super::super::value::{Dictionary, Text};// The derive orders each dictionary's final member names lexicographically;// inherited dictionaries such as RelyingParty declare their base explicitly.#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialCreationOptionsJSON")]+#[webidl(prefix = "PublicKeyCredentialCreationOptionsJSON", snapshot)]pub(super) struct CreationJson {#[webidl(converter = "raw", default = Text::from("none"))]pub(super) attestation: Text,@@ -14,7 +14,7 @@ pub(super) struct CreationJson {pub(super) attestation_formats: webidl::Sequence<Text>,#[webidl(converter = "raw")]pub(super) authenticator_selection: Option<Dictionary<Selection>>,- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) challenge: Text,#[webidl(converter = "raw", default = webidl::Sequence(Vec::new()))]pub(super) exclude_credentials: webidl::Sequence<Dictionary<DescriptorJson>>,@@ -32,11 +32,11 @@ pub(super) struct CreationJson {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialRequestOptionsJSON")]+#[webidl(prefix = "PublicKeyCredentialRequestOptionsJSON", snapshot)]pub(super) struct RequestJson {#[webidl(converter = "raw", default = webidl::Sequence(Vec::new()))]pub(super) allow_credentials: webidl::Sequence<Dictionary<DescriptorJson>>,- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) challenge: Text,#[webidl(converter = "raw")]pub(super) extensions: Option<Dictionary<ExtensionsJson>>,@@ -50,20 +50,20 @@ pub(super) struct RequestJson {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialUserEntityJSON")]+#[webidl(prefix = "PublicKeyCredentialUserEntityJSON", snapshot)]pub(super) struct UserJson {#[webidl(required, converter = "raw")]pub(super) display_name: Text,- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) id: Text,- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_order = 0)]pub(super) name: Text,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialDescriptorJSON")]+#[webidl(prefix = "PublicKeyCredentialDescriptorJSON", snapshot)]pub(super) struct DescriptorJson {- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) id: Text,#[webidl(converter = "raw")]pub(super) transports: Option<webidl::Sequence<Text>>,@@ -72,13 +72,13 @@ pub(super) struct DescriptorJson {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AuthenticationExtensionsClientInputsJSON")]+#[webidl(prefix = "AuthenticationExtensionsClientInputsJSON", snapshot)]pub(super) struct ExtensionsJson {#[webidl(converter = "raw")]pub(super) appid: Option<Text>,#[webidl(converter = "raw")]pub(super) appid_exclude: Option<Text>,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) cred_blob: Option<Text>,pub(super) cred_props: Option<bool>,#[webidl(converter = "usv_string")]@@ -97,17 +97,17 @@ pub(super) struct ExtensionsJson {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AuthenticationExtensionsLargeBlobInputsJSON")]+#[webidl(prefix = "AuthenticationExtensionsLargeBlobInputsJSON", snapshot)]pub(super) struct LargeBlobJson {pub(super) read: Option<bool>,#[webidl(converter = "raw")]pub(super) support: Option<Text>,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) write: Option<Text>,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AuthenticationExtensionsPRFInputsJSON")]+#[webidl(prefix = "AuthenticationExtensionsPRFInputsJSON", snapshot)]pub(super) struct PrfJson {#[webidl(converter = "raw")]pub(super) eval: Option<Dictionary<PrfValuesJson>>,@@ -116,10 +116,10 @@ pub(super) struct PrfJson {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AuthenticationExtensionsPRFValuesJSON")]+#[webidl(prefix = "AuthenticationExtensionsPRFValuesJSON", snapshot)]pub(super) struct PrfValuesJson {- #[webidl(required, converter = "raw")]+ #[webidl(required, converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) first: Text,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_with = super::encode::decode_buffer, snapshot_kind = webidl::SnapshotKind::BufferSource)]pub(super) second: Option<Text>,}diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/schema.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/schema.rsindex 550f69570..875a43ad0 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/schema.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/schema.rs@@ -5,14 +5,14 @@ use crate::webidl;use super::value::Text;#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialEntity")]+#[webidl(prefix = "PublicKeyCredentialEntity", snapshot)]pub(super) struct Entity {#[webidl(required, converter = "raw")]pub(super) name: Text,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialRpEntity")]+#[webidl(prefix = "PublicKeyCredentialRpEntity", snapshot)]pub(super) struct RelyingParty {#[webidl(inherit)]pub(super) base: Entity,@@ -21,7 +21,7 @@ pub(super) struct RelyingParty {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "PublicKeyCredentialParameters")]+#[webidl(prefix = "PublicKeyCredentialParameters", snapshot)]pub(super) struct Parameters {#[webidl(required)]pub(super) alg: i32,@@ -30,7 +30,7 @@ pub(super) struct Parameters {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "AuthenticatorSelectionCriteria")]+#[webidl(prefix = "AuthenticatorSelectionCriteria", snapshot)]pub(super) struct Selection {#[webidl(converter = "raw")]pub(super) authenticator_attachment: Option<Text>,diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/value.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/value.rsindex cd2809014..b7211f8ce 100644--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/value.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials/value.rs@@ -62,3 +62,20 @@ impl<'s, T: webidl::WebIdlDictionary<'s>> webidl::WebIdlConverter<'s> for Dictio}}}++impl webidl::WebIdlSnapshotValue for Text {+ const SNAPSHOT_KIND: webidl::SnapshotKind = webidl::SnapshotKind::Scalar;+}++impl<T: webidl::WebIdlDictionarySnapshot> webidl::WebIdlSnapshotValue for Dictionary<T> {+ const SNAPSHOT_KIND: webidl::SnapshotKind =+ webidl::SnapshotKind::Dictionary(&T::SNAPSHOT_SCHEMA);+}++impl<'s, T: webidl::WebIdlDictionarySerialize<'s>> WebApiValue<'s> for Dictionary<T> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ self.0+ .to_js_snapshot(scope, webidl::SnapshotPrototype::Ordinary)+ .map(Into::into)+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/range.rs b/moli-renderer-v8/src/context_bootstrap/range.rsindex 715b9327d..034285772 100644--- a/moli-renderer-v8/src/context_bootstrap/range.rs+++ b/moli-renderer-v8/src/context_bootstrap/range.rs@@ -15,5 +15,5 @@ pub(super) use object::{range_boundary_container_object, range_boundary_offset, range_is_collapsed,range_native_record_handle, set_range_boundary,};-pub(super) use static_storage::initialize_static_range_object;+pub(super) use static_storage::{StaticRangeInitMembers, initialize_static_range_object};pub(super) use validation::{child_index, range_node_length, range_validate_boundary_point};diff --git a/moli-renderer-v8/src/context_bootstrap/range/static_storage.rs b/moli-renderer-v8/src/context_bootstrap/range/static_storage.rsindex 62cfd52f7..7b99c481e 100644--- a/moli-renderer-v8/src/context_bootstrap/range/static_storage.rs+++ b/moli-renderer-v8/src/context_bootstrap/range/static_storage.rs@@ -2,19 +2,53 @@ use super::*;use crate::native_bridge::RangeBoundarySide;use crate::util::{get_private_value, set_private_value};use crate::web_api_interfaces;+use crate::webidl::{self, WebIdlDictionarySerialize};use moli_webapi_declare::WebApiObject;#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::AbstractRange)]-struct StaticRangeBoundaryStorageDeclaration<'scope> {- #[webapi(slot = STATIC_RANGE_START_CONTAINER_STORAGE_KEY)]- start_container: v8::Local<'scope, v8::Object>,- #[webapi(slot = STATIC_RANGE_START_OFFSET_STORAGE_KEY)]- start_offset: f64,- #[webapi(slot = STATIC_RANGE_END_CONTAINER_STORAGE_KEY)]- end_container: v8::Local<'scope, v8::Object>,- #[webapi(slot = STATIC_RANGE_END_OFFSET_STORAGE_KEY)]- end_offset: f64,+struct StaticRangeBoundaryStorageDeclaration {}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "StaticRangeInit", snapshot)]+pub(in crate::context_bootstrap) struct StaticRangeInitMembers<'s> {+ #[webidl(required, name = "startContainer", with = static_range_node_member)]+ #[webidl(snapshot_slot = STATIC_RANGE_START_CONTAINER_STORAGE_KEY)]+ pub(in crate::context_bootstrap) start_container: v8::Local<'s, v8::Object>,+ #[webidl(required, name = "startOffset")]+ #[webidl(snapshot_slot = STATIC_RANGE_START_OFFSET_STORAGE_KEY)]+ pub(in crate::context_bootstrap) start_offset: u32,+ #[webidl(required, name = "endContainer", with = static_range_node_member)]+ #[webidl(snapshot_slot = STATIC_RANGE_END_CONTAINER_STORAGE_KEY)]+ pub(in crate::context_bootstrap) end_container: v8::Local<'s, v8::Object>,+ #[webidl(required, name = "endOffset")]+ #[webidl(snapshot_slot = STATIC_RANGE_END_OFFSET_STORAGE_KEY)]+ pub(in crate::context_bootstrap) end_offset: u32,+}++fn static_range_node_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<v8::Local<'s, v8::Object>, webidl::WebIdlError> {+ let context = webidl::Context::member("StaticRangeInit", name);+ let Some(value) = webidl::property_result(scope, object, name, context)? else {+ return Err(webidl::WebIdlError::missing_required(context));+ };+ if value.is_undefined() {+ return Err(webidl::WebIdlError::missing_required(context));+ }+ let Ok(node) = v8::Local::<v8::Object>::try_from(value) else {+ return Err(webidl::WebIdlError::custom_message(+ "StaticRangeInit member is not a Node.",+ ));+ };+ if object_number_property(scope, node, "nodeType").is_none() {+ return Err(webidl::WebIdlError::custom_message(+ "StaticRangeInit member is not a Node.",+ ));+ }+ Ok(node)}pub(in crate::context_bootstrap) fn initialize_static_range_object<'s>(@@ -25,14 +59,17 @@ pub(in crate::context_bootstrap) fn initialize_static_range_object<'s>(end_container: v8::Local<'s, v8::Object>,end_offset: u32,) {- StaticRangeBoundaryStorageDeclaration::new(+ StaticRangeInitMembers {start_container,- start_offset as f64,+ start_offset,end_container,- end_offset as f64,- )- .initialize(scope, range)- .expect("StaticRange boundary declaration should initialize object");+ end_offset,+ }+ .initialize_snapshot(scope, range)+ .expect("StaticRange boundaries");+ StaticRangeBoundaryStorageDeclaration::new()+ .initialize(scope, range)+ .expect("StaticRange boundary declaration should initialize object");}pub(in crate::context_bootstrap) fn set_static_range_boundary<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/range_surface.rs b/moli-renderer-v8/src/context_bootstrap/range_surface.rsindex ba970a389..bb5362b80 100644--- a/moli-renderer-v8/src/context_bootstrap/range_surface.rs+++ b/moli-renderer-v8/src/context_bootstrap/range_surface.rs@@ -1,8 +1,9 @@use super::range::{- RANGE_WRAPPER_INTERNAL_FIELD_COUNT, RangeBoundarySide, child_index, current_document_object,- initialize_range_object, initialize_static_range_object, new_range_for_document,- range_boundary_container_object, range_boundary_offset, range_is_collapsed, range_node_length,- range_validate_boundary_point, set_range_boundary, throw_named_dom_exception, webidl_node_arg,+ RANGE_WRAPPER_INTERNAL_FIELD_COUNT, RangeBoundarySide, StaticRangeInitMembers, child_index,+ current_document_object, initialize_range_object, initialize_static_range_object,+ new_range_for_document, range_boundary_container_object, range_boundary_offset,+ range_is_collapsed, range_node_length, range_validate_boundary_point, set_range_boundary,+ throw_named_dom_exception, webidl_node_arg,};use super::range_algorithms::{create_contextual_fragment_internal, native_boundary_point_from_node,diff --git a/moli-renderer-v8/src/context_bootstrap/range_surface/construction.rs b/moli-renderer-v8/src/context_bootstrap/range_surface/construction.rsindex 00682f486..275f0db98 100644--- a/moli-renderer-v8/src/context_bootstrap/range_surface/construction.rs+++ b/moli-renderer-v8/src/context_bootstrap/range_surface/construction.rs@@ -8,19 +8,6 @@ struct StaticRangeConstructorArgs<'s> {init: v8::Local<'s, v8::Object>,}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "StaticRangeInit")]-struct StaticRangeInitMembers<'s> {- #[webidl(required, name = "startContainer", with = static_range_node_member)]- start_container: v8::Local<'s, v8::Object>,- #[webidl(required, name = "startOffset")]- start_offset: u32,- #[webidl(required, name = "endContainer", with = static_range_node_member)]- end_container: v8::Local<'s, v8::Object>,- #[webidl(required, name = "endOffset")]- end_offset: u32,-}-pub(super) fn range_constructor_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -98,31 +85,6 @@ pub(super) fn document_create_range_callback<'s>(rv.set(range.into());}-fn static_range_node_member<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &'static str,-) -> Result<v8::Local<'s, v8::Object>, webidl::WebIdlError> {- let context = webidl::Context::member("StaticRangeInit", name);- let Some(value) = webidl::property_result(scope, object, name, context)? else {- return Err(webidl::WebIdlError::missing_required(context));- };- if value.is_undefined() {- return Err(webidl::WebIdlError::missing_required(context));- }- let Ok(node) = v8::Local::<v8::Object>::try_from(value) else {- return Err(webidl::WebIdlError::custom_message(- "StaticRangeInit member is not a Node.",- ));- };- if object_number_property(scope, node, "nodeType").is_none() {- return Err(webidl::WebIdlError::custom_message(- "StaticRangeInit member is not a Node.",- ));- }- Ok(node)-}-fn static_range_endpoint_type_is_invalid<'s>(scope: &mut v8::PinScope<'s, '_>,node: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rsindex 34ecdbf47..e3af8c43a 100644--- a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs@@ -9,6 +9,7 @@ use crate::webidl;use entry::ResizeObserverEntryData;pub(super) use entry::install_resize_observer_entry_template_bindings;use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::ResizeObserver)]@@ -34,8 +35,6 @@ struct ResizeObserverObjectDeclaration<'s> {struct ResizeObserverObservedRecordDeclaration<'scope> {#[webapi(slot = RESIZE_OBSERVER_RECORD_TARGET_SLOT)]target: v8::Local<'scope, v8::Object>,- #[webapi(slot = RESIZE_OBSERVER_RECORD_BOX_SLOT)]- observed_box: String,}#[derive(webidl::WebIdlArgs)]@@ -74,16 +73,6 @@ enum ResizeObserverBoxOptions {DevicePixelContentBox,}-impl ResizeObserverBoxOptions {- fn as_str(self) -> &'static str {- match self {- Self::ContentBox => "content-box",- Self::BorderBox => "border-box",- Self::DevicePixelContentBox => "device-pixel-content-box",- }- }-}-const RESIZE_OBSERVER_RECORD_TARGET_SLOT: &str = "__moliResizeObserverRecordTarget";const RESIZE_OBSERVER_RECORD_BOX_SLOT: &str = "__moliResizeObserverRecordBox";const RESIZE_OBSERVER_RECORD_LAST_INLINE_SIZE_SLOT: &str =@@ -91,9 +80,10 @@ const RESIZE_OBSERVER_RECORD_LAST_INLINE_SIZE_SLOT: &str =const RESIZE_OBSERVER_RECORD_LAST_BLOCK_SIZE_SLOT: &str = "__moliResizeObserverRecordLastBlockSize";#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "ResizeObserverOptions")]+#[webidl(prefix = "ResizeObserverOptions", snapshot)]struct ResizeObserverOptions {#[webidl(name = "box", converter = "enum", default = ResizeObserverBoxOptions::ContentBox)]+ #[webidl(snapshot_slot = RESIZE_OBSERVER_RECORD_BOX_SLOT)]observed_box: ResizeObserverBoxOptions,}@@ -470,12 +460,12 @@ fn build_observed_record<'s>(target: v8::Local<'s, v8::Object>,observed_box: ResizeObserverBoxOptions,) -> v8::Local<'s, v8::Object> {- let record = ResizeObserverObservedRecordDeclaration {- target,- observed_box: observed_box.as_str().to_owned(),- }- .bind(scope)- .expect("ResizeObserver observed record declaration should bind");+ let record = ResizeObserverObservedRecordDeclaration { target }+ .bind(scope)+ .expect("ResizeObserver observed record declaration should bind");+ ResizeObserverOptions { observed_box }+ .initialize_snapshot(scope, record)+ .expect("ResizeObserver options");reset_resize_observer_last_reported_size(scope, record);record}@@ -485,8 +475,9 @@ fn set_observed_record_box<'s>(record: v8::Local<'s, v8::Object>,observed_box: ResizeObserverBoxOptions,) {- let value = v8str(scope, observed_box.as_str());- set_private_value(scope, record, RESIZE_OBSERVER_RECORD_BOX_SLOT, value.into());+ ResizeObserverOptions { observed_box }+ .initialize_snapshot(scope, record)+ .expect("ResizeObserver options");reset_resize_observer_last_reported_size(scope, record);}diff --git a/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs b/moli-renderer-v8/src/context_bootstrap/streams/constructors.rsindex dfcebd5c9..0005c1474 100644--- a/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs+++ b/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs@@ -5,6 +5,7 @@ use crate::{webidl,};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionarySerialize;const COUNT_QUEUING_STRATEGY_SIZE_FUNCTION_SLOT: &str = "__moliCountQueuingStrategySizeFunction";const BYTE_LENGTH_QUEUING_STRATEGY_SIZE_FUNCTION_SLOT: &str =@@ -25,25 +26,15 @@ struct TextEncoderStreamObjectDeclaration {struct TextDecoderStreamObjectDeclaration {#[webapi(data_property)]encoding: String,- #[webapi(data_property)]- fatal: bool,- #[webapi(data_property = "ignoreBOM")]- ignore_bom: bool,}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::CountQueuingStrategy)]-struct CountQueuingStrategyObjectDeclaration {- #[webapi(slot = COUNT_QUEUING_STRATEGY_HIGH_WATER_MARK_SLOT)]- high_water_mark: f64,-}+struct CountQueuingStrategyObjectDeclaration {}#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::ByteLengthQueuingStrategy)]-struct ByteLengthQueuingStrategyObjectDeclaration {- #[webapi(slot = BYTE_LENGTH_QUEUING_STRATEGY_HIGH_WATER_MARK_SLOT)]- high_water_mark: f64,-}+struct ByteLengthQueuingStrategyObjectDeclaration {}#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::CountQueuingStrategy, enumerable)]@@ -112,29 +103,32 @@ struct TextDecoderStreamConstructorArgs {#[webidl(prefix = "CountQueuingStrategy")]struct CountQueuingStrategyConstructorArgs {#[webidl(required, dictionary)]- init: QueuingStrategyInit,+ init: QueuingStrategyInit<true>,}#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "ByteLengthQueuingStrategy")]struct ByteLengthQueuingStrategyConstructorArgs {#[webidl(required, dictionary)]- init: QueuingStrategyInit,+ init: QueuingStrategyInit<false>,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "QueuingStrategyInit")]-struct QueuingStrategyInit {+#[webidl(prefix = "QueuingStrategyInit", snapshot)]+struct QueuingStrategyInit<const COUNT: bool> {#[webidl(required, converter = "unrestricted_double")]+ #[webidl(snapshot_slot = if COUNT { COUNT_QUEUING_STRATEGY_HIGH_WATER_MARK_SLOT } else { BYTE_LENGTH_QUEUING_STRATEGY_HIGH_WATER_MARK_SLOT })]high_water_mark: f64,}#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "TextDecoderOptions")]+#[webidl(prefix = "TextDecoderOptions", snapshot)]struct TextDecoderStreamOptions {#[webidl(default = false)]+ #[webidl(snapshot_attributes = v8::PropertyAttribute::DONT_ENUM)]fatal: bool,#[webidl(name = "ignoreBOM", default = false)]+ #[webidl(snapshot_attributes = v8::PropertyAttribute::DONT_ENUM)]ignore_bom: bool,}@@ -394,9 +388,13 @@ pub(in crate::context_bootstrap) fn text_decoder_stream_constructor_callback<'s>let writable = stream_slot_object(scope, args.this(), TRANSFORM_STREAM_WRITABLE_SLOT).expect("a new text decoder stream owns its writable endpoint");init_text_decoder_state(scope, writable, encoding, fatal, ignore_bom);- TextDecoderStreamObjectDeclaration::new(encoding_name, fatal, ignore_bom)+ TextDecoderStreamObjectDeclaration::new(encoding_name).initialize(scope, args.this()).expect("TextDecoderStream declaration should initialize object");+ parsed+ .options+ .initialize_snapshot(scope, args.this())+ .expect("TextDecoderStream options");rv.set(args.this().into());}@@ -416,7 +414,11 @@ pub(in crate::context_bootstrap) fn count_queuing_strategy_constructor_callback<else {return;};- CountQueuingStrategyObjectDeclaration::new(parsed.init.high_water_mark)+ parsed+ .init+ .initialize_snapshot(scope, args.this())+ .expect("queuing strategy state");+ CountQueuingStrategyObjectDeclaration::new().initialize(scope, args.this()).expect("CountQueuingStrategy declaration should initialize object");rv.set(args.this().into());@@ -438,7 +440,11 @@ pub(in crate::context_bootstrap) fn byte_length_queuing_strategy_constructor_calelse {return;};- ByteLengthQueuingStrategyObjectDeclaration::new(parsed.init.high_water_mark)+ parsed+ .init+ .initialize_snapshot(scope, args.this())+ .expect("queuing strategy state");+ ByteLengthQueuingStrategyObjectDeclaration::new().initialize(scope, args.this()).expect("ByteLengthQueuingStrategy declaration should initialize object");rv.set(args.this().into());diff --git a/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs b/moli-renderer-v8/src/context_bootstrap/touch_runtime.rsindex b5cb800fe..c0515c193 100644--- a/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/touch_runtime.rs@@ -3,6 +3,7 @@ use crate::util::{callback_data_index_value, get_private_value};use crate::web_api_interfaces;use crate::webidl;use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionarySerialize;const TOUCH_IDENTIFIER_SLOT: &str = "__lmTouchIdentifier";const TOUCH_TARGET_SLOT: &str = "__lmTouchTarget";@@ -27,35 +28,6 @@ const TOUCH_EVENT_META_KEY_SLOT: &str = "__lmTouchEventMetaKey";const TOUCH_EVENT_CTRL_KEY_SLOT: &str = "__lmTouchEventCtrlKey";const TOUCH_EVENT_SHIFT_KEY_SLOT: &str = "__lmTouchEventShiftKey";-#[derive(WebApiObject)]-#[webapi(interface = web_api_interfaces::Touch)]-struct TouchObjectDeclaration<'scope> {- #[webapi(slot = TOUCH_IDENTIFIER_SLOT)]- identifier: f64,- #[webapi(slot = TOUCH_TARGET_SLOT)]- target: v8::Local<'scope, v8::Object>,- #[webapi(slot = TOUCH_SCREEN_X_SLOT)]- screen_x: f64,- #[webapi(slot = TOUCH_SCREEN_Y_SLOT)]- screen_y: f64,- #[webapi(slot = TOUCH_CLIENT_X_SLOT)]- client_x: f64,- #[webapi(slot = TOUCH_CLIENT_Y_SLOT)]- client_y: f64,- #[webapi(slot = TOUCH_PAGE_X_SLOT)]- page_x: f64,- #[webapi(slot = TOUCH_PAGE_Y_SLOT)]- page_y: f64,- #[webapi(slot = TOUCH_RADIUS_X_SLOT)]- radius_x: f64,- #[webapi(slot = TOUCH_RADIUS_Y_SLOT)]- radius_y: f64,- #[webapi(slot = TOUCH_ROTATION_ANGLE_SLOT)]- rotation_angle: f64,- #[webapi(slot = TOUCH_FORCE_SLOT)]- force: f64,-}-#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::Touch)]struct TouchPrototypeDeclaration {@@ -171,31 +143,43 @@ struct TouchListItemArgs {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "TouchInit")]+#[webidl(prefix = "TouchInit", snapshot)]struct TouchInitMembers<'s> {#[webidl(required)]+ #[webidl(snapshot_slot = TOUCH_IDENTIFIER_SLOT)]identifier: i32,#[webidl(required, interface = web_api_interfaces::EventTarget)]+ #[webidl(snapshot_slot = TOUCH_TARGET_SLOT)]target: v8::Local<'s, v8::Object>,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_SCREEN_X_SLOT)]screen_x: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_SCREEN_Y_SLOT)]screen_y: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_CLIENT_X_SLOT)]client_x: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_CLIENT_Y_SLOT)]client_y: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_PAGE_X_SLOT)]page_x: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_PAGE_Y_SLOT)]page_y: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_RADIUS_X_SLOT)]radius_x: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_RADIUS_Y_SLOT)]radius_y: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_ROTATION_ANGLE_SLOT)]rotation_angle: f64,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_slot = TOUCH_FORCE_SLOT)]force: f64,}@@ -338,22 +322,8 @@ pub(in crate::context_bootstrap) fn touch_constructor_callback<'s>(}};- TouchObjectDeclaration::new(- f64::from(init.identifier),- init.target,- init.screen_x,- init.screen_y,- init.client_x,- init.client_y,- init.page_x,- init.page_y,- init.radius_x,- init.radius_y,- init.rotation_angle,- init.force,- )- .bind_into(scope, touch)- .expect("Touch declaration should bind into constructed object");+ init.initialize_snapshot(scope, touch).expect("Touch state");+ web_api_interfaces::initialize(scope, touch, "Touch").expect("Touch brand");rv.set(touch.into());}diff --git a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs b/moli-renderer-v8/src/context_bootstrap/trusted_types.rsindex e1341f01b..da4bfb591 100644--- a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs+++ b/moli-renderer-v8/src/context_bootstrap/trusted_types.rs@@ -10,7 +10,7 @@ mod policy_callbacks;mod realm_state;use policy_callbacks::{- TrustedTypePolicyCallbackOutcome, invoke_policy_callback, parse_policy_callback_carriers,+ TrustedTypePolicyCallbackOutcome, invoke_policy_callback, parse_policy_callbacks,};#[cfg(test)]@@ -65,8 +65,6 @@ struct TrustedTypePrototypeDeclaration {struct TrustedTypePolicyDeclaration<'scope> {#[webapi(data_property)]name: v8::Local<'scope, v8::String>,- #[webapi(slot = TRUSTED_TYPES_CREATE_HTML_SLOT)]- create_html_callback: Option<v8::Local<'scope, v8::Object>>,#[webapi(method = "createHTML",callback = trusted_type_policy_create_callback,@@ -74,8 +72,6 @@ struct TrustedTypePolicyDeclaration<'scope> {length = 1)]create_html: (),- #[webapi(slot = TRUSTED_TYPES_CREATE_SCRIPT_SLOT)]- create_script_callback: Option<v8::Local<'scope, v8::Object>>,#[webapi(method,callback = trusted_type_policy_create_callback,@@ -83,8 +79,6 @@ struct TrustedTypePolicyDeclaration<'scope> {length = 1)]create_script: (),- #[webapi(slot = TRUSTED_TYPES_CREATE_SCRIPT_URL_SLOT)]- create_script_url_callback: Option<v8::Local<'scope, v8::Object>>,#[webapi(method = "createScriptURL",callback = trusted_type_policy_create_callback,@@ -710,7 +704,7 @@ fn trusted_types_create_policy_callback<'s>(return;};let name: String = name.into();- let Some(callbacks) = parse_policy_callback_carriers(scope, args.get(1)) else {+ let Some(callbacks) = parse_policy_callbacks(scope, args.get(1)) else {return;};@@ -723,14 +717,11 @@ fn trusted_types_create_policy_callback<'s>(}let policy_name = v8_string(scope, &name).unwrap_or_else(|| v8::String::empty(scope));- let policy = TrustedTypePolicyDeclaration::new(- policy_name,- callbacks.create_html,- callbacks.create_script,- callbacks.create_script_url,- )- .bind(scope)- .expect("TrustedTypePolicy declaration should bind");+ let policy = TrustedTypePolicyDeclaration::new(policy_name)+ .bind(scope)+ .expect("TrustedTypePolicy declaration should bind");+ webidl::WebIdlDictionarySerialize::initialize_snapshot(&callbacks, scope, policy)+ .expect("TrustedTypePolicy callbacks should initialize");if name == "default" {let global = scope.get_current_context().global(scope);diff --git a/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rsindex 3b787552d..e0539ab5d 100644--- a/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs+++ b/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs@@ -7,7 +7,10 @@//! naming, CSP, Trusted Type construction, sink selection, and default-policy//! result handling to `trusted_types`.-use super::TrustedTypeKind;+use super::{+ TRUSTED_TYPES_CREATE_HTML_SLOT, TRUSTED_TYPES_CREATE_SCRIPT_SLOT,+ TRUSTED_TYPES_CREATE_SCRIPT_URL_SLOT, TrustedTypeKind,+};use crate::dom::native::DomStringValue;use crate::{util::{get_private_value, v8str},@@ -17,40 +20,28 @@ use crate::{};#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "TrustedTypePolicyOptions")]-struct TrustedTypePolicyOptionsMembers {+#[webidl(prefix = "TrustedTypePolicyOptions", snapshot)]+pub(super) struct TrustedTypePolicyOptionsMembers {#[webidl(name = "createHTML", converter = "callback_function")]+ #[webidl(snapshot_slot = TRUSTED_TYPES_CREATE_HTML_SLOT, snapshot_state_with = callback_carrier)]create_html: Option<webidl::WebIdlCallbackFunction>,#[webidl(name = "createScript", converter = "callback_function")]+ #[webidl(snapshot_slot = TRUSTED_TYPES_CREATE_SCRIPT_SLOT, snapshot_state_with = callback_carrier)]create_script: Option<webidl::WebIdlCallbackFunction>,#[webidl(name = "createScriptURL", converter = "callback_function")]+ #[webidl(snapshot_slot = TRUSTED_TYPES_CREATE_SCRIPT_URL_SLOT, snapshot_state_with = callback_carrier)]create_script_url: Option<webidl::WebIdlCallbackFunction>,}-pub(super) struct TrustedTypePolicyCallbackCarriers<'s> {- pub(super) create_html: Option<v8::Local<'s, v8::Object>>,- pub(super) create_script: Option<v8::Local<'s, v8::Object>>,- pub(super) create_script_url: Option<v8::Local<'s, v8::Object>>,-}--impl<'s> TrustedTypePolicyCallbackCarriers<'s> {- fn from_members(- scope: &mut v8::PinScope<'s, '_>,- members: TrustedTypePolicyOptionsMembers,- ) -> Self {- Self {- create_html: callback_carrier(scope, members.create_html),- create_script: callback_carrier(scope, members.create_script),- create_script_url: callback_carrier(scope, members.create_script_url),- }- }-}-fn callback_carrier<'s>(scope: &mut v8::PinScope<'s, '_>,- callback: Option<webidl::WebIdlCallbackFunction>,-) -> Option<v8::Local<'s, v8::Object>> {- callback.map(|callback| V8TracedWebIdlCallbackFunction::new(scope, callback).into_object())+ callback: &webidl::WebIdlCallbackFunction,+) -> Option<v8::Local<'s, v8::Value>> {+ Some(+ V8TracedWebIdlCallbackFunction::from_callback(scope, callback)+ .into_object()+ .into(),+ )}/// Converts the optional `TrustedTypePolicyOptions` dictionary before the@@ -59,10 +50,10 @@ fn callback_carrier<'s>(/// Web IDL treats omitted, `undefined`, and `null` as an empty dictionary./// Member reads and callback conversion retain their ordinary getter order and/// abrupt completion.-pub(super) fn parse_policy_callback_carriers<'s>(+pub(super) fn parse_policy_callbacks<'s>(scope: &mut v8::PinScope<'s, '_>,options: v8::Local<'s, v8::Value>,-) -> Option<TrustedTypePolicyCallbackCarriers<'s>> {+) -> Option<TrustedTypePolicyOptionsMembers> {let members = match webidl::parse_dictionary::<TrustedTypePolicyOptionsMembers>(scope,options,@@ -75,9 +66,7 @@ pub(super) fn parse_policy_callback_carriers<'s>(return None;}};- Some(TrustedTypePolicyCallbackCarriers::from_members(- scope, members,- ))+ Some(members)}pub(super) enum TrustedTypePolicyCallbackOutcome {diff --git a/moli-renderer-v8/src/context_bootstrap/video_codecs.rs b/moli-renderer-v8/src/context_bootstrap/video_codecs.rsindex 4e0877f6a..84130b1b2 100644--- a/moli-renderer-v8/src/context_bootstrap/video_codecs.rs+++ b/moli-renderer-v8/src/context_bootstrap/video_codecs.rs@@ -1,8 +1,6 @@-use crate::{- util::{v8_string, v8_string_from_utf16_units},- web_api_interfaces, webidl,-};-use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject, WebApiValue};+use crate::{web_api_interfaces, webidl};+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::{SnapshotPrototype, WebIdlDictionarySerialize};#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "HardwareAcceleration")]@@ -14,16 +12,6 @@ enum HardwareAcceleration {#[webidl(token = "prefer-software")]PreferSoftware,}-impl HardwareAcceleration {- fn as_str(self) -> &'static str {- match self {- Self::NoPreference => "no-preference",- Self::PreferHardware => "prefer-hardware",- Self::PreferSoftware => "prefer-software",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "AlphaOption")]enum AlphaOption {@@ -32,15 +20,6 @@ enum AlphaOption {#[webidl(token = "keep")]Keep,}-impl AlphaOption {- fn as_str(self) -> &'static str {- match self {- Self::Discard => "discard",- Self::Keep => "keep",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "LatencyMode")]enum LatencyMode {@@ -49,15 +28,6 @@ enum LatencyMode {#[webidl(token = "realtime")]Realtime,}-impl LatencyMode {- fn as_str(self) -> &'static str {- match self {- Self::Quality => "quality",- Self::Realtime => "realtime",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "VideoEncoderBitrateMode")]enum VideoEncoderBitrateMode {@@ -68,16 +38,6 @@ enum VideoEncoderBitrateMode {#[webidl(token = "quantizer")]Quantizer,}-impl VideoEncoderBitrateMode {- fn as_str(self) -> &'static str {- match self {- Self::Variable => "variable",- Self::Constant => "constant",- Self::Quantizer => "quantizer",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "VideoColorPrimaries")]enum VideoColorPrimaries {@@ -92,18 +52,6 @@ enum VideoColorPrimaries {#[webidl(token = "smpte432")]Smpte432,}-impl VideoColorPrimaries {- fn as_str(self) -> &'static str {- match self {- Self::Bt709 => "bt709",- Self::Bt470bg => "bt470bg",- Self::Smpte170m => "smpte170m",- Self::Bt2020 => "bt2020",- Self::Smpte432 => "smpte432",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "VideoTransferCharacteristics")]enum VideoTransferCharacteristics {@@ -120,19 +68,6 @@ enum VideoTransferCharacteristics {#[webidl(token = "hlg")]Hlg,}-impl VideoTransferCharacteristics {- fn as_str(self) -> &'static str {- match self {- Self::Bt709 => "bt709",- Self::Smpte170m => "smpte170m",- Self::Srgb => "iec61966-2-1",- Self::Linear => "linear",- Self::Pq => "pq",- Self::Hlg => "hlg",- }- }-}-#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "VideoMatrixCoefficients")]enum VideoMatrixCoefficients {@@ -147,28 +82,20 @@ enum VideoMatrixCoefficients {#[webidl(token = "bt2020-ncl")]Bt2020Ncl,}-impl VideoMatrixCoefficients {- fn as_str(self) -> &'static str {- match self {- Self::Rgb => "rgb",- Self::Bt709 => "bt709",- Self::Bt470bg => "bt470bg",- Self::Smpte170m => "smpte170m",- Self::Bt2020Ncl => "bt2020-ncl",- }- }-}-#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "VideoColorSpaceInit")]+#[webidl(prefix = "VideoColorSpaceInit", snapshot)]struct VideoColorSpaceInit {#[webidl(nullable)]+ #[webidl(snapshot_order = 3)]full_range: Option<bool>,#[webidl(nullable, converter = "enum")]+ #[webidl(snapshot_order = 2)]matrix: Option<VideoMatrixCoefficients>,#[webidl(nullable, converter = "enum")]+ #[webidl(snapshot_order = 0)]primaries: Option<VideoColorPrimaries>,#[webidl(nullable, converter = "enum")]+ #[webidl(snapshot_order = 1)]transfer: Option<VideoTransferCharacteristics>,}@@ -221,60 +148,84 @@ impl<'s> Description<'s> {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "VideoDecoderConfig")]+#[webidl(prefix = "VideoDecoderConfig", snapshot)]struct VideoDecoderConfig<'s> {#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 1)]coded_height: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 2)]coded_width: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(required, converter = "raw")]+ #[webidl(snapshot_order = 0)]codec: webidl::DomString16,#[webidl(dictionary)]+ #[webidl(snapshot_order = 10)]color_space: Option<VideoColorSpaceInit>,- #[webidl(converter = "raw")]+ #[webidl(converter = "raw", snapshot_with = description_snapshot, snapshot_kind = webidl::SnapshotKind::BufferSource)]+ #[webidl(snapshot_order = 9)]description: Option<Description<'s>>,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 3)]display_aspect_height: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 4)]display_aspect_width: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(default = false)]+ #[webidl(snapshot_order = 8)]flip: bool,#[webidl(converter = "enum", default = HardwareAcceleration::NoPreference)]+ #[webidl(snapshot_order = 5)]hardware_acceleration: HardwareAcceleration,#[webidl(default = false)]+ #[webidl(snapshot_order = 6)]optimize_for_latency: bool,#[webidl(converter = "double", default = 0.0)]+ #[webidl(snapshot_order = 7)]rotation: f64,}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "VideoEncoderConfig")]+#[webidl(prefix = "VideoEncoderConfig", snapshot)]struct VideoEncoderConfig {#[webidl(converter = "enum", default = AlphaOption::Discard)]+ #[webidl(snapshot_order = 10)]alpha: AlphaOption,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 5)]bitrate: Option<webidl::EnforceRangeUnsignedLongLong>,#[webidl(converter = "enum", default = VideoEncoderBitrateMode::Variable)]+ #[webidl(snapshot_order = 11)]bitrate_mode: VideoEncoderBitrateMode,#[webidl(required, converter = "raw")]+ #[webidl(snapshot_order = 0)]codec: webidl::DomString16,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 8)]content_hint: Option<webidl::DomString16>,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 3)]display_height: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 4)]display_width: Option<webidl::EnforceRangeUnsignedLong>,#[webidl(converter = "double")]+ #[webidl(snapshot_order = 6)]framerate: Option<f64>,#[webidl(converter = "enum", default = HardwareAcceleration::NoPreference)]+ #[webidl(snapshot_order = 9)]hardware_acceleration: HardwareAcceleration,#[webidl(required, converter = "raw")]+ #[webidl(snapshot_order = 2)]height: webidl::EnforceRangeUnsignedLong,#[webidl(converter = "enum", default = LatencyMode::Quality)]+ #[webidl(snapshot_order = 12)]latency_mode: LatencyMode,#[webidl(converter = "raw")]+ #[webidl(snapshot_order = 7)]scalability_mode: Option<webidl::DomString16>,#[webidl(required, converter = "raw")]+ #[webidl(snapshot_order = 1)]width: webidl::EnforceRangeUnsignedLong,}@@ -337,28 +288,14 @@ fn valid_dimensions(&& a.is_none_or(|value| value.0 != 0)&& b.is_none_or(|value| value.0 != 0)}-fn property<'s>(+fn description_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &str,- value: impl WebApiValue<'s>,-) {- let key = v8_string(scope, name).expect("video config key");- let value = value.to_v8_value(scope).expect("video config value");- assert_eq!(- object.create_data_property(scope, key.into(), value),- Some(true)- );-}-fn string_property<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- name: &str,- value: &webidl::DomString16,-) {- let value = v8_string_from_utf16_units(scope, &value.0).expect("video config string");- property(scope, object, name, value);+ value: &Description<'s>,+ _: SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {+ webidl::buffer_snapshot(scope, value.0)}+fn resolve_unsupported<'s>(scope: &mut v8::PinScope<'s, '_>,config: v8::Local<'s, v8::Object>,@@ -392,76 +329,9 @@ fn decoder_is_config_supported<'s>(crate::context_bootstrap::throw_type_error(scope, "Invalid VideoDecoderConfig.");return;}- let clone = v8::Object::new(scope);- string_property(scope, clone, "codec", &config.codec);- for (name, value) in [- ("codedHeight", config.coded_height),- ("codedWidth", config.coded_width),- ("displayAspectHeight", config.display_aspect_height),- ("displayAspectWidth", config.display_aspect_width),- ] {- if let Some(value) = value {- property(scope, clone, name, value.0);- }- }- property(- scope,- clone,- "hardwareAcceleration",- config.hardware_acceleration.as_str(),- );- property(- scope,- clone,- "optimizeForLatency",- config.optimize_for_latency,- );- property(scope, clone, "rotation", config.rotation);- property(scope, clone, "flip", config.flip);- if let Some(description) = config.description {- let context = webidl::Context::member("VideoDecoderConfig", "description");- let bytes = match webidl::convert::<webidl::BufferSource>(scope, description.0, context) {- Ok(bytes) => bytes.0,- Err(error) => {- webidl::throw_error(scope, &error);- return;- }- };- let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();- let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);- property(scope, clone, "description", buffer);- }- if let Some(color_space) = config.color_space {- let color = v8::Object::new(scope);- for (name, value) in [- (- "primaries",- color_space.primaries.map(VideoColorPrimaries::as_str),- ),- (- "transfer",- color_space- .transfer- .map(VideoTransferCharacteristics::as_str),- ),- (- "matrix",- color_space.matrix.map(VideoMatrixCoefficients::as_str),- ),- ] {- let value: v8::Local<v8::Value> = match value {- Some(value) => v8_string(scope, value).expect("video color enum").into(),- None => v8::null(scope).into(),- };- property(scope, color, name, value);- }- let full_range: v8::Local<v8::Value> = match color_space.full_range {- Some(value) => v8::Boolean::new(scope, value).into(),- None => v8::null(scope).into(),- };- property(scope, color, "fullRange", full_range);- property(scope, clone, "colorSpace", color);- }+ let Some(clone) = config.to_js_snapshot(scope, SnapshotPrototype::Ordinary) else {+ return;+ };resolve_unsupported(scope, clone, rv);}@@ -483,38 +353,8 @@ fn encoder_is_config_supported<'s>(crate::context_bootstrap::throw_type_error(scope, "Invalid VideoEncoderConfig.");return;}- let clone = v8::Object::new(scope);- string_property(scope, clone, "codec", &config.codec);- property(scope, clone, "width", config.width.0);- property(scope, clone, "height", config.height.0);- for (name, value) in [- ("displayHeight", config.display_height),- ("displayWidth", config.display_width),- ] {- if let Some(value) = value {- property(scope, clone, name, value.0);- }- }- if let Some(value) = config.bitrate {- property(scope, clone, "bitrate", value.0);- }- if let Some(value) = config.framerate {- property(scope, clone, "framerate", value);- }- if let Some(value) = config.scalability_mode {- string_property(scope, clone, "scalabilityMode", &value);- }- if let Some(value) = config.content_hint {- string_property(scope, clone, "contentHint", &value);- }- property(- scope,- clone,- "hardwareAcceleration",- config.hardware_acceleration.as_str(),- );- property(scope, clone, "alpha", config.alpha.as_str());- property(scope, clone, "bitrateMode", config.bitrate_mode.as_str());- property(scope, clone, "latencyMode", config.latency_mode.as_str());+ let Some(clone) = config.to_js_snapshot(scope, SnapshotPrototype::Ordinary) else {+ return;+ };resolve_unsupported(scope, clone, rv);}diff --git a/moli-renderer-v8/src/context_bootstrap/web_mcp/conversion.rs b/moli-renderer-v8/src/context_bootstrap/web_mcp/conversion.rsindex d6d029e5b..7a96a13bb 100644--- a/moli-renderer-v8/src/context_bootstrap/web_mcp/conversion.rs+++ b/moli-renderer-v8/src/context_bootstrap/web_mcp/conversion.rs@@ -1,20 +1,24 @@use super::bindings::{dom_error, js_string};use super::state::{DocumentTools, RegisteredTool};use crate::web_api_interfaces;-use moli_webapi_declare::WebApiObject;+use crate::webidl::WebIdlDictionarySerialize;use crate::{abort_signal_route::ResolvedAbortSignal, webidl};#[derive(Clone, Copy, Default, PartialEq, Eq, webidl::WebIdlDictionary)]-#[webidl(prefix = "ToolAnnotations")]+#[webidl(prefix = "ToolAnnotations", snapshot)]pub(super) struct ToolAnnotations {#[webidl(name = "consequentialHint", default = false)]+ #[webidl(snapshot_order = 1)]pub(super) consequential: bool,#[webidl(default = false)]+ #[webidl(snapshot_order = 3)]pub(super) debugging: bool,#[webidl(name = "readOnlyHint", default = false)]+ #[webidl(snapshot_order = 0)]pub(super) read_only: bool,#[webidl(name = "untrustedContentHint", default = false)]+ #[webidl(snapshot_order = 2)]pub(super) untrusted_content: bool,}@@ -59,21 +63,28 @@ pub(super) struct ExecuteOptions<'s> {}#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "RegisteredTool")]+#[webidl(prefix = "RegisteredTool", snapshot)]pub(super) struct ToolReference<'s> {#[webidl(dictionary)]+ #[webidl(snapshot_order = 6)]pub(super) annotations: Option<ToolAnnotations>,#[webidl(required, converter = "dom_string")]+ #[webidl(snapshot_order = 1)]pub(super) description: String,#[webidl(name = "inputSchema")]+ #[webidl(snapshot_order = 5)]pub(super) input_schema: Option<v8::Local<'s, v8::Object>>,#[webidl(required, converter = "dom_string")]+ #[webidl(snapshot_order = 0)]pub(super) name: String,#[webidl(required, converter = "usv_string")]+ #[webidl(snapshot_order = 3)]pub(super) origin: String,#[webidl(converter = "dom_string")]+ #[webidl(snapshot_order = 2)]pub(super) title: Option<String>,#[webidl(with = window_member)]+ #[webidl(snapshot_order = 4)]pub(super) window: v8::Local<'s, v8::Object>,}@@ -174,27 +185,6 @@ pub(super) fn stringify_object<'s>(Ok(value)}-#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable, scope_lifetime = 's, no_dynamic_constructor)]-struct ToolSnapshot<'s, 'metadata> {- name: &'metadata str,- description: &'metadata str,- title: &'metadata str,- origin: String,- window: v8::Local<'s, v8::Object>,- input_schema: Option<v8::Local<'s, v8::Object>>,- annotations: Option<AnnotationSnapshot>,-}--#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct AnnotationSnapshot {- read_only_hint: bool,- consequential_hint: bool,- untrusted_content_hint: bool,- debugging: bool,-}-pub(super) fn tool_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,document: &DocumentTools,@@ -208,20 +198,14 @@ pub(super) fn tool_snapshot<'s>(} else {None};- ToolSnapshot {- name,- description: &metadata.description,- title: &metadata.title,+ ToolReference {+ name: name.to_owned(),+ description: metadata.description.clone(),+ title: Some(metadata.title.clone()),origin: document.origin.ascii_serialization(),window: v8::Local::new(scope, &document.window),input_schema: schema,- annotations: metadata.annotations.map(|annotations| AnnotationSnapshot {- read_only_hint: annotations.read_only,- consequential_hint: annotations.consequential,- untrusted_content_hint: annotations.untrusted_content,- debugging: annotations.debugging,- }),+ annotations: metadata.annotations,}- .bind(scope)- .ok()+ .to_js_snapshot(scope, webidl::SnapshotPrototype::Ordinary)}diff --git a/moli-renderer-v8/src/context_bootstrap/web_storage.rs b/moli-renderer-v8/src/context_bootstrap/web_storage.rsindex 12ebffd59..bf2f53531 100644--- a/moli-renderer-v8/src/context_bootstrap/web_storage.rs+++ b/moli-renderer-v8/src/context_bootstrap/web_storage.rs@@ -3,6 +3,16 @@ use crate::webidl;pub(crate) struct StorageReference<'scope>(pub(crate) v8::Local<'scope, v8::Object>);+impl webidl::WebIdlSnapshotValue for StorageReference<'_> {+ const SNAPSHOT_KIND: webidl::SnapshotKind = webidl::SnapshotKind::Identity;+}++impl<'s> moli_webapi_declare::WebApiValue<'s> for StorageReference<'s> {+ fn to_v8_value(&self, _: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ Some(self.0.into())+ }+}+impl<'scope> webidl::WebIdlConverter<'scope> for StorageReference<'scope> {type Options = ();diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc.rs b/moli-renderer-v8/src/context_bootstrap/webrtc.rsindex 6761aad90..51b189057 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc.rs@@ -74,7 +74,7 @@ const RTC_DATA_CHANNEL_VALUE_SLOTS: &[&str] = &[#[webapi(interface = web_api_interfaces::RTCPeerConnection)]struct RtcPeerConnectionObjectDeclaration<'scope> {#[webapi(slot = RTC_PEER_CONNECTION_CONFIGURATION_SLOT)]- configuration: v8::Local<'scope, v8::Object>,+ configuration: configuration::ConfigurationSnapshot<'scope>,#[webapi(slot = RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT)]signaling_state: v8::Local<'scope, v8::String>,#[webapi(slot = RTC_PEER_CONNECTION_ICE_GATHERING_STATE_SLOT)]diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs b/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rsindex ea23f1f9d..4b7d8f4db 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/configuration.rs@@ -6,11 +6,11 @@ use super::{RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT,};use crate::{- util::{get_private_value, set_private_value, v8str},+ util::{get_private_value, v8str},web_api_interfaces, webidl,};-use moli_webapi_declare::{WebApiObject, WebApiValue};-use webidl::{SnapshotKind, SnapshotPrototype, WebIdlDictionarySnapshot, WebIdlSnapshotValue};+use moli_webapi_declare::WebApiValue;+use webidl::{SnapshotKind, SnapshotPrototype, WebIdlDictionarySerialize, WebIdlSnapshotValue};#[derive(Clone, Copy, webidl::WebIdlEnum)]#[webidl(name = "RTCBundlePolicy")]@@ -39,37 +39,10 @@ enum RtcpMuxPolicy {Require,}-impl<'s> WebApiValue<'s> for BundlePolicy {- fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {- match self {- Self::Balanced => "balanced",- Self::MaxCompat => "max-compat",- Self::MaxBundle => "max-bundle",- }- .to_v8_value(scope)- }-}--impl<'s> WebApiValue<'s> for IceTransportPolicy {- fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {- match self {- Self::All => "all",- Self::Relay => "relay",- }- .to_v8_value(scope)- }-}--impl<'s> WebApiValue<'s> for RtcpMuxPolicy {- fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {- "require".to_v8_value(scope)- }-}-struct PoolSize(u8);impl WebIdlSnapshotValue for PoolSize {- const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Identity;+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar;}impl<'s> webidl::WebIdlConverter<'s> for PoolSize {@@ -97,7 +70,7 @@ impl<'s> WebApiValue<'s> for PoolSize {struct Text(webidl::DomString16);impl WebIdlSnapshotValue for Text {- const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Identity;+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar;}impl<'s> webidl::WebIdlConverter<'s> for Text {@@ -123,7 +96,7 @@ struct IceUrls(Vec<String>);impl WebIdlSnapshotValue for IceUrls {// The union converter always binds its canonical value as a URL sequence.- const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Sequence(&SnapshotKind::Identity);+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Sequence(&SnapshotKind::Scalar);}impl<'s> webidl::WebIdlConverter<'s> for IceUrls {@@ -155,9 +128,8 @@ impl<'s> WebApiValue<'s> for IceUrls {}}-#[derive(webidl::WebIdlDictionary, WebApiObject)]+#[derive(webidl::WebIdlDictionary)]#[webidl(prefix = "RTCIceServer", snapshot)]-#[webapi(plain, data_properties, enumerable)]struct IceServer {#[webidl(converter = "raw")]credential: Option<Text>,@@ -167,10 +139,9 @@ struct IceServer {username: Option<Text>,}-#[derive(webidl::WebIdlDictionary, WebApiObject)]+#[derive(webidl::WebIdlDictionary)]#[webidl(prefix = "RTCConfiguration", snapshot)]-#[webapi(plain, data_properties, enumerable)]-struct Configuration<'s> {+pub(super) struct Configuration<'s> {#[webidl(converter = "enum", default = BundlePolicy::Balanced)]bundle_policy: BundlePolicy,#[webidl(sequence, interface = web_api_interfaces::RTCCertificate, default = Vec::new())]@@ -192,20 +163,15 @@ struct ConfigurationArgs<'s> {configuration: Configuration<'s>,}+pub(super) type ConfigurationSnapshot<'s> = webidl::DictionarySnapshot<'s, Configuration<'s>>;+pub(super) fn constructor_configuration<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,-) -> Option<v8::Local<'s, v8::Object>> {+) -> Option<ConfigurationSnapshot<'s>> {let parsed = webidl::parse_args::<ConfigurationArgs>(scope, args)?;validate_servers(scope, &parsed.configuration)?;- let object = parsed- .configuration- .bind(scope)- .expect("converted RTCConfiguration");- Some(- Configuration::to_js_snapshot(scope, object, SnapshotPrototype::Null)- .expect("converted RTCConfiguration snapshot"),- )+ parsed.configuration.to_snapshot(scope)}fn target<'s>(@@ -219,9 +185,8 @@ fn target<'s>(fn configuration<'s>(scope: &mut v8::PinScope<'s, '_>,target: v8::Local<'s, v8::Object>,-) -> v8::Local<'s, v8::Object> {- get_private_value(scope, target, RTC_PEER_CONNECTION_CONFIGURATION_SLOT)- .and_then(|value| v8::Local::try_from(value).ok())+) -> ConfigurationSnapshot<'s> {+ ConfigurationSnapshot::from_private_slot(scope, target, RTC_PEER_CONNECTION_CONFIGURATION_SLOT).expect("native RTCConfiguration snapshot")}@@ -232,7 +197,8 @@ pub(super) fn get_configuration<'s>() {let target = target(scope, args.this());let stored = configuration(scope, target);- let snapshot = Configuration::to_js_snapshot(scope, stored, SnapshotPrototype::Ordinary)+ let snapshot = stored+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary).expect("native RTCConfiguration snapshot");rv.set(snapshot.into());}@@ -252,11 +218,16 @@ pub(super) fn set_configuration<'s>(webidl::throw_dom_exception(scope, "InvalidStateError", "The connection is closed.");return;}- let old = configuration(scope, target);- let next = parsed+ let old = configuration(scope, target)+ .to_v8_value(scope)+ .unwrap()+ .try_into()+ .unwrap();+ let snapshot = parsed.configuration- .bind(scope)+ .to_snapshot(scope).expect("converted RTCConfiguration");+ let next = snapshot.to_v8_value(scope).unwrap().try_into().unwrap();let local_description =get_private_value(scope, target, RTC_PEER_CONNECTION_LOCAL_DESCRIPTION_SLOT).expect("native local description");@@ -281,14 +252,9 @@ pub(super) fn set_configuration<'s>(if validate_servers(scope, &parsed.configuration).is_none() {return;}- let snapshot = Configuration::to_js_snapshot(scope, next, SnapshotPrototype::Null)- .expect("converted RTCConfiguration snapshot");- set_private_value(- scope,- target,- RTC_PEER_CONNECTION_CONFIGURATION_SLOT,- snapshot.into(),- );+ snapshot+ .store_private(scope, target, RTC_PEER_CONNECTION_CONFIGURATION_SLOT)+ .expect("RTCConfiguration snapshot slot");}fn validate_servers(scope: &mut v8::PinScope<'_, '_>, config: &Configuration<'_>) -> Option<()> {diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc/ice_error_event.rs b/moli-renderer-v8/src/context_bootstrap/webrtc/ice_error_event.rsindex dde056c21..3fc84943f 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc/ice_error_event.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/ice_error_event.rs@@ -9,8 +9,8 @@ use crate::{},web_api_interfaces, webidl,};-use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};-use webidl::WebIdlDictionary;+use moli_webapi_declare::WebApiFunctionTemplate;+use webidl::{WebIdlDictionary, WebIdlDictionarySerialize};const ADDRESS_SLOT: &str = "__moliRtcIceErrorAddress";const PORT_SLOT: &str = "__moliRtcIceErrorPort";@@ -26,20 +26,25 @@ const PAYLOAD_SLOTS: &[&str] = &[];#[derive(webidl::WebIdlDictionary)]-#[webidl(prefix = "RTCPeerConnectionIceErrorEventInit")]+#[webidl(prefix = "RTCPeerConnectionIceErrorEventInit", snapshot)]struct Init {// EventInit precedes derived members, which are converted lexically.#[webidl(inherit)]base: EventInit,#[webidl(nullable, converter = "raw")]+ #[webidl(snapshot_slot = ADDRESS_SLOT)]address: Option<webidl::DomString16>,#[webidl(required)]+ #[webidl(snapshot_slot = ERROR_CODE_SLOT)]error_code: u16,#[webidl(default = "", converter = "usv_string")]+ #[webidl(snapshot_slot = ERROR_TEXT_SLOT)]error_text: String,#[webidl(nullable)]+ #[webidl(snapshot_slot = PORT_SLOT)]port: Option<u16>,#[webidl(default = "", converter = "usv_string")]+ #[webidl(snapshot_slot = URL_SLOT)]url: String,}@@ -70,23 +75,6 @@ fn parse_init_arg<'s>(Init::parse_dictionary(scope, object)}-#[derive(WebApiObject)]-#[webapi(interface = web_api_interfaces::RTCPeerConnectionIceErrorEvent)]-struct StateDeclaration<'s> {- #[webapi(data_property, enumerable)]- composed: bool,- #[webapi(slot = ADDRESS_SLOT)]- address: v8::Local<'s, v8::Value>,- #[webapi(slot = ERROR_CODE_SLOT)]- error_code: u16,- #[webapi(slot = ERROR_TEXT_SLOT)]- error_text: v8::Local<'s, v8::String>,- #[webapi(slot = PORT_SLOT)]- port: v8::Local<'s, v8::Value>,- #[webapi(slot = URL_SLOT)]- url: v8::Local<'s, v8::String>,-}-#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::RTCPeerConnectionIceErrorEvent, receiver, enumerable)]struct PrototypeDeclaration {@@ -126,28 +114,6 @@ pub(in crate::context_bootstrap) fn rtc_peer_connection_ice_error_event_construcelse {return;};- let address = match parsed.init.address {- Some(address) => {- let Some(address) =- v8::String::new_from_two_byte(scope, &address.0, v8::NewStringType::Normal)- else {- return;- };- address.into()- }- None => v8::null(scope).into(),- };- let port = parsed- .init- .port- .map(|port| v8::Number::new(scope, f64::from(port)).into())- .unwrap_or_else(|| v8::null(scope).into());- let Some(error_text) = v8::String::new(scope, &parsed.init.error_text) else {- return;- };- let Some(url) = v8::String::new(scope, &parsed.init.url) else {- return;- };let state = new_event_state(scope);initialize_event_object_with_type(scope,@@ -156,15 +122,8 @@ pub(in crate::context_bootstrap) fn rtc_peer_connection_ice_error_event_construcparsed.init.base.bubbles,parsed.init.base.cancelable,);- let declaration = StateDeclaration::new(- parsed.init.base.composed,- address,- parsed.init.error_code,- error_text,- port,- url,- );- if declaration.initialize(scope, state).is_err()+ if parsed.init.initialize_snapshot(scope, state).is_none()+ || web_api_interfaces::initialize(scope, state, "RTCPeerConnectionIceErrorEvent").is_err()|| initialize_event_wrapper(scope, args.this(), state).is_none(){return;diff --git a/moli-renderer-v8/src/network_host/xhr/bindings/progress_event.rs b/moli-renderer-v8/src/network_host/xhr/bindings/progress_event.rsindex d5f2ed7cc..3aa411554 100644--- a/moli-renderer-v8/src/network_host/xhr/bindings/progress_event.rs+++ b/moli-renderer-v8/src/network_host/xhr/bindings/progress_event.rs@@ -1,35 +1,27 @@use super::*;use crate::web_api_interfaces;use crate::webidl;-use moli_webapi_declare::WebApiObject;+use webidl::WebIdlDictionarySerialize;const PROGRESS_EVENT_LENGTH_COMPUTABLE_SLOT: &str = "__lmProgressEventLengthComputable";const PROGRESS_EVENT_LOADED_SLOT: &str = "__lmProgressEventLoaded";const PROGRESS_EVENT_TOTAL_SLOT: &str = "__lmProgressEventTotal";-#[derive(WebApiObject)]-#[webapi(interface = web_api_interfaces::ProgressEvent)]-struct ProgressEventStateDeclaration {- #[webapi(slot = PROGRESS_EVENT_LENGTH_COMPUTABLE_SLOT)]- length_computable: bool,- #[webapi(slot = PROGRESS_EVENT_LOADED_SLOT)]- loaded: f64,- #[webapi(slot = PROGRESS_EVENT_TOTAL_SLOT)]- total: f64,-}-#[derive(Default, webidl::WebIdlDictionary)]-#[webidl(prefix = "ProgressEventInit")]+#[webidl(prefix = "ProgressEventInit", snapshot)]struct ProgressEventInitArgs {#[webidl(default = false)]bubbles: bool,#[webidl(default = false)]cancelable: bool,#[webidl(default = false)]+ #[webidl(snapshot_slot = PROGRESS_EVENT_LENGTH_COMPUTABLE_SLOT)]length_computable: bool,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = PROGRESS_EVENT_LOADED_SLOT)]loaded: f64,#[webidl(default = 0.0)]+ #[webidl(snapshot_slot = PROGRESS_EVENT_TOTAL_SLOT)]total: f64,}@@ -69,13 +61,10 @@ pub(crate) fn progress_event_constructor_callback<'s>(parsed.init.bubbles,parsed.init.cancelable,);- ProgressEventStateDeclaration::new(- parsed.init.length_computable,- parsed.init.loaded,- parsed.init.total,- )- .initialize(scope, obj)- .expect("ProgressEvent state declaration should initialize");+ parsed+ .init+ .initialize_snapshot(scope, obj)+ .expect("ProgressEvent state");web_api_interfaces::initialize(scope, obj, "ProgressEvent").expect("ProgressEvent brand");if crate::context_bootstrap::initialize_event_wrapper(scope, wrapper, obj).is_some() {rv.set(wrapper.into());diff --git a/moli-renderer-v8/src/runtime/browser_context_runtime.rs b/moli-renderer-v8/src/runtime/browser_context_runtime.rsindex e352f8ece..533e01632 100644--- a/moli-renderer-v8/src/runtime/browser_context_runtime.rs+++ b/moli-renderer-v8/src/runtime/browser_context_runtime.rs@@ -181,16 +181,6 @@ pub(crate) enum ClipboardPresentationStyle {Attachment,}-impl ClipboardPresentationStyle {- pub(crate) const fn as_str(self) -> &'static str {- match self {- Self::Unspecified => "unspecified",- Self::Inline => "inline",- Self::Attachment => "attachment",- }- }-}-#[derive(Clone, Debug, Default)]pub(crate) struct ClipboardSnapshot {pub(crate) presentation_style: ClipboardPresentationStyle,diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.js b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.jsindex 4f3b2b4d3..0e796eb03 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.js+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.js@@ -13,6 +13,9 @@const support = await promise;assert(support.supported === false && support.config !== config && Object.getPrototypeOf(support.config) === realm.Object.prototype, name + ' honest independent config');assert(support.config.codec === 'vp8' && support.config.hardwareAcceleration === 'no-preference', name + ' converted defaults');+ const outputKeys = encoder ? ['codec','width','height','hardwareAcceleration','alpha','bitrateMode','latencyMode']+ : ['codec','hardwareAcceleration','optimizeForLatency','rotation','flip'];+ assert(JSON.stringify(Object.keys(support.config)) === JSON.stringify(outputKeys), name + ' snapshot property order');assert(!Object.hasOwn(support.config, encoder ? 'displayWidth' : 'codedWidth'), name + ' absent members stay absent');const inherited = Object.create({codec: {toString: () => 'vp8'}});if (encoder) { inherited.width = '640.9'; inherited.height = 480; }@@ -56,6 +59,7 @@const cloned = (await promise).config;assert(cloned.description instanceof realm.ArrayBuffer && Array.from(new Uint8Array(cloned.description)).join() === '1,3', 'description bytes snapshot after conversion without author access');assert(cloned.colorSpace.primaries === 'bt709' && cloned.colorSpace.fullRange === true && cloned.colorSpace.matrix === null && !Object.hasOwn(cloned.colorSpace, 'ignored'), 'nested color-space conversion');+ assert(Object.keys(cloned.colorSpace).join() === 'primaries,transfer,matrix,fullRange', 'nested snapshot property order');const buffer = new ArrayBuffer(1);let detachedError;try { await realm.VideoDecoder.isConfigSupported({codec:'vp8', description:buffer,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.rsindex ac10aec70..fa2ded93a 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@@ -536,6 +536,11 @@ fn text_stream_constructors_preserve_declared_metadata() {fatal: true,ignoreBOM: true,});+ const metadataOrder = Object.getOwnPropertyNames(decoder)+ .filter(name => ["encoding", "fatal", "ignoreBOM"].includes(name));+ if (metadataOrder.join() !== "encoding,fatal,ignoreBOM") {+ throw Error("TextDecoderStream metadata property order");+ }const descriptor = (object, name) => {const desc = Object.getOwnPropertyDescriptor(object, name);return `${desc && desc.value}:${desc && desc.enumerable}`;diff --git a/moli-renderer-v8/src/v8_traced_webidl_callback.rs b/moli-renderer-v8/src/v8_traced_webidl_callback.rsindex 7c73670ca..e6416f189 100644--- a/moli-renderer-v8/src/v8_traced_webidl_callback.rs+++ b/moli-renderer-v8/src/v8_traced_webidl_callback.rs@@ -100,6 +100,13 @@ pub(crate) struct V8TracedWebIdlCallbackFunction<'s> {impl<'s> V8TracedWebIdlCallbackFunction<'s> {pub(crate) fn new(scope: &mut v8::PinScope<'s, '_>, callback: WebIdlCallbackFunction) -> Self {+ Self::from_callback(scope, &callback)+ }++ pub(crate) fn from_callback(+ scope: &mut v8::PinScope<'s, '_>,+ callback: &WebIdlCallbackFunction,+ ) -> Self {let carrier = v8::Object::new(scope);let callback_value = v8::Local::<v8::Object>::try_from(callback.value(scope)).expect("a Web IDL callback function must be a callable object");diff --git a/moli-webapi-declare/src/value.rs b/moli-webapi-declare/src/value.rsindex 59cfc81a1..5a60298c4 100644--- a/moli-webapi-declare/src/value.rs+++ b/moli-webapi-declare/src/value.rs@@ -47,6 +47,16 @@ macro_rules! impl_number_value {impl_number_value!(f64, f32, usize, u64, u32, u16, u8, isize, i64, i32, i16, i8);+/// None inside a value is null; dictionary derives separately omit absent members.+impl<'s, T: WebApiValue<'s>> WebApiValue<'s> for Option<T> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ match self {+ Some(value) => value.to_v8_value(scope),+ None => Some(v8::null(scope).into()),+ }+ }+}+impl<'s> WebApiValue<'s> for bool {fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {Some(v8::Boolean::new(scope, *self).into())diff --git a/moli-webidl-derive/src/attrs.rs b/moli-webidl-derive/src/attrs.rsindex 9a3961a2d..17bb9d946 100644--- a/moli-webidl-derive/src/attrs.rs+++ b/moli-webidl-derive/src/attrs.rs@@ -77,16 +77,64 @@ pub(crate) struct FieldAttrs {pub(crate) nullable: bool,pub(crate) with: Option<Path>,pub(crate) variadic: bool,+ pub(crate) snapshot_with: Option<Path>,+ pub(crate) snapshot_state_with: Option<Path>,+ pub(crate) snapshot_kind: Option<Expr>,+ pub(crate) snapshot_default: Option<Expr>,+ pub(crate) snapshot_slot: Option<Expr>,+ pub(crate) snapshot_attributes: Option<Expr>,+ pub(crate) snapshot_frozen: bool,+ pub(crate) snapshot_order: Option<u32>,}pub(crate) fn parse_field_attrs(field: &Field) -> Result<FieldAttrs, Error> {let mut parsed = FieldAttrs::default();+ let mut snapshot_attributes = std::collections::HashSet::new();for attr in field.attrs.iter().filter(|attr| attr.path().is_ident("webidl")){attr.parse_nested_meta(|meta| {+ if let Some(ident) = meta.path.get_ident()+ && ident.to_string().starts_with("snapshot_")+ && !snapshot_attributes.insert(ident.to_string())+ {+ return Err(meta.error("duplicate snapshot attribute"));+ }+ if meta.path.is_ident("snapshot_with") {+ parsed.snapshot_with = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_state_with") {+ parsed.snapshot_state_with = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_kind") {+ parsed.snapshot_kind = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_default") {+ parsed.snapshot_default = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_slot") {+ parsed.snapshot_slot = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_attributes") {+ parsed.snapshot_attributes = Some(meta.value()?.parse()?);+ return Ok(());+ }+ if meta.path.is_ident("snapshot_frozen") {+ parsed.snapshot_frozen = true;+ return Ok(());+ }+ if meta.path.is_ident("snapshot_order") {+ let order: LitInt = meta.value()?.parse()?;+ parsed.snapshot_order = Some(order.base10_parse()?);+ return Ok(());+ }if meta.path.is_ident("inherit") {if parsed.inherit {return Err(meta.error("duplicate inherit attribute"));@@ -186,6 +234,14 @@ pub(crate) fn parse_field_attrs(field: &Field) -> Result<FieldAttrs, Error> {|| parsed.treat_null_as_empty_string|| parsed.nullable|| parsed.with.is_some()+ || parsed.snapshot_with.is_some()+ || parsed.snapshot_state_with.is_some()+ || parsed.snapshot_kind.is_some()+ || parsed.snapshot_default.is_some()+ || parsed.snapshot_slot.is_some()+ || parsed.snapshot_attributes.is_some()+ || parsed.snapshot_frozen+ || parsed.snapshot_order.is_some()|| parsed.variadic){return Err(Error::new(@@ -250,6 +306,19 @@ pub(crate) fn parse_field_attrs(field: &Field) -> Result<FieldAttrs, Error> {Ok(parsed)}+impl FieldAttrs {+ pub(crate) fn has_snapshot_attributes(&self) -> bool {+ self.snapshot_with.is_some()+ || self.snapshot_state_with.is_some()+ || self.snapshot_kind.is_some()+ || self.snapshot_default.is_some()+ || self.snapshot_slot.is_some()+ || self.snapshot_attributes.is_some()+ || self.snapshot_frozen+ || self.snapshot_order.is_some()+ }+}+#[derive(Default)]pub(crate) struct EnumAttrs {pub(crate) name: Option<LitStr>,diff --git a/moli-webidl-derive/src/expand.rs b/moli-webidl-derive/src/expand.rsindex aeda11c46..da93d575f 100644--- a/moli-webidl-derive/src/expand.rs+++ b/moli-webidl-derive/src/expand.rs@@ -16,6 +16,12 @@ pub(crate) fn expand_webidl_args(input: DeriveInput) -> Result<proc_macro2::Tokelet struct_name = input.ident;let generics = input.generics.clone();let attrs = parse_container_attrs(&input.attrs)?;+ if attrs.snapshot {+ return Err(Error::new(+ struct_name.span(),+ "snapshot requires WebIdlDictionary",+ ));+ }let prefix = attrs.prefix.unwrap_or_else(|| LitStr::new(&struct_name.to_string(), proc_macro2::Span::call_site()));@@ -23,6 +29,15 @@ pub(crate) fn expand_webidl_args(input: DeriveInput) -> Result<proc_macro2::Tokeimpl_parts_for_scope(&generics, attrs.scope_lifetime.as_ref(), struct_name.span())?;let fields = named_fields(&input.data)?;+ for field in &fields {+ if parse_field_attrs(field)?.has_snapshot_attributes() {+ return Err(Error::new(+ field.span(),+ "snapshot attributes require #[webidl(snapshot)] on a WebIdlDictionary",+ ));+ }+ }+// Arity is checked before any conversion, including custom parsers. A// missing later argument must not invoke an earlier argument's toString.let required_checks = fields@@ -88,6 +103,17 @@ pub(crate) fn expand_webidl_dictionary(let rename_all = attrs.rename_all.unwrap_or(RenameRule::CamelCase);let fields = named_fields(&input.data)?;+ if !attrs.snapshot {+ for field in &fields {+ if parse_field_attrs(field)?.has_snapshot_attributes() {+ return Err(Error::new(+ field.span(),+ "snapshot attributes require #[webidl(snapshot)]",+ ));+ }+ }+ }+// Dictionary inheritance is converted before this dictionary's members,// which WebIDL orders by their final JavaScript names, not Rust layout.let mut inherited = None;@@ -124,7 +150,13 @@ pub(crate) fn expand_webidl_dictionary(.chain(members.into_values()).collect::<Vec<_>>();let snapshot = if attrs.snapshot {- crate::snapshot::expand_snapshot(&struct_name, &generics, &ordered_fields, rename_all)?+ crate::snapshot::expand_snapshot(+ &struct_name,+ &generics,+ &ordered_fields,+ rename_all,+ &scope_lifetime,+ )?} else {quote! {}};@@ -162,6 +194,7 @@ pub(crate) fn expand_webidl_enum(input: DeriveInput) -> Result<proc_macro2::Toke.name.unwrap_or_else(|| LitStr::new(&type_name.to_string(), proc_macro2::Span::call_site()));let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();+ let mut snapshot_tokens = Vec::new();let parse_body = if let Some(parse_with) = attrs.parse_with {quote!(#parse_with(value))} else {@@ -190,6 +223,8 @@ pub(crate) fn expand_webidl_enum(input: DeriveInput) -> Result<proc_macro2::Toketokens.push(LitStr::new(&token, variant.ident.span()));}let ident = &variant.ident;+ let canonical = &tokens[0];+ snapshot_tokens.push(quote!(Self::#ident => #canonical,));for token in tokens {let value = token.value();if let Some(previous) = seen.insert(value.clone(), token.span()) {@@ -210,7 +245,13 @@ pub(crate) fn expand_webidl_enum(input: DeriveInput) -> Result<proc_macro2::Toke}}};+ let snapshot_impl = (!snapshot_tokens.is_empty()).then(|| quote! {+ impl #impl_generics ::moli_webidl::WebIdlEnumSnapshot for #type_name #ty_generics #where_clause {+ fn snapshot_token(&self) -> &'static str { match self { #(#snapshot_tokens)* } }+ }+ });Ok(quote! {+ #snapshot_implimpl #impl_generics ::moli_webidl::WebIdlEnum for #type_name #ty_generics #where_clause {const NAME: &'static str = #enum_name;@@ -679,22 +720,27 @@ mod tests {use syn::parse_quote;#[test]- fn snapshots_reject_unsupported_ownership_and_member_policies() {+ fn snapshot_policies_reject_incompatible_fields() {for input in [- parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(inherit)] base: Base } },- parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(nullable)] value: Option<String> } },- parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(with = parse)] value: Custom } },- parse_quote! { #[webidl(snapshot)] struct Options { value: BufferSource } },- parse_quote! { #[webidl(snapshot)] struct Options { value: WebIdlCallbackFunction } },- parse_quote! { #[webidl(snapshot)] struct Options { value: WebIdlCallbackInterface } },+ parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(default = false, snapshot_frozen)] value: bool } },+ parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(default = 0, snapshot_default = v8::null(scope).into())] value: u32 } },+ parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(inherit, snapshot_with = custom)] base: Base } },+ parse_quote! { struct Options { #[webidl(snapshot_slot = "slot")] value: Option<String> } },+ parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(snapshot_slot = "slot", snapshot_attributes = v8::PropertyAttribute::NONE)] value: Option<String> } },+ parse_quote! { #[webidl(snapshot)] struct Options { #[webidl(snapshot_order = 0, snapshot_order = 1)] value: Option<String> } },] {- assert!(- expand_webidl_dictionary(input)- .unwrap_err()- .to_string()- .starts_with("dictionary snapshots")- );+ assert!(expand_webidl_dictionary(input).is_err());}+ assert!(+ expand_webidl_args(parse_quote! { #[webidl(snapshot)] struct Args { value: String } })+ .is_err()+ );+ assert!(+ expand_webidl_args(+ parse_quote! { struct Args { #[webidl(snapshot_with = custom)] value: String } }+ )+ .is_err()+ );}#[test]diff --git a/moli-webidl-derive/src/lib.rs b/moli-webidl-derive/src/lib.rsindex ee6e74ccb..5cac0d755 100644--- a/moli-webidl-derive/src/lib.rs+++ b/moli-webidl-derive/src/lib.rs@@ -49,10 +49,27 @@ pub fn derive_webidl_args(input: TokenStream) -> TokenStream {/// Nested members support `dictionary`: null parses an empty dictionary while/// `Option<T>` skips missing/undefined and `nullable` also skips null./// Iterable members support `sequence` with `Vec<T>` or `Option<Vec<T>>`.-/// `#[webidl(snapshot)]` additionally derives `WebIdlDictionarySnapshot` for-/// copying already-converted, native-owned dictionary objects. Raw converters-/// must supply a `WebIdlSnapshotValue` policy. This opt-in pilot does not support-/// inheritance, nullable members, custom member parsers, buffers, or callbacks.+/// `#[webidl(snapshot)]` also derives `WebIdlDictionarySnapshot` and+/// `WebIdlDictionarySerialize`. `to_js_snapshot` serializes converted Rust+/// fields; `to_snapshot` creates a typed, V8-traced private carrier for later+/// copies. Input getters and iterators are never consulted again.+/// Inheritance, nullable/optional values, sequences, records, buffers and+/// callback identity/context anchors are supported. Raw/custom converters use+/// `WebIdlSnapshotValue` to describe their canonical JS shape.+///+/// Field policies: `snapshot_with = path` overrides output conversion;+/// `snapshot_kind = expression` describes its copy policy; `snapshot_frozen`+/// freezes a sequence; `snapshot_default = expression` handles an absent Option;+/// `snapshot_order = integer` sets output order independently of input order.+/// `initialize_snapshot` writes existing backing state: `snapshot_slot = key`+/// maps a member to a private slot, and `snapshot_attributes = expression`+/// preserves state data-property attributes. Public dictionary output always+/// uses writable, enumerable, configurable WebIDL member properties.+/// `snapshot_state_with = path` overrides only native-state conversion, e.g.+/// storing an invocation carrier while snapshots expose the original callback.+/// Interface allocation, callback invocation and API validation remain with+/// their native owners; hooks implement special policies such as base64url+/// decoding or producing a branded platform object from a nested dictionary.#[proc_macro_derive(WebIdlDictionary, attributes(webidl))]pub fn derive_webidl_dictionary(input: TokenStream) -> TokenStream {match expand::expand_webidl_dictionary(parse_macro_input!(input as DeriveInput)) {diff --git a/moli-webidl-derive/src/snapshot.rs b/moli-webidl-derive/src/snapshot.rsindex c8f81fe40..d5446ac76 100644--- a/moli-webidl-derive/src/snapshot.rs+++ b/moli-webidl-derive/src/snapshot.rs@@ -1,87 +1,233 @@-use quote::quote;-use syn::spanned::Spanned;-use syn::{Error, Field, Generics, Ident};--use crate::attrs::{RenameRule, field_member_name, parse_field_attrs};+use crate::attrs::{RenameRule, field_ident, field_member_name, parse_field_attrs};use crate::converter::{ConverterKind, converter_kind, inner_type_for_field, is_option_type, vec_inner_type,};+use quote::quote;+use syn::spanned::Spanned;+use syn::{Error, Field, GenericParam, Generics, Ident, Lifetime};pub(crate) fn expand_snapshot(name: &Ident,generics: &Generics,fields: &[&Field],rename_all: RenameRule,+ lifetime: &Lifetime,) -> Result<proc_macro2::TokenStream, Error> {- let mut members = Vec::with_capacity(fields.len());- for field in fields {+ let mut members = Vec::new();+ let mut writes = Vec::new();+ let mut inherited_write = None;+ let mut inherited = quote!(::std::option::Option::None);+ let mut fields = fields+ .iter()+ .map(|field| {+ let attrs = parse_field_attrs(field)?;+ Ok((+ !attrs.inherit,+ attrs.snapshot_order.unwrap_or(u32::MAX),+ *field,+ ))+ })+ .collect::<Result<Vec<_>, Error>>()?;+ fields.sort_by_key(|(own, order, _)| (*own, *order));+ for (_, _, field) in fields {let attrs = parse_field_attrs(field)?;- if attrs.inherit || attrs.nullable || attrs.with.is_some() {+ let ident = field_ident(field)?;+ if attrs.inherit {+ let ty = &field.ty;+ inherited = quote!(::std::option::Option::Some(&<#ty as ::moli_webidl::WebIdlDictionarySnapshot>::SNAPSHOT_SCHEMA));+ inherited_write = Some(+ quote!(::moli_webidl::WebIdlDictionarySerialize::write_snapshot_fields(&self.#ident, scope, writer)?;),+ );+ continue;+ }+ if attrs.snapshot_frozen && !attrs.sequence {+ return Err(Error::new(+ field.span(),+ "snapshot_frozen requires a sequence field",+ ));+ }+ if attrs.snapshot_default.is_some() && !is_option_type(&field.ty) {return Err(Error::new(field.span(),- "dictionary snapshots do not yet support inherit, nullable, or with",+ "snapshot_default requires an Option field",));}- let converter = converter_kind(field, &attrs)?;- let mut ty = inner_type_for_field(field);- if attrs.sequence {- ty = vec_inner_type(ty).expect("validated sequence field");+ if attrs.snapshot_slot.is_some() && attrs.snapshot_attributes.is_some() {+ return Err(Error::new(+ field.span(),+ "private snapshot slots cannot have property attributes",+ ));}- let kind = match converter.kind {- ConverterKind::Dictionary => quote! {- ::moli_webidl::SnapshotKind::Dictionary(<#ty as ::moli_webidl::WebIdlDictionarySnapshot>::SNAPSHOT_MEMBERS)- },- ConverterKind::Raw => quote! {- <#ty as ::moli_webidl::WebIdlSnapshotValue>::SNAPSHOT_KIND- },- ConverterKind::BufferSource- | ConverterKind::CallbackFunction- | ConverterKind::CallbackInterface => {- return Err(Error::new(- field.span(),- "dictionary snapshots require an explicit raw policy for buffers and callbacks",- ));+ let converter = if attrs.with.is_some() {+ ConverterKind::Raw+ } else {+ converter_kind(field, &attrs)?.kind+ };+ let field_ty = inner_type_for_field(field);+ let ty = if attrs.sequence {+ vec_inner_type(field_ty).expect("validated sequence")+ } else {+ field_ty+ };+ let item_kind = if let Some(kind) = &attrs.snapshot_kind {+ quote!(#kind)+ } else {+ match converter {+ ConverterKind::Dictionary => {+ quote!(::moli_webidl::SnapshotKind::Dictionary(&<#ty as ::moli_webidl::WebIdlDictionarySnapshot>::SNAPSHOT_SCHEMA))+ }+ ConverterKind::Raw => {+ quote!(<#ty as ::moli_webidl::WebIdlSnapshotValue>::SNAPSHOT_KIND)+ }+ ConverterKind::Interface+ | ConverterKind::CallbackFunction+ | ConverterKind::CallbackInterface => quote!(::moli_webidl::SnapshotKind::Identity),+ ConverterKind::BufferSource => quote!(::moli_webidl::SnapshotKind::BufferSource),+ _ => quote!(::moli_webidl::SnapshotKind::Scalar),}- ConverterKind::DomString- | ConverterKind::DomString16- | ConverterKind::UsvString- | ConverterKind::ByteString- | ConverterKind::Octet- | ConverterKind::Long- | ConverterKind::LongLong- | ConverterKind::EnforceRangeLong- | ConverterKind::Short- | ConverterKind::UnsignedShort- | ConverterKind::EnforceRangeUnsignedShort- | ConverterKind::ClampedUnsignedShort- | ConverterKind::UnsignedLong- | ConverterKind::EnforceRangeUnsignedLong- | ConverterKind::EnforceRangeLongLong- | ConverterKind::UnsignedLongLong- | ConverterKind::EnforceRangeUnsignedLongLong- | ConverterKind::Float- | ConverterKind::UnrestrictedFloat- | ConverterKind::Double- | ConverterKind::UnrestrictedDouble- | ConverterKind::Boolean- | ConverterKind::Enum- | ConverterKind::Interface => quote!(::moli_webidl::SnapshotKind::Identity),};let kind = if attrs.sequence {- quote!(::moli_webidl::SnapshotKind::Sequence(&#kind))+ if attrs.snapshot_frozen {+ quote!(::moli_webidl::SnapshotKind::FrozenSequence(&#item_kind))+ } else {+ quote!(::moli_webidl::SnapshotKind::Sequence(&#item_kind))+ }+ } else {+ item_kind+ };+ let kind = if attrs.nullable {+ quote!(::moli_webidl::SnapshotKind::Nullable(&#kind))} else {kind};let member_name = field_member_name(field, &attrs, rename_all)?;- let optional = is_option_type(&field.ty);- members.push(quote! {- ::moli_webidl::SnapshotMember { name: #member_name, kind: #kind, optional: #optional }+ let optional =+ is_option_type(&field.ty) && !attrs.nullable && attrs.snapshot_default.is_none();+ members.push(quote!(::moli_webidl::SnapshotMember { name: #member_name, kind: #kind, optional: #optional }));+ let item_value = if let Some(with) = &attrs.snapshot_with {+ quote!(#with(scope, value, writer.prototype))+ } else {+ match converter {+ ConverterKind::Dictionary => quote!(+ ::moli_webidl::WebIdlDictionarySerialize::to_js_snapshot(+ value,+ scope,+ writer.prototype+ )+ .map(::std::convert::Into::into)+ ),+ ConverterKind::Enum => {+ quote!(::moli_webidl::__private::enum_snapshot_value(scope, value))+ }+ ConverterKind::DomString16 => quote!(+ v8::String::new_from_two_byte(scope, value, v8::NewStringType::Normal)+ .map(::std::convert::Into::into)+ ),+ ConverterKind::ByteString if vec_inner_type(ty).is_some() => quote!(+ v8::String::new_from_one_byte(scope, value, v8::NewStringType::Normal)+ .map(::std::convert::Into::into)+ ),+ ConverterKind::BufferSource => quote!(::std::option::Option::Some(+ ::moli_webidl::__private::bytes_snapshot(+ scope,+ ::std::convert::AsRef::<[u8]>::as_ref(value)+ )+ )),+ ConverterKind::CallbackFunction | ConverterKind::CallbackInterface => quote!({+ let relevant = value+ .relevant_context(scope)+ .get_extras_binding_object(scope);+ let incumbent = value+ .incumbent_context(scope)+ .get_extras_binding_object(scope);+ writer.anchor_contexts(scope, &[relevant, incumbent])?;+ ::std::option::Option::Some(value.value(scope))+ }),+ _ => quote!(::moli_webidl::__private::WebApiValue::to_v8_value(+ value, scope+ )),+ }+ };+ let item_value = if let Some(with) = &attrs.snapshot_state_with {+ quote!(if writer.is_state() { #with(scope, value) } else { #item_value })+ } else {+ item_value+ };+ let value = if attrs.sequence {+ quote!({+ let mut items = ::std::vec::Vec::with_capacity(value.len());+ for value in value.iter() { items.push(#item_value?); }+ ::std::option::Option::Some(v8::Array::new_with_elements(scope, &items).into())+ })+ } else {+ item_value+ };+ let slot = match &attrs.snapshot_slot {+ Some(slot) => quote!(::std::option::Option::Some(#slot)),+ None => quote!(::std::option::Option::None),+ };+ let attributes = attrs+ .snapshot_attributes+ .as_ref()+ .map(|attributes| quote!(#attributes))+ .unwrap_or_else(|| quote!(v8::PropertyAttribute::NONE));+ let raw_copy = (converter == ConverterKind::Raw && attrs.snapshot_with.is_none()).then(|| {+ if attrs.snapshot_state_with.is_some() {+ quote!(let value = if writer.is_state() { value } else { (#kind).copy(scope, value, writer.prototype)? };)+ } else {+ quote!(let value = (#kind).copy(scope, value, writer.prototype)?;)+ }});+ let freeze = attrs.snapshot_frozen.then(|| {+ quote! {+ let array = v8::Local::<v8::Array>::try_from(value).ok()?;+ array.set_integrity_level(scope, v8::IntegrityLevel::Frozen)?.then_some(())?;+ }+ });+ let write = quote! {+ let value: v8::Local<#lifetime, v8::Value> = #value?;+ #raw_copy+ #freeze+ writer.set(scope, #member_name, #slot, value, #attributes)?;+ };+ let write = if is_option_type(&field.ty) {+ let default = attrs+ .snapshot_default+ .as_ref()+ .map(|value| quote!(#value))+ .or_else(|| attrs.nullable.then(|| quote!(v8::null(scope).into())));+ let absent = default.map(|value| quote!(else { let value: v8::Local<#lifetime, v8::Value> = #value; writer.set(scope, #member_name, #slot, value, #attributes)?; }));+ quote!(if let ::std::option::Option::Some(value) = &self.#ident { #write } #absent)+ } else {+ quote!({ let value = &self.#ident; #write })+ };+ writes.push(write);}let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();+ let mut serialize_generics = generics.clone();+ if !serialize_generics+ .params+ .iter()+ .any(|param| matches!(param, GenericParam::Lifetime(param) if param.lifetime == *lifetime))+ {+ serialize_generics+ .params+ .insert(0, syn::parse_quote!(#lifetime));+ }+ let (serialize_impl, _, serialize_where) = serialize_generics.split_for_impl();Ok(quote! {impl #impl_generics ::moli_webidl::WebIdlDictionarySnapshot for #name #ty_generics #where_clause {- const SNAPSHOT_MEMBERS: &'static [::moli_webidl::SnapshotMember] = &[#(#members),*];+ const SNAPSHOT_SCHEMA: ::moli_webidl::SnapshotSchema = ::moli_webidl::SnapshotSchema { inherited: #inherited, members: &[#(#members),*] };+ }+ impl #serialize_impl ::moli_webidl::WebIdlDictionarySerialize<#lifetime> for #name #ty_generics #serialize_where {+ fn write_snapshot_own_fields(&self, scope: &mut v8::PinScope<#lifetime, '_>, writer: &::moli_webidl::SnapshotWriter<#lifetime>) -> ::std::option::Option<()> {+ #(#writes)*+ ::std::option::Option::Some(())+ }+ fn write_snapshot_fields(&self, scope: &mut v8::PinScope<#lifetime, '_>, writer: &::moli_webidl::SnapshotWriter<#lifetime>) -> ::std::option::Option<()> {+ #inherited_write+ ::moli_webidl::WebIdlDictionarySerialize::write_snapshot_own_fields(self, scope, writer)+ }}})}diff --git a/moli-webidl/Cargo.toml b/moli-webidl/Cargo.tomlindex cc4e47d1c..c5124c596 100644--- a/moli-webidl/Cargo.toml+++ b/moli-webidl/Cargo.toml@@ -6,13 +6,13 @@ edition = "2024"[dependencies]moli-v8-util = { path = "../moli-v8-util" }+moli-webapi-declare = { path = "../moli-webapi-declare" }moli-webidl-callback = { path = "../moli-webidl-callback" }moli-webidl-derive = { path = "../moli-webidl-derive" }v8 = "152.2.0"[dev-dependencies]moli-v8-test-util = { path = "../moli-v8-test-util" }-moli-webapi-declare = { path = "../moli-webapi-declare" }[lints]workspace = truediff --git a/moli-webidl/src/lib.rs b/moli-webidl/src/lib.rsindex dcfd8191f..01ed24805 100644--- a/moli-webidl/src/lib.rs+++ b/moli-webidl/src/lib.rs@@ -28,9 +28,11 @@//! native binding's `FunctionCallbackArguments`. `#[derive(WebIdlDictionary)]`//! generates named property parsing for dictionary objects. Both derives use//! the converter wrappers in `types` and produce Rust values. The opt-in-//! `#[webidl(snapshot)]` also generates copy metadata for already-bound native-//! dictionary snapshots; object shape declaration and Web API wrapper allocation-//! remain outside this crate.+//! `#[webidl(snapshot)]` also serializes converted Rust fields to fresh JS+//! dictionaries or existing backing state, and creates typed private carriers+//! for subsequent snapshots. These paths copy containers without repeating+//! input conversion or running author getters/iterators. Web API wrapper+//! allocation and native interface identity remain outside this crate.//! Dictionary members are converted in lexicographical order of their final//! JavaScript names. `#[webidl(inherit)]` on one dictionary field converts the//! ancestor's members from the same object first; it does not read a nested@@ -95,8 +97,28 @@ pub use moli_webidl_callback::{};pub use moli_webidl_derive::{WebIdlArgs, WebIdlDictionary, WebIdlEnum};pub use snapshot::{- SnapshotKind, SnapshotMember, SnapshotPrototype, WebIdlDictionarySnapshot, WebIdlSnapshotValue,+ DictionarySnapshot, SnapshotKind, SnapshotMember, SnapshotPrototype, SnapshotSchema,+ SnapshotWriter, WebIdlDictionarySerialize, WebIdlDictionarySnapshot, WebIdlSnapshotValue,+ buffer_snapshot,};++/// Canonical output token for enums whose variants have declarative WebIDL tokens.+pub trait WebIdlEnumSnapshot {+ fn snapshot_token(&self) -> &'static str;+}++#[doc(hidden)]+pub mod __private {+ pub use crate::snapshot::bytes_snapshot;+ pub use moli_webapi_declare::WebApiValue;++ pub fn enum_snapshot_value<'s, T: crate::WebIdlEnumSnapshot>(+ scope: &mut v8::PinScope<'s, '_>,+ value: &T,+ ) -> Option<v8::Local<'s, v8::Value>> {+ crate::v8_string(scope, value.snapshot_token()).map(Into::into)+ }+}pub use traits::{ParseOutcome, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum};pub use types::{Boolean, BufferSource, ByteString, ClampedUnsignedShort, Dictionary, DomString, DomString16,diff --git a/moli-webidl/src/snapshot.rs b/moli-webidl/src/snapshot.rsindex 621ecff22..713e6be34 100644--- a/moli-webidl/src/snapshot.rs+++ b/moli-webidl/src/snapshot.rs@@ -1,91 +1,326 @@-//! Snapshot copies of already-converted, native-owned dictionaries.+//! Typed dictionary snapshots. Only parsed Rust fields and native private slots+//! can create the carrier accepted by the copy path. Author JS objects cannot+//! accidentally be reparsed or invoke their getters during snapshotting.//!-//! This pilot deliberately keeps ownership in V8 private slots. Dictionary and-//! sequence containers are copied, while interface leaves keep their identity-//! and remain traced by V8. It does not turn scoped handles into Rust-owned-//! state: doing that needs an explicit rooting/teardown policy and cannot be-//! inferred from a raw converter or an interface's WebIDL name.+//! Parsing already produces Rust scalar/container values. JS/interface leaves+//! remain scoped V8 handles; snapshots move long-lived ownership into the+//! receiver's V8 graph. A generic `into_native` that stores independent Global+//! roots would retain otherwise collectible owner/interface cycles, including+//! across retained Realms. CommonRuntimeState remains appropriate for native+//! handles and API algorithm state, with its existing owner-lifetime protocol.//!-//! RTCConfiguration therefore stays attached to its receiver, including when a-//! method from another Realm is borrowed. A CommonRuntimeState map is useful-//! for native payloads such as codecs, but a map holding Global<Object> leaves-//! would root certificate -> connection cycles. Moving these dictionaries there-//! would also require receiver-owner lookup, weak/finalizer cleanup, and isolate-//! teardown ordering. Native certificate handles need a real native payload and-//! wrapper identity policy first; this pilot adds neither a store nor globals.+//! Renderer migrations use the dictionary schema for RTC configuration,+//! WebCodecs support results, WebAuthn JSON decoding, WebMCP tool snapshots,+//! inherited event payloads, Touch, DOMPoint/DOMRect, ImageData settings,+//! StaticRange, errors, text decoders, queuing strategies, observer options,+//! ClipboardItem options and Trusted Types policy callbacks. Native producers+//! reuse those typed dictionaries instead of a second JS field declaration.//!-//! `to_js_snapshot` copies canonical binding output, not arbitrary JS input or-//! Rust values. Binding remains the declaration layer's job. An `into_native`-//! derive is deferred until field ownership policies (including custom raw-//! converters) can be expressed without guessing or generating a parallel Rust-//! type/lifetime graph. Only RTCConfiguration and its nested ICE server opt in.+//! Input-only dictionaries retain their parser without opting into output:+//! fetch/body/header normalization, Blob/File byte and MIME processing,+//! permissions/storage/OPFS/service-worker commands, credential validation,+//! media/geolocation/worklet options, CSS/font parsing, transform math, observer+//! scheduling and compact modifier bitsets. Streams' source/sink/transformer+//! dictionaries feed native algorithms and their existing invocation carriers;+//! they are not persisted or returned as dictionary snapshots. Structured-clone+//! algorithms (e.g. Performance detail) keep their API-specific clone policy.-use moli_v8_util::{new_null_prototype_object, v8str};+mod value;++use moli_v8_util::{get_private_value, new_null_prototype_object, private_key, v8_string, v8str};+use moli_webapi_declare::WebApiValue;+use std::marker::PhantomData;-/// Prototype policy for every dictionary in a snapshot, including nested ones.#[derive(Clone, Copy)]pub enum SnapshotPrototype {- /// Internal records must not consult author-modifiable Object.prototype.Null,- /// Public snapshots use the current (callee) Realm's Object.prototype.Ordinary,}-/// Copy policy for the canonical JS representation of a converted member.#[derive(Clone, Copy)]pub enum SnapshotKind {- /// Immutable scalar values or interface objects whose identity is retained.+ /// Primitive values; containers are rejected instead of silently aliased.+ Scalar,+ /// Opaque JS values/interfaces whose identity must be preserved.Identity,Sequence(&'static SnapshotKind),- Dictionary(&'static [SnapshotMember]),+ FrozenSequence(&'static SnapshotKind),+ Dictionary(&'static SnapshotSchema),+ Nullable(&'static SnapshotKind),+ Record(&'static SnapshotKind),+ BufferSource,+ /// API-specific policy for an already converted native value.+ Custom(+ for<'s, 'i> fn(+ &mut v8::PinScope<'s, 'i>,+ v8::Local<'s, v8::Value>,+ SnapshotPrototype,+ ) -> Option<v8::Local<'s, v8::Value>>,+ ),}-/// A member generated from the same metadata as dictionary argument conversion.pub struct SnapshotMember {pub name: &'static str,pub kind: SnapshotKind,pub optional: bool,}-/// Explicit snapshot policy for custom raw converters.-///-/// Raw conversion can produce a scalar, an interface, or a canonical container;-/// its representation cannot safely be inferred by the dictionary derive.+pub struct SnapshotSchema {+ pub inherited: Option<&'static SnapshotSchema>,+ pub members: &'static [SnapshotMember],+}++/// Raw/custom converters explicitly describe their canonical JS representation.pub trait WebIdlSnapshotValue {const SNAPSHOT_KIND: SnapshotKind;}--/// Opt-in dictionary copy metadata, generated by `#[webidl(snapshot)]`.-///-/// Sources must be fresh native binding output or private snapshots, with own-/// data properties and dense arrays. This is not WebIDL input conversion and-/// must never be applied directly to an author-supplied dictionary. It ignores-/// absent optional members and unknown properties, without consulting iterators-/// or prototypes. Missing non-optional members fail instead of silently losing-/// a field when a binding declaration is incomplete.pub trait WebIdlDictionarySnapshot {- const SNAPSHOT_MEMBERS: &'static [SnapshotMember];+ const SNAPSHOT_SCHEMA: SnapshotSchema;+}++/// Writes converted Rust fields without reading author object properties.+pub trait WebIdlDictionarySerialize<'s>: WebIdlDictionarySnapshot + Sized {+ fn write_snapshot_own_fields(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ writer: &SnapshotWriter<'s>,+ ) -> Option<()>;++ fn write_snapshot_fields(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ writer: &SnapshotWriter<'s>,+ ) -> Option<()>;++ fn to_js_snapshot(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ prototype: SnapshotPrototype,+ ) -> Option<v8::Local<'s, v8::Object>> {+ let writer = SnapshotWriter {+ object: new_object(scope, prototype),+ prototype,+ state: false,+ };+ self.write_snapshot_fields(scope, &writer)?;+ Some(writer.object)+ }++ fn to_snapshot(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ ) -> Option<DictionarySnapshot<'s, Self>> {+ let object = self.to_js_snapshot(scope, SnapshotPrototype::Null)?;+ Some(DictionarySnapshot {+ object,+ marker: PhantomData,+ })+ }++ /// Install fields on an existing native backing. Slot mappings apply here;+ /// dictionary results always use their original WebIDL member names.+ fn initialize_snapshot(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ ) -> Option<()> {+ self.write_snapshot_fields(+ scope,+ &SnapshotWriter {+ object,+ prototype: SnapshotPrototype::Null,+ state: true,+ },+ )+ }- fn to_js_snapshot<'s>(+ /// Legacy reinitializers update this dictionary's payload without resetting+ /// inherited event state that their own algorithms have already initialized.+ fn initialize_own_snapshot(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ ) -> Option<()> {+ self.write_snapshot_own_fields(+ scope,+ &SnapshotWriter {+ object,+ prototype: SnapshotPrototype::Null,+ state: true,+ },+ )+ }+}++/// Traced internal state. No constructor accepts an arbitrary JS object.+pub struct DictionarySnapshot<'s, T: WebIdlDictionarySnapshot> {+ object: v8::Local<'s, v8::Object>,+ marker: PhantomData<fn() -> T>,+}++impl<'s, T: WebIdlDictionarySnapshot> DictionarySnapshot<'s, T> {+ pub fn from_private_slot(+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+ slot: &'static str,+ ) -> Option<Self> {+ let object = get_private_value(scope, owner, slot)?.try_into().ok()?;+ Some(Self {+ object,+ marker: PhantomData,+ })+ }++ pub fn store_private(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ owner: v8::Local<'s, v8::Object>,+ slot: &'static str,+ ) -> Option<()> {+ let key = private_key(scope, slot)?;+ owner+ .set_private(scope, key, self.object.into())?+ .then_some(())+ }++ pub fn to_js_snapshot(+ &self,scope: &mut v8::PinScope<'s, '_>,- source: v8::Local<'s, v8::Object>,prototype: SnapshotPrototype,) -> Option<v8::Local<'s, v8::Object>> {- copy_dictionary(scope, source, Self::SNAPSHOT_MEMBERS, prototype)+ copy_dictionary(scope, self.object, &T::SNAPSHOT_SCHEMA, prototype)+ }+}++impl<'s, T: WebIdlDictionarySnapshot> WebApiValue<'s> for DictionarySnapshot<'s, T> {+ fn to_v8_value(&self, _: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ Some(self.object.into())}}+/// Sink used by generated serializers for dictionary results and backing state.+pub struct SnapshotWriter<'s> {+ object: v8::Local<'s, v8::Object>,+ pub prototype: SnapshotPrototype,+ state: bool,+}++const CALLBACK_CONTEXTS: &str = "__moliDictionarySnapshotCallbackContexts";++impl<'s> SnapshotWriter<'s> {+ /// Native state hooks may store invocation carriers while JS snapshots+ /// retain the original callback/interface identity.+ pub const fn is_state(&self) -> bool {+ self.state+ }++ /// Converted callbacks retain their conversion-time contexts in the V8+ /// owner graph, never in a process- or runtime-owned Global root.+ pub fn anchor_contexts(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ contexts: &[v8::Local<'s, v8::Object>],+ ) -> Option<()> {+ let key = private_key(scope, CALLBACK_CONTEXTS)?;+ let array = match get_private_value(scope, self.object, CALLBACK_CONTEXTS) {+ Some(value) => v8::Local::<v8::Array>::try_from(value).ok()?,+ None => {+ let array = v8::Array::new(scope, 0);+ array+ .set_prototype(scope, v8::null(scope).into())?+ .then_some(())?;+ self.object+ .set_private(scope, key, array.into())?+ .then_some(())?;+ array+ }+ };+ for context in contexts {+ moli_webapi_declare::define_array_data_property(+ scope,+ array,+ array.length(),+ (*context).into(),+ )?;+ }+ Some(())+ }++ pub fn set(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ name: &'static str,+ slot: Option<&str>,+ value: v8::Local<'s, v8::Value>,+ attributes: v8::PropertyAttribute,+ ) -> Option<()> {+ if self.state+ && let Some(slot) = slot+ {+ let key = private_key(scope, slot)?;+ self.object.set_private(scope, key, value)?.then_some(())+ } else if self.state && attributes != v8::PropertyAttribute::NONE {+ self.object+ .define_own_property(scope, v8str(scope, name).into(), value, attributes)?+ .then_some(())+ } else {+ self.object+ .create_data_property(scope, v8str(scope, name).into(), value)?+ .then_some(())+ }+ }+}++fn new_object<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ prototype: SnapshotPrototype,+) -> v8::Local<'s, v8::Object> {+ match prototype {+ SnapshotPrototype::Null => new_null_prototype_object(scope),+ SnapshotPrototype::Ordinary => v8::Object::new(scope),+ }+}++// Inspect an own data descriptor. Even a corrupted native carrier must not run+// an accessor or consult a polluted prototype during a snapshot read.+fn data_property<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ key: v8::Local<'s, v8::Name>,+) -> Option<v8::Local<'s, v8::Value>> {+ let descriptor = object.get_own_property_descriptor(scope, key)?;+ let descriptor = v8::Local::<v8::Object>::try_from(descriptor).ok()?;+ moli_v8_util::get_own_static_property(scope, descriptor, "value")+}+fn copy_dictionary<'s>(scope: &mut v8::PinScope<'s, '_>,source: v8::Local<'s, v8::Object>,- members: &'static [SnapshotMember],+ schema: &'static SnapshotSchema,prototype: SnapshotPrototype,) -> Option<v8::Local<'s, v8::Object>> {- let output = match prototype {- SnapshotPrototype::Null => new_null_prototype_object(scope),- SnapshotPrototype::Ordinary => v8::Object::new(scope),- };- for member in members {+ let output = new_object(scope, prototype);+ copy_members(scope, source, output, schema, prototype)?;+ if matches!(prototype, SnapshotPrototype::Null)+ && let Some(contexts) = get_private_value(scope, source, CALLBACK_CONTEXTS)+ {+ let key = private_key(scope, CALLBACK_CONTEXTS)?;+ output.set_private(scope, key, contexts)?.then_some(())?;+ }+ Some(output)+}++fn copy_members<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ source: v8::Local<'s, v8::Object>,+ output: v8::Local<'s, v8::Object>,+ schema: &'static SnapshotSchema,+ prototype: SnapshotPrototype,+) -> Option<()> {+ if let Some(base) = schema.inherited {+ copy_members(scope, source, output, base, prototype)?;+ }+ for member in schema.members {let key = v8str(scope, member.name);if !source.has_own_property(scope, key.into())? {if member.optional {@@ -93,37 +328,97 @@ fn copy_dictionary<'s>(}return None;}- let value = source.get(scope, key.into())?;+ let value = data_property(scope, source, key.into())?;let value = member.kind.copy(scope, value, prototype)?;- if !output.create_data_property(scope, key.into(), value)? {- return None;- }+ output+ .create_data_property(scope, key.into(), value)?+ .then_some(())?;}- Some(output)+ Some(())}impl SnapshotKind {- fn copy<'s>(+ pub fn copy<'s>(&self,scope: &mut v8::PinScope<'s, '_>,source: v8::Local<'s, v8::Value>,prototype: SnapshotPrototype,) -> Option<v8::Local<'s, v8::Value>> {match self {+ Self::Scalar => (!source.is_object()).then_some(source),Self::Identity => Some(source),- Self::Sequence(item_kind) => {+ Self::Nullable(_) if source.is_null() => Some(source),+ Self::Nullable(kind) => kind.copy(scope, source, prototype),+ Self::Sequence(kind) | Self::FrozenSequence(kind) => {let source = v8::Local::<v8::Array>::try_from(source).ok()?;let mut items = Vec::with_capacity(source.length() as usize);for index in 0..source.length() {- let item = source.get_index(scope, index)?;- items.push(item_kind.copy(scope, item, prototype)?);+ let key = v8_string(scope, &index.to_string())?;+ let item = data_property(scope, source.into(), key.into())?;+ items.push(kind.copy(scope, item, prototype)?);}- Some(v8::Array::new_with_elements(scope, &items).into())+ let output = v8::Array::new_with_elements(scope, &items);+ if matches!(self, Self::FrozenSequence(_)) {+ output+ .set_integrity_level(scope, v8::IntegrityLevel::Frozen)?+ .then_some(())?;+ }+ Some(output.into())+ }+ Self::Dictionary(schema) => {+ copy_dictionary(scope, source.try_into().ok()?, schema, prototype).map(Into::into)}- Self::Dictionary(members) => {+ Self::Record(kind) => {let source = v8::Local::<v8::Object>::try_from(source).ok()?;- copy_dictionary(scope, source, members, prototype).map(Into::into)+ let output = new_object(scope, prototype);+ let keys = source.get_own_property_names(scope, Default::default())?;+ for index in 0..keys.length() {+ let key =+ v8::Local::<v8::Name>::try_from(keys.get_index(scope, index)?).ok()?;+ let value = data_property(scope, source, key)?;+ let value = kind.copy(scope, value, prototype)?;+ output+ .create_data_property(scope, key, value)?+ .then_some(())?;+ }+ Some(output.into())}+ Self::BufferSource => buffer_snapshot(scope, source),+ Self::Custom(copy) => copy(scope, source, prototype),}}}++pub fn buffer_snapshot<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ source: v8::Local<'s, v8::Value>,+) -> Option<v8::Local<'s, v8::Value>> {+ let bytes = match crate::convert::<crate::BufferSource>(+ scope,+ source,+ crate::Context::member("DictionarySnapshot", "buffer"),+ ) {+ Ok(value) => value.0,+ Err(error) => {+ crate::throw_error(scope, &error);+ return None;+ }+ };+ Some(buffer_from_bytes(scope, bytes))+}++fn buffer_from_bytes<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ bytes: Vec<u8>,+) -> v8::Local<'s, v8::Value> {+ let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();+ v8::ArrayBuffer::with_backing_store(scope, &store).into()+}++#[doc(hidden)]+pub fn bytes_snapshot<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ bytes: &[u8],+) -> v8::Local<'s, v8::Value> {+ buffer_from_bytes(scope, bytes.to_vec())+}diff --git a/moli-webidl/src/snapshot/value.rs b/moli-webidl/src/snapshot/value.rsnew file mode 100644index 000000000..8065bf4c4--- /dev/null+++ b/moli-webidl/src/snapshot/value.rs@@ -0,0 +1,129 @@+use super::*;++impl AsRef<[u8]> for crate::BufferSource {+ fn as_ref(&self) -> &[u8] {+ self.as_bytes()+ }+}++macro_rules! scalar_snapshot {+ ($($ty:ty),* $(,)?) => { $(impl WebIdlSnapshotValue for $ty { const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar; })* };+}+scalar_snapshot!(+ String, str, &str, bool, u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64+);++impl<T: WebIdlSnapshotValue> WebIdlSnapshotValue for Option<T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Nullable(&T::SNAPSHOT_KIND);+}+impl<T: WebIdlSnapshotValue> WebIdlSnapshotValue for Vec<T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Sequence(&T::SNAPSHOT_KIND);+}+impl<T> WebIdlSnapshotValue for v8::Local<'_, T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Identity;+}+impl<T: WebIdlSnapshotValue> WebIdlSnapshotValue for crate::Sequence<T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Sequence(&T::SNAPSHOT_KIND);+}+impl<'s, T: WebApiValue<'s>> WebApiValue<'s> for crate::Sequence<T> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ self.0.to_v8_value(scope)+ }+}+impl<T: WebIdlDictionarySnapshot> WebIdlSnapshotValue for crate::Dictionary<T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Dictionary(&T::SNAPSHOT_SCHEMA);+}+impl<'s, T: WebIdlDictionarySerialize<'s>> WebApiValue<'s> for crate::Dictionary<T> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ self.0+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .map(Into::into)+ }+}+impl<K, V: WebIdlSnapshotValue> WebIdlSnapshotValue for crate::Record<K, V> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Record(&V::SNAPSHOT_KIND);+}+impl<'s, K: WebApiValue<'s>, V: WebApiValue<'s>> WebApiValue<'s> for crate::Record<K, V> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ let output = new_null_prototype_object(scope);+ for (key, value) in &self.0 {+ let key = v8::Local::<v8::Name>::try_from(key.to_v8_value(scope)?).ok()?;+ let value = value.to_v8_value(scope)?;+ output+ .create_data_property(scope, key, value)?+ .then_some(())?;+ }+ Some(output.into())+ }+}+macro_rules! wrapper_snapshot {+ ($($ty:ty),* $(,)?) => { $(+ impl WebIdlSnapshotValue for $ty { const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar; }+ impl<'s> WebApiValue<'s> for $ty {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> { self.0.to_v8_value(scope) }+ }+ )* };+}+wrapper_snapshot!(+ crate::Boolean,+ crate::Octet,+ crate::UnrestrictedDouble,+ crate::UnrestrictedFloat,+ crate::Float,+ crate::Double,+ crate::Long,+ crate::UnsignedLong,+ crate::Short,+ crate::UnsignedShort,+ crate::ClampedUnsignedShort,+ crate::LongLong,+ crate::UnsignedLongLong,+ crate::EnforceRangeLongLong,+ crate::DomString,+ crate::UsvString,+ crate::EnforceRangeUnsignedLong,+ crate::EnforceRangeUnsignedLongLong,+ crate::EnforceRangeLong,+ crate::EnforceRangeUnsignedShort+);+impl WebIdlSnapshotValue for crate::DomString16 {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar;+}+impl<'s> WebApiValue<'s> for crate::DomString16 {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ v8::String::new_from_two_byte(scope, &self.0, v8::NewStringType::Normal).map(Into::into)+ }+}+impl WebIdlSnapshotValue for crate::BufferSource {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::BufferSource;+}+impl<'s> WebApiValue<'s> for crate::BufferSource {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ Some(buffer_from_bytes(scope, self.0.clone()))+ }+}++impl<T: crate::WebIdlEnumSnapshot> WebIdlSnapshotValue for crate::EnumValue<T> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar;+}+impl<'s, T: crate::WebIdlEnumSnapshot> WebApiValue<'s> for crate::EnumValue<T> {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ crate::__private::enum_snapshot_value(scope, &self.0)+ }+}+impl WebIdlSnapshotValue for crate::InterfaceObject<'_> {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Identity;+}+impl<'s> WebApiValue<'s> for crate::InterfaceObject<'s> {+ fn to_v8_value(&self, _: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ Some(self.0.into())+ }+}+impl WebIdlSnapshotValue for crate::ByteString {+ const SNAPSHOT_KIND: SnapshotKind = SnapshotKind::Scalar;+}+impl<'s> WebApiValue<'s> for crate::ByteString {+ fn to_v8_value(&self, scope: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {+ v8::String::new_from_one_byte(scope, &self.0, v8::NewStringType::Normal).map(Into::into)+ }+}diff --git a/moli-webidl/tests/dictionary_snapshots.rs b/moli-webidl/tests/dictionary_snapshots.rsindex 026d251a0..bf739869e 100644--- a/moli-webidl/tests/dictionary_snapshots.rs+++ b/moli-webidl/tests/dictionary_snapshots.rs@@ -1,5 +1,5 @@-use moli_webapi_declare::WebApiObject;-use moli_webidl::{SnapshotPrototype, WebIdlDictionary, WebIdlDictionarySnapshot};+use moli_webapi_declare::WebApiValue;+use moli_webidl::{SnapshotPrototype, WebIdlDictionary, WebIdlDictionarySerialize};mod interfaces {moli_webapi_declare::declare_web_api_interfaces! {@@ -7,21 +7,18 @@ mod interfaces {}}-#[derive(WebIdlDictionary, WebApiObject)]+#[derive(WebIdlDictionary)]#[webidl(snapshot)]-#[webapi(plain, data_properties, enumerable)]struct Server {#[webidl(sequence, required)]urls: Vec<String>,username: Option<String>,}-#[derive(WebIdlDictionary, WebApiObject)]+#[derive(WebIdlDictionary)]#[webidl(snapshot)]-#[webapi(plain, data_properties, enumerable)]struct Options<'s> {#[webidl(default = 7, name = "renamedNumber")]- #[webapi(data_property = "renamedNumber")]number: u32,#[webidl(sequence, converter = "dictionary", default = Vec::new())]servers: Vec<Server>,@@ -37,8 +34,13 @@ fn snapshot<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'s>,) {- let stored = v8::Local::<v8::Object>::try_from(args.data()).unwrap();- let snapshot = Options::to_js_snapshot(scope, stored, SnapshotPrototype::Ordinary).unwrap();+ let owner = v8::Local::<v8::Object>::try_from(args.data()).unwrap();+ let stored =+ moli_webidl::DictionarySnapshot::<Options>::from_private_slot(scope, owner, "SnapshotTest")+ .unwrap();+ let snapshot = stored+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();rv.set(snapshot.into());}@@ -74,15 +76,23 @@ fn snapshots_follow_dictionary_metadata_and_copy_only_containers() {);let parsed =moli_webidl::parse_dictionary_object::<Options>(scope, source.try_into().unwrap()).unwrap();- let bound = parsed.bind(scope).unwrap();- let stored = Options::to_js_snapshot(scope, bound, SnapshotPrototype::Null).unwrap();+ let snapshot_state = parsed.to_snapshot(scope).unwrap();+ let stored: v8::Local<v8::Object> = snapshot_state+ .to_v8_value(scope)+ .unwrap()+ .try_into()+ .unwrap();+ let owner = v8::Object::new(scope);+ snapshot_state+ .store_private(scope, owner, "SnapshotTest")+ .unwrap();let key = v8::String::new(scope, "stored").unwrap();assert_eq!(global.create_data_property(scope, key.into(), stored.into()),Some(true));let snapshot = v8::Function::builder(snapshot)- .data(stored.into())+ .data(owner.into()).build(scope).unwrap();let key = v8::String::new(scope, "snapshot").unwrap();@@ -128,10 +138,26 @@ fn snapshots_follow_dictionary_metadata_and_copy_only_containers() {return true;})()"#).is_true());+ // Even a corrupted private carrier must not run an accessor.+ eval(+ scope,+ "globalThis.reads = 0; Object.defineProperty(stored, 'addedLater', {configurable:true, get(){ ++reads; throw Error('getter'); }})",+ );+ assert!(+ snapshot_state+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .is_none()+ );+ assert_eq!(eval(scope, "reads").int32_value(scope), Some(0));+// An incomplete binding is an invariant violation, not a partial snapshot.let key = v8::String::new(scope, "addedLater").unwrap();assert_eq!(stored.delete(scope, key.into()), Some(true));- assert!(Options::to_js_snapshot(scope, stored, SnapshotPrototype::Ordinary).is_none());+ assert!(+ snapshot_state+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .is_none()+ );}#[test]@@ -147,18 +173,15 @@ fn private_snapshots_trace_interfaces_without_rooting_unreachable_cycles() {interfaces::Certificate::DESCRIPTOR.initialize(scope, certificate).unwrap();- let bound = Options {+ let parsed = Options {number: 7,servers: Vec::new(),certificates: vec![certificate],added_later: "new member".into(),- }- .bind(scope)- .unwrap();- let stored = Options::to_js_snapshot(scope, bound, SnapshotPrototype::Null).unwrap();+ };+ let stored = parsed.to_snapshot(scope).unwrap();let owner = v8::Object::new(scope);- let slot = v8::Private::new(scope, None);- assert_eq!(owner.set_private(scope, slot, stored.into()), Some(true));+ stored.store_private(scope, owner, "SnapshotTest").unwrap();let key = v8::String::new(scope, "owner").unwrap();assert_eq!(certificate.create_data_property(scope, key.into(), owner.into()),diff --git a/moli-webidl/tests/snapshot_policies.rs b/moli-webidl/tests/snapshot_policies.rsnew file mode 100644index 000000000..5e3df1d32--- /dev/null+++ b/moli-webidl/tests/snapshot_policies.rs@@ -0,0 +1,327 @@+use moli_webapi_declare::WebApiValue;+use moli_webidl::{SnapshotPrototype, WebIdlDictionary, WebIdlDictionarySerialize};++#[derive(WebIdlDictionary)]+#[webidl(snapshot)]+struct Base {+ #[webidl(default = true, snapshot_slot = "SnapshotBaseEnabled")]+ enabled: bool,+}++#[derive(WebIdlDictionary)]+#[webidl(snapshot)]+struct Child {+ #[webidl(sequence, required)]+ values: Vec<String>,+}++#[derive(WebIdlDictionary)]+#[webidl(snapshot)]+struct Policies {+ #[webidl(inherit)]+ base: Base,+ #[webidl(required, converter = "buffer_source")]+ buffer: Vec<u8>,+ #[webidl(with = custom_member, snapshot_with = custom_snapshot, snapshot_state_with = custom_state)]+ custom: String,+ #[webidl(sequence, default = Vec::new(), snapshot_frozen)]+ frozen_items: Vec<String>,+ #[webidl(nullable, dictionary)]+ nullable_child: Option<Child>,+ #[webidl(required, converter = "raw")]+ record: moli_webidl::Record<moli_webidl::DomString, moli_webidl::Dictionary<Child>>,+ #[webidl(snapshot_default = v8::Integer::new(scope, 99).into(), snapshot_slot = "SnapshotSeed")]+ seed: Option<u32>,+ #[webidl(default = "state", snapshot_attributes = v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE)]+ state_label: String,+ #[webidl(with = nullable_member)]+ tri_state: Option<Option<String>>,+ #[webidl(default = moli_webidl::DomString16(Vec::new()), converter = "raw")]+ utf16: moli_webidl::DomString16,+ #[webidl(default = moli_webidl::EnforceRangeUnsignedLong(4), converter = "raw")]+ wrapped: moli_webidl::EnforceRangeUnsignedLong,+}++fn custom_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<String, moli_webidl::WebIdlError> {+ let context = moli_webidl::Context::member("Policies", name);+ moli_webidl::optional_member::<moli_webidl::DomString>(scope, object, name, context).map(+ |value| {+ value+ .map(|value| value.0)+ .unwrap_or_default()+ .to_uppercase()+ },+ )+}++fn custom_snapshot<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: &str,+ _: SnapshotPrototype,+) -> Option<v8::Local<'s, v8::Value>> {+ v8::String::new(scope, &format!("copy:{value}")).map(Into::into)+}++fn custom_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: &str,+) -> Option<v8::Local<'s, v8::Value>> {+ v8::String::new(scope, &format!("state:{value}")).map(Into::into)+}++fn nullable_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<Option<Option<String>>, moli_webidl::WebIdlError> {+ let context = moli_webidl::Context::member("Policies", name);+ match moli_webidl::property_result(scope, object, name, context)? {+ None => Ok(None),+ Some(value) if value.is_undefined() => Ok(None),+ Some(value) if value.is_null() => Ok(Some(None)),+ Some(value) => moli_webidl::convert::<moli_webidl::DomString>(scope, value, context)+ .map(|value| Some(Some(value.0))),+ }+}++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()+}++fn expose<'s>(scope: &mut v8::PinScope<'s, '_>, name: &str, value: v8::Local<'s, v8::Value>) {+ let global = scope.get_current_context().global(scope);+ let name = v8::String::new(scope, name).unwrap();+ assert_eq!(+ global.create_data_property(scope, name.into(), value),+ Some(true)+ );+}++#[test]+fn inherited_nullable_record_buffer_and_state_policies_preserve_conversion() {+ moli_v8_test_util::ensure_v8();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = std::pin::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 source = eval(+ scope,+ r#"(() => {+ globalThis.reads = [];+ globalThis.bytes = new Uint8Array([8, 1, 2, 9]);+ const values = {+ enabled: true, buffer: bytes.subarray(1, 3), custom: 'tag',+ frozenItems: ['one'], nullableChild: null,+ record: {['__proto__']: {values:['safe']}, alpha:{values:['original']}},+ triState: null, utf16: '\ud800', wrapped: 8+ };+ globalThis.input = {};+ for (const key of Object.keys(values)) Object.defineProperty(input, key, {+ configurable:true, get(){ reads.push(key); return values[key]; }+ });+ return input;+ })()"#,+ );+ let mut parsed =+ moli_webidl::parse_dictionary_object::<Policies>(scope, source.try_into().unwrap())+ .unwrap();+ assert!(+ eval(+ scope,+ "reads[0] === 'enabled' && new Set(reads).size === reads.length"+ )+ .is_true()+ );+ eval(+ scope,+ "bytes.fill(0); for (const key of Object.getOwnPropertyNames(input)) Object.defineProperty(input, key, {get(){throw Error('re-read')}, configurable:true})",+ );+ let stored = parsed.to_snapshot(scope).unwrap();+ let internal = stored.to_v8_value(scope).unwrap();+ expose(scope, "internal", internal);+ let first = stored+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ expose(scope, "first", first.into());+ assert!(eval(scope, r#"(() => {+ const assert = (ok) => { if (!ok) throw Error('snapshot policy'); };+ assert(first.enabled && first.seed === 99 && first.wrapped === 8);+ assert(first.nullableChild === null && first.triState === null);+ assert(first.custom === 'copy:TAG' && first.utf16.charCodeAt(0) === 0xd800);+ assert(Object.getPrototypeOf(internal.record) === null);+ assert(Object.getPrototypeOf(internal.record.alpha) === null);+ assert(Object.getPrototypeOf(first.record) === Object.prototype);+ assert(Object.hasOwn(first.record, '__proto__') && first.record.__proto__.values[0] === 'safe');+ assert(Object.isFrozen(first.frozenItems) && first.frozenItems[0] === 'one');+ assert(new Uint8Array(first.buffer).join() === '1,2');+ new Uint8Array(first.buffer).fill(7);+ first.record.alpha.values[0] = 'changed';+ const descriptor = Object.getOwnPropertyDescriptor(first, 'stateLabel');+ assert(descriptor.writable && descriptor.enumerable && descriptor.configurable);+ return true;+ })()"#).is_true());+ let second = stored+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ expose(scope, "second", second.into());+ assert!(eval(scope, "new Uint8Array(second.buffer).join() === '1,2' && second.record.alpha.values[0] === 'original' && second.buffer !== first.buffer && second.record !== first.record").is_true());++ let state = v8::Object::new(scope);+ parsed.initialize_snapshot(scope, state).unwrap();+ expose(scope, "state", state.into());+ assert!(eval(scope, "state.custom === 'state:TAG'").is_true());+ assert!(eval(scope, "!Object.hasOwn(state, 'seed') && !Object.hasOwn(state, 'enabled') && !Object.getOwnPropertyDescriptor(state, 'stateLabel').writable && !Object.getOwnPropertyDescriptor(state, 'stateLabel').configurable").is_true());+ parsed.base.enabled = false;+ parsed.seed = Some(5);+ parsed.tri_state = None;+ parsed.initialize_own_snapshot(scope, state).unwrap();+ let enabled = moli_v8_util::get_private_value(scope, state, "SnapshotBaseEnabled").unwrap();+ assert!(+ enabled.is_true(),+ "own-member initialization preserves inherited state"+ );+ let seed = moli_v8_util::get_private_value(scope, state, "SnapshotSeed").unwrap();+ assert_eq!(seed.uint32_value(scope), Some(5));+ let output = parsed+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ expose(scope, "output", output.into());+ assert!(+ eval(+ scope,+ "!Object.hasOwn(output, 'triState') && output.seed === 5 && !output.enabled"+ )+ .is_true()+ );+ parsed.tri_state = Some(Some("present".into()));+ let output = parsed+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ expose(scope, "output", output.into());+ assert!(eval(scope, "output.triState === 'present'").is_true());+}++#[derive(WebIdlDictionary)]+#[webidl(snapshot)]+struct Frozen {+ #[webidl(sequence, converter = "dictionary", default = Vec::new(), snapshot_frozen)]+ children: Vec<Child>,+}++#[test]+fn snapshot_containers_and_frozen_arrays_use_the_entered_realm() {+ moli_v8_test_util::ensure_v8();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let original = v8::Context::new(scope, Default::default());+ let other = v8::Context::new(scope, Default::default());+ let stored = {+ let scope = &mut v8::ContextScope::new(scope, original);+ Frozen {+ children: vec![Child {+ values: vec!["value".into()],+ }],+ }+ .to_snapshot(scope)+ .unwrap()+ };+ let scope = &mut v8::ContextScope::new(scope, other);+ eval(+ scope,+ "Object.defineProperty(Object.prototype, 'children', {set(){throw Error('setter')}, configurable:true}); Object.defineProperty(Array.prototype, '0', {set(){throw Error('index')}, configurable:true}); Array.prototype[Symbol.iterator] = () => {throw Error('iterator')}",+ );+ let output = stored+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ assert_eq!(output.get_creation_context(scope).unwrap(), other);+ expose(scope, "snapshot", output.into());+ assert!(eval(scope, "Object.getPrototypeOf(snapshot) === Object.prototype && snapshot.children instanceof Array && Object.isFrozen(snapshot.children) && Object.getPrototypeOf(snapshot.children[0]) === Object.prototype && snapshot.children[0].values instanceof Array && snapshot.children[0].values[0] === 'value'").is_true());+}++#[derive(WebIdlDictionary)]+#[webidl(snapshot)]+struct Callbacks {+ #[webidl(converter = "callback_function")]+ handler: Option<moli_webidl::WebIdlCallbackFunction>,+ #[webidl(converter = "callback_interface")]+ listener: Option<moli_webidl::WebIdlCallbackInterface>,+}++#[test]+fn snapshot_callback_contexts_are_traced_and_owner_cycles_are_collectible() {+ moli_v8_test_util::ensure_v8();+ let mut isolate = v8::Isolate::new(Default::default());+ let (owner, weak_owner, weak_callback, weak_incumbent) = {+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let relevant = v8::Context::new(scope, Default::default());+ let incumbent = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, relevant);+ let function: v8::Local<v8::Object> = eval(scope, "(() => {})").try_into().unwrap();+ let listener = v8::Object::new(scope);+ let parsed = Callbacks {+ handler: Some(+ moli_webidl::WebIdlCallbackFunction::try_new(scope, function, relevant, incumbent)+ .unwrap(),+ ),+ listener: Some(moli_webidl::WebIdlCallbackInterface::new(+ scope, listener, relevant, incumbent,+ )),+ };+ let snapshot = parsed.to_snapshot(scope).unwrap();+ let public = snapshot+ .to_js_snapshot(scope, SnapshotPrototype::Ordinary)+ .unwrap();+ let handler = v8::String::new(scope, "handler").unwrap();+ let listener_key = v8::String::new(scope, "listener").unwrap();+ assert!(+ public+ .get(scope, handler.into())+ .unwrap()+ .strict_equals(function.into())+ );+ assert!(+ public+ .get(scope, listener_key.into())+ .unwrap()+ .strict_equals(listener.into())+ );+ let owner = v8::Object::new(scope);+ snapshot.store_private(scope, owner, "Callbacks").unwrap();+ let key = v8::String::new(scope, "owner").unwrap();+ function+ .create_data_property(scope, key.into(), owner.into())+ .unwrap();+ let incumbent_anchor = incumbent.get_extras_binding_object(scope);+ (+ v8::Global::new(scope, owner),+ v8::Weak::new(scope, owner),+ v8::Weak::new(scope, function),+ v8::Weak::new(scope, incumbent_anchor),+ )+ };+ isolate.low_memory_notification();+ assert!(!weak_callback.is_empty());+ assert!(+ !weak_incumbent.is_empty(),+ "the independent conversion-time incumbent is retained"+ );+ drop(owner);+ isolate.low_memory_notification();+ assert!(weak_owner.is_empty());+ assert!(weak_callback.is_empty());+ assert!(+ weak_incumbent.is_empty(),+ "no native Global permanently roots the callback contexts"+ );+}