Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cdp): isolate console Error stack formatting

ldm0db98c4208724
diff --git a/moli-protocol/src/domains/runtime/tests/console.rs b/moli-protocol/src/domains/runtime/tests/console.rs
index 294eaf7e9..cc87c820f 100644
--- a/moli-protocol/src/domains/runtime/tests/console.rs
+++ b/moli-protocol/src/domains/runtime/tests/console.rs
@@ -1309,6 +1309,86 @@ async fn runtime_console_api_called_preserves_basic_argument_shapes() {
assert_eq!(args[11]["type"], json!("bigint"));
assert_eq!(args[11]["unserializableValue"], json!("1n"));
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn runtime_console_error_does_not_invoke_error_prepare_stack_trace() {
+ let mut ctx = TestContext::new();
+ with_loaded_document_async(&mut ctx, "<!doctype html><body></body>").await;
+ let execution_context_id =
+ enable_runtime_and_take_execution_context_id_async(&mut ctx, 206_844).await;
+ ctx.sent.clear();
+
+ ctx.process_async(json!({
+ "id": 206_845,
+ "method": "Runtime.evaluate",
+ "params": {
+ "expression": r#"
+ (() => {
+ let accessed = false;
+ const originalPrepareStackTrace = Error.prepareStackTrace;
+ try {
+ Error.prepareStackTrace = () => {
+ accessed = true;
+ return "detected";
+ };
+ console.log(new Error(""));
+ const afterConsole = accessed;
+ void new Error("explicit stack access").stack;
+ return `${afterConsole}|${accessed}`;
+ } finally {
+ Error.prepareStackTrace = originalPrepareStackTrace;
+ }
+ })()
+ "#
+ }
+ }))
+ .await;
+
+ let response = take_response_by_id(&mut ctx, 206_845);
+ assert_eq!(response["result"]["result"]["value"], json!("false|true"));
+
+ wait_until_message(
+ &mut ctx,
+ None,
+ "Runtime.consoleAPICalled with Error argument",
+ |message| {
+ message["method"] == json!("Runtime.consoleAPICalled")
+ && message["params"]["executionContextId"] == json!(execution_context_id)
+ },
+ )
+ .await;
+ let event = ctx
+ .sent
+ .iter()
+ .find(|message| {
+ message["method"] == json!("Runtime.consoleAPICalled")
+ && message["params"]["executionContextId"] == json!(execution_context_id)
+ })
+ .expect("consoleAPICalled event should be recorded");
+ let error = &event["params"]["args"][0];
+ assert_eq!(error["type"], json!("object"));
+ assert_eq!(error["subtype"], json!("error"));
+ let error_object_id = error["objectId"]
+ .as_str()
+ .unwrap_or_else(|| panic!("Error console argument should retain its V8 objectId: {event}"))
+ .to_owned();
+
+ ctx.process_async(json!({
+ "id": 206_846,
+ "method": "Runtime.getProperties",
+ "params": {
+ "objectId": error_object_id,
+ "ownProperties": true
+ }
+ }))
+ .await;
+ let properties = take_response_by_id(&mut ctx, 206_846);
+ assert!(
+ properties["result"]["result"].is_array(),
+ "Error objectId should remain inspectable: {properties}"
+ );
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn runtime_console_api_called_includes_basic_stack_trace() {
let mut ctx = TestContext::new();
diff --git a/moli-renderer-v8/src/context_bootstrap/window_events/console.rs b/moli-renderer-v8/src/context_bootstrap/window_events/console.rs
index 4287e7cba..fc44362d1 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_events/console.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_events/console.rs
@@ -152,5 +152,30 @@ fn call_original_console_method<'s>(
for index in 0..args.length() {
forwarded_args.push(args.get(index));
}
+ let suppress_page_stack_hook = forwarded_args.iter().any(|value| value.is_native_error())
+ && error_prepare_stack_trace_is_function(scope);
+ if suppress_page_stack_hook {
+ scope.set_prepare_stack_trace_callback(inspector_console_stack_without_page_hook);
+ }
let _ = method.call(scope, original_console.into(), &forwarded_args);
+ if suppress_page_stack_hook {
+ scope.clear_prepare_stack_trace_callback();
+ }
+}
+
+fn error_prepare_stack_trace_is_function(scope: &mut v8::PinScope<'_, '_>) -> bool {
+ let global = scope.get_current_context().global(scope);
+ global
+ .get(scope, v8str(scope, "Error").into())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .and_then(|error| error.get(scope, v8str(scope, "prepareStackTrace").into()))
+ .is_some_and(|value| value.is_function())
+}
+
+fn inspector_console_stack_without_page_hook<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _error: v8::Local<'s, v8::Value>,
+ _sites: v8::Local<'s, v8::Array>,
+) -> v8::Local<'s, v8::Value> {
+ v8::String::empty(scope).into()
}
diff --git a/vendor/v8-152.2.0/src/isolate.rs b/vendor/v8-152.2.0/src/isolate.rs
index 872ecbce3..8cefc2413 100644
--- a/vendor/v8-152.2.0/src/isolate.rs
+++ b/vendor/v8-152.2.0/src/isolate.rs
@@ -782,7 +782,7 @@ unsafe extern "C" {
fn v8__Isolate__GetCppHeap(isolate: *mut RealIsolate) -> *mut Heap;
fn v8__Isolate__SetPrepareStackTraceCallback(
isolate: *mut RealIsolate,
- callback: PrepareStackTraceCallback,
+ callback: Option<PrepareStackTraceCallback>,
);
fn v8__Isolate__SetPromiseHook(isolate: *mut RealIsolate, hook: PromiseHook);
fn v8__Isolate__SetPromiseRejectCallback(
@@ -1655,11 +1655,21 @@ impl Isolate {
unsafe {
v8__Isolate__SetPrepareStackTraceCallback(
self.as_real_ptr(),
- callback.map_fn_to(),
+ Some(callback.map_fn_to()),
);
};
}
+ /// Clears the embedder callback installed by
+ /// [`Self::set_prepare_stack_trace_callback`], restoring V8's normal
+ /// `Error.prepareStackTrace` behavior.
+ #[inline(always)]
+ pub fn clear_prepare_stack_trace_callback(&mut self) {
+ unsafe {
+ v8__Isolate__SetPrepareStackTraceCallback(self.as_real_ptr(), None);
+ };
+ }
+
/// Set the PromiseHook callback for various promise lifecycle
/// events.
#[inline(always)]