Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(encoding): initialize decoder streams through native endpoints
ldm08c5ed2c7f5c9
diff --git a/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs b/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rsindex 56334d82e..b8093a53d 100644--- a/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs+++ b/moli-renderer-v8/src/context_bootstrap/constructors/text_codecs.rs@@ -1,7 +1,6 @@use super::*;use crate::web_api_interfaces;use crate::{- text_codec::TextDecodeError,util::{callback_data_index_value, callback_data_item, get_private_value},webidl,};@@ -359,27 +358,3 @@ fn text_decoder_decode_callback<'s>(}}}--fn init_text_decoder_state(- scope: &mut v8::PinScope<'_, '_>,- decoder: v8::Local<'_, v8::Object>,- encoding: &'static encoding_rs::Encoding,- fatal: bool,- ignore_bom: bool,-) {- if let Some(common) = crate::common_runtime::CommonRuntimeState::from_scope(scope) {- common- .text_codecs- .init_decoder(scope, decoder, encoding, fatal, ignore_bom);- }-}--fn decode_text_decoder_state(- scope: &mut v8::PinScope<'_, '_>,- decoder_id: u32,- bytes: &[u8],- stream: bool,-) -> Option<Result<String, TextDecodeError>> {- let common = crate::common_runtime::CommonRuntimeState::from_scope(scope)?;- Some(common.text_codecs.decode(decoder_id, bytes, stream))-}diff --git a/moli-renderer-v8/src/context_bootstrap/shared.rs b/moli-renderer-v8/src/context_bootstrap/shared.rsindex 78fa82761..f692be7ad 100644--- a/moli-renderer-v8/src/context_bootstrap/shared.rs+++ b/moli-renderer-v8/src/context_bootstrap/shared.rs@@ -5,6 +5,7 @@ mod definition;mod dom;mod object;mod slots;+mod text_codecs;mod time;use crate::{@@ -35,6 +36,7 @@ pub(in crate::context_bootstrap) use moli_browser_profile::{};pub(in crate::context_bootstrap) use object::*;pub(crate) use slots::*;+pub(in crate::context_bootstrap) use text_codecs::*;pub(crate) use time::*;pub(in crate::context_bootstrap) use super::shared_installers::{diff --git a/moli-renderer-v8/src/context_bootstrap/shared/buffers.rs b/moli-renderer-v8/src/context_bootstrap/shared/buffers.rsindex 332e5870a..0e3f66f1a 100644--- a/moli-renderer-v8/src/context_bootstrap/shared/buffers.rs+++ b/moli-renderer-v8/src/context_bootstrap/shared/buffers.rs@@ -1,15 +1,3 @@-pub(in crate::context_bootstrap) fn text_decoder_encoding_for_label(- label: &str,-) -> Option<&'static encoding_rs::Encoding> {- encoding_rs::Encoding::for_label_no_replacement(label.as_bytes())-}--pub(in crate::context_bootstrap) fn canonical_text_decoder_encoding_name(- encoding: &'static encoding_rs::Encoding,-) -> String {- encoding.name().to_ascii_lowercase()-}-pub(in crate::context_bootstrap) fn new_uint8_array_from_bytes<'s>(scope: &mut v8::PinScope<'s, '_>,bytes: Vec<u8>,diff --git a/moli-renderer-v8/src/context_bootstrap/shared/text_codecs.rs b/moli-renderer-v8/src/context_bootstrap/shared/text_codecs.rsnew file mode 100644index 000000000..9035868b4--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/shared/text_codecs.rs@@ -0,0 +1,37 @@+use crate::text_codec::TextDecodeError;++pub(in crate::context_bootstrap) fn text_decoder_encoding_for_label(+ label: &str,+) -> Option<&'static encoding_rs::Encoding> {+ encoding_rs::Encoding::for_label_no_replacement(label.as_bytes())+}++pub(in crate::context_bootstrap) fn canonical_text_decoder_encoding_name(+ encoding: &'static encoding_rs::Encoding,+) -> String {+ encoding.name().to_ascii_lowercase()+}++pub(in crate::context_bootstrap) fn init_text_decoder_state(+ scope: &mut v8::PinScope<'_, '_>,+ decoder: v8::Local<'_, v8::Object>,+ encoding: &'static encoding_rs::Encoding,+ fatal: bool,+ ignore_bom: bool,+) {+ if let Some(common) = crate::common_runtime::CommonRuntimeState::from_scope(scope) {+ common+ .text_codecs+ .init_decoder(scope, decoder, encoding, fatal, ignore_bom);+ }+}++pub(in crate::context_bootstrap) fn decode_text_decoder_state(+ scope: &mut v8::PinScope<'_, '_>,+ decoder_id: u32,+ bytes: &[u8],+ stream: bool,+) -> Option<Result<String, TextDecodeError>> {+ let common = crate::common_runtime::CommonRuntimeState::from_scope(scope)?;+ Some(common.text_codecs.decode(decoder_id, bytes, stream))+}diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rsindex c9aa2c186..374e5c224 100644--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs@@ -2298,20 +2298,11 @@ fn decode_text_decoder_stream<'s>(bytes: &[u8],stream_decode: bool,) -> Result<String, TextDecodeError> {- let Some(common) = crate::common_runtime::CommonRuntimeState::from_scope(scope) else {+ let Some(decoder_id) = TextCodecStore::decoder_id_from_object(scope, stream) else {return Ok(String::new());};- let Some(decoder_id) = text_decoder_stream_decoder_id(scope, stream) else {- return Ok(String::new());- };- common.text_codecs.decode(decoder_id, bytes, stream_decode)-}--fn text_decoder_stream_decoder_id<'s>(- scope: &mut v8::PinScope<'s, '_>,- stream: v8::Local<'s, v8::Object>,-) -> Option<u32> {- TextCodecStore::decoder_id_from_object(scope, stream)+ decode_text_decoder_state(scope, decoder_id, bytes, stream_decode)+ .unwrap_or_else(|| Ok(String::new()))}fn reject_text_decoder_stream<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs b/moli-renderer-v8/src/context_bootstrap/streams/constructors.rsindex 62c329128..dfcebd5c9 100644--- a/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs+++ b/moli-renderer-v8/src/context_bootstrap/streams/constructors.rs@@ -391,13 +391,9 @@ pub(in crate::context_bootstrap) fn text_decoder_stream_constructor_callback<'s>0.0,None,);- if let Some(writable) = object_property_as_object(scope, args.this(), "writable")- && let Some(common) = crate::common_runtime::CommonRuntimeState::from_scope(scope)- {- common- .text_codecs- .init_decoder(scope, writable, encoding, fatal, ignore_bom);- }+ let writable = stream_slot_object(scope, args.this(), TRANSFORM_STREAM_WRITABLE_SLOT)+ .expect("a new text decoder stream owns its writable endpoint");+ init_text_decoder_state(scope, writable, encoding, fatal, ignore_bom);TextDecoderStreamObjectDeclaration::new(encoding_name, fatal, ignore_bom).initialize(scope, args.this()).expect("TextDecoderStream declaration should initialize object");diff --git a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rsindex bbdb8f670..59a1783be 100644--- a/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs+++ b/moli-renderer-v8/src/script_vm/tests/webidl_fetch/webidl_and_transform_streams.rs@@ -602,6 +602,29 @@ fn text_decoder_stream_uses_encoding_rs_labels_and_streaming_decode() {assert_eq!(settled, r#"["太平洋:false"]"#);}+#[test]+fn text_decoder_stream_uses_private_endpoints_and_owned_codec_state() {+ let mut vm = new_storage_test_vm("https://text-decoder-state.test/");+ vm.eval(include_str!(+ "../../../../tests/fixtures/text-decoder-state.js"+ ))+ .expect("text decoder state contract should load");+ vm.eval("runTextDecoderStateContract().then(result => globalThis.__textDecoderStateResults = result)")+ .expect("text decoder state contract should execute");+ let facts: serde_json::Value = serde_json::from_str(+ &vm.eval("JSON.stringify(__textDecoderStateResults)")+ .expect("text decoder state results should serialize"),+ )+ .expect("text decoder state results should be valid JSON");+ let checks = facts["checks"].as_array().expect("state checks");+ let failures = checks+ .iter()+ .filter(|check| check["passed"] != true)+ .collect::<Vec<_>>();+ assert!(failures.is_empty(), "{failures:#?}");+ assert_eq!(checks.len(), 20);+}+#[test]fn text_decoder_stream_fatal_errors_reject_write_and_read() {let mut vm = new_storage_test_vm("https://example.com/");diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/background_apis_and_worker_events.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/background_apis_and_worker_events.rsindex 7a73a937f..ba50efe84 100644--- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/background_apis_and_worker_events.rs+++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/background_apis_and_worker_events.rs@@ -1,5 +1,35 @@use super::*;+#[tokio::test]+async fn worker_text_decoder_stream_uses_private_endpoints_and_owned_codec_state() {+ ensure_v8();+ let source = [+ include_str!("../../../../../tests/fixtures/text-decoder-state.js"),+ r#"+runTextDecoderStateContract().then(+ result => { postMessage(result); close(); },+ error => { postMessage({ failure: String(error) }); close(); }+);+"#,+ ]+ .join("\n");+ let mut handle = spawn_worker(source, "https://text-decoder-state.test/worker.js".into());+ let message = timeout(TIMEOUT, handle.recv())+ .await+ .expect("text decoder state contract should complete")+ .expect("worker result channel should stay open");+ handle.terminate_and_join();+ let facts: serde_json::Value = serde_json::from_str(&expect_post_json(message))+ .expect("text decoder state results should be valid JSON");+ let checks = facts["checks"].as_array().expect("state checks");+ let failures = checks+ .iter()+ .filter(|check| check["passed"] != true)+ .collect::<Vec<_>>();+ assert!(failures.is_empty(), "{failures:#?}");+ assert_eq!(checks.len(), 20);+}+#[tokio::test]async fn service_worker_push_manager_subscription_resolves_from_parent_results() {ensure_v8();diff --git a/moli-renderer-v8/tests/fixtures/text-decoder-state.js b/moli-renderer-v8/tests/fixtures/text-decoder-state.jsnew file mode 100644index 000000000..90fd266ec--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/text-decoder-state.js@@ -0,0 +1,94 @@+globalThis.runTextDecoderStateContract = async function () {+ const checks = [];+ const readable = Object.getOwnPropertyDescriptor(TextDecoderStream.prototype, "readable").get;+ const writable = Object.getOwnPropertyDescriptor(TextDecoderStream.prototype, "writable").get;+ async function check(name, operation) {+ try {+ checks.push({ name, passed: await operation() === true });+ } catch (error) {+ checks.push({ name, passed: false, error: String(error) });+ }+ }+ async function decode(label, options, chunks, Decoder = TextDecoderStream) {+ const decoder = new Decoder(label, options);+ const endpoints = { readable: readable.call(decoder), writable: writable.call(decoder) };+ const source = new ReadableStream({ start(controller) {+ for (const bytes of chunks) controller.enqueue(Uint8Array.from(bytes));+ controller.close();+ } });+ const reader = source.pipeThrough(endpoints).getReader();+ const output = [];+ while (true) {+ const item = await reader.read();+ if (item.done) return output;+ output.push(item.value);+ }+ }+ for (const [name, label, options, chunks, expected] of [+ ["ASCII chunks", "utf-8", {}, [[97], [], [98, 99]], "abc"],+ ["split UTF-8", "utf-8", {}, [[0xe2], [0x82, 0xac]], "\u20ac"],+ ["split UTF-16BE", "utf-16be", {}, [[0], [65]], "A"],+ ["split UTF-16LE", "utf-16le", {}, [[65], [0]], "A"],+ ["UTF-8 BOM removal", "utf-8", {}, [[0xef], [0xbb], [0xbf, 65]], "A"],+ ["UTF-8 BOM preservation", "utf-8", { ignoreBOM: true }, [[0xef], [0xbb], [0xbf, 65]], "\ufeffA"],+ ["UTF-16LE BOM removal", "utf-16le", {}, [[0xff], [0xfe, 65, 0]], "A"],+ ["UTF-16LE BOM preservation", "utf-16le", { ignoreBOM: true }, [[0xff], [0xfe, 65, 0]], "\ufeffA"],+ ["legacy GBK", "gbk", {}, [[0xcc], [0xab, 0xc6], [0xbd, 0xd1], [0xf3]], "\u592a\u5e73\u6d0b"],+ ["ISO-2022-JP state", "iso-2022-jp", {}, [[0x1b, 0x28], [0x4a, 0x7e]], "\u203e"],+ ["incomplete UTF-8 flush", "utf-8", {}, [[0xe2], [0x82]], "\ufffd"],+ ["incomplete UTF-16 flush", "utf-16be", {}, [[0]], "\ufffd"],+ ]) {+ await check(name, async () => (await decode(label, options, chunks)).join("") === expected);+ }+ for (const [label, chunks] of [["utf-8", [[0xff]]], ["utf-8", [[0xe2]]], ["utf-16be", [[0]]]]) {+ await check(`fatal ${label} ${chunks[0][0]}`, async () => {+ try { await decode(label, { fatal: true }, chunks); return false; }+ catch (error) { return error instanceof TypeError; }+ });+ }+ await check("interleaved decoder states", async () => {+ const results = await Promise.all([+ decode("utf-8", {}, [[0xe2], [0x82, 0xac]]),+ decode("utf-16be", {}, [[0], [65]]),+ decode("windows-1252", {}, [[0x80]]),+ ]);+ return JSON.stringify(results.map(parts => parts.join(""))) === JSON.stringify(["\u20ac", "A", "\u20ac"]);+ });+ for (const throws of [true, false]) {+ await check(`subclass writable getter ${throws ? "throws" : "redirects"}`, async () => {+ let calls = 0;+ class Decoder extends TextDecoderStream {+ get writable() {+ calls++;+ if (throws) throw Error("author writable getter");+ return new WritableStream();+ }+ }+ const result = await decode("utf-8", {}, [[97, 98, 99]], Decoder);+ return calls === 0 && result.join("") === "abc";+ });+ }+ await check("public prototype writable getter", async () => {+ const descriptor = Object.getOwnPropertyDescriptor(TextDecoderStream.prototype, "writable");+ let calls = 0;+ Object.defineProperty(TextDecoderStream.prototype, "writable", { configurable: true, get() {+ calls++;+ throw Error("replaced writable getter");+ } });+ try {+ return (await decode("utf-8", {}, [[65]])).join("") === "A" && calls === 0;+ } finally { Object.defineProperty(TextDecoderStream.prototype, "writable", descriptor); }+ });+ await check("stream state ignores the public TextDecoder constructor", async () => {+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "TextDecoder");+ let calls = 0;+ Object.defineProperty(globalThis, "TextDecoder", { configurable: true, get() {+ calls++;+ throw Error("public TextDecoder getter");+ } });+ try {+ return (await decode("utf-8", {}, [[65]])).join("") === "A" && calls === 0;+ } finally { Object.defineProperty(globalThis, "TextDecoder", descriptor); }+ });+ return { checks };+};