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): construct ICE error events with native fields
ldm0c5d665cad81f
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rsindex c669ef97c..0b3c3b3d5 100644--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs@@ -651,6 +651,14 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(.length(1).build(scope)}+ ConstructorKind::RtcPeerConnectionIceErrorEvent => {+ v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!(+ web_api_interfaces::RTCPeerConnectionIceErrorEvent,+ super::super::webrtc::rtc_peer_connection_ice_error_event_constructor+ ))+ .length(2)+ .build(scope)+ }ConstructorKind::RtcDataChannelEvent => {v8::FunctionTemplate::builder(rtc_data_channel_event_constructor_callback).length(2)diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rsindex 1a33bffd9..34e190407 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs@@ -1007,6 +1007,10 @@ const CONSTRUCTOR_SPECS_AFTER_STREAMS: &[ConstructorSpec] = &[interface: web_api_interfaces::RTCDataChannelEvent::DESCRIPTOR,kind: ConstructorKind::RtcDataChannelEvent,},+ ConstructorSpec {+ interface: web_api_interfaces::RTCPeerConnectionIceErrorEvent::DESCRIPTOR,+ kind: ConstructorKind::RtcPeerConnectionIceErrorEvent,+ },ConstructorSpec {interface: web_api_interfaces::RTCRtpReceiver::DESCRIPTOR,kind: ConstructorKind::Illegal,diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rsindex 4f06d5d23..5e929d3dc 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs@@ -105,6 +105,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind {RtcIceCandidate,RtcSessionDescription,RtcPeerConnectionIceEvent,+ RtcPeerConnectionIceErrorEvent,RtcDataChannelEvent,Navigator,WorkerNavigator,diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc.rs b/moli-renderer-v8/src/context_bootstrap/webrtc.rsindex 38f8da322..eeba3064a 100644--- a/moli-renderer-v8/src/context_bootstrap/webrtc.rs+++ b/moli-renderer-v8/src/context_bootstrap/webrtc.rs@@ -8,12 +8,14 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};mod events;mod ice_candidate;mod ice_candidate_parser;+mod ice_error_event;mod session_description;pub(in crate::context_bootstrap) use events::{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 ice_error_event::rtc_peer_connection_ice_error_event_constructor;pub(in crate::context_bootstrap) use session_description::rtc_session_description_constructor_callback;const RTC_PEER_CONNECTION_CONFIGURATION_SLOT: &str = "__moliRtcPeerConnectionConfiguration";@@ -208,6 +210,7 @@ pub(in crate::context_bootstrap) fn install_webrtc_template_bindings<'s>() {let prototype = template.prototype_template(scope);match interface_name {+ "RTCPeerConnectionIceErrorEvent" => ice_error_event::install(scope, prototype),"RTCPeerConnectionIceEvent" | "RTCDataChannelEvent" => {events::install_event_template_bindings(scope, template, interface_name)}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.rsnew file mode 100644index 000000000..9fdd71506--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/ice_error_event.rs@@ -0,0 +1,197 @@+use crate::{+ context_bootstrap::events::{+ event_private_value, initialize_event_object_with_type, initialize_event_wrapper,+ new_event_state,+ },+ util::{+ apply_webidl_constructor_prototype_fallback, callback_data_index_value, callback_data_item,+ throw_type_error,+ },+ web_api_interfaces, webidl,+};+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+use webidl::WebIdlDictionary;++const ADDRESS_SLOT: &str = "__moliRtcIceErrorAddress";+const PORT_SLOT: &str = "__moliRtcIceErrorPort";+const URL_SLOT: &str = "__moliRtcIceErrorUrl";+const ERROR_CODE_SLOT: &str = "__moliRtcIceErrorCode";+const ERROR_TEXT_SLOT: &str = "__moliRtcIceErrorText";+const PAYLOAD_SLOTS: &[&str] = &[+ ADDRESS_SLOT,+ PORT_SLOT,+ URL_SLOT,+ ERROR_CODE_SLOT,+ ERROR_TEXT_SLOT,+];++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "RTCPeerConnectionIceErrorEventInit")]+struct Init {+ // EventInit precedes derived members, which are converted lexically.+ #[webidl(default = false)]+ bubbles: bool,+ #[webidl(default = false)]+ cancelable: bool,+ #[webidl(default = false)]+ composed: bool,+ #[webidl(nullable, converter = "raw")]+ address: Option<webidl::DomString16>,+ #[webidl(required)]+ error_code: u16,+ #[webidl(default = "", converter = "usv_string")]+ error_text: String,+ #[webidl(nullable)]+ port: Option<u16>,+ #[webidl(default = "", converter = "usv_string")]+ url: String,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "RTCPeerConnectionIceErrorEvent")]+struct Args {+ #[webidl(required, converter = "raw")]+ event_type: webidl::DomString16,+ #[webidl(required, with = parse_init_arg)]+ init: Init,+}++fn parse_init_arg<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+ index: i32,+) -> Result<Init, webidl::WebIdlError> {+ let object = webidl::dictionary_value(+ args.get(index),+ webidl::Context::argument("RTCPeerConnectionIceErrorEvent", (index + 1) as usize),+ )?+ .ok_or_else(|| {+ webidl::WebIdlError::missing_required(webidl::Context::member(+ "RTCPeerConnectionIceErrorEventInit",+ "errorCode",+ ))+ })?;+ 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 {+ #[webapi(accessor_property, getter = payload_getter, data = callback_data_index_value(scope, 0))]+ address: (),+ #[webapi(accessor_property, getter = payload_getter, data = callback_data_index_value(scope, 1))]+ port: (),+ #[webapi(accessor_property, getter = payload_getter, data = callback_data_index_value(scope, 2))]+ url: (),+ #[webapi(accessor_property, getter = payload_getter, data = callback_data_index_value(scope, 3))]+ error_code: (),+ #[webapi(accessor_property, getter = payload_getter, data = callback_data_index_value(scope, 4))]+ error_text: (),+}++pub(super) fn install<'s>(+ scope: &mut v8::PinScope<'s, '_, ()>,+ prototype: v8::Local<'s, v8::ObjectTemplate>,+) {+ PrototypeDeclaration::initialize_prototype_template(scope, prototype);+}++pub(in crate::context_bootstrap) fn rtc_peer_connection_ice_error_event_constructor<'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, "RTCPeerConnectionIceErrorEvent requires 'new'.");+ return;+ }+ let Some(parsed) = webidl::parse_args::<Args>(scope, &args) else {+ return;+ };+ let Some(event_type) =+ v8::String::new_from_two_byte(scope, &parsed.event_type.0, v8::NewStringType::Normal)+ else {+ 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,+ state,+ event_type,+ parsed.init.bubbles,+ parsed.init.cancelable,+ );+ let declaration = StateDeclaration::new(+ parsed.init.composed,+ address,+ parsed.init.error_code,+ error_text,+ port,+ url,+ );+ if declaration.initialize(scope, state).is_err()+ || initialize_event_wrapper(scope, args.this(), state).is_none()+ {+ return;+ }+ apply_webidl_constructor_prototype_fallback(+ scope,+ args.this(),+ args.new_target(),+ "RTCPeerConnectionIceErrorEvent",+ );+ rv.set(args.this().into());+}++fn payload_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s, v8::Value>,+) {+ let Some(slot) = callback_data_item(scope, &args, PAYLOAD_SLOTS, "ICE error event attribute")+ else {+ return;+ };+ if let Some(value) = event_private_value(scope, args.this(), slot) {+ rv.set(value);+ }+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/ice_error_event.js b/moli-renderer-v8/src/script_vm/tests/browser_api/ice_error_event.jsnew file mode 100644index 000000000..a8575e1e0--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/ice_error_event.js@@ -0,0 +1,165 @@+(() => {+ const Ctor = RTCPeerConnectionIceErrorEvent;+ const rows = [];+ const check = (name, passed) => rows.push({name, passed: !!passed});+ const throws = (fn, Expected = TypeError) => {+ try { fn(); return false; } catch (error) { return error instanceof Expected; }+ };+ const throwsExactly = (fn, expected) => {+ try { fn(); return false; } catch (error) { return error === expected; }+ };+ const minimal = {errorCode: 701};+ const empty = new Ctor('error', minimal);+ const raw = '\ud800\0\udc00';+ const scalar = '\ufffd\0\ufffd';+ const payload = {address: raw, port: 4711, errorCode: 703, errorText: raw, url: raw};+ const event = new Ctor(raw, {...payload, bubbles: true, cancelable: true, composed: true});+ check('inheritance', event instanceof Ctor && event instanceof Event &&+ Object.getPrototypeOf(Ctor.prototype) === Event.prototype);+ check('tag', Object.prototype.toString.call(event) === '[object RTCPeerConnectionIceErrorEvent]');+ check('constructor length', Ctor.length === 2);+ check('default payload', empty.address === null && empty.port === null &&+ empty.url === '' && empty.errorText === '' && empty.errorCode === 701);+ check('EventInit defaults', !empty.bubbles && !empty.cancelable && !empty.composed && !empty.isTrusted);+ check('DOMString code units', event.type === raw && event.address === raw);+ check('USVString scalar values', event.url === scalar && event.errorText === scalar);+ check('explicit payload', event.port === 4711 && event.errorCode === 703);+ check('EventInit flags', event.bubbles && event.cancelable && event.composed && !event.isTrusted);+ check('new required', throws(() => Ctor('error', minimal)));+ check('missing type', throws(() => new Ctor()));+ let typeConversions = 0;+ check('arity before conversion', throws(() => new Ctor({toString() {+ typeConversions++; return 'type';+ }})) && typeConversions === 0);+ check('Symbol type', throws(() => new Ctor(Symbol(), minimal)));+ check('undefined type converts', new Ctor(undefined, minimal).type === 'undefined');+ check('null type converts', new Ctor(null, minimal).type === 'null');+ for (const init of [undefined, null, {}, true, 1, 'dictionary', Symbol(), 1n, {errorCode: undefined}]) {+ check('invalid dictionary', throws(() => new Ctor('error', init)));+ }+ check('null required number converts', new Ctor('error', {errorCode: null}).errorCode === 0);+ for (const [value, expected] of [[-1, 65535], [65537, 1], [65535, 65535], [3.9, 3],+ [-3.9, 65533], [NaN, 0], [Infinity, 0], [-Infinity, 0], [false, 0], ['65537', 1]]) {+ const converted = new Ctor('error', {errorCode: value, port: value});+ check('unsigned short ' + String(value), converted.errorCode === expected && converted.port === expected);+ }+ for (const name of ['port', 'errorCode']) {+ check(name + ' BigInt rejects', throws(() => new Ctor('error', {...minimal, [name]: 1n})));+ check(name + ' Symbol rejects', throws(() => new Ctor('error', {...minimal, [name]: Symbol()})));+ }+ for (const nullish of [null, undefined]) {+ const converted = new Ctor('error', {...minimal, address: nullish, port: nullish});+ check('nullable address and port', converted.address === null && converted.port === null);+ }+ check('nullable number object converts', new Ctor('error', {...minimal,+ port: {valueOf() { return null; }}+ }).port === 0);+ check('synthetic payload members are independent', new Ctor('error', {...minimal, port: 5}).port === 5);+ for (const name of ['address', 'url', 'errorText']) {+ check(name + ' Symbol rejects', throws(() => new Ctor('error', {...minimal, [name]: Symbol()})));+ for (const [value, expected] of [[false, 'false'], [2n, '2'], ['', ''], ['\ud83d\ude00', '\ud83d\ude00']]) {+ check(name + ' string conversion ' + String(value), new Ctor('error', {...minimal, [name]: value})[name] === expected);+ }+ }+ for (const name of ['url', 'errorText']) {+ check(name + ' null stringifies', new Ctor('error', {...minimal, [name]: null})[name] === 'null');+ check(name + ' undefined defaults', new Ctor('error', {...minimal, [name]: undefined})[name] === '');+ }+ const names = ['bubbles', 'cancelable', 'composed', 'address', 'errorCode', 'errorText', 'port', 'url'];+ const reads = [];+ const dictionary = Object.create({...payload, bubbles: 1, cancelable: [], composed: 'yes'});+ const converted = new Ctor({toString() { reads.push('type'); return 'converted'; }},+ new Proxy(dictionary, {get(object, name) { reads.push(name); return object[name]; }}));+ check('inherited dictionary order', reads.join() === ['type', ...names].join());+ check('inherited dictionary values', converted.address === raw && converted.url === scalar &&+ converted.errorText === scalar && converted.errorCode === 703 && converted.port === 4711 &&+ converted.bubbles && converted.cancelable && converted.composed);+ const sentinel = new RangeError('sentinel');+ for (const name of names) {+ const touched = [];+ const dictionary = new Proxy({...payload}, {get(object, key) {+ touched.push(key);+ if (key === name) throw sentinel;+ return object[key];+ }});+ check('getter failure stops at ' + name, throwsExactly(() => new Ctor('error', dictionary), sentinel) &&+ touched.join() === names.slice(0, names.indexOf(name) + 1).join());+ }+ check('type conversion exception', throwsExactly(() => new Ctor({toString() { throw sentinel; }}, minimal), sentinel));+ for (const name of ['address', 'errorCode', 'errorText', 'port', 'url']) {+ check(name + ' conversion exception', throwsExactly(() => new Ctor('error', {...minimal,+ [name]: {toString() { throw sentinel; }, valueOf() { throw sentinel; }}+ }), sentinel));+ }+ const touched = [];+ check('missing required member stops conversion', throws(() => new Ctor('error', new Proxy({}, {+ get(object, key) { touched.push(key); }+ }))) && touched.join() === 'bubbles,cancelable,composed,address,errorCode');+ Object.defineProperty(Object.prototype, 'bubbles', {configurable: true, get() { throw sentinel; }});+ try {+ check('null dictionary avoids prototype pollution', throws(() => new Ctor('error', null)));+ check('undefined dictionary avoids prototype pollution', throws(() => new Ctor('error', undefined)));+ } finally { delete Object.prototype.bubbles; }+ let hostCandidateRead = false;+ new Ctor('error', {...minimal, get hostCandidate() { hostCandidateRead = true; return 'legacy'; }});+ check('obsolete dictionary member ignored', !hostCandidateRead);+ check('obsolete attribute absent', !('hostCandidate' in Ctor.prototype));+ for (const [name, expected] of Object.entries({...payload, errorText: scalar, url: scalar})) {+ const descriptor = Object.getOwnPropertyDescriptor(Ctor.prototype, name);+ check(name + ' descriptor', descriptor && descriptor.enumerable && descriptor.configurable &&+ !descriptor.set && descriptor.get.name === 'get ' + name && descriptor.get.length === 0 && !Object.hasOwn(event, name));+ event[name] = 'changed';+ check(name + ' readonly', event[name] === expected && throws(() => { 'use strict'; event[name] = null; }));+ let traps = 0;+ const proxy = new Proxy(event, {get() { traps++; throw sentinel; }, getPrototypeOf() { traps++; throw sentinel; }});+ const revoked = Proxy.revocable(event, {});+ revoked.revoke();+ for (const receiver of [undefined, null, {}, Ctor.prototype, Event.prototype, new Event('error'),+ Object.create(event), proxy, revoked.proxy]) {+ check(name + ' invalid receiver', throws(() => descriptor.get.call(receiver)));+ }+ check(name + ' no author Proxy traps', traps === 0);+ }+ for (const name of ['type', 'bubbles', 'cancelable', 'composed']) {+ check(name + ' Event field readonly', throws(() => { 'use strict'; event[name] = 'changed'; }));+ }+ const target = new EventTarget();+ let delivered = false;+ target.addEventListener(raw, received => {+ delivered = received === event && received.address === raw && received.target === target &&+ received.currentTarget === target;+ received.preventDefault();+ });+ check('dispatch and cancellation', target.dispatchEvent(event) === false && delivered && event.defaultPrevented &&+ event.currentTarget === null && !event.isTrusted);+ event.initEvent('again', false, false);+ check('reinitialization', event.type === 'again' && !event.bubbles && !event.cancelable && !event.defaultPrevented);+ for (const [name, expected] of Object.entries({...payload, errorText: scalar, url: scalar})) {+ check(name + ' payload after initEvent', event[name] === expected);+ }+ const child = document.querySelector('#child').contentWindow;+ const foreign = new child.RTCPeerConnectionIceErrorEvent(raw, payload);+ for (const [name, expected] of Object.entries({...payload, errorText: scalar, url: scalar})) {+ check(name + ' cross realm getter', Object.getOwnPropertyDescriptor(Ctor.prototype, name).get.call(foreign) === expected);+ check(name + ' callee realm receiver error', throws(() => Object.getOwnPropertyDescriptor(+ child.RTCPeerConnectionIceErrorEvent.prototype, name).get.call({}), child.TypeError));+ }+ check('callee realm constructor error', throws(() => new child.RTCPeerConnectionIceErrorEvent('error', {}), child.TypeError));+ class Derived extends Ctor {}+ const derived = new Derived('derived', payload);+ check('subclass', derived instanceof Derived && derived instanceof Ctor && derived.port === payload.port);+ const newTarget = child.Function('');+ newTarget.prototype = 0;+ let prototypeReads = 0;+ const fallback = Reflect.construct(Ctor, ['error', payload], new Proxy(newTarget, {get(object, key) {+ if (key === 'prototype') prototypeReads++;+ return Reflect.get(object, key);+ }}));+ check('new target realm fallback', Object.getPrototypeOf(fallback) === child.RTCPeerConnectionIceErrorEvent.prototype &&+ fallback.address === raw && prototypeReads === 1);+ Object.setPrototypeOf(event, null);+ check('brand survives prototype removal', Object.getOwnPropertyDescriptor(Ctor.prototype, 'errorCode').get.call(event) === 703 &&+ Object.getOwnPropertyDescriptor(Event.prototype, 'type').get.call(event) === 'again');+ globalThis.__iceErrorResults = {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/ice_error_event.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/ice_error_event.rsnew file mode 100644index 000000000..3c6dcbf82--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/ice_error_event.rs@@ -0,0 +1,13 @@+use super::*;++#[test]+fn ice_error_event_converts_payloads_and_preserves_native_event_semantics() {+ let mut vm = new_parsed_test_vm(+ "https://ice-error-event.test/",+ "<!doctype html><iframe id=child></iframe>",+ );+ let result = vm+ .eval(include_str!("ice_error_event.js"))+ .expect("ICE error events should retain WebIDL conversion and native Event identity");+ assert_eq!(result, "true");+}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 3a9d7887b..8be94b647 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@@ -24,6 +24,7 @@ mod fontface_descriptors;mod gamepad;mod history_worlds;mod ice_candidate;+mod ice_error_event;mod idle_callbacks;mod idle_detection;mod images;diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rsindex 662fd1b80..5d10ff52d 100644--- a/moli-renderer-v8/src/web_api_interfaces.rs+++ b/moli-renderer-v8/src/web_api_interfaces.rs@@ -378,6 +378,7 @@ interfaces! {RTCPeerConnection: EventTarget;RTCPeerConnectionIceEvent: Event;RTCDataChannelEvent: Event;+ RTCPeerConnectionIceErrorEvent: Event;RTCRtpReceiver;RTCSessionDescription;RadioNodeList: NodeList;