Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(renderer): declare Date and Intl wrapper bindings

ldm09fda0f808e25
diff --git a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
index 1e71cddbe..50fd0617c 100644
--- a/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime.rs
@@ -2,6 +2,7 @@ use super::*;
use crate::util::{get_private_value, set_private_value};
use anyhow::Result;
+mod bindings;
mod date;
mod intl;
mod overrides;
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.rs
new file mode 100644
index 000000000..1417e39ae
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/bindings.rs
@@ -0,0 +1,57 @@
+//! 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/constructor.rs b/moli-renderer-v8/src/context_bootstrap/date_locale_runtime/date/constructor.rs
index 5537846bd..d302b710a 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
@@ -1,10 +1,54 @@
-use super::*;
-use crate::util::call_script_visible_function;
+use super::{DateIntrinsic, original_date_method};
+use crate::util::{call_script_visible_function, 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>,
@@ -12,16 +56,7 @@ pub(super) fn install_date_parse_override<'s>(
let Some(original) = original_date_method(scope, DateIntrinsic::Parse) else {
return Ok(());
};
- let Some(wrapper) = v8::Function::builder(date_parse_callback)
- .data(original.into())
- .length(1)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Date.parse override"));
- };
- let name = v8str(scope, "parse");
- wrapper.set_name(name);
- let _ = constructor.set(scope, name.into(), wrapper.into());
+ DateParseDeclaration::new(original).initialize(scope, constructor.into())?;
Ok(())
}
@@ -31,22 +66,7 @@ pub(super) fn install_date_constructor_proxy<'s>(
original: v8::Local<'s, v8::Function>,
prototype: v8::Local<'s, v8::Object>,
) -> Result<()> {
- let Some(reflect) = global
- .get(scope, v8str(scope, "Reflect").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return Ok(());
- };
- let Some(reflect_apply) = reflect
- .get(scope, v8str(scope, "apply").into())
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- return Ok(());
- };
- let Some(reflect_construct) = reflect
- .get(scope, v8str(scope, "construct").into())
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
+ let Some(reflect) = ReflectIntrinsics::from_global(scope, global) else {
return Ok(());
};
let Some(date_now) = original_date_method(scope, DateIntrinsic::Now) else {
@@ -59,32 +79,11 @@ pub(super) fn install_date_constructor_proxy<'s>(
return Ok(());
};
- let apply_data = v8::Array::new(scope, 2);
- let _ = apply_data.set_index(scope, 0, reflect_apply.into());
- let _ = apply_data.set_index(scope, 1, date_now.into());
- let Some(apply) = v8::Function::builder(date_constructor_proxy_apply_callback)
- .data(apply_data.into())
- .length(3)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Date constructor apply trap"));
- };
-
- let construct_data = v8::Array::new(scope, 3);
- let _ = construct_data.set_index(scope, 0, reflect_construct.into());
- let _ = construct_data.set_index(scope, 1, date_utc.into());
- let _ = construct_data.set_index(scope, 2, date_parse.into());
- let Some(construct) = v8::Function::builder(date_constructor_proxy_construct_callback)
- .data(construct_data.into())
- .length(3)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Date constructor construct trap"));
- };
-
- let handler = v8::Object::new(scope);
- let _ = handler.set(scope, v8str(scope, "apply").into(), apply.into());
- let _ = handler.set(scope, v8str(scope, "construct").into(), construct.into());
+ 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"));
};
@@ -98,31 +97,19 @@ fn date_constructor_proxy_apply_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let Ok(data) = v8::Local::<v8::Array>::try_from(args.data()) else {
- rv.set_undefined();
+ let Some(data) = callback_data::<DateApplyData>(scope, args.data()) else {
return;
};
- let Some(reflect_apply) = data
- .get_index(scope, 0)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- rv.set_undefined();
- return;
- };
- let Some(date_now) = data
- .get_index(scope, 1)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- rv.set_undefined();
+ 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.get(0), args.get(1), args.get(2)];
+ let invoke_args = [args.target, args.receiver, args.arguments.into()];
let receiver = v8::undefined(scope);
if let Some(result) = call_script_visible_function(
scope,
- reflect_apply,
+ data.reflect_apply,
receiver.into(),
&invoke_args,
"invoke Date through Reflect.apply",
@@ -138,7 +125,7 @@ fn date_constructor_proxy_apply_callback<'s>(
let receiver = v8::undefined(scope);
let Some(now) = call_script_visible_function(
scope,
- date_now,
+ data.date_now,
receiver.into(),
&[],
"read Date.now for the Date function",
@@ -159,51 +146,32 @@ fn date_constructor_proxy_construct_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let Ok(data) = v8::Local::<v8::Array>::try_from(args.data()) else {
- rv.set_undefined();
- return;
- };
- let Some(reflect_construct) = data
- .get_index(scope, 0)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- rv.set_undefined();
+ let Some(data) = callback_data::<DateConstructData>(scope, args.data()) else {
return;
};
- let Some(date_utc) = data
- .get_index(scope, 1)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- rv.set_undefined();
- return;
- };
- let Some(date_parse) = data
- .get_index(scope, 2)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- rv.set_undefined();
- return;
- };
- let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
- rv.set_undefined();
+ 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, arguments, date_utc, date_parse, timezone,
+ scope,
+ args.arguments,
+ data.date_utc,
+ data.date_parse,
+ timezone,
) {
Ok(replacement) => replacement,
Err(()) => return,
},
None => None,
};
- let arguments = replacement.unwrap_or(arguments);
- let invoke_args = [args.get(0), arguments.into(), args.get(2)];
+ 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,
- reflect_construct,
+ data.reflect_construct,
receiver.into(),
&invoke_args,
"invoke Date through Reflect.construct",
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 38c2126c8..7396d8427 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
@@ -1,45 +1,80 @@
-use super::*;
-use crate::util::{call_script_visible_function, get_private_value, set_private_value};
+use crate::util::{
+ call_script_visible_function, 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;
const INTL_DEFAULT_LOCALE_SLOT: &str = "__moliIntlDefaultLocale";
-#[derive(Clone, Copy)]
-enum IntlConstructorKind {
- Collator,
- DateTimeFormat,
- DisplayNames,
- DurationFormat,
- ListFormat,
- NumberFormat,
- PluralRules,
- RelativeTimeFormat,
- Segmenter,
+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,
}
-impl IntlConstructorKind {
- const ALL: &[(Self, &str)] = &[
- (Self::Collator, "Collator"),
- (Self::DateTimeFormat, "DateTimeFormat"),
- (Self::DisplayNames, "DisplayNames"),
- (Self::DurationFormat, "DurationFormat"),
- (Self::ListFormat, "ListFormat"),
- (Self::NumberFormat, "NumberFormat"),
- (Self::PluralRules, "PluralRules"),
- (Self::RelativeTimeFormat, "RelativeTimeFormat"),
- (Self::Segmenter, "Segmenter"),
- ];
+#[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: (),
+}
- fn from_index(index: u32) -> Option<Self> {
- Self::ALL.get(index as usize).map(|(kind, _)| *kind)
- }
+#[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: (),
+}
- fn uses_timezone(self) -> bool {
- matches!(self, Self::DateTimeFormat)
- }
+#[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>,
@@ -55,25 +90,10 @@ pub(super) fn install_intl_default_override_constructors<'s>(
let Ok(intl) = v8::Local::<v8::Object>::try_from(intl_value) else {
return Ok(());
};
- let Some(reflect) = global
- .get(scope, v8str(scope, "Reflect").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return Ok(());
- };
- let Some(reflect_apply) = reflect
- .get(scope, v8str(scope, "apply").into())
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
+ let Some(reflect) = ReflectIntrinsics::from_global(scope, global) else {
return Ok(());
};
- let Some(reflect_construct) = reflect
- .get(scope, v8str(scope, "construct").into())
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- return Ok(());
- };
- for (index, (_, name)) in IntlConstructorKind::ALL.iter().enumerate() {
+ for &name in INTL_CONSTRUCTORS {
let key = v8str(scope, name);
let Some(original_value) = intl.get(scope, key.into()) else {
continue;
@@ -87,30 +107,12 @@ pub(super) fn install_intl_default_override_constructors<'s>(
{
install_intl_resolved_options_override(scope, prototype)?;
}
- let kind = v8::Integer::new_from_unsigned(scope, index as u32);
- let apply_data = v8::Array::new(scope, 2);
- let _ = apply_data.set_index(scope, 0, kind.into());
- let _ = apply_data.set_index(scope, 1, reflect_apply.into());
- let Some(apply) = v8::Function::builder(intl_constructor_proxy_apply_callback)
- .data(apply_data.into())
- .length(3)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Intl.{name} apply trap"));
- };
- let construct_data = v8::Array::new(scope, 2);
- let _ = construct_data.set_index(scope, 0, kind.into());
- let _ = construct_data.set_index(scope, 1, reflect_construct.into());
- let Some(construct) = v8::Function::builder(intl_constructor_proxy_construct_callback)
- .data(construct_data.into())
- .length(3)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Intl.{name} construct trap"));
- };
- let handler = v8::Object::new(scope);
- let _ = handler.set(scope, v8str(scope, "apply").into(), apply.into());
- let _ = handler.set(scope, v8str(scope, "construct").into(), construct.into());
+ let uses_timezone = name == "DateTimeFormat";
+ let handler = IntlConstructorHandler::new(
+ IntlConstructorData::new(reflect.apply, uses_timezone),
+ IntlConstructorData::new(reflect.construct, uses_timezone),
+ )
+ .bind(scope)?;
let Some(proxy) = v8::Proxy::new(scope, original.into(), handler) else {
return Err(anyhow!("failed to create Intl.{name} constructor proxy"));
};
@@ -136,15 +138,7 @@ fn install_intl_resolved_options_override<'s>(
let Ok(original) = v8::Local::<v8::Function>::try_from(original) else {
return Ok(());
};
- let Some(wrapper) = v8::Function::builder(intl_resolved_options_callback)
- .data(original.into())
- .length(0)
- .build(scope)
- else {
- return Err(anyhow!("failed to create Intl resolvedOptions wrapper"));
- };
- wrapper.set_name(key);
- let _ = prototype.set(scope, key.into(), wrapper.into());
+ IntlResolvedOptionsDeclaration::new(original).initialize(scope, prototype)?;
Ok(())
}
@@ -153,20 +147,18 @@ fn intl_constructor_proxy_apply_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let Some((kind, reflect_apply)) = intl_constructor_callback_data(scope, args.data()) else {
- rv.set_undefined();
+ let Some(data) = callback_data::<IntlConstructorData>(scope, args.data()) else {
return;
};
- let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(2)) else {
- rv.set_undefined();
+ let Some(args) = webidl::parse_args::<ConstructorApplyArgs>(scope, &args) else {
return;
};
- let applied_locale = apply_intl_constructor_defaults(scope, arguments, kind);
- let invoke_args = [args.get(0), args.get(1), arguments.into()];
+ let applied_locale = apply_intl_constructor_defaults(scope, args.arguments, data.uses_timezone);
+ let invoke_args = [args.target, args.receiver, args.arguments.into()];
let receiver = v8::undefined(scope);
if let Some(result) = call_script_visible_function(
scope,
- reflect_apply,
+ data.reflect,
receiver.into(),
&invoke_args,
"invoke Intl constructor through Reflect.apply",
@@ -181,20 +173,18 @@ fn intl_constructor_proxy_construct_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let Some((kind, reflect_construct)) = intl_constructor_callback_data(scope, args.data()) else {
- rv.set_undefined();
+ let Some(data) = callback_data::<IntlConstructorData>(scope, args.data()) else {
return;
};
- let Ok(arguments) = v8::Local::<v8::Array>::try_from(args.get(1)) else {
- rv.set_undefined();
+ let Some(args) = webidl::parse_args::<ConstructorConstructArgs>(scope, &args) else {
return;
};
- let applied_locale = apply_intl_constructor_defaults(scope, arguments, kind);
- let invoke_args = [args.get(0), arguments.into(), args.get(2)];
+ let applied_locale = apply_intl_constructor_defaults(scope, args.arguments, data.uses_timezone);
+ 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,
- reflect_construct,
+ data.reflect,
receiver.into(),
&invoke_args,
"invoke Intl constructor through Reflect.construct",
@@ -207,7 +197,7 @@ fn intl_constructor_proxy_construct_callback<'s>(
fn apply_intl_constructor_defaults<'s>(
scope: &mut v8::PinScope<'s, '_>,
arguments: v8::Local<'s, v8::Array>,
- kind: IntlConstructorKind,
+ uses_timezone: bool,
) -> Option<String> {
let (locale_override, timezone_override) = current_date_locale_overrides(scope);
let mut applied_locale = None;
@@ -219,7 +209,7 @@ fn apply_intl_constructor_defaults<'s>(
let _ = arguments.set_index(scope, 0, value.into());
applied_locale = locale_override;
}
- if kind.uses_timezone()
+ if uses_timezone
&& let Some(timezone) = timezone_override.as_deref()
&& let Some(options) = intl_datetime_options_with_default_timezone(
scope,
@@ -277,24 +267,11 @@ fn intl_resolved_options_callback<'s>(
rv.set(options.into());
}
-fn intl_constructor_callback_data<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- value: v8::Local<'s, v8::Value>,
-) -> Option<(IntlConstructorKind, v8::Local<'s, v8::Function>)> {
- let data = v8::Local::<v8::Array>::try_from(value).ok()?;
- let index = data.get_index(scope, 0)?.uint32_value(scope)?;
- let builtin = data
- .get_index(scope, 1)
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())?;
- Some((IntlConstructorKind::from_index(index)?, builtin))
-}
-
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>> {
- let key = v8str(scope, "timeZone");
if let Some(original) = original.filter(|value| !value.is_undefined()) {
if !original.is_object() {
// Let the native constructor preserve its TypeError for null and
@@ -312,20 +289,18 @@ pub(super) fn intl_datetime_options_with_default_timezone<'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(data.into())
- .length(3)
- .build(scope)?;
- let _ = handler.set(scope, v8str(scope, "get").into(), get.into());
+ let handler =
+ TimezoneOptionsHandler::new(TimezoneOptionsData::new(original, timezone.into()))
+ .bind(scope)
+ .ok()?;
return v8::Proxy::new(scope, target, handler).map(Into::into);
}
- let options = v8::Object::new(scope);
let timezone = v8_string(scope, timezone)?;
- let _ = options.set(scope, key.into(), timezone.into());
- Some(options.into())
+ DefaultTimezoneOptions::new(timezone.into())
+ .bind(scope)
+ .ok()
+ .map(Into::into)
}
fn intl_datetime_options_get_callback<'s>(
@@ -333,28 +308,18 @@ fn intl_datetime_options_get_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- 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();
+ 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) = target.get(scope, key) else {
+ let Some(value) = data.original.get(scope, key) else {
return;
};
if key.strict_equals(v8str(scope, "timeZone").into()) && value.is_undefined() {
- if let Some(timezone) = data.get_index(scope, 1) {
- rv.set(timezone);
- }
+ rv.set(data.timezone);
} else {
rv.set(value);
}
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
index 46783a0af..300f23418 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,5 +1,127 @@
use super::*;
+#[test]
+fn date_and_intl_declared_wrappers_preserve_native_method_descriptors() {
+ let mut vm = new_storage_test_vm("https://date-intl-declarations.test/");
+ let probe = r#"JSON.stringify((() => {
+ const constructors = ['Collator', 'DateTimeFormat', 'DisplayNames', 'DurationFormat',
+ 'ListFormat', 'NumberFormat', 'PluralRules', 'RelativeTimeFormat', 'Segmenter'];
+ const methods = [[Date, 'parse', 1], ...constructors
+ .filter(name => typeof Intl[name] === 'function')
+ .map(name => [Intl[name].prototype, 'resolvedOptions', 0])];
+ return methods.map(([owner, name, length]) => {
+ const descriptor = Object.getOwnPropertyDescriptor(owner, name);
+ const method = descriptor.value;
+ let nonConstructible = false;
+ // Test [[Construct]] without executing the method with an invalid receiver.
+ try { Reflect.construct(function() {}, [], method); }
+ catch (error) { nonConstructible = error instanceof TypeError; }
+ return [method.name === name, method.length === length,
+ !descriptor.enumerable, descriptor.writable, descriptor.configurable,
+ !Object.hasOwn(method, 'prototype'), nonConstructible];
+ });
+ })())"#;
+ for timezone in [None, Some("Europe/Paris"), None] {
+ vm.set_timezone_override(timezone);
+ let rows: Vec<Vec<bool>> = serde_json::from_str(&vm.eval(probe).unwrap()).unwrap();
+ assert!(
+ rows.len() >= 9,
+ "Date and native Intl methods must be covered"
+ );
+ for (index, row) in rows.into_iter().enumerate() {
+ assert_eq!(row, vec![true; 7], "method {index}, timezone {timezone:?}");
+ }
+ }
+}
+
+#[test]
+fn emulation_constructor_envelopes_do_not_convert_page_arguments() {
+ let mut vm = new_storage_test_vm("https://date-intl-raw-arguments.test/");
+ let probe = r#"JSON.stringify((() => {
+ const sentinel = {};
+ const poison = {[Symbol.toPrimitive]() { throw sentinel; }};
+ const ignored = typeof Date(poison) === 'string' &&
+ typeof Date.call(poison, poison) === 'string';
+ const conversions = [];
+ const fields = [2024, 0, 2, 3, 4, 5, 6].map((value, index) => ({
+ [Symbol.toPrimitive](hint) { conversions.push(`${index}:${hint}`); return value; }
+ }));
+ class DerivedDate extends Date {}
+ const date = new DerivedDate(...fields, poison);
+ const localFields = [date.getFullYear(), date.getMonth(), date.getDate(),
+ date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()];
+ class DerivedFormat extends Intl.DateTimeFormat {}
+ const format = new DerivedFormat('en-US', {timeZone: 'UTC'});
+ const callable = [Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat].every(
+ Ctor => Ctor('en-US') instanceof Ctor);
+ const constructOnly = ['DisplayNames', 'DurationFormat', 'ListFormat',
+ 'PluralRules', 'RelativeTimeFormat', 'Segmenter'].every(name => {
+ const Ctor = Intl[name];
+ if (typeof Ctor !== 'function') return true;
+ try { Ctor(poison, poison); return false; }
+ catch (error) { return error instanceof TypeError; }
+ });
+ return [ignored, conversions, localFields,
+ Object.getPrototypeOf(date) === DerivedDate.prototype,
+ Object.getPrototypeOf(format) === DerivedFormat.prototype,
+ callable, constructOnly, Number.isNaN(Date.parse()),
+ Number.isNaN(+new Date(undefined)), Number.isFinite(+new Date()),
+ Date.parse('2024-01-01T00:00:00Z', poison) === 1704067200000];
+ })())"#;
+ for (locale, timezone) in [
+ (None, None),
+ (Some("fr_FR"), Some("America/New_York")),
+ (Some("zh_Hant_TW"), Some("Asia/Shanghai")),
+ (None, None),
+ ] {
+ vm.set_locale_override(locale);
+ vm.set_timezone_override(timezone);
+ 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]"#,
+ "locale {locale:?}, timezone {timezone:?}"
+ );
+ }
+}
+
+#[test]
+fn emulation_private_declarations_do_not_invoke_inherited_setters() {
+ let mut vm = new_storage_test_vm("https://date-intl-private-declarations.test/");
+ vm.set_timezone_override(Some("Europe/Paris"));
+ let result = vm
+ .eval(
+ r#"JSON.stringify((() => {
+ const keys = ['get', 'timeZone', 'original', 'timezone'];
+ const before = keys.map(key => Object.getOwnPropertyDescriptor(Object.prototype, key));
+ const sentinel = {};
+ // These setters must not participate in building the private handler,
+ // callback data or default options objects.
+ try {
+ for (const key of keys) Object.defineProperty(Object.prototype, key, {
+ set() { throw sentinel; }, configurable: true
+ });
+ const date = new Date('2024-01-01T00:00:00Z');
+ const frozen = Object.freeze({timeZone: undefined});
+ const explicit = {timeZone: 'Europe/Paris'};
+ return [
+ new Intl.DateTimeFormat('en-US').resolvedOptions().timeZone,
+ new Intl.DateTimeFormat('en-US', frozen).resolvedOptions().timeZone,
+ ...['toLocaleString', 'toLocaleDateString', 'toLocaleTimeString'].map(method =>
+ date[method]('en-US') === date[method]('en-US', explicit) &&
+ date[method]('en-US', frozen) === date[method]('en-US', explicit))
+ ];
+ } finally {
+ keys.forEach((key, index) => {
+ if (before[index]) Object.defineProperty(Object.prototype, key, before[index]);
+ else delete Object.prototype[key];
+ });
+ }
+ })())"#,
+ )
+ .unwrap();
+ assert_eq!(result, r#"["Europe/Paris","Europe/Paris",true,true,true]"#);
+}
+
#[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/");