Truly independent web browser
LibWeb: Implement XMLHttpRequest in Rust
Shannon Boothdba755baf549
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rsindex c8903f50f2d..fcda287d151 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs@@ -10,7 +10,9 @@ use core::ffi::c_void;use core::ptr::NonNull;+use ak::Utf16String;use libjs_rust::api::{Gc, Object, Trace};+use liburl_rust::{RustUrl, Url};use crate::bindings::cpp_cell::CppCell;@@ -22,6 +24,17 @@ unsafe extern "C" {id: *mut c_void,on_id: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),);+ fn web_bindings_environment_settings_object_encoding_parse_url(+ settings_object: *mut c_void,+ url: usize,+ parsed_url: *mut c_void,+ on_url: unsafe extern "C" fn(*mut c_void, *const RustUrl),+ );+}++unsafe extern "C" fn on_url(parsed_url: *mut c_void, url: *const RustUrl) {+ // SAFETY: parsed_url is the URL of the caller, and LibWeb lends the URL for the call.+ unsafe { *parsed_url.cast::<Option<Url>>() = Some((*url).to_url()) };}unsafe extern "C" fn on_id(id: *mut c_void, bytes: ak::Span<'_, u8>) {@@ -62,4 +75,19 @@ impl CppEnvironmentSettingsObject {// SAFETY: The global object is live.unsafe { Gc::from_non_null(NonNull::new(global_object.cast()).expect("a settings object has a global object")) }}++ /// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#encoding-parsing-a-url+ pub(crate) fn encoding_parse_url(&self, url: &Utf16String) -> Option<Url> {+ let mut parsed_url = None;+ // SAFETY: The settings object is live, the URL is lent for the call, and the parsed URL outlives it.+ unsafe {+ web_bindings_environment_settings_object_encoding_parse_url(+ self.as_ptr(),+ url.raw_identity(),+ (&raw mut parsed_url).cast(),+ on_url,+ );+ }+ parsed_url+ }}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rsindex bb6f3c96705..85210ed822d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs@@ -35,6 +35,7 @@ unsafe extern "C" {steps: unsafe extern "C" fn(*mut c_void),);fn web_bindings_has_event_listener(event_target: *mut c_void, r#type: ak::Span<'_, u8>) -> bool;+ fn web_bindings_has_event_listeners(event_target: *mut c_void) -> bool;fn web_bindings_event_handler_attribute(event_target: *mut c_void, name: ak::Span<'_, u8>) -> u64;fn web_bindings_set_event_handler_attribute(event_target: *mut c_void, name: ak::Span<'_, u8>, value: u64);fn web_bindings_add_event_listener(@@ -77,6 +78,7 @@ unsafe extern "C" {source: *mut c_void,) -> *mut c_void;fn web_bindings_message_event_data(event: u64) -> u64;+ fn web_bindings_set_has_pending_activity(realm: *mut c_void, event_target: *mut c_void, has_pending_activity: bool);fn web_bindings_set_event_owner(event: *mut c_void, interface_name: u16, owner: *mut c_void);fn web_bindings_event_set_is_trusted(event: *mut c_void, is_trusted: bool);fn web_bindings_dispatch_event(target: *mut c_void, event: *mut c_void) -> bool;@@ -160,6 +162,11 @@ impl CppEventTarget {unsafe { web_bindings_has_event_listener(self.as_ptr(), ak::Span::new(event_type.as_bytes())) }}+ pub(crate) fn has_event_listeners(&self) -> bool {+ // SAFETY: The EventTarget is live.+ unsafe { web_bindings_has_event_listeners(self.as_ptr()) }+ }+/// Adds an event listener for the event type whose callback is the function, with no options,/// https://dom.spec.whatwg.org/#add-an-event-listenerpub(crate) fn add_event_listener(&self, cx: &CallContext, event_type: &str, callback: Gc<FunctionObject>) {@@ -206,6 +213,11 @@ impl CppEventTarget {unsafe { web_bindings_dispatch_event(self.as_ptr(), event.as_ptr()) }}+ pub(crate) fn set_has_pending_activity(&self, realm: Gc<Realm>, has_pending_activity: bool) {+ // SAFETY: The realm and the EventTarget are live.+ unsafe { web_bindings_set_has_pending_activity(realm.as_ptr().cast(), self.as_ptr(), has_pending_activity) };+ }+/// Returns the legacyOutputDidListenersThrowFlag.pub(crate) fn dispatch_event_with_legacy_output_did_listeners_throw_flag(&self, event: &CppEvent) -> bool {// SAFETY: The EventTarget and the event are live.diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rsindex d30be250b10..fbe96788d8b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/global_object.rs@@ -24,6 +24,7 @@ unsafe extern "C" {fn web_bindings_window_as_event_target(window: *mut c_void) -> *mut c_void;fn web_bindings_document_has_navigable(document: *mut c_void) -> bool;fn web_bindings_document_is_fully_active(document: *mut c_void) -> bool;+ fn web_bindings_document_has_been_destroyed(document: *mut c_void) -> bool;fn web_bindings_document_url(document: *mut c_void) -> liburl_rust::RustUrl;fn web_bindings_worker_global_scope_from_global_object(global_object: *mut c_void) -> *mut c_void;fn web_bindings_worker_global_scope_is_closing(worker_global_scope: *mut c_void) -> bool;@@ -123,6 +124,12 @@ impl CppDocument {unsafe { web_bindings_document_is_fully_active(self.0.as_ptr()) }}+ /// https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document+ pub(crate) fn has_been_destroyed(&self) -> bool {+ // SAFETY: The Document is live.+ unsafe { web_bindings_document_has_been_destroyed(self.0.as_ptr()) }+ }+/// Whether the Document's node navigable is not null, https://html.spec.whatwg.org/multipage/document-sequences.html#node-navigablepub(crate) fn has_navigable(&self) -> bool {// SAFETY: The Document is live.diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/body_init.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/body_init.rsnew file mode 100644index 00000000000..242ada876ef--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/body_init.rs@@ -0,0 +1,100 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm};++use crate::bindings::conversions::UsvString;+use crate::bindings::interface::{Ref, cell_into_abi};+use crate::domurl::url_search_params::URLSearchParams;+use crate::fetch::infrastructure::http::bodies::CppBody;+use crate::file_api::blob::AnyBlob;+use crate::xhr::form_data::FormData;++#[repr(u8)]+enum BodyInitKind {+ Blob = 0,+ Bytes = 1,+ FormData = 2,+ URLSearchParams = 3,+ String = 4,+}++#[repr(C)]+struct BodyInitAbi<'a> {+ kind: BodyInitKind,+ cell: *mut c_void,+ bytes: ak::Span<'a, u8>,+ string: usize,+}++unsafe extern "C" {+ fn web_fetch_safely_extract_body(+ realm: *mut c_void,+ object: *const BodyInitAbi<'_>,+ out_type: *mut usize,+ ) -> *mut c_void;+}++/// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit+pub(crate) enum XMLHttpRequestBodyInit {+ Blob(AnyBlob),+ Bytes(Vec<u8>),+ FormData(Ref<FormData>),+ URLSearchParams(Ref<URLSearchParams>),+ String(UsvString),+}++/// https://fetch.spec.whatwg.org/#body-with-type+pub(crate) struct BodyWithType {+ pub(crate) body: CppBody,+ pub(crate) r#type: Option<Utf16String>,+}++/// https://fetch.spec.whatwg.org/#bodyinit-safely-extract+pub(crate) fn safely_extract_body(realm: Gc<Realm>, object: &XMLHttpRequestBodyInit) -> BodyWithType {+ let mut abi = BodyInitAbi {+ kind: BodyInitKind::Bytes,+ cell: core::ptr::null_mut(),+ bytes: ak::Span::new(&[]),+ string: 0,+ };+ match object {+ XMLHttpRequestBodyInit::Blob(blob) => {+ abi.kind = BodyInitKind::Blob;+ abi.cell = blob.clone().cell_into_abi();+ }+ XMLHttpRequestBodyInit::Bytes(bytes) => abi.bytes = ak::Span::new(bytes),+ XMLHttpRequestBodyInit::FormData(form_data) => {+ abi.kind = BodyInitKind::FormData;+ abi.cell = cell_into_abi(*form_data);+ }+ XMLHttpRequestBodyInit::URLSearchParams(url_search_params) => {+ abi.kind = BodyInitKind::URLSearchParams;+ abi.cell = cell_into_abi(*url_search_params);+ }+ XMLHttpRequestBodyInit::String(string) => {+ abi.kind = BodyInitKind::String;+ abi.string = string.as_utf16_string().raw_identity();+ }+ }+ let mut r#type = 0;+ // SAFETY: The realm and the object are live, the object is lent for the call, and LibWeb returns a live body and+ // hands over 0 or the type.+ unsafe {+ let body = CppBody::from_raw(web_fetch_safely_extract_body(+ realm.as_ptr().cast(),+ &raw const abi,+ &raw mut r#type,+ ));+ BodyWithType {+ body,+ r#type: (r#type != 0).then(|| Utf16String::from_raw_owned(r#type)),+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/fetch_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/fetch_controller.rsnew file mode 100644index 00000000000..1025aeed5ed--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/fetch_controller.rs@@ -0,0 +1,72 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use libjs_rust::api::{Gc, Object, Realm, Trace};++use crate::bindings::cpp_cell::CppCell;++unsafe extern "C" {+ fn web_fetch_controller_create(global_object: *mut c_void) -> *mut c_void;+ fn web_fetch_controller_terminate(controller: *mut c_void);+ fn web_fetch_controller_abort(controller: *mut c_void, realm: *mut c_void);+ fn web_fetch_controller_has_report_timing_steps(controller: *mut c_void) -> bool;+ fn web_fetch_controller_report_timing(controller: *mut c_void, global_object: *mut c_void);+}++/// https://fetch.spec.whatwg.org/#fetch-controller+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppFetchController(CppCell);++impl PartialEq for CppFetchController {+ fn eq(&self, other: &Self) -> bool {+ self.as_ptr() == other.as_ptr()+ }+}++impl CppFetchController {+ pub(crate) fn create(global_object: Gc<Object>) -> Self {+ // SAFETY: The global object is live, and LibWeb returns a new, live fetch controller.+ Self(unsafe { CppCell::from_raw(web_fetch_controller_create(global_object.as_ptr().cast())) })+ }++ /// # Safety+ ///+ /// `controller` must be a live fetch controller.+ pub(crate) unsafe fn from_raw(controller: *mut c_void) -> Self {+ // SAFETY: The caller passes a live fetch controller.+ Self(unsafe { CppCell::from_raw(controller) })+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://fetch.spec.whatwg.org/#fetch-controller-terminate+ pub(crate) fn terminate(&self) {+ // SAFETY: The fetch controller is live.+ unsafe { web_fetch_controller_terminate(self.as_ptr()) };+ }++ /// https://fetch.spec.whatwg.org/#fetch-controller-abort+ pub(crate) fn abort(&self, realm: Gc<Realm>) {+ // SAFETY: The fetch controller and the realm are live.+ unsafe { web_fetch_controller_abort(self.as_ptr(), realm.as_ptr().cast()) };+ }++ pub(crate) fn has_report_timing_steps(&self) -> bool {+ // SAFETY: The fetch controller is live.+ unsafe { web_fetch_controller_has_report_timing_steps(self.as_ptr()) }+ }++ /// https://fetch.spec.whatwg.org/#finalize-and-report-timing+ pub(crate) fn report_timing(&self, global_object: Gc<Object>) {+ // SAFETY: The fetch controller and the global object are live.+ unsafe { web_fetch_controller_report_timing(self.as_ptr(), global_object.as_ptr().cast()) };+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/bodies.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/bodies.rsnew file mode 100644index 00000000000..fc32754dde0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/bodies.rs@@ -0,0 +1,41 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use libjs_rust::api::Trace;++use crate::bindings::cpp_cell::CppCell;++unsafe extern "C" {+ fn web_fetch_body_length(body: *mut c_void, out_length: *mut u64) -> bool;+}++/// https://fetch.spec.whatwg.org/#concept-body+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppBody(CppCell);++impl CppBody {+ /// # Safety+ ///+ /// `body` must be a live body.+ pub(crate) unsafe fn from_raw(body: *mut c_void) -> Self {+ // SAFETY: The caller passes a live body.+ Self(unsafe { CppCell::from_raw(body) })+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://fetch.spec.whatwg.org/#concept-body-total-bytes+ pub(crate) fn length(&self) -> Option<u64> {+ let mut length = 0;+ // SAFETY: The body is live, and the length outlives the call.+ unsafe { web_fetch_body_length(self.as_ptr(), &raw mut length) }.then_some(length)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/mod.rsnew file mode 100644index 00000000000..2dab2f4430b--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/mod.rs@@ -0,0 +1,11 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! HTTP, https://fetch.spec.whatwg.org/#http++pub(crate) mod bodies;+pub(crate) mod requests;+pub(crate) mod response_view;diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rsnew file mode 100644index 00000000000..ec6bf6433f0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs@@ -0,0 +1,42 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;+use core::ptr::NonNull;++unsafe extern "C" {+ fn web_fetch_request_done(request: *mut c_void) -> bool;+ fn web_fetch_request_unref(request: *mut c_void);+}++/// https://fetch.spec.whatwg.org/#concept-request+pub(crate) struct CppRequest(NonNull<c_void>);++impl CppRequest {+ /// # Safety+ ///+ /// `request` must be a request that LibWeb hands over a reference to.+ pub(crate) unsafe fn adopt(request: *mut c_void) -> Self {+ Self(NonNull::new(request).expect("LibWeb hands over a request"))+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://fetch.spec.whatwg.org/#done-flag+ pub(crate) fn done(&self) -> bool {+ // SAFETY: This holds a reference to the request.+ unsafe { web_fetch_request_done(self.0.as_ptr()) }+ }+}++impl Drop for CppRequest {+ fn drop(&mut self) {+ // SAFETY: This holds a reference to the request, which it lets go of.+ unsafe { web_fetch_request_unref(self.0.as_ptr()) };+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/response_view.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/response_view.rsnew file mode 100644index 00000000000..8beef62d9ca--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/response_view.rs@@ -0,0 +1,155 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::Trace;+use libwebcommon_rust::mime_sniff::mime_type::MimeType;++use crate::bindings::cpp_cell::CppCell;++unsafe extern "C" {+ fn web_fetch_response_is_network_error(response: *mut c_void) -> bool;+ fn web_fetch_response_aborted(response: *mut c_void) -> bool;+ fn web_fetch_response_status(response: *mut c_void) -> u16;+ fn web_fetch_response_status_message(+ response: *mut c_void,+ bytes: *mut c_void,+ on_bytes: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ );+ fn web_fetch_response_get_header(+ response: *mut c_void,+ name: ak::Span<'_, u8>,+ bytes: *mut c_void,+ on_bytes: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ ) -> bool;+ fn web_fetch_response_sort_and_combine(+ response: *mut c_void,+ headers: *mut c_void,+ on_header: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, u8>),+ );+ fn web_fetch_response_extract_length(response: *mut c_void, out_length: *mut u64) -> bool;+ fn web_fetch_response_extract_mime_type(response: *mut c_void) -> usize;+ fn web_fetch_response_url(response: *mut c_void, exclude_fragment: bool) -> usize;+ fn web_fetch_response_has_body(response: *mut c_void) -> bool;+ fn web_fetch_response_network_error_message(response: *mut c_void) -> usize;+}++unsafe extern "C" fn on_bytes(bytes: *mut c_void, lent: ak::Span<'_, u8>) {+ // SAFETY: bytes is the vector of the caller, and LibWeb lends the bytes for the call.+ unsafe { *bytes.cast::<Vec<u8>>() = lent.as_slice().to_vec() };+}++unsafe extern "C" fn on_header(headers: *mut c_void, name: ak::Span<'_, u8>, value: ak::Span<'_, u8>) {+ // SAFETY: headers is the list of the caller, and LibWeb lends the name and the value for the call.+ unsafe {+ (*headers.cast::<Vec<(Vec<u8>, Vec<u8>)>>()).push((name.as_slice().to_vec(), value.as_slice().to_vec()));+ }+}++/// # Safety+///+/// `string` must be 0 or a raw string that LibWeb hands over.+unsafe fn string_if_not_null(string: usize) -> Option<Utf16String> {+ // SAFETY: The caller passes a raw string that LibWeb hands over.+ (string != 0).then(|| unsafe { Utf16String::from_raw_owned(string) })+}++/// https://fetch.spec.whatwg.org/#concept-response+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppResponseView(CppCell);++impl CppResponseView {+ /// # Safety+ ///+ /// `response` must be a live ResponseView.+ pub(crate) unsafe fn from_raw(response: *mut c_void) -> Self {+ // SAFETY: The caller passes a live ResponseView.+ Self(unsafe { CppCell::from_raw(response) })+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ /// https://fetch.spec.whatwg.org/#concept-network-error+ pub(crate) fn is_network_error(&self) -> bool {+ // SAFETY: The response is live.+ unsafe { web_fetch_response_is_network_error(self.as_ptr()) }+ }++ /// https://fetch.spec.whatwg.org/#concept-response-aborted+ pub(crate) fn aborted(&self) -> bool {+ // SAFETY: The response is live.+ unsafe { web_fetch_response_aborted(self.as_ptr()) }+ }++ /// https://fetch.spec.whatwg.org/#concept-response-status+ pub(crate) fn status(&self) -> u16 {+ // SAFETY: The response is live.+ unsafe { web_fetch_response_status(self.as_ptr()) }+ }++ /// https://fetch.spec.whatwg.org/#concept-response-status-message+ pub(crate) fn status_message(&self) -> Vec<u8> {+ let mut bytes = Vec::new();+ // SAFETY: The response is live, and the bytes outlive the call.+ unsafe { web_fetch_response_status_message(self.as_ptr(), (&raw mut bytes).cast(), on_bytes) };+ bytes+ }++ /// https://fetch.spec.whatwg.org/#concept-header-list-get+ pub(crate) fn get_header(&self, name: &[u8]) -> Option<Vec<u8>> {+ let mut bytes = Vec::new();+ // SAFETY: The response is live, the name is lent for the call, and the bytes outlive it.+ unsafe { web_fetch_response_get_header(self.as_ptr(), ak::Span::new(name), (&raw mut bytes).cast(), on_bytes) }+ .then_some(bytes)+ }++ /// https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine+ pub(crate) fn sort_and_combine(&self) -> Vec<(Vec<u8>, Vec<u8>)> {+ let mut headers = Vec::new();+ // SAFETY: The response is live, and the headers outlive the call.+ unsafe { web_fetch_response_sort_and_combine(self.as_ptr(), (&raw mut headers).cast(), on_header) };+ headers+ }++ /// https://fetch.spec.whatwg.org/#header-list-extract-a-length+ pub(crate) fn extract_length(&self) -> Option<u64> {+ let mut length = 0;+ // SAFETY: The response is live, and the length outlives the call.+ unsafe { web_fetch_response_extract_length(self.as_ptr(), &raw mut length) }.then_some(length)+ }++ /// https://fetch.spec.whatwg.org/#concept-header-extract-mime-type+ pub(crate) fn extract_mime_type(&self) -> Option<MimeType> {+ // SAFETY: The response is live, and LibWeb hands over 0 or the serialization of the MIME type.+ let serialized = unsafe { string_if_not_null(web_fetch_response_extract_mime_type(self.as_ptr())) }?;+ let code_points: Vec<char> = char::decode_utf16(serialized.to_utf16().iter().copied())+ .map(|code_point| code_point.expect("the serialization of a MIME type is well-formed"))+ .collect();+ Some(MimeType::parse(&code_points).expect("the serialization of a MIME type parses"))+ }++ /// https://fetch.spec.whatwg.org/#concept-response-url+ pub(crate) fn url(&self, exclude_fragment: bool) -> Option<Utf16String> {+ // SAFETY: The response is live, and LibWeb hands over 0 or the serialization of the URL.+ unsafe { string_if_not_null(web_fetch_response_url(self.as_ptr(), exclude_fragment)) }+ }++ /// https://fetch.spec.whatwg.org/#concept-response-body+ pub(crate) fn has_body(&self) -> bool {+ // SAFETY: The response is live.+ unsafe { web_fetch_response_has_body(self.as_ptr()) }+ }++ pub(crate) fn network_error_message(&self) -> Option<Utf16String> {+ // SAFETY: The response is live, and LibWeb hands over 0 or the message.+ unsafe { string_if_not_null(web_fetch_response_network_error_message(self.as_ptr())) }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/mod.rsnew file mode 100644index 00000000000..acb9980c41b--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/mod.rs@@ -0,0 +1,10 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Infrastructure, https://fetch.spec.whatwg.org/#infrastructure++pub(crate) mod fetch_controller;+pub(crate) mod http;diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/mod.rssimilarity index 95%rename from Libraries/LibWeb/Bindings/Rust/src/fetch.rsrename to Libraries/LibWeb/Bindings/Rust/src/fetch/mod.rsindex 0803b509e52..004fc01c3b1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/fetch.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/mod.rs@@ -4,6 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/+//! The Fetch Standard, https://fetch.spec.whatwg.org/++pub(crate) mod body_init;+pub(crate) mod infrastructure;+use core::ffi::c_void;use crate::bindings::interface::{cell_from_abi, cell_into_abi, realm_arguments};diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 491d7636c1b..4c11720ce0c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -130,6 +130,8 @@ pub(crate) mod indexed_db;allow(dead_code, reason = "only the generated bindings use the interfaces"))]pub(crate) mod notifications_api;+#[cfg(not(test))]+pub(crate) mod platform;#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/Bindings/Rust/src/platform/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/platform/mod.rsnew file mode 100644index 00000000000..40f45a43202--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/platform/mod.rs@@ -0,0 +1,7 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub(crate) mod timer;diff --git a/Libraries/LibWeb/Bindings/Rust/src/platform/timer.rs b/Libraries/LibWeb/Bindings/Rust/src/platform/timer.rsnew file mode 100644index 00000000000..8ec184a5a52--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/platform/timer.rs@@ -0,0 +1,49 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use libjs_rust::api::{Trace, Vm};++use crate::bindings::cpp_cell::CppCell;+use crate::bindings::promise::{pending_steps, run_pending_steps};++unsafe extern "C" {+ fn web_platform_timer_create_single_shot(+ milliseconds: u64,+ cell: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),+ ) -> *mut c_void;+ fn web_platform_timer_stop(timer: *mut c_void);+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppTimer(CppCell);++impl CppTimer {+ pub(crate) fn create_single_shot<C: Trace + Clone + 'static>(+ vm: &Vm,+ milliseconds: u64,+ captures: C,+ steps: fn(&Vm, C),+ ) -> Self {+ let cell = pending_steps(vm, captures, steps);+ // SAFETY: The cell is live, and LibWeb returns a live timer.+ Self(unsafe {+ CppCell::from_raw(web_platform_timer_create_single_shot(+ milliseconds,+ cell,+ run_pending_steps,+ ))+ })+ }++ pub(crate) fn stop(&self) {+ // SAFETY: The timer is live.+ unsafe { web_platform_timer_stop(self.0.as_ptr()) };+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rsindex 6b32768d298..3d0fe409459 100644--- a/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/exports.rs@@ -8,15 +8,17 @@//! The C ABI through which LibWeb's C++ creates FormData objects, reads their entry lists and creates entries.use core::ffi::c_void;+use core::ptr::NonNull;use ak::Utf16String;-use libjs_rust::api::{JSVM, vm_from_abi};+use libjs_rust::api::{Gc, JSVM, Vm, vm_from_abi};use super::form_data::{Entry, FormData, FormDataEntryValue, StringOrBlob, create_an_entry};-use super::progress_event::{ProgressEvent, ProgressEventInit};+use super::xml_http_request::{NullOrFailureOrBytes, SyncSendRef, XMLHttpRequest};use crate::bindings::conversions::UsvString;use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi, realm_arguments};-use crate::dom::event::EventInit;+use crate::fetch::infrastructure::fetch_controller::CppFetchController;+use crate::fetch::infrastructure::http::response_view::CppResponseView;use crate::file_api::exports::any_blob_from_abi;#[repr(C)]@@ -176,29 +178,164 @@ pub unsafe extern "C" fn web_html_create_an_entry(/// # Safety///-/// `vm` must be the live VM, `realm` a live realm, and `event_name` a raw string that C++ owns a reference to.+/// `vm` must be the live VM and `realm` a live realm.#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_xhr_create_progress_event(- vm: *mut c_void,- realm: *mut c_void,- event_name: usize,- length_computable: bool,- loaded: f64,- total: f64,-) -> *mut c_void {- // SAFETY: The caller passes the live VM and a live realm, and hands over the name.- let ((vm, realm), event_name) = unsafe { (realm_arguments(vm, realm), Utf16String::from_raw_owned(event_name)) };- let event_init = ProgressEventInit {- parent: EventInit {- bubbles: false,- cancelable: false,- composed: false,- },- length_computable,- loaded,- total,+pub unsafe extern "C" fn web_rust_xhr_create(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(XMLHttpRequest::create(vm, realm))+}++/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+unsafe fn xhr_arguments<'vm>(vm: *mut JSVM, xhr: *mut c_void) -> (&'vm Vm, Ref<XMLHttpRequest>) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ unsafe { (vm_from_abi(vm), cell_from_abi(xhr)) }+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_request_body_chunk_length(+ vm: *mut JSVM,+ xhr: *mut c_void,+ request_body_length: u64,+ bytes_length: u64,+) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ let (vm, xhr) = unsafe { xhr_arguments(vm, xhr) };+ xhr.process_request_body_chunk_length(vm, request_body_length, bytes_length);+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_request_end_of_body(+ vm: *mut JSVM,+ xhr: *mut c_void,+ request_body_length: u64,+) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ let (vm, xhr) = unsafe { xhr_arguments(vm, xhr) };+ xhr.process_request_end_of_body(vm, request_body_length);+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, `xhr` the live cell of an XMLHttpRequest, and `response` a live ResponseView.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_response(vm: *mut JSVM, xhr: *mut c_void, response: *mut c_void) {+ // SAFETY: The caller passes the live VM, the live cell of an XMLHttpRequest and a live ResponseView.+ let ((vm, xhr), response) = unsafe { (xhr_arguments(vm, xhr), CppResponseView::from_raw(response)) };+ XMLHttpRequest::process_response(xhr, vm, response);+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_body_chunk(+ vm: *mut JSVM,+ xhr: *mut c_void,+ length: u64,+ bytes: ak::Span<'_, u8>,+) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ let (vm, xhr) = unsafe { xhr_arguments(vm, xhr) };+ xhr.process_body_chunk(vm, length, bytes.as_slice());+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_end_of_body(vm: *mut JSVM, xhr: *mut c_void) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ let (vm, xhr) = unsafe { xhr_arguments(vm, xhr) };+ xhr.process_end_of_body(vm);+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, and `xhr` the live cell of an XMLHttpRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_body_error(vm: *mut JSVM, xhr: *mut c_void) {+ // SAFETY: The caller passes the live VM and the live cell of an XMLHttpRequest.+ let (vm, xhr) = unsafe { xhr_arguments(vm, xhr) };+ xhr.process_body_error(vm);+}++/// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+///+/// # Safety+///+/// `vm` must be the live VM, `xhr` the live cell of an XMLHttpRequest, `sync_send` the live flags of its send(), and+/// `response` a live ResponseView.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_process_response_consume_body(+ vm: *mut JSVM,+ xhr: *mut c_void,+ sync_send: *mut c_void,+ response: *mut c_void,+ kind: u8,+ bytes: ak::Span<'_, u8>,+) {+ // SAFETY: The caller passes the live VM, the live cell of an XMLHttpRequest, the live flags of its send() and a+ // live ResponseView.+ let ((_, xhr), sync_send, response) = unsafe {+ (+ xhr_arguments(vm, xhr),+ sync_send_from_abi(sync_send),+ CppResponseView::from_raw(response),+ )+ };+ let null_or_failure_or_bytes = match kind {+ 0 => NullOrFailureOrBytes::Null,+ 1 => NullOrFailureOrBytes::Failure,+ _ => NullOrFailureOrBytes::Bytes(bytes.as_slice()),};- ProgressEvent::create(vm, realm, &event_name, event_init)- .event()- .as_ptr()+ xhr.process_response_consume_body(&sync_send, response, null_or_failure_or_bytes);+}++/// # Safety+///+/// `vm` must be the live VM, `xhr` the live cell of an XMLHttpRequest, and `fetch_controller` a live fetch controller.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_fetch_stopped(vm: *mut JSVM, xhr: *mut c_void, fetch_controller: *mut c_void) {+ // SAFETY: The caller passes the live VM, the live cell of an XMLHttpRequest and a live fetch controller.+ let ((vm, xhr), fetch_controller) =+ unsafe { (xhr_arguments(vm, xhr), CppFetchController::from_raw(fetch_controller)) };+ XMLHttpRequest::fetch_stopped(xhr, vm, fetch_controller);+}++/// # Safety+///+/// `sync_send` must be the live flags of a send().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_xhr_sync_send_is_over(sync_send: *mut c_void) -> bool {+ // SAFETY: The caller passes the live flags of a send().+ unsafe { sync_send_from_abi(sync_send) }.is_over()+}++/// # Safety+///+/// `sync_send` must be the live flags of a send().+unsafe fn sync_send_from_abi(sync_send: *mut c_void) -> SyncSendRef {+ // SAFETY: The caller passes the live flags of a send().+ unsafe { Gc::from_non_null(NonNull::new(sync_send.cast()).expect("C++ passes the flags of a send()")) }}diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rsindex a5c96a46edc..6ccbc188180 100644--- a/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/mod.rs@@ -12,3 +12,9 @@ pub(crate) mod exports;pub(crate) mod form_data;#[cfg(not(test))]pub(crate) mod progress_event;+#[cfg(not(test))]+pub(crate) mod xml_http_request;+#[cfg(not(test))]+pub(crate) mod xml_http_request_event_target;+#[cfg(not(test))]+pub(crate) mod xml_http_request_upload;diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request.rsnew file mode 100644index 00000000000..d68198b1de0--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request.rs@@ -0,0 +1,2146 @@+/*+ * Copyright (c) 2020-2023, Andreas Kling <[email protected]>+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>+ * Copyright (c) 2022-2023, Luke Wilde <[email protected]>+ * Copyright (c) 2022, Ali Mohammad Pur <[email protected]>+ * Copyright (c) 2022-2024, Kenneth Myhra <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! XMLHttpRequest, https://xhr.spec.whatwg.org/#interface-xmlhttprequest++use core::cell::{Cell, RefCell};+use core::ffi::c_void;+use core::ptr::NonNull;+use std::time::{Duration, Instant};++use ak::Utf16String;+use encoding_rs::{Encoding, UTF_8};+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferShared, EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, JSONObject, Object,+ PrimitiveString, Realm, Trace, Utf16View, Value, Visitor, Vm,+};+use liburl_rust::{RustUrl, Url};+use libwebcommon_rust::mime_sniff::mime_type::MimeType;++use super::form_data::FormData;+use super::progress_event::{ProgressEvent, ProgressEventInit};+use super::xml_http_request_event_target::XMLHttpRequestEventTarget;+use super::xml_http_request_upload::XMLHttpRequestUpload;+use crate::bindings::conversions::{BufferSource, ByteString, CppInterface, UsvString};+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::environment_settings_object::relevant_settings_object;+use crate::bindings::event_target::{CppEvent, CppEventTarget, EventListenerListChanged, GetTheParent};+use crate::bindings::global_object::window_from_global_object;+use crate::bindings::interface::{+ Inherits, Ref, Wrappable, allocate, cell_into_abi, realm_is_window, with_temporary_execution_context, wrap,+};+use crate::bindings::promise::{TaskSource, queue_a_global_task};+use crate::bindings::realm_data::{WrapperWorld, wrapper_world_of};+use crate::bindings::{CallContext, Exception, MustNotThrow as _, WebIdlResult};+use crate::css::css_rule::wrap_cpp_cell;+use crate::dom::event::EventInit;+use crate::domurl::url_input;+use crate::domurl::url_search_params::URLSearchParams;+use crate::fetch::body_init::{XMLHttpRequestBodyInit, safely_extract_body};+use crate::fetch::infrastructure::fetch_controller::CppFetchController;+use crate::fetch::infrastructure::http::bodies::CppBody;+use crate::fetch::infrastructure::http::requests::CppRequest;+use crate::fetch::infrastructure::http::response_view::CppResponseView;+use crate::file_api::blob::{AnyBlob, Blob};+use crate::platform::timer::CppTimer;++#[repr(C)]+struct RequestAbi<'a> {+ method: ak::Span<'a, u8>,+ url: *const RustUrl,+ header_names: *const ak::Span<'a, u8>,+ header_values: *const ak::Span<'a, u8>,+ header_count: usize,+ body: *mut c_void,+ use_cors_preflight: bool,+ include_credentials: bool,+ use_url_credentials: bool,+}++unsafe extern "C" {+ fn web_xhr_is_method(method: ak::Span<'_, u8>) -> bool;+ fn web_xhr_is_forbidden_method(method: ak::Span<'_, u8>) -> bool;+ fn web_xhr_normalize_method(+ method: ak::Span<'_, u8>,+ bytes: *mut c_void,+ on_bytes: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ );+ fn web_xhr_normalize_header_value(+ value: ak::Span<'_, u8>,+ bytes: *mut c_void,+ on_bytes: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ );+ fn web_xhr_is_header_name(name: ak::Span<'_, u8>) -> bool;+ fn web_xhr_is_header_value(value: ak::Span<'_, u8>) -> bool;+ fn web_xhr_is_forbidden_request_header(name: ak::Span<'_, u8>, value: ak::Span<'_, u8>) -> bool;+ fn web_xhr_document_is_html_document(document: *mut c_void) -> bool;+ fn web_xhr_document_as_body(realm: *mut c_void, document: *mut c_void) -> *mut c_void;+ fn web_xhr_create_request(realm: *mut c_void, request: *const RequestAbi<'_>) -> *mut c_void;+ fn web_xhr_fetch(+ realm: *mut c_void,+ request: *mut c_void,+ xhr: *mut c_void,+ sync_send: *mut c_void,+ request_body_length: u64,+ ) -> *mut c_void;+ fn web_xhr_incrementally_read_body(realm: *mut c_void, response: *mut c_void, xhr: *mut c_void, length: u64);+ fn web_xhr_pause_until_sync_send_is_over(sync_send: *mut c_void);+ fn web_html_get_an_xml_encoding(+ bytes: ak::Span<'_, u8>,+ label: *mut c_void,+ on_label: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ );+ fn web_xhr_create_document_response(+ global_object: *mut c_void,+ response: *mut c_void,+ received_bytes: ak::Span<'_, u8>,+ final_mime: usize,+ final_mime_is_html: bool,+ final_encoding: ak::Span<'_, u8>,+ has_final_encoding: bool,+ ) -> *mut c_void;+}++unsafe extern "C" fn on_bytes(bytes: *mut c_void, lent: ak::Span<'_, u8>) {+ // SAFETY: bytes is the vector of the caller, and LibWeb lends the bytes for the call.+ unsafe { *bytes.cast::<Vec<u8>>() = lent.as_slice().to_vec() };+}++unsafe extern "C" fn on_label(label: *mut c_void, lent: ak::Span<'_, u8>) {+ // SAFETY: label is the label of the caller, and LibWeb lends the label for the call.+ unsafe { *label.cast::<Option<Vec<u8>>>() = Some(lent.as_slice().to_vec()) };+}++// https://xhr.spec.whatwg.org/#xmlhttprequestresponsetype+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum XMLHttpRequestResponseType {+ Empty,+ Arraybuffer,+ Blob,+ Document,+ Json,+ Text,+}++pub(crate) enum DocumentOrXMLHttpRequestBodyInit {+ Document(CppInterface),+ Blob(AnyBlob),+ BufferSource(BufferSource),+ FormData(Ref<FormData>),+ URLSearchParams(Ref<URLSearchParams>),+ USVString(UsvString),+}++// https://xhr.spec.whatwg.org/#concept-xmlhttprequest-state+#[derive(Clone, Copy, PartialEq, Eq)]+enum State {+ Unsent = 0,+ Opened = 1,+ HeadersReceived = 2,+ Loading = 3,+ Done = 4,+}++#[derive(Clone)]+enum Response {+ NetworkError { message: &'static str, aborted: bool },+ Fetched(CppResponseView),+}++// SAFETY: A response that the fetch handed over is the only cell this reaches.+unsafe impl Trace for Response {+ fn trace(&self, visitor: &mut Visitor) {+ if let Self::Fetched(response) = self {+ response.trace(visitor);+ }+ }+}++impl Response {+ fn network_error(message: &'static str) -> Self {+ Self::NetworkError {+ message,+ aborted: false,+ }+ }++ fn aborted_network_error() -> Self {+ Self::NetworkError {+ message: "Fetch was aborted",+ aborted: true,+ }+ }++ fn fetched(&self) -> Option<&CppResponseView> {+ match self {+ Self::NetworkError { .. } => None,+ Self::Fetched(response) => Some(response),+ }+ }++ fn is_network_error(&self) -> bool {+ self.fetched().is_none_or(CppResponseView::is_network_error)+ }++ fn aborted(&self) -> bool {+ match self {+ Self::NetworkError { aborted, .. } => *aborted,+ Self::Fetched(response) => response.aborted(),+ }+ }++ fn has_body(&self) -> bool {+ self.fetched().is_some_and(CppResponseView::has_body)+ }++ fn network_error_message(&self) -> Option<Utf16String> {+ match self {+ Self::NetworkError { message, .. } => Some(Utf16String::from_ascii(message.as_bytes())),+ Self::Fetched(response) => response.network_error_message(),+ }+ }++ fn extract_length(&self) -> Option<u64> {+ self.fetched().and_then(CppResponseView::extract_length)+ }+}++/// https://xhr.spec.whatwg.org/#response-object+enum ResponseObject {+ Null,+ Document(CppCell),+ Blob(Ref<Blob>),+}++// SAFETY: The Document and the Blob are the only cells this reaches.+unsafe impl Trace for ResponseObject {+ fn trace(&self, visitor: &mut Visitor) {+ match self {+ Self::Null => {}+ Self::Document(document) => document.trace(visitor),+ Self::Blob(blob) => blob.trace(visitor),+ }+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct CachedResponseObject {+ #[gc(untraced)]+ wrapper_world: WrapperWorld,+ object: Value,+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct SyncSend {+ #[gc(untraced)]+ processed_response: Cell<bool>,+ #[gc(untraced)]+ did_time_out: Cell<bool>,+}++static SYNC_SEND_CLASS: EmbedderClass<SyncSend> = EmbedderClass::new("XMLHttpRequestSyncSend");++impl EmbedderValue for SyncSend {+ const CLASS: &'static EmbedderClass<Self> = &SYNC_SEND_CLASS;+}++pub(crate) type SyncSendRef = Gc<EmbedderCell<SyncSend>>;++impl SyncSend {+ pub(crate) fn is_over(&self) -> bool {+ self.processed_response.get() || self.did_time_out.get()+ }+}++pub(crate) enum NullOrFailureOrBytes<'a> {+ Null,+ Failure,+ Bytes(&'a [u8]),+}++// https://xhr.spec.whatwg.org/#xmlhttprequest+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct XMLHttpRequest {+ target: XMLHttpRequestEventTarget,+ realm: Gc<Realm>,++ // https://xhr.spec.whatwg.org/#upload-object+ // upload object+ // An XMLHttpRequestUpload object.+ upload_object: Ref<XMLHttpRequestUpload>,++ // https://xhr.spec.whatwg.org/#concept-xmlhttprequest-state+ // state+ // One of unsent, opened, headers received, loading, and done; initially unsent.+ #[gc(untraced)]+ state: Cell<State>,++ // https://xhr.spec.whatwg.org/#send-flag+ // send() flag+ // A flag, initially unset.+ #[gc(untraced)]+ send: Cell<bool>,++ // https://xhr.spec.whatwg.org/#timeout+ // timeout+ // An unsigned integer, initially 0.+ #[gc(untraced)]+ timeout: Cell<u32>,++ // https://xhr.spec.whatwg.org/#cross-origin-credentials+ // cross-origin credentials+ // A boolean, initially false.+ #[gc(untraced)]+ cross_origin_credentials: Cell<bool>,++ // https://xhr.spec.whatwg.org/#request-method+ // request method+ // A method.+ #[gc(untraced)]+ request_method: RefCell<Vec<u8>>,++ // https://xhr.spec.whatwg.org/#request-url+ // request URL+ // A URL.+ #[gc(untraced)]+ request_url: RefCell<Option<Url>>,++ // https://xhr.spec.whatwg.org/#author-request-headers+ // author request headers+ // A header list, initially empty.+ #[gc(untraced)]+ author_request_headers: RefCell<Vec<(Vec<u8>, Vec<u8>)>>,++ // https://xhr.spec.whatwg.org/#request-body+ // request body+ // Initially null.+ request_body: GcRefCell<Option<CppBody>>,++ // https://xhr.spec.whatwg.org/#synchronous-flag+ // synchronous flag+ // A flag, initially unset.+ #[gc(untraced)]+ synchronous: Cell<bool>,++ // https://xhr.spec.whatwg.org/#upload-complete-flag+ // upload complete flag+ // A flag, initially unset.+ #[gc(untraced)]+ upload_complete: Cell<bool>,++ // https://xhr.spec.whatwg.org/#upload-listener-flag+ // upload listener flag+ // A flag, initially unset.+ #[gc(untraced)]+ upload_listener: Cell<bool>,++ // https://xhr.spec.whatwg.org/#timed-out-flag+ // timed out flag+ // A flag, initially unset.+ #[gc(untraced)]+ timed_out: Cell<bool>,++ // https://xhr.spec.whatwg.org/#response+ // response+ // A response, initially a network error.+ response: GcRefCell<Response>,++ // https://xhr.spec.whatwg.org/#received-bytes+ // received bytes+ // A byte sequence, initially the empty byte sequence.+ #[gc(untraced)]+ received_bytes: RefCell<Vec<u8>>,++ // https://xhr.spec.whatwg.org/#response-type+ // response type+ // One of the empty string, "arraybuffer", "blob", "document", "json", and "text"; initially the empty string.+ #[gc(untraced)]+ response_type: Cell<XMLHttpRequestResponseType>,++ // https://xhr.spec.whatwg.org/#response-object+ // response object+ // An object, failure, or null, initially null.+ response_object: GcRefCell<ResponseObject>,+ cached_response_objects: GcRefCell<Vec<CachedResponseObject>>,++ // https://xhr.spec.whatwg.org/#xmlhttprequest-fetch-controller+ // fetch controller+ // A fetch controller, initially a new fetch controller.+ // NOTE: The send() method sets it to a useful fetch controller, but for simplicity it always holds a fetch controller.+ fetch_controller: GcRefCell<CppFetchController>,++ // https://xhr.spec.whatwg.org/#override-mime-type+ // override MIME type+ // A MIME type or null, initially null.+ // NOTE: Can get a value when overrideMimeType() is invoked.+ #[gc(untraced)]+ override_mime_type: RefCell<Option<MimeType>>,++ // Non-standard, see async path in `send()`+ #[gc(untraced)]+ request_body_transmitted: Cell<u64>,+ #[gc(untraced)]+ last_upload_progress_timestamp: Cell<Option<Instant>>,+ #[gc(untraced)]+ last_download_progress_timestamp: Cell<Option<Instant>>,++ #[gc(untraced)]+ async_request: RefCell<Option<CppRequest>>,+ #[gc(untraced)]+ async_send_start_time: Cell<Option<Instant>>,+ timeout_timer: GcRefCell<Option<CppTimer>>,+}++impl Inherits<XMLHttpRequestEventTarget> for XMLHttpRequest {+ fn parent(&self) -> &XMLHttpRequestEventTarget {+ &self.target+ }+}++impl Wrappable for XMLHttpRequest {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.target.cpp_parent()+ }+}++impl GetTheParent for XMLHttpRequest {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl EventListenerListChanged for XMLHttpRequest {+ fn event_listener_list_changed(this: Ref<Self>) {+ this.update_pending_activity();+ }+}++fn bytes_to_code_points(bytes: &[u8]) -> Vec<char> {+ bytes.iter().map(|&byte| char::from(byte)).collect()+}++fn string_to_code_points(string: &Utf16String) -> Vec<char> {+ char::decode_utf16(string.to_utf16().iter().copied())+ .map(|code_point| code_point.unwrap_or(char::REPLACEMENT_CHARACTER))+ .collect()+}++fn new_mime_type(r#type: &str, subtype: &str) -> MimeType {+ MimeType::new(String::from(r#type), String::from(subtype))+}++// https://infra.spec.whatwg.org/#isomorphic-encode+fn isomorphic_encode(string: &str) -> Vec<u8> {+ string+ .chars()+ .map(|code_point| u8::try_from(u32::from(code_point)).expect("the code point is at most U+00FF"))+ .collect()+}++// https://fetch.spec.whatwg.org/#header-list-contains+fn find_header(list: &[(Vec<u8>, Vec<u8>)], name: &[u8]) -> Option<usize> {+ list.iter()+ .position(|(header_name, _)| header_name.eq_ignore_ascii_case(name))+}++// https://fetch.spec.whatwg.org/#concept-header-list-get+fn get_header(list: &[(Vec<u8>, Vec<u8>)], name: &[u8]) -> Option<Vec<u8>> {+ // 1. If list does not contain name, then return null.+ find_header(list, name)?;++ // 2. Return the values of all headers in list whose name is a byte-case-insensitive match for name, separated from+ // each other by 0x2C 0x20, in order.+ let values: Vec<&[u8]> = list+ .iter()+ .filter(|(header_name, _)| header_name.eq_ignore_ascii_case(name))+ .map(|(_, value)| value.as_slice())+ .collect();+ Some(values.join(&b", "[..]))+}++// https://fetch.spec.whatwg.org/#concept-header-list-set+fn set_header(list: &mut Vec<(Vec<u8>, Vec<u8>)>, name: &[u8], value: Vec<u8>) {+ // 1. If list contains name, then set the value of the first such header to value and remove the others.+ if let Some(index) = find_header(list, name) {+ list[index].1 = value;+ let mut position = 0;+ list.retain(|(header_name, _)| {+ let keep = position <= index || !header_name.eq_ignore_ascii_case(name);+ position += 1;+ keep+ });+ }+ // 2. Otherwise, append (name, value) to list.+ else {+ list.push((name.to_vec(), value));+ }+}++// https://fetch.spec.whatwg.org/#concept-header-list-combine+fn combine_header(list: &mut Vec<(Vec<u8>, Vec<u8>)>, name: Vec<u8>, value: Vec<u8>) {+ // 1. If list contains name, then set the value of the first such header to its value, followed by 0x2C 0x20,+ // followed by value.+ if let Some(index) = find_header(list, &name) {+ let header_value = &mut list[index].1;+ header_value.extend_from_slice(b", ");+ header_value.extend_from_slice(&value);+ }+ // 2. Otherwise, append (name, value) to list.+ else {+ list.push((name, value));+ }+}++// https://xhr.spec.whatwg.org/#legacy-uppercased-byte-less-than+fn is_legacy_uppercased_byte_less_than(a: &[u8], b: &[u8]) -> bool {+ // 1. Let A be a, byte-uppercased.+ let uppercased_a = a.to_ascii_uppercase();++ // 2. Let B be b, byte-uppercased.+ let uppercased_b = b.to_ascii_uppercase();++ // 3. Return A is byte less than B.+ uppercased_a < uppercased_b+}++// https://xhr.spec.whatwg.org/#concept-event-fire-progress+fn fire_progress_event(+ vm: &Vm,+ realm: Gc<Realm>,+ target: &CppEventTarget,+ event_name: &str,+ transmitted: u64,+ length: u64,+) {+ // To fire a progress event named e at target, given transmitted and length, means to fire an event named e at target, using ProgressEvent,+ // with the loaded attribute initialized to transmitted, and if length is not 0, with the lengthComputable attribute initialized to true+ // and the total attribute initialized to length.+ let event_init = ProgressEventInit {+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ length_computable: length != 0,+ loaded: transmitted as f64,+ total: length as f64,+ };+ let event = ProgressEvent::create(vm, realm, &Utf16String::from_ascii(event_name.as_bytes()), event_init);+ target.dispatch_event(event.event());+}++fn current_global_object_is_window(vm: &Vm) -> bool {+ realm_is_window(vm.current_realm().expect("the steps run in a realm"))+}++impl XMLHttpRequest {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {+ let upload_object = XMLHttpRequestUpload::create(vm);+ let fetch_controller = CppFetchController::create(realm.global_object());+ let xhr = allocate(vm, |_| Self {+ target: XMLHttpRequestEventTarget::new(),+ realm,+ upload_object,+ state: Cell::new(State::Unsent),+ send: Cell::new(false),+ timeout: Cell::new(0),+ cross_origin_credentials: Cell::new(false),+ request_method: RefCell::new(Vec::new()),+ request_url: RefCell::new(None),+ author_request_headers: RefCell::new(Vec::new()),+ request_body: GcRefCell::new(None),+ synchronous: Cell::new(false),+ upload_complete: Cell::new(false),+ upload_listener: Cell::new(false),+ timed_out: Cell::new(false),+ response: GcRefCell::new(Response::network_error("Not sent yet")),+ received_bytes: RefCell::new(Vec::new()),+ response_type: Cell::new(XMLHttpRequestResponseType::Empty),+ response_object: GcRefCell::new(ResponseObject::Null),+ cached_response_objects: GcRefCell::new(Vec::new()),+ fetch_controller: GcRefCell::new(fetch_controller),+ override_mime_type: RefCell::new(None),+ request_body_transmitted: Cell::new(0),+ last_upload_progress_timestamp: Cell::new(None),+ last_download_progress_timestamp: Cell::new(None),+ async_request: RefCell::new(None),+ async_send_start_time: Cell::new(None),+ timeout_timer: GcRefCell::new(None),+ });+ xhr.target.event_target().set_owner(xhr);+ xhr.target+ .event_target()+ .set_event_listener_list_changed_steps::<Self>();+ xhr+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest+ pub(crate) fn construct(cx: &mut CallContext) -> WebIdlResult<Ref<Self>> {+ Ok(Self::create(cx.vm(), cx.realm()))+ }++ fn event_target(&self) -> &CppEventTarget {+ self.target.event_target()+ }++ fn relevant_global_object(&self) -> Gc<Object> {+ self.realm.global_object()+ }++ fn fetch_controller(&self) -> CppFetchController {+ self.fetch_controller.borrow().clone()+ }++ fn set_response(&self, response: Response) {+ self.response.replace(response);+ }++ fn response_record(&self) -> Response {+ self.response.borrow().clone()+ }++ fn fire_event(&self, event_name: &str) {+ let event = CppEvent::create(self.realm, event_name, false, false, false);+ self.event_target().dispatch_event(&event);+ }++ fn fire_progress_event(&self, vm: &Vm, event_name: &str, transmitted: u64, length: u64) {+ fire_progress_event(vm, self.realm, self.event_target(), event_name, transmitted, length);+ }++ fn fire_upload_progress_event(&self, vm: &Vm, event_name: &str, transmitted: u64, length: u64) {+ fire_progress_event(+ vm,+ self.realm,+ self.upload_object.event_target(),+ event_name,+ transmitted,+ length,+ );+ }++ fn restart_timeout_timer(this: Ref<Self>, vm: &Vm) {+ this.stop_timeout_timer();+ let Some(send_start_time) = this.async_send_start_time.get() else {+ return;+ };+ let request_is_done = this.async_request.borrow().as_ref().is_none_or(CppRequest::done);+ if !this.send.get() || this.synchronous.get() || request_is_done || this.timeout.get() == 0 {+ return;+ }++ // NB: Timeout changes keep the deadline relative to send(), rather than starting a fresh timeout period.+ let elapsed = Instant::now().saturating_duration_since(send_start_time);+ let remaining = Duration::from_millis(u64::from(this.timeout.get())).saturating_sub(elapsed);+ let milliseconds = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX);+ let timer = CppTimer::create_single_shot(+ vm,+ milliseconds,+ (this, this.fetch_controller()),+ |vm, (this, fetch_controller)| {+ if this.async_request.borrow().is_none() || this.fetch_controller() != fetch_controller {+ return;+ }++ this.stop_timeout_timer();+ let request = this+ .async_request+ .take()+ .expect("the timer runs for an ongoing request");+ if !request.done() {+ this.timed_out.set(true);+ fetch_controller.terminate();+ this.handle_errors(vm).must();+ }+ },+ );+ this.timeout_timer.replace(Some(timer));+ }++ fn stop_timeout_timer(&self) {+ if let Some(timer) = self.timeout_timer.replace(None) {+ timer.stop();+ }+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext+ pub(crate) fn response_text(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.+ let response_type = self.response_type.get();+ if response_type != XMLHttpRequestResponseType::Empty && response_type != XMLHttpRequestResponseType::Text {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR responseText can only be used for responseType \"\" or \"text\""),+ ));+ }++ // 2. If this’s state is not loading or done, then return the empty string.+ if self.state.get() != State::Loading && self.state.get() != State::Done {+ return Ok(UsvString::from_ascii(b""));+ }++ // 3. Return the result of getting a text response for this.+ Ok(UsvString::from_utf16_string(&self.text_response()))+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsexml+ pub(crate) fn response_xml(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ // 1. If this’s response type is not the empty string or "document", then throw an "InvalidStateError" DOMException.+ let response_type = self.response_type.get();+ if response_type != XMLHttpRequestResponseType::Empty && response_type != XMLHttpRequestResponseType::Document {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR responseXML can only be used for responseXML \"\" or \"document\""),+ ));+ }++ // 2. If this’s state is not done, then return null.+ if self.state.get() != State::Done {+ return Ok(None);+ }++ // 3. Assert: this’s response object is not failure.+ // NB: Nothing sets the response object to failure, see response().++ // 4. If this’s response object is non-null, then return it.+ if let Some(document) = self.response_document() {+ return Ok(Some(wrap_cpp_cell(cx, &document)));+ }++ // 5. Set a document response for this.+ self.set_document_response();++ // 6. Return this’s response object.+ Ok(self.response_document().map(|document| wrap_cpp_cell(cx, &document)))+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-response+ pub(crate) fn response(&self, cx: &mut CallContext) -> WebIdlResult<Value> {+ let vm = cx.vm();+ let realm = cx.realm();+ let wrapper_world = wrapper_world_of(vm, realm);+ let cached_response_object = || {+ self.cached_response_objects+ .borrow()+ .iter()+ .find(|cached| cached.wrapper_world == wrapper_world)+ .map(|cached| cached.object)+ };+ let cache_response_object = |object: Value| {+ self.cached_response_objects+ .borrow_mut(vm)+ .push(CachedResponseObject { wrapper_world, object });+ };++ // 1. If this’s response type is the empty string or "text", then:+ let response_type = self.response_type.get();+ if response_type == XMLHttpRequestResponseType::Empty || response_type == XMLHttpRequestResponseType::Text {+ // 1. If this’s state is not loading or done, then return the empty string.+ if self.state.get() != State::Loading && self.state.get() != State::Done {+ return Ok(Value::from_string(PrimitiveString::create(vm, Utf16String::default())));+ }++ // 2. Return the result of getting a text response for this.+ return Ok(Value::from_string(PrimitiveString::create(vm, self.text_response())));+ }++ // 2. If this’s state is not done, then return null.+ if self.state.get() != State::Done {+ return Ok(Value::NULL);+ }++ // 3. If this’s response object is failure, then return null.+ // NB: Nothing sets the response object to failure, see step 5.++ // 4. If this’s response object is non-null, then return it.+ if let Some(document) = self.response_document() {+ return Ok(Value::from_object(wrap_cpp_cell(cx, &document).wrapper()));+ }+ if let ResponseObject::Blob(blob) = &*self.response_object.borrow() {+ return Ok(Value::from_object(wrap(cx, *blob)));+ }++ // 5. If this’s response type is "arraybuffer",+ if response_type == XMLHttpRequestResponseType::Arraybuffer {+ if let Some(cached_object) = cached_response_object() {+ return Ok(cached_object);+ }++ // then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws+ // an exception, then set this’s response object to failure and return null.+ let buffer =+ ArrayBuffer::create_from_bytes(vm, realm, &self.received_bytes.borrow(), ArrayBufferShared::No);+ let buffer = Value::from_object(buffer);+ cache_response_object(buffer);+ return Ok(buffer);+ }++ // 6. Otherwise, if this’s response type is "blob", set this’s response object to a new Blob object representing+ // this’s received bytes with type set to the result of get a final MIME type for this.+ if response_type == XMLHttpRequestResponseType::Blob {+ let mime_type_as_string = Utf16String::from_utf8(&self.final_mime_type().serialize());+ let bytes = self.received_bytes.borrow().clone();+ let blob = allocate(vm, |_| Blob::new(bytes, mime_type_as_string));+ self.set_response_object(ResponseObject::Blob(blob));+ return Ok(Value::from_object(wrap(cx, blob)));+ }++ // 7. Otherwise, if this’s response type is "document", set a document response for this.+ if response_type == XMLHttpRequestResponseType::Document {+ self.set_document_response();+ return Ok(self.response_document().map_or(Value::NULL, |document| {+ Value::from_object(wrap_cpp_cell(cx, &document).wrapper())+ }));+ }++ // 8. Otherwise:+ // 1. Assert: this’s response type is "json".+ // Note: Automatically done by the layers above us.++ // 2. If this’s response’s body is null, then return null.+ if !self.response.borrow().has_body() {+ return Ok(Value::NULL);+ }++ if let Some(cached_object) = cached_response_object() {+ return Ok(cached_object);+ }++ // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an+ // exception, then return null.+ let json = {+ let received_bytes = self.received_bytes.borrow();+ let (json, _) = UTF_8.decode_with_bom_removal(&received_bytes);+ Utf16String::from_utf8(&json)+ };+ let json_object_result =+ with_temporary_execution_context(realm, || JSONObject::parse_json(vm, Utf16View::of_string(&json), None));+ let Ok(json_object) = json_object_result else {+ return Ok(Value::NULL);+ };++ // 4. Set this’s response object to jsonObject.+ cache_response_object(json_object);++ // 9. Return this’s response object.+ Ok(json_object)+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype+ pub(crate) fn response_type(&self, _: &mut CallContext) -> WebIdlResult<XMLHttpRequestResponseType> {+ Ok(self.response_type.get())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype+ pub(crate) fn set_response_type(+ &self,+ cx: &mut CallContext,+ response_type: XMLHttpRequestResponseType,+ ) -> WebIdlResult<()> {+ let current_global_object_is_window = current_global_object_is_window(cx.vm());++ // 1. If the current global object is not a Window object and the given value is "document", then return.+ if !current_global_object_is_window && response_type == XMLHttpRequestResponseType::Document {+ return Ok(());+ }++ // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.+ if self.state.get() == State::Loading || self.state.get() == State::Done {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"Can't readyState when XHR is loading or done"),+ ));+ }++ // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.+ if current_global_object_is_window && self.synchronous.get() {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_ascii(b"Can't set readyState on synchronous XHR in Window environment"),+ ));+ }++ // 4. Set this’s response type to the given value.+ self.response_type.set(response_type);+ Ok(())+ }++ fn response_document(&self) -> Option<CppCell> {+ match &*self.response_object.borrow() {+ ResponseObject::Document(document) => Some(document.clone()),+ ResponseObject::Null | ResponseObject::Blob(_) => None,+ }+ }++ fn set_response_object(&self, response_object: ResponseObject) {+ self.response_object.replace(response_object);+ self.cached_response_objects.replace(Vec::new());+ }++ fn reset_response_object(&self) {+ self.set_response_object(ResponseObject::Null);+ }++ // https://xhr.spec.whatwg.org/#text-response+ fn text_response(&self) -> Utf16String {+ // 1. If xhr’s response’s body is null, then return the empty string.+ if !self.response.borrow().has_body() {+ return Utf16String::default();+ }++ // 2. Let charset be the result of get a final encoding for xhr.+ let mut charset = self.final_encoding();++ let received_bytes = self.received_bytes.borrow();++ // 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,+ if self.response_type.get() == XMLHttpRequestResponseType::Empty+ && charset.is_none()+ && self.final_mime_type().essence().is_xml()+ {+ // then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]+ // NB: The encoding declaration names the encoding, which this finds the way the HTML Standard does when+ // sniffing an encoding. Without one, charset stays null and is set to UTF-8 below, as the XML+ // specification requires.+ let mut xml_encoding: Option<Vec<u8>> = None;+ // SAFETY: The bytes are lent for the call, and the label outlives it.+ unsafe {+ web_html_get_an_xml_encoding(ak::Span::new(&received_bytes), (&raw mut xml_encoding).cast(), on_label);+ }+ if let Some(xml_encoding) = xml_encoding {+ charset = Encoding::for_label(&xml_encoding);+ }+ }++ // 4. If charset is null, then set charset to UTF-8.+ let charset = charset.unwrap_or(UTF_8);++ // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.+ let (decoded, _, _) = charset.decode(&received_bytes);+ Utf16String::from_utf8(&decoded)+ }++ // https://xhr.spec.whatwg.org/#document-response+ fn set_document_response(&self) {+ // 1. If xhr’s response’s body is null, then return.+ let response = self.response_record();+ if !response.has_body() {+ return;+ }+ let response = response+ .fetched()+ .expect("a response with a body is one that the fetch handed over");++ // 2. Let finalMIME be the result of get a final MIME type for xhr.+ let final_mime = self.final_mime_type();+ let final_mime_is_html = final_mime.essence().is_html();++ // 3. If finalMIME is not an HTML MIME type or an XML MIME type, then return.+ if !final_mime_is_html && !final_mime.essence().is_xml() {+ return;+ }++ // 4. If xhr’s response type is the empty string and finalMIME is an HTML MIME type, then return.+ if self.response_type.get() == XMLHttpRequestResponseType::Empty && final_mime_is_html {+ return;+ }++ // NB: LibWeb creates and parses the document in steps 5 to 11.+ let final_mime = Utf16String::from_utf8(&final_mime.serialize());+ let final_encoding = self.final_encoding();+ let final_encoding_name = final_encoding.map_or("", Encoding::name);+ let received_bytes = self.received_bytes.borrow().clone();+ // SAFETY: The global object and the response are live, and the bytes, the MIME type and the encoding are lent+ // for the call. LibWeb returns null or a live Document.+ let document = unsafe {+ let document = web_xhr_create_document_response(+ self.relevant_global_object().as_ptr().cast(),+ response.as_ptr(),+ ak::Span::new(&received_bytes),+ final_mime.raw_identity(),+ final_mime_is_html,+ ak::Span::new(final_encoding_name.as_bytes()),+ final_encoding.is_some(),+ );+ (!document.is_null()).then(|| CppCell::from_raw(document))+ };+ let Some(document) = document else {+ self.reset_response_object();+ return;+ };++ // 12. Set xhr’s response object to document.+ self.set_response_object(ResponseObject::Document(document));+ }++ // https://xhr.spec.whatwg.org/#final-mime-type+ fn final_mime_type(&self) -> MimeType {+ // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.+ // 2. Return xhr’s override MIME type.+ self.override_mime_type+ .borrow()+ .clone()+ .unwrap_or_else(|| self.response_mime_type())+ }++ // https://xhr.spec.whatwg.org/#response-mime-type+ fn response_mime_type(&self) -> MimeType {+ // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.+ let mime_type = self+ .response+ .borrow()+ .fetched()+ .and_then(CppResponseView::extract_mime_type);++ // 2. If mimeType is failure, then set mimeType to text/xml.+ // 3. Return mimeType.+ mime_type.unwrap_or_else(|| new_mime_type("text", "xml"))+ }++ // https://xhr.spec.whatwg.org/#final-charset+ fn final_encoding(&self) -> Option<&'static Encoding> {+ // 1. Let label be null.+ let mut label = None;++ // 2. Let responseMIME be the result of get a response MIME type for xhr.+ let response_mime = self.response_mime_type();++ // 3. If responseMIME’s parameters["charset"] exists, then set label to it.+ if let Some((_, charset)) = response_mime.parameters().find(|(name, _)| *name == "charset") {+ label = Some(String::from(charset));+ }++ // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.+ if let Some(override_mime_type) = &*self.override_mime_type.borrow()+ && let Some((_, charset)) = override_mime_type.parameters().find(|(name, _)| *name == "charset")+ {+ label = Some(String::from(charset));+ }++ // 5. If label is null, then return null.+ // 6. Let encoding be the result of getting an encoding from label.+ // 7. If encoding is failure, then return null.+ // 8. Return encoding.+ Encoding::for_label(label?.as_bytes())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader+ pub(crate) fn set_request_header(+ &self,+ _: &mut CallContext,+ name: ByteString,+ value: ByteString,+ ) -> WebIdlResult<()> {+ // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.+ if self.state.get() != State::Opened {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR readyState is not OPENED"),+ ));+ }++ // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.+ if self.send.get() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR send() flag is already set"),+ ));+ }++ let name = name.into_bytes();++ // 3. Normalize value.+ let mut normalized_value = Vec::new();+ // SAFETY: The value is lent for the call, and the normalized value outlives it.+ unsafe {+ web_xhr_normalize_header_value(+ ak::Span::new(value.as_bytes()),+ (&raw mut normalized_value).cast(),+ on_bytes,+ );+ }+ let value = normalized_value;++ // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.+ // SAFETY: The name is lent for the call.+ if !unsafe { web_xhr_is_header_name(ak::Span::new(&name)) } {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_ascii(b"Header name contains invalid characters."),+ ));+ }+ // SAFETY: The value is lent for the call.+ if !unsafe { web_xhr_is_header_value(ak::Span::new(&value)) } {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_ascii(b"Header value contains invalid characters."),+ ));+ }++ // 5. If (name, value) is a forbidden request-header, then return.+ // SAFETY: The name and the value are lent for the call.+ if unsafe { web_xhr_is_forbidden_request_header(ak::Span::new(&name), ak::Span::new(&value)) } {+ return Ok(());+ }++ // 6. Combine (name, value) in this’s author request headers.+ combine_header(&mut self.author_request_headers.borrow_mut(), name, value);++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open+ pub(crate) fn open(&self, cx: &mut CallContext, method: ByteString, url: UsvString) -> WebIdlResult<()> {+ // 7. If the async argument is omitted, set async to true, and set username and password to null.+ self.open_with_async(cx, method, url, true, None, None)+ }++ pub(crate) fn open_with_async(+ &self,+ cx: &mut CallContext,+ method: ByteString,+ url: UsvString,+ r#async: bool,+ username: Option<UsvString>,+ password: Option<UsvString>,+ ) -> WebIdlResult<()> {+ // 1. If this’s relevant global object is a Window object and its associated Document is not fully active, then throw an "InvalidStateError" DOMException.+ if let Some(window) = window_from_global_object(self.relevant_global_object())+ && !window.associated_document().is_fully_active()+ {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"Invalid state: Window's associated document is not fully active."),+ ));+ }++ // 2. If method is not a method, then throw a "SyntaxError" DOMException.+ // SAFETY: The method is lent for the call.+ if !unsafe { web_xhr_is_method(ak::Span::new(method.as_bytes())) } {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_ascii(b"An invalid or illegal string was specified."),+ ));+ }++ // 3. If method is a forbidden method, then throw a "SecurityError" DOMException.+ // SAFETY: The method is lent for the call.+ if unsafe { web_xhr_is_forbidden_method(ak::Span::new(method.as_bytes())) } {+ return Err(Exception::Dom(+ "SecurityError",+ Utf16String::from_ascii(b"Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'"),+ ));+ }++ // 4. Normalize method.+ let mut normalized_method = Vec::new();+ // SAFETY: The method is lent for the call, and the normalized method outlives it.+ unsafe {+ web_xhr_normalize_method(+ ak::Span::new(method.as_bytes()),+ (&raw mut normalized_method).cast(),+ on_bytes,+ );+ }++ // 5. Let parsedURL be the result of encoding-parsing a URL url, relative to this’s relevant settings object.+ let parsed_url =+ relevant_settings_object(self.relevant_global_object()).encoding_parse_url(url.as_utf16_string());++ // 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.+ let Some(mut parsed_url) = parsed_url else {+ return Err(Exception::Dom("SyntaxError", Utf16String::from_ascii(b"Invalid URL")));+ };++ // 7. If the async argument is omitted, set async to true, and set username and password to null.+ // NOTE: This is handled in the overload lacking the async argument.++ // 8. If parsedURL’s host is non-null, then:+ if parsed_url.serialized_host().is_some() {+ // 1. If the username argument is not null, set the username given parsedURL and username.+ if let Some(username) = &username {+ parsed_url.set_username(url_input(username.units()));+ }+ // 2. If the password argument is not null, set the password given parsedURL and password.+ if let Some(password) = &password {+ parsed_url.set_password(url_input(password.units()));+ }+ }++ // 9. If async is false, the current global object is a Window object, and either this’s timeout is+ // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.+ if !r#async+ && current_global_object_is_window(cx.vm())+ && (self.timeout.get() != 0 || self.response_type.get() != XMLHttpRequestResponseType::Empty)+ {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_ascii(+ b"Synchronous XMLHttpRequests in a Window context do not support timeout or a non-empty responseType",+ ),+ ));+ }++ // 10. Terminate this’s fetch controller.+ // Spec Note: A fetch can be ongoing at this point.+ self.fetch_controller().terminate();+ self.stop_timeout_timer();+ self.async_request.take();+ self.event_target().set_has_pending_activity(self.realm, false);++ // 11. Set variables associated with the object as follows:+ // Unset this’s send() flag.+ self.send.set(false);+ // Set this’s request method to method.+ *self.request_method.borrow_mut() = normalized_method;+ // Set this’s request URL to parsedURL.+ *self.request_url.borrow_mut() = Some(parsed_url);+ // Empty this’s author request headers.+ self.author_request_headers.borrow_mut().clear();+ // Set this’s request body to null.+ self.request_body.replace(None);+ // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.+ self.synchronous.set(!r#async);+ // Unset this’s upload listener flag.+ self.upload_listener.set(false);+ // Set this’s response to a network error.+ self.set_response(Response::network_error("Not yet sent"));+ // Set this’s received bytes to the empty byte sequence.+ self.received_bytes.borrow_mut().clear();+ // Set this’s response object to null.+ self.reset_response_object();+ // Spec Note: Override MIME type is not overridden here as the overrideMimeType() method can be invoked before the open() method.++ // 12. If this’s state is not opened, then:+ if self.state.get() != State::Opened {+ // 1. Set this’s state to opened.+ self.state.set(State::Opened);++ // 2. Fire an event named readystatechange at this.+ self.fire_event("readystatechange");+ }++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn send(+ this: &Ref<Self>,+ cx: &mut CallContext,+ body: Option<DocumentOrXMLHttpRequestBodyInit>,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let associated_realm = this.realm;++ // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.+ if this.state.get() != State::Opened {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR readyState is not OPENED"),+ ));+ }++ // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.+ if this.send.get() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR send() flag is already set"),+ ));+ }++ // 3. If this’s request method is `GET` or `HEAD`, then set body to null.+ let request_method = this.request_method.borrow().clone();+ let body = if request_method == b"GET" || request_method == b"HEAD" {+ None+ } else {+ body+ };++ // 4. If body is not null, then:+ if let Some(body) = body {+ // 1. Let extractedContentType be null.+ let mut extracted_content_type = None;++ // 2. If body is a Document, then set this’s request body to body, serialized, converted, and UTF-8 encoded.+ if let DocumentOrXMLHttpRequestBodyInit::Document(document) = &body {+ // SAFETY: The realm and the Document are live, and LibWeb returns a live body.+ let request_body = unsafe {+ CppBody::from_raw(web_xhr_document_as_body(+ associated_realm.as_ptr().cast(),+ document.wrapper().as_ptr().cast(),+ ))+ };+ this.request_body.replace(Some(request_body));+ }+ // 3. Otherwise:+ else {+ let body_init = match &body {+ DocumentOrXMLHttpRequestBodyInit::Document(_) => unreachable!("a Document is handled above"),+ DocumentOrXMLHttpRequestBodyInit::Blob(blob) => XMLHttpRequestBodyInit::Blob(blob.clone()),+ DocumentOrXMLHttpRequestBodyInit::BufferSource(buffer_source) => {+ let mut bytes = Vec::new();+ // SAFETY: Copying the bytes neither runs script nor allocates a cell.+ unsafe { buffer_source.with_bytes(|source| bytes.extend_from_slice(source)) };+ XMLHttpRequestBodyInit::Bytes(bytes)+ }+ DocumentOrXMLHttpRequestBodyInit::FormData(form_data) => {+ XMLHttpRequestBodyInit::FormData(*form_data)+ }+ DocumentOrXMLHttpRequestBodyInit::URLSearchParams(url_search_params) => {+ XMLHttpRequestBodyInit::URLSearchParams(*url_search_params)+ }+ DocumentOrXMLHttpRequestBodyInit::USVString(string) => {+ XMLHttpRequestBodyInit::String(string.clone())+ }+ };++ // 1. Let bodyWithType be the result of safely extracting body.+ let body_with_type = safely_extract_body(associated_realm, &body_init);++ // 2. Set this’s request body to bodyWithType’s body.+ this.request_body.replace(Some(body_with_type.body));++ // 3. Set extractedContentType to bodyWithType’s type.+ extracted_content_type = body_with_type.r#type;+ }++ // 4. Let originalAuthorContentType be the result of getting `Content-Type` from this’s author request headers.+ let original_author_content_type = get_header(&this.author_request_headers.borrow(), b"Content-Type");++ // 5. If originalAuthorContentType is non-null, then:+ if let Some(original_author_content_type) = original_author_content_type {+ // 1. If body is a Document object, a URLSearchParams object, or a string:+ if matches!(+ body,+ DocumentOrXMLHttpRequestBodyInit::Document(_)+ | DocumentOrXMLHttpRequestBodyInit::URLSearchParams(_)+ | DocumentOrXMLHttpRequestBodyInit::USVString(_)+ ) {+ // 1. Let contentTypeRecord be the result of parsing originalAuthorContentType.+ let content_type_record = MimeType::parse(&bytes_to_code_points(&original_author_content_type));++ // 2. If contentTypeRecord is not failure, contentTypeRecord’s parameters["charset"] exists, and parameters["charset"] is not an ASCII case-insensitive match for "UTF-8", then:+ if let Some(mut content_type_record) = content_type_record+ && content_type_record+ .parameters()+ .any(|(name, value)| name == "charset" && !value.eq_ignore_ascii_case("UTF-8"))+ {+ // 1. Set contentTypeRecord’s parameters["charset"] to "UTF-8".+ content_type_record.set_parameter(String::from("charset"), String::from("UTF-8"));++ // 2. Let newContentTypeSerialized be the result of serializing contentTypeRecord.+ let new_content_type_serialized = content_type_record.serialize();++ // 3. Set (`Content-Type`, newContentTypeSerialized) in this’s author request headers.+ set_header(+ &mut this.author_request_headers.borrow_mut(),+ b"Content-Type",+ isomorphic_encode(&new_content_type_serialized),+ );+ }+ }+ }+ // 6. Otherwise:+ else if let DocumentOrXMLHttpRequestBodyInit::Document(document) = &body {+ // NOTE: A document can only be an HTML document or XML document.+ // SAFETY: The Document is live.+ let is_html_document = unsafe { web_xhr_document_is_html_document(document.wrapper().as_ptr().cast()) };++ // 1. If body is an HTML document, then set (`Content-Type`, `text/html;charset=UTF-8`) in this’s author request headers.+ // 2. Otherwise, if body is an XML document, set (`Content-Type`, `application/xml;charset=UTF-8`) in this’s author request headers.+ let content_type: &[u8] = if is_html_document {+ b"text/html;charset=UTF-8"+ } else {+ b"application/xml;charset=UTF-8"+ };+ set_header(+ &mut this.author_request_headers.borrow_mut(),+ b"Content-Type",+ content_type.to_vec(),+ );+ }+ // 3. Otherwise, if extractedContentType is not null, set (`Content-Type`, extractedContentType) in this’s author request headers.+ else if let Some(extracted_content_type) = extracted_content_type {+ let extracted_content_type: String =+ string_to_code_points(&extracted_content_type).into_iter().collect();+ set_header(+ &mut this.author_request_headers.borrow_mut(),+ b"Content-Type",+ isomorphic_encode(&extracted_content_type),+ );+ }+ }++ // 5. If one or more event listeners are registered on this’s upload object, then set this’s upload listener flag.+ this.upload_listener+ .set(this.upload_object.event_target().has_event_listeners());++ // 6. Let req be a new request, initialized as follows:+ // NB: XHR/XMLHttpRequest.cpp creates the request from these fields.+ let request_body = this.request_body.borrow().clone();+ let request = {+ let request_url = this.request_url.borrow();+ let request_url = request_url.as_ref().expect("open() set the request URL");+ let author_request_headers = this.author_request_headers.borrow();+ let header_names: Vec<ak::Span<'_, u8>> = author_request_headers+ .iter()+ .map(|(name, _)| ak::Span::new(name))+ .collect();+ let header_values: Vec<ak::Span<'_, u8>> = author_request_headers+ .iter()+ .map(|(_, value)| ak::Span::new(value))+ .collect();+ let rust_url = RustUrl::from_url(request_url);+ let request = RequestAbi {+ method: ak::Span::new(&request_method),+ url: &raw const rust_url,+ header_names: header_names.as_ptr(),+ header_values: header_values.as_ptr(),+ header_count: author_request_headers.len(),+ body: request_body.as_ref().map_or(core::ptr::null_mut(), CppBody::as_ptr),+ use_cors_preflight: this.upload_listener.get(),+ include_credentials: this.cross_origin_credentials.get(),+ use_url_credentials: request_url.includes_credentials(),+ };+ // SAFETY: The realm is live, the fields are lent for the call, and LibWeb hands over a reference to the+ // request.+ unsafe {+ CppRequest::adopt(web_xhr_create_request(+ associated_realm.as_ptr().cast(),+ &raw const request,+ ))+ }+ };++ // 7. Unset this’s upload complete flag.+ this.upload_complete.set(false);++ // 8. Unset this’s timed out flag.+ this.timed_out.set(false);++ // 9. If req’s body is null, then set this’s upload complete flag.+ // NOTE: req's body is always this's request body, see step 6.+ if request_body.is_none() {+ this.upload_complete.set(true);+ }++ // 10. Set this’s send() flag.+ this.send.set(true);+ this.update_pending_activity();++ // 11. If this’s synchronous flag is unset, then:+ if !this.synchronous.get() {+ // 1. Fire a progress event named loadstart at this with 0 and 0.+ this.fire_progress_event(vm, "loadstart", 0, 0);++ // 2. Let requestBodyTransmitted be 0.+ // NOTE: This is kept on the XHR object itself instead of the stack, as we cannot capture references to stack variables in an async context.+ this.request_body_transmitted.set(0);+ this.last_upload_progress_timestamp.set(None);+ this.last_download_progress_timestamp.set(None);++ // 3. Let requestBodyLength be req’s body’s length, if req’s body is non-null; otherwise 0.+ // NOTE: req's body is always this's request body, see step 6.+ // 4. Assert: requestBodyLength is an integer.+ let request_body_length = request_body.as_ref().map_or(0, |body| {+ body.length()+ .expect("the length of a body that send() extracted is an integer")+ });++ // 5. If this’s upload complete flag is unset and this’s upload listener flag is set, then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted and requestBodyLength.+ if !this.upload_complete.get() && this.upload_listener.get() {+ this.fire_upload_progress_event(+ vm,+ "loadstart",+ this.request_body_transmitted.get(),+ request_body_length,+ );+ }++ // 6. If this’s state is not opened or this’s send() flag is unset, then return.+ if this.state.get() != State::Opened || !this.send.get() {+ return Ok(());+ }++ // 7. Let processRequestBodyChunkLength, given a bytesLength, be these steps:+ // NB: See process_request_body_chunk_length().++ // 8. Let processRequestEndOfBody be these steps:+ // NB: See process_request_end_of_body().++ // 9. Let processResponse, given a response, be these steps:+ // NB: See process_response().++ // 10. Set this’s fetch controller to the result of fetching req with processRequestBodyChunkLength set to processRequestBodyChunkLength, processRequestEndOfBody set to processRequestEndOfBody, and processResponse set to processResponse.+ // SAFETY: The realm, the request and this are live, and LibWeb returns a live fetch controller.+ let fetch_controller = unsafe {+ CppFetchController::from_raw(web_xhr_fetch(+ associated_realm.as_ptr().cast(),+ request.as_ptr(),+ cell_into_abi(*this),+ core::ptr::null_mut(),+ request_body_length,+ ))+ };+ this.fetch_controller.replace(fetch_controller);++ // 11. Let now be the present time.+ this.async_send_start_time.set(Some(Instant::now()));+ *this.async_request.borrow_mut() = Some(request);++ // 12. Run these steps in parallel:+ // 1. Wait until either req’s done flag is set or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.+ // 2. If req’s done flag is unset, then set this’s timed out flag and terminate this’s fetch controller.+ Self::restart_timeout_timer(*this, vm);+ }+ // 12. Otherwise, if this’s synchronous flag is set:+ else {+ // NB: These flags can't live in this stack frame: The fetch algorithms below share them, and can run after+ // send() has returned (a response that completes after the fetch was terminated for timing out, e.g.).+ // 1. Let processedResponse be false.+ let sync_send = SYNC_SEND_CLASS.allocate(vm, |_| SyncSend {+ processed_response: Cell::new(false),+ did_time_out: Cell::new(false),+ });++ // 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:+ // NB: See process_response_consume_body().++ // 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.+ // SAFETY: The realm, the request, this and the flags are live, and LibWeb returns a live fetch controller.+ let fetch_controller = unsafe {+ CppFetchController::from_raw(web_xhr_fetch(+ associated_realm.as_ptr().cast(),+ request.as_ptr(),+ cell_into_abi(*this),+ sync_send.as_ptr().cast(),+ 0,+ ))+ };+ this.fetch_controller.replace(fetch_controller.clone());++ // 4. Let now be the present time.+ // 5. Pause until either processedResponse is true or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.+ if this.timeout.get() != 0 {+ this.stop_timeout_timer();+ let timer = CppTimer::create_single_shot(+ vm,+ u64::from(this.timeout.get()),+ (*this, sync_send),+ |_, (this, sync_send)| {+ sync_send.did_time_out.set(true);+ this.stop_timeout_timer();+ },+ );+ this.timeout_timer.replace(Some(timer));+ }++ // NB: XHR/XMLHttpRequest.cpp pauses the event loop for the wait.+ // SAFETY: The flags are live.+ unsafe { web_xhr_pause_until_sync_send_is_over(sync_send.as_ptr().cast()) };++ this.stop_timeout_timer();++ // 6. If processedResponse is false, then set this’s timed out flag and terminate this’s fetch controller.+ if !sync_send.processed_response.get() {+ this.timed_out.set(true);+ fetch_controller.terminate();+ }++ // 7. Report timing for this’s fetch controller given the current global object.+ // AD-HOC: A request that timed out before its fetch set up the report timing steps has no timing to report.+ // Spec issue: https://github.com/whatwg/xhr/issues/412+ if !this.timed_out.get() || fetch_controller.has_report_timing_steps() {+ let current_realm = vm.current_realm().expect("send() runs in a realm");+ fetch_controller.report_timing(current_realm.global_object());+ }++ // 8. Run handle response end-of-body for this.+ this.handle_response_end_of_body(vm)?;+ }+ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_request_body_chunk_length(&self, vm: &Vm, request_body_length: u64, bytes_length: u64) {+ // AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a+ // null body, so ignore everything after the upload completed.+ // Spec issue: https://github.com/whatwg/xhr/issues/242+ if self.upload_complete.get() {+ return;+ }++ // 1. Increase requestBodyTransmitted by bytesLength.+ self.request_body_transmitted+ .set(self.request_body_transmitted.get() + bytes_length);++ // 2. If not roughly 50ms have passed since these steps were last invoked, then return.+ let now = Instant::now();+ let enough_time_passed = self+ .last_upload_progress_timestamp+ .get()+ .is_none_or(|timestamp| now - timestamp >= Duration::from_millis(50));+ if !enough_time_passed {+ return;+ }+ self.last_upload_progress_timestamp.set(Some(now));++ // 3. If this’s upload listener flag is set, then fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.+ if self.upload_listener.get() {+ self.fire_upload_progress_event(vm, "progress", self.request_body_transmitted.get(), request_body_length);+ }+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_request_end_of_body(&self, vm: &Vm, request_body_length: u64) {+ // AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a+ // null body, so ignore everything after the upload completed.+ // Spec issue: https://github.com/whatwg/xhr/issues/242+ if self.upload_complete.get() {+ return;+ }++ // 1. Set this’s upload complete flag.+ self.upload_complete.set(true);++ // 2. If this’s upload listener flag is unset, then return.+ if !self.upload_listener.get() {+ return;+ }++ // 3. Fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.+ self.fire_upload_progress_event(vm, "progress", self.request_body_transmitted.get(), request_body_length);++ // 4. Fire a progress event named load at this’s upload object with requestBodyTransmitted and requestBodyLength.+ self.fire_upload_progress_event(vm, "load", self.request_body_transmitted.get(), request_body_length);++ // 5. Fire a progress event named loadend at this’s upload object with requestBodyTransmitted and requestBodyLength.+ self.fire_upload_progress_event(vm, "loadend", self.request_body_transmitted.get(), request_body_length);+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_response(this: Ref<Self>, vm: &Vm, response: CppResponseView) {+ // 1. Set this’s response to response.+ this.set_response(Response::Fetched(response.clone()));++ // 2. Handle errors for this.+ // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.+ this.handle_errors(vm).must();++ // 3. If this’s response is a network error, then return.+ if this.response.borrow().is_network_error() {+ return;+ }++ // 4. Set this’s state to headers received.+ this.state.set(State::HeadersReceived);+ this.update_pending_activity();++ // 5. Fire an event named readystatechange at this.+ this.fire_event("readystatechange");++ // 6. If this’s state is not headers received, then return.+ if this.state.get() != State::HeadersReceived {+ return;+ }++ // 7. If this’s response’s body is null, then run handle response end-of-body for this and return.+ if !this.response.borrow().has_body() {+ // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.+ this.handle_response_end_of_body(vm).must();+ return;+ }++ // 8. Let length be the result of extracting a length from this’s response’s header list.+ // 9. If length is not an integer, then set it to 0.+ let length = this.response.borrow().extract_length().unwrap_or(0);++ // Pre-allocate received bytes buffer if Content-Length is known.+ if let Ok(length) = usize::try_from(length) {+ this.received_bytes.borrow_mut().reserve(length);+ }++ // 10. Let processBodyChunk given bytes be these steps:+ // NB: See process_body_chunk().++ // 11. Let processEndOfBody be this step: run handle response end-of-body for this.+ // NB: See process_end_of_body().++ // 12. Let processBodyError be these steps:+ // NB: See process_body_error().++ // 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.+ // SAFETY: The realm, the response and this are live.+ unsafe {+ web_xhr_incrementally_read_body(+ this.realm.as_ptr().cast(),+ response.as_ptr(),+ cell_into_abi(this),+ length,+ );+ }+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_body_chunk(&self, vm: &Vm, length: u64, bytes: &[u8]) {+ // 1. Append bytes to this’s received bytes.+ self.received_bytes.borrow_mut().extend_from_slice(bytes);++ // 2. If not roughly 50ms have passed since these steps were last invoked, then return.+ let now = Instant::now();+ let enough_time_passed = self+ .last_download_progress_timestamp+ .get()+ .is_none_or(|timestamp| now - timestamp >= Duration::from_millis(50));+ if !enough_time_passed {+ return;+ }+ self.last_download_progress_timestamp.set(Some(now));++ // 3. If this’s state is headers received, then set this’s state to loading.+ if self.state.get() == State::HeadersReceived {+ self.state.set(State::Loading);+ }+ self.update_pending_activity();++ // 4. Fire an event named readystatechange at this.+ // Spec Note: Web compatibility is the reason readystatechange fires more often than this’s state changes.+ self.fire_event("readystatechange");++ // 5. Fire a progress event named progress at this with this’s received bytes’s length and length.+ let received_length = self.received_bytes.borrow().len() as u64;+ self.fire_progress_event(vm, "progress", received_length, length);+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_end_of_body(&self, vm: &Vm) {+ // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.+ self.handle_response_end_of_body(vm).must();+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_body_error(&self, vm: &Vm) {+ // 1. Set this’s response to a network error.+ self.set_response(Response::network_error("A network error occurred processing body."));+ // 2. Run handle errors for this.+ // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.+ self.handle_errors(vm).must();+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+ pub(crate) fn process_response_consume_body(+ &self,+ sync_send: &SyncSend,+ response: CppResponseView,+ null_or_failure_or_bytes: NullOrFailureOrBytes<'_>,+ ) {+ // AD-HOC: Leave this's response and received bytes alone once send() returned for a timeout.+ if sync_send.did_time_out.get() {+ return;+ }++ // 1. If nullOrFailureOrBytes is not failure, then set this’s response to response.+ if !matches!(null_or_failure_or_bytes, NullOrFailureOrBytes::Failure) {+ self.set_response(Response::Fetched(response));+ }++ // 2. If nullOrFailureOrBytes is a byte sequence, then append nullOrFailureOrBytes to this’s received bytes.+ if let NullOrFailureOrBytes::Bytes(bytes) = null_or_failure_or_bytes {+ self.received_bytes.borrow_mut().extend_from_slice(bytes);+ }++ // 3. Set processedResponse to true.+ sync_send.processed_response.set(true);+ }++ // AD-HOC: Stopping the fetch, as aborting the document does, discards it without a response. Hand this an+ // aborted network error instead, so that it fires abort as for a canceled fetch.+ pub(crate) fn fetch_stopped(this: Ref<Self>, vm: &Vm, fetch_controller: CppFetchController) {+ queue_a_global_task(+ vm,+ this.relevant_global_object(),+ TaskSource::Networking,+ (this, fetch_controller),+ |vm, (this, fetch_controller)| {+ if this.fetch_controller() != fetch_controller {+ return;+ }+ this.set_response(Response::aborted_network_error());+ this.handle_errors(vm).must();+ },+ );+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getresponseheader+ pub(crate) fn get_response_header(+ &self,+ _: &mut CallContext,+ name: ByteString,+ ) -> WebIdlResult<Option<ByteString>> {+ // The getResponseHeader(name) method steps are to return the result of getting name from this’s response’s header list.+ Ok(self+ .response+ .borrow()+ .fetched()+ .and_then(|response| response.get_header(name.as_bytes()))+ .map(ByteString::from_bytes))+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getallresponseheaders+ pub(crate) fn get_all_response_headers(&self, _: &mut CallContext) -> WebIdlResult<ByteString> {+ // 1. Let output be an empty byte sequence.+ let mut output = Vec::new();++ // 2. Let initialHeaders be the result of running sort and combine with this’s response’s header list.+ let mut initial_headers = self+ .response+ .borrow()+ .fetched()+ .map(CppResponseView::sort_and_combine)+ .unwrap_or_default();++ // 3. Let headers be the result of sorting initialHeaders in ascending order, with a being less than b if a’s name is legacy-uppercased-byte less than b’s name.+ // NOTE: Unfortunately, this is needed for compatibility with deployed content.+ initial_headers.sort_by(|(a, _), (b, _)| {+ if is_legacy_uppercased_byte_less_than(a, b) {+ core::cmp::Ordering::Less+ } else if is_legacy_uppercased_byte_less_than(b, a) {+ core::cmp::Ordering::Greater+ } else {+ core::cmp::Ordering::Equal+ }+ });++ // 4. For each header in headers, append header’s name, followed by a 0x3A 0x20 byte pair, followed by header’s value, followed by a 0x0D 0x0A byte pair, to output.+ for (name, value) in initial_headers {+ output.extend_from_slice(&name);+ output.extend_from_slice(b": ");+ output.extend_from_slice(&value);+ output.extend_from_slice(b"\r\n");+ }++ // 5. Return output.+ Ok(ByteString::from_bytes(output))+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype+ pub(crate) fn override_mime_type(&self, _: &mut CallContext, mime: Utf16String) -> WebIdlResult<()> {+ // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.+ if self.state.get() == State::Loading || self.state.get() == State::Done {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"Cannot override MIME type when state is Loading or Done."),+ ));+ }++ // 2. Set this’s override MIME type to the result of parsing mime.+ let override_mime_type = MimeType::parse(&string_to_code_points(&mime));++ // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.+ *self.override_mime_type.borrow_mut() =+ Some(override_mime_type.unwrap_or_else(|| new_mime_type("application", "octet-stream")));++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout+ pub(crate) fn timeout(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(self.timeout.get())+ }++ // https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2+ pub(crate) fn set_timeout(this: &Ref<Self>, cx: &mut CallContext, timeout: u32) -> WebIdlResult<()> {+ // 1. If the current global object is a Window object and this’s synchronous flag is set,+ // then throw an "InvalidAccessError" DOMException.+ if current_global_object_is_window(cx.vm()) && this.synchronous.get() {+ return Err(Exception::Dom(+ "InvalidAccessError",+ Utf16String::from_ascii(+ b"Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context.",+ ),+ ));+ }++ // 2. Set this’s timeout to the given value.+ this.timeout.set(timeout);++ // NB: The asynchronous send() timeout wait observes changes to this value.+ if this.send.get() && !this.synchronous.get() {+ Self::restart_timeout_timer(*this, cx.vm());+ }++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials+ pub(crate) fn with_credentials(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The withCredentials getter steps are to return this’s cross-origin credentials.+ Ok(self.cross_origin_credentials.get())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials+ pub(crate) fn set_with_credentials(&self, _: &mut CallContext, with_credentials: bool) -> WebIdlResult<()> {+ // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.+ if self.state.get() != State::Unsent && self.state.get() != State::Opened {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR readyState is not UNSENT or OPENED"),+ ));+ }++ // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.+ if self.send.get() {+ return Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"XHR send() flag is already set"),+ ));+ }++ // 3. Set this’s cross-origin credentials to the given value.+ self.cross_origin_credentials.set(with_credentials);++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-abort+ pub(crate) fn abort(&self, cx: &mut CallContext) -> WebIdlResult<()> {+ let vm = cx.vm();+ self.stop_timeout_timer();+ self.async_request.take();++ // 1. Abort this’s fetch controller.+ self.fetch_controller().abort(self.realm);++ // 2. If this’s state is opened with this’s send() flag set, headers received, or loading, then run the request error steps for this and abort.+ let state = self.state.get();+ if (state == State::Opened && self.send.get()) || state == State::HeadersReceived || state == State::Loading {+ // NOTE: This cannot throw as we don't pass in an exception. XHR::abort cannot be reached in a synchronous context where the state matches above.+ // This is because it pauses inside XHR::send until the request is done or times out and then immediately calls `handle_response_end_of_body`+ // which will always set `m_state` to `Done`.+ self.request_error_steps(vm, "abort", None).must();+ }++ // 3. If this’s state is done, then set this’s state to unsent and this’s response to a network error.+ // Spec Note: No readystatechange event is dispatched.+ if self.state.get() == State::Done {+ self.state.set(State::Unsent);+ self.set_response(Response::network_error("Not yet sent"));+ self.update_pending_activity();+ }++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-upload+ pub(crate) fn upload(&self, _: &mut CallContext) -> WebIdlResult<Ref<XMLHttpRequestUpload>> {+ // The upload getter steps are to return this’s upload object.+ Ok(self.upload_object)+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate+ pub(crate) fn ready_state(&self, _: &mut CallContext) -> WebIdlResult<u16> {+ Ok(self.state.get() as u16)+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-status+ pub(crate) fn status(&self, _: &mut CallContext) -> WebIdlResult<u16> {+ // The status getter steps are to return this’s response’s status.+ Ok(self.response.borrow().fetched().map_or(0, CppResponseView::status))+ }++ // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-statustext+ pub(crate) fn status_text(&self, _: &mut CallContext) -> WebIdlResult<ByteString> {+ // The statusText getter steps are to return this’s response’s status message.+ let status_message = self+ .response+ .borrow()+ .fetched()+ .map(CppResponseView::status_message)+ .unwrap_or_default();+ Ok(ByteString::from_bytes(status_message))+ }++ // https://xhr.spec.whatwg.org/#handle-response-end-of-body+ fn handle_response_end_of_body(&self, vm: &Vm) -> WebIdlResult<()> {+ self.stop_timeout_timer();+ self.async_request.take();++ // 1. Handle errors for xhr.+ self.handle_errors(vm)?;++ // 2. If xhr’s response is a network error, then return.+ if self.response.borrow().is_network_error() {+ return Ok(());+ }++ // 3. Let transmitted be xhr’s received bytes’s length.+ let transmitted = self.received_bytes.borrow().len() as u64;++ // 4. Let length be the result of extracting a length from this’s response’s header list.+ // 5. If length is not an integer, then set it to 0.+ let length = self.response.borrow().extract_length().unwrap_or(0);++ // 6. If xhr’s synchronous flag is unset, then fire a progress event named progress at xhr with transmitted and length.+ if !self.synchronous.get() {+ self.fire_progress_event(vm, "progress", transmitted, length);+ }++ // 7. Set xhr’s state to done.+ self.state.set(State::Done);++ // 8. Unset xhr’s send() flag.+ self.send.set(false);+ self.update_pending_activity();++ // 9. Fire an event named readystatechange at xhr.+ self.fire_event("readystatechange");++ // 10. Fire a progress event named load at xhr with transmitted and length.+ self.fire_progress_event(vm, "load", transmitted, length);++ // 11. Fire a progress event named loadend at xhr with transmitted and length.+ self.fire_progress_event(vm, "loadend", transmitted, length);++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#handle-errors+ fn handle_errors(&self, vm: &Vm) -> WebIdlResult<()> {+ // 1. If xhr’s send() flag is unset, then return.+ if !self.send.get() {+ return Ok(());+ }++ // 2. If xhr’s timed out flag is set, then run the request error steps for xhr, timeout, and "TimeoutError" DOMException.+ if self.timed_out.get() {+ return self.request_error_steps(+ vm,+ "timeout",+ Some(("TimeoutError", Utf16String::from_ascii(b"Timed out"))),+ );+ }++ // 3. Otherwise, if xhr’s response’s aborted flag is set, run the request error steps for xhr, abort, and "AbortError" DOMException.+ let response = self.response_record();+ if response.aborted() {+ return self.request_error_steps(vm, "abort", Some(("AbortError", Utf16String::from_ascii(b"Aborted"))));+ }++ // 4. Otherwise, if xhr’s response is a network error, then run the request error steps for xhr, error, and "NetworkError" DOMException.+ if response.is_network_error() {+ let message = response+ .network_error_message()+ .unwrap_or_else(|| Utf16String::from_ascii(b"Unknown error"));+ return self.request_error_steps(vm, "error", Some(("NetworkError", message)));+ }++ Ok(())+ }++ // https://xhr.spec.whatwg.org/#request-error-steps+ fn request_error_steps(+ &self,+ vm: &Vm,+ event_name: &str,+ exception: Option<(&'static str, Utf16String)>,+ ) -> WebIdlResult<()> {+ self.stop_timeout_timer();+ self.async_request.take();++ // 1. Set xhr’s state to done.+ self.state.set(State::Done);++ // 2. Unset xhr’s send() flag.+ self.send.set(false);+ self.update_pending_activity();++ // 3. Set xhr’s response to a network error.+ self.set_response(Response::network_error("Failed to load"));++ // 4. If xhr’s synchronous flag is set, then throw exception.+ if self.synchronous.get() {+ let (name, message) = exception.expect("a synchronous request has an exception to throw");+ return Err(Exception::Dom(name, message));+ }++ // 5. Fire an event named readystatechange at xhr.+ self.fire_event("readystatechange");++ // 6. If xhr’s upload complete flag is unset, then:+ if !self.upload_complete.get() {+ // 1. Set xhr’s upload complete flag.+ self.upload_complete.set(true);++ // 2. If xhr’s upload listener flag is set, then:+ if self.upload_listener.get() {+ // 1. Fire a progress event named event at xhr’s upload object with 0 and 0.+ self.fire_upload_progress_event(vm, event_name, 0, 0);++ // 2. Fire a progress event named loadend at xhr’s upload object with 0 and 0.+ self.fire_upload_progress_event(vm, "loadend", 0, 0);+ }+ }++ // 7. Fire a progress event named event at xhr with 0 and 0.+ self.fire_progress_event(vm, event_name, 0, 0);++ // 8. Fire a progress event named loadend at xhr with 0 and 0.+ self.fire_progress_event(vm, "loadend", 0, 0);++ Ok(())+ }++ fn should_be_kept_alive(&self) -> bool {+ if let Some(window) = window_from_global_object(self.relevant_global_object())+ && window.associated_document().has_been_destroyed()+ {+ return false;+ }++ let state = self.state.get();+ if !((state == State::Opened && self.send.get()) || state == State::HeadersReceived || state == State::Loading)+ {+ return false;+ }++ [+ "readystatechange",+ "progress",+ "abort",+ "error",+ "load",+ "timeout",+ "loadend",+ ]+ .iter()+ .any(|event_type| self.event_target().has_event_listener(event_type))+ }++ fn update_pending_activity(&self) {+ self.event_target()+ .set_has_pending_activity(self.realm, self.should_be_kept_alive());+ }++ // https://xhr.spec.whatwg.org/#the-responseurl-attribute+ pub(crate) fn response_url(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {+ // The responseURL getter steps are to return the empty string if this’s response’s URL is null;+ // otherwise its serialization with the exclude fragment flag set.+ let url = self.response.borrow().fetched().and_then(|response| response.url(true));+ Ok(url.map_or_else(|| UsvString::from_ascii(b""), |url| UsvString::from_utf16_string(&url)))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_event_target.rsnew file mode 100644index 00000000000..d604785b67d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_event_target.rs@@ -0,0 +1,48 @@+/*+ * Copyright (c) 2021, the SerenityOS developers.+ * Copyright (c) 2021, Andreas Kling <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! XMLHttpRequestEventTarget, https://xhr.spec.whatwg.org/#xmlhttprequesteventtarget++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::Trace;++use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::Wrappable;++// https://xhr.spec.whatwg.org/#xmlhttprequesteventtarget+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct XMLHttpRequestEventTarget {+ event_target: CppEventTarget,+}++impl Wrappable for XMLHttpRequestEventTarget {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for XMLHttpRequestEventTarget {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl XMLHttpRequestEventTarget {+ pub(crate) fn new() -> Self {+ Self {+ event_target: CppEventTarget::new(),+ }+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ &self.event_target+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_upload.rs b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_upload.rsnew file mode 100644index 00000000000..6cb8d834edd--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/xhr/xml_http_request_upload.rs@@ -0,0 +1,56 @@+/*+ * Copyright (c) 2023, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! XMLHttpRequestUpload, https://xhr.spec.whatwg.org/#xmlhttprequestupload++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{Trace, Vm};++use super::xml_http_request_event_target::XMLHttpRequestEventTarget;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};++// https://xhr.spec.whatwg.org/#xmlhttprequestupload+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct XMLHttpRequestUpload {+ target: XMLHttpRequestEventTarget,+}++impl Inherits<XMLHttpRequestEventTarget> for XMLHttpRequestUpload {+ fn parent(&self) -> &XMLHttpRequestEventTarget {+ &self.target+ }+}++impl Wrappable for XMLHttpRequestUpload {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.target.cpp_parent()+ }+}++impl GetTheParent for XMLHttpRequestUpload {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl XMLHttpRequestUpload {+ pub(crate) fn create(vm: &Vm) -> Ref<Self> {+ let upload = allocate(vm, |_| Self {+ target: XMLHttpRequestEventTarget::new(),+ });+ upload.event_target().set_owner(upload);+ upload+ }++ pub(crate) fn event_target(&self) -> &CppEventTarget {+ self.target.event_target()+ }+}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 24686a3c725..da43fb71266 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -24,6 +24,7 @@#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/HTML/Window.h>+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/HTML/WindowProxy.h>#include <LibWeb/HTML/WorkerGlobalScope.h>#include <LibWeb/Page/Page.h>@@ -101,12 +102,15 @@ u64 web_bindings_window_page_id(HTML::Window*);DOM::EventTarget* web_bindings_window_as_event_target(HTML::Window*);bool web_bindings_document_has_navigable(DOM::Document*);bool web_bindings_document_is_fully_active(DOM::Document*);+bool web_bindings_document_has_been_destroyed(DOM::Document*);URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object);JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject*);void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject*, void* ctx, void (*on_id)(void*, ReadonlyBytes));bool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);+void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget*, bool has_pending_activity);+void web_bindings_environment_settings_object_encoding_parse_url(HTML::EnvironmentSettingsObject*, FlatPtr url, void* parsed_url, void (*on_url)(void*, URL::FFI::RustUrl const*));void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*));bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);@@ -208,6 +212,11 @@ bool web_bindings_document_is_fully_active(DOM::Document* document)return document->is_fully_active();}+bool web_bindings_document_has_been_destroyed(DOM::Document* document)+{+ return document->has_been_destroyed();+}+URL::FFI::RustUrl web_bindings_document_url(DOM::Document* document){return document->url().to_rust();@@ -238,6 +247,20 @@ bool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope* workerreturn worker_global_scope->is_closing();}+void web_bindings_environment_settings_object_encoding_parse_url(HTML::EnvironmentSettingsObject* settings_object, FlatPtr url, void* parsed_url, void (*on_url)(void*, URL::FFI::RustUrl const*))+{+ auto result = settings_object->encoding_parse_url(Utf16String::from_raw(url));+ if (!result.has_value())+ return;+ auto rust_url = result->to_rust();+ on_url(parsed_url, &rust_url);+}++void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget* event_target, bool has_pending_activity)+{+ HTML::relevant_window_or_worker_global_scope(static_cast<JS::Realm*>(realm)->global_object()).set_has_pending_activity(*event_target, has_pending_activity);+}+void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*)){HTML::TemporaryExecutionContext execution_context { *static_cast<JS::Realm*>(realm), callbacks_enabled ? HTML::TemporaryExecutionContext::CallbacksEnabled::Yes : HTML::TemporaryExecutionContext::CallbacksEnabled::No };diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cppindex dcad910183b..8fd247f7531 100644--- a/Libraries/LibWeb/Bindings/RustEventTarget.cpp+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp@@ -111,6 +111,7 @@ RustEventTarget* web_bindings_create_event_target();void web_bindings_set_event_target_owner(RustEventTarget*, u16 interface_name, RustInterfaceCell* owner, RustEventTarget::GetTheParent);void web_bindings_set_event_listener_list_changed_steps(RustEventTarget*, RustEventTarget::EventListenerListChanged);bool web_bindings_has_event_listener(DOM::EventTarget*, ReadonlyBytes type);+bool web_bindings_has_event_listeners(DOM::EventTarget*);JSValue web_bindings_event_handler_attribute(RustEventTarget*, ReadonlyBytes name);void web_bindings_set_event_handler_attribute(RustEventTarget*, ReadonlyBytes name, JSValue);void web_bindings_add_event_listener(void* realm, DOM::EventTarget*, ReadonlyBytes type, JSObject* callback);@@ -149,6 +150,11 @@ bool web_bindings_has_event_listener(DOM::EventTarget* event_target, ReadonlyBytreturn event_target->has_event_listener(Utf16FlyString::from_utf8_without_validation(type));}+bool web_bindings_has_event_listeners(DOM::EventTarget* event_target)+{+ return event_target->has_event_listeners();+}+// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-idl-attributesJSValue web_bindings_event_handler_attribute(RustEventTarget* event_target, ReadonlyBytes name){diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 62af9d0fb45..1b45500d0ad 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -1001,11 +1001,8 @@ set(SOURCESWebVTT/Parser.cppWebVTT/VTTCue.cppWebVTT/VTTRegion.cpp- XHR/EventNames.cppXHR/FormData.cppXHR/XMLHttpRequest.cpp- XHR/XMLHttpRequestEventTarget.cpp- XHR/XMLHttpRequestUpload.cppXLink/AttributeNames.cppXML/XMLDocumentBuilder.cppXML/XMLFragmentParser.cppdiff --git a/Libraries/LibWeb/Fetch/BodyInit.cpp b/Libraries/LibWeb/Fetch/BodyInit.cppindex d2c5f81067a..30aeda65bce 100644--- a/Libraries/LibWeb/Fetch/BodyInit.cpp+++ b/Libraries/LibWeb/Fetch/BodyInit.cpp@@ -23,6 +23,27 @@namespace Web::Fetch {+struct BodyInitABI {+ enum class Kind : u8 {+ Blob,+ Bytes,+ FormData,+ URLSearchParams,+ String,+ };++ Kind kind;+ void* cell;+ ReadonlyBytes bytes;+ FlatPtr string;+};++extern "C" {++// Called by Bindings/Rust/src/fetch/body_init.rs.+Infrastructure::Body* web_fetch_safely_extract_body(void* realm, BodyInitABI const*, FlatPtr* out_type);+}+// https://fetch.spec.whatwg.org/#bodyinit-safely-extractInfrastructure::BodyWithType safely_extract_body(JS::Realm& realm, BodyInitOrReadableBytes const& object){@@ -176,4 +197,26 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm,return Infrastructure::BodyWithType { .body = body, .type = move(type) };}+Infrastructure::Body* web_fetch_safely_extract_body(void* realm, BodyInitABI const* object, FlatPtr* out_type)+{+ auto body_init = [&]() -> BodyInitOrReadableBytes {+ switch (object->kind) {+ case BodyInitABI::Kind::Blob:+ return GC::Ref { *static_cast<FileAPI::Blob*>(object->cell) };+ case BodyInitABI::Kind::Bytes:+ return object->bytes;+ case BodyInitABI::Kind::FormData:+ return GC::Ref { *static_cast<XHR::FormData*>(object->cell) };+ case BodyInitABI::Kind::URLSearchParams:+ return GC::Ref { *static_cast<DOMURL::URLSearchParams*>(object->cell) };+ case BodyInitABI::Kind::String:+ return Utf16String::from_raw(object->string);+ }+ VERIFY_NOT_REACHED();+ }();+ auto body_with_type = safely_extract_body(*static_cast<JS::Realm*>(realm), body_init);+ *out_type = body_with_type.type.has_value() ? move(*body_with_type.type).into_raw() : 0;+ return body_with_type.body.ptr();+}+}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 04ee2d83602..5a10ab0cf01 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -5,6 +5,7 @@*/#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>#include <LibWeb/Fetch/Fetching/PendingResponse.h>@@ -12,6 +13,8 @@#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/Scripting/Agent.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/Page/RenderingStats.h>#include <LibWeb/WebDriver/BiDi/BiDi.h>@@ -20,6 +23,16 @@namespace Web::Fetch::Infrastructure {+extern "C" {++// Called by Bindings/Rust/src/fetch/infrastructure/fetch_controller.rs.+FetchController* web_fetch_controller_create(JSObject* global_object);+void web_fetch_controller_terminate(FetchController*);+void web_fetch_controller_abort(FetchController*, void* realm);+bool web_fetch_controller_has_report_timing_steps(FetchController*);+void web_fetch_controller_report_timing(FetchController*, JSObject* global_object);+}+GC_DEFINE_ALLOCATOR(FetchController);FetchController::FetchController(FetchControllerRegistry& registry)@@ -297,4 +310,30 @@ void FetchControllerHolder::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_controller);}+FetchController* web_fetch_controller_create(JSObject* global_object)+{+ auto& relevant_agent = HTML::relevant_agent(*JS::HostABI::object_from_abi(global_object));+ return FetchController::create(relevant_agent.fetch_controller_registry).ptr();+}++void web_fetch_controller_terminate(FetchController* controller)+{+ controller->terminate();+}++void web_fetch_controller_abort(FetchController* controller, void* realm)+{+ controller->abort(*static_cast<JS::Realm*>(realm), {});+}++bool web_fetch_controller_has_report_timing_steps(FetchController* controller)+{+ return controller->has_report_timing_steps();+}++void web_fetch_controller_report_timing(FetchController* controller, JSObject* global_object)+{+ controller->report_timing(*JS::HostABI::object_from_abi(global_object));+}+}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cppindex edee441c51c..ff1f4c798ee 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp@@ -19,6 +19,12 @@namespace Web::Fetch::Infrastructure {+extern "C" {++// Called by Bindings/Rust/src/fetch/infrastructure/http/bodies.rs.+bool web_fetch_body_length(Body*, u64* out_length);+}+GC_DEFINE_ALLOCATOR(Body);FetchBody::FetchBody(Optional<Core::ImmutableBytes> source, Optional<u64> length)@@ -235,4 +241,12 @@ void cancel_incremental_read(Streams::ReadableStreamDefaultReader& reader)reader.cancel({});}+bool web_fetch_body_length(Body* body, u64* out_length)+{+ if (!body->length().has_value())+ return false;+ *out_length = *body->length();+ return true;+}+}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cppindex 3326425859d..741a22b6628 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp@@ -19,6 +19,13 @@namespace Web::Fetch::Infrastructure {+extern "C" {++// Called by Bindings/Rust/src/fetch/infrastructure/http/requests.rs.+bool web_fetch_request_done(Request*);+void web_fetch_request_unref(Request*);+}+NonnullRefPtr<Request> Request::create(){return adopt_ref(*new Request(HTTP::HeaderList::create()));@@ -644,4 +651,14 @@ Optional<Request::Priority> request_priority_from_string(Utf16String const& strireturn request_priority_from_string(string.utf16_view());}+bool web_fetch_request_done(Request* request)+{+ return request->done();+}++void web_fetch_request_unref(Request* request)+{+ request->unref();+}+}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cppindex 22f0c47b50f..5c8c8ee7f44 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/ResponseView.cpp@@ -5,10 +5,28 @@*/#include <LibGC/Heap.h>+#include <LibHTTP/HeaderList.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>namespace Web::Fetch::Infrastructure {+extern "C" {++// Called by Bindings/Rust/src/fetch/infrastructure/http/response_view.rs.+bool web_fetch_response_is_network_error(ResponseView*);+bool web_fetch_response_aborted(ResponseView*);+u16 web_fetch_response_status(ResponseView*);+void web_fetch_response_status_message(ResponseView*, void* bytes, void (*on_bytes)(void*, ReadonlyBytes));+bool web_fetch_response_get_header(ResponseView*, ReadonlyBytes name, void* bytes, void (*on_bytes)(void*, ReadonlyBytes));+void web_fetch_response_sort_and_combine(ResponseView*, void* headers, void (*on_header)(void*, ReadonlyBytes name, ReadonlyBytes value));+bool web_fetch_response_extract_length(ResponseView*, u64* out_length);+FlatPtr web_fetch_response_extract_mime_type(ResponseView*);+FlatPtr web_fetch_response_url(ResponseView*, bool exclude_fragment);+bool web_fetch_response_has_body(ResponseView*);+FlatPtr web_fetch_response_network_error_message(ResponseView*);+}+GC_DEFINE_ALLOCATOR(ResponseView);GC::Ref<ResponseView> ResponseView::create(NonnullRefPtr<Response const> record, GC::Ptr<Body> body_view)@@ -80,4 +98,77 @@ GC::Ref<ResponseView> ResponseView::clone(JS::Realm& realm) constreturn create(m_record->clone(), body_view);}+bool web_fetch_response_is_network_error(ResponseView* response)+{+ return response->is_network_error();+}++bool web_fetch_response_aborted(ResponseView* response)+{+ return response->aborted();+}++u16 web_fetch_response_status(ResponseView* response)+{+ return response->status();+}++void web_fetch_response_status_message(ResponseView* response, void* bytes, void (*on_bytes)(void*, ReadonlyBytes))+{+ on_bytes(bytes, response->status_message().bytes());+}++bool web_fetch_response_get_header(ResponseView* response, ReadonlyBytes name, void* bytes, void (*on_bytes)(void*, ReadonlyBytes))+{+ auto value = response->header_list()->get(StringView { name });+ if (!value.has_value())+ return false;+ on_bytes(bytes, value->bytes());+ return true;+}++void web_fetch_response_sort_and_combine(ResponseView* response, void* headers, void (*on_header)(void*, ReadonlyBytes name, ReadonlyBytes value))+{+ for (auto const& header : response->header_list()->sort_and_combine())+ on_header(headers, header.name.bytes(), header.value.bytes());+}++bool web_fetch_response_extract_length(ResponseView* response, u64* out_length)+{+ auto length = response->header_list()->extract_length();+ if (!length.has<u64>())+ return false;+ *out_length = length.get<u64>();+ return true;+}++FlatPtr web_fetch_response_extract_mime_type(ResponseView* response)+{+ auto mime_type = extract_mime_type(response->header_list());+ if (!mime_type.has_value())+ return 0;+ return Utf16String::from_utf8(mime_type->serialized()).into_raw();+}++FlatPtr web_fetch_response_url(ResponseView* response, bool exclude_fragment)+{+ auto url = response->url();+ if (!url.has_value())+ return 0;+ return Utf16String::from_utf8(url->serialize(exclude_fragment ? URL::ExcludeFragment::Yes : URL::ExcludeFragment::No)).into_raw();+}++bool web_fetch_response_has_body(ResponseView* response)+{+ return response->body() != nullptr;+}++FlatPtr web_fetch_response_network_error_message(ResponseView* response)+{+ auto const& message = response->network_error_message();+ if (!message.has_value())+ return 0;+ return Utf16String::from_utf8(*message).into_raw();+}+}diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 720b8ce6eb1..fdd2b469ce8 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1301,8 +1301,6 @@ namespace Web::XHR {class FormData;class XMLHttpRequest;-class XMLHttpRequestEventTarget;-class XMLHttpRequestUpload;struct FormDataEntry;diff --git a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cppindex 9b1e33f6feb..911e15960ac 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLEncodingDetection.cpp@@ -22,6 +22,12 @@namespace Web::HTML {+extern "C" {++// Called by Bindings/Rust/src/xhr/xml_http_request.rs.+void web_html_get_an_xml_encoding(ReadonlyBytes input, void* label, void (*on_label)(void*, ReadonlyBytes));+}+static Utf16FlyString prescan_attribute_name(Utf16StringBuilder const& attribute_name){return Utf16FlyString::from_utf16(attribute_name.view());@@ -742,4 +748,10 @@ EncodingSniffingResult sniff_encoding_after_prescan(DOM::Document& document, Reareturn { "UTF-8", EncodingConfidence::Tentative };}+void web_html_get_an_xml_encoding(ReadonlyBytes input, void* label, void (*on_label)(void*, ReadonlyBytes))+{+ if (auto encoding = get_an_xml_encoding(input); encoding.has_value())+ on_label(label, encoding->bytes());+}+}diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 03bf443a15e..8b4e0adbd11 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -558,7 +558,7 @@ bool Internals::message_ports_are_directly_entangled(HTML::MessagePort& first, HGC::Ref<XHR::XMLHttpRequest> Internals::create_xml_http_request_for_document(DOM::Document& document){VERIFY(document.window());- return XHR::XMLHttpRequest::create(*document.window());+ return XHR::XMLHttpRequest::create(document.window()->principal_realm());}Optional<Painting::HitTestResult> Internals::hit_test(double x, double y)diff --git a/Libraries/LibWeb/Platform/Timer.cpp b/Libraries/LibWeb/Platform/Timer.cppindex 5fbcb4418c8..dc663d1699e 100644--- a/Libraries/LibWeb/Platform/Timer.cpp+++ b/Libraries/LibWeb/Platform/Timer.cpp@@ -7,10 +7,19 @@#include <LibCore/Timer.h>#include <LibGC/Function.h>#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Platform/Timer.h>namespace Web::Platform {+extern "C" {++// Called by Bindings/Rust/src/platform/timer.rs.+Timer* web_platform_timer_create_single_shot(u64 milliseconds, void* cell, void (*steps)(JSVM*, void*));+void web_platform_timer_stop(Timer*);+}+GC_DEFINE_ALLOCATOR(Timer);Timer::Timer()@@ -115,4 +124,21 @@ void Timer::set_single_shot(bool single_shot)m_timer->set_single_shot(single_shot);}+Timer* web_platform_timer_create_single_shot(u64 milliseconds, void* cell, void (*steps)(JSVM*, void*))+{+ // NB: The timer's captures, which the collector traces, keep the cell alive until the steps run or the timer stops.+ auto timeout_handler = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& cell, auto& steps) {+ steps(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr());+ });+ auto timer = Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(static_cast<i64>(milliseconds)), timeout_handler);+ timer->start();+ return timer.ptr();+}++void web_platform_timer_stop(Timer* timer)+{+ timer->stop();+ timer->on_timeout = nullptr;+}+}diff --git a/Libraries/LibWeb/XHR/EventNames.cpp b/Libraries/LibWeb/XHR/EventNames.cppdeleted file mode 100644index e081b4244e8..00000000000--- a/Libraries/LibWeb/XHR/EventNames.cpp+++ /dev/null@@ -1,16 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/XHR/EventNames.h>--namespace Web::XHR::EventNames {--#define __ENUMERATE_XHR_EVENT(name) \- Utf16FlyString const& name = *new Utf16FlyString(#name##_utf16_fly_string);-ENUMERATE_XHR_EVENTS-#undef __ENUMERATE_XHR_EVENT--}diff --git a/Libraries/LibWeb/XHR/EventNames.h b/Libraries/LibWeb/XHR/EventNames.hdeleted file mode 100644index 48d25c68fb3..00000000000--- a/Libraries/LibWeb/XHR/EventNames.h+++ /dev/null@@ -1,27 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Utf16FlyString.h>--namespace Web::XHR::EventNames {--#define ENUMERATE_XHR_EVENTS \- __ENUMERATE_XHR_EVENT(abort) \- __ENUMERATE_XHR_EVENT(error) \- __ENUMERATE_XHR_EVENT(load) \- __ENUMERATE_XHR_EVENT(loadend) \- __ENUMERATE_XHR_EVENT(loadstart) \- __ENUMERATE_XHR_EVENT(progress) \- __ENUMERATE_XHR_EVENT(readystatechange) \- __ENUMERATE_XHR_EVENT(timeout)--#define __ENUMERATE_XHR_EVENT(name) extern Utf16FlyString const& name;-ENUMERATE_XHR_EVENTS-#undef __ENUMERATE_XHR_EVENT--}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cppindex 431333ce9d6..ba4ed8a1a3c 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp@@ -10,795 +10,170 @@#include <AK/ByteBuffer.h>#include <AK/Debug.h>-#include <AK/GenericLexer.h>-#include <AK/QuickSort.h>#include <LibGC/Heap.h>+#include <LibHTTP/Header.h>+#include <LibHTTP/HeaderList.h>#include <LibHTTP/Method.h>#include <LibJS/HostClassBuilder.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Completion.h>-#include <LibJS/Runtime/FunctionObject.h>-#include <LibJS/Runtime/GlobalObject.h>-#include <LibJS/Runtime/PrimitiveString.h>-#include <LibTextCodec/Decoder.h>-#include <LibURL/Origin.h>-#include <LibWeb/Bindings/Blob.h>-#include <LibWeb/Bindings/Document.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/DocumentLoading.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/DOM/EventDispatcher.h>-#include <LibWeb/DOM/IDLEventListener.h>#include <LibWeb/DOM/XMLDocument.h>-#include <LibWeb/DOMURL/DOMURL.h>-#include <LibWeb/Fetch/BodyInit.h>#include <LibWeb/Fetch/Fetching/Fetching.h>-#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>-#include <LibWeb/Fetch/Infrastructure/HTTP.h>-#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>-#include <LibWeb/FileAPI/Blob.h>-#include <LibWeb/HTML/EventHandler.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventNames.h>#include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>#include <LibWeb/HTML/Parser/HTMLParser.h>-#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/HTML/WorkerGlobalScope.h>#include <LibWeb/HTML/XMLSerializer.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/Infra/ByteSequences.h>-#include <LibWeb/Infra/JSON.h>-#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/Platform/Timer.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/XHR/EventNames.h>#include <LibWeb/XHR/XMLHttpRequest.h>-#include <LibWeb/XHR/XMLHttpRequestUpload.h>#include <LibWeb/XML/XMLDocumentBuilder.h>namespace Web::XHR {+struct RequestABI {+ ReadonlyBytes method;+ URL::FFI::RustUrl const* url;+ ReadonlyBytes const* header_names;+ ReadonlyBytes const* header_values;+ size_t header_count;+ void* body;+ bool use_cors_preflight;+ bool include_credentials;+ bool use_url_credentials;+};+extern "C" {// Defined in Bindings/Rust/src/xhr/exports.rs.-void* web_rust_xhr_create_progress_event(JSVM*, void* realm, FlatPtr event_name, bool length_computable, double loaded, double total);-}--GC_DEFINE_ALLOCATOR(XMLHttpRequest);--GC::Ref<XMLHttpRequest> XMLHttpRequest::create(GC::Ref<DOM::EventTarget> relevant_global_object)-{- auto upload_object = GC::Heap::the().allocate<XMLHttpRequestUpload>();- auto author_request_headers = HTTP::HeaderList::create();- auto response = Fetch::Infrastructure::ResponseView::network_error("Not sent yet"_string);- auto& global_scope = HTML::relevant_window_or_worker_global_scope(*relevant_global_object);- auto& relevant_agent = HTML::relevant_agent(HTML::relevant_global_object(global_scope));- auto fetch_controller = Fetch::Infrastructure::FetchController::create(relevant_agent.fetch_controller_registry);- return GC::Heap::the().allocate<XMLHttpRequest>(relevant_global_object, *upload_object, move(author_request_headers), *response, *fetch_controller);-}--GC::Ptr<Bindings::Wrappable> XMLHttpRequest::relevant_global_impl() const-{- return m_global_object;-}--WebIDL::ExceptionOr<GC::Ref<XMLHttpRequest>> XMLHttpRequest::create_for_constructor(JS::Object& relevant_global_object)-{- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object);- VERIFY(global_scope);- return XMLHttpRequest::create(global_scope->this_impl());-}--XMLHttpRequest::XMLHttpRequest(GC::Ref<DOM::EventTarget> relevant_global_object, XMLHttpRequestUpload& upload_object, NonnullRefPtr<HTTP::HeaderList> author_request_headers, Fetch::Infrastructure::ResponseView& response, Fetch::Infrastructure::FetchController& fetch_controller)- : XMLHttpRequestEventTarget()- , m_upload_object(upload_object)- , m_global_object(relevant_global_object)- , m_author_request_headers(move(author_request_headers))- , m_response(response)- , m_fetch_controller(fetch_controller)-{-}--XMLHttpRequest::~XMLHttpRequest() = default;--JS::Object& XMLHttpRequest::relevant_global_object() const-{- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));-}--GC::Ref<DOM::Event> XMLHttpRequest::create_associated_event(Utf16FlyString const& event_name) const-{- return DOM::Event::create(event_name,- HighResolutionTime::current_high_resolution_time(relevant_global_object()));-}--HTML::EnvironmentSettingsObject& XMLHttpRequest::relevant_settings_object() const-{- return HTML::relevant_settings_object(relevant_global_object());-}--void XMLHttpRequest::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_upload_object);- visitor.visit(m_global_object);- visitor.visit(m_request_body);- visitor.visit(m_response);- visitor.visit(m_fetch_controller);- visitor.visit(m_timeout_timer);-- m_response_object.visit(- [&](GC::Ref<DOM::Document> document) { visitor.visit(document); },- [&](GC::Ref<FileAPI::Blob> blob) { visitor.visit(blob); },- [](auto const&) { });- for (auto const& cached_response_object : m_cached_response_objects)- visitor.visit(cached_response_object.object);-}--void XMLHttpRequest::restart_timeout_timer()-{- stop_timeout_timer();- if (!m_send || m_synchronous || !m_async_request || m_async_request->done() || m_timeout == 0)- return;-- // NB: Timeout changes keep the deadline relative to send(), rather than starting a fresh timeout period.- auto elapsed = MonotonicTime::now() - m_async_send_start_time;- auto remaining = max(AK::Duration::zero(), AK::Duration::from_milliseconds(m_timeout) - elapsed);- m_timeout_timer = Platform::Timer::create_single_shot(heap(), remaining, nullptr);- auto request = NonnullRefPtr { *m_async_request };- m_timeout_timer->on_timeout = GC::create_function(heap(), GC::captures(*this, request, m_fetch_controller), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Infrastructure::Request>& request, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {- if (self.m_async_request.ptr() != request.ptr() || self.m_fetch_controller != fetch_controller)- return;-- self.stop_timeout_timer();- self.m_async_request = nullptr;- if (!request->done()) {- self.m_timed_out = true;- fetch_controller->terminate();- MUST(self.handle_errors());- }- });- m_timeout_timer->start();-}--void XMLHttpRequest::stop_timeout_timer()-{- if (!m_timeout_timer)- return;- m_timeout_timer->stop();- m_timeout_timer->on_timeout = nullptr;- m_timeout_timer = nullptr;-}--// https://xhr.spec.whatwg.org/#concept-event-fire-progress-static void fire_progress_event(JS::Object& relevant_global_object, XMLHttpRequestEventTarget& target,- Utf16FlyString const& event_name, u64 transmitted, u64 length)-{- // To fire a progress event named e at target, given transmitted and length, means to fire an event named e at target, using ProgressEvent,- // with the loaded attribute initialized to transmitted, and if length is not 0, with the lengthComputable attribute initialized to true- // and the total attribute initialized to length.- auto& realm = HTML::relevant_realm(relevant_global_object);- auto* event = web_rust_xhr_create_progress_event(JS::HostABI::vm_to_abi(realm.vm()), &realm, event_name.to_utf16_string().into_raw(), length != 0, transmitted, length);- target.dispatch_event(*static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)));-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetext-WebIDL::ExceptionOr<Utf16String> XMLHttpRequest::response_text() const-{- // 1. If this’s response type is not the empty string or "text", then throw an "InvalidStateError" DOMException.- if (m_response_type != XMLHttpRequest::ResponseType::Empty && m_response_type != XMLHttpRequest::ResponseType::Text)- return WebIDL::InvalidStateError::create("XHR responseText can only be used for responseType \"\" or \"text\""_utf16);-- // 2. If this’s state is not loading or done, then return the empty string.- if (m_state != State::Loading && m_state != State::Done)- return Utf16String {};-- // 3. Return the result of getting a text response for this.- return get_text_response();-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsexml-WebIDL::ExceptionOr<GC::Ptr<DOM::Document>> XMLHttpRequest::response_xml()-{- // 1. If this’s response type is not the empty string or "document", then throw an "InvalidStateError" DOMException.- if (m_response_type != XMLHttpRequest::ResponseType::Empty && m_response_type != XMLHttpRequest::ResponseType::Document)- return WebIDL::InvalidStateError::create("XHR responseXML can only be used for responseXML \"\" or \"document\""_utf16);+void* web_rust_xhr_create(JSVM*, void* realm);+void web_rust_xhr_process_request_body_chunk_length(JSVM*, void* xhr, u64 request_body_length, u64 bytes_length);+void web_rust_xhr_process_request_end_of_body(JSVM*, void* xhr, u64 request_body_length);+void web_rust_xhr_process_response(JSVM*, void* xhr, Fetch::Infrastructure::ResponseView*);+void web_rust_xhr_process_body_chunk(JSVM*, void* xhr, u64 length, ReadonlyBytes);+void web_rust_xhr_process_end_of_body(JSVM*, void* xhr);+void web_rust_xhr_process_body_error(JSVM*, void* xhr);+void web_rust_xhr_process_response_consume_body(JSVM*, void* xhr, void* sync_send, Fetch::Infrastructure::ResponseView*, u8 kind, ReadonlyBytes);+void web_rust_xhr_fetch_stopped(JSVM*, void* xhr, Fetch::Infrastructure::FetchController*);+bool web_rust_xhr_sync_send_is_over(void* sync_send);- // 2. If this’s state is not done, then return null.- if (m_state != State::Done)- return nullptr;-- // 3. Assert: this’s response object is not failure.- VERIFY(!m_response_object.has<Failure>());-- // 4. If this’s response object is non-null, then return it.- if (auto* document = m_response_object.get_pointer<GC::Ref<DOM::Document>>())- return *document;-- // 5. Set a document response for this.- set_document_response();-- // 6. Return this’s response object.- if (auto* document = m_response_object.get_pointer<GC::Ref<DOM::Document>>())- return *document;- return nullptr;-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-response-WebIDL::ExceptionOr<JS::Value> XMLHttpRequest::response(JS::Realm& realm)-{- auto& vm = realm.vm();- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);- auto wrapper = Bindings::wrap(wrapper_world, realm, GC::Ref { *this });- m_cached_response_objects.remove_all_matching([](auto const& entry) { return !entry.wrapper; });-- auto cached_response_object = [&]() -> Optional<JS::Value> {- auto cached = m_cached_response_objects.find_if([&](auto const& entry) { return entry.wrapper.ptr() == wrapper; });- if (cached.is_end())- return {};- return cached->object;- };-- auto cache_response_object = [&](JS::Value object) {- m_cached_response_objects.append({ wrapper, object });- };-- // 1. If this’s response type is the empty string or "text", then:- if (m_response_type == XMLHttpRequest::ResponseType::Empty || m_response_type == XMLHttpRequest::ResponseType::Text) {- // 1. If this’s state is not loading or done, then return the empty string.- if (m_state != State::Loading && m_state != State::Done)- return JS::PrimitiveString::create(vm, Utf16String {});-- // 2. Return the result of getting a text response for this.- return JS::PrimitiveString::create(vm, get_text_response());- }-- // 2. If this’s state is not done, then return null.- if (m_state != State::Done)- return JS::js_null();-- // 3. If this’s response object is failure, then return null.- if (m_response_object.has<Failure>())- return JS::js_null();-- // 4. If this’s response object is non-null, then return it.- if (auto document = response_document())- return Bindings::wrap(wrapper_world, realm, GC::Ref { *document });- if (auto blob = response_blob())- return Bindings::wrap(wrapper_world, realm, GC::Ref { *blob });-- // 5. If this’s response type is "arraybuffer",- if (m_response_type == XMLHttpRequest::ResponseType::Arraybuffer) {- if (auto cached_object = cached_response_object(); cached_object.has_value())- return *cached_object;-- // then set this’s response object to a new ArrayBuffer object representing this’s received bytes. If this throws- // an exception, then set this’s response object to failure and return null.- auto buffer = JS::ArrayBuffer::create(realm, MUST(ByteBuffer::copy(m_received_bytes.bytes())));- cache_response_object(buffer);- return buffer;- }-- // 6. Otherwise, if this’s response type is "blob", set this’s response object to a new Blob object representing- // this’s received bytes with type set to the result of get a final MIME type for this.- if (m_response_type == XMLHttpRequest::ResponseType::Blob) {- auto mime_type_as_string = get_final_mime_type().serialized();- auto blob = FileAPI::Blob::create(MUST(ByteBuffer::copy(m_received_bytes.bytes())), move(mime_type_as_string));- set_blob_response_object(blob);- return Bindings::wrap(wrapper_world, realm, blob);- }-- // 7. Otherwise, if this’s response type is "document", set a document response for this.- if (m_response_type == XMLHttpRequest::ResponseType::Document) {- set_document_response();- if (auto document = response_document())- return Bindings::wrap(wrapper_world, realm, GC::Ref { *document });- return JS::js_null();- }-- // 8. Otherwise:- // 1. Assert: this’s response type is "json".- // Note: Automatically done by the layers above us.-- // 2. If this’s response’s body is null, then return null.- if (!m_response->body())- return JS::js_null();-- if (auto cached_object = cached_response_object(); cached_object.has_value())- return *cached_object;-- // 3. Let jsonObject be the result of running parse JSON from bytes on this’s received bytes. If that threw an- // exception, then return null.- auto json_object_result = Infra::parse_json_bytes_to_javascript_value(realm, m_received_bytes);- if (json_object_result.is_error())- return JS::js_null();-- // 4. Set this’s response object to jsonObject.- auto json_object = json_object_result.release_value();- cache_response_object(json_object);-- // 9. Return this’s response object.- return json_object;-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-responsetype-WebIDL::ExceptionOr<void> XMLHttpRequest::set_response_type(ResponseType response_type)-{- auto* current_window = HTML::window_from_global_object(HTML::current_global_object());-- // 1. If the current global object is not a Window object and the given value is "document", then return.- if (!current_window && response_type == XMLHttpRequest::ResponseType::Document)- return {};-- // 2. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.- if (m_state == State::Loading || m_state == State::Done)- return WebIDL::InvalidStateError::create("Can't readyState when XHR is loading or done"_utf16);-- // 3. If the current global object is a Window object and this’s synchronous flag is set, then throw an "InvalidAccessError" DOMException.- if (current_window && m_synchronous)- return WebIDL::InvalidAccessError::create("Can't set readyState on synchronous XHR in Window environment"_utf16);-- // 4. Set this’s response type to the given value.- m_response_type = response_type;- return {};+// Called by Bindings/Rust/src/xhr/xml_http_request.rs.+bool web_xhr_is_method(ReadonlyBytes method);+bool web_xhr_is_forbidden_method(ReadonlyBytes method);+void web_xhr_normalize_method(ReadonlyBytes method, void* bytes, void (*on_bytes)(void*, ReadonlyBytes));+void web_xhr_normalize_header_value(ReadonlyBytes value, void* bytes, void (*on_bytes)(void*, ReadonlyBytes));+bool web_xhr_is_header_name(ReadonlyBytes name);+bool web_xhr_is_header_value(ReadonlyBytes value);+bool web_xhr_is_forbidden_request_header(ReadonlyBytes name, ReadonlyBytes value);+bool web_xhr_document_is_html_document(JSObject* document);+Fetch::Infrastructure::Body* web_xhr_document_as_body(void* realm, JSObject* document);+Fetch::Infrastructure::Request* web_xhr_create_request(void* realm, RequestABI const*);+Fetch::Infrastructure::FetchController* web_xhr_fetch(void* realm, Fetch::Infrastructure::Request*, void* xhr, void* sync_send, u64 request_body_length);+void web_xhr_incrementally_read_body(void* realm, Fetch::Infrastructure::ResponseView*, void* xhr, u64 length);+void web_xhr_pause_until_sync_send_is_over(void* sync_send);+DOM::Document* web_xhr_create_document_response(JSObject* global_object, Fetch::Infrastructure::ResponseView*, ReadonlyBytes received_bytes, FlatPtr final_mime, bool final_mime_is_html, ReadonlyBytes final_encoding, bool has_final_encoding);}-GC::Ptr<DOM::Document> XMLHttpRequest::response_document() const+static JSVM* vm_abi(){- if (auto* document = m_response_object.get_pointer<GC::Ref<DOM::Document>>())- return *document;- return nullptr;+ return JS::HostABI::vm_to_abi(JS::VM::the());}-GC::Ptr<FileAPI::Blob> XMLHttpRequest::response_blob() const+static DOM::Document& document_from_wrapper(JSObject* document){- if (auto* blob = m_response_object.get_pointer<GC::Ref<FileAPI::Blob>>())- return *blob;- return nullptr;+ return as<DOM::Document>(*Bindings::wrappable_impl_from(JS::HostABI::object_from_abi(document)));}-void XMLHttpRequest::set_blob_response_object(GC::Ref<FileAPI::Blob> blob)+GC::Ref<XMLHttpRequest> XMLHttpRequest::create(JS::Realm& realm){- m_response_object = blob;- m_cached_response_objects.clear();+ return *static_cast<XMLHttpRequest*>(web_rust_xhr_create(JS::HostABI::vm_to_abi(realm.vm()), &realm));}-// https://xhr.spec.whatwg.org/#text-response-Utf16String XMLHttpRequest::get_text_response() const+bool web_xhr_is_method(ReadonlyBytes method){- // 1. If xhr’s response’s body is null, then return the empty string.- if (!m_response->body())- return Utf16String {};-- // 2. Let charset be the result of get a final encoding for xhr.- auto charset = get_final_encoding();-- // 3. If xhr’s response type is the empty string, charset is null, and the result of get a final MIME type for xhr is an XML MIME type,- if (m_response_type == XMLHttpRequest::ResponseType::Empty && !charset.has_value() && get_final_mime_type().is_xml()) {- // then use the rules set forth in the XML specifications to determine the encoding. Let charset be the determined encoding. [XML] [XML-NAMES]- // NB: The encoding declaration names the encoding, which this finds the way the HTML Standard does when- // sniffing an encoding. Without one, charset stays null and is set to UTF-8 below, as the XML- // specification requires.- if (auto xml_encoding = HTML::get_an_xml_encoding(m_received_bytes); xml_encoding.has_value())- charset = TextCodec::get_standardized_encoding(*xml_encoding);- }-- // 4. If charset is null, then set charset to UTF-8.- if (!charset.has_value())- charset = "UTF-8"sv;-- // 5. Return the result of running decode on xhr’s received bytes using fallback encoding charset.- auto decoder = TextCodec::decoder_for(charset.value());-- // If we don't support the decoder yet, let's crash instead of attempting to return something, as the result would be incorrect and create obscure bugs.- VERIFY(decoder.has_value());-- return TextCodec::decode_to_utf16(m_received_bytes, *decoder).release_value_but_fixme_should_propagate_errors();+ return HTTP::is_method(StringView { method });}-// https://xhr.spec.whatwg.org/#document-response-void XMLHttpRequest::set_document_response()+bool web_xhr_is_forbidden_method(ReadonlyBytes method){- // 1. If xhr’s response’s body is null, then return.- if (!m_response->body())- return;-- // 2. Let finalMIME be the result of get a final MIME type for xhr.- auto final_mime = get_final_mime_type();-- // 3. If finalMIME is not an HTML MIME type or an XML MIME type, then return.- if (!final_mime.is_html() && !final_mime.is_xml())- return;-- // 4. If xhr’s response type is the empty string and finalMIME is an HTML MIME type, then return.- if (m_response_type == XMLHttpRequest::ResponseType::Empty && final_mime.is_html())- return;-- // 5. If finalMIME is an HTML MIME type, then:- Optional<Utf16String> charset;- GC::Ptr<DOM::Document> document;- auto& global_scope = HTML::relevant_window_or_worker_global_scope(*m_global_object);- auto& page = [&]() -> Page& {- if (auto* window = as_if<HTML::Window>(&global_scope))- return window->page();- auto* worker_global_scope = as_if<HTML::WorkerGlobalScope>(&global_scope);- VERIFY(worker_global_scope);- auto* worker_page = worker_global_scope->page();- VERIFY(worker_page);- return *worker_page;- }();-- if (final_mime.is_html()) {- // 5.1. Let charset be the result of get a final encoding for xhr.- if (auto final_encoding = get_final_encoding(); final_encoding.has_value())- charset = Utf16String::from_utf8(*final_encoding);-- // 5.2. If charset is null, prescan the first 1024 bytes of xhr’s received bytes and if that does not terminate unsuccessfully then let charset be the return value.- document = DOM::Document::create(page, *m_global_object);- if (!charset.has_value())- if (auto found_charset = HTML::run_prescan_byte_stream_algorithm(*document, m_received_bytes); found_charset.has_value())- charset = Utf16String::from_utf8(MUST(String::from_byte_string(found_charset.value())));-- // 5.3. If charset is null, then set charset to UTF-8.- if (!charset.has_value())- charset = "UTF-8"_utf16;-- // 5.4. Let document be a document that represents the result parsing xhr’s received bytes following the rules set forth in the HTML Standard for an HTML parser with scripting disabled and a known definite encoding charset.- auto scripting_mode = document->is_scripting_enabled() ? HTML::ParserScriptingMode::Normal : HTML::ParserScriptingMode::Disabled;- auto charset_for_parser = charset->to_utf8();- auto parser = HTML::HTMLParser::create_from_byte_string(*document, m_received_bytes, scripting_mode, charset_for_parser);- parser->run(document->url());-- // 5.5. Flag document as an HTML document.- document->set_document_type(DOM::Document::Type::HTML);- }-- // 6. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.- else {- document = DOM::XMLDocument::create(page, *m_global_object, m_response->url().value_or({}));- if (!Web::build_xml_document(*document, m_received_bytes, get_final_encoding(), XMLScriptingSupport::Disabled)) {- reset_response_object();- return;- }- }-- // 7. If charset is null, then set charset to UTF-8.- if (!charset.has_value())- charset = "UTF-8"_utf16;-- // 8. Set document’s encoding to charset.- document->set_encoding(move(charset));-- // 9. Set document’s content type to finalMIME.- document->set_content_type(Utf16FlyString::from_utf8(final_mime.serialized()));-- // 10. Set document’s URL to xhr’s response’s URL.- document->set_url(m_response->url().value_or({}));-- // 11. Set document’s origin to xhr’s relevant settings object’s origin.- document->set_origin(relevant_settings_object().origin());-- // 12. Set xhr’s response object to document.- m_response_object = GC::Ref { *document };- m_cached_response_objects.clear();+ return HTTP::is_forbidden_method(StringView { method });}-// https://xhr.spec.whatwg.org/#final-mime-type-MimeSniff::MimeType XMLHttpRequest::get_final_mime_type() const+void web_xhr_normalize_method(ReadonlyBytes method, void* bytes, void (*on_bytes)(void*, ReadonlyBytes)){- // 1. If xhr’s override MIME type is null, return the result of get a response MIME type for xhr.- if (!m_override_mime_type.has_value())- return get_response_mime_type();-- // 2. Return xhr’s override MIME type.- return *m_override_mime_type;+ auto normalized_method = HTTP::normalize_method(StringView { method });+ on_bytes(bytes, normalized_method.bytes());}-// https://xhr.spec.whatwg.org/#response-mime-type-MimeSniff::MimeType XMLHttpRequest::get_response_mime_type() const+void web_xhr_normalize_header_value(ReadonlyBytes value, void* bytes, void (*on_bytes)(void*, ReadonlyBytes)){- // 1. Let mimeType be the result of extracting a MIME type from xhr’s response’s header list.- auto mime_type = Fetch::Infrastructure::extract_mime_type(m_response->header_list());-- // 2. If mimeType is failure, then set mimeType to text/xml.- if (!mime_type.has_value())- return MimeSniff::MimeType::create("text"_string, "xml"_string);-- // 3. Return mimeType.- return mime_type.release_value();+ on_bytes(bytes, HTTP::normalize_header_value(StringView { value }).bytes());}-// https://xhr.spec.whatwg.org/#final-charset-Optional<StringView> XMLHttpRequest::get_final_encoding() const+bool web_xhr_is_header_name(ReadonlyBytes name){- // 1. Let label be null.- Optional<String> label;-- // 2. Let responseMIME be the result of get a response MIME type for xhr.- auto response_mime = get_response_mime_type();-- // 3. If responseMIME’s parameters["charset"] exists, then set label to it.- auto response_mime_charset_it = response_mime.parameters().find("charset"sv);- if (response_mime_charset_it != response_mime.parameters().end())- label = response_mime_charset_it->value;-- // 4. If xhr’s override MIME type’s parameters["charset"] exists, then set label to it.- if (m_override_mime_type.has_value()) {- auto override_mime_charset_it = m_override_mime_type->parameters().find("charset"sv);- if (override_mime_charset_it != m_override_mime_type->parameters().end())- label = override_mime_charset_it->value;- }-- // 5. If label is null, then return null.- if (!label.has_value())- return OptionalNone {};-- // 6. Let encoding be the result of getting an encoding from label.- auto encoding = TextCodec::get_standardized_encoding(label.value());-- // 7. If encoding is failure, then return null.- // 8. Return encoding.- return encoding;+ return HTTP::is_header_name(StringView { name });}-// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-setrequestheader-WebIDL::ExceptionOr<void> XMLHttpRequest::set_request_header(String const& name, String const& value)+bool web_xhr_is_header_value(ReadonlyBytes value){- // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.- if (m_state != State::Opened)- return WebIDL::InvalidStateError::create("XHR readyState is not OPENED"_utf16);-- // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.- if (m_send)- return WebIDL::InvalidStateError::create("XHR send() flag is already set"_utf16);-- // NB: The ByteString arguments hold their bytes as code points, which have to be isomorphic encoded back into bytes.- auto header = HTTP::Header::isomorphic_encode(name, value);-- // 3. Normalize value.- header.value = HTTP::normalize_header_value(header.value);-- // 4. If name is not a header name or value is not a header value, then throw a "SyntaxError" DOMException.- if (!HTTP::is_header_name(header.name))- return WebIDL::SyntaxError::create("Header name contains invalid characters."_utf16);- if (!HTTP::is_header_value(header.value))- return WebIDL::SyntaxError::create("Header value contains invalid characters."_utf16);-- // 5. If (name, value) is a forbidden request-header, then return.- if (HTTP::is_forbidden_request_header(header))- return {};-- // 6. Combine (name, value) in this’s author request headers.- m_author_request_headers->combine(move(header));-- return {};+ return HTTP::is_header_value(StringView { value });}-// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-open-WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method, Utf16String const& url)+bool web_xhr_is_forbidden_request_header(ReadonlyBytes name, ReadonlyBytes value){- // 7. If the async argument is omitted, set async to true, and set username and password to null.- return open(method, url, true, {}, {});+ return HTTP::is_forbidden_request_header({ ByteString { name }, ByteString { value } });}-WebIDL::ExceptionOr<void> XMLHttpRequest::open(String const& method, Utf16String const& url, bool async, Optional<Utf16String> const& username, Optional<Utf16String> const& password)+bool web_xhr_document_is_html_document(JSObject* document){- // 1. If this’s relevant global object is a Window object and its associated Document is not fully active, then throw an "InvalidStateError" DOMException.- if (auto const* window = HTML::window_from_global_object(relevant_global_object()); window) {- if (!window->associated_document().is_fully_active())- return WebIDL::InvalidStateError::create("Invalid state: Window's associated document is not fully active."_utf16);- }-- // 2. If method is not a method, then throw a "SyntaxError" DOMException.- if (!HTTP::is_method(method))- return WebIDL::SyntaxError::create("An invalid or illegal string was specified."_utf16);-- // 3. If method is a forbidden method, then throw a "SecurityError" DOMException.- if (HTTP::is_forbidden_method(method))- return WebIDL::SecurityError::create("Forbidden method, must not be 'CONNECT', 'TRACE', or 'TRACK'"_utf16);-- // 4. Normalize method.- auto normalized_method = HTTP::normalize_method(method);-- // 5. Let parsedURL be the result of encoding-parsing a URL url, relative to this’s relevant settings object.- auto& relevant_settings_object = this->relevant_settings_object();- auto parsed_url = relevant_settings_object.encoding_parse_url(url);-- // 6. If parsedURL is failure, then throw a "SyntaxError" DOMException.- if (!parsed_url.has_value())- return WebIDL::SyntaxError::create("Invalid URL"_utf16);-- // 7. If the async argument is omitted, set async to true, and set username and password to null.- // NOTE: This is handled in the overload lacking the async argument.-- // 8. If parsedURL’s host is non-null, then:- if (parsed_url->host().has_value()) {- // 1. If the username argument is not null, set the username given parsedURL and username.- if (username.has_value())- parsed_url->set_username(username->utf16_view());- // 2. If the password argument is not null, set the password given parsedURL and password.- if (password.has_value())- parsed_url->set_password(password->utf16_view());- }-- // 9. If async is false, the current global object is a Window object, and either this’s timeout is- // not 0 or this’s response type is not the empty string, then throw an "InvalidAccessError" DOMException.- if (!async- && HTML::window_from_global_object(HTML::current_global_object())- && (m_timeout != 0 || m_response_type != XMLHttpRequest::ResponseType::Empty)) {- return WebIDL::InvalidAccessError::create("Synchronous XMLHttpRequests in a Window context do not support timeout or a non-empty responseType"_utf16);- }-- // 10. Terminate this’s fetch controller.- // Spec Note: A fetch can be ongoing at this point.- m_fetch_controller->terminate();- stop_timeout_timer();- m_async_request = nullptr;- HTML::relevant_window_or_worker_global_scope(*m_global_object).set_has_pending_activity(*this, false);-- // 11. Set variables associated with the object as follows:- // Unset this’s send() flag.- m_send = false;- // Set this’s request method to method.- m_request_method = move(normalized_method);- // Set this’s request URL to parsedURL.- m_request_url = parsed_url.release_value();- // Empty this’s author request headers.- m_author_request_headers->clear();- // Set this’s request body to null.- m_request_body = nullptr;- // Set this’s synchronous flag if async is false; otherwise unset this’s synchronous flag.- m_synchronous = !async;- // Unset this’s upload listener flag.- m_upload_listener = false;- // Set this’s response to a network error.- m_response = Fetch::Infrastructure::ResponseView::network_error("Not yet sent"_string);- // Set this’s received bytes to the empty byte sequence.- m_received_bytes = {};- // Set this’s response object to null.- reset_response_object();- // Spec Note: Override MIME type is not overridden here as the overrideMimeType() method can be invoked before the open() method.-- // 12. If this’s state is not opened, then:- if (m_state != State::Opened) {- // 1. Set this’s state to opened.- m_state = State::Opened;-- // 2. Fire an event named readystatechange at this.- dispatch_event(create_associated_event(EventNames::readystatechange));- }-- return {};+ return document_from_wrapper(document).is_html_document();}-void XMLHttpRequest::reset_response_object()+// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+Fetch::Infrastructure::Body* web_xhr_document_as_body(void* realm, JSObject* document){- m_response_object = {};- m_cached_response_objects.clear();+ // If body is a Document, then set this’s request body to body, serialized, converted, and UTF-8 encoded.+ auto string_serialized_document = MUST(document_from_wrapper(document).serialize_fragment(HTML::RequireWellFormed::No));+ auto string_serialized_document_utf8 = string_serialized_document.to_well_formed_utf8();+ return Fetch::Infrastructure::byte_sequence_as_body(*static_cast<JS::Realm*>(realm), string_serialized_document_utf8.bytes()).ptr();}// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send-WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestBodyInit body)+Fetch::Infrastructure::Request* web_xhr_create_request(void* realm, RequestABI const* request_abi){- auto& associated_realm = HTML::relevant_realm(relevant_global_object());-- // 1. If this’s state is not opened, then throw an "InvalidStateError" DOMException.- if (m_state != State::Opened)- return WebIDL::InvalidStateError::create("XHR readyState is not OPENED"_utf16);-- // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.- if (m_send)- return WebIDL::InvalidStateError::create("XHR send() flag is already set"_utf16);-- // 3. If this’s request method is `GET` or `HEAD`, then set body to null.- if (m_request_method.is_one_of("GET"sv, "HEAD"sv))- body = Empty {};-- // 4. If body is not null, then:- if (!body.has<Empty>()) {- // 1. Let extractedContentType be null.- Optional<Utf16String> extracted_content_type;-- // 2. If body is a Document, then set this’s request body to body, serialized, converted, and UTF-8 encoded.- if (body.has<GC::Ref<DOM::Document>>()) {- auto string_serialized_document = TRY(body.get<GC::Ref<DOM::Document>>()->serialize_fragment(HTML::RequireWellFormed::No));- auto string_serialized_document_utf8 = string_serialized_document.to_well_formed_utf8();- m_request_body = Fetch::Infrastructure::byte_sequence_as_body(associated_realm, string_serialized_document_utf8.bytes());- }- // 3. Otherwise:- else {- // 1. Let bodyWithType be the result of safely extracting body.- auto body_with_type = Fetch::safely_extract_body(associated_realm, body.downcast<Fetch::BodyInitOrReadableBytes>());-- // 2. Set this’s request body to bodyWithType’s body.- m_request_body = body_with_type.body;-- // 3. Set extractedContentType to bodyWithType’s type.- extracted_content_type = move(body_with_type.type);- }-- // 4. Let originalAuthorContentType be the result of getting `Content-Type` from this’s author request headers.- auto original_author_content_type = m_author_request_headers->get("Content-Type"sv);-- // 5. If originalAuthorContentType is non-null, then:- if (original_author_content_type.has_value()) {- // 1. If body is a Document object, a URLSearchParams object, or a string:- if (body.has<GC::Ref<DOM::Document>>() || body.has<GC::Ref<DOMURL::URLSearchParams>>() || body.has<Utf16String>()) {- // 1. Let contentTypeRecord be the result of parsing originalAuthorContentType.- auto content_type_record = MimeSniff::MimeType::parse(original_author_content_type.value());-- // 2. If contentTypeRecord is not failure, contentTypeRecord’s parameters["charset"] exists, and parameters["charset"] is not an ASCII case-insensitive match for "UTF-8", then:- if (content_type_record.has_value()) {- auto charset_parameter_iterator = content_type_record->parameters().find("charset"sv);- if (charset_parameter_iterator != content_type_record->parameters().end() && !charset_parameter_iterator->value.equals_ignoring_ascii_case("UTF-8"sv)) {- // 1. Set contentTypeRecord’s parameters["charset"] to "UTF-8".- content_type_record->set_parameter("charset"_string, "UTF-8"_string);-- // 2. Let newContentTypeSerialized be the result of serializing contentTypeRecord.- auto new_content_type_serialized = content_type_record->serialized();-- // 3. Set (`Content-Type`, newContentTypeSerialized) in this’s author request headers.- auto header = HTTP::Header::isomorphic_encode("Content-Type"sv, new_content_type_serialized);- m_author_request_headers->set(move(header));- }- }- }- }- // 6. Otherwise:- else {- if (body.has<GC::Ref<DOM::Document>>()) {- auto document = body.get<GC::Ref<DOM::Document>>();-- // NOTE: A document can only be an HTML document or XML document.- // 1. If body is an HTML document, then set (`Content-Type`, `text/html;charset=UTF-8`) in this’s author request headers.- if (document->is_html_document()) {- m_author_request_headers->set({ "Content-Type"sv, "text/html;charset=UTF-8"sv });- }- // 2. Otherwise, if body is an XML document, set (`Content-Type`, `application/xml;charset=UTF-8`) in this’s author request headers.- else if (document->is_xml_document()) {- m_author_request_headers->set({ "Content-Type"sv, "application/xml;charset=UTF-8"sv });- } else {- VERIFY_NOT_REACHED();- }- }- // 3. Otherwise, if extractedContentType is not null, set (`Content-Type`, extractedContentType) in this’s author request headers.- else if (extracted_content_type.has_value()) {- auto header = HTTP::Header::isomorphic_encode("Content-Type"sv, extracted_content_type.value());- m_author_request_headers->set(move(header));- }- }- }-- // 5. If one or more event listeners are registered on this’s upload object, then set this’s upload listener flag.- m_upload_listener = m_upload_object->has_event_listeners();+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto& relevant_settings_object = HTML::relevant_settings_object(js_realm.global_object());// 6. Let req be a new request, initialized as follows:auto request = Fetch::Infrastructure::Request::create();// method// This’s request method.- request->set_method(m_request_method);+ request->set_method(ByteString { request_abi->method });// URL// This’s request URL.- request->set_url(m_request_url);+ URL::URL url;+ url.set_from_rust(*request_abi->url);+ request->set_url(move(url));// header list// This’s author request headers.- request->set_header_list(m_author_request_headers);+ auto header_list = HTTP::HeaderList::create();+ for (size_t i = 0; i < request_abi->header_count; ++i)+ header_list->append({ ByteString { request_abi->header_names[i] }, ByteString { request_abi->header_values[i] } });+ request->set_header_list(move(header_list));// unsafe-request flag// Set.@@ -806,12 +181,12 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// body// This’s request body.- if (m_request_body)- request->set_body(m_request_body->fetch_body());+ if (request_abi->body)+ request->set_body(static_cast<Fetch::Infrastructure::Body*>(request_abi->body)->fetch_body());// client// This’s relevant settings object.- request->set_client(relevant_settings_object().address());+ request->set_client(relevant_settings_object.address());// mode// "cors".@@ -819,212 +194,49 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// use-CORS-preflight flag// Set if this’s upload listener flag is set.- request->set_use_cors_preflight(m_upload_listener);+ request->set_use_cors_preflight(request_abi->use_cors_preflight);// credentials mode// If this’s cross-origin credentials is true, then "include"; otherwise "same-origin".- request->set_credentials_mode(m_cross_origin_credentials ? Fetch::Infrastructure::Request::CredentialsMode::Include : Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);+ request->set_credentials_mode(request_abi->include_credentials ? Fetch::Infrastructure::Request::CredentialsMode::Include : Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);// use-URL-credentials flag// Set if this’s request URL includes credentials.- request->set_use_url_credentials(m_request_url.includes_credentials());+ request->set_use_url_credentials(request_abi->use_url_credentials);// initiator type// "xmlhttprequest".request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::XMLHttpRequest);- // 7. Unset this’s upload complete flag.- m_upload_complete = false;-- // 8. Unset this’s timed out flag.- m_timed_out = false;-- // 9. If req’s body is null, then set this’s upload complete flag.- // NOTE: req's body is always m_request_body here, see step 6.- if (!m_request_body)- m_upload_complete = true;+ return &request.leak_ref();+}- // 10. Set this’s send() flag.- m_send = true;- update_pending_activity();+// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+Fetch::Infrastructure::FetchController* web_xhr_fetch(void* realm, Fetch::Infrastructure::Request* request, void* xhr, void* sync_send, u64 request_body_length)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ GC::Ref<GC::Cell> xhr_cell = *static_cast<GC::Cell*>(xhr);- dbgln_if(SPAM_DEBUG, "{}XHR send from {} to {}", m_synchronous ? "\033[33;1mSynchronous\033[0m " : "", relevant_settings_object().creation_url, m_request_url);+ dbgln_if(SPAM_DEBUG, "{}XHR send from {} to {}", sync_send ? "\033[33;1mSynchronous\033[0m " : "", HTML::relevant_settings_object(js_realm.global_object()).creation_url, request->url());// 11. If this’s synchronous flag is unset, then:- if (!m_synchronous) {- // 1. Fire a progress event named loadstart at this with 0 and 0.- fire_progress_event(associated_realm.global_object(), *this, EventNames::loadstart, 0, 0);-- // 2. Let requestBodyTransmitted be 0.- // NOTE: This is kept on the XHR object itself instead of the stack, as we cannot capture references to stack variables in an async context.- m_request_body_transmitted = 0;- m_last_upload_progress_timestamp = {};- m_last_download_progress_timestamp = {};-- // 3. Let requestBodyLength be req’s body’s length, if req’s body is non-null; otherwise 0.- // NOTE: req's body is always m_request_body here, see step 6.- // 4. Assert: requestBodyLength is an integer.- // NOTE: This is done to provide a better assertion failure message, whereas below the message would be "m_has_value"- if (m_request_body)- VERIFY(m_request_body->length().has_value());-- // NOTE: This is const to allow the callback functions to take a copy of it and know it won't change.- auto const request_body_length = m_request_body ? m_request_body->length().value() : 0;-- // 5. If this’s upload complete flag is unset and this’s upload listener flag is set, then fire a progress event named loadstart at this’s upload object with requestBodyTransmitted and requestBodyLength.- if (!m_upload_complete && m_upload_listener)- fire_progress_event(associated_realm.global_object(), m_upload_object, EventNames::loadstart,- m_request_body_transmitted, request_body_length);-- // 6. If this’s state is not opened or this’s send() flag is unset, then return.- if (m_state != State::Opened || !m_send)- return {};-+ if (!sync_send) {// 7. Let processRequestBodyChunkLength, given a bytesLength, be these steps:- // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_request_body_chunk_length = GC::create_function<void(u64)>(GC::Heap::the(), GC::captures(*this, request_body_length), [](XMLHttpRequest& self, auto& request_body_length, u64 bytes_length) {- // AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a- // null body, so ignore everything after the upload completed.- // Spec issue: https://github.com/whatwg/xhr/issues/242- if (self.m_upload_complete)- return;-- // 1. Increase requestBodyTransmitted by bytesLength.- self.m_request_body_transmitted += bytes_length;-- // 2. If not roughly 50ms have passed since these steps were last invoked, then return.- auto now = MonotonicTime::now();- bool enough_time_passed = !self.m_last_upload_progress_timestamp.has_value() || (now - self.m_last_upload_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);- if (!enough_time_passed)- return;- self.m_last_upload_progress_timestamp = now;-- // 3. If this’s upload listener flag is set, then fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.- if (self.m_upload_listener)- fire_progress_event(self.relevant_global_object(), self.m_upload_object, EventNames::progress,- self.m_request_body_transmitted, request_body_length);+ auto process_request_body_chunk_length = GC::create_function<void(u64)>(GC::Heap::the(), GC::captures(xhr_cell, request_body_length), [](auto& xhr, auto& request_body_length, u64 bytes_length) {+ web_rust_xhr_process_request_body_chunk_length(vm_abi(), xhr.ptr(), request_body_length, bytes_length);});// 8. Let processRequestEndOfBody be these steps:- // NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_request_end_of_body = GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, request_body_length), [](XMLHttpRequest& self, auto& request_body_length) {- // AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a- // null body, so ignore everything after the upload completed.- // Spec issue: https://github.com/whatwg/xhr/issues/242- if (self.m_upload_complete)- return;-- // 1. Set this’s upload complete flag.- self.m_upload_complete = true;-- // 2. If this’s upload listener flag is unset, then return.- if (!self.m_upload_listener)- return;-- // 3. Fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.- auto& associated_realm = HTML::relevant_realm(self.relevant_global_object());- fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::progress,- self.m_request_body_transmitted, request_body_length);-- // 4. Fire a progress event named load at this’s upload object with requestBodyTransmitted and requestBodyLength.- fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::load,- self.m_request_body_transmitted, request_body_length);-- // 5. Fire a progress event named loadend at this’s upload object with requestBodyTransmitted and requestBodyLength.- fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::loadend,- self.m_request_body_transmitted, request_body_length);+ auto process_request_end_of_body = GC::create_function<void()>(GC::Heap::the(), GC::captures(xhr_cell, request_body_length), [](auto& xhr, auto& request_body_length) {+ web_rust_xhr_process_request_end_of_body(vm_abi(), xhr.ptr(), request_body_length);});// 9. Let processResponse, given a response, be these steps:// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_response = GC::create_function(GC::Heap::the(), GC::captures(*this), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::ResponseView> response) {- // 1. Set this’s response to response.- self.m_response = response;-- // 2. Handle errors for this.- // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.- MUST(self.handle_errors());-- // 3. If this’s response is a network error, then return.- if (self.m_response->is_network_error())- return;-- // 4. Set this’s state to headers received.- self.m_state = State::HeadersReceived;- self.update_pending_activity();-- // 5. Fire an event named readystatechange at this.- self.dispatch_event(self.create_associated_event(EventNames::readystatechange));-- // 6. If this’s state is not headers received, then return.- if (self.m_state != State::HeadersReceived)- return;-- // 7. If this’s response’s body is null, then run handle response end-of-body for this and return.- if (!self.m_response->body()) {- // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.- MUST(self.handle_response_end_of_body());- return;- }-- // 8. Let length be the result of extracting a length from this’s response’s header list.- auto length = self.m_response->header_list()->extract_length();-- // 9. If length is not an integer, then set it to 0.- if (!length.has<u64>())- length = 0;-- // Pre-allocate received bytes buffer if Content-Length is known.- if (length.get<u64>() > 0)- self.m_received_bytes.ensure_capacity(length.get<u64>());-- // 10. Let processBodyChunk given bytes be these steps:- auto process_body_chunks = GC::create_function(GC::Heap::the(), GC::captures(self, length.get<u64>()), [](XMLHttpRequest& self, u64& length, ByteBuffer byte_buffer) {- // 1. Append bytes to this’s received bytes.- self.m_received_bytes.append(byte_buffer);-- // 2. If not roughly 50ms have passed since these steps were last invoked, then return.- auto now = MonotonicTime::now();- bool enough_time_passed = !self.m_last_download_progress_timestamp.has_value() || (now - self.m_last_download_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);- if (!enough_time_passed)- return;- self.m_last_download_progress_timestamp = now;-- // 3. If this’s state is headers received, then set this’s state to loading.- if (self.m_state == State::HeadersReceived)- self.m_state = State::Loading;- self.update_pending_activity();-- // 4. Fire an event named readystatechange at this.- // Spec Note: Web compatibility is the reason readystatechange fires more often than this’s state changes.- auto& associated_realm = HTML::relevant_realm(self.relevant_global_object());- self.dispatch_event(self.create_associated_event(EventNames::readystatechange));-- // 5. Fire a progress event named progress at this with this’s received bytes’s length and length.- fire_progress_event(associated_realm.global_object(), self, EventNames::progress,- self.m_received_bytes.size(), length);- });-- // 11. Let processEndOfBody be this step: run handle response end-of-body for this.- auto process_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(self), [](XMLHttpRequest& self) {- // NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.- MUST(self.handle_response_end_of_body());- });-- // 12. Let processBodyError be these steps:- auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(self), [](XMLHttpRequest& self, JS::Value) {- // 1. Set this’s response to a network error.- self.m_response = Fetch::Infrastructure::ResponseView::network_error("A network error occurred processing body."_string);- // 2. Run handle errors for this.- // NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.- MUST(self.handle_errors());- });-- // 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.- auto global_object = GC::Ref<JS::Object> { self.relevant_global_object() };- response->body()->incrementally_read(HTML::relevant_realm(self.relevant_global_object()), process_body_chunks, process_end_of_body, process_body_error, global_object);+ auto process_response = GC::create_function(GC::Heap::the(), GC::captures(xhr_cell), [](auto& xhr, GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ web_rust_xhr_process_response(vm_abi(), xhr.ptr(), response.ptr());});// 10. Set this’s fetch controller to the result of fetching req with processRequestBodyChunkLength set to processRequestBodyChunkLength, processRequestEndOfBody set to processRequestEndOfBody, and processResponse set to processResponse.@@ -1032,442 +244,156 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestBfetch_algorithms_input.process_request_body_chunk_length = process_request_body_chunk_length;fetch_algorithms_input.process_request_end_of_body = process_request_end_of_body;fetch_algorithms_input.process_response = process_response;- m_fetch_controller = Fetch::Fetching::fetch(associated_realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));+ auto fetch_controller = Fetch::Fetching::fetch(js_realm, *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));// AD-HOC: Stopping the fetch, as aborting the document does, discards it without a response. Hand this an// aborted network error instead, so that it fires abort as for a canceled fetch.- m_fetch_controller->set_stop_steps(GC::create_function(heap(), GC::captures(*this, m_fetch_controller), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {- HTML::queue_global_task(HTML::Task::Source::Networking, self.relevant_global_object(), GC::create_function(self.heap(), GC::captures(self, fetch_controller), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {- if (self.m_fetch_controller != fetch_controller)- return;- self.m_response = Fetch::Infrastructure::ResponseView::aborted_network_error();- MUST(self.handle_errors());- }));+ fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), GC::captures(xhr_cell, fetch_controller), [](auto& xhr, auto& fetch_controller) {+ web_rust_xhr_fetch_stopped(vm_abi(), xhr.ptr(), fetch_controller.ptr());}));- // 11. Let now be the present time.- m_async_send_start_time = MonotonicTime::now();- m_async_request = request;-- // 12. Run these steps in parallel:- // 1. Wait until either req’s done flag is set or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.- // 2. If req’s done flag is unset, then set this’s timed out flag and terminate this’s fetch controller.- restart_timeout_timer();+ return fetch_controller.ptr();}- // 12. Otherwise, if this’s synchronous flag is set:- else {- // NB: These flags can't live in this stack frame: The fetch algorithms below share them, and can run after- // send() has returned (a response that completes after the fetch was terminated for timing out, e.g.).- // 1. Let processedResponse be false.- auto processed_response = Fetch::Fetching::RefCountedFlag::create(false);- auto did_time_out = Fetch::Fetching::RefCountedFlag::create(false);-- // 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:- auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, processed_response, did_time_out), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& processed_response, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& did_time_out, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes null_or_failure_or_bytes) {- // AD-HOC: Leave this's response and received bytes alone once send() returned for a timeout.- if (did_time_out->value())- return;-- // 1. If nullOrFailureOrBytes is not failure, then set this’s response to response.- if (!null_or_failure_or_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>())- self.m_response = response;-- // 2. If nullOrFailureOrBytes is a byte sequence, then append nullOrFailureOrBytes to this’s received bytes.- if (null_or_failure_or_bytes.has<Core::ImmutableBytes>()) {- // NOTE: We are not in a context where we can throw if this fails due to OOM.- self.m_received_bytes.append(null_or_failure_or_bytes.get<Core::ImmutableBytes>().bytes());- }- // 3. Set processedResponse to true.- processed_response->set_value(true);- });-- // 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.- Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::SyncAccumulate };- fetch_algorithms_input.process_response_consume_body = process_response_consume_body;- m_fetch_controller = Fetch::Fetching::fetch(associated_realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);-- // 4. Let now be the present time.- // 5. Pause until either processedResponse is true or this’s timeout is not 0 and this’s timeout milliseconds have passed since now.- if (m_timeout != 0) {- stop_timeout_timer();- m_timeout_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(m_timeout), nullptr);- m_timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), GC::captures(*this, did_time_out), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& did_time_out) {- did_time_out->set_value(true);- self.stop_timeout_timer();+ // 12. Otherwise, if this’s synchronous flag is set:+ GC::Ref<GC::Cell> sync_send_cell = *static_cast<GC::Cell*>(sync_send);++ // 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:+ auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(xhr_cell, sync_send_cell), [](auto& xhr, auto& sync_send, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes null_or_failure_or_bytes) {+ u8 kind = 0;+ ReadonlyBytes bytes;+ null_or_failure_or_bytes.visit(+ [&](Empty) { kind = 0; },+ [&](Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag) { kind = 1; },+ [&](Core::ImmutableBytes const& byte_sequence) {+ kind = 2;+ bytes = byte_sequence.bytes();});- m_timeout_timer->start();- }-- {- // NB: While a sync send() is blocked, the event loop must not run tasks or perform microtask checkpoints- // (https://html.spec.whatwg.org/multipage/webappapis.html#pause). The fetch above runs on a parallel- // queue, and progresses on the platform event loop (deferred invocations, IPC, timers) — all that's- // pumped here. So, the response arrives and is read to completion while the HTML event loop stays- // paused; see the sync XHR body path in fetch_response_handover(), and the direct delivery in- // BodyStreamPullSource::push_while_paused(). Blink/WebKit block the thread outright for a sync load:- // Blink on a WaitableEvent (ResourceRequestSender::SendSync), WebKit on a sync IPC reply- // (WebLoaderStrategy::loadResourceSynchronously). Gecko instead spins a nested event loop- // (XMLHttpRequestMainThread::SendInternal), with the top window suspended and its documents' microtasks- // deferred by nsAutoSyncOperation — so its timers and author microtasks hold as well.- // AD-HOC: We don't update the rendering when pausing: That runs author callbacks (e.g., rAF callbacks),- // which must not run inside a blocked send() — itself possibly invoked from within a microtask.- auto pause_handle = HTML::current_event_loop().pause(HTML::EventLoop::UpdateTheRendering::No);- Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), GC::captures(processed_response, did_time_out), [](auto& processed_response, auto& did_time_out) {- return processed_response->value() || did_time_out->value();- }));- }-- stop_timeout_timer();-- // 6. If processedResponse is false, then set this’s timed out flag and terminate this’s fetch controller.- if (!processed_response->value()) {- m_timed_out = true;- m_fetch_controller->terminate();- }-- // 7. Report timing for this’s fetch controller given the current global object.- // AD-HOC: A request that timed out before its fetch set up the report timing steps has no timing to report.- // Spec issue: https://github.com/whatwg/xhr/issues/412- if (!m_timed_out || m_fetch_controller->has_report_timing_steps())- m_fetch_controller->report_timing(HTML::current_global_object());-- // 8. Run handle response end-of-body for this.- TRY(handle_response_end_of_body());- }- return {};-}--WebIDL::CallbackType* XMLHttpRequest::onreadystatechange()-{- return event_handler_attribute(Web::XHR::EventNames::readystatechange);-}--void XMLHttpRequest::set_onreadystatechange(WebIDL::CallbackType* value)-{- set_event_handler_attribute(Web::XHR::EventNames::readystatechange, value);-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getresponseheader-Optional<String> XMLHttpRequest::get_response_header(String const& name) const-{- // The getResponseHeader(name) method steps are to return the result of getting name from this’s response’s header list.- auto header_bytes = m_response->header_list()->get(name);- if (!header_bytes.has_value())- return {};-- // FIXME: The spec doesn't mention isomorphic decode. Spec bug?- return TextCodec::isomorphic_decode(*header_bytes);-}--// https://xhr.spec.whatwg.org/#legacy-uppercased-byte-less-than-static bool is_legacy_uppercased_byte_less_than(ByteString const& a, ByteString const& b)-{- // 1. Let A be a, byte-uppercased.- auto uppercased_a = a.to_uppercase();-- // 2. Let B be b, byte-uppercased.- auto uppercased_b = b.to_uppercase();-- // 3. Return A is byte less than B.- return Infra::is_byte_less_than(uppercased_a.bytes(), uppercased_b.bytes());-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-getallresponseheaders-String XMLHttpRequest::get_all_response_headers() const-{- // 1. Let output be an empty byte sequence.- StringBuilder output;-- // 2. Let initialHeaders be the result of running sort and combine with this’s response’s header list.- auto initial_headers = m_response->header_list()->sort_and_combine();-- // 3. Let headers be the result of sorting initialHeaders in ascending order, with a being less than b if a’s name is legacy-uppercased-byte less than b’s name.- // NOTE: Unfortunately, this is needed for compatibility with deployed content.- quick_sort(initial_headers, [](HTTP::Header const& a, HTTP::Header const& b) {- return is_legacy_uppercased_byte_less_than(a.name, b.name);+ web_rust_xhr_process_response_consume_body(vm_abi(), xhr.ptr(), sync_send.ptr(), response.ptr(), kind, bytes);});- // 4. For each header in headers, append header’s name, followed by a 0x3A 0x20 byte pair, followed by header’s value, followed by a 0x0D 0x0A byte pair, to output.- for (auto const& header : initial_headers) {- // FIXME: The spec does not mention isomorphic decode. Spec bug?- output.appendff("{}: {}\r\n", header.name, TextCodec::isomorphic_decode(header.value));- }-- // 5. Return output.- return MUST(output.to_string());-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-overridemimetype-WebIDL::ExceptionOr<void> XMLHttpRequest::override_mime_type(Utf16String const& mime)-{- // 1. If this’s state is loading or done, then throw an "InvalidStateError" DOMException.- if (m_state == State::Loading || m_state == State::Done)- return WebIDL::InvalidStateError::create("Cannot override MIME type when state is Loading or Done."_utf16);-- // 2. Set this’s override MIME type to the result of parsing mime.- m_override_mime_type = MimeSniff::MimeType::parse(mime.utf16_view());-- // 3. If this’s override MIME type is failure, then set this’s override MIME type to application/octet-stream.- if (!m_override_mime_type.has_value())- m_override_mime_type = MimeSniff::MimeType::create("application"_string, "octet-stream"_string);-- return {};-}--// https://xhr.spec.whatwg.org/#ref-for-dom-xmlhttprequest-timeout%E2%91%A2-WebIDL::ExceptionOr<void> XMLHttpRequest::set_timeout(u32 timeout)-{- // 1. If the current global object is a Window object and this’s synchronous flag is set,- // then throw an "InvalidAccessError" DOMException.- if (HTML::window_from_global_object(HTML::current_global_object()) && m_synchronous)- return WebIDL::InvalidAccessError::create("Use of XMLHttpRequest's timeout attribute is not supported in the synchronous mode in window context."_utf16);-- // 2. Set this’s timeout to the given value.- m_timeout = timeout;-- // NB: The asynchronous send() timeout wait observes changes to this value.- if (m_send && !m_synchronous)- restart_timeout_timer();-- return {};-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-timeout-u32 XMLHttpRequest::timeout() const { return m_timeout; }--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials-bool XMLHttpRequest::with_credentials() const-{- // The withCredentials getter steps are to return this’s cross-origin credentials.- return m_cross_origin_credentials;+ // 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.+ Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::SyncAccumulate };+ fetch_algorithms_input.process_response_consume_body = process_response_consume_body;+ return Fetch::Fetching::fetch(js_realm, *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes).ptr();}-// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials-WebIDL::ExceptionOr<void> XMLHttpRequest::set_with_credentials(bool with_credentials)-{- // 1. If this’s state is not unsent or opened, then throw an "InvalidStateError" DOMException.- if (m_state != State::Unsent && m_state != State::Opened)- return WebIDL::InvalidStateError::create("XHR readyState is not UNSENT or OPENED"_utf16);-- // 2. If this’s send() flag is set, then throw an "InvalidStateError" DOMException.- if (m_send)- return WebIDL::InvalidStateError::create("XHR send() flag is already set"_utf16);-- // 3. Set this’s cross-origin credentials to the given value.- m_cross_origin_credentials = with_credentials;-- return {};-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-abort-void XMLHttpRequest::abort()-{- stop_timeout_timer();- m_async_request = nullptr;- auto& associated_realm = HTML::relevant_realm(relevant_global_object());-- // 1. Abort this’s fetch controller.- m_fetch_controller->abort(associated_realm, {});-- // 2. If this’s state is opened with this’s send() flag set, headers received, or loading, then run the request error steps for this and abort.- if ((m_state == State::Opened && m_send) || m_state == State::HeadersReceived || m_state == State::Loading) {- // NOTE: This cannot throw as we don't pass in an exception. XHR::abort cannot be reached in a synchronous context where the state matches above.- // This is because it pauses inside XHR::send until the request is done or times out and then immediately calls `handle_response_end_of_body`- // which will always set `m_state` to `Done`.- MUST(request_error_steps(EventNames::abort));- }-- // 3. If this’s state is done, then set this’s state to unsent and this’s response to a network error.- // Spec Note: No readystatechange event is dispatched.- if (m_state == State::Done) {- m_state = State::Unsent;- m_response = Fetch::Infrastructure::ResponseView::network_error("Not yet sent"_string);- update_pending_activity();- }-}--// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-upload-GC::Ref<XMLHttpRequestUpload> XMLHttpRequest::upload() const+// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+void web_xhr_incrementally_read_body(void* realm, Fetch::Infrastructure::ResponseView* response, void* xhr, u64 length){- // The upload getter steps are to return this’s upload object.- return m_upload_object;-}+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ GC::Ref<GC::Cell> xhr_cell = *static_cast<GC::Cell*>(xhr);-// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-status-Fetch::Infrastructure::Status XMLHttpRequest::status() const-{- // The status getter steps are to return this’s response’s status.- return m_response->status();-}+ auto process_body_chunk = GC::create_function(GC::Heap::the(), GC::captures(xhr_cell, length), [](auto& xhr, auto& length, ByteBuffer bytes) {+ web_rust_xhr_process_body_chunk(vm_abi(), xhr.ptr(), length, bytes);+ });+ auto process_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(xhr_cell), [](auto& xhr) {+ web_rust_xhr_process_end_of_body(vm_abi(), xhr.ptr());+ });+ auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(xhr_cell), [](auto& xhr, JS::Value) {+ web_rust_xhr_process_body_error(vm_abi(), xhr.ptr());+ });-// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-statustext-WebIDL::ExceptionOr<String> XMLHttpRequest::status_text() const-{- // The statusText getter steps are to return this’s response’s status message.- return MUST(String::from_byte_string(m_response->status_message()));+ // 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.+ GC::Ref<JS::Object> global_object = js_realm.global_object();+ response->body()->incrementally_read(js_realm, process_body_chunk, process_end_of_body, process_body_error, global_object);}-// https://xhr.spec.whatwg.org/#handle-response-end-of-body-WebIDL::ExceptionOr<void> XMLHttpRequest::handle_response_end_of_body()-{- stop_timeout_timer();- m_async_request = nullptr;-- // 1. Handle errors for xhr.- TRY(handle_errors());-- // 2. If xhr’s response is a network error, then return.- if (m_response->is_network_error())- return {};-- // 3. Let transmitted be xhr’s received bytes’s length.- auto transmitted = m_received_bytes.size();-- // 4. Let length be the result of extracting a length from this’s response’s header list.- auto maybe_length = m_response->header_list()->extract_length();-- // 5. If length is not an integer, then set it to 0.- if (!maybe_length.has<u64>())- maybe_length = 0;-- auto length = maybe_length.get<u64>();-- // 6. If xhr’s synchronous flag is unset, then fire a progress event named progress at xhr with transmitted and length.- auto& event_realm = HTML::relevant_realm(relevant_global_object());- if (!m_synchronous)- fire_progress_event(event_realm.global_object(), *this, EventNames::progress, transmitted, length);-- // 7. Set xhr’s state to done.- m_state = State::Done;-- // 8. Unset xhr’s send() flag.- m_send = false;- update_pending_activity();-- // 9. Fire an event named readystatechange at xhr.- dispatch_event(create_associated_event(EventNames::readystatechange));-- // 10. Fire a progress event named load at xhr with transmitted and length.- fire_progress_event(event_realm.global_object(), *this, EventNames::load, transmitted, length);-- // 11. Fire a progress event named loadend at xhr with transmitted and length.- fire_progress_event(event_realm.global_object(), *this, EventNames::loadend, transmitted, length);-- return {};+// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-send+void web_xhr_pause_until_sync_send_is_over(void* sync_send)+{+ GC::Ref<GC::Cell> sync_send_cell = *static_cast<GC::Cell*>(sync_send);++ // NB: While a sync send() is blocked, the event loop must not run tasks or perform microtask checkpoints+ // (https://html.spec.whatwg.org/multipage/webappapis.html#pause). The fetch above runs on a parallel+ // queue, and progresses on the platform event loop (deferred invocations, IPC, timers) — all that's+ // pumped here. So, the response arrives and is read to completion while the HTML event loop stays+ // paused; see the sync XHR body path in fetch_response_handover(), and the direct delivery in+ // BodyStreamPullSource::push_while_paused(). Blink/WebKit block the thread outright for a sync load:+ // Blink on a WaitableEvent (ResourceRequestSender::SendSync), WebKit on a sync IPC reply+ // (WebLoaderStrategy::loadResourceSynchronously). Gecko instead spins a nested event loop+ // (XMLHttpRequestMainThread::SendInternal), with the top window suspended and its documents' microtasks+ // deferred by nsAutoSyncOperation — so its timers and author microtasks hold as well.+ // AD-HOC: We don't update the rendering when pausing: That runs author callbacks (e.g., rAF callbacks),+ // which must not run inside a blocked send() — itself possibly invoked from within a microtask.+ auto pause_handle = HTML::current_event_loop().pause(HTML::EventLoop::UpdateTheRendering::No);+ Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), GC::captures(sync_send_cell), [](auto& sync_send) {+ return web_rust_xhr_sync_send_is_over(sync_send.ptr());+ }));}-// https://xhr.spec.whatwg.org/#handle-errors-WebIDL::ExceptionOr<void> XMLHttpRequest::handle_errors()+// https://xhr.spec.whatwg.org/#document-response+DOM::Document* web_xhr_create_document_response(JSObject* global_object, Fetch::Infrastructure::ResponseView* response, ReadonlyBytes received_bytes, FlatPtr final_mime, bool final_mime_is_html, ReadonlyBytes final_encoding, bool has_final_encoding){- // 1. If xhr’s send() flag is unset, then return.- if (!m_send)- return {};-- // 2. If xhr’s timed out flag is set, then run the request error steps for xhr, timeout, and "TimeoutError" DOMException.- if (m_timed_out)- return TRY(request_error_steps(EventNames::timeout, WebIDL::TimeoutError::create("Timed out"_utf16)));-- // 3. Otherwise, if xhr’s response’s aborted flag is set, run the request error steps for xhr, abort, and "AbortError" DOMException.- if (m_response->aborted())- return TRY(request_error_steps(EventNames::abort, WebIDL::AbortError::create("Aborted"_utf16)));-- // 4. Otherwise, if xhr’s response is a network error, then run the request error steps for xhr, error, and "NetworkError" DOMException.- if (m_response->is_network_error()) {- auto message = m_response->network_error_message().value_or("Unknown error"_string);- return TRY(request_error_steps(EventNames::error, WebIDL::NetworkError::create(Utf16String::from_utf8(message))));- }+ auto& global = *JS::HostABI::object_from_abi(global_object);+ Optional<StringView> final_encoding_name;+ if (has_final_encoding)+ final_encoding_name = StringView { final_encoding };- return {};-}+ // 5. If finalMIME is an HTML MIME type, then:+ Optional<Utf16String> charset;+ GC::Ptr<DOM::Document> document;+ auto& global_scope = HTML::relevant_window_or_worker_global_scope(global);+ auto& page = [&]() -> Page& {+ if (auto* window = as_if<HTML::Window>(&global_scope))+ return window->page();+ auto* worker_global_scope = as_if<HTML::WorkerGlobalScope>(&global_scope);+ VERIFY(worker_global_scope);+ auto* worker_page = worker_global_scope->page();+ VERIFY(worker_page);+ return *worker_page;+ }();-WebIDL::ExceptionOr<void> XMLHttpRequest::request_error_steps(Utf16FlyString const& event_name, GC::Ptr<WebIDL::DOMException> exception)-{- stop_timeout_timer();- m_async_request = nullptr;+ if (final_mime_is_html) {+ // 5.1. Let charset be the result of get a final encoding for xhr.+ if (final_encoding_name.has_value())+ charset = Utf16String::from_utf8(*final_encoding_name);- // 1. Set xhr’s state to done.- m_state = State::Done;+ // 5.2. If charset is null, prescan the first 1024 bytes of xhr’s received bytes and if that does not terminate unsuccessfully then let charset be the return value.+ document = DOM::Document::create(page, global_scope.this_impl());+ if (!charset.has_value())+ if (auto found_charset = HTML::run_prescan_byte_stream_algorithm(*document, received_bytes); found_charset.has_value())+ charset = Utf16String::from_utf8(MUST(String::from_byte_string(found_charset.value())));- // 2. Unset xhr’s send() flag.- m_send = false;- update_pending_activity();+ // 5.3. If charset is null, then set charset to UTF-8.+ if (!charset.has_value())+ charset = "UTF-8"_utf16;- // 3. Set xhr’s response to a network error.- m_response = Fetch::Infrastructure::ResponseView::network_error("Failed to load"_string);+ // 5.4. Let document be a document that represents the result parsing xhr’s received bytes following the rules set forth in the HTML Standard for an HTML parser with scripting disabled and a known definite encoding charset.+ auto scripting_mode = document->is_scripting_enabled() ? HTML::ParserScriptingMode::Normal : HTML::ParserScriptingMode::Disabled;+ auto charset_for_parser = charset->to_utf8();+ auto parser = HTML::HTMLParser::create_from_byte_string(*document, received_bytes, scripting_mode, charset_for_parser);+ parser->run(document->url());- // 4. If xhr’s synchronous flag is set, then throw exception.- if (m_synchronous) {- VERIFY(exception);- return GC::Ref { *exception };+ // 5.5. Flag document as an HTML document.+ document->set_document_type(DOM::Document::Type::HTML);}- auto& event_realm = HTML::relevant_realm(relevant_global_object());-- // 5. Fire an event named readystatechange at xhr.- dispatch_event(create_associated_event(EventNames::readystatechange));-- // 6. If xhr’s upload complete flag is unset, then:- if (!m_upload_complete) {- // 1. Set xhr’s upload complete flag.- m_upload_complete = true;-- // 2. If xhr’s upload listener flag is set, then:- if (m_upload_listener) {- // 1. Fire a progress event named event at xhr’s upload object with 0 and 0.- fire_progress_event(event_realm.global_object(), m_upload_object, event_name, 0, 0);-- // 2. Fire a progress event named loadend at xhr’s upload object with 0 and 0.- fire_progress_event(event_realm.global_object(), m_upload_object, EventNames::loadend, 0, 0);- }+ // 6. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.+ else {+ document = DOM::XMLDocument::create(page, global_scope.this_impl(), response->url().value_or({}));+ if (!Web::build_xml_document(*document, MUST(ByteBuffer::copy(received_bytes)), final_encoding_name, XMLScriptingSupport::Disabled))+ return nullptr;}- // 7. Fire a progress event named event at xhr with 0 and 0.- fire_progress_event(event_realm.global_object(), *this, event_name, 0, 0);-- // 8. Fire a progress event named loadend at xhr with 0 and 0.- fire_progress_event(event_realm.global_object(), *this, EventNames::loadend, 0, 0);-- return {};-}--bool XMLHttpRequest::should_be_kept_alive() const-{- auto& global = relevant_global_object();- if (auto* window = HTML::window_from_global_object(global); window && window->associated_document().has_been_destroyed())- return false;-- if (!((m_state == State::Opened && m_send) || m_state == State::HeadersReceived || m_state == State::Loading))- return false;+ // 7. If charset is null, then set charset to UTF-8.+ if (!charset.has_value())+ charset = "UTF-8"_utf16;- return has_event_listener(EventNames::readystatechange)- || has_event_listener(EventNames::progress)- || has_event_listener(EventNames::abort)- || has_event_listener(EventNames::error)- || has_event_listener(EventNames::load)- || has_event_listener(EventNames::timeout)- || has_event_listener(EventNames::loadend);-}+ // 8. Set document’s encoding to charset.+ document->set_encoding(move(charset));-void XMLHttpRequest::update_pending_activity()-{- HTML::relevant_window_or_worker_global_scope(*m_global_object).set_has_pending_activity(*this, should_be_kept_alive());-}+ // 9. Set document’s content type to finalMIME.+ auto final_mime_string = Utf16String::from_raw(final_mime);+ document->set_content_type(Utf16FlyString::from_utf16(final_mime_string.utf16_view()));-void XMLHttpRequest::event_listener_list_changed()-{- update_pending_activity();-}+ // 10. Set document’s URL to xhr’s response’s URL.+ document->set_url(response->url().value_or({}));-// https://xhr.spec.whatwg.org/#the-responseurl-attribute-Utf16String XMLHttpRequest::response_url()-{- // The responseURL getter steps are to return the empty string if this’s response’s URL is null;- // otherwise its serialization with the exclude fragment flag set.- if (!m_response->url().has_value())- return {};+ // 11. Set document’s origin to xhr’s relevant settings object’s origin.+ document->set_origin(HTML::relevant_settings_object(global).origin());- return Utf16String::from_utf8(m_response->url().value().serialize(URL::ExcludeFragment::Yes));+ return document.ptr();}}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.h b/Libraries/LibWeb/XHR/XMLHttpRequest.hindex d283db3c59b..b988c9c68a6 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.h+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.h@@ -8,246 +8,18 @@#pragma once-#include <AK/ByteBuffer.h>-#include <AK/RefCounted.h>-#include <AK/RefPtr.h>-#include <AK/Time.h>-#include <AK/Vector.h>-#include <AK/Weakable.h>-#include <LibHTTP/HeaderList.h>#include <LibJS/Forward.h>-#include <LibURL/URL.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Bindings/XMLHttpRequest.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/DOMURL/URLSearchParams.h>-#include <LibWeb/Fetch/BodyInit.h>-#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Platform/Timer.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/XHR/XMLHttpRequestEventTarget.h>-#include <LibWebCommon/Fetch/Infrastructure/HTTP/Statuses.h>-#include <LibWebCommon/MimeSniff/MimeType.h>--namespace Web::DOM {--class EventTarget;--}--namespace Web::FileAPI {--class Blob;--}namespace Web::XHR {-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit-using DocumentOrXMLHttpRequestBodyInit = FlattenVariant<Variant<GC::Ref<Web::DOM::Document>>, Fetch::XMLHttpRequestBodyInit>;-using NullableDocumentOrXMLHttpRequestBodyInit = FlattenVariant<DocumentOrXMLHttpRequestBodyInit, Variant<Empty>>;--class XMLHttpRequest final : public XMLHttpRequestEventTarget {- WEB_WRAPPABLE(XMLHttpRequest, XMLHttpRequestEventTarget);- GC_DECLARE_ALLOCATOR(XMLHttpRequest);+// https://xhr.spec.whatwg.org/#xmlhttprequest+class XMLHttpRequest final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(XMLHttpRequest, xml_http_request)public:- enum class State : u16 {- Unsent = 0,- Opened = 1,- HeadersReceived = 2,- Loading = 3,- Done = 4,- };-- using ResponseType = Bindings::XMLHttpRequestResponseType;-- static GC::Ref<XMLHttpRequest> create(GC::Ref<DOM::EventTarget> relevant_global_object);- static WebIDL::ExceptionOr<GC::Ref<XMLHttpRequest>> create_for_constructor(JS::Object&);-- virtual ~XMLHttpRequest() override;-- State ready_state() const { return m_state; }- Fetch::Infrastructure::Status status() const;- WebIDL::ExceptionOr<String> status_text() const;- WebIDL::ExceptionOr<JS::Value> response(JS::Realm&);- WebIDL::ExceptionOr<Utf16String> response_text() const;- WebIDL::ExceptionOr<GC::Ptr<DOM::Document>> response_xml();- ResponseType response_type() const { return m_response_type; }- Utf16String response_url();-- WebIDL::ExceptionOr<void> open(String const& method, Utf16String const& url);- WebIDL::ExceptionOr<void> open(String const& method, Utf16String const& url, bool async, Optional<Utf16String> const& username = Optional<Utf16String> {}, Optional<Utf16String> const& password = Optional<Utf16String> {});- WebIDL::ExceptionOr<void> send(NullableDocumentOrXMLHttpRequestBodyInit body);-- WebIDL::ExceptionOr<void> set_request_header(String const& name, String const& value);- WebIDL::ExceptionOr<void> set_response_type(ResponseType);-- Optional<String> get_response_header(String const& name) const;- String get_all_response_headers() const;-- WebIDL::CallbackType* onreadystatechange();- void set_onreadystatechange(WebIDL::CallbackType*);-- WebIDL::ExceptionOr<void> override_mime_type(Utf16String const& mime);-- u32 timeout() const;- WebIDL::ExceptionOr<void> set_timeout(u32 timeout);-- bool with_credentials() const;- WebIDL::ExceptionOr<void> set_with_credentials(bool);-- void abort();-- GC::Ref<XMLHttpRequestUpload> upload() const;- Utf16String get_text_response() const;- ByteBuffer const& received_bytes() const { return m_received_bytes; }- bool response_object_is_failure() const { return m_response_object.has<Failure>(); }- GC::Ptr<DOM::Document> response_document() const;- GC::Ptr<FileAPI::Blob> response_blob() const;- void set_blob_response_object(GC::Ref<FileAPI::Blob>);- void set_document_response();- MimeSniff::MimeType get_final_mime_type() const;--private:- virtual void visit_edges(Cell::Visitor&) override;- virtual void event_listener_list_changed() override;- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;-- [[nodiscard]] MimeSniff::MimeType get_response_mime_type() const;- [[nodiscard]] Optional<StringView> get_final_encoding() const;-- JS::Object& relevant_global_object() const;- GC::Ref<DOM::Event> create_associated_event(Utf16FlyString const&) const;- HTML::EnvironmentSettingsObject& relevant_settings_object() const;- void reset_response_object();-- WebIDL::ExceptionOr<void> handle_response_end_of_body();- WebIDL::ExceptionOr<void> handle_errors();- WebIDL::ExceptionOr<void> request_error_steps(Utf16FlyString const& event_name, GC::Ptr<WebIDL::DOMException> exception = nullptr);-- void restart_timeout_timer();- void stop_timeout_timer();- bool should_be_kept_alive() const;- void update_pending_activity();-- XMLHttpRequest(GC::Ref<DOM::EventTarget> relevant_global_object, XMLHttpRequestUpload&, NonnullRefPtr<HTTP::HeaderList>, Fetch::Infrastructure::ResponseView&, Fetch::Infrastructure::FetchController&);-- // https://xhr.spec.whatwg.org/#upload-object- // upload object- // An XMLHttpRequestUpload object.- GC::Ref<XMLHttpRequestUpload> m_upload_object;- GC::Ref<DOM::EventTarget> m_global_object;-- // https://xhr.spec.whatwg.org/#concept-xmlhttprequest-state- // state- // One of unsent, opened, headers received, loading, and done; initially unsent.- State m_state { State::Unsent };-- // https://xhr.spec.whatwg.org/#send-flag- // send() flag- // A flag, initially unset.- bool m_send { false };-- // https://xhr.spec.whatwg.org/#timeout- // timeout- // An unsigned integer, initially 0.- u32 m_timeout { 0 };-- // https://xhr.spec.whatwg.org/#cross-origin-credentials- // cross-origin credentials- // A boolean, initially false.- bool m_cross_origin_credentials { false };-- // https://xhr.spec.whatwg.org/#request-method- // request method- // A method.- ByteString m_request_method;-- // https://xhr.spec.whatwg.org/#request-url- // request URL- // A URL.- URL::URL m_request_url;-- // https://xhr.spec.whatwg.org/#author-request-headers- // author request headers- // A header list, initially empty.- NonnullRefPtr<HTTP::HeaderList> m_author_request_headers;-- // https://xhr.spec.whatwg.org/#request-body- // request body- // Initially null.- GC::Ptr<Fetch::Infrastructure::Body> m_request_body;-- // https://xhr.spec.whatwg.org/#synchronous-flag- // synchronous flag- // A flag, initially unset.- bool m_synchronous { false };-- // https://xhr.spec.whatwg.org/#upload-complete-flag- // upload complete flag- // A flag, initially unset.- bool m_upload_complete { false };-- // https://xhr.spec.whatwg.org/#upload-listener-flag- // upload listener flag- // A flag, initially unset.- bool m_upload_listener { false };-- // https://xhr.spec.whatwg.org/#timed-out-flag- // timed out flag- // A flag, initially unset.- bool m_timed_out { false };-- // https://xhr.spec.whatwg.org/#response- // response- // A response, initially a network error.- GC::Ref<Fetch::Infrastructure::ResponseView> m_response;-- // https://xhr.spec.whatwg.org/#received-bytes- // received bytes- // A byte sequence, initially the empty byte sequence.- ByteBuffer m_received_bytes;-- // https://xhr.spec.whatwg.org/#response-type- // response type- // One of the empty string, "arraybuffer", "blob", "document", "json", and "text"; initially the empty string.- ResponseType m_response_type { ResponseType::Empty };-- enum class Failure {- /// ????- };-- // https://xhr.spec.whatwg.org/#response-object- // response object- // An object, failure, or null, initially null.- Variant<GC::Ref<DOM::Document>, GC::Ref<FileAPI::Blob>, Failure, Empty> m_response_object;- struct CachedResponseObject {- GC::Weak<JS::HostObject> wrapper;- JS::Value object;- };- Vector<CachedResponseObject> m_cached_response_objects;-- // https://xhr.spec.whatwg.org/#xmlhttprequest-fetch-controller- // fetch controller- // A fetch controller, initially a new fetch controller.- // NOTE: The send() method sets it to a useful fetch controller, but for simplicity it always holds a fetch controller.- GC::Ref<Fetch::Infrastructure::FetchController> m_fetch_controller;-- // https://xhr.spec.whatwg.org/#override-mime-type- // override MIME type- // A MIME type or null, initially null.- // NOTE: Can get a value when overrideMimeType() is invoked.- Optional<MimeSniff::MimeType> m_override_mime_type;-- // Non-standard, see async path in `send()`- u64 m_request_body_transmitted { 0 };- Optional<MonotonicTime> m_last_upload_progress_timestamp;- Optional<MonotonicTime> m_last_download_progress_timestamp;-- RefPtr<Fetch::Infrastructure::Request> m_async_request;- MonotonicTime m_async_send_start_time;- GC::Ptr<Platform::Timer> m_timeout_timer;+ [[nodiscard]] static GC::Ref<XMLHttpRequest> create(JS::Realm&);};}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.idl b/Libraries/LibWeb/XHR/XMLHttpRequest.idlindex 6f6c08c8b5d..be3c974771b 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.idl+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.idl@@ -8,7 +8,7 @@ enum XMLHttpRequestResponseType {};// https://xhr.spec.whatwg.org/#xmlhttprequest-[Exposed=(Window,DedicatedWorker,SharedWorker)]+[Exposed=(Window,DedicatedWorker,SharedWorker), ImplementedIn=Rust]interface XMLHttpRequest : XMLHttpRequestEventTarget {constructor();@@ -25,8 +25,8 @@ interface XMLHttpRequest : XMLHttpRequestEventTarget {readonly attribute unsigned short readyState;// request- undefined open(ByteString method, USVString url);- undefined open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null);+ [ImplementedAs=open] undefined open(ByteString method, USVString url);+ [ImplementedAs=open_with_async] undefined open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null);undefined setRequestHeader(ByteString name, ByteString value);attribute unsigned long timeout;attribute boolean withCredentials;diff --git a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.cpp b/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.cppdeleted file mode 100644index 19a93d5d739..00000000000--- a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.cpp+++ /dev/null@@ -1,26 +0,0 @@-/*- * Copyright (c) 2021, Andreas Kling <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/HTML/EventHandler.h>-#include <LibWeb/XHR/EventNames.h>-#include <LibWeb/XHR/XMLHttpRequestEventTarget.h>--namespace Web::XHR {--#undef __ENUMERATE-#define __ENUMERATE(attribute_name, event_name) \- void XMLHttpRequestEventTarget::set_##attribute_name(WebIDL::CallbackType* value) \- { \- set_event_handler_attribute(event_name, value); \- } \- WebIDL::CallbackType* XMLHttpRequestEventTarget::attribute_name() \- { \- return event_handler_attribute(event_name); \- }-ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE)-#undef __ENUMERATE--}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.h b/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.hdeleted file mode 100644index 495959a5657..00000000000--- a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.h+++ /dev/null@@ -1,43 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/DOM/EventDispatcher.h>-#include <LibWeb/DOM/EventTarget.h>--namespace Web::XHR {--#define ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(E) \- E(onloadstart, XHR::EventNames::loadstart) \- E(onprogress, XHR::EventNames::progress) \- E(onabort, XHR::EventNames::abort) \- E(onerror, XHR::EventNames::error) \- E(onload, XHR::EventNames::load) \- E(ontimeout, XHR::EventNames::timeout) \- E(onloadend, XHR::EventNames::loadend)--class XMLHttpRequestEventTarget : public DOM::EventTarget {- WEB_WRAPPABLE(XMLHttpRequestEventTarget, DOM::EventTarget);--public:- virtual ~XMLHttpRequestEventTarget() override { }--#undef __ENUMERATE-#define __ENUMERATE(attribute_name, event_name) \- void set_##attribute_name(WebIDL::CallbackType*); \- WebIDL::CallbackType* attribute_name();- ENUMERATE_XML_HTTP_REQUEST_EVENT_TARGET_EVENT_HANDLERS(__ENUMERATE)-#undef __ENUMERATE--protected:- XMLHttpRequestEventTarget()- : DOM::EventTarget()- {- }-};--}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl b/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idlindex a27c845470b..61464ef23ab 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl+++ b/Libraries/LibWeb/XHR/XMLHttpRequestEventTarget.idl@@ -1,5 +1,5 @@// https://xhr.spec.whatwg.org/#xmlhttprequesteventtarget-[Exposed=(Window,DedicatedWorker,SharedWorker)]+[Exposed=(Window,DedicatedWorker,SharedWorker), ImplementedIn=Rust]interface XMLHttpRequestEventTarget : EventTarget {// event handlersdiff --git a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.cpp b/Libraries/LibWeb/XHR/XMLHttpRequestUpload.cppdeleted file mode 100644index 145d7319466..00000000000--- a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.cpp+++ /dev/null@@ -1,20 +0,0 @@-/*- * Copyright (c) 2023, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/XHR/XMLHttpRequestUpload.h>--namespace Web::XHR {--GC_DEFINE_ALLOCATOR(XMLHttpRequestUpload);--XMLHttpRequestUpload::XMLHttpRequestUpload()- : XMLHttpRequestEventTarget()-{-}--XMLHttpRequestUpload::~XMLHttpRequestUpload() = default;--}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.h b/Libraries/LibWeb/XHR/XMLHttpRequestUpload.hdeleted file mode 100644index bf831278271..00000000000--- a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.h+++ /dev/null@@ -1,24 +0,0 @@-/*- * Copyright (c) 2023, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/XHR/XMLHttpRequestEventTarget.h>--namespace Web::XHR {--class XMLHttpRequestUpload : public XMLHttpRequestEventTarget {- WEB_WRAPPABLE(XMLHttpRequestUpload, XMLHttpRequestEventTarget);- GC_DECLARE_ALLOCATOR(XMLHttpRequestUpload);--public:- virtual ~XMLHttpRequestUpload() override;--private:- XMLHttpRequestUpload();-};--}diff --git a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.idl b/Libraries/LibWeb/XHR/XMLHttpRequestUpload.idlindex 043458d3650..68fec5a460b 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequestUpload.idl+++ b/Libraries/LibWeb/XHR/XMLHttpRequestUpload.idl@@ -1,4 +1,4 @@// https://xhr.spec.whatwg.org/#xmlhttprequestupload-[Exposed=(Window,DedicatedWorker,SharedWorker)]+[Exposed=(Window,DedicatedWorker,SharedWorker), ImplementedIn=Rust]interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {};diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 2029f8290f1..b78bde7450d 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -52,10 +52,11 @@ ALLOWED_REALM_MENTIONS = {),"Fetch": (22,- 62,+ 64,"Fetch bodies, headers, requests, responses, response views, and controllers still materialize JS values/streams; ""BodyStreamPullSource creates body streams and materializes their pulls and errors on the consumer side, each in "- "its stream's realm; Body.textStream() creates its empty stream or streaming decoder in the receiver's realm",+ "its stream's realm; Body.textStream() creates its empty stream or streaming decoder in the receiver's realm; "+ "the Rust XMLHttpRequest extracts bodies and aborts fetch controllers in its relevant realm",),"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),"HTML": (@@ -102,7 +103,12 @@ ALLOWED_REALM_MENTIONS = {"peer connections, data channels and senders resolve promises and fire events in their relevant realm, encoded ""frames are constructed and deserialized in the worker's realm, and the stats report's maplike glue",),- "XHR": (3, 3, "XHR/FormData/FileReader-style paths still materialize JS values and events"),+ "XHR": (+ 3,+ 7,+ "XHR/FormData/FileReader-style paths still materialize JS values and events; the Rust XMLHttpRequest creates "+ "its request, its body and its fetch in its relevant realm",+ ),}