Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(scripts): execute child inline classics synchronously (#766)

Donough Liu80d4d8613f76
diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
index 4e64ad31a..828f1c1d7 100644
--- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs
+++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
@@ -1781,22 +1781,7 @@ pub(super) fn finish_runtime_mutation_effects(
}
for candidate in runtime_script_start_candidates {
- let (node, host_script_handle) = candidate.into_parts();
- let Some(plan) = runtime.host_plan_script_start(node, &host_script_handle) else {
- continue;
- };
- match unsafe { &mut *host_ptr }.commit_current_main_runtime_script_start(runtime, plan) {
- Ok(Some(committed)) => {
- execute_committed_inline_classic_script(runtime, scope, host_ptr, committed);
- }
- Ok(None) => {}
- Err(message) => {
- if let Some(message) = v8::String::new(scope, &message) {
- let exception = v8::Exception::error(scope, message);
- scope.throw_exception(exception);
- }
- }
- }
+ finish_runtime_script_start_candidate(runtime, scope, host_ptr, candidate);
}
for popover in removed_open_popovers {
@@ -1874,6 +1859,143 @@ pub(super) fn finish_runtime_mutation_effects(
changed
}
+pub(super) fn finish_runtime_script_start_candidate(
+ runtime: &mut DocumentRuntime,
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ candidate: crate::mutation_coordinator::RuntimeScriptStartCandidate,
+) {
+ let node = candidate.into_node();
+ let Some(owner_document_handle) = runtime.dom_host.owner_document_handle(node) else {
+ return;
+ };
+ if owner_document_handle != runtime.dom_host.document_handle() {
+ start_connected_child_document_script(
+ runtime,
+ scope,
+ host_ptr,
+ node,
+ owner_document_handle,
+ );
+ return;
+ }
+ let wrapper = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, node);
+ let Some(wrapper) = wrapper else {
+ return;
+ };
+
+ let host_script_handle = native_bridge::object_string_property(scope, wrapper, "__moliHandle")
+ .unwrap_or_else(|| {
+ let handle = format!("dynamic-script-native-{}", node.index());
+ if let Some(value) = v8::String::new(scope, &handle) {
+ let key = v8str(scope, "__moliHandle");
+ let _ = wrapper.define_own_property(
+ scope,
+ key.into(),
+ value.into(),
+ v8::PropertyAttribute::DONT_ENUM,
+ );
+ }
+ handle
+ });
+ let Some(plan) = runtime.host_plan_script_start(node, &host_script_handle) else {
+ return;
+ };
+ match unsafe { &mut *host_ptr }.commit_current_main_runtime_script_start(runtime, plan) {
+ Ok(Some(committed)) => {
+ execute_committed_inline_classic_script(runtime, scope, host_ptr, committed);
+ }
+ Ok(None) => {}
+ Err(message) => {
+ if let Some(message) = v8::String::new(scope, &message) {
+ let exception = v8::Exception::error(scope, message);
+ scope.throw_exception(exception);
+ }
+ }
+ }
+}
+
+fn start_connected_child_document_script(
+ runtime: &mut DocumentRuntime,
+ scope: &mut v8::PinScope<'_, '_>,
+ host_ptr: *mut JsContextHost,
+ node: DomHandle,
+ owner_document_handle: DomHandle,
+) {
+ use crate::host::{
+ RuntimeScriptStartDecision, ScriptElementLoader, ScriptElementLoaderOptions,
+ };
+ let (preparation, decision) = ScriptElementLoader::prepare(
+ &mut runtime.dom_host,
+ &runtime.document,
+ node,
+ ScriptElementLoaderOptions::with_scripting_enabled(
+ unsafe { &*host_ptr }.document_scripting_enabled(owner_document_handle),
+ ),
+ )
+ .into_parts();
+ match decision {
+ RuntimeScriptStartDecision::Skip { commit_start, .. } => {
+ if commit_start {
+ let _ = runtime.dom_host.set_script_already_started(node, true);
+ }
+ }
+ RuntimeScriptStartDecision::ExecuteInlineClassic { source } => {
+ if let Err(error) = unsafe { &mut *host_ptr }
+ .execute_child_dynamic_inline_classic_script_on_current_stack(
+ scope,
+ owner_document_handle,
+ node,
+ source,
+ )
+ {
+ // Script exceptions are reported in the child Window. They do
+ // not escape from the DOM operation that inserted the element.
+ tracing::debug!(%error, "child dynamic inline classic script failed");
+ }
+ }
+ RuntimeScriptStartDecision::Queue {
+ source,
+ kind,
+ mode,
+ source_kind,
+ } => {
+ match unsafe { &mut *host_ptr }
+ .queue_child_dynamic_external_classic_script_for_current_document(
+ scope,
+ owner_document_handle,
+ node,
+ &preparation,
+ &source,
+ kind,
+ mode,
+ source_kind,
+ ) {
+ Ok(true) => {}
+ Ok(false) => tracing::debug!(
+ node = ?node,
+ owner_document_handle = ?owner_document_handle,
+ kind = ?kind,
+ mode = ?mode,
+ source_kind = ?source_kind,
+ "child runtime script has no supported current-document queue"
+ ),
+ Err(error) => tracing::warn!(
+ node = ?node,
+ owner_document_handle = ?owner_document_handle,
+ %error,
+ "failed to prepare child runtime external classic script"
+ ),
+ }
+ }
+ RuntimeScriptStartDecision::RegisterImportMap { .. }
+ | RuntimeScriptStartDecision::RejectExternalImportMap
+ | RuntimeScriptStartDecision::QueueFailed { .. } => {}
+ }
+}
+
fn execute_committed_inline_classic_script(
runtime: &mut DocumentRuntime,
scope: &mut v8::PinScope<'_, '_>,
@@ -1999,9 +2121,8 @@ pub(super) fn apply_runtime_mutation_effects_to_dom_host(
.map(|started| started.elapsed().as_micros())
.unwrap_or_default();
let started = dom_binding_timing_started();
- let mutation_result = mutations.apply(
- scope, host_ptr, dom_host, document, scripts, events, effects, options,
- );
+ let mutation_result =
+ mutations.apply(scope, host_ptr, dom_host, scripts, events, effects, options);
if let Some(started) = total_started {
let total_us = started.elapsed().as_micros();
if total_us >= 500 {
diff --git a/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs b/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs
index 35f938245..d4cb126aa 100644
--- a/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs
+++ b/moli-renderer-v8/src/document_script_scheduler/frame_document_script_owner.rs
@@ -107,10 +107,10 @@ mod tests {
use crate::document_runtime::DomHandle;
use crate::document_script_scheduler::DocumentScriptExecutionOutcome;
use crate::frame_owner_model::{
- DocumentId, FrameDocumentDynamicClassicScriptExecutionAction,
+ DocumentId, FrameDocumentExternalClassicScriptExecutionAction,
FrameDocumentScriptExecutionWork, FrameDocumentTaskOwner, FrameId, FrameRealmId,
FrameSchedulerLaneId, FrameScriptJob, FrameScriptJobKind, FrameScriptSource, LocalWindowId,
- PendingChildDynamicDocumentScript,
+ PendingChildExternalClassicDocumentScript,
};
use moli_fetch::RequestCredentialsMode;
@@ -171,7 +171,6 @@ mod tests {
work: FrameDocumentScriptExecutionWork,
) -> Self::ExecuteFuture<'_> {
self.events.push(match work {
- FrameDocumentScriptExecutionWork::DynamicClassic(_) => "dynamic-classic",
FrameDocumentScriptExecutionWork::ExternalClassic(_) => "external-classic",
FrameDocumentScriptExecutionWork::JavascriptUrl(_) => "javascript-url",
FrameDocumentScriptExecutionWork::ModuleScript(_) => "module-script",
@@ -208,7 +207,7 @@ mod tests {
}
}
- fn dynamic_classic_work() -> FrameDocumentScriptExecutionWork {
+ fn external_classic_work() -> FrameDocumentScriptExecutionWork {
let script_url = url::Url::parse("https://frame-document-script-owner.test/dynamic.js")
.expect("dynamic script URL should parse");
let owner = FrameDocumentTaskOwner::new(
@@ -216,21 +215,23 @@ mod tests {
LocalWindowId(10),
DocumentId(20),
);
- let pending = PendingChildDynamicDocumentScript {
+ let pending = PendingChildExternalClassicDocumentScript {
child_handle: DomHandle::new(1),
owner,
realm_id: Some(FrameRealmId(30)),
script_handle: DomHandle::new(40),
- source: "globalThis.__dynamic = true;".to_owned(),
- script_nonce: None,
- script_integrity: None,
+ load_delay:
+ crate::frame_owner_model::ChildDocumentAsyncClassicScriptLoadDelay::AlreadyUnblocked,
+ source_result: Ok("globalThis.__dynamic = true;".to_owned()),
+ script_url: script_url.clone(),
+ script_base_url: script_url.clone(),
};
let job = FrameScriptJob {
frame_id: FrameId("dynamic-frame".to_owned()),
local_window_id: owner.local_window_id,
document_id: owner.document_id,
current_script: Some(DomHandle::new(40)),
- kind: FrameScriptJobKind::DynamicClassic,
+ kind: FrameScriptJobKind::ExternalClassic,
source: FrameScriptSource::SourceText("globalThis.__dynamic = true;".to_owned()),
script_url: script_url.clone(),
base_url: script_url,
@@ -239,10 +240,12 @@ mod tests {
credentials_mode: RequestCredentialsMode::SameOrigin,
referrer_policy: None,
};
- FrameDocumentScriptExecutionWork::dynamic_classic(
- FrameDocumentDynamicClassicScriptExecutionAction::new(
+ FrameDocumentScriptExecutionWork::external_classic(
+ FrameDocumentExternalClassicScriptExecutionAction::new(
pending.execution_target(FrameRealmId(30)),
- job,
+ crate::frame_owner_model::FrameDocumentExternalClassicScriptExecution::ScriptJob(
+ Box::new(job),
+ ),
),
)
}
@@ -250,7 +253,7 @@ mod tests {
#[tokio::test]
async fn started_frame_document_script_execution_runs_work_and_reports_followup() {
let hooks = FakeFrameDocumentScriptHooks {
- prepared_work: Some(dynamic_classic_work()),
+ prepared_work: Some(external_classic_work()),
..Default::default()
};
let mut owner = FrameDocumentScriptExecutionOwner::new(hooks);
@@ -261,7 +264,7 @@ mod tests {
.expect("frame document script owner should run ready work");
assert_eq!(outcome, DocumentScriptExecutionOutcome::Progressed);
- assert_eq!(owner.hooks.events, ["prepare", "dynamic-classic"]);
+ assert_eq!(owner.hooks.events, ["prepare", "external-classic"]);
assert_eq!(
owner.hooks.execution_followups,
[FakeExecutionFollowup { attempted: true }]
@@ -294,7 +297,7 @@ mod tests {
#[tokio::test]
async fn frame_document_script_execution_error_stops_before_outcome_mapping() {
let hooks = FakeFrameDocumentScriptHooks {
- prepared_work: Some(dynamic_classic_work()),
+ prepared_work: Some(external_classic_work()),
fail_execution: true,
..Default::default()
};
@@ -306,7 +309,7 @@ mod tests {
.expect_err("frame document script owner should propagate execution failures");
assert_eq!(error.to_string(), "frame document script execution failed");
- assert_eq!(owner.hooks.events, ["prepare", "dynamic-classic"]);
+ assert_eq!(owner.hooks.events, ["prepare", "external-classic"]);
assert!(owner.hooks.execution_followups.is_empty());
assert!(owner.hooks.dropped_followups.is_empty());
}
diff --git a/moli-renderer-v8/src/frame_owner_model.rs b/moli-renderer-v8/src/frame_owner_model.rs
index f05745081..8418fe310 100644
--- a/moli-renderer-v8/src/frame_owner_model.rs
+++ b/moli-renderer-v8/src/frame_owner_model.rs
@@ -50,8 +50,6 @@ pub(crate) use classic_script_tasks::{
frame_script_job_kind_from_parser_classic_ready_kind,
};
pub(crate) use frame_task_sources::{
- FrameDocumentDynamicClassicExecutionFollowup, FrameDocumentDynamicClassicPrepareFollowup,
- FrameDocumentDynamicClassicPrepareSkipReason, FrameDocumentDynamicClassicScriptExecutionAction,
FrameDocumentExternalClassicExecutionFollowup, FrameDocumentExternalClassicExecutionResult,
FrameDocumentExternalClassicPostExecutionAction, FrameDocumentExternalClassicPrepareFollowup,
FrameDocumentExternalClassicPrepareSkipReason, FrameDocumentExternalClassicScriptExecution,
@@ -65,8 +63,7 @@ pub(crate) use frame_task_sources::{
FrameDocumentScriptExecutionWork, FrameDocumentScriptPrepareFollowup,
FrameDocumentScriptReadyTaskWork, FrameDocumentScriptWorkAdmission,
FrameDocumentUnboundScriptWork, PendingChildDocumentScriptExecutionWork,
- PendingChildDynamicDocumentScript, PendingChildExternalClassicDocumentScript,
- PendingChildJavascriptUrlDocumentScript,
+ PendingChildExternalClassicDocumentScript, PendingChildJavascriptUrlDocumentScript,
};
pub(crate) use lifecycle_tasks::{
ChildDocumentAsyncClassicScriptLoadDelay, DocumentLinkEventOwner,
diff --git a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs
index 5d1532bc4..cf27efe38 100644
--- a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs
+++ b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/document_script_ready.rs
@@ -11,37 +11,6 @@ use crate::frame_owner_model::{
};
use url::Url;
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub(crate) struct PendingChildDynamicDocumentScript {
- pub(crate) child_handle: DomHandle,
- pub(crate) owner: FrameDocumentTaskOwner,
- pub(crate) realm_id: Option<FrameRealmId>,
- pub(crate) script_handle: DomHandle,
- pub(crate) source: String,
- pub(crate) script_nonce: Option<String>,
- pub(crate) script_integrity: Option<String>,
-}
-
-impl DocumentScriptReadyActionRoute<FrameDocumentOwner> for PendingChildDynamicDocumentScript {
- fn payload_document_owner(&self) -> FrameDocumentOwner {
- self.owner.document_owner()
- }
-}
-
-impl DocumentScriptReadyActionDispatchRoute<FrameDocumentReadyActionRoute>
- for PendingChildDynamicDocumentScript
-{
- fn dispatch_route(&self) -> FrameDocumentReadyActionRoute {
- FrameDocumentReadyActionRoute::from_frame_document_parts(
- Some(self.child_handle),
- self.owner,
- self.realm_id,
- self.realm_id.is_some(),
- self.script_handle,
- )
- }
-}
-
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PendingChildExternalClassicDocumentScript {
pub(crate) child_handle: DomHandle,
@@ -98,14 +67,12 @@ pub(crate) struct PendingChildJavascriptUrlDocumentScript {
/// before the prerequisite turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FrameDocumentUnboundScriptWork {
- DynamicClassic(PendingChildDynamicDocumentScript),
ExternalClassic(PendingChildExternalClassicDocumentScript),
JavascriptUrl(PendingChildJavascriptUrlDocumentScript),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FrameDocumentRealmBoundScriptWork {
- DynamicClassic(PendingChildDynamicDocumentScript),
ExternalClassic(PendingChildExternalClassicDocumentScript),
JavascriptUrl(PendingChildJavascriptUrlDocumentScript),
}
@@ -125,7 +92,6 @@ impl FrameDocumentScriptWorkAdmission {
impl FrameDocumentUnboundScriptWork {
pub(crate) fn child_handle(&self) -> DomHandle {
match self {
- Self::DynamicClassic(work) => work.child_handle,
Self::ExternalClassic(work) => work.child_handle,
Self::JavascriptUrl(work) => work.child_handle,
}
@@ -133,7 +99,6 @@ impl FrameDocumentUnboundScriptWork {
pub(crate) fn owner(&self) -> FrameDocumentTaskOwner {
match self {
- Self::DynamicClassic(work) => work.owner,
Self::ExternalClassic(work) => work.owner,
Self::JavascriptUrl(work) => work.owner,
}
@@ -141,7 +106,6 @@ impl FrameDocumentUnboundScriptWork {
pub(crate) fn expected_realm_id(&self) -> Option<FrameRealmId> {
match self {
- Self::DynamicClassic(work) => work.realm_id,
Self::ExternalClassic(work) => work.realm_id,
Self::JavascriptUrl(work) => work.realm_id,
}
@@ -155,10 +119,6 @@ impl FrameDocumentUnboundScriptWork {
pub(crate) fn bind_to_realm(self, realm_id: FrameRealmId) -> FrameDocumentRealmBoundScriptWork {
debug_assert!(self.can_materialize_in_realm(realm_id));
match self {
- Self::DynamicClassic(mut work) => {
- work.realm_id = Some(realm_id);
- FrameDocumentRealmBoundScriptWork::DynamicClassic(work)
- }
Self::ExternalClassic(mut work) => {
work.realm_id = Some(realm_id);
FrameDocumentRealmBoundScriptWork::ExternalClassic(work)
@@ -173,7 +133,6 @@ impl FrameDocumentUnboundScriptWork {
#[derive(Debug)]
pub(crate) enum PendingChildDocumentScriptExecutionWork {
- DynamicClassic(PendingChildDynamicDocumentScript),
ExternalClassic(PendingChildExternalClassicDocumentScript),
JavascriptUrl(PendingChildJavascriptUrlDocumentScript),
ModuleScript(Box<FrameDocumentModuleScriptReadyWork>),
@@ -196,7 +155,6 @@ impl FrameDocumentScriptReadyTaskWork {
match self {
Self::Scheduler(work) => work.dispatch_route(),
Self::DocumentScriptExecution(work) => match work.as_ref() {
- FrameDocumentRealmBoundScriptWork::DynamicClassic(work) => work.dispatch_route(),
FrameDocumentRealmBoundScriptWork::ExternalClassic(work) => work.dispatch_route(),
FrameDocumentRealmBoundScriptWork::JavascriptUrl(work) => {
FrameDocumentReadyActionRoute::from_frame_document_parts(
@@ -218,20 +176,6 @@ impl From<FrameDocumentRealmBoundScriptWork> for FrameDocumentScriptReadyTaskWor
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct FrameDocumentDynamicClassicScriptExecutionTarget {
- child_handle: DomHandle,
- task_owner: FrameDocumentTaskOwner,
- realm_id: FrameRealmId,
- script_handle: DomHandle,
-}
-
-#[derive(Debug, Clone)]
-pub(crate) struct FrameDocumentDynamicClassicScriptExecutionAction {
- target: FrameDocumentDynamicClassicScriptExecutionTarget,
- job: FrameScriptJob,
-}
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FrameDocumentExternalClassicScriptExecutionTarget {
child_handle: DomHandle,
@@ -272,7 +216,6 @@ pub(crate) enum FrameDocumentExternalClassicScriptExecution {
#[derive(Debug)]
pub(crate) enum FrameDocumentScriptExecutionWork {
- DynamicClassic(Box<FrameDocumentDynamicClassicScriptExecutionAction>),
ExternalClassic(FrameDocumentExternalClassicScriptExecutionAction),
JavascriptUrl(Box<FrameDocumentJavascriptUrlScriptExecutionAction>),
ModuleScript(Box<FrameDocumentModuleScriptReadyWork>),
@@ -280,7 +223,6 @@ pub(crate) enum FrameDocumentScriptExecutionWork {
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FrameDocumentScriptExecutionResult {
- DynamicClassic(FrameDocumentDynamicClassicExecutionFollowup),
ExternalClassic(FrameDocumentExternalClassicExecutionResult),
JavascriptUrl(FrameDocumentJavascriptUrlExecutionResult),
ModuleScript(
@@ -292,7 +234,6 @@ pub(crate) enum FrameDocumentScriptExecutionResult {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FrameDocumentScriptPrepareFollowup {
- DynamicClassic(FrameDocumentDynamicClassicPrepareFollowup),
ExternalClassic(FrameDocumentExternalClassicPrepareFollowup),
JavascriptUrl(FrameDocumentJavascriptUrlPrepareFollowup),
ModuleScript(crate::document_script_scheduler::DocumentScriptExecutionOutcome),
@@ -300,7 +241,6 @@ pub(crate) enum FrameDocumentScriptPrepareFollowup {
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FrameDocumentScriptExecutionFollowup {
- DynamicClassic(FrameDocumentDynamicClassicExecutionFollowup),
ExternalClassic(FrameDocumentExternalClassicPostExecutionAction),
JavascriptUrl(FrameDocumentJavascriptUrlPostExecutionAction),
ModuleScript(
@@ -310,29 +250,6 @@ pub(crate) enum FrameDocumentScriptExecutionFollowup {
),
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum FrameDocumentDynamicClassicPrepareSkipReason {
- RealmMaterializationFailed,
- MissingCurrentRealm,
- StaleRealm {
- expected: FrameRealmId,
- current: FrameRealmId,
- },
- ExecutionActionUnavailable,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct FrameDocumentDynamicClassicPrepareFollowup {
- prepared_execution_action: bool,
- skip_reason: Option<FrameDocumentDynamicClassicPrepareSkipReason>,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct FrameDocumentDynamicClassicExecutionFollowup {
- attempted_script_job: bool,
- failed_script_job: bool,
-}
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FrameDocumentExternalClassicPrepareSkipReason {
RealmMaterializationFailed,
@@ -437,57 +354,6 @@ pub(crate) struct FrameDocumentJavascriptUrlPostExecutionApplication {
pub(crate) owner_transition: Option<FrameDocumentOwnerTransition>,
}
-impl FrameDocumentDynamicClassicScriptExecutionTarget {
- pub(crate) fn new(
- child_handle: DomHandle,
- task_owner: FrameDocumentTaskOwner,
- realm_id: FrameRealmId,
- script_handle: DomHandle,
- ) -> Self {
- Self {
- child_handle,
- task_owner,
- realm_id,
- script_handle,
- }
- }
-
- pub(crate) fn child_handle(&self) -> DomHandle {
- self.child_handle
- }
-
- pub(crate) fn owner(&self) -> FrameDocumentOwner {
- self.task_owner.document_owner()
- }
-
- #[cfg(test)]
- pub(crate) fn task_owner(&self) -> FrameDocumentTaskOwner {
- self.task_owner
- }
-
- pub(crate) fn realm_id(&self) -> FrameRealmId {
- self.realm_id
- }
-
- pub(crate) fn script_handle(&self) -> DomHandle {
- self.script_handle
- }
-}
-
-impl PendingChildDynamicDocumentScript {
- pub(crate) fn execution_target(
- &self,
- realm_id: FrameRealmId,
- ) -> FrameDocumentDynamicClassicScriptExecutionTarget {
- FrameDocumentDynamicClassicScriptExecutionTarget::new(
- self.child_handle,
- self.owner,
- realm_id,
- self.script_handle,
- )
- }
-}
-
impl PendingChildExternalClassicDocumentScript {
pub(crate) fn execution_target(
&self,
@@ -517,23 +383,6 @@ impl PendingChildJavascriptUrlDocumentScript {
}
}
-impl FrameDocumentDynamicClassicScriptExecutionAction {
- pub(crate) fn new(
- target: FrameDocumentDynamicClassicScriptExecutionTarget,
- job: FrameScriptJob,
- ) -> Self {
- Self { target, job }
- }
-
- pub(crate) fn target(&self) -> FrameDocumentDynamicClassicScriptExecutionTarget {
- self.target
- }
-
- pub(crate) fn into_job(self) -> FrameScriptJob {
- self.job
- }
-}
-
impl FrameDocumentExternalClassicScriptExecutionTarget {
pub(crate) fn new(
child_handle: DomHandle,
@@ -676,12 +525,6 @@ impl FrameDocumentExternalClassicScriptExecution {
}
impl FrameDocumentScriptExecutionWork {
- pub(crate) fn dynamic_classic(
- action: FrameDocumentDynamicClassicScriptExecutionAction,
- ) -> Self {
- Self::DynamicClassic(Box::new(action))
- }
-
pub(crate) fn external_classic(
action: FrameDocumentExternalClassicScriptExecutionAction,
) -> Self {
@@ -700,7 +543,6 @@ impl FrameDocumentScriptExecutionWork {
impl FrameDocumentScriptPrepareFollowup {
pub(crate) fn made_progress(&self) -> bool {
match self {
- Self::DynamicClassic(followup) => followup.made_progress(),
Self::ExternalClassic(followup) => followup.made_progress(),
Self::JavascriptUrl(followup) => followup.made_progress(),
Self::ModuleScript(outcome) => outcome.made_progress(),
@@ -708,50 +550,6 @@ impl FrameDocumentScriptPrepareFollowup {
}
}
-impl FrameDocumentDynamicClassicPrepareFollowup {
- pub(crate) fn prepared_execution_action() -> Self {
- Self {
- prepared_execution_action: true,
- skip_reason: None,
- }
- }
-
- pub(crate) fn skipped(reason: FrameDocumentDynamicClassicPrepareSkipReason) -> Self {
- Self {
- prepared_execution_action: false,
- skip_reason: Some(reason),
- }
- }
-
- pub(crate) fn made_progress(&self) -> bool {
- self.prepared_execution_action || self.skip_reason.is_some()
- }
-}
-
-impl FrameDocumentDynamicClassicExecutionFollowup {
- pub(crate) fn completed_script_job() -> Self {
- Self {
- attempted_script_job: true,
- failed_script_job: false,
- }
- }
-
- pub(crate) fn failed_script_job() -> Self {
- Self {
- attempted_script_job: true,
- failed_script_job: true,
- }
- }
-
- pub(crate) fn made_progress(&self) -> bool {
- self.attempted_script_job
- }
-
- pub(crate) fn attempted_script_job(&self) -> bool {
- self.attempted_script_job
- }
-}
-
impl FrameDocumentExternalClassicPrepareFollowup {
pub(crate) fn prepared_execution_action() -> Self {
Self {
diff --git a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/mod.rs b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/mod.rs
index fffae34df..3cfe5b8df 100644
--- a/moli-renderer-v8/src/frame_owner_model/frame_task_sources/mod.rs
+++ b/moli-renderer-v8/src/frame_owner_model/frame_task_sources/mod.rs
@@ -1,7 +1,5 @@
mod document_script_ready;
pub(crate) use document_script_ready::{
- FrameDocumentDynamicClassicExecutionFollowup, FrameDocumentDynamicClassicPrepareFollowup,
- FrameDocumentDynamicClassicPrepareSkipReason, FrameDocumentDynamicClassicScriptExecutionAction,
FrameDocumentExternalClassicExecutionFollowup, FrameDocumentExternalClassicExecutionResult,
FrameDocumentExternalClassicPostExecutionAction, FrameDocumentExternalClassicPrepareFollowup,
FrameDocumentExternalClassicPrepareSkipReason, FrameDocumentExternalClassicScriptExecution,
@@ -15,6 +13,5 @@ pub(crate) use document_script_ready::{
FrameDocumentScriptExecutionWork, FrameDocumentScriptPrepareFollowup,
FrameDocumentScriptReadyTaskWork, FrameDocumentScriptWorkAdmission,
FrameDocumentUnboundScriptWork, PendingChildDocumentScriptExecutionWork,
- PendingChildDynamicDocumentScript, PendingChildExternalClassicDocumentScript,
- PendingChildJavascriptUrlDocumentScript,
+ PendingChildExternalClassicDocumentScript, PendingChildJavascriptUrlDocumentScript,
};
diff --git a/moli-renderer-v8/src/mutation_coordinator.rs b/moli-renderer-v8/src/mutation_coordinator.rs
index 2e18e3e11..c62147d08 100644
--- a/moli-renderer-v8/src/mutation_coordinator.rs
+++ b/moli-renderer-v8/src/mutation_coordinator.rs
@@ -6,12 +6,8 @@ mod notifications;
pub(crate) use notifications::notify_dom_mutation;
use super::{
- host::{
- HostDocumentState, HostEventTargetRegistry, HostScriptScheduler,
- RuntimeScriptStartDecision, ScriptElementLoader, ScriptElementLoaderOptions,
- },
- native_bridge::{self, JsContextHost},
- util::v8str,
+ host::{HostEventTargetRegistry, HostScriptScheduler},
+ native_bridge::JsContextHost,
};
#[derive(Debug, Default)]
@@ -25,12 +21,11 @@ pub(super) struct MutationCoordinatorApplyResult {
#[derive(Debug)]
pub(super) struct RuntimeScriptStartCandidate {
node: NativeNodeId,
- host_script_handle: String,
}
impl RuntimeScriptStartCandidate {
- pub(super) fn into_parts(self) -> (NativeNodeId, String) {
- (self.node, self.host_script_handle)
+ pub(super) fn into_node(self) -> NativeNodeId {
+ self.node
}
}
@@ -164,7 +159,6 @@ impl MutationCoordinator {
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut JsContextHost,
dom_host: &mut DomHost,
- document: &HostDocumentState,
_scripts: &mut HostScriptScheduler,
_events: &mut HostEventTargetRegistry,
effects: DomMutationEffects,
@@ -257,13 +251,9 @@ impl MutationCoordinator {
if request.clears_force_async {
let _ = dom_host.set_script_force_async(request.handle, false);
}
- if let Some(candidate) = self.collect_connected_script_start_candidate(
- scope,
- host_ptr,
- dom_host,
- request.handle,
- document,
- ) {
+ if let Some(candidate) =
+ self.collect_connected_script_start_candidate(dom_host, request.handle)
+ {
runtime_script_start_candidates.push(candidate);
}
}
@@ -359,130 +349,13 @@ impl MutationCoordinator {
fn collect_connected_script_start_candidate(
&mut self,
- scope: &mut v8::PinScope<'_, '_>,
- host_ptr: *mut JsContextHost,
- dom_host: &mut DomHost,
+ dom_host: &DomHost,
node: NativeNodeId,
- document: &HostDocumentState,
) -> Option<RuntimeScriptStartCandidate> {
- if !dom_host
+ dom_host
.node(node)
.is_some_and(crate::dom::native::Node::is_script_element)
- {
- return None;
- }
- let owner_document_handle = dom_host.owner_document_handle(node)?;
- if owner_document_handle != dom_host.document_handle() {
- self.start_connected_child_document_script(
- scope,
- host_ptr,
- dom_host,
- node,
- owner_document_handle,
- document,
- );
- return None;
- }
- let wrapper = unsafe { &mut *host_ptr }
- .native_bridge_mut()
- .wrap_handle(scope, host_ptr, node)?;
-
- let host_script_handle =
- native_bridge::object_string_property(scope, wrapper, "__moliHandle").unwrap_or_else(
- || {
- let handle = format!("dynamic-script-native-{}", node.index());
- if let Some(value) = v8::String::new(scope, &handle) {
- let key = v8str(scope, "__moliHandle");
- let _ = wrapper.define_own_property(
- scope,
- key.into(),
- value.into(),
- v8::PropertyAttribute::DONT_ENUM,
- );
- }
- handle
- },
- );
- Some(RuntimeScriptStartCandidate {
- node,
- host_script_handle,
- })
- }
-
- fn start_connected_child_document_script(
- &mut self,
- scope: &mut v8::PinScope<'_, '_>,
- host_ptr: *mut JsContextHost,
- dom_host: &mut DomHost,
- node: NativeNodeId,
- owner_document_handle: NativeNodeId,
- document: &HostDocumentState,
- ) {
- let (preparation, decision) = ScriptElementLoader::prepare(
- dom_host,
- document,
- node,
- ScriptElementLoaderOptions::with_scripting_enabled(
- unsafe { &*host_ptr }.document_scripting_enabled(owner_document_handle),
- ),
- )
- .into_parts();
- match decision {
- RuntimeScriptStartDecision::Skip { commit_start, .. } => {
- if commit_start {
- let _ = dom_host.set_script_already_started(node, true);
- }
- }
- RuntimeScriptStartDecision::ExecuteInlineClassic { source } => {
- if unsafe { &mut *host_ptr }
- .queue_child_dynamic_inline_classic_script_for_current_document(
- scope,
- owner_document_handle,
- node,
- source,
- )
- {
- let _ = dom_host.set_script_already_started(node, true);
- }
- }
- RuntimeScriptStartDecision::Queue {
- source,
- kind,
- mode,
- source_kind,
- } => {
- match unsafe { &mut *host_ptr }
- .queue_child_dynamic_external_classic_script_for_current_document(
- scope,
- owner_document_handle,
- node,
- &preparation,
- &source,
- kind,
- mode,
- source_kind,
- ) {
- Ok(true) => {}
- Ok(false) => tracing::debug!(
- node = ?node,
- owner_document_handle = ?owner_document_handle,
- kind = ?kind,
- mode = ?mode,
- source_kind = ?source_kind,
- "child runtime script has no supported current-document queue"
- ),
- Err(error) => tracing::warn!(
- node = ?node,
- owner_document_handle = ?owner_document_handle,
- %error,
- "failed to prepare child runtime external classic script"
- ),
- }
- }
- RuntimeScriptStartDecision::RegisterImportMap { .. }
- | RuntimeScriptStartDecision::RejectExternalImportMap
- | RuntimeScriptStartDecision::QueueFailed { .. } => {}
- }
+ .then_some(RuntimeScriptStartCandidate { node })
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
index 42ad8071a..9244a3da0 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
@@ -1500,7 +1500,7 @@ impl JsContextHost {
self.apply_child_document_write_classic_completion(scope, completion)
}
- fn execute_child_frame_script_job_on_current_stack(
+ pub(in crate::native_bridge::context_host) fn execute_child_frame_script_job_on_current_stack(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
script_context: v8::Local<'_, v8::Context>,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs b/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs
index 242c0dbbc..321f298b2 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_dynamic_scripts.rs
@@ -1,11 +1,6 @@
use super::*;
use crate::{
- dom::native::Node,
- frame_owner_model::{
- FrameDocumentDynamicClassicScriptExecutionAction, FrameDocumentUnboundScriptWork,
- FrameRealmId, PendingChildDynamicDocumentScript,
- },
host::{RuntimeScriptPreparationContext, build_runtime_prepared_script},
types::{ScriptKind, ScriptMode, ScriptSourceKind},
};
@@ -53,100 +48,62 @@ impl JsContextHost {
)
}
- pub(crate) fn queue_child_dynamic_inline_classic_script_for_current_document(
+ pub(crate) fn execute_child_dynamic_inline_classic_script_on_current_stack(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
owner_document_handle: DomHandle,
script_handle: DomHandle,
source: String,
- ) -> bool {
+ ) -> anyhow::Result<()> {
let Some(child_handle) =
self.child_browsing_context_handle_by_document_handle(scope, owner_document_handle)
else {
- return false;
+ return Ok(());
};
if !self.child_browsing_context_is_live(child_handle)
|| self.child_browsing_context_document_handle(child_handle)
!= Some(owner_document_handle)
|| self.dom_host().owner_document_handle(script_handle) != Some(owner_document_handle)
{
- return false;
+ return Ok(());
}
let Some(owner) = self
.frame_owner_store
.current_child_document_task_owner(child_handle)
else {
- return false;
+ return Ok(());
};
- let realm_id = self
+ let Some(mut job) = self
.frame_owner_store
- .current_reserved_realm_id_for_document_task_owner(owner);
- let script_nonce = self
+ .child_dynamic_classic_script_job_for_owner(
+ child_handle,
+ owner.local_window_id,
+ owner.document_id,
+ Some(script_handle),
+ source,
+ )
+ else {
+ return Ok(());
+ };
+ job.script_nonce = self
.dom_host()
.node(script_handle)
- .and_then(Node::as_element)
+ .and_then(crate::dom::native::Node::as_element)
.and_then(|element| element.cryptographic_nonce())
.map(str::to_owned)
.or_else(|| self.dom_host().get_attribute(script_handle, "nonce"));
- let script_integrity = self.dom_host().get_attribute(script_handle, "integrity");
- self.queue_child_document_script_work_with_realm_prerequisite(
- FrameDocumentUnboundScriptWork::DynamicClassic(PendingChildDynamicDocumentScript {
- child_handle,
- owner,
- realm_id,
- script_handle,
- source,
- script_nonce,
- script_integrity,
- }),
- )
- .is_some()
- }
-
- pub(crate) fn child_dynamic_classic_script_execution_action_for_owner(
- &self,
- work: &PendingChildDynamicDocumentScript,
- realm_id: FrameRealmId,
- ) -> Option<FrameDocumentDynamicClassicScriptExecutionAction> {
- let current_realm_id = self
- .frame_owner_store
- .current_materialized_realm_id_for_document_task_owner(work.owner);
- if current_realm_id != Some(realm_id) {
- tracing::debug!(
- child_handle = ?work.child_handle,
- owner = ?work.owner,
- expected_realm_id = ?realm_id,
- current_realm_id = ?current_realm_id,
- script_handle = ?work.script_handle,
- "dropping child dynamic classic script whose materialized FrameRealm is no longer current"
- );
- return None;
- };
- if work.realm_id.is_some_and(|expected| expected != realm_id) {
- tracing::debug!(
- child_handle = ?work.child_handle,
- owner = ?work.owner,
- expected_realm_id = ?work.realm_id,
- current_realm_id = ?realm_id,
- script_handle = ?work.script_handle,
- "dropping child dynamic classic script with stale FrameRealm"
- );
- return None;
+ job.script_integrity = self.dom_host().get_attribute(script_handle, "integrity");
+ // Commit before entering V8: the script can remove and reinsert itself,
+ // mutate another pending script, or replace its preparation Document.
+ let _ = self
+ .dom_host_mut()
+ .set_script_already_started(script_handle, true);
+ let context = self.ensure_prebootstrapped_child_default_context(scope, child_handle)?;
+ if self.current_child_document_task_owner(child_handle) != Some(owner)
+ || self.dom_host().owner_document_handle(script_handle) != Some(owner_document_handle)
+ {
+ return Ok(());
}
- let mut job = self
- .frame_owner_store
- .child_dynamic_classic_script_job_for_owner(
- work.child_handle,
- work.owner.local_window_id,
- work.owner.document_id,
- Some(work.script_handle),
- work.source.clone(),
- )?;
- job.script_nonce = work.script_nonce.clone();
- job.script_integrity = work.script_integrity.clone();
- Some(FrameDocumentDynamicClassicScriptExecutionAction::new(
- work.execution_target(realm_id),
- job,
- ))
+ self.execute_child_frame_script_job_on_current_stack(scope, context, job)
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
index 0dc3c8844..019eb73d3 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
@@ -99,12 +99,12 @@ impl ChildBrowsingContextEntry {
.is_executing_parser_script()
}
- fn push_child_current_script(&mut self, script_handle: DomHandle) {
+ fn push_child_current_script(&mut self, script_handle: Option<DomHandle>) {
self.classic_script_document_state
.push_current_script(script_handle);
}
- fn pop_child_current_script(&mut self, script_handle: DomHandle) {
+ fn pop_child_current_script(&mut self, script_handle: Option<DomHandle>) {
self.classic_script_document_state
.pop_current_script(script_handle);
}
@@ -182,15 +182,20 @@ impl JsContextHost {
pub(crate) fn push_frame_script_job_current_script(
&mut self,
job: &FrameScriptJob,
- ) -> Option<(DomHandle, DomHandle)> {
+ ) -> Option<(DomHandle, Option<DomHandle>)> {
let script_handle = job.current_script?;
let child_handle = self.frame_owner_child_handle_for_script_job(job)?;
+ let script_handle = self
+ .dom_host()
+ .containing_shadow_root(script_handle)
+ .is_none()
+ .then_some(script_handle);
let entry = self.child_browsing_contexts.get_mut(&child_handle)?;
entry.push_child_current_script(script_handle);
Some((child_handle, script_handle))
}
- pub(crate) fn pop_child_current_script(&mut self, token: (DomHandle, DomHandle)) {
+ pub(crate) fn pop_child_current_script(&mut self, token: (DomHandle, Option<DomHandle>)) {
let (child_handle, script_handle) = token;
if let Some(entry) = self.child_browsing_contexts.get_mut(&child_handle) {
entry.pop_child_current_script(script_handle);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts/document_state.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts/document_state.rs
index 795a77411..56e7f8e51 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts/document_state.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts/document_state.rs
@@ -2,7 +2,9 @@ use crate::document_runtime::DomHandle;
#[derive(Debug, Clone, Default)]
pub(in crate::native_bridge::context_host) struct ChildClassicScriptDocumentState {
- current_script_stack: Vec<DomHandle>,
+ // Capture currentScript at execution entry. Adoption or a move into a
+ // shadow tree during execution must not change the active value.
+ current_script_stack: Vec<Option<DomHandle>>,
// Counts nested synchronous parser-blocking execution scopes for this
// exact Document, including load/error completion dispatched before parser
// resume. Parser-inserted ownership, deferred-script execution, DOM
@@ -40,11 +42,11 @@ impl ChildClassicScriptDocumentState {
self.parser_script_nesting_level > 0
}
- pub(super) fn push_current_script(&mut self, script_handle: DomHandle) {
+ pub(super) fn push_current_script(&mut self, script_handle: Option<DomHandle>) {
self.current_script_stack.push(script_handle);
}
- pub(super) fn pop_current_script(&mut self, script_handle: DomHandle) {
+ pub(super) fn pop_current_script(&mut self, script_handle: Option<DomHandle>) {
if self.current_script_stack.last().copied() == Some(script_handle) {
self.current_script_stack.pop();
return;
@@ -57,6 +59,6 @@ impl ChildClassicScriptDocumentState {
}
pub(super) fn current_script(&self) -> Option<DomHandle> {
- self.current_script_stack.last().copied()
+ self.current_script_stack.last().copied().flatten()
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/document_script_ready_inputs.rs b/moli-renderer-v8/src/native_bridge/context_host/document_script_ready_inputs.rs
index 043214e09..eecdd1c3b 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/document_script_ready_inputs.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/document_script_ready_inputs.rs
@@ -451,7 +451,6 @@ impl JsContextHost {
return;
};
match *work {
- FrameDocumentRealmBoundScriptWork::DynamicClassic(_) => {}
FrameDocumentRealmBoundScriptWork::ExternalClassic(work) => {
let _ = self.settle_child_async_classic_script_load_delay(
work.child_handle,
diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs
index 5865c1f0e..db87be835 100644
--- a/moli-renderer-v8/src/native_bridge/document.rs
+++ b/moli-renderer-v8/src/native_bridge/document.rs
@@ -1020,16 +1020,20 @@ fn current_script_handle_for_document(
runtime: &JsContextHost,
document_handle: DomHandle,
) -> Option<DomHandle> {
+ if runtime
+ .child_browsing_context_host_for_document_handle(document_handle)
+ .is_some()
+ {
+ // This stack belongs to the execution Document. A script can change
+ // its node document or tree while its currentScript value stays set.
+ return runtime.child_current_script_handle_for_document(document_handle);
+ }
if let Some(script) = runtime.current_inline_script_handle()
&& current_script_belongs_to_document(runtime, script, document_handle)
{
return current_script_is_visible_for_document(runtime, script, document_handle)
.then_some(script);
}
- if let Some(script) = runtime.child_current_script_handle_for_document(document_handle) {
- return current_script_is_visible_for_document(runtime, script, document_handle)
- .then_some(script);
- }
runtime
.current_script_handle()
.filter(|script| current_script_is_visible_for_document(runtime, *script, document_handle))
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/child_document_script_ready.rs b/moli-renderer-v8/src/runtime/page_vm/tests/child_document_script_ready.rs
index ff6b7708c..7f81e5f2f 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/child_document_script_ready.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/child_document_script_ready.rs
@@ -10,10 +10,7 @@ async fn install_child_classic_script_ready_fixture(
globalThis.__lmChildClassicScriptTaskBoundary = [];
const frame = document.createElement("iframe");
frame.id = {frame_id:?};
- document.body.appendChild(frame);
- void frame.contentWindow.Function;
- const script = frame.contentDocument.createElement("script");
- script.textContent = `
+ frame.srcdoc = `<script>
parent.__lmChildClassicScriptTaskBoundary.push("script");
Promise.resolve().then(() => {{
parent.__lmChildClassicScriptTaskBoundary.push("microtask");
@@ -22,12 +19,18 @@ async fn install_child_classic_script_ready_fixture(
sibling.srcdoc = "<!doctype html><body>reaction child</body>";
parent.document.body.appendChild(sibling);
}});
- `;
- frame.contentDocument.body.appendChild(script);
+ <\/script>`;
+ document.body.appendChild(frame);
return "queued";
}})()
"#,
))?;
+ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(
+ page_vm,
+ ChildFrameSemanticTurnKind::NavigationCommit,
+ "child parser classic script fixture navigation",
+ )
+ .await;
run_expected_child_realm_materialization_for_wait(
page_vm,
"child classic script task fixture realm",
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization.rs b/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization.rs
index b09e3f6b4..d7383d0c0 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/child_realm_materialization.rs
@@ -147,7 +147,7 @@ async fn runtime_realm_inventory_observes_without_materializing_pending_child_re
}
#[tokio::test(flavor = "current_thread")]
-async fn prebootstrapped_child_script_becomes_runnable_only_after_typed_realm_materialization() {
+async fn prebootstrapped_child_inline_script_runs_before_deferred_realm_registration() {
run_page_vm_async_test(async move {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
let document_url = Url::parse("https://example.com/prebootstrapped-child-script").unwrap();
@@ -186,8 +186,8 @@ async fn prebootstrapped_child_script_becomes_runnable_only_after_typed_realm_ma
);
assert_eq!(
page_vm.vm_mut().eval("__prebootstrappedChildScript")?,
- "pending",
- "probing a non-head family executor must not consume pre-realm work"
+ "ran:true:script",
+ "inline script execution must finish before deferred realm registration"
);
let materialization = page_vm
@@ -198,18 +198,18 @@ async fn prebootstrapped_child_script_becomes_runnable_only_after_typed_realm_ma
PageChildRealmMaterializationTargetEffect::MaterializedCurrentOwnerWithoutDocumentStartScript
);
assert!(
- page_vm
+ !page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?,
- "the realm-bound script must retain one typed selected Page task"
+ "synchronous inline execution must not leave a second script task"
);
assert_eq!(
page_vm.vm_mut().eval("__prebootstrappedChildScript")?,
"ran:true:script",
- "the promoted work must execute in the registered child realm"
+ "realm registration must preserve the synchronous script result"
);
assert!(
page_vm
@@ -222,7 +222,7 @@ async fn prebootstrapped_child_script_becomes_runnable_only_after_typed_realm_ma
Ok::<_, anyhow::Error>(())
})
.await
- .expect("prebootstrapped child script should wait for typed realm materialization");
+ .expect("prebootstrapped child inline execution should precede realm registration");
}
#[tokio::test(flavor = "current_thread")]
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index 98500ffcc..0298a7d02 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -10755,12 +10755,11 @@ async fn page_vm_realm_materialization_created_ready_work_enters_document_script
}
#[tokio::test]
-async fn child_dynamic_inline_script_runs_on_document_script_ready_source() {
- let (events_before_script_ready, script_ready_source, events_after_script_ready, next_source) =
- run_page_vm_async_test(async move {
- let mut page_vm = test_page_vm();
- page_vm.vm_mut().eval(
- r#"
+async fn child_dynamic_inline_script_runs_synchronously_without_document_script_ready_work() {
+ let (immediate_events, settled_events, next_source) = run_page_vm_async_test(async move {
+ let mut page_vm = test_page_vm();
+ page_vm.vm_mut().eval(
+ r#"
(() => {
globalThis.__childDynamicReadySourceEvents = [];
const root = document.documentElement || document.appendChild(document.createElement("html"));
@@ -10775,54 +10774,37 @@ async fn child_dynamic_inline_script_runs_on_document_script_ready_source() {
);
`;
frame.contentDocument.body.appendChild(script);
+ __childDynamicReadySourceEvents.push("returned");
})()
"#,
- )?;
-
- let events_before_script_ready = page_vm
- .vm_mut()
- .eval("__childDynamicReadySourceEvents.join('|')")?;
- run_expected_child_realm_materialization_for_wait(
- &mut page_vm,
- "dynamic child inline-script realm",
- )
+ )?;
+ let immediate_events = page_vm
+ .vm_mut()
+ .eval("__childDynamicReadySourceEvents.join('|')")?;
+ run_expected_child_realm_materialization_for_wait(
+ &mut page_vm,
+ "dynamic child inline-script realm",
+ )
+ .await;
+ let next_source = page_vm
+ .run_next_child_frame_task_source_for_semantic_test()
.await;
- let script_ready_source = page_vm
- .run_next_child_frame_task_source_for_semantic_test()
- .await;
- let events_after_script_ready = page_vm
- .vm_mut()
- .eval("__childDynamicReadySourceEvents.join('|')")?;
- let next_source = page_vm
- .run_next_child_frame_task_source_for_semantic_test()
- .await;
-
- Ok::<_, anyhow::Error>((
- events_before_script_ready,
- script_ready_source,
- events_after_script_ready,
- next_source,
- ))
- })
- .await
- .expect("child dynamic inline script source test should run");
+ let settled_events = page_vm
+ .vm_mut()
+ .eval("__childDynamicReadySourceEvents.join('|')")?;
+ Ok::<_, anyhow::Error>((immediate_events, settled_events, next_source))
+ })
+ .await
+ .expect("child dynamic inline script source test should run");
assert_eq!(
- events_before_script_ready, "frame-load",
- "the initial about:blank load must dispatch synchronously when the frame is connected"
- );
- assert_eq!(
- script_ready_source,
- Some(ChildFrameSemanticTurnKind::DocumentScriptReady),
- "dynamic child inline script should run from the document-script ready source"
- );
- assert_eq!(
- events_after_script_ready, "frame-load|dynamic:script",
- "DocumentScriptReady should execute the dynamic child script after the synchronous initial load"
+ immediate_events, "frame-load|dynamic:script|returned",
+ "both initial about:blank load and dynamic inline execution are synchronous"
);
+ assert_eq!(settled_events, immediate_events);
assert_eq!(
next_source, None,
- "synchronous initial about:blank delivery must leave no HostLoad source"
+ "inline execution must leave no DocumentScriptReady or HostLoad task"
);
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/webcrypto.rs b/moli-renderer-v8/src/runtime/page_vm/tests/webcrypto.rs
index 893981127..16bb6434e 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/webcrypto.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/webcrypto.rs
@@ -7,7 +7,7 @@ use crate::page_task_queue::{
};
#[tokio::test(flavor = "current_thread")]
-async fn selected_child_script_registers_webcrypto_to_child_window_and_retires_on_detach() {
+async fn child_inline_script_registers_webcrypto_to_child_window_and_retires_on_detach() {
run_page_vm_async_test(async move {
let mut page_vm = test_page_vm();
let loader = page_vm.request_client.clone();
@@ -51,13 +51,13 @@ async fn selected_child_script_registers_webcrypto_to_child_window_and_retires_o
)
.await;
assert!(
- page_vm
+ !page_vm
.run_exact_selected_page_task_for_test(
PageSelectedTaskTestSelector::ChildDocumentScriptReady,
&loader,
)
.await?,
- "child WebCrypto registration must execute from the complete selected script task"
+ "child WebCrypto registration must already have run synchronously"
);
let child_handle = page_vm
@@ -84,7 +84,7 @@ async fn selected_child_script_registers_webcrypto_to_child_window_and_retires_o
Ok::<_, anyhow::Error>(())
})
.await
- .expect("child WebCrypto owner should be tested through a complete selected script task");
+ .expect("child WebCrypto ownership should survive deferred realm registration");
}
#[test]
diff --git a/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs b/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
index f93a0f54c..f0ed2a713 100644
--- a/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
+++ b/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
@@ -14,7 +14,7 @@ use crate::{
FrameDocumentClassicScriptReadyTarget, FrameDocumentClassicScriptSourceFailureTarget,
FrameDocumentClassicSourceFailureReportApplication, FrameDocumentJavascriptUrlCompletion,
FrameDocumentJavascriptUrlPostExecutionApplication, FrameDocumentScriptElementEventKind,
- FrameDocumentTaskOwner, FrameRealmId, FrameScriptJob, PendingChildDynamicDocumentScript,
+ FrameDocumentTaskOwner, FrameRealmId, FrameScriptJob,
PendingChildExternalClassicDocumentScript, PendingChildJavascriptUrlDocumentScript,
},
native_bridge::JsContextHost,
@@ -259,17 +259,6 @@ impl<'vm> ChildDocumentScriptOwnerHooks<'vm> {
.notify_parser_classic_next_owner_action(work)
}
- pub(in crate::script_vm) fn child_dynamic_classic_script_execution_action_for_owner(
- &mut self,
- work: &PendingChildDynamicDocumentScript,
- realm_id: FrameRealmId,
- ) -> Option<crate::frame_owner_model::FrameDocumentDynamicClassicScriptExecutionAction> {
- self.vm
- ._context_host
- .borrow()
- .child_dynamic_classic_script_execution_action_for_owner(work, realm_id)
- }
-
pub(in crate::script_vm) fn child_external_classic_script_execution_action_for_owner(
&mut self,
work: &PendingChildExternalClassicDocumentScript,
diff --git a/moli-renderer-v8/src/script_vm/child_dynamic_document_script.rs b/moli-renderer-v8/src/script_vm/child_dynamic_document_script.rs
index b8af26218..d3805a24e 100644
--- a/moli-renderer-v8/src/script_vm/child_dynamic_document_script.rs
+++ b/moli-renderer-v8/src/script_vm/child_dynamic_document_script.rs
@@ -5,8 +5,6 @@ use crate::{
FrameModuleScriptTaskActivity,
},
frame_owner_model::{
- FrameDocumentDynamicClassicExecutionFollowup, FrameDocumentDynamicClassicPrepareFollowup,
- FrameDocumentDynamicClassicPrepareSkipReason,
FrameDocumentExternalClassicExecutionFollowup, FrameDocumentExternalClassicExecutionResult,
FrameDocumentExternalClassicPrepareFollowup, FrameDocumentExternalClassicPrepareSkipReason,
FrameDocumentExternalClassicScriptExecution, FrameDocumentJavascriptUrlCompletion,
@@ -14,8 +12,8 @@ use crate::{
FrameDocumentJavascriptUrlPrepareFollowup, FrameDocumentJavascriptUrlPrepareSkipReason,
FrameDocumentScriptExecutionFollowup, FrameDocumentScriptExecutionResult,
FrameDocumentScriptExecutionWork, FrameDocumentScriptPrepareFollowup,
- PendingChildDocumentScriptExecutionWork, PendingChildDynamicDocumentScript,
- PendingChildExternalClassicDocumentScript, PendingChildJavascriptUrlDocumentScript,
+ PendingChildDocumentScriptExecutionWork, PendingChildExternalClassicDocumentScript,
+ PendingChildJavascriptUrlDocumentScript,
},
};
use std::{future::Future, pin::Pin};
@@ -99,76 +97,6 @@ impl ScriptVmChildDocumentScriptExecutionHooks<'_> {
)
}
- fn prepare_dynamic_classic(
- &mut self,
- work: PendingChildDynamicDocumentScript,
- ) -> FrameDocumentScriptExecutionStartReport<FrameDocumentScriptPrepareFollowup> {
- match self.hooks.select_current_realm(
- work.child_handle,
- work.realm_id,
- work.script_handle,
- "child_dynamic_classic_ready",
- ) {
- ChildDocumentScriptRealmSelection::Current(realm_id) => {
- let action = self
- .hooks
- .child_dynamic_classic_script_execution_action_for_owner(&work, realm_id);
- let Some(action) = action else {
- tracing::debug!(
- child_handle = ?work.child_handle,
- script_handle = ?work.script_handle,
- owner = ?work.owner,
- realm_id = ?realm_id,
- "child dynamic classic script task is stale"
- );
- return FrameDocumentScriptExecutionStartReport::dropped(
- FrameDocumentScriptPrepareFollowup::DynamicClassic(
- FrameDocumentDynamicClassicPrepareFollowup::skipped(
- FrameDocumentDynamicClassicPrepareSkipReason::ExecutionActionUnavailable,
- ),
- ),
- );
- };
- FrameDocumentScriptExecutionStartReport::execute(
- FrameDocumentScriptExecutionWork::dynamic_classic(action),
- FrameDocumentScriptPrepareFollowup::DynamicClassic(
- FrameDocumentDynamicClassicPrepareFollowup::prepared_execution_action(),
- ),
- )
- }
- ChildDocumentScriptRealmSelection::RealmMaterializationFailed => {
- FrameDocumentScriptExecutionStartReport::dropped(
- FrameDocumentScriptPrepareFollowup::DynamicClassic(
- FrameDocumentDynamicClassicPrepareFollowup::skipped(
- FrameDocumentDynamicClassicPrepareSkipReason::RealmMaterializationFailed,
- ),
- ),
- )
- }
- ChildDocumentScriptRealmSelection::MissingCurrentRealm => {
- FrameDocumentScriptExecutionStartReport::dropped(
- FrameDocumentScriptPrepareFollowup::DynamicClassic(
- FrameDocumentDynamicClassicPrepareFollowup::skipped(
- FrameDocumentDynamicClassicPrepareSkipReason::MissingCurrentRealm,
- ),
- ),
- )
- }
- ChildDocumentScriptRealmSelection::StaleRealm { expected, current } => {
- FrameDocumentScriptExecutionStartReport::dropped(
- FrameDocumentScriptPrepareFollowup::DynamicClassic(
- FrameDocumentDynamicClassicPrepareFollowup::skipped(
- FrameDocumentDynamicClassicPrepareSkipReason::StaleRealm {
- expected,
- current,
- },
- ),
- ),
- )
- }
- }
- }
-
fn prepare_external_classic(
&mut self,
work: PendingChildExternalClassicDocumentScript,
@@ -284,32 +212,6 @@ impl ScriptVmChildDocumentScriptExecutionHooks<'_> {
)
}
- fn execute_dynamic_classic(
- &mut self,
- action: crate::frame_owner_model::FrameDocumentDynamicClassicScriptExecutionAction,
- ) -> FrameDocumentScriptExecutionResult {
- let target = action.target();
- if let Err(error) = self
- .hooks
- .execute_frame_script_job_selected_task_body(action.into_job())
- {
- tracing::warn!(
- error = %error,
- child_handle = ?target.child_handle(),
- script_handle = ?target.script_handle(),
- owner = ?target.owner(),
- realm_id = ?target.realm_id(),
- "child dynamic classic script execution failed"
- );
- return FrameDocumentScriptExecutionResult::DynamicClassic(
- FrameDocumentDynamicClassicExecutionFollowup::failed_script_job(),
- );
- }
- FrameDocumentScriptExecutionResult::DynamicClassic(
- FrameDocumentDynamicClassicExecutionFollowup::completed_script_job(),
- )
- }
-
fn execute_external_classic(
&mut self,
action: crate::frame_owner_model::FrameDocumentExternalClassicScriptExecutionAction,
@@ -457,9 +359,6 @@ impl DocumentScriptExecutionHooks for ScriptVmChildDocumentScriptExecutionHooks<
work: PendingChildDocumentScriptExecutionWork,
) -> FrameDocumentScriptExecutionStartReport<FrameDocumentScriptPrepareFollowup> {
match work {
- PendingChildDocumentScriptExecutionWork::DynamicClassic(work) => {
- self.prepare_dynamic_classic(work)
- }
PendingChildDocumentScriptExecutionWork::ExternalClassic(work) => {
self.prepare_external_classic(work)
}
@@ -475,9 +374,6 @@ impl DocumentScriptExecutionHooks for ScriptVmChildDocumentScriptExecutionHooks<
fn execute_work(&mut self, work: FrameDocumentScriptExecutionWork) -> Self::ExecuteFuture<'_> {
Box::pin(async move {
Ok(match work {
- FrameDocumentScriptExecutionWork::DynamicClassic(action) => {
- self.execute_dynamic_classic(*action)
- }
FrameDocumentScriptExecutionWork::ExternalClassic(action) => {
self.execute_external_classic(action)
}
@@ -498,9 +394,6 @@ impl DocumentScriptExecutionHooks for ScriptVmChildDocumentScriptExecutionHooks<
execution_result: FrameDocumentScriptExecutionResult,
) -> anyhow::Result<FrameDocumentScriptExecutionFollowup> {
Ok(match execution_result {
- FrameDocumentScriptExecutionResult::DynamicClassic(followup) => {
- FrameDocumentScriptExecutionFollowup::DynamicClassic(followup)
- }
FrameDocumentScriptExecutionResult::ExternalClassic(result) => {
FrameDocumentScriptExecutionFollowup::ExternalClassic(
result.into_post_execution_action(),
@@ -522,14 +415,6 @@ impl DocumentScriptExecutionHooks for ScriptVmChildDocumentScriptExecutionHooks<
followup: FrameDocumentScriptExecutionFollowup,
) -> anyhow::Result<ChildDocumentScriptReadyRunOutcome> {
let (made_progress, activity) = match followup {
- FrameDocumentScriptExecutionFollowup::DynamicClassic(followup) => (
- followup.made_progress(),
- if followup.attempted_script_job() {
- ChildDocumentScriptActivity::ScriptOrEvent
- } else {
- ChildDocumentScriptActivity::NoScriptOrEvent
- },
- ),
FrameDocumentScriptExecutionFollowup::ExternalClassic(action) => {
let followup = self.apply_external_classic_post_execution(action);
(
diff --git a/moli-renderer-v8/src/script_vm/native_module/child_ready_document_script.rs b/moli-renderer-v8/src/script_vm/native_module/child_ready_document_script.rs
index b3379777b..59757f2f2 100644
--- a/moli-renderer-v8/src/script_vm/native_module/child_ready_document_script.rs
+++ b/moli-renderer-v8/src/script_vm/native_module/child_ready_document_script.rs
@@ -52,9 +52,6 @@ impl<'vm> ChildReadyDocumentScriptOwner<'vm> {
}
FrameDocumentScriptReadyTaskWork::DocumentScriptExecution(work) => {
let work = match *work {
- FrameDocumentRealmBoundScriptWork::DynamicClassic(work) => {
- PendingChildDocumentScriptExecutionWork::DynamicClassic(work)
- }
FrameDocumentRealmBoundScriptWork::ExternalClassic(work) => {
PendingChildDocumentScriptExecutionWork::ExternalClassic(work)
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/crypto_misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/crypto_misc.rs
index cd28ebe6c..611f98ed3 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/crypto_misc.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/crypto_misc.rs
@@ -810,19 +810,21 @@ fn child_initial_about_blank_executes_dynamic_inline_script_from_parent_document
crypto.subtle.digest(algorithm, new Uint8Array());
top.__childDynamicScriptEvents.push("after-call");
`;
- frame.contentDocument.body.appendChild(script);
+ const child = frame.contentDocument;
+ child.body.appendChild(script);
+ __childDynamicScriptEvents.push("returned");
return [
- String(frame.contentDocument.body !== null),
- String(frame.contentDocument.getElementsByTagName("script").length)
+ String(child.body !== null),
+ String(child.getElementsByTagName("script").length),
+ JSON.stringify(__childDynamicScriptEvents)
].join("|");
})()
"#,
)
.expect("dynamic child script setup should evaluate");
- assert_eq!(setup, "true|1");
- assert!(
- vm.has_pending_child_frame_realm_materialization(),
- "the script must wait behind its typed child-realm prerequisite"
+ assert_eq!(
+ setup, r#"true|1|["start:true","getter","after-call","returned"]"#,
+ "the child script must execute before appendChild returns, even when it removes the frame"
);
vm.drain_pending_child_frame_work_for_test();
@@ -831,5 +833,5 @@ fn child_initial_about_blank_executes_dynamic_inline_script_from_parent_document
.eval("JSON.stringify(globalThis.__childDynamicScriptEvents)")
.expect("dynamic child script events should be readable");
- assert_eq!(result, r#"["start:true","getter","after-call"]"#);
+ assert_eq!(result, r#"["start:true","getter","after-call","returned"]"#);
}
diff --git a/moli-renderer-v8/src/script_vm/tests/child_dynamic_inline_scripts.rs b/moli-renderer-v8/src/script_vm/tests/child_dynamic_inline_scripts.rs
new file mode 100644
index 000000000..b65acf684
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/child_dynamic_inline_scripts.rs
@@ -0,0 +1,227 @@
+use super::*;
+
+fn child_inline_test_vm(loaded_srcdoc: bool) -> StandaloneScriptVmHarness {
+ let mut vm = new_storage_test_vm("https://child-inline.test/parent");
+ vm.eval(
+ r#"
+ const root = document.documentElement || document.appendChild(document.createElement('html'));
+ const body = document.body || root.appendChild(document.createElement('body'));
+ globalThis.frame = document.createElement('iframe');
+ body.appendChild(frame);
+ "#,
+ )
+ .unwrap();
+ if loaded_srcdoc {
+ vm.eval("frame.srcdoc = '<!doctype html><html><head></head><body></body></html>'")
+ .unwrap();
+ vm.drain_pending_child_frame_work_for_test();
+ }
+ vm
+}
+
+#[test]
+fn child_dynamic_inline_scripts_execute_synchronously_with_nested_current_script() {
+ for loaded_srcdoc in [false, true] {
+ let mut vm = child_inline_test_vm(loaded_srcdoc);
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ globalThis.events = [];
+ const child = frame.contentDocument;
+ frame.contentWindow.record = value => events.push(value);
+ const script = document.createElement('script');
+ script.id = 'outer';
+ script.textContent = `
+ record('outer:' + document.currentScript.id);
+ record('realm:' + (globalThis === document.defaultView));
+ const inner = document.createElement('script');
+ inner.id = 'inner';
+ inner.text = "record('inner:' + document.currentScript.id)";
+ document.body.appendChild(inner);
+ record('restored:' + document.currentScript.id);
+ document.body.appendChild(document.currentScript);
+ Promise.resolve().then(() => record('microtask:' + document.currentScript));
+ `;
+ child.body.appendChild(script);
+ events.push('returned:' + child.currentScript);
+ script.remove();
+ child.body.appendChild(script);
+ events.push('reinserted');
+ return JSON.stringify(events);
+ })()
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"["outer:outer","realm:true","inner:inner","restored:outer","returned:null","reinserted"]"#,
+ "loaded_srcdoc={loaded_srcdoc}"
+ );
+ vm.drain_pending_child_frame_work_for_test();
+ assert_eq!(
+ vm.eval("JSON.stringify(events)").unwrap(),
+ r#"["outer:outer","realm:true","inner:inner","restored:outer","returned:null","reinserted","microtask:null"]"#,
+ "script cleanup must neither run during the outer call nor execute the script again"
+ );
+ }
+}
+
+#[test]
+fn child_dynamic_inline_scripts_prepare_each_connected_script_after_reentrant_mutation() {
+ let mut vm = child_inline_test_vm(false);
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const child = frame.contentDocument;
+ const events = [];
+ frame.contentWindow.record = value => events.push(value);
+ const fragment = child.createDocumentFragment();
+ const first = child.createElement('script');
+ const second = child.createElement('script');
+ const removed = child.createElement('script');
+ second.id = 'second';
+ removed.id = 'removed';
+ second.textContent = "record('stale source')";
+ removed.textContent = "record('removed script')";
+ first.textContent = `
+ record('first');
+ document.getElementById('removed').remove();
+ document.getElementById('second').textContent = "record('updated source')";
+ record('first finished');
+ `;
+ fragment.append(first, second, removed);
+ child.body.appendChild(fragment);
+ events.push('returned');
+ child.body.appendChild(removed);
+ return JSON.stringify(events);
+ })()
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"["first","updated source","first finished","returned","removed script"]"#
+ );
+}
+
+#[test]
+fn child_dynamic_inline_script_exceptions_are_reported_before_insertion_returns() {
+ for loaded_srcdoc in [false, true] {
+ let mut vm = child_inline_test_vm(loaded_srcdoc);
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const child = frame.contentDocument;
+ const win = frame.contentWindow;
+ const events = [];
+ window.onerror = () => { events.push('wrong Window'); return true; };
+ win.onerror = (message, source, line, column, error) => {
+ events.push(error.name + ':' + (error instanceof win.Error) + ':' +
+ child.currentScript.id);
+ return true;
+ };
+ for (const [id, source] of [['syntax', '{'], ['runtime', "throw new TypeError('test')"]]) {
+ const script = document.createElement('script');
+ script.id = id;
+ script.textContent = source;
+ script.onload = () => events.push('unexpected load');
+ script.onerror = () => events.push('unexpected element error');
+ try {
+ child.body.appendChild(script);
+ events.push('returned:' + child.currentScript);
+ } catch (error) {
+ events.push('escaped:' + error.name);
+ }
+ }
+ return JSON.stringify(events);
+ })()
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"["SyntaxError:true:syntax","returned:null","TypeError:true:runtime","returned:null"]"#,
+ "loaded_srcdoc={loaded_srcdoc}"
+ );
+ }
+}
+
+#[test]
+fn child_dynamic_inline_script_adoption_preserves_its_execution_document() {
+ let mut vm = child_inline_test_vm(false);
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ globalThis.events = [];
+ const child = frame.contentDocument;
+ const script = document.createElement('script');
+ script.textContent = `
+ const script = document.currentScript;
+ parent.events.push('before:' + (script.ownerDocument === document));
+ parent.document.body.appendChild(script);
+ parent.events.push('after:' + (script.ownerDocument === parent.document));
+ parent.events.push('current:' + (document.currentScript === script));
+ parent.events.push('parent:' + parent.document.currentScript);
+ `;
+ child.body.appendChild(script);
+ events.push('returned:' + child.currentScript);
+ const inactiveScript = child.createElement('script');
+ inactiveScript.textContent = "parent.events.push('inactive')";
+ const inactiveBody = child.body;
+ frame.remove();
+ inactiveBody.appendChild(inactiveScript);
+ return JSON.stringify(events);
+ })()
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"["before:true","after:true","current:true","parent:null","returned:null"]"#
+ );
+}
+
+#[test]
+fn child_dynamic_inline_script_current_script_uses_shadow_root_at_execution_entry() {
+ let mut vm = child_inline_test_vm(false);
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const child = frame.contentDocument;
+ const events = [];
+ frame.contentWindow.record = value => events.push(value);
+ const script = child.createElement('script');
+ script.id = 'outer';
+ script.textContent = `
+ const outer = document.currentScript;
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const shadow = host.attachShadow({mode: 'open'});
+ shadow.appendChild(outer);
+ record('moved:' + (document.currentScript === outer));
+ const inner = document.createElement('script');
+ inner.textContent = \`
+ record('shadow:' + document.currentScript);
+ document.body.appendChild(inner);
+ record('moved out:' + document.currentScript);
+ \`;
+ shadow.appendChild(inner);
+ record('restored:' + (document.currentScript === outer));
+ `;
+ child.body.appendChild(script);
+ events.push('returned:' + child.currentScript);
+ return JSON.stringify(events);
+ })()
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ r#"["moved:true","shadow:null","moved out:null","restored:true","returned:null"]"#
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 5615fdad0..72dedf026 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -6670,95 +6670,6 @@ async fn child_document_script_owner_hooks_select_current_realm() {
));
}
-#[tokio::test]
-async fn child_dynamic_execution_action_requires_materialized_current_realm() {
- use crate::frame_owner_model::{
- FrameDocumentTaskOwner, FrameRealmId, PendingChildDynamicDocumentScript,
- };
-
- let mut vm = new_storage_test_vm("https://child-dynamic-current-realm.test/");
-
- vm.eval(
- r#"
-(() => {
- const root = document.documentElement || document.appendChild(document.createElement("html"));
- const body = document.body || root.appendChild(document.createElement("body"));
- const frame = document.createElement("iframe");
- body.appendChild(frame);
-})()
-"#,
- )
- .expect("child dynamic current-realm setup should evaluate");
- assert_initial_about_blank_child_completed_synchronously_for_test(
- &mut vm,
- "child dynamic current-realm setup",
- )
- .await;
- let child_context_id = materialize_single_child_default_realm_for_test(
- &mut vm,
- "child dynamic current-realm setup",
- );
- let (child_handle, task_owner, owner_realm_id) = {
- let realm = vm
- .child_frame_realm_store
- .get(&child_context_id)
- .expect("child realm record should exist");
- let snapshot = vm
- ._context_host
- .borrow()
- .frame_owner_current_child_snapshot(realm.child_handle)
- .expect("child frame should expose a current owner snapshot");
- (
- realm.child_handle,
- FrameDocumentTaskOwner::new(
- snapshot.scheduler_lane_id,
- snapshot.local_window_id,
- snapshot.document_id,
- ),
- realm.owner_realm_id,
- )
- };
- let script_handle = DomHandle::new(9001);
- let work_without_realm = PendingChildDynamicDocumentScript {
- child_handle,
- owner: task_owner,
- realm_id: None,
- script_handle,
- source: "globalThis.__childDynamicMaterializedRealm = true;".to_owned(),
- script_nonce: Some("captured-nonce".to_owned()),
- script_integrity: Some("sha256-captured-integrity".to_owned()),
- };
-
- let action = vm
- ._context_host
- .borrow()
- .child_dynamic_classic_script_execution_action_for_owner(
- &work_without_realm,
- owner_realm_id,
- )
- .expect("current dynamic work should materialize an execution action");
- assert_eq!(action.target().task_owner(), task_owner);
- assert_eq!(action.target().realm_id(), owner_realm_id);
- let job = action.into_job();
- assert_eq!(job.script_nonce.as_deref(), Some("captured-nonce"));
- assert_eq!(
- job.script_integrity.as_deref(),
- Some("sha256-captured-integrity")
- );
-
- let stale_work = PendingChildDynamicDocumentScript {
- realm_id: Some(FrameRealmId(owner_realm_id.0 + 1)),
- ..work_without_realm
- };
- assert!(
- vm._context_host
- .borrow()
- .child_dynamic_classic_script_execution_action_for_owner(&stale_work, owner_realm_id)
- .is_none(),
- "stale dynamic child work must not produce an execution action"
- );
-}
-
#[tokio::test]
async fn function_constructor_frame_script_job_returns_child_realm_function() {
let mut vm = new_storage_test_vm("https://child-function-job.test/");
@@ -15206,6 +15117,7 @@ mod browser_api;
mod canvas_arguments;
mod canvas_paths;
mod canvas_webgl;
+mod child_dynamic_inline_scripts;
mod dom_elements;
mod dom_xhr;
mod http_fixture;