Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(webrtc): implement native RTCError and RTCErrorEvent
ldm0ae1aeb37f4cc
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rsindex 747f33c5f..c669ef97c 100644--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs@@ -62,8 +62,8 @@ use super::super::{offline_audio_context_constructor_callback,},webrtc::{- rtc_data_channel_event_constructor_callback, rtc_ice_candidate_constructor_callback,- rtc_peer_connection_constructor_callback,+ rtc_data_channel_event_constructor_callback, rtc_error_event_constructor_callback,+ rtc_ice_candidate_constructor_callback, rtc_peer_connection_constructor_callback,rtc_peer_connection_ice_event_constructor_callback,rtc_session_description_constructor_callback,},@@ -243,6 +243,22 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(.length(0).build(scope)}+ ConstructorKind::RtcError => {+ v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(+ web_api_interfaces::RTCError,+ rtc_error_constructor_callback+ ))+ .length(1)+ .build(scope)+ }+ ConstructorKind::RtcErrorEvent => {+ v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(+ web_api_interfaces::RTCErrorEvent,+ rtc_error_event_constructor_callback+ ))+ .length(2)+ .build(scope)+ }ConstructorKind::DomError => {v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(web_api_interfaces::DOMError,diff --git a/moli-renderer-v8/src/context_bootstrap/constructors.rs b/moli-renderer-v8/src/context_bootstrap/constructors.rsindex b760451fd..a666c66ec 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors.rs@@ -37,8 +37,8 @@ pub(crate) use dom_exception::{initialize_websocket_error, install_dom_exception_template_bindings, new_dom_error_value,new_dom_exception_value, new_most_derived_dom_exception_value, new_quota_exceeded_error_value,new_websocket_error_value, quota_exceeded_error_clone_fields,- quota_exceeded_error_constructor_callback, throw_dom_exception_value,- websocket_error_close_info,+ quota_exceeded_error_constructor_callback, rtc_error_constructor_callback,+ throw_dom_exception_value, websocket_error_close_info,};pub(crate) use dom_implementation::ensure_dom_implementation_singleton;pub(super) use dom_implementation::install_dom_implementation_template_bindings;diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rsindex b5fe84e44..9abee3965 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception.rs@@ -4,6 +4,9 @@ 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};+mod rtc_error;+pub(crate) use rtc_error::rtc_error_constructor_callback;+const DOM_EXCEPTION_MESSAGE_SLOT: &str = "__lmDomExceptionMessage";const DOM_EXCEPTION_NAME_SLOT: &str = "__lmDomExceptionName";const DOM_EXCEPTION_CODE_SLOT: &str = "__lmDomExceptionCode";@@ -187,6 +190,7 @@ pub(crate) fn install_dom_exception_template_bindings<'s>(scope, prototype,);}+ "RTCError" => rtc_error::install(scope, prototype),_ => {}}}@@ -266,11 +270,9 @@ fn dom_exception_message_getter_callback<'s>(let Some(receiver) = dom_exception_receiver(scope, args.this()) else {return;};- let message = get_private_value(scope, receiver, DOM_EXCEPTION_MESSAGE_SLOT)- .and_then(|value| value.to_string(scope))- .map(|value| value.to_rust_string_lossy(scope))- .unwrap_or_default();- if let Some(message) = v8_string(scope, &message) {+ if let Some(message) = get_private_value(scope, receiver, DOM_EXCEPTION_MESSAGE_SLOT)+ .and_then(|value| v8::Local::<v8::String>::try_from(value).ok())+ {rv.set(message.into());} else {rv.set_empty_string();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.rsnew file mode 100644index 000000000..2fa26f80e--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/constructors/dom_exception/rtc_error.rs@@ -0,0 +1,166 @@+use super::*;+use crate::util::apply_webidl_constructor_prototype_fallback;+use webidl::WebIdlDictionary;++const ERROR_DETAIL: &str = "__moliRtcErrorDetail";+const SDP_LINE_NUMBER: &str = "__moliRtcErrorSdpLineNumber";+const SCTP_CAUSE_CODE: &str = "__moliRtcErrorSctpCauseCode";+const RECEIVED_ALERT: &str = "__moliRtcErrorReceivedAlert";+const SENT_ALERT: &str = "__moliRtcErrorSentAlert";++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "RTCErrorDetailType", rename_all = "kebab-case")]+enum ErrorDetail {+ DataChannelFailure,+ DtlsFailure,+ FingerprintFailure,+ SctpFailure,+ SdpSyntaxError,+ HardwareEncoderNotAvailable,+ 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")]+struct ErrorInit {+ // Dictionary members are visited lexically, before the message argument.+ #[webidl(required, converter = "enum")]+ error_detail: ErrorDetail,+ received_alert: Option<u32>,+ sctp_cause_code: Option<i32>,+ sdp_line_number: Option<i32>,+ sent_alert: Option<u32>,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "RTCError")]+struct ConstructorArgs {+ #[webidl(required, with = parse_init_arg)]+ init: ErrorInit,+ #[webidl(default = webidl::DomString16(Vec::new()), converter = "raw")]+ message: webidl::DomString16,+}++fn parse_init_arg<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+ index: i32,+) -> Result<ErrorInit, webidl::WebIdlError> {+ let object = webidl::dictionary_value(+ args.get(index),+ webidl::Context::argument("RTCError", (index + 1) as usize),+ )?+ .ok_or_else(|| {+ webidl::WebIdlError::missing_required(webidl::Context::member(+ "RTCErrorInit",+ "errorDetail",+ ))+ })?;+ ErrorInit::parse_dictionary(scope, object)+}++#[derive(WebApiObject)]+#[webapi(interface = web_api_interfaces::RTCError)]+struct ObjectDeclaration<'s> {+ #[webapi(slot = DOM_EXCEPTION_MESSAGE_SLOT)]+ message: v8::Local<'s, v8::String>,+ #[webapi(slot = DOM_EXCEPTION_NAME_SLOT, init = string("OperationError"))]+ 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)]+#[webapi(interface = web_api_interfaces::RTCError, receiver, enumerable)]+struct PrototypeDeclaration {+ #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, ERROR_DETAIL))]+ error_detail: (),+ #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, SDP_LINE_NUMBER))]+ sdp_line_number: (),+ #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, SCTP_CAUSE_CODE))]+ sctp_cause_code: (),+ #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, RECEIVED_ALERT))]+ received_alert: (),+ #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, SENT_ALERT))]+ sent_alert: (),+}++pub(super) fn install<'s>(+ scope: &mut v8::PinScope<'s, '_, ()>,+ prototype: v8::Local<'s, v8::ObjectTemplate>,+) {+ PrototypeDeclaration::initialize_prototype_template(scope, prototype);+}++pub(crate) fn rtc_error_constructor_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ if !args.is_construct_call() {+ throw_type_error(scope, "RTCError constructor requires 'new'.");+ return;+ }+ let Some(parsed) = webidl::parse_args::<ConstructorArgs>(scope, &args) else {+ return;+ };+ let Some(message) =+ v8::String::new_from_two_byte(scope, &parsed.message.0, v8::NewStringType::Normal)+ 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() {+ apply_webidl_constructor_prototype_fallback(+ scope,+ args.this(),+ args.new_target(),+ "RTCError",+ );+ rv.set(args.this().into());+ }+}++fn slot_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let slot = v8::Local::<v8::String>::try_from(args.data())+ .expect("RTCError attribute slot")+ .to_rust_string_lossy(scope);+ if let Some(value) = get_private_value(scope, args.this(), &slot) {+ rv.set(value);+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rsindex 2101e00d2..1a33bffd9 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs@@ -408,6 +408,14 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[interface: web_api_interfaces::DOMException::DESCRIPTOR,kind: ConstructorKind::DomException,},+ ConstructorSpec {+ interface: web_api_interfaces::RTCError::DESCRIPTOR,+ kind: ConstructorKind::RtcError,+ },+ ConstructorSpec {+ interface: web_api_interfaces::RTCErrorEvent::DESCRIPTOR,+ kind: ConstructorKind::RtcErrorEvent,+ },ConstructorSpec {interface: web_api_interfaces::DOMError::DESCRIPTOR,kind: ConstructorKind::DomError,diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rsindex 5c889f274..4f06d5d23 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs@@ -46,6 +46,8 @@ pub(in crate::context_bootstrap) enum ConstructorKind {HashChangeEvent,PageTransitionEvent,DomException,+ RtcError,+ RtcErrorEvent,DomError,QuotaExceededError,CustomElementRegistry,diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc.rs b/moli-renderer-v8/src/context_bootstrap/webrtc.rsindex 6a08991f6..38f8da322 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc.rs@@ -10,7 +10,8 @@ mod ice_candidate;mod ice_candidate_parser;mod session_description;pub(in crate::context_bootstrap) use events::{- rtc_data_channel_event_constructor_callback, rtc_peer_connection_ice_event_constructor_callback,+ rtc_data_channel_event_constructor_callback, rtc_error_event_constructor_callback,+ rtc_peer_connection_ice_event_constructor_callback,};pub(in crate::context_bootstrap) use ice_candidate::rtc_ice_candidate_constructor_callback;pub(in crate::context_bootstrap) use session_description::rtc_session_description_constructor_callback;@@ -219,6 +220,7 @@ pub(in crate::context_bootstrap) fn install_webrtc_template_bindings<'s>("RTCPeerConnection" => {RtcPeerConnectionPrototypeDeclaration::initialize_prototype_template(scope, prototype);}+ "RTCErrorEvent" => events::install_event_template_bindings(scope, template, interface_name),"RTCRtpReceiver" => {RtcRtpReceiverConstructorDeclaration::initialize_template(scope, template);}diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc/events.rs b/moli-renderer-v8/src/context_bootstrap/webrtc/events.rsindex 23b2d54df..38c68045a 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc/events.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/events.rs@@ -1,10 +1,13 @@use super::{ice_candidate::ice_candidate_receiver_branded, rtc_data_channel_receiver_branded};use crate::web_api_interfaces;use crate::{- context_bootstrap::events::{initialize_event_object_with_type, parse_event_init},+ context_bootstrap::events::{+ event_private_value, initialize_event_object_with_type, initialize_event_wrapper,+ new_event_state, parse_event_init,+ },util::{apply_webidl_constructor_prototype_fallback, callback_data_index_value, callback_data_item,- get_private_value, throw_type_error, v8str,+ throw_type_error, v8str,},webidl::{self, WebIdlConverter},};@@ -13,10 +16,12 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};const ICE_EVENT_CANDIDATE_SLOT: &str = "__moliRtcIceEventCandidate";const ICE_EVENT_URL_SLOT: &str = "__moliRtcIceEventUrl";const DATA_CHANNEL_EVENT_CHANNEL_SLOT: &str = "__moliRtcDataChannelEventChannel";+const ERROR_EVENT_ERROR_SLOT: &str = "__moliRtcErrorEventError";const EVENT_MEMBER_SLOTS: &[&str] = &[ICE_EVENT_CANDIDATE_SLOT,ICE_EVENT_URL_SLOT,DATA_CHANNEL_EVENT_CHANNEL_SLOT,+ ERROR_EVENT_ERROR_SLOT,];#[derive(WebApiObject)]@@ -39,6 +44,15 @@ struct DataChannelEventObjectDeclaration<'scope> {channel: v8::Local<'scope, v8::Value>,}+#[derive(WebApiObject)]+#[webapi(interface = web_api_interfaces::RTCErrorEvent)]+struct ErrorEventObjectDeclaration<'scope> {+ #[webapi(data_property, enumerable)]+ composed: bool,+ #[webapi(slot = ERROR_EVENT_ERROR_SLOT)]+ error: v8::Local<'scope, v8::Value>,+}+#[derive(WebApiFunctionTemplate)]#[webapi(interface = web_api_interfaces::RTCPeerConnectionIceEvent, receiver, enumerable)]struct IceEventPrototypeDeclaration {@@ -55,6 +69,13 @@ struct DataChannelEventPrototypeDeclaration {channel: (),}+#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::RTCErrorEvent, receiver, enumerable)]+struct ErrorEventPrototypeDeclaration {+ #[webapi(accessor_property, getter = event_member_getter, data = callback_data_index_value(scope, 3))]+ error: (),+}+pub(super) fn install_event_template_bindings<'s>(scope: &mut v8::PinScope<'s, '_, ()>,template: v8::Local<'s, v8::FunctionTemplate>,@@ -68,6 +89,9 @@ pub(super) fn install_event_template_bindings<'s>("RTCDataChannelEvent" => {DataChannelEventPrototypeDeclaration::initialize_prototype_template(scope, prototype)}+ "RTCErrorEvent" => {+ ErrorEventPrototypeDeclaration::initialize_prototype_template(scope, prototype)+ }_ => unreachable!("unsupported WebRTC event interface"),}}@@ -77,7 +101,7 @@ pub(in crate::context_bootstrap) fn rtc_peer_connection_ice_event_constructor_caargs: v8::FunctionCallbackArguments<'s>,rv: v8::ReturnValue<'s, v8::Value>,) {- construct_event(scope, args, rv, false);+ construct_event(scope, args, rv, EventKind::IceCandidate);}pub(in crate::context_bootstrap) fn rtc_data_channel_event_constructor_callback<'s>(@@ -85,19 +109,39 @@ pub(in crate::context_bootstrap) fn rtc_data_channel_event_constructor_callback<args: v8::FunctionCallbackArguments<'s>,rv: v8::ReturnValue<'s, v8::Value>,) {- construct_event(scope, args, rv, true);+ construct_event(scope, args, rv, EventKind::DataChannel);+}++pub(in crate::context_bootstrap) fn rtc_error_event_constructor_callback<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'s, v8::Value>,+) {+ construct_event(scope, args, rv, EventKind::Error);+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum EventKind {+ IceCandidate,+ DataChannel,+ Error,}fn construct_event<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'s, v8::Value>,- is_data_channel_event: bool,+ kind: EventKind,) {- let (name, required_arguments, member) = if is_data_channel_event {- ("RTCDataChannelEvent", 2, "channel")- } else {- ("RTCPeerConnectionIceEvent", 1, "candidate")+ let (name, required_arguments, member, member_interface) = match kind {+ EventKind::IceCandidate => (+ "RTCPeerConnectionIceEvent",+ 1,+ "candidate",+ "RTCIceCandidate",+ ),+ EventKind::DataChannel => ("RTCDataChannelEvent", 2, "channel", "RTCDataChannel"),+ EventKind::Error => ("RTCErrorEvent", 2, "error", "RTCError"),};if !args.is_construct_call() || args.length() < required_arguments {throw_type_error(@@ -137,36 +181,30 @@ fn construct_event<'s>(} else {v8::undefined(scope).into()};- let value = if !is_data_channel_event && value.is_null_or_undefined() {+ let value = if kind == EventKind::IceCandidate && value.is_null_or_undefined() {v8::null(scope).into()} else {- let branded = v8::Local::<v8::Object>::try_from(value)- .ok()- .is_some_and(|object| {- if is_data_channel_event {- rtc_data_channel_receiver_branded(scope, object)- } else {- ice_candidate_receiver_branded(scope, object)- }- });+ let branded =+ v8::Local::<v8::Object>::try_from(value)+ .ok()+ .is_some_and(|object| match kind {+ EventKind::IceCandidate => ice_candidate_receiver_branded(scope, object),+ EventKind::DataChannel => rtc_data_channel_receiver_branded(scope, object),+ EventKind::Error => web_api_interfaces::RTCError::is_instance(scope, object),+ });if !branded {throw_type_error(scope,- &format!(- "{name}.{member} must be a genuine {} object.",- if is_data_channel_event {- "RTCDataChannel"- } else {- "RTCIceCandidate"- }- ),+ &format!("{name}.{member} must be a genuine {member_interface} object."),);return;}value};let mut url = v8::null(scope).into();- if !is_data_channel_event && let Some(init) = init {+ if kind == EventKind::IceCandidate+ && let Some(init) = init+ {let Some(raw) = init.get(scope, v8str(scope, "url").into()) else {return;};@@ -189,18 +227,32 @@ fn construct_event<'s>(url = converted.into();}}- let event = args.this();- initialize_event_object_with_type(scope, event, event_type, bubbles, cancelable);- let initialized = if is_data_channel_event {- DataChannelEventObjectDeclaration::new(composed, value).initialize(scope, event)+ let wrapper = args.this();+ let event = if kind == EventKind::Error {+ new_event_state(scope)} else {- IceEventObjectDeclaration::new(composed, value, url).initialize(scope, event)+ wrapper+ };+ initialize_event_object_with_type(scope, event, event_type, bubbles, cancelable);+ let initialized = match kind {+ EventKind::IceCandidate => {+ IceEventObjectDeclaration::new(composed, value, url).initialize(scope, event)+ }+ EventKind::DataChannel => {+ DataChannelEventObjectDeclaration::new(composed, value).initialize(scope, event)+ }+ EventKind::Error => {+ ErrorEventObjectDeclaration::new(composed, value).initialize(scope, event)+ }};if initialized.is_err() {return;}- apply_webidl_constructor_prototype_fallback(scope, event, args.new_target(), name);- rv.set(event.into());+ if kind == EventKind::Error && initialize_event_wrapper(scope, wrapper, event).is_none() {+ return;+ }+ apply_webidl_constructor_prototype_fallback(scope, wrapper, args.new_target(), name);+ rv.set(wrapper.into());}fn event_member_getter<'s>(@@ -212,7 +264,7 @@ fn event_member_getter<'s>(else {return;};- if let Some(value) = get_private_value(scope, args.this(), slot) {+ if let Some(value) = event_private_value(scope, args.this(), slot) {rv.set(value);} else {throw_type_error(scope, "Illegal invocation");diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex bddb247cc..3a9d7887b 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -43,6 +43,7 @@ mod pointer_capture;mod pointer_lock;mod popup_hyperlinks;mod promise_rejection;+mod rtc_error;mod security_policy;mod security_policy_event_init;mod service_worker_drain;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.js b/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.jsnew file mode 100644index 000000000..95904cb5f--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.js@@ -0,0 +1,222 @@+(() => {+ const rows = [];+ const check = (name, passed) => rows.push({name, passed: !!passed});+ const throws = (fn, Ctor = TypeError) => {+ try { fn(); return false; } catch (error) { return error instanceof Ctor; }+ };+ const throwsExactly = (fn, expected) => {+ try { fn(); return false; } catch (error) { return error === expected; }+ };+ const init = {errorDetail: 'sdp-syntax-error'};+ const numbers = ['receivedAlert', 'sctpCauseCode', 'sdpLineNumber', 'sentAlert'];+ const error = new RTCError(init, 'message');+ check('inheritance', error instanceof RTCError && error instanceof DOMException &&+ error instanceof Error && Object.getPrototypeOf(RTCError.prototype) === DOMException.prototype);+ check('DOMException fields', error.name === 'OperationError' && error.code === 0 &&+ error.message === 'message');+ check('constructor lengths', RTCError.length === 1 && RTCErrorEvent.length === 2);+ check('tags', Object.prototype.toString.call(error) === '[object RTCError]');+ check('new required', throws(() => RTCError(init)));+ for (const value of [undefined, null, {}, true, 1, 'dictionary', Symbol(), 1n,+ {errorDetail: undefined}, {errorDetail: null}, {errorDetail: 'invalid'}]) {+ check('invalid dictionary ' + String(value), throws(() => new RTCError(value)));+ }+ check('missing argument', throws(() => new RTCError()));+ for (const detail of ['data-channel-failure', 'dtls-failure', 'fingerprint-failure',+ 'sctp-failure', 'sdp-syntax-error', 'hardware-encoder-not-available', 'hardware-encoder-error']) {+ check('enum ' + detail, new RTCError({errorDetail: detail}).errorDetail === detail);+ }+ const utf16 = '\ud800\0\udc00';+ for (const [message, expected] of [[undefined, ''], [null, 'null'], [false, 'false'],+ [2n, '2'], [utf16, utf16]]) {+ check('DOMString message ' + String(message), new RTCError(init, message).message === expected);+ }+ check('message default', new RTCError(init).message === '');+ check('Symbol message', throws(() => new RTCError(init, Symbol())));+ check('message conversion exception', throwsExactly(() => new RTCError(init, {+ toString() { throw error; }+ }), error));+ for (const name of numbers) {+ check(name + ' absent', error[name] === null);+ check(name + ' undefined', new RTCError({...init, [name]: undefined})[name] === null);+ check(name + ' null converts to zero', new RTCError({...init, [name]: null})[name] === 0);+ for (const value of [NaN, Infinity, -Infinity]) {+ check(name + ' nonfinite ' + value, new RTCError({...init, [name]: value})[name] === 0);+ }+ const signed = name === 'sctpCauseCode' || name === 'sdpLineNumber';+ for (const [value, expected] of [[-1, signed ? -1 : 4294967295],+ [4294967297, 1], [2147483648, signed ? -2147483648 : 2147483648], [3.9, 3]]) {+ check(name + ' numeric ' + value, new RTCError({...init, [name]: value})[name] === expected);+ }+ check(name + ' BigInt rejects', throws(() => new RTCError({...init, [name]: 1n})));+ check(name + ' Symbol rejects', throws(() => new RTCError({...init, [name]: Symbol()})));+ }+ const dictionaryReads = ['errorDetail', ...numbers];+ const reads = [];+ const dictionary = Object.create({...init, receivedAlert: 2, sctpCauseCode: 3,+ sdpLineNumber: 4, sentAlert: 5});+ const converted = new RTCError(new Proxy(dictionary, {+ get(object, name) { reads.push(name); return object[name]; }+ }), {toString() { reads.push('message'); return utf16; }});+ check('dictionary lexical order before message', reads.join() === [...dictionaryReads, 'message'].join());+ check('inherited dictionary members', converted.receivedAlert === 2 && converted.sctpCauseCode === 3 &&+ converted.sdpLineNumber === 4 && converted.sentAlert === 5 && converted.message === utf16);+ const sentinel = new RangeError('sentinel');+ for (const name of dictionaryReads) {+ const touched = [];+ const bad = new Proxy(dictionary, {get(object, key) {+ touched.push(key);+ if (key === name) throw sentinel;+ return object[key];+ }});+ check('getter failure stops at ' + name, throwsExactly(() => new RTCError(bad, {+ toString() { touched.push('message'); return ''; }+ }), sentinel) && touched.join() === dictionaryReads.slice(0, dictionaryReads.indexOf(name) + 1).join());+ }+ check('enum conversion exception', throwsExactly(() => new RTCError({errorDetail: {+ toString() { throw sentinel; }+ }}), sentinel));+ Object.defineProperty(Object.prototype, 'errorDetail', {+ configurable: true, get() { throw sentinel; }+ });+ try {+ check('null dictionary avoids prototype pollution', throws(() => new RTCError(null)));+ check('undefined dictionary avoids prototype pollution', throws(() => new RTCError(undefined)));+ } finally { delete Object.prototype.errorDetail; }+ let removedMemberRead = false;+ new RTCError({...init, get httpRequestStatusCode() { removedMemberRead = true; return 0; }});+ check('removed dictionary member ignored', !removedMemberRead);++ for (const name of ['errorDetail', ...numbers]) {+ const descriptor = Object.getOwnPropertyDescriptor(RTCError.prototype, name);+ check(name + ' descriptor', descriptor && descriptor.enumerable && descriptor.configurable &&+ descriptor.get.name === 'get ' + name && descriptor.get.length === 0 && !descriptor.set &&+ !Object.hasOwn(error, name));+ const original = error[name];+ error[name] = 'changed';+ check(name + ' readonly', error[name] === original && throws(() => {+ 'use strict'; error[name] = 1;+ }));+ let traps = 0;+ const proxy = new Proxy(error, {get() { traps++; throw sentinel; },+ getPrototypeOf() { traps++; throw sentinel; }});+ const revoked = Proxy.revocable(error, {});+ revoked.revoke();+ for (const receiver of [null, undefined, {}, RTCError.prototype, Object.create(error),+ new DOMException(), proxy, revoked.proxy]) {+ check(name + ' invalid receiver', throws(() => descriptor.get.call(receiver)));+ }+ check(name + ' no author Proxy traps', traps === 0);+ }+ const event = new RTCErrorEvent(utf16, {error, bubbles: true, cancelable: true, composed: true});+ check('event inheritance and payload', event instanceof RTCErrorEvent && event instanceof Event &&+ event.error === error && event.error === event.error && event.type === utf16);+ check('event flags', event.bubbles && event.cancelable && event.composed && !event.isTrusted);+ check('event tag', Object.prototype.toString.call(event) === '[object RTCErrorEvent]');+ let typeConversions = 0;+ check('event arity before conversion', throws(() => new RTCErrorEvent({toString() {+ typeConversions++; return 'error';+ }})) && typeConversions === 0);+ check('event new required', throws(() => RTCErrorEvent('error', {error})));+ for (const dictionary of [undefined, null, {}, true, 1, 'dictionary', Symbol(), 1n,+ {error: null}, {error: undefined}, {error: {}}, {error: new DOMException()},+ {error: Object.create(error)}, {error: new Proxy(error, {})}]) {+ check('event invalid required member', throws(() => new RTCErrorEvent('error', dictionary)));+ }+ const eventReads = [];+ const eventInit = Object.create({bubbles: 1, cancelable: [], composed: 'yes', error});+ const convertedEvent = new RTCErrorEvent({toString() { eventReads.push('type'); return 'converted'; }},+ new Proxy(eventInit, {get(object, name) { eventReads.push(name); return object[name]; }}));+ check('inherited EventInit first', eventReads.join() === 'type,bubbles,cancelable,composed,error' &&+ convertedEvent.error === error && convertedEvent.bubbles && convertedEvent.cancelable && convertedEvent.composed);+ for (const name of ['bubbles', 'cancelable', 'composed', 'error']) {+ check('event dictionary exception ' + name, throwsExactly(() => new RTCErrorEvent('error', {+ ...eventInit, error, get [name]() { throw sentinel; }+ }), sentinel));+ }+ const descriptor = Object.getOwnPropertyDescriptor(RTCErrorEvent.prototype, 'error');+ check('event error descriptor', descriptor && descriptor.enumerable && descriptor.configurable &&+ descriptor.get.name === 'get error' && descriptor.get.length === 0 && !descriptor.set &&+ !Object.hasOwn(event, 'error'));+ for (const receiver of [{}, Event.prototype, new Event('error'), Object.create(event),+ new Proxy(event, {})]) {+ check('event getter invalid receiver', throws(() => descriptor.get.call(receiver)));+ }+ check('event error readonly', throws(() => { 'use strict'; event.error = null; }) && event.error === error);+ const target = new EventTarget();+ let delivered = false;+ target.addEventListener(utf16, received => {+ delivered = received === event && received.error === error && received.target === target &&+ received.currentTarget === target;+ received.preventDefault();+ });+ check('event dispatch', target.dispatchEvent(event) === false && delivered && event.defaultPrevented &&+ event.currentTarget === null);+ event.initEvent('again', false, false);+ check('event reinitialization retains error', event.error === error && event.type === 'again' &&+ !event.defaultPrevented && !event.bubbles && !event.cancelable);+ for (const value of [error, event]) {+ let cloneError;+ try { structuredClone(value); } catch (exception) { cloneError = exception; }+ check('nonserializable ' + value.constructor.name, cloneError instanceof DOMException &&+ cloneError.name === 'DataCloneError');+ }++ const child = document.querySelector('#child').contentWindow;+ const foreignError = new child.RTCError(init, utf16);+ check('foreign DOMException getter', Object.getOwnPropertyDescriptor(DOMException.prototype,+ 'message').get.call(foreignError) === utf16);+ check('foreign required interface', new RTCErrorEvent('error', {error: foreignError}).error === foreignError);+ check('callee realm TypeError', throws(() => new child.RTCError({}), child.TypeError) &&+ throws(() => new child.RTCErrorEvent('error', {error: {}}), child.TypeError));+ check('foreign getter TypeError', throws(() => Object.getOwnPropertyDescriptor(child.RTCError.prototype,+ 'errorDetail').get.call({}), child.TypeError));+ for (const [name, args, member, expected] of [+ ['RTCError', [init, utf16], 'message', utf16],+ ['RTCErrorEvent', ['error', {error: foreignError}], 'error', foreignError]+ ]) {+ const Ctor = window[name];+ class Derived extends Ctor {}+ const derived = new Derived(...args);+ check(name + ' subclass', derived instanceof Derived && derived instanceof Ctor && derived[member] === expected);+ const newTarget = child.Function('');+ newTarget.prototype = 0;+ let prototypeReads = 0;+ const fallback = Reflect.construct(Ctor, args, new Proxy(newTarget, {get(object, key) {+ if (key === 'prototype') prototypeReads++;+ return Reflect.get(object, key);+ }}));+ check(name + ' new target realm fallback', Object.getPrototypeOf(fallback) === child[name].prototype &&+ fallback[member] === expected && prototypeReads === 1);+ }+ {+ const frozenEvent = Object.freeze(new RTCErrorEvent('frozen', {+ error, bubbles: true, cancelable: true, composed: true+ }));+ const target = new EventTarget();+ let deliveries = 0;+ target.addEventListener('frozen', event => {+ check('frozen wrapper during dispatch', event === frozenEvent && event.target === target &&+ event.currentTarget === target && event.error === error && event.composed);+ event.preventDefault();+ deliveries++;+ });+ check('frozen wrapper dispatch cancellation', target.dispatchEvent(frozenEvent) === false &&+ deliveries === 1 && frozenEvent.defaultPrevented && frozenEvent.target === target &&+ frozenEvent.currentTarget === null && frozenEvent.eventPhase === Event.NONE);+ check('frozen wrapper redispatch', target.dispatchEvent(frozenEvent) === false && deliveries === 2 &&+ frozenEvent.type === 'frozen' && frozenEvent.error === error);+ }+ Object.defineProperty(RTCError, Symbol.hasInstance, {+ configurable: true, value() { throw sentinel; }+ });+ try {+ check('interface validation avoids instanceof', new RTCErrorEvent('error', {error}).error === error &&+ throws(() => new RTCErrorEvent('error', {error: {}})));+ } finally { delete RTCError[Symbol.hasInstance]; }+ Object.setPrototypeOf(error, null);+ check('brand survives prototype removal', new RTCErrorEvent('error', {error}).error === error &&+ Object.getOwnPropertyDescriptor(RTCError.prototype, 'errorDetail').get.call(error) === init.errorDetail);+ globalThis.__rtcErrorResults = {rows, passed: rows.filter(row => row.passed).length, total: rows.length};+ return rows.every(row => row.passed) || JSON.stringify(rows.filter(row => !row.passed));+})()diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.rsnew file mode 100644index 000000000..a3c791e7d--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/rtc_error.rs@@ -0,0 +1,13 @@+use super::*;++#[test]+fn rtc_error_and_event_preserve_native_identity_and_webidl_conversion() {+ let mut vm = new_parsed_test_vm(+ "https://rtc-error.test/",+ "<!doctype html><iframe id=child></iframe>",+ );+ let result = vm+ .eval(include_str!("rtc_error.js"))+ .expect("RTCError and RTCErrorEvent should use native WebIDL and Event semantics");+ assert_eq!(result, "true");+}diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rsindex 8633b2b18..662fd1b80 100644--- a/moli-renderer-v8/src/web_api_interfaces.rs+++ b/moli-renderer-v8/src/web_api_interfaces.rs@@ -372,6 +372,8 @@ interfaces! {PushSubscriptionOptions;QuotaExceededError: DOMException;RTCDataChannel: EventTarget;+ RTCError: DOMException;+ RTCErrorEvent: Event;RTCIceCandidate;RTCPeerConnection: EventTarget;RTCPeerConnectionIceEvent: Event;