Skip to content

Truly independent web browser

LibURL+LibWeb: Implement URL and URLSearchParams in Rust

Shannon Booth73ba6e782197
diff --git a/Libraries/LibURL/Rust/src/origin.rs b/Libraries/LibURL/Rust/src/origin.rs
index e5cbec3806d..94e28b427fb 100644
--- a/Libraries/LibURL/Rust/src/origin.rs
+++ b/Libraries/LibURL/Rust/src/origin.rs
@@ -178,6 +178,34 @@ impl Origin {
}
}
}
+
+ // https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin
+ pub fn serialize(&self) -> String {
+ match self {
+ // 1. If origin is an opaque origin, then return "null"
+ Self::Opaque { .. } => "null".to_owned(),
+ Self::Tuple { scheme, host, port, .. } => {
+ // 2. Otherwise, let result be origin's scheme.
+ let mut result = scheme.clone();
+
+ // 3. Append "://" to result.
+ result.push_str("://");
+
+ // 4. Append origin's host, serialized, to result.
+ result.push_str(&host.serialization);
+
+ // 5. If origin's port is non-null, append a U+003A COLON character (:), and origin's port, serialized,
+ // to result.
+ if let Some(port) = port {
+ result.push(':');
+ result.push_str(&port.to_string());
+ }
+
+ // 6. Return result
+ result
+ }
+ }
+ }
}
impl<Serialization: AsRef<str>> Url<Serialization> {
diff --git a/Libraries/LibURL/Rust/src/url/types.rs b/Libraries/LibURL/Rust/src/url/types.rs
index 44376ded96a..0072fb4b78a 100644
--- a/Libraries/LibURL/Rust/src/url/types.rs
+++ b/Libraries/LibURL/Rust/src/url/types.rs
@@ -203,6 +203,14 @@ impl<Serialization: AsRef<str>> Url<Serialization> {
self.components.host_kind != HostKind::Null && self.components.host_start > self.components.scheme_end + 3
}
+ // https://url.spec.whatwg.org/#cannot-have-a-username-password-port
+ pub fn cannot_have_a_username_or_password_or_port(&self) -> bool {
+ // A URL cannot have a username/password/port if its host is null or the empty string, or its scheme is "file".
+ self.components.host_kind == HostKind::Null
+ || self.components.host_start == self.components.host_end
+ || self.components.scheme_type == SchemeType::File
+ }
+
pub fn host_kind(&self) -> HostKind {
self.components.host_kind
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index f6cff471959..2ca0c01bc5d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -70,6 +70,16 @@ impl UsvString {
}
}
+ /// The string without its first code unit, if that is the ASCII character.
+ pub(crate) fn strip_ascii_prefix(&self, prefix: u8) -> Option<Self> {
+ match self.units() {
+ Utf16StringUnits::Ascii(bytes) => bytes.strip_prefix(&[prefix]).map(Self::from_ascii),
+ Utf16StringUnits::Utf16(code_units) => code_units
+ .strip_prefix(&[u16::from(prefix)])
+ .map(|rest| Self(Utf16String::from_utf16(rest))),
+ }
+ }
+
pub(crate) fn into_utf16_string(self) -> Utf16String {
self.0
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/exports.rs
new file mode 100644
index 00000000000..fb830776d9d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/exports.rs
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which LibWeb's C++ reads the URLSearchParams objects that it receives from script, which
+//! Libraries/LibWeb/DOMURL/URLSearchParams.h declares.
+
+use core::ffi::c_void;
+
+use super::url_search_params::URLSearchParams;
+use crate::bindings::interface::{Ref, cell_from_abi};
+
+/// Calls `on_complete` with the serialization of the list of the URLSearchParams whose cell C++ lends, an ASCII
+/// string that it borrows for the call, https://url.spec.whatwg.org/#concept-urlencoded-serializer
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a URLSearchParams.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_url_search_params_serialize(
+ cell: *mut c_void,
+ ctx: *mut c_void,
+ on_complete: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+) {
+ // SAFETY: The caller passes a live cell of a URLSearchParams.
+ let object: Ref<URLSearchParams> = unsafe { cell_from_abi(cell) };
+ let serialization = object.serialize();
+ // SAFETY: on_complete is a valid function pointer; ctx is caller-provided.
+ unsafe { on_complete(ctx, serialization.as_ptr(), serialization.len()) };
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/mod.rs
index 5fe4a9656c6..61b13e4022a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/domurl/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/mod.rs
@@ -10,8 +10,14 @@
use ak::Utf16StringUnits;
use liburl_rust::url::UrlInput;
+#[cfg(not(test))]
+pub(crate) mod exports;
#[cfg(not(test))]
pub(crate) mod origin;
+#[cfg(not(test))]
+pub(crate) mod url;
+#[cfg(not(test))]
+pub(crate) mod url_search_params;
pub(crate) fn url_input(units: Utf16StringUnits<'_>) -> UrlInput<'_> {
match units {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs
index d905a6e796a..28a4a0fa84c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/origin.rs
@@ -11,6 +11,7 @@ use libjs_rust::api::{Trace, Value, is_host_instance_of};
use liburl_rust::origin::{OpaqueOriginKind, Origin as OriginValue};
use liburl_rust::{BasicParseOptions, FfiOrigin, basic_parse};
+use super::url::URL;
use super::url_input;
use crate::bindings::conversions::to_dom_string;
use crate::bindings::interface::{Interface, Ref, Wrappable, allocate, implementation_of};
@@ -98,6 +99,9 @@ fn extract_an_origin(value: Value) -> Option<OriginValue> {
if is_host_instance_of(&object, Origin::wrapper_class()) {
return Some(implementation_of::<Origin>(object).origin.clone());
}
+ if is_host_instance_of(&object, URL::wrapper_class()) {
+ return Some(implementation_of::<URL>(object).extract_an_origin());
+ }
unsafe extern "C" fn on_origin(ctx: *mut core::ffi::c_void, ffi_origin: *const FfiOrigin) {
// SAFETY: ctx is the result below, and LibWeb lends the origin for the call.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs
new file mode 100644
index 00000000000..07dd54fc5c9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! URL, https://url.spec.whatwg.org/#url-class
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use liburl_rust::origin::Origin;
+use liburl_rust::url::{ExcludeFragment, State};
+use liburl_rust::{BasicParseOptions, Url, basic_parse, basic_parse_with_state_override};
+
+use super::url_input;
+use super::url_search_params::{URLSearchParams, parse_query};
+use crate::bindings::conversions::{CppInterface, UsvString};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ /// Adds an entry to the blob URL store for the Blob or MediaSource that the wrapper wraps, and returns the URL as
+ /// a raw AK::Utf16String that the caller owns.
+ fn web_url_create_object_url(object: *mut c_void) -> usize;
+
+ /// Runs the revokeObjectURL(url) steps for the URL, a raw AK::Utf16String that the call borrows.
+ fn web_url_revoke_object_url(url: usize);
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+#[expect(
+ clippy::upper_case_acronyms,
+ reason = "the bindings name the implementation after the interface"
+)]
+pub(crate) struct URL {
+ // https://url.spec.whatwg.org/#concept-url-url
+ #[gc(untraced)]
+ url: RefCell<Url>,
+ // https://url.spec.whatwg.org/#concept-url-query-object
+ query: Cell<Option<Ref<URLSearchParams>>>,
+}
+
+impl Wrappable for URL {}
+
+// https://url.spec.whatwg.org/#api-url-parser
+fn parse_api_url(url: &UsvString, base: Option<&UsvString>) -> Option<Url> {
+ // 1. Let parsedBase be null.
+ // 2. If base is non-null:
+ let parsed_base = match base {
+ // 1. Set parsedBase to the result of running the basic URL parser on base.
+ // 2. If parsedBase is failure, then return failure.
+ Some(base) => Some(basic_parse(url_input(base.units()), BasicParseOptions::new())?),
+ None => None,
+ };
+
+ // 3. Return the result of running the basic URL parser on url with parsedBase.
+ let mut options = BasicParseOptions::new();
+ if let Some(parsed_base) = &parsed_base {
+ options = options.base_url(parsed_base);
+ }
+ basic_parse(url_input(url.units()), options)
+}
+
+impl URL {
+ // https://url.spec.whatwg.org/#url-initialize
+ fn initialize(url_record: Url) -> Self {
+ // OPTIMIZATION: Defer creating and initializing the query object until searchParams is accessed.
+ // 2. Set url's URL to urlRecord.
+ Self {
+ url: RefCell::new(url_record),
+ query: Cell::new(None),
+ }
+ }
+
+ // https://url.spec.whatwg.org/#url-initialize
+ // NB: The steps of initialize that searchParams defers.
+ fn initialize_query_object(this: &Ref<Self>, vm: &Vm) -> Ref<URLSearchParams> {
+ // 1. Let query be urlRecord's query, if that is non-null; otherwise the empty string.
+ let url = this.url.borrow();
+ let query = url.query().unwrap_or("");
+
+ // 3. Set url's query object to a new URLSearchParams object.
+ // 4. Initialize url's query object with query.
+ // 5. Set url's query object's URL object to url.
+ let query_object = allocate(vm, URLSearchParams::new(parse_query(query), Some(*this)));
+ this.query.set(Some(query_object));
+ query_object
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-url
+ pub(crate) fn construct(_: &mut CallContext, url: UsvString, base: Option<UsvString>) -> WebIdlResult<Self> {
+ // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsed_url = parse_api_url(&url, base.as_ref())
+ .ok_or_else(|| Exception::TypeError(Utf16String::from_utf8("Invalid URL")))?;
+
+ // 3. Initialize this with parsedURL.
+ Ok(Self::initialize(parsed_url))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-parse
+ pub(crate) fn parse(
+ cx: &mut CallContext,
+ url: UsvString,
+ base: Option<UsvString>,
+ ) -> WebIdlResult<Option<Ref<Self>>> {
+ // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
+ // 2. If parsedURL is failure, then return null.
+ let Some(parsed_url) = parse_api_url(&url, base.as_ref()) else {
+ return Ok(None);
+ };
+
+ // 3. Let url be a new URL object.
+ // 4. Initialize url with parsedURL.
+ // 5. Return url.
+ Ok(Some(allocate(cx.vm(), Self::initialize(parsed_url))))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-canparse
+ pub(crate) fn can_parse(_: &mut CallContext, url: UsvString, base: Option<UsvString>) -> WebIdlResult<bool> {
+ // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
+ // 2. If parsedURL is failure, then return false.
+ // 3. Return true.
+ Ok(parse_api_url(&url, base.as_ref()).is_some())
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-createObjectURL
+ pub(crate) fn create_object_url(_: &mut CallContext, obj: CppInterface) -> WebIdlResult<Utf16String> {
+ // The createObjectURL(obj) static method must return the result of adding an entry to the blob URL store for
+ // obj.
+ // SAFETY: The wrapper is live, and LibWeb returns a string that the caller owns.
+ Ok(unsafe { Utf16String::from_raw_owned(web_url_create_object_url(obj.wrapper().as_ptr().cast())) })
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
+ pub(crate) fn revoke_object_url(_: &mut CallContext, url: Utf16String) -> WebIdlResult<()> {
+ // SAFETY: The string outlives the call, which borrows it.
+ unsafe { web_url_revoke_object_url(url.raw_identity()) };
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#extract-an-origin
+ pub(crate) fn extract_an_origin(&self) -> Origin {
+ // Objects implementing the URL interface's extract an origin steps are to return this's URL's origin.
+ self.url.borrow().origin()
+ }
+
+ pub(crate) fn set_query(&self, query: Option<&str>) {
+ self.url.borrow_mut().set_query(query);
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-href
+ pub(crate) fn href(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The href getter steps and the toJSON() method steps are to return the serialization of this's URL.
+ Ok(UsvString::from_ascii(
+ self.url.borrow().serialize(ExcludeFragment::No).as_bytes(),
+ ))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-tojson
+ pub(crate) fn to_json(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The href getter steps and the toJSON() method steps are to return the serialization of this's URL.
+ Ok(UsvString::from_ascii(
+ self.url.borrow().serialize(ExcludeFragment::No).as_bytes(),
+ ))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-href②
+ pub(crate) fn set_href(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ // 1. Let parsedURL be the result of running the basic URL parser on the given value.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsed_url = basic_parse(url_input(value.units()), BasicParseOptions::new())
+ .ok_or_else(|| Exception::TypeError(Utf16String::from_utf8("Invalid URL")))?;
+
+ // 3. Set this's URL to parsedURL.
+ *self.url.borrow_mut() = parsed_url;
+
+ if let Some(query_object) = self.query.get() {
+ // 4. Empty this's query object's list.
+ // 5. Let query be this's URL's query.
+ // 6. If query is non-null, then set this's query object's list to the result of parsing query.
+ query_object.set_list(self.url.borrow().query().map(parse_query).unwrap_or_default());
+ }
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-origin
+ pub(crate) fn origin(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The origin getter steps are to return the serialization of this's URL's origin. [HTML]
+ Ok(UsvString::from_ascii(self.url.borrow().origin().serialize().as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-protocol
+ pub(crate) fn protocol(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The protocol getter steps are to return this's URL's scheme, followed by U+003A (:).
+ Ok(UsvString::from_ascii(
+ format!("{}:", self.url.borrow().scheme()).as_bytes(),
+ ))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-protocol%E2%91%A0
+ pub(crate) fn set_protocol(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ // The protocol setter steps are to basic URL parse the given value, followed by U+003A (:), with this's URL as
+ // url and scheme start state as state override.
+ let value_with_colon = format!("{}:", value.to_utf8());
+ basic_parse_with_state_override(
+ value_with_colon.as_str(),
+ &mut self.url.borrow_mut(),
+ State::SchemeStart,
+ None,
+ );
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-username
+ pub(crate) fn username(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The username getter steps are to return this's URL's username.
+ Ok(UsvString::from_ascii(self.url.borrow().username().as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-username%E2%91%A0
+ pub(crate) fn set_username(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL cannot have a username/password/port, then return.
+ if url.cannot_have_a_username_or_password_or_port() {
+ return Ok(());
+ }
+
+ // 2. Set the username given this's URL and the given value.
+ url.set_username(url_input(value.units()));
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-password
+ pub(crate) fn password(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The password getter steps are to return this's URL's password.
+ Ok(UsvString::from_ascii(self.url.borrow().password().as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-password%E2%91%A0
+ pub(crate) fn set_password(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL cannot have a username/password/port, then return.
+ if url.cannot_have_a_username_or_password_or_port() {
+ return Ok(());
+ }
+
+ // 2. Set the password given this's URL and the given value.
+ url.set_password(url_input(value.units()));
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-host
+ pub(crate) fn host(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // 1. Let url be this's URL.
+ let url = self.url.borrow();
+
+ // 2. If url's host is null, then return the empty string.
+ let Some(host) = url.serialized_host() else {
+ return Ok(UsvString::from_ascii(b""));
+ };
+
+ // 3. If url's port is null, return url's host, serialized.
+ let Some(port) = url.port() else {
+ return Ok(UsvString::from_ascii(host.as_bytes()));
+ };
+
+ // 4. Return url's host, serialized, followed by U+003A (:) and url's port, serialized.
+ Ok(UsvString::from_ascii(format!("{host}:{port}").as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-host
+ pub(crate) fn set_host(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL has an opaque path, then return.
+ if url.has_opaque_path() {
+ return Ok(());
+ }
+
+ // 2. Basic URL parse the given value with this's URL as url and host state as state override.
+ basic_parse_with_state_override(url_input(value.units()), &mut url, State::Host, None);
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-hostname
+ pub(crate) fn hostname(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // 1. If this's URL's host is null, then return the empty string.
+ // 2. Return this's URL's host, serialized.
+ Ok(UsvString::from_ascii(
+ self.url.borrow().serialized_host().unwrap_or("").as_bytes(),
+ ))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-hostname①
+ pub(crate) fn set_hostname(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL has an opaque path, then return.
+ if url.has_opaque_path() {
+ return Ok(());
+ }
+
+ // 2. Basic URL parse the given value with this's URL as url and hostname state as state override.
+ basic_parse_with_state_override(url_input(value.units()), &mut url, State::Hostname, None);
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-port
+ pub(crate) fn port(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // 1. If this's URL's port is null, then return the empty string.
+ // 2. Return this's URL's port, serialized.
+ let port = self
+ .url
+ .borrow()
+ .port()
+ .map(|port| port.to_string())
+ .unwrap_or_default();
+ Ok(UsvString::from_ascii(port.as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-port%E2%91%A0
+ pub(crate) fn set_port(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL cannot have a username/password/port, then return.
+ if url.cannot_have_a_username_or_password_or_port() {
+ return Ok(());
+ }
+
+ // 2. If the given value is the empty string, then set this's URL's port to null.
+ if value.length_in_code_units() == 0 {
+ url.set_port(None);
+ }
+ // 3. Otherwise, basic URL parse the given value with this's URL as url and port state as state override.
+ else {
+ basic_parse_with_state_override(url_input(value.units()), &mut url, State::Port, None);
+ }
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-pathname
+ pub(crate) fn pathname(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // The pathname getter steps are to return the result of URL path serializing this's URL.
+ Ok(UsvString::from_ascii(self.url.borrow().serialize_path().as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-pathname%E2%91%A0
+ pub(crate) fn set_pathname(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If this's URL has an opaque path, then return.
+ if url.has_opaque_path() {
+ return Ok(());
+ }
+
+ // 2. Empty this's URL's path.
+ url.set_path(core::iter::empty());
+
+ // 3. Basic URL parse the given value with this's URL as url and path start state as state override.
+ basic_parse_with_state_override(url_input(value.units()), &mut url, State::PathStart, None);
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-search
+ pub(crate) fn search(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // 1. If this's URL's query is either null or the empty string, then return the empty string.
+ // 2. Return U+003F (?), followed by this's URL's query.
+ let query = match self.url.borrow().query() {
+ None | Some("") => String::new(),
+ Some(query) => format!("?{query}"),
+ };
+ Ok(UsvString::from_ascii(query.as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-search%E2%91%A0
+ pub(crate) fn set_search(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ // 1. Let url be this's URL.
+ let mut url = self.url.borrow_mut();
+
+ // 2. If the given value is the empty string, then set url's query to null, empty this's query object's list,
+ // and return.
+ if value.length_in_code_units() == 0 {
+ url.set_query(None);
+ if let Some(query_object) = self.query.get() {
+ query_object.set_list(Vec::new());
+ }
+ return Ok(());
+ }
+
+ // 3. Let input be the given value with a single leading U+003F (?) removed, if any.
+ let input = value.strip_ascii_prefix(b'?').unwrap_or(value);
+
+ // 4. Set url's query to the empty string.
+ url.set_query(Some(""));
+
+ // 5. Basic URL parse input with url as url and query state as state override.
+ basic_parse_with_state_override(url_input(input.units()), &mut url, State::Query, None);
+
+ // 6. Set this's query object's list to the result of parsing url's query.
+ if let Some(query_object) = self.query.get() {
+ query_object.set_list(url.query().map(parse_query).unwrap_or_default());
+ }
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-searchparams
+ pub(crate) fn search_params(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Ref<URLSearchParams>> {
+ // The searchParams getter steps are to return this's query object.
+ Ok(this
+ .query
+ .get()
+ .unwrap_or_else(|| Self::initialize_query_object(this, cx.vm())))
+ }
+
+ // https://url.spec.whatwg.org/#dom-url-hash
+ pub(crate) fn hash(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ // 1. If this's URL's fragment is either null or the empty string, then return the empty string.
+ // 2. Return U+0023 (#), followed by this's URL's fragment.
+ let fragment = match self.url.borrow().fragment() {
+ None | Some("") => String::new(),
+ Some(fragment) => format!("#{fragment}"),
+ };
+ Ok(UsvString::from_ascii(fragment.as_bytes()))
+ }
+
+ // https://url.spec.whatwg.org/#ref-for-dom-url-hash%E2%91%A0
+ pub(crate) fn set_hash(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ let mut url = self.url.borrow_mut();
+
+ // 1. If the given value is the empty string, then set this's URL's fragment to null and return.
+ if value.length_in_code_units() == 0 {
+ url.set_fragment(None);
+ return Ok(());
+ }
+
+ // 2. Let input be the given value with a single leading U+0023 (#) removed, if any.
+ let input = value.strip_ascii_prefix(b'#').unwrap_or(value);
+
+ // 3. Set this's URL's fragment to the empty string.
+ url.set_fragment(Some(""));
+
+ // 4. Basic URL parse input with this's URL as url and fragment state as state override.
+ basic_parse_with_state_override(url_input(input.units()), &mut url, State::Fragment, None);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/url_search_params.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/url_search_params.rs
new file mode 100644
index 00000000000..dbbfa04450b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/url_search_params.rs
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! URLSearchParams, https://url.spec.whatwg.org/#interface-urlsearchparams
+
+use core::cell::{self, Cell, RefCell};
+use core::ops::Deref;
+
+use ak::{Utf16String, Utf16StringUnits};
+use encoding_rs::UTF_8;
+use libjs_rust::api::Trace;
+use liburl_rust::url::form_urlencoded;
+
+use super::url::URL;
+use super::url_input;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Ref, Wrappable};
+use crate::bindings::iterable::PairIterable;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// The union (sequence<sequence<USVString>> or record<USVString, USVString> or USVString) of
+/// DOMURL/URLSearchParams.idl, whose members the bindings convert.
+pub(crate) enum USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString {
+ Sequence(Vec<Vec<UsvString>>),
+ Record(Vec<(UsvString, UsvString)>),
+ USVString(UsvString),
+}
+
+type Init = USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString;
+
+/// A name-value tuple.
+pub(crate) type Tuple = (UsvString, UsvString);
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct URLSearchParams {
+ // https://url.spec.whatwg.org/#concept-urlsearchparams-list
+ #[gc(untraced)]
+ list: RefCell<Vec<Tuple>>,
+ // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
+ url_object: Cell<Option<Ref<URL>>>,
+}
+
+impl Wrappable for URLSearchParams {}
+
+fn code_units(string: &UsvString) -> impl Iterator<Item = u16> + '_ {
+ let (ascii, utf16) = match string.units() {
+ Utf16StringUnits::Ascii(bytes) => (bytes, &[][..]),
+ Utf16StringUnits::Utf16(code_units) => (&[][..], code_units),
+ };
+ ascii.iter().map(|byte| u16::from(*byte)).chain(utf16.iter().copied())
+}
+
+// https://url.spec.whatwg.org/#concept-urlencoded-string-parser
+pub(crate) fn parse_query(input: &str) -> Vec<Tuple> {
+ form_urlencoded::parse(input.as_bytes())
+ .into_iter()
+ .map(|(name, value)| (UsvString::from_utf8(&name), UsvString::from_utf8(&value)))
+ .collect()
+}
+
+impl URLSearchParams {
+ pub(crate) fn new(list: Vec<Tuple>, url_object: Option<Ref<URL>>) -> Self {
+ Self {
+ list: RefCell::new(list),
+ url_object: Cell::new(url_object),
+ }
+ }
+
+ pub(crate) fn set_list(&self, list: Vec<Tuple>) {
+ *self.list.borrow_mut() = list;
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
+ pub(crate) fn construct(_: &mut CallContext, init: Init) -> WebIdlResult<Self> {
+ // 1. If init is a string and starts with U+003F (?), then remove the first code point from init.
+ let init = match init {
+ Init::USVString(string) => Init::USVString(string.strip_ascii_prefix(b'?').unwrap_or(string)),
+ init => init,
+ };
+
+ // 2. Initialize this with init.
+ Ok(Self::new(Self::initialize(init)?, None))
+ }
+
+ // https://url.spec.whatwg.org/#urlsearchparams-initialize
+ fn initialize(init: Init) -> WebIdlResult<Vec<Tuple>> {
+ match init {
+ // 1. If init is a sequence, then for each innerSequence of init:
+ Init::Sequence(sequence) => sequence
+ .into_iter()
+ .map(|inner_sequence| {
+ // 1. If innerSequence's size is not 2, then throw a TypeError.
+ let [name, value]: [UsvString; 2] = inner_sequence.try_into().map_err(|_| {
+ Exception::TypeError(Utf16String::from_utf8("Expected each pair to contain exactly 2 items"))
+ })?;
+
+ // 2. Append (innerSequence[0], innerSequence[1]) to query's list.
+ Ok((name, value))
+ })
+ .collect(),
+ // 2. Otherwise, if init is a record, then for each name → value of init, append (name, value) to query's
+ // list.
+ Init::Record(record) => Ok(record),
+ // 3. Otherwise:
+ // 1. Assert: init is a string.
+ // 2. Set query's list to the result of parsing init.
+ Init::USVString(string) => Ok(parse_query(&string.to_utf8())),
+ }
+ }
+
+ // https://url.spec.whatwg.org/#concept-urlsearchparams-update
+ fn update(&self) {
+ // 1. If query's URL object is null, then return.
+ let Some(url_object) = self.url_object.get() else {
+ return;
+ };
+
+ // 2. Let serializedQuery be the serialization of query's list.
+ let serialized_query = self.serialize();
+
+ // 3. If serializedQuery is the empty string, then set serializedQuery to null.
+ let serialized_query = (!serialized_query.is_empty()).then_some(serialized_query.as_str());
+
+ // 4. Set query's URL object's URL's query to serializedQuery.
+ url_object.set_query(serialized_query);
+ }
+
+ // https://url.spec.whatwg.org/#concept-urlencoded-serializer
+ pub(crate) fn serialize(&self) -> String {
+ let list = self.list.borrow();
+ form_urlencoded::serialize(
+ list.iter()
+ .map(|(name, value)| (url_input(name.units()), url_input(value.units()))),
+ UTF_8,
+ )
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-size
+ pub(crate) fn size(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The size getter steps are to return this's list's size.
+ Ok(u32::try_from(self.list.borrow().len()).unwrap_or(u32::MAX))
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-append
+ pub(crate) fn append(&self, _: &mut CallContext, name: UsvString, value: UsvString) -> WebIdlResult<()> {
+ // 1. Append (name, value) to this's list.
+ self.list.borrow_mut().push((name, value));
+
+ // 2. Update this.
+ self.update();
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
+ pub(crate) fn delete(&self, _: &mut CallContext, name: UsvString, value: Option<UsvString>) -> WebIdlResult<()> {
+ match value {
+ // 1. If value is given, then remove all tuples whose name is name and value is value from this's list.
+ Some(value) => self
+ .list
+ .borrow_mut()
+ .retain(|(tuple_name, tuple_value)| *tuple_name != name || *tuple_value != value),
+ // 2. Otherwise, remove all tuples whose name is name from this's list.
+ None => self.list.borrow_mut().retain(|(tuple_name, _)| *tuple_name != name),
+ }
+
+ // 3. Update this.
+ self.update();
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-get
+ pub(crate) fn get(&self, _: &mut CallContext, name: UsvString) -> WebIdlResult<Option<UsvString>> {
+ // The get(name) method steps are to return the value of the first tuple whose name is name in this's list, if
+ // there is such a tuple; otherwise null.
+ Ok(self
+ .list
+ .borrow()
+ .iter()
+ .find(|(tuple_name, _)| *tuple_name == name)
+ .map(|(_, tuple_value)| tuple_value.clone()))
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
+ pub(crate) fn get_all(&self, _: &mut CallContext, name: UsvString) -> WebIdlResult<Vec<UsvString>> {
+ // The getAll(name) method steps are to return the values of all tuples whose name is name in this's list, in
+ // list order; otherwise the empty sequence.
+ Ok(self
+ .list
+ .borrow()
+ .iter()
+ .filter(|(tuple_name, _)| *tuple_name == name)
+ .map(|(_, tuple_value)| tuple_value.clone())
+ .collect())
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-has
+ pub(crate) fn has(&self, _: &mut CallContext, name: UsvString, value: Option<UsvString>) -> WebIdlResult<bool> {
+ let list = self.list.borrow();
+ match value {
+ // 1. If value is given and there is a tuple whose name is name and value is value in this's list, then
+ // return true.
+ Some(value)
+ if list
+ .iter()
+ .any(|(tuple_name, tuple_value)| *tuple_name == name && *tuple_value == value) =>
+ {
+ return Ok(true);
+ }
+ // 2. If value is not given and there is a tuple whose name is name in this's list, then return true.
+ None if list.iter().any(|(tuple_name, _)| *tuple_name == name) => return Ok(true),
+ _ => {}
+ }
+
+ // 3. Return false.
+ Ok(false)
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-set
+ pub(crate) fn set(&self, _: &mut CallContext, name: UsvString, value: UsvString) -> WebIdlResult<()> {
+ {
+ let mut list = self.list.borrow_mut();
+
+ // 1. If this's list contains any tuples whose name is name, then set the value of the first such tuple
+ // to value and remove the others.
+ if list.iter().any(|(tuple_name, _)| *tuple_name == name) {
+ let mut is_first = true;
+ list.retain_mut(|(tuple_name, tuple_value)| {
+ if *tuple_name != name {
+ return true;
+ }
+ if is_first {
+ is_first = false;
+ *tuple_value = value.clone();
+ return true;
+ }
+ false
+ });
+ }
+ // 2. Otherwise, append (name, value) to this's list.
+ else {
+ list.push((name, value));
+ }
+ }
+
+ // 3. Update this.
+ self.update();
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#dom-urlsearchparams-sort
+ pub(crate) fn sort(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // 1. Set this's list to the result of sorting in ascending order this's list, with a being less than b if a's
+ // name is code unit less than b's name.
+ self.list
+ .borrow_mut()
+ .sort_by(|(a_name, _), (b_name, _)| code_units(a_name).cmp(code_units(b_name)));
+
+ // 2. Update this.
+ self.update();
+ Ok(())
+ }
+
+ // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
+ pub(crate) fn to_string(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The stringification behavior steps are to return the serialization of this's list.
+ Ok(Utf16String::from_ascii(self.serialize().as_bytes()))
+ }
+}
+
+impl PairIterable for URLSearchParams {
+ type Key = UsvString;
+ type Value = UsvString;
+
+ // https://url.spec.whatwg.org/#ref-for-dfn-value-pairs-to-iterate-over
+ fn value_pairs_to_iterate_over(&self) -> impl Deref<Target = [(UsvString, UsvString)]> + '_ {
+ // The value pairs to iterate over are this's list's tuples with the key being the name and the value being the
+ // value.
+ cell::Ref::map(self.list.borrow(), Vec::as_slice)
+ }
+}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index f366e07a0fd..081a90062eb 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -328,7 +328,6 @@ set(SOURCES
DOM/XMLDocument.cpp
DOMURL/DOMURL.cpp
DOMURL/URLSearchParams.cpp
- DOMURL/URLSearchParamsIterator.cpp
Dump.cpp
Editing/CommandNames.cpp
Editing/Commands.cpp
diff --git a/Libraries/LibWeb/DOMURL/DOMURL.cpp b/Libraries/LibWeb/DOMURL/DOMURL.cpp
index 199c69910c0..69611c300f0 100644
--- a/Libraries/LibWeb/DOMURL/DOMURL.cpp
+++ b/Libraries/LibWeb/DOMURL/DOMURL.cpp
@@ -7,107 +7,44 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/IPv4Address.h>
-#include <AK/IPv6Address.h>
-#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibURL/Parser.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/DOMURL/DOMURL.h>
+#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/FileAPI/BlobURLStore.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Infra/SerializedURL.h>
+#include <LibWeb/MediaSourceExtensions/MediaSource.h>
#include <LibWeb/Page/Page.h>
namespace Web::DOMURL {
-GC_DEFINE_ALLOCATOR(DOMURL);
-
-GC::Ref<DOMURL> DOMURL::create(URL::URL url)
-{
- return GC::Heap::the().allocate<DOMURL>(move(url));
-}
-
-// https://url.spec.whatwg.org/#api-url-parser
-static Optional<URL::URL> parse_api_url(Utf16View url, Optional<Utf16String> const& base)
-{
- // 1. Let parsedBase be null.
- Optional<URL::URL> parsed_base;
-
- // 2. If base is non-null:
- if (base.has_value()) {
- // 1. Set parsedBase to the result of running the basic URL parser on base.
- auto parsed_base_url = URL::Parser::basic_parse(base->utf16_view());
-
- // 2. If parsedBase is failure, then return failure.
- if (!parsed_base_url.has_value())
- return {};
-
- parsed_base = parsed_base_url;
- }
-
- // 3. Return the result of running the basic URL parser on url with parsedBase.
- return URL::Parser::basic_parse(url, parsed_base);
-}
-
-// https://url.spec.whatwg.org/#url-initialize
-GC::Ref<DOMURL> DOMURL::initialize_a_url(URL::URL const& url_record)
-{
- // OPTIMIZATION: Defer creating and initializing the query object until searchParams is accessed.
- return DOMURL::create(url_record);
-}
-
-// https://url.spec.whatwg.org/#dom-url-parse
-GC::Ptr<DOMURL> DOMURL::parse_for_bindings(Utf16String const& url, Optional<Utf16String> const& base)
-{
- // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
- auto parsed_url = parse_api_url(url.utf16_view(), base);
-
- // 2. If parsedURL is failure, then return null.
- if (!parsed_url.has_value())
- return nullptr;
-
- // 3. Let url be a new URL object.
- // 4. Initialize url with parsedURL.
- // 5. Return url.
- return initialize_a_url(parsed_url.value());
-}
-
-// https://url.spec.whatwg.org/#dom-url-url
-WebIDL::ExceptionOr<GC::Ref<DOMURL>> DOMURL::create_from_url(Utf16String const& url, Optional<Utf16String> const& base)
-{
- // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
- auto parsed_url = parse_api_url(url.utf16_view(), base);
-
- // 2. If parsedURL is failure, then throw a TypeError.
- if (!parsed_url.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid URL"_utf16 };
-
- // 3. Initialize this with parsedURL.
- return initialize_a_url(parsed_url.value());
-}
-
-DOMURL::DOMURL(URL::URL url)
- : m_url(move(url))
-{
-}
-
-DOMURL::~DOMURL() = default;
-
-void DOMURL::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_query);
+// Called by Bindings/Rust/src/domurl/url.rs.
+extern "C" {
+FlatPtr web_url_create_object_url(JSObject* object);
+void web_url_revoke_object_url(FlatPtr raw_url);
}
// https://w3c.github.io/FileAPI/#dfn-createObjectURL
-WebIDL::ExceptionOr<Utf16String> DOMURL::create_object_url(FileAPI::BlobURLEntry::Object object)
+extern "C" FlatPtr web_url_create_object_url(JSObject* object)
{
+ auto* wrappable = Bindings::wrappable_impl_from(JS::HostABI::object_from_abi(object));
+ FileAPI::BlobURLEntry::Object blob_url_entry_object = [&] -> FileAPI::BlobURLEntry::Object {
+ if (auto* blob = as_if<FileAPI::Blob>(wrappable))
+ return GC::Ref { *blob };
+ return GC::Ref { as<MediaSourceExtensions::MediaSource>(*wrappable) };
+ }();
+
// The createObjectURL(obj) static method must return the result of adding an entry to the blob URL store for obj.
- return TRY_OR_THROW_OOM(JS::VM::the(), FileAPI::add_entry_to_blob_url_store(object));
+ return MUST(FileAPI::add_entry_to_blob_url_store(blob_url_entry_object)).into_raw();
}
// https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
-void DOMURL::revoke_object_url(Utf16String const& url)
+extern "C" void web_url_revoke_object_url(FlatPtr raw_url)
{
+ auto url = Utf16String::from_raw(raw_url);
+
// 1. Let url record be the result of parsing url.
auto url_record = parse(url.utf16_view());
@@ -143,304 +80,6 @@ void DOMURL::revoke_object_url(Utf16String const& url)
FileAPI::remove_entry_from_blob_url_store(*url_record);
}
-// https://url.spec.whatwg.org/#dom-url-canparse
-bool DOMURL::can_parse(Utf16String const& url, Optional<Utf16String> const& base)
-{
- // 1. Let parsedURL be the result of running the API URL parser on url with base, if given.
- auto parsed_url = parse_api_url(url.utf16_view(), base);
-
- // 2. If parsedURL is failure, then return false.
- if (!parsed_url.has_value())
- return false;
-
- // 3. Return true.
- return true;
-}
-
-// https://url.spec.whatwg.org/#dom-url-href
-Utf16String DOMURL::href() const
-{
- // The href getter steps and the toJSON() method steps are to return the serialization of this’s URL.
- return utf16_string_from_url_ascii(m_url.serialize());
-}
-
-// https://url.spec.whatwg.org/#dom-url-tojson
-Utf16String DOMURL::to_json() const
-{
- // The href getter steps and the toJSON() method steps are to return the serialization of this’s URL.
- return utf16_string_from_url_ascii(m_url.serialize());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-href②
-WebIDL::ExceptionOr<void> DOMURL::set_href(Utf16String const& value)
-{
- // 1. Let parsedURL be the result of running the basic URL parser on the given value.
- auto parsed_url = URL::Parser::basic_parse(value.utf16_view());
-
- // 2. If parsedURL is failure, then throw a TypeError.
- if (!parsed_url.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid URL"_utf16 };
-
- // 3. Set this’s URL to parsedURL.
- m_url = parsed_url.release_value();
-
- if (m_query) {
- // 4. Empty this’s query object’s list.
- m_query->m_list.clear();
-
- // 5. Let query be this’s URL’s query.
- auto query = m_url.query();
-
- // 6. If query is non-null, then set this’s query object’s list to the result of parsing query.
- if (query.has_value())
- m_query->m_list = url_decode(*query);
- }
- return {};
-}
-
-// https://url.spec.whatwg.org/#dom-url-origin
-Utf16String DOMURL::origin() const
-{
- // The origin getter steps are to return the serialization of this’s URL’s origin. [HTML]
- return utf16_string_from_url_ascii(m_url.origin().serialize());
-}
-
-// https://url.spec.whatwg.org/#dom-url-protocol
-Utf16String DOMURL::protocol() const
-{
- // The protocol getter steps are to return this’s URL’s scheme, followed by U+003A (:).
- return Utf16String::formatted("{}:", m_url.scheme());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-protocol%E2%91%A0
-void DOMURL::set_protocol(Utf16String const& protocol)
-{
- // The protocol setter steps are to basic URL parse the given value, followed by U+003A (:), with this’s URL as
- // url and scheme start state as state override.
- auto protocol_with_colon = Utf16String::formatted("{}:", protocol);
- (void)URL::Parser::basic_parse(protocol_with_colon.utf16_view(), m_url, URL::Parser::State::SchemeStart);
-}
-
-// https://url.spec.whatwg.org/#dom-url-username
-Utf16String DOMURL::username() const
-{
- // The username getter steps are to return this’s URL’s username.
- return utf16_string_from_url_ascii(m_url.username());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-username%E2%91%A0
-void DOMURL::set_username(Utf16String const& username)
-{
- // 1. If this’s URL cannot have a username/password/port, then return.
- if (m_url.cannot_have_a_username_or_password_or_port())
- return;
-
- // 2. Set the username given this’s URL and the given value.
- m_url.set_username(username.utf16_view());
-}
-
-// https://url.spec.whatwg.org/#dom-url-password
-Utf16String DOMURL::password() const
-{
- // The password getter steps are to return this’s URL’s password.
- return utf16_string_from_url_ascii(m_url.password());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-password%E2%91%A0
-void DOMURL::set_password(Utf16String const& password)
-{
- // 1. If this’s URL cannot have a username/password/port, then return.
- if (m_url.cannot_have_a_username_or_password_or_port())
- return;
-
- // 2. Set the password given this’s URL and the given value.
- m_url.set_password(password.utf16_view());
-}
-
-// https://url.spec.whatwg.org/#dom-url-host
-Utf16String DOMURL::host() const
-{
- // 1. Let url be this’s URL.
- auto const& url = m_url;
-
- // 2. If url’s host is null, then return the empty string.
- if (!url.host().has_value())
- return {};
-
- // 3. If url’s port is null, return url’s host, serialized.
- if (!url.port().has_value())
- return utf16_string_from_url_ascii(url.serialized_host());
-
- // 4. Return url’s host, serialized, followed by U+003A (:) and url’s port, serialized.
- return utf16_string_from_url_ascii_host_and_port(url.serialized_host(), *url.port());
-}
-
-// https://url.spec.whatwg.org/#dom-url-host
-void DOMURL::set_host(Utf16String const& host)
-{
- // 1. If this’s URL has an opaque path, then return.
- if (m_url.has_an_opaque_path())
- return;
-
- // 2. Basic URL parse the given value with this’s URL as url and host state as state override.
- (void)URL::Parser::basic_parse(host.utf16_view(), m_url, URL::Parser::State::Host);
-}
-
-// https://url.spec.whatwg.org/#dom-url-hostname
-Utf16String DOMURL::hostname() const
-{
- // 1. If this’s URL’s host is null, then return the empty string.
- if (!m_url.host().has_value())
- return {};
-
- // 2. Return this’s URL’s host, serialized.
- return utf16_string_from_url_ascii(m_url.serialized_host());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-hostname①
-void DOMURL::set_hostname(Utf16String const& hostname)
-{
- // 1. If this’s URL has an opaque path, then return.
- if (m_url.has_an_opaque_path())
- return;
-
- // 2. Basic URL parse the given value with this’s URL as url and hostname state as state override.
- (void)URL::Parser::basic_parse(hostname.utf16_view(), m_url, URL::Parser::State::Hostname);
-}
-
-// https://url.spec.whatwg.org/#dom-url-port
-Utf16String DOMURL::port() const
-{
- // 1. If this’s URL’s port is null, then return the empty string.
- if (!m_url.port().has_value())
- return {};
-
- // 2. Return this’s URL’s port, serialized.
- return Utf16String::formatted("{}", *m_url.port());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-port%E2%91%A0
-void DOMURL::set_port(Utf16String const& port)
-{
- // 1. If this’s URL cannot have a username/password/port, then return.
- if (m_url.cannot_have_a_username_or_password_or_port())
- return;
-
- // 2. If the given value is the empty string, then set this’s URL’s port to null.
- if (port.is_empty()) {
- m_url.set_port({});
- }
- // 3. Otherwise, basic URL parse the given value with this’s URL as url and port state as state override.
- else {
- (void)URL::Parser::basic_parse(port.utf16_view(), m_url, URL::Parser::State::Port);
- }
-}
-
-// https://url.spec.whatwg.org/#dom-url-pathname
-Utf16String DOMURL::pathname() const
-{
- // The pathname getter steps are to return the result of URL path serializing this’s URL.
- return utf16_string_from_url_ascii(m_url.serialize_path());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-pathname%E2%91%A0
-void DOMURL::set_pathname(Utf16String const& pathname)
-{
- // 1. If this’s URL has an opaque path, then return.
- if (m_url.has_an_opaque_path())
- return;
-
- // 2. Empty this’s URL’s path.
- m_url.set_path({});
-
- // 3. Basic URL parse the given value with this’s URL as url and path start state as state override.
- (void)URL::Parser::basic_parse(pathname.utf16_view(), m_url, URL::Parser::State::PathStart);
-}
-
-// https://url.spec.whatwg.org/#dom-url-search
-Utf16String DOMURL::search() const
-{
- // 1. If this’s URL’s query is either null or the empty string, then return the empty string.
- if (!m_url.query().has_value() || m_url.query()->is_empty())
- return {};
-
- // 2. Return U+003F (?), followed by this’s URL’s query.
- return Utf16String::formatted("?{}", *m_url.query());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-search%E2%91%A0
-void DOMURL::set_search(Utf16String const& search)
-{
- // 1. Let url be this’s URL.
- auto& url = m_url;
-
- // 2. If the given value is the empty string, then set url’s query to null, empty this’s query object’s list, and return.
- if (search.is_empty()) {
- url.set_query({});
- if (m_query)
- m_query->m_list.clear();
- return;
- }
-
- // 3. Let input be the given value with a single leading U+003F (?) removed, if any.
- auto search_as_utf16_view = search.utf16_view();
- auto input = search_as_utf16_view.substring_view(search_as_utf16_view.starts_with('?'));
-
- // 4. Set url’s query to the empty string.
- url.set_query(""sv);
-
- // 5. Basic URL parse input with url as url and query state as state override.
- (void)URL::Parser::basic_parse(input, url, URL::Parser::State::Query);
-
- // 6. Set this’s query object’s list to the result of parsing url’s query.
- if (m_query)
- m_query->m_list = url_decode(*url.query());
-}
-
-// https://url.spec.whatwg.org/#dom-url-searchparams
-GC::Ref<URLSearchParams const> DOMURL::search_params()
-{
- // The searchParams getter steps are to return this’s query object.
- if (!m_query) {
- auto query = m_url.query().value_or(String {});
- m_query = URLSearchParams::create(query);
- m_query->m_url = this;
- }
-
- return *m_query;
-}
-
-// https://url.spec.whatwg.org/#dom-url-hash
-Utf16String DOMURL::hash() const
-{
- // 1. If this’s URL’s fragment is either null or the empty string, then return the empty string.
- if (!m_url.fragment().has_value() || m_url.fragment()->is_empty())
- return {};
-
- // 2. Return U+0023 (#), followed by this’s URL’s fragment.
- return utf16_string_from_url_ascii_with_prefix('#', *m_url.fragment());
-}
-
-// https://url.spec.whatwg.org/#ref-for-dom-url-hash%E2%91%A0
-void DOMURL::set_hash(Utf16String const& hash)
-{
- // 1. If the given value is the empty string, then set this’s URL’s fragment to null and return.
- if (hash.is_empty()) {
- m_url.set_fragment({});
- return;
- }
-
- // 2. Let input be the given value with a single leading U+0023 (#) removed, if any.
- auto hash_as_utf16_view = hash.utf16_view();
- auto input = hash_as_utf16_view.substring_view(hash_as_utf16_view.starts_with('#'));
-
- // 3. Set this’s URL’s fragment to the empty string.
- m_url.set_fragment(""sv);
-
- // 4. Basic URL parse input with this’s URL as url and fragment state as state override.
- (void)URL::Parser::basic_parse(input, m_url, URL::Parser::State::Fragment);
-}
-
// https://url.spec.whatwg.org/#concept-url-parser
static Optional<URL::URL> finish_parsing(Optional<URL::URL> url)
{
@@ -479,11 +118,4 @@ Optional<URL::URL> parse(Utf16View input, Optional<URL::URL const&> base_url, Op
return finish_parsing(URL::Parser::basic_parse(input, base_url, encoding_view));
}
-// FIXME: At time of writing, still open spec MR: https://github.com/whatwg/url/pull/892
-Optional<URL::Origin> DOMURL::extract_an_origin() const
-{
- // Objects implementing the URL interface's extract an origin steps are to return this's URL's origin. [[HTML]]
- return m_url.origin();
-}
-
}
diff --git a/Libraries/LibWeb/DOMURL/DOMURL.h b/Libraries/LibWeb/DOMURL/DOMURL.h
index 63227ff3517..9707c17eac9 100644
--- a/Libraries/LibWeb/DOMURL/DOMURL.h
+++ b/Libraries/LibWeb/DOMURL/DOMURL.h
@@ -10,90 +10,10 @@
#pragma once
#include <LibURL/URL.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/DOMURL/URLSearchParams.h>
#include <LibWeb/Export.h>
-#include <LibWeb/FileAPI/BlobURLStore.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::DOMURL {
-class DOMURL : public Bindings::GCAllocatedWrappable {
- // NOTE: This is 'URL' in the IDL, but we call it DOMURL to avoid name conflicts with LibURL.
- WEB_WRAPPABLE(URL, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(DOMURL);
-
-public:
- [[nodiscard]] static GC::Ref<DOMURL> create(URL::URL);
- static WebIDL::ExceptionOr<GC::Ref<DOMURL>> create_from_url(Utf16String const& url, Optional<Utf16String> const& base = {});
-
- virtual ~DOMURL() override;
-
- static WebIDL::ExceptionOr<Utf16String> create_object_url(FileAPI::BlobURLEntry::Object object);
- static void revoke_object_url(Utf16String const& url);
-
- static GC::Ptr<DOMURL> parse_for_bindings(Utf16String const& url, Optional<Utf16String> const& base = {});
- static bool can_parse(Utf16String const& url, Optional<Utf16String> const& base = {});
-
- Utf16String href() const;
- WebIDL::ExceptionOr<void> set_href(Utf16String const&);
-
- Utf16String origin() const;
-
- Utf16String protocol() const;
- void set_protocol(Utf16String const&);
-
- Utf16String username() const;
- void set_username(Utf16String const&);
-
- Utf16String password() const;
- void set_password(Utf16String const&);
-
- Utf16String host() const;
- void set_host(Utf16String const&);
-
- Utf16String hostname() const;
- void set_hostname(Utf16String const&);
-
- Utf16String port() const;
- void set_port(Utf16String const&);
-
- Utf16String pathname() const;
- void set_pathname(Utf16String const&);
-
- Optional<StringView> fragment() const { return m_url.fragment(); }
-
- ByteString path_segment_at_index(size_t index) const { return m_url.path_segment_at_index(index); }
-
- bool has_an_opaque_path() const { return m_url.has_an_opaque_path(); }
-
- Utf16String search() const;
- void set_search(Utf16String const&);
-
- GC::Ref<URLSearchParams const> search_params();
-
- Utf16String hash() const;
- void set_hash(Utf16String const&);
-
- Utf16String to_json() const;
-
- Optional<StringView> query() const { return m_url.query(); }
- void set_query(Badge<URLSearchParams>, Optional<StringView> query) { m_url.set_query(query); }
-
- virtual Optional<URL::Origin> extract_an_origin() const override;
-
-private:
- explicit DOMURL(URL::URL);
-
- static GC::Ref<DOMURL> initialize_a_url(URL::URL const&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- URL::URL m_url;
- // Most URL users never access searchParams, so avoid its parsing and allocation until needed.
- GC::Ptr<URLSearchParams> m_query;
-};
-
// https://url.spec.whatwg.org/#concept-url-parser
WEB_API Optional<URL::URL> parse_from_byte_string(StringView input, Optional<URL::URL const&> base_url = {}, Optional<StringView> encoding = {});
WEB_API Optional<URL::URL> parse(Utf16View input, Optional<URL::URL const&> base_url = {}, Optional<Utf16View> encoding = {});
diff --git a/Libraries/LibWeb/DOMURL/DOMURL.idl b/Libraries/LibWeb/DOMURL/URL.idl
similarity index 73%
rename from Libraries/LibWeb/DOMURL/DOMURL.idl
rename to Libraries/LibWeb/DOMURL/URL.idl
index e76a1bf0b78..3a26e86675e 100644
--- a/Libraries/LibWeb/DOMURL/DOMURL.idl
+++ b/Libraries/LibWeb/DOMURL/URL.idl
@@ -1,9 +1,9 @@
// https://url.spec.whatwg.org/#url
-[Exposed=*, LegacyWindowAlias=webkitURL, ImplementedAs=DOMURL]
+[Exposed=*, LegacyWindowAlias=webkitURL, ImplementedIn=Rust]
interface URL {
- [ImplementedAs=create_from_url] constructor(USVString url, optional USVString base);
+ constructor(USVString url, optional USVString base);
- [ImplementedAs=parse_for_bindings] static URL? parse(USVString url, optional USVString base);
+ static URL? parse(USVString url, optional USVString base);
static boolean canParse(USVString url, optional USVString base);
stringifier attribute USVString href;
diff --git a/Libraries/LibWeb/DOMURL/URLSearchParams.cpp b/Libraries/LibWeb/DOMURL/URLSearchParams.cpp
index 5ac0b283ed1..2fb54c24016 100644
--- a/Libraries/LibWeb/DOMURL/URLSearchParams.cpp
+++ b/Libraries/LibWeb/DOMURL/URLSearchParams.cpp
@@ -5,33 +5,12 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/QuickSort.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf8View.h>
-#include <LibGC/Heap.h>
-#include <LibURL/Parser.h>
#include <LibURL/RustFFI.h>
#include <LibURL/RustIntegration.h>
-#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/DOMURL/URLSearchParams.h>
namespace Web::DOMURL {
-GC_DEFINE_ALLOCATOR(URLSearchParams);
-
-URLSearchParams::URLSearchParams(Vector<QueryParam> list)
- : m_list(move(list))
-{
-}
-
-URLSearchParams::~URLSearchParams() = default;
-
-void URLSearchParams::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_url);
-}
-
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
String url_encode(Vector<QueryParam> const& tuples, StringView encoding)
{
@@ -60,242 +39,19 @@ Vector<QueryParam> url_decode(StringView input)
return output;
}
-Vector<QueryParam> url_decode(Utf16View input)
-{
- auto utf8 = input.to_utf8_but_should_be_ported_to_utf16();
- return url_decode(utf8);
-}
-
-GC::Ref<URLSearchParams> URLSearchParams::create(Vector<QueryParam> list)
-{
- return GC::Heap::the().allocate<URLSearchParams>(move(list));
-}
-
-// https://url.spec.whatwg.org/#urlsearchparams-initialize
-GC::Ref<URLSearchParams> URLSearchParams::create(StringView init)
-{
- // NOTE: We skip the other steps since we know it is a string at this point.
- // b. Set query’s list to the result of parsing init.
- return URLSearchParams::create(url_decode(init));
-}
-
-GC::Ref<URLSearchParams> URLSearchParams::create(Utf16View init)
-{
- return URLSearchParams::create(url_decode(init));
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
-// https://url.spec.whatwg.org/#urlsearchparams-initialize
-WebIDL::ExceptionOr<GC::Ref<URLSearchParams>> URLSearchParams::create_from_init(Variant<Vector<Vector<Utf16String>>, OrderedHashMap<Utf16String, Utf16String>, Utf16String> const& init)
-{
- // 1. If init is a string and starts with U+003F (?), then remove the first code point from init.
- // NOTE: We do this when we know that it's a string on step 3 of initialization.
-
- // 2. Initialize this with init.
-
- // URLSearchParams init from this point forward
-
- // 1. If init is a sequence, then for each pair in init:
- if (init.has<Vector<Vector<Utf16String>>>()) {
- auto const& init_sequence = init.get<Vector<Vector<Utf16String>>>();
-
- Vector<QueryParam> list;
- list.ensure_capacity(init_sequence.size());
-
- for (auto const& pair : init_sequence) {
- // a. If pair does not contain exactly two items, then throw a TypeError.
- if (pair.size() != 2)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Expected each pair to contain exactly 2 items"_utf16 };
-
- // b. Append a new name-value pair whose name is pair’s first item, and value is pair’s second item, to query’s list.
- list.append(QueryParam { .name = pair[0], .value = pair[1] });
- }
-
- return URLSearchParams::create(move(list));
- }
-
- // 2. Otherwise, if init is a record, then for each name → value of init, append a new name-value pair whose name is name and value is value, to query’s list.
- if (init.has<OrderedHashMap<Utf16String, Utf16String>>()) {
- auto const& init_record = init.get<OrderedHashMap<Utf16String, Utf16String>>();
-
- Vector<QueryParam> list;
- list.ensure_capacity(init_record.size());
+extern "C" {
- for (auto const& pair : init_record)
- list.append(QueryParam { .name = pair.key, .value = pair.value });
-
- return URLSearchParams::create(move(list));
- }
-
- // 3. Otherwise:
- // a. Assert: init is a string.
- // NOTE: `get` performs `VERIFY(has<T>())`
- auto const& init_string = init.get<Utf16String>();
-
- // See NOTE at the start of this function.
- auto init_string_view = init_string.utf16_view();
- auto stripped_init = init_string_view.substring_view(init_string_view.starts_with('?'));
-
- // b. Set query’s list to the result of parsing init.
- return URLSearchParams::create(stripped_init);
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-size
-size_t URLSearchParams::size() const
-{
- // The size getter steps are to return this’s list’s size.
- return m_list.size();
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-append
-void URLSearchParams::append(Utf16String const& name, Utf16String const& value)
-{
- // 1. Append a new name-value pair whose name is name and value is value, to list.
- m_list.empend(name, value);
-
- // 2. Update this.
- update();
-}
-
-// https://url.spec.whatwg.org/#concept-urlsearchparams-update
-void URLSearchParams::update()
-{
- // 1. If query’s URL object is null, then return.
- if (!m_url)
- return;
-
- // 2. Let serializedQuery be the serialization of query’s list.
- Optional<String> serialized_query = serialize_to_byte_string();
-
- // 3. If serializedQuery is the empty string, then set serializedQuery to null.
- if (serialized_query == String {})
- serialized_query = {};
-
- // 4. Set query’s URL object’s URL’s query to serializedQuery.
- m_url->set_query({}, serialized_query.map([](String const& query) { return query.bytes_as_string_view(); }));
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
-void URLSearchParams::delete_(Utf16String const& name, Optional<Utf16String> const& value)
-{
- // 1. If value is given, then remove all tuples whose name is name and value is value from this’s list.
- if (value.has_value()) {
- m_list.remove_all_matching([&name, &value](auto& entry) {
- return entry.name == name && entry.value == value.value();
- });
- }
- // 2. Otherwise, remove all tuples whose name is name from this’s list.
- else {
- m_list.remove_all_matching([&name](auto& entry) {
- return entry.name == name;
- });
- }
-
- // 2. Update this.
- update();
-}
-
-Optional<Utf16String> URLSearchParams::get(Utf16String const& name)
-{
- // return the value of the first name-value pair whose name is name in this’s list, if there is such a pair, and null otherwise.
- auto result = m_list.find_if([&name](auto& entry) {
- return entry.name == name;
- });
- if (result.is_end())
- return {};
- return result->value;
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
-Vector<Utf16String> URLSearchParams::get_all(Utf16String const& name)
-{
- // return the values of all name-value pairs whose name is name, in this’s list, in list order, and the empty sequence otherwise.
- Vector<Utf16String> values;
- for (auto& entry : m_list) {
- if (entry.name == name)
- values.append(entry.value);
- }
- return values;
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-has
-bool URLSearchParams::has(Utf16String const& name, Optional<Utf16String> const& value)
-{
- // 1. If value is given and there is a tuple whose name is name and value is value in this’s list, then return true.
- if (value.has_value()) {
- if (!m_list.find_if([&name, &value](auto& entry) {
- return entry.name == name && entry.value == value.value();
- })
- .is_end()) {
- return true;
- }
- }
- // 2. If value is not given and there is a tuple whose name is name in this’s list, then return true.
- else {
- if (!m_list.find_if([&name](auto& entry) {
- return entry.name == name;
- })
- .is_end()) {
- return true;
- }
- }
-
- // 3. Return false.
- return false;
-}
-
-void URLSearchParams::set(Utf16String const& name, Utf16String const& value)
-{
- // 1. If this’s list contains any name-value pairs whose name is name, then set the value of the first such name-value pair to value and remove the others.
- auto existing = m_list.find_if([&name](auto& entry) {
- return entry.name == name;
- });
- if (!existing.is_end()) {
- existing->value = value;
- m_list.remove_all_matching([&name, &existing](auto& entry) {
- return &entry != &*existing && entry.name == name;
- });
- }
- // 2. Otherwise, append a new name-value pair whose name is name and value is value, to this’s list.
- else {
- m_list.empend(name, value);
- }
-
- // 3. Update this.
- update();
-}
-
-// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
-void URLSearchParams::sort()
-{
- // 1. Set this’s list to the result of sorting in ascending order this’s list, with a being less than b if a’s name is code unit less than b’s name.
- insertion_sort(m_list, [](auto& a, auto& b) {
- return a.name.utf16_view().is_code_unit_less_than(b.name);
- });
-
- // 2. Update this.
- update();
+// Defined in Bindings/Rust/src/domurl/exports.rs.
+void web_url_search_params_serialize(void* cell, void* ctx, void (*on_complete)(void*, u8 const*, size_t));
}
String URLSearchParams::serialize_to_byte_string() const
{
- // return the serialization of this’s list.
- return url_encode(m_list);
-}
-
-Utf16String URLSearchParams::to_string() const
-{
- auto serialized = serialize_to_byte_string();
- return Utf16String::from_ascii_without_validation(serialized.bytes());
-}
-
-void URLSearchParams::for_each(ForEachCallback callback)
-{
- for (auto i = 0u; i < m_list.size(); ++i) {
- auto& query_param = m_list[i]; // We are explicitly iterating over the indices here as the callback might delete items from the list
- if (callback(query_param.name, query_param.value) == IterationDecision::Break)
- break;
- }
+ String serialization;
+ web_url_search_params_serialize(const_cast<URLSearchParams*>(this), &serialization, [](void* ctx, u8 const* data, size_t length) {
+ *static_cast<String*>(ctx) = String::from_ascii_without_validation({ data, length });
+ });
+ return serialization;
}
}
diff --git a/Libraries/LibWeb/DOMURL/URLSearchParams.h b/Libraries/LibWeb/DOMURL/URLSearchParams.h
index 08fa960ba19..2950ca26e8d 100644
--- a/Libraries/LibWeb/DOMURL/URLSearchParams.h
+++ b/Libraries/LibWeb/DOMURL/URLSearchParams.h
@@ -6,11 +6,11 @@
#pragma once
-#include <AK/IterationDecision.h>
+#include <AK/Utf16String.h>
#include <AK/Vector.h>
-#include <LibURL/URL.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/URLSearchParams.h>
+#include <LibWeb/Export.h>
namespace Web::DOMURL {
@@ -20,48 +20,12 @@ struct QueryParam {
};
String url_encode(Vector<QueryParam> const&, StringView encoding = "UTF-8"sv);
Vector<QueryParam> url_decode(StringView);
-Vector<QueryParam> url_decode(Utf16View);
-class URLSearchParams : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(URLSearchParams, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(URLSearchParams);
+class WEB_API URLSearchParams final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(URLSearchParams, url_search_params)
public:
- static GC::Ref<URLSearchParams> create(StringView);
- static GC::Ref<URLSearchParams> create(Utf16View);
- static GC::Ref<URLSearchParams> create(Vector<QueryParam> list);
- static WebIDL::ExceptionOr<GC::Ref<URLSearchParams>> create_from_init(Variant<Vector<Vector<Utf16String>>, OrderedHashMap<Utf16String, Utf16String>, Utf16String> const& init);
-
- virtual ~URLSearchParams() override;
-
- size_t size() const;
- void append(Utf16String const& name, Utf16String const& value);
- void delete_(Utf16String const& name, Optional<Utf16String> const& value = {});
- Optional<Utf16String> get(Utf16String const& name);
- Vector<Utf16String> get_all(Utf16String const& name);
- bool has(Utf16String const& name, Optional<Utf16String> const& value = {});
- void set(Utf16String const& name, Utf16String const& value);
-
- void sort();
-
String serialize_to_byte_string() const;
- Utf16String to_string() const;
-
- using ForEachCallback = Function<IterationDecision(Utf16String const&, Utf16String const&)>;
- void for_each(ForEachCallback);
-
-private:
- friend class DOMURL;
- friend class URLSearchParamsIterator;
-
- explicit URLSearchParams(Vector<QueryParam> list);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- void update();
-
- Vector<QueryParam> m_list;
- GC::Ptr<DOMURL> m_url;
};
}
diff --git a/Libraries/LibWeb/DOMURL/URLSearchParams.idl b/Libraries/LibWeb/DOMURL/URLSearchParams.idl
index 1557b983198..b5ba15a9f66 100644
--- a/Libraries/LibWeb/DOMURL/URLSearchParams.idl
+++ b/Libraries/LibWeb/DOMURL/URLSearchParams.idl
@@ -1,8 +1,8 @@
// https://url.spec.whatwg.org/#urlsearchparams
-[Exposed=*]
+[Exposed=*, ImplementedIn=Rust]
interface URLSearchParams {
- [ImplementedAs=create_from_init] constructor(optional (sequence<sequence<USVString>> or record<USVString, USVString> or USVString) init = "");
+ constructor(optional (sequence<sequence<USVString>> or record<USVString, USVString> or USVString) init = "");
readonly attribute unsigned long size;
diff --git a/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.cpp b/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.cpp
deleted file mode 100644
index 13fd371e57f..00000000000
--- a/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2021, Idan Horowitz <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/Iterator.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/URLSearchParams.h>
-#include <LibWeb/DOMURL/URLSearchParamsIterator.h>
-
-namespace Web::DOMURL {
-
-GC_DEFINE_ALLOCATOR(URLSearchParamsIterator);
-
-static constexpr JSHostClass url_search_params_iterator_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "URLSearchParamsIterator"sv, nullptr, nullptr, nullptr, 0);
-
-URLSearchParamsIterator::URLSearchParamsIterator(URLSearchParams const& url_search_params, JS::Object::PropertyKind iteration_kind)
- : m_url_search_params(url_search_params)
- , m_iteration_kind(iteration_kind)
-{
-}
-
-URLSearchParamsIterator::~URLSearchParamsIterator() = default;
-
-WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> URLSearchParamsIterator::create(JS::Realm& realm, URLSearchParams const& url_search_params, JS::Object::PropertyKind iteration_kind)
-{
- static auto const& prototype_name = "URLSearchParamsIterator"_utf16_fly_string;
- auto iterator = realm.create<URLSearchParamsIterator>(url_search_params, iteration_kind);
- auto& prototype = Bindings::ensure_web_prototype<Bindings::URLSearchParamsIteratorPrototype>(realm, prototype_name);
- return JS::HostObject::create(realm, url_search_params_iterator_host_class, prototype, {}, iterator);
-}
-
-void URLSearchParamsIterator::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_url_search_params);
-}
-
-JS::Object* URLSearchParamsIterator::next(JS::Realm& realm)
-{
- if (m_index >= m_url_search_params->m_list.size())
- return JS::create_iterator_result_object(realm, JS::js_undefined(), true).ptr();
-
- auto& entry = m_url_search_params->m_list[m_index++];
- if (m_iteration_kind == JS::Object::PropertyKind::Key)
- return JS::create_iterator_result_object(realm, JS::PrimitiveString::create(vm(), entry.name), false).ptr();
- else if (m_iteration_kind == JS::Object::PropertyKind::Value)
- return JS::create_iterator_result_object(realm, JS::PrimitiveString::create(vm(), entry.value), false).ptr();
-
- return JS::create_iterator_result_object(realm, JS::Array::create_from(realm, { JS::PrimitiveString::create(vm(), entry.name), JS::PrimitiveString::create(vm(), entry.value) }), false).ptr();
-}
-
-}
diff --git a/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.h b/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.h
deleted file mode 100644
index af0235d9167..00000000000
--- a/Libraries/LibWeb/DOMURL/URLSearchParamsIterator.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2021, Idan Horowitz <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Heap/Cell.h>
-#include <LibJS/Runtime/HostObject.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibWeb/DOMURL/URLSearchParams.h>
-
-namespace Web::DOMURL {
-
-// The state of a URLSearchParams iterator. The iterator's JS object is a host object that carries this cell as its
-// host data.
-class URLSearchParamsIterator final : public JS::Cell {
- GC_CELL(URLSearchParamsIterator, JS::Cell);
- GC_DECLARE_ALLOCATOR(URLSearchParamsIterator);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- static WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create(JS::Realm&, URLSearchParams const&, JS::Object::PropertyKind iteration_kind);
-
- virtual ~URLSearchParamsIterator() override;
-
- JS::Object* next(JS::Realm&);
-
-private:
- URLSearchParamsIterator(URLSearchParams const&, JS::Object::PropertyKind iteration_kind);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<URLSearchParams const> m_url_search_params;
- JS::Object::PropertyKind m_iteration_kind;
- size_t m_index { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 3e6e59646e1..721d4a55d5f 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1210,9 +1210,7 @@ class UIEvent;
namespace Web::DOMURL {
-class DOMURL;
class URLSearchParams;
-class URLSearchParamsIterator;
}
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index bfe5c9e7867..5ae17dc6c38 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -146,7 +146,7 @@ libweb_js_bindings(DOM/StaticRange)
libweb_js_bindings(DOM/Text)
libweb_js_bindings(DOM/TreeWalker)
libweb_js_bindings(DOM/XMLDocument)
-libweb_js_bindings(DOMURL/DOMURL)
+libweb_js_bindings(DOMURL/URL)
libweb_js_bindings(DOMURL/Origin)
libweb_js_bindings(DOMURL/URLSearchParams)
libweb_js_bindings(Encoding/TextDecoder)
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 50e463bee36..81fb700589c 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -43,7 +43,6 @@ ALLOWED_REALM_MENTIONS = {
"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),
"Crypto": (8, 383, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
- "DOMURL": (2, 4, "URLSearchParams iterator objects still materialize JS iterator results in selected realms"),
"Fetch": (
22,
62,