mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(dom): parse popup document streams incrementally
Keep a live parser session for popup document.open/write/close, sharing DOM mutation and element construction with the child-document parser. Preserve split tokens, node identity and parser-script insertion order; resume external scripts and drain deferred work before completion. Cancel stale parser and lifecycle work when a stream is replaced, and mark prepared scripts started before CSP filtering. Cover tree reset, script scheduling, custom-element reentry and blocked-script adoption.
This commit is contained in:
@@ -1,13 +1,11 @@
|
||||
use super::super::document_parser_owner::ContextDocumentParserOwner;
|
||||
use super::super::{ChildParserClassicScriptCandidate, PageScriptHost};
|
||||
use crate::{
|
||||
StylesheetBlockingReadView, StylesheetElementRead,
|
||||
content_security_policy::ContentSecurityPolicyScriptElementRequest,
|
||||
custom_elements,
|
||||
document_runtime::DomHandle,
|
||||
document_script_scheduler::FrameDocumentClassicScriptSchedulerWork,
|
||||
dom::native::{
|
||||
Attribute, DocumentReadyState, DomMutationEffects, DomStylesheetOwnerChange, Node,
|
||||
},
|
||||
dom::native::DocumentReadyState,
|
||||
frame_owner_model::{
|
||||
DocumentId, FrameClassicDocumentScriptExecutionStart,
|
||||
FrameDocumentClassicCompletionFinishAction, FrameDocumentClassicParserResumeApplication,
|
||||
@@ -17,19 +15,14 @@ use crate::{
|
||||
},
|
||||
live_document_parser::{
|
||||
DocumentParserCloseDisposition, DocumentParserLifetime, DocumentParserRunState,
|
||||
DocumentParserSession, LiveDocumentParserOwner, LiveDocumentParserStepOutcome,
|
||||
ParserStopReason, ParserSuspensionCause,
|
||||
DocumentParserSession, LiveDocumentParserStepOutcome, ParserStopReason,
|
||||
ParserSuspensionCause,
|
||||
},
|
||||
modulepreload::{
|
||||
invalid_modulepreload_as_value, invalid_modulepreload_as_warning,
|
||||
modulepreload_fetch_candidate, modulepreload_href, resolve_parser_network_resource_url,
|
||||
},
|
||||
parser::{
|
||||
ParserDomMutation, ParserDomMutationConsumer, ParserDomReadConsumer,
|
||||
ParserElementCreationConsumer, ParserElementCreationRequest, ParserMutationEffectConsumer,
|
||||
ParserPlanningReadView, ParserScriptHandoff, ParserScriptRead, PreparedImportMapSource,
|
||||
},
|
||||
parser_mutation_effects::{ParserMutationEffectsOwner, apply_parser_mutation_effects},
|
||||
parser::{ParserScriptHandoff, PreparedImportMapSource},
|
||||
planning::ScriptSource,
|
||||
types::{ScriptKind, ScriptSourceKind},
|
||||
};
|
||||
@@ -57,570 +50,6 @@ impl ChildLiveDocumentParserStartResult {
|
||||
}
|
||||
}
|
||||
|
||||
struct ChildFrameLiveParserOwner<'a, 'scope, 'pin> {
|
||||
host: &'a mut PageScriptHost,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
child_document_handle: DomHandle,
|
||||
document_owner: Option<FrameDocumentOwner>,
|
||||
parser_control: Option<crate::live_document_parser::DocumentParserSessionControlHandle>,
|
||||
mutation_effects: ChildParserMutationEffects,
|
||||
}
|
||||
|
||||
struct ChildParserMutationEffects {
|
||||
document_handle: DomHandle,
|
||||
reaction_queue_active: bool,
|
||||
}
|
||||
|
||||
impl ParserMutationEffectsOwner for ChildParserMutationEffects {
|
||||
type Prepared = Vec<DomStylesheetOwnerChange>;
|
||||
|
||||
fn prepare_parser_mutation_effects(&mut self, effects: &DomMutationEffects) -> Self::Prepared {
|
||||
effects.stylesheet_owners().changes().to_vec()
|
||||
}
|
||||
|
||||
fn ensure_parser_reaction_queue(&mut self, host_ptr: *mut PageScriptHost) {
|
||||
if !self.reaction_queue_active {
|
||||
custom_elements::push_parser_custom_element_reaction_queue(host_ptr);
|
||||
self.reaction_queue_active = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_parser_mutation_effects(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
prepared: Self::Prepared,
|
||||
) {
|
||||
unsafe { &mut *host_ptr }.sync_child_browsing_context_subtree(scope, self.document_handle);
|
||||
crate::native_bridge::document::apply_stylesheet_owner_css_projections(
|
||||
scope,
|
||||
unsafe { &*host_ptr },
|
||||
&prepared,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'scope, 'pin> ChildFrameLiveParserOwner<'a, 'scope, 'pin> {
|
||||
fn new(
|
||||
host: &'a mut PageScriptHost,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
child_document_handle: DomHandle,
|
||||
) -> Self {
|
||||
let document_owner = host
|
||||
.child_browsing_context_host_for_document_handle(child_document_handle)
|
||||
.and_then(|child| host.frame_owner_store.current_child_document_owner(child));
|
||||
let parser_control = document_owner
|
||||
.and_then(|owner| host.child_document_parsers.insertion_handle(owner))
|
||||
.map(|insertion| insertion.control_handle());
|
||||
Self {
|
||||
host,
|
||||
scope,
|
||||
child_document_handle,
|
||||
document_owner,
|
||||
parser_control,
|
||||
mutation_effects: ChildParserMutationEffects {
|
||||
document_handle: child_document_handle,
|
||||
reaction_queue_active: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn targets_current_document(&self) -> bool {
|
||||
self.host
|
||||
.child_browsing_context_host_for_document_handle(self.child_document_handle)
|
||||
.and_then(|child| {
|
||||
self.host
|
||||
.frame_owner_store
|
||||
.current_child_document_owner(child)
|
||||
})
|
||||
== self.document_owner
|
||||
}
|
||||
}
|
||||
|
||||
impl LiveDocumentParserOwner for ChildFrameLiveParserOwner<'_, '_, '_> {}
|
||||
|
||||
impl StylesheetBlockingReadView for ChildFrameLiveParserOwner<'_, '_, '_> {
|
||||
fn media_query_matches(&self, media: &str) -> bool {
|
||||
self.host
|
||||
.media_query_matches_for_document(self.child_document_handle, media)
|
||||
}
|
||||
|
||||
fn stylesheet_element(&self, node_id: DomHandle) -> Option<StylesheetElementRead> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(StylesheetElementRead::from_node)
|
||||
}
|
||||
|
||||
fn child_ids(&self, node_id: DomHandle) -> Vec<DomHandle> {
|
||||
self.host.dom_host().child_handles(node_id).collect()
|
||||
}
|
||||
|
||||
fn text_content(&self, node_id: DomHandle) -> Option<String> {
|
||||
self.host.dom_host().text_content(node_id)
|
||||
}
|
||||
|
||||
fn final_url_clone(&self) -> Option<Url> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(self.child_document_handle)
|
||||
.and_then(Node::as_document)
|
||||
.map(|document| document.url().clone())
|
||||
}
|
||||
|
||||
fn document_base_url_clone(&self) -> Option<Url> {
|
||||
Some(
|
||||
self.host
|
||||
.document_base_url_for_handle(self.child_document_handle),
|
||||
)
|
||||
}
|
||||
|
||||
fn document_node_id(&self) -> DomHandle {
|
||||
self.child_document_handle
|
||||
}
|
||||
|
||||
fn document_is_quirks_mode(&self) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(self.child_document_handle)
|
||||
.and_then(Node::as_document)
|
||||
.is_some_and(|document| document.is_quirks_mode())
|
||||
}
|
||||
|
||||
fn document_order_stylesheet_candidate_ids_before(
|
||||
&self,
|
||||
target_node_id: Option<crate::dom::NodeId>,
|
||||
) -> Vec<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.stylesheet_candidate_handles_before_in_tree_scope(
|
||||
self.child_document_handle,
|
||||
target_node_id.map(|node_id| DomHandle::new(node_id.index())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserMutationEffectConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
|
||||
fn consume_parser_mutation_effects(&mut self, effects: DomMutationEffects) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
for &root in effects.tree().connected_roots() {
|
||||
crate::native_bridge::element::initialize_parser_inserted_body_window_event_handlers(
|
||||
self.scope, self.host, root,
|
||||
);
|
||||
}
|
||||
apply_parser_mutation_effects(self.scope, self.host, &mut self.mutation_effects, &effects);
|
||||
if self.targets_current_document() {
|
||||
// Register parser declarations before the parser can run a later
|
||||
// script, using the same path as script-created declarations.
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
let runtime = unsafe { &mut *self.host.document_runtime };
|
||||
runtime.note_parser_meta_refresh_mutation(self.scope, host_ptr, &effects);
|
||||
runtime
|
||||
.process_connected_meta_content_security_policies(effects.tree().connected_roots());
|
||||
let mut checked_inline_styles = Vec::new();
|
||||
for change in effects.stylesheet_owners().changes() {
|
||||
let owner = change.owner();
|
||||
if runtime.dom_host().is_inline_style_sheet_owner(owner)
|
||||
&& !checked_inline_styles.contains(&owner)
|
||||
{
|
||||
checked_inline_styles.push(owner);
|
||||
runtime.apply_inline_style_element_csp_check(self.scope, host_ptr, owner);
|
||||
}
|
||||
}
|
||||
|
||||
// Admit the resource while this parser element is inserted/finished,
|
||||
// before a later meta can become policy for an earlier request.
|
||||
let stylesheet_inputs = effects
|
||||
.stylesheet_owners()
|
||||
.changes()
|
||||
.iter()
|
||||
.filter(|change| self.host.dom_host().is_connected(change.owner()))
|
||||
.filter_map(|change| {
|
||||
crate::stylesheet_blocking::document_owned_stylesheet_discovery_input_for_node(
|
||||
self,
|
||||
crate::dom::NodeId::new(change.owner().index()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !stylesheet_inputs.is_empty()
|
||||
&& let Some(child) = self
|
||||
.host
|
||||
.child_browsing_context_host_for_document_handle(self.child_document_handle)
|
||||
&& let Some(owner) = self.host.current_child_document_task_owner(child)
|
||||
{
|
||||
self.host
|
||||
.accept_child_parser_stylesheet_inputs(child, owner, stylesheet_inputs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {
|
||||
if std::mem::take(&mut self.mutation_effects.reaction_queue_active) {
|
||||
custom_elements::flush_parser_custom_element_reaction_queue(self.scope, self.host);
|
||||
}
|
||||
if !self.targets_current_document()
|
||||
|| self.parser_control.as_ref().is_some_and(|control| {
|
||||
!matches!(
|
||||
control.run_state(),
|
||||
DocumentParserRunState::Ready | DocumentParserRunState::Pumping { .. }
|
||||
)
|
||||
})
|
||||
{
|
||||
return std::ops::ControlFlow::Break(());
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserDomReadConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
|
||||
fn stylesheet_media_matches(&mut self, media: &str) -> bool {
|
||||
self.host
|
||||
.media_query_matches_for_document(self.child_document_handle, media)
|
||||
}
|
||||
|
||||
fn node_exists(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host.dom_host().node(node_id).is_some()
|
||||
}
|
||||
|
||||
fn is_connected(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host.dom_host().is_connected(node_id)
|
||||
}
|
||||
|
||||
fn is_text_node(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::as_text)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn owner_document(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host.dom_host().owner_document_handle(node_id)
|
||||
}
|
||||
|
||||
fn parent_node(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::parent_node)
|
||||
}
|
||||
|
||||
fn previous_sibling(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::prev_sibling)
|
||||
}
|
||||
|
||||
fn last_child(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::last_child)
|
||||
}
|
||||
|
||||
fn child_handles(&mut self, node_id: DomHandle) -> Vec<DomHandle> {
|
||||
self.host.dom_host().child_handles(node_id).collect()
|
||||
}
|
||||
|
||||
fn document_body_handle_for_document(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.document_body_handle_for_document(document_handle)
|
||||
}
|
||||
|
||||
fn document_base_url(&mut self, document_handle: DomHandle) -> Option<Url> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.document_base_url_for_handle(document_handle)
|
||||
}
|
||||
|
||||
fn template_contents_handle(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.parser_template_contents_handle(node_id)
|
||||
}
|
||||
|
||||
fn is_html_element_named(&mut self, node_id: DomHandle, local_name: &str) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.dom()
|
||||
.is_html_element_named(node_id, local_name)
|
||||
}
|
||||
|
||||
fn is_external_async_classic_candidate(&mut self, node_id: DomHandle) -> bool {
|
||||
let Some(element) = self
|
||||
.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::as_element)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !element.is_html_element("script")
|
||||
|| element.attribute("src").is_none()
|
||||
|| element.attribute("async").is_none()
|
||||
|| element.attribute("nomodule").is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(script_type) = element.attribute("type") else {
|
||||
return true;
|
||||
};
|
||||
script_type.is_empty()
|
||||
|| moli_script::classify_script_kind(Some(script_type))
|
||||
== crate::types::ScriptKind::Classic
|
||||
}
|
||||
|
||||
fn parser_script_read(&mut self, node_id: DomHandle) -> Option<ParserScriptRead> {
|
||||
<crate::dom::native::DomHost as ParserPlanningReadView>::parser_script_read(
|
||||
self.host.dom_host(),
|
||||
node_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn stylesheet_element(&mut self, node_id: DomHandle) -> Option<StylesheetElementRead> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(StylesheetElementRead::from_node)
|
||||
}
|
||||
|
||||
fn text_content(&mut self, node_id: DomHandle) -> Option<String> {
|
||||
self.host.dom_host().text_content(node_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
|
||||
fn apply_parser_dom_mutation(&mut self, mutation: ParserDomMutation) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
// The tree sink invokes this queue after releasing its structural
|
||||
// borrow, before returning to the tree builder. Nested document.write
|
||||
// can then use the insertion point preceding this element's children.
|
||||
self.mutation_effects
|
||||
.ensure_parser_reaction_queue(self.host);
|
||||
let effects = mutation.apply_to_dom_host(self.host.dom_host_mut());
|
||||
self.consume_parser_mutation_effects(effects);
|
||||
}
|
||||
|
||||
fn create_element_for_document_without_attributes(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
local_name: String,
|
||||
namespace: String,
|
||||
prefix: Option<String>,
|
||||
) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_element_without_attributes_for_document(
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_parser_element_for_document_without_attributes(
|
||||
&mut self,
|
||||
construction: &moli_dom::native::ParserConstruction,
|
||||
document_handle: DomHandle,
|
||||
local_name: String,
|
||||
namespace: String,
|
||||
prefix: Option<String>,
|
||||
) -> DomHandle {
|
||||
construction.create_element(
|
||||
self.host.dom_host_mut(),
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
}
|
||||
|
||||
fn add_attrs_if_missing_for_parser(&mut self, node_id: DomHandle, attrs: Vec<Attribute>) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.add_attrs_if_missing_for_parser(node_id, attrs);
|
||||
}
|
||||
|
||||
fn create_text_node(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_text_node_for_document(document_handle, &text)
|
||||
}
|
||||
|
||||
fn create_comment(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_comment_for_document(document_handle, &text)
|
||||
}
|
||||
|
||||
fn create_processing_instruction(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
target: String,
|
||||
data: String,
|
||||
) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_processing_instruction_for_document(document_handle, &target, &data)
|
||||
}
|
||||
|
||||
fn create_cdata_section(&mut self, document_handle: DomHandle, data: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_cdata_section_for_document(document_handle, &data)
|
||||
}
|
||||
|
||||
fn create_document_type(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
name: String,
|
||||
public_id: String,
|
||||
system_id: String,
|
||||
) -> DomHandle {
|
||||
self.host.dom_host_mut().create_document_type_for_document(
|
||||
document_handle,
|
||||
&name,
|
||||
&public_id,
|
||||
&system_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn prepend_text_to_text_node(
|
||||
&mut self,
|
||||
node_id: DomHandle,
|
||||
text: String,
|
||||
) -> DomMutationEffects {
|
||||
let host = self.host.dom_host_mut();
|
||||
let Some(previous) = host.node(node_id).and_then(Node::as_text) else {
|
||||
return DomMutationEffects::default();
|
||||
};
|
||||
let mut merged = text;
|
||||
merged.push_str(previous.data());
|
||||
host.set_text_content_effects(node_id, &merged)
|
||||
}
|
||||
|
||||
fn append_text_to_text_node(&mut self, node_id: DomHandle, text: String) -> DomMutationEffects {
|
||||
let host = self.host.dom_host_mut();
|
||||
let Some(previous) = host.node(node_id).and_then(Node::as_text) else {
|
||||
return DomMutationEffects::default();
|
||||
};
|
||||
let mut merged = previous.data().to_owned();
|
||||
merged.push_str(&text);
|
||||
host.set_text_content_effects(node_id, &merged)
|
||||
}
|
||||
|
||||
fn push_parse_error(&mut self, error: String) {
|
||||
self.host.dom_host_mut().push_parse_error(error);
|
||||
}
|
||||
|
||||
fn set_html_quirks_mode_for_parser(&mut self, quirks_mode: QuirksMode) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.set_html_quirks_mode_for_parser_document(self.child_document_handle, quirks_mode);
|
||||
}
|
||||
|
||||
fn mark_script_already_started_for_parser(&mut self, node_id: DomHandle) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.set_script_already_started(node_id, true);
|
||||
}
|
||||
|
||||
fn mark_unclosed_form_control_for_parser(&mut self, node_id: DomHandle) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
let _ = self
|
||||
.host
|
||||
.dom_host_mut()
|
||||
.set_blocks_form_submission(node_id, true);
|
||||
}
|
||||
|
||||
fn finish_parsing_children(
|
||||
&mut self,
|
||||
construction: &moli_dom::native::ParserConstruction,
|
||||
node_id: DomHandle,
|
||||
) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
let effects = construction.finish_children(self.host.dom_host_mut(), node_id);
|
||||
self.consume_parser_mutation_effects(effects);
|
||||
}
|
||||
|
||||
fn maybe_clone_an_option_into_selectedcontent(&mut self, node_id: DomHandle) {
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
let _ = self
|
||||
.host
|
||||
.sync_selectedcontents_after_parser_option_finished(self.scope, host_ptr, node_id);
|
||||
}
|
||||
|
||||
fn attach_declarative_shadow_for_parser(
|
||||
&mut self,
|
||||
host_id: DomHandle,
|
||||
template_id: DomHandle,
|
||||
attrs: Vec<Attribute>,
|
||||
) -> bool {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.attach_declarative_shadow_for_parser(host_id, template_id, &attrs)
|
||||
}
|
||||
|
||||
fn associate_parser_form_owner(&mut self, target: DomHandle, form: DomHandle) -> bool {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.associate_parser_form_owner(target, form)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserElementCreationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
|
||||
fn create_parser_element(
|
||||
&mut self,
|
||||
request: ParserElementCreationRequest<'_>,
|
||||
) -> Option<DomHandle> {
|
||||
if !self.targets_current_document() {
|
||||
return None;
|
||||
}
|
||||
let child_handle = self
|
||||
.host
|
||||
.child_browsing_context_host_for_document_handle(request.document_handle)?;
|
||||
// A child with a registered definition already has a realm. Keep the
|
||||
// initial parser lazy, and create wrappers in that realm once it exists.
|
||||
let context = self
|
||||
.host
|
||||
.child_browsing_context_relevant_context(self.scope, child_handle)?;
|
||||
let scope = &mut v8::ContextScope::new(self.scope, context);
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
custom_elements::create_and_construct_parser_custom_element_direct_for_document(
|
||||
scope,
|
||||
host_ptr,
|
||||
request.document_handle,
|
||||
request.local_name,
|
||||
request.namespace,
|
||||
request.prefix,
|
||||
request.attributes,
|
||||
request.intended_parent,
|
||||
|document_handle, local_name, namespace, prefix| {
|
||||
request.construction.create_element(
|
||||
self.host.dom_host_mut(),
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum ParserProgress {
|
||||
/// Every parser-owned input frame is empty and this parser's lifetime
|
||||
@@ -678,7 +107,7 @@ impl PageScriptHost {
|
||||
document_handle: DomHandle,
|
||||
prepare_script: impl FnOnce(
|
||||
crate::parser::ParserScriptPreparationRequest,
|
||||
&mut ChildFrameLiveParserOwner<'_, '_, '_>,
|
||||
&mut ContextDocumentParserOwner<'_, '_, '_>,
|
||||
) -> ParserScriptHandoff,
|
||||
outcome: LiveDocumentParserStepOutcome,
|
||||
) -> Option<LiveDocumentParserStepOutcome> {
|
||||
@@ -702,7 +131,7 @@ impl PageScriptHost {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
|
||||
let mut owner = ContextDocumentParserOwner::new_child(self, scope, document_handle);
|
||||
let handoff = prepare_script(*request, &mut owner);
|
||||
Some(LiveDocumentParserStepOutcome::ScriptHandoff(Box::new(
|
||||
handoff,
|
||||
@@ -751,7 +180,8 @@ impl PageScriptHost {
|
||||
.insertion_handle()
|
||||
.map(|handle| self.child_document_parsers.enter_active(owner, handle));
|
||||
let outcome = {
|
||||
let mut parser_owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
|
||||
let mut parser_owner =
|
||||
ContextDocumentParserOwner::new_child(self, scope, document_handle);
|
||||
parser.advance_queued_or_resume_step(&mut parser_owner)
|
||||
};
|
||||
if self
|
||||
@@ -1148,7 +578,7 @@ impl PageScriptHost {
|
||||
parser.request_finish();
|
||||
let _ = parser.admit_delayed_finish_at_local_owner_boundary();
|
||||
let finish_signals = {
|
||||
let mut owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
|
||||
let mut owner = ContextDocumentParserOwner::new_child(self, scope, document_handle);
|
||||
parser.finish(&mut owner)
|
||||
};
|
||||
self.queue_live_child_parser_discovery_signals(
|
||||
@@ -1448,7 +878,8 @@ impl PageScriptHost {
|
||||
return true;
|
||||
}
|
||||
let outcome = {
|
||||
let mut parser_owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
|
||||
let mut parser_owner =
|
||||
ContextDocumentParserOwner::new_child(self, scope, document_handle);
|
||||
insertion.advance_queued_or_resume_step(&mut parser_owner)
|
||||
};
|
||||
if matches!(insertion.run_state(), DocumentParserRunState::Stopped(_)) {
|
||||
|
||||
@@ -0,0 +1,616 @@
|
||||
use super::PageScriptHost;
|
||||
use crate::{
|
||||
StylesheetBlockingReadView, StylesheetElementRead, custom_elements,
|
||||
document_runtime::DomHandle,
|
||||
dom::native::{Attribute, DomMutationEffects, DomStylesheetOwnerChange, Node},
|
||||
frame_owner_model::FrameDocumentOwner,
|
||||
live_document_parser::{DocumentParserRunState, LiveDocumentParserOwner},
|
||||
parser::{
|
||||
ParserDomMutation, ParserDomMutationConsumer, ParserDomReadConsumer,
|
||||
ParserElementCreationConsumer, ParserElementCreationRequest, ParserMutationEffectConsumer,
|
||||
ParserPlanningReadView, ParserScriptRead,
|
||||
},
|
||||
parser_mutation_effects::{ParserMutationEffectsOwner, apply_parser_mutation_effects},
|
||||
window_document_identity::LightweightPopupDocumentOwner,
|
||||
};
|
||||
use html5ever::tree_builder::QuirksMode;
|
||||
use url::Url;
|
||||
|
||||
pub(super) struct ContextDocumentParserOwner<'a, 'scope, 'pin> {
|
||||
host: &'a mut PageScriptHost,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
document_handle: DomHandle,
|
||||
document_owner: Option<FrameDocumentOwner>,
|
||||
popup_owner: Option<LightweightPopupDocumentOwner>,
|
||||
parser_control: Option<crate::live_document_parser::DocumentParserSessionControlHandle>,
|
||||
mutation_effects: DocumentParserMutationEffects,
|
||||
}
|
||||
|
||||
struct DocumentParserMutationEffects {
|
||||
document_handle: DomHandle,
|
||||
reaction_queue_active: bool,
|
||||
}
|
||||
|
||||
impl ParserMutationEffectsOwner for DocumentParserMutationEffects {
|
||||
type Prepared = Vec<DomStylesheetOwnerChange>;
|
||||
|
||||
fn prepare_parser_mutation_effects(&mut self, effects: &DomMutationEffects) -> Self::Prepared {
|
||||
effects.stylesheet_owners().changes().to_vec()
|
||||
}
|
||||
|
||||
fn ensure_parser_reaction_queue(&mut self, host_ptr: *mut PageScriptHost) {
|
||||
if !self.reaction_queue_active {
|
||||
custom_elements::push_parser_custom_element_reaction_queue(host_ptr);
|
||||
self.reaction_queue_active = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_parser_mutation_effects(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
prepared: Self::Prepared,
|
||||
) {
|
||||
unsafe { &mut *host_ptr }.sync_child_browsing_context_subtree(scope, self.document_handle);
|
||||
crate::native_bridge::document::apply_stylesheet_owner_css_projections(
|
||||
scope,
|
||||
unsafe { &*host_ptr },
|
||||
&prepared,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'scope, 'pin> ContextDocumentParserOwner<'a, 'scope, 'pin> {
|
||||
pub(super) fn new_child(
|
||||
host: &'a mut PageScriptHost,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
document_handle: DomHandle,
|
||||
) -> Self {
|
||||
let document_owner = host
|
||||
.child_browsing_context_host_for_document_handle(document_handle)
|
||||
.and_then(|child| host.frame_owner_store.current_child_document_owner(child));
|
||||
let parser_control = document_owner
|
||||
.and_then(|owner| host.child_document_parsers.insertion_handle(owner))
|
||||
.map(|insertion| insertion.control_handle());
|
||||
Self {
|
||||
host,
|
||||
scope,
|
||||
document_handle,
|
||||
document_owner,
|
||||
popup_owner: None,
|
||||
parser_control,
|
||||
mutation_effects: DocumentParserMutationEffects {
|
||||
document_handle,
|
||||
reaction_queue_active: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn new_popup(
|
||||
host: &'a mut PageScriptHost,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
document_handle: DomHandle,
|
||||
popup_owner: LightweightPopupDocumentOwner,
|
||||
parser_control: crate::live_document_parser::DocumentParserSessionControlHandle,
|
||||
) -> Self {
|
||||
Self {
|
||||
host,
|
||||
scope,
|
||||
document_handle,
|
||||
document_owner: None,
|
||||
popup_owner: Some(popup_owner),
|
||||
parser_control: Some(parser_control),
|
||||
mutation_effects: DocumentParserMutationEffects {
|
||||
document_handle,
|
||||
reaction_queue_active: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn targets_current_document(&self) -> bool {
|
||||
if let Some(owner) = self.popup_owner {
|
||||
return self.parser_control.as_ref().is_some_and(|control| {
|
||||
self.host
|
||||
.popup_document_parser_is_current(owner, control.session_id())
|
||||
}) && self
|
||||
.host
|
||||
.lightweight_popup_document_handle(owner.popup_id())
|
||||
== Some(self.document_handle);
|
||||
}
|
||||
self.host
|
||||
.child_browsing_context_host_for_document_handle(self.document_handle)
|
||||
.and_then(|child| {
|
||||
self.host
|
||||
.frame_owner_store
|
||||
.current_child_document_owner(child)
|
||||
})
|
||||
== self.document_owner
|
||||
}
|
||||
}
|
||||
|
||||
impl LiveDocumentParserOwner for ContextDocumentParserOwner<'_, '_, '_> {}
|
||||
|
||||
impl StylesheetBlockingReadView for ContextDocumentParserOwner<'_, '_, '_> {
|
||||
fn media_query_matches(&self, media: &str) -> bool {
|
||||
self.host
|
||||
.media_query_matches_for_document(self.document_handle, media)
|
||||
}
|
||||
|
||||
fn stylesheet_element(&self, node_id: DomHandle) -> Option<StylesheetElementRead> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(StylesheetElementRead::from_node)
|
||||
}
|
||||
|
||||
fn child_ids(&self, node_id: DomHandle) -> Vec<DomHandle> {
|
||||
self.host.dom_host().child_handles(node_id).collect()
|
||||
}
|
||||
|
||||
fn text_content(&self, node_id: DomHandle) -> Option<String> {
|
||||
self.host.dom_host().text_content(node_id)
|
||||
}
|
||||
|
||||
fn final_url_clone(&self) -> Option<Url> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(self.document_handle)
|
||||
.and_then(Node::as_document)
|
||||
.map(|document| document.url().clone())
|
||||
}
|
||||
|
||||
fn document_base_url_clone(&self) -> Option<Url> {
|
||||
Some(self.host.document_base_url_for_handle(self.document_handle))
|
||||
}
|
||||
|
||||
fn document_node_id(&self) -> DomHandle {
|
||||
self.document_handle
|
||||
}
|
||||
|
||||
fn document_is_quirks_mode(&self) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(self.document_handle)
|
||||
.and_then(Node::as_document)
|
||||
.is_some_and(|document| document.is_quirks_mode())
|
||||
}
|
||||
|
||||
fn document_order_stylesheet_candidate_ids_before(
|
||||
&self,
|
||||
target_node_id: Option<crate::dom::NodeId>,
|
||||
) -> Vec<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.stylesheet_candidate_handles_before_in_tree_scope(
|
||||
self.document_handle,
|
||||
target_node_id.map(|node_id| DomHandle::new(node_id.index())),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserMutationEffectConsumer for ContextDocumentParserOwner<'_, '_, '_> {
|
||||
fn consume_parser_mutation_effects(&mut self, effects: DomMutationEffects) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
for &root in effects.tree().connected_roots() {
|
||||
crate::native_bridge::element::initialize_parser_inserted_body_window_event_handlers(
|
||||
self.scope, self.host, root,
|
||||
);
|
||||
}
|
||||
apply_parser_mutation_effects(self.scope, self.host, &mut self.mutation_effects, &effects);
|
||||
if self.targets_current_document() {
|
||||
// Register parser declarations before the parser can run a later
|
||||
// script, using the same path as script-created declarations.
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
let runtime = unsafe { &mut *self.host.document_runtime };
|
||||
runtime.note_parser_meta_refresh_mutation(self.scope, host_ptr, &effects);
|
||||
runtime
|
||||
.process_connected_meta_content_security_policies(effects.tree().connected_roots());
|
||||
let mut checked_inline_styles = Vec::new();
|
||||
for change in effects.stylesheet_owners().changes() {
|
||||
let owner = change.owner();
|
||||
if runtime.dom_host().is_inline_style_sheet_owner(owner)
|
||||
&& !checked_inline_styles.contains(&owner)
|
||||
{
|
||||
checked_inline_styles.push(owner);
|
||||
runtime.apply_inline_style_element_csp_check(self.scope, host_ptr, owner);
|
||||
}
|
||||
}
|
||||
|
||||
// Admit the resource while this parser element is inserted/finished,
|
||||
// before a later meta can become policy for an earlier request.
|
||||
let stylesheet_inputs = effects
|
||||
.stylesheet_owners()
|
||||
.changes()
|
||||
.iter()
|
||||
.filter(|change| self.host.dom_host().is_connected(change.owner()))
|
||||
.filter_map(|change| {
|
||||
crate::stylesheet_blocking::document_owned_stylesheet_discovery_input_for_node(
|
||||
self,
|
||||
crate::dom::NodeId::new(change.owner().index()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !stylesheet_inputs.is_empty()
|
||||
&& let Some(child) = self
|
||||
.host
|
||||
.child_browsing_context_host_for_document_handle(self.document_handle)
|
||||
&& let Some(owner) = self.host.current_child_document_task_owner(child)
|
||||
{
|
||||
self.host
|
||||
.accept_child_parser_stylesheet_inputs(child, owner, stylesheet_inputs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {
|
||||
if std::mem::take(&mut self.mutation_effects.reaction_queue_active) {
|
||||
custom_elements::flush_parser_custom_element_reaction_queue(self.scope, self.host);
|
||||
}
|
||||
if !self.targets_current_document()
|
||||
|| self.parser_control.as_ref().is_some_and(|control| {
|
||||
!matches!(
|
||||
control.run_state(),
|
||||
DocumentParserRunState::Ready
|
||||
| DocumentParserRunState::Pumping { .. }
|
||||
| DocumentParserRunState::Finishing
|
||||
)
|
||||
})
|
||||
{
|
||||
return std::ops::ControlFlow::Break(());
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserDomReadConsumer for ContextDocumentParserOwner<'_, '_, '_> {
|
||||
fn stylesheet_media_matches(&mut self, media: &str) -> bool {
|
||||
self.host
|
||||
.media_query_matches_for_document(self.document_handle, media)
|
||||
}
|
||||
|
||||
fn node_exists(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host.dom_host().node(node_id).is_some()
|
||||
}
|
||||
|
||||
fn is_connected(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host.dom_host().is_connected(node_id)
|
||||
}
|
||||
|
||||
fn is_text_node(&mut self, node_id: DomHandle) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::as_text)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn owner_document(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host.dom_host().owner_document_handle(node_id)
|
||||
}
|
||||
|
||||
fn parent_node(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::parent_node)
|
||||
}
|
||||
|
||||
fn previous_sibling(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::prev_sibling)
|
||||
}
|
||||
|
||||
fn last_child(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::last_child)
|
||||
}
|
||||
|
||||
fn child_handles(&mut self, node_id: DomHandle) -> Vec<DomHandle> {
|
||||
self.host.dom_host().child_handles(node_id).collect()
|
||||
}
|
||||
|
||||
fn document_body_handle_for_document(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.document_body_handle_for_document(document_handle)
|
||||
}
|
||||
|
||||
fn document_base_url(&mut self, document_handle: DomHandle) -> Option<Url> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.document_base_url_for_handle(document_handle)
|
||||
}
|
||||
|
||||
fn template_contents_handle(&mut self, node_id: DomHandle) -> Option<DomHandle> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.parser_template_contents_handle(node_id)
|
||||
}
|
||||
|
||||
fn is_html_element_named(&mut self, node_id: DomHandle, local_name: &str) -> bool {
|
||||
self.host
|
||||
.dom_host()
|
||||
.dom()
|
||||
.is_html_element_named(node_id, local_name)
|
||||
}
|
||||
|
||||
fn is_external_async_classic_candidate(&mut self, node_id: DomHandle) -> bool {
|
||||
let Some(element) = self
|
||||
.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(Node::as_element)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !element.is_html_element("script")
|
||||
|| element.attribute("src").is_none()
|
||||
|| element.attribute("async").is_none()
|
||||
|| element.attribute("nomodule").is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(script_type) = element.attribute("type") else {
|
||||
return true;
|
||||
};
|
||||
script_type.is_empty()
|
||||
|| moli_script::classify_script_kind(Some(script_type))
|
||||
== crate::types::ScriptKind::Classic
|
||||
}
|
||||
|
||||
fn parser_script_read(&mut self, node_id: DomHandle) -> Option<ParserScriptRead> {
|
||||
<crate::dom::native::DomHost as ParserPlanningReadView>::parser_script_read(
|
||||
self.host.dom_host(),
|
||||
node_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn stylesheet_element(&mut self, node_id: DomHandle) -> Option<StylesheetElementRead> {
|
||||
self.host
|
||||
.dom_host()
|
||||
.node(node_id)
|
||||
.and_then(StylesheetElementRead::from_node)
|
||||
}
|
||||
|
||||
fn text_content(&mut self, node_id: DomHandle) -> Option<String> {
|
||||
self.host.dom_host().text_content(node_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserDomMutationConsumer for ContextDocumentParserOwner<'_, '_, '_> {
|
||||
fn apply_parser_dom_mutation(&mut self, mutation: ParserDomMutation) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
// The tree sink invokes this queue after releasing its structural
|
||||
// borrow, before returning to the tree builder. Nested document.write
|
||||
// can then use the insertion point preceding this element's children.
|
||||
self.mutation_effects
|
||||
.ensure_parser_reaction_queue(self.host);
|
||||
let effects = mutation.apply_to_dom_host(self.host.dom_host_mut());
|
||||
self.consume_parser_mutation_effects(effects);
|
||||
}
|
||||
|
||||
fn create_element_for_document_without_attributes(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
local_name: String,
|
||||
namespace: String,
|
||||
prefix: Option<String>,
|
||||
) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_element_without_attributes_for_document(
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
}
|
||||
|
||||
fn create_parser_element_for_document_without_attributes(
|
||||
&mut self,
|
||||
construction: &moli_dom::native::ParserConstruction,
|
||||
document_handle: DomHandle,
|
||||
local_name: String,
|
||||
namespace: String,
|
||||
prefix: Option<String>,
|
||||
) -> DomHandle {
|
||||
construction.create_element(
|
||||
self.host.dom_host_mut(),
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
}
|
||||
|
||||
fn add_attrs_if_missing_for_parser(&mut self, node_id: DomHandle, attrs: Vec<Attribute>) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.add_attrs_if_missing_for_parser(node_id, attrs);
|
||||
}
|
||||
|
||||
fn create_text_node(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_text_node_for_document(document_handle, &text)
|
||||
}
|
||||
|
||||
fn create_comment(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_comment_for_document(document_handle, &text)
|
||||
}
|
||||
|
||||
fn create_processing_instruction(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
target: String,
|
||||
data: String,
|
||||
) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_processing_instruction_for_document(document_handle, &target, &data)
|
||||
}
|
||||
|
||||
fn create_cdata_section(&mut self, document_handle: DomHandle, data: String) -> DomHandle {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.create_cdata_section_for_document(document_handle, &data)
|
||||
}
|
||||
|
||||
fn create_document_type(
|
||||
&mut self,
|
||||
document_handle: DomHandle,
|
||||
name: String,
|
||||
public_id: String,
|
||||
system_id: String,
|
||||
) -> DomHandle {
|
||||
self.host.dom_host_mut().create_document_type_for_document(
|
||||
document_handle,
|
||||
&name,
|
||||
&public_id,
|
||||
&system_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn prepend_text_to_text_node(
|
||||
&mut self,
|
||||
node_id: DomHandle,
|
||||
text: String,
|
||||
) -> DomMutationEffects {
|
||||
let host = self.host.dom_host_mut();
|
||||
let Some(previous) = host.node(node_id).and_then(Node::as_text) else {
|
||||
return DomMutationEffects::default();
|
||||
};
|
||||
let mut merged = text;
|
||||
merged.push_str(previous.data());
|
||||
host.set_text_content_effects(node_id, &merged)
|
||||
}
|
||||
|
||||
fn append_text_to_text_node(&mut self, node_id: DomHandle, text: String) -> DomMutationEffects {
|
||||
let host = self.host.dom_host_mut();
|
||||
let Some(previous) = host.node(node_id).and_then(Node::as_text) else {
|
||||
return DomMutationEffects::default();
|
||||
};
|
||||
let mut merged = previous.data().to_owned();
|
||||
merged.push_str(&text);
|
||||
host.set_text_content_effects(node_id, &merged)
|
||||
}
|
||||
|
||||
fn push_parse_error(&mut self, error: String) {
|
||||
self.host.dom_host_mut().push_parse_error(error);
|
||||
}
|
||||
|
||||
fn set_html_quirks_mode_for_parser(&mut self, quirks_mode: QuirksMode) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.set_html_quirks_mode_for_parser_document(self.document_handle, quirks_mode);
|
||||
}
|
||||
|
||||
fn mark_script_already_started_for_parser(&mut self, node_id: DomHandle) {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.set_script_already_started(node_id, true);
|
||||
}
|
||||
|
||||
fn mark_unclosed_form_control_for_parser(&mut self, node_id: DomHandle) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
let _ = self
|
||||
.host
|
||||
.dom_host_mut()
|
||||
.set_blocks_form_submission(node_id, true);
|
||||
}
|
||||
|
||||
fn finish_parsing_children(
|
||||
&mut self,
|
||||
construction: &moli_dom::native::ParserConstruction,
|
||||
node_id: DomHandle,
|
||||
) {
|
||||
if !self.targets_current_document() {
|
||||
return;
|
||||
}
|
||||
let effects = construction.finish_children(self.host.dom_host_mut(), node_id);
|
||||
self.consume_parser_mutation_effects(effects);
|
||||
}
|
||||
|
||||
fn maybe_clone_an_option_into_selectedcontent(&mut self, node_id: DomHandle) {
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
let _ = self
|
||||
.host
|
||||
.sync_selectedcontents_after_parser_option_finished(self.scope, host_ptr, node_id);
|
||||
}
|
||||
|
||||
fn attach_declarative_shadow_for_parser(
|
||||
&mut self,
|
||||
host_id: DomHandle,
|
||||
template_id: DomHandle,
|
||||
attrs: Vec<Attribute>,
|
||||
) -> bool {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.attach_declarative_shadow_for_parser(host_id, template_id, &attrs)
|
||||
}
|
||||
|
||||
fn associate_parser_form_owner(&mut self, target: DomHandle, form: DomHandle) -> bool {
|
||||
self.host
|
||||
.dom_host_mut()
|
||||
.associate_parser_form_owner(target, form)
|
||||
}
|
||||
}
|
||||
|
||||
impl ParserElementCreationConsumer for ContextDocumentParserOwner<'_, '_, '_> {
|
||||
fn create_parser_element(
|
||||
&mut self,
|
||||
request: ParserElementCreationRequest<'_>,
|
||||
) -> Option<DomHandle> {
|
||||
if !self.targets_current_document() {
|
||||
return None;
|
||||
}
|
||||
let context = if let Some(owner) = self.popup_owner {
|
||||
self.host
|
||||
.lightweight_popup_window(self.scope, owner.popup_id())?
|
||||
.get_creation_context(self.scope)?
|
||||
} else {
|
||||
let child_handle = self
|
||||
.host
|
||||
.child_browsing_context_host_for_document_handle(request.document_handle)?;
|
||||
// Keep a child parser lazy until its relevant realm exists.
|
||||
self.host
|
||||
.child_browsing_context_relevant_context(self.scope, child_handle)?
|
||||
};
|
||||
let scope = &mut v8::ContextScope::new(self.scope, context);
|
||||
let host_ptr = self.host as *mut PageScriptHost;
|
||||
custom_elements::create_and_construct_parser_custom_element_direct_for_document(
|
||||
scope,
|
||||
host_ptr,
|
||||
request.document_handle,
|
||||
request.local_name,
|
||||
request.namespace,
|
||||
request.prefix,
|
||||
request.attributes,
|
||||
request.intended_parent,
|
||||
|document_handle, local_name, namespace, prefix| {
|
||||
request.construction.create_element(
|
||||
self.host.dom_host_mut(),
|
||||
document_handle,
|
||||
local_name,
|
||||
namespace,
|
||||
prefix,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ mod child_events;
|
||||
mod child_frame_navigation;
|
||||
mod child_frame_runtime;
|
||||
mod child_runtime_script_order;
|
||||
mod document_parser_owner;
|
||||
pub(crate) use child_frame_runtime::install_child_window_proxy_access_check_handlers;
|
||||
mod child_frame_snapshots;
|
||||
mod child_frames;
|
||||
|
||||
@@ -56,6 +56,12 @@ use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiObject};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use url::Url;
|
||||
|
||||
mod document_stream;
|
||||
mod event_handlers;
|
||||
use document_stream::{PopupDocumentStream, PopupStreamScriptMode};
|
||||
use event_handlers::{
|
||||
PopupWindowContentEventHandlers, clear_lightweight_popup_window_document_event_state,
|
||||
};
|
||||
const LIGHTWEIGHT_POPUP_ID_SLOT: &str = "__lmLightweightPopupId";
|
||||
const LIGHTWEIGHT_POPUP_OPENER_SLOT: &str = "__lmLightweightPopupOpener";
|
||||
const ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT: &str = "__lmActiveLightweightPopupId";
|
||||
@@ -65,8 +71,6 @@ const LIGHTWEIGHT_POPUP_JAVASCRIPT_DOCUMENT_ID_SLOT: &str =
|
||||
const LIGHTWEIGHT_POPUP_JAVASCRIPT_NAVIGATION_ID_SLOT: &str =
|
||||
"__lmLightweightPopupJavascriptNavigationId";
|
||||
const LIGHTWEIGHT_POPUP_JAVASCRIPT_SOURCE_SLOT: &str = "__lmLightweightPopupJavascriptSource";
|
||||
const LIGHTWEIGHT_POPUP_DOCUMENT_WRITE_SESSION_SLOT: &str =
|
||||
"__lmLightweightPopupDocumentWriteSession";
|
||||
const LIGHTWEIGHT_POPUP_VIEWPORT_SURFACE_PROPERTIES: &[&str] = &[
|
||||
"innerWidth",
|
||||
"innerHeight",
|
||||
@@ -236,8 +240,9 @@ struct LightweightPopupClassicScriptContinuation {
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
document_handle: DomHandle,
|
||||
document_url: Url,
|
||||
scripts: Vec<DomHandle>,
|
||||
next_script_index: usize,
|
||||
stream_script: Option<(PopupStreamScriptMode, crate::parser::PreparedScript)>,
|
||||
parser_steps: Vec<LightweightPopupParserStep>,
|
||||
next_step_index: usize,
|
||||
response_content_security_policies: Vec<ContentSecurityPolicy>,
|
||||
response_content_security_report_only_policies: Vec<ContentSecurityPolicy>,
|
||||
response_content_security_reporting_endpoints:
|
||||
@@ -414,6 +419,8 @@ struct LightweightPopupDocumentRecord {
|
||||
wrapper: Option<v8::Global<v8::Object>>,
|
||||
handle: Option<DomHandle>,
|
||||
script_globals: HashMap<String, v8::Global<v8::Value>>,
|
||||
stream: Option<PopupDocumentStream>,
|
||||
content_event_handlers: PopupWindowContentEventHandlers,
|
||||
incomplete_child_frame_loads: HashSet<DomHandle>,
|
||||
dom_content_loaded: PopupDomContentLoadedState,
|
||||
pending_load_event: Option<LightweightPopupNavigationTaskToken>,
|
||||
@@ -1092,6 +1099,8 @@ impl PageScriptHost {
|
||||
wrapper: None,
|
||||
handle: None,
|
||||
script_globals: HashMap::new(),
|
||||
stream: None,
|
||||
content_event_handlers: PopupWindowContentEventHandlers::default(),
|
||||
incomplete_child_frame_loads: HashSet::new(),
|
||||
dom_content_loaded: PopupDomContentLoadedState::NotRequired,
|
||||
pending_load_event: None,
|
||||
@@ -2194,7 +2203,7 @@ impl PageScriptHost {
|
||||
&& self.lightweight_popup_navigation_id(task.popup_id()) == Some(task.navigation_id)
|
||||
}
|
||||
|
||||
fn lightweight_popup_committed_navigation_task_is_current(
|
||||
pub(crate) fn lightweight_popup_committed_navigation_task_is_current(
|
||||
&self,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
) -> bool {
|
||||
@@ -2329,6 +2338,8 @@ impl PageScriptHost {
|
||||
wrapper: None,
|
||||
handle: None,
|
||||
script_globals: HashMap::new(),
|
||||
stream: None,
|
||||
content_event_handlers: PopupWindowContentEventHandlers::default(),
|
||||
incomplete_child_frame_loads: HashSet::new(),
|
||||
dom_content_loaded: PopupDomContentLoadedState::NotRequired,
|
||||
pending_load_event: None,
|
||||
@@ -3723,8 +3734,9 @@ impl PageScriptHost {
|
||||
task,
|
||||
document_handle,
|
||||
document_url: document.url.clone(),
|
||||
scripts: self.dom_host().script_handles_in_subtree(document_handle),
|
||||
next_script_index: 0,
|
||||
stream_script: None,
|
||||
parser_steps,
|
||||
next_step_index: 0,
|
||||
response_content_security_policies: response_content_security_policies.to_vec(),
|
||||
response_content_security_report_only_policies:
|
||||
response_content_security_report_only_policies.to_vec(),
|
||||
@@ -3763,14 +3775,25 @@ impl PageScriptHost {
|
||||
let script_type = self
|
||||
.child_document_native_script_attribute(script, "type")
|
||||
.unwrap_or_default();
|
||||
if !script_type.is_empty()
|
||||
if continuation.stream_script.is_none()
|
||||
&& !script_type.is_empty()
|
||||
&& !script_type.eq_ignore_ascii_case("text/javascript")
|
||||
&& !script_type.eq_ignore_ascii_case("application/javascript")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let script_src = self.child_document_native_script_attribute(script, "src");
|
||||
let script_src = match continuation
|
||||
.stream_script
|
||||
.as_ref()
|
||||
.map(|(_, prepared)| prepared)
|
||||
{
|
||||
Some(prepared) => {
|
||||
matches!(prepared.source, crate::planning::ScriptSource::External)
|
||||
.then(|| prepared.url.to_string())
|
||||
}
|
||||
None => self.child_document_native_script_attribute(script, "src"),
|
||||
};
|
||||
let source = if let Some(src) = script_src.as_deref() {
|
||||
if src.is_empty() {
|
||||
continue;
|
||||
@@ -3779,7 +3802,12 @@ impl PageScriptHost {
|
||||
.lightweight_popup_document_record(popup_id)
|
||||
.map(|document| &document.state.base_url)
|
||||
.unwrap_or(&continuation.document_url);
|
||||
let Ok(script_url) = Url::options().base_url(Some(base_url)).parse(src) else {
|
||||
let Some(script_url) = continuation
|
||||
.stream_script
|
||||
.as_ref()
|
||||
.map(|(_, script)| script.url.clone())
|
||||
.or_else(|| Url::options().base_url(Some(base_url)).parse(src).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(violation) = unsafe { &*self.document_runtime }
|
||||
@@ -3817,8 +3845,9 @@ impl PageScriptHost {
|
||||
continue;
|
||||
}
|
||||
self.mark_child_document_native_script_already_started(script);
|
||||
if let Some(source) =
|
||||
self.materialize_local_lightweight_popup_script_source(&script_url)
|
||||
if continuation.stream_script.is_none()
|
||||
&& let Some(source) =
|
||||
self.materialize_local_lightweight_popup_script_source(&script_url)
|
||||
{
|
||||
source
|
||||
} else {
|
||||
@@ -3836,6 +3865,26 @@ impl PageScriptHost {
|
||||
);
|
||||
return LightweightPopupClassicScriptAdvance::Pending(body_activity);
|
||||
}
|
||||
} else if let Some((_, prepared)) = &continuation.stream_script {
|
||||
let crate::planning::ScriptSource::Inline(source) = &prepared.source else {
|
||||
continue;
|
||||
};
|
||||
let Some(source) =
|
||||
crate::native_bridge::element::inline_script_source_for_execution(
|
||||
scope,
|
||||
self as *mut PageScriptHost,
|
||||
script,
|
||||
source,
|
||||
crate::content_security_policy::ContentSecurityPolicyScriptElementRequest {
|
||||
nonce: prepared.fetch_metadata.nonce.as_deref(),
|
||||
integrity: prepared.fetch_metadata.integrity.as_deref(),
|
||||
parser_inserted: true,
|
||||
},
|
||||
)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
source
|
||||
} else {
|
||||
self.child_document_native_script_text_content(script)
|
||||
};
|
||||
@@ -3844,6 +3893,7 @@ impl PageScriptHost {
|
||||
continue;
|
||||
}
|
||||
if script_src.is_none()
|
||||
&& continuation.stream_script.is_none()
|
||||
&& let Some(violation) = unsafe { &*self.document_runtime }
|
||||
.inline_script_csp_report_only_violation_for_document(
|
||||
&continuation.document_url,
|
||||
@@ -3860,6 +3910,7 @@ impl PageScriptHost {
|
||||
}
|
||||
}
|
||||
if script_src.is_none()
|
||||
&& continuation.stream_script.is_none()
|
||||
&& let Some(violation) = unsafe { &*self.document_runtime }
|
||||
.inline_script_csp_violation_for_document(
|
||||
Some(continuation.document_handle),
|
||||
@@ -3888,6 +3939,7 @@ impl PageScriptHost {
|
||||
script,
|
||||
&continuation.document_url,
|
||||
&source,
|
||||
continuation.stream_script.as_ref().map(|(mode, _)| *mode),
|
||||
);
|
||||
}
|
||||
LightweightPopupClassicScriptAdvance::Completed(body_activity)
|
||||
@@ -3900,8 +3952,22 @@ impl PageScriptHost {
|
||||
script: DomHandle,
|
||||
document_url: &Url,
|
||||
source: &str,
|
||||
stream_mode: Option<PopupStreamScriptMode>,
|
||||
) {
|
||||
let popup_id = task.popup_id();
|
||||
let insertion = (stream_mode == Some(PopupStreamScriptMode::Blocking))
|
||||
.then(|| self.popup_document_stream_insertion(popup_id))
|
||||
.flatten();
|
||||
let _nesting = insertion
|
||||
.as_ref()
|
||||
.map(|insertion| insertion.control_handle().enter_parser_script_nesting());
|
||||
let _input = insertion
|
||||
.as_ref()
|
||||
.map(|insertion| insertion.enter_script_input_context());
|
||||
let _ignore_writes = stream_mode
|
||||
.filter(|mode| *mode != PopupStreamScriptMode::Blocking)
|
||||
.and_then(|_| self.lightweight_popup_document_handle(popup_id))
|
||||
.map(|document| self.enter_ignore_destructive_writes(document));
|
||||
let Some(window) = self.lightweight_popup_window(scope, popup_id) else {
|
||||
return;
|
||||
};
|
||||
@@ -3998,6 +4064,10 @@ impl PageScriptHost {
|
||||
request: Request,
|
||||
) {
|
||||
let task = continuation.task;
|
||||
let local_source = continuation
|
||||
.stream_script
|
||||
.as_ref()
|
||||
.and_then(|_| self.materialize_local_lightweight_popup_script_source(&script_url));
|
||||
let load_id = self.next_lightweight_popup_classic_script_load_id;
|
||||
self.next_lightweight_popup_classic_script_load_id = self
|
||||
.next_lightweight_popup_classic_script_load_id
|
||||
@@ -4019,6 +4089,13 @@ impl PageScriptHost {
|
||||
let completion_tx = self.resource_completion_tx.clone();
|
||||
loader.spawn_resource_task(async move {
|
||||
let result = async {
|
||||
if let Some(source) = local_source {
|
||||
return Ok(LoadedChildScriptSource {
|
||||
final_url: script_url.clone(),
|
||||
redirected: false,
|
||||
source,
|
||||
});
|
||||
}
|
||||
let response = request_client
|
||||
.fetch_text_stream_with_cancel(request, cancel_handle)
|
||||
.await
|
||||
@@ -4068,6 +4145,16 @@ impl PageScriptHost {
|
||||
let mut body_activity = PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch;
|
||||
let task = pending.continuation.task;
|
||||
let popup_id = task.popup_id();
|
||||
let stream_mode = pending
|
||||
.continuation
|
||||
.stream_script
|
||||
.as_ref()
|
||||
.map(|(mode, _)| *mode);
|
||||
if let Some(mode) = stream_mode
|
||||
&& !self.prepare_popup_document_stream_script_resume(task, mode)
|
||||
{
|
||||
return PopupClassicScriptLoadApplication::NotApplied;
|
||||
}
|
||||
|
||||
match completion.result {
|
||||
Ok(fetched_source) => {
|
||||
@@ -4100,6 +4187,7 @@ impl PageScriptHost {
|
||||
pending.script_handle,
|
||||
&pending.continuation.document_url,
|
||||
&fetched_source.source,
|
||||
stream_mode,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4113,6 +4201,13 @@ impl PageScriptHost {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mode) = stream_mode {
|
||||
self.resume_popup_document_stream_script(scope, task, mode);
|
||||
return PopupClassicScriptLoadApplication::Applied {
|
||||
body_activity,
|
||||
parser_completion: None,
|
||||
};
|
||||
}
|
||||
if !self.lightweight_popup_committed_navigation_task_is_current(task) {
|
||||
return PopupClassicScriptLoadApplication::Applied {
|
||||
body_activity,
|
||||
@@ -4822,6 +4917,10 @@ impl PageScriptHost {
|
||||
)
|
||||
&& document.queued_load_event.is_none()
|
||||
&& document.incomplete_child_frame_loads.is_empty()
|
||||
&& document
|
||||
.stream
|
||||
.as_ref()
|
||||
.is_none_or(|stream| stream.async_loads_finished())
|
||||
&& !self
|
||||
.pending_lightweight_popup_classic_script_loads
|
||||
.values()
|
||||
@@ -5686,114 +5785,6 @@ fn lightweight_popup_location_href<'s>(
|
||||
Url::parse(&href).ok()
|
||||
}
|
||||
|
||||
fn lightweight_popup_document_write_session_active<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
document: v8::Local<'s, v8::Object>,
|
||||
) -> bool {
|
||||
get_private_value(
|
||||
scope,
|
||||
document,
|
||||
LIGHTWEIGHT_POPUP_DOCUMENT_WRITE_SESSION_SLOT,
|
||||
)
|
||||
.is_some_and(|value| value.boolean_value(scope))
|
||||
}
|
||||
|
||||
fn set_lightweight_popup_document_write_session<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
document: v8::Local<'s, v8::Object>,
|
||||
active: bool,
|
||||
) {
|
||||
let value = v8::Boolean::new(scope, active);
|
||||
set_private_value(
|
||||
scope,
|
||||
document,
|
||||
LIGHTWEIGHT_POPUP_DOCUMENT_WRITE_SESSION_SLOT,
|
||||
value.into(),
|
||||
);
|
||||
}
|
||||
|
||||
impl PageScriptHost {
|
||||
pub(in crate::native_bridge) fn open_lightweight_popup_document_stream<'s>(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
document: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
debug_assert!(std::ptr::eq(host_ptr, self));
|
||||
let owner = self
|
||||
.lightweight_popup_id_for_document_handle(document_handle)
|
||||
.and_then(|popup_id| self.current_lightweight_popup_document_owner(popup_id));
|
||||
let entry_document = self.document_open_entry_document(scope);
|
||||
// Erase the current shadow-including tree before disconnecting it.
|
||||
// Popup Windows have their own listener store despite sharing a V8
|
||||
// realm with the opener; do not clear other Windows in that realm.
|
||||
self.clear_event_callbacks_for_document_replacement(document_handle, false);
|
||||
if let Some(window) =
|
||||
owner.and_then(|owner| self.lightweight_popup_window(scope, owner.popup_id()))
|
||||
{
|
||||
clear_lightweight_popup_window_document_event_state(scope, window);
|
||||
}
|
||||
crate::native_bridge::document::set_detached_html_document_body_html(
|
||||
scope,
|
||||
host_ptr,
|
||||
document_handle,
|
||||
"",
|
||||
);
|
||||
unsafe { &*host_ptr }
|
||||
.reset_meta_content_security_policy_processing_for_document(document_handle);
|
||||
set_lightweight_popup_document_write_session(scope, document, true);
|
||||
if let Some(owner) = owner
|
||||
&& self.lightweight_popup_document_owner_is_current(owner)
|
||||
&& let Some(entry_document) = entry_document
|
||||
{
|
||||
let popup_id = owner.popup_id();
|
||||
let url = self.document_open_replacement_url(document_handle, entry_document);
|
||||
self.set_lightweight_popup_same_document_url(scope, popup_id, url.clone());
|
||||
if let Some(window) = self.lightweight_popup_window(scope, popup_id) {
|
||||
// Publish native state before the history update can dispatch
|
||||
// author callbacks that perform another URL change.
|
||||
crate::context_bootstrap::update_history_for_document_open(scope, window, &url);
|
||||
}
|
||||
// Initial about:blank suppresses Navigation API events during
|
||||
// the URL/history update. Clear it only after that update.
|
||||
if let Some(record) = self.lightweight_popup_document_record_mut(popup_id)
|
||||
&& record.owner == owner
|
||||
{
|
||||
record.is_initial_empty_document = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn write_lightweight_popup_document_stream<'s>(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
document: v8::Local<'s, v8::Object>,
|
||||
html: &str,
|
||||
) {
|
||||
debug_assert!(std::ptr::eq(host_ptr, self));
|
||||
if !lightweight_popup_document_write_session_active(scope, document) {
|
||||
self.open_lightweight_popup_document_stream(scope, host_ptr, document_handle, document);
|
||||
}
|
||||
crate::native_bridge::document::append_detached_html_document_body_html(
|
||||
scope,
|
||||
host_ptr,
|
||||
document_handle,
|
||||
html,
|
||||
);
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn close_lightweight_popup_document_stream<'s>(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
document: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
set_lightweight_popup_document_write_session(scope, document, false);
|
||||
}
|
||||
}
|
||||
|
||||
fn lightweight_popup_javascript_url_callback<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
use super::*;
|
||||
use crate::{
|
||||
custom_elements,
|
||||
dom::native::DocumentReadyState,
|
||||
live_document_parser::{
|
||||
DocumentParserCloseDisposition, DocumentParserLifetime, DocumentParserRunState,
|
||||
DocumentParserSession, LiveDocumentParserStepOutcome, ParserInsertionHandle,
|
||||
ParserStopReason, ParserSuspensionCause,
|
||||
},
|
||||
native_bridge::context_host::document_parser_owner::ContextDocumentParserOwner,
|
||||
parser::{ParserScriptHandoff, PreparedScript},
|
||||
types::ScriptKind,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum PopupStreamScriptMode {
|
||||
Blocking,
|
||||
Async,
|
||||
Deferred,
|
||||
}
|
||||
|
||||
pub(super) struct PopupDocumentStream {
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
control: crate::live_document_parser::DocumentParserSessionControlHandle,
|
||||
parser: Option<DocumentParserSession>,
|
||||
deferred: std::collections::VecDeque<PreparedScript>,
|
||||
deferred_pending: bool,
|
||||
async_pending: usize,
|
||||
}
|
||||
|
||||
impl PopupDocumentStream {
|
||||
pub(super) fn async_loads_finished(&self) -> bool {
|
||||
self.async_pending == 0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PopupDocumentStream {
|
||||
fn drop(&mut self) {
|
||||
// EOF can synchronously construct an element whose callback opens a
|
||||
// replacement stream. The old finishing owner detects that replacement;
|
||||
// let its already-admitted finish transition unwind normally.
|
||||
if self.control.run_state() != DocumentParserRunState::Finishing {
|
||||
self.control.stop(ParserStopReason::DocumentReplacement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PageScriptHost {
|
||||
pub(in crate::native_bridge::context_host) fn popup_document_parser_is_current(
|
||||
&self,
|
||||
owner: LightweightPopupDocumentOwner,
|
||||
session: crate::live_document_parser::ParserSessionId,
|
||||
) -> bool {
|
||||
self.lightweight_popup_document_record(owner.popup_id())
|
||||
.and_then(|record| record.stream.as_ref())
|
||||
.is_some_and(|stream| {
|
||||
stream.control.session_id() == session
|
||||
&& self.popup_document_stream_is_current(stream.task)
|
||||
})
|
||||
}
|
||||
|
||||
fn popup_document_stream_is_current(&self, task: LightweightPopupNavigationTaskToken) -> bool {
|
||||
self.lightweight_popup_document_owner_is_current(task.document_owner())
|
||||
&& self.lightweight_popup_navigation_id(task.popup_id()) == Some(task.navigation_id)
|
||||
&& self
|
||||
.lightweight_popup_document_record(task.popup_id())
|
||||
.and_then(|record| record.stream.as_ref())
|
||||
.is_some_and(|stream| stream.task == task)
|
||||
}
|
||||
|
||||
pub(super) fn popup_document_stream_insertion(
|
||||
&self,
|
||||
popup_id: u64,
|
||||
) -> Option<ParserInsertionHandle> {
|
||||
let stream = self
|
||||
.lightweight_popup_document_record(popup_id)?
|
||||
.stream
|
||||
.as_ref()?;
|
||||
self.popup_document_stream_is_current(stream.task)
|
||||
.then(|| stream.parser.as_ref()?.insertion_handle())
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn open_lightweight_popup_document_stream(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
) {
|
||||
let Some(popup_id) = self.lightweight_popup_id_for_document_handle(document_handle) else {
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.popup_document_stream_insertion(popup_id)
|
||||
.is_some_and(|insertion| insertion.control_handle().parser_script_nesting_level() != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(owner) = self.current_lightweight_popup_document_owner(popup_id) else {
|
||||
return;
|
||||
};
|
||||
let entry_document = self.document_open_entry_document(scope);
|
||||
self.dispatch_document_open_descendant_frame_unload_lifecycle(scope, document_handle);
|
||||
if !self.lightweight_popup_document_owner_is_current(owner) {
|
||||
return;
|
||||
}
|
||||
let url = entry_document
|
||||
.map(|entry| self.document_open_replacement_url(document_handle, entry))
|
||||
.unwrap_or_else(|| self.document_url_for_handle(document_handle));
|
||||
let Some(task) = self.start_lightweight_popup_navigation_attempt(
|
||||
popup_id,
|
||||
self.document_url_for_handle(document_handle),
|
||||
LightweightPopupNavigationDocumentTarget::CurrentDocument,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.clear_event_callbacks_for_document_replacement(document_handle, false);
|
||||
if let Some(window) = self.lightweight_popup_window(scope, popup_id) {
|
||||
clear_lightweight_popup_window_document_event_state(scope, window);
|
||||
}
|
||||
let scripting_enabled = self.lightweight_popup_scripting_enabled(popup_id);
|
||||
custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| {
|
||||
let host = unsafe { &mut *host_ptr };
|
||||
// Drop the old session before removal callbacks can write again.
|
||||
host.lightweight_popup_document_record_mut(popup_id)
|
||||
.expect("current popup")
|
||||
.stream = None;
|
||||
host.remove_all_children_for_document_replacement(scope, host_ptr, document_handle);
|
||||
host.set_lightweight_popup_same_document_url(scope, popup_id, url.clone());
|
||||
host.dom_host_mut()
|
||||
.set_html_quirks_mode_for_parser_document(
|
||||
document_handle,
|
||||
html5ever::tree_builder::QuirksMode::NoQuirks,
|
||||
);
|
||||
let parser = DocumentParserSession::start_open_live_document(
|
||||
url.clone(),
|
||||
document_handle,
|
||||
scripting_enabled,
|
||||
);
|
||||
let record = host
|
||||
.lightweight_popup_document_record_mut(popup_id)
|
||||
.expect("current popup");
|
||||
record.stream = Some(PopupDocumentStream {
|
||||
task,
|
||||
control: parser.control_handle(),
|
||||
parser: Some(parser),
|
||||
deferred: Default::default(),
|
||||
deferred_pending: false,
|
||||
async_pending: 0,
|
||||
});
|
||||
record.dom_content_loaded = PopupDomContentLoadedState::Parsing;
|
||||
record.pending_load_event = None;
|
||||
record.queued_load_event = None;
|
||||
record.load_event_dispatched = false;
|
||||
record.incomplete_child_frame_loads.clear();
|
||||
host.set_dom_document_ready_state_for_handle(
|
||||
document_handle,
|
||||
DocumentReadyState::Loading,
|
||||
);
|
||||
if let Some(window) = host.lightweight_popup_window(scope, popup_id) {
|
||||
crate::context_bootstrap::update_history_for_document_open(scope, window, &url);
|
||||
}
|
||||
if host.popup_document_stream_is_current(task) {
|
||||
host.lightweight_popup_document_record_mut(popup_id)
|
||||
.expect("current popup")
|
||||
.is_initial_empty_document = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn write_lightweight_popup_document_stream(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
html: &str,
|
||||
) {
|
||||
let Some(popup_id) = self.lightweight_popup_id_for_document_handle(document_handle) else {
|
||||
return;
|
||||
};
|
||||
if self.has_ignore_destructive_writes_counter(document_handle) {
|
||||
return;
|
||||
}
|
||||
if self.popup_document_stream_insertion(popup_id).is_none() {
|
||||
if self.has_document_unload_counter(document_handle) {
|
||||
return;
|
||||
}
|
||||
self.open_lightweight_popup_document_stream(scope, host_ptr, document_handle);
|
||||
}
|
||||
let Some(task) = self
|
||||
.lightweight_popup_document_record(popup_id)
|
||||
.and_then(|record| record.stream.as_ref())
|
||||
.map(|stream| stream.task)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.pump_popup_document_stream(scope, task, Some(html), false);
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn close_lightweight_popup_document_stream(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
document_handle: DomHandle,
|
||||
) {
|
||||
let Some(task) = self
|
||||
.lightweight_popup_id_for_document_handle(document_handle)
|
||||
.and_then(|id| self.lightweight_popup_document_record(id))
|
||||
.and_then(|record| record.stream.as_ref())
|
||||
.map(|stream| stream.task)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.pump_popup_document_stream(scope, task, None, true);
|
||||
}
|
||||
|
||||
fn pump_popup_document_stream(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
html: Option<&str>,
|
||||
close: bool,
|
||||
) {
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
let popup_id = task.popup_id();
|
||||
let Some(insertion) = self.popup_document_stream_insertion(popup_id) else {
|
||||
return;
|
||||
};
|
||||
let document_handle = self
|
||||
.lightweight_popup_document_handle(popup_id)
|
||||
.expect("parser Document");
|
||||
let control = insertion.control_handle();
|
||||
let in_script = control.parser_script_nesting_level() != 0;
|
||||
let nested_pump = matches!(
|
||||
insertion.run_state(),
|
||||
DocumentParserRunState::Pumping { .. }
|
||||
);
|
||||
let ready = if close {
|
||||
insertion.request_close() == DocumentParserCloseDisposition::DrainNow && !in_script
|
||||
} else {
|
||||
matches!(
|
||||
insertion.run_state(),
|
||||
DocumentParserRunState::Ready | DocumentParserRunState::Pumping { .. }
|
||||
)
|
||||
};
|
||||
if let Some(html) = html {
|
||||
if nested_pump && !in_script {
|
||||
insertion.append_at_current_insertion_point(html);
|
||||
} else if ready {
|
||||
// A runnable nested write needs a fresh input frame ahead of
|
||||
// the suspended outer tail, just like a child parser write.
|
||||
insertion.enqueue_script_input_html(html.to_owned());
|
||||
} else if in_script {
|
||||
if !insertion.append_to_current_script_input(html) {
|
||||
insertion.enqueue_script_input_html(html.to_owned());
|
||||
}
|
||||
} else {
|
||||
insertion.queue_arrived_chunk(html.to_owned());
|
||||
}
|
||||
}
|
||||
if !ready {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
if !self.popup_document_stream_is_current(task)
|
||||
|| matches!(control.run_state(), DocumentParserRunState::Stopped(_))
|
||||
{
|
||||
insertion.stop(ParserStopReason::DocumentReplacement);
|
||||
return;
|
||||
}
|
||||
if insertion.is_suspended() {
|
||||
return;
|
||||
}
|
||||
let outcome = {
|
||||
let mut owner = ContextDocumentParserOwner::new_popup(
|
||||
self,
|
||||
scope,
|
||||
document_handle,
|
||||
task.document_owner(),
|
||||
control.clone(),
|
||||
);
|
||||
insertion.advance_queued_or_resume_step(&mut owner)
|
||||
};
|
||||
// A parser mutation can invoke a custom element callback which
|
||||
// replaces the stream and drops the old insertion controller.
|
||||
if !self.popup_document_stream_is_current(task)
|
||||
|| matches!(control.run_state(), DocumentParserRunState::Stopped(_))
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Native parser mutations deliver meta policies and maintain frame
|
||||
// ownership before a script preparation checkpoint can run.
|
||||
let _ = insertion.take_discovery_signals();
|
||||
let outcome = if let LiveDocumentParserStepOutcome::ScriptPreparation(request) = outcome
|
||||
{
|
||||
if request.needs_microtask_checkpoint() {
|
||||
let _ =
|
||||
crate::script_cleanup::perform_parser_script_preparation_checkpoint(scope);
|
||||
}
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
let mut owner = ContextDocumentParserOwner::new_popup(
|
||||
self,
|
||||
scope,
|
||||
document_handle,
|
||||
task.document_owner(),
|
||||
control.clone(),
|
||||
);
|
||||
LiveDocumentParserStepOutcome::ScriptHandoff(Box::new(
|
||||
insertion.prepare_script(*request, &mut owner),
|
||||
))
|
||||
} else {
|
||||
outcome
|
||||
};
|
||||
match outcome {
|
||||
LiveDocumentParserStepOutcome::InputBoundary => {
|
||||
if in_script || nested_pump {
|
||||
return;
|
||||
}
|
||||
if !insertion.input_is_empty() {
|
||||
continue;
|
||||
}
|
||||
if insertion.lifetime() == DocumentParserLifetime::Closing {
|
||||
let Some(mut parser) = self
|
||||
.lightweight_popup_document_record_mut(popup_id)
|
||||
.and_then(|record| record.stream.as_mut())
|
||||
.and_then(|stream| stream.parser.take())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
parser.request_finish();
|
||||
let _ = parser.admit_delayed_finish_at_local_owner_boundary();
|
||||
let mut owner = ContextDocumentParserOwner::new_popup(
|
||||
self,
|
||||
scope,
|
||||
document_handle,
|
||||
task.document_owner(),
|
||||
control.clone(),
|
||||
);
|
||||
let signals = parser.finish(&mut owner);
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
custom_elements::apply_parser_created_null_registry_associations(
|
||||
self,
|
||||
&signals.parser_created_null_registry_elements,
|
||||
);
|
||||
self.finish_popup_document_stream(scope, task);
|
||||
}
|
||||
return;
|
||||
}
|
||||
LiveDocumentParserStepOutcome::CustomElementConstructionHandoff(handoff) => {
|
||||
let host_ptr = self as *mut PageScriptHost;
|
||||
let _ =
|
||||
custom_elements::construct_parser_created_autonomous_element_from_handoff(
|
||||
scope, host_ptr, &handoff,
|
||||
);
|
||||
custom_elements::flush_parser_custom_element_handoff_replacements(
|
||||
scope, host_ptr,
|
||||
);
|
||||
}
|
||||
LiveDocumentParserStepOutcome::ScriptHandoff(handoff) => {
|
||||
let (mode, script) = match *handoff {
|
||||
ParserScriptHandoff::BlockingClassic { script, .. } => {
|
||||
(PopupStreamScriptMode::Blocking, script)
|
||||
}
|
||||
ParserScriptHandoff::AsyncPostParse { script, .. } => {
|
||||
(PopupStreamScriptMode::Async, script)
|
||||
}
|
||||
ParserScriptHandoff::NonAsyncPostParse { script, .. } => {
|
||||
(PopupStreamScriptMode::Deferred, script)
|
||||
}
|
||||
other => {
|
||||
crate::host::apply_parser_script_element_state_without_execution(
|
||||
self.dom_host_mut(),
|
||||
&other,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Preparation starts the element even when CSP prevents
|
||||
// execution or the script waits in the deferred queue.
|
||||
self.dom_host_mut()
|
||||
.set_script_already_started(script.node_id, true);
|
||||
if script.kind != ScriptKind::Classic {
|
||||
continue;
|
||||
}
|
||||
if mode == PopupStreamScriptMode::Deferred {
|
||||
self.lightweight_popup_document_record_mut(popup_id)
|
||||
.expect("current stream")
|
||||
.stream
|
||||
.as_mut()
|
||||
.expect("current stream")
|
||||
.deferred
|
||||
.push_back(script);
|
||||
} else if self.run_popup_document_stream_script(scope, task, mode, script)
|
||||
&& mode == PopupStreamScriptMode::Blocking
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
LiveDocumentParserStepOutcome::BlockingStylesheetPause(_) => {}
|
||||
LiveDocumentParserStepOutcome::ScriptPreparation(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_popup_document_stream_script(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
mode: PopupStreamScriptMode,
|
||||
script: PreparedScript,
|
||||
) -> bool {
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return false;
|
||||
}
|
||||
let record = self
|
||||
.lightweight_popup_document_record(task.popup_id())
|
||||
.expect("current stream");
|
||||
let handle = record.handle.expect("parser Document");
|
||||
let script_handle = script.node_id;
|
||||
let continuation = LightweightPopupClassicScriptContinuation {
|
||||
task,
|
||||
document_handle: handle,
|
||||
document_url: record.url.clone(),
|
||||
parser_steps: vec![LightweightPopupParserStep::Script(script.node_id)],
|
||||
next_step_index: 0,
|
||||
stream_script: Some((mode, script)),
|
||||
response_content_security_policies: record
|
||||
.state
|
||||
.policy_container
|
||||
.response_content_security_policies
|
||||
.clone(),
|
||||
response_content_security_report_only_policies: record
|
||||
.state
|
||||
.policy_container
|
||||
.response_content_security_report_only_policies
|
||||
.clone(),
|
||||
response_content_security_reporting_endpoints: record
|
||||
.state
|
||||
.policy_container
|
||||
.content_security_reporting_endpoints
|
||||
.clone(),
|
||||
};
|
||||
let pending = matches!(
|
||||
self.advance_lightweight_popup_classic_scripts(
|
||||
scope,
|
||||
continuation,
|
||||
PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch
|
||||
),
|
||||
LightweightPopupClassicScriptAdvance::Pending(_)
|
||||
);
|
||||
if pending && self.popup_document_stream_is_current(task) {
|
||||
let stream = self
|
||||
.lightweight_popup_document_record_mut(task.popup_id())
|
||||
.expect("current stream")
|
||||
.stream
|
||||
.as_mut()
|
||||
.expect("current stream");
|
||||
match mode {
|
||||
PopupStreamScriptMode::Blocking => {
|
||||
stream.parser.as_mut().expect("blocking parser").suspend(
|
||||
ParserSuspensionCause::DocumentWriteExternalScript {
|
||||
script: script_handle,
|
||||
},
|
||||
);
|
||||
}
|
||||
PopupStreamScriptMode::Async => stream.async_pending += 1,
|
||||
PopupStreamScriptMode::Deferred => stream.deferred_pending = true,
|
||||
}
|
||||
}
|
||||
pending
|
||||
}
|
||||
|
||||
fn finish_popup_document_stream(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
) {
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
if let Some(window) = self.current_popup_window_event_target(task.popup_id()) {
|
||||
self.dispatch_lightweight_popup_document_readiness(
|
||||
scope,
|
||||
window,
|
||||
DocumentReadyState::Interactive,
|
||||
);
|
||||
}
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
let stream = self
|
||||
.lightweight_popup_document_record_mut(task.popup_id())
|
||||
.expect("current stream")
|
||||
.stream
|
||||
.as_mut()
|
||||
.expect("current stream");
|
||||
if stream.parser.is_some() || stream.deferred_pending {
|
||||
return;
|
||||
}
|
||||
let Some(script) = stream.deferred.pop_front() else {
|
||||
break;
|
||||
};
|
||||
if self.run_popup_document_stream_script(
|
||||
scope,
|
||||
task,
|
||||
PopupStreamScriptMode::Deferred,
|
||||
script,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(completion) = self.prepare_lightweight_popup_parser_completion(task)
|
||||
&& self.begin_lightweight_popup_interactive(scope, completion)
|
||||
{
|
||||
self.finish_lightweight_popup_interactive(completion);
|
||||
}
|
||||
if self.popup_document_stream_is_current(task)
|
||||
&& let Some(window) = self.current_popup_window_event_target(task.popup_id())
|
||||
{
|
||||
self.dispatch_lightweight_popup_document_readiness(
|
||||
scope,
|
||||
window,
|
||||
DocumentReadyState::Complete,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resume_popup_document_stream_script(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
mode: PopupStreamScriptMode,
|
||||
) {
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return;
|
||||
}
|
||||
let stream = self
|
||||
.lightweight_popup_document_record_mut(task.popup_id())
|
||||
.expect("current stream")
|
||||
.stream
|
||||
.as_mut()
|
||||
.expect("current stream");
|
||||
match mode {
|
||||
PopupStreamScriptMode::Blocking => {
|
||||
self.pump_popup_document_stream(scope, task, None, false)
|
||||
}
|
||||
PopupStreamScriptMode::Deferred => {
|
||||
stream.deferred_pending = false;
|
||||
self.finish_popup_document_stream(scope, task);
|
||||
}
|
||||
PopupStreamScriptMode::Async => {
|
||||
stream.async_pending -= 1;
|
||||
self.publish_lightweight_popup_load_event_if_ready(task.popup_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_popup_document_stream_script_resume(
|
||||
&mut self,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
mode: PopupStreamScriptMode,
|
||||
) -> bool {
|
||||
if !self.popup_document_stream_is_current(task) {
|
||||
return false;
|
||||
}
|
||||
if mode == PopupStreamScriptMode::Blocking {
|
||||
let parser = self
|
||||
.lightweight_popup_document_record_mut(task.popup_id())
|
||||
.expect("current stream")
|
||||
.stream
|
||||
.as_mut()
|
||||
.expect("current stream")
|
||||
.parser
|
||||
.as_mut()
|
||||
.expect("blocking parser");
|
||||
let Some(permit) = parser.current_resume_permit() else {
|
||||
return false;
|
||||
};
|
||||
return parser.resume(permit);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -280,9 +280,6 @@ pub(super) use hit_test::{
|
||||
node_document_elements_from_point_callback, node_shadow_root_element_from_point_callback,
|
||||
node_shadow_root_elements_from_point_callback,
|
||||
};
|
||||
pub(in crate::native_bridge) use lifecycle::{
|
||||
append_detached_html_document_body_html, set_detached_html_document_body_html,
|
||||
};
|
||||
pub(super) use lifecycle::{
|
||||
node_document_close_callback, node_document_exec_command_callback, node_document_open_callback,
|
||||
node_document_query_command_enabled_callback, node_document_query_command_indeterm_callback,
|
||||
|
||||
@@ -136,7 +136,6 @@ fn node_document_write_or_writeln_callback<'s>(
|
||||
scope,
|
||||
runtime_ptr,
|
||||
handle,
|
||||
args.this(),
|
||||
&html,
|
||||
);
|
||||
rv.set_undefined();
|
||||
@@ -301,7 +300,6 @@ pub(in crate::native_bridge) fn node_document_open_callback<'s>(
|
||||
scope,
|
||||
runtime_ptr,
|
||||
handle,
|
||||
args.this(),
|
||||
);
|
||||
rv.set(args.this().into());
|
||||
return;
|
||||
@@ -545,8 +543,7 @@ pub(in crate::native_bridge) fn node_document_close_callback<'s>(
|
||||
.lightweight_popup_id_for_document_handle(handle)
|
||||
.is_some()
|
||||
{
|
||||
unsafe { &mut *runtime_ptr }
|
||||
.close_lightweight_popup_document_stream(scope, args.this());
|
||||
unsafe { &mut *runtime_ptr }.close_lightweight_popup_document_stream(scope, handle);
|
||||
rv.set_undefined();
|
||||
return;
|
||||
}
|
||||
@@ -623,55 +620,6 @@ fn close_windowless_document<'s>(
|
||||
unsafe { &mut *runtime_ptr }.release_finished_windowless_document_parser(handle, &token);
|
||||
}
|
||||
|
||||
fn detached_html_document_body_handle(
|
||||
runtime: &PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
) -> Option<DomHandle> {
|
||||
let dom = runtime.dom_host().dom();
|
||||
dom.node(document_handle)?
|
||||
.as_document()?
|
||||
.body_handle(dom, document_handle)
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn set_detached_html_document_body_html(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
runtime_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
html: &str,
|
||||
) -> bool {
|
||||
custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
|
||||
let runtime = unsafe { &mut *runtime_ptr };
|
||||
let Some(body) = detached_html_document_body_handle(runtime, document_handle) else {
|
||||
return false;
|
||||
};
|
||||
if html.is_empty() && runtime.dom_host().child_handles(body).next().is_none() {
|
||||
return true;
|
||||
}
|
||||
runtime.set_inner_html(scope, runtime_ptr, body, html)
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::native_bridge) fn append_detached_html_document_body_html(
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
runtime_ptr: *mut PageScriptHost,
|
||||
document_handle: DomHandle,
|
||||
html: &str,
|
||||
) -> bool {
|
||||
custom_elements::with_custom_element_reaction_scope(scope, runtime_ptr, |scope| {
|
||||
let runtime = unsafe { &mut *runtime_ptr };
|
||||
let Some(body) = detached_html_document_body_handle(runtime, document_handle) else {
|
||||
return false;
|
||||
};
|
||||
let scripting_enabled_for_node = |node| runtime.node_document_scripting_enabled(node);
|
||||
let mut next = runtime
|
||||
.dom_host()
|
||||
.get_html(body, &scripting_enabled_for_node, false, &[])
|
||||
.unwrap_or_default();
|
||||
next.push_str(html);
|
||||
runtime.set_inner_html(scope, runtime_ptr, body, &next)
|
||||
})
|
||||
}
|
||||
|
||||
fn normalized_editing_command<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: &v8::FunctionCallbackArguments<'s>,
|
||||
|
||||
@@ -20,6 +20,7 @@ pub(crate) enum PopupDocumentLifecycleStep {
|
||||
|
||||
pub(crate) struct PopupDocumentLifecycleCheckpoint {
|
||||
window: PopupWindowEventTarget,
|
||||
task: LightweightPopupNavigationTaskToken,
|
||||
continuation: PopupDocumentLifecycleContinuation,
|
||||
}
|
||||
|
||||
@@ -87,6 +88,7 @@ impl ScriptVm {
|
||||
Ok(PopupDocumentLifecycleStep::Checkpoint(
|
||||
PopupDocumentLifecycleCheckpoint {
|
||||
window,
|
||||
task: target,
|
||||
continuation: match event {
|
||||
PopupDocumentLifecycleEvent::DomContentLoaded => {
|
||||
PopupDocumentLifecycleContinuation::FinishDomContentLoaded
|
||||
@@ -109,6 +111,7 @@ impl ScriptVm {
|
||||
Ok(if entered {
|
||||
PopupDocumentLifecycleStep::Checkpoint(PopupDocumentLifecycleCheckpoint {
|
||||
window: completion.window,
|
||||
task: completion.task,
|
||||
continuation: PopupDocumentLifecycleContinuation::FinishInteractive(completion),
|
||||
})
|
||||
} else {
|
||||
@@ -136,6 +139,10 @@ impl ScriptVm {
|
||||
._context_host
|
||||
.borrow()
|
||||
.popup_window_event_target_is_current(window)
|
||||
|| !self
|
||||
._context_host
|
||||
.borrow()
|
||||
.lightweight_popup_committed_navigation_task_is_current(checkpoint.task)
|
||||
{
|
||||
return Ok(PopupDocumentLifecycleStep::Completed);
|
||||
}
|
||||
@@ -164,6 +171,7 @@ impl ScriptVm {
|
||||
Ok(PopupDocumentLifecycleStep::Checkpoint(
|
||||
PopupDocumentLifecycleCheckpoint {
|
||||
window,
|
||||
task: checkpoint.task,
|
||||
continuation: if dispatched {
|
||||
PopupDocumentLifecycleContinuation::ContinuePageshow
|
||||
} else {
|
||||
@@ -183,6 +191,7 @@ impl ScriptVm {
|
||||
Ok(PopupDocumentLifecycleStep::Checkpoint(
|
||||
PopupDocumentLifecycleCheckpoint {
|
||||
window,
|
||||
task: checkpoint.task,
|
||||
continuation: PopupDocumentLifecycleContinuation::FinishLoad,
|
||||
},
|
||||
))
|
||||
|
||||
@@ -75,6 +75,7 @@ mod popup_document_open_listeners;
|
||||
mod popup_document_open_url;
|
||||
mod popup_document_stream;
|
||||
mod popup_hyperlinks;
|
||||
mod popup_live_document_stream;
|
||||
mod promise_rejection;
|
||||
mod request_init;
|
||||
mod retained_simple_targets;
|
||||
|
||||
@@ -96,7 +96,7 @@ window.__loadedUrlReady = () => {
|
||||
__loadedUrlResults.push([mode,same,d === w.document,d.URL === expected,
|
||||
d.documentURI === expected,d.baseURI === expected,w.location.href === expected,
|
||||
w.history.state === state,w.history.length === length,
|
||||
d.body.textContent]);
|
||||
d.body && d.body.textContent]);
|
||||
d.close();
|
||||
}
|
||||
};
|
||||
@@ -123,7 +123,7 @@ for (const mode of ['open','borrowed','write','writeln']) {
|
||||
vm.eval("__loadedUrlReady()").unwrap();
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__loadedUrlResults)").unwrap(),
|
||||
r#"[["open",true,true,true,true,true,true,true,true,""],["borrowed",true,true,true,true,true,true,true,true,""],["write",true,true,true,true,true,true,true,true,"replacement"],["writeln",true,true,true,true,true,true,true,true,"replacement\n"]]"#
|
||||
r#"[["open",true,true,true,true,true,true,true,true,null],["borrowed",true,true,true,true,true,true,true,true,null],["write",true,true,true,true,true,true,true,true,"replacement"],["writeln",true,true,true,true,true,true,true,true,"replacement\n"]]"#
|
||||
);
|
||||
vm.eval("__loadedUrlPopups.forEach(([,w]) => w.close())")
|
||||
.unwrap();
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_open_replaces_the_tree_and_close_finishes_the_parser() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-open.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document, root = d.documentElement, old = [...d.childNodes];
|
||||
try {
|
||||
const observer = new MutationObserver(() => {});
|
||||
observer.observe(d, {childList:true});
|
||||
const same = d.open() === d;
|
||||
const removals = observer.takeRecords();
|
||||
const opened = [same, d === w.document, d.childNodes.length, d.documentElement,
|
||||
d.head, d.body, root.isConnected, d.readyState, d.compatMode,
|
||||
removals.length, removals[0].removedNodes.length === old.length];
|
||||
d.close();
|
||||
const closed = [d.readyState, d.body.localName, d.body.textContent];
|
||||
return JSON.stringify({opened, closed});
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result,
|
||||
r#"{"opened":[true,true,0,null,null,null,false,"loading","CSS1Compat",1,true],"closed":["complete","body",""]}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_write_preserves_split_tokens_and_native_node_identity() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-token.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
try {
|
||||
d.open();
|
||||
d.write('<!doctype html><title>Stream');
|
||||
d.write(' title</title><p id="fir');
|
||||
d.write('st">one');
|
||||
const first = d.getElementById('first');
|
||||
let events = 0;
|
||||
first.addEventListener('click', () => ++events);
|
||||
d.write(' two</p><!-- com');
|
||||
d.writeln('ment --><p>three</p>');
|
||||
d.close();
|
||||
first.dispatchEvent(new Event('click'));
|
||||
return JSON.stringify([d.title, first === d.getElementById('first'), first.textContent,
|
||||
d.body.innerHTML, events, d.readyState]);
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result,
|
||||
r#"["Stream title",true,"one two","<p id=\"first\">one two</p><!-- comment --><p>three</p>\n",1,"complete"]"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_inline_scripts_keep_insertion_order_and_ignore_nested_open() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-scripts.test/");
|
||||
let result = vm.eval(r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
globalThis.__popupStreamOrder = [];
|
||||
try {
|
||||
d.open();
|
||||
d.write('<!doctype html><div id="before"></div><scr');
|
||||
d.write('ipt>opener.__popupStreamOrder.push([document===window.document, document.currentScript.tagName, !!document.getElementById("after")]);document.open();document.write("<span id=written>nested</span>");opener.__popupStreamOrder.push(!!document.getElementById("written"));document.close();</scr');
|
||||
d.write('ipt><p id="after">after</p>');
|
||||
const order = __popupStreamOrder.slice();
|
||||
return JSON.stringify({order, nodes:Array.from(d.body.children,n=>n.id||n.tagName),
|
||||
ready:d.readyState, current:d.currentScript});
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#).unwrap();
|
||||
assert_eq!(
|
||||
result,
|
||||
r#"{"order":[[true,"SCRIPT",false],true],"nodes":["before","SCRIPT","written","after"],"ready":"complete","current":null}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_parser_delivers_meta_csp_before_inline_script_preparation() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-csp.test/");
|
||||
let result = vm.eval(r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
globalThis.__popupStreamCsp = [];
|
||||
try {
|
||||
d.open();
|
||||
d.write('<!doctype html><meta http-equiv="Content-Security-Policy" content="script-src 'nonce-ok'"><body><script>opener.__popupStreamCsp.push("blocked")</script><script nonce="ok">opener.__popupStreamCsp.push("allowed")</script>');
|
||||
d.close();
|
||||
return JSON.stringify(__popupStreamCsp);
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#).unwrap();
|
||||
assert_eq!(result, r#"["allowed"]"#);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn popup_live_document_csp_blocked_script_cannot_execute_after_adoption() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_parsed_page_task_executor_test_vm(
|
||||
"https://popup-live-blocked-adoption.test/",
|
||||
"<!doctype html><body>opener",
|
||||
&loader,
|
||||
);
|
||||
let result = vm.eval(r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
globalThis.__popupBlockedStream = 0;
|
||||
try {
|
||||
d.open();
|
||||
d.write('<!doctype html><meta http-equiv="Content-Security-Policy" content="script-src 'none'"><body><script id=s>window.__popupBlockedStream++</script>');
|
||||
d.close();
|
||||
document.body.appendChild(d.getElementById('s'));
|
||||
return String(__popupBlockedStream);
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#).unwrap();
|
||||
assert_eq!(result, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_custom_element_callback_writes_at_the_active_insertion_point() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-ce-write.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document, calls = [];
|
||||
try {
|
||||
const registry = new CustomElementRegistry();
|
||||
registry.initialize(d);
|
||||
registry.define('popup-stream-writer', class extends HTMLElement {
|
||||
connectedCallback() {
|
||||
calls.push('connected');
|
||||
d.write('<b id=nested>nested</b>');
|
||||
}
|
||||
});
|
||||
d.open();
|
||||
d.write('<!doctype html><body><popup-stream-writer></popup-stream-writer><p id=tail>tail</p>');
|
||||
d.close();
|
||||
return JSON.stringify({calls, body:d.body.innerHTML});
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result,
|
||||
r#"{"calls":["connected"],"body":"<popup-stream-writer></popup-stream-writer><p id=\"tail\">tail</p><b id=\"nested\">nested</b>"}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_custom_element_callback_can_replace_the_active_parser() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-ce-open.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
try {
|
||||
const registry = new CustomElementRegistry();
|
||||
registry.initialize(d);
|
||||
registry.define('popup-stream-opener', class extends HTMLElement {
|
||||
connectedCallback() {
|
||||
d.open();
|
||||
d.write('<!doctype html><p>replacement</p>');
|
||||
d.close();
|
||||
}
|
||||
});
|
||||
d.open();
|
||||
d.write('<!doctype html><body><popup-stream-opener></popup-stream-opener><p>stale tail</p>');
|
||||
return JSON.stringify([d.body.textContent, d.readyState]);
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, r#"["replacement","complete"]"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popup_live_document_readiness_callback_can_replace_a_finishing_stream() {
|
||||
let mut vm = new_storage_test_vm("https://popup-live-readiness-reentry.test/");
|
||||
let result = vm
|
||||
.eval(
|
||||
r#"
|
||||
(() => {
|
||||
const w = open(), d = w.document;
|
||||
try {
|
||||
d.open();
|
||||
d.addEventListener('readystatechange', function once() {
|
||||
if (d.readyState === 'interactive') {
|
||||
d.removeEventListener('readystatechange', once);
|
||||
d.open();
|
||||
d.write('<!doctype html><p>replacement</p>');
|
||||
}
|
||||
});
|
||||
d.write('<!doctype html><p>old</p>');
|
||||
d.close();
|
||||
return JSON.stringify([d.body.textContent, d.readyState]);
|
||||
} finally { w.close(); }
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, r#"["replacement","loading"]"#);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn popup_live_document_external_script_resumes_before_close_and_deferred_work() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_parsed_page_task_executor_test_vm(
|
||||
"https://popup-live-external.test/",
|
||||
"<!doctype html><body>opener",
|
||||
&loader,
|
||||
);
|
||||
vm.eval(r#"
|
||||
globalThis.__popupStreamExternal = [];
|
||||
globalThis.__popupStreamWindow = open();
|
||||
const d = __popupStreamWindow.document;
|
||||
d.open();
|
||||
const blocking = URL.createObjectURL(new Blob([
|
||||
'opener.__popupStreamExternal.push(["blocking",!!document.getElementById("after")]);document.write("<b id=nested>nested</b>");'
|
||||
], {type:'text/javascript'}));
|
||||
const deferred = URL.createObjectURL(new Blob([
|
||||
'opener.__popupStreamExternal.push(["deferred",!!document.getElementById("after"),document.readyState]);'
|
||||
], {type:'text/javascript'}));
|
||||
d.write('<!doctype html><script src="'+blocking+'"></script><p id=after>after</p><script defer src="'+deferred+'"></script>');
|
||||
globalThis.__popupStreamPaused = !d.getElementById('after') && d.readyState === 'loading';
|
||||
d.close();
|
||||
__popupStreamWindow.addEventListener('load', () => __popupStreamExternal.push(['load', d.readyState]));
|
||||
"#).unwrap();
|
||||
assert_eq!(vm.eval("String(__popupStreamPaused)").unwrap(), "true");
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"String(__popupStreamExternal.length)",
|
||||
"3",
|
||||
"popup stream external and deferred scripts",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__popupStreamExternal)").unwrap(),
|
||||
r#"[["blocking",false],["deferred",true,"interactive"],["load","complete"]]"#
|
||||
);
|
||||
assert_eq!(
|
||||
vm.eval("__popupStreamWindow.document.getElementById('nested').textContent")
|
||||
.unwrap(),
|
||||
"nested"
|
||||
);
|
||||
vm.eval("__popupStreamWindow.close()").unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn popup_live_document_replacement_discards_old_external_script_completion() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_parsed_page_task_executor_test_vm(
|
||||
"https://popup-live-replacement.test/",
|
||||
"<!doctype html><body>opener",
|
||||
&loader,
|
||||
);
|
||||
vm.eval(r#"
|
||||
globalThis.__popupStreamRetired = [];
|
||||
globalThis.__popupStreamReplacement = open();
|
||||
const d = __popupStreamReplacement.document;
|
||||
d.open();
|
||||
const source = URL.createObjectURL(new Blob(['opener.__popupStreamRetired.push("old")'], {type:'text/javascript'}));
|
||||
d.write('<!doctype html><script src="'+source+'"></script><p>old tail</p>');
|
||||
d.close();
|
||||
d.open();
|
||||
d.write('<!doctype html><p>replacement</p>');
|
||||
__popupStreamReplacement.addEventListener('load', () => __popupStreamRetired.push('new load'));
|
||||
d.close();
|
||||
"#).unwrap();
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"JSON.stringify(__popupStreamRetired)",
|
||||
r#"["new load"]"#,
|
||||
"replacement popup stream load",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vm.eval("__popupStreamReplacement.document.body.textContent")
|
||||
.unwrap(),
|
||||
"replacement"
|
||||
);
|
||||
vm.eval("__popupStreamReplacement.close()").unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn popup_live_document_async_script_keeps_parsing_and_delays_load() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_parsed_page_task_executor_test_vm(
|
||||
"https://popup-live-async.test/",
|
||||
"<!doctype html><body>opener",
|
||||
&loader,
|
||||
);
|
||||
vm.eval(r#"
|
||||
globalThis.__popupStreamAsync = [];
|
||||
globalThis.__popupStreamAsyncWindow = open();
|
||||
const d = __popupStreamAsyncWindow.document;
|
||||
d.open();
|
||||
const source = URL.createObjectURL(new Blob([
|
||||
'opener.__popupStreamAsync.push(["async",!!document.getElementById("after")]);document.write("destructive");'
|
||||
], {type:'text/javascript'}));
|
||||
d.write('<!doctype html><script async src="'+source+'"></script><p id=after>after</p>');
|
||||
globalThis.__popupStreamNotBlocked = !!d.getElementById('after') && __popupStreamAsync.length === 0;
|
||||
d.close();
|
||||
globalThis.__popupStreamAwaitingAsync = d.readyState;
|
||||
__popupStreamAsyncWindow.addEventListener('load', () => __popupStreamAsync.push(['load', d.body.textContent]));
|
||||
"#).unwrap();
|
||||
assert_eq!(vm.eval("String(__popupStreamNotBlocked)").unwrap(), "true");
|
||||
assert_eq!(vm.eval("__popupStreamAwaitingAsync").unwrap(), "complete");
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"String(__popupStreamAsync.length)",
|
||||
"2",
|
||||
"popup stream async script and load",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__popupStreamAsync)").unwrap(),
|
||||
r#"[["async",true],["load","after"]]"#
|
||||
);
|
||||
vm.eval("__popupStreamAsyncWindow.close()").unwrap();
|
||||
}
|
||||
Reference in New Issue
Block a user