Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
perf(fetch): share immutable request bodies with Bytes
ldm0d75c82c30a7a
diff --git a/Cargo.lock b/Cargo.lockindex a45559008..529eae40b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2723,6 +2723,7 @@ name = "moli-core"version = "0.1.0"dependencies = ["anyhow",+ "bytes","moli-browser-profile","moli-cookie-jar","moli-dom",@@ -2847,6 +2848,7 @@ name = "moli-fetch"version = "0.1.0"dependencies = ["anyhow",+ "bytes","cidr","crossbeam-channel","curl",@@ -3080,6 +3082,7 @@ name = "moli-page-types"version = "0.1.0"dependencies = ["bitflags",+ "bytes","http-auth","moli-browser-profile","moli-cookie-jar",@@ -3150,6 +3153,7 @@ dependencies = ["anyhow","axum","base64 0.22.1",+ "bytes","chromiumoxide_cdp","data-url","futures-util",@@ -3246,6 +3250,7 @@ name = "moli-protocol-webdriver-bidi"version = "0.1.0"dependencies = ["base64 0.22.1",+ "bytes","moli-header-field","moli-protocol","serde_json",@@ -3269,6 +3274,7 @@ dependencies = ["app_units","base64 0.22.1","brotlic",+ "bytes","crossbeam-channel","cssparser","curl",diff --git a/moli-core/Cargo.toml b/moli-core/Cargo.tomlindex 18f0629fb..0cfeaca1f 100644--- a/moli-core/Cargo.toml+++ b/moli-core/Cargo.toml@@ -15,6 +15,7 @@ wpt-extensions = ["moli-renderer-v8/wpt-extensions"][dependencies]anyhow = "1.0.100"+bytes = "1"moli-browser-profile = { path = "../moli-browser-profile" }moli-dom = { path = "../moli-dom" }moli-parser = { path = "../moli-parser" }diff --git a/moli-core/src/page/subresource_support.rs b/moli-core/src/page/subresource_support.rsindex 7e1cfc3f6..13114354c 100644--- a/moli-core/src/page/subresource_support.rs+++ b/moli-core/src/page/subresource_support.rs@@ -29,7 +29,7 @@ impl Page {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,@@ -51,7 +51,7 @@ impl Page {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,diff --git a/moli-core/src/runtime/navigation_engine.rs b/moli-core/src/runtime/navigation_engine.rsindex 96ebf1ea4..d4e20f7dc 100644--- a/moli-core/src/runtime/navigation_engine.rs+++ b/moli-core/src/runtime/navigation_engine.rs@@ -1043,7 +1043,7 @@ impl NavigationEngine {request_origin: Option<moli_url::WebOrigin>,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,auth: Option<SubresourceAuthCredentials>,) -> Result<NetworkFetchResult<NavigationResponse>> {@@ -1108,7 +1108,7 @@ impl NavigationEngine {request_origin,method,raw_url,- body.map(String::into_bytes),+ body.map(bytes::Bytes::from),request_headers,auth,)@@ -1125,7 +1125,7 @@ impl NavigationEngine {request_origin: Option<moli_url::WebOrigin>,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,auth: Option<SubresourceAuthCredentials>,cancel_handle: FetchCancelHandle,@@ -1212,7 +1212,7 @@ impl NavigationEngine {request_origin,method,raw_url,- body.map(String::into_bytes),+ body.map(bytes::Bytes::from),request_headers,auth,FetchCancelHandle::new(),@@ -1231,7 +1231,7 @@ impl NavigationEngine {request_origin: Option<moli_url::WebOrigin>,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,auth: Option<SubresourceAuthCredentials>,cancel_handle: FetchCancelHandle,diff --git a/moli-fetch/Cargo.toml b/moli-fetch/Cargo.tomlindex a048d1918..d441c8ca6 100644--- a/moli-fetch/Cargo.toml+++ b/moli-fetch/Cargo.toml@@ -11,6 +11,7 @@ test-support = ["moli-cookie-jar/test-support"][dependencies]moli-header-field = { path = "../moli-header-field" }anyhow = "1.0.100"+bytes = "1"cidr = "0.3.2"crossbeam-channel = "0.5.15"curl = { version = "0.4.51", default-features = false, features = ["brotli", "http2", "poll_7_68_0", "ssl", "static-curl"] }diff --git a/moli-fetch/src/network_fetch_result.rs b/moli-fetch/src/network_fetch_result.rsindex dd09d8b1f..30e962853 100644--- a/moli-fetch/src/network_fetch_result.rs+++ b/moli-fetch/src/network_fetch_result.rs@@ -384,7 +384,7 @@ pub struct NetworkFetchFailureContext {pub struct NetworkFetchFailureRequestContext {current_url: Url,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: crate::RequestHeaders,redirect_chain: Vec<RedirectInfo>,}@@ -393,7 +393,7 @@ impl NetworkFetchFailureRequestContext {pub(crate) fn new(current_url: Url,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: crate::RequestHeaders,redirect_chain: Vec<RedirectInfo>,) -> Self {@@ -414,8 +414,8 @@ impl NetworkFetchFailureRequestContext {&self.request_method}- pub fn request_body(&self) -> Option<&[u8]> {- self.request_body.as_deref()+ pub fn request_body(&self) -> Option<&bytes::Bytes> {+ self.request_body.as_ref()}pub fn request_headers(&self) -> &crate::RequestHeaders {@@ -684,7 +684,7 @@ mod tests {request_context: Some(NetworkFetchFailureRequestContext::new(Url::parse("https://example.test/").expect("test URL should parse"),"POST".to_owned(),- Some(b"secret request body".to_vec()),+ Some(bytes::Bytes::from_static(b"secret request body")),vec![("Authorization".to_owned(), "secret token".to_owned())].into(),Vec::new(),)),diff --git a/moli-fetch/src/request.rs b/moli-fetch/src/request.rsindex 8d7b0d671..73ac00b15 100644--- a/moli-fetch/src/request.rs+++ b/moli-fetch/src/request.rs@@ -28,7 +28,8 @@ enum RequestContext {pub struct Request {pub url: Url,pub method: String,- pub body: Option<Vec<u8>>,+ /// Immutable upload bytes, shared when a request is cloned or redirected.+ pub body: Option<bytes::Bytes>,/// Wire bytes, with the source encoding resolved before header merging.pub request_headers: crate::RequestHeaders,redirect_headers: Option<crate::RequestHeaders>,@@ -542,7 +543,7 @@ impl Request {Self::new_bytes(method,raw_url,- body.map(String::into_bytes),+ body.map(bytes::Bytes::from),request_headers,)}@@ -552,7 +553,7 @@ impl Request {pub fn new_bytes(method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: impl Into<crate::RequestHeaders>,) -> Result<Self> {let url = Url::parse(raw_url)@@ -563,7 +564,7 @@ impl Request {fn new_http_with_url(method: &str,url: Url,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: impl Into<crate::RequestHeaders>,) -> Self {Self {@@ -887,7 +888,7 @@ impl Request {pub fn new_browser_bytes(method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: impl Into<crate::RequestHeaders>,origin: WebOrigin,) -> Result<Self> {@@ -897,7 +898,7 @@ impl Request {pub fn new_browser(method: &str,url: Url,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: impl Into<crate::RequestHeaders>,origin: WebOrigin,) -> Self {diff --git a/moli-fetch/src/tests/mod.rs b/moli-fetch/src/tests/mod.rsindex 06fd5de68..12225957e 100644--- a/moli-fetch/src/tests/mod.rs+++ b/moli-fetch/src/tests/mod.rs@@ -306,6 +306,36 @@ async fn http_transport_rejects_file_urls_in_every_response_mode() -> Result<()>Ok(())}+#[test]+fn cloned_requests_and_preserving_redirects_share_upload_storage() -> Result<()> {+ let upload = vec![0, 255, 195, 40, 128, 65];+ let original_storage = upload.as_ptr().wrapping_add(1);+ let body = bytes::Bytes::from(upload).slice(1..5);+ let request = Request::new_bytes(+ "POST",+ "https://example.test/upload",+ Some(body.clone()),+ Vec::new(),+ )?;++ for status in [307, 308] {+ let mut redirected = request.clone();+ redirected.apply_redirect_status(status);+ let retained = redirected.body.as_ref().unwrap();+ assert_eq!(retained.as_ptr(), original_storage);+ assert_eq!(retained, &body);+ assert_eq!(redirected.method, "POST");+ }++ let mut rewritten = request.clone();+ rewritten.apply_redirect_status(303);+ assert_eq!(rewritten.method, "GET");+ assert!(rewritten.body.is_none());+ assert_eq!(request.body.as_ref().unwrap().as_ptr(), original_storage);+ assert_eq!(request.body.as_ref().unwrap(), &body);+ Ok(())+}+#[test]fn request_apply_redirect_status_rewrites_post_to_get_and_drops_body_headers() {let mut request = Request::new(@@ -1711,7 +1741,11 @@ async fn request_headers_distinguish_empty_values_from_absent_upload_content_typfor method in ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "YO",] {- for body in [None, Some(Vec::new()), Some(b"payload".to_vec())] {+ for body in [+ None,+ Some(bytes::Bytes::new()),+ Some(bytes::Bytes::from_static(b"payload")),+ ] {if matches!(method, "GET" | "HEAD") && body.is_some() {continue;}@@ -1781,7 +1815,7 @@ async fn request_headers_distinguish_empty_values_from_absent_upload_content_typcontent_type.iter().copied().collect::<Vec<_>>(),"{case:?}: {request}");- if body.as_ref().is_none_or(Vec::is_empty) {+ if body.as_ref().is_none_or(bytes::Bytes::is_empty) {let expected_length = if body.is_some() || matches!(*method, "POST" | "PUT") {vec!["0"]} else {diff --git a/moli-page-types/Cargo.toml b/moli-page-types/Cargo.tomlindex e233bc27a..2eaca49ba 100644--- a/moli-page-types/Cargo.toml+++ b/moli-page-types/Cargo.toml@@ -9,6 +9,7 @@ test-support = ["moli-disk-pool/test-support"][dependencies]bitflags = "2.11.0"+bytes = "1"moli-browser-profile = { path = "../moli-browser-profile" }moli-cookie-jar = { path = "../moli-cookie-jar" }moli-dom = { path = "../moli-dom" }diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rsindex 3964c5304..150af3a7b 100644--- a/moli-page-types/src/lib.rs+++ b/moli-page-types/src/lib.rs@@ -1094,7 +1094,7 @@ struct SubresourceNetworkRecordInner {method: String,request_headers: moli_fetch::RequestHeaders,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,request_initiator_type: SubresourceRequestInitiatorType,request_cookie_report: Option<StoredCookieQueryReport>,@@ -1127,7 +1127,7 @@ pub struct SubresourceRequestStarted {method: String,request_headers: moli_fetch::RequestHeaders,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,keepalive: bool,resource_type: SubresourceResourceType,request_initiator_type: SubresourceRequestInitiatorType,@@ -1240,7 +1240,7 @@ impl SubresourceRequestStarted {self.handle}- pub fn with_request_body_bytes(mut self, request_body_bytes: Option<Vec<u8>>) -> Self {+ pub fn with_request_body_bytes(mut self, request_body_bytes: Option<bytes::Bytes>) -> Self {self.request_body_bytes =request_body_bytes.or_else(|| request_body_text_bytes(&self.request_body));self@@ -1275,8 +1275,8 @@ impl SubresourceRequestStarted {self.request_body.as_deref()}- pub fn request_body_bytes(&self) -> Option<&[u8]> {- self.request_body_bytes.as_deref()+ pub fn request_body_bytes(&self) -> Option<&bytes::Bytes> {+ self.request_body_bytes.as_ref()}pub fn keepalive(&self) -> bool {@@ -2258,7 +2258,7 @@ impl SubresourceNetworkRecord {self}- pub fn with_request_body_bytes(mut self, request_body_bytes: Option<Vec<u8>>) -> Self {+ pub fn with_request_body_bytes(mut self, request_body_bytes: Option<bytes::Bytes>) -> Self {let inner = Arc::make_mut(&mut self.inner);inner.request_body_bytes =request_body_bytes.or_else(|| request_body_text_bytes(&inner.request_body));@@ -2337,8 +2337,8 @@ impl SubresourceNetworkRecord {self.inner.request_body.as_deref()}- pub fn request_body_bytes(&self) -> Option<&[u8]> {- self.inner.request_body_bytes.as_deref()+ pub fn request_body_bytes(&self) -> Option<&bytes::Bytes> {+ self.inner.request_body_bytes.as_ref()}pub fn resource_type(&self) -> SubresourceResourceType {@@ -2394,8 +2394,10 @@ impl SubresourceNetworkRecord {}}-fn request_body_text_bytes(request_body: &Option<String>) -> Option<Vec<u8>> {- request_body.as_ref().map(|body| body.as_bytes().to_vec())+fn request_body_text_bytes(request_body: &Option<String>) -> Option<bytes::Bytes> {+ request_body+ .as_ref()+ .map(|body| bytes::Bytes::copy_from_slice(body.as_bytes()))}#[derive(Debug, Clone, PartialEq, Eq)]@@ -2409,7 +2411,7 @@ pub struct PendingSubresourceFetchInfo {pub method: String,pub request_headers: moli_fetch::RequestHeaders,pub request_body: Option<String>,- pub request_body_bytes: Option<Vec<u8>>,+ pub request_body_bytes: Option<bytes::Bytes>,pub resource_type: SubresourceResourceType,pub request_cookie_report: Option<StoredCookieQueryReport>,}diff --git a/moli-page-types/src/renderer_transport_memory.rs b/moli-page-types/src/renderer_transport_memory.rsindex 8b0fb0a02..b3b98acef 100644--- a/moli-page-types/src/renderer_transport_memory.rs+++ b/moli-page-types/src/renderer_transport_memory.rs@@ -4,6 +4,8 @@//! definitions, where private capacities and disk-backed response state are//! visible. They do not model serialized CDP JSON; protocol projection has not//! happened while these values are queued.+//! Shared upload buffers are charged by their visible byte length per item,+//! even when multiple queued items retain the same backing storage.use super::*;@@ -155,7 +157,7 @@ impl PendingSubresourceFetchInfo {.saturating_add(self.request_body_bytes.as_ref()- .map(Vec::capacity)+ .map(bytes::Bytes::len).unwrap_or(0),)}@@ -285,7 +287,7 @@ fn request_started_charge(request: &SubresourceRequestStarted) -> usize {request.request_body_bytes.as_ref()- .map(Vec::capacity)+ .map(bytes::Bytes::len).unwrap_or(0),)}@@ -336,7 +338,7 @@ fn network_record_charge(record: &SubresourceNetworkRecord) -> usize {record.request_body_bytes.as_ref()- .map(Vec::capacity)+ .map(bytes::Bytes::len).unwrap_or(0),).saturating_add(record.cookie_set_reports.len().saturating_mul(256))diff --git a/moli-protocol-webdriver-bidi/Cargo.toml b/moli-protocol-webdriver-bidi/Cargo.tomlindex ae5ba0ac1..97f703c0b 100644--- a/moli-protocol-webdriver-bidi/Cargo.toml+++ b/moli-protocol-webdriver-bidi/Cargo.toml@@ -6,6 +6,7 @@ edition = "2024"[dependencies]base64 = "0.22"+bytes = "1"moli-header-field = { path = "../moli-header-field" }moli-protocol = { path = "../moli-protocol" }serde_json = "1.0.145"diff --git a/moli-protocol-webdriver-bidi/src/commands.rs b/moli-protocol-webdriver-bidi/src/commands.rsindex e6232901b..c979089aa 100644--- a/moli-protocol-webdriver-bidi/src/commands.rs+++ b/moli-protocol-webdriver-bidi/src/commands.rs@@ -1024,7 +1024,7 @@ fn bidi_network_continue_request_command(request_id: DevToolsRequestId::from(request),url: optional_string(&command.params, "url")?.map(str::to_owned),method: optional_string(&command.params, "method")?.map(str::to_owned),- post_data: optional_network_bytes_string(&command.params, "body")?,+ post_data: optional_network_bytes(&command.params, "body")?.map(bytes::Bytes::from),headers,intercept_response: optional_bool(&command.params, "interceptResponse")?.unwrap_or(false),})@@ -1172,13 +1172,6 @@ fn optional_network_status_code(params: &Value) -> Result<Option<u16>, BidiErrorOk(Some(code as u16))}-fn optional_network_bytes_string(params: &Value, field: &str) -> Result<Option<String>, BidiError> {- params- .get(field)- .map(|value| required_network_bytes_value(value, field))- .transpose()-}-fn optional_network_bytes(params: &Value, field: &str) -> Result<Option<Vec<u8>>, BidiError> {params.get(field)diff --git a/moli-protocol-webdriver-bidi/src/tests/session_and_network_commands.rs b/moli-protocol-webdriver-bidi/src/tests/session_and_network_commands.rsindex dd85efd55..09b059fcf 100644--- a/moli-protocol-webdriver-bidi/src/tests/session_and_network_commands.rs+++ b/moli-protocol-webdriver-bidi/src/tests/session_and_network_commands.rs@@ -709,7 +709,7 @@ fn maps_network_continue_request_to_shared_fetch_command() {assert_eq!(command.request_id.as_str(), "REQ-7");assert_eq!(command.url.as_deref(), Some("https://example.test/next"));assert_eq!(command.method.as_deref(), Some("POST"));- assert_eq!(command.post_data.as_deref(), Some("payload"));+ assert_eq!(command.post_data.as_deref(), Some(b"payload".as_slice()));assert!(command.intercept_response);assert_eq!(command.headers.map(|headers| headers.to_byte_strings()),@@ -2033,3 +2033,27 @@ fn maps_browsing_context_get_tree_root_to_shared_get_frame_tree_command() {Some("TARGET-1"));}++#[test]+fn network_continue_request_preserves_non_utf8_base64_body() {+ let command = super::super::parse_bidi_command(json!({+ "id": 7,+ "method": "network.continueRequest",+ "params": {+ "request": "REQ-7",+ "body": {"type": "base64", "value": "AP7AgEFC"}+ }+ }))+ .expect("BiDi command");+ let context = super::super::BidiDevToolsCommandContext::new("bidi-session-1");+ let shared = super::super::automation_command_from_bidi_command(&command, &context)+ .expect("binary body must not require UTF-8");+ let moli_protocol::automation::AutomationCommand::ContinueInterceptedRequest(command) = shared+ else {+ panic!("expected ContinueInterceptedRequest command");+ };+ assert_eq!(+ command.post_data.as_deref(),+ Some([0, 254, 192, 128, 65, 66].as_slice())+ );+}diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.tomlindex 4dfed44b5..13cfb110d 100644--- a/moli-protocol/Cargo.toml+++ b/moli-protocol/Cargo.toml@@ -11,6 +11,7 @@ test-support = [][dependencies]anyhow = "1.0.100"base64 = "0.22"+bytes = "1"indexmap = "2.14.2"moli-bounded-buffer = { path = "../moli-bounded-buffer" }moli-core = { path = "../moli-core" }diff --git a/moli-protocol/src/automation.rs b/moli-protocol/src/automation.rsindex 907e6ebc2..4d9bd2df1 100644--- a/moli-protocol/src/automation.rs+++ b/moli-protocol/src/automation.rs@@ -1342,7 +1342,8 @@ pub struct DevToolsContinueInterceptedRequestCommand {pub request_id: DevToolsRequestId,pub url: Option<String>,pub method: Option<String>,- pub post_data: Option<String>,+ /// No replacement when absent; an empty buffer explicitly clears the upload.+ pub post_data: Option<bytes::Bytes>,pub headers: Option<moli_fetch::RequestHeaders>,pub intercept_response: bool,}diff --git a/moli-protocol/src/conn/body_spool.rs b/moli-protocol/src/conn/body_spool.rsindex 66435726c..00d9243fb 100644--- a/moli-protocol/src/conn/body_spool.rs+++ b/moli-protocol/src/conn/body_spool.rs@@ -26,7 +26,7 @@ pub struct CapturedBody {#[derive(Debug)]enum CapturedBodyInner {- Memory(Vec<u8>),+ Memory(bytes::Bytes),SharedMemory(Arc<[u8]>),File { path: PathBuf, len: usize },Subresource(moli_core::page::SubresourceResponseBody),@@ -45,9 +45,9 @@ impl CapturedBody {Self::from_bytes(body.into_bytes())}- pub(crate) fn from_bytes(body: Vec<u8>) -> Self {+ pub(crate) fn from_bytes(body: impl Into<bytes::Bytes>) -> Self {Self {- inner: Arc::new(CapturedBodyInner::Memory(body)),+ inner: Arc::new(CapturedBodyInner::Memory(body.into())),}}@@ -100,7 +100,7 @@ impl CapturedBody {pub(crate) fn materialize_bytes(&self) -> Result<Vec<u8>> {match self.inner.as_ref() {- CapturedBodyInner::Memory(bytes) => Ok(bytes.clone()),+ CapturedBodyInner::Memory(bytes) => Ok(bytes.to_vec()),CapturedBodyInner::SharedMemory(bytes) => Ok(bytes.to_vec()),CapturedBodyInner::File { path, .. } => {let mut file = File::open(path).with_context(|| {@@ -445,6 +445,20 @@ fn configure_secure_spool_file_options(_options: &mut OpenOptions) {}mod tests {use super::*;+ #[test]+ fn captured_upload_shares_storage_with_transport_bytes() -> Result<()> {+ let upload = bytes::Bytes::from(vec![0, 255, 195, 40, 128, 65]);+ let original_storage = upload.as_ptr();+ let body = CapturedBody::from_bytes(upload.clone());+ let CapturedBodyInner::Memory(captured) = body.inner.as_ref() else {+ panic!("captured upload must retain its shared bytes");+ };+ assert_eq!(captured.as_ptr(), original_storage);+ drop(upload);+ assert_eq!(body.materialize_bytes()?, [0, 255, 195, 40, 128, 65]);+ Ok(())+ }+#[test]fn captured_body_writer_keeps_small_body_in_memory() -> Result<()> {let mut writer = CapturedBodyWriter::new(16);diff --git a/moli-protocol/src/conn/fetch_support.rs b/moli-protocol/src/conn/fetch_support.rsindex 4c87fb06b..102973c21 100644--- a/moli-protocol/src/conn/fetch_support.rs+++ b/moli-protocol/src/conn/fetch_support.rs@@ -1480,7 +1480,7 @@ impl PendingSubresourceFetchRequest {&mut self,url: Option<Url>,method: Option<String>,- body: Option<String>,+ body: Option<bytes::Bytes>,headers: Option<moli_fetch::RequestHeaderOverride>,) {let Some(chain) = self.request_stage_chain.as_mut() else {@@ -1493,8 +1493,8 @@ impl PendingSubresourceFetchRequest {chain.method = method;}if let Some(body) = body {- chain.body = Some(body);- chain.body_overridden = true;+ chain.body = Some(String::from_utf8_lossy(&body).into_owned());+ chain.body_override = Some(body);}if let Some(headers) = headers {chain.headers = headers.headers().clone();@@ -1508,7 +1508,7 @@ impl PendingSubresourceFetchRequest {) -> (Option<Url>,Option<String>,- Option<Option<String>>,+ Option<Option<bytes::Bytes>>,Option<moli_fetch::RequestHeaderOverride>,) {let Some(chain) = self.request_stage_chain.as_ref() else {@@ -1517,7 +1517,7 @@ impl PendingSubresourceFetchRequest {(Some(chain.url.clone()),Some(chain.method.clone()),- chain.body_overridden.then(|| chain.body.clone()),+ chain.body_override.clone().map(Some),chain.header_override.clone(),)}@@ -1541,8 +1541,8 @@ pub struct PendingSubresourceFetchRequestStageChain {pub method: String,pub headers: moli_fetch::RequestHeaders,pub body: Option<String>,- /// A display snapshot is not an override of the renderer's binary body.- pub body_overridden: bool,+ /// None preserves the renderer's upload; Some(empty) explicitly clears it.+ pub body_override: Option<bytes::Bytes>,pub request_cookie_report: Option<StoredCookieQueryReport>,pub remaining_sessions: Vec<PendingSubresourceFetchRequestStage>,}@@ -1707,7 +1707,7 @@ impl CdpConnection {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaders>,intercept_response: bool,handle_auth_requests: bool,@@ -1731,7 +1731,7 @@ impl CdpConnection {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaders>,intercept_response: bool,handle_auth_requests: bool,@@ -1756,7 +1756,7 @@ impl CdpConnection {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaders>,intercept_response: bool,handle_auth_requests: bool,diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rsindex 0de1687c9..e70e53abb 100644--- a/moli-protocol/src/conn/runtime_load.rs+++ b/moli-protocol/src/conn/runtime_load.rs@@ -809,7 +809,7 @@ pub(crate) struct BackgroundNavigationLoadJob {load_inputs: TargetNavigationLoadInputs,method: String,raw_url: String,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,body_progress_source: MainDocumentBodyProgressSource,/// Browser-context transport/cache state shared with the resident engine.@@ -2356,7 +2356,7 @@ impl CdpConnection {load_inputs,method,raw_url,- body.map(String::into_bytes),+ body.map(bytes::Bytes::from),request_headers,body_progress_source,)@@ -2417,7 +2417,7 @@ impl CdpConnection {load_inputs: TargetNavigationLoadInputs,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,body_progress_source: MainDocumentBodyProgressSource,) -> anyhow::Result<NavigationLoadOutcome> {@@ -3192,7 +3192,7 @@ impl CdpConnection {&load_inputs,method,raw_url,- body.map(String::into_bytes),+ body.map(bytes::Bytes::from),request_headers,auth,)@@ -3221,7 +3221,7 @@ impl CdpConnection {load_inputs: &TargetNavigationLoadInputs,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,auth: Option<SubresourceAuthCredentials>,) -> anyhow::Result<NetworkFetchResult<StreamingRawResponse>> {@@ -3899,7 +3899,7 @@ fn build_navigation_network_request(load_inputs: &TargetNavigationLoadInputs,method: &str,raw_url: &str,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,request_headers: moli_fetch::RequestHeaders,auth: Option<SubresourceAuthCredentials>,) -> anyhow::Result<Request> {diff --git a/moli-protocol/src/conn/state/fetch.rs b/moli-protocol/src/conn/state/fetch.rsindex 271c70d11..8896cfa10 100644--- a/moli-protocol/src/conn/state/fetch.rs+++ b/moli-protocol/src/conn/state/fetch.rs@@ -2476,7 +2476,7 @@ mod tests {method: "GET".to_owned(),headers: Vec::new().into(),body: None,- body_overridden: false,+ body_override: None,request_cookie_report: None,remaining_sessions: vec![PendingSubresourceFetchRequestStage {@@ -2648,7 +2648,7 @@ mod tests {method: "GET".to_owned(),headers: Vec::new().into(),body: None,- body_overridden: false,+ body_override: None,request_cookie_report: None,remaining_sessions: vec![PendingSubresourceFetchRequestStage {diff --git a/moli-protocol/src/conn/state/navigation_outcome.rs b/moli-protocol/src/conn/state/navigation_outcome.rsindex 4fcf2c79c..1fa97da34 100644--- a/moli-protocol/src/conn/state/navigation_outcome.rs+++ b/moli-protocol/src/conn/state/navigation_outcome.rs@@ -358,7 +358,7 @@ pub struct NavigationDispatchState {pub request_body: Option<String>,/// Authoritative bytes used for transport. This differs from the text/// projection for multipart form data containing binary file payloads.- pub request_body_bytes: Option<Vec<u8>>,+ pub request_body_bytes: Option<bytes::Bytes>,pub request_headers: moli_fetch::RequestHeaders,pub request_load_policy: NavigationRequestLoadPolicy,pub timestamp: f64,@@ -366,15 +366,15 @@ pub struct NavigationDispatchState {}impl NavigationDispatchState {- pub(crate) fn clone_request_body_bytes(&self) -> Option<Vec<u8>> {+ pub(crate) fn clone_request_body_bytes(&self) -> Option<bytes::Bytes> {self.request_body_bytes.clone()- .or_else(|| self.request_body.clone().map(String::into_bytes))+ .or_else(|| self.request_body.clone().map(bytes::Bytes::from))}- pub(crate) fn set_request_body_text(&mut self, body: String) {- self.request_body_bytes = Some(body.as_bytes().to_vec());- self.request_body = Some(body);+ pub(crate) fn set_request_body_bytes(&mut self, body: bytes::Bytes) {+ self.request_body = Some(String::from_utf8_lossy(&body).into_owned());+ self.request_body_bytes = Some(body);}}diff --git a/moli-protocol/src/conn/state/runtime_slot.rs b/moli-protocol/src/conn/state/runtime_slot.rsindex 174b09c91..29bd0dd60 100644--- a/moli-protocol/src/conn/state/runtime_slot.rs+++ b/moli-protocol/src/conn/state/runtime_slot.rs@@ -1136,7 +1136,7 @@ impl TargetRuntimeSlot {pub(crate) fn record_captured_request_body_with_collector_scope(&mut self,request_id: String,- request_body: Vec<u8>,+ request_body: bytes::Bytes,session_ids: impl IntoIterator<Item = Option<String>>,collector_ids: impl IntoIterator<Item = String>,collection_was_gated: bool,diff --git a/moli-protocol/src/domains/fetch/commands.rs b/moli-protocol/src/domains/fetch/commands.rsindex 3edc2bf9d..e0625f0ce 100644--- a/moli-protocol/src/domains/fetch/commands.rs+++ b/moli-protocol/src/domains/fetch/commands.rs@@ -18,8 +18,7 @@ use moli_url_policy::BrowserUrlScheme;use url::Url;use super::helpers::{- decode_base64_bytes, decode_base64_to_string, response_headers_from_params,- response_headers_with_presence_from_params,+ decode_base64_bytes, response_headers_from_params, response_headers_with_presence_from_params,};use super::navigation::{complete_tokened_materialized_navigation_as_background_events_async,@@ -166,8 +165,8 @@ fn build_cdp_continue_intercepted_request_command(parse_continue_request_url(url)?;}let decoded_post_data = match params.post_data.as_ref().map(AsRef::as_ref) {- Some(post_data) => match decode_base64_to_string(post_data) {- Ok(body) => Some(body),+ Some(post_data) => match decode_base64_bytes(post_data) {+ Ok(body) => Some(bytes::Bytes::from(body)),Err(()) => return Err(()),},None => None,@@ -378,7 +377,7 @@ fn start_devtools_continue_intercepted_request_command(pending.navigation.request_method = method;}if let Some(body) = command.post_data.clone() {- pending.navigation.set_request_body_text(body);+ pending.navigation.set_request_body_bytes(body);}if let Some(headers) = command.headers.clone() {if command.context.protocol == FrontendProtocol::Cdp {@@ -1983,7 +1982,7 @@ mod protocol_neutral_tests {assert_eq!(command.request_id.as_str(), "interception-job-0");assert_eq!(command.url.as_deref(), Some("https://example.test/next"));assert_eq!(command.method.as_deref(), Some("POST"));- assert_eq!(command.post_data.as_deref(), Some("hello"));+ assert_eq!(command.post_data.as_deref(), Some(b"hello".as_slice()));assert_eq!(command.headers.map(|headers| headers.to_byte_strings()),Some(vec![("x-test".to_owned(), "1".to_owned())])@@ -2103,7 +2102,7 @@ mod protocol_neutral_tests {method: "GET".to_owned(),headers: vec![("x-old".to_owned(), "1".to_owned())].into(),body: None,- body_overridden: false,+ body_override: None,request_cookie_report: None,remaining_sessions: vec![PendingSubresourceFetchRequestStage {session_id: Some("SID-attached".to_owned()),@@ -2142,6 +2141,8 @@ mod protocol_neutral_tests {let command = build_cdp_continue_intercepted_request_command(&conn, &cmd, params).expect("continueRequest command should normalize");+ let upload_storage = command.post_data.as_ref().unwrap().as_ptr();+let step = start_devtools_fetch_command(&mut conn,cmd.id,@@ -2208,7 +2209,11 @@ mod protocol_neutral_tests {Some("https://example.test/rewritten"));assert_eq!(method.as_deref(), Some("POST"));- assert_eq!(body, Some(Some("body".to_owned())));+ assert_eq!(body, Some(Some(bytes::Bytes::from_static(b"body"))));+ assert_eq!(+ body.as_ref().unwrap().as_ref().unwrap().as_ptr(),+ upload_storage+ );assert_eq!(headers.map(|headers| headers.headers().to_byte_strings()),Some(vec![("x-new".to_owned(), "2".to_owned())])@@ -2388,7 +2393,7 @@ mod protocol_neutral_tests {method: "GET".to_owned(),headers: Vec::new().into(),body: None,- body_overridden: false,+ body_override: None,request_cookie_report: None,remaining_sessions: vec![PendingSubresourceFetchRequestStage {session_id: Some("BIDI-SID".to_owned()),diff --git a/moli-protocol/src/domains/fetch/helpers.rs b/moli-protocol/src/domains/fetch/helpers.rsindex 58d6bbe25..bb1f1af1e 100644--- a/moli-protocol/src/domains/fetch/helpers.rs+++ b/moli-protocol/src/domains/fetch/helpers.rs@@ -22,11 +22,6 @@ use url::Url;use super::params::HeaderEntry;-pub(crate) fn decode_base64_to_string(body: &str) -> Result<String, ()> {- let decoded = decode_base64_bytes(body)?;- String::from_utf8(decoded).map_err(|_| ())-}-// CDP Unicode input uses UTF-8; binary input remains raw HTTP bytes.pub(super) fn response_headers_from_params(response_headers: Option<Vec<HeaderEntry>>,diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rsindex 4cb8e95e8..866bf228c 100644--- a/moli-protocol/src/domains/fetch/subresource.rs+++ b/moli-protocol/src/domains/fetch/subresource.rs@@ -319,7 +319,7 @@ async fn prepare_subresource_fetch_pause_sources_async(method: info.method.clone(),headers: info.request_headers.clone(),body: info.request_body.clone(),- body_overridden: false,+ body_override: None,request_cookie_report: info.request_cookie_report.clone(),remaining_sessions,}));diff --git a/moli-protocol/src/domains/fetch/tests/basics.rs b/moli-protocol/src/domains/fetch/tests/basics.rsindex cd60be335..4762b6eea 100644--- a/moli-protocol/src/domains/fetch/tests/basics.rs+++ b/moli-protocol/src/domains/fetch/tests/basics.rs@@ -1082,7 +1082,7 @@ async fn disable_clears_fetch_state() {requested_url: Url::parse("http://example.test/auth").unwrap(),request_method: "POST".to_owned(),request_body: Some("payload".to_owned()),- request_body_bytes: Some(b"payload".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from_static(b"payload")),request_headers: vec![("x-auth".to_owned(), "1".to_owned())].into(),request_load_policy: crate::conn::NavigationRequestLoadPolicy::DocumentInitiated,timestamp: 0.0,@@ -1129,7 +1129,7 @@ async fn disable_clears_fetch_state() {requested_url: Url::parse("http://example.test/auth").unwrap(),request_method: "POST".to_owned(),request_body: Some("payload".to_owned()),- request_body_bytes: Some(b"payload".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from_static(b"payload")),request_headers: vec![("x-auth".to_owned(), "1".to_owned())].into(),request_load_policy:crate::conn::NavigationRequestLoadPolicy::DocumentInitiated,@@ -1621,7 +1621,7 @@ fn emit_auth_required_preserves_request_headers_and_post_data_shape() {requested_url: Url::parse("http://example.test/auth").unwrap(),request_method: "POST".to_owned(),request_body: Some("payload".to_owned()),- request_body_bytes: Some(b"payload".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from_static(b"payload")),request_headers: vec![("x-test".to_owned(), "yes".to_owned())].into(),request_load_policy: crate::conn::NavigationRequestLoadPolicy::DocumentInitiated,timestamp: 0.0,diff --git a/moli-protocol/src/domains/fetch/tests/binary_request.rs b/moli-protocol/src/domains/fetch/tests/binary_request.rsindex e4582234e..34ce45a99 100644--- a/moli-protocol/src/domains/fetch/tests/binary_request.rs+++ b/moli-protocol/src/domains/fetch/tests/binary_request.rs@@ -13,7 +13,7 @@ async fn binary_request_round_trip(scope: RequestScope,xhr: bool,chained: bool,- replacement: Option<&str>,+ replacement: Option<&[u8]>,inspect_paused_body: bool,) {let (sender, mut received) = tokio::sync::mpsc::unbounded_channel();@@ -169,7 +169,7 @@ async fn binary_request_round_trip(let actual = received.try_recv().expect("server must have consumed the body before completion");- let expected = replacement.map(str::as_bytes).unwrap_or(BODY);+ let expected = replacement.unwrap_or(BODY);assert_eq!(actual, expected,"Fetch.continueRequest must preserve the original bytes unless overridden"@@ -191,15 +191,18 @@ async fn binary_request_round_trip("params":{"requestId":network_id}}),).await;- let body = replacement.map_or_else(|| BASE64_STANDARD.encode(BODY), str::to_owned);- if replacement == Some("") {+ let (body, base64_encoded) = match std::str::from_utf8(expected) {+ Ok(body) => (body.to_owned(), false),+ Err(_) => (BASE64_STANDARD.encode(expected), true),+ };+ if expected.is_empty() {// Keep the existing Network API contract for an empty upload; the// server and JavaScript assertions above still require zero bytes.ctx.expect_error(id, -32000, "No post data available for the request");} else {ctx.expect_result(id,- json!({"postData":body,"base64Encoded":replacement.is_none()}),+ json!({"postData":body,"base64Encoded":base64_encoded}),Some("SID-1"),);}@@ -227,7 +230,7 @@ async fn chained_fetch_text_override_replaces_binary_request_body() {RequestScope::Window,false,true,- Some("replacement"),+ Some(b"replacement"),false,).await;@@ -260,12 +263,12 @@ async fn chained_worker_xhr_noop_preserves_binary_request_body() {#[tokio::test(flavor = "multi_thread")]async fn chained_worker_fetch_empty_override_replaces_binary_request_body() {- binary_request_round_trip(RequestScope::Worker, false, true, Some(""), false).await;+ binary_request_round_trip(RequestScope::Worker, false, true, Some(b""), false).await;}#[tokio::test(flavor = "multi_thread")]async fn chained_worker_xhr_empty_override_replaces_binary_request_body() {- binary_request_round_trip(RequestScope::Worker, true, true, Some(""), false).await;+ binary_request_round_trip(RequestScope::Worker, true, true, Some(b""), false).await;}#[tokio::test(flavor = "multi_thread")]@@ -274,7 +277,7 @@ async fn chained_worker_fetch_text_override_replaces_binary_request_body() {RequestScope::Worker,false,true,- Some("replacement"),+ Some(b"replacement"),false,).await;@@ -282,7 +285,14 @@ async fn chained_worker_fetch_text_override_replaces_binary_request_body() {#[tokio::test(flavor = "multi_thread")]async fn chained_worker_xhr_text_override_replaces_binary_request_body() {- binary_request_round_trip(RequestScope::Worker, true, true, Some("replacement"), false).await;+ binary_request_round_trip(+ RequestScope::Worker,+ true,+ true,+ Some(b"replacement"),+ false,+ )+ .await;}#[tokio::test(flavor = "multi_thread")]@@ -304,3 +314,75 @@ async fn shared_worker_fetch_noop_preserves_binary_request_body() {async fn shared_worker_xhr_noop_preserves_binary_request_body() {binary_request_round_trip(RequestScope::SharedWorker, true, false, None, false).await;}++#[tokio::test(flavor = "multi_thread")]+async fn chained_fetch_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::Window,+ false,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn chained_xhr_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::Window,+ true,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn chained_worker_fetch_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::Worker,+ false,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn chained_worker_xhr_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::Worker,+ true,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn chained_shared_worker_fetch_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::SharedWorker,+ false,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}++#[tokio::test(flavor = "multi_thread")]+async fn chained_shared_worker_xhr_binary_override_preserves_bytes() {+ binary_request_round_trip(+ RequestScope::SharedWorker,+ true,+ true,+ Some(&[0, 254, 192, 128, 65, 66]),+ false,+ )+ .await;+}diff --git a/moli-protocol/src/domains/network/agent.rs b/moli-protocol/src/domains/network/agent.rsindex 8f0538755..93273d176 100644--- a/moli-protocol/src/domains/network/agent.rs+++ b/moli-protocol/src/domains/network/agent.rs@@ -621,7 +621,7 @@ impl TargetNetworkAgentState {pub(crate) fn record_captured_request_body_with_collector_scope(&mut self,request_id: String,- request_body: Vec<u8>,+ request_body: bytes::Bytes,session_ids: impl IntoIterator<Item = Option<String>>,collector_ids: impl IntoIterator<Item = String>,collection_was_gated: bool,@@ -1228,7 +1228,7 @@ pub(crate) struct CapturedRequestBody {impl CapturedRequestBody {pub(crate) fn new_with_collector_scope(- body: Vec<u8>,+ body: bytes::Bytes,session_ids: impl IntoIterator<Item = Option<String>>,collector_ids: impl IntoIterator<Item = String>,collection_was_gated: bool,@@ -1297,7 +1297,7 @@ impl CapturedRequestBodyStore {pub(crate) fn insert_with_collector_scope(&mut self,request_id: String,- body: Vec<u8>,+ body: bytes::Bytes,session_ids: impl IntoIterator<Item = Option<String>>,collector_ids: impl IntoIterator<Item = String>,collection_was_gated: bool,@@ -1671,7 +1671,7 @@ impl TargetNetworkBodyArtifacts {pub(crate) fn insert_request_body_with_collector_scope(&mut self,request_id: String,- request_body: Vec<u8>,+ request_body: bytes::Bytes,session_ids: impl IntoIterator<Item = Option<String>>,collector_ids: impl IntoIterator<Item = String>,collection_was_gated: bool,diff --git a/moli-protocol/src/domains/network/backlog.rs b/moli-protocol/src/domains/network/backlog.rsindex 5b717c5fb..09e7a0d81 100644--- a/moli-protocol/src/domains/network/backlog.rs+++ b/moli-protocol/src/domains/network/backlog.rs@@ -864,7 +864,7 @@ pub(crate) fn record_subresource_request_body(conn: &mut CdpConnection,owner: &CommandOwnerScope,request_id: &str,- request_body: Option<&[u8]>,+ request_body: Option<&bytes::Bytes>,session_ids: &[Option<String>],) {let Some(request_body) = request_body else {@@ -877,7 +877,7 @@ pub(crate) fn record_subresource_request_body(conn.record_collected_network_data_body(request_id.to_owned(),data_type,- crate::conn::CapturedBody::from_bytes(request_body.to_vec()),+ crate::conn::CapturedBody::from_bytes(request_body.clone()),collector_ids.iter().cloned(),collection_was_gated,);@@ -886,7 +886,7 @@ pub(crate) fn record_subresource_request_body(};runtime_slot.record_captured_request_body_with_collector_scope(request_id.to_owned(),- request_body.to_vec(),+ request_body.clone(),session_ids.to_vec(),collector_ids,collection_was_gated,diff --git a/moli-protocol/src/domains/network/events.rs b/moli-protocol/src/domains/network/events.rsindex df313f66a..fb72137a6 100644--- a/moli-protocol/src/domains/network/events.rs+++ b/moli-protocol/src/domains/network/events.rs@@ -1360,7 +1360,7 @@ mod tests {method: "POST".to_owned(),request_headers: vec![("x-test".to_owned(), "1".to_owned())].into(),request_body: Some("body".to_owned()),- request_body_bytes: Some(b"body".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from_static(b"body")),resource_type: SubresourceResourceType::Fetch,request_cookie_report: None,};diff --git a/moli-protocol/src/domains/network/main_document_progress/mod.rs b/moli-protocol/src/domains/network/main_document_progress/mod.rsindex 3d477b71d..d363091d2 100644--- a/moli-protocol/src/domains/network/main_document_progress/mod.rs+++ b/moli-protocol/src/domains/network/main_document_progress/mod.rs@@ -2371,7 +2371,7 @@ pub(crate) fn record_main_document_request_body(.unwrap_or_else(|| String::from_utf8_lossy(&transport_bytes).into_owned());runtime_slot.record_captured_request_body_with_collector_scope(request_id,- cdp_request_body.into_bytes(),+ cdp_request_body.into(),session_ids.iter().cloned(),collector_ids,collection_was_gated,diff --git a/moli-protocol/src/domains/network/output.rs b/moli-protocol/src/domains/network/output.rsindex ddb87b47f..4d085dc70 100644--- a/moli-protocol/src/domains/network/output.rs+++ b/moli-protocol/src/domains/network/output.rs@@ -67,7 +67,7 @@ pub(crate) struct TargetSubresourceFetchPauseNetworkOutput {method: String,request_headers: Vec<(String, String)>,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,request_cookie_report: Option<StoredCookieQueryReport>,blocked_intercepts: Vec<DevToolsNetworkInterceptId>,@@ -151,8 +151,8 @@ impl TargetSubresourceFetchPauseNetworkOutput {self.request_body.as_deref()}- pub(crate) fn request_body_bytes(&self) -> Option<&[u8]> {- self.request_body_bytes.as_deref()+ pub(crate) fn request_body_bytes(&self) -> Option<&bytes::Bytes> {+ self.request_body_bytes.as_ref()}pub(crate) fn resource_type(&self) -> SubresourceResourceType {@@ -193,7 +193,7 @@ mod tests {method: "POST".to_owned(),request_headers: vec![("content-type".to_owned(), "text/plain".to_owned())].into(),request_body: Some("payload".to_owned()),- request_body_bytes: Some(b"payload".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from(b"payload".to_vec())),resource_type: SubresourceResourceType::Fetch,request_cookie_report: None,}@@ -230,6 +230,11 @@ mod tests {&[("content-type".to_owned(), "text/plain".to_owned())]);assert_eq!(output.request_body(), Some("payload"));+ assert_eq!(+ output.request_body_bytes().unwrap().as_ptr(),+ info.request_body_bytes.as_ref().unwrap().as_ptr(),+ "the pause output must share the original upload allocation"+ );assert_eq!(output.resource_type(), SubresourceResourceType::Fetch);assert!(output.request_cookie_report().is_none());}diff --git a/moli-protocol/src/domains/network/output_queue.rs b/moli-protocol/src/domains/network/output_queue.rsindex 90e6199a4..7ef965a86 100644--- a/moli-protocol/src/domains/network/output_queue.rs+++ b/moli-protocol/src/domains/network/output_queue.rs@@ -1373,7 +1373,7 @@ pub(crate) struct TargetSubresourceRequestStartedOutput {method: String,request_headers: Vec<(String, String)>,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,request_initiator_type: SubresourceRequestInitiatorType,request_cookie_report: Option<StoredCookieQueryReport>,@@ -1397,7 +1397,7 @@ impl TargetSubresourceRequestStartedOutput {method: request.method().to_owned(),request_headers: request.request_headers().to_byte_strings(),request_body: request.request_body().map(str::to_owned),- request_body_bytes: request.request_body_bytes().map(<[u8]>::to_vec),+ request_body_bytes: request.request_body_bytes().cloned(),resource_type: request.resource_type(),request_initiator_type: request.request_initiator_type(),request_cookie_report: request.request_cookie_report().cloned(),@@ -1444,8 +1444,8 @@ impl TargetSubresourceRequestStartedOutput {self.request_body.as_deref()}- pub(crate) fn request_body_bytes(&self) -> Option<&[u8]> {- self.request_body_bytes.as_deref()+ pub(crate) fn request_body_bytes(&self) -> Option<&bytes::Bytes> {+ self.request_body_bytes.as_ref()}pub(crate) fn resource_type(&self) -> SubresourceResourceType {@@ -1759,7 +1759,7 @@ pub(crate) struct TargetSubresourceMetadataOutput {method: String,request_headers: Vec<(String, String)>,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,request_initiator_type: SubresourceRequestInitiatorType,request_cookie_report: Option<StoredCookieQueryReport>,@@ -1790,7 +1790,7 @@ impl TargetSubresourceMetadataOutput {method: record.method().to_owned(),request_headers: record.request_headers().to_byte_strings(),request_body: record.request_body().map(str::to_owned),- request_body_bytes: record.request_body_bytes().map(|body| body.to_vec()),+ request_body_bytes: record.request_body_bytes().cloned(),resource_type: record.resource_type(),request_initiator_type: record.request_initiator_type(),request_cookie_report: record.request_cookie_report().cloned(),@@ -1852,8 +1852,8 @@ impl TargetSubresourceMetadataOutput {self.request_body.as_deref()}- pub(crate) fn request_body_bytes(&self) -> Option<&[u8]> {- self.request_body_bytes.as_deref()+ pub(crate) fn request_body_bytes(&self) -> Option<&bytes::Bytes> {+ self.request_body_bytes.as_ref()}pub(crate) fn resource_type(&self) -> SubresourceResourceType {diff --git a/moli-protocol/src/domains/network/tests/response_body.rs b/moli-protocol/src/domains/network/tests/response_body.rsindex 6965e4914..4275983d4 100644--- a/moli-protocol/src/domains/network/tests/response_body.rs+++ b/moli-protocol/src/domains/network/tests/response_body.rs@@ -257,7 +257,7 @@ async fn get_request_post_data_matches_chromium_errors_and_binary_encoding() {.runtime_slot.record_captured_request_body_with_collector_scope("REQ-empty".to_owned(),- Vec::new(),+ bytes::Bytes::new(),[None::<String>],std::iter::empty::<String>(),false,@@ -267,7 +267,7 @@ async fn get_request_post_data_matches_chromium_errors_and_binary_encoding() {.runtime_slot.record_captured_request_body_with_collector_scope("REQ-binary".to_owned(),- vec![0x00, 0xff, b'a'],+ bytes::Bytes::from_static(&[0x00, 0xff, b'a']),[None::<String>],std::iter::empty::<String>(),false,@@ -464,7 +464,7 @@ async fn get_request_post_data_respects_recorded_session_visibility() {.runtime_slot.record_captured_request_body_with_collector_scope("REQ-aux-only".to_owned(),- b"aux-only body".to_vec(),+ bytes::Bytes::from_static(b"aux-only body"),[Some("SID-attached".to_owned())],std::iter::empty::<String>(),false,@@ -526,7 +526,7 @@ async fn get_request_post_data_returns_main_document_navigation_post_body() {requested_url,request_method: "POST".to_owned(),request_body: Some("username=alice&pw=s3cret".to_owned()),- request_body_bytes: Some(b"username=alice&pw=s3cret".to_vec()),+ request_body_bytes: Some(bytes::Bytes::from_static(b"username=alice&pw=s3cret")),request_headers: Vec::new().into(),request_load_policy: crate::conn::NavigationRequestLoadPolicy::DocumentInitiated,timestamp: 0.0,@@ -599,6 +599,7 @@ async fn get_request_post_data_uses_text_projection_while_bidi_collector_keeps_tlet mut transport_bytes = multipart_text.as_bytes().to_vec();transport_bytes.extend_from_slice(&file_bytes);transport_bytes.extend_from_slice(b"\r\n----MoliFormDataBoundary0000--\r\n");+ let transport_bytes = bytes::Bytes::from(transport_bytes);let requested_url = Url::parse("http://127.0.0.1:1/upload").unwrap();let navigation_state = NavigationDispatchState {@@ -763,13 +764,13 @@ async fn get_network_data_returns_bidi_response_body_bytes() {.expect("bidi session runtime slot").record_captured_request_body_with_collector_scope("REQ-bidi-request".to_owned(),- "bidi request body".as_bytes().to_vec(),+ bytes::Bytes::from_static(b"bidi request body"),[Some("bidi-session-1".to_owned())],request_collector_ids,false,);- let binary_request = vec![0x00, 0xff, b'a'];+ let binary_request = bytes::Bytes::from_static(&[0x00, 0xff, b'a']);let binary_request_collector_ids = ctx.conn.network_data_collector_ids_for_session_owner_body(Some("bidi-session-1"),crate::automation::DevToolsNetworkDataType::Request,diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rsindex d62330e86..f8081c96d 100644--- a/moli-protocol/src/domains/page.rs+++ b/moli-protocol/src/domains/page.rs@@ -1388,7 +1388,7 @@ pub(in crate::domains) async fn navigate_command_owner_from_renderer_request_bacowner: CommandOwnerScope,url: &str,request_method: &str,- request_body: Option<&[u8]>,+ request_body: Option<&bytes::Bytes>,request_headers: &[(String, String)],browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,web_mcp_invocation: Option<moli_page_types::RendererWebMcpNavigation>,diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rsindex 74c22641f..103ff3a18 100644--- a/moli-protocol/src/domains/page/navigation.rs+++ b/moli-protocol/src/domains/page/navigation.rs@@ -2056,7 +2056,7 @@ pub(super) fn start_session_owner_navigation_from_renderer(owner: &CommandOwnerScope,url: &str,request_method: &str,- request_body: Option<&[u8]>,+ request_body: Option<&bytes::Bytes>,request_headers: &[(String, String)],browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,web_mcp_invocation: Option<moli_page_types::RendererWebMcpNavigation>,@@ -2101,7 +2101,7 @@ pub(super) fn start_session_owner_navigation_from_renderer(None,result_projection,request_method,- request_body.map(<[u8]>::to_vec),+ request_body.cloned(),request_headers.to_vec(),// The renderer has already settled the browsing-context action;// fetching and committing the destination is a new navigation@@ -2688,7 +2688,7 @@ fn start_navigate_to_url_command_with_background_policy_and_request(referrer: Option<&str>,result_projection: NavigationResultProjection,request_method: &str,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,allow_background_navigation: bool,request_load_policy: NavigationRequestLoadPolicy,diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.tomlindex da507adf0..5e810f1f5 100644--- a/moli-renderer-v8/Cargo.toml+++ b/moli-renderer-v8/Cargo.toml@@ -19,6 +19,7 @@ anyhow = "1.0.100"app_units = "0.7.8"base64 = "0.22"brotlic = "0.8.2"+bytes = "1"crossbeam-channel = "0.5.15"cssparser = "0.37"data-url = "0.3.2"diff --git a/moli-renderer-v8/src/content_security_policy.rs b/moli-renderer-v8/src/content_security_policy.rsindex 397131bcf..d5e3b554f 100644--- a/moli-renderer-v8/src/content_security_policy.rs+++ b/moli-renderer-v8/src/content_security_policy.rs@@ -546,7 +546,7 @@ fn append_content_security_policy_report_requests(let Ok(request) = Request::new_bytes("POST",endpoint,- Some(body.as_bytes().to_vec()),+ Some(bytes::Bytes::copy_from_slice(body.as_bytes())),vec![("Content-Type".to_owned(), content_type.to_owned())],) else {continue;diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex aff2dc02c..764b80051 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -1169,7 +1169,7 @@ impl LayoutMetricTrace {pub(crate) struct ChildBrowsingContextNavigationRequest {pub(crate) url: Url,pub(crate) method: String,- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) request_headers: Vec<(String, String)>,}diff --git a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs b/moli-renderer-v8/src/native_bridge/context_host/navigation.rsindex eec8cbe32..7020cd7cf 100644--- a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs@@ -60,7 +60,7 @@ pub(crate) struct PendingLocationNavigation {/// form POST callers retain raw bytes and their generated Content-Type.pub(crate) url: Url,pub(crate) request_method: String,- pub(crate) request_body: Option<Vec<u8>>,+ pub(crate) request_body: Option<bytes::Bytes>,pub(crate) request_headers: Vec<(String, String)>,pub(crate) browser_navigation_kind: BrowserNavigationRequestKind,pub(crate) navigation_initiator: Option<crate::runtime::RendererNavigationInitiator>,@@ -164,7 +164,7 @@ impl JsContextHost {&mut self,url: Url,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,entry_seed: Option<NavigationHistoryEntrySeed>,browser_navigation_kind: BrowserNavigationRequestKind,diff --git a/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs b/moli-renderer-v8/src/native_bridge/context_host/service_workers.rsindex 2ab1aab6a..f2d16d056 100644--- a/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/service_workers.rs@@ -1755,7 +1755,7 @@ impl JsContextHost {url: Url,method: String,headers: impl Into<moli_fetch::RequestHeaders>,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,destination: ServiceWorkerRequestDestination,request_mode: moli_fetch::RequestMode,credentials_mode: moli_fetch::RequestCredentialsMode,diff --git a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs b/moli-renderer-v8/src/native_bridge/element/forms/submission.rsindex c25a26201..2280c5ffa 100644--- a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs+++ b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs@@ -836,7 +836,7 @@ enum FormSubmissionMethod {},Post {resolved_url: Url,- body: Vec<u8>,+ body: bytes::Bytes,content_type: String,form_data_entries: Vec<(String, v8::Global<v8::Value>)>,},@@ -978,7 +978,7 @@ fn submit_post_form_to_top_level_browsing_context(form_handle: DomHandle,submitter: Option<DomHandle>,resolved_url: Url,- body: Vec<u8>,+ body: bytes::Bytes,content_type: String,form_data_entries: &[(String, v8::Global<v8::Value>)],user_initiated: bool,@@ -1031,7 +1031,7 @@ fn submit_post_form_to_child_browsing_context(submitter: Option<DomHandle>,target_document: DomHandle,resolved_url: Url,- body: Vec<u8>,+ body: bytes::Bytes,content_type: String,form_data_entries: &[(String, v8::Global<v8::Value>)],) -> bool {@@ -1128,7 +1128,7 @@ fn build_form_submission_request(let encoded = serialize_submission_body(scope, &entries, enctype?, submission_encoding);return Some(FormSubmissionMethod::Post {resolved_url,- body: encoded.body,+ body: encoded.body.into(),content_type: encoded.content_type,form_data_entries: entries,});diff --git a/moli-renderer-v8/src/network_host/beacon.rs b/moli-renderer-v8/src/network_host/beacon.rsindex a6ee6299c..0e3ba8c91 100644--- a/moli-renderer-v8/src/network_host/beacon.rs+++ b/moli-renderer-v8/src/network_host/beacon.rs@@ -229,7 +229,9 @@ pub(crate) fn send_link_audit_ping(method: "POST".to_owned(),request_headers: request_headers.clone(),request_body: request_body.clone(),- request_body_bytes: request_body.as_ref().map(|body| body.as_bytes().to_vec()),+ request_body_bytes: request_body+ .as_ref()+ .map(|body| bytes::Bytes::copy_from_slice(body.as_bytes())),resource_type: SubresourceResourceType::Ping,request_cookie_report,};@@ -264,7 +266,7 @@ pub(crate) fn send_link_audit_ping(let request = match Request::new_bytes("POST",ping_url.as_str(),- Some(b"PING".to_vec()),+ Some(bytes::Bytes::from_static(b"PING")),request_headers.clone(),) {Ok(request) => request@@ -352,7 +354,7 @@ fn window_ping_request_context(fn navigator_beacon_body<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,-) -> Option<(Option<Vec<u8>>, Option<String>)> {+) -> Option<(Option<bytes::Bytes>, Option<String>)> {if args.length() < 2 || args.get(1).is_null_or_undefined() {return Some((None, None));}@@ -379,7 +381,7 @@ fn navigator_beacon_body<'s>(}}-fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}diff --git a/moli-renderer-v8/src/network_host/body.rs b/moli-renderer-v8/src/network_host/body.rsindex 425951b95..9010646b0 100644--- a/moli-renderer-v8/src/network_host/body.rs+++ b/moli-renderer-v8/src/network_host/body.rs@@ -29,14 +29,14 @@ pub(in crate::network_host) fn readable_body_stream_unusable<'s>(#[derive(Debug, Clone)]pub(in crate::network_host) struct PreparedBodyInit {- pub(in crate::network_host) bytes: Vec<u8>,+ pub(in crate::network_host) bytes: bytes::Bytes,pub(in crate::network_host) content_type: Option<String>,}impl PreparedBodyInit {fn new(bytes: Vec<u8>, content_type: Option<String>) -> Self {Self {- bytes,+ bytes: bytes.into(),content_type,}}diff --git a/moli-renderer-v8/src/network_host/body_source.rs b/moli-renderer-v8/src/network_host/body_source.rsindex fb8ae8887..13f9fdde9 100644--- a/moli-renderer-v8/src/network_host/body_source.rs+++ b/moli-renderer-v8/src/network_host/body_source.rs@@ -371,9 +371,10 @@ fn context_host_mut<'s>(pub(in crate::network_host) fn set_network_body_owned_bytes<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,- bytes: Vec<u8>,+ bytes: impl Into<Vec<u8>>,) -> Option<v8::Local<'s, v8::ArrayBuffer>> {- let buffer = blob::array_buffer_from_bytes(scope, bytes)?;+ // JS can mutate this backing store, so it must own its bytes exclusively.+ let buffer = blob::array_buffer_from_bytes(scope, bytes.into())?;// Keep body storage behind a dedicated source object. Today this source is// still ArrayBuffer-backed; stream/spool-backed variants should extend this// module instead of teaching Fetch/XHR call sites about more hidden slots.diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rsindex 345d1bc93..84a727733 100644--- a/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs+++ b/moli-renderer-v8/src/network_host/fetch/bindings/paths.rs@@ -325,7 +325,7 @@ fn window_fetch_script_metadata(})}-fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/request.rs b/moli-renderer-v8/src/network_host/fetch/bindings/request.rsindex b6630a518..316ddea44 100644--- a/moli-renderer-v8/src/network_host/fetch/bindings/request.rs+++ b/moli-renderer-v8/src/network_host/fetch/bindings/request.rs@@ -66,7 +66,7 @@ pub(super) struct PreparedWindowFetchRequest {pub(super) method: String,pub(super) request_headers: moli_fetch::RequestHeaders,pub(super) cors_preflight_request_headers: Vec<(String, String)>,- pub(super) body: Option<Vec<u8>>,+ pub(super) body: Option<bytes::Bytes>,pub(super) request_mode: moli_fetch::RequestMode,pub(super) credentials_mode: moli_fetch::RequestCredentialsMode,pub(super) redirect_mode: moli_fetch::RequestRedirectMode,diff --git a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rsindex ce016c29f..3dbd555f7 100644--- a/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs+++ b/moli-renderer-v8/src/network_host/fetch/bindings/service_worker.rs@@ -130,7 +130,7 @@ pub(super) fn dispatch_service_worker_fetch(Some(internal_id)}-fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}diff --git a/moli-renderer-v8/src/network_host/fetch/input.rs b/moli-renderer-v8/src/network_host/fetch/input.rsindex 3137d8373..fa2a89be2 100644--- a/moli-renderer-v8/src/network_host/fetch/input.rs+++ b/moli-renderer-v8/src/network_host/fetch/input.rs@@ -5,7 +5,7 @@ use std::str::FromStr;pub(super) struct ParsedWindowFetchInput {pub(super) url: String,pub(super) method: String,- pub(super) body: Option<Vec<u8>>,+ pub(super) body: Option<bytes::Bytes>,pub(super) headers: Vec<(String, String)>,pub(super) request_mode: moli_fetch::RequestMode,pub(super) credentials_mode: moli_fetch::RequestCredentialsMode,diff --git a/moli-renderer-v8/src/network_host/request/bindings/init.rs b/moli-renderer-v8/src/network_host/request/bindings/init.rsindex ff7335dc7..6668e33f5 100644--- a/moli-renderer-v8/src/network_host/request/bindings/init.rs+++ b/moli-renderer-v8/src/network_host/request/bindings/init.rs@@ -23,7 +23,7 @@ pub(super) struct RequestConstructionState {pub(super) keepalive: bool,pub(super) priority: moli_fetch::FetchPriorityHint,pub(super) duplex: String,- pub(super) body: Option<Vec<u8>>,+ pub(super) body: Option<bytes::Bytes>,pub(super) inherited_body_unusable: bool,pub(super) body_content_type: Option<String>,pub(super) headers: Vec<(String, String)>,diff --git a/moli-renderer-v8/src/network_host/request/init.rs b/moli-renderer-v8/src/network_host/request/init.rsindex 3fec5fdaf..31f351e5c 100644--- a/moli-renderer-v8/src/network_host/request/init.rs+++ b/moli-renderer-v8/src/network_host/request/init.rs@@ -35,7 +35,7 @@ pub(crate) fn convert_fetch_arguments<'s, T>(pub(crate) struct ParsedFetchInit {pub(crate) method: String,pub(crate) method_present: bool,- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) body_present: bool,pub(crate) body_content_type: Option<String>,pub(crate) headers: Vec<(String, String)>,diff --git a/moli-renderer-v8/src/network_host/request/input.rs b/moli-renderer-v8/src/network_host/request/input.rsindex d679dedd8..a81ff9110 100644--- a/moli-renderer-v8/src/network_host/request/input.rs+++ b/moli-renderer-v8/src/network_host/request/input.rs@@ -53,7 +53,7 @@ pub(crate) struct RequestInputSnapshot {pub(crate) keepalive: bool,pub(crate) priority: moli_fetch::FetchPriorityHint,pub(crate) duplex: String,- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) body_unusable: bool,pub(crate) headers: Vec<(String, String)>,pub(crate) signal: Option<v8::Global<v8::Object>>,@@ -134,7 +134,8 @@ fn request_input_snapshot_inner<'s>(let duplex = defined_object_string_property(scope, object, "duplex").unwrap_or_else(|| "half".to_owned());let body = try_network_body_bytes_from_object(scope, object)- .map_err(|_| webidl::WebIdlError::custom_message("Failed to materialize request body"))?;+ .map_err(|_| webidl::WebIdlError::custom_message("Failed to materialize request body"))?+ .map(bytes::Bytes::from);let headers = webidl::property_result(scope,object,@@ -201,9 +202,9 @@ fn request_input_snapshot_from_private_slots<'s>(let body = if body_unusable {None} else {- try_network_body_bytes_from_object(scope, object).map_err(|_| {- webidl::WebIdlError::custom_message("Failed to materialize request body")- })?+ try_network_body_bytes_from_object(scope, object)+ .map_err(|_| webidl::WebIdlError::custom_message("Failed to materialize request body"))?+ .map(bytes::Bytes::from)};// Inherited headers are an internal list copy, unlike an explicit// RequestInit.headers value, which undergoes WebIDL iterable conversion.diff --git a/moli-renderer-v8/src/network_host/xhr/send/paths.rs b/moli-renderer-v8/src/network_host/xhr/send/paths.rsindex 70f156def..61c214a69 100644--- a/moli-renderer-v8/src/network_host/xhr/send/paths.rs+++ b/moli-renderer-v8/src/network_host/xhr/send/paths.rs@@ -373,7 +373,7 @@ pub(super) fn spawn_network_xhr_fetch(internal_id}-pub(super) fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+pub(super) fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}diff --git a/moli-renderer-v8/src/network_host/xhr/send/request.rs b/moli-renderer-v8/src/network_host/xhr/send/request.rsindex 58d7c02e7..a84560491 100644--- a/moli-renderer-v8/src/network_host/xhr/send/request.rs+++ b/moli-renderer-v8/src/network_host/xhr/send/request.rs@@ -25,7 +25,7 @@ pub(super) struct PreparedXhrSendRequest {pub(super) method: String,pub(super) request_headers: moli_fetch::RequestHeaders,pub(super) cors_preflight_request_headers: Vec<(String, String)>,- pub(super) send_body: Option<Vec<u8>>,+ pub(super) send_body: Option<bytes::Bytes>,pub(super) credentials_mode: moli_fetch::RequestCredentialsMode,pub(super) use_cors_preflight: bool,}@@ -111,7 +111,7 @@ pub(super) fn prepare_xhr_send_request<'s>(}pub(crate) struct PreparedXhrSendBody {- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) default_content_type: Option<String>,}@@ -150,7 +150,7 @@ impl PreparedXhrSendBody {fn new(body: Vec<u8>, default_content_type: Option<String>) -> Self {Self {- body: Some(body),+ body: Some(body.into()),default_content_type,}}diff --git a/moli-renderer-v8/src/runtime/page_network.rs b/moli-renderer-v8/src/runtime/page_network.rsindex e338d31b6..c70c50126 100644--- a/moli-renderer-v8/src/runtime/page_network.rs+++ b/moli-renderer-v8/src/runtime/page_network.rs@@ -230,7 +230,7 @@ impl PageVm {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex 7a298ee19..c814d7fdd 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -324,7 +324,7 @@ struct RendererTopLevelNavigationRequest {web_mcp_invocation: Option<moli_page_types::RendererWebMcpNavigation>,url: String,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,history_mutation: moli_page_types::NavigationHistoryMutation,@@ -355,7 +355,7 @@ impl RendererDocumentSourcedTopLevelLocationNavigation {source_document: RendererDocumentLifecycleIdentity,url: String,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,runtime_command_cause: Option<RendererRuntimeCommandCausalIdentity>,@@ -431,8 +431,8 @@ impl RendererDocumentSourcedTopLevelLocationNavigation {&self.request.request_method}- pub fn request_body(&self) -> Option<&[u8]> {- self.request.request_body.as_deref()+ pub fn request_body(&self) -> Option<&bytes::Bytes> {+ self.request.request_body.as_ref()}pub fn request_headers(&self) -> &[(String, String)] {@@ -5145,7 +5145,7 @@ pub enum RendererPageCommand {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,diff --git a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rsindex edd6a0696..599071c3f 100644--- a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs+++ b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs@@ -67,7 +67,7 @@ pub(super) async fn load_followed_location_navigation(initiator_url: Url,url: Url,request_method: String,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,browser_navigation_kind: BrowserNavigationRequestKind,) -> Result<LoadedFollowedLocationNavigation> {@@ -461,7 +461,7 @@ fn build_followed_location_navigation_request(initiator_url: &Url,url: &Url,request_method: &str,- request_body: Option<Vec<u8>>,+ request_body: Option<bytes::Bytes>,request_headers: Vec<(String, String)>,browser_navigation_kind: BrowserNavigationRequestKind,) -> Result<Request> {@@ -1586,7 +1586,7 @@ mod tests {fn followed_location_navigation_preserves_post_request() {let initiator_url = Url::parse("https://example.com/form").unwrap();let target_url = Url::parse("https://example.com/submit").unwrap();- let body = b"answer=42".to_vec();+ let body = bytes::Bytes::from_static(b"answer=42");let request = build_followed_location_navigation_request(&initiator_url,@@ -1640,7 +1640,7 @@ mod tests {initiator,Url::parse("data:text/html,<p>payload</p>").unwrap(),"POST".to_owned(),- Some(b"upload".to_vec()),+ Some(bytes::Bytes::from_static(b"upload")),Vec::new(),BrowserNavigationRequestKind::Navigate,)diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch.rsindex c380863ce..7ed28dde3 100644--- a/moli-renderer-v8/src/script_vm/subresource_fetch.rs+++ b/moli-renderer-v8/src/script_vm/subresource_fetch.rs@@ -647,7 +647,7 @@ impl WorkerOwnedCspReportTarget {fn with_pending_subresource_record_identity(record: SubresourceNetworkRecord,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,request_handle: Option<SubresourceNetworkRequestHandle>,) -> SubresourceNetworkRecord {let mut record = record.with_request_body_bytes(request_body_bytes);diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rsindex 56de20d13..e8af791e6 100644--- a/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/pending_fetch.rs@@ -6,7 +6,7 @@ impl ScriptVm {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,@@ -46,7 +46,10 @@ impl ScriptVm {// The text snapshot is only for protocol display. Unless the client// explicitly replaces the body, retain the original binary upload.if let Some(body) = &body {- info.request_body_bytes = body.as_ref().map(|body| body.as_bytes().to_vec());+ info.request_body_bytes = body.clone();+ info.request_body = body+ .as_ref()+ .map(|body| String::from_utf8_lossy(body).into_owned());}let pending = match continuation {PendingSubresourceContinuation::WebSocket(connection) => {@@ -74,7 +77,7 @@ impl ScriptVm {let fetch_id = target.fetch_id();let request_url = url.unwrap_or_else(|| info.url.clone());let request_method = method.unwrap_or_else(|| info.method.clone());- let request_body = body.unwrap_or_else(|| info.request_body.clone());+ let request_body = info.request_body.clone();let request_headers = headers.unwrap_or_else(|| info.request_headers.clone());let continued = self.continue_worker_owned_fetch(target,@@ -131,7 +134,7 @@ impl ScriptVm {let xhr_id = target.xhr_id();let request_url = url.unwrap_or_else(|| info.url.clone());let request_method = method.unwrap_or_else(|| info.method.clone());- let request_body = body.unwrap_or_else(|| info.request_body.clone());+ let request_body = info.request_body.clone();let request_headers = headers.unwrap_or_else(|| info.request_headers.clone());let continued = self.continue_worker_owned_xhr(target,@@ -215,12 +218,8 @@ impl ScriptVm {PendingSubresourceContinuation::CspReport { client_id } => {let request_url = url.unwrap_or_else(|| info.url.clone());let request_method = method.unwrap_or_else(|| info.method.clone());- let request_body_bytes = match &body {- Some(Some(body)) => Some(body.as_bytes().to_vec()),- Some(None) => None,- None => info.request_body_bytes.clone(),- };- let request_body = body.unwrap_or_else(|| info.request_body.clone());+ let request_body_bytes = info.request_body_bytes.clone();+ let request_body = info.request_body.clone();let request_headers = headers.unwrap_or_else(|| info.request_headers.clone());let pending = PendingSubresourceFetchState {redirect_headers: redirect_headers.clone(),@@ -286,7 +285,7 @@ impl ScriptVm {};let request_url = url.unwrap_or_else(|| pending.info.url.clone());let request_method = method.unwrap_or_else(|| pending.info.method.clone());- let request_body = body.unwrap_or_else(|| pending.info.request_body.clone());+ let request_body = pending.info.request_body.clone();let request_headers = headers.unwrap_or_else(|| pending.info.request_headers.clone());self.continue_pending_subresource_fetch_via_loader(pending,@@ -412,7 +411,7 @@ impl ScriptVm {request_method: String,request_headers: moli_fetch::RequestHeaders,request_body: Option<String>,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,) -> Result<Option<PendingSubresourceFetchState>> {if self._context_host@@ -2020,7 +2019,7 @@ impl ScriptVm {internal_id: u64,url: Option<Url>,method: Option<String>,- body: Option<Option<String>>,+ body: Option<Option<bytes::Bytes>>,headers: Option<moli_fetch::RequestHeaderOverride>,intercept_response: bool,handle_auth_requests: bool,diff --git a/moli-renderer-v8/src/service_worker_runtime/events.rs b/moli-renderer-v8/src/service_worker_runtime/events.rsindex 20967abc0..fb51b1d81 100644--- a/moli-renderer-v8/src/service_worker_runtime/events.rs+++ b/moli-renderer-v8/src/service_worker_runtime/events.rs@@ -472,7 +472,7 @@ pub(crate) struct ServiceWorkerFetchRequest {pub(crate) method: String,/// Isomorphically decoded wire bytes, ready for the worker's Fetch Headers.pub(crate) headers: Vec<(String, String)>,- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) destination: ServiceWorkerRequestDestination,pub(crate) request_mode: moli_fetch::RequestMode,pub(crate) credentials_mode: moli_fetch::RequestCredentialsMode,diff --git a/moli-renderer-v8/src/service_worker_runtime/service.rs b/moli-renderer-v8/src/service_worker_runtime/service.rsindex b669f3587..77f71e6f9 100644--- a/moli-renderer-v8/src/service_worker_runtime/service.rs+++ b/moli-renderer-v8/src/service_worker_runtime/service.rs@@ -326,7 +326,7 @@ impl std::fmt::Debug for ServiceWorkerRuntimeService {}}-fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}diff --git a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rsindex ddfcb904d..c9e4fde06 100644--- a/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs+++ b/moli-renderer-v8/src/service_worker_runtime/service/fetch_settlement.rs@@ -1942,7 +1942,7 @@ mod tests {moli_fetch::Request::new_browser("POST",request_url.clone(),- Some(b"payload".to_vec()),+ Some(bytes::Bytes::from_static(b"payload")),vec![("content-type".to_owned(), "text/plain".to_owned()),("x-keep".to_owned(), "yes".to_owned()),diff --git a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rsindex f125d729c..96bf95fea 100644--- a/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs+++ b/moli-renderer-v8/src/worker/global_scope/content_security_policy.rs@@ -677,7 +677,7 @@ fn record_worker_content_security_policy_report_failure(request.url,request.method,request.request_headers.clone(),- request_body.map(String::into_bytes),+ request_body.map(bytes::Bytes::from),SubresourceResourceType::CspReport,message,);diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rsindex 5743b9051..ad0c21f9f 100644--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs@@ -24,7 +24,7 @@ pub(in crate::worker) fn record_worker_subresource_failure(url,method,request_headers,- request_body.map(String::into_bytes),+ request_body.map(bytes::Bytes::from),resource_type,error_text,);@@ -37,7 +37,7 @@ pub(in crate::worker) fn record_worker_subresource_failure_with_handle(url: Url,method: String,request_headers: moli_fetch::RequestHeaders,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,error_text: String,) {@@ -78,7 +78,7 @@ pub(in crate::worker) fn record_worker_subresource_success(url,method,request_headers,- request_body.map(String::into_bytes),+ request_body.map(bytes::Bytes::from),resource_type,None,head,@@ -93,7 +93,7 @@ pub(in crate::worker) fn record_worker_subresource_success_with_handle(url: Url,method: String,request_headers: moli_fetch::RequestHeaders,- request_body_bytes: Option<Vec<u8>>,+ request_body_bytes: Option<bytes::Bytes>,resource_type: SubresourceResourceType,network_request_headers: Option<Vec<(String, String)>>,head: ResponseHead,@@ -151,7 +151,7 @@ pub(in crate::worker) fn spawn_worker_fetch_network(network_partition_key: Option<String>,resolved_url: Url,method: String,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: moli_fetch::RequestHeaders,request_mode: RequestMode,credentials_mode: RequestCredentialsMode,@@ -393,7 +393,7 @@ fn spawn_worker_fetch_service_worker(policy_context: SubresourcePolicyContext,resolved_url: Url,method: String,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: moli_fetch::RequestHeaders,request_mode: RequestMode,credentials_mode: RequestCredentialsMode,@@ -514,7 +514,7 @@ pub(in crate::worker) fn spawn_worker_xhr_network(network_partition_key: Option<String>,resolved_url: Url,method: String,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: moli_fetch::RequestHeaders,credentials_mode: RequestCredentialsMode,use_cors_preflight: bool,@@ -1752,7 +1752,7 @@ pub(in crate::worker) fn response_header_name_is(candidate: &str, expected: &HeaHeaderName::from_bytes(candidate.as_bytes()).is_ok_and(|candidate| candidate == *expected)}-pub(in crate::worker) fn request_body_text(body: &Option<Vec<u8>>) -> Option<String> {+pub(in crate::worker) fn request_body_text(body: &Option<bytes::Bytes>) -> Option<String> {body.as_ref().map(|body| String::from_utf8_lossy(body).into_owned())}@@ -1844,7 +1844,7 @@ pub(in crate::worker) fn worker_fetch_signal_option<'s>(pub(in crate::worker) struct ResolvedWorkerFetchInput<'s> {resolved_url: Url,method: String,- body: Option<Vec<u8>>,+ body: Option<bytes::Bytes>,headers: Vec<(String, String)>,request_mode: moli_fetch::RequestMode,credentials_mode: RequestCredentialsMode,@@ -2768,7 +2768,7 @@ pub(in crate::worker) fn record_worker_fetch_failure(pending.request_body.as_ref()- .map(|body| body.as_bytes().to_vec()),+ .map(|body| bytes::Bytes::copy_from_slice(body.as_bytes())),SubresourceResourceType::Fetch,network_error_text,);diff --git a/moli-renderer-v8/src/worker/global_scope/network_state.rs b/moli-renderer-v8/src/worker/global_scope/network_state.rsindex d6e45cbb9..b64a1fcce 100644--- a/moli-renderer-v8/src/worker/global_scope/network_state.rs+++ b/moli-renderer-v8/src/worker/global_scope/network_state.rs@@ -113,7 +113,7 @@ pub(in crate::worker) struct PendingWorkerFetchNetworkRecord {pub(in crate::worker) url: Url,pub(in crate::worker) method: String,pub(in crate::worker) request_headers: moli_fetch::RequestHeaders,- pub(in crate::worker) request_body_bytes: Option<Vec<u8>>,+ pub(in crate::worker) request_body_bytes: Option<bytes::Bytes>,pub(in crate::worker) initial_network_request_headers: Option<Vec<(String, String)>>,pub(in crate::worker) intercept_response: bool,pub(in crate::worker) handle_auth_requests: bool,diff --git a/moli-renderer-v8/src/worker/global_scope/xhr.rs b/moli-renderer-v8/src/worker/global_scope/xhr.rsindex 59eac243d..3d45bb374 100644--- a/moli-renderer-v8/src/worker/global_scope/xhr.rs+++ b/moli-renderer-v8/src/worker/global_scope/xhr.rs@@ -13,7 +13,7 @@ pub(in crate::worker) struct PreparedWorkerXhrSendRequest {resolved_url: Url,method: String,request_headers: moli_fetch::RequestHeaders,- send_body: Option<Vec<u8>>,+ send_body: Option<bytes::Bytes>,credentials_mode: RequestCredentialsMode,}@@ -906,7 +906,7 @@ pub(in crate::worker) fn record_worker_xhr_failure(pending.request_body.as_ref()- .map(|body| body.as_bytes().to_vec()),+ .map(|body| bytes::Bytes::copy_from_slice(body.as_bytes())),SubresourceResourceType::Xhr,network_error_text,);diff --git a/moli-renderer-v8/src/worker/handle.rs b/moli-renderer-v8/src/worker/handle.rsindex 74bb7d44a..416b7a7c6 100644--- a/moli-renderer-v8/src/worker/handle.rs+++ b/moli-renderer-v8/src/worker/handle.rs@@ -572,7 +572,7 @@ pub(crate) struct WorkerPendingFetchContinue {pub(crate) url: Url,pub(crate) method: String,/// Upload bytes after applying explicit overrides, including an empty body.- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) headers: moli_fetch::RequestHeaders,pub(crate) intercept_response: bool,pub(crate) handle_auth_requests: bool,@@ -588,7 +588,7 @@ pub(crate) struct WorkerPendingXhrContinue {pub(crate) url: Url,pub(crate) method: String,/// Upload bytes after applying explicit overrides, including an empty body.- pub(crate) body: Option<Vec<u8>>,+ pub(crate) body: Option<bytes::Bytes>,pub(crate) headers: moli_fetch::RequestHeaders,pub(crate) intercept_response: bool,pub(crate) handle_auth_requests: bool,diff --git a/moli-renderer-v8/src/worker/thread/dispatch.rs b/moli-renderer-v8/src/worker/thread/dispatch.rsindex cfcc6c018..a8b8c6ded 100644--- a/moli-renderer-v8/src/worker/thread/dispatch.rs+++ b/moli-renderer-v8/src/worker/thread/dispatch.rs@@ -2084,7 +2084,8 @@ fn new_service_worker_fetch_request<'s>(if !matches!(event.request.method.as_str(), "GET" | "HEAD")&& let Some(body) = event.request.body.clone(){- let backing_store = v8::ArrayBuffer::new_backing_store_from_vec(body).make_shared();+ // The mutable JS buffer must not alias shared immutable upload bytes.+ let backing_store = v8::ArrayBuffer::new_backing_store_from_vec(body.into()).make_shared();let body = v8::ArrayBuffer::with_backing_store(scope, &backing_store);let _ = init.set(scope, v8str(scope, "body").into(), body.into());}diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rsindex f5862c412..31ad359fd 100644--- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs+++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/fetch_events_and_messages.rs@@ -1025,7 +1025,7 @@ async fn service_worker_fetch_event_request_body_used_guards_inherited_body() {url: url::Url::parse("https://example.test/app/post").unwrap(),method: "POST".to_owned(),headers: vec![("content-type".to_owned(), "text/plain".to_owned())],- body: Some(b"fetch-body".to_vec()),+ body: Some(bytes::Bytes::from_static(b"fetch-body")),destination: ServiceWorkerRequestDestination::Empty,request_mode: moli_fetch::RequestMode::Cors,credentials_mode: moli_fetch::RequestCredentialsMode::SameOrigin,