Skip to content

armgit / moli

Public Imported from GitHub
0

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

feat(xpath): expose compiled expressions with context document evaluation

ldm03c7557ee2de0
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index 76c8fbf63..9cd930550 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -1793,6 +1793,7 @@ pub(crate) fn finish_context_bootstrap(
("NodeIterator", "NodeIterator"),
("TreeWalker", "TreeWalker"),
("XPathEvaluator", "XPathEvaluator"),
+ ("XPathExpression", "XPathExpression"),
("XPathResult", "XPathResult"),
("SVGLength", "SVGLength"),
("SVGNumber", "SVGNumber"),
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
index ec51932f2..32550392d 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
@@ -644,6 +644,10 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[
interface: web_api_interfaces::XPathEvaluator::DESCRIPTOR,
kind: ConstructorKind::XPathEvaluator,
},
+ ConstructorSpec {
+ interface: web_api_interfaces::XPathExpression::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
ConstructorSpec {
interface: web_api_interfaces::XPathResult::DESCRIPTOR,
kind: ConstructorKind::Illegal,
diff --git a/moli-renderer-v8/src/mutation_coordinator/notifications.rs b/moli-renderer-v8/src/mutation_coordinator/notifications.rs
index 2ced50f76..2a6aa6cb0 100644
--- a/moli-renderer-v8/src/mutation_coordinator/notifications.rs
+++ b/moli-renderer-v8/src/mutation_coordinator/notifications.rs
@@ -22,6 +22,9 @@ pub(crate) fn notify_dom_mutation(
dom_host: &DomHost,
effects: &DomMutationEffects,
) -> MutationNotificationTimings {
+ crate::native_bridge::document::detached_record_native_tree_mutations(
+ scope, host_ptr, dom_host, effects,
+ );
let host = unsafe { &mut *host_ptr };
if !effects.stylesheet_owners().changes().is_empty() {
host.apply_stylesheet_owner_changes(effects.stylesheet_owners().changes());
diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs
index 8c99d15be..141466f6d 100644
--- a/moli-renderer-v8/src/native_bridge/document.rs
+++ b/moli-renderer-v8/src/native_bridge/document.rs
@@ -166,9 +166,10 @@ pub(in crate::native_bridge::document) use detached_objects::*;
pub(crate) use detached_objects::{
build_detached_cdata_section_object, build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type, detached_node_is_connected,
- is_valid_pi_target, preserve_detached_element_bridge_for_custom_prototype,
- read_detached_native_attribute, read_detached_native_attribute_names,
- read_detached_native_attribute_snapshot, read_detached_native_has_attribute,
+ detached_record_native_tree_mutations, is_valid_pi_target,
+ preserve_detached_element_bridge_for_custom_prototype, read_detached_native_attribute,
+ read_detached_native_attribute_names, read_detached_native_attribute_snapshot,
+ read_detached_native_has_attribute,
remove_detached_native_attribute_appending_to_current_reaction_queue,
remove_detached_native_attribute_ns_appending_to_current_reaction_queue,
with_detached_native_element_reaction_scope,
@@ -289,8 +290,9 @@ pub(super) use queries::{
bridge_detached_get_elements_by_tag_name_ns_callback, bridge_detached_matches_callback,
bridge_detached_query_selector_all_callback, bridge_detached_query_selector_callback,
bridge_document_getter, bridge_get_element_by_id_callback, node_create_node_iterator_callback,
- node_create_tree_walker_callback, node_document_create_ns_resolver_callback,
- node_document_evaluate_callback, node_get_element_by_id_callback,
+ node_create_tree_walker_callback, node_document_create_expression_callback,
+ node_document_create_ns_resolver_callback, node_document_evaluate_callback,
+ node_get_element_by_id_callback,
};
pub(super) use state::{
node_document_active_element_getter_function, throw_document_domain_security_error,
@@ -1472,7 +1474,9 @@ struct DocumentPrototypeMethodsDeclaration {
callback = node_document_create_ns_resolver_callback
)]
create_ns_resolver: (),
- #[webapi(method, length = 5, callback = node_document_evaluate_callback)]
+ #[webapi(method, length = 1, callback = node_document_create_expression_callback)]
+ create_expression: (),
+ #[webapi(method, length = 2, callback = node_document_evaluate_callback)]
evaluate: (),
#[webapi(
method = "hasStorageAccess",
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects.rs
index 0876db999..c5b99dd2b 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects.rs
@@ -54,5 +54,5 @@ pub(in crate::native_bridge) use self::state_tree::{
};
pub(crate) use self::state_tree::{
detached_native_handle_for_runtime, detached_native_object_for_handle,
- paired_detached_native_object_for_handle,
+ detached_record_native_tree_mutations, paired_detached_native_object_for_handle,
};
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
index 0f903a94e..97af9c4ec 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::{
custom_elements,
- dom::native::DomHost,
+ dom::native::{DomHost, DomMutationEffects},
dom_parser::DOM_PARSER_FOREIGN_NODE_SLOT,
util::{
context_host_ptr_from_global_bridge, get_private_object, get_private_value,
@@ -1175,6 +1175,43 @@ pub(in crate::native_bridge) fn detached_record_tree_mutation<'s>(
);
}
+pub(crate) fn detached_record_native_tree_mutations(
+ scope: &mut v8::PinScope<'_, '_>,
+ runtime_ptr: *mut JsContextHost,
+ dom_host: &DomHost,
+ effects: &DomMutationEffects,
+) {
+ // Native-backed detached nodes can use the ordinary Node mutation path.
+ // Keep their document-local query version in sync there too. These facts
+ // are available even when no MutationObserver has enabled record capture.
+ let inputs = effects.style();
+ let targets = inputs
+ .child_list_mutations()
+ .iter()
+ .map(|mutation| mutation.target())
+ .chain(
+ inputs
+ .attribute_mutations()
+ .iter()
+ .map(|mutation| mutation.target()),
+ )
+ .chain(inputs.character_data_mutations().iter().copied());
+ let mut documents = Vec::new();
+ for target in targets {
+ if let Some(document) = dom_host.owner_document_handle(target)
+ && !documents.contains(&document)
+ {
+ documents.push(document);
+ }
+ }
+ for document in documents {
+ if let Some(object) = paired_detached_native_object_for_handle(scope, runtime_ptr, document)
+ {
+ detached_record_tree_mutation(scope, object);
+ }
+ }
+}
+
pub(in crate::native_bridge::document) fn detached_state_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
node: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/native_bridge/document/queries.rs b/moli-renderer-v8/src/native_bridge/document/queries.rs
index 91025847a..698ed8142 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries.rs
@@ -3,7 +3,7 @@ use super::super::super::{
util::{throw_type_error, v8_string},
};
use super::super::node::{
- node_arg_handle, node_is_document, node_or_foreign_arg_handle_preserve_detached,
+ node_is_document, node_or_foreign_arg_handle_preserve_detached,
node_runtime_and_handle_from_args_or_detached,
};
use super::super::traversal;
@@ -37,7 +37,7 @@ pub(in crate::native_bridge) use traversal_factories::{
node_create_node_iterator_callback, node_create_tree_walker_callback,
};
pub(in crate::native_bridge) use xpath::{
- bridge_detached_document_evaluate_callback, node_document_create_ns_resolver_callback,
- node_document_evaluate_callback,
+ bridge_detached_document_evaluate_callback, node_document_create_expression_callback,
+ node_document_create_ns_resolver_callback, node_document_evaluate_callback,
};
pub(crate) use xpath::{evaluate_live_xpath_search_node_handles, install_xpath_template_bindings};
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath.rs
index 03e98e733..95e01bdfb 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath.rs
@@ -1,5 +1,6 @@
mod callbacks;
mod evaluation;
+mod expression;
mod live_dom;
mod resolver;
mod result;
@@ -9,8 +10,8 @@ mod types;
pub(crate) use live_dom::evaluate_live_xpath_search_node_handles;
pub(in crate::native_bridge) use callbacks::{
- bridge_detached_document_evaluate_callback, node_document_create_ns_resolver_callback,
- node_document_evaluate_callback,
+ bridge_detached_document_evaluate_callback, node_document_create_expression_callback,
+ node_document_create_ns_resolver_callback, node_document_evaluate_callback,
};
pub(crate) fn install_xpath_template_bindings<'s>(
@@ -20,6 +21,7 @@ pub(crate) fn install_xpath_template_bindings<'s>(
) {
match interface_name {
"XPathEvaluator" => callbacks::install_xpath_evaluator_template_bindings(scope, template),
+ "XPathExpression" => callbacks::install_xpath_expression_template_bindings(scope, template),
"XPathResult" => result::install_xpath_result_template_bindings(scope, template),
_ => {}
}
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/callbacks.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/callbacks.rs
index d50807eb7..c2806f0a6 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/callbacks.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/callbacks.rs
@@ -1,19 +1,23 @@
+use std::borrow::Cow;
+
use super::super::*;
use super::XPathEvaluationError;
use super::evaluation::{evaluate_xpath_over_live_dom, evaluate_xpath_over_object_tree};
+use super::expression::{expression_for_receiver, new_xpath_expression};
use super::resolver::V8XPathNamespaceResolver;
use super::result::is_supported_xpath_result_type;
use crate::native_bridge::{
- document::{detached_node_type, detached_tree_root_object},
- node_runtime_and_handle_from_object,
+ document::detached_tree_root_object, node_runtime_and_handle_from_object,
};
use crate::web_api_interfaces;
use crate::webidl;
use moli_webapi_declare::WebApiFunctionTemplate;
#[derive(WebApiFunctionTemplate)]
-#[webapi(interface = web_api_interfaces::XPathEvaluator, enumerable)]
+#[webapi(interface = web_api_interfaces::XPathEvaluator, enumerable, receiver)]
struct XPathEvaluatorPrototypeDeclaration {
+ #[webapi(method, length = 1, callback = xpath_evaluator_create_expression_callback)]
+ create_expression: (),
#[webapi(method, length = 2, callback = xpath_evaluator_evaluate_callback)]
evaluate: (),
#[webapi(
@@ -24,6 +28,42 @@ struct XPathEvaluatorPrototypeDeclaration {
create_ns_resolver: (),
}
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::XPathExpression, enumerable, receiver)]
+struct XPathExpressionPrototypeDeclaration {
+ #[webapi(method, length = 1, callback = xpath_expression_evaluate_callback)]
+ evaluate: (),
+}
+
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "Document.createExpression")]
+struct DocumentCreateExpressionArgs {
+ #[webidl(required)]
+ expression: String,
+ #[webidl(index = 1, converter = "callback_interface", nullable)]
+ namespace_resolver: Option<webidl::WebIdlCallbackInterface>,
+}
+
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "XPathEvaluator.createExpression")]
+struct XPathEvaluatorCreateExpressionArgs {
+ #[webidl(required)]
+ expression: String,
+ #[webidl(index = 1, converter = "callback_interface", nullable)]
+ namespace_resolver: Option<webidl::WebIdlCallbackInterface>,
+}
+
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "XPathExpression.evaluate")]
+struct XPathExpressionEvaluateArgs<'s> {
+ #[webidl(required, with = document_evaluate_context_node_arg)]
+ context_node: v8::Local<'s, v8::Object>,
+ #[webidl(index = 1, default = 0)]
+ result_type: u16,
+ #[webidl(index = 2, with = document_evaluate_existing_result_arg)]
+ _existing_result: Option<v8::Local<'s, v8::Object>>,
+}
+
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "Document.evaluate")]
struct DetachedDocumentEvaluateArgs<'s> {
@@ -94,7 +134,7 @@ fn document_evaluate_context_node_arg<'s>(
"Document.evaluate requires a context Node",
));
};
- if detached_node_type(scope, object).is_some_and(|node_type| node_type > 0) {
+ if web_api_interfaces::Node::is_instance(scope, object) {
Ok(object)
} else {
Err(webidl::WebIdlError::custom_message(
@@ -151,15 +191,41 @@ pub(super) fn install_xpath_evaluator_template_bindings<'s>(
);
}
-#[allow(clippy::too_many_arguments)]
+pub(super) fn install_xpath_expression_template_bindings<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ template: v8::Local<'s, v8::FunctionTemplate>,
+) {
+ XPathExpressionPrototypeDeclaration::initialize_prototype_template(
+ scope,
+ template.prototype_template(scope),
+ );
+}
+
+enum XPathInput<'a> {
+ Source(&'a str, Option<webidl::WebIdlCallbackInterface>),
+ Compiled(&'a moli_xpath::Expression),
+}
+
+fn compile_xpath(
+ scope: &mut v8::PinScope<'_, '_>,
+ expression: &str,
+ namespace_resolver: Option<webidl::WebIdlCallbackInterface>,
+) -> Result<moli_xpath::Expression, XPathEvaluationError> {
+ let namespace_resolver =
+ namespace_resolver.map(|callback| V8XPathNamespaceResolver::new(scope, callback));
+ // Preserve local-name case: the evaluated node's document determines HTML
+ // matching, even when this expression is created by an HTML Document.
+ moli_xpath::parse(expression, namespace_resolver, false).map_err(|error| match error {
+ moli_xpath::ParserError::FailedToResolveNamespacePrefix => XPathEvaluationError::Namespace,
+ _ => XPathEvaluationError::InvalidExpression,
+ })
+}
+
fn evaluate_xpath<'a>(
scope: &mut v8::PinScope<'a, '_>,
receiver: v8::Local<'a, v8::Object>,
- root: v8::Local<'a, v8::Object>,
- live_runtime_ptr: Option<*mut JsContextHost>,
- expression: &str,
+ input: XPathInput<'_>,
context_node: v8::Local<'a, v8::Object>,
- namespace_resolver: Option<webidl::WebIdlCallbackInterface>,
requested_result_type: u32,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
@@ -179,29 +245,23 @@ fn evaluate_xpath<'a>(
};
let result = {
let scope = &mut v8::ContextScope::new(scope, context);
- let namespace_resolver =
- namespace_resolver.map(|callback| V8XPathNamespaceResolver::new(scope, callback));
- if let Some(runtime_ptr) = live_runtime_ptr
- && let Some(context_handle) = node_arg_handle(scope, runtime_ptr, context_node.into())
- {
- evaluate_xpath_over_live_dom(
- scope,
- runtime_ptr,
- expression,
- context_handle,
- namespace_resolver,
- requested_result_type,
- )
- } else {
- evaluate_xpath_over_object_tree(
+ // Resolver callbacks may adopt or mutate the context node. Select its
+ // current tree only after compilation, with no DOM borrow or snapshot
+ // retained across author code. Compiled expressions reuse their AST.
+ let expression = match input {
+ XPathInput::Source(source, resolver) => {
+ compile_xpath(scope, source, resolver).map(Cow::Owned)
+ }
+ XPathInput::Compiled(expression) => Ok(Cow::Borrowed(expression)),
+ };
+ expression.and_then(|expression| {
+ evaluate_parsed_xpath_for_context(
scope,
- root,
- expression,
- Some(context_node),
- namespace_resolver,
+ &expression,
+ context_node,
requested_result_type,
)
- }
+ })
};
match result {
Ok(Some(result)) => rv.set(result.into()),
@@ -210,6 +270,34 @@ fn evaluate_xpath<'a>(
}
}
+fn evaluate_parsed_xpath_for_context<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ expression: &moli_xpath::Expression,
+ context_node: v8::Local<'s, v8::Object>,
+ requested_result_type: u32,
+) -> Result<Option<v8::Local<'s, v8::Object>>, XPathEvaluationError> {
+ if let Ok((runtime_ptr, context_handle)) =
+ node_runtime_and_handle_from_object(scope, context_node)
+ {
+ evaluate_xpath_over_live_dom(
+ scope,
+ runtime_ptr,
+ expression,
+ context_handle,
+ requested_result_type,
+ )
+ } else {
+ let root = detached_tree_root_object(scope, context_node).unwrap_or(context_node);
+ evaluate_xpath_over_object_tree(
+ scope,
+ root,
+ expression,
+ Some(context_node),
+ requested_result_type,
+ )
+ }
+}
+
pub(in crate::native_bridge) fn node_document_create_ns_resolver_callback<'a>(
scope: &mut v8::PinScope<'a, '_>,
args: v8::FunctionCallbackArguments<'a>,
@@ -248,11 +336,8 @@ pub(in crate::native_bridge) fn bridge_detached_document_evaluate_callback<'a>(
evaluate_xpath(
scope,
root,
- root,
- None,
- &parsed.expression,
+ XPathInput::Source(&parsed.expression, parsed.namespace_resolver),
parsed.context_node,
- parsed.namespace_resolver,
u32::from(parsed.result_type),
rv,
);
@@ -267,17 +352,11 @@ pub(in crate::native_bridge) fn node_document_evaluate_callback<'a>(
let Some(parsed) = webidl::parse_args::<DocumentEvaluateArgs<'a>>(scope, &args) else {
return;
};
- let live_runtime_ptr = node_runtime_and_handle_from_object(scope, root)
- .ok()
- .map(|(runtime_ptr, _)| runtime_ptr);
evaluate_xpath(
scope,
root,
- root,
- live_runtime_ptr,
- &parsed.expression,
+ XPathInput::Source(&parsed.expression, parsed.namespace_resolver),
parsed.context_node,
- parsed.namespace_resolver,
u32::from(parsed.result_type),
rv,
);
@@ -291,22 +370,89 @@ fn xpath_evaluator_evaluate_callback<'a>(
let Some(parsed) = webidl::parse_args::<XPathEvaluatorEvaluateArgs<'a>>(scope, &args) else {
return;
};
- let live_runtime_ptr = node_runtime_and_handle_from_object(scope, parsed.context_node)
- .ok()
- .map(|(runtime_ptr, _)| runtime_ptr);
- let root = if live_runtime_ptr.is_some() {
- parsed.context_node
- } else {
- detached_tree_root_object(scope, parsed.context_node).unwrap_or(parsed.context_node)
- };
evaluate_xpath(
scope,
args.this(),
- root,
- live_runtime_ptr,
- &parsed.expression,
+ XPathInput::Source(&parsed.expression, parsed.namespace_resolver),
parsed.context_node,
+ u32::from(parsed.result_type),
+ rv,
+ );
+}
+
+fn create_xpath_expression<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Object>,
+ expression: &str,
+ namespace_resolver: Option<webidl::WebIdlCallbackInterface>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(context) = receiver.get_creation_context(scope) else {
+ return;
+ };
+ let result = {
+ let scope = &mut v8::ContextScope::new(scope, context);
+ compile_xpath(scope, expression, namespace_resolver)
+ .map(|expression| new_xpath_expression(scope, expression))
+ };
+ match result {
+ Ok(Some(expression)) => rv.set(expression.into()),
+ Ok(None) => {}
+ Err(error) => throw_xpath_evaluation_error(scope, error),
+ }
+}
+
+pub(in crate::native_bridge) fn node_document_create_expression_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(parsed) = webidl::parse_args::<DocumentCreateExpressionArgs>(scope, &args) else {
+ return;
+ };
+ create_xpath_expression(
+ scope,
+ args.this(),
+ &parsed.expression,
+ parsed.namespace_resolver,
+ rv,
+ );
+}
+
+fn xpath_evaluator_create_expression_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(parsed) = webidl::parse_args::<XPathEvaluatorCreateExpressionArgs>(scope, &args)
+ else {
+ return;
+ };
+ create_xpath_expression(
+ scope,
+ args.this(),
+ &parsed.expression,
parsed.namespace_resolver,
+ rv,
+ );
+}
+
+fn xpath_expression_evaluate_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(parsed) = webidl::parse_args::<XPathExpressionEvaluateArgs<'s>>(scope, &args) else {
+ return;
+ };
+ let Some(expression) = expression_for_receiver(scope, args.this()) else {
+ return;
+ };
+ evaluate_xpath(
+ scope,
+ args.this(),
+ XPathInput::Compiled(&expression),
+ parsed.context_node,
u32::from(parsed.result_type),
rv,
);
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/evaluation.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/evaluation.rs
index 1724f3287..3d3daca2e 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/evaluation.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/evaluation.rs
@@ -1,6 +1,5 @@
use super::super::*;
-use super::live_dom::{LiveXPathResultNode, LiveXPathValue, evaluate_live_xpath};
-use super::resolver::V8XPathNamespaceResolver;
+use super::live_dom::{LiveXPathResultNode, LiveXPathValue, evaluate_live_parsed_xpath};
use super::result::{
XPathIteratorMutationState, build_xpath_nodes_result, build_xpath_scalar_result,
};
@@ -9,35 +8,28 @@ use crate::native_bridge::document::{
detached_node_type, detached_tree_query_version, detached_tree_root_object,
live_get_attribute_node_ns_object, live_get_attribute_node_object,
};
-use moli_xpath::{
- ParserError, SnapshotValue, SnapshotXPathEvaluationError,
- evaluate_snapshot_xpath_with_resolver_detailed,
-};
+use moli_xpath::{SnapshotValue, evaluate_parsed_snapshot_xpath};
use super::XPathEvaluationError;
+use super::types::{XPATH_NUMBER_TYPE, XPATH_STRING_TYPE};
pub(super) fn evaluate_xpath_over_live_dom<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
runtime_ptr: *mut JsContextHost,
- expression: &str,
+ expression: &moli_xpath::Expression,
context_handle: DomHandle,
- namespace_resolver: Option<V8XPathNamespaceResolver<'s, 'i>>,
requested_result_type: u32,
) -> Result<Option<v8::Local<'s, v8::Object>>, XPathEvaluationError> {
- let runtime = unsafe { &*runtime_ptr };
- let document_handle = runtime.dom_host().document_handle();
- let is_in_html_document = runtime
- .dom_host()
- .node(document_handle)
- .and_then(crate::dom::native::Node::as_document)
- .is_some_and(|document| document.is_html_document());
- let value = evaluate_live_xpath(
- runtime.dom_host(),
- expression,
- context_handle,
- is_in_html_document,
- namespace_resolver,
- )?;
+ let (value, baseline_query_version) = {
+ let runtime = unsafe { &*runtime_ptr };
+ let value = evaluate_live_parsed_xpath(
+ runtime.dom_host(),
+ expression,
+ context_handle,
+ requested_result_type,
+ )?;
+ (value, runtime.dom_host().query_version())
+ };
match value {
LiveXPathValue::Nodes(handles) => {
@@ -48,7 +40,6 @@ pub(super) fn evaluate_xpath_over_live_dom<'s, 'i>(
};
resolved.push(node);
}
- let baseline_query_version = runtime.dom_host().query_version();
Ok(build_xpath_nodes_result(
scope,
&resolved,
@@ -110,9 +101,8 @@ fn live_xpath_result_node_object<'s>(
pub(super) fn evaluate_xpath_over_object_tree<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
root: v8::Local<'s, v8::Object>,
- expression: &str,
+ expression: &moli_xpath::Expression,
context_node: Option<v8::Local<'s, v8::Object>>,
- namespace_resolver: Option<V8XPathNamespaceResolver<'s, 'i>>,
requested_result_type: u32,
) -> Result<Option<v8::Local<'s, v8::Object>>, XPathEvaluationError> {
let root_node_type = detached_node_type(scope, root).unwrap_or_default();
@@ -135,21 +125,24 @@ pub(super) fn evaluate_xpath_over_object_tree<'s, 'i>(
));
};
- let value = evaluate_snapshot_xpath_with_resolver_detailed::<V8XPathNamespaceResolver<'s, 'i>>(
- &snapshot.snapshot,
- expression,
- context_id,
- true,
- namespace_resolver,
- )
- .map_err(|error| match error {
- SnapshotXPathEvaluationError::Parse(ParserError::FailedToResolveNamespacePrefix) => {
- XPathEvaluationError::Namespace
- }
- _ => XPathEvaluationError::InvalidExpression,
- })?;
+ let value = evaluate_parsed_snapshot_xpath(&snapshot.snapshot, expression, context_id)
+ .map_err(|_| XPathEvaluationError::InvalidExpression)?;
match value {
+ SnapshotValue::Nodes(nodes)
+ if matches!(requested_result_type, XPATH_NUMBER_TYPE | XPATH_STRING_TYPE) =>
+ {
+ let text = nodes
+ .first()
+ .and_then(|id| snapshot.snapshot.node(*id))
+ .map(|node| moli_xpath::Node::text_content(&node))
+ .unwrap_or_default();
+ Ok(build_xpath_scalar_result(
+ scope,
+ SnapshotValue::String(text),
+ requested_result_type,
+ ))
+ }
SnapshotValue::Nodes(nodes) => {
let mut resolved = Vec::new();
for node_id in nodes {
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/expression.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/expression.rs
new file mode 100644
index 000000000..f79ab6c8b
--- /dev/null
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/expression.rs
@@ -0,0 +1,141 @@
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use moli_webapi_declare::WebApiObject;
+use moli_xpath::Expression;
+
+use crate::{
+ util::{get_private_value, set_private_value},
+ web_api_interfaces,
+};
+
+const EXPRESSION_ID_SLOT: &str = "__moliXPathExpressionId";
+type Store = Rc<RefCell<Expressions>>;
+
+#[derive(Default)]
+struct Expressions {
+ next_id: u64,
+ entries: HashMap<u64, (v8::Weak<v8::Object>, Rc<Expression>)>,
+}
+
+#[derive(WebApiObject)]
+#[webapi(interface = web_api_interfaces::XPathExpression)]
+struct XPathExpressionDeclaration {}
+
+pub(super) fn new_xpath_expression<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ expression: Expression,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let object = XPathExpressionDeclaration::new().bind(scope).ok()?;
+ retain_expression(scope, object, expression);
+ Some(object)
+}
+
+// Compiled expressions contain resolved names and Rust values only. Neither
+// the resolver nor a native host/context pointer survives compilation. The
+// wrapper's weak entry releases the AST on GC or isolate teardown.
+fn retain_expression<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ expression: Expression,
+) {
+ let store = if let Some(store) = scope.get_slot::<Store>() {
+ store.clone()
+ } else {
+ let store = Store::default();
+ scope.set_slot(store.clone());
+ store
+ };
+ let id = {
+ let mut store = store.borrow_mut();
+ store.next_id = store
+ .next_id
+ .checked_add(1)
+ .expect("XPath expression identity exhausted");
+ store.next_id
+ };
+ set_private_value(
+ scope,
+ object,
+ EXPRESSION_ID_SLOT,
+ v8::BigInt::new_from_u64(scope, id).into(),
+ );
+ let weak_store = Rc::downgrade(&store);
+ let weak = v8::Weak::with_finalizer(
+ scope,
+ object,
+ Box::new(move |_| {
+ if let Some(store) = weak_store.upgrade() {
+ store.borrow_mut().entries.remove(&id);
+ }
+ }),
+ );
+ store
+ .borrow_mut()
+ .entries
+ .insert(id, (weak, Rc::new(expression)));
+}
+
+pub(super) fn expression_for_receiver<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+) -> Option<Rc<Expression>> {
+ let value = get_private_value(scope, object, EXPRESSION_ID_SLOT)?;
+ let (id, lossless) = v8::Local::<v8::BigInt>::try_from(value).ok()?.u64_value();
+ if !lossless {
+ return None;
+ }
+ scope
+ .get_slot::<Store>()?
+ .borrow()
+ .entries
+ .get(&id)
+ .map(|(_, expression)| expression.clone())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn compiled_xpath_lifetime_follows_wrapper_gc_and_isolate_teardown() {
+ moli_v8_test_util::ensure_v8();
+ for collect in [true, false] {
+ let weak_expression = {
+ let mut isolate = v8::Isolate::new(Default::default());
+ let (wrapper, weak_expression) = {
+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let object = v8::Object::new(scope);
+ retain_expression(scope, object, Expression::ContextItem);
+ let expression = expression_for_receiver(scope, object).expect("stored AST");
+ (v8::Global::new(scope, object), Rc::downgrade(&expression))
+ };
+ isolate.low_memory_notification();
+ assert!(
+ weak_expression.upgrade().is_some(),
+ "live wrapper retains AST"
+ );
+ drop(wrapper);
+ if collect {
+ isolate.low_memory_notification();
+ assert!(weak_expression.upgrade().is_none(), "GC releases AST");
+ assert!(
+ isolate
+ .get_slot::<Store>()
+ .unwrap()
+ .borrow()
+ .entries
+ .is_empty()
+ );
+ }
+ weak_expression
+ };
+ assert!(
+ weak_expression.upgrade().is_none(),
+ "isolate teardown releases AST"
+ );
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/live_dom.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/live_dom.rs
index bd15edc89..c9494b2d8 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/live_dom.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/live_dom.rs
@@ -1,3 +1,4 @@
+use super::types::{XPATH_ANY_TYPE, XPATH_BOOLEAN_TYPE, XPATH_NUMBER_TYPE, XPATH_STRING_TYPE};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::ptr::NonNull;
@@ -86,9 +87,24 @@ pub(super) fn evaluate_live_xpath(
XPathEvaluationError::InvalidExpression
}
})?;
+ evaluate_live_parsed_xpath(dom, &expression, context, XPATH_ANY_TYPE)
+}
+
+pub(super) fn evaluate_live_parsed_xpath(
+ dom: &DomHost,
+ expression: &moli_xpath::Expression,
+ context: DomHandle,
+ requested_result_type: u32,
+) -> Result<LiveXPathValue, XPathEvaluationError> {
let context = LiveXPathNode::new(dom, context);
- let value = evaluate_parsed_xpath::<LiveXPathDom>(&expression, context)
+ let value = evaluate_parsed_xpath::<LiveXPathDom>(expression, context)
.map_err(|_| XPathEvaluationError::InvalidExpression)?;
+ let value = match requested_result_type {
+ XPATH_NUMBER_TYPE => Value::Number(value.convert_to_number()),
+ XPATH_STRING_TYPE => Value::String(value.convert_to_string()),
+ XPATH_BOOLEAN_TYPE => Value::Boolean(value.convert_to_boolean()),
+ _ => value,
+ };
Ok(live_xpath_value(value))
}
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/resolver.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/resolver.rs
index bfa54525c..073a6c2a2 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/resolver.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/resolver.rs
@@ -17,7 +17,7 @@ use moli_xpath::NamespaceResolver;
/// `moli-xpath` may clone its resolver while parsing, so the independently
/// rooted callback snapshot is shared with `Rc`. The raw scope pointer is safe
/// only because the entire adapter remains inside one `Document.evaluate` /
-/// `XPathEvaluator.evaluate` V8 callback and never crosses an await, task, or
+/// `XPathEvaluator.evaluate` / `createExpression` V8 callback and never crosses an await, task, or
/// thread boundary.
#[derive(Clone)]
pub(super) struct V8XPathNamespaceResolver<'s, 'i> {
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/result.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/result.rs
index 9038f5f21..6d96fefe2 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/result.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/result.rs
@@ -411,10 +411,17 @@ pub(super) fn build_xpath_scalar_result<'s>(
requested_result_type: u32,
) -> Option<v8::Local<'s, v8::Object>> {
let result_type = match requested_result_type {
- XPATH_ANY_TYPE | XPATH_STRING_TYPE => XPATH_STRING_TYPE,
- XPATH_NUMBER_TYPE => XPATH_NUMBER_TYPE,
- XPATH_BOOLEAN_TYPE => XPATH_BOOLEAN_TYPE,
- _ => XPATH_STRING_TYPE,
+ XPATH_ANY_TYPE => match &value {
+ SnapshotValue::Boolean(_) => XPATH_BOOLEAN_TYPE,
+ SnapshotValue::Number(_) => XPATH_NUMBER_TYPE,
+ SnapshotValue::String(_) => XPATH_STRING_TYPE,
+ SnapshotValue::Nodes(_) => return None,
+ },
+ XPATH_STRING_TYPE | XPATH_NUMBER_TYPE | XPATH_BOOLEAN_TYPE => requested_result_type,
+ _ => {
+ throw_type_error(scope, "The XPath result is not a node set.");
+ return None;
+ }
};
let object = build_xpath_result_base(scope, result_type)?;
match result_type {
diff --git a/moli-renderer-v8/src/native_bridge/document/queries/xpath/snapshot.rs b/moli-renderer-v8/src/native_bridge/document/queries/xpath/snapshot.rs
index e299dacac..4405ed804 100644
--- a/moli-renderer-v8/src/native_bridge/document/queries/xpath/snapshot.rs
+++ b/moli-renderer-v8/src/native_bridge/document/queries/xpath/snapshot.rs
@@ -45,9 +45,12 @@ fn detached_xpath_native_node_info<'s>(
DetachedXPathNativeNodeInfo::Element {
tag_name: element.local_name().to_owned(),
prefix: element.prefix().map(str::to_owned),
- is_html_element: namespace
- .as_deref()
- .is_none_or(|namespace| namespace == "http://www.w3.org/1999/xhtml"),
+ is_html_element: namespace.as_deref() == Some("http://www.w3.org/1999/xhtml")
+ && node
+ .owner_document()
+ .and_then(|owner| dom_host.node(owner))
+ .and_then(crate::dom::native::Node::as_document)
+ .is_some_and(|document| document.is_html_document()),
namespace,
}
}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_state_and_form_controls.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_state_and_form_controls.rs
index 0fcc720bf..6f16ea309 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_state_and_form_controls.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_state_and_form_controls.rs
@@ -1005,7 +1005,8 @@ fn document_template_methods_keep_declared_reflection_shape() {
["createNodeIterator", 1],
["createTreeWalker", 1],
["createNSResolver", 1],
- ["evaluate", 5],
+ ["createExpression", 1],
+ ["evaluate", 2],
["hasStorageAccess", 0],
["requestStorageAccess", 0]
];
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_and_selectors.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_and_selectors.rs
index 48a249560..73527fbc2 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_and_selectors.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_and_selectors.rs
@@ -1,5 +1,28 @@
use super::*;
+#[test]
+fn xpath_compiled_expressions_preserve_namespaces_brands_and_realms() {
+ let mut vm = new_parsed_test_vm(
+ "https://xpath-expression.test/",
+ "<html><body></body></html>",
+ );
+ assert_eq!(
+ vm.eval(include_str!("xpath_compiled_expressions.js"))
+ .expect("compiled XPath expression fixture should evaluate"),
+ "true"
+ );
+}
+
+#[test]
+fn xpath_evaluation_uses_context_document_after_resolver_callbacks() {
+ let mut vm = new_parsed_test_vm("https://xpath-context.test/", "<html><body></body></html>");
+ assert_eq!(
+ vm.eval(include_str!("xpath_context_documents.js"))
+ .expect("XPath context document fixture should evaluate"),
+ "true"
+ );
+}
+
#[test]
fn xpath_evaluator_constructor_requires_new() {
let mut vm = new_parsed_test_vm(
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_compiled_expressions.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_compiled_expressions.js
new file mode 100644
index 000000000..65fde7f73
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_compiled_expressions.js
@@ -0,0 +1,134 @@
+(() => {
+ const check = (value, message) => { if (!value) throw new Error(message); };
+ const throws = (callback, name, Constructor = Error) => {
+ let caught;
+ try { callback(); } catch (e) { caught = e; }
+ check(caught && caught.name === name && caught instanceof Constructor, name + ' required');
+ };
+ check(XPathExpression.name === 'XPathExpression' && XPathExpression.length === 0, 'constructor metadata');
+ throws(() => XPathExpression(), 'TypeError', TypeError);
+ throws(() => new XPathExpression(), 'TypeError', TypeError);
+ check(document.createExpression.length === 1 && XPathEvaluator.prototype.createExpression.length === 1,
+ 'createExpression required argument count');
+ check(Document.prototype.evaluate.length === 2 && XPathEvaluator.prototype.evaluate.length === 2,
+ 'uncompiled evaluate required argument count');
+ check(XPathExpression.prototype.evaluate.length === 1, 'evaluate required argument count');
+ const descriptor = Object.getOwnPropertyDescriptor(XPathExpression.prototype, 'evaluate');
+ check(descriptor.enumerable && descriptor.configurable && descriptor.writable, 'evaluate descriptor');
+
+ const xml = new DOMParser().parseFromString('<root xmlns:p="urn:items"><p:item>4</p:item><p:other>6</p:other><UPPER/></root>', 'text/xml');
+ const evaluator = new XPathEvaluator();
+ let conversions = 0, calls = 0;
+ const resolver = {lookupNamespaceURI(prefix) {calls++; check(prefix === 'p', 'prefix'); return 'urn:items';}};
+ const compiled = evaluator.createExpression({toString() {conversions++;return '//p:item | //p:other';}}, resolver);
+ check(conversions === 1 && calls === 2, 'resolve namespaces while compiling');
+ resolver.lookupNamespaceURI = () => {throw new Error('resolver must not be retained');};
+ check(Object.getPrototypeOf(compiled) === XPathExpression.prototype, 'native prototype');
+ check(Object.prototype.toString.call(compiled) === '[object XPathExpression]', 'native tag');
+ check(Object.keys(compiled).length === 0, 'expression has no public state');
+ check(document.createExpression('1') !== document.createExpression('1'), 'NewObject');
+ const first = compiled.evaluate(xml, 7);
+ check(first.snapshotLength === 2 && first.snapshotItem(0) === xml.documentElement.firstChild, 'snapshot result');
+ check(compiled.evaluate(xml, 1).numberValue === 4, 'numeric conversion');
+ check(compiled.evaluate(xml, 2).stringValue === '4', 'string conversion');
+ check(compiled.evaluate(xml, 3).booleanValue, 'boolean conversion');
+ check(compiled.evaluate(xml, 9).singleNodeValue === xml.documentElement.firstChild, 'single-node conversion');
+ check(compiled.evaluate(xml).iterateNext() === xml.documentElement.firstChild, 'default iterator result');
+ check(calls === 2 && conversions === 1, 'evaluation uses compiled expression');
+ check(document.createExpression('//UPPER').evaluate(xml, 7).snapshotLength === 1, 'XML case is preserved');
+
+ const htmlNS = 'http://www.w3.org/1999/xhtml';
+ const xmlHtml = document.implementation.createDocument(htmlNS, 'html');
+ const html = document.implementation.createHTMLDocument();
+ for (const creator of [document, xmlHtml, html, evaluator]) {
+ const expression = creator.createExpression('//html');
+ check(expression.evaluate(xmlHtml, 7).snapshotLength === 0, 'XML namespace matching');
+ check(expression.evaluate(html, 7).snapshotItem(0) === html.documentElement, 'HTML namespace matching');
+ }
+ for (const run of [
+ (source, context, type) => document.evaluate(source, context, null, type),
+ (source, context, type) => evaluator.evaluate(source, context, null, type),
+ (source, context, type) => document.createExpression(source).evaluate(context, type)
+ ]) {
+ for (const context of [xml, document]) {
+ check(run('1 + 2', context).numberValue === 3, 'default numeric result type');
+ check(run('false()', context).booleanValue === false, 'default boolean result type');
+ check(run('"text"', context).stringValue === 'text', 'default string result type');
+ check(run('false()', context, 1).numberValue === 0, 'boolean to number');
+ check(run('3', context, 2).stringValue === '3', 'number to string');
+ check(run('0', context, 3).booleanValue === false, 'number to boolean');
+ for (const type of [4, 5, 6, 7, 8, 9]) {
+ throws(() => run('3', context, type), 'TypeError', TypeError);
+ }
+ check(run('//absent', context, 2).stringValue === '', 'empty nodes to string');
+ check(Number.isNaN(run('//absent', context, 1).numberValue), 'empty nodes to number');
+ }
+ check(run('//root/*', xml, 1).numberValue === 4, 'node-set to number');
+ check(run('//root/*', xml, 2).stringValue === '4', 'node-set to string');
+ }
+
+ const iterator = compiled.evaluate(xml);
+ const another = xml.createElementNS('urn:items', 'p:item');
+ xml.documentElement.appendChild(another);
+ check(iterator.invalidIteratorState, 'mutation invalidates compiled expression iterator');
+ check(compiled.evaluate(xml, 7).snapshotLength === 3, 're-evaluation sees current DOM');
+ check(first.snapshotLength === 2, 'prior snapshot stays stable');
+ check(document.createExpression('1 + 2').evaluate(document).numberValue === 3, 'scalar default type');
+ throws(() => evaluator.createExpression('//*['), 'SyntaxError', DOMException);
+ throws(() => document.createExpression('//unresolved:item'), 'NamespaceError', DOMException);
+ throws(() => compiled.evaluate(), 'TypeError', TypeError);
+ check(compiled.evaluate(xml, 65536).resultType === 4, 'result type uses WebIDL unsigned short conversion');
+ for (const receiver of [{}, Object.create(compiled), Object.create(XPathExpression.prototype), new Proxy(compiled, {})]) {
+ let converted = false;
+ throws(() => XPathExpression.prototype.evaluate.call(receiver, document, {valueOf() {converted=true;return 0;}}), 'TypeError', TypeError);
+ check(!converted, 'receiver check precedes type conversion');
+ }
+ let traps = 0;
+ const revoked = Proxy.revocable(xml, {});revoked.revoke();
+ const forged = Object.defineProperty({}, 'nodeType', {get() {traps++;return 9;}});
+ for (const context of [forged, Object.create(xml), new Proxy(xml, {get() {traps++;throw Error('trap');}}), revoked.proxy]) {
+ throws(() => compiled.evaluate(context), 'TypeError', TypeError);
+ }
+ check(traps === 0, 'native Node brand check does not run author getters or Proxy traps');
+ for (const [method, real] of [[Document.prototype.createExpression, document], [XPathEvaluator.prototype.createExpression, evaluator]]) {
+ for (const receiver of [{}, Object.create(real), new Proxy(real, {})]) {
+ let converted = false;
+ throws(() => method.call(receiver, {toString() {converted=true;return '1';}}), 'TypeError', TypeError);
+ check(!converted, 'createExpression receiver check precedes conversion');
+ }
+ }
+ const SavedExpression = XPathExpression;
+ const SavedResult = XPathResult;
+ try {
+ globalThis.XPathExpression = function FakeExpression() {};
+ globalThis.XPathResult = function FakeResult() {};
+ const expression = document.createExpression('3');
+ check(Object.getPrototypeOf(expression) === SavedExpression.prototype, 'intrinsic expression prototype');
+ check(expression.evaluate(document) instanceof SavedResult, 'intrinsic result prototype');
+ } finally {
+ globalThis.XPathExpression = SavedExpression;
+ globalThis.XPathResult = SavedResult;
+ }
+ Object.freeze(compiled);
+ check(compiled.evaluate(xml, 7).snapshotLength === 3, 'frozen wrapper preserves compiled state');
+
+ const exception = {};
+ let caught;
+ try { document.createExpression({toString() {throw exception;}}); } catch (e) {caught=e;}
+ check(caught === exception, 'expression conversion preserves abrupt completion');
+ const conversionOrder = [];
+ const noPrefix = document.createExpression({toString() {conversionOrder.push('expression');return '1';}}, {get lookupNamespaceURI() {throw Error('unused resolver getter');}});
+ check(conversionOrder.join() === 'expression' && noPrefix.evaluate(document).numberValue === 1, 'unused resolver is not invoked');
+
+ const frame = document.createElement('iframe');document.body.appendChild(frame);
+ const other = frame.contentWindow;
+ const foreign = other.document.createExpression('count(//body)');
+ check(foreign instanceof other.XPathExpression && !(foreign instanceof XPathExpression), 'expression relevant realm');
+ check(foreign.evaluate(document) instanceof other.XPathResult, 'result relevant realm');
+ check(other.Document.prototype.createExpression.call(document, '1') instanceof XPathExpression, 'creator receiver determines realm');
+ check(other.XPathExpression.prototype.evaluate.call(compiled, xml) instanceof XPathResult, 'expression receiver determines result realm');
+ throws(() => other.XPathExpression.prototype.evaluate.call({}, document), 'TypeError', other.TypeError);
+ frame.remove();
+ check(foreign.evaluate(document).numberValue === 1, 'compiled expression survives creator frame removal');
+ return true;
+})()
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_context_documents.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_context_documents.js
new file mode 100644
index 000000000..9565aca90
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom/xpath_context_documents.js
@@ -0,0 +1,84 @@
+(() => {
+ const check = (condition, message) => {
+ if (!condition) throw new Error(message);
+ };
+ const htmlNS = 'http://www.w3.org/1999/xhtml';
+ const xml = document.implementation.createDocument(htmlNS, 'html');
+ const html = document.implementation.createHTMLDocument('XPath');
+ const contexts = [xml, html];
+ for (const evaluator of [document, xml, html, new XPathEvaluator()]) {
+ for (const context of contexts) {
+ const result = evaluator.evaluate('//html', context, null, 7);
+ const expected = context === html ? [html.documentElement] : [];
+ check(result.snapshotLength === expected.length, 'context document controls HTML matching');
+ if (expected.length) {
+ check(result.snapshotItem(0) === expected[0], 'context document controls node identity');
+ }
+ const namespaced = evaluator.evaluate('//h:html', context, () => htmlNS, 7);
+ check(namespaced.snapshotLength === 1, 'explicit namespace matches both document types');
+ check(namespaced.snapshotItem(0) === context.documentElement, 'explicit namespace returns context tree');
+ }
+ }
+
+ const mixedCase = new DOMParser().parseFromString('<root><UPPER/><upper/></root>', 'text/xml');
+ for (const name of ['UPPER', 'upper']) {
+ const result = document.evaluate('//' + name, mixedCase, null, 7);
+ check(result.snapshotLength === 1, 'XML local names remain case sensitive');
+ check(result.snapshotItem(0).localName === name, 'HTML evaluator must preserve XML name case');
+ }
+
+ const source = new DOMParser().parseFromString('<root/>', 'text/xml');
+ const target = new DOMParser().parseFromString('<root/>', 'text/xml');
+ const moved = source.createElementNS('urn:items', 'item');
+ source.documentElement.appendChild(moved);
+ const existing = target.createElementNS('urn:items', 'item');
+ target.documentElement.appendChild(existing);
+ let calls = 0;
+ const result = document.evaluate('//p:item', moved, () => {
+ calls++;
+ target.documentElement.appendChild(target.adoptNode(moved));
+ return 'urn:items';
+ }, 7);
+ check(calls === 1, 'namespace resolver runs once for one prefix occurrence');
+ check(result.snapshotLength === 2, 'evaluation observes tree after resolver mutation');
+ check(result.snapshotItem(0) === existing && result.snapshotItem(1) === moved,
+ 'resolver adoption changes the context tree before evaluation');
+
+ const iterator = document.evaluate('//p:item', target, () => 'urn:items');
+ check(iterator.iterateNext() === existing, 'iterator reads context document');
+ target.documentElement.appendChild(target.createElement('new'));
+ check(iterator.invalidIteratorState, 'context document mutation invalidates iterator');
+ let invalidated = false;
+ try { iterator.iterateNext(); } catch (error) { invalidated = error.name === 'InvalidStateError'; }
+ check(invalidated, 'invalidated iterator throws');
+
+ for (const createDocument of [
+ () => new DOMParser().parseFromString('<root/>', 'text/xml'),
+ () => document.implementation.createDocument(null, 'root'),
+ () => document.implementation.createHTMLDocument('')
+ ]) {
+ const doc = createDocument();
+ const unrelated = createDocument();
+ const unrelatedIterator = document.evaluate('//*', unrelated);
+ const parent = doc.documentElement;
+ const node = parent.appendChild(doc.createElement('item'));
+ const text = node.appendChild(doc.createTextNode('before'));
+ for (const [name, mutate] of [
+ ['append', () => parent.appendChild(doc.createElement('next'))],
+ ['attribute', () => node.setAttribute('key', 'value')],
+ ['character data', () => { text.data = 'after'; }],
+ ['replace', () => parent.replaceChild(doc.createElement('replacement'), node)],
+ ['remove', () => parent.removeChild(parent.lastChild)]
+ ]) {
+ const iterator = document.evaluate('//*', doc);
+ const snapshot = document.evaluate('//*', doc, null, 7);
+ const first = snapshot.snapshotItem(0);
+ mutate();
+ check(iterator.invalidIteratorState, name + ' invalidates its document iterator');
+ check(!unrelatedIterator.invalidIteratorState, name + ' preserves unrelated document iterator');
+ check(!snapshot.invalidIteratorState && snapshot.snapshotItem(0) === first,
+ name + ' preserves prior snapshot');
+ }
+ }
+ return true;
+})()
diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rs
index 6d4baead6..ee32e318c 100644
--- a/moli-renderer-v8/src/web_api_interfaces.rs
+++ b/moli-renderer-v8/src/web_api_interfaces.rs
@@ -512,6 +512,7 @@ interfaces! {
XMLHttpRequestUpload: XMLHttpRequestEventTarget;
XMLSerializer;
XPathEvaluator;
+ XPathExpression;
XPathResult;
}
diff --git a/moli-xpath/src/lib.rs b/moli-xpath/src/lib.rs
index a2b722118..2cf89ad9c 100644
--- a/moli-xpath/src/lib.rs
+++ b/moli-xpath/src/lib.rs
@@ -21,7 +21,7 @@ use markup5ever::{LocalName, Namespace, Prefix};
pub use parser::{Error as ParserError, parse};
pub use snapshot::{
Snapshot, SnapshotBuilder, SnapshotNodeId, SnapshotValue, SnapshotXPathEvaluationError,
- evaluate_snapshot_xpath, evaluate_snapshot_xpath_with_resolver,
+ evaluate_parsed_snapshot_xpath, evaluate_snapshot_xpath, evaluate_snapshot_xpath_with_resolver,
evaluate_snapshot_xpath_with_resolver_detailed,
};
pub use value::{NodeSet, Value};
diff --git a/moli-xpath/src/snapshot.rs b/moli-xpath/src/snapshot.rs
index b64eaca08..885747fc9 100644
--- a/moli-xpath/src/snapshot.rs
+++ b/moli-xpath/src/snapshot.rs
@@ -273,10 +273,18 @@ where
{
let expression = parse(expression, namespace_resolver, is_in_html_document)
.map_err(SnapshotXPathEvaluationError::Parse)?;
+ evaluate_parsed_snapshot_xpath(snapshot, &expression, context_node)
+}
+
+pub fn evaluate_parsed_snapshot_xpath(
+ snapshot: &Snapshot,
+ expression: &crate::Expression,
+ context_node: SnapshotNodeId,
+) -> Result<SnapshotValue, SnapshotXPathEvaluationError> {
let context = snapshot
.node(context_node)
.ok_or(SnapshotXPathEvaluationError::ContextNodeNotInSnapshot)?;
- let value = evaluate_parsed_xpath::<SnapshotDom>(&expression, context)
+ let value = evaluate_parsed_xpath::<SnapshotDom>(expression, context)
.map_err(SnapshotXPathEvaluationError::Evaluation)?;
Ok(snapshot_value(value))
}