Skip to content

Truly independent web browser

LibWeb: Implement Blob and File in Rust

Shannon Booth68d948b0d7b5
diff --git a/Cargo.lock b/Cargo.lock
index 805aca05215..7321288dca7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -869,6 +869,7 @@ dependencies = [
"libtextcodec_rust",
"liburl_rust",
"libweb_rust",
+ "libwebcommon_rust",
"rustc-demangle",
"serde_json",
]
diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
index 31fa7040383..8de8a27559c 100644
--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
@@ -27,6 +27,7 @@ libjs_rust = { path = "../../../LibJS/Rust", default-features = false }
libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }
liburl_rust = { path = "../../../LibURL/Rust", default-features = false }
libweb_rust = { path = "../../Rust" }
+libwebcommon_rust = { path = "../../../LibWebCommon/Rust" }
rustc-demangle = "0.1"
[build-dependencies]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs b/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs
index 07dd54fc5c9..72b30719e23 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/domurl/url.rs
@@ -20,16 +20,27 @@ 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};
+use crate::file_api::blob::AnyBlob;
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;
+ /// Adds an entry to the blob URL store for the Blob or File whose cell the call borrows, and returns the URL as a
+ /// raw AK::Utf16String that the caller owns.
+ fn web_url_create_object_url_for_blob(blob: *mut c_void) -> usize;
+
+ /// Adds an entry to the blob URL store for the MediaSource that the wrapper wraps, and returns the URL as a raw
+ /// AK::Utf16String that the caller owns.
+ fn web_url_create_object_url_for_media_source(media_source: *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);
}
+/// The union (Blob or MediaSource) of DOMURL/URL.idl, whose members the bindings convert.
+pub(crate) enum BlobOrMediaSource {
+ Blob(AnyBlob),
+ MediaSource(CppInterface),
+}
+
#[derive(Trace)]
#[gc(crate = libjs_rust)]
#[expect(
@@ -129,11 +140,18 @@ impl URL {
}
// https://w3c.github.io/FileAPI/#dfn-createObjectURL
- pub(crate) fn create_object_url(_: &mut CallContext, obj: CppInterface) -> WebIdlResult<Utf16String> {
+ pub(crate) fn create_object_url(_: &mut CallContext, obj: BlobOrMediaSource) -> 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())) })
+ // SAFETY: The object is live, and LibWeb returns a string that the caller owns.
+ Ok(unsafe {
+ Utf16String::from_raw_owned(match obj {
+ BlobOrMediaSource::Blob(blob) => web_url_create_object_url_for_blob(blob.cell_into_abi()),
+ BlobOrMediaSource::MediaSource(media_source) => {
+ web_url_create_object_url_for_media_source(media_source.wrapper().as_ptr().cast())
+ }
+ })
+ })
}
// https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
new file mode 100644
index 00000000000..b32777a0c7b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs
@@ -0,0 +1,568 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Blob, https://w3c.github.io/FileAPI/#blob-section
+
+use core::cell::{Ref as CellRef, RefCell};
+use core::ffi::c_void;
+use core::ops::Deref;
+use core::ptr::NonNull;
+
+use ak::{Utf16String, Utf16StringUnits};
+use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Trace};
+use libwebcommon_rust::mime_sniff::mime_type::MimeType;
+
+use super::file::File;
+use crate::bindings::conversions::{BufferSource, CppInterface, UsvString};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_blob_bytes_destroy(owner: *mut c_void);
+ fn web_blob_get_stream(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
+ fn web_blob_text(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
+ fn web_blob_array_buffer(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
+ fn web_blob_bytes(realm: *mut c_void, bytes: ak::Span<'_, u8>) -> *mut c_void;
+ fn web_blob_deserialize_byte_sequence(
+ serialized: *mut c_void,
+ out_bytes: &mut ForeignBytesAbi,
+ ) -> RawNativeFunctionResult;
+}
+
+/// The enumeration EndingType of FileAPI/Blob.idl.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum EndingType {
+ Transparent,
+ Native,
+}
+
+/// The dictionary BlobPropertyBag of FileAPI/Blob.idl, whose members the bindings convert.
+pub(crate) struct BlobPropertyBag {
+ pub(crate) endings: EndingType,
+ pub(crate) r#type: Utf16String,
+}
+
+/// An object of Blob or of File, which inherits from it.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum AnyBlob {
+ Blob(Ref<Blob>),
+ File(Ref<File>),
+}
+
+impl Deref for AnyBlob {
+ type Target = Blob;
+
+ fn deref(&self) -> &Blob {
+ match self {
+ Self::Blob(blob) => blob,
+ Self::File(file) => {
+ let file: &File = file;
+ file.parent()
+ }
+ }
+ }
+}
+
+impl AnyBlob {
+ /// The cell of the object, as LibWeb's C++ code holds it.
+ pub(crate) fn cell_into_abi(self) -> *mut c_void {
+ match self {
+ Self::Blob(blob) => cell_into_abi(blob),
+ Self::File(file) => cell_into_abi(file),
+ }
+ }
+}
+
+/// The union (BufferSource or Blob or USVString) of FileAPI/Blob.idl, whose members the bindings convert.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum BlobPart {
+ BufferSource(BufferSource),
+ Blob(AnyBlob),
+ USVString(#[gc(untraced)] UsvString),
+}
+
+/// Bytes that C++ owns for a Blob, as it hands them over: the owner, which web_blob_bytes_destroy() destroys, and the
+/// bytes, which live as long as it.
+#[repr(C)]
+pub(crate) struct ForeignBytesAbi {
+ pub(crate) owner: *mut c_void,
+ pub(crate) data: *const u8,
+ pub(crate) length: usize,
+}
+
+/// Bytes that a C++ Web::FileAPI::BlobBytes owns: those that C++ created the Blob with, or moved to shared memory.
+struct ForeignBytes {
+ owner: NonNull<c_void>,
+ data: *const u8,
+ length: usize,
+}
+
+impl ForeignBytes {
+ /// # Safety
+ ///
+ /// `bytes` must be bytes that C++ hands over, which nothing else destroys.
+ unsafe fn from_abi(bytes: ForeignBytesAbi) -> Self {
+ Self {
+ owner: NonNull::new(bytes.owner).expect("C++ hands over the owner of the bytes"),
+ data: bytes.data,
+ length: bytes.length,
+ }
+ }
+
+ fn as_slice(&self) -> &[u8] {
+ // SAFETY: The owner keeps the bytes alive and unchanged for as long as it lives.
+ unsafe { ak::slice_from_raw_parts(self.data, self.length) }
+ }
+}
+
+impl Drop for ForeignBytes {
+ fn drop(&mut self) {
+ // SAFETY: The value owns the owner, which nothing uses after this.
+ unsafe { web_blob_bytes_destroy(self.owner.as_ptr()) };
+ }
+}
+
+/// https://w3c.github.io/FileAPI/#dfn-byte-sequence
+enum ByteSequence {
+ Owned(Vec<u8>),
+ Foreign(ForeignBytes),
+}
+
+impl ByteSequence {
+ fn as_slice(&self) -> &[u8] {
+ match self {
+ Self::Owned(bytes) => bytes,
+ Self::Foreign(bytes) => bytes.as_slice(),
+ }
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Blob {
+ // https://w3c.github.io/FileAPI/#dfn-byte-sequence
+ // NB: The bytes move to shared memory the first time they are shared, and stay there.
+ #[gc(untraced)]
+ byte_sequence: RefCell<ByteSequence>,
+ // https://w3c.github.io/FileAPI/#dfn-type
+ #[gc(untraced)]
+ r#type: Utf16String,
+}
+
+impl Wrappable for Blob {}
+
+fn append_utf8(bytes: &mut Vec<u8>, string: &UsvString) {
+ let length = string.utf8_length();
+ bytes.reserve(length);
+ // SAFETY: The spare capacity has room for the encoding, which encode_utf8() initializes before the length grows
+ // over it.
+ unsafe {
+ let written = string.encode_utf8(bytes.spare_capacity_mut());
+ bytes.set_len(bytes.len() + written);
+ }
+}
+
+// https://w3c.github.io/FileAPI/#convert-line-endings-to-native
+fn convert_line_endings_to_native(s: &str) -> String {
+ // 1. Let native line ending be the code point U+000A LF.
+ let native_line_ending = "\n";
+
+ // 2. If the underlying platform’s conventions are to represent newlines as a carriage return and line feed
+ // sequence, set native line ending to the code point U+000D CR followed by the code point U+000A LF.
+ // NOTE: this step is a no-op since LibWeb does not compile on Windows, which is the only platform we know of that
+ // that uses a carriage return and line feed sequence for line endings.
+
+ let code_points = s.as_bytes();
+ let collect_token = |position: &mut usize| {
+ let token_start = *position;
+ while *position < code_points.len() && code_points[*position] != b'\n' && code_points[*position] != b'\r' {
+ *position += 1;
+ }
+ &s[token_start..*position]
+ };
+
+ // 3. Set result to the empty string.
+ let mut result = String::with_capacity(s.len());
+
+ // 4. Let position be a position variable for s, initially pointing at the start of s.
+ let mut position = 0;
+
+ // 5. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR
+ // from s given position.
+ let token = collect_token(&mut position);
+
+ // 6. Append token to result.
+ result.push_str(token);
+
+ // 7. While position is not past the end of s:
+ while position < code_points.len() {
+ // 1. If the code point at position within s equals U+000D CR:
+ if code_points[position] == b'\r' {
+ // 1. Append native line ending to result.
+ result.push_str(native_line_ending);
+
+ // 2. Advance position by 1.
+ position += 1;
+
+ // 3. If position is not past the end of s and the code point at position within s equals U+000A LF advance
+ // position by 1.
+ if position < code_points.len() && code_points[position] == b'\n' {
+ position += 1;
+ }
+ }
+ // 2. Otherwise if the code point at position within s equals U+000A LF, advance position by 1 and append native
+ // line ending to result.
+ else if code_points[position] == b'\n' {
+ position += 1;
+ result.push_str(native_line_ending);
+ }
+
+ // 3. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D
+ // CR from s given position.
+ let token = collect_token(&mut position);
+
+ // 4. Append token to result.
+ result.push_str(token);
+ }
+
+ // 8. Return result.
+ result
+}
+
+// https://w3c.github.io/FileAPI/#process-blob-parts
+pub(crate) fn process_blob_parts(blob_parts: &MarkedVec<'_, BlobPart>, options: &BlobPropertyBag) -> Vec<u8> {
+ // 1. Let bytes be an empty sequence of bytes.
+ let mut bytes = Vec::new();
+
+ // 2. For each element in parts:
+ blob_parts.with_values(|blob_parts| {
+ for element in blob_parts {
+ match element {
+ // 1. If element is a USVString, run the following sub-steps:
+ BlobPart::USVString(string) => {
+ // 1. Let s be element.
+ // 2. If the endings member of options is "native", set s to the result of converting line endings
+ // to native of element.
+ // 3. Append the result of UTF-8 encoding s to bytes.
+ if options.endings == EndingType::Native {
+ bytes.extend_from_slice(convert_line_endings_to_native(&string.to_utf8()).as_bytes());
+ } else {
+ append_utf8(&mut bytes, string);
+ }
+ }
+ // 2. If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those
+ // bytes to bytes.
+ BlobPart::BufferSource(buffer_source) => {
+ // SAFETY: Appending the bytes neither runs script nor allocates a cell.
+ unsafe { buffer_source.with_bytes(|held_bytes| bytes.extend_from_slice(held_bytes)) };
+ }
+ // 3. If element is a Blob, append the bytes it represents to bytes.
+ BlobPart::Blob(blob) => bytes.extend_from_slice(&blob.raw_bytes()),
+ }
+ }
+ });
+
+ // 3. Return bytes.
+ bytes
+}
+
+fn is_basic_latin(string: &Utf16String) -> bool {
+ match string.as_units() {
+ Utf16StringUnits::Ascii(bytes) => bytes.iter().all(|&byte| (0x20..=0x7E).contains(&byte)),
+ Utf16StringUnits::Utf16(code_units) => code_units.iter().all(|&code_unit| (0x20..=0x7E).contains(&code_unit)),
+ }
+}
+
+/// The type of a Blob or a File that is constructed with the type member of its options.
+pub(crate) fn type_from_options(r#type: &Utf16String) -> Utf16String {
+ // FIXME: 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
+ // If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return
+ // from these substeps.
+ // FIXME: 2. Convert every character in t to ASCII lowercase.
+
+ // NOTE: The spec is out of date, and we are supposed to call into the MimeType parser here.
+ if !is_basic_latin(r#type) {
+ return Utf16String::default();
+ }
+ let input: Vec<char> = r#type
+ .to_utf16()
+ .iter()
+ .map(|&code_unit| char::from(code_unit as u8))
+ .collect();
+ MimeType::parse(&input).map_or_else(Utf16String::default, |mime_type| {
+ Utf16String::from_ascii(mime_type.serialize().as_bytes())
+ })
+}
+
+impl Blob {
+ pub(crate) fn new(bytes: Vec<u8>, r#type: Utf16String) -> Self {
+ Self {
+ byte_sequence: RefCell::new(ByteSequence::Owned(bytes)),
+ r#type,
+ }
+ }
+
+ /// A Blob that refers to bytes that C++ hands over.
+ ///
+ /// # Safety
+ ///
+ /// `bytes` must be bytes that C++ hands over, which nothing else destroys.
+ pub(crate) unsafe fn with_foreign_bytes(bytes: ForeignBytesAbi, r#type: Utf16String) -> Self {
+ Self {
+ // SAFETY: The caller hands over the bytes.
+ byte_sequence: RefCell::new(ByteSequence::Foreign(unsafe { ForeignBytes::from_abi(bytes) })),
+ r#type,
+ }
+ }
+
+ pub(crate) fn raw_bytes(&self) -> CellRef<'_, [u8]> {
+ CellRef::map(self.byte_sequence.borrow(), ByteSequence::as_slice)
+ }
+
+ pub(crate) fn foreign_bytes_owner(&self) -> *mut c_void {
+ match &*self.byte_sequence.borrow() {
+ ByteSequence::Owned(_) => core::ptr::null_mut(),
+ ByteSequence::Foreign(bytes) => bytes.owner.as_ptr(),
+ }
+ }
+
+ pub(crate) fn type_string(&self) -> &Utf16String {
+ &self.r#type
+ }
+
+ /// Makes the Blob refer to the same bytes in storage that C++ hands over, as it does when it moves them to shared
+ /// memory.
+ ///
+ /// # Safety
+ ///
+ /// `bytes` must be bytes that C++ hands over, which nothing else destroys.
+ pub(crate) unsafe fn set_foreign_bytes(&self, bytes: ForeignBytesAbi) {
+ // SAFETY: The caller hands over the bytes.
+ let bytes = unsafe { ForeignBytes::from_abi(bytes) };
+ *self.byte_sequence.borrow_mut() = ByteSequence::Foreign(bytes);
+ }
+
+ // https://w3c.github.io/FileAPI/#ref-for-dom-blob-blob
+ pub(crate) fn construct(
+ _: &mut CallContext,
+ blob_parts: Option<MarkedVec<'_, BlobPart>>,
+ options: BlobPropertyBag,
+ ) -> WebIdlResult<Self> {
+ // 1. If invoked with zero parameters, return a new Blob object consisting of 0 bytes, with size set to 0, and
+ // with type set to the empty string.
+ // NB: The steps below do that for a Blob constructed with zero parameters, whose options are an empty
+ // dictionary.
+
+ // 2. Let bytes be the result of processing blob parts given blobParts and options.
+ let bytes = blob_parts.map_or_else(Vec::new, |blob_parts| process_blob_parts(&blob_parts, &options));
+
+ // 3. If the type member of the options argument is not the empty string, run the following sub-steps:
+ let r#type = if options.r#type.is_empty() {
+ Utf16String::default()
+ } else {
+ type_from_options(&options.r#type)
+ };
+
+ // 4. Return a Blob object referring to bytes as its associated byte sequence, with its size set to the length
+ // of bytes, and its type set to the value of t from the substeps above.
+ Ok(Self::new(bytes, r#type))
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-size
+ pub(crate) fn size(&self, _: &mut CallContext) -> WebIdlResult<u64> {
+ Ok(self.raw_bytes().len() as u64)
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-type
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.r#type.clone())
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-slice
+ pub(crate) fn slice(
+ &self,
+ cx: &mut CallContext,
+ start: Option<i64>,
+ end: Option<i64>,
+ content_type: Option<Utf16String>,
+ ) -> WebIdlResult<Ref<Blob>> {
+ // 1. Let sliceStart, sliceEnd, and sliceContentType be null.
+ // 2. If start is given, set sliceStart to start.
+ // 3. If end is given, set sliceEnd to end.
+ // 3. If contentType is given, set sliceContentType to contentType.
+ // 4. Return the result of slice blob given this, sliceStart, sliceEnd, and sliceContentType.
+ Ok(allocate(cx.vm(), self.slice_blob(start, end, content_type.as_ref())))
+ }
+
+ // https://w3c.github.io/FileAPI/#slice-blob
+ pub(crate) fn slice_blob(&self, start: Option<i64>, end: Option<i64>, content_type: Option<&Utf16String>) -> Blob {
+ let bytes = self.raw_bytes();
+
+ // 1. Let originalSize be blob’s size.
+ let original_size = i64::try_from(bytes.len()).expect("a Blob has fewer than 2^63 bytes");
+
+ // 2. The start parameter, if non-null, is a value for the start point of a slice blob call, and must be treated
+ // as a byte-order position, with the zeroth position representing the first byte. User agents must normalize
+ // start according to the following:
+ let relative_start = match start {
+ // a. If start is null, let relativeStart be 0.
+ None => 0,
+ // b. If start is negative, let relativeStart be max((originalSize + start), 0).
+ Some(start) if start < 0 => (original_size + start).max(0),
+ // c. Otherwise, let relativeStart be min(start, originalSize).
+ Some(start) => start.min(original_size),
+ };
+
+ // 3. The end parameter, if non-null. is a value for the end point of a slice blob call. User agents must
+ // normalize end according to the following:
+ let relative_end = match end {
+ // a. If end is null, let relativeEnd be originalSize.
+ None => original_size,
+ // b. If end is negative, let relativeEnd be max((originalSize + end), 0).
+ Some(end) if end < 0 => (original_size + end).max(0),
+ // c. Otherwise, let relativeEnd be min(end, originalSize).
+ Some(end) => end.min(original_size),
+ };
+
+ // 4. The contentType parameter, if non-null, is used to set the ASCII-encoded string in lower case representing
+ // the media type of the Blob. User agents must normalize contentType according to the following:
+ let relative_content_type = match content_type {
+ // a. If contentType is null, let relativeContentType be set to the empty string.
+ None => Utf16String::default(),
+ // b. Otherwise, let relativeContentType be set to contentType and run the substeps below:
+ // 1. If relativeContentType contains any characters outside the range of U+0020 to U+007E, then set
+ // relativeContentType to the empty string and return from these substeps:
+ Some(content_type) if !is_basic_latin(content_type) => Utf16String::default(),
+ // 2. Convert every character in relativeContentType to ASCII lowercase.
+ Some(content_type) => {
+ let lowercase: Vec<u8> = content_type
+ .to_utf16()
+ .iter()
+ .map(|&code_unit| (code_unit as u8).to_ascii_lowercase())
+ .collect();
+ Utf16String::from_ascii(&lowercase)
+ }
+ };
+
+ // 5. Let span be max((relativeEnd - relativeStart), 0).
+ let span = (relative_end - relative_start).max(0);
+
+ // 6. Return a new Blob object S with the following characteristics:
+ // a. S refers to span consecutive bytes from blob’s associated byte sequence, beginning with the byte at
+ // byte-order position relativeStart.
+ // b. S.size = span.
+ // c. S.type = relativeContentType.
+ let relative_start = usize::try_from(relative_start).expect("relativeStart is not negative");
+ let span = usize::try_from(span).expect("span is not negative");
+ Blob::new(
+ bytes[relative_start..relative_start + span].to_vec(),
+ relative_content_type,
+ )
+ }
+
+ // https://w3c.github.io/FileAPI/#dom-blob-stream
+ pub(crate) fn stream(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // SAFETY: The realm is live, LibWeb copies the bytes, and it returns the wrapper of a new ReadableStream.
+ unsafe {
+ let stream = web_blob_get_stream(cx.realm().as_ptr().cast(), ak::Span::new(&self.raw_bytes()));
+ Ok(CppInterface::from_wrapper(object_from_abi(stream)))
+ }
+ }
+
+ // https://w3c.github.io/FileAPI/#dom-blob-text
+ pub(crate) fn text(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ // SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
+ Ok(unsafe {
+ object_from_abi(web_blob_text(
+ cx.realm().as_ptr().cast(),
+ ak::Span::new(&self.raw_bytes()),
+ ))
+ })
+ }
+
+ // https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
+ pub(crate) fn array_buffer(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ // SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
+ Ok(unsafe {
+ object_from_abi(web_blob_array_buffer(
+ cx.realm().as_ptr().cast(),
+ ak::Span::new(&self.raw_bytes()),
+ ))
+ })
+ }
+
+ // https://w3c.github.io/FileAPI/#dom-blob-bytes
+ pub(crate) fn bytes(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ // SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new promise.
+ Ok(unsafe {
+ object_from_abi(web_blob_bytes(
+ cx.realm().as_ptr().cast(),
+ ak::Span::new(&self.raw_bytes()),
+ ))
+ })
+ }
+
+ pub(crate) fn serialize(&self, serialized: &mut SerializationWriter) {
+ // FIXME: 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
+
+ // NON-STANDARD: FileAPI spec doesn't specify that type should be serialized, although
+ // to be conformant with other browsers this needs to be serialized.
+ serialized.write_utf16_string(&self.r#type);
+
+ // 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
+ serialized.write_bytes(&self.raw_bytes());
+ }
+
+ pub(crate) fn deserialize(serialized: &mut SerializationReader) -> WebIdlResult<Self> {
+ // FIXME: 1. Set value’s snapshot state to serialized.[[SnapshotState]].
+
+ // NON-STANDARD: FileAPI spec doesn't specify that type should be deserialized, although
+ // to be conformant with other browsers this needs to be deserialized.
+ let r#type = serialized.read_utf16_string()?;
+
+ // 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
+ let mut bytes = ForeignBytesAbi {
+ owner: core::ptr::null_mut(),
+ data: core::ptr::null(),
+ length: 0,
+ };
+ // SAFETY: The reader is lent for the steps.
+ unsafe { web_blob_deserialize_byte_sequence(serialized.as_raw(), &mut bytes) }.into_completion()?;
+
+ // SAFETY: C++ hands over the bytes it decoded.
+ Ok(unsafe { Self::with_foreign_bytes(bytes, r#type) })
+ }
+}
+
+/// The object that LibWeb returns.
+///
+/// # Safety
+///
+/// `object` must be a live object.
+unsafe fn object_from_abi(object: *mut c_void) -> Gc<Object> {
+ let object = NonNull::new(object.cast::<Object>()).expect("LibWeb returns an object");
+ // SAFETY: The caller passes a live object.
+ unsafe { Gc::from_non_null(object) }
+}
+
+impl Serializable for Blob {
+ fn serialization_steps(
+ &self,
+ _: &mut CallContext,
+ serialized: &mut SerializationWriter,
+ _for_storage: bool,
+ ) -> WebIdlResult<()> {
+ self.serialize(serialized);
+ Ok(())
+ }
+
+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {
+ Self::deserialize(serialized)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs
new file mode 100644
index 00000000000..9e22ec5a81b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/exports.rs
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which LibWeb's C++ creates the Blob and File objects that it hands to script, and reads those that
+//! it receives, which Libraries/LibWeb/FileAPI/Blob.h and File.h declare. A Blob cell can be that of a File.
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::Vm;
+
+use super::blob::{Blob, BlobPropertyBag, EndingType, ForeignBytesAbi};
+use super::file::{File, FilePropertyBag};
+use crate::bindings::interface::{Inherits, Interface, Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi};
+
+/// # Safety
+///
+/// `vm` must be the live VM.
+unsafe fn vm_from_abi<'vm>(vm: *mut c_void) -> &'vm Vm {
+ assert!(!vm.is_null(), "C++ passes the VM");
+ // SAFETY: The caller passes the live VM.
+ unsafe { &*vm.cast::<Vm>() }
+}
+
+/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of an object of the interface, and it must outlive `'a`.
+unsafe fn object_from_abi<'a, T: Interface>(cell: *mut c_void) -> &'a T {
+ // SAFETY: The caller passes a live cell of the interface.
+ let object: Ref<T> = unsafe { cell_from_abi(cell) };
+ // SAFETY: The caller keeps the cell alive for 'a.
+ unsafe { &*object.as_ptr() }
+}
+
+/// The Blob or File whose cell C++ lends, as a Blob.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File, and it must outlive `'a`.
+unsafe fn blob_from_abi<'a>(cell: *mut c_void) -> &'a Blob {
+ // SAFETY: The caller passes a live cell.
+ if let Some(blob) = unsafe { cell_if_abi::<Blob>(cell) } {
+ // SAFETY: The caller keeps the cell alive for 'a.
+ return unsafe { &*blob.as_ptr() };
+ }
+ // SAFETY: The caller passes the cell of a File, which it keeps alive for 'a.
+ unsafe { object_from_abi::<File>(cell) }.parent()
+}
+
+/// A new Blob that refers to the bytes that C++ hands over, with the type, a raw AK::Utf16String that C++ hands over.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `bytes` bytes that C++ hands over, and `type` a raw string that C++ owns a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_create(vm: *mut c_void, bytes: ForeignBytesAbi, r#type: usize) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the bytes and the string.
+ let blob = unsafe { Blob::with_foreign_bytes(bytes, Utf16String::from_raw_owned(r#type)) };
+ cell_into_abi(allocate(vm, blob))
+}
+
+/// The byte sequence of the Blob or File, which lives until the object dies or its bytes move to shared memory.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_byte_sequence(cell: *mut c_void, out_length: &mut usize) -> *const u8 {
+ // SAFETY: The caller passes a live cell.
+ let bytes = unsafe { blob_from_abi(cell) }.raw_bytes();
+ *out_length = bytes.len();
+ bytes.as_ptr()
+}
+
+/// The owner of the bytes of the Blob or File if C++ handed them over, or null.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_foreign_bytes_owner(cell: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell.
+ unsafe { blob_from_abi(cell) }.foreign_bytes_owner()
+}
+
+/// Makes the Blob or File refer to the same bytes in storage that C++ hands over.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File, and `bytes` bytes that C++ hands over, which are those of the
+/// object.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_set_foreign_bytes(cell: *mut c_void, bytes: ForeignBytesAbi) {
+ // SAFETY: The caller passes a live cell and hands over the bytes.
+ unsafe { blob_from_abi(cell).set_foreign_bytes(bytes) };
+}
+
+/// The type of the Blob or File, a raw AK::Utf16String that the call lends for as long as the object lives.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_type(cell: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell.
+ unsafe { blob_from_abi(cell) }.type_string().raw_identity()
+}
+
+/// The result of slice blob given the Blob or File, start, end and contentType, which are null unless `has_start`,
+/// `has_end` and `has_content_type`. contentType is a raw AK::Utf16String that C++ hands over,
+/// https://w3c.github.io/FileAPI/#slice-blob
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `cell` the live cell of a Blob or a File, and `content_type` a raw string that C++ owns a
+/// reference to if `has_content_type`.
+#[unsafe(no_mangle)]
+#[allow(
+ clippy::too_many_arguments,
+ reason = "the arguments are the parameters of slice blob, which can each be null"
+)]
+pub unsafe extern "C" fn web_blob_slice(
+ vm: *mut c_void,
+ cell: *mut c_void,
+ has_start: bool,
+ start: i64,
+ has_end: bool,
+ end: i64,
+ has_content_type: bool,
+ content_type: usize,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the string if it has one.
+ let content_type = has_content_type.then(|| unsafe { Utf16String::from_raw_owned(content_type) });
+ // SAFETY: The caller passes a live cell.
+ let blob = unsafe { blob_from_abi(cell) };
+ let sliced_blob = blob.slice_blob(
+ has_start.then_some(start),
+ has_end.then_some(end),
+ content_type.as_ref(),
+ );
+ cell_into_abi(allocate(vm, sliced_blob))
+}
+
+/// Whether the cell of a Blob or a File is that of a File.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a Blob or a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_blob_is_file(cell: *mut c_void) -> bool {
+ // SAFETY: The caller passes a live cell.
+ unsafe { cell_if_abi::<File>(cell) }.is_some()
+}
+
+/// A new File, as the File constructor creates it given one part of the bytes, the file name and the options with the
+/// type, which are raw AK::Utf16Strings that C++ hands over, and the last modified date if `has_last_modified`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `file_name` and `type` raw strings that C++ owns a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_file_create(
+ vm: *mut c_void,
+ bytes: ak::Span<'_, u8>,
+ file_name: usize,
+ r#type: usize,
+ has_last_modified: bool,
+ last_modified: i64,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the strings.
+ let (file_name, r#type) = unsafe {
+ (
+ Utf16String::from_raw_owned(file_name),
+ Utf16String::from_raw_owned(r#type),
+ )
+ };
+ let options = FilePropertyBag {
+ parent: BlobPropertyBag {
+ endings: EndingType::Transparent,
+ r#type,
+ },
+ last_modified: has_last_modified.then_some(last_modified),
+ };
+ let file = File::create(bytes.as_slice().to_vec(), file_name, &options);
+ cell_into_abi(allocate(vm, file))
+}
+
+/// The name of the File, a raw AK::Utf16String that the call lends for as long as the File lives.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_file_name(cell: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell of a File.
+ unsafe { object_from_abi::<File>(cell) }.name_string().raw_identity()
+}
+
+/// # Safety
+///
+/// `cell` must be the live cell of a File.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_file_last_modified(cell: *mut c_void) -> i64 {
+ // SAFETY: The caller passes a live cell of a File.
+ unsafe { object_from_abi::<File>(cell) }.last_modified_value()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/file.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/file.rs
new file mode 100644
index 00000000000..dd2fcb161ed
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/file.rs
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! File, https://w3c.github.io/FileAPI/#file-section
+
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace};
+
+use super::blob::{Blob, BlobPart, BlobPropertyBag, process_blob_parts, type_from_options};
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Inherits, Wrappable};
+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
+use crate::bindings::{CallContext, WebIdlResult};
+
+/// The dictionary FilePropertyBag of FileAPI/File.idl, whose members the bindings convert.
+pub(crate) struct FilePropertyBag {
+ pub(crate) parent: BlobPropertyBag,
+ pub(crate) last_modified: Option<i64>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct File {
+ blob: Blob,
+ // https://w3c.github.io/FileAPI/#dfn-name
+ #[gc(untraced)]
+ name: Utf16String,
+ // https://w3c.github.io/FileAPI/#dfn-lastModified
+ #[gc(untraced)]
+ last_modified: i64,
+}
+
+impl Wrappable for File {}
+
+impl Inherits<Blob> for File {
+ fn parent(&self) -> &Blob {
+ &self.blob
+ }
+}
+
+impl File {
+ // https://w3c.github.io/FileAPI/#ref-for-dom-file-file
+ pub(crate) fn construct(
+ _: &mut CallContext,
+ file_bits: MarkedVec<'_, BlobPart>,
+ file_name: UsvString,
+ options: FilePropertyBag,
+ ) -> WebIdlResult<Self> {
+ // 1. Let bytes be the result of processing blob parts given fileBits and options.
+ let bytes = process_blob_parts(&file_bits, &options.parent);
+
+ Ok(Self::create(bytes, file_name.into_utf16_string(), &options))
+ }
+
+ /// Steps 2 to 4 of the File constructor, given the bytes that step 1 results in.
+ pub(crate) fn create(bytes: Vec<u8>, file_name: Utf16String, options: &FilePropertyBag) -> Self {
+ // 2. Let n be the fileName argument to the constructor.
+ // NOTE: Underlying OS filesystems use differing conventions for file name; with constructed files, mandating
+ // UTF-16 lessens ambiquity when file names are converted to byte sequences.
+ let name = file_name;
+
+ // 3. Process FilePropertyBag dictionary argument by running the following substeps:
+ let r#type = type_from_options(&options.parent.r#type);
+
+ // 3. If the lastModified member is provided, let d be set to the lastModified dictionary member. If it is not
+ // provided, set d to the current date and time represented as the number of milliseconds since the Unix
+ // Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ // Note: Since ECMA-262 Date objects convert to long long values representing the number of milliseconds
+ // since the Unix Epoch, the lastModified member could be a Date object [ECMA-262].
+ let last_modified = options.last_modified.unwrap_or_else(|| {
+ let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
+ i64::try_from(since_epoch.as_millis()).unwrap_or(i64::MAX)
+ });
+
+ // 4. Return a new File object F such that:
+ // 2. F refers to the bytes byte sequence.
+ // NOTE: Spec started at 2 therefore keeping the same number sequence here.
+ // 3. F.size is set to the number of total bytes in bytes.
+ // 4. F.name is set to n.
+ // 5. F.type is set to t.
+ // 6. F.lastModified is set to d.
+ Self {
+ blob: Blob::new(bytes, r#type),
+ name,
+ last_modified,
+ }
+ }
+
+ pub(crate) fn name_string(&self) -> &Utf16String {
+ &self.name
+ }
+
+ pub(crate) fn last_modified_value(&self) -> i64 {
+ self.last_modified
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.name.clone())
+ }
+
+ // https://w3c.github.io/FileAPI/#dfn-lastModified
+ pub(crate) fn last_modified(&self, _: &mut CallContext) -> WebIdlResult<i64> {
+ Ok(self.last_modified)
+ }
+}
+
+impl Serializable for File {
+ fn serialization_steps(
+ &self,
+ _: &mut CallContext,
+ serialized: &mut SerializationWriter,
+ _for_storage: bool,
+ ) -> WebIdlResult<()> {
+ // 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
+ // 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
+ self.blob.serialize(serialized);
+
+ // 3. Set serialized.[[Name]] to the value of value’s name attribute.
+ serialized.write_utf16_string(&self.name);
+
+ // 4. Set serialized.[[LastModified]] to the value of value’s lastModified attribute.
+ serialized.write_i64(self.last_modified);
+
+ Ok(())
+ }
+
+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {
+ // 1. Set value’s snapshot state to serialized.[[SnapshotState]].
+ // 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
+ let blob = Blob::deserialize(serialized)?;
+
+ // 3. Initialize the value of value’s name attribute to serialized.[[Name]].
+ let name = serialized.read_utf16_string()?;
+
+ // 4. Initialize the value of value’s lastModified attribute to serialized.[[LastModified]].
+ let last_modified = serialized.read_i64()?;
+
+ Ok(Self {
+ blob,
+ name,
+ last_modified,
+ })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs
new file mode 100644
index 00000000000..feaeda52a91
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/mod.rs
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The File API, https://w3c.github.io/FileAPI/
+
+#[cfg(not(test))]
+pub(crate) mod blob;
+#[cfg(not(test))]
+pub(crate) mod exports;
+#[cfg(not(test))]
+pub(crate) mod file;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 67d078f29b5..29cdab44c2f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -61,6 +61,15 @@ pub(crate) mod encoding;
clippy::unnecessary_wraps,
reason = "the bindings call every attribute and operation as one that can throw"
)]
+pub(crate) mod file_api;
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
pub(crate) mod geometry;
#[cfg_attr(
not(web_idl_bindings),
diff --git a/Libraries/LibWeb/DOMURL/DOMURL.cpp b/Libraries/LibWeb/DOMURL/DOMURL.cpp
index 69611c300f0..e7b410b4ba1 100644
--- a/Libraries/LibWeb/DOMURL/DOMURL.cpp
+++ b/Libraries/LibWeb/DOMURL/DOMURL.cpp
@@ -22,22 +22,27 @@ namespace Web::DOMURL {
// Called by Bindings/Rust/src/domurl/url.rs.
extern "C" {
-FlatPtr web_url_create_object_url(JSObject* object);
+FlatPtr web_url_create_object_url_for_blob(FileAPI::Blob* blob);
+FlatPtr web_url_create_object_url_for_media_source(JSObject* object);
void web_url_revoke_object_url(FlatPtr raw_url);
}
// https://w3c.github.io/FileAPI/#dfn-createObjectURL
-extern "C" FlatPtr web_url_create_object_url(JSObject* object)
+static FlatPtr create_object_url(FileAPI::BlobURLEntry::Object obj)
{
- 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 MUST(FileAPI::add_entry_to_blob_url_store(blob_url_entry_object)).into_raw();
+ return MUST(FileAPI::add_entry_to_blob_url_store(obj)).into_raw();
+}
+
+extern "C" FlatPtr web_url_create_object_url_for_blob(FileAPI::Blob* blob)
+{
+ return create_object_url(GC::Ref { *blob });
+}
+
+extern "C" FlatPtr web_url_create_object_url_for_media_source(JSObject* object)
+{
+ auto* wrappable = Bindings::wrappable_impl_from(JS::HostABI::object_from_abi(object));
+ return create_object_url(GC::Ref { as<MediaSourceExtensions::MediaSource>(*wrappable) });
}
// https://w3c.github.io/FileAPI/#dfn-revokeObjectURL
diff --git a/Libraries/LibWeb/Fetch/Body.cpp b/Libraries/LibWeb/Fetch/Body.cpp
index de7652c8c46..bc970168015 100644
--- a/Libraries/LibWeb/Fetch/Body.cpp
+++ b/Libraries/LibWeb/Fetch/Body.cpp
@@ -430,10 +430,7 @@ MultipartParsingErrorOr<GC::ConservativeVector<XHR::FormDataEntry>> parse_multip
// 3. Let value be a new File object with name filename, type contentType, and body body.
auto content_type = header.content_type.release_value();
- auto blob = FileAPI::Blob::create(MUST(ByteBuffer::copy(body.bytes())), content_type);
- FileAPI::FilePropertyBag options {};
- options.type = Utf16String::from_utf8(content_type);
- value = MUST(FileAPI::File::create({ { blob } }, header.filename.release_value(), move(options)));
+ value = FileAPI::File::create(body.bytes(), Utf16String::from_utf8(header.filename.release_value()), Utf16String::from_utf8(content_type));
}
// 11. Otherwise:
else {
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 2772508ddb8..1d3652c0267 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -1252,7 +1252,7 @@ GC::Ref<PendingResponse> scheme_fetch(JS::Realm& realm, Infrastructure::FetchPar
}
// 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, rangeEnd + 1, and type.
- auto sliced_blob = MUST(blob->slice_blob(*range_start, *range_end + 1, type));
+ auto sliced_blob = blob->slice_blob(*range_start, *range_end + 1, type);
// 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
auto sliced_body_with_type = safely_extract_body(realm, sliced_blob->raw_bytes());
diff --git a/Libraries/LibWeb/FileAPI/Blob.cpp b/Libraries/LibWeb/FileAPI/Blob.cpp
index 1b41c8f2df1..9f23152df1d 100644
--- a/Libraries/LibWeb/FileAPI/Blob.cpp
+++ b/Libraries/LibWeb/FileAPI/Blob.cpp
@@ -5,351 +5,121 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/GenericLexer.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/TypedArray.h>
+#include <LibJS/Runtime/VM.h>
#include <LibTextCodec/Decoder.h>
+#include <LibWeb/Bindings/RustSerialization.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
#include <LibWeb/Streams/ReadableStreamOperations.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/Buffers.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
#include <LibWeb/WebIDL/Promise.h>
-#include <LibWebCommon/Infra/Strings.h>
-#include <LibWebCommon/MimeSniff/MimeType.h>
namespace Web::FileAPI {
-GC_DEFINE_ALLOCATOR(Blob);
+// The bytes that C++ hands a Blob, which the Blob owns from then on.
+struct BlobBytes {
+ AK_ALLOC_WITH_KMALLOC;
-ReadonlyBytes Blob::raw_bytes() const
-{
- return m_byte_sequence.visit(
- [](ByteBuffer const& bytes) { return bytes.bytes(); },
- [](Core::AnonymousBuffer const& buffer) { return buffer.bytes(); });
-}
+ Variant<ByteBuffer, Core::AnonymousBuffer> bytes;
+};
-ErrorOr<Core::AnonymousBuffer> Blob::shared_bytes()
-{
- if (auto* bytes = m_byte_sequence.get_pointer<ByteBuffer>()) {
- Core::AnonymousBuffer buffer;
- if (!bytes->is_empty()) {
- buffer = TRY(Core::AnonymousBuffer::create_with_size(bytes->size()));
- bytes->bytes().copy_to({ buffer.data<u8>(), buffer.size() });
- }
- m_byte_sequence = move(buffer);
- }
- return m_byte_sequence.get<Core::AnonymousBuffer>();
-}
+// The bytes as Bindings/Rust/src/file_api/blob.rs takes them over.
+struct BlobBytesABI {
+ BlobBytes* owner { nullptr };
+ u8 const* data { nullptr };
+ size_t length { 0 };
+};
-GC::Ref<Blob> Blob::create(ByteBuffer byte_buffer, Utf16String type)
+static BlobBytesABI hand_over(Variant<ByteBuffer, Core::AnonymousBuffer> bytes)
{
- return GC::Heap::the().allocate<Blob>(move(byte_buffer), move(type));
+ auto* owner = new BlobBytes { move(bytes) };
+ auto data = owner->bytes.visit([](auto const& bytes) { return bytes.bytes(); });
+ return { .owner = owner, .data = data.data(), .length = data.size() };
}
-GC::Ref<Blob> Blob::create(Core::AnonymousBuffer bytes, Utf16String type)
-{
- return GC::Heap::the().allocate<Blob>(move(bytes), move(type));
+extern "C" {
+
+// Defined in Bindings/Rust/src/file_api/exports.rs.
+void* web_blob_create(JSVM*, BlobBytesABI bytes, FlatPtr type);
+u8 const* web_blob_byte_sequence(void* blob, size_t* out_length);
+BlobBytes* web_blob_foreign_bytes_owner(void* blob);
+void web_blob_set_foreign_bytes(void* blob, BlobBytesABI bytes);
+void* web_blob_slice(JSVM*, void* blob, bool has_start, i64 start, bool has_end, i64 end, bool has_content_type, FlatPtr content_type);
+FlatPtr web_blob_type(void* blob);
+bool web_blob_is_file(void* blob);
+
+// Called by Bindings/Rust/src/file_api/blob.rs.
+void web_blob_bytes_destroy(BlobBytes*);
+JSObject* web_blob_get_stream(void* realm, ReadonlyBytes);
+JSObject* web_blob_text(void* realm, ReadonlyBytes);
+JSObject* web_blob_array_buffer(void* realm, ReadonlyBytes);
+JSObject* web_blob_bytes(void* realm, ReadonlyBytes);
+JSCompletion web_blob_deserialize_byte_sequence(Bindings::RustSerializationReader*, BlobBytesABI* out_bytes);
}
-// https://w3c.github.io/FileAPI/#convert-line-endings-to-native
-ErrorOr<Utf16String> convert_line_endings_to_native(Utf16View string)
+GC::Ref<Blob> Blob::create(ByteBuffer bytes, Utf16String type)
{
- // 1. Let native line ending be the code point U+000A LF.
- auto native_line_ending = "\n"_utf16;
-
- // 2. If the underlying platform’s conventions are to represent newlines as a carriage return and line feed sequence, set native line ending to the code point U+000D CR followed by the code point U+000A LF.
- // NOTE: this step is a no-op since LibWeb does not compile on Windows, which is the only platform we know of that that uses a carriage return and line feed sequence for line endings.
-
- // 3. Set result to the empty string.
- Utf16StringBuilder result { string.length_in_code_units() };
-
- // 4. Let position be a position variable for s, initially pointing at the start of s.
- size_t position = 0;
-
- // 5. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
- size_t token_start = position;
- while (position < string.length_in_code_units() && string.code_unit_at(position) != '\n' && string.code_unit_at(position) != '\r')
- ++position;
-
- // 6. Append token to result.
- result.append(string.substring_view(token_start, position - token_start));
-
- // 7. While position is not past the end of s:
- while (position < string.length_in_code_units()) {
- // 1. If the code point at position within s equals U+000D CR:
- if (string.code_unit_at(position) == '\r') {
- // 1. Append native line ending to result.
- result.append(native_line_ending);
-
- // 2. Advance position by 1.
- ++position;
-
- // 3. If position is not past the end of s and the code point at position within s equals U+000A LF advance position by 1.
- if (position < string.length_in_code_units() && string.code_unit_at(position) == '\n')
- ++position;
- }
- // 2. Otherwise if the code point at position within s equals U+000A LF, advance position by 1 and append native line ending to result.
- else if (string.code_unit_at(position) == '\n') {
- ++position;
- result.append(native_line_ending);
- }
-
- // 3. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
- token_start = position;
- while (position < string.length_in_code_units() && string.code_unit_at(position) != '\n' && string.code_unit_at(position) != '\r')
- ++position;
-
- // 4. Append token to result.
- result.append(string.substring_view(token_start, position - token_start));
- }
- // 5. Return result.
- return result.to_string();
+ return GC::Ref { *static_cast<Blob*>(web_blob_create(JS::HostABI::vm_to_abi(JS::VM::the()), hand_over(move(bytes)), move(type).into_raw())) };
}
-// https://w3c.github.io/FileAPI/#process-blob-parts
-ErrorOr<ByteBuffer> process_blob_parts(BlobParts const& blob_parts, Optional<BlobPropertyBag> const& options)
-{
- // 1. Let bytes be an empty sequence of bytes.
- ByteBuffer bytes {};
-
- // 2. For each element in parts:
- for (auto const& blob_part : blob_parts) {
- TRY(blob_part.visit(
- // 1. If element is a USVString, run the following sub-steps:
- [&](Utf16String const& string) -> ErrorOr<void> {
- // 1. Let s be element.
- auto s = string;
-
- // 2. If the endings member of options is "native", set s to the result of converting line endings to native of element.
- if (options.has_value() && options->endings == EndingType::Native)
- s = TRY(convert_line_endings_to_native(s));
-
- // 3. Append the result of UTF-8 encoding s to bytes.
- auto encoded_string = s.to_utf8();
- return bytes.try_append(encoded_string.bytes());
- },
- // 2. If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those bytes to bytes.
- [&](WebIDL::BufferSourceVariant buffer_source) -> ErrorOr<void> {
- auto data_buffer = TRY(WebIDL::get_buffer_source_copy(buffer_source));
- return bytes.try_append(data_buffer.bytes());
- },
- // 3. If element is a Blob, append the bytes it represents to bytes.
- [&](GC::Ref<Blob> const& blob) -> ErrorOr<void> {
- return bytes.try_append(blob->raw_bytes());
- }));
- }
- // 3. Return bytes.
- return bytes;
-}
-
-bool is_basic_latin(Utf16View view)
-{
- for (auto code_point : view) {
- if (code_point < 0x0020 || code_point > 0x007E)
- return false;
- }
- return true;
-}
-
-Blob::Blob()
-{
-}
-
-Blob::Blob(ByteBuffer byte_buffer, Utf16String type)
- : m_byte_sequence(move(byte_buffer))
- , m_type(move(type))
-{
-}
-
-Blob::Blob(Core::AnonymousBuffer bytes, Utf16String type)
- : m_byte_sequence(move(bytes))
- , m_type(move(type))
+GC::Ref<Blob> Blob::create(Core::AnonymousBuffer bytes, Utf16String type)
{
+ return GC::Ref { *static_cast<Blob*>(web_blob_create(JS::HostABI::vm_to_abi(JS::VM::the()), hand_over(move(bytes)), move(type).into_raw())) };
}
-Blob::Blob(ByteBuffer byte_buffer)
- : m_byte_sequence(move(byte_buffer))
+Utf16String Blob::type() const
{
+ return Utf16String::from_raw(web_blob_type(const_cast<Blob*>(this)));
}
-Blob::~Blob() = default;
-
-WebIDL::ExceptionOr<void> Blob::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)
+ReadonlyBytes Blob::raw_bytes() const
{
- // FIXME: 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
-
- // NON-STANDARD: FileAPI spec doesn't specify that type should be serialized, although
- // to be conformant with other browsers this needs to be serialized.
- serialized.encode(m_type);
-
- // 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
- serialized.encode(raw_bytes());
-
- return {};
+ size_t length = 0;
+ auto const* data = web_blob_byte_sequence(const_cast<Blob*>(this), &length);
+ return { data, length };
}
-WebIDL::ExceptionOr<void> Blob::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)
-{
- // FIXME: 1. Set value’s snapshot state to serialized.[[SnapshotState]].
-
- // NON-STANDARD: FileAPI spec doesn't specify that type should be deserialized, although
- // to be conformant with other browsers this needs to be deserialized.
- m_type = TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized));
-
- // 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
- m_byte_sequence = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized));
-
- return {};
-}
-
-// https://w3c.github.io/FileAPI/#ref-for-dom-blob-blob
-GC::Ref<Blob> Blob::create(Optional<BlobPartsOrByteBuffer> const& blob_parts_or_byte_buffer, Optional<BlobPropertyBag> const& options)
+ErrorOr<Core::AnonymousBuffer> Blob::shared_bytes()
{
- // 1. If invoked with zero parameters, return a new Blob object consisting of 0 bytes, with size set to 0, and with type set to the empty string.
- if (!blob_parts_or_byte_buffer.has_value() && !options.has_value())
- return GC::Heap::the().allocate<Blob>();
-
- ByteBuffer byte_buffer {};
- // 2. Let bytes be the result of processing blob parts given blobParts and options.
- if (blob_parts_or_byte_buffer.has_value()) {
- byte_buffer = blob_parts_or_byte_buffer->visit(
- [&](BlobParts const& blob_parts) {
- return MUST(process_blob_parts(blob_parts, options));
- },
- [](ByteBuffer const& byte_buffer) {
- return byte_buffer;
- });
- }
-
- auto type = Utf16String {};
- // 3. If the type member of the options argument is not the empty string, run the following sub-steps:
- if (options.has_value() && !options->type.is_empty()) {
- // FIXME: 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
- // If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps.
- // FIXME: 2. Convert every character in t to ASCII lowercase.
-
- // NOTE: The spec is out of date, and we are supposed to call into the MimeType parser here.
- if (is_basic_latin(options->type.utf16_view())) {
- auto maybe_parsed_type = MimeSniff::MimeType::parse(options->type.utf16_view());
- if (maybe_parsed_type.has_value())
- type = maybe_parsed_type->serialized_as_utf16();
- }
+ if (auto* owner = web_blob_foreign_bytes_owner(this); owner && owner->bytes.has<Core::AnonymousBuffer>())
+ return owner->bytes.get<Core::AnonymousBuffer>();
+
+ auto bytes = raw_bytes();
+ Core::AnonymousBuffer buffer;
+ if (!bytes.is_empty()) {
+ buffer = TRY(Core::AnonymousBuffer::create_with_size(bytes.size()));
+ bytes.copy_to({ buffer.data<u8>(), buffer.size() });
}
-
- // 4. Return a Blob object referring to bytes as its associated byte sequence, with its size set to the length of bytes, and its type set to the value of t from the substeps above.
- return GC::Heap::the().allocate<Blob>(move(byte_buffer), move(type));
-}
-
-WebIDL::ExceptionOr<GC::Ref<Blob>> Blob::construct_impl(Optional<BlobParts> const& blob_parts, Optional<BlobPropertyBag> const& options)
-{
- if (blob_parts.has_value())
- return create(BlobPartsOrByteBuffer { blob_parts.value() }, options);
- return create({}, options);
+ web_blob_set_foreign_bytes(this, hand_over(buffer));
+ return buffer;
}
-// https://w3c.github.io/FileAPI/#dfn-slice
-WebIDL::ExceptionOr<GC::Ref<Blob>> Blob::slice(Optional<i64> start, Optional<i64> end, Optional<Utf16String> const& content_type)
+GC::Ref<Blob> Blob::slice_blob(Optional<i64> start, Optional<i64> end, Optional<Utf16String> content_type) const
{
- // 1. Let sliceStart, sliceEnd, and sliceContentType be null.
- // 2. If start is given, set sliceStart to start.
- // 3. If end is given, set sliceEnd to end.
- // 3. If contentType is given, set sliceContentType to contentType.
- // 4. Return the result of slice blob given this, sliceStart, sliceEnd, and sliceContentType.
- return TRY_OR_THROW_OOM(JS::VM::the(), slice_blob(start, end, content_type));
-}
-
-// https://w3c.github.io/FileAPI/#slice-blob
-ErrorOr<GC::Ref<Blob>> Blob::slice_blob(Optional<i64> start, Optional<i64> end, Optional<Utf16String> const& content_type)
-{
- // 1. Let originalSize be blob’s size.
- auto original_size = size();
-
- // 2. The start parameter, if non-null, is a value for the start point of a slice blob call, and must be treated as a byte-order position,
- // with the zeroth position representing the first byte. User agents must normalize start according to the following:
- i64 relative_start;
- if (!start.has_value()) {
- // a. If start is null, let relativeStart be 0.
- relative_start = 0;
- } else {
- auto start_value = start.value();
-
- // b. If start is negative, let relativeStart be max((originalSize + start), 0).
- if (start_value < 0) {
- relative_start = max((static_cast<i64>(original_size) + start_value), 0);
- }
- // c. Otherwise, let relativeStart be min(start, originalSize).
- else {
- relative_start = min(start_value, original_size);
- }
- }
-
- // 3. The end parameter, if non-null. is a value for the end point of a slice blob call. User agents must normalize end according to the following:
- i64 relative_end;
- if (!end.has_value()) {
- // a. If end is null, let relativeEnd be originalSize.
- relative_end = original_size;
- } else {
- auto end_value = end.value();
-
- // b. If end is negative, let relativeEnd be max((originalSize + end), 0).
- if (end_value < 0) {
- relative_end = max((static_cast<i64>(original_size) + end_value), 0);
- }
- // c. Otherwise, let relativeEnd be min(end, originalSize).
- else {
- relative_end = min(end_value, original_size);
- }
- }
-
- // 4. The contentType parameter, if non-null, is used to set the ASCII-encoded string in lower case representing the media type of the Blob.
- // User agents must normalize contentType according to the following:
- Utf16String relative_content_type;
- if (!content_type.has_value()) {
- // a. If contentType is null, let relativeContentType be set to the empty string.
- relative_content_type = {};
- } else {
- // b. Otherwise, let relativeContentType be set to contentType and run the substeps below:
-
- // 1. If relativeContentType contains any characters outside the range of U+0020 to U+007E, then set relativeContentType to the empty string
- // and return from these substeps:
- if (!is_basic_latin(content_type->utf16_view())) {
- relative_content_type = {};
- }
- // 2. Convert every character in relativeContentType to ASCII lowercase.
- else {
- relative_content_type = content_type->to_ascii_lowercase();
- }
- }
-
- // 5. Let span be max((relativeEnd - relativeStart), 0).
- auto span = max((relative_end - relative_start), 0);
-
- // 6. Return a new Blob object S with the following characteristics:
- // a. S refers to span consecutive bytes from blob’s associated byte sequence, beginning with the byte at byte-order position relativeStart.
- // b. S.size = span.
- // c. S.type = relativeContentType.
- auto byte_buffer = TRY(ByteBuffer::copy(raw_bytes().slice(relative_start, span)));
- return create(move(byte_buffer), move(relative_content_type));
+ auto has_content_type = content_type.has_value();
+ auto raw_content_type = has_content_type ? content_type.release_value().into_raw() : 0;
+ auto* sliced_blob = web_blob_slice(JS::HostABI::vm_to_abi(JS::VM::the()), const_cast<Blob*>(this), start.has_value(), start.value_or(0), end.has_value(), end.value_or(0), has_content_type, raw_content_type);
+ return GC::Ref { *static_cast<Blob*>(sliced_blob) };
}
-// https://w3c.github.io/FileAPI/#dom-blob-stream
-GC::Ref<Streams::ReadableStream> Blob::stream(JS::Object const& relevant_global_object)
+bool Blob::is_file() const
{
- // The stream() method, when invoked, must return the result of calling get stream on this.
- return get_stream(HTML::relevant_realm(relevant_global_object));
+ return web_blob_is_file(const_cast<Blob*>(this));
}
// https://w3c.github.io/FileAPI/#blob-get-stream
-GC::Ref<Streams::ReadableStream> Blob::get_stream(JS::Realm& realm)
+static GC::Ref<Streams::ReadableStream> get_stream(JS::Realm& realm, ReadonlyBytes blob_bytes)
{
// 1. Let stream be a new ReadableStream created in blob’s relevant Realm.
auto stream = GC::Heap::the().allocate<Streams::ReadableStream>();
@@ -363,7 +133,7 @@ GC::Ref<Streams::ReadableStream> Blob::get_stream(JS::Realm& realm)
// NOTE: for simplicity the chunk is the entire buffer for now.
{
// 1. Let bytes be the byte sequence that results from reading a chunk from blob, or failure if a chunk cannot be read.
- auto bytes = MUST(ByteBuffer::copy(raw_bytes()));
+ auto bytes = MUST(ByteBuffer::copy(blob_bytes));
// 2. Queue a global task on the file reading task source given blob’s relevant global object to perform the following steps:
HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, stream, bytes = move(bytes)]() {
@@ -396,23 +166,38 @@ GC::Ref<Streams::ReadableStream> Blob::get_stream(JS::Realm& realm)
return stream;
}
-static GC::Ref<WebIDL::Promise> read_all_blob_bytes(JS::Realm& realm, Blob& blob)
+GC::Ref<Streams::ReadableStream> Blob::get_stream(JS::Realm& realm) const
{
- auto stream = blob.get_stream(realm);
+ return FileAPI::get_stream(realm, raw_bytes());
+}
+
+static GC::Ref<WebIDL::Promise> read_all_blob_bytes(JS::Realm& realm, ReadonlyBytes blob_bytes)
+{
+ auto stream = get_stream(realm, blob_bytes);
auto reader_or_exception = stream->get_a_reader();
if (reader_or_exception.is_exception())
return WebIDL::create_rejected_promise_from_exception(realm, reader_or_exception.release_error());
return reader_or_exception.release_value()->read_all_bytes_deprecated();
}
+// https://w3c.github.io/FileAPI/#dom-blob-stream
+JSObject* web_blob_get_stream(void* realm, ReadonlyBytes blob_bytes)
+{
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+
+ // The stream() method, when invoked, must return the result of calling get stream on this.
+ auto stream = get_stream(js_realm, blob_bytes);
+ return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, stream).ptr());
+}
+
// https://w3c.github.io/FileAPI/#dom-blob-text
-GC::Ref<WebIDL::Promise> Blob::text(JS::Object const& relevant_global_object)
+JSObject* web_blob_text(void* realm, ReadonlyBytes blob_bytes)
{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto& vm = realm.vm();
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ auto& vm = js_realm.vm();
- auto promise = read_all_blob_bytes(realm, *this);
- return WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&vm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
+ auto promise = read_all_blob_bytes(js_realm, blob_bytes);
+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&vm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
auto const& object = first_argument.as_object();
VERIFY(is<JS::ArrayBuffer>(object));
auto const& array_buffer = static_cast<JS::ArrayBuffer const&>(object);
@@ -420,33 +205,52 @@ GC::Ref<WebIDL::Promise> Blob::text(JS::Object const& relevant_global_object)
auto text = TRY_OR_THROW_OOM(vm, TextCodec::utf8_decode_to_utf16(ReadonlyBytes { array_buffer.data_at(0), array_buffer.byte_length() }));
return JS::PrimitiveString::create(vm, move(text));
}));
+ return JS::HostABI::object_to_abi(promise->promise().ptr());
}
// https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
-GC::Ref<WebIDL::Promise> Blob::array_buffer(JS::Object const& relevant_global_object)
+JSObject* web_blob_array_buffer(void* realm, ReadonlyBytes blob_bytes)
{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto promise = read_all_blob_bytes(realm, *this);
- return WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+
+ auto promise = read_all_blob_bytes(js_realm, blob_bytes);
+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&js_realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
auto const& object = first_argument.as_object();
VERIFY(is<JS::ArrayBuffer>(object));
auto const& array_buffer = static_cast<JS::ArrayBuffer const&>(object);
- return JS::ArrayBuffer::create(realm, MUST(ByteBuffer::copy(ReadonlyBytes { array_buffer.data_at(0), array_buffer.byte_length() })));
+ return JS::ArrayBuffer::create(js_realm, MUST(ByteBuffer::copy(ReadonlyBytes { array_buffer.data_at(0), array_buffer.byte_length() })));
}));
+ return JS::HostABI::object_to_abi(promise->promise().ptr());
}
// https://w3c.github.io/FileAPI/#dom-blob-bytes
-GC::Ref<WebIDL::Promise> Blob::bytes(JS::Object const& relevant_global_object)
+JSObject* web_blob_bytes(void* realm, ReadonlyBytes blob_bytes)
{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto promise = read_all_blob_bytes(realm, *this);
- return WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+
+ auto promise = read_all_blob_bytes(js_realm, blob_bytes);
+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&js_realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {
auto& object = first_argument.as_object();
VERIFY(is<JS::ArrayBuffer>(object));
auto& array_buffer = static_cast<JS::ArrayBuffer&>(object);
- return JS::Uint8Array::create(realm, array_buffer.byte_length(), array_buffer);
+ return JS::Uint8Array::create(js_realm, array_buffer.byte_length(), array_buffer);
}));
+ return JS::HostABI::object_to_abi(promise->promise().ptr());
+}
+
+void web_blob_bytes_destroy(BlobBytes* bytes)
+{
+ delete bytes;
+}
+
+JSCompletion web_blob_deserialize_byte_sequence(Bindings::RustSerializationReader* reader, BlobBytesABI* out_bytes)
+{
+ auto bytes = HTML::decode_or_throw_data_clone_error<ByteBuffer>(reader->realm, reader->serialized);
+ if (bytes.is_exception())
+ return Bindings::completion_to_abi(reader->realm, bytes.exception());
+ *out_bytes = hand_over(bytes.release_value());
+ return Bindings::completion_to_abi(reader->realm, JS::js_undefined());
}
}
diff --git a/Libraries/LibWeb/FileAPI/Blob.h b/Libraries/LibWeb/FileAPI/Blob.h
index 959b8ab98b6..c4a4468ee71 100644
--- a/Libraries/LibWeb/FileAPI/Blob.h
+++ b/Libraries/LibWeb/FileAPI/Blob.h
@@ -6,77 +6,49 @@
#pragma once
-#include <AK/NonnullRefPtr.h>
+#include <AK/ByteBuffer.h>
#include <AK/Utf16String.h>
-#include <AK/Vector.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibWeb/Bindings/Blob.h>
-#include <LibWeb/Bindings/Serializable.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::FileAPI {
-using BlobPart = FlattenVariant<WebIDL::BufferSourceVariant, Variant<GC::Ref<Blob>, Utf16String>>;
-using BlobParts = GC::ConservativeVector<BlobPart>;
-using BlobPartsOrByteBuffer = Variant<BlobParts, ByteBuffer>;
-using EndingType = Bindings::EndingType;
-using BlobPropertyBag = Bindings::BlobPropertyBag;
-
-[[nodiscard]] ErrorOr<Utf16String> convert_line_endings_to_native(Utf16View string);
-[[nodiscard]] ErrorOr<ByteBuffer> process_blob_parts(BlobParts const& blob_parts, Optional<BlobPropertyBag> const& options = {});
-[[nodiscard]] bool is_basic_latin(Utf16View view);
-
-class WEB_API Blob
- : public Bindings::GCAllocatedWrappable
- , public Bindings::Serializable {
- WEB_WRAPPABLE(Blob, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Blob);
+// https://w3c.github.io/FileAPI/#blob-section
+// The C++ side of a Blob, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/file_api): what C++ creates
+// and reads. A Blob that C++ holds can be a File.
+class WEB_API Blob : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Blob, blob)
public:
- virtual ~Blob() override;
-
[[nodiscard]] static GC::Ref<Blob> create(ByteBuffer, Utf16String type);
- [[nodiscard]] static GC::Ref<Blob> create(ByteBuffer bytes, String type) { return create(move(bytes), Utf16String::from_utf8(type)); }
+ [[nodiscard]] static GC::Ref<Blob> create(ByteBuffer bytes, String const& type) { return create(move(bytes), Utf16String::from_utf8(type)); }
[[nodiscard]] static GC::Ref<Blob> create(Core::AnonymousBuffer, Utf16String type);
- [[nodiscard]] static GC::Ref<Blob> create(Optional<BlobPartsOrByteBuffer> const& blob_parts_or_byte_buffer = {}, Optional<BlobPropertyBag> const& options = {});
- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<Blob>> construct_impl(Optional<BlobParts> const& blob_parts, Optional<BlobPropertyBag> const& options);
// https://w3c.github.io/FileAPI/#dfn-size
u64 size() const { return raw_bytes().size(); }
// https://w3c.github.io/FileAPI/#dfn-type
- Utf16String const& type() const { return m_type; }
+ Utf16String type() const;
- WebIDL::ExceptionOr<GC::Ref<Blob>> slice(Optional<i64> start = {}, Optional<i64> end = {}, Optional<Utf16String> const& content_type = {});
- ErrorOr<GC::Ref<Blob>> slice_blob(Optional<i64> start = {}, Optional<i64> end = {}, Optional<Utf16String> const& content_type = {});
-
- GC::Ref<Streams::ReadableStream> stream(JS::Object const& relevant_global_object);
- GC::Ref<WebIDL::Promise> text(JS::Object const& relevant_global_object);
- GC::Ref<WebIDL::Promise> array_buffer(JS::Object const& relevant_global_object);
- GC::Ref<WebIDL::Promise> bytes(JS::Object const& relevant_global_object);
ReadonlyBytes raw_bytes() const LIFETIME_BOUND;
ErrorOr<Core::AnonymousBuffer> shared_bytes();
- GC::Ref<Streams::ReadableStream> get_stream(JS::Realm&);
-
- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;
- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;
+ // https://w3c.github.io/FileAPI/#slice-blob
+ GC::Ref<Blob> slice_blob(Optional<i64> start, Optional<i64> end, Optional<Utf16String> content_type) const;
-protected:
- Blob(ByteBuffer, Utf16String type);
- Blob(Core::AnonymousBuffer, Utf16String type);
- Blob(ByteBuffer);
+ GC::Ref<Streams::ReadableStream> get_stream(JS::Realm&) const;
- // https://w3c.github.io/FileAPI/#dfn-byte-sequence
- // NB: The bytes move to shared memory the first time they are shared, and stay there.
- Variant<ByteBuffer, Core::AnonymousBuffer> m_byte_sequence { ByteBuffer {} };
- Utf16String m_type {};
+ template<typename T>
+ bool fast_is() const
+ requires(IsSame<T, File>)
+ {
+ return is_file();
+ }
private:
- Blob();
+ bool is_file() const;
};
}
diff --git a/Libraries/LibWeb/FileAPI/Blob.idl b/Libraries/LibWeb/FileAPI/Blob.idl
index 2f6388266d4..2540c51cc6d 100644
--- a/Libraries/LibWeb/FileAPI/Blob.idl
+++ b/Libraries/LibWeb/FileAPI/Blob.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/FileAPI/#blob-section
-[Exposed=(Window,Worker), Serializable]
+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]
interface Blob {
constructor(optional sequence<BlobPart> blobParts, optional BlobPropertyBag options = {});
diff --git a/Libraries/LibWeb/FileAPI/File.cpp b/Libraries/LibWeb/FileAPI/File.cpp
index acaf9aa5041..facc1c74152 100644
--- a/Libraries/LibWeb/FileAPI/File.cpp
+++ b/Libraries/LibWeb/FileAPI/File.cpp
@@ -4,129 +4,34 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Time.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Completion.h>
-#include <LibJS/Runtime/Realm.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/FileAPI/File.h>
-#include <LibWeb/HTML/StructuredSerialize.h>
-#include <LibWebCommon/Infra/Strings.h>
-#include <LibWebCommon/MimeSniff/MimeType.h>
namespace Web::FileAPI {
-GC_DEFINE_ALLOCATOR(File);
+extern "C" {
-File::File(ByteBuffer byte_buffer, Utf16String file_name, Utf16String type, i64 last_modified)
- : Blob(move(byte_buffer), move(type))
- , m_name(move(file_name))
- , m_last_modified(last_modified)
-{
-}
-
-File::File()
- : Blob(ByteBuffer {})
-{
-}
-
-File::~File() = default;
-
-GC::Ref<File> File::create()
-{
- return GC::Heap::the().allocate<File>();
+// Defined in Bindings/Rust/src/file_api/exports.rs.
+void* web_file_create(JSVM*, ReadonlyBytes, FlatPtr file_name, FlatPtr type, bool has_last_modified, i64 last_modified);
+FlatPtr web_file_name(void* file);
+i64 web_file_last_modified(void* file);
}
-// https://w3c.github.io/FileAPI/#ref-for-dom-file-file
-ErrorOr<GC::Ref<File>> File::create(BlobParts const& file_bits, Utf16String const& file_name, Optional<FilePropertyBag> const& options)
+GC::Ref<File> File::create(ReadonlyBytes bytes, Utf16String file_name, Utf16String type, Optional<i64> last_modified)
{
- // 1. Let bytes be the result of processing blob parts given fileBits and options.
- Optional<BlobPropertyBag> blob_options;
- if (options.has_value()) {
- blob_options = BlobPropertyBag {
- .endings = options->endings,
- .type = options->type,
- };
- }
- auto bytes = TRY(process_blob_parts(file_bits, blob_options));
-
- // 2. Let n be the fileName argument to the constructor.
- // NOTE: Underlying OS filesystems use differing conventions for file name; with constructed files, mandating UTF-16 lessens ambiquity when file names are converted to byte sequences.
- auto name = file_name;
-
- auto type = Utf16String {};
- i64 last_modified = 0;
- // 3. Process FilePropertyBag dictionary argument by running the following substeps:
- if (options.has_value()) {
- // FIXME: 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
- // If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps.
- // FIXME: 2. Convert every character in t to ASCII lowercase.
-
- // NOTE: The spec is out of date, and we are supposed to call into the MimeType parser here.
- if (is_basic_latin(options->type.utf16_view())) {
- auto maybe_parsed_type = Web::MimeSniff::MimeType::parse(options->type.utf16_view());
-
- if (maybe_parsed_type.has_value())
- type = maybe_parsed_type->serialized_as_utf16();
- }
-
- // 3. If the lastModified member is provided, let d be set to the lastModified dictionary member. If it is not provided, set d to the current date and time represented as the number of milliseconds since the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- // Note: Since ECMA-262 Date objects convert to long long values representing the number of milliseconds since the Unix Epoch, the lastModified member could be a Date object [ECMA-262].
- last_modified = options->last_modified.has_value() ? options->last_modified.value() : UnixDateTime::now().milliseconds_since_epoch();
- }
-
- // 4. Return a new File object F such that:
- // 2. F refers to the bytes byte sequence.
- // NOTE: Spec started at 2 therefore keeping the same number sequence here.
- // 3. F.size is set to the number of total bytes in bytes.
- // 4. F.name is set to n.
- // 5. F.type is set to t.
- // 6. F.lastModified is set to d.
- return GC::Heap::the().allocate<File>(move(bytes), move(name), move(type), last_modified);
+ auto* file = web_file_create(JS::HostABI::vm_to_abi(JS::VM::the()), bytes, move(file_name).into_raw(), move(type).into_raw(), last_modified.has_value(), last_modified.value_or(0));
+ return GC::Ref { *static_cast<File*>(file) };
}
-WebIDL::ExceptionOr<GC::Ref<File>> File::construct_impl(BlobParts const& file_bits, Utf16String const& file_name, Optional<FilePropertyBag> const& options)
+Utf16String File::name() const
{
- return TRY_OR_THROW_OOM(JS::VM::the(), create(file_bits, file_name, options));
+ return Utf16String::from_raw(web_file_name(const_cast<File*>(this)));
}
-WebIDL::ExceptionOr<void> File::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)
+i64 File::last_modified() const
{
- // FIXME: 1. Set serialized.[[SnapshotState]] to value’s snapshot state.
-
- // NON-STANDARD: FileAPI spec doesn't specify that type should be serialized, although
- // to be conformant with other browsers this needs to be serialized.
- serialized.encode(m_type);
-
- // 2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
- serialized.encode(raw_bytes());
-
- // 3. Set serialized.[[Name]] to the value of value’s name attribute.
- serialized.encode(m_name);
-
- // 4. Set serialized.[[LastModified]] to the value of value’s lastModified attribute.
- serialized.encode(m_last_modified);
-
- return {};
-}
-
-WebIDL::ExceptionOr<void> File::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)
-{
- // FIXME: 1. Set value’s snapshot state to serialized.[[SnapshotState]].
-
- // NON-STANDARD: FileAPI spec doesn't specify that type should be deserialized, although
- // to be conformant with other browsers this needs to be deserialized.
- m_type = TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized));
-
- // 2. Set value’s underlying byte sequence to serialized.[[ByteSequence]].
- m_byte_sequence = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized));
-
- // 3. Initialize the value of value’s name attribute to serialized.[[Name]].
- m_name = TRY(HTML::decode_or_throw_data_clone_error<Utf16String>(realm, serialized));
-
- // 4. Initialize the value of value’s lastModified attribute to serialized.[[LastModified]].
- m_last_modified = TRY(HTML::decode_or_throw_data_clone_error<i64>(realm, serialized));
-
- return {};
+ return web_file_last_modified(const_cast<File*>(this));
}
}
diff --git a/Libraries/LibWeb/FileAPI/File.h b/Libraries/LibWeb/FileAPI/File.h
index cb9683743d7..551dfa5b993 100644
--- a/Libraries/LibWeb/FileAPI/File.h
+++ b/Libraries/LibWeb/FileAPI/File.h
@@ -11,34 +11,21 @@
namespace Web::FileAPI {
-using FilePropertyBag = Bindings::FilePropertyBag;
-
+// https://w3c.github.io/FileAPI/#file-section
+// The C++ side of a File, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/file_api): what C++ creates
+// and reads.
class WEB_API File : public Blob {
- WEB_WRAPPABLE(File, Blob);
- GC_DECLARE_ALLOCATOR(File);
+ WEB_RUST_INTERFACE(File, file)
public:
- static GC::Ref<File> create();
- static ErrorOr<GC::Ref<File>> create(BlobParts const& file_bits, Utf16String const& file_name, Optional<FilePropertyBag> const& options = {});
- static ErrorOr<GC::Ref<File>> create(BlobParts const& file_bits, String const& file_name, Optional<FilePropertyBag> const& options = {}) { return create(file_bits, Utf16String::from_utf8(file_name), options); }
- static WebIDL::ExceptionOr<GC::Ref<File>> construct_impl(BlobParts const& file_bits, Utf16String const& file_name, Optional<FilePropertyBag> const& options);
-
- virtual ~File() override;
+ // https://w3c.github.io/FileAPI/#ref-for-dom-file-file, given the bytes as the one part of fileBits, and options
+ // with the type and, if it has a value, the last modified date.
+ static GC::Ref<File> create(ReadonlyBytes, Utf16String file_name, Utf16String type, Optional<i64> last_modified = {});
// https://w3c.github.io/FileAPI/#dfn-name
- Utf16String const& name() const { return m_name; }
+ Utf16String name() const;
// https://w3c.github.io/FileAPI/#dfn-lastModified
- i64 last_modified() const { return m_last_modified; }
-
- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;
- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;
-
-private:
- File(ByteBuffer, Utf16String file_name, Utf16String type, i64 last_modified);
- File();
-
- Utf16String m_name;
- i64 m_last_modified { 0 };
+ i64 last_modified() const;
};
}
diff --git a/Libraries/LibWeb/FileAPI/File.idl b/Libraries/LibWeb/FileAPI/File.idl
index d60d2f786c7..0e414bd0070 100644
--- a/Libraries/LibWeb/FileAPI/File.idl
+++ b/Libraries/LibWeb/FileAPI/File.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/FileAPI/#file-section
-[Exposed=(Window,Worker), Serializable]
+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]
interface File : Blob {
constructor(sequence<BlobPart> fileBits, USVString fileName, optional FilePropertyBag options = {});
diff --git a/Libraries/LibWeb/FileAPI/FileList.cpp b/Libraries/LibWeb/FileAPI/FileList.cpp
index 167f84c2c2b..03ee8b0c501 100644
--- a/Libraries/LibWeb/FileAPI/FileList.cpp
+++ b/Libraries/LibWeb/FileAPI/FileList.cpp
@@ -5,6 +5,7 @@
*/
#include <LibGC/Heap.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/FileAPI/FileList.h>
#include <LibWeb/HTML/StructuredSerialize.h>
@@ -40,7 +41,8 @@ WebIDL::ExceptionOr<void> FileList::serialization_steps(HTML::StructuredSerializ
serialized.encode(Bindings::InterfaceName::File);
if (serialized.type() == HTML::SerializationType::Storage)
serialized.encode(u64 { 1 });
- TRY(file->serialization_steps(serialized, for_storage, memory));
+ auto serializable = Bindings::SerializablePlatformObject { .rust_object = file, .interface_name = Bindings::InterfaceName::File, .realm = JS::VM::the().current_realm() };
+ TRY(serializable.serialization_steps(serialized, for_storage, memory));
}
return {};
@@ -61,9 +63,8 @@ WebIDL::ExceptionOr<void> FileList::deserialization_steps(JS::Realm& realm, HTML
if (version != 1)
return WebIDL::DataCloneError::create("Unsupported FileList entry version"_utf16);
}
- auto file = File::create();
- TRY(file->deserialization_steps(realm, serialized, memory));
- m_files.append(file);
+ auto wrapper = TRY(Bindings::deserialize_rust_platform_object(Bindings::InterfaceName::File, realm, serialized, memory));
+ m_files.append(*Bindings::impl_from<File>(wrapper.ptr()));
}
return {};
diff --git a/Libraries/LibWeb/FileAPI/FileList.h b/Libraries/LibWeb/FileAPI/FileList.h
index 42c2a289b87..4c4651273c8 100644
--- a/Libraries/LibWeb/FileAPI/FileList.h
+++ b/Libraries/LibWeb/FileAPI/FileList.h
@@ -9,6 +9,7 @@
#include <AK/Vector.h>
#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/Serializable.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Export.h>
#include <LibWeb/FileAPI/File.h>
diff --git a/Libraries/LibWeb/HTML/DataTransfer.cpp b/Libraries/LibWeb/HTML/DataTransfer.cpp
index a0e21508c60..5326a4e9f47 100644
--- a/Libraries/LibWeb/HTML/DataTransfer.cpp
+++ b/Libraries/LibWeb/HTML/DataTransfer.cpp
@@ -300,18 +300,8 @@ GC::Ref<FileAPI::FileList> DataTransfer::files() const
if (item.kind != DragDataStoreItem::Kind::File)
continue;
- auto blob = FileAPI::Blob::create(MUST(ByteBuffer::copy(item.file_data)), item.type_string.to_utf16_string());
-
- // File names are UTF-16 at the DOM boundary. The File API still has a
- // legacy byte-string constructor, so perform this conversion only at
- // that API boundary.
- auto file_name = item.file_name.to_utf8();
-
// FIXME: Fill in other fields (e.g. last_modified).
- FileAPI::FilePropertyBag options {};
- options.type = item.type_string.to_utf16_string();
-
- auto file = MUST(FileAPI::File::create({ { blob } }, file_name, move(options)));
+ auto file = FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string());
files->add_file(file);
}
diff --git a/Libraries/LibWeb/HTML/DataTransferItem.cpp b/Libraries/LibWeb/HTML/DataTransferItem.cpp
index 8a359da41e7..f4090379495 100644
--- a/Libraries/LibWeb/HTML/DataTransferItem.cpp
+++ b/Libraries/LibWeb/HTML/DataTransferItem.cpp
@@ -134,17 +134,8 @@ GC::Ptr<FileAPI::File> DataTransferItem::get_as_file() const
return nullptr;
// 3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.
- auto blob = FileAPI::Blob::create(MUST(ByteBuffer::copy(item.file_data)), item.type_string.to_utf16_string());
-
- auto file_name = item.file_name.to_utf8();
-
// FIXME: Fill in other fields (e.g. last_modified).
- FileAPI::FilePropertyBag options {};
- options.type = item.type_string.to_utf16_string();
-
- FileAPI::BlobParts file_bits {};
- file_bits.append(blob);
- return MUST(FileAPI::File::create(file_bits, file_name, move(options)));
+ return FileAPI::File::create(item.file_data, item.file_name, item.type_string.to_utf16_string());
}
// https://wicg.github.io/entries-api/#dom-datatransferitem-webkitgetasentry
diff --git a/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp b/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
index 9312eb9cf31..baf79cd6a60 100644
--- a/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
+++ b/Libraries/LibWeb/HTML/FormControlInfrastructure.cpp
@@ -31,22 +31,13 @@ static WebIDL::ExceptionOr<XHR::FormDataEntry> create_entry_with_scalar_name(JS:
[&](GC::Ref<FileAPI::Blob> blob) -> WebIDL::ExceptionOr<XHR::FormDataEntry::Value> {
// 1. If value is not a File object, then set value to a new File object, representing the same bytes, whose
// name attribute value is "blob".
- if (!is<FileAPI::File>(*blob)) {
- FileAPI::FilePropertyBag options {};
- options.type = blob->type();
-
- blob = TRY(FileAPI::File::construct_impl({ { blob } }, "blob"_utf16, move(options)));
- }
+ if (!is<FileAPI::File>(*blob))
+ blob = FileAPI::File::create(blob->raw_bytes(), "blob"_utf16, blob->type());
// 2. If filename is given, then set value to a new File object, representing the same bytes, whose name
// attribute is filename.
- if (filename.has_value()) {
- FileAPI::FilePropertyBag options {};
- options.type = blob->type();
- options.last_modified = as<FileAPI::File>(*blob).last_modified();
-
- blob = TRY(FileAPI::File::construct_impl({ { blob } }, filename.value(), move(options)));
- }
+ if (filename.has_value())
+ blob = FileAPI::File::create(blob->raw_bytes(), filename.value(), blob->type(), as<FileAPI::File>(*blob).last_modified());
return GC::Ref { as<FileAPI::File>(*blob) };
}));
@@ -211,9 +202,7 @@ WebIDL::ExceptionOr<Optional<GC::ConservativeVector<XHR::FormDataEntry>>> constr
else if (auto* file_element = as_if<HTMLInputElement>(*control); file_element && file_element->type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
// 1. If there are no selected files, then create an entry with name and a new File object with an empty name, application/octet-stream as type, and an empty body, and append it to entry list.
if (file_element->files()->length() == 0) {
- Bindings::FilePropertyBag options {};
- options.type = "application/octet-stream"_utf16;
- auto file = TRY(FileAPI::File::construct_impl({}, Utf16String {}, options));
+ auto file = FileAPI::File::create({}, {}, "application/octet-stream"_utf16);
entry_list.append(TRY(create_entry(realm, name.view(), Variant<GC::Ref<FileAPI::Blob>, Utf16String> { GC::Ref<FileAPI::Blob> { file } })));
}
// 2. Otherwise, for each file in selected files, create an entry with name and a File object representing the file, and append it to entry list.
@@ -339,7 +328,8 @@ ErrorOr<SerializedFormData> serialize_to_multipart_form_data(GC::ConservativeVec
TRY(entry.value.visit(
[&](GC::Ref<FileAPI::File> file) -> ErrorOr<void> {
// For filenames replace any 0x0A (LF) bytes with the byte sequence `%0A`, 0x0D (CR) with `%0D` and 0x22 (") with `%22`
- auto escaped_filename = TRY(escape_line_feed_carriage_return_double_quote(file->name().utf16_view()));
+ auto file_name = file->name();
+ auto escaped_filename = TRY(escape_line_feed_carriage_return_double_quote(file_name.utf16_view()));
auto escaped_filename_utf8 = TRY(escaped_filename.utf16_view().to_utf8());
// Add a `Content-Disposition` header with a `name` set to entry's name and `filename` set to entry's filename.
TRY(builder.try_append(TRY(String::formatted("Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n", escaped_name_utf8, escaped_filename_utf8))));
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index 10f576868d1..a0f921ff7ce 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -631,16 +631,12 @@ void HTMLInputElement::did_select_files(Span<SelectedFile> selected_files, Multi
auto contents = selected_file.take_contents();
auto mime_type = MimeSniff::Resource::sniff(contents);
- auto blob = FileAPI::Blob::create(move(contents), mime_type.essence());
// FIXME: The FileAPI should use ByteString for file names.
auto file_name = selected_file.name();
// FIXME: Fill in other fields (e.g. last_modified).
- FileAPI::FilePropertyBag options {};
- options.type = Utf16String::from_ascii_without_validation(mime_type.essence().bytes());
-
- auto file = MUST(FileAPI::File::create({ { blob } }, file_name, move(options)));
+ auto file = FileAPI::File::create(contents, file_name, Utf16String::from_ascii_without_validation(mime_type.essence().bytes()));
files->add_file(file);
}
diff --git a/Libraries/LibWebCommon/Rust/Cargo.toml b/Libraries/LibWebCommon/Rust/Cargo.toml
index 5c4ba6fb552..e34b92e57bc 100644
--- a/Libraries/LibWebCommon/Rust/Cargo.toml
+++ b/Libraries/LibWebCommon/Rust/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[lib]
-crate-type = ["staticlib"]
+crate-type = ["rlib", "staticlib"]
[dependencies]
ak = { path = "../../../AK/Rust" }
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 81fb700589c..9ebec065aa5 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -48,7 +48,7 @@ ALLOWED_REALM_MENTIONS = {
62,
"Fetch bodies, headers, requests, responses, and controllers still materialize JS values/streams; the body receiver's delivery and close tasks carry the realm its stream is enqueued and closed in",
),
- "FileAPI": (6, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),
+ "FileAPI": (4, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),
"HTML": (
64,
200,
diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
index d4657a40fb3..2fdb4d92a61 100644
--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
@@ -962,7 +962,7 @@ TEST_CASE(file_api_serializables_encode_to_frozen_bytes)
expect_storage_encoding(blob, serializable_storage_record("Blob"sv, 1, body));
}
- auto file = MUST(Web::FileAPI::File::create({ { "data"_utf16 } }, "f.txt"_utf16));
+ auto file = Web::FileAPI::File::create("data"sv.bytes(), "f.txt"_utf16, {});
{
Vector<u8> body;
append_storage_string(body, ""sv); // default type