Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(script): report document.write exceptions through shared execution

ldm024743af0e4b9
diff --git a/moli-core/tests/fixtures/runtime/document_write_reported_errors.js b/moli-core/tests/fixtures/runtime/document_write_reported_errors.js
new file mode 100644
index 000000000..2ae0e9b28
--- /dev/null
+++ b/moli-core/tests/fixtures/runtime/document_write_reported_errors.js
@@ -0,0 +1,79 @@
+window.writeErrorTrace = [];
+window.writeErrorDetails = [];
+window.writeErrorEscaped = [];
+window.writeErrorRestored = [];
+window.writeErrorToken = new Error('written runtime exception');
+
+window.addEventListener('error', event => {
+ const script = document.currentScript;
+ const id = script && script.id;
+ writeErrorTrace.push('error:' + id);
+ writeErrorDetails.push({
+ id,
+ identity: id === 'runtime' ? event.error === writeErrorToken :
+ id === 'syntax' ? event.error instanceof SyntaxError :
+ id === 'external' && event.error === window.externalWriteError,
+ filename: event.filename === (script && script.src || document.URL),
+ target: event.target === window,
+ trusted: event.isTrusted,
+ cancelable: event.cancelable
+ });
+ event.preventDefault();
+ document.write('<b class="reported">' + id + '</b>');
+ queueMicrotask(() => writeErrorTrace.push('report-microtask:' + id));
+});
+
+function writeFailingScript(id, source, external) {
+ const attributes = external ? ' src="data:text/javascript,' + encodeURIComponent(source) +
+ '" onload="writeErrorTrace.push(\'load:external\')" onerror="writeErrorTrace.push(\'load-error:external\')"' : '';
+ try {
+ document.write('<script id="' + id + '"' + attributes + '>' +
+ (external ? '' : source) + '<' + '/script>');
+ } catch (error) {
+ writeErrorEscaped.push(id);
+ }
+ writeErrorRestored.push(document.currentScript && document.currentScript.id);
+ writeErrorTrace.push('returned:' + id);
+}
+
+writeFailingScript('runtime',
+ 'writeErrorTrace.push("body:runtime"); queueMicrotask(() => writeErrorTrace.push("body-microtask:runtime")); throw writeErrorToken;',
+ false);
+writeFailingScript('syntax', 'let = ;', false);
+writeFailingScript('external',
+ 'writeErrorTrace.push("body:external"); queueMicrotask(() => writeErrorTrace.push("body-microtask:external")); window.externalWriteError = new TypeError("external writer"); throw externalWriteError;',
+ true);
+document.write('<script>writeErrorTrace.push("tail-script")<' + '/script><main id="tail">tail</main>');
+writeErrorTrace.push('outer-end');
+
+window.writeErrorResult = () => {
+ let checks = 0;
+ const failures = [];
+ const check = (name, actual, expected) => {
+ checks++;
+ if (JSON.stringify(actual) !== JSON.stringify(expected))
+ failures.push({name, actual, expected});
+ };
+ const before = (first, second) => writeErrorTrace.includes(first) &&
+ writeErrorTrace.indexOf(first) < writeErrorTrace.indexOf(second);
+ check('exceptions stay inside written scripts', writeErrorEscaped, []);
+ check('each exception reaches its Window', writeErrorDetails.map(error => error.id),
+ ['runtime', 'syntax', 'external']);
+ for (const field of ['identity', 'filename', 'target', 'trusted', 'cancelable'])
+ check('error event ' + field, writeErrorDetails.map(error => error[field]), [true, true, true]);
+ check('currentScript returns to the writer', writeErrorRestored, ['outer', 'outer', 'outer']);
+ check('error handlers retain the insertion point',
+ Array.from(document.querySelectorAll('.reported'), node => node.textContent),
+ ['runtime', 'syntax', 'external']);
+ check('inline runtime error precedes write return', before('error:runtime', 'returned:runtime'), true);
+ check('inline syntax error precedes write return', before('error:syntax', 'returned:syntax'), true);
+ check('external evaluation error still allows load', writeErrorTrace.filter(value => value.startsWith('load')), ['load:external']);
+ check('external error precedes body microtasks', before('error:external', 'body-microtask:external'), true);
+ check('inline error precedes its microtasks', before('error:runtime', 'body-microtask:runtime'), true);
+ check('microtasks retain enqueue order', before('body-microtask:external', 'report-microtask:external'), true);
+ check('load precedes later parser scripts', before('load:external', 'tail-script'), true);
+ check('outer writer continues', writeErrorTrace.includes('outer-end'), true);
+ check('parser reaches the written tail', document.getElementById('tail')?.textContent, 'tail');
+ check('currentScript clears after parsing', document.currentScript, null);
+ return {checks, failures};
+};
diff --git a/moli-core/tests/scripts.rs b/moli-core/tests/scripts.rs
index a6a02404a..ae0f63834 100644
--- a/moli-core/tests/scripts.rs
+++ b/moli-core/tests/scripts.rs
@@ -6708,3 +6708,6 @@ async fn parse_time_lifecycle_queue_can_stop_cleanly_at_load_stage_after_load_mi
server.shutdown().await;
Ok(())
}
+
+#[path = "scripts/document_write_errors.rs"]
+mod document_write_errors;
diff --git a/moli-core/tests/scripts/document_write_errors.rs b/moli-core/tests/scripts/document_write_errors.rs
new file mode 100644
index 000000000..17379f47d
--- /dev/null
+++ b/moli-core/tests/scripts/document_write_errors.rs
@@ -0,0 +1,94 @@
+use super::*;
+
+const ERROR_SCRIPT: &str = include_str!("../fixtures/runtime/document_write_reported_errors.js");
+
+fn markup_url(server: &FixtureServer, markup: &str) -> String {
+ let mut url = url::Url::parse(&server.url("/compat/child-dynamic-markup-document")).unwrap();
+ url.query_pairs_mut().append_pair("markup", markup);
+ url.into()
+}
+
+async fn written_script_errors_are_reported(child: bool, script_created: bool) -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+ let fixture = format!("<!doctype html><body><script id=outer>{ERROR_SCRIPT}</script>");
+ let markup = if script_created {
+ "<!doctype html><body>".to_owned()
+ } else {
+ fixture.clone()
+ };
+ let markup = if child {
+ format!(
+ "<!doctype html><body><iframe id=target src=\"{}\"></iframe>",
+ markup_url(&server, &markup)
+ )
+ } else {
+ markup
+ };
+ let mut page = tokio::time::timeout(
+ Duration::from_secs(10),
+ browser.fetch(&markup_url(&server, &markup)),
+ )
+ .await??;
+ let receiver = if child {
+ "document.getElementById('target').contentWindow"
+ } else {
+ "window"
+ };
+ if script_created {
+ let script = format!(
+ r#"new Promise(resolve => {{
+ const doc = {receiver}.document;
+ doc.open();
+ doc.addEventListener('DOMContentLoaded', () => resolve(true), {{once: true}});
+ doc.write({});
+ doc.close();
+ }})"#,
+ serde_json::to_string(&fixture)?
+ );
+ tokio::time::timeout(
+ Duration::from_secs(10),
+ page.evaluate_runtime_expression_with_await_async(&script, true),
+ )
+ .await??;
+ }
+ let observation = page
+ .evaluate_runtime_expression_with_await_async(
+ &format!("JSON.stringify({receiver}.writeErrorResult())"),
+ true,
+ )
+ .await?;
+ let observation: serde_json::Value = serde_json::from_str(
+ observation["value"]
+ .as_str()
+ .expect("error report observation"),
+ )?;
+ assert_eq!(
+ observation,
+ serde_json::json!({"checks": 19, "failures": []})
+ );
+ server.shutdown().await;
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn main_parser_reports_written_script_errors_without_throwing_into_writer() -> Result<()> {
+ written_script_errors_are_reported(false, false).await
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn main_open_parser_reports_written_script_errors_without_throwing_into_writer() -> Result<()>
+{
+ written_script_errors_are_reported(false, true).await
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn child_parser_reports_written_script_errors_without_throwing_into_writer() -> Result<()> {
+ written_script_errors_are_reported(true, false).await
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn child_open_parser_reports_written_script_errors_without_throwing_into_writer() -> Result<()>
+{
+ written_script_errors_are_reported(true, true).await
+}
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index 8b278b7ae..74d75cc71 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -1580,6 +1580,7 @@ impl DocumentRuntime {
start.node,
&start.host_script_handle,
source,
+ &start.script,
Some(insertion.parser_bridge.clone()),
DocumentWriteCurrentScriptEventBehavior::DispatchImmediately(
ScriptEventKind::Load,
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
index 02a53a085..a7a583a0b 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
@@ -6,7 +6,6 @@ use crate::host::{
use crate::planning::ScriptSource;
use crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections;
use crate::types::ScriptKind;
-use crate::util::create_script_origin;
use crate::v8_execution_watchdog::{
SCRIPT_TURN_WATCHDOG_TIMEOUT, V8ExecutionWatchdog, V8ExecutionWatchdogKind,
V8ExecutionWatchdogOutcome,
@@ -110,6 +109,7 @@ impl DocumentRuntime {
node,
&host_script_handle,
source,
+ &script,
parser_bridge,
DocumentWriteCurrentScriptEventBehavior::Skip,
);
@@ -133,6 +133,7 @@ impl DocumentRuntime {
node: DomHandle,
host_script_handle: &str,
source: String,
+ script: &PreparedScript,
parser_bridge: Option<ParserConnectedScriptBridge>,
current_script_event_behavior: DocumentWriteCurrentScriptEventBehavior,
) {
@@ -149,31 +150,28 @@ impl DocumentRuntime {
"parser-created top-level script execution requires the page main-world context",
);
let scope = &mut v8::ContextScope::new(scope, default_context);
- let watchdog = V8ExecutionWatchdog::arm(
- V8ExecutionWatchdogKind::ScriptTurn,
- scope.thread_safe_handle(),
- SCRIPT_TURN_WATCHDOG_TIMEOUT,
- );
let run_result = {
let _parser_script_nesting = self.enter_parser_script_nesting();
- (|| {
- let source = v8::String::new(scope, &source)?;
- let origin = create_script_origin(scope, self.document_url().as_str(), 0);
- let script = v8::Script::compile(scope, source, Some(&origin))?;
- crate::script_execution::execute_compiled_script(scope, script)
- })()
+ // A written script is an independent script execution. Report its
+ // exception to its Window, then continue the caller's write and
+ // parser completion, including load for a fetched classic script.
+ crate::script_vm::execute_source_text_on_current_stack(
+ scope,
+ &source,
+ Some(&script.url),
+ Some(&script.base_url),
+ 0,
+ script.fetch_metadata.nonce.as_deref(),
+ true,
+ )
};
- let script_timed_out = watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut;
self.clear_current_script_handle();
- if run_result.is_none() {
- if script_timed_out {
- tracing::warn!(
- host_script_handle,
- timeout = ?SCRIPT_TURN_WATCHDOG_TIMEOUT,
- "document.write script execution exceeded its deadline and was terminated"
- );
- }
- return;
+ if let Err(error) = run_result {
+ debug!(
+ host_script_handle,
+ %error,
+ "document.write immediate script execution failed"
+ );
}
match current_script_event_behavior {
DocumentWriteCurrentScriptEventBehavior::Skip => {}
@@ -288,6 +286,7 @@ impl DocumentRuntime {
node,
host_script_handle,
source,
+ &script,
parser_bridge,
DocumentWriteCurrentScriptEventBehavior::DispatchImmediately(ScriptEventKind::Load),
);
diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs
index 1ff2ee510..a47c10134 100644
--- a/moli-renderer-v8/src/util.rs
+++ b/moli-renderer-v8/src/util.rs
@@ -167,14 +167,6 @@ pub(crate) fn apply_webidl_constructor_prototype_fallback<'s>(
let _ = receiver.set_prototype(scope, prototype.into());
}
-pub(super) fn create_script_origin<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- resource_name: &str,
- line_offset: i32,
-) -> v8::ScriptOrigin<'s> {
- create_script_origin_with_base_url(scope, resource_name, line_offset, None)
-}
-
pub(super) fn create_script_origin_with_base_url<'s>(
scope: &mut v8::PinScope<'s, '_>,
resource_name: &str,