Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(emulation): use native process-wide ICU defaults
ldm03bead428087c
diff --git a/Cargo.lock b/Cargo.lockindex f58675d22..cafa13de0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -635,16 +635,6 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"-[[package]]-name = "combine"-version = "4.6.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"-dependencies = [- "bytes",- "memchr",-]-[[package]]name = "compact-enc-det"version = "0.1.0"@@ -2062,12 +2052,6 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "84de9d95a6d2547d9b77ee3f25fa0ee32e3c3a6484d47a55adebc0439c077992"-[[package]]-name = "jiff-tzdb"-version = "0.1.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"-[[package]]name = "jobserver"version = "0.1.34"@@ -3132,7 +3116,6 @@ dependencies = [name = "moli-time"version = "0.1.0"dependencies = [- "temporal_rs","time",]@@ -5093,10 +5076,7 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52"dependencies = [- "combine",- "jiff-tzdb","tinystr",- "tzif","zerotrie","zerovec","zoneinfo64",@@ -5403,15 +5383,6 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"-[[package]]-name = "tzif"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a0376dfa52cce372f3b095010fd064fb850a5d8fbfd5be8b0ffa3d64eeab5a5d"-dependencies = [- "combine",-]-[[package]]name = "uluru"version = "3.1.0"diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.pyindex ffdf8c90f..fc5b6fed8 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_contracts.py@@ -32,7 +32,7 @@ def multi_page_contract_cases() -> tuple[MultiPageCase, ...]:_same_name_runtime_bindings_keep_session_authority,_session_detach_cancels_only_its_pending_await,_fetch_interception_is_session_local,- _network_and_emulation_profiles_are_target_local,+ _network_profiles_are_target_local_with_shared_native_environment,_closed_target_new_document_script_does_not_leak,_broadcast_channel_context_partition,_same_target_navigation_supersession,@@ -2091,7 +2091,7 @@ async def _fetch_interception_is_session_local(await close_context(context)-async def _network_and_emulation_profiles_are_target_local(+async def _network_profiles_are_target_local_with_shared_native_environment(browser: Any,fixture: str,results: list[dict[str, Any]],@@ -2111,20 +2111,25 @@ async def _network_and_emulation_profiles_are_target_local(session_a.send("Network.enable"),session_b.send("Network.enable"),)+ runtime_profile = """({+ userAgent: navigator.userAgent,+ language: navigator.language,+ locale: Intl.NumberFormat().resolvedOptions().locale,+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ })"""+ baseline_runtime = await page_a.evaluate(runtime_profile)profiles = ((session_a,"target-a","MultiPageAgentA/1.0","fr-FR",- "Europe/Paris",),(session_b,"target-b","MultiPageAgentB/1.0","ja-JP",- "Asia/Tokyo",),)await asyncio.gather(@@ -2141,18 +2146,16 @@ async def _network_and_emulation_profiles_are_target_local("acceptLanguage": language,},),- session.send(- "Emulation.setLocaleOverride",- {"locale": language},- ),- session.send(- "Emulation.setTimezoneOverride",- {"timezoneId": timezone},- ),)- for session, marker, user_agent, language, timezone in profiles+ for session, marker, user_agent, language in profiles))+ # Unlike request/navigator identity, native ICU defaults belong to the+ # renderer process. A single session owns them for both live targets.+ await session_a.send("Emulation.setLocaleOverride", {"locale": "fr-FR"})+ await session_a.send(+ "Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"}+ )tokens = ("multi-page-profile-a", "multi-page-profile-b")navigation_results = await asyncio.gather(@@ -2203,11 +2206,7 @@ async def _network_and_emulation_profiles_are_target_local(response = await session.send("Runtime.evaluate",{- "expression": """({- userAgent: navigator.userAgent,- language: navigator.language,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- })""",+ "expression": runtime_profile,"returnByValue": True,},)@@ -2239,18 +2238,20 @@ async def _network_and_emulation_profiles_are_target_local({"userAgent": "MultiPageAgentA/1.0","language": "fr-FR",+ "locale": "fr-FR","timezone": "Europe/Paris",},{"userAgent": "MultiPageAgentB/1.0","language": "ja-JP",- "timezone": "Asia/Tokyo",+ "locale": "fr-FR",+ "timezone": "Europe/Paris",},]assert_equal(runtime_profiles,expected_runtime_profiles,- "target-local Runtime emulation profiles",+ "target-local navigator identity with shared Date/Intl defaults",)assert_equal([@@ -2288,44 +2289,33 @@ async def _network_and_emulation_profiles_are_target_local(f"{fixture}/profile-result?token={detached_token}",)detached_runtime_profile, surviving_runtime_profile = await asyncio.gather(- page_a.evaluate(- """() => ({- userAgent: navigator.userAgent,- language: navigator.language,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- })"""- ),- page_b.evaluate(- """() => ({- userAgent: navigator.userAgent,- language: navigator.language,- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- })"""- ),+ page_a.evaluate(runtime_profile),+ page_b.evaluate(runtime_profile),)if detached_wire_profile.get("extraHeader") is not None:raise SmokeError("detached target retained its session-owned extra header: "f"{detached_wire_profile!r}")- if detached_runtime_profile == expected_runtime_profiles[0]:- raise SmokeError(- "detached target retained every session-owned emulation override: "- f"{detached_runtime_profile!r}"- )+ assert_equal(detached_runtime_profile, baseline_runtime, "owner detach restores defaults")assert_equal(surviving_runtime_profile,- expected_runtime_profiles[1],- "peer target emulation profile after owner detach",+ {+ **expected_runtime_profiles[1],+ "locale": baseline_runtime["locale"],+ "timezone": baseline_runtime["timezone"],+ },+ "peer keeps navigator identity while native process defaults restore",)record_contract(results,"multi_page_network_and_emulation_profile_ownership",contract=(- "Headers, user agent, locale, and timezone overrides are target-local; "- "detaching their owning session clears that target without mutating a peer."+ "Headers and navigator identity are target-local. Date/Intl defaults "+ "are process-wide; owner detach restores those defaults for every peer "+ "without changing peer network/navigator policy."),- source="Chromium Network and Emulation agent oracle",+ source="Chromium single-renderer ICU defaults and target-local Network policy",commands=["Network.setExtraHTTPHeaders","Emulation.setUserAgentOverride",diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.py b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.pyindex 47bd36416..06389143b 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/multi_page_isolation_contracts.py@@ -594,8 +594,8 @@ async def _same_target_session_policies_follow_chromium(contract=("Enabled Network sessions merge non-conflicting headers and select wire ""and live renderer identity by attachment order; locale/timezone use "- "exclusive claims, and detach "- "recomputes only the owning target."+ "process-wide exclusive claims. Detach restores native defaults "+ "process-wide while Network identity remains target-local."),source="Chromium NetworkHandler and InspectorEmulationAgent executable oracle",commands=[diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.pynew file mode 100644index 000000000..df3c08102--- /dev/null+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py@@ -0,0 +1,189 @@+from __future__ import annotations++import asyncio+import contextlib+from typing import Any++from ..assertions import SmokeError, assert_equal, record+++READ_DEFAULTS = """() => [+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone,+ new Date('2024-01-01T00:00:00Z').getTimezoneOffset(),+ new Date('2024-07-01T00:00:00Z').getTimezoneOffset()+]"""+++async def _expect_error(session: Any, method: str, params: dict[str, Any]) -> None:+ try:+ await session.send(method, params)+ except Exception as error:+ if "already in effect" in str(error):+ return+ raise SmokeError(f"{method} returned an unexpected error: {error}") from error+ raise SmokeError(f"{method} unexpectedly accepted a conflicting process claim")+++async def _worker_defaults(page: Any) -> list[Any]:+ # A request/reply boundary, not a sleep or retry that could hide a lost wake.+ return await asyncio.wait_for(page.evaluate("""async () => {+ const read = channel => new Promise((resolve, reject) => {+ channel.onmessage = event => resolve(event.data);+ channel.onmessageerror = reject;+ channel.postMessage('read');+ });+ return [await read(globalThis.environmentWorker),+ await read(globalThis.environmentShared.port)];+ }"""), timeout=10)+++async def _install_workers(page: Any) -> None:+ await page.evaluate("""read => {+ const source = 'const read = ' + read + ';' ++ 'self.onmessage = () => postMessage(read());' ++ 'self.onconnect = event => {' ++ ' const port = event.ports[0];' ++ ' port.onmessage = () => port.postMessage(read()); port.start(); };';+ const url = URL.createObjectURL(new Blob([source], {type: 'text/javascript'}));+ globalThis.environmentWorker = new Worker(url);+ globalThis.environmentShared = new SharedWorker(url, 'environment-defaults');+ environmentShared.port.start();+ globalThis.environmentDate = Date;+ globalThis.environmentIntl = Intl.DateTimeFormat;+ }""", READ_DEFAULTS)+++async def _override_while_peer_paused(control: Any, peer: Any) -> None:+ # A paused isolate cannot drain its ordinary foreground notification. The+ # nested Inspector command must see the new default before JS is resumed.+ await peer.send("Debugger.enable")+ paused = asyncio.get_running_loop().create_future()++ def on_paused(event: dict[str, Any]) -> None:+ if not paused.done():+ paused.set_result(event)++ peer.once("Debugger.paused", on_paused)+ evaluation = asyncio.create_task(peer.send("Runtime.evaluate", {+ "expression": "debugger;",+ }))+ try:+ event = await asyncio.wait_for(paused, timeout=10)+ await control.send("Emulation.setLocaleOverride", {"locale": "fr_FR"})+ await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})+ result = await peer.send("Debugger.evaluateOnCallFrame", {+ "callFrameId": event["callFrames"][0]["callFrameId"],+ "expression": f"({READ_DEFAULTS})()",+ "returnByValue": True,+ })+ assert_equal(result.get("result", {}).get("value"),+ ["fr-FR", "Europe/Paris", -60, -120],+ "paused isolate observes process defaults without resuming")+ finally:+ peer.remove_listener("Debugger.paused", on_paused)+ with contextlib.suppress(Exception):+ await asyncio.wait_for(peer.send("Debugger.resume"), timeout=5)+ with contextlib.suppress(Exception):+ await asyncio.wait_for(evaluation, timeout=5)+ await peer.send("Debugger.disable")+++async def run_process_environment_group(+ browser: Any, fixture: str, results: list[dict[str, Any]]+) -> None:+ """Moli's one-process contract (Chrome can split these Pages into processes).++ Configuration ownership is session-local; ICU defaults are process-wide.+ Test cross-context propagation, late isolates, both Worker kinds, navigation,+ failed/same-value claims, detach, target/context close, and exact restoration.+ """+ owner_context = await browser.new_context()+ peer_context = await browser.new_context()+ sessions: list[Any] = []+ try:+ owner = await owner_context.new_page()+ peer = await peer_context.new_page()+ await owner.goto(f"{fixture}/plain")+ await peer.goto(f"{fixture}/plain")+ control = await owner_context.new_cdp_session(owner)+ other = await peer_context.new_cdp_session(peer)+ sessions.extend([control, other])+ baseline = await peer.evaluate(READ_DEFAULTS)+ await _install_workers(peer)+ assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker baseline")+ record(results, "process_environment_workers_before_override")++ await _override_while_peer_paused(control, other)+ record(results, "process_environment_paused_inspector_refresh")+ expected = ["fr-FR", "Europe/Paris", -60, -120]+ assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "existing peer isolate")+ assert_equal(await _worker_defaults(peer), [expected, expected], "existing worker isolates")+ assert_equal(await peer.evaluate(+ "() => [Date === environmentDate, Intl.DateTimeFormat === environmentIntl]"+ ), [True, True], "native builtins are not replaced")+ record(results, "process_environment_existing_pages_and_workers")++ late = await peer_context.new_page()+ await late.goto(f"{fixture}/plain")+ assert_equal(await late.evaluate(READ_DEFAULTS), expected, "late isolate inherits ICU")+ await _install_workers(late)+ assert_equal(await _worker_defaults(late), [expected, expected], "late workers inherit ICU")+ await owner.reload()+ assert_equal(await owner.evaluate(READ_DEFAULTS), expected, "navigation keeps session claim")+ record(results, "process_environment_new_isolate_and_navigation")++ await _expect_error(other, "Emulation.setLocaleOverride", {"locale": "de_DE"})+ await _expect_error(other, "Emulation.setLocaleOverride", {"locale": ""})+ await _expect_error(other, "Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ # Chromium accepts the installed timezone without granting a second lease.+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "non-owner cannot clear")+ record(results, "process_environment_cross_target_exclusive_claims")++ await control.detach()+ sessions.remove(control)+ assert_equal(await peer.evaluate(READ_DEFAULTS), baseline, "detach restores host defaults")+ assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker restoration")+ assert_equal(await _worker_defaults(late), [baseline, baseline], "late worker restoration")+ await late.reload()+ assert_equal(await late.evaluate(READ_DEFAULTS), baseline, "no stale navigation replay")+ record(results, "process_environment_detach_restores_all_isolates")++ control = await owner_context.new_cdp_session(owner)+ sessions.append(control)+ await control.send("Emulation.setLocaleOverride", {"locale": "de_DE"})+ await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ expected = ["de-DE", "Asia/Shanghai", -480, -480]+ assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "new owner after release")+ await owner.close()+ sessions.remove(control)+ assert_equal(await peer.evaluate(READ_DEFAULTS), baseline, "target close releases claims")+ assert_equal(await _worker_defaults(peer), [baseline, baseline], "close restores workers")+ record(results, "process_environment_target_close_releases_claims")++ replacement = await owner_context.new_page()+ control = await owner_context.new_cdp_session(replacement)+ sessions.append(control)+ await control.send("Emulation.setLocaleOverride", {"locale": "de_DE"})+ await control.send("Emulation.setTimezoneOverride", {"timezoneId": "Asia/Shanghai"})+ assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "context owns live claims")+ await owner_context.close()+ sessions.remove(control)+ assert_equal(await peer.evaluate(READ_DEFAULTS), baseline, "context disposal releases claims")+ assert_equal(await _worker_defaults(peer), [baseline, baseline], "context disposal restores workers")+ record(results, "process_environment_context_disposal_releases_claims")++ await other.send("Emulation.setLocaleOverride", {"locale": "fr_FR"})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": "Europe/Paris"})+ await other.send("Emulation.setLocaleOverride", {"locale": ""})+ await other.send("Emulation.setTimezoneOverride", {"timezoneId": ""})+ assert_equal(await late.evaluate(READ_DEFAULTS), baseline, "explicit clear restores peers")+ record(results, "process_environment_explicit_clear")+ finally:+ for session in sessions:+ with contextlib.suppress(Exception):+ await session.detach()+ await owner_context.close()+ await peer_context.close()diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.pyindex 1783f985a..3fb4b364d 100644--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py@@ -40,6 +40,7 @@ from .groups.inspector_routing import run_inspector_routing_groupfrom .groups.iframe_input import run_iframe_input_groupfrom .groups.layout_screenshot import run_layout_screenshot_groupfrom .groups.locale_timezone_inputs import run_locale_timezone_inputs_group+from .groups.process_environment import run_process_environment_groupfrom .groups.multi_client import run_multi_client_groupfrom .groups.multi_context import run_multi_context_groupfrom .groups.multi_page import run_multi_page_group@@ -373,6 +374,12 @@ BROWSER_GROUPS: tuple[SmokeGroup, ...] = ("browser",run_locale_timezone_inputs_group,),+ SmokeGroup(+ "process-environment",+ "Process-wide locale/timezone claims, existing/new Pages and Workers, detach and close.",+ "browser",+ run_process_environment_group,+ ),SmokeGroup("multi-context","Cross-context owner-state routing and target isolation workflows.",diff --git a/moli-core/src/lib.rs b/moli-core/src/lib.rsindex 4670f9ff1..675a2518c 100644--- a/moli-core/src/lib.rs+++ b/moli-core/src/lib.rs@@ -18,6 +18,7 @@ pub mod testing;pub use moli_page_types as protocol_types;pub use moli_page_types::{LayoutPolicy, OptionalResourceFetchMask};+pub use moli_renderer_v8::ProcessEnvironmentOwner;pub use moli_renderer_v8::renderer_output_transport_channel;pub use moli_renderer_v8::{PageId, RendererBrowserContextRuntimeId, RendererDocumentLifecycleIdentity,diff --git a/moli-core/src/page/settings_support.rs b/moli-core/src/page/settings_support.rsindex 919846f4d..a0e2ad1c8 100644--- a/moli-core/src/page/settings_support.rs+++ b/moli-core/src/page/settings_support.rs@@ -246,57 +246,6 @@ impl Page {)}- pub async fn set_locale_override_async(&mut self, locale: Option<&str>) -> Result<()> {- self.dispatch_unit_page_command_async(- RendererPageCommand::SetLocaleOverride(locale.map(str::to_owned)),- "set locale override",- )- .await- }-- pub fn start_set_locale_override(&self, locale: Option<&str>) -> Result<PendingPageCommand> {- self.start_page_command(RendererPageCommand::SetLocaleOverride(- locale.map(str::to_owned),- ))- }-- pub fn finish_set_locale_override(&mut self, completion: CompletedPageCommand) -> Result<()> {- let reply = self.finish_page_command(completion);- expect_page_reply!(- reply,- "set locale override",- "a unit reply",- RendererPageReply::Unit => Ok(()),- )- }-- pub async fn set_timezone_override_async(&mut self, timezone: Option<&str>) -> Result<()> {- self.dispatch_unit_page_command_async(- RendererPageCommand::SetTimezoneOverride(timezone.map(str::to_owned)),- "set timezone override",- )- .await- }-- pub fn start_set_timezone_override(- &self,- timezone: Option<&str>,- ) -> Result<PendingPageCommand> {- self.start_page_command(RendererPageCommand::SetTimezoneOverride(- timezone.map(str::to_owned),- ))- }-- pub fn finish_set_timezone_override(&mut self, completion: CompletedPageCommand) -> Result<()> {- let reply = self.finish_page_command(completion);- expect_page_reply!(- reply,- "set timezone override",- "a unit reply",- RendererPageReply::Unit => Ok(()),- )- }-pub async fn set_script_execution_disabled_async(&mut self, disabled: bool) -> Result<()> {self.dispatch_unit_page_command_async(RendererPageCommand::SetScriptExecutionDisabled(disabled),diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rsindex 46ba7b367..642a39b28 100644--- a/moli-core/src/runtime/mod.rs+++ b/moli-core/src/runtime/mod.rs@@ -1286,8 +1286,6 @@ impl Browser {document_start_scripts,vec![],vec![],- None,- None,self.config.script_execution_disabled(),false,1.0,diff --git a/moli-core/src/runtime/navigation_engine.rs b/moli-core/src/runtime/navigation_engine.rsindex 055e2bb24..4c8613ada 100644--- a/moli-core/src/runtime/navigation_engine.rs+++ b/moli-core/src/runtime/navigation_engine.rs@@ -51,8 +51,6 @@ struct DocumentPageLoadOptions {pub runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,pub runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,pub extra_http_headers: Vec<(String, String)>,- pub locale_override: Option<String>,- pub timezone_override: Option<String>,pub script_execution_disabled: bool,pub bypass_content_security_policy: bool,pub cpu_throttling_rate: f64,@@ -202,8 +200,6 @@ pub struct PreparedDocumentPageCommitConfiguration {pub runtime_isolated_worlds: Vec<RuntimeIsolatedWorldDefinition>,pub permission_overrides: Vec<PermissionOverrideRegistration>,pub extra_http_headers: Vec<(String, String)>,- pub locale_override: Option<String>,- pub timezone_override: Option<String>,pub script_execution_disabled: bool,pub bypass_content_security_policy: bool,pub cpu_throttling_rate: f64,@@ -265,8 +261,6 @@ impl PreparedDocumentPage {runtime_isolated_worlds: configuration.runtime_isolated_worlds,permission_overrides: configuration.permission_overrides,extra_http_headers: configuration.extra_http_headers,- locale_override: configuration.locale_override,- timezone_override: configuration.timezone_override,script_execution_disabled: configuration.script_execution_disabled,bypass_content_security_policy: configuration.bypass_content_security_policy,cpu_throttling_rate: configuration.cpu_throttling_rate,@@ -1147,8 +1141,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1182,8 +1174,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy: false,cpu_throttling_rate,@@ -1213,8 +1203,6 @@ impl NavigationEngine {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1233,8 +1221,6 @@ impl NavigationEngine {runtime_bindings,Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,cpu_throttling_rate,emulated_media,@@ -1260,8 +1246,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1287,8 +1271,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,cpu_throttling_rate,emulated_media,@@ -1322,8 +1304,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -1357,8 +1337,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -1388,8 +1366,6 @@ impl NavigationEngine {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1413,8 +1389,6 @@ impl NavigationEngine {runtime_bindings,Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -1446,8 +1420,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -1479,8 +1451,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -1523,8 +1493,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -1561,8 +1529,6 @@ impl NavigationEngine {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -1596,8 +1562,6 @@ impl NavigationEngine {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1623,8 +1587,6 @@ impl NavigationEngine {runtime_bindings,Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -1657,8 +1619,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -1692,8 +1652,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -1728,8 +1686,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1765,8 +1721,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -1808,8 +1762,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -1854,8 +1806,6 @@ impl NavigationEngine {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -1896,8 +1846,6 @@ impl NavigationEngine {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1922,8 +1870,6 @@ impl NavigationEngine {runtime_bindings,Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,cpu_throttling_rate,emulated_media,@@ -1958,8 +1904,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -1994,8 +1938,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,cpu_throttling_rate,emulated_media,@@ -2031,8 +1973,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -2069,8 +2009,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -2130,8 +2068,6 @@ impl NavigationEngine {options.document_start_scripts,options.runtime_bindings,options.extra_http_headers,- options.locale_override,- options.timezone_override,options.script_execution_disabled,options.bypass_content_security_policy,options.cpu_throttling_rate,@@ -2185,8 +2121,6 @@ impl NavigationEngine {options.runtime_bindings,options.runtime_inspector_session_restore_snapshots,options.extra_http_headers,- options.locale_override,- options.timezone_override,options.script_execution_disabled,options.bypass_content_security_policy,options.cpu_throttling_rate,@@ -2247,8 +2181,6 @@ impl NavigationEngine {runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -2286,8 +2218,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -2318,8 +2248,6 @@ impl NavigationEngine {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::page::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: EmulatedMediaOverrides,@@ -2353,8 +2281,6 @@ impl NavigationEngine {runtime_bindings,runtime_inspector_session_restore_snapshots: Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy: false,cpu_throttling_rate,diff --git a/moli-core/src/runtime/tests.rs b/moli-core/src/runtime/tests.rsindex 948ec1d4b..3fcd9c053 100644--- a/moli-core/src/runtime/tests.rs+++ b/moli-core/src/runtime/tests.rs@@ -1541,8 +1541,6 @@ async fn navigation_engine_keeps_network_runtime_when_web_storage_changes() -> RVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -1578,8 +1576,6 @@ async fn navigation_engine_keeps_network_runtime_when_web_storage_changes() -> RVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),diff --git a/moli-protocol-server/src/protocol_server/tests/bidi.rs b/moli-protocol-server/src/protocol_server/tests/bidi.rsindex 18d81f87e..feed31254 100644--- a/moli-protocol-server/src/protocol_server/tests/bidi.rs+++ b/moli-protocol-server/src/protocol_server/tests/bidi.rs@@ -11909,10 +11909,10 @@ async fn websocket_bidi_emulation_user_context_overrides_apply_to_later_http_nav}#[tokio::test]-async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_precedence() {- // Ported from Chromium/WPT- // webdriver/tests/bidi/emulation/set_locale_override/{locale,contexts,user_contexts}.py- // and set_timezone_override/{timezone,contexts,user_contexts}.py.+async fn websocket_bidi_environment_uses_process_claims_instead_of_per_context_precedence() {+ // One Moli renderer process shares native ICU defaults. User contexts+ // cannot create independent Date/Intl environments; conflicting ownership+ // must fail without mutating or staging a later navigation policy.let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;let (mut socket, default_context_id) = bidi_session_with_context(cdp_addr).await;@@ -11975,6 +11975,29 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre.expect("created userContext tab").to_owned();+ let batch = send_bidi_command(+ &mut socket,+ 600,+ "emulation.setLocaleOverride",+ json!({"contexts": [default_context_id, user_context_tab_id], "locale": "fr-FR"}),+ )+ .await;+ assert_bidi_error(+ &batch,+ "unsupported operation",+ "multi-owner claim cannot partially commit",+ );+ assert_eq!(+ bidi_string_script_value(+ &mut socket,+ 601,+ &default_context_id,+ "Intl.DateTimeFormat().resolvedOptions().locale"+ )+ .await,+ default_locale+ );+let set_user_context_locale = send_bidi_command(&mut socket,7,@@ -12025,8 +12048,8 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre"Intl.DateTimeFormat().resolvedOptions().locale").await,- default_locale,- "non-default userContext locale should not affect default contexts"+ user_context_locale,+ "native locale is shared across every context in this process");assert_eq!(bidi_string_script_value(@@ -12036,8 +12059,8 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre"Intl.DateTimeFormat().resolvedOptions().timeZone").await,- default_timezone,- "non-default userContext timezone should not affect default contexts"+ user_context_timezone,+ "native timezone is shared across every context in this process");let set_context_locale = send_bidi_command(@@ -12050,7 +12073,11 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre}),).await;- assert_eq!(set_context_locale["type"], json!("success"));+ assert_bidi_error(+ &set_context_locale,+ "invalid argument",+ "another owner holds the process claim",+ );let set_context_timezone = send_bidi_command(&mut socket,14,@@ -12061,7 +12088,11 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre}),).await;- assert_eq!(set_context_timezone["type"], json!("success"));+ assert_bidi_error(+ &set_context_timezone,+ "invalid argument",+ "another owner holds the process claim",+ );assert_eq!(bidi_string_script_value(&mut socket,@@ -12070,7 +12101,7 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre"Intl.DateTimeFormat().resolvedOptions().locale").await,- context_locale+ user_context_locale);assert_eq!(bidi_string_script_value(@@ -12080,7 +12111,7 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre"Intl.DateTimeFormat().resolvedOptions().timeZone").await,- context_timezone+ user_context_timezone);let reset_context_locale = send_bidi_command(@@ -12093,7 +12124,11 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre}),).await;- assert_eq!(reset_context_locale["type"], json!("success"));+ assert_bidi_error(+ &reset_context_locale,+ "invalid argument",+ "another owner holds the process claim",+ );let reset_context_timezone = send_bidi_command(&mut socket,18,@@ -12114,7 +12149,7 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre).await,user_context_locale,- "context locale reset should reveal userContext locale override"+ "a rejected non-owner reset must preserve the process locale");assert_eq!(bidi_string_script_value(@@ -12125,7 +12160,7 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_pre).await,user_context_timezone,- "context timezone reset should reveal userContext timezone override"+ "a non-owner reset must preserve the process timezone");let reset_user_context_locale = send_bidi_command(@@ -12171,6 +12206,56 @@ async fn websocket_bidi_emulation_set_locale_and_timezone_override_match_wpt_predefault_timezone);+ // Disposal must release process claims even while another context stays+ // alive; no explicit reset or navigation is necessary for that peer.+ for (id, method, params) in [+ (+ 25,+ "emulation.setLocaleOverride",+ json!({+ "userContexts": [user_context_id], "locale": user_context_locale+ }),+ ),+ (+ 26,+ "emulation.setTimezoneOverride",+ json!({+ "userContexts": [user_context_id], "timezone": user_context_timezone+ }),+ ),+ ] {+ let response = send_bidi_command(&mut socket, id, method, params).await;+ assert_eq!(response["type"], json!("success"));+ }+ let removed = send_bidi_command(+ &mut socket,+ 27,+ "browser.removeUserContext",+ json!({"userContext": user_context_id}),+ )+ .await;+ assert_eq!(removed["type"], json!("success"));+ assert_eq!(+ bidi_string_script_value(+ &mut socket,+ 28,+ &default_context_id,+ "Intl.DateTimeFormat().resolvedOptions().locale",+ )+ .await,+ default_locale+ );+ assert_eq!(+ bidi_string_script_value(+ &mut socket,+ 29,+ &default_context_id,+ "Intl.DateTimeFormat().resolvedOptions().timeZone",+ )+ .await,+ default_timezone+ );+let _ = socket.close(None).await;protocol_server.abort();}@@ -18703,6 +18788,14 @@ async fn websocket_bidi_emulation_locale_timezone_invalid_parameters_match_wpt_e"emulation.setTimezoneOverride",json!({"contexts": [context_id.clone()], "timezone": "Europe/Bielefeld"}),),+ (+ "emulation.setTimezoneOverride",+ json!({"contexts": [context_id.clone()], "timezone": "America/Not_A_Zone"}),+ ),+ (+ "emulation.setTimezoneOverride",+ json!({"contexts": [context_id.clone()], "timezone": "Z"}),+ ),("emulation.setTimezoneOverride",json!({"contexts": [context_id.clone()], "timezone": "+1:00"}),diff --git a/moli-protocol-webdriver-bidi/src/commands.rs b/moli-protocol-webdriver-bidi/src/commands.rsindex eba8765a4..be4ee7b72 100644--- a/moli-protocol-webdriver-bidi/src/commands.rs+++ b/moli-protocol-webdriver-bidi/src/commands.rs@@ -2953,12 +2953,9 @@ fn normalized_bidi_timezone(timezone: String) -> Result<String, BidiError> {"invalid timezone",));}- if !is_valid_named_timezone(&timezone) {- return Err(BidiError::new(- BidiErrorCode::InvalidArgument,- "invalid timezone",- ));- }+ // This adapter only normalizes BiDi syntax. The process environment+ // controller validates names against the same ICU database that Date/Intl+ // use. System zoneinfo and region heuristics can disagree with that data.Ok(timezone)}@@ -2966,51 +2963,6 @@ fn is_timezone_name_char(value: char) -> bool {value.is_ascii_alphanumeric() || matches!(value, '_' | '-' | '+' | '/')}-fn is_valid_named_timezone(timezone: &str) -> bool {- if matches!(timezone, "UTC" | "Etc/UTC" | "GMT") {- return true;- }- if timezone.starts_with('/')- || timezone.ends_with('/')- || timezone.contains("//")- || timezone.ends_with("/Bielefeld")- {- return false;- }- if let Some(valid) = timezone_exists_in_system_zoneinfo(timezone) {- return valid;- }- [- "Africa/",- "America/",- "Antarctica/",- "Arctic/",- "Asia/",- "Atlantic/",- "Australia/",- "Europe/",- "Indian/",- "Pacific/",- "Etc/",- "Brazil/",- "Canada/",- "Chile/",- "Mexico/",- "US/",- ]- .iter()- .any(|prefix| timezone.starts_with(prefix))-}--fn timezone_exists_in_system_zoneinfo(timezone: &str) -> Option<bool> {- let root = std::path::Path::new("/usr/share/zoneinfo");- if !root.is_dir() {- return None;- }- let path = root.join(timezone);- path.is_file().then_some(true)-}-fn is_timezone_offset_string(timezone: &str) -> bool {let bytes = timezone.as_bytes();bytes.len() == 6diff --git a/moli-protocol-webdriver-bidi/src/tests.rs b/moli-protocol-webdriver-bidi/src/tests.rsindex e564aa8f9..c2ff4779b 100644--- a/moli-protocol-webdriver-bidi/src/tests.rs+++ b/moli-protocol-webdriver-bidi/src/tests.rs@@ -12345,7 +12345,7 @@ fn maps_emulation_set_geolocation_override_reset_and_error_to_distinct_shared_st}#[test]-fn accepts_valid_iana_timezone_regions_for_emulation_set_timezone_override() {+fn timezone_adapter_defers_name_validation_to_native_environment_controller() {for timezone in ["Africa/Cairo","Pacific/Auckland",@@ -12355,6 +12355,11 @@ fn accepts_valid_iana_timezone_regions_for_emulation_set_timezone_override() {"Arctic/Longyearbyen","Antarctica/McMurdo","Etc/GMT+5",+ "CET",+ "Japan",+ "Europe/Bielefeld",+ "America/Not_A_Zone",+ "Z",] {let command = super::parse_bidi_command(json!({"id": 29,@@ -12552,11 +12557,9 @@ fn rejects_chromium_wpt_invalid_emulation_set_timezone_override_params() {"timezone": "Asia/Tokyo"}),json!({"contexts": ["TARGET-1"], "timezone": ""}),- json!({"contexts": ["TARGET-1"], "timezone": "Europe/Bielefeld"}),json!({"contexts": ["TARGET-1"], "timezone": "+1:00"}),json!({"contexts": ["TARGET-1"], "timezone": "GMT+05:00"}),json!({"contexts": ["TARGET-1"], "timezone": "UTC+05:00"}),- json!({"contexts": ["TARGET-1"], "timezone": "Z"}),] {assert_bidi_adapter_invalid("emulation.setTimezoneOverride", params);}diff --git a/moli-protocol/src/conn/browser_context/emulation_owner.rs b/moli-protocol/src/conn/browser_context/emulation_owner.rsindex 24e138fa2..b91fc184d 100644--- a/moli-protocol/src/conn/browser_context/emulation_owner.rs+++ b/moli-protocol/src/conn/browser_context/emulation_owner.rs@@ -107,21 +107,23 @@ impl TargetSessionOwnerMut<'_> {&mut self,locale_override: Option<String>,fallback_identity: &moli_browser_profile::BrowserIdentityProfile,- ) -> bool {+ ) -> Result<(), &'static str> {self.mutate_page_state(|state, _session_key| {- state.set_base_locale_override(locale_override.clone());+ state.set_base_locale_override(locale_override.clone())?;state.network_policy.set_base_accept_language_override(locale_override, fallback_identity);- });- true+ Ok(())+ })}- fn set_base_timezone_override(&mut self, timezone_override: Option<String>) -> bool {+ fn set_base_timezone_override(+ &mut self,+ timezone_override: Option<String>,+ ) -> Result<(), &'static str> {self.mutate_page_state(|state, _session_key| {- state.set_base_timezone_override(timezone_override);- });- true+ state.set_base_timezone_override(timezone_override)+ })}}@@ -185,21 +187,21 @@ impl CdpConnection {&mut self,owner: &crate::conn::CommandOwnerScope,locale_override: Option<String>,- ) -> bool {+ ) -> Result<(), &'static str> {let fallback_identity = self.base_browser_identity.clone();self.target_session_owner_mut_for_owner(owner)- .is_some_and(|mut owner| {- owner.set_base_locale_override(locale_override, &fallback_identity)- })+ .ok_or("BrowserContextNotLoaded")?+ .set_base_locale_override(locale_override, &fallback_identity)}pub(crate) fn set_base_timezone_override_for_owner(&mut self,owner: &crate::conn::CommandOwnerScope,timezone_override: Option<String>,- ) -> bool {+ ) -> Result<(), &'static str> {self.target_session_owner_mut_for_owner(owner)- .is_some_and(|mut owner| owner.set_base_timezone_override(timezone_override))+ .ok_or("BrowserContextNotLoaded")?+ .set_base_timezone_override(timezone_override)}pub(crate) fn emit_touch_events_for_mouse_for_session_owner(diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rsindex 2b45e5cf4..b2be08fb2 100644--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs@@ -164,8 +164,6 @@ pub(crate) struct TargetNavigationLoadInputs {pub(crate) runtime_inspector_session_restore_snapshots:Vec<RendererInspectorSessionRestoreSnapshot>,pub(crate) extra_http_headers: Vec<(String, String)>,- pub(crate) locale_override: Option<String>,- pub(crate) timezone_override: Option<String>,pub(crate) script_execution_disabled: bool,pub(crate) bypass_content_security_policy: bool,pub(crate) cpu_throttling_rate: f64,@@ -317,14 +315,6 @@ impl TargetNavigationLoadInputs {.runtime_inspector_restore_snapshots(),extra_http_headers: browser_context.merged_extra_headers_for_target_policy(effective_policy.extra_headers()),- locale_override: effective_policy- .locale_override()- .map(str::to_owned)- .or_else(|| browser_context.default_locale_override.clone()),- timezone_override: effective_policy- .timezone_override()- .map(str::to_owned)- .or_else(|| browser_context.default_timezone_override.clone()),script_execution_disabled: page_state.effective_emulation_state.script_execution_disabled,@@ -368,8 +358,6 @@ impl TargetNavigationLoadInputs {browser_context.effective_active_tls_verify_host_override();inputs.document_start_scripts = browser_context.default_document_start_script_descriptors();inputs.extra_http_headers = browser_context.effective_extra_headers();- inputs.locale_override = browser_context.effective_active_locale_override_owned();- inputs.timezone_override = browser_context.effective_active_timezone_override_owned();inputs.viewport_surface = browser_context.default_emulated_device_metrics.as_ref()@@ -399,8 +387,6 @@ impl TargetNavigationLoadInputs {runtime_bindings: Vec::new(),runtime_inspector_session_restore_snapshots: Vec::new(),extra_http_headers: Vec::new(),- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -2938,9 +2924,6 @@ mod tests {#[test]fn target_session_owner_mut_prepares_background_navigation_request_preflight() {let mut background = BrowserContext::new_with_page_for_test("BID-background", "TID-active");- background- .active_page_target_mut()- .set_base_locale_override(Some("zh-CN".to_owned()));background.active_page_target_mut().network_policy@@ -3105,9 +3088,6 @@ mod tests {#[test]fn target_session_owner_ref_snapshots_background_navigation_load_inputs() {let mut background = BrowserContext::new_with_page_for_test("BID-background", "TID-active");- background- .active_page_target_mut()- .set_base_locale_override(Some("zh-CN".to_owned()));background.insert_page_target_host(crate::conn::PageTargetHost::with_url("TID-background".to_owned(),Some("SID-background".to_owned()),@@ -3117,8 +3097,6 @@ mod tests {let state = background.background_target_mut("TID-background").expect("background target must exist");- state.set_base_locale_override(Some("fr-FR".to_owned()));- state.set_base_timezone_override(Some("Europe/Paris".to_owned()));state.http_proxy_override = Some("http://proxy.example:8080".to_owned());state.http_no_proxy_override = Some("localhost,127.0.0.1".to_owned());state.tls_verify_host_override = Some(false);@@ -3213,8 +3191,6 @@ mod tests {.iter().all(|(name, _)| !name.eq_ignore_ascii_case("accept-language")));- assert_eq!(inputs.locale_override.as_deref(), Some("fr-FR"));- assert_eq!(inputs.timezone_override.as_deref(), Some("Europe/Paris"));assert_eq!(inputs.browser_identity_overridediff --git a/moli-protocol/src/conn/dispatch_tests.rs b/moli-protocol/src/conn/dispatch_tests.rsindex dd7f1d04a..2a1ac334b 100644--- a/moli-protocol/src/conn/dispatch_tests.rs+++ b/moli-protocol/src/conn/dispatch_tests.rs@@ -8287,9 +8287,6 @@ async fn pending_emulation_timezone_keeps_background_owner_route_across_completi.replace_loaded_page(Some(background_page));conn.install_browser_context_fixture_for_test(browser_context);- let background_route = conn- .target_session_route_for_target_id("TID-emulation-timezone-background")- .expect("background target route");let background_session =attach_page_session_for_test(&mut conn, "TID-emulation-timezone-background").await;let raw = serde_json::to_string(&json!({@@ -8299,17 +8296,7 @@ async fn pending_emulation_timezone_keeps_background_owner_route_across_completi"sessionId": background_session})).unwrap();- let pending = match conn.start_command_dispatch(&raw) {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Emulation.setTimezoneOverride should update the live background page: {:?}",- outcome.into_parts().0- )- }- };-- let messages = complete_command_task_for_test(&mut conn, *pending).await;+ let messages = complete_messages(conn.start_command_dispatch(&raw));assert_eq!(messages,@@ -8337,14 +8324,22 @@ async fn pending_emulation_timezone_keeps_background_owner_route_across_completi"background timezone","background Emulation completion should preserve the captured owner");- let background_inputs = conn.navigation_load_inputs_for_owner(- &crate::conn::CommandOwnerScope::for_route(background_route.clone()),+ assert_eq!(+ browser_context+ .background_target("TID-emulation-timezone-background")+ .unwrap()+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),+ Some("UTC"));- assert_eq!(background_inputs.timezone_override.as_deref(), Some("UTC"));- assert!(- conn.navigation_load_inputs_for_session_owner(None)- .timezone_override- .is_none()+ assert_eq!(+ browser_context+ .active_page_target()+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),+ None);}@@ -8371,16 +8366,8 @@ async fn command_dispatch_completes_live_emulation_locale_without_legacy_fallbac"params": { "locale": "fr-FR" }})).unwrap();- let pending = match conn.start_command_dispatch(&raw) {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(_) => {- panic!("live Emulation.setLocaleOverride should update the live page")- }- };- let completed = pending.wait().await;- let step = conn.complete_pending_command_dispatch(completed).await;assert_eq!(- complete_messages(step),+ complete_messages(conn.start_command_dispatch(&raw)),vec![json!({ "id": 685, "result": {} })]);}diff --git a/moli-protocol/src/conn/page_state/page_targets.rs b/moli-protocol/src/conn/page_state/page_targets.rsindex b80d33159..9b10edbf9 100644--- a/moli-protocol/src/conn/page_state/page_targets.rs+++ b/moli-protocol/src/conn/page_state/page_targets.rs@@ -395,14 +395,6 @@ impl BrowserContext {let effective_headers =self.merged_extra_headers_for_target_policy(effective.extra_headers());- let effective_locale = effective- .locale_override()- .map(str::to_owned)- .or_else(|| self.default_locale_override.clone());- let effective_timezone = effective- .timezone_override()- .map(str::to_owned)- .or_else(|| self.default_timezone_override.clone());let page = self.page_target_mut(target_id).and_then(|target| target.runtime_slot.loaded_page_mut());@@ -423,20 +415,8 @@ impl BrowserContext {)})?;}- if delta.locale {- page.set_locale_override_async(effective_locale.as_deref())- .await- .map_err(|error| {- anyhow::anyhow!("failed to restore detached session locale: {error}")- })?;- }- if delta.timezone {- page.set_timezone_override_async(effective_timezone.as_deref())- .await- .map_err(|error| {- anyhow::anyhow!("failed to restore detached session timezone: {error}")- })?;- }+ // Session disposal already released its process-wide ICU claims.+ // Do not recreate them on the Page while restoring target-local policy.Ok(browser_identity_changed)}@@ -462,14 +442,6 @@ impl BrowserContext {.page_target(target_id).expect("disposing page target must remain registered");let effective_policy = target.effective_policy();- let effective_locale = effective_policy- .locale_override()- .map(str::to_owned)- .or_else(|| self.default_locale_override.clone());- let effective_timezone = effective_policy- .timezone_override()- .map(str::to_owned)- .or_else(|| self.default_timezone_override.clone());let surface_script = if is_active {self.generated_surface_override_script_for_active_target()} else {@@ -503,22 +475,6 @@ impl BrowserContext {anyhow::anyhow!("failed to clear page script execution disabled state: {error}")});}- if let Err(error) = page- .set_locale_override_async(effective_locale.as_deref())- .await- {- first_error.get_or_insert_with(|| {- anyhow::anyhow!("failed to restore page locale: {error}")- });- }- if let Err(error) = page- .set_timezone_override_async(effective_timezone.as_deref())- .await- {- first_error.get_or_insert_with(|| {- anyhow::anyhow!("failed to restore page timezone: {error}")- });- }if let Err(error) = page.set_navigator_overrides_async(&navigator_overrides).awaitdiff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rsindex c2af0b434..ad135ab05 100644--- a/moli-protocol/src/conn/runtime_load.rs+++ b/moli-protocol/src/conn/runtime_load.rs@@ -1377,8 +1377,6 @@ async fn build_navigation_from_streaming_raw_response_with_engine_async(.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -1449,8 +1447,6 @@ async fn build_navigation_from_streaming_raw_response_with_engine_async(.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -1559,8 +1555,6 @@ impl CdpConnection {runtime_isolated_worlds: Vec::new(),permission_overrides: load_inputs.permission_overrides,extra_http_headers: load_inputs.extra_http_headers,- locale_override: load_inputs.locale_override,- timezone_override: load_inputs.timezone_override,script_execution_disabled: load_inputs.script_execution_disabled,bypass_content_security_policy: load_inputs.bypass_content_security_policy,cpu_throttling_rate: load_inputs.cpu_throttling_rate,@@ -1687,8 +1681,6 @@ impl CdpConnection {.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -1947,8 +1939,6 @@ impl CdpConnection {.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -2904,8 +2894,6 @@ impl CdpConnection {.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -3198,8 +3186,6 @@ impl CdpConnection {.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -3832,8 +3818,6 @@ async fn prepare_captured_document_response_with_engine_async(.runtime_inspector_session_restore_snapshots.clone(),load_inputs.extra_http_headers.clone(),- load_inputs.locale_override.clone(),- load_inputs.timezone_override.clone(),load_inputs.script_execution_disabled,load_inputs.bypass_content_security_policy,load_inputs.cpu_throttling_rate,@@ -3918,12 +3902,8 @@ async fn apply_navigation_load_input_overrides_async(if mode == NavigationLoadInputOverrideMode::FreshlyBuiltPage {return Ok(());}- page.set_locale_override_async(load_inputs.locale_override.as_deref())- .await- .map_err(|error| format!("failed to apply page locale override: {error}"))?;- page.set_timezone_override_async(load_inputs.timezone_override.as_deref())- .await- .map_err(|error| format!("failed to apply page timezone override: {error}"))?;+ // Locale/timezone claims belong to the protocol configuration owner, not+ // the new Document. Native isolates inherit the process default at entry.page.set_script_execution_disabled_async(load_inputs.script_execution_disabled).await.map_err(|error| format!("failed to apply page script execution override: {error}"))?;diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rsindex d7d3fe77d..3a115c1d9 100644--- a/moli-protocol/src/conn/state/browser_context.rs+++ b/moli-protocol/src/conn/state/browser_context.rs@@ -64,8 +64,7 @@ pub struct BrowserContext {pub(crate) default_extra_headers: Vec<(String, String)>,pub(crate) global_extra_headers: Vec<(String, String)>,default_browser_identity: super::BaseBrowserIdentityOverrideState,- pub(crate) default_locale_override: Option<String>,- pub(crate) default_timezone_override: Option<String>,+ environment_owner: moli_core::ProcessEnvironmentOwner,pub(crate) default_network_conditions: Option<EmulatedNetworkConditions>,pub(crate) default_geolocation_override: Option<EmulatedGeolocationOverrideState>,pub(crate) global_network_conditions: Option<EmulatedNetworkConditions>,@@ -516,8 +515,7 @@ impl BrowserContext {default_extra_headers: Vec::new(),global_extra_headers: Vec::new(),default_browser_identity: super::BaseBrowserIdentityOverrideState::default(),- default_locale_override: None,- default_timezone_override: None,+ environment_owner: Default::default(),default_network_conditions: None,default_geolocation_override: None,global_network_conditions: None,@@ -1549,10 +1547,19 @@ impl BrowserContext {&mut self,locale: Option<String>,fallback: &moli_browser_profile::BrowserIdentityProfile,- ) {- self.default_locale_override = locale.clone();+ ) -> Result<(), &'static str> {+ self.environment_owner.set_locale(locale.as_deref())?;self.default_browser_identity.set_accept_language(locale, fallback);+ Ok(())+ }++ pub(crate) fn set_default_timezone_override(+ &mut self,+ timezone: Option<String>,+ ) -> Result<(), &'static str> {+ self.environment_owner.set_timezone(timezone.as_deref())?;+ Ok(())}#[cfg(test)]@@ -1563,24 +1570,6 @@ impl BrowserContext {self.default_browser_identity.replace_profile(identity);}- pub(crate) fn effective_active_locale_override_owned(&self) -> Option<String> {- self.page_targets- .active()- .and_then(|host| host.effective_policy().locale_override().map(str::to_owned))- .or_else(|| self.default_locale_override.clone())- }-- pub(crate) fn effective_active_timezone_override_owned(&self) -> Option<String> {- self.page_targets- .active()- .and_then(|host| {- host.effective_policy()- .timezone_override()- .map(str::to_owned)- })- .or_else(|| self.default_timezone_override.clone())- }-pub(crate) fn effective_active_network_conditions(&self) -> Option<EmulatedNetworkConditions> {self.page_targets.active()@@ -1640,20 +1629,6 @@ impl BrowserContext {.is_some_and(|conditions| !conditions.navigator_online())}- pub(crate) fn effective_locale_override_for_target_owned(- &self,- target_id: &str,- ) -> Option<String> {- self.page_target(target_id)- .and_then(|state| {- state- .effective_policy()- .locale_override()- .map(str::to_owned)- })- .or_else(|| self.default_locale_override.clone())- }-pub(crate) fn has_active_target(&self) -> bool {self.page_targets.active().is_some()}diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rsindex 3bb5a75f6..7a9371220 100644--- a/moli-protocol/src/conn/state/devtools_session.rs+++ b/moli-protocol/src/conn/state/devtools_session.rs@@ -63,6 +63,7 @@ pub(crate) struct DevToolsSessionRegistry {primary_session_id: Option<String>,states: BTreeMap<DevToolsSessionKey, DevToolsSessionState>,attached_order: Vec<String>,+ environment_owners: BTreeMap<DevToolsSessionKey, moli_core::ProcessEnvironmentOwner>,}impl Default for DevToolsSessionRegistry {@@ -74,6 +75,7 @@ impl Default for DevToolsSessionRegistry {DevToolsSessionState::default(),)]),attached_order: Vec::new(),+ environment_owners: BTreeMap::new(),}}}@@ -148,6 +150,7 @@ impl DevToolsSessionRegistry {pub(crate) fn remove_attached(&mut self, session_id: &str) -> Option<DevToolsSessionState> {let key = DevToolsSessionKey::Attached(session_id.to_owned());+ self.release_environment_owner(&key);let removed = self.states.remove(&key);if removed.is_some() {self.attached_order@@ -172,6 +175,7 @@ impl DevToolsSessionRegistry {return None;}self.primary_session_id = None;+ self.release_environment_owner(session_key);Some(std::mem::take(self.primary_mut()))}DevToolsSessionKey::Attached(attached_session_id)@@ -333,19 +337,15 @@ impl DevToolsSessionRegistry {session_key: &DevToolsSessionKey,locale_override: Option<String>,) -> Result<(), &'static str> {- let current_session_owns_override = self- .states+ // Admission is process-wide and precedes publishing session policy.+ // A rejected claim must not be replayed later during navigation.+ let owner = self+ .environment_owners.get(session_key)- .is_some_and(|state| state.emulation_session_state.locale_override.is_some());- let another_session_owns_override = self.states.iter().any(|(candidate, state)| {- candidate != session_key && state.emulation_session_state.locale_override.is_some()- });- if !current_session_owns_override && another_session_owns_override {- return Err("Another locale override is already in effect");- }- self.ensure_session(session_key)- .emulation_session_state- .locale_override = locale_override;+ .cloned()+ .unwrap_or_default();+ owner.set_locale(locale_override.as_deref())?;+ self.retain_environment_owner(session_key, owner);Ok(())}@@ -354,35 +354,43 @@ impl DevToolsSessionRegistry {session_key: &DevToolsSessionKey,timezone_override: Option<String>,) -> Result<(), &'static str> {- let current_session_owns_override = self- .states+ let owner = self+ .environment_owners.get(session_key)- .is_some_and(|state| state.emulation_session_state.timezone_override.is_some());- let another_session_owns_override = self.states.iter().any(|(candidate, state)| {- candidate != session_key && state.emulation_session_state.timezone_override.is_some()- });- if timezone_override.is_some()- && !current_session_owns_override- && another_session_owns_override- {- return Err("Timezone override is already in effect");- }- self.ensure_session(session_key)- .emulation_session_state- .timezone_override = timezone_override;+ .cloned()+ .unwrap_or_default();+ owner.set_timezone(timezone_override.as_deref())?;+ self.retain_environment_owner(session_key, owner);Ok(())}- pub(crate) fn effective_locale_override(&self) -> Option<&str> {- self.states+ fn retain_environment_owner(+ &mut self,+ key: &DevToolsSessionKey,+ owner: moli_core::ProcessEnvironmentOwner,+ ) {+ // Same-timezone non-owner success creates no retained state. There is+ // no second copy of the claim in an Emulation snapshot or navigation.+ if owner.has_override() {+ self.ensure_session(key);+ self.environment_owners.insert(key.clone(), owner);+ } else {+ self.environment_owners.remove(key);+ }+ }++ #[cfg(test)]+ pub(crate) fn effective_locale_override(&self) -> Option<String> {+ self.environment_owners.values()- .find_map(|state| state.emulation_session_state.locale_override.as_deref())+ .find_map(moli_core::ProcessEnvironmentOwner::locale)}- pub(crate) fn effective_timezone_override(&self) -> Option<&str> {- self.states+ #[cfg(test)]+ pub(crate) fn effective_timezone_override(&self) -> Option<String> {+ self.environment_owners.values()- .find_map(|state| state.emulation_session_state.timezone_override.as_deref())+ .find_map(moli_core::ProcessEnvironmentOwner::timezone)}pub(crate) fn clear_network_state(&mut self, session_key: &DevToolsSessionKey) {@@ -392,11 +400,16 @@ impl DevToolsSessionRegistry {}pub(crate) fn clear_emulation_policy_state(&mut self, session_key: &DevToolsSessionKey) {+ self.release_environment_owner(session_key);if let Some(state) = self.states.get_mut(session_key) {let emulation = &mut state.emulation_session_state;emulation.browser_identity_override = None;- emulation.locale_override = None;- emulation.timezone_override = None;+ }+ }++ fn release_environment_owner(&mut self, session_key: &DevToolsSessionKey) {+ if let Some(owner) = self.environment_owners.remove(session_key) {+ owner.release();}}@@ -405,7 +418,12 @@ impl DevToolsSessionRegistry {}pub(crate) fn has_non_default_state(&self) -> bool {- self.primary() != &DevToolsSessionState::default() || !self.attached_is_empty()+ self.primary() != &DevToolsSessionState::default()+ || !self.attached_is_empty()+ || self+ .environment_owners+ .values()+ .any(moli_core::ProcessEnvironmentOwner::has_override)}pub(crate) fn has_pending_inspector_awaits(&self) -> bool {@@ -666,8 +684,6 @@ pub(crate) struct DevToolsEmulationSessionState {// UA, Accept-Language, and platform are independent handler contributions.pub(crate) browser_identity_override: Option<DevToolsBrowserIdentityOverride>,// Locale and timezone are exclusive controller claims, unlike UA fields.- pub(crate) locale_override: Option<String>,- pub(crate) timezone_override: Option<String>,pub(crate) network_conditions: Option<super::EmulatedNetworkConditions>,pub(crate) geolocation_override: Option<super::EmulatedGeolocationOverrideState>,pub(crate) emulated_media: super::EmulatedMediaOverrides,@@ -683,8 +699,6 @@ impl Default for DevToolsEmulationSessionState {fn default() -> Self {Self {browser_identity_override: None,- locale_override: None,- timezone_override: None,network_conditions: None,geolocation_override: None,emulated_media: super::EmulatedMediaOverrides::default(),@@ -1364,7 +1378,10 @@ mod tests {sessions.set_locale_override(&session_a, Some("it-IT".to_owned())).unwrap();- assert_eq!(sessions.effective_locale_override(), Some("it-IT"));+ assert_eq!(+ sessions.effective_locale_override().as_deref(),+ Some("it-IT")+ );sessions.set_timezone_override(&session_a, Some("Europe/Paris".to_owned()))@@ -1378,11 +1395,14 @@ mod tests {sessions.set_timezone_override(&session_b, None).expect("Chromium accepts a non-owner timezone clear as a no-op");- assert_eq!(sessions.effective_timezone_override(), Some("Europe/Paris"));+ assert_eq!(+ sessions.effective_timezone_override().as_deref(),+ Some("Europe/Paris")+ );sessions.remove_attached("SID-a");- assert_eq!(sessions.effective_locale_override(), None);- assert_eq!(sessions.effective_timezone_override(), None);+ assert_eq!(sessions.effective_locale_override().as_deref(), None);+ assert_eq!(sessions.effective_timezone_override().as_deref(), None);sessions.set_locale_override(&session_b, Some("de-DE".to_owned())).unwrap();diff --git a/moli-protocol/src/conn/state/page_target_host.rs b/moli-protocol/src/conn/state/page_target_host.rsindex f6ce560d3..8ccd1dae1 100644--- a/moli-protocol/src/conn/state/page_target_host.rs+++ b/moli-protocol/src/conn/state/page_target_host.rs@@ -28,8 +28,7 @@ pub struct PageTargetHost {pub(crate) http_proxy_override: Option<String>,pub(crate) http_no_proxy_override: Option<String>,pub(crate) tls_verify_host_override: Option<bool>,- pub(crate) base_locale_override: Option<String>,- pub(crate) base_timezone_override: Option<String>,+ pub(crate) environment_owner: moli_core::ProcessEnvironmentOwner,pub(crate) effective_emulation_state: EffectiveTargetEmulationState,pub(crate) input_intercept_drags_enabled: bool,pub(crate) input_drag_intercepted: bool,@@ -53,8 +52,7 @@ impl PageTargetHost {http_proxy_override: None,http_no_proxy_override: None,tls_verify_host_override: None,- base_locale_override: None,- base_timezone_override: None,+ environment_owner: Default::default(),effective_emulation_state: EffectiveTargetEmulationState::default(),input_intercept_drags_enabled: false,input_drag_intercepted: false,diff --git a/moli-protocol/src/conn/state/session.rs b/moli-protocol/src/conn/state/session.rsindex 2237f8679..d0ac43e47 100644--- a/moli-protocol/src/conn/state/session.rs+++ b/moli-protocol/src/conn/state/session.rs@@ -87,16 +87,6 @@ impl PageTargetHost {.devtools_sessions.effective_renderer_browser_identity_override().or_else(|| self.network_policy.base_browser_identity.profile_owned()),- locale_override: self- .devtools_sessions- .effective_locale_override()- .map(str::to_owned)- .or_else(|| self.base_locale_override.clone()),- timezone_override: self- .devtools_sessions- .effective_timezone_override()- .map(str::to_owned)- .or_else(|| self.base_timezone_override.clone()),}}@@ -143,12 +133,22 @@ impl PageTargetHost {.set_timezone_override(session_key, timezone_override)}- pub(crate) fn set_base_locale_override(&mut self, locale_override: Option<String>) {- self.base_locale_override = locale_override;+ pub(crate) fn set_base_locale_override(+ &mut self,+ locale_override: Option<String>,+ ) -> Result<(), &'static str> {+ self.environment_owner+ .set_locale(locale_override.as_deref())?;+ Ok(())}- pub(crate) fn set_base_timezone_override(&mut self, timezone_override: Option<String>) {- self.base_timezone_override = timezone_override;+ pub(crate) fn set_base_timezone_override(+ &mut self,+ timezone_override: Option<String>,+ ) -> Result<(), &'static str> {+ self.environment_owner+ .set_timezone(timezone_override.as_deref())?;+ Ok(())}pub(crate) fn clear_devtools_network_state(@@ -182,8 +182,7 @@ impl PageTargetHost {|| self.http_proxy_override.is_some()|| self.http_no_proxy_override.is_some()|| self.tls_verify_host_override.is_some()- || self.base_locale_override.is_some()- || self.base_timezone_override.is_some()+ || self.environment_owner.has_override()|| self.effective_emulation_state != super::EffectiveTargetEmulationState::default()|| self.input_intercept_drags_enabled|| self.input_drag_intercepted@@ -225,8 +224,6 @@ pub(crate) struct EffectiveTargetPolicy {extra_headers: Vec<(String, String)>,browser_identity_override: Option<moli_browser_profile::BrowserIdentityProfile>,renderer_browser_identity_override: Option<moli_browser_profile::BrowserIdentityProfile>,- locale_override: Option<String>,- timezone_override: Option<String>,}impl EffectiveTargetPolicy {@@ -239,8 +236,6 @@ impl EffectiveTargetPolicy {browser_identity: self.browser_identity_override != next.browser_identity_override,renderer_browser_identity: self.renderer_browser_identity_override!= next.renderer_browser_identity_override,- locale: self.locale_override != next.locale_override,- timezone: self.timezone_override != next.timezone_override,}}@@ -271,14 +266,6 @@ impl EffectiveTargetPolicy {) -> Option<moli_browser_profile::BrowserIdentityProfile> {self.renderer_browser_identity_override.clone()}-- pub(crate) fn locale_override(&self) -> Option<&str> {- self.locale_override.as_deref()- }-- pub(crate) fn timezone_override(&self) -> Option<&str> {- self.timezone_override.as_deref()- }}/// Renderer surfaces that must be replayed after an effective policy change.@@ -287,8 +274,6 @@ pub(crate) struct EffectiveTargetPolicyDelta {pub(crate) network_request: bool,pub(crate) browser_identity: bool,pub(crate) renderer_browser_identity: bool,- pub(crate) locale: bool,- pub(crate) timezone: bool,}impl EffectiveTargetPolicyDelta {@@ -297,11 +282,7 @@ impl EffectiveTargetPolicyDelta {}pub(crate) fn is_empty(self) -> bool {- !self.network_request- && !self.browser_identity- && !self.renderer_browser_identity- && !self.locale- && !self.timezone+ !self.network_request && !self.browser_identity && !self.renderer_browser_identity}}@@ -706,8 +687,6 @@ mod tests {#[test]fn devtools_emulation_overrides_reveal_target_base_state_when_cleared() {let mut state = PageTargetHost::empty("TID-policy-test".to_owned());- state.set_base_locale_override(Some("en-GB".to_owned()));- state.set_base_timezone_override(Some("Europe/London".to_owned()));state.network_policy.set_browser_identity_override(moli_browser_profile::BrowserIdentityProfile::new("Moli/Base", "en-GB"),);@@ -737,8 +716,6 @@ mod tests {.emulation_session_state.cpu_throttling_rate = 4.0;let effective = state.effective_policy();- assert_eq!(effective.locale_override(), Some("fr-FR"));- assert_eq!(effective.timezone_override(), Some("Europe/Paris"));assert_eq!(effective.browser_identity_override()@@ -749,8 +726,6 @@ mod tests {state.clear_devtools_network_state(&DevToolsSessionKey::Primary);state.clear_devtools_emulation_policy_state(&DevToolsSessionKey::Primary);let effective = state.effective_policy();- assert_eq!(effective.locale_override(), Some("en-GB"));- assert_eq!(effective.timezone_override(), Some("Europe/London"));assert_eq!(state.devtools_sessionsdiff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rsindex a45d599ce..af36f6727 100644--- a/moli-protocol/src/domains/emulation.rs+++ b/moli-protocol/src/domains/emulation.rs@@ -94,12 +94,10 @@ pub(crate) enum EmulationCommandTaskStep {enum PendingEmulationPageOperation {SetExtraHttpHeaders,- SetLocaleOverride,SetNetworkConditions,SetCpuThrottlingRate,SetIdleOverride,SetNavigatorOverrides,- SetTimezoneOverride,SetEmulatedMedia,SetViewportSurface,SetUserAgentLoader,@@ -112,10 +110,8 @@ impl PendingEmulationPageOperation {match self {Self::SetExtraHttpHeaders| Self::SetNavigatorOverrides- | Self::SetLocaleOverride| Self::SetNetworkConditions| Self::SetCpuThrottlingRate- | Self::SetTimezoneOverride| Self::SetEmulatedMedia| Self::SetViewportSurface| Self::SetUserAgentLoader@@ -503,12 +499,9 @@ fn start_locale_override_command());}};- if conn.browser_context.is_none() {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));- }- let locale_override = params.locale.clone().filter(|value| !value.is_empty());+ let locale_override = params.locale.filter(|value| !value.is_empty());if let Err(message) =- conn.set_devtools_locale_override_for_session_owner(cmd.session_id, locale_override.clone())+ conn.set_devtools_locale_override_for_session_owner(cmd.session_id, locale_override){let code = if message == "BrowserContextNotLoaded" {-31998@@ -517,29 +510,9 @@ fn start_locale_override_command(};return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(code, message));}- let pending = if emulation_command_is_context_wide(conn, cmd.session_id) {- match start_context_locale_override_page_commands(conn, locale_override.as_deref()) {- Ok(pending) => pending,- Err(error) => {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-32000, error));- }- }- } else {- match start_session_locale_override_page_commands(conn, cmd.session_id) {- Ok(pending) => pending,- Err(error) => {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-32000, error));- }- }- };- if pending.is_empty() {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));- }- EmulationCommandTaskStep::Pending(PendingEmulationCommandDispatch {- command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),- pending: PendingEmulationRendererDispatch::Pages(pending),- })+ // The session owns a process-wide ICU claim. Isolate entry/foreground+ // notifications refresh native V8 caches; navigation must not re-acquire it.+ EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})))}fn start_idle_override_command(@@ -621,35 +594,19 @@ fn start_timezone_override_command(let trimmed = params.timezone_id.trim();(!trimmed.is_empty()).then(|| trimmed.to_owned())};- if let Err(message) = validate_timezone_override(timezone_override.as_deref()) {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-32602, message));- }- if let Err(message) = conn- .set_devtools_timezone_override_for_session_owner(cmd.session_id, timezone_override.clone())+ if let Err(message) =+ conn.set_devtools_timezone_override_for_session_owner(cmd.session_id, timezone_override){let code = if message == "BrowserContextNotLoaded" {-31998+ } else if message == "Invalid timezone id" {+ -32602} else {-32000};return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(code, message));}- let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);- let Some(page) = loaded_page_mut_for_target_configuration(conn, cmd.session_id) else {- return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));- };- match page.start_set_timezone_override(timezone_override.as_deref()) {- Ok(pending) => EmulationCommandTaskStep::Pending(single_pending_emulation_dispatch(- cmd.id,- owner_scope,- PendingEmulationPageOperation::SetTimezoneOverride,- pending,- None,- )),- Err(error) => {- EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-32000, error.to_string()))- }- }+ EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})))}fn start_geolocation_override_command(@@ -1091,7 +1048,7 @@ pub(crate) async fn execute_devtools_emulation_command_async(execute_devtools_set_locale_override_command_async(conn, command).await}DevToolsCommand::SetTimezoneOverride(command) => {- execute_devtools_set_timezone_override_command_async(conn, command).await+ execute_devtools_set_timezone_override_command(conn, command)}DevToolsCommand::SetGeolocationOverride(command) => {execute_devtools_set_geolocation_override_command_async(conn, command).await@@ -1712,6 +1669,19 @@ fn start_user_agent_loader_update_for_current_route(}))}+/// One process cannot promise independent BiDi environments. Reject a batch+/// before changing any owner rather than applying a prefix and then conflicting.+/// Choosing one owner already updates every Page/Worker's native defaults.+fn single_environment_owner<T>(owners: &[T]) -> Result<&T, DevToolsError> {+ let [owner] = owners else {+ return Err(DevToolsError::new(+ DevToolsErrorKind::Unsupported,+ "Locale/timezone overrides are process-wide; select one configuration owner",+ ));+ };+ Ok(owner)+}+async fn execute_devtools_set_locale_override_command_async(conn: &mut CdpConnection,command: DevToolsSetLocaleOverrideCommand,@@ -1732,16 +1702,13 @@ async fn execute_devtools_set_locale_override_for_targets(conn: &mut CdpConnection,command: DevToolsSetLocaleOverrideCommand,) -> Result<DevToolsCommandResult, DevToolsError> {- let mut pending = Vec::new();- for target_id in &command.target_ids {- let route = emulation_route_for_target(- conn,- target_id,- "ChildFrameContextNotSupportedForLocaleOverride",- )?;- let result = start_locale_override_for_current_route(conn, &route, command.locale.clone());- pending.extend(result?);- }+ let target_id = single_environment_owner(&command.target_ids)?;+ let route = emulation_route_for_target(+ conn,+ target_id,+ "ChildFrameContextNotSupportedForLocaleOverride",+ )?;+ let pending = start_locale_override_for_current_route(conn, &route, command.locale)?;complete_emulation_page_updates(conn, devtools_command_session_id(&command.context), pending).await}@@ -1752,12 +1719,11 @@ async fn execute_devtools_set_locale_override_for_browser_contexts() -> Result<DevToolsCommandResult, DevToolsError> {let browser_context_ids = resolve_bidi_browser_context_ids(conn, &command.browser_context_ids)?;let fallback_identity = conn.base_browser_identity().clone();- for browser_context_id in &browser_context_ids {- let browser_context = conn- .browser_context_by_id_mut(browser_context_id)- .expect("resolved browser context must remain addressable");- browser_context.set_default_locale_override(command.locale.clone(), &fallback_identity);- }+ let browser_context_id = single_environment_owner(&browser_context_ids)?;+ conn.browser_context_by_id_mut(browser_context_id)+ .expect("resolved browser context must remain addressable")+ .set_default_locale_override(command.locale, &fallback_identity)+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;let routes = top_level_target_routes_for_browser_contexts(conn, Some(&browser_context_ids));execute_locale_updates_for_routes(conn, devtools_command_session_id(&command.context), routes).await@@ -1782,11 +1748,8 @@ fn start_locale_override_for_current_route(locale: Option<String>,) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {let owner = CommandOwnerScope::for_route(route.clone());- if !conn.set_base_locale_override_for_owner(&owner, locale) {- return Err(devtools_emulation_owner_error(- "BrowserContextNotLoaded".to_owned(),- ));- }+ conn.set_base_locale_override_for_owner(&owner, locale)+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;start_locale_update_for_current_route(conn, route)}@@ -1794,39 +1757,24 @@ fn start_locale_update_for_current_route(conn: &mut CdpConnection,route: &CdpSessionRoute,) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {- let mut pending = Vec::new();- if let Some(identity_update) = start_user_agent_loader_update_for_current_route(conn, route)? {- pending.push(identity_update);- }- let target = pending_emulation_target_for_route(conn, route)?;- let owner = CommandOwnerScope::for_route(route.clone());- let Some(locale_override) = locale_override_for_owner(conn, &owner) else {- return Ok(pending);- };- let Some(page) = conn- .loaded_page_mut_for_target_configuration_for_owner(&owner)- .ok()- else {- return Ok(pending);- };- pending.extend(- start_locale_override_page_command(target, page, locale_override.as_deref())- .map_err(|error| DevToolsError::new(DevToolsErrorKind::Internal, error))?,- );- Ok(pending)+ // BiDi locale also controls transport language. Date/Intl use the already+ // committed process default, not a second renderer-side configuration.+ Ok(+ start_user_agent_loader_update_for_current_route(conn, route)?+ .into_iter()+ .collect(),+ )}-async fn execute_devtools_set_timezone_override_command_async(+fn execute_devtools_set_timezone_override_command(conn: &mut CdpConnection,command: DevToolsSetTimezoneOverrideCommand,) -> Result<DevToolsCommandResult, DevToolsError> {- validate_timezone_override(command.timezone.as_deref())- .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;if !command.target_ids.is_empty() {- return execute_devtools_set_timezone_override_for_targets(conn, command).await;+ return execute_devtools_set_timezone_override_for_targets(conn, command);}if !command.browser_context_ids.is_empty() {- return execute_devtools_set_timezone_override_for_browser_contexts(conn, command).await;+ return execute_devtools_set_timezone_override_for_browser_contexts(conn, command);}Err(DevToolsError::new(DevToolsErrorKind::InvalidArgument,@@ -1834,101 +1782,33 @@ async fn execute_devtools_set_timezone_override_command_async())}-fn validate_timezone_override(timezone: Option<&str>) -> Result<(), &'static str> {- if timezone.is_some_and(|timezone| !moli_time::is_valid_time_zone_identifier(timezone)) {- return Err("Invalid timezone id");- }- Ok(())-}--async fn execute_devtools_set_timezone_override_for_targets(+fn execute_devtools_set_timezone_override_for_targets(conn: &mut CdpConnection,command: DevToolsSetTimezoneOverrideCommand,) -> Result<DevToolsCommandResult, DevToolsError> {- let mut pending = Vec::new();- for target_id in &command.target_ids {- let route = emulation_route_for_target(- conn,- target_id,- "ChildFrameContextNotSupportedForTimezoneOverride",- )?;- let result =- start_timezone_override_for_current_route(conn, &route, command.timezone.clone());- if let Some(pending_command) = result? {- pending.push(pending_command);- }- }- complete_emulation_page_updates(conn, devtools_command_session_id(&command.context), pending)- .await+ let target_id = single_environment_owner(&command.target_ids)?;+ let route = emulation_route_for_target(+ conn,+ target_id,+ "ChildFrameContextNotSupportedForTimezoneOverride",+ )?;+ let owner = CommandOwnerScope::for_route(route);+ conn.set_base_timezone_override_for_owner(&owner, command.timezone)+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;+ Ok(DevToolsCommandResult::Empty)}-async fn execute_devtools_set_timezone_override_for_browser_contexts(+fn execute_devtools_set_timezone_override_for_browser_contexts(conn: &mut CdpConnection,command: DevToolsSetTimezoneOverrideCommand,) -> Result<DevToolsCommandResult, DevToolsError> {let browser_context_ids = resolve_bidi_browser_context_ids(conn, &command.browser_context_ids)?;- for browser_context_id in &browser_context_ids {- let browser_context = conn- .browser_context_by_id_mut(browser_context_id)- .expect("resolved browser context must remain addressable");- browser_context.default_timezone_override = command.timezone.clone();- }- let routes = top_level_target_routes_for_browser_contexts(conn, Some(&browser_context_ids));- execute_timezone_updates_for_routes(conn, devtools_command_session_id(&command.context), routes)- .await-}--async fn execute_timezone_updates_for_routes(- conn: &mut CdpConnection,- session_id: Option<String>,- routes: Vec<CdpSessionRoute>,-) -> Result<DevToolsCommandResult, DevToolsError> {- let mut pending = Vec::new();- for route in routes {- let result = start_timezone_update_for_current_route(conn, &route);- if let Some(pending_command) = result? {- pending.push(pending_command);- }- }- complete_emulation_page_updates(conn, session_id, pending).await-}--fn start_timezone_override_for_current_route(- conn: &mut CdpConnection,- route: &CdpSessionRoute,- timezone: Option<String>,-) -> Result<Option<PendingEmulationPageCommand>, DevToolsError> {- let owner = CommandOwnerScope::for_route(route.clone());- if !conn.set_base_timezone_override_for_owner(&owner, timezone) {- return Err(devtools_emulation_owner_error(- "BrowserContextNotLoaded".to_owned(),- ));- }- start_timezone_update_for_current_route(conn, route)-}--fn start_timezone_update_for_current_route(- conn: &mut CdpConnection,- route: &CdpSessionRoute,-) -> Result<Option<PendingEmulationPageCommand>, DevToolsError> {- let target = pending_emulation_target_for_route(conn, route)?;- let owner = CommandOwnerScope::for_route(route.clone());- let load_inputs = conn.navigation_load_inputs_for_owner(&owner);- let Some(page) = conn- .loaded_page_mut_for_target_configuration_for_owner(&owner)- .ok()- else {- return Ok(None);- };- let pending = page- .start_set_timezone_override(load_inputs.timezone_override.as_deref())- .map_err(|error| DevToolsError::new(DevToolsErrorKind::Internal, error.to_string()))?;- Ok(Some(PendingEmulationPageCommand {- target,- operation: PendingEmulationPageOperation::SetTimezoneOverride,- pending,- runtime_response_rx: None,- }))+ let browser_context_id = single_environment_owner(&browser_context_ids)?;+ conn.browser_context_by_id_mut(browser_context_id)+ .expect("resolved browser context must remain addressable")+ .set_default_timezone_override(command.timezone)+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::InvalidArgument, message))?;+ Ok(DevToolsCommandResult::Empty)}fn pending_emulation_target_for_route(@@ -2808,53 +2688,6 @@ fn start_context_emulated_media_page_commands(Ok(pending)}-fn start_session_locale_override_page_commands(- conn: &mut CdpConnection,- session_id: Option<&str>,-) -> Result<Vec<PendingEmulationPageCommand>, String> {- let Some(locale_override) = locale_override_for_session(conn, session_id) else {- return Ok(Vec::new());- };- let owner_scope = CommandOwnerScope::capture(conn, session_id);- let Some(page) = loaded_page_mut_for_target_configuration(conn, session_id) else {- return Ok(Vec::new());- };- start_locale_override_page_command(- PendingEmulationPageTarget::SessionOwner { owner_scope },- page,- locale_override.as_deref(),- )-}--fn start_context_locale_override_page_commands(- conn: &mut CdpConnection,- locale_override: Option<&str>,-) -> Result<Vec<PendingEmulationPageCommand>, String> {- let mut pending = Vec::new();- for browser_context in conn- .browser_context- .iter_mut()- .chain(conn.inactive_browser_contexts.iter_mut())- {- let browser_context_id = browser_context.id.clone();- for target in browser_context.page_targets.iter_mut() {- let target_id = target.target_id().to_owned();- let Some(page) = target.loaded_page_mut() else {- continue;- };- pending.extend(start_locale_override_page_command(- PendingEmulationPageTarget::BrowserContextTarget {- browser_context_id: browser_context_id.clone(),- target_id,- },- page,- locale_override,- )?);- }- }- Ok(pending)-}-fn start_geolocation_surface_override_page_commands(conn: &mut CdpConnection,cmd: &Cmd<'_>,@@ -3022,42 +2855,6 @@ fn start_surface_override_page_command(])}-fn start_locale_override_page_command(- target: PendingEmulationPageTarget,- page: &moli_core::page::Page,- locale_override: Option<&str>,-) -> Result<Vec<PendingEmulationPageCommand>, String> {- let locale_update = page- .start_set_locale_override(locale_override)- .map_err(|error| format!("failed to update page locale override: {error}"))?;- Ok(vec![PendingEmulationPageCommand {- target,- operation: PendingEmulationPageOperation::SetLocaleOverride,- pending: locale_update,- runtime_response_rx: None,- }])-}--fn locale_override_for_session(- conn: &CdpConnection,- session_id: Option<&str>,-) -> Option<Option<String>> {- let owner = CommandOwnerScope::capture(conn, session_id);- locale_override_for_owner(conn, &owner)-}--fn locale_override_for_owner(- conn: &CdpConnection,- owner: &CommandOwnerScope,-) -> Option<Option<String>> {- let (browser_context_id, target_id) = conn.target_owner_identity_for_owner(owner)?;- let browser_context = conn.browser_context_by_id(&browser_context_id)?;- if let Some(target_id) = target_id {- return Some(browser_context.effective_locale_override_for_target_owned(&target_id));- }- Some(browser_context.effective_active_locale_override_owned())-}-fn finish_pending_emulation_page_command(conn: &mut CdpConnection,operation: PendingEmulationPageOperation,@@ -3124,9 +2921,6 @@ fn finish_emulation_page_operation(PendingEmulationPageOperation::SetExtraHttpHeaders => page.finish_set_extra_http_headers(completion).map_err(|error| error.to_string()),- PendingEmulationPageOperation::SetLocaleOverride => page- .finish_set_locale_override(completion)- .map_err(|error| error.to_string()),PendingEmulationPageOperation::SetNetworkConditions => page.finish_set_network_offline(completion).map_err(|error| error.to_string()),@@ -3139,9 +2933,6 @@ fn finish_emulation_page_operation(PendingEmulationPageOperation::SetNavigatorOverrides => page.finish_set_navigator_overrides(completion).map_err(|error| error.to_string()),- PendingEmulationPageOperation::SetTimezoneOverride => page- .finish_set_timezone_override(completion)- .map_err(|error| error.to_string()),PendingEmulationPageOperation::SetEmulatedMedia => page.finish_set_emulated_media(completion).map_err(|error| error.to_string()),diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rsindex 3b61a7f99..81d002c71 100644--- a/moli-protocol/src/domains/emulation/tests.rs+++ b/moli-protocol/src/domains/emulation/tests.rs@@ -336,7 +336,7 @@ async fn attached_session_first_io_emulation_response_uses_its_session_host() {}#[tokio::test(flavor = "multi_thread")]-async fn timezone_override_can_complete_through_pending_command_dispatch() {+async fn timezone_override_completes_without_replaying_a_renderer_command() {let mut ctx = TestContext::new();load_session_page_for_pending_emulation_test(&mut ctx).await;@@ -347,11 +347,9 @@ async fn timezone_override_can_complete_through_pending_command_dispatch() {"params": { "timezoneId": "Asia/Shanghai" }}).to_string();- let pending = ctx- .conn- .try_start_pending_command_dispatch(&raw)- .expect("timezone override should use pending command dispatch");- let messages = complete_pending_command_task_for_test(&mut ctx, pending).await;+ ctx.process_async(serde_json::from_str::<serde_json::Value>(&raw).unwrap())+ .await;+ let messages = ctx.take_all();assert!(messages.iter().any(|message| {message["id"] == json!(9102)@@ -364,8 +362,9 @@ async fn timezone_override_can_complete_through_pending_command_dispatch() {.as_ref().unwrap().active_page_target()- .effective_policy()- .timezone_override(),+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),Some("Asia/Shanghai"));}@@ -440,7 +439,7 @@ async fn pending_emulation_completion_follows_the_exact_target_across_activation!super::pending_emulation_page_configuration_will_be_replayed(&ctx.conn,&target,- &super::PendingEmulationPageOperation::SetTimezoneOverride,+ &super::PendingEmulationPageOperation::SetCpuThrottlingRate,Some(dispatched_attachment_id),),"changing foreground selection must not make an error from the same Page look stale"@@ -458,7 +457,7 @@ async fn pending_emulation_completion_follows_the_exact_target_across_activationsuper::pending_emulation_page_configuration_will_be_replayed(&ctx.conn,&target,- &super::PendingEmulationPageOperation::SetTimezoneOverride,+ &super::PendingEmulationPageOperation::SetCpuThrottlingRate,Some(dispatched_attachment_id),),"only replacement of the exact target attachment may retire its renderer error"@@ -481,7 +480,7 @@ async fn pending_emulation_completion_follows_the_exact_target_across_activationcompleted: super::CompletedEmulationRendererDispatch::Pages(vec![super::CompletedEmulationPageCommand {target,- operation: super::PendingEmulationPageOperation::SetTimezoneOverride,+ operation: super::PendingEmulationPageOperation::SetCpuThrottlingRate,dispatched_attachment_id: Some(dispatched_attachment_id),completed: Err("renderer attachment retired".to_owned()),},@@ -1108,7 +1107,7 @@ async fn live_cpu_throttling_rate_uses_pending_command_dispatch() {}#[tokio::test(flavor = "multi_thread")]-async fn set_timezone_override_without_loaded_browser_context_errors() {+async fn process_environment_overrides_without_a_configuration_owner_error() {let mut ctx = TestContext::new();ctx.process_async(json!({@@ -1118,6 +1117,13 @@ async fn set_timezone_override_without_loaded_browser_context_errors() {})).await;ctx.expect_error(7, -31998, "BrowserContextNotLoaded");+ ctx.process_async(json!({+ "id": 8,+ "method": "Emulation.setLocaleOverride",+ "params": { "locale": "fr_FR" }+ }))+ .await;+ ctx.expect_error(8, -31998, "BrowserContextNotLoaded");}#[tokio::test(flavor = "multi_thread")]@@ -1148,8 +1154,9 @@ async fn invalid_timezone_override_is_rejected_without_replacing_active_state().as_ref().expect("browser context").active_page_target()- .effective_policy()- .timezone_override(),+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),Some("Europe/Paris"));}@@ -1215,11 +1222,17 @@ async fn multi_session_locale_and_timezone_claims_match_chromium() {.expect("browser context").active_page_target();assert_eq!(- page_state.effective_policy().locale_override(),+ page_state+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("fr-FR"));assert_eq!(- page_state.effective_policy().timezone_override(),+ page_state+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),Some("Europe/Paris"));}@@ -3119,8 +3132,9 @@ async fn context_locale_override_applies_to_loaded_background_page_without_activassert_eq!(browser_context.active_page_target()- .effective_policy()- .locale_override(),+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("fr-FR"));assert!(@@ -3129,8 +3143,9 @@ async fn context_locale_override_applies_to_loaded_background_page_without_activ.filter(|target| target.has_non_default_session_state()).and_then(|state| {state- .effective_policy()- .locale_override()+ .devtools_sessions+ .effective_locale_override()+ .as_deref().map(str::to_owned)}).is_none(),@@ -3254,8 +3269,9 @@ async fn session_emulation_routes_to_loaded_background_owner_without_activation(assert!(browser_context.active_page_target()- .effective_policy()- .locale_override()+ .devtools_sessions+ .effective_locale_override()+ .as_deref().is_none(),"background Emulation should not mutate the active target locale override");@@ -3272,7 +3288,10 @@ async fn session_emulation_routes_to_loaded_background_owner_without_activation(Some("dark"));assert_eq!(- background.effective_policy().locale_override(),+ background+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("zh-CN"));assert_eq!(diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rsindex 9c705ca10..706644251 100644--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs@@ -2825,7 +2825,7 @@ async fn same_context_background_session_can_clear_its_own_user_agent_before_act}#[tokio::test(flavor = "multi_thread")]-async fn same_context_background_session_stages_locale_without_changing_request_language() {+async fn process_environment_conflicts_do_not_stage_navigation_policy_or_change_request_language() {async fn handler(State(seen): State<Arc<Mutex<Vec<(String, Option<String>)>>>>,headers: HeaderMap,@@ -2928,7 +2928,10 @@ async fn same_context_background_session_stages_locale_without_changing_request_"params": { "locale": "fr-FR" }})).await;- ctx.expect_result(10419484, json!({}), Some(&second_session_id));+ assert_eq!(+ take_response_by_id(&mut ctx, 10419484)["error"]["message"],+ "Another locale override is already in effect"+ );ctx.process_async(json!({"id": 10419485,@@ -2937,7 +2940,10 @@ async fn same_context_background_session_stages_locale_without_changing_request_"params": { "timezoneId": "Asia/Shanghai" }})).await;- ctx.expect_result(10419485, json!({}), Some(&second_session_id));+ assert_eq!(+ take_response_by_id(&mut ctx, 10419485)["error"]["message"],+ "Timezone override is already in effect"+ );{let active = ctx@@ -2948,25 +2954,36 @@ async fn same_context_background_session_stages_locale_without_changing_request_assert_eq!(active.active_page_target()- .effective_policy()- .locale_override(),+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("en-GB"));assert_eq!(active.active_page_target()- .effective_policy()- .timezone_override(),+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),Some("UTC"));let staged = active.background_target(&second_target_id)- .filter(|target| target.has_non_default_session_state())- .expect("second target should have staged background page session state");- assert_eq!(staged.effective_policy().locale_override(), Some("fr-FR"));+ .expect("second target is present without a process environment claim");+ assert_eq!(+ staged+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),+ None,+ "a rejected process claim must not be replayed by navigation"+ );assert_eq!(- staged.effective_policy().timezone_override(),- Some("Asia/Shanghai")+ staged+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),+ None);}@@ -3016,6 +3033,26 @@ async fn same_context_background_session_stages_locale_without_changing_request_let _ = take_response_by_id(&mut ctx, 10419488);ctx.take_all();+ // The rejected values were not staged. After the owning target closes,+ // this session can explicitly acquire both claims for the first time.+ for (id, method, params) in [+ (+ 104194880,+ "Emulation.setLocaleOverride",+ json!({"locale": "fr-FR"}),+ ),+ (+ 104194881,+ "Emulation.setTimezoneOverride",+ json!({"timezoneId": "Asia/Shanghai"}),+ ),+ ] {+ ctx.process_async(json!({"id": id, "method": method,+ "sessionId": second_session_id, "params": params}))+ .await;+ ctx.expect_result(id, json!({}), Some(&second_session_id));+ }+let url_b = format!("http://{addr}/page-b");ctx.process_async(json!({"id": 10419489,@@ -3159,8 +3196,9 @@ async fn same_context_background_session_can_clear_its_own_locale_before_activatassert!(active.active_page_target()- .effective_policy()- .locale_override()+ .devtools_sessions+ .effective_locale_override()+ .as_deref().is_none(),"active target should keep its default locale override",);@@ -3323,8 +3361,9 @@ async fn same_context_background_session_can_clear_its_own_timezone_before_activassert!(active.active_page_target()- .effective_policy()- .timezone_override()+ .devtools_sessions+ .effective_timezone_override()+ .as_deref().is_none(),"active target should keep its default timezone override",);diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rsindex 0e7ba1b0b..5c3d41574 100644--- a/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs+++ b/moli-protocol/src/domains/target/tests/tests_same_context_overrides.rs@@ -1,7 +1,7 @@use super::*;#[tokio::test(flavor = "multi_thread")]-async fn same_context_targets_restore_their_own_page_session_overrides_after_switching() {+async fn same_context_targets_keep_local_network_policy_but_share_process_locale() {let mut ctx = TestContext::new();load_bc_with_titled_page_async(&mut ctx,@@ -117,7 +117,10 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swi"params": { "locale": "fr-FR" }})).await;- ctx.expect_result(104165, json!({}), Some(&second_session_id));+ assert_eq!(+ take_response_by_id(&mut ctx, 104165)["error"]["message"],+ "Another locale override is already in effect"+ );ctx.process_async(json!({"id": 104166,@@ -139,7 +142,10 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swivec![("X-Target".into(), "A".into())]);assert_eq!(- bc.active_page_target().effective_policy().locale_override(),+ bc.active_page_target()+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("en-GB"));}@@ -200,8 +206,12 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swivec![("X-Target".into(), "B".into())]);assert_eq!(- bc.active_page_target().effective_policy().locale_override(),- Some("fr-FR")+ bc.active_page_target()+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),+ None,+ "a rejected process claim must not become target-local policy");}@@ -239,7 +249,7 @@ async fn same_context_targets_restore_their_own_page_session_overrides_after_swiserde_json::from_str(second_payload).expect("second payload should be valid json");assert_eq!(second_payload["title"], json!("second-restored"));assert_eq!(second_payload["lang"], json!("en-US"));- assert_eq!(second_payload["locale"], json!("fr-FR"));+ assert_eq!(second_payload["locale"], json!("en-GB"));}#[tokio::test(flavor = "multi_thread")]diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rsindex 20e291a0c..40af0524d 100644--- a/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs+++ b/moli-protocol/src/domains/target/tests/tests_same_context_target_local.rs@@ -2671,15 +2671,17 @@ async fn playwright_over_cdp_context_target_attach_and_navigate_smoke() {assert_eq!(active.active_page_target()- .effective_policy()- .locale_override(),+ .devtools_sessions+ .effective_locale_override()+ .as_deref(),Some("fr-FR"));assert_eq!(active.active_page_target()- .effective_policy()- .timezone_override(),+ .devtools_sessions+ .effective_timezone_override()+ .as_deref(),Some("UTC"));}diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex 02079db99..c590d113c 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -9,7 +9,6 @@ mod crypto;mod css_fontface_runtime;mod css_runtime;pub(crate) mod css_stylesheet_runtime;-mod date_locale_runtime;mod dom_rect;mod event_document;mod event_legacy;diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rsdeleted file mode 100644index 50fd0617c..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs+++ /dev/null@@ -1,28 +0,0 @@-use super::*;-use crate::util::{get_private_value, set_private_value};-use anyhow::Result;--mod bindings;-mod date;-mod intl;-mod overrides;--const DATE_LOCALE_RUNTIME_INSTALLED_SLOT: &str = "__moliDateLocaleRuntimeInstalled";--pub(super) fn install_date_locale_runtime_state<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,-) -> Result<()> {- if get_private_value(scope, global, DATE_LOCALE_RUNTIME_INSTALLED_SLOT).is_some() {- return Ok(());- }- date::install_date_runtime_state(scope, global)?;- intl::install_intl_default_override_constructors(scope, global)?;- set_private_value(- scope,- global,- DATE_LOCALE_RUNTIME_INSTALLED_SLOT,- v8::Boolean::new(scope, true).into(),- );- Ok(())-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/bindings.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/bindings.rsdeleted file mode 100644index 1417e39ae..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/bindings.rs+++ /dev/null@@ -1,57 +0,0 @@-//! Fixed-shape plumbing shared by the Date and Intl wrappers. Only V8's-//! Proxy trap envelope and our private callback data are decoded here. The-//! page's argument values and options must still be interpreted by V8, not-//! eagerly converted as WebIDL strings, numbers, sequences or dictionaries.--use crate::util::v8str;-use crate::webidl;--#[derive(webidl::WebIdlArgs)]-pub(super) struct ConstructorApplyArgs<'s> {- #[webidl(required)]- pub target: v8::Local<'s, v8::Value>,- #[webidl(required)]- pub receiver: v8::Local<'s, v8::Value>,- #[webidl(required)]- pub arguments: v8::Local<'s, v8::Array>,-}--#[derive(webidl::WebIdlArgs)]-pub(super) struct ConstructorConstructArgs<'s> {- #[webidl(required)]- pub target: v8::Local<'s, v8::Value>,- #[webidl(required)]- pub arguments: v8::Local<'s, v8::Array>,- #[webidl(required)]- pub new_target: v8::Local<'s, v8::Value>,-}--#[derive(webidl::WebIdlDictionary)]-pub(super) struct ReflectIntrinsics<'s> {- #[webidl(required)]- pub apply: v8::Local<'s, v8::Function>,- #[webidl(required)]- pub construct: v8::Local<'s, v8::Function>,-}--impl<'s> ReflectIntrinsics<'s> {- pub fn from_global(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,- ) -> Option<Self> {- let reflect = global.get(scope, v8str(scope, "Reflect").into())?;- let reflect = v8::Local::<v8::Object>::try_from(reflect).ok()?;- webidl::parse_dictionary_object(scope, reflect).ok()- }-}--pub(super) fn callback_data<'s, T: webidl::WebIdlDictionary<'s>>(- scope: &mut v8::PinScope<'s, '_>,- data: v8::Local<'s, v8::Value>,-) -> Option<T> {- // These objects are built by our declarations, retained only in native- // callback data and never published to page JavaScript. Named own fields- // replace positional arrays without introducing page-visible coercions.- let object = v8::Local::<v8::Object>::try_from(data).ok()?;- webidl::parse_dictionary_object(scope, object).ok()-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rsdeleted file mode 100644index 56170d511..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs+++ /dev/null@@ -1,219 +0,0 @@-use super::*;-use crate::util::{callback_data_index_value, get_private_value, set_private_value};-use anyhow::{Result, anyhow};-use moli_webapi_declare::WebApiObject;--mod constructor;-mod parse_input;-mod prototype;--use constructor::{install_date_constructor_proxy, install_date_parse_override};-use prototype::{- date_get_timezone_offset_callback, date_local_field_callback, date_local_setter_callback,- date_to_date_string_callback, date_to_locale_date_string_callback,- date_to_locale_string_callback, date_to_locale_time_string_callback, date_to_string_callback,- date_to_time_string_callback,-};--const RETAINED_DATE_INTRINSICS_SLOT: &str = "__moliRetainedDateIntrinsics";-#[derive(Clone, Copy)]-#[repr(u32)]-enum DateIntrinsic {- Parse,- Utc,- Now,- ToString,- ToDateString,- ToTimeString,- ToLocaleString,- ToLocaleDateString,- ToLocaleTimeString,- GetTimezoneOffset,- GetFullYear,- GetMonth,- GetDate,- GetDay,- GetHours,- GetMinutes,- GetSeconds,- GetMilliseconds,- SetDate,- SetFullYear,- SetHours,- SetMilliseconds,- SetMinutes,- SetMonth,- SetSeconds,- SetTime,- SetUtcDate,- SetUtcFullYear,- SetUtcHours,- SetUtcMilliseconds,- SetUtcMinutes,- SetUtcMonth,- SetUtcSeconds,-}--impl DateIntrinsic {- const COUNT: i32 = Self::SetUtcSeconds as i32 + 1;-- const fn index(self) -> u32 {- self as u32- }-}--const DATE_STATIC_INTRINSICS: &[(DateIntrinsic, &str)] = &[- (DateIntrinsic::Parse, "parse"),- (DateIntrinsic::Utc, "UTC"),- (DateIntrinsic::Now, "now"),-];--const DATE_PROTOTYPE_INTRINSICS: &[(DateIntrinsic, &str)] = &[- (DateIntrinsic::ToString, "toString"),- (DateIntrinsic::ToDateString, "toDateString"),- (DateIntrinsic::ToTimeString, "toTimeString"),- (DateIntrinsic::ToLocaleString, "toLocaleString"),- (DateIntrinsic::ToLocaleDateString, "toLocaleDateString"),- (DateIntrinsic::ToLocaleTimeString, "toLocaleTimeString"),- (DateIntrinsic::GetTimezoneOffset, "getTimezoneOffset"),- (DateIntrinsic::GetFullYear, "getFullYear"),- (DateIntrinsic::GetMonth, "getMonth"),- (DateIntrinsic::GetDate, "getDate"),- (DateIntrinsic::GetDay, "getDay"),- (DateIntrinsic::GetHours, "getHours"),- (DateIntrinsic::GetMinutes, "getMinutes"),- (DateIntrinsic::GetSeconds, "getSeconds"),- (DateIntrinsic::GetMilliseconds, "getMilliseconds"),- (DateIntrinsic::SetDate, "setDate"),- (DateIntrinsic::SetFullYear, "setFullYear"),- (DateIntrinsic::SetHours, "setHours"),- (DateIntrinsic::SetMilliseconds, "setMilliseconds"),- (DateIntrinsic::SetMinutes, "setMinutes"),- (DateIntrinsic::SetMonth, "setMonth"),- (DateIntrinsic::SetSeconds, "setSeconds"),- (DateIntrinsic::SetTime, "setTime"),- (DateIntrinsic::SetUtcDate, "setUTCDate"),- (DateIntrinsic::SetUtcFullYear, "setUTCFullYear"),- (DateIntrinsic::SetUtcHours, "setUTCHours"),- (DateIntrinsic::SetUtcMilliseconds, "setUTCMilliseconds"),- (DateIntrinsic::SetUtcMinutes, "setUTCMinutes"),- (DateIntrinsic::SetUtcMonth, "setUTCMonth"),- (DateIntrinsic::SetUtcSeconds, "setUTCSeconds"),-];--#[derive(Default, WebApiObject)]-#[webapi(fragment, prototype = "Date")]-struct DateLocalePrototypeDeclaration {- #[webapi(method = "toString", length = 0, callback = date_to_string_callback)]- to_string: (),- #[webapi(method = "toDateString", length = 0, callback = date_to_date_string_callback)]- to_date_string: (),- #[webapi(method = "toTimeString", length = 0, callback = date_to_time_string_callback)]- to_time_string: (),- #[webapi(method, length = 0, callback = date_to_locale_string_callback)]- to_locale_string: (),- #[webapi(method, length = 0, callback = date_to_locale_date_string_callback)]- to_locale_date_string: (),- #[webapi(method, length = 0, callback = date_to_locale_time_string_callback)]- to_locale_time_string: (),- #[webapi(- method = "getTimezoneOffset",- length = 0,- callback = date_get_timezone_offset_callback- )]- get_timezone_offset: (),- #[webapi(method = "getFullYear", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 0))]- get_full_year: (),- #[webapi(method = "getMonth", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 1))]- get_month: (),- #[webapi(method = "getDate", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 2))]- get_date: (),- #[webapi(method = "getDay", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 3))]- get_day: (),- #[webapi(method = "getHours", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 4))]- get_hours: (),- #[webapi(method = "getMinutes", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 5))]- get_minutes: (),- #[webapi(method = "getSeconds", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 6))]- get_seconds: (),- #[webapi(method = "getMilliseconds", length = 0, callback = date_local_field_callback, data = callback_data_index_value(scope, 7))]- get_milliseconds: (),- #[webapi(method = "setDate", length = 1, callback = date_local_setter_callback, data = callback_data_index_value(scope, 0))]- set_date: (),- #[webapi(method = "setFullYear", length = 3, callback = date_local_setter_callback, data = callback_data_index_value(scope, 1))]- set_full_year: (),- #[webapi(method = "setHours", length = 4, callback = date_local_setter_callback, data = callback_data_index_value(scope, 2))]- set_hours: (),- #[webapi(method = "setMilliseconds", length = 1, callback = date_local_setter_callback, data = callback_data_index_value(scope, 3))]- set_milliseconds: (),- #[webapi(method = "setMinutes", length = 3, callback = date_local_setter_callback, data = callback_data_index_value(scope, 4))]- set_minutes: (),- #[webapi(method = "setMonth", length = 2, callback = date_local_setter_callback, data = callback_data_index_value(scope, 5))]- set_month: (),- #[webapi(method = "setSeconds", length = 2, callback = date_local_setter_callback, data = callback_data_index_value(scope, 6))]- set_seconds: (),-}--pub(super) fn install_date_runtime_state<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,-) -> Result<()> {- if get_private_value(scope, global, RETAINED_DATE_INTRINSICS_SLOT).is_some() {- return Ok(());- }- let Some(date_ctor_value) = global.get(scope, v8str(scope, "Date").into()) else {- return Ok(());- };- let Ok(date_ctor) = v8::Local::<v8::Function>::try_from(date_ctor_value) else {- return Ok(());- };- let Some(date_proto_value) = date_ctor.get(scope, v8str(scope, "prototype").into()) else {- return Ok(());- };- let Ok(date_proto) = v8::Local::<v8::Object>::try_from(date_proto_value) else {- return Ok(());- };-- let Some(retained) = retain_date_intrinsics(scope, date_ctor, date_proto) else {- return Ok(());- };- set_private_value(- scope,- global,- RETAINED_DATE_INTRINSICS_SLOT,- retained.into(),- );- DateLocalePrototypeDeclaration::default()- .initialize(scope, date_proto)- .map_err(|err| anyhow!("failed to initialize Date locale methods: {err}"))?;- install_date_parse_override(scope, date_ctor)?;- install_date_constructor_proxy(scope, global, date_ctor, date_proto)-}--fn retain_date_intrinsics<'s>(- scope: &mut v8::PinScope<'s, '_>,- constructor: v8::Local<'s, v8::Function>,- prototype: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Array>> {- let retained = v8::Array::new(scope, DateIntrinsic::COUNT);- for &(intrinsic, name) in DATE_STATIC_INTRINSICS {- let value = constructor.get(scope, v8str(scope, name).into())?;- let _ = retained.set_index(scope, intrinsic.index(), value);- }- for &(intrinsic, name) in DATE_PROTOTYPE_INTRINSICS {- let value = prototype.get(scope, v8str(scope, name).into())?;- let _ = retained.set_index(scope, intrinsic.index(), value);- }- Some(retained)-}--fn original_date_method<'s>(- scope: &mut v8::PinScope<'s, '_>,- intrinsic: DateIntrinsic,-) -> Option<v8::Local<'s, v8::Function>> {- let global = scope.get_current_context().global(scope);- get_private_value(scope, global, RETAINED_DATE_INTRINSICS_SLOT)- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())- .and_then(|retained| retained.get_index(scope, intrinsic.index()))- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rsdeleted file mode 100644index d4e97bfb8..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs+++ /dev/null@@ -1,356 +0,0 @@-use super::{DateIntrinsic, original_date_method};-use crate::util::{call_script_visible_function, throw_type_error, v8_string, v8str};-use crate::webidl;-use anyhow::{Result, anyhow};-use moli_webapi_declare::WebApiObject;--use super::super::bindings::{- ConstructorApplyArgs, ConstructorConstructArgs, ReflectIntrinsics, callback_data,-};-use super::super::overrides::current_date_locale_overrides;-use super::parse_input::local_date_parse_input_as_utc;--#[derive(WebApiObject)]-#[webapi(fragment)]-struct DateParseDeclaration<'s> {- original: v8::Local<'s, v8::Function>,- #[webapi(method, length = 1, callback = date_parse_callback, data = self.original)]- parse: (),-}--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-struct DateApplyData<'s> {- #[webidl(required)]- reflect_apply: v8::Local<'s, v8::Function>,- #[webidl(required)]- date_now: v8::Local<'s, v8::Function>,-}--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-struct DateConstructData<'s> {- #[webidl(required)]- reflect_construct: v8::Local<'s, v8::Function>,- #[webidl(required)]- date_utc: v8::Local<'s, v8::Function>,- #[webidl(required)]- date_parse: v8::Local<'s, v8::Function>,-}--#[derive(WebApiObject)]-#[webapi(plain)]-struct DateConstructorHandler<'s> {- apply_data: DateApplyData<'s>,- construct_data: DateConstructData<'s>,- #[webapi(method, length = 3, callback = date_constructor_proxy_apply_callback, data = self.apply_data)]- apply: (),- #[webapi(method, length = 3, callback = date_constructor_proxy_construct_callback, data = self.construct_data)]- construct: (),-}--pub(super) fn install_date_parse_override<'s>(- scope: &mut v8::PinScope<'s, '_>,- constructor: v8::Local<'s, v8::Function>,-) -> Result<()> {- let Some(original) = original_date_method(scope, DateIntrinsic::Parse) else {- return Ok(());- };- DateParseDeclaration::new(original).initialize(scope, constructor.into())?;- Ok(())-}--pub(super) fn install_date_constructor_proxy<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,- original: v8::Local<'s, v8::Function>,- prototype: v8::Local<'s, v8::Object>,-) -> Result<()> {- let Some(reflect) = ReflectIntrinsics::from_global(scope, global) else {- return Ok(());- };- let Some(date_now) = original_date_method(scope, DateIntrinsic::Now) else {- return Ok(());- };- let Some(date_utc) = original_date_method(scope, DateIntrinsic::Utc) else {- return Ok(());- };- let Some(date_parse) = original_date_method(scope, DateIntrinsic::Parse) else {- return Ok(());- };-- let handler = DateConstructorHandler::new(- DateApplyData::new(reflect.apply, date_now),- DateConstructData::new(reflect.construct, date_utc, date_parse),- )- .bind(scope)?;- let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {- return Err(anyhow!("failed to create Date constructor proxy"));- };- let _ = global.set(scope, v8str(scope, "Date").into(), proxy.into());- let _ = prototype.set(scope, v8str(scope, "constructor").into(), proxy.into());- Ok(())-}--fn date_constructor_proxy_apply_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<DateApplyData>(scope, args.data()) else {- return;- };- let Some(args) = webidl::parse_args::<ConstructorApplyArgs>(scope, &args) else {- return;- };- let (_, timezone_override) = current_date_locale_overrides(scope);- let Some(timezone) = timezone_override.as_deref() else {- let invoke_args = [args.target, args.receiver, args.arguments.into()];- let receiver = v8::undefined(scope);- if let Some(result) = call_script_visible_function(- scope,- data.reflect_apply,- receiver.into(),- &invoke_args,- "invoke Date through Reflect.apply",- ) {- rv.set(result);- }- return;- };-- // Calling Date as a function ignores every argument and returns the same- // local representation as a freshly constructed Date's toString(). Use- // the retained native clock, then apply only the target-local timezone.- let receiver = v8::undefined(scope);- let Some(now) = call_script_visible_function(- scope,- data.date_now,- receiver.into(),- &[],- "read Date.now for the Date function",- ) else {- return;- };- let Some(timestamp_ms) = now.number_value(scope) else {- return;- };- let value = moli_time::format_date_local_string(timestamp_ms, Some(timezone));- if let Some(value) = v8_string(scope, &value) {- rv.set(value.into());- }-}--fn date_constructor_proxy_construct_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<DateConstructData>(scope, args.data()) else {- return;- };- let Some(args) = webidl::parse_args::<ConstructorConstructArgs>(scope, &args) else {- return;- };- let (_, timezone_override) = current_date_locale_overrides(scope);- let replacement = match timezone_override.as_deref() {- Some(timezone) => match date_constructor_timezone_arguments(- scope,- args.arguments,- data.date_utc,- data.date_parse,- timezone,- ) {- Ok(replacement) => replacement,- Err(()) => return,- },- None => None,- };- let arguments = replacement.unwrap_or(args.arguments);- let invoke_args = [args.target, arguments.into(), args.new_target];- let receiver = v8::undefined(scope);- if let Some(result) = call_script_visible_function(- scope,- data.reflect_construct,- receiver.into(),- &invoke_args,- "invoke Date through Reflect.construct",- ) {- rv.set(result);- }-}--fn date_constructor_timezone_arguments<'s>(- scope: &mut v8::PinScope<'s, '_>,- arguments: v8::Local<'s, v8::Array>,- date_utc: v8::Local<'s, v8::Function>,- date_parse: v8::Local<'s, v8::Function>,- timezone: &str,-) -> Result<Option<v8::Local<'s, v8::Array>>, ()> {- let wall_clock = if arguments.length() >= 2 {- let forwarded = (0..arguments.length())- .filter_map(|index| arguments.get_index(scope, index))- .collect::<Vec<_>>();- let receiver = v8::undefined(scope);- call_script_visible_function(- scope,- date_utc,- receiver.into(),- &forwarded,- "normalize local Date constructor fields with Date.UTC",- )- .ok_or(())?- } else if arguments.length() == 1 {- let input = arguments.get_index(scope, 0).ok_or(())?;- // Date copies another Date's [[DateValue]] without invoking even an- // own @@toPrimitive getter. Every other object is converted with the- // default hint, then strings are parsed and other primitives become- // numeric epochs. Forward the primitive, never the original object,- // so V8 cannot run the page's conversion hooks a second time.- if input.is_date() {- return Ok(None);- }- let input = date_constructor_primitive(scope, input).ok_or(())?;- if !input.is_string() {- return Ok(Some(v8::Array::new_with_elements(scope, &[input])));- }- let input = v8::Local::<v8::String>::try_from(input).map_err(|_| ())?;- let epoch = parse_date_string(scope, date_parse, input, Some(timezone)).ok_or(())?;- return Ok(Some(v8::Array::new_with_elements(scope, &[epoch])));- } else {- return Ok(None);- };- Ok(Some(single_date_epoch_argument(- scope,- wall_clock.number_value(scope),- timezone,- )))-}--/// ECMA-262 ToPrimitive with no preferred type (Date constructor step 3.b.i).-/// rusty_v8 does not expose this abstract operation. Keep the small conversion-/// boundary here rather than using ToString/ToNumber, which change both the-/// hint and which branch the native Date constructor must take.-fn date_constructor_primitive<'s>(- scope: &mut v8::PinScope<'s, '_>,- input: v8::Local<'s, v8::Value>,-) -> Option<v8::Local<'s, v8::Value>> {- if !input.is_object() {- return Some(input);- }- let object = v8::Local::<v8::Object>::try_from(input).ok()?;- let key = v8::Symbol::get_to_primitive(scope);- let exotic = object.get(scope, key.into())?;- if !exotic.is_null_or_undefined() {- let Ok(method) = v8::Local::<v8::Function>::try_from(exotic) else {- throw_type_error(scope, "Symbol.toPrimitive is not callable");- return None;- };- let hint = v8str(scope, "default");- let result = call_script_visible_function(- scope,- method,- input,- &[hint.into()],- "Date constructor ToPrimitive",- )?;- if !result.is_object() {- return Some(result);- }- } else {- for key in ["valueOf", "toString"] {- let method = object.get(scope, v8str(scope, key).into())?;- if let Ok(method) = v8::Local::<v8::Function>::try_from(method) {- let result = call_script_visible_function(- scope,- method,- input,- &[],- "Date constructor OrdinaryToPrimitive",- )?;- if !result.is_object() {- return Some(result);- }- }- }- }- throw_type_error(scope, "Cannot convert object to primitive value");- None-}--fn single_date_epoch_argument<'s>(- scope: &mut v8::PinScope<'s, '_>,- wall_clock_utc_ms: Option<f64>,- timezone: &str,-) -> v8::Local<'s, v8::Array> {- let epoch_ms = epoch_for_local_wall_clock(wall_clock_utc_ms, timezone);- let epoch_ms = v8::Number::new(scope, epoch_ms);- v8::Array::new_with_elements(scope, &[epoch_ms.into()])-}--fn epoch_for_local_wall_clock(wall_clock_utc_ms: Option<f64>, timezone: &str) -> f64 {- wall_clock_utc_ms- .filter(|value| value.is_finite())- .and_then(|value| moli_time::epoch_millis_for_local_wall_clock(value, timezone))- .unwrap_or(f64::NAN)-}--fn date_parse_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Ok(original) = v8::Local::<v8::Function>::try_from(args.data()) else {- rv.set_undefined();- return;- };- // Date.parse performs ToString exactly once. Convert here before deciding- // whether the string denotes local time so observable conversion hooks are- // neither skipped nor invoked twice.- let Some(input) = args.get(0).to_string(scope) else {- return;- };- let (_, timezone_override) = current_date_locale_overrides(scope);- if let Some(parsed) = parse_date_string(scope, original, input, timezone_override.as_deref()) {- rv.set(parsed);- }-}--fn parse_date_string<'s>(- scope: &mut v8::PinScope<'s, '_>,- original: v8::Local<'s, v8::Function>,- input: v8::Local<'s, v8::String>,- timezone: Option<&str>,-) -> Option<v8::Local<'s, v8::Value>> {- let receiver = v8::undefined(scope);- // V8 owns acceptance of both ISO and implementation-defined legacy input.- // Never turn an originally invalid string into a valid one by adding a- // suffix. The argument is already a String, so neither native parse invokes- // the page's ToPrimitive/ToString hooks a second time.- let parsed = call_script_visible_function(- scope,- original,- receiver.into(),- &[input.into()],- "Date.parse",- )?;- let Some(timezone) = timezone else {- return Some(parsed);- };- if !parsed.number_value(scope)?.is_finite() {- return Some(parsed);- }- let Some(utc_input) = local_date_parse_input_as_utc(&input.to_rust_string_lossy(scope)) else {- return Some(parsed);- };- let utc_input = v8_string(scope, &utc_input)?;- let wall_clock = call_script_visible_function(- scope,- original,- receiver.into(),- &[utc_input.into()],- "read local Date string fields through native UTC parsing",- )?;- let epoch = epoch_for_local_wall_clock(wall_clock.number_value(scope), timezone);- Some(v8::Number::new(scope, epoch).into())-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rsdeleted file mode 100644index eed4097a1..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs+++ /dev/null@@ -1,194 +0,0 @@-//! Classify timezone *ownership*, not date validity. V8 still parses the original-//! input first. Only timezone-less input needs a second parse as UTC wall-clock-//! fields before applying the target's timezone/DST policy.--pub(super) fn local_date_parse_input_as_utc(input: &str) -> Option<String> {- // DateParser's InputReader treats NUL as end-of-input. Any timezone or- // comment after that point must not affect classification or consume the- // annotation we append for a second native parse.- let input = input.split_once('\0').map_or(input, |(prefix, _)| prefix);- // Do not trim: whitespace can turn an ISO date-only form (UTC) into a- // legacy date (local time). Fixed offsets below index bytes, never UTF-8 str.- if let Some(date_end) = iso_date_prefix_len(input.as_bytes()) {- let rest = input.as_bytes().get(date_end..)?;- if rest.is_empty() {- return None;- }- if matches!(rest.first(), Some(b'T' | b't')) {- if rest- .iter()- .any(|byte| matches!(byte, b'Z' | b'z' | b'+' | b'-'))- {- return None;- }- return Some(format!("{input}Z"));- }- }- let (explicit_timezone, open_comments) = legacy_timezone(input);- if explicit_timezone {- return None;- }- // V8's legacy scanner ignores parenthesized text, including an unclosed- // trailing comment. Close that ignored suffix so the UTC annotation is- // outside it; never interpret a timezone name found inside a comment.- Some(format!("{input}{} UTC", ")".repeat(open_comments)))-}--fn iso_date_prefix_len(bytes: &[u8]) -> Option<usize> {- let signed = matches!(bytes.first(), Some(b'+' | b'-'));- let year_len = if signed { 7 } else { 4 };- let year = bytes.get(usize::from(signed)..year_len)?;- if !year.iter().all(u8::is_ascii_digit) || (bytes.first() == Some(&b'-') && year == b"000000") {- return None;- }- let mut end = year_len;- for _ in 0..2 {- if bytes.get(end) != Some(&b'-') {- break;- }- if !bytes.get(end + 1..end + 3)?.iter().all(u8::is_ascii_digit) {- return None;- }- end += 3;- }- Some(end)-}--fn legacy_timezone(input: &str) -> (bool, usize) {- // Match V8 DateParser's TIME_ZONE_NAME tokens (dateparser.cc), not- // substrings. In particular Tue/Thu/Sat and PST's final T are not ISO- // separators. Like V8, names only designate a zone after a date number.- const ZONES: &[&str] = &[- "ut", "utc", "gmt", "z", "est", "edt", "cst", "cdt", "mst", "mdt", "pst", "pdt",- ];- const MONTHS: &[&str] = &[- "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",- ];- let mut chars = input.char_indices().peekable();- let mut comments = 0;- let mut number_seen = false;- let mut time_fields = 0;- while let Some((start, ch)) = chars.next() {- if ch == '(' {- comments += 1;- } else if comments > 0 {- if ch == ')' {- comments -= 1;- }- } else if ch.is_ascii_digit() {- number_seen = true;- let mut number = ch.to_digit(10).unwrap();- while let Some((_, digit)) = chars.next_if(|(_, ch)| ch.is_ascii_digit()) {- number = number- .saturating_mul(10)- .saturating_add(digit.to_digit(10).unwrap());- }- // Mirror DateParser's token consumption, not a full date parser:- // day numbers and month names consume their following '-' before- // the timezone branch sees it. A completed time does NOT consume- // that sign (00:00:00-0100 is an offset). The original native parse- // above still decides validity, ranges and calendar composition.- if chars.next_if(|(_, ch)| *ch == ':').is_some() {- time_fields += 1;- if chars.next_if(|(_, ch)| *ch == ':').is_some() {- time_fields += 1;- } else {- let _ = chars.next_if(|(_, ch)| *ch == '.');- }- } else if ((time_fields == 1 || time_fields == 2) && number <= 59)- || (time_fields == 3 && number <= 999)- {- time_fields = 4;- if chars.next_if(|(_, ch)| *ch == '.').is_some() {- while chars.next_if(|(_, ch)| ch.is_ascii_digit()).is_some() {}- }- } else {- let _ = chars.next_if(|(_, ch)| *ch == '-');- }- } else if matches!(ch, '+' | '-') && time_fields > 0 {- return (true, comments);- } else if is_legacy_word_char(ch) {- while chars.peek().is_some_and(|(_, ch)| is_legacy_word_char(*ch)) {- chars.next();- }- let end = chars.peek().map_or(input.len(), |(index, _)| *index);- // Both bounds come from char_indices, so Unicode input is safe.- let word = &input[start..end];- if number_seen && ZONES.iter().any(|zone| word.eq_ignore_ascii_case(zone)) {- return (true, comments);- }- if word.as_bytes().get(..3).is_some_and(|prefix| {- MONTHS- .iter()- .any(|month| prefix.eq_ignore_ascii_case(month.as_bytes()))- }) {- let _ = chars.next_if(|(_, ch)| *ch == '-');- }- }- }- (false, comments)-}--fn is_legacy_word_char(ch: char) -> bool {- ch >= 'A' && !ch.is_whitespace() && ch != '\u{feff}'-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn iso_date_only_recognition_rejects_unicode_without_panicking() {- for input in ["你好", "🙂", "+你好啊", "-🙂abc", "2024-你好", "ééé"] {- assert_ne!(- iso_date_prefix_len(input.as_bytes()),- Some(input.len()),- "{input:?}"- );- let _ = local_date_parse_input_as_utc(input);- }- }-- #[test]- fn date_timezone_ownership_distinguishes_iso_legacy_and_comments() {- for input in [- "2024",- "2024-01",- "2024-01-01",- "+002024-01-01",- "2024-01-01T00:00:00Z",- "2024-01-01t00:00:00-02:30",- "Jan 1 2024 00:00:00 PST",- "Jan 1 2024 00:00:00 eSt\u{a0}",- "Jan 1 2024 00:00:00 +0530",- "00:00:00-0100 Jan-01-2024",- "00:00-01:00 01-01-2024",- "00:00:00.000-0100 Jan-01-2024",- ] {- assert_eq!(local_date_parse_input_as_utc(input), None, "{input}");- }- for input in [- "Tue Jan 02 2024 00:00:00",- "Thu Jan 04 2024 00:00:00",- "Jan 1 2024 (PST)",- " 2024-01-01 ",- "00:00:00 Jan-01-2024",- "00:00:00 01-01-2024",- "00:00 January-01-2024",- "00:00:00.000 Jan-01-2024",- ] {- assert_eq!(- local_date_parse_input_as_utc(input),- Some(format!("{input} UTC"))- );- }- assert_eq!(- local_date_parse_input_as_utc("2024-01-01T00:00:00"),- Some("2024-01-01T00:00:00Z".into())- );- assert_eq!(- local_date_parse_input_as_utc("Jan 1 2024 (PST"),- Some("Jan 1 2024 (PST) UTC".into())- );- }-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rsdeleted file mode 100644index 0d4fb1f72..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/prototype.rs+++ /dev/null@@ -1,354 +0,0 @@-use super::*;-use crate::util::call_script_visible_function;--use super::super::{- intl::{intl_date_locales_with_default, intl_datetime_options_with_default_timezone},- overrides::current_date_locale_overrides,-};--const DATE_LOCAL_FIELD_INTRINSICS: &[DateIntrinsic] = &[- DateIntrinsic::GetFullYear,- DateIntrinsic::GetMonth,- DateIntrinsic::GetDate,- DateIntrinsic::GetDay,- DateIntrinsic::GetHours,- DateIntrinsic::GetMinutes,- DateIntrinsic::GetSeconds,- DateIntrinsic::GetMilliseconds,-];--const DATE_LOCAL_SETTER_INTRINSICS: &[(DateIntrinsic, DateIntrinsic)] = &[- (DateIntrinsic::SetDate, DateIntrinsic::SetUtcDate),- (DateIntrinsic::SetFullYear, DateIntrinsic::SetUtcFullYear),- (DateIntrinsic::SetHours, DateIntrinsic::SetUtcHours),- (- DateIntrinsic::SetMilliseconds,- DateIntrinsic::SetUtcMilliseconds,- ),- (DateIntrinsic::SetMinutes, DateIntrinsic::SetUtcMinutes),- (DateIntrinsic::SetMonth, DateIntrinsic::SetUtcMonth),- (DateIntrinsic::SetSeconds, DateIntrinsic::SetUtcSeconds),-];--pub(super) fn date_to_locale_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_locale_method_result(- scope,- args,- rv,- DateIntrinsic::ToLocaleString,- "Date.prototype.toLocaleString",- );-}--pub(super) fn date_to_locale_date_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_locale_method_result(- scope,- args,- rv,- DateIntrinsic::ToLocaleDateString,- "Date.prototype.toLocaleDateString",- );-}--pub(super) fn date_to_locale_time_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_locale_method_result(- scope,- args,- rv,- DateIntrinsic::ToLocaleTimeString,- "Date.prototype.toLocaleTimeString",- );-}--fn set_date_locale_method_result<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,- original: DateIntrinsic,- action: &str,-) {- let Some(original) = original_date_method(scope, original) else {- rv.set_undefined();- return;- };- let (locale_override, timezone_override) = current_date_locale_overrides(scope);- let mut forwarded = (0..args.length())- .map(|index| args.get(index))- .collect::<Vec<_>>();- if let Some(locale) = locale_override.as_deref()- && let Some(locale) = intl_date_locales_with_default(scope, args.get(0), locale)- {- if forwarded.is_empty() {- forwarded.push(locale);- } else {- forwarded[0] = locale;- }- }- if let Some(timezone) = timezone_override.as_deref()- && let Some(options) =- intl_datetime_options_with_default_timezone(scope, forwarded.get(1).copied(), timezone)- {- while forwarded.len() < 2 {- forwarded.push(v8::undefined(scope).into());- }- forwarded[1] = options;- }- if let Some(value) =- call_script_visible_function(scope, original, args.this().into(), &forwarded, action)- {- rv.set(value);- }-}--pub(super) fn date_get_timezone_offset_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let (_, timezone_override) = current_date_locale_overrides(scope);- // Preserve V8's complete native Date behavior outside emulation. The- // target-local path below exists because V8's Date cache is also driven by- // process-global timezone state.- if timezone_override.is_none()- && set_original_date_method_result(- scope,- &args,- &mut rv,- DateIntrinsic::GetTimezoneOffset,- "Date.prototype.getTimezoneOffset",- )- {- return;- }- let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {- throw_type_error(- scope,- "Method Date.prototype.getTimezoneOffset called on incompatible receiver.",- );- return;- };- let timestamp = date.value_of();- let offset_minutes = timezone_override- .as_deref()- .and_then(|timezone| moli_time::time_zone_offset_seconds(timestamp, timezone))- .or_else(|| moli_time::local_time_zone_offset_seconds(timestamp))- .map(|seconds| -f64::from(seconds) / 60.0)- .unwrap_or(f64::NAN);- rv.set(v8::Number::new(scope, offset_minutes).into());-}--pub(super) fn date_local_field_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let field = args.data().uint32_value(scope).unwrap_or(u32::MAX);- let (_, timezone_override) = current_date_locale_overrides(scope);- if timezone_override.is_none()- && let Some(&intrinsic) = DATE_LOCAL_FIELD_INTRINSICS.get(field as usize)- && set_original_date_method_result(- scope,- &args,- &mut rv,- intrinsic,- "Date local field getter",- )- {- return;- }- let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {- throw_type_error(scope, "Date method called on incompatible receiver.");- return;- };- let Some(fields) = moli_time::local_date_fields(date.value_of(), timezone_override.as_deref())- else {- rv.set(v8::Number::new(scope, f64::NAN).into());- return;- };- let value = match field {- 0 => f64::from(fields.year),- 1 => f64::from(fields.month_zero_based),- 2 => f64::from(fields.day),- 3 => f64::from(fields.weekday_sunday_zero),- 4 => f64::from(fields.hour),- 5 => f64::from(fields.minute),- 6 => f64::from(fields.second),- 7 => f64::from(fields.millisecond),- _ => f64::NAN,- };- rv.set(v8::Number::new(scope, value).into());-}--pub(super) fn date_local_setter_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let setter = args.data().uint32_value(scope).unwrap_or(u32::MAX);- let Some(&(local_intrinsic, utc_intrinsic)) = DATE_LOCAL_SETTER_INTRINSICS.get(setter as usize)- else {- rv.set(v8::Number::new(scope, f64::NAN).into());- return;- };- let forwarded = (0..args.length())- .map(|index| args.get(index))- .collect::<Vec<_>>();- let (_, timezone_override) = current_date_locale_overrides(scope);- let Some(timezone) = timezone_override.as_deref() else {- let Some(method) = original_date_method(scope, local_intrinsic) else {- rv.set_undefined();- return;- };- if let Some(value) = call_script_visible_function(- scope,- method,- args.this().into(),- &forwarded,- "Date local field setter",- ) {- rv.set(value);- }- return;- };- let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {- throw_type_error(scope, "Date method called on incompatible receiver.");- return;- };- let wall_clock =- moli_time::local_wall_clock_as_utc_millis(date.value_of(), timezone).unwrap_or(f64::NAN);- let Some(temporary) = v8::Date::new(scope, wall_clock) else {- rv.set(v8::Number::new(scope, f64::NAN).into());- return;- };- let Some(utc_setter) = original_date_method(scope, utc_intrinsic) else {- rv.set_undefined();- return;- };- let Some(next_wall_clock) = call_script_visible_function(- scope,- utc_setter,- temporary.into(),- &forwarded,- "normalize a Date local setter through its UTC counterpart",- ) else {- return;- };- let epoch_ms = next_wall_clock- .number_value(scope)- .filter(|value| value.is_finite())- .and_then(|value| moli_time::epoch_millis_for_local_wall_clock(value, timezone))- .unwrap_or(f64::NAN);- let Some(set_time) = original_date_method(scope, DateIntrinsic::SetTime) else {- rv.set_undefined();- return;- };- let epoch_ms = v8::Number::new(scope, epoch_ms);- if let Some(value) = call_script_visible_function(- scope,- set_time,- args.this().into(),- &[epoch_ms.into()],- "commit a Date local setter",- ) {- rv.set(value);- }-}--pub(super) fn date_to_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_local_string_result(- scope,- args,- rv,- moli_time::format_date_local_string,- DateIntrinsic::ToString,- "Date.prototype.toString",- );-}--pub(super) fn date_to_date_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_local_string_result(- scope,- args,- rv,- moli_time::format_date_local_date_string,- DateIntrinsic::ToDateString,- "Date.prototype.toDateString",- );-}--pub(super) fn date_to_time_string_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- rv: v8::ReturnValue<'s, v8::Value>,-) {- set_date_local_string_result(- scope,- args,- rv,- moli_time::format_date_local_time_string,- DateIntrinsic::ToTimeString,- "Date.prototype.toTimeString",- );-}--fn set_date_local_string_result<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,- format: fn(f64, Option<&str>) -> String,- original: DateIntrinsic,- action: &str,-) {- let (_, timezone_override) = current_date_locale_overrides(scope);- if timezone_override.is_none()- && set_original_date_method_result(scope, &args, &mut rv, original, action)- {- return;- }- let Ok(date) = v8::Local::<v8::Date>::try_from(args.this()) else {- throw_type_error(scope, "Date method called on incompatible receiver.");- return;- };- let value = format(date.value_of(), timezone_override.as_deref());- if let Some(value) = v8_string(scope, &value) {- rv.set(value.into());- }-}--fn set_original_date_method_result<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,- rv: &mut v8::ReturnValue<'s, v8::Value>,- intrinsic: DateIntrinsic,- action: &str,-) -> bool {- let Some(method) = original_date_method(scope, intrinsic) else {- return false;- };- if let Some(value) =- call_script_visible_function(scope, method, args.this().into(), &[], action)- {- rv.set(value);- }- true-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rsdeleted file mode 100644index 992d9801c..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs+++ /dev/null@@ -1,368 +0,0 @@-use crate::util::{- call_script_visible_function, define_v8_array_data_property, get_private_value,- set_private_value, v8_string, v8str,-};-use crate::webidl;-use anyhow::{Result, anyhow};-use moli_webapi_declare::WebApiObject;--use super::bindings::{- ConstructorApplyArgs, ConstructorConstructArgs, ReflectIntrinsics, callback_data,-};-use super::overrides::current_date_locale_overrides;--mod locales;-use locales::LocaleIntrinsics;--const INTL_DEFAULT_LOCALE_SLOT: &str = "__moliIntlDefaultLocale";--const INTL_CONSTRUCTORS: &[&str] = &[- "Collator",- "DateTimeFormat",- "DisplayNames",- "DurationFormat",- "ListFormat",- "NumberFormat",- "PluralRules",- "RelativeTimeFormat",- "Segmenter",-];--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-struct IntlConstructorData<'s> {- #[webidl(required)]- reflect: v8::Local<'s, v8::Function>,- #[webidl(required)]- uses_timezone: bool,- #[webidl(required)]- canonicalize_locales: v8::Local<'s, v8::Function>,- #[webidl(required)]- supported_locales: v8::Local<'s, v8::Function>,-}--#[derive(WebApiObject)]-#[webapi(plain)]-struct IntlConstructorHandler<'s> {- apply_data: IntlConstructorData<'s>,- construct_data: IntlConstructorData<'s>,- #[webapi(method, length = 3, callback = intl_constructor_proxy_apply_callback, data = self.apply_data)]- apply: (),- #[webapi(method, length = 3, callback = intl_constructor_proxy_construct_callback, data = self.construct_data)]- construct: (),-}--#[derive(WebApiObject)]-#[webapi(fragment)]-struct IntlResolvedOptionsDeclaration<'s> {- original: v8::Local<'s, v8::Function>,- #[webapi(method, length = 0, callback = intl_resolved_options_callback, data = self.original)]- resolved_options: (),-}--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-struct TimezoneOptionsData<'s> {- #[webidl(required)]- original: v8::Local<'s, v8::Object>,- #[webidl(required)]- timezone: v8::Local<'s, v8::Value>,-}--#[derive(WebApiObject)]-#[webapi(plain)]-struct TimezoneOptionsHandler<'s> {- data: TimezoneOptionsData<'s>,- #[webapi(method, length = 3, callback = intl_datetime_options_get_callback, data = self.data)]- get: (),-}--#[derive(WebApiObject)]-#[webapi(plain, data_properties, enumerable)]-struct DefaultTimezoneOptions<'s> {- time_zone: v8::Local<'s, v8::Value>,-}--pub(super) fn install_intl_default_override_constructors<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,-) -> Result<()> {- // Chromium changes ICU's process-wide default and notifies every isolate.- // Moli can host independently configured targets in one renderer process,- // so a process-global ICU mutation would leak one target's emulation into- // another. Keep the override context-local; native locale matching tries- // the page's canonical requests before our fallback, and explicit timeZone- // values win. The locale adapter is lazy to preserve native getter order.- let Some(intl_value) = global.get(scope, v8str(scope, "Intl").into()) else {- return Ok(());- };- let Ok(intl) = v8::Local::<v8::Object>::try_from(intl_value) else {- return Ok(());- };- let Some(reflect) = ReflectIntrinsics::from_global(scope, global) else {- return Ok(());- };- let canonicalize = intl- .get(scope, v8str(scope, "getCanonicalLocales").into())- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())- .ok_or_else(|| anyhow!("missing native Intl.getCanonicalLocales"))?;- for &name in INTL_CONSTRUCTORS {- let key = v8str(scope, name);- let Some(original_value) = intl.get(scope, key.into()) else {- continue;- };- let Ok(original) = v8::Local::<v8::Function>::try_from(original_value) else {- continue;- };- if let Some(prototype) = original- .get(scope, v8str(scope, "prototype").into())- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- install_intl_resolved_options_override(scope, prototype)?;- }- let uses_timezone = name == "DateTimeFormat";- let supported = original- .get(scope, v8str(scope, "supportedLocalesOf").into())- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())- .ok_or_else(|| anyhow!("missing native Intl.{name}.supportedLocalesOf"))?;- if uses_timezone {- locales::retain_date_locale_intrinsics(- scope,- global,- LocaleIntrinsics::new(canonicalize, supported),- )?;- }- let handler = IntlConstructorHandler::new(- IntlConstructorData::new(reflect.apply, uses_timezone, canonicalize, supported),- IntlConstructorData::new(reflect.construct, uses_timezone, canonicalize, supported),- )- .bind(scope)?;- let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {- return Err(anyhow!("failed to create Intl.{name} constructor proxy"));- };- let _ = intl.set(scope, key.into(), proxy.into());- if let Some(prototype) = original- .get(scope, v8str(scope, "prototype").into())- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- let _ = prototype.set(scope, v8str(scope, "constructor").into(), proxy.into());- }- }- Ok(())-}--fn install_intl_resolved_options_override<'s>(- scope: &mut v8::PinScope<'s, '_>,- prototype: v8::Local<'s, v8::Object>,-) -> Result<()> {- let key = v8str(scope, "resolvedOptions");- let Some(original) = prototype.get(scope, key.into()) else {- return Ok(());- };- let Ok(original) = v8::Local::<v8::Function>::try_from(original) else {- return Ok(());- };- IntlResolvedOptionsDeclaration::new(original).initialize(scope, prototype)?;- Ok(())-}--fn intl_constructor_proxy_apply_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<IntlConstructorData>(scope, args.data()) else {- return;- };- let Some(args) = webidl::parse_args::<ConstructorApplyArgs>(scope, &args) else {- return;- };- let locale_list = apply_intl_constructor_defaults(scope, args.arguments, data);- let invoke_args = [args.target, args.receiver, args.arguments.into()];- let receiver = v8::undefined(scope);- if let Some(result) = call_script_visible_function(- scope,- data.reflect,- receiver.into(),- &invoke_args,- "invoke Intl constructor through Reflect.apply",- ) {- tag_intl_default_locale(scope, result, locale_list);- rv.set(result);- }-}--fn intl_constructor_proxy_construct_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<IntlConstructorData>(scope, args.data()) else {- return;- };- let Some(args) = webidl::parse_args::<ConstructorConstructArgs>(scope, &args) else {- return;- };- let locale_list = apply_intl_constructor_defaults(scope, args.arguments, data);- let invoke_args = [args.target, args.arguments.into(), args.new_target];- let receiver = v8::undefined(scope);- if let Some(result) = call_script_visible_function(- scope,- data.reflect,- receiver.into(),- &invoke_args,- "invoke Intl constructor through Reflect.construct",- ) {- tag_intl_default_locale(scope, result, locale_list);- rv.set(result);- }-}--fn apply_intl_constructor_defaults<'s>(- scope: &mut v8::PinScope<'s, '_>,- arguments: v8::Local<'s, v8::Array>,- data: IntlConstructorData<'s>,-) -> Option<v8::Local<'s, v8::Object>> {- let (locale_override, timezone_override) = current_date_locale_overrides(scope);- let locale_list = locale_override.as_deref().and_then(|locale| {- // The Proxy trap array is internal and dense. Reading beyond its- // length would incorrectly consult the page's Array.prototype.- let original = if arguments.length() == 0 {- v8::undefined(scope).into()- } else {- arguments.get_index(scope, 0)?- };- let list = locales::defer_locale_list(- scope,- original,- locale,- LocaleIntrinsics::new(data.canonicalize_locales, data.supported_locales),- )?;- define_v8_array_data_property(scope, arguments, 0, list.into())?;- Some(list)- });- if data.uses_timezone- && let Some(timezone) = timezone_override.as_deref()- && let Some(options) = intl_datetime_options_with_default_timezone(- scope,- (arguments.length() > 1)- .then(|| arguments.get_index(scope, 1))- .flatten(),- timezone,- )- {- let _ = define_v8_array_data_property(scope, arguments, 1, options);- }- locale_list-}--fn tag_intl_default_locale<'s>(- scope: &mut v8::PinScope<'s, '_>,- result: v8::Local<'s, v8::Value>,- locale_list: Option<v8::Local<'s, v8::Object>>,-) {- // Supplying the emulated default as an explicit locale can minimize a- // service's resolved tag (for example Collator may report `fr`). ICU's- // overridden default, and therefore Chromium, retains `fr-FR`. Tag the- // instance so resolvedOptions can expose that same default identity.- if let Some(list) = locale_list- && let Some(locale) = get_private_value(scope, list, locales::DEFAULT_LOCALE_SLOT)- && let Ok(instance) = v8::Local::<v8::Object>::try_from(result)- {- set_private_value(scope, instance, INTL_DEFAULT_LOCALE_SLOT, locale);- }-}--pub(super) fn intl_date_locales_with_default<'s>(- scope: &mut v8::PinScope<'s, '_>,- original: v8::Local<'s, v8::Value>,- locale: &str,-) -> Option<v8::Local<'s, v8::Value>> {- locales::defer_date_locale_list(scope, original, locale).map(Into::into)-}--fn intl_resolved_options_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Ok(original) = v8::Local::<v8::Function>::try_from(args.data()) else {- rv.set_undefined();- return;- };- let Some(result) = call_script_visible_function(- scope,- original,- args.this().into(),- &[],- "Intl resolvedOptions",- ) else {- return;- };- let Ok(options) = v8::Local::<v8::Object>::try_from(result) else {- rv.set(result);- return;- };- if let Some(locale) = get_private_value(scope, args.this(), INTL_DEFAULT_LOCALE_SLOT) {- let _ = options.set(scope, v8str(scope, "locale").into(), locale);- }- rv.set(options.into());-}--pub(super) fn intl_datetime_options_with_default_timezone<'s>(- scope: &mut v8::PinScope<'s, '_>,- original: Option<v8::Local<'s, v8::Value>>,- timezone: &str,-) -> Option<v8::Local<'s, v8::Value>> {- if let Some(original) = original.filter(|value| !value.is_undefined()) {- if original.is_null() {- // Native code owns when null throws (an invalid Date, for example,- // returns before consulting options). Other primitives are boxed- // by CoerceOptionsToObject and must receive the default too.- return Some(original);- }- let original = original.to_object(scope)?;- // Do not inspect `timeZone` here. Reading it before V8 processes the- // remaining options changes observable getter/Proxy ordering and can- // read an explicit accessor twice. The transparent proxy supplies the- // default exactly when V8 performs its ordinary [[Get]]. Do not use- // the page's object as the Proxy target: substituting a default for a- // frozen own `timeZone: undefined` would violate Proxy [[Get]]'s- // SameValue invariant. The empty target has no such own properties;- // callback data retains the original object only for forwarding reads.- let target = v8::Object::new(scope);- let timezone = v8_string(scope, timezone)?;- let handler =- TimezoneOptionsHandler::new(TimezoneOptionsData::new(original, timezone.into()))- .bind(scope)- .ok()?;- return v8::Proxy::new(scope, target, handler).map(Into::into);- }- let timezone = v8_string(scope, timezone)?;- DefaultTimezoneOptions::new(timezone.into())- .bind(scope)- .ok()- .map(Into::into)-}--fn intl_datetime_options_get_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<TimezoneOptionsData>(scope, args.data()) else {- return;- };- let key = args.get(1);- // The outer proxy is an implementation detail. Forward with the page's- // original options object as receiver so an accessor observes exactly the- // same `this` value it would have seen without emulation.- let Some(value) = data.original.get(scope, key) else {- return;- };- if key.strict_equals(v8str(scope, "timeZone").into()) && value.is_undefined() {- rv.set(data.timezone);- } else {- rv.set(value);- }-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rsdeleted file mode 100644index 73a8111d2..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl/locales.rs+++ /dev/null@@ -1,156 +0,0 @@-//! A per-call, lazy locale list. Let the native constructor decide *when* to-//! canonicalize locales: doing it in our outer Proxy trap would run page-//! getters before newTarget.prototype, or even for calls that should throw-//! without examining arguments. Date locale methods likewise return early for-//! an invalid Date. Only the native CanonicalizeLocaleList's length read opens-//! this adapter; it never eagerly inspects the page's options.--use crate::util::{- call_script_visible_function, get_private_value, set_private_value, v8_string, v8str,-};-use crate::webidl;-use moli_webapi_declare::WebApiObject;--use super::super::bindings::callback_data;--const DATE_LOCALE_INTRINSICS_SLOT: &str = "__moliDateLocaleListIntrinsics";-pub(super) const DEFAULT_LOCALE_SLOT: &str = "__moliLocaleListDefault";--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-pub(super) struct LocaleIntrinsics<'s> {- #[webidl(required)]- pub canonicalize: v8::Local<'s, v8::Function>,- #[webidl(required)]- pub supported: v8::Local<'s, v8::Function>,-}--#[derive(Clone, Copy, WebApiObject, webidl::WebIdlDictionary)]-#[webapi(plain, data_properties)]-struct LocaleListData<'s> {- requested: Option<v8::Local<'s, v8::Value>>,- #[webidl(required)]- fallback: v8::Local<'s, v8::Value>,- #[webidl(required)]- canonicalize: v8::Local<'s, v8::Function>,- #[webidl(required)]- supported: v8::Local<'s, v8::Function>,-}--#[derive(WebApiObject)]-#[webapi(plain)]-struct DeferredLocaleList<'s> {- data: LocaleListData<'s>,- #[webapi(accessor_property, getter = locale_list_length_callback, data = self.data)]- length: (),-}--pub(super) fn defer_locale_list<'s>(- scope: &mut v8::PinScope<'s, '_>,- original: v8::Local<'s, v8::Value>,- fallback: &str,- intrinsics: LocaleIntrinsics<'s>,-) -> Option<v8::Local<'s, v8::Object>> {- let fallback = v8_string(scope, fallback)?;- DeferredLocaleList::new(LocaleListData::new(- Some(original),- fallback.into(),- intrinsics.canonicalize,- intrinsics.supported,- ))- .bind(scope)- .ok()-}--pub(super) fn retain_date_locale_intrinsics<'s>(- scope: &mut v8::PinScope<'s, '_>,- global: v8::Local<'s, v8::Object>,- intrinsics: LocaleIntrinsics<'s>,-) -> Result<(), moli_webapi_declare::BindError> {- let value = intrinsics.bind(scope)?;- set_private_value(scope, global, DATE_LOCALE_INTRINSICS_SLOT, value.into());- Ok(())-}--pub(super) fn defer_date_locale_list<'s>(- scope: &mut v8::PinScope<'s, '_>,- original: v8::Local<'s, v8::Value>,- fallback: &str,-) -> Option<v8::Local<'s, v8::Object>> {- let global = scope.get_current_context().global(scope);- let data = get_private_value(scope, global, DATE_LOCALE_INTRINSICS_SLOT)?;- let intrinsics = callback_data::<LocaleIntrinsics>(scope, data)?;- defer_locale_list(scope, original, fallback, intrinsics)-}--fn locale_list_length_callback<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(data) = callback_data::<LocaleListData>(scope, args.data()) else {- return;- };- let receiver = v8::undefined(scope);- let Some(canonical) = call_script_visible_function(- scope,- data.canonicalize,- receiver.into(),- &[data.requested.unwrap_or_else(|| receiver.into())],- "canonicalize emulated Intl locales",- )- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok()) else {- return;- };-- // Match on the native service's available locales, using only canonical- // strings, not the page's array-like again. This records default identity- // for resolvedOptions (e.g. Collator otherwise minimizes fr-FR to fr).- // Actual selection remains native: preserve the ordered request list and- // put our default last, including when a caller selects localeMatcher.- let Some(supported) = call_script_visible_function(- scope,- data.supported,- receiver.into(),- &[canonical.into()],- "check native Intl locale support",- )- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok()) else {- return;- };- if supported.length() == 0 {- set_private_value(scope, args.this(), DEFAULT_LOCALE_SLOT, data.fallback);- }- for index in 0..canonical.length() {- let Some(value) = canonical.get_index(scope, index) else {- return;- };- let Some(key) = v8_string(scope, &index.to_string()) else {- return;- };- if args.this().create_data_property(scope, key.into(), value) != Some(true) {- return;- }- }- let Some(key) = v8_string(scope, &canonical.length().to_string()) else {- return;- };- if args- .this()- .create_data_property(scope, key.into(), data.fallback)- != Some(true)- {- return;- }- let length = v8::Number::new(scope, f64::from(canonical.length()) + 1.0);- // Replace the getter with an own data property. Repeated reads of this- // internal list must never repeat the page's getters or coercion hooks.- let key = v8str(scope, "length");- if args- .this()- .create_data_property(scope, key.into(), length.into())- == Some(true)- {- rv.set(length.into());- }-}diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rsdeleted file mode 100644index 4d8f408bd..000000000--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/overrides.rs+++ /dev/null@@ -1,17 +0,0 @@-use crate::util::date_locale_runtime_state_from_context;--/// Copies the target-owned Date/Intl emulation state for the current realm.-///-/// Every Window realm installed by a `ScriptVm` receives the same reference--/// counted runtime-state slot, so main, child, and isolated worlds observe one-/// applied renderer state without mirroring values into each V8 global object-/// or dereferencing the re-entrant `JsContextHost` callback pointer.-pub(super) fn current_date_locale_overrides(- scope: &mut v8::PinScope<'_, '_>,-) -> (Option<String>, Option<String>) {- let context = scope.get_current_context();- let Some(state) = date_locale_runtime_state_from_context(context) else {- return (None, None);- };- state.snapshot()-}diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rsindex 276f64e94..c6e7bbec7 100644--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs@@ -1,4 +1,3 @@-use super::date_locale_runtime::install_date_locale_runtime_state;use super::file_api::initialize_file_api_runtime_queues;use super::shared::*;use super::webassembly_runtime::install_webassembly_runtime_extensions;@@ -1970,7 +1969,6 @@ fn install_window_runtime_state<'s>(WINDOW_SECURE_CONTEXT_AVAILABLE_SLOT,v8::Boolean::new(scope, secure_context_available).into(),);- install_date_locale_runtime_state(scope, global)?;install_webassembly_runtime_state(scope, global)?;install_webidl_collection_iterator_intrinsics(scope, global)?;diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rsindex 5d0dc491e..d80bbb95c 100644--- a/moli-renderer-v8/src/lib.rs+++ b/moli-renderer-v8/src/lib.rs@@ -13,6 +13,7 @@ pub use moli_dom as dom;pub use moli_page_types as protocol_types;pub use moli_parser as parser;pub use moli_selector as selector;+pub use moli_v8_platform::ProcessEnvironmentOwner;pub use app_manifest::{RendererAppManifest, RendererAppManifestDisplayMode, RendererAppManifestError,diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rsindex e40c7d2a7..ede83fe66 100644--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs@@ -263,7 +263,6 @@ impl JsContextHost {app_manifest_link_change_epoch: 0,extra_http_headers: Vec::new(),permission_overrides: Vec::new(),- date_locale_runtime_state: Rc::new(DateLocaleRuntimeState::default()),idle_override: None,protocol_user_gesture_activation_depth: 0,current_input_event: None,diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rsindex d8960a4f2..c425ba38e 100644--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs@@ -1,7 +1,7 @@-use std::{collections::HashSet, rc::Rc};+use std::collections::HashSet;use super::{- DateLocaleRuntimeState, JsContextHost,+ JsContextHost,permissions::{permission_names_match, permission_override_name},};use crate::{@@ -704,22 +704,6 @@ impl JsContextHost {&self.permission_overrides}- pub(crate) fn set_locale_override(&self, locale: Option<&str>) {- self.date_locale_runtime_state.set_locale(locale);- }-- pub(crate) fn set_timezone_override(&self, timezone: Option<&str>) {- self.date_locale_runtime_state.set_timezone(timezone);- }-- pub(crate) fn date_locale_runtime_state(&self) -> Rc<DateLocaleRuntimeState> {- Rc::clone(&self.date_locale_runtime_state)- }-- pub(crate) fn timezone_override(&self) -> Option<String> {- self.date_locale_runtime_state.timezone()- }-pub(crate) fn set_idle_override(&mut self,idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex ebcb0f3ae..d4a83ecdf 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -797,50 +797,6 @@ impl PendingImageLoadEvent {pub(crate) type JsContextHostPageTaskCapabilities =crate::page_task_queue::RendererPageJsContextTaskSenders;-#[derive(Debug, Default)]-pub(crate) struct DateLocaleRuntimeState {- overrides: RefCell<DateLocaleOverrides>,-}--#[derive(Debug, Default)]-struct DateLocaleOverrides {- locale: Option<String>,- timezone: Option<String>,-}--impl DateLocaleRuntimeState {- pub(crate) fn set_locale(&self, locale: Option<&str>) {- // CDP accepts ICU locale IDs, while explicit Intl locale arguments- // require BCP47. Normalize once at the shared state boundary so every- // Window realm and Date locale method consumes the same language tag.- // Conversion errors fall back to native Intl validation of the input.- self.overrides.borrow_mut().locale = locale.map(|locale| {- let tag = v8::icu::language_tag_for_locale(locale).unwrap_or_else(|| locale.to_owned());- // V8's Isolate::DefaultLocale maps ICU's en_US_POSIX to en-US.- // Passing the otherwise valid POSIX tag explicitly would suppress- // number grouping, unlike Chromium's emulated default locale.- if tag == "en-US-u-va-posix" {- "en-US".to_owned()- } else {- tag- }- });- }-- pub(crate) fn set_timezone(&self, timezone: Option<&str>) {- self.overrides.borrow_mut().timezone = timezone.map(str::to_owned);- }-- pub(crate) fn snapshot(&self) -> (Option<String>, Option<String>) {- let overrides = self.overrides.borrow();- (overrides.locale.clone(), overrides.timezone.clone())- }-- pub(crate) fn timezone(&self) -> Option<String> {- self.overrides.borrow().timezone.clone()- }-}-pub(crate) struct JsContextHost {runtime: *mut DocumentRuntime,layout_policy: moli_page_types::LayoutPolicy,@@ -911,7 +867,6 @@ pub(crate) struct JsContextHost {app_manifest_link_change_epoch: u64,extra_http_headers: Vec<(String, String)>,permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,- date_locale_runtime_state: Rc<DateLocaleRuntimeState>,idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,protocol_user_gesture_activation_depth: usize,current_input_event: Option<crate::native_bridge::CurrentInputEvent>,diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rsindex 1d83686aa..73b520ecf 100644--- a/moli-renderer-v8/src/native_bridge/document.rs+++ b/moli-renderer-v8/src/native_bridge/document.rs@@ -968,14 +968,16 @@ fn document_last_modified_getter_function<'s>(return;};let runtime = unsafe { &*runtime_ptr };- let timezone_override = runtime.timezone_override();- let value = moli_time::format_document_last_modified_value(- runtime- .dom_host()- .document_source_last_modified_for_handle(handle),- moli_time::unix_epoch_millis(),- timezone_override.as_deref(),- );+ let format = |timestamp| {+ let offset = v8::icu::default_time_zone_offset_seconds(timestamp)?;+ moli_time::format_document_last_modified_value(timestamp, offset)+ };+ let value = runtime+ .dom_host()+ .document_source_last_modified_for_handle(handle)+ .and_then(format)+ .or_else(|| format(moli_time::unix_epoch_millis()))+ .unwrap_or_else(|| "01/01/1970 00:00:00".to_owned());set_document_string_return_value(scope, &mut rv, &value);}diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rsindex 48482eb2d..5f9cdf755 100644--- a/moli-renderer-v8/src/native_bridge/mod.rs+++ b/moli-renderer-v8/src/native_bridge/mod.rs@@ -7,8 +7,8 @@ mod collections;mod context_host;mod current_input;pub(crate) use context_host::{- DateLocaleRuntimeState, JsContextHost, JsContextHostPageTaskCapabilities,- PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,+ JsContextHost, JsContextHostPageTaskCapabilities, PendingScrollObservableEffects,+ PostParseAutofocusAdmission, ServiceWorkerWindowOwner,};pub(crate) use current_input::{CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rsindex 78ad3292f..cd6ecec48 100644--- a/moli-renderer-v8/src/runtime/owner.rs+++ b/moli-renderer-v8/src/runtime/owner.rs@@ -106,8 +106,6 @@ pub struct RendererPreparedDocumentCommitConfiguration {pub runtime_isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,pub permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,pub extra_http_headers: Vec<(String, String)>,- pub locale_override: Option<String>,- pub timezone_override: Option<String>,pub script_execution_disabled: bool,pub bypass_content_security_policy: bool,pub cpu_throttling_rate: f64,@@ -153,8 +151,6 @@ pub struct RendererCreateHtmlPageRequest {pub runtime_isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,pub permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,pub extra_http_headers: Vec<(String, String)>,- pub locale_override: Option<String>,- pub timezone_override: Option<String>,pub script_execution_disabled: bool,pub bypass_content_security_policy: bool,pub cpu_throttling_rate: f64,@@ -203,8 +199,6 @@ pub struct RendererCreateStreamingRawPageRequest {pub runtime_isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,pub permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,pub extra_http_headers: Vec<(String, String)>,- pub locale_override: Option<String>,- pub timezone_override: Option<String>,pub script_execution_disabled: bool,pub bypass_content_security_policy: bool,pub cpu_throttling_rate: f64,@@ -2089,8 +2083,6 @@ impl RendererOwnerHandle {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- None,- None,false,false,1.0,@@ -2121,8 +2113,6 @@ impl RendererOwnerHandle {runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -2156,8 +2146,6 @@ impl RendererOwnerHandle {runtime_isolated_worlds: Vec::new(),permission_overrides: Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -2199,8 +2187,6 @@ impl RendererOwnerHandle {runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -2233,8 +2219,6 @@ impl RendererOwnerHandle {runtime_isolated_worlds: Vec::new(),permission_overrides: Vec::new(),extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -6836,8 +6820,6 @@ impl RendererOwnerHandle {runtime_isolated_worlds,permission_overrides,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -6927,8 +6909,6 @@ impl RendererOwnerHandle {document_policy_container,document_default_language,document_last_modified,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -7151,8 +7131,6 @@ impl RendererOwnerHandle {runtime_isolated_worlds,permission_overrides,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -7230,8 +7208,6 @@ impl RendererOwnerHandle {document_policy_container,document_default_language,document_last_modified,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,diff --git a/moli-renderer-v8/src/runtime/owner_local_store/mod.rs b/moli-renderer-v8/src/runtime/owner_local_store/mod.rsindex 15202f87a..9102271d8 100644--- a/moli-renderer-v8/src/runtime/owner_local_store/mod.rs+++ b/moli-renderer-v8/src/runtime/owner_local_store/mod.rs@@ -910,8 +910,6 @@ impl RendererOwnerLocalStore {request.runtime_isolated_worlds = configuration.runtime_isolated_worlds;request.permission_overrides = configuration.permission_overrides;request.extra_http_headers = configuration.extra_http_headers;- request.locale_override = configuration.locale_override;- request.timezone_override = configuration.timezone_override;request.script_execution_disabled = configuration.script_execution_disabled;request.bypass_content_security_policy =configuration.bypass_content_security_policy;diff --git a/moli-renderer-v8/src/runtime/page.rs b/moli-renderer-v8/src/runtime/page.rsindex 9a68db8bb..862dda0a6 100644--- a/moli-renderer-v8/src/runtime/page.rs+++ b/moli-renderer-v8/src/runtime/page.rs@@ -238,8 +238,6 @@ impl JsRuntime {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -343,8 +341,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: crate::protocol_types::EmulatedMediaOverrides,@@ -376,8 +372,6 @@ impl JsRuntime {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -412,8 +406,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -452,8 +444,6 @@ impl JsRuntime {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -504,8 +494,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: crate::protocol_types::EmulatedMediaOverrides,@@ -532,8 +520,6 @@ impl JsRuntime {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -570,8 +556,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -606,8 +590,6 @@ impl JsRuntime {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -663,8 +645,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,cpu_throttling_rate: f64,emulated_media: crate::protocol_types::EmulatedMediaOverrides,@@ -701,8 +681,6 @@ impl JsRuntime {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,false,cpu_throttling_rate,@@ -745,8 +723,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -792,8 +768,6 @@ impl JsRuntime {document_start_scripts,runtime_bindings,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,@@ -841,8 +815,6 @@ impl JsRuntime {document_start_scripts: Vec<DocumentStartScript>,runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,extra_http_headers: Vec<(String, String)>,- locale_override: Option<String>,- timezone_override: Option<String>,script_execution_disabled: bool,bypass_content_security_policy: bool,cpu_throttling_rate: f64,@@ -882,8 +854,6 @@ impl JsRuntime {runtime_bindings,runtime_inspector_session_restore_snapshots,extra_http_headers,- locale_override,- timezone_override,script_execution_disabled,bypass_content_security_policy,cpu_throttling_rate,diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rsindex 75dfb37c1..46aaf3564 100644--- a/moli-renderer-v8/src/runtime/page_commands.rs+++ b/moli-renderer-v8/src/runtime/page_commands.rs@@ -1116,14 +1116,6 @@ impl PageVm {self.set_navigator_overrides(&overrides)?;Ok(RendererPageReply::Unit)}- RendererPageCommand::SetLocaleOverride(locale) => {- self.set_locale_override(locale.as_deref())?;- Ok(RendererPageReply::Unit)- }- RendererPageCommand::SetTimezoneOverride(timezone) => {- self.set_timezone_override(timezone.as_deref())?;- Ok(RendererPageReply::Unit)- }RendererPageCommand::SetScriptExecutionDisabled(disabled) => {self.set_script_execution_disabled(disabled);Ok(RendererPageReply::Unit)diff --git a/moli-renderer-v8/src/runtime/page_network.rs b/moli-renderer-v8/src/runtime/page_network.rsindex 38519c34a..d71524ad3 100644--- a/moli-renderer-v8/src/runtime/page_network.rs+++ b/moli-renderer-v8/src/runtime/page_network.rs@@ -149,16 +149,6 @@ impl PageVm {self.vm_mut().set_permission_overrides(overrides);}- pub(crate) fn set_locale_override(&mut self, locale: Option<&str>) -> Result<()> {- self.vm_mut().set_locale_override(locale);- Ok(())- }-- pub(crate) fn set_timezone_override(&mut self, timezone: Option<&str>) -> Result<()> {- self.vm_mut().set_timezone_override(timezone);- Ok(())- }-pub(crate) fn set_script_execution_disabled(&mut self, disabled: bool) {self.vm_mut().set_script_execution_disabled(disabled);}diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rsindex 184f22aea..cd44de0c2 100644--- a/moli-renderer-v8/src/runtime/page_surface.rs+++ b/moli-renderer-v8/src/runtime/page_surface.rs@@ -5308,8 +5308,6 @@ pub enum RendererPageCommand {SetPermissionOverrides(Vec<crate::protocol_types::PermissionOverrideRegistration>),SetIdleOverride(Option<crate::protocol_types::EmulatedIdleOverride>),SetNavigatorOverrides(moli_page_types::NavigatorOverrides),- SetLocaleOverride(Option<String>),- SetTimezoneOverride(Option<String>),SetScriptExecutionDisabled(bool),SetBypassContentSecurityPolicy(bool),SetCpuThrottlingRate(f64),diff --git a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rsindex 2f008bbea..7b4cc9a86 100644--- a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs+++ b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs@@ -1189,8 +1189,6 @@ impl PageVm {},document_default_language: None,document_last_modified: None,- locale_override: self.locale_override.clone(),- timezone_override: self.timezone_override.clone(),script_execution_disabled: self.script_execution_disabled(),bypass_content_security_policy: self.bypass_content_security_policy,cpu_throttling_rate: self.cpu_throttling_rate,diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rsindex 4df4e0cb3..23726c0c7 100644--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs@@ -1081,8 +1081,6 @@ pub(crate) struct PageVmEnvConfig {pub(crate) document_policy_container: crate::document_runtime::DocumentPolicyContainer,pub(crate) document_default_language: Option<String>,pub(crate) document_last_modified: Option<f64>,- pub(crate) locale_override: Option<String>,- pub(crate) timezone_override: Option<String>,pub(crate) script_execution_disabled: bool,pub(crate) bypass_content_security_policy: bool,pub(crate) cpu_throttling_rate: f64,@@ -1605,8 +1603,6 @@ pub(crate) struct PageVm {pub(super) runtime_inspector_protocol_configurations:BTreeMap<DevToolsSessionKey, RendererInspectorProtocolConfiguration>,pub(super) extra_http_headers: Vec<(String, String)>,- pub(super) locale_override: Option<String>,- pub(super) timezone_override: Option<String>,pub(super) bypass_content_security_policy: bool,pub(super) cpu_throttling_rate: f64,pub(super) emulated_media: crate::protocol_types::EmulatedMediaOverrides,@@ -4325,8 +4321,6 @@ impl PageVm {}).collect(),extra_http_headers: env.extra_http_headers.clone(),- locale_override: env.locale_override.clone(),- timezone_override: env.timezone_override.clone(),bypass_content_security_policy: env.bypass_content_security_policy,cpu_throttling_rate: env.cpu_throttling_rate,emulated_media: env.emulated_media.clone(),@@ -4387,12 +4381,6 @@ impl PageVm {page_vm.vm_mut().set_stored_runtime_bindings(&env.runtime_bindings);- page_vm- .vm_mut()- .set_locale_override(env.locale_override.as_deref());- page_vm- .vm_mut()- .set_timezone_override(env.timezone_override.as_deref());page_vm.vm_mut().set_emulated_media(&env.emulated_media);page_vm.vm_mut().set_idle_override(env.idle_override);page_vmdiff --git a/moli-renderer-v8/src/runtime/page_vm/test_support.rs b/moli-renderer-v8/src/runtime/page_vm/test_support.rsindex efbad25f3..a0ed28985 100644--- a/moli-renderer-v8/src/runtime/page_vm/test_support.rs+++ b/moli-renderer-v8/src/runtime/page_vm/test_support.rs@@ -666,8 +666,6 @@ fn minimal_test_page_vm_env_config() -> PageVmEnvConfig {document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/command_checkpoint.rs b/moli-renderer-v8/src/runtime/page_vm/tests/command_checkpoint.rsindex 61c410f9c..d311275ca 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/command_checkpoint.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/command_checkpoint.rs@@ -47,8 +47,9 @@ Promise.resolve().then(() => __passiveTimezoneCheckpoint += 1);).expect("timezone checkpoint witness should queue a reaction");- page_vm- .set_timezone_override(Some("UTC"))+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();+ environment+ .set_timezone(Some("UTC")).expect("timezone surface should update without executing Page work");assert_eq!(diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rsindex 7f77920c7..1f94af339 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs@@ -1805,8 +1805,6 @@ fn test_page_vm_with_loader_dom_host_hooks_and_response_referrer_policy(},document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -3194,8 +3192,6 @@ fn default_runtime_hooks_reject_direct_no_owner_page_vm_construction() {document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rsindex eb81afe46..3c37993bb 100644--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs@@ -2542,8 +2542,6 @@ document.body.setAttribute('data-error-state', [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -6316,8 +6314,6 @@ globalThis.__outerDocumentWriteScriptContinued = true;document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -14722,8 +14718,6 @@ document.body.setAttribute('data-result', [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -14904,8 +14898,6 @@ document.body.setAttribute('data-result', [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -15135,8 +15127,6 @@ document.body.setAttribute('data-result', [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -17135,8 +17125,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -17265,8 +17253,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -17405,8 +17391,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -17580,8 +17564,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -17905,8 +17887,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -18077,8 +18057,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -18167,8 +18145,6 @@ document.body.setAttribute("data-range", [document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming.rs b/moli-renderer-v8/src/runtime/phase_one/streaming.rsindex cb81dd458..913aa5f7d 100644--- a/moli-renderer-v8/src/runtime/phase_one/streaming.rs+++ b/moli-renderer-v8/src/runtime/phase_one/streaming.rs@@ -944,8 +944,6 @@ mod tests {document_policy_container: Default::default(),document_default_language: None,document_last_modified: None,- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rsindex a0a37a0c9..9587e9425 100644--- a/moli-renderer-v8/src/runtime/tests.rs+++ b/moli-renderer-v8/src/runtime/tests.rs@@ -90,8 +90,6 @@ async fn prepare_test_external_raw_document_with_content_type_and_reply_boundaryVec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -1503,8 +1501,6 @@ async fn streaming_unstyled_xml_converts_live_document_before_domcontentloaded()runtime_isolated_worlds: Vec::new(),permission_overrides: Vec::new(),extra_http_headers: Vec::new(),- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -1641,8 +1637,6 @@ async fn prepared_streaming_xml_document_waits_for_permit_and_uses_latest_config}],permission_overrides: Vec::new(),extra_http_headers: Vec::new(),- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -2270,8 +2264,6 @@ async fn external_raw_streaming_page_command_builds_phase_one_page() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -2619,8 +2611,6 @@ globalThis.__preparedCommitObserved = JSON.stringify([embedded_origin: None,}],extra_http_headers: Vec::new(),- locale_override: None,- timezone_override: None,script_execution_disabled: false,bypass_content_security_policy: false,cpu_throttling_rate: 1.0,@@ -3006,8 +2996,6 @@ async fn external_raw_streaming_empty_document_reaches_dom_content_loaded() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -3320,8 +3308,6 @@ async fn external_raw_streaming_delegates_post_load_meta_refresh_to_browser() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -3409,8 +3395,6 @@ async fn external_raw_streaming_defers_dcl_handler_navigation_to_page_reply() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -3496,8 +3480,6 @@ globalThis.__ordinaryAfterDcl = new Promise(resolve => {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -3589,8 +3571,6 @@ async fn renderer_owned_navigation_survives_page_creation_observer_detach() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -3818,8 +3798,6 @@ async fn per_page_isolate_policy_uses_distinct_isolates_and_isolates_contexts()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -3858,8 +3836,6 @@ async fn per_page_isolate_policy_uses_distinct_isolates_and_isolates_contexts()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4332,8 +4308,6 @@ async fn page_document_isolate_completes_real_v8_foreground_task() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4394,8 +4368,6 @@ async fn per_page_isolate_policy_routes_unhandled_rejections_to_originating_pageVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4426,8 +4398,6 @@ async fn per_page_isolate_policy_routes_unhandled_rejections_to_originating_pageVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4607,8 +4577,6 @@ async fn per_page_isolate_policy_keeps_window_open_routes_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4639,8 +4607,6 @@ async fn per_page_isolate_policy_keeps_window_open_routes_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4770,8 +4736,6 @@ async fn per_page_isolate_policy_keeps_dedicated_worker_events_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -4802,8 +4766,6 @@ async fn per_page_isolate_policy_keeps_dedicated_worker_events_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5051,8 +5013,6 @@ async fn per_page_isolate_policy_keeps_indexed_db_managers_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5083,8 +5043,6 @@ async fn per_page_isolate_policy_keeps_indexed_db_managers_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5158,8 +5116,6 @@ async fn per_page_isolate_policy_keeps_blob_urls_page_owned_after_other_page_cloVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5190,8 +5146,6 @@ async fn per_page_isolate_policy_keeps_blob_urls_page_owned_after_other_page_cloVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5294,8 +5248,6 @@ async fn per_page_isolate_policy_keeps_domparser_detached_docs_cleanup_neutral()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5326,8 +5278,6 @@ async fn per_page_isolate_policy_keeps_domparser_detached_docs_cleanup_neutral()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5436,8 +5386,6 @@ async fn per_page_isolate_policy_keeps_isolated_worlds_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5468,8 +5416,6 @@ async fn per_page_isolate_policy_keeps_isolated_worlds_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5671,8 +5617,6 @@ async fn per_page_isolate_policy_keeps_child_default_contexts_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5704,8 +5648,6 @@ async fn per_page_isolate_policy_keeps_child_default_contexts_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5892,8 +5834,6 @@ async fn per_page_isolate_policy_keeps_child_isolated_worlds_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -5926,8 +5866,6 @@ async fn per_page_isolate_policy_keeps_child_isolated_worlds_page_owned() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6138,8 +6076,6 @@ async fn per_page_isolate_policy_reuses_navigation_isolate_and_replaces_contextsVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6170,8 +6106,6 @@ async fn per_page_isolate_policy_reuses_navigation_isolate_and_replaces_contextsVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6474,8 +6408,6 @@ async fn per_page_isolate_parser_blocking_navigation_restores_replacement_inspecVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6589,8 +6521,6 @@ async fn per_page_isolate_navigation_churn_disposes_replaced_page_vms() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6715,8 +6645,6 @@ async fn per_page_isolate_policy_drops_stale_timer_after_navigation_replacement(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6747,8 +6675,6 @@ async fn per_page_isolate_policy_drops_stale_timer_after_navigation_replacement(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6888,8 +6814,6 @@ async fn per_page_isolate_policy_drops_stale_fetch_after_navigation_replacement(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -6920,8 +6844,6 @@ async fn per_page_isolate_policy_drops_stale_fetch_after_navigation_replacement(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7087,8 +7009,6 @@ export const marker = "late-module";"#,Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7119,8 +7039,6 @@ export const marker = "late-module";"#,Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7278,8 +7196,6 @@ async fn per_page_isolate_policy_drops_stale_worker_message_after_navigation_repVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7310,8 +7226,6 @@ async fn per_page_isolate_policy_drops_stale_worker_message_after_navigation_repVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7521,8 +7435,6 @@ async fn per_page_isolate_policy_routes_dynamic_import_to_originating_page() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7553,8 +7465,6 @@ async fn per_page_isolate_policy_routes_dynamic_import_to_originating_page() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7667,8 +7577,6 @@ async fn per_page_isolate_policy_keeps_shared_worker_alive_after_peer_page_closeVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -7699,8 +7607,6 @@ async fn per_page_isolate_policy_keeps_shared_worker_alive_after_peer_page_closeVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8064,8 +7970,6 @@ async fn per_page_isolate_policy_removes_only_navigated_shared_worker_client() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8096,8 +8000,6 @@ async fn per_page_isolate_policy_removes_only_navigated_shared_worker_client() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8254,8 +8156,6 @@ async fn per_page_isolate_policy_rejects_cross_page_runtime_object_ids() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8286,8 +8186,6 @@ async fn per_page_isolate_policy_rejects_cross_page_runtime_object_ids() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8529,8 +8427,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_context_idVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8561,8 +8457,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_context_idVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8724,8 +8618,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_default_coVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8756,8 +8648,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_default_coVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8903,8 +8793,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_child_contVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -8937,8 +8825,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_evaluate_child_contVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9170,8 +9056,6 @@ async fn per_page_isolate_policy_keeps_release_object_group_page_local() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9202,8 +9086,6 @@ async fn per_page_isolate_policy_keeps_release_object_group_page_local() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9352,8 +9234,6 @@ async fn per_page_isolate_policy_replays_runtime_contexts_per_page() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9384,8 +9264,6 @@ async fn per_page_isolate_policy_replays_runtime_contexts_per_page() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9595,8 +9473,6 @@ async fn runtime_enable_events_for_new_inspector_session_replays_existing_isolatVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9653,8 +9529,6 @@ async fn runtime_enable_events_include_renderer_root_frame_id_for_default_contexVec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -9732,8 +9606,6 @@ async fn per_page_isolate_policy_scopes_runtime_bindings_to_page_worlds() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -9764,8 +9636,6 @@ async fn per_page_isolate_policy_scopes_runtime_bindings_to_page_worlds() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10403,8 +10273,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_binding_context_id_Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10435,8 +10303,6 @@ async fn per_page_isolate_policy_scopes_same_numeric_runtime_binding_context_id_Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10621,8 +10487,6 @@ async fn per_page_isolate_policy_keeps_remove_binding_page_local() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10653,8 +10517,6 @@ async fn per_page_isolate_policy_keeps_remove_binding_page_local() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10798,8 +10660,6 @@ async fn per_page_isolate_policy_scopes_document_start_scripts_to_page_worlds()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10830,8 +10690,6 @@ async fn per_page_isolate_policy_scopes_document_start_scripts_to_page_worlds()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10946,8 +10804,6 @@ async fn per_page_isolate_policy_keeps_stored_document_start_scripts_page_local(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -10978,8 +10834,6 @@ async fn per_page_isolate_policy_keeps_stored_document_start_scripts_page_local(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -11125,8 +10979,6 @@ async fn stored_document_start_script_remove_uses_registry_key_namespace() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -11247,8 +11099,6 @@ async fn owner_loop_applies_subresource_fetch_completion_without_wait_command()Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -15443,8 +15293,6 @@ async fn owner_loop_ticks_page_timer_from_active_timer_index() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -15684,8 +15532,6 @@ async fn owner_runtime_expression_await_uses_page_wake_or_timer_deadline() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -16345,8 +16191,6 @@ async fn domcontentloaded_page_creation_reply_resumes_owner_to_load_without_exteVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -16433,8 +16277,6 @@ async fn document_commit_background_dcl_completion_resumes_owner_to_load() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -16748,8 +16590,6 @@ async fn owner_loop_completes_post_dcl_async_script_without_wait_command() {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -17137,8 +16977,6 @@ document.addEventListener("DOMContentLoaded", () => {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -17264,8 +17102,6 @@ blocked pageVec::new(),Vec::new(),Vec::new(),- None,- None,false,1.0,Default::default(),@@ -17719,8 +17555,6 @@ fn start_test_html_page_with_optional_indexed_db_manager_and_navigation_dispatchVec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,@@ -17795,8 +17629,6 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,diff --git a/moli-renderer-v8/src/runtime/tests/open_streaming.rs b/moli-renderer-v8/src/runtime/tests/open_streaming.rsindex 6560481d9..ad7cb581d 100644--- a/moli-renderer-v8/src/runtime/tests/open_streaming.rs+++ b/moli-renderer-v8/src/runtime/tests/open_streaming.rs@@ -194,8 +194,6 @@ impl OpenStreamingPage {Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,diff --git a/moli-renderer-v8/src/runtime/tests/redirect_chain.rs b/moli-renderer-v8/src/runtime/tests/redirect_chain.rsindex 22857f8c0..6719288da 100644--- a/moli-renderer-v8/src/runtime/tests/redirect_chain.rs+++ b/moli-renderer-v8/src/runtime/tests/redirect_chain.rs@@ -71,8 +71,6 @@ async fn assert_streaming_redirect_chain(reply_boundary: RendererReplyBoundary)Vec::new(),Vec::new(),Vec::new(),- None,- None,false,false,1.0,diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex d2f77a959..525eb0b41 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -5001,14 +5001,6 @@ impl ScriptVm {.set_permission_overrides(overrides);}- pub(super) fn set_locale_override(&self, locale: Option<&str>) {- self._context_host.borrow().set_locale_override(locale);- }-- pub(super) fn set_timezone_override(&self, timezone: Option<&str>) {- self._context_host.borrow().set_timezone_override(timezone);- }-pub(super) fn set_emulated_media(&mut self,overrides: &crate::protocol_types::EmulatedMediaOverrides,diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rsindex 956af5473..0107f6379 100644--- a/moli-renderer-v8/src/script_vm/document_isolate.rs+++ b/moli-renderer-v8/src/script_vm/document_isolate.rs@@ -710,6 +710,7 @@ fn with_entered_owned_isolate<T>(isolate.enter();}let _guard = EnteredIsolateGuard(isolate);+ moli_v8_platform::refresh_process_environment(isolate);op(isolate)}@@ -721,6 +722,7 @@ fn with_entered_owned_isolate_value<T>(isolate.enter();}let _guard = EnteredIsolateGuard(isolate);+ moli_v8_platform::refresh_process_environment(isolate);op(isolate)}diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rsindex d87698e41..46ad8f74f 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend.rs@@ -211,6 +211,12 @@ impl RendererInspectorSessionExecutorLocal {}command}) {+ // Pause-loop work bypasses normal isolate entry and foreground+ // notifications. Refresh for each nested command, not just when+ // entering the pause: process defaults may change while waiting.+ let isolate = unsafe { &mut *self.isolate.get() };+ let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(isolate) };+ moli_v8_platform::refresh_process_environment(isolate);match command {RendererInspectorNestedCommand::Main(command) => {self.dispatch_main_command(context_group_id, command);diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rsindex f3a3448af..4b7f13456 100644--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs@@ -92,6 +92,9 @@ pub(super) unsafe extern "C" fn dispatch_inspector_interrupt(};let mut isolate_ptr = isolate;let isolate = unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut(&mut isolate_ptr) };+ // Running JavaScript has not returned to the owner loop to consume the+ // foreground notification. An Inspector interrupt is also an observation.+ moli_v8_platform::refresh_process_environment(isolate);with_scoped_inspector_microtasks(isolate, || {session_executor.dispatch_next_io_command_from_interrupt();});@@ -115,6 +118,7 @@ pub(crate) fn dispatch_inspector_io_owner_wake(wake: RendererInspectorIoOwnerWakisolate.enter();}let _entered_isolate = EnteredOwnerWakeIsolateGuard(isolate);+ moli_v8_platform::refresh_process_environment(isolate);let scope = pin!(v8::HandleScope::new(isolate));let scope = &mut scope.init();with_scoped_inspector_microtasks(scope, || {diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rsindex 6d7bb4d79..c27d464f8 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs@@ -1,10 +1,91 @@use super::*;+#[test]+fn process_environment_defaults_reach_existing_and_new_isolates_without_wrapping_builtins() {+ let owner = moli_v8_platform::ProcessEnvironmentOwner::default();+ let mut peer = new_storage_test_vm("https://environment-peer.test/");+ let defaults = r#"JSON.stringify([+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone,+ new Date('2024-01-01T00:00:00Z').getTimezoneOffset()+ ])"#;+ let baseline = peer.eval(defaults).unwrap();+ peer.eval(+ r#"globalThis.originalDate = Date;+ globalThis.originalParse = Date.parse;+ globalThis.originalIntl = Intl.DateTimeFormat;+ globalThis.savedFormatter = new Intl.DateTimeFormat();+ globalThis.savedZone = savedFormatter.resolvedOptions().timeZone;+ globalThis.savedDate = new Date('2024-01-01T00:00:00Z');"#,+ )+ .unwrap();+ owner.set_locale(Some("fr_FR")).unwrap();+ owner.set_timezone(Some("Europe/Paris")).unwrap();+ assert_eq!(+ peer.eval(defaults).unwrap(),+ r#"["fr-FR","Europe/Paris",-60]"#+ );+ let mut late = new_storage_test_vm("https://environment-late.test/");+ assert_eq!(late.eval(defaults).unwrap(), peer.eval(defaults).unwrap());+ assert_eq!(+ peer.eval(+ r#"JSON.stringify([+ Date === originalDate, Date.parse === originalParse,+ Intl.DateTimeFormat === originalIntl,+ Function.prototype.toString.call(Date).includes('[native code]'),+ savedFormatter.resolvedOptions().timeZone === savedZone,+ savedDate.getTimezoneOffset() === -60+ ])"#+ )+ .unwrap(),+ "[true,true,true,true,true,true]"+ );+ drop(owner);+ assert_eq!(peer.eval(defaults).unwrap(), baseline);+ assert_eq!(late.eval(defaults).unwrap(), baseline);+}++#[test]+fn process_environment_claim_conflicts_and_failed_updates_leave_the_default_unchanged() {+ let peer_owner = moli_v8_platform::ProcessEnvironmentOwner::default();+ let owner = moli_v8_platform::ProcessEnvironmentOwner::default();+ let mut peer = new_storage_test_vm("https://environment-other.test/");+ let probe = r#"JSON.stringify([+ new Intl.NumberFormat().resolvedOptions().locale,+ new Intl.DateTimeFormat().resolvedOptions().timeZone+ ])"#;+ let baseline = peer.eval(probe).unwrap();+ owner.set_locale(Some("fr_FR")).unwrap();+ owner.set_timezone(Some("Europe/Paris")).unwrap();+ assert!(peer_owner.set_locale(Some("fr_FR")).is_err());+ assert!(peer_owner.set_locale(None).is_err());+ assert!(peer_owner.set_timezone(Some("Asia/Shanghai")).is_err());+ // Success without ownership must neither reset nor resurrect the claim.+ peer_owner.set_timezone(Some("Europe/Paris")).unwrap();+ peer_owner.set_timezone(None).unwrap();+ for invalid in ["_@invalid", "fr_FR\0en_US"] {+ assert!(owner.set_locale(Some(invalid)).is_err());+ }+ for invalid in ["Mars/Olympus", "Etc/Unknown", "UTC\0Europe/Paris"] {+ assert!(owner.set_timezone(Some(invalid)).is_err());+ }+ assert_eq!(peer.eval(probe).unwrap(), r#"["fr-FR","Europe/Paris"]"#);+ drop(owner);+ assert_eq!(peer.eval(probe).unwrap(), baseline);+ peer_owner.set_locale(Some("de_DE")).unwrap();+ peer_owner.set_timezone(Some("Asia/Shanghai")).unwrap();+ assert_eq!(peer.eval(probe).unwrap(), r#"["de-DE","Asia/Shanghai"]"#);+ peer_owner.set_locale(None).unwrap();+ peer_owner.set_timezone(None).unwrap();+ assert_eq!(peer.eval(probe).unwrap(), baseline);+}+#[test]fn emulation_date_constructor_converts_objects_once_with_default_hint() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-object-conversion.test/");for timezone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"] {- vm.set_timezone_override(Some(timezone));+ environment.set_timezone(Some(timezone)).unwrap();assert_eq!(vm.eval(r#"JSON.stringify((() => {const input = '2024-01-01T00:00:00';const expected = +new Date(2024, 0, 1);@@ -41,9 +122,10 @@ fn emulation_date_constructor_converts_objects_once_with_default_hint() {#[test]fn emulation_locale_fallback_covers_empty_and_unmatched_lists() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://intl-locale-fallback.test/");- vm.set_locale_override(Some("fr_FR"));- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_locale(Some("fr_FR")).unwrap();+ environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(vm.eval(r#"JSON.stringify((() => {const constructors = ['Collator', 'DateTimeFormat', 'DisplayNames', 'DurationFormat','ListFormat', 'NumberFormat', 'PluralRules', 'RelativeTimeFormat', 'Segmenter'];@@ -70,6 +152,7 @@ fn emulation_locale_fallback_covers_empty_and_unmatched_lists() {#[test]fn emulation_locale_fallback_preserves_native_observation_order() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://intl-locale-coercion.test/");let probe = r#"JSON.stringify((() => {const date = new Date(0);@@ -94,8 +177,8 @@ fn emulation_locale_fallback_preserves_native_observation_order() {});})())"#;let baseline = vm.eval(probe).unwrap();- vm.set_locale_override(Some("fr_FR"));- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_locale(Some("fr_FR")).unwrap();+ environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(vm.eval(probe).unwrap(), baseline);assert_eq!(vm.eval(@@ -119,9 +202,10 @@ fn emulation_locale_fallback_preserves_native_observation_order() {#[test]fn emulation_default_arguments_do_not_read_array_prototype() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://intl-private-arguments.test/");- vm.set_locale_override(Some("fr_FR"));- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_locale(Some("fr_FR")).unwrap();+ environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(vm.eval(r#"(() => {@@ -148,8 +232,9 @@ fn emulation_default_arguments_do_not_read_array_prototype() {#[test]fn emulation_timezone_boxes_primitive_options_without_losing_defaults() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://intl-primitive-options.test/");- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(vm.eval(r#"JSON.stringify((() => {const date = new Date('2024-01-01T00:00:00Z');const options = [42, true, '', Symbol(), 1n];@@ -165,9 +250,10 @@ fn emulation_timezone_boxes_primitive_options_without_losing_defaults() {#[test]fn emulation_date_time_first_legacy_hyphens_are_not_timezone_offsets() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-time-first.test/");for timezone in ["Europe/Paris", "America/New_York", "Asia/Shanghai"] {- vm.set_timezone_override(Some(timezone));+ environment.set_timezone(Some(timezone)).unwrap();assert_eq!(vm.eval(r#"JSON.stringify([@@ -185,7 +271,8 @@ fn emulation_date_time_first_legacy_hyphens_are_not_timezone_offsets() {}#[test]-fn date_and_intl_declared_wrappers_preserve_native_method_descriptors() {+fn date_and_intl_native_method_descriptors_are_unchanged() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-intl-declarations.test/");let probe = r#"JSON.stringify((() => {const constructors = ['Collator', 'DateTimeFormat', 'DisplayNames', 'DurationFormat',@@ -206,7 +293,7 @@ fn date_and_intl_declared_wrappers_preserve_native_method_descriptors() {});})())"#;for timezone in [None, Some("Europe/Paris"), None] {- vm.set_timezone_override(timezone);+ environment.set_timezone(timezone).unwrap();let rows: Vec<Vec<bool>> = serde_json::from_str(&vm.eval(probe).unwrap()).unwrap();assert!(rows.len() >= 9,@@ -220,6 +307,7 @@ fn date_and_intl_declared_wrappers_preserve_native_method_descriptors() {#[test]fn emulation_constructor_envelopes_do_not_convert_page_arguments() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-intl-raw-arguments.test/");let probe = r#"JSON.stringify((() => {const sentinel = {};@@ -258,8 +346,8 @@ fn emulation_constructor_envelopes_do_not_convert_page_arguments() {(Some("zh_Hant_TW"), Some("Asia/Shanghai")),(None, None),] {- vm.set_locale_override(locale);- vm.set_timezone_override(timezone);+ environment.set_locale(locale).unwrap();+ environment.set_timezone(timezone).unwrap();assert_eq!(vm.eval(probe).unwrap(),r#"[true,["0:number","1:number","2:number","3:number","4:number","5:number","6:number"],[2024,0,2,3,4,5,6],true,true,true,true,true,true,true,true]"#,@@ -270,8 +358,9 @@ fn emulation_constructor_envelopes_do_not_convert_page_arguments() {#[test]fn emulation_private_declarations_do_not_invoke_inherited_setters() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-intl-private-declarations.test/");- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_timezone(Some("Europe/Paris")).unwrap();let result = vm.eval(r#"JSON.stringify((() => {@@ -307,35 +396,10 @@ fn emulation_private_declarations_do_not_invoke_inherited_setters() {}#[test]-fn icu_locale_conversion_is_fallible_and_does_not_set_the_global_default() {- let mut vm = new_storage_test_vm("https://icu-language-tag.test/");- let baseline = vm- .eval("new Intl.NumberFormat().resolvedOptions().locale")- .unwrap();- assert_eq!(- v8::icu::language_tag_for_locale("en_US").as_deref(),- Some("en-US")- );- assert_eq!(- v8::icu::language_tag_for_locale("de_DE@collation=phonebook;numbers=latn").as_deref(),- Some("de-DE-u-co-phonebk-nu-latn")- );- assert_eq!(- v8::icu::language_tag_for_locale("en_US_POSIX").as_deref(),- Some("en-US-u-va-posix")- );- assert_eq!(v8::icu::language_tag_for_locale("en_US\0fr_FR"), None);- assert_eq!(- vm.eval("new Intl.NumberFormat().resolvedOptions().locale")- .unwrap(),- baseline- );-}--#[test]-fn emulation_icu_locale_ids_are_converted_before_default_intl_arguments() {+fn native_icu_locale_ids_drive_default_intl_behavior() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://icu-locale-defaults.test/");- vm.set_timezone_override(Some("UTC"));+ environment.set_timezone(Some("UTC")).unwrap();for (locale, language_tag) in [("en_US", "en-US"),("fr_FR", "fr-FR"),@@ -345,7 +409,7 @@ fn emulation_icu_locale_ids_are_converted_before_default_intl_arguments() {("th_TH@calendar=buddhist", "th-TH-u-ca-buddhist"),("ar_EG@numbers=latn", "ar-EG-u-nu-latn"),] {- vm.set_locale_override(Some(locale));+ environment.set_locale(Some(locale)).unwrap();let result = vm.eval(&format!(r#"(() => {{const tag = {language_tag:?};@@ -371,6 +435,7 @@ fn emulation_icu_locale_ids_are_converted_before_default_intl_arguments() {#[test]fn emulation_date_unicode_and_invalid_input_stays_invalid() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://unicode-date-input.test/");let probe = r#"JSON.stringify(['你好', '🙂', '+你好啊', '-🙂abc', '2024-你好', '\ud800', '\udfff',@@ -379,16 +444,17 @@ fn emulation_date_unicode_and_invalid_input_stays_invalid() {let expected = serde_json::to_string(&vec![(true, "Invalid Date"); 11]).unwrap();assert_eq!(vm.eval(probe).unwrap(), expected);for timezone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"] {- vm.set_timezone_override(Some(timezone));+ environment.set_timezone(Some(timezone)).unwrap();assert_eq!(vm.eval(probe).unwrap(), expected, "{timezone}");}}#[test]fn emulation_date_local_grammar_and_coercion_preserve_native_contracts() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://local-date-input.test/");for timezone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"] {- vm.set_timezone_override(Some(timezone));+ environment.set_timezone(Some(timezone)).unwrap();let result = vm.eval(r#"(() => {@@ -424,6 +490,7 @@ fn emulation_date_local_grammar_and_coercion_preserve_native_contracts() {#[test]fn emulation_timezone_does_not_change_option_get_order_or_exceptions() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://intl-option-read-order.test/");// Capture native behavior in this same V8, without hard-coding the list of// options that a particular V8 release implements or reads more than once.@@ -458,16 +525,17 @@ fn emulation_timezone_does_not_change_option_get_order_or_exceptions() {assert_eq!(row[2], true, "the original thrown value must propagate");assert_eq!(row[3], 1, "a throwing timeZone getter is read once");}- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_timezone(Some("Europe/Paris")).unwrap();assert_eq!(vm.eval(probe).unwrap(), baseline);- vm.set_timezone_override(None);+ environment.set_timezone(None).unwrap();assert_eq!(vm.eval(probe).unwrap(), baseline);}#[test]fn emulation_timezone_preserves_frozen_options_and_original_getter_receivers() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://frozen-intl-options.test/");- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_timezone(Some("Europe/Paris")).unwrap();let result = vm.eval(r#"(() => {const date = new Date('2024-01-01T00:00:00Z');const frozen = Object.freeze({timeZone: undefined});@@ -493,6 +561,7 @@ fn emulation_timezone_preserves_frozen_options_and_original_getter_receivers() {#[test]fn emulation_date_parsing_preserves_native_explicit_legacy_timezones() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://legacy-date-zones.test/");vm.eval(r#"globalThis.explicitDateInputs = [@@ -513,7 +582,7 @@ fn emulation_date_parsing_preserves_native_explicit_legacy_timezones() {"JSON.stringify(explicitDateInputs.map(input => [Date.parse(input), +new Date(input)]))";let baseline = vm.eval(probe).unwrap();for timezone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"] {- vm.set_timezone_override(Some(timezone));+ environment.set_timezone(Some(timezone)).unwrap();assert_eq!(vm.eval(probe).unwrap(), baseline, "{timezone}");}}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rsindex b3eb28012..1545f79d2 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs@@ -91,16 +91,17 @@ fn service_worker_csp_report_seen(#[test]fn date_locale_methods_use_shared_time_formatting_surface() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-locale-formatting.test/");- vm.set_timezone_override(Some("UTC"));+ environment.set_timezone(Some("UTC")).unwrap();let us = vm.eval("new Date(0).toLocaleString()").expect("default Date locale formatting should evaluate");assert_eq!(us, "1/1/1970, 12:00:00 AM");- vm.set_locale_override(Some("fr-FR"));- vm.set_timezone_override(Some("Asia/Shanghai"));+ environment.set_locale(Some("fr-FR")).unwrap();+ environment.set_timezone(Some("Asia/Shanghai")).unwrap();let result = vm.eval(@@ -141,6 +142,7 @@ fn date_locale_methods_use_shared_time_formatting_surface() {#[test]fn emulation_defaults_drive_real_intl_and_local_date_operations() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-locale-emulation-surface.test/");let baseline = vm.eval(@@ -167,8 +169,8 @@ fn emulation_defaults_drive_real_intl_and_local_date_operations() {"#,).expect("baseline Intl and Date surfaces should evaluate");- vm.set_locale_override(Some("fr-FR"));- vm.set_timezone_override(Some("Europe/Paris"));+ environment.set_locale(Some("fr-FR")).unwrap();+ environment.set_timezone(Some("Europe/Paris")).unwrap();let result = vm.eval(@@ -205,11 +207,11 @@ fn emulation_defaults_drive_real_intl_and_local_date_operations() {assert_eq!(result,- r#"{"locales":["fr-FR","fr-FR","fr-FR","fr-FR"],"timezone":"Europe/Paris","formattedAsFrench":true,"winter":[-60,1,1],"summer":[-120,2,1],"strings":["Mon Jan 01 2024 01:00:00 GMT+0100","Mon Jan 01 2024","01:00:00 GMT+0100"],"explicit":["en-US","UTC"],"invalidOptions":"TypeError","navigatorLanguage":"en-US"}"#+ r#"{"locales":["fr-FR","fr-FR","fr-FR","fr-FR"],"timezone":"Europe/Paris","formattedAsFrench":true,"winter":[-60,1,1],"summer":[-120,2,1],"strings":["Mon Jan 01 2024 01:00:00 GMT+0100 (heure normale d’Europe centrale)","Mon Jan 01 2024","01:00:00 GMT+0100 (heure normale d’Europe centrale)"],"explicit":["en-US","UTC"],"invalidOptions":"TypeError","navigatorLanguage":"en-US"}"#);- vm.set_locale_override(None);- vm.set_timezone_override(None);+ environment.set_locale(None).unwrap();+ environment.set_timezone(None).unwrap();let restored = vm.eval(r#"@@ -240,9 +242,10 @@ fn emulation_defaults_drive_real_intl_and_local_date_operations() {#[test]fn emulation_preserves_intl_construction_and_complete_local_date_operations() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-locale-native-semantics.test/");- vm.set_locale_override(Some("fr-FR"));- vm.set_timezone_override(Some("America/New_York"));+ environment.set_locale(Some("fr-FR")).unwrap();+ environment.set_timezone(Some("America/New_York")).unwrap();let result = vm.eval(@@ -336,6 +339,7 @@ fn emulation_preserves_intl_construction_and_complete_local_date_operations() {#[test]fn date_locale_override_updates_reach_existing_main_child_and_isolated_realms() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_parsed_test_vm("https://date-locale-shared-state.test/","<!doctype html><html><body></body></html>",@@ -368,8 +372,8 @@ document.body.appendChild(iframe);].join("|")"#;- vm.set_locale_override(Some("fr-FR"));- vm.set_timezone_override(Some("Asia/Shanghai"));+ environment.set_locale(Some("fr-FR")).unwrap();+ environment.set_timezone(Some("Asia/Shanghai")).unwrap();assert_eq!(vm.eval(PROBE).unwrap(), "fr-FR|Asia/Shanghai|8");assert_eq!(vm.eval_in_child_default_context(child_context_id, PROBE)@@ -382,8 +386,8 @@ document.body.appendChild(iframe);"fr-FR|Asia/Shanghai|8");- vm.set_locale_override(Some("en-US"));- vm.set_timezone_override(Some("America/New_York"));+ environment.set_locale(Some("en-US")).unwrap();+ environment.set_timezone(Some("America/New_York")).unwrap();assert_eq!(vm.eval(PROBE).unwrap(), "en-US|America/New_York|19");assert_eq!(vm.eval_in_child_default_context(child_context_id, PROBE)@@ -399,8 +403,9 @@ document.body.appendChild(iframe);#[test]fn date_locale_methods_are_declared_on_date_prototype() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://date-locale-declared.test/");- vm.set_timezone_override(Some("UTC"));+ environment.set_timezone(Some("UTC")).unwrap();let result = vm.eval(diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rsindex 021a57e66..2b3302ef9 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs@@ -3495,10 +3495,11 @@ fn document_metadata_uses_document_and_node_prototype_accessors() {#[test]fn document_last_modified_uses_source_time_and_readonly_document_accessor() {+ let environment = moli_v8_platform::ProcessEnvironmentOwner::default();let mut vm = new_storage_test_vm("https://document-last-modified.test/");vm.document_runtime.set_document_source_last_modified(Some(5_025_000.0));- vm.set_timezone_override(Some("Asia/Shanghai"));+ environment.set_timezone(Some("Asia/Shanghai")).unwrap();let result = vm.eval(diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rsindex d9f3a61b2..154626bac 100644--- a/moli-renderer-v8/src/util.rs+++ b/moli-renderer-v8/src/util.rs@@ -1,5 +1,5 @@use super::document_runtime::DomHandle;-use super::native_bridge::{DateLocaleRuntimeState, JsContextHost};+use super::native_bridge::JsContextHost;pub use moli_v8_util::{array_contains_strict, array_push_value, call_object_method, callback_data_index_value,callback_data_item, constructor_object, constructor_prototype, constructor_prototype_object,@@ -396,10 +396,6 @@ pub(super) fn install_context_host_pointer_slot() {let host_ptr =NonNull::new(host_ptr).expect("V8 context JsContextHost pointer should not be null");- // SAFETY: the caller installs context slots while the owning ScriptVm's- // `Rc<RefCell<JsContextHost>>` is alive. Clone the independently owned- // Date/Intl state before exposing the context to script.- let date_locale_runtime_state = unsafe { host_ptr.as_ref() }.date_locale_runtime_state();let previous = context.set_slot(Rc::new(ContextHostPointerSlot(host_ptr)));assert!(previous@@ -407,19 +403,6 @@ pub(super) fn install_context_host_pointer_slot(.is_none_or(|previous| previous.0 == host_ptr),"V8 context JsContextHost pointer must not be rebound");- let previous = context.set_slot(Rc::clone(&date_locale_runtime_state));- assert!(- previous- .as_ref()- .is_none_or(|previous| Rc::ptr_eq(previous, &date_locale_runtime_state)),- "V8 context Date/Intl runtime state must not be rebound"- );-}--pub(super) fn date_locale_runtime_state_from_context(- context: v8::Local<'_, v8::Context>,-) -> Option<Rc<DateLocaleRuntimeState>> {- context.get_slot::<DateLocaleRuntimeState>()}pub(super) fn context_host_ptr_from_context_slot(diff --git a/moli-renderer-v8/src/worker/thread/isolate.rs b/moli-renderer-v8/src/worker/thread/isolate.rsindex 80684b9dd..18af5fcc5 100644--- a/moli-renderer-v8/src/worker/thread/isolate.rs+++ b/moli-renderer-v8/src/worker/thread/isolate.rs@@ -64,6 +64,7 @@ impl WorkerIsolateState {}pub(super) fn worker_isolate_mut(&mut self) -> &mut v8::OwnedIsolate {+ moli_v8_platform::refresh_process_environment(&mut self.isolate);&mut self.isolate}@@ -74,6 +75,7 @@ impl WorkerIsolateState {pub(super) fn worker_isolate_and_runtime_inspector(&mut self,) -> (&mut v8::OwnedIsolate, Rc<WorkerRuntimeInspector>) {+ moli_v8_platform::refresh_process_environment(&mut self.isolate);(&mut self.isolate, Rc::clone(&self.runtime_inspector))}diff --git a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs b/moli-renderer-v8/src/worker/thread/runtime_inspector.rsindex 398dfe57b..c74a96405 100644--- a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs+++ b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs@@ -565,6 +565,10 @@ impl WorkerRuntimeInspector {}pub(super) fn execute_task(&self, isolate: &mut v8::Isolate, task: WorkerInspectorTask) {+ // This common entry also serves active-JS interrupts and nested pauses,+ // where neither ordinary Worker entry nor foreground tasks can refresh+ // V8's cached locale/timezone before the next Inspector observation.+ moli_v8_platform::refresh_process_environment(isolate);match task {WorkerInspectorTask::DispatchProtocolMessage {inspector_session_id,@@ -801,6 +805,59 @@ mod tests {rv.set(v8::Boolean::new(scope, inspector_policy_is_scoped).into());}+ #[test]+ fn worker_inspector_observes_environment_without_an_owner_loop_turn() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ isolate.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);+ let inspector = WorkerRuntimeInspector::new_for_test(&mut isolate);+ {+ let scope = pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ inspector.attach_context(+ context,+ v8::Global::new(scope, context),+ "https://worker-environment.test/worker.js",+ );+ }+ let read_defaults = |isolate: &mut v8::Isolate| {+ let (response_tx, mut response_rx) = tokio::sync::oneshot::channel();+ // Interrupts and nested pauses enter execute_task directly, without+ // WorkerIsolateState or a foreground task refreshing the isolate.+ inspector.execute_task(+ isolate,+ WorkerInspectorTask::DispatchProtocolMessage {+ inspector_session_id: None,+ raw_json: json!({+ "id": 1,+ "method": "Runtime.evaluate",+ "params": {+ "expression": "[new Intl.NumberFormat().resolvedOptions().locale, new Intl.DateTimeFormat().resolvedOptions().timeZone, new Date('2024-01-01T00:00:00Z').getTimezoneOffset()]",+ "returnByValue": true,+ },+ }).to_string(),+ deferred_response: None,+ response_tx,+ },+ );+ let messages = response_rx.try_recv().unwrap().unwrap();+ let response = protocol_response(&messages, 1);+ assert!(response.get("error").is_none(), "{response:#?}");+ response["result"]["result"]["value"].clone()+ };+ let baseline = read_defaults(&mut isolate);+ let owner = moli_v8_platform::ProcessEnvironmentOwner::default();+ owner.set_locale(Some("fr_FR")).unwrap();+ owner.set_timezone(Some("Europe/Paris")).unwrap();+ assert_eq!(+ read_defaults(&mut isolate),+ json!(["fr-FR", "Europe/Paris", -60])+ );+ owner.release();+ assert_eq!(read_defaults(&mut isolate), baseline);+ }+#[test]fn worker_inspector_dispatch_scopes_microtasks_and_restores_owner_policy() {crate::ensure_v8_for_test();diff --git a/moli-time/Cargo.toml b/moli-time/Cargo.tomlindex aa84172be..04326fdfa 100644--- a/moli-time/Cargo.toml+++ b/moli-time/Cargo.toml@@ -5,8 +5,7 @@ version = "0.1.0"edition = "2024"[dependencies]-temporal_rs = { version = "0.2.6", default-features = false, features = ["compiled_data"] }-time = { version = "0.3", features = ["large-dates", "local-offset"] }+time = { version = "0.3", features = ["large-dates"] }[lints]workspace = truediff --git a/moli-time/src/lib.rs b/moli-time/src/lib.rsindex bb499e28c..5c302cd75 100644--- a/moli-time/src/lib.rs+++ b/moli-time/src/lib.rs@@ -1,35 +1,13 @@-//! Shared browser-facing time helpers.-//!-//! Servo's date/time surfaces mostly lean on the `time` crate with large-date-//! support. Keep the V8 bridge thin by centralizing browser timestamp and-//! lightweight Date locale formatting behavior here.-+//! Shared browser clocks, timer scheduling, and timestamp formatting.+//! Date parsing, Intl and timezone rules belong to native V8/ICU.use std::{sync::OnceLock,time::{Duration, Instant, SystemTime, UNIX_EPOCH},};-use temporal_rs::{- PlainDateTime, TimeZone,- options::Disambiguation,- provider::{COMPILED_TZ_PROVIDER, TimeZoneProvider},-};mod timers;-pub use timers::{ReadyTimer, TimerId, TimerReadyAllowance, TimerScheduler};-#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub struct LocalDateFields {- pub year: i32,- pub month_zero_based: u8,- pub day: u8,- pub weekday_sunday_zero: u8,- pub hour: u8,- pub minute: u8,- pub second: u8,- pub millisecond: u16,-}-pub fn unix_epoch_millis() -> f64 {SystemTime::now().duration_since(UNIX_EPOCH)@@ -73,36 +51,24 @@ pub fn dom_time_since_origin_millis(time_origin: f64) -> f64 {coarsened_dom_time_millis((unix_epoch_millis() - time_origin).max(0.0))}-/// Formats the source modification time exposed by `Document.lastModified`.-///-/// The HTML surface uses the user's local time zone unless CDP has installed-/// an explicit override. A missing or unrepresentable source timestamp falls-/// back to the supplied current timestamp so callers can preserve the spec's-/// per-access fallback while tests remain deterministic.+/// Formats HTML's fixed, locale-independent Document.lastModified surface.+/// The caller supplies the timestamp-sensitive offset from the native+/// environment. This crate does not carry a second timezone database.pub fn format_document_last_modified_value(- source_timestamp_ms: Option<f64>,- current_timestamp_ms: f64,- timezone_override: Option<&str>,-) -> String {- let datetime = source_timestamp_ms- .and_then(offset_datetime_from_unix_millis)- .or_else(|| offset_datetime_from_unix_millis(current_timestamp_ms))- .unwrap_or(time::OffsetDateTime::UNIX_EPOCH);- let offset = match timezone_override {- Some(timezone) => resolve_time_zone_offset(datetime, timezone),- None => time::UtcOffset::local_offset_at(datetime).unwrap_or(time::UtcOffset::UTC),- };- let datetime = datetime.to_offset(offset);+ timestamp_ms: f64,+ offset_seconds: i32,+) -> Option<String> {+ let datetime = offset_datetime_from_unix_millis(timestamp_ms)?+ .to_offset(time::UtcOffset::from_whole_seconds(offset_seconds).ok()?);let month = u8::from(datetime.month());-- format!(+ Some(format!("{month:02}/{day:02}/{year:04} {hour:02}:{minute:02}:{second:02}",day = datetime.day(),year = datetime.year(),hour = datetime.hour(),minute = datetime.minute(),second = datetime.second(),- )+ ))}fn offset_datetime_from_unix_millis(timestamp_ms: f64) -> Option<time::OffsetDateTime> {@@ -122,275 +88,22 @@ fn offset_datetime_from_unix_millis(timestamp_ms: f64) -> Option<time::OffsetDattime::OffsetDateTime::from_unix_timestamp_nanos(whole_nanos.checked_add(fractional_nanos)?).ok()}-fn unix_millis_from_offset_datetime(datetime: time::OffsetDateTime) -> f64 {- const NANOS_PER_MILLISECOND: i128 = 1_000_000;- let nanos = datetime.unix_timestamp_nanos();- let whole_millis = nanos.div_euclid(NANOS_PER_MILLISECOND);- let fractional_nanos = nanos.rem_euclid(NANOS_PER_MILLISECOND);- whole_millis as f64 + fractional_nanos as f64 / NANOS_PER_MILLISECOND as f64-}--fn resolve_time_zone_offset(datetime: time::OffsetDateTime, timezone: &str) -> time::UtcOffset {- let Some(offset_seconds) =- time_zone_offset_seconds_at(datetime.unix_timestamp_nanos(), timezone)- else {- return time::UtcOffset::UTC;- };- time::UtcOffset::from_whole_seconds(offset_seconds).unwrap_or(time::UtcOffset::UTC)-}--/// Resolves the IANA time-zone offset used by local `Date` operations.-///-/// The lookup is timestamp-sensitive, so daylight-saving transitions follow-/// the same tzdb data used by Temporal instead of a fixed per-zone table.-pub fn time_zone_offset_seconds(timestamp_ms: f64, timezone: &str) -> Option<i32> {- let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;- time_zone_offset_seconds_at(datetime.unix_timestamp_nanos(), timezone)-}--pub fn local_time_zone_offset_seconds(timestamp_ms: f64) -> Option<i32> {- let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;- Some(- time::UtcOffset::local_offset_at(datetime)- .unwrap_or(time::UtcOffset::UTC)- .whole_seconds(),- )-}--/// Returns whether the compiled IANA database recognizes a time-zone name.-///-/// Protocol surfaces must reject an unknown override before publishing it to-/// a target. Date formatting deliberately has a UTC fallback for defensive-/// rendering, so using an offset lookup as validation after committing state-/// would turn an invalid CDP command into a misleading success.-pub fn is_valid_time_zone_identifier(timezone: &str) -> bool {- !timezone.is_empty() && COMPILED_TZ_PROVIDER.get(timezone.as_bytes()).is_ok()-}--pub fn local_date_fields(timestamp_ms: f64, timezone: Option<&str>) -> Option<LocalDateFields> {- let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;- let offset = timezone- .map(|timezone| resolve_time_zone_offset(datetime, timezone))- .unwrap_or_else(|| {- time::UtcOffset::local_offset_at(datetime).unwrap_or(time::UtcOffset::UTC)- });- let datetime = datetime.to_offset(offset);- Some(LocalDateFields {- year: datetime.year(),- month_zero_based: u8::from(datetime.month()).saturating_sub(1),- day: datetime.day(),- weekday_sunday_zero: datetime.weekday().number_days_from_sunday(),- hour: datetime.hour(),- minute: datetime.minute(),- second: datetime.second(),- millisecond: datetime.millisecond(),- })-}--/// Projects an instant into a UTC-shaped millisecond value whose fields are-/// the instant's local wall-clock fields in `timezone`.-///-/// V8's UTC Date setters already implement ECMAScript argument conversion and-/// field balancing. The renderer uses this projection as their temporary input-/// and converts the resulting fields back with-/// [`epoch_millis_for_local_wall_clock`], avoiding a second implementation of-/// Date's normalization rules.-pub fn local_wall_clock_as_utc_millis(timestamp_ms: f64, timezone: &str) -> Option<f64> {- let datetime = offset_datetime_from_unix_millis(timestamp_ms)?;- let offset = resolve_time_zone_offset(datetime, timezone);- let wall_clock = datetime- .to_offset(offset)- .replace_offset(time::UtcOffset::UTC);- Some(unix_millis_from_offset_datetime(wall_clock))-}--/// Interprets the UTC fields of `wall_clock_utc_ms` as a local wall-clock time-/// in `timezone` and returns the corresponding ECMAScript epoch milliseconds.-///-/// Temporal's `Compatible` disambiguation matches legacy Date behavior: it-/// chooses the earlier instant for a repeated clock time and advances across a-/// daylight-saving gap.-pub fn epoch_millis_for_local_wall_clock(wall_clock_utc_ms: f64, timezone: &str) -> Option<f64> {- let fields = offset_datetime_from_unix_millis(wall_clock_utc_ms)?;- let date_time = PlainDateTime::try_new_iso(- fields.year(),- u8::from(fields.month()),- fields.day(),- fields.hour(),- fields.minute(),- fields.second(),- fields.millisecond(),- 0,- 0,- )- .ok()?;- let time_zone = TimeZone::try_from_identifier_str(timezone).ok()?;- let zoned = date_time- .to_zoned_date_time(time_zone, Disambiguation::Compatible)- .ok()?;- Some(zoned.epoch_milliseconds() as f64)-}--pub fn format_date_local_string(timestamp_ms: f64, timezone: Option<&str>) -> String {- let Some(fields) = local_date_fields(timestamp_ms, timezone) else {- return "Invalid Date".to_owned();- };- format!(- "{} {} {:02} {:04} {}",- weekday_name(fields.weekday_sunday_zero),- month_name(fields.month_zero_based),- fields.day,- fields.year,- format_date_local_time_string(timestamp_ms, timezone),- )-}--pub fn format_date_local_date_string(timestamp_ms: f64, timezone: Option<&str>) -> String {- let Some(fields) = local_date_fields(timestamp_ms, timezone) else {- return "Invalid Date".to_owned();- };- format!(- "{} {} {:02} {:04}",- weekday_name(fields.weekday_sunday_zero),- month_name(fields.month_zero_based),- fields.day,- fields.year,- )-}--pub fn format_date_local_time_string(timestamp_ms: f64, timezone: Option<&str>) -> String {- let Some(fields) = local_date_fields(timestamp_ms, timezone) else {- return "Invalid Date".to_owned();- };- let offset_seconds = timezone- .and_then(|timezone| time_zone_offset_seconds(timestamp_ms, timezone))- .or_else(|| local_time_zone_offset_seconds(timestamp_ms))- .unwrap_or_default();- let sign = if offset_seconds < 0 { '-' } else { '+' };- let offset_minutes = offset_seconds.unsigned_abs() / 60;- let offset_hours = offset_minutes / 60;- let offset_minutes = offset_minutes % 60;- format!(- "{:02}:{:02}:{:02} GMT{sign}{offset_hours:02}{offset_minutes:02}",- fields.hour, fields.minute, fields.second,- )-}--fn weekday_name(weekday_sunday_zero: u8) -> &'static str {- ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]- .get(usize::from(weekday_sunday_zero))- .copied()- .unwrap_or("Invalid")-}--fn month_name(month_zero_based: u8) -> &'static str {- [- "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",- ]- .get(usize::from(month_zero_based))- .copied()- .unwrap_or("Invalid")-}--fn time_zone_offset_seconds_at(epoch_nanoseconds: i128, timezone: &str) -> Option<i32> {- let id = COMPILED_TZ_PROVIDER.get(timezone.as_bytes()).ok()?;- let seconds = COMPILED_TZ_PROVIDER- .transition_nanoseconds_for_utc_epoch_nanoseconds(id, epoch_nanoseconds)- .ok()?- .0;- i32::try_from(seconds).ok()-}-#[cfg(test)]mod tests {use super::*;#[test]- fn iana_timezone_offsets_follow_daylight_saving_transitions() {- let winter = 1_704_067_200_000.0; // 2024-01-01T00:00:00Z- let summer = 1_719_792_000_000.0; // 2024-07-01T00:00:00Z-- assert_eq!(time_zone_offset_seconds(winter, "Europe/Paris"), Some(3600));- assert_eq!(time_zone_offset_seconds(summer, "Europe/Paris"), Some(7200));- assert_eq!(- time_zone_offset_seconds(winter, "America/New_York"),- Some(-18_000)- );- assert_eq!(time_zone_offset_seconds(winter, "Not/AZone"), None);- assert_eq!(- local_date_fields(winter, Some("Europe/Paris")),- Some(LocalDateFields {- year: 2024,- month_zero_based: 0,- day: 1,- weekday_sunday_zero: 1,- hour: 1,- minute: 0,- second: 0,- millisecond: 0,- })- );- assert_eq!(- format_date_local_string(winter, Some("Europe/Paris")),- "Mon Jan 01 2024 01:00:00 GMT+0100"- );- }-- #[test]- fn time_zone_identifier_validation_uses_the_same_compiled_database() {- assert!(is_valid_time_zone_identifier("UTC"));- assert!(is_valid_time_zone_identifier("Europe/Paris"));- assert!(!is_valid_time_zone_identifier(""));- assert!(!is_valid_time_zone_identifier("Mars/Olympus"));- }-- #[test]- fn local_wall_clock_round_trips_through_the_selected_timezone() {- let instant = 1_704_067_200_123.0; // 2024-01-01T00:00:00.123Z- let wall_clock = local_wall_clock_as_utc_millis(instant, "Europe/Paris")- .expect("Paris wall clock should project");- assert_eq!(wall_clock, 1_704_070_800_123.0);- assert_eq!(- epoch_millis_for_local_wall_clock(wall_clock, "Europe/Paris"),- Some(instant)- );- }-- #[test]- fn epoch_millisecond_conversion_does_not_round_through_large_f64_nanoseconds() {- for timestamp_ms in [-1.0, 0.0, 1_704_130_496_789.0] {- let datetime = offset_datetime_from_unix_millis(timestamp_ms)- .expect("ECMAScript timestamp should be representable");- assert_eq!(unix_millis_from_offset_datetime(datetime), timestamp_ms);- }- }-- #[test]- fn local_wall_clock_uses_legacy_date_dst_disambiguation() {- // 2024-03-10T02:30 does not exist in New York. Compatible- // disambiguation advances it to 03:30 EDT (07:30Z).- assert_eq!(- epoch_millis_for_local_wall_clock(1_710_037_800_000.0, "America/New_York"),- Some(1_710_055_800_000.0)- );- // 2024-11-03T01:30 occurs twice. Legacy Date selects the earlier EDT- // occurrence (05:30Z).- assert_eq!(- epoch_millis_for_local_wall_clock(1_730_597_400_000.0, "America/New_York"),- Some(1_730_611_800_000.0)- );- }-- #[test]- fn document_last_modified_uses_source_time_and_current_fallback() {+ fn document_last_modified_formats_native_offsets_and_rejects_invalid_timestamps() {assert_eq!(- format_document_last_modified_value(Some(5_025_000.0), 0.0, Some("Asia/Shanghai")),- "01/01/1970 09:23:45"+ format_document_last_modified_value(5_025_000.0, 28_800).as_deref(),+ Some("01/01/1970 09:23:45"));assert_eq!(- format_document_last_modified_value(None, 1_704_067_384_005.0, Some("UTC")),- "01/01/2024 00:03:04"+ format_document_last_modified_value(1_704_067_384_005.0, 0).as_deref(),+ Some("01/01/2024 00:03:04"));+ assert_eq!(format_document_last_modified_value(f64::NAN, 0), None);+ assert_eq!(format_document_last_modified_value(f64::INFINITY, 0), None);}#[test]diff --git a/moli-v8-platform/src/environment.rs b/moli-v8-platform/src/environment.rsnew file mode 100644index 000000000..156b1357c--- /dev/null+++ b/moli-v8-platform/src/environment.rs@@ -0,0 +1,340 @@+//! Renderer-process defaults, not a second implementation of Date or Intl.+//!+//! Like Blink's TimeZoneController/LocaleController, one owner may override+//! each ICU default at a time. All Pages and Workers in this process observe+//! that default; independent environments require separate processes. Native+//! V8 retains responsibility for parsing, coercion, locale matching and DST.++use std::sync::{+ Arc, OnceLock,+ atomic::{AtomicU64, Ordering},+};++use parking_lot::Mutex;++use super::{+ dispatch_isolate_owner_callback, registered_isolate_owners, unsafe_raw_isolate_ptr_from_addr,+};++static GENERATION: AtomicU64 = AtomicU64::new(1);+static ENVIRONMENT: OnceLock<Mutex<Environment>> = OnceLock::new();++fn environment() -> &'static Mutex<Environment> {+ ENVIRONMENT.get_or_init(|| {+ Mutex::new(Environment {+ original_locale: v8::icu::get_default_locale_name(),+ original_timezone: v8::icu::get_default_time_zone(),+ locale: None,+ timezone: None,+ })+ })+}++struct Claim {+ owner: u64,+ value: String,+}++struct Environment {+ original_locale: String,+ original_timezone: String,+ locale: Option<Claim>,+ timezone: Option<Claim>,+}++/// Cloneable identity for one configuration owner. Explicit release handles+/// session/target retirement; final drop also restores defaults on failed setup.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ProcessEnvironmentOwner(Arc<Owner>);++#[derive(Debug, PartialEq, Eq)]+struct Owner(u64);++impl Default for ProcessEnvironmentOwner {+ fn default() -> Self {+ static NEXT_OWNER: AtomicU64 = AtomicU64::new(1);+ Self(Arc::new(Owner(NEXT_OWNER.fetch_add(1, Ordering::Relaxed))))+ }+}++impl ProcessEnvironmentOwner {+ pub fn set_locale(&self, locale: Option<&str>) -> Result<(), &'static str> {+ let locale = locale.filter(|value| !value.is_empty());+ let mut state = environment().lock();+ if state+ .locale+ .as_ref()+ .is_some_and(|claim| claim.owner != self.0.0)+ {+ return Err("Another locale override is already in effect");+ }+ if state.locale.as_ref().map(|claim| claim.value.as_str()) == locale {+ return Ok(());+ }+ if let Some(locale) = locale {+ if !v8::icu::try_set_default_locale(locale) {+ return Err("Invalid locale name");+ }+ } else {+ v8::icu::set_default_locale(&state.original_locale);+ }+ state.locale = locale.map(|value| Claim {+ owner: self.0.0,+ value: value.to_owned(),+ });+ changed(state);+ Ok(())+ }++ /// As in Chromium, requesting an already-installed timezone succeeds but+ /// does not acquire another lease. Clearing a non-owner is a no-op.+ pub fn set_timezone(&self, timezone: Option<&str>) -> Result<(), &'static str> {+ let timezone = timezone.filter(|value| !value.is_empty());+ let mut state = environment().lock();+ if state.timezone.as_ref().map(|claim| claim.value.as_str()) == timezone {+ return Ok(());+ }+ let owns = state+ .timezone+ .as_ref()+ .is_some_and(|claim| claim.owner == self.0.0);+ if timezone.is_none() && !owns {+ return Ok(());+ }+ if state.timezone.is_some() && !owns {+ return Err("Timezone override is already in effect");+ }+ let applied = match timezone {+ Some(timezone) => v8::icu::set_default_time_zone(timezone),+ None => v8::icu::restore_default_time_zone(&state.original_timezone),+ };+ if !applied {+ return Err("Invalid timezone id");+ }+ state.timezone = timezone.map(|value| Claim {+ owner: self.0.0,+ value: value.to_owned(),+ });+ changed(state);+ Ok(())+ }++ /// Only claims belonging to this identity, not another owner's inherited+ /// process defaults. This is also the sole source of retained policy state.+ pub fn locale(&self) -> Option<String> {+ let state = environment().lock();+ state+ .locale+ .as_ref()+ .filter(|claim| claim.owner == self.0.0)+ .map(|claim| claim.value.clone())+ }++ pub fn timezone(&self) -> Option<String> {+ let state = environment().lock();+ state+ .timezone+ .as_ref()+ .filter(|claim| claim.owner == self.0.0)+ .map(|claim| claim.value.clone())+ }++ pub fn has_override(&self) -> bool {+ let Some(environment) = ENVIRONMENT.get() else {+ return false;+ };+ let state = environment.lock();+ [&state.locale, &state.timezone]+ .iter()+ .any(|claim| claim.as_ref().is_some_and(|claim| claim.owner == self.0.0))+ }++ pub fn release(&self) {+ release(self.0.0);+ }+}++impl Drop for Owner {+ fn drop(&mut self) {+ release(self.0);+ }+}++fn release(owner: u64) {+ // Unused identities must not initialize ICU or capture host defaults.+ let Some(environment) = ENVIRONMENT.get() else {+ return;+ };+ let mut state = environment.lock();+ let locale = state+ .locale+ .as_ref()+ .is_some_and(|claim| claim.owner == owner);+ let timezone = state+ .timezone+ .as_ref()+ .is_some_and(|claim| claim.owner == owner);+ if !locale && !timezone {+ return;+ }+ if locale {+ v8::icu::set_default_locale(&state.original_locale);+ state.locale = None;+ }+ if timezone {+ let restored = v8::icu::restore_default_time_zone(&state.original_timezone);+ debug_assert!(restored, "the original ICU timezone must be restorable");+ state.timezone = None;+ }+ changed(state);+}++fn changed(state: parking_lot::MutexGuard<'_, Environment>) {+ GENERATION.fetch_add(1, Ordering::Release);+ drop(state);+ // Reuse the platform's exact-generation routes: no second isolate registry,+ // no timer/polling, and queued work is cancelled before isolate disposal.+ for owner in registered_isolate_owners() {+ let address = owner.isolate_addr;+ dispatch_isolate_owner_callback(owner, move || {+ // SAFETY: the platform invokes this on the registered owner thread+ // while its exact generation is live. Page owners enter the isolate+ // before running foreground tasks; Worker isolates remain entered.+ let mut isolate = unsafe {+ v8::Isolate::from_raw_isolate_ptr(unsafe_raw_isolate_ptr_from_addr(address))+ };+ refresh_process_environment(&mut isolate);+ });+ }+}++#[derive(Clone, Copy)]+struct ObservedEnvironment(u64);++/// Call at isolate entry as well as on the foreground notification. The entry+/// check prevents a command from overtaking a queued notification. No clean+/// operation resets V8 caches; changes within a turn coalesce by generation.+pub fn refresh_process_environment(isolate: &mut v8::Isolate) {+ let generation = GENERATION.load(Ordering::Acquire);+ if isolate+ .get_slot::<ObservedEnvironment>()+ .is_some_and(|seen| seen.0 == generation)+ {+ return;+ }+ isolate.locale_configuration_change_notification();+ // Redetect would overwrite the emulated ICU timezone with the host zone.+ isolate.date_time_configuration_change_notification(v8::TimeZoneDetection::Skip);+ isolate.set_slot(ObservedEnvironment(generation));+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn independent_claims_and_retained_owner_clones_release_only_their_own_defaults() {+ let locale = v8::icu::get_default_locale_name();+ let timezone = v8::icu::get_default_time_zone();+ let locale_owner = ProcessEnvironmentOwner::default();+ let retained = locale_owner.clone();+ let timezone_owner = ProcessEnvironmentOwner::default();+ locale_owner.set_locale(Some("fr_FR")).unwrap();+ timezone_owner.set_timezone(Some("Europe/Paris")).unwrap();+ drop(locale_owner);+ assert_eq!(retained.locale().as_deref(), Some("fr_FR"));+ retained.release();+ assert_eq!(v8::icu::get_default_locale_name(), locale);+ assert_eq!(v8::icu::get_default_time_zone(), "Europe/Paris");++ let replacement = ProcessEnvironmentOwner::default();+ replacement.set_locale(Some("de_DE")).unwrap();+ retained.release();+ drop(retained);+ assert_eq!(replacement.locale().as_deref(), Some("de_DE"));+ drop(timezone_owner);+ assert_eq!(v8::icu::get_default_time_zone(), timezone);+ assert_eq!(v8::icu::get_default_locale_name(), "de_DE");+ drop(replacement);+ assert_eq!(v8::icu::get_default_locale_name(), locale);+ }++ #[test]+ fn environment_notifications_use_exact_owner_generation_and_cancel_on_disposal() {+ moli_v8_init::ensure_v8_initialized(crate::create_platform);+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_time()+ .build()+ .unwrap();+ runtime.block_on(async {+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let mut isolate = v8::Isolate::new(Default::default());+ let registration = crate::V8PlatformIsolateRegistration::register(+ &mut isolate,+ crate::V8ForegroundTaskWake::queued(move |task| {+ let _ = tx.send(task);+ }),+ );+ let owner = ProcessEnvironmentOwner::default();+ let before = isolate.get_slot::<ObservedEnvironment>().unwrap().0;+ owner.set_locale(Some("fr_FR")).unwrap();+ let task = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())+ .await+ .expect("locale notification timed out")+ .expect("locale update must notify the registered isolate");+ assert_eq!(isolate.get_slot::<ObservedEnvironment>().unwrap().0, before);+ assert!(task.run());+ let after = isolate.get_slot::<ObservedEnvironment>().unwrap().0;+ assert!(after > before);+ // A clean entry and a repeated same-owner setting allocate no work.+ refresh_process_environment(&mut isolate);+ owner.set_locale(Some("fr_FR")).unwrap();+ assert_eq!(GENERATION.load(Ordering::Acquire), after);+ assert!(rx.try_recv().is_err());++ owner.set_timezone(Some("Europe/Paris")).unwrap();+ let stale = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())+ .await+ .expect("timezone notification timed out")+ .expect("timezone update must notify the isolate");+ // A command can overtake the notification without observing old caches.+ refresh_process_environment(&mut isolate);+ assert_eq!(+ isolate.get_slot::<ObservedEnvironment>().unwrap().0,+ GENERATION.load(Ordering::Acquire)+ );+ registration.unregister();+ drop(registration);+ drop(isolate);+ assert!(+ !stale.run(),+ "queued notification must not touch a disposed isolate"+ );+ });+ }++ #[test]+ fn native_default_zone_offset_includes_dst_and_rejects_invalid_input() {+ let owner = ProcessEnvironmentOwner::default();+ owner.set_timezone(Some("Europe/Paris")).unwrap();+ assert_eq!(+ v8::icu::default_time_zone_offset_seconds(1_704_067_200_000.0),+ Some(3600)+ );+ assert_eq!(+ v8::icu::default_time_zone_offset_seconds(1_719_792_000_000.0),+ Some(7200)+ );+ assert_eq!(v8::icu::default_time_zone_offset_seconds(f64::NAN), None);+ owner.set_timezone(Some("GMT+05:30")).unwrap();+ assert_eq!(+ v8::icu::default_time_zone_offset_seconds(1_704_067_200_000.0),+ Some(19_800)+ );+ let locale = v8::icu::get_default_locale_name();+ owner.set_locale(Some("en_US_POSIX")).unwrap();+ assert_eq!(v8::icu::get_default_locale_name(), "en_US_POSIX");+ owner.set_locale(None).unwrap();+ assert_eq!(v8::icu::get_default_locale_name(), locale);+ }+}diff --git a/moli-v8-platform/src/lib.rs b/moli-v8-platform/src/lib.rsindex c01716f61..b1e1b7502 100644--- a/moli-v8-platform/src/lib.rs+++ b/moli-v8-platform/src/lib.rs@@ -22,6 +22,9 @@ use tracing::trace;const MAX_V8_BACKGROUND_WORKER_THREADS: usize = 8;mod cpu_tracing;+mod environment;++pub use environment::{ProcessEnvironmentOwner, refresh_process_environment};pub use cpu_tracing::{PendingV8CpuTraceStart, PendingV8CpuTraceStop, V8CpuProfileSegment, V8CpuTraceConfiguration,@@ -312,6 +315,7 @@ pub struct V8PlatformIsolateRegistration {impl V8PlatformIsolateRegistration {pub fn register(isolate: &mut v8::OwnedIsolate, wake: V8ForegroundTaskWake) -> Self {+ refresh_process_environment(isolate);// SAFETY: `OwnedIsolate::as_raw_isolate_ptr` returns the V8 isolate// pointer used by platform foreground-task callbacks. Ownership remains// with `OwnedIsolate`; this registration stores only the address value.diff --git a/vendor/v8-152.2.0/src/icu.rs b/vendor/v8-152.2.0/src/icu.rsindex 5ab1647ab..bdb668fc7 100644--- a/vendor/v8-152.2.0/src/icu.rs+++ b/vendor/v8-152.2.0/src/icu.rs@@ -3,15 +3,35 @@ use crate::support::char;use std::ffi::CString;unsafe extern "C" {- fn icu_get_default_locale(output: *mut char, output_len: usize) -> usize;- fn icu_set_default_locale(locale: *const char);- fn uloc_toLanguageTag_78(+ fn ucal_open_78(+ zone: *const u16,+ length: i32,locale: *const char,- output: *mut char,+ kind: i32,+ error: *mut i32,+ ) -> *mut std::ffi::c_void;+ fn ucal_setMillis_78(+ calendar: *mut std::ffi::c_void,+ millis: f64,+ error: *mut i32,+ );+ fn ucal_get_78(+ calendar: *const std::ffi::c_void,+ field: i32,+ error: *mut i32,+ ) -> i32;+ fn ucal_close_78(calendar: *mut std::ffi::c_void);+ fn uloc_getDefault_78() -> *const char;+ fn uloc_getLanguage_78(+ locale: *const char,+ language: *mut char,capacity: i32,- strict: i8,error: *mut i32,) -> i32;+ fn uloc_setDefault_78(locale: *const char, error: *mut i32);+ fn ucal_setDefaultTimeZone_78(time_zone_id: *const u16, error: *mut i32);+ fn icu_get_default_locale(output: *mut char, output_len: usize) -> usize;+ fn icu_set_default_locale(locale: *const char);fn icu_get_default_time_zone(output: *mut char, output_len: usize) -> usize;fn icu_set_default_time_zone(time_zone_id: *const char) -> bool;fn udata_setCommonData_78(this: *const u8, error_code: *mut i32);@@ -79,44 +99,82 @@ pub fn set_default_locale(locale: &str) {}}-/// Converts an ICU locale ID (such as `en_US` or-/// `de_DE@collation=phonebook`) into its BCP47 language tag without changing-/// ICU's process-wide default. Uses the same ICU data as V8's Intl services.-///-/// Like `Locale::toLanguageTag`, conversion is non-strict: ICU omits fields-/// that cannot be represented in BCP47. Interior NULs and ICU errors return-/// `None`. The versioned ABI lives here alongside the other bundled-ICU APIs.-pub fn language_tag_for_locale(locale: &str) -> Option<String> {- let locale = CString::new(locale).ok()?;- let mut error = 0;- // SAFETY: locale is NUL-terminated and remains live throughout the call.- // ICU explicitly supports a null, zero-capacity output for preflighting.- let required = unsafe {- uloc_toLanguageTag_78(locale.as_ptr(), std::ptr::null_mut(), 0, 0, &mut error)+/// Returns the exact ICU locale ID, including legacy variants/keywords. Use+/// this, not a BCP47 serialization, when saving a default for later restoration.+/// Callers must serialize access with changes to ICU's process-wide default.+pub fn get_default_locale_name() -> String {+ // SAFETY: ICU returns a NUL-terminated default locale name.+ unsafe { std::ffi::CStr::from_ptr(uloc_getDefault_78()) }+ .to_string_lossy()+ .into_owned()+}++/// Validates the language component and sets ICU's default without panicking+/// on untrusted protocol input. Like Blink, this accepts ICU locale IDs rather+/// than requiring a BCP47 tag. A rejected value leaves the default unchanged.+pub fn try_set_default_locale(locale: &str) -> bool {+ let Ok(locale) = CString::new(locale) else {+ return false;};- const BUFFER_OVERFLOW_ERROR: i32 = 15;- if required < 0 || (error > 0 && error != BUFFER_OVERFLOW_ERROR) {- return None;- }- let capacity = required.checked_add(1)?;- let mut output = vec![0u8; usize::try_from(capacity).ok()?];- error = 0;- // SAFETY: output has `capacity` writable bytes, including the terminator.- // The input is immutable, so preflight and conversion see the same ID.- let written = unsafe {- uloc_toLanguageTag_78(+ let mut error = 0;+ let mut language = [0u8; 128];+ // SAFETY: the input and output buffers are live for the call.+ let length = unsafe {+ uloc_getLanguage_78(locale.as_ptr(),- output.as_mut_ptr().cast(),- capacity,- 0,+ language.as_mut_ptr().cast(),+ language.len() as i32,&mut error,)};- if error > 0 || written != required {+ if error > 0 || length <= 0 {+ return false;+ }+ // SAFETY: locale is NUL-terminated; ICU copies the locale ID.+ unsafe {+ uloc_setDefault_78(locale.as_ptr(), &mut error);+ }+ error <= 0+}++/// Restores a previously saved default, including ICU's valid fallback state+/// `Etc/Unknown`. Unlike the public override setter this must accept that state.+pub fn restore_default_time_zone(time_zone_id: &str) -> bool {+ if time_zone_id.contains('\0') {+ return false;+ }+ let mut id: Vec<u16> = time_zone_id.encode_utf16().collect();+ id.push(0);+ let mut error = 0;+ // SAFETY: id is a live, NUL-terminated UTF-16 string; ICU copies it.+ unsafe {+ ucal_setDefaultTimeZone_78(id.as_ptr(), &mut error);+ }+ error <= 0+}++/// Timestamp-sensitive offset from the same default ICU zone V8 uses. This+/// serves host Web APIs such as Document.lastModified without a second tzdb.+pub fn default_time_zone_offset_seconds(timestamp_ms: f64) -> Option<i32> {+ if !timestamp_ms.is_finite() {return None;}- output.truncate(usize::try_from(written).ok()?);- String::from_utf8(output).ok()+ let mut error = 0;+ // ICU: null zone selects the process default, UCAL_GREGORIAN = 1.+ // SAFETY: ICU copies the locale. Every non-null calendar is closed below,+ // including errors from setMillis/get; no borrowed ICU pointer escapes.+ unsafe {+ let calendar =+ ucal_open_78(std::ptr::null(), 0, c"en_US_POSIX".as_ptr(), 1, &mut error);+ if calendar.is_null() {+ return None;+ }+ ucal_setMillis_78(calendar, timestamp_ms, &mut error);+ let standard = ucal_get_78(calendar, 15, &mut error); // UCAL_ZONE_OFFSET+ let daylight = ucal_get_78(calendar, 16, &mut error); // UCAL_DST_OFFSET+ ucal_close_78(calendar);+ (error <= 0).then(|| standard.saturating_add(daylight) / 1000)+ }}/// Returns the id of ICU's current default time zone, usually an IANA id suchdiff --git a/vendor/v8-152.2.0/src/isolate.rs b/vendor/v8-152.2.0/src/isolate.rsindex 8cefc2413..a976320c5 100644--- a/vendor/v8-152.2.0/src/isolate.rs+++ b/vendor/v8-152.2.0/src/isolate.rs@@ -2093,6 +2093,19 @@ impl Isolate {}}+ /// Invalidates this isolate's cached default locale after an ICU default+ /// locale change. Existing explicitly constructed Intl objects are unchanged.+ pub fn locale_configuration_change_notification(&mut self) {+ unsafe extern "C" {+ fn v8__Isolate__LocaleConfigurationChangeNotification(+ isolate: *mut RealIsolate,+ );+ }+ unsafe {+ v8__Isolate__LocaleConfigurationChangeNotification(self.as_real_ptr());+ }+ }+/// Returns true if there is ongoing background work within V8 that will/// eventually post a foreground task, like asynchronous WebAssembly/// compilation.diff --git a/vendor/v8-152.2.0/src/locale_ext.cc b/vendor/v8-152.2.0/src/locale_ext.ccnew file mode 100644index 000000000..31d233306--- /dev/null+++ b/vendor/v8-152.2.0/src/locale_ext.cc@@ -0,0 +1,8 @@+// Copyright 2026 the Moli authors. MIT license.++#include "v8-isolate.h"++extern "C" void v8__Isolate__LocaleConfigurationChangeNotification(+ v8::Isolate* isolate) {+ isolate->LocaleConfigurationChangeNotification();+}