fix(modules): report child script exceptions in their owning Window

Route child parse, link, and evaluation failures to the exact current Window while retaining the original exception value, including deferred top-level await rejection. Keep fetch failures on script.error, restrict load events to external modules, and avoid a second load on deferred rejection.

Reuse body-only error dispatch and preserve selected-task checkpoints, parser order, and stale-owner guards. Add six end-to-end regressions and update two old syntax-error fixtures to require Window.error followed by external script load.

Validation: cargo fmt --all; full workspace all-targets all-features Clippy with warnings denied; full nextest 17659 passed, 13 skipped. Fixed-binary CLI and CDP each run the same 166 WPT cases: 139 to 140 passed, with no other case regressions and two additional crossorigin subtests passing. Move only module/errorhandling.html into the passed list. CDP smoke: 42/43 groups; Puppeteer cannot start because node is absent.
This commit is contained in:
ldm0
2026-11-21 19:24:44 +08:00
parent 8ee45ed3ff
commit 7879fa6206
8 changed files with 761 additions and 245 deletions
@@ -10,10 +10,12 @@ use crate::{
frame_owner_model::{
FrameDocumentScriptElementEventKind, FrameDocumentTaskOwner, FrameRealmId,
},
host::ModuleFailurePolicy,
module_runtime::{ModuleEntryId, ModuleGraphHandle, ModuleLoadError, ModuleMapKey},
module_script_continuation::ModuleScriptEvaluationReactionState,
parser_module_evaluation::ParserModuleEvaluationContinuation,
planning::PreparedScript,
types::{ScriptErrorValue, ScriptSourceKind},
};
use super::{
@@ -232,6 +234,15 @@ pub(crate) trait FrameModuleScriptDocumentScriptHooks {
kind: FrameDocumentScriptElementEventKind,
) -> Result<()>;
fn report_module_exception(
&mut self,
owner: FrameDocumentTaskOwner,
realm_id: FrameRealmId,
message: &str,
filename: &str,
error_value: Option<ScriptErrorValue>,
) -> Result<()>;
fn finish_graph_failure<'owner>(
&'owner mut self,
work: &Self::GraphFailureWork,
@@ -282,6 +293,7 @@ enum FrameModuleScriptExecutionResult<GraphReady, GraphFailure> {
EvaluationRejected {
work: GraphReady,
reason: String,
error_value: Option<ScriptErrorValue>,
},
EvaluationPending {
work: GraphReady,
@@ -644,9 +656,14 @@ where
completion_kind: FrameModuleScriptEvaluationCompletionKind::TopLevelAwait,
}
}
ModuleScriptEvaluationReactionState::Rejected { reason, .. } => {
FrameModuleScriptExecutionResult::EvaluationRejected { work, reason }
}
ModuleScriptEvaluationReactionState::Rejected {
reason,
error_value,
} => FrameModuleScriptExecutionResult::EvaluationRejected {
work,
reason,
error_value,
},
ModuleScriptEvaluationReactionState::Pending => {
FrameModuleScriptExecutionResult::EvaluationPending { work }
}
@@ -686,7 +703,9 @@ where
} else {
FrameModuleScriptTaskActivity::NoScriptOrEvent
};
if completion_kind.dispatches_script_load_event() {
if completion_kind.dispatches_script_load_event()
&& work.script().source_kind == ScriptSourceKind::External
{
let event_result = self
.hooks
.dispatch_script_element_event(&work, FrameDocumentScriptElementEventKind::Load);
@@ -730,9 +749,10 @@ where
let owner = work.owner();
let realm_id = work.realm_id();
let script_handle = work.script_handle();
if let Err(error) = self
.hooks
.dispatch_script_element_event(&work, FrameDocumentScriptElementEventKind::Load)
if work.script().source_kind == ScriptSourceKind::External
&& let Err(error) = self
.hooks
.dispatch_script_element_event(&work, FrameDocumentScriptElementEventKind::Load)
{
tracing::warn!(
owner = ?owner,
@@ -756,19 +776,39 @@ where
let realm_id = work.realm_id();
let script_handle = work.script_handle();
let request_url = work.request_key().url().clone();
let event_result = self.hooks.dispatch_graph_failure_script_element_event(
&work,
FrameDocumentScriptElementEventKind::Error,
let reports_exception = matches!(
ModuleFailurePolicy::for_module_load_error(work.error()),
ModuleFailurePolicy::GraphFailure | ModuleFailurePolicy::EvaluationFailure
);
let event_dispatched = event_result.is_ok();
if let Err(error) = event_result {
let exception_reported = reports_exception
&& self.report_module_exception(
owner,
realm_id,
work.error().message(),
work.script().url.as_str(),
work.error().error_value(),
);
let event_kind = if reports_exception {
FrameDocumentScriptElementEventKind::Load
} else {
FrameDocumentScriptElementEventKind::Error
};
let event_result = (!reports_exception
|| work.script().source_kind == ScriptSourceKind::External)
.then(|| {
self.hooks
.dispatch_graph_failure_script_element_event(&work, event_kind)
});
let event_dispatched =
exception_reported || event_result.as_ref().is_some_and(|result| result.is_ok());
if let Some(Err(error)) = event_result {
tracing::warn!(
owner = ?owner,
realm_id = ?realm_id,
script_handle = ?script_handle,
url = %request_url,
error = ?error,
"frame parser module script error event dispatch failed after graph failure"
"frame module script terminal event dispatch failed after graph failure"
);
}
self.hooks.record_runtime_warning(format_args!(
@@ -804,16 +844,24 @@ where
let owner = work.owner();
let realm_id = work.realm_id();
let script_handle = work.script_handle();
let event_result = self
.hooks
.dispatch_script_element_event(&work, FrameDocumentScriptElementEventKind::Error);
if let Err(dispatch_error) = event_result {
self.report_module_exception(
owner,
realm_id,
error.message(),
work.script().url.as_str(),
error.error_value(),
);
if work.script().source_kind == ScriptSourceKind::External
&& let Err(dispatch_error) = self
.hooks
.dispatch_script_element_event(&work, FrameDocumentScriptElementEventKind::Load)
{
tracing::warn!(
owner = ?owner,
realm_id = ?realm_id,
script_handle = ?script_handle,
error = ?dispatch_error,
"frame parser module script error event dispatch failed"
"frame module script load event dispatch failed after evaluation failure"
);
}
self.hooks.record_runtime_warning(format_args!(
@@ -830,15 +878,48 @@ where
&mut self,
work: Hooks::GraphReadyWork,
reason: String,
error_value: Option<ScriptErrorValue>,
) -> FrameModuleScriptOutputAction<Hooks::GraphReadyWork, Hooks::GraphFailureWork> {
let request_url = work.request_key().url().clone();
self.hooks.record_runtime_warning(format_args!(
"frame parser module graph `{}` pending evaluation rejected: {}",
request_url, reason
));
FrameModuleScriptOutputAction::without_script_or_event(
FrameModuleScriptFinalizationAction::FinishEvaluationRejected { work },
)
let reported = self.report_module_exception(
work.owner(),
work.realm_id(),
&reason,
work.script().url.as_str(),
error_value,
);
let finalization = FrameModuleScriptFinalizationAction::FinishEvaluationRejected { work };
if reported {
FrameModuleScriptOutputAction::after_script_or_event(finalization)
} else {
FrameModuleScriptOutputAction::without_script_or_event(finalization)
}
}
fn report_module_exception(
&mut self,
owner: FrameDocumentTaskOwner,
realm_id: FrameRealmId,
message: &str,
filename: &str,
error_value: Option<ScriptErrorValue>,
) -> bool {
match self
.hooks
.report_module_exception(owner, realm_id, message, filename, error_value)
{
Ok(()) => true,
Err(error) => {
self.hooks.record_runtime_warning(format_args!(
"frame module exception reporting failed for `{filename}`: {error}"
));
false
}
}
}
}
@@ -910,9 +991,11 @@ where
FrameModuleScriptExecutionResult::GraphFailure { work } => {
self.apply_graph_failure(work)
}
FrameModuleScriptExecutionResult::EvaluationRejected { work, reason } => {
self.apply_evaluation_rejected(work, reason)
}
FrameModuleScriptExecutionResult::EvaluationRejected {
work,
reason,
error_value,
} => self.apply_evaluation_rejected(work, reason, error_value),
FrameModuleScriptExecutionResult::EvaluationPending { work } => {
FrameModuleScriptOutputAction::without_script_or_event(
FrameModuleScriptFinalizationAction::FinishEvaluationPending { work },
@@ -1284,6 +1367,17 @@ mod tests {
Ok(())
}
fn report_module_exception(
&mut self,
_owner: FrameDocumentTaskOwner,
_realm_id: FrameRealmId,
_message: &str,
_filename: &str,
_error_value: Option<ScriptErrorValue>,
) -> Result<()> {
Ok(())
}
fn finish_graph_failure<'owner>(
&'owner mut self,
_work: &DocumentModuleGraphFailedWork,
@@ -1603,7 +1697,7 @@ mod tests {
);
assert!(
runner.hooks.dispatch_script_element_event_called,
"failed graph evaluation should dispatch the error event"
"failed graph evaluation should still dispatch the external script load event"
);
assert!(
runner.hooks.record_runtime_warning_called,
@@ -1,6 +1,6 @@
use super::*;
async fn queue_child_module_document_script_ready(
pub(super) async fn queue_child_module_document_script_ready(
page_vm: &mut PageVm,
base_url: &str,
create_reaction_child: bool,
@@ -0,0 +1,360 @@
use super::child_module_document_script_ready::queue_child_module_document_script_ready;
use super::child_parser_module_root_start_completion::advance_to_child_parser_module_root;
use super::*;
async fn queue_inline_child_error(
page_vm: &mut PageVm,
loader: &crate::network::ResourceRequestClient,
source: &str,
value: &str,
) -> anyhow::Result<()> {
let html = format!("<script id='broken' type='module'>{source}</script>");
page_vm.vm_mut().eval(&format!(
r#"
const frame = document.createElement('iframe');
frame.id = 'module-error-child';
frame.srcdoc = {html};
document.body.appendChild(frame);
"#,
html = serde_json::to_string(&html)?
))?;
advance_to_child_parser_module_root(page_vm, loader).await?;
install_child_error_observers(page_vm, "module-error-child", value)?;
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildParserModuleRootStart,
loader,
)
.await?
);
// The inline root completes its graph in the root-start body. Parser
// completion still has to release the deferred-script ordering barrier.
for _ in 0..4 {
if page_vm.has_ready_child_frame_semantic_turn_for_test(
ChildFrameSemanticTurnKind::DocumentScriptReady,
) {
return Ok(());
}
anyhow::ensure!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentLifecycle,
loader,
)
.await?,
"inline module must finish its parser before becoming runnable"
);
}
anyhow::bail!("inline child module did not become runnable")
}
fn install_child_error_observers(
page_vm: &mut PageVm,
frame_id: &str,
value: &str,
) -> anyhow::Result<()> {
page_vm.vm_mut().eval(&format!(
r#"
globalThis.__childErrors = [];
globalThis.__childOnerrors = [];
globalThis.__childErrorOrder = [];
globalThis.__parentErrors = 0;
globalThis.__scriptErrors = 0;
globalThis.__scriptLoads = 0;
globalThis.__coercions = 0;
globalThis.__unhandled = 0;
addEventListener('error', event => {{ ++__parentErrors; event.preventDefault(); }});
const child = document.getElementById({frame_id:?}).contentWindow;
child.__reason = {value};
const expectedReason = child.__reason;
child.addEventListener('unhandledrejection', event => {{ ++__unhandled; event.preventDefault(); }});
child.addEventListener('error', event => {{
__childErrors.push([
event.error, event instanceof child.ErrorEvent,
event.target === child, event.isTrusted,
event.error instanceof child.SyntaxError
]);
__childErrorOrder.push('window-error');
Promise.resolve().then(() => __childErrorOrder.push('error-microtask'));
event.preventDefault();
}});
child.onerror = (message, filename, line, column, error) => {{
__childOnerrors.push(error);
return true;
}};
const script = child.document.querySelector('script[type=module]');
script.addEventListener('error', () => ++__scriptErrors);
script.addEventListener('load', () => {{ ++__scriptLoads; __childErrorOrder.push('script-load'); }});
"#
))?;
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_reports_root_parse_error_to_its_window() {
run_page_vm_async_test(async {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader,
Url::parse("https://example.com/child-module-errors.html").unwrap(),
);
queue_inline_child_error(&mut page_vm, &loader, "export const broken = ;", "null").await?;
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?
);
assert_eq!(
page_vm
.vm_mut()
.eval_without_microtask_checkpoint_for_test(
r#"
JSON.stringify([
__childErrors.length, __childOnerrors.length,
__childErrors[0]?.slice(1).every(Boolean),
__childErrors[0]?.[0] === __childOnerrors[0],
__parentErrors, __scriptErrors, __scriptLoads,
__childErrorOrder.join('|')
])
"#
)?,
r#"[1,1,true,true,0,0,0,"window-error|error-microtask"]"#
);
Ok::<_, anyhow::Error>(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_preserves_synchronous_thrown_values() {
run_page_vm_async_test(async {
for value in [
"Object.freeze(new child.TypeError('original'))",
"undefined",
"null",
"false",
"-0",
"NaN",
"17n",
"Symbol('original')",
"Object.freeze({marker: 42})",
"({toString() { ++__coercions; throw new Error('must not coerce'); }})",
] {
let loader =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader,
Url::parse("https://example.com/child-module-errors.html").unwrap(),
);
queue_inline_child_error(&mut page_vm, &loader, "throw globalThis.__reason;", value)
.await?;
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?
);
assert_eq!(
page_vm
.vm_mut()
.eval_without_microtask_checkpoint_for_test(
r#"
JSON.stringify([
__childErrors.length, __childOnerrors.length,
Object.is(__childErrors[0]?.[0], child.__reason),
Object.is(__childOnerrors[0], child.__reason),
__childErrors[0]?.slice(1, 4).every(Boolean),
__parentErrors, __scriptErrors, __scriptLoads, __coercions
])
"#
)?,
"[1,1,true,true,true,0,0,0,0]",
"{value}"
);
}
Ok::<_, anyhow::Error>(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_distinguishes_fetch_parse_and_evaluation_failures() {
run_page_vm_async_test(async {
for kind in ["fetch", "parse", "evaluate", "retire"] {
let status = if kind == "fetch" { "HTTP/1.1 404 Not Found" } else { "HTTP/1.1 200 OK" };
let source = if kind == "parse" { "export const broken = ;" } else { "throw globalThis.__reason;" };
let (base_url, server) = spawn_path_response_http_server(vec![(
"/child-module-task-boundary.js", status, source.to_owned(), Duration::from_millis(50),
)]).await;
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader, Url::parse(&format!("{base_url}/page")).unwrap(),
);
queue_child_module_document_script_ready(&mut page_vm, &base_url, false).await?;
install_child_error_observers(&mut page_vm, "child-module-task-boundary", "Object.freeze(new child.TypeError('original'))")?;
if kind == "retire" {
page_vm.vm_mut().eval("child.addEventListener('error', () => document.getElementById('child-module-task-boundary').remove())")?;
}
assert!(page_vm.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady, &loader,
).await?);
let expected = match kind {
"fetch" => "0|0|0|1|0|0",
"retire" => "1|1|0|0|0|0",
_ => "1|1|0|0|1|0",
};
assert_eq!(page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(
"[__childErrors.length, __childOnerrors.length, __parentErrors, __scriptErrors, __scriptLoads, __unhandled].join('|')",
)?, expected, "{kind}");
assert_eq!(page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(&format!(r#"
__childErrors.every((entry, i) => entry[1] && entry[2] && entry[3] &&
entry[0] === __childOnerrors[i] &&
({parse} ? entry[4] : Object.is(entry[0], expectedReason)))
"#, parse = kind == "parse"))?, "true", "{kind}");
if matches!(kind, "parse" | "evaluate") {
assert_eq!(page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(
"__childErrorOrder.indexOf('window-error') < __childErrorOrder.indexOf('script-load') && __childErrorOrder.includes('error-microtask')",
)?, "true", "{kind}");
}
server.await.unwrap();
}
Ok::<_, anyhow::Error>(())
}).await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_preserves_deferred_rejections_without_repeating_load() {
run_page_vm_async_test(async {
for value in [
"Object.freeze(new child.TypeError('original'))",
"undefined",
"({toString() { ++__coercions; throw new Error('must not coerce'); }})",
] {
let (base_url, server) = spawn_path_response_http_server(vec![(
"/child-module-task-boundary.js",
"HTTP/1.1 200 OK",
"await new Promise((_, reject) => { globalThis.__reject = reject; });".to_owned(),
Duration::from_millis(50),
)])
.await;
let loader =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader,
Url::parse(&format!("{base_url}/page")).unwrap(),
);
queue_child_module_document_script_ready(&mut page_vm, &base_url, false).await?;
install_child_error_observers(&mut page_vm, "child-module-task-boundary", value)?;
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?
);
assert_eq!(
page_vm
.vm_mut()
.eval_without_microtask_checkpoint_for_test(
"[__childErrors.length, __scriptLoads].join('|')",
)?,
"0|1"
);
run_child_domcontentloaded_then_host_load_for_wait(&mut page_vm, "pending child TLA")
.await;
page_vm.vm_mut().eval("child.__reject(expectedReason)")?;
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ModuleReaction,
&loader,
)
.await?
);
assert!(
page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?
);
assert_eq!(
page_vm
.vm_mut()
.eval_without_microtask_checkpoint_for_test(
r#"
JSON.stringify([
__childErrors.length, __childOnerrors.length,
Object.is(__childErrors[0]?.[0], expectedReason),
Object.is(__childOnerrors[0], expectedReason),
__childErrors[0]?.slice(1, 4).every(Boolean),
__scriptErrors, __scriptLoads, __parentErrors, __unhandled, __coercions,
__childErrorOrder.includes('error-microtask')
])
"#
)?,
"[1,1,true,true,true,0,1,0,0,0,true]",
"{value}"
);
server.await.unwrap();
}
Ok::<_, anyhow::Error>(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_body_leaves_the_checkpoint_to_the_selected_task() {
run_page_vm_async_test(async {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader, Url::parse("https://example.com/child-module-errors.html").unwrap(),
);
queue_inline_child_error(&mut page_vm, &loader, "export const broken = ;", "null").await?;
let outcome = page_vm.run_page_child_document_script_ready_body_for_test().await?.unwrap();
assert!(matches!(outcome.action.target_effect,
crate::page_task_queue::PageChildDocumentScriptReadyTargetEffect::AppliedScriptOrEventToCurrentOwner { made_progress: true }
));
assert_eq!(page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(
"__childErrorOrder.join('|')",
)?, "window-error");
Ok::<_, anyhow::Error>(())
}).await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn child_module_error_reporting_discards_a_claim_from_a_replaced_document() {
run_page_vm_async_test(async {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).unwrap();
let (mut page_vm, _resource, _wake) = page_vm_with_bound_task_sources_and_owner_wake(
&loader, Url::parse("https://example.com/child-module-errors.html").unwrap(),
);
queue_inline_child_error(&mut page_vm, &loader, "export const broken = ;", "null").await?;
let claim = page_vm.claim_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
).unwrap();
page_vm.vm_mut().eval("document.getElementById('module-error-child').srcdoc = '<body>replacement</body>'")?;
assert!(page_vm.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildNavigationCommit, &loader,
).await?);
page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(
"globalThis.__retiredCheckpoint = 0; Promise.resolve().then(() => ++__retiredCheckpoint)",
)?;
page_vm.run_claimed_selected_page_task_for_test(claim, &loader).await?;
assert_eq!(page_vm.vm_mut().eval_without_microtask_checkpoint_for_test(
"[__childErrors.length, __parentErrors, __scriptErrors, __scriptLoads, __retiredCheckpoint].join('|')",
)?, "0|0|0|0|0");
Ok::<_, anyhow::Error>(())
}).await.unwrap();
}
@@ -27,7 +27,7 @@ document.body.appendChild(frame);
Ok(())
}
async fn advance_to_child_parser_module_root(
pub(super) async fn advance_to_child_parser_module_root(
page_vm: &mut PageVm,
loader: &crate::network::ResourceRequestClient,
) -> anyhow::Result<()> {
@@ -823,6 +823,13 @@ globalThis.__childModuleDeferFailureOrderFirst = 1;
<script id="first-module-defer-success" type="module" src="{first_script_url}"><\/script>
<script id="second-module-defer-failure" type="module" src="{second_script_url}"><\/script>
<script>
addEventListener("error", event => {{
parent.__childModuleDeferFailureOrderEvents.push("window-error:" + (
event instanceof ErrorEvent && event.error instanceof SyntaxError &&
event.target === window && event.isTrusted
));
event.preventDefault();
}});
document.getElementById("first-module-defer-success").addEventListener("load", () => {{
parent.__childModuleDeferFailureOrderEvents.push("first-load");
}});
@@ -957,8 +964,8 @@ globalThis.__childModuleDeferFailureOrderFirst = 1;
page_vm
.vm_mut()
.eval("__childModuleDeferFailureOrderEvents.join('|')")?,
"before:true|after:undefined|first-module:true|first-load|second-error",
"later graph failure should dispatch only after the earlier module-defer completes"
"before:true|after:undefined|first-module:true|first-load|window-error:true|second-load",
"later parse failure should report to its Window and fire external script load only after the earlier module-defer completes"
);
followup_sources.push(
run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(
@@ -1019,7 +1026,7 @@ globalThis.__childModuleDeferFailureOrderFirst = 1;
);
assert_eq!(
events_after_second_completion, "before:true|after:undefined",
"faster second graph failure completion must not dispatch script error before earlier parser module"
"faster second graph failure completion must not report an exception before the earlier parser module"
);
assert_eq!(
events_after_second_module_owner, "before:true|after:undefined",
@@ -1031,7 +1038,7 @@ globalThis.__childModuleDeferFailureOrderFirst = 1;
);
assert_eq!(
events_after_blocked_second_terminal, "before:true|after:undefined",
"blocked later graph failure should not dispatch script error or iframe load"
"blocked later graph failure should not report an exception or dispatch script or iframe load"
);
assert!(matches!(
first_completion.action.source(),
@@ -1058,7 +1065,7 @@ globalThis.__childModuleDeferFailureOrderFirst = 1;
);
assert_eq!(
final_events,
"before:true|after:undefined|first-module:true|first-load|second-error|load",
"before:true|after:undefined|first-module:true|first-load|window-error:true|second-load|load",
"later graph failure should preserve parser module document order and keep iframe load on HostLoad"
);
@@ -2252,184 +2259,7 @@ globalThis.__childDynamicImportLeafValue = 701;
})
.await;
}
#[tokio::test]
async fn page_vm_child_module_graph_failure_blocks_host_load_until_error_dispatches() {
run_page_vm_async_test(async move {
let (base_url, server) = spawn_path_response_http_server(vec![(
"/child-bad-module.js",
"HTTP/1.1 200 OK",
"import {".to_owned(),
Duration::from_millis(200),
)])
.await;
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
let document_url = Url::parse(&format!("{base_url}/page")).expect("page url");
let page_vm = test_page_vm_with_loader_and_document_url(&loader, Vec::new(), document_url);
let local_executor = page_vm.local_executor.clone();
let (
pre_completion_sources,
events_before_completion,
resource_ready_before_wait,
completion_source,
events_after_module_owner,
graph_failure_source,
events_after_graph_failure,
host_load_source,
final_events,
) = local_executor
.run(async move {
let mut page_vm = page_vm;
let script_url = format!("{base_url}/child-bad-module.js");
page_vm.vm_mut().eval(&format!(
r#"
(() => {{
globalThis.__childModuleFailureHostLoadEvents = [];
const root = document.documentElement || document.appendChild(document.createElement("html"));
const body = document.body || root.appendChild(document.createElement("body"));
const frame = document.createElement("iframe");
frame.onload = () => globalThis.__childModuleFailureHostLoadEvents.push("frame-load");
frame.srcdoc = `
<script>parent.__childModuleFailureHostLoadEvents.push("before:" + (globalThis === self));<\/script>
<script id="bad-module" type="module" src="{script_url}"><\/script>
<script>
const script = document.getElementById("bad-module");
const recordTerminal = event => {{
if (!(event instanceof Event) || !event.isTrusted || event.target !== script ||
event.bubbles || event.cancelable || event.composed)
throw Error("native child script terminal event realm, trust or flags");
parent.__childModuleFailureHostLoadEvents.push("script-" + event.type);
}};
script.addEventListener("load", recordTerminal);
script.addEventListener("error", recordTerminal);
parent.__childModuleFailureHostLoadEvents.push("after");
<\/script>
`;
body.appendChild(frame);
}})()
"#
))?;
let mut pre_completion_sources = Vec::new();
let mut events_before_completion = String::new();
for _ in 0..8 {
let source = page_vm.run_next_child_frame_task_source_for_semantic_test().await;
events_before_completion = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
if let Some(source) = source {
pre_completion_sources.push(source);
}
if source.is_none()
|| page_vm.has_ready_page_websocket_task_for_test()
|| events_before_completion.contains("frame-load")
{
break;
}
}
let resource_ready_before_wait = page_vm
.page_resource_completion_queue()
.has_ready_completion();
if !page_vm.page_resource_completion_queue().has_ready_completion() {
let arrived = tokio::time::timeout(
Duration::from_secs(2),
wait_for_typed_page_resource_completion(&mut page_vm),
)
.await
.expect("child bad module completion should arrive before timeout");
assert!(arrived, "child bad module completion sender should remain open");
}
let completion =
run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;
let completion_source = completion.action.source();
run_expected_child_module_script_terminal_turn(
&mut page_vm,
"child graph-failure module terminal",
)
.await;
let events_after_module_owner = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
let graph_failure_source = page_vm.run_next_child_frame_task_source_for_semantic_test().await;
let events_after_graph_failure = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
let host_load_source = Some(
run_child_domcontentloaded_then_host_load_for_wait(
&mut page_vm,
"child module graph-failure iframe load",
)
.await,
);
let final_events = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
Ok::<_, anyhow::Error>((
pre_completion_sources,
events_before_completion,
resource_ready_before_wait,
completion_source,
events_after_module_owner,
graph_failure_source,
events_after_graph_failure,
host_load_source,
final_events,
))
})
.await
.expect("page vm child bad module HostLoad gate test should run");
assert!(
pre_completion_sources.contains(&ChildFrameSemanticTurnKind::ParserModuleRootStart),
"pre-completion turns should start the module root fetch from its typed source: {pre_completion_sources:?}"
);
assert!(
!resource_ready_before_wait,
"delayed bad module response should leave a window to prove HostLoad is gated before completion"
);
assert_eq!(
events_before_completion, "before:true|after",
"pending bad module script must block iframe load before resource completion"
);
assert_eq!(
completion_source,
RendererOwnerResourceActivitySource::ModuleGraphFetch
);
assert_eq!(
events_after_module_owner, "before:true|after",
"module owner event should not dispatch script error or iframe load inline"
);
assert_eq!(
graph_failure_source,
Some(ChildFrameSemanticTurnKind::DocumentScriptReady),
"graph failure should dispatch through DocumentScriptReady"
);
assert_eq!(
events_after_graph_failure, "before:true|after|script-error",
"graph failure should dispatch script error without iframe load"
);
assert_eq!(
host_load_source,
Some(ChildFrameSemanticTurnKind::HostLoad),
"iframe load should remain a later HostLoad source after graph failure"
);
assert_eq!(
final_events, "before:true|after|script-error|frame-load",
"HostLoad should dispatch iframe load only after graph failure finalizes"
);
server
.await
.expect("child bad module HostLoad gate server should finish");
})
.await;
}
#[tokio::test]
async fn page_vm_child_module_dependency_completion_queues_module_script_terminal_work() {
run_page_vm_async_test(async move {
@@ -2971,3 +2801,189 @@ parent.__childModuleDependencyFailureEvents.push("root:" + depValue);
})
.await;
}
#[tokio::test]
async fn page_vm_child_module_parse_failure_blocks_host_load_until_exception_is_reported() {
run_page_vm_async_test(async move {
let (base_url, server) = spawn_path_response_http_server(vec![(
"/child-bad-module.js",
"HTTP/1.1 200 OK",
"import {".to_owned(),
Duration::from_millis(200),
)])
.await;
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
let document_url = Url::parse(&format!("{base_url}/page")).expect("page url");
let page_vm = test_page_vm_with_loader_and_document_url(&loader, Vec::new(), document_url);
let local_executor = page_vm.local_executor.clone();
let (
pre_completion_sources,
events_before_completion,
resource_ready_before_wait,
completion_source,
events_after_module_owner,
graph_failure_source,
events_after_graph_failure,
host_load_source,
final_events,
) = local_executor
.run(async move {
let mut page_vm = page_vm;
let script_url = format!("{base_url}/child-bad-module.js");
page_vm.vm_mut().eval(&format!(
r#"
(() => {{
globalThis.__childModuleFailureHostLoadEvents = [];
const root = document.documentElement || document.appendChild(document.createElement("html"));
const body = document.body || root.appendChild(document.createElement("body"));
const frame = document.createElement("iframe");
frame.onload = () => globalThis.__childModuleFailureHostLoadEvents.push("frame-load");
frame.srcdoc = `
<script>parent.__childModuleFailureHostLoadEvents.push("before:" + (globalThis === self));<\/script>
<script id="bad-module" type="module" src="{script_url}"><\/script>
<script>
addEventListener("error", event => {{
parent.__childModuleFailureHostLoadEvents.push("window-error:" + (
event instanceof ErrorEvent && event.error instanceof SyntaxError &&
event.target === window && event.isTrusted
));
event.preventDefault();
}});
const script = document.getElementById("bad-module");
const recordTerminal = event => {{
if (!(event instanceof Event) || !event.isTrusted || event.target !== script ||
event.bubbles || event.cancelable || event.composed)
throw Error("native child script terminal event realm, trust or flags");
parent.__childModuleFailureHostLoadEvents.push("script-" + event.type);
}};
script.addEventListener("load", recordTerminal);
script.addEventListener("error", recordTerminal);
parent.__childModuleFailureHostLoadEvents.push("after");
<\/script>
`;
body.appendChild(frame);
}})()
"#
))?;
let mut pre_completion_sources = Vec::new();
let mut events_before_completion = String::new();
for _ in 0..8 {
let source = page_vm.run_next_child_frame_task_source_for_semantic_test().await;
events_before_completion = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
if let Some(source) = source {
pre_completion_sources.push(source);
}
if source.is_none()
|| page_vm.has_ready_page_websocket_task_for_test()
|| events_before_completion.contains("frame-load")
{
break;
}
}
let resource_ready_before_wait = page_vm
.page_resource_completion_queue()
.has_ready_completion();
if !page_vm.page_resource_completion_queue().has_ready_completion() {
let arrived = tokio::time::timeout(
Duration::from_secs(2),
wait_for_typed_page_resource_completion(&mut page_vm),
)
.await
.expect("child bad module completion should arrive before timeout");
assert!(arrived, "child bad module completion sender should remain open");
}
let completion =
run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;
let completion_source = completion.action.source();
run_expected_child_module_script_terminal_turn(
&mut page_vm,
"child graph-failure module terminal",
)
.await;
let events_after_module_owner = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
let graph_failure_source = page_vm.run_next_child_frame_task_source_for_semantic_test().await;
let events_after_graph_failure = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
let host_load_source = Some(
run_child_domcontentloaded_then_host_load_for_wait(
&mut page_vm,
"child module graph-failure iframe load",
)
.await,
);
let final_events = page_vm
.vm_mut()
.eval("__childModuleFailureHostLoadEvents.join('|')")?;
Ok::<_, anyhow::Error>((
pre_completion_sources,
events_before_completion,
resource_ready_before_wait,
completion_source,
events_after_module_owner,
graph_failure_source,
events_after_graph_failure,
host_load_source,
final_events,
))
})
.await
.expect("page vm child bad module HostLoad gate test should run");
assert!(
pre_completion_sources.contains(&ChildFrameSemanticTurnKind::ParserModuleRootStart),
"pre-completion turns should start the module root fetch from its typed source: {pre_completion_sources:?}"
);
assert!(
!resource_ready_before_wait,
"delayed bad module response should leave a window to prove HostLoad is gated before completion"
);
assert_eq!(
events_before_completion, "before:true|after",
"pending bad module script must block iframe load before resource completion"
);
assert_eq!(
completion_source,
RendererOwnerResourceActivitySource::ModuleGraphFetch
);
assert_eq!(
events_after_module_owner, "before:true|after",
"module owner event should not report an exception or dispatch script or iframe load inline"
);
assert_eq!(
graph_failure_source,
Some(ChildFrameSemanticTurnKind::DocumentScriptReady),
"graph failure should dispatch through DocumentScriptReady"
);
assert_eq!(
events_after_graph_failure, "before:true|after|window-error:true|script-load",
"parse failure should report to its Window and fire external script load without iframe load"
);
assert_eq!(
host_load_source,
Some(ChildFrameSemanticTurnKind::HostLoad),
"iframe load should remain a later HostLoad source after graph failure"
);
assert_eq!(
final_events, "before:true|after|window-error:true|script-load|frame-load",
"HostLoad should dispatch iframe load only after graph failure finalizes"
);
server
.await
.expect("child bad module HostLoad gate server should finish");
})
.await;
}
@@ -111,6 +111,7 @@ mod child_dynamic_import_owner_action;
mod child_host_load;
mod child_module_dependency_fetch_start;
mod child_module_document_script_ready;
mod child_module_error_reporting;
mod child_module_integrity;
mod child_module_script_terminal;
mod child_module_script_terminal_completion;
@@ -11,7 +11,7 @@ use crate::{
FrameDocumentScriptElementEventKind, FrameDocumentTaskOwner, FrameRealmId,
},
module_runtime::{ModuleEntryId, ModuleLoadError},
types::ScriptMode,
types::{ScriptErrorValue, ScriptMode},
};
use super::super::super::{ScriptVm, child_document_event::ChildDocumentEventOwner};
@@ -205,6 +205,18 @@ impl FrameModuleScriptDocumentScriptHooks for ChildModuleScriptExecutionOwner<'_
)
}
fn report_module_exception(
&mut self,
owner: FrameDocumentTaskOwner,
realm_id: FrameRealmId,
message: &str,
filename: &str,
error_value: Option<ScriptErrorValue>,
) -> Result<()> {
self.vm
.report_child_window_error_body(owner, realm_id, message, filename, error_value)
}
fn finish_graph_failure<'owner>(
&'owner mut self,
work: &DocumentModuleGraphFailedWork,
@@ -12,6 +12,7 @@ use crate::context_bootstrap::{
ORIGINAL_WEBASSEMBLY_COMPILE_ERROR_CONSTRUCTOR_SLOT,
ORIGINAL_WEBASSEMBLY_LINK_ERROR_CONSTRUCTOR_SLOT, dispatch_window_error_event_with_details,
};
use crate::frame_owner_model::{FrameDocumentTaskOwner, FrameRealmId};
use crate::host::ScriptEventTask;
use crate::module_runtime::{ModuleEntryId, ModuleLoadError};
use crate::native_bridge::PageScriptHost;
@@ -122,49 +123,81 @@ impl ScriptVm {
.map_err(anyhow::Error::msg);
}
}
let global = scope.get_current_context().global(scope);
let message_value = v8_string(scope, message)
.ok_or_else(|| anyhow!("failed to allocate reportError message"))?;
let retained = matches!(error_value, Some(ScriptErrorValue::Retained(_)));
let error_value = match error_value {
Some(ScriptErrorValue::Retained(id)) => {
super::native_module::retained_module_exception(scope, id)?
}
Some(ScriptErrorValue::Constructor(kind)) => {
window_script_failure_error_value(scope, global, Some(kind), message_value)
}
None => window_script_failure_error_value(scope, global, None, message_value),
};
// Location metadata belongs to the ErrorEvent. Never mutate
// the original exception (or invoke an author's setter).
if !retained
&& let Some(filename) = filename
&& let Some(filename_value) = v8_string(scope, filename)
&& let Ok(error_object) = v8::Local::<v8::Object>::try_from(error_value)
{
let _ = error_object.set(
scope,
v8str(scope, "fileName").into(),
filename_value.into(),
);
}
// Internal script failure reporting must not call the page-visible
// window.reportError function while lifecycle state is unwinding.
// Dispatch the equivalent ErrorEvent body directly.
dispatch_window_error_event_with_details(
dispatch_script_failure_error_body(scope, host_ptr, message, filename, error_value)
})
}
pub(crate) fn report_child_window_error_body(
&mut self,
owner: FrameDocumentTaskOwner,
realm_id: FrameRealmId,
message: &str,
filename: &str,
error_value: Option<ScriptErrorValue>,
) -> Result<()> {
anyhow::ensure!(
self.child_parser_module_route_task_is_current(owner, realm_id),
"child module exception reporting owner is no longer current"
);
self.with_frame_realm_scope(realm_id, |scope, host_ptr| {
dispatch_script_failure_error_body(
scope,
host_ptr,
message,
filename.unwrap_or(""),
0,
0,
Some(error_value),
Some(filename),
error_value,
)
.map_err(anyhow::Error::msg)
})
}
}
fn dispatch_script_failure_error_body(
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
message: &str,
filename: Option<&str>,
error_value: Option<ScriptErrorValue>,
) -> Result<()> {
let global = scope.get_current_context().global(scope);
let message_value = v8_string(scope, message)
.ok_or_else(|| anyhow!("failed to allocate reportError message"))?;
let retained = matches!(error_value, Some(ScriptErrorValue::Retained(_)));
let error_value = match error_value {
Some(ScriptErrorValue::Retained(id)) => {
super::native_module::retained_module_exception(scope, id)?
}
Some(ScriptErrorValue::Constructor(kind)) => {
window_script_failure_error_value(scope, global, Some(kind), message_value)
}
None => window_script_failure_error_value(scope, global, None, message_value),
};
// Location metadata belongs to the ErrorEvent. Never mutate
// the original exception (or invoke an author's setter).
if !retained
&& let Some(filename) = filename
&& let Some(filename_value) = v8_string(scope, filename)
&& let Ok(error_object) = v8::Local::<v8::Object>::try_from(error_value)
{
let _ = error_object.set(
scope,
v8str(scope, "fileName").into(),
filename_value.into(),
);
}
// This body must not call the page-visible reportError function or own
// a checkpoint, whether it runs in the main Window or a child realm.
dispatch_window_error_event_with_details(
scope,
host_ptr,
message,
filename.unwrap_or(""),
0,
0,
Some(error_value),
)
.map_err(anyhow::Error::msg)
}
fn window_script_failure_error_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,