Skip to content

armgit / moli

Public Imported from GitHub
0

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

feat(webrtc): implement RTCSessionDescription data model

ldm0db559629b6e1
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
index e82e3f33f..3531f1f07 100644
--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
@@ -55,7 +55,10 @@ use super::super::{
build_audio_context_constructor_template, build_audio_worklet_node_constructor_template,
offline_audio_context_constructor_callback,
},
- webrtc::{rtc_ice_candidate_constructor_callback, rtc_peer_connection_constructor_callback},
+ webrtc::{
+ rtc_ice_candidate_constructor_callback, rtc_peer_connection_constructor_callback,
+ rtc_session_description_constructor_callback,
+ },
websocket::{
websocket_constructor_callback, websocket_error_constructor_callback,
websocket_stream_constructor_callback,
@@ -439,6 +442,11 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(
.length(0)
.build(scope)
}
+ ConstructorKind::RtcSessionDescription => {
+ v8::FunctionTemplate::builder(rtc_session_description_constructor_callback)
+ .length(1)
+ .build(scope)
+ }
ConstructorKind::Navigator
| ConstructorKind::WorkerNavigator
| ConstructorKind::Permissions
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index 1a689469e..a14b5b773 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -1829,6 +1829,7 @@ pub(crate) fn finish_context_bootstrap(
("WebSocketStream", "WebSocketStream"),
("RTCPeerConnection", "RTCPeerConnection"),
("RTCIceCandidate", "RTCIceCandidate"),
+ ("RTCSessionDescription", "RTCSessionDescription"),
("RTCRtpReceiver", "RTCRtpReceiver"),
("RTCDataChannel", "RTCDataChannel"),
("Blob", "Blob"),
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
index 2422dbe58..7450445e0 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
@@ -1036,6 +1036,11 @@ const CONSTRUCTOR_SPECS_AFTER_STREAMS: &[ConstructorSpec] = &[
parent: None,
kind: ConstructorKind::RtcIceCandidate,
},
+ ConstructorSpec {
+ name: "RTCSessionDescription",
+ parent: None,
+ kind: ConstructorKind::RtcSessionDescription,
+ },
ConstructorSpec {
name: "RTCRtpReceiver",
parent: None,
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
index 8e5bbf3da..3c1f2c1cd 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
@@ -87,6 +87,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind {
WebSocket,
RtcPeerConnection,
RtcIceCandidate,
+ RtcSessionDescription,
Navigator,
WorkerNavigator,
Permissions,
diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc.rs b/moli-renderer-v8/src/context_bootstrap/webrtc.rs
index 7ef0a632c..9300c4549 100644
--- a/moli-renderer-v8/src/context_bootstrap/webrtc.rs
+++ b/moli-renderer-v8/src/context_bootstrap/webrtc.rs
@@ -6,7 +6,9 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
mod ice_candidate;
mod ice_candidate_parser;
+mod session_description;
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;
const RTC_PEER_CONNECTION_BRAND_SLOT: &str = "__moliRtcPeerConnectionBrand";
const RTC_PEER_CONNECTION_CONFIGURATION_SLOT: &str = "__moliRtcPeerConnectionConfiguration";
@@ -125,7 +127,7 @@ struct RtcDataChannelObjectDeclaration<'scope> {
#[derive(WebApiObject)]
#[webapi(interface = "Object")]
-struct RtcSessionDescriptionDeclaration<'scope> {
+struct RtcSessionDescriptionInitDeclaration<'scope> {
#[webapi(data_property, enumerable)]
r#type: v8::Local<'scope, v8::String>,
#[webapi(data_property, enumerable)]
@@ -209,6 +211,9 @@ pub(in crate::context_bootstrap) fn install_webrtc_template_bindings<'s>(
"RTCIceCandidate" => {
ice_candidate::install_ice_candidate_template_bindings(scope, template)
}
+ "RTCSessionDescription" => {
+ session_description::install_session_description_template_bindings(scope, template)
+ }
"RTCPeerConnection" => {
RtcPeerConnectionPrototypeDeclaration::initialize_prototype_template(scope, prototype);
}
@@ -369,7 +374,7 @@ fn rtc_peer_connection_create_offer_callback<'s>(
rv.set_undefined();
return;
};
- let offer = RtcSessionDescriptionDeclaration::new(v8str(scope, "offer"), sdp)
+ let offer = RtcSessionDescriptionInitDeclaration::new(v8str(scope, "offer"), sdp)
.bind(scope)
.expect("RTC offer declaration should bind");
set_resolved_promise(scope, &mut rv, offer.into());
diff --git a/moli-renderer-v8/src/context_bootstrap/webrtc/session_description.rs b/moli-renderer-v8/src/context_bootstrap/webrtc/session_description.rs
new file mode 100644
index 000000000..e948dca93
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/webrtc/session_description.rs
@@ -0,0 +1,161 @@
+use super::RtcSessionDescriptionInitDeclaration;
+use crate::{
+ util::{
+ apply_webidl_constructor_prototype_fallback, callback_data_index_value, callback_data_item,
+ get_private_value, throw_type_error, v8str,
+ },
+ webidl,
+};
+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
+
+const DESCRIPTION_TYPE_SLOT: &str = "__moliRtcSessionDescriptionType";
+const DESCRIPTION_SDP_SLOT: &str = "__moliRtcSessionDescriptionSdp";
+const DESCRIPTION_SLOTS: &[&str] = &[DESCRIPTION_TYPE_SLOT, DESCRIPTION_SDP_SLOT];
+
+#[derive(WebApiObject)]
+#[webapi(interface = "RTCSessionDescription")]
+struct SessionDescriptionObjectDeclaration<'scope> {
+ #[webapi(slot = DESCRIPTION_TYPE_SLOT)]
+ r#type: v8::Local<'scope, v8::String>,
+ #[webapi(slot = DESCRIPTION_SDP_SLOT)]
+ sdp: v8::Local<'scope, v8::String>,
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(name = "RTCSessionDescription", enumerable)]
+struct SessionDescriptionPrototypeDeclaration {
+ #[webapi(accessor_property, getter = description_attribute_getter, data = callback_data_index_value(scope, 0))]
+ r#type: (),
+ #[webapi(accessor_property, getter = description_attribute_getter, data = callback_data_index_value(scope, 1))]
+ sdp: (),
+ #[webapi(method = "toJSON", length = 0, callback = description_to_json_callback)]
+ to_json: (),
+}
+
+pub(super) fn install_session_description_template_bindings<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ template: v8::Local<'s, v8::FunctionTemplate>,
+) {
+ SessionDescriptionPrototypeDeclaration::initialize_prototype_template(
+ scope,
+ template.prototype_template(scope),
+ );
+}
+
+pub(in crate::context_bootstrap) fn rtc_session_description_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, "RTCSessionDescription constructor requires 'new'.");
+ return;
+ }
+ let dictionary = match webidl::dictionary_value(
+ args.get(0),
+ webidl::Context::argument("RTCSessionDescription", 1),
+ ) {
+ Ok(Some(dictionary)) => dictionary,
+ Ok(None) => {
+ throw_type_error(scope, "RTCSessionDescriptionInit requires type.");
+ return;
+ }
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return;
+ }
+ };
+ // WebIDL converts dictionary members in lexical order, including defaults.
+ // SDP is a DOMString: retain the V8 string, including lone UTF-16 surrogates.
+ // Its contents are not validated by this legacy data-model constructor.
+ let Some(raw_sdp) = dictionary.get(scope, v8str(scope, "sdp").into()) else {
+ return;
+ };
+ let sdp = if raw_sdp.is_undefined() {
+ v8str(scope, "")
+ } else {
+ if raw_sdp.is_symbol() {
+ throw_type_error(scope, "Cannot convert a Symbol to a DOMString.");
+ return;
+ }
+ let Some(sdp) = raw_sdp.to_string(scope) else {
+ return;
+ };
+ sdp
+ };
+ let Some(raw_type) = dictionary.get(scope, v8str(scope, "type").into()) else {
+ return;
+ };
+ if raw_type.is_undefined() {
+ throw_type_error(scope, "RTCSessionDescriptionInit requires type.");
+ return;
+ }
+ if raw_type.is_symbol() {
+ throw_type_error(scope, "Cannot convert a Symbol to an RTCSdpType.");
+ return;
+ }
+ let Some(kind) = raw_type.to_string(scope) else {
+ return;
+ };
+ if !matches!(
+ kind.to_rust_string_lossy(scope).as_str(),
+ "offer" | "pranswer" | "answer" | "rollback"
+ ) {
+ throw_type_error(scope, "Invalid RTCSdpType.");
+ return;
+ }
+ if SessionDescriptionObjectDeclaration::new(kind, sdp)
+ .initialize(scope, args.this())
+ .is_err()
+ {
+ return;
+ }
+ apply_webidl_constructor_prototype_fallback(
+ scope,
+ args.this(),
+ args.new_target(),
+ "RTCSessionDescription",
+ );
+ rv.set(args.this().into());
+}
+
+fn description_attribute_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,
+ DESCRIPTION_SLOTS,
+ "RTCSessionDescription attribute",
+ ) else {
+ return;
+ };
+ if let Some(value) = get_private_value(scope, args.this(), slot) {
+ rv.set(value);
+ } else {
+ throw_type_error(scope, "Illegal invocation");
+ }
+}
+
+fn description_to_json_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ let Some(kind) = get_private_value(scope, args.this(), DESCRIPTION_TYPE_SLOT)
+ .and_then(|value| v8::Local::<v8::String>::try_from(value).ok())
+ else {
+ throw_type_error(scope, "Illegal invocation");
+ return;
+ };
+ let Some(sdp) = get_private_value(scope, args.this(), DESCRIPTION_SDP_SLOT)
+ .and_then(|value| v8::Local::<v8::String>::try_from(value).ok())
+ else {
+ return;
+ };
+ if let Ok(json) = RtcSessionDescriptionInitDeclaration::new(kind, sdp).bind(scope) {
+ rv.set(json.into());
+ }
+}
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.rs
index 646146633..d3f2f16b4 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
@@ -29,6 +29,7 @@ mod pointer_lock;
mod promise_rejection;
mod security_policy;
mod service_worker_drain;
+mod session_description;
mod speech_synthesis;
mod storage_access;
mod structured_clone;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/session_description.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/session_description.rs
new file mode 100644
index 000000000..faadaf52b
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/session_description.rs
@@ -0,0 +1,168 @@
+use super::*;
+
+#[test]
+fn rtc_session_description_requires_a_dictionary_with_a_valid_type() {
+ let mut vm = new_storage_test_vm("http://session-description.test/");
+ let result = vm.eval(r#"
+ (() => {
+ const rejects = callback => {
+ try { callback(); return false; } catch (error) { return error instanceof TypeError; }
+ };
+ const checks = [
+ RTCSessionDescription.length === 1,
+ RTCSessionDescription.name === 'RTCSessionDescription',
+ rejects(() => RTCSessionDescription({type: 'offer'})),
+ rejects(() => new RTCSessionDescription())
+ ];
+ for (const value of [undefined, null, {}, true, 3, 'offer', Symbol(), 1n,
+ {type: undefined}, {type: null}, {type: ''}, {type: 'Offer'},
+ {type: ' offer'}, {type: 'answer\0'}, {type: Symbol()}, {type: 1}]) {
+ checks.push(rejects(() => new RTCSessionDescription(value)));
+ }
+ for (const type of ['offer', 'pranswer', 'answer', 'rollback']) {
+ const description = new RTCSessionDescription({type});
+ checks.push(description.type === type, description.sdp === '');
+ const raw = 'not valid SDP\r\n\ud800\0\udc00';
+ const supplied = new RTCSessionDescription({type, sdp: raw});
+ checks.push(supplied.sdp === raw, supplied.toJSON().sdp === raw);
+ }
+ const values = [undefined, null, false, 123, 1n, ['sdp']];
+ for (const sdp of values) {
+ checks.push(new RTCSessionDescription({type: 'offer', sdp}).sdp ===
+ (sdp === undefined ? '' : String(sdp)));
+ }
+ checks.push(rejects(() => new RTCSessionDescription({type: 'offer', sdp: Symbol()})));
+ return checks.every(Boolean);
+ })()
+ "#).expect("RTCSessionDescription should require an RTCSdpType and retain DOMString SDP without validation");
+ assert_eq!(result, "true");
+}
+
+#[test]
+fn rtc_session_description_converts_members_in_order_and_preserves_exceptions() {
+ let mut vm = new_storage_test_vm("https://session-description-conversion.test/");
+ let result = vm.eval(r#"
+ (() => {
+ const reads = [];
+ const dictionary = Object.create({
+ sdp: {toString() { reads.push('convert sdp'); return 'sdp'; }},
+ type: {toString() { reads.push('convert type'); return 'answer'; }}
+ });
+ const description = new RTCSessionDescription(new Proxy(dictionary, {
+ get(target, name) { reads.push(name); return target[name]; }
+ }));
+ const checks = [reads.join(',') === 'sdp,convert sdp,type,convert type',
+ description.type === 'answer', description.sdp === 'sdp'];
+ const error = new RangeError('original exception');
+ for (const member of ['sdp', 'type']) {
+ for (const conversion of [false, true]) {
+ const bad = {type: 'offer'};
+ Object.defineProperty(bad, member, {
+ get() { if (!conversion) throw error; return {toString() { throw error; }}; }
+ });
+ try { new RTCSessionDescription(bad); checks.push(false); }
+ catch (caught) { checks.push(caught === error); }
+ }
+ }
+ let typeRead = false;
+ try {
+ new RTCSessionDescription({sdp: Symbol(), get type() { typeRead = true; return 'offer'; }});
+ checks.push(false);
+ } catch (caught) { checks.push(caught instanceof TypeError, !typeRead); }
+ let sdpRead = false;
+ try { new RTCSessionDescription({get sdp() { sdpRead = true; return ''; }}); checks.push(false); }
+ catch (caught) { checks.push(caught instanceof TypeError, sdpRead); }
+ Object.defineProperty(Object.prototype, 'type', {
+ configurable: true, get() { throw error; }
+ });
+ try {
+ for (const value of [undefined, null]) {
+ try { new RTCSessionDescription(value); checks.push(false); }
+ catch (caught) { checks.push(caught instanceof TypeError); }
+ }
+ } finally { delete Object.prototype.type; }
+ const clone = new RTCSessionDescription(description);
+ checks.push(clone !== description, clone.type === 'answer', clone.sdp === 'sdp');
+ return checks.every(Boolean);
+ })()
+ "#).expect("RTCSessionDescription dictionary conversion should observe WebIDL order and original exceptions");
+ assert_eq!(result, "true");
+}
+
+#[test]
+fn rtc_session_description_has_readonly_branded_attributes_and_default_json() {
+ let mut vm = new_storage_test_vm("https://session-description-prototype.test/");
+ let result = vm.eval(r#"
+ (() => {
+ const description = new RTCSessionDescription({type: 'offer', sdp: 'original'});
+ const rejects = callback => {
+ try { callback(); return false; } catch (error) { return error instanceof TypeError; }
+ };
+ const checks = [description instanceof RTCSessionDescription,
+ Object.prototype.toString.call(description) === '[object RTCSessionDescription]',
+ Object.getOwnPropertyNames(description).length === 0,
+ Object.getPrototypeOf(RTCSessionDescription.prototype) === Object.prototype];
+ const fakes = [undefined, null, {}, RTCSessionDescription.prototype,
+ Object.create(description), new Proxy(description, {})];
+ for (const name of ['type', 'sdp']) {
+ const descriptor = Object.getOwnPropertyDescriptor(RTCSessionDescription.prototype, name);
+ if (!descriptor) return 'missing:' + name;
+ checks.push(descriptor.get.name === 'get ' + name, descriptor.get.length === 0,
+ descriptor.set === undefined, descriptor.enumerable, descriptor.configurable);
+ const original = description[name];
+ description[name] = 'changed';
+ checks.push(description[name] === original,
+ rejects(() => { 'use strict'; description[name] = 'changed'; }));
+ for (const fake of fakes) checks.push(rejects(() => descriptor.get.call(fake)));
+ }
+ const method = Object.getOwnPropertyDescriptor(RTCSessionDescription.prototype, 'toJSON');
+ checks.push(method.value.name === 'toJSON', method.value.length === 0,
+ method.writable, method.enumerable, method.configurable);
+ for (const fake of fakes) checks.push(rejects(() => method.value.call(fake)));
+ const first = description.toJSON();
+ const second = description.toJSON();
+ checks.push(first !== second, Object.getPrototypeOf(first) === Object.prototype,
+ Object.keys(first).join(',') === 'type,sdp',
+ JSON.stringify(description) === '{"type":"offer","sdp":"original"}');
+ for (const name of ['type', 'sdp']) {
+ const descriptor = Object.getOwnPropertyDescriptor(first, name);
+ checks.push(descriptor.writable, descriptor.enumerable, descriptor.configurable);
+ first[name] = 'changed';
+ Object.defineProperty(description, name, {get() { throw new Error('shadow getter'); }});
+ }
+ checks.push(JSON.stringify(description.toJSON()) === '{"type":"offer","sdp":"original"}');
+ return checks.every(Boolean);
+ })()
+ "#).expect("RTCSessionDescription should expose readonly IDL attributes and serialize only internal values");
+ assert_eq!(result, "true");
+}
+
+#[test]
+fn rtc_session_description_preserves_subclasses_and_cross_realm_behavior() {
+ let mut vm = new_parsed_test_vm(
+ "https://session-description-realms.test/",
+ "<!doctype html><iframe></iframe>",
+ );
+ let result = vm.eval(r#"
+ (() => {
+ const child = document.querySelector('iframe').contentWindow;
+ class Derived extends RTCSessionDescription {}
+ const derived = new Derived({type: 'offer'});
+ const foreign = new child.RTCSessionDescription({type: 'answer', sdp: 'foreign'});
+ const newTarget = child.Function('');
+ newTarget.prototype = null;
+ const fallback = Reflect.construct(RTCSessionDescription, [{type: 'rollback'}], newTarget);
+ const json = RTCSessionDescription.prototype.toJSON.call(foreign);
+ const foreignJson = child.RTCSessionDescription.prototype.toJSON.call(derived);
+ return [derived instanceof Derived, derived instanceof RTCSessionDescription,
+ Object.getPrototypeOf(foreign) === child.RTCSessionDescription.prototype,
+ Object.getPrototypeOf(fallback) === child.RTCSessionDescription.prototype,
+ Object.getOwnPropertyDescriptor(RTCSessionDescription.prototype, 'sdp').get.call(foreign) === 'foreign',
+ json.type === 'answer', json.sdp === 'foreign',
+ Object.getPrototypeOf(json) === Object.prototype,
+ Object.getPrototypeOf(foreignJson) === child.Object.prototype
+ ].every(Boolean);
+ })()
+ "#).expect("RTCSessionDescription should use NewTarget prototypes and the toJSON method's realm");
+ assert_eq!(result, "true");
+}