Skip to content

armgit / moli

Public Imported from GitHub
0

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

feat(renderer): expose Chromium window.chrome surface

ldm084c3d853c901
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index f349d184b..8849bcc90 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -3,6 +3,7 @@ mod assets;
pub(crate) mod bridge_descriptor;
mod broadcast_channel;
mod canvas;
+mod chrome_runtime;
mod constructors;
mod crypto;
mod css_fontface_runtime;
diff --git a/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs b/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs
new file mode 100644
index 000000000..ad32503d6
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs
@@ -0,0 +1,381 @@
+//! Chromium's small browser-vendor surface exposed to ordinary web pages.
+//!
+//! Chrome installs `chrome.loadTimes()` and `chrome.csi()` through a V8
+//! extension, while the extensions bindings layer adds the legacy `chrome.app`
+//! API to web-page contexts. Keep this separate from WebIDL APIs: these are
+//! Chromium compatibility properties, not web-platform interfaces.
+
+use super::{
+ dom_time_since_origin_millis, performance_runtime::current_window_navigation_timing_snapshot,
+};
+use crate::{
+ host::HostTimerOwner,
+ util::{context_host_ptr_from_global_bridge, throw_type_error, v8str},
+};
+use anyhow::{Result, anyhow};
+use moli_webapi_declare::WebApiObject;
+
+const INSTALL_STATE_NOT_INSTALLED: &str = "not_installed";
+const RUNNING_STATE_CANNOT_RUN: &str = "cannot_run";
+
+#[derive(WebApiObject)]
+#[webapi(interface = "Object", data_properties, enumerable)]
+struct ChromeInstallStateDeclaration {
+ #[webapi(data_property = "DISABLED")]
+ disabled: &'static str,
+ #[webapi(data_property = "INSTALLED")]
+ installed: &'static str,
+ #[webapi(data_property = "NOT_INSTALLED")]
+ not_installed: &'static str,
+}
+
+#[derive(WebApiObject)]
+#[webapi(interface = "Object", data_properties, enumerable)]
+struct ChromeRunningStateDeclaration {
+ #[webapi(data_property = "CANNOT_RUN")]
+ cannot_run: &'static str,
+ #[webapi(data_property = "READY_TO_RUN")]
+ ready_to_run: &'static str,
+ #[webapi(data_property = "RUNNING")]
+ running: &'static str,
+}
+
+#[derive(WebApiObject)]
+#[webapi(interface = "Object", enumerable)]
+struct ChromeAppDeclaration<'scope> {
+ #[webapi(
+ native_data_property = "isInstalled",
+ getter = chrome_value_getter,
+ setter = chrome_value_empty_setter,
+ data = v8::Boolean::new(scope, false)
+ )]
+ is_installed: (),
+ #[webapi(method = "getDetails", length = 0, callback = chrome_app_get_details)]
+ get_details: (),
+ #[webapi(
+ method = "getIsInstalled",
+ length = 0,
+ callback = chrome_app_get_is_installed
+ )]
+ get_is_installed: (),
+ #[webapi(method = "installState", length = 0, callback = chrome_app_install_state)]
+ install_state_method: (),
+ #[webapi(method = "runningState", length = 0, callback = chrome_app_running_state)]
+ running_state_method: (),
+ #[webapi(data_property = "InstallState")]
+ install_state: v8::Local<'scope, v8::Object>,
+ #[webapi(data_property = "RunningState")]
+ running_state: v8::Local<'scope, v8::Object>,
+}
+
+pub(in crate::context_bootstrap) fn install_chrome_runtime_state<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ global: v8::Local<'s, v8::Object>,
+) -> Result<()> {
+ let chrome = v8::Object::new(scope);
+ let load_times = v8::Function::builder(chrome_load_times)
+ .length(0)
+ .build(scope)
+ .ok_or_else(|| anyhow!("failed to create chrome.loadTimes"))?;
+ let csi = v8::Function::builder(chrome_csi)
+ .length(0)
+ .build(scope)
+ .ok_or_else(|| anyhow!("failed to create chrome.csi"))?;
+ let install_state =
+ ChromeInstallStateDeclaration::new("disabled", "installed", INSTALL_STATE_NOT_INSTALLED)
+ .bind(scope)
+ .map_err(|error| anyhow!("failed to create chrome.app.InstallState: {error}"))?;
+ let running_state =
+ ChromeRunningStateDeclaration::new(RUNNING_STATE_CANNOT_RUN, "ready_to_run", "running")
+ .bind(scope)
+ .map_err(|error| anyhow!("failed to create chrome.app.RunningState: {error}"))?;
+ let app = ChromeAppDeclaration::new(install_state, running_state)
+ .bind(scope)
+ .map_err(|error| anyhow!("failed to create chrome.app: {error}"))?;
+
+ define_chrome_member(scope, chrome, "loadTimes", load_times.into())?;
+ define_chrome_member(scope, chrome, "csi", csi.into())?;
+ define_chrome_member(scope, chrome, "app", app.into())?;
+
+ global
+ .define_own_property(
+ scope,
+ v8str(scope, "chrome").into(),
+ chrome.into(),
+ v8::PropertyAttribute::DONT_DELETE,
+ )
+ .unwrap_or(false)
+ .then_some(())
+ .ok_or_else(|| anyhow!("failed to define window.chrome"))
+}
+
+fn define_chrome_member<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ chrome: v8::Local<'s, v8::Object>,
+ name: &'static str,
+ value: v8::Local<'s, v8::Value>,
+) -> Result<()> {
+ chrome
+ .create_data_property(scope, v8str(scope, name).into(), value)
+ .unwrap_or(false)
+ .then_some(())
+ .ok_or_else(|| anyhow!("failed to define chrome.{name}"))
+}
+
+fn define_chrome_snapshot_property<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+ value: v8::Local<'s, v8::Value>,
+) -> Result<()> {
+ object
+ .set_native_data_property_with_configuration(
+ scope,
+ v8str(scope, name).into(),
+ v8::NativeDataPropertyConfiguration::new(chrome_value_getter)
+ .setter(chrome_value_empty_setter)
+ .data(value),
+ )
+ .unwrap_or(false)
+ .then_some(())
+ .ok_or_else(|| anyhow!("failed to define chrome timing property {name}"))
+}
+
+fn chrome_value_getter<'s>(
+ _scope: &mut v8::PinScope<'s, '_>,
+ _name: v8::Local<'s, v8::Name>,
+ args: v8::PropertyCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ rv.set(args.data());
+}
+
+fn chrome_value_empty_setter<'s>(
+ _scope: &mut v8::PinScope<'s, '_>,
+ _name: v8::Local<'s, v8::Name>,
+ _value: v8::Local<'s, v8::Value>,
+ _args: v8::PropertyCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, ()>,
+) {
+}
+
+fn chrome_load_times<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ rv.set_null();
+ let Some(timing) = current_window_navigation_timing_snapshot(scope) else {
+ return;
+ };
+ let result = v8::Object::new(scope);
+ let start_seconds = timing.time_origin_millis / 1_000.0;
+ let finish_document_seconds = completed_epoch_seconds(
+ timing.time_origin_millis,
+ timing.dom_content_loaded_end_millis,
+ );
+ let finish_load_seconds =
+ completed_epoch_seconds(timing.time_origin_millis, timing.load_event_end_millis);
+ let navigation_type = chrome_navigation_type(&timing.navigation_type);
+
+ let properties = [
+ ("requestTime", v8::Number::new(scope, start_seconds).into()),
+ (
+ "startLoadTime",
+ v8::Number::new(scope, start_seconds).into(),
+ ),
+ (
+ "commitLoadTime",
+ v8::Number::new(scope, start_seconds).into(),
+ ),
+ (
+ "finishDocumentLoadTime",
+ v8::Number::new(scope, finish_document_seconds).into(),
+ ),
+ (
+ "finishLoadTime",
+ v8::Number::new(scope, finish_load_seconds).into(),
+ ),
+ ("firstPaintTime", v8::Number::new(scope, 0.0).into()),
+ (
+ "firstPaintAfterLoadTime",
+ v8::Number::new(scope, 0.0).into(),
+ ),
+ ("navigationType", v8str(scope, navigation_type).into()),
+ ("wasFetchedViaSpdy", v8::Boolean::new(scope, false).into()),
+ ("wasNpnNegotiated", v8::Boolean::new(scope, false).into()),
+ ("npnNegotiatedProtocol", v8str(scope, "").into()),
+ (
+ "wasAlternateProtocolAvailable",
+ v8::Boolean::new(scope, false).into(),
+ ),
+ ("connectionInfo", v8str(scope, "unknown").into()),
+ ];
+ for (name, value) in properties {
+ if define_chrome_snapshot_property(scope, result, name, value).is_err() {
+ return;
+ }
+ }
+ rv.set(result.into());
+}
+
+fn chrome_csi<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ rv.set_null();
+ let Some(timing) = current_window_navigation_timing_snapshot(scope) else {
+ return;
+ };
+ let result = v8::Object::new(scope);
+ let onload_millis = completed_epoch_millis(
+ timing.time_origin_millis,
+ timing.dom_content_loaded_end_millis,
+ );
+ let transition = chrome_csi_transition(&timing.navigation_type);
+ let properties = [
+ (
+ "startE",
+ v8::Number::new(scope, timing.time_origin_millis).into(),
+ ),
+ ("onloadT", v8::Number::new(scope, onload_millis).into()),
+ (
+ "pageT",
+ v8::Number::new(
+ scope,
+ dom_time_since_origin_millis(timing.time_origin_millis).max(0.0),
+ )
+ .into(),
+ ),
+ ("tran", v8::Integer::new(scope, transition).into()),
+ ];
+ for (name, value) in properties {
+ if define_chrome_snapshot_property(scope, result, name, value).is_err() {
+ return;
+ }
+ }
+ rv.set(result.into());
+}
+
+fn completed_epoch_seconds(time_origin_millis: f64, relative_millis: Option<f64>) -> f64 {
+ completed_epoch_millis(time_origin_millis, relative_millis) / 1_000.0
+}
+
+fn completed_epoch_millis(time_origin_millis: f64, relative_millis: Option<f64>) -> f64 {
+ relative_millis
+ .map(|relative| time_origin_millis + relative)
+ .unwrap_or(0.0)
+}
+
+fn chrome_navigation_type(navigation_type: &str) -> &'static str {
+ match navigation_type {
+ "reload" => "Reload",
+ "traverse" => "BackForward",
+ _ => "Other",
+ }
+}
+
+fn chrome_csi_transition(navigation_type: &str) -> i32 {
+ match navigation_type {
+ "reload" => 16,
+ "traverse" => 6,
+ _ => 15,
+ }
+}
+
+fn reject_chrome_app_arguments(
+ scope: &mut v8::PinScope<'_, '_>,
+ args: &v8::FunctionCallbackArguments<'_>,
+ method: &'static str,
+) -> bool {
+ if args.length() == 0 {
+ return false;
+ }
+ throw_type_error(scope, &format!("Error in invocation of app.{method}(): "));
+ true
+}
+
+fn chrome_app_get_details<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ if reject_chrome_app_arguments(scope, &args, "getDetails") {
+ return;
+ }
+ rv.set_null();
+}
+
+fn chrome_app_get_is_installed<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ if reject_chrome_app_arguments(scope, &args, "getIsInstalled") {
+ return;
+ }
+ rv.set(v8::Boolean::new(scope, false).into());
+}
+
+fn chrome_app_running_state<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ if reject_chrome_app_arguments(scope, &args, "runningState") {
+ return;
+ }
+ rv.set(v8str(scope, RUNNING_STATE_CANNOT_RUN).into());
+}
+
+fn chrome_app_install_state<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ if args.length() == 0 {
+ rv.set_undefined();
+ return;
+ }
+ let callback = if args.length() == 1 {
+ v8::Local::<v8::Function>::try_from(args.get(0)).ok()
+ } else {
+ None
+ };
+ let Some(callback) = callback else {
+ throw_type_error(
+ scope,
+ "Error in invocation of app.installState(function callback): ",
+ );
+ return;
+ };
+ let trampoline = v8::Function::builder(run_chrome_app_install_state_callback)
+ .data(callback.into())
+ .constructor_behavior(v8::ConstructorBehavior::Throw)
+ .build(scope)
+ .expect("chrome.app.installState callback trampoline should allocate");
+ if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
+ unsafe { &mut *host_ptr }.queue_timeout(
+ scope,
+ trampoline,
+ 0,
+ HostTimerOwner::Window,
+ Vec::new(),
+ );
+ }
+ rv.set_undefined();
+}
+
+fn run_chrome_app_install_state_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s, v8::Value>,
+) {
+ let callback = v8::Local::<v8::Function>::try_from(args.data())
+ .expect("chrome.app.installState trampoline must retain its callback");
+ let receiver = v8::undefined(scope);
+ let state: v8::Local<'s, v8::Value> = v8str(scope, INSTALL_STATE_NOT_INSTALLED).into();
+ let _ = callback.call(scope, receiver.into(), &[state]);
+ rv.set_undefined();
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
index 4472a8e12..7acaf99a2 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
@@ -141,6 +141,37 @@ pub(super) fn ensure_current_performance_for_api<'s>(
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
}
+pub(in crate::context_bootstrap) struct WindowNavigationTimingSnapshot {
+ pub(in crate::context_bootstrap) time_origin_millis: f64,
+ pub(in crate::context_bootstrap) dom_content_loaded_end_millis: Option<f64>,
+ pub(in crate::context_bootstrap) load_event_end_millis: Option<f64>,
+ pub(in crate::context_bootstrap) navigation_type: String,
+}
+
+pub(in crate::context_bootstrap) fn current_window_navigation_timing_snapshot(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> Option<WindowNavigationTimingSnapshot> {
+ let performance = ensure_current_performance_for_api(scope)?;
+ Some(WindowNavigationTimingSnapshot {
+ time_origin_millis: performance_slot_number(
+ scope,
+ performance,
+ PERFORMANCE_TIME_ORIGIN_SLOT,
+ )?,
+ dom_content_loaded_end_millis: install::performance_lifecycle_timestamp(
+ scope,
+ performance,
+ install::DOM_CONTENT_LOADED_END_INDEX,
+ ),
+ load_event_end_millis: install::performance_lifecycle_timestamp(
+ scope,
+ performance,
+ install::LOAD_END_INDEX,
+ ),
+ navigation_type: install::performance_navigation_type_seed(scope, performance),
+ })
+}
+
pub(in crate::context_bootstrap) fn ensure_navigation_performance_entry_for_api<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
index 898cefea8..76a397ca8 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
@@ -52,9 +52,9 @@ pub(super) const EVENT_COUNTS_TRACKED_TYPES: &[&str] = &[
];
const DOM_CONTENT_LOADED_START_INDEX: usize = 0;
-const DOM_CONTENT_LOADED_END_INDEX: usize = 1;
+pub(super) const DOM_CONTENT_LOADED_END_INDEX: usize = 1;
const LOAD_START_INDEX: usize = 2;
-const LOAD_END_INDEX: usize = 3;
+pub(super) const LOAD_END_INDEX: usize = 3;
const LIFECYCLE_TIMESTAMP_COUNT: usize = 4;
#[derive(WebApiObject)]
@@ -1014,7 +1014,7 @@ fn apply_lifecycle_to_navigation_entry<'s>(
}
}
-fn performance_navigation_type_seed<'s>(
+pub(super) fn performance_navigation_type_seed<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
) -> String {
@@ -1024,7 +1024,7 @@ fn performance_navigation_type_seed<'s>(
.unwrap_or_else(|| "navigate".to_owned())
}
-fn performance_lifecycle_timestamp<'s>(
+pub(super) fn performance_lifecycle_timestamp<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
index: usize,
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index fbb0b11b4..fda6a1b11 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -4,6 +4,7 @@ use super::shared::*;
use super::webassembly_runtime::install_webassembly_runtime_extensions;
use super::window_events::*;
use super::{
+ chrome_runtime::install_chrome_runtime_state,
crypto::install_window_crypto_runtime_state,
css_runtime::install_css_runtime_state,
exposed_interfaces::is_lazy_exposed_interface,
@@ -2037,6 +2038,7 @@ fn install_window_runtime_state<'s>(
install_window_crypto_runtime_state(scope, global, secure_context_available)?;
install_css_runtime_state(scope, global)?;
install_default_window_performance_seed(scope, global)?;
+ install_chrome_runtime_state(scope, global)?;
install_storage_runtime_state(scope, global)?;
network_host::initialize_fetch_realm_helpers(scope)?;
install_public_window_surface_accessors(scope, global)?;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/chrome.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/chrome.rs
new file mode 100644
index 000000000..a63d6d673
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/chrome.rs
@@ -0,0 +1,161 @@
+use super::*;
+
+#[test]
+fn window_chrome_matches_the_ordinary_chromium_page_surface() {
+ let mut vm = new_storage_test_vm("https://chrome-surface.test/");
+
+ assert_eq!(
+ vm.eval(
+ r#"
+ JSON.stringify({
+ chromeType: typeof chrome,
+ sameWindowValue: chrome === window.chrome,
+ chromeKeys: Object.keys(chrome),
+ chromePrototype: Object.getPrototypeOf(chrome) === Object.prototype,
+ chromeDescriptor: (() => {
+ const descriptor = Object.getOwnPropertyDescriptor(window, "chrome");
+ return [
+ descriptor.value === chrome,
+ descriptor.writable,
+ descriptor.enumerable,
+ descriptor.configurable,
+ ];
+ })(),
+ loadTimesFunction: [
+ chrome.loadTimes.name,
+ chrome.loadTimes.length,
+ String(chrome.loadTimes),
+ (() => { try { return typeof new chrome.loadTimes(); } catch { return "throws"; } })(),
+ ],
+ csiFunction: [
+ chrome.csi.name,
+ chrome.csi.length,
+ String(chrome.csi),
+ (() => { try { return typeof new chrome.csi(); } catch { return "throws"; } })(),
+ ],
+ appKeys: Object.keys(chrome.app),
+ appPrototype: Object.getPrototypeOf(chrome.app) === Object.prototype,
+ frameChromeType: (() => {
+ const frame = document.createElement("iframe");
+ (document.body || document.documentElement || document).appendChild(frame);
+ return typeof frame.contentWindow.chrome;
+ })(),
+ appValues: [
+ chrome.app.isInstalled,
+ chrome.app.getDetails(),
+ chrome.app.getIsInstalled(),
+ chrome.app.runningState(),
+ ],
+ installState: chrome.app.InstallState,
+ runningState: chrome.app.RunningState,
+ runtimeType: typeof chrome.runtime,
+ })
+ "#,
+ )
+ .expect("inspect window.chrome"),
+ r#"{"chromeType":"object","sameWindowValue":true,"chromeKeys":["loadTimes","csi","app"],"chromePrototype":true,"chromeDescriptor":[true,true,true,false],"loadTimesFunction":["",0,"function () { [native code] }","object"],"csiFunction":["",0,"function () { [native code] }","object"],"appKeys":["isInstalled","getDetails","getIsInstalled","installState","runningState","InstallState","RunningState"],"appPrototype":true,"frameChromeType":"object","appValues":[false,null,false,"cannot_run"],"installState":{"DISABLED":"disabled","INSTALLED":"installed","NOT_INSTALLED":"not_installed"},"runningState":{"CANNOT_RUN":"cannot_run","READY_TO_RUN":"ready_to_run","RUNNING":"running"},"runtimeType":"undefined"}"#
+ );
+}
+
+#[test]
+fn chrome_timing_snapshots_have_chromium_shape_and_ignore_assignment() {
+ let mut vm = new_storage_test_vm("https://chrome-timing.test/");
+
+ assert_eq!(
+ vm.eval(
+ r#"
+ const loadTimes = chrome.loadTimes();
+ const csi = chrome.csi();
+ const requestTime = loadTimes.requestTime;
+ const startE = csi.startE;
+ loadTimes.requestTime = -1;
+ csi.startE = -1;
+ chrome.app.isInstalled = true;
+ JSON.stringify({
+ loadTimesKeys: Object.keys(loadTimes),
+ csiKeys: Object.keys(csi),
+ timingTypes: [
+ typeof loadTimes.requestTime,
+ typeof loadTimes.navigationType,
+ typeof loadTimes.wasFetchedViaSpdy,
+ typeof csi.startE,
+ typeof csi.tran,
+ ],
+ timingRelations: [
+ loadTimes.requestTime === requestTime,
+ loadTimes.requestTime === loadTimes.startLoadTime,
+ loadTimes.requestTime > 0,
+ csi.startE === startE,
+ csi.startE === loadTimes.requestTime * 1000,
+ csi.pageT >= 0,
+ ],
+ fixedValues: [
+ loadTimes.firstPaintAfterLoadTime,
+ loadTimes.navigationType,
+ loadTimes.wasFetchedViaSpdy,
+ loadTimes.wasNpnNegotiated,
+ loadTimes.npnNegotiatedProtocol,
+ loadTimes.wasAlternateProtocolAvailable,
+ loadTimes.connectionInfo,
+ csi.tran,
+ chrome.app.isInstalled,
+ ],
+ })
+ "#,
+ )
+ .expect("inspect Chromium timing compatibility objects"),
+ r#"{"loadTimesKeys":["requestTime","startLoadTime","commitLoadTime","finishDocumentLoadTime","finishLoadTime","firstPaintTime","firstPaintAfterLoadTime","navigationType","wasFetchedViaSpdy","wasNpnNegotiated","npnNegotiatedProtocol","wasAlternateProtocolAvailable","connectionInfo"],"csiKeys":["startE","onloadT","pageT","tran"],"timingTypes":["number","string","boolean","number","number"],"timingRelations":[true,true,true,true,true,true],"fixedValues":[0,"Other",false,false,"",false,"unknown",15,false]}"#
+ );
+}
+
+#[test]
+fn chrome_app_install_state_is_async_and_validates_its_callback() {
+ let mut vm = new_storage_test_vm("https://chrome-app.test/");
+
+ assert_eq!(
+ vm.eval(
+ r#"
+ globalThis.chromeInstallStateResult = "pending";
+ globalThis.chromeInstallStateOrder = [];
+ let synchronous = true;
+ const returned = chrome.app.installState((state) => {
+ globalThis.chromeInstallStateResult = `${state}:${synchronous}`;
+ chromeInstallStateOrder.push("app");
+ });
+ Promise.resolve().then(() => chromeInstallStateOrder.push("promise"));
+ synchronous = false;
+ String(returned)
+ "#,
+ )
+ .expect("schedule chrome.app.installState callback"),
+ "undefined"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify([chromeInstallStateResult, chromeInstallStateOrder])")
+ .expect("inspect chrome.app.installState before its task"),
+ r#"["pending",["promise"]]"#
+ );
+ assert!(matches!(
+ vm.run_next_timeout_for_test()
+ .expect("chrome.app.installState task should run"),
+ crate::host::HostTimeoutRunResult::Consumed
+ ));
+ assert_eq!(
+ vm.eval("JSON.stringify([chromeInstallStateResult, chromeInstallStateOrder])")
+ .expect("read chrome.app.installState callback result"),
+ r#"["not_installed:false",["promise","app"]]"#
+ );
+ assert_eq!(
+ vm.eval(
+ r#"
+ JSON.stringify([
+ chrome.app.installState() === undefined,
+ (() => { try { chrome.app.getDetails(1); return false; } catch (error) { return error.message; } })(),
+ (() => { try { chrome.app.installState(1); return false; } catch (error) { return error.message; } })(),
+ ])
+ "#,
+ )
+ .expect("validate chrome.app argument handling"),
+ r#"[true,"Error in invocation of app.getDetails(): ","Error in invocation of app.installState(function callback): "]"#
+ );
+}
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 655a151af..8a79216ab 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
@@ -1,6 +1,7 @@
use super::*;
mod broadcast_channel;
+mod chrome;
mod crypto_misc;
mod crypto_subtle_aes;
mod crypto_subtle_digest;
diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
index 9df4c638d..707f30173 100644
--- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
+++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
@@ -16,6 +16,8 @@ use std::{
enum DirectCallOwner {
/// Shared renderer adapter for a typed Web IDL callback.
TypedWebIdlAdapter,
+ /// Callback accepted by a Chromium-specific API outside Web IDL.
+ VendorApiCallback,
/// HTML event-handler or reaction policy owned by the renderer.
EventHandlerOrReaction,
/// Promise capability or browser-created algorithm function.
@@ -68,6 +70,11 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[
1,
DirectCallOwner::TypedWebIdlAdapter,
),
+ allowed(
+ "context_bootstrap/chrome_runtime.rs",
+ 1,
+ DirectCallOwner::VendorApiCallback,
+ ),
// Event-handler/reaction policy. These are HTML-owned callbacks rather
// than values accepted through a Web IDL callback parameter.
allowed(