Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(emulation): preserve Date and Intl input semantics

ldm0156e16873dfa
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index c5fa6d0fe..43f50e00e 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -38,6 +38,18 @@ returns `InvalidParams` on initial admission, while its active override
Moli additionally locks down the latter state-preservation case in a focused
Rust protocol test.
+The default `locale-timezone-inputs` group adds input-boundary regressions for
+PR #369. It was calibrated on 2026-09-10 against `/usr/bin/chromium`
+145.0.7632.116 using the group unchanged: four timezone overrides cover Unicode
+and lone-surrogate rejection, explicit legacy timezone tokens, ISO date-only
+versus local parsing, weekday names and ignored comments, and frozen Intl
+options. Option getter order and receiver identity are compared with the
+same engine before emulation. Seven ICU locale IDs cover underscore/script
+forms, POSIX default normalization, and calendar/collation/numbering keywords;
+explicit page locales still use native BCP47 validation. Clearing overrides
+must restore the original defaults. The group has its own Moli process because
+the Unicode regression previously panicked in a native callback.
+
For example, Chromium resolves Playwright
`page.goto(..., wait_until="load")` after `Page.loadEventFired` but before the
later `Page.frameStoppedLoading` delivery. A smoke scenario that starts a new
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py b/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py
new file mode 100644
index 000000000..09089225e
--- /dev/null
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/locale_timezone_inputs.py
@@ -0,0 +1,161 @@
+from __future__ import annotations
+
+import contextlib
+from typing import Any
+
+from ..assertions import assert_equal, record
+
+
+EXPLICIT_DATE_INPUTS = [
+ *(f"Mon Jan 01 2024 00:00:00 {zone}" for zone in
+ ["PST", "PDT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "UT", "UTC", "GMT", "Z"]),
+ "Mon Jan 01 2024 00:00:00 +0530",
+ "Mon Jan 01 2024 00:00:00 -04:00",
+ "Mon Jan 01 2024 00:00:00 PST (Pacific Standard Time)",
+ "Mon Jan 01 2024 00:00:00 pSt\u00a0",
+ "2024-01-01T00:00:00Z",
+ "2024-01-01T00:00:00+02:00",
+ "2024", "2024-01", "2024-01-01", "+002024-01-01",
+ "2024-01-01\0PST",
+]
+
+DATE_VALUES = "inputs => inputs.map(input => [Date.parse(input), +new Date(input)])"
+
+OPTION_READS = """() => {
+ const date = new Date('2024-01-01T00:00:00Z');
+ return ['Intl', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method => {
+ const reads = [];
+ const receivers = [];
+ const target = Object.freeze({
+ timeZone: undefined,
+ get year() { receivers.push(this === options); return 'numeric'; },
+ get month() { receivers.push(this === options); return '2-digit'; }
+ });
+ const options = new Proxy(target, {
+ get(target, key, receiver) {
+ reads.push(String(key));
+ return Reflect.get(target, key, receiver);
+ }
+ });
+ if (method === 'Intl') new Intl.DateTimeFormat('en-US', options);
+ else date[method]('en-US', options);
+ return [method, reads, receivers];
+ });
+}"""
+
+
+async def run_locale_timezone_inputs_group(
+ browser: Any, _fixture: str, results: list[dict[str, Any]]
+) -> None:
+ """Input-boundary contracts, runnable unchanged against Moli or Chromium.
+
+ Keep this group process-isolated: the Unicode regression used to panic in
+ a native callback. Each completed matrix row is recorded before advancing.
+ Native explicit-zone parsing and option-access traces are captured before
+ emulation so host timezone and V8 option-list differences are not goldens.
+ """
+ context = await browser.new_context()
+ cdp = None
+ try:
+ page = await context.new_page()
+ await page.goto("data:text/html,<!doctype html><title>Date Intl inputs</title>")
+ cdp = await context.new_cdp_session(page)
+ baseline_dates = await page.evaluate(DATE_VALUES, EXPLICIT_DATE_INPUTS)
+ assert_equal(
+ all(value is not None for pair in baseline_dates for value in pair),
+ True, "explicit-zone reference inputs must be valid native dates",
+ )
+ baseline_reads = await page.evaluate(OPTION_READS)
+ baseline_defaults = await page.evaluate("""() => [
+ new Intl.NumberFormat().resolvedOptions().locale,
+ new Intl.DateTimeFormat().resolvedOptions().timeZone,
+ new Date(0).getTimezoneOffset()
+ ]""")
+ for zone in ["UTC", "Europe/Paris", "America/New_York", "Asia/Shanghai"]:
+ await cdp.send("Emulation.setTimezoneOverride", {"timezoneId": zone})
+ unicode_result = await page.evaluate(r"""() => [
+ '你好', '🙂', '+你好啊', '-🙂abc', '2024-你好', '\ud800', '\udfff'
+ ].map(input => [Number.isNaN(Date.parse(input)), new Date(input).toString()])""")
+ assert_equal(unicode_result, [[True, "Invalid Date"]] * 7, f"Unicode dates under {zone}")
+ record(results, "timezone_unicode_dates", {"timezone": zone, "inputs": 7})
+
+ dates = await page.evaluate(DATE_VALUES, EXPLICIT_DATE_INPUTS)
+ assert_equal(dates, baseline_dates, f"explicit date zones survive {zone}")
+ record(results, "timezone_explicit_dates", {"timezone": zone, "inputs": len(dates)})
+
+ local_dates = await page.evaluate(r"""() => [
+ ['Tue Jan 02 2024 00:00:00', 2],
+ ['Thu Jan 04 2024 00:00:00', 4],
+ ['Sat Jan 06 2024 00:00:00', 6],
+ ['Jan 02 2024 (PST)', 2],
+ ['Jan 02 2024 (PST (ignored)', 2],
+ [' 2024-01-02 ', 2],
+ ['2024-01-02T00:00:00', 2],
+ ['2024-01-02t00:00:00', 2],
+ ['Jan 02 2024\0PST', 2],
+ ['2024-01-02T00:00:00\0Z', 2]
+ ].map(([input, day]) => [
+ Date.parse(input) === +new Date(2024, 0, day),
+ +new Date(input) === +new Date(2024, 0, day)
+ ])""")
+ assert_equal(local_dates, [[True, True]] * 10, f"local ISO/legacy fields under {zone}")
+ record(results, "timezone_local_date_grammars", {"timezone": zone, "inputs": 10})
+
+ frozen = await page.evaluate("""zone => {
+ const date = new Date('2024-01-01T00:00:00Z');
+ const options = Object.freeze({timeZone: undefined});
+ const noGetter = Object.defineProperty({}, 'timeZone', {get: undefined});
+ return [
+ new Intl.DateTimeFormat('en-US', options).resolvedOptions().timeZone === zone,
+ new Intl.DateTimeFormat('en-US', noGetter).resolvedOptions().timeZone === zone,
+ new Intl.DateTimeFormat('en-US', Object.freeze({timeZone: 'UTC'})).resolvedOptions().timeZone === 'UTC',
+ ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>
+ date[method]('en-US', options) === date[method]('en-US', {timeZone: zone})),
+ options.timeZone === undefined && !Object.isExtensible(options)
+ ];
+ }""", zone)
+ assert_equal(frozen, [True] * 7, f"frozen options under {zone}")
+ assert_equal(await page.evaluate(OPTION_READS), baseline_reads, f"native option read order/receiver under {zone}")
+ record(results, "timezone_frozen_options_and_getters", {"timezone": zone})
+
+ for locale, tag in [
+ ("en_US", "en-US"), ("fr_FR", "fr-FR"),
+ ("zh_Hant_TW", "zh-Hant-TW"),
+ # V8's DefaultLocale deliberately maps ICU's POSIX locale to en-US.
+ ("en_US_POSIX", "en-US"),
+ ("de_DE@collation=phonebook", "de-DE-u-co-phonebk"),
+ ("th_TH@calendar=buddhist", "th-TH-u-ca-buddhist"),
+ ("ar_EG@numbers=latn", "ar-EG-u-nu-latn"),
+ ]:
+ await cdp.send("Emulation.setLocaleOverride", {"locale": locale})
+ result = await page.evaluate("""tag => {
+ const date = new Date('2024-01-01T00:00:00Z');
+ return [
+ new Intl.NumberFormat().format(1234.5) === new Intl.NumberFormat(tag).format(1234.5),
+ new Intl.DateTimeFormat().format(date) === new Intl.DateTimeFormat(tag).format(date),
+ new Intl.Collator().compare('ä', 'ae') === new Intl.Collator(tag).compare('ä', 'ae'),
+ ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>
+ date[method]() === date[method](tag)),
+ new Intl.NumberFormat('ja-JP').resolvedOptions().locale === 'ja-JP',
+ Intl.getCanonicalLocales(new Intl.NumberFormat().resolvedOptions().locale).length === 1,
+ (() => { try { new Intl.NumberFormat('en_US'); return false; }
+ catch (error) { return error instanceof RangeError; } })()
+ ];
+ }""", tag)
+ assert_equal(result, [True] * 9, f"ICU locale {locale} matches explicit {tag}")
+ record(results, "icu_locale_default_conversion", {"locale": locale, "language_tag": tag})
+
+ await cdp.send("Emulation.setLocaleOverride", {"locale": ""})
+ await cdp.send("Emulation.setTimezoneOverride", {"timezoneId": ""})
+ restored = await page.evaluate("""() => [
+ new Intl.NumberFormat().resolvedOptions().locale,
+ new Intl.DateTimeFormat().resolvedOptions().timeZone,
+ new Date(0).getTimezoneOffset()
+ ]""")
+ assert_equal(restored, baseline_defaults, "clearing input-matrix overrides restores native defaults")
+ record(results, "locale_timezone_input_matrix_reset")
+ finally:
+ if cdp is not None:
+ with contextlib.suppress(Exception):
+ await cdp.detach()
+ await context.close()
diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.py
index e161ec874..1783f985a 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py
@@ -39,6 +39,7 @@ from .groups.fetch_runtime_teardown import run_fetch_runtime_teardown_group
from .groups.inspector_routing import run_inspector_routing_group
from .groups.iframe_input import run_iframe_input_group
from .groups.layout_screenshot import run_layout_screenshot_group
+from .groups.locale_timezone_inputs import run_locale_timezone_inputs_group
from .groups.multi_client import run_multi_client_group
from .groups.multi_context import run_multi_context_group
from .groups.multi_page import run_multi_page_group
@@ -366,6 +367,12 @@ BROWSER_GROUPS: tuple[SmokeGroup, ...] = (
"browser",
run_emulation_storage_group,
),
+ SmokeGroup(
+ "locale-timezone-inputs",
+ "Unicode and legacy Date input, ICU locale IDs, frozen Intl options and getter contracts.",
+ "browser",
+ run_locale_timezone_inputs_group,
+ ),
SmokeGroup(
"multi-context",
"Cross-context owner-state routing and target isolation workflows.",
diff --git a/moli-cdp-smoke/tests/test_group_selection.py b/moli-cdp-smoke/tests/test_group_selection.py
index fd40533aa..a03a4c3e9 100644
--- a/moli-cdp-smoke/tests/test_group_selection.py
+++ b/moli-cdp-smoke/tests/test_group_selection.py
@@ -32,6 +32,7 @@ class GroupSelectionTests(unittest.TestCase):
self.assertIn("inspector-routing", DEFAULT_GROUP_NAMES)
self.assertIn("navigation-outcomes", DEFAULT_GROUP_NAMES)
self.assertIn("media-error", DEFAULT_GROUP_NAMES)
+ self.assertIn("locale-timezone-inputs", DEFAULT_GROUP_NAMES)
self.assertIn("webgl-viewport", DEFAULT_GROUP_NAMES)
self.assertIn("svg-rect", DEFAULT_GROUP_NAMES)
self.assertIn("target-lifecycle", DEFAULT_GROUP_NAMES)
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.rs
index 83fee24b7..56170d511 100644
--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date.rs
@@ -4,6 +4,7 @@ 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};
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.rs
index 9e993a75d..5537846bd 100644
--- 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.rs
@@ -3,6 +3,7 @@ use crate::util::call_script_visible_function;
use anyhow::{Result, anyhow};
use super::super::overrides::current_date_locale_overrides;
+use super::parse_input::local_date_parse_input_as_utc;
pub(super) fn install_date_parse_override<'s>(
scope: &mut v8::PinScope<'s, '_>,
@@ -236,20 +237,9 @@ fn date_constructor_timezone_arguments<'s>(
if !input.is_string() {
return Ok(None);
}
- let input = input.to_rust_string_lossy(scope);
- let Some(utc_input) = local_date_parse_input_as_utc(&input) else {
- return Ok(None);
- };
- let utc_input = v8_string(scope, &utc_input).ok_or(())?;
- let receiver = v8::undefined(scope);
- call_script_visible_function(
- scope,
- date_parse,
- receiver.into(),
- &[utc_input.into()],
- "parse a local Date constructor string as UTC fields",
- )
- .ok_or(())?
+ 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);
};
@@ -265,14 +255,18 @@ fn single_date_epoch_argument<'s>(
wall_clock_utc_ms: Option<f64>,
timezone: &str,
) -> v8::Local<'s, v8::Array> {
- let epoch_ms = 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);
+ 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>,
@@ -289,87 +283,46 @@ fn date_parse_callback<'s>(
return;
};
let (_, timezone_override) = current_date_locale_overrides(scope);
- let utc_input = timezone_override
- .as_deref()
- .and_then(|_| local_date_parse_input_as_utc(&input.to_rust_string_lossy(scope)));
- let parse_input: v8::Local<'s, v8::Value> = match utc_input.as_deref() {
- Some(utc_input) => {
- let Some(utc_input) = v8_string(scope, utc_input) else {
- return;
- };
- utc_input.into()
- }
- None => input.into(),
- };
+ 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);
- let Some(parsed) = call_script_visible_function(
+ // 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(),
- &[parse_input],
+ &[input.into()],
"Date.parse",
- ) else {
- return;
- };
- let Some(timezone) = timezone_override.as_deref() else {
- rv.set(parsed);
- return;
+ )?;
+ let Some(timezone) = timezone else {
+ return Some(parsed);
};
- if utc_input.is_none() {
- rv.set(parsed);
- return;
- }
- let epoch = single_date_epoch_argument(scope, parsed.number_value(scope), timezone);
- if let Some(epoch) = epoch.get_index(scope, 0) {
- rv.set(epoch);
- }
-}
-
-fn local_date_parse_input_as_utc(input: &str) -> Option<String> {
- let input = input.trim();
- if input.is_empty() || iso_date_only_uses_utc(input) {
- return None;
+ if !parsed.number_value(scope)?.is_finite() {
+ return Some(parsed);
}
- let lower = input.to_ascii_lowercase();
- if lower.ends_with('z') || lower.contains("gmt") || lower.contains("utc") {
- return None;
- }
- let time_start = input
- .find(['T', 't'])
- .or_else(|| input.find(':'))
- .unwrap_or(input.len());
- if input[time_start..].contains(['+', '-']) {
- return None;
- }
- if input.contains(['T', 't']) {
- Some(format!("{input}Z"))
- } else {
- // Legacy date grammars generally recognize a UTC suffix more reliably
- // than a trailing ISO `Z`.
- Some(format!("{input} UTC"))
- }
-}
-
-fn iso_date_only_uses_utc(input: &str) -> bool {
- let (year_len, rest) = match input.as_bytes().first() {
- Some(b'+' | b'-') if input.len() >= 7 => (7, &input[7..]),
- _ if input.len() >= 4 => (4, &input[4..]),
- _ => return false,
+ let Some(utc_input) = local_date_parse_input_as_utc(&input.to_rust_string_lossy(scope)) else {
+ return Some(parsed);
};
- if !input.as_bytes()[..year_len]
- .iter()
- .enumerate()
- .all(|(index, byte)| (index == 0 && matches!(byte, b'+' | b'-')) || byte.is_ascii_digit())
- {
- return false;
- }
- rest.is_empty()
- || (rest.len() == 3
- && rest.as_bytes()[0] == b'-'
- && rest.as_bytes()[1..3].iter().all(u8::is_ascii_digit))
- || (rest.len() == 6
- && rest.as_bytes()[0] == b'-'
- && rest.as_bytes()[3] == b'-'
- && rest.as_bytes()[1..3].iter().all(u8::is_ascii_digit)
- && rest.as_bytes()[4..6].iter().all(u8::is_ascii_digit))
+ 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.rs
new file mode 100644
index 000000000..5fdfc9349
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/parse_input.rs
@@ -0,0 +1,151 @@
+//! 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",
+ ];
+ let mut chars = input.char_indices().peekable();
+ let mut comments = 0;
+ let mut number_seen = false;
+ let mut time_seen = false;
+ 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;
+ } else if ch == ':' {
+ time_seen = true;
+ } else if matches!(ch, '+' | '-') && time_seen {
+ 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);
+ }
+ }
+ }
+ (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",
+ ] {
+ 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 ",
+ ] {
+ 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/intl.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs
index 340f5f768..38c2126c8 100644
--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/intl.rs
@@ -302,15 +302,21 @@ pub(super) fn intl_datetime_options_with_default_timezone<'s>(
// behalf.
return Some(original);
}
- let target = original.to_object(scope)?;
+ 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]].
+ // 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 handler = v8::Object::new(scope);
let timezone = v8_string(scope, timezone)?;
+ let data = v8::Array::new_with_elements(scope, &[original.into(), timezone.into()]);
let get = v8::Function::builder(intl_datetime_options_get_callback)
- .data(timezone.into())
+ .data(data.into())
.length(3)
.build(scope)?;
let _ = handler.set(scope, v8str(scope, "get").into(), get.into());
@@ -327,7 +333,14 @@ fn intl_datetime_options_get_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let Ok(target) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
+ let Ok(data) = v8::Local::<v8::Array>::try_from(args.data()) else {
+ rv.set_undefined();
+ return;
+ };
+ let Some(target) = data
+ .get_index(scope, 0)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ else {
rv.set_undefined();
return;
};
@@ -339,7 +352,9 @@ fn intl_datetime_options_get_callback<'s>(
return;
};
if key.strict_equals(v8str(scope, "timeZone").into()) && value.is_undefined() {
- rv.set(args.data());
+ if let Some(timezone) = data.get_index(scope, 1) {
+ rv.set(timezone);
+ }
} else {
rv.set(value);
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
index e89ce96c0..ebcb0f3ae 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -810,7 +810,21 @@ struct DateLocaleOverrides {
impl DateLocaleRuntimeState {
pub(crate) fn set_locale(&self, locale: Option<&str>) {
- self.overrides.borrow_mut().locale = locale.map(str::to_owned);
+ // 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>) {
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.rs
new file mode 100644
index 000000000..46783a0af
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs
@@ -0,0 +1,213 @@
+use super::*;
+
+#[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() {
+ let mut vm = new_storage_test_vm("https://icu-locale-defaults.test/");
+ vm.set_timezone_override(Some("UTC"));
+ for (locale, language_tag) in [
+ ("en_US", "en-US"),
+ ("fr_FR", "fr-FR"),
+ ("zh_Hant_TW", "zh-Hant-TW"),
+ ("en_US_POSIX", "en-US"),
+ ("de_DE@collation=phonebook", "de-DE-u-co-phonebk"),
+ ("th_TH@calendar=buddhist", "th-TH-u-ca-buddhist"),
+ ("ar_EG@numbers=latn", "ar-EG-u-nu-latn"),
+ ] {
+ vm.set_locale_override(Some(locale));
+ let result = vm.eval(&format!(
+ r#"(() => {{
+ const tag = {language_tag:?};
+ const date = new Date('2024-01-01T00:00:00Z');
+ return JSON.stringify([
+ new Intl.NumberFormat().format(1234.5) === new Intl.NumberFormat(tag).format(1234.5),
+ new Intl.DateTimeFormat().format(date) === new Intl.DateTimeFormat(tag).format(date),
+ new Intl.Collator().compare('ä', 'ae') === new Intl.Collator(tag).compare('ä', 'ae'),
+ date.toLocaleString() === date.toLocaleString(tag),
+ date.toLocaleDateString() === date.toLocaleDateString(tag),
+ date.toLocaleTimeString() === date.toLocaleTimeString(tag),
+ new Intl.NumberFormat('ja-JP').resolvedOptions().locale === 'ja-JP'
+ ]);
+ }})()"#
+ ));
+ assert_eq!(
+ result.unwrap(),
+ "[true,true,true,true,true,true,true]",
+ "{locale}"
+ );
+ }
+}
+
+#[test]
+fn emulation_date_unicode_and_invalid_input_stays_invalid() {
+ let mut vm = new_storage_test_vm("https://unicode-date-input.test/");
+ let probe = r#"JSON.stringify([
+ '你好', '🙂', '+你好啊', '-🙂abc', '2024-你好', '\ud800', '\udfff',
+ '2024-13-01', '2024-01-32', '2024-01-01Tgarbage', '-000000-01-01T00:00:00'
+ ].map(input => [Number.isNaN(Date.parse(input)), new Date(input).toString()]))"#;
+ 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));
+ assert_eq!(vm.eval(probe).unwrap(), expected, "{timezone}");
+ }
+}
+
+#[test]
+fn emulation_date_local_grammar_and_coercion_preserve_native_contracts() {
+ 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));
+ let result = vm
+ .eval(
+ r#"(() => {
+ const inputs = [
+ ['Tue Jan 02 2024 00:00:00', 2], ['Thu Jan 04 2024 00:00:00', 4],
+ ['Sat Jan 06 2024 00:00:00', 6], ['Jan 02 2024 (PST)', 2],
+ ['Jan 02 2024 (PST (ignored)', 2], [' 2024-01-02 ', 2],
+ ['2024-01-02T00:00:00', 2], ['2024-01-02t00:00:00', 2],
+ ['Jan 02 2024\0PST', 2], ['2024-01-02T00:00:00\0Z', 2]
+ ];
+ const localFields = inputs.every(([input, day]) =>
+ Date.parse(input) === +new Date(2024, 0, day) &&
+ +new Date(input) === +new Date(2024, 0, day));
+ const conversions = [];
+ const parsed = Date.parse({[Symbol.toPrimitive](hint) {
+ conversions.push(hint); return 'Tue Jan 02 2024 00:00:00';
+ }});
+ const sentinel = {};
+ let exceptionPreserved = false;
+ try { Date.parse({toString() { throw sentinel; }}); }
+ catch (error) { exceptionPreserved = error === sentinel; }
+ let symbolRejected = false;
+ try { Date.parse(Symbol()); }
+ catch (error) { symbolRejected = error instanceof TypeError; }
+ return JSON.stringify([localFields, conversions,
+ parsed === +new Date(2024, 0, 2), exceptionPreserved, symbolRejected]);
+ })()"#,
+ )
+ .unwrap();
+ assert_eq!(result, r#"[true,["string"],true,true,true]"#, "{timezone}");
+ }
+}
+
+#[test]
+fn emulation_timezone_does_not_change_option_get_order_or_exceptions() {
+ 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.
+ let probe = r#"JSON.stringify((() => {
+ const date = new Date('2024-01-01T00:00:00Z');
+ return ['Intl', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method => {
+ const call = options => method === 'Intl'
+ ? new Intl.DateTimeFormat('en-US', options) : date[method]('en-US', options);
+ const reads = [];
+ const receivers = [];
+ const target = Object.freeze({timeZone: undefined,
+ get year() { receivers.push(this === options); return 'numeric'; }
+ });
+ const options = new Proxy(target, {
+ get(target, key, receiver) {
+ reads.push(String(key)); return Reflect.get(target, key, receiver);
+ }
+ });
+ call(options);
+ const sentinel = {};
+ let throwsSame = false;
+ let count = 0;
+ try { call(Object.freeze({get timeZone() { count++; throw sentinel; }})); }
+ catch (error) { throwsSame = error === sentinel; }
+ return [reads, receivers, throwsSame, count];
+ });
+ })())"#;
+ let baseline = vm.eval(probe).unwrap();
+ let rows: Vec<serde_json::Value> = serde_json::from_str(&baseline).unwrap();
+ assert_eq!(rows.len(), 4);
+ for row in rows {
+ 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"));
+ assert_eq!(vm.eval(probe).unwrap(), baseline);
+ vm.set_timezone_override(None);
+ assert_eq!(vm.eval(probe).unwrap(), baseline);
+}
+
+#[test]
+fn emulation_timezone_preserves_frozen_options_and_original_getter_receivers() {
+ let mut vm = new_storage_test_vm("https://frozen-intl-options.test/");
+ vm.set_timezone_override(Some("Europe/Paris"));
+ let result = vm.eval(r#"(() => {
+ const date = new Date('2024-01-01T00:00:00Z');
+ const frozen = Object.freeze({timeZone: undefined});
+ const noGetter = Object.defineProperty({}, 'timeZone', {get: undefined});
+ let receiver;
+ const accessor = Object.freeze({get timeZone() { receiver = this; return undefined; }});
+ const methods = ['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'];
+ return JSON.stringify([
+ new Intl.DateTimeFormat('en-US', frozen).resolvedOptions().timeZone,
+ new Intl.DateTimeFormat('en-US', noGetter).resolvedOptions().timeZone,
+ new Intl.DateTimeFormat('en-US', accessor).resolvedOptions().timeZone,
+ receiver === accessor,
+ ...methods.map(method => date[method]('en-US', frozen) === date[method]('en-US', {timeZone: 'Europe/Paris'})),
+ new Intl.DateTimeFormat('en-US', Object.freeze({timeZone: 'UTC'})).resolvedOptions().timeZone,
+ frozen.timeZone === undefined
+ ]);
+ })()"#).unwrap();
+ assert_eq!(
+ result,
+ r#"["Europe/Paris","Europe/Paris","Europe/Paris",true,true,true,true,"UTC",true]"#
+ );
+}
+
+#[test]
+fn emulation_date_parsing_preserves_native_explicit_legacy_timezones() {
+ let mut vm = new_storage_test_vm("https://legacy-date-zones.test/");
+ vm.eval(
+ r#"globalThis.explicitDateInputs = [
+ 'Mon Jan 01 2024 00:00:00 PST', 'Mon Jan 01 2024 00:00:00 EST',
+ 'Mon Jan 01 2024 00:00:00 PDT', 'Mon Jan 01 2024 00:00:00 EDT',
+ 'Mon Jan 01 2024 00:00:00 CST', 'Mon Jan 01 2024 00:00:00 CDT',
+ 'Mon Jan 01 2024 00:00:00 MST', 'Mon Jan 01 2024 00:00:00 MDT',
+ 'Mon Jan 01 2024 00:00:00 UT', 'Mon Jan 01 2024 00:00:00 UTC',
+ 'Mon Jan 01 2024 00:00:00 GMT', 'Mon Jan 01 2024 00:00:00 Z',
+ 'Mon Jan 01 2024 00:00:00 +0530', 'Mon Jan 01 2024 00:00:00 -04:00',
+ '2024-01-01T00:00:00Z', '2024-01-01T00:00:00+02:00',
+ '2024', '2024-01', '2024-01-01', '+002024-01-01', '2024-01-01\0PST',
+ 'Mon Jan 01 2024 00:00:00 PST (Pacific Standard Time)'
+ ]; JSON.stringify(explicitDateInputs.map(Date.parse))"#,
+ )
+ .unwrap();
+ let probe =
+ "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));
+ assert_eq!(vm.eval(probe).unwrap(), baseline, "{timezone}");
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index f42bbc4da..7df1f0fa2 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -11,6 +11,7 @@ mod crypto_subtle_hmac;
mod crypto_subtle_jwk;
mod crypto_subtle_other;
mod crypto_subtle_x25519;
+mod date_locale;
mod details;
mod event_handlers;
mod events_selection_storage;
diff --git a/vendor/v8-152.2.0/src/icu.rs b/vendor/v8-152.2.0/src/icu.rs
index cb76ce0cf..5ab1647ab 100644
--- a/vendor/v8-152.2.0/src/icu.rs
+++ b/vendor/v8-152.2.0/src/icu.rs
@@ -5,6 +5,13 @@ 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(
+ locale: *const char,
+ output: *mut char,
+ capacity: i32,
+ strict: i8,
+ error: *mut i32,
+ ) -> i32;
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);
@@ -72,6 +79,46 @@ 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)
+ };
+ 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(
+ locale.as_ptr(),
+ output.as_mut_ptr().cast(),
+ capacity,
+ 0,
+ &mut error,
+ )
+ };
+ if error > 0 || written != required {
+ return None;
+ }
+ output.truncate(usize::try_from(written).ok()?);
+ String::from_utf8(output).ok()
+}
+
/// Returns the id of ICU's current default time zone, usually an IANA id such
/// as `"America/New_York"`. It can also be a custom offset id like
/// `"GMT+05:00"`, either because one was installed with