Skip to content

The headless browser for AI agents and web scraping

fix(js): document.write feeds one input stream per document

aech0ca7ac059910
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index ff2d73aa..41c82baa 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -319,6 +319,7 @@ impl DomTree {
self.inner.borrow()
}
+
/// Create and attach a native shadow-root node to `host`.
pub fn attach_shadow_root(
&self,
@@ -1397,7 +1398,7 @@ impl DomTree {
pub fn import_children_from(&self, parent_id: NodeId, source: &DomTree, source_node: NodeId) {
let source_children = source.children(source_node);
for source_child_id in source_children {
- self.import_node_from(parent_id, source, source_child_id);
+ let _ = self.import_node_from(parent_id, source, source_child_id);
}
}
@@ -1468,12 +1469,21 @@ impl DomTree {
}
}
- fn import_node_from(&self, parent_id: NodeId, source: &DomTree, source_node_id: NodeId) {
+ /// Copies a node together with its subtree from `source` and attaches it to `parent_id`.
+ /// Returns the copy of `source_node_id` itself, so that a caller that keeps parsing into
+ /// `source` can map the source to its copy.
+ pub fn import_node_from(
+ &self,
+ parent_id: NodeId,
+ source: &DomTree,
+ source_node_id: NodeId,
+ ) -> Option<NodeId> {
// Iterative DFS with an explicit (dest_parent, source_node) stack so a
// deeply nested source tree cannot overflow the thread stack and abort
// the process. Children are pushed in reverse so they are appended in
// document order (append_child always appends to the end, so each level
// keeps the source ordering).
+ let mut imported_root = None;
let mut stack = vec![(parent_id, source_node_id)];
while let Some((dest_parent, src_id)) = stack.pop() {
let node_data = {
@@ -1486,6 +1496,10 @@ impl DomTree {
let new_id = self.new_node(node_data);
self.append_child(dest_parent, new_id);
+ // The first node off the stack is source_node_id itself.
+ if imported_root.is_none() {
+ imported_root = Some(new_id);
+ }
// A <template>'s children hang off a separate contents document, so
// the child walk below never reaches them. Worse, the cloned data
@@ -1523,6 +1537,7 @@ impl DomTree {
stack.push((new_id, child_id));
}
}
+ imported_root
}
pub fn len(&self) -> usize {
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index e5ec0968..39ba17dc 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -106,11 +106,12 @@ const _DOM_MUTATION_COMMANDS = new Set([
"append_child", "insert_before", "remove_child",
"set_attribute", "remove_attribute",
"set_text_content", "set_inner_html", "set_inner_html_context",
- "set_fragment_html_executable",
+ "set_fragment_html_executable", "document_write",
]);
const _DOM_TREE_MUTATION_COMMANDS = new Set([
"append_child", "insert_before", "remove_child",
"set_inner_html", "set_inner_html_context", "set_fragment_html_executable",
+ "document_write",
]);
// Which realm this bootstrap closure belongs to. Every wrapper's methods come
// from its own realm's prototypes, so a DOM call names the document it belongs
@@ -2087,8 +2088,8 @@ class Node {
_detachStyleSheetsInSubtree(oldChild);
_registerWindowNamedTree(newChild);
_reconcileWindowNamedProperties(removedWindowNames);
- // As in appendChild and removeChild. A replacement is an insertion and a removal, an
- // observer saw neither one nor the other.
+ // As in appendChild and removeChild. A replacement is an insertion and a removal. An
+ // observer saw neither so far.
if (globalThis.__mutationObservers?.length) {
globalThis.__notifyMutation('childList', this._nid, [newChild._nid], [oldChild._nid]);
}
@@ -5340,16 +5341,52 @@ class Document extends Node {
if (!v) return;
Deno.core.ops.op_set_cookie(v);
}
+ // Inserts into the document's input stream, which the host keeps alive across calls.
+ // Parsing each call on its own would lose every construct that spans two of them. This is
+ // exactly how the SAP UI5 cachebuster writes its bootstrap tags: one call for "<script",
+ // one per attribute, then ">".
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
write(...args) {
var html = args.join('');
if (!html) return;
var body = this.body;
if (!body) return;
- var temp = this.createDocumentFragment();
- _dom("set_fragment_html_executable", temp._nid, _fragmentContextPayload('body', html));
- var children = Array.from(temp.childNodes);
- for (var i = 0; i < children.length; i++) {
- body.appendChild(children[i]);
+ // The host parses into the input stream and returns [[parent, node], …], parents first. The
+ // insertion stays here, because appendChild does more than append: it reports the
+ // mutation, registers window named access, and loads a written stylesheet.
+ var placements = _domParse("document_write", "", html) || [];
+ // The insertion point is the position of the running script. What it writes belongs
+ // behind it, not at the end of the body. The point moves along with every node placed,
+ // even across calls, so that a script's second call lands behind the first instead of
+ // directly behind the script again.
+ var scriptNid = globalThis.__currentScriptNid || 0;
+ var after = null;
+ if (scriptNid) {
+ var anchorNid = this._writeAnchorScript === scriptNid && this._writeAnchorNid
+ ? this._writeAnchorNid
+ : scriptNid;
+ var anchor = _wrap(anchorNid);
+ if (anchor && anchor.parentNode) after = anchor;
+ }
+ for (var i = 0; i < placements.length; i++) {
+ var parentNid = +placements[i][0];
+ var node = _wrap(+placements[i][1]);
+ if (!node) continue;
+ if (parentNid) {
+ var parent = _wrap(parentNid);
+ if (parent) parent.appendChild(node);
+ continue;
+ }
+ if (after) {
+ after.parentNode.insertBefore(node, after.nextSibling);
+ after = node;
+ } else {
+ body.appendChild(node);
+ }
+ }
+ if (scriptNid && after) {
+ this._writeAnchorScript = scriptNid;
+ this._writeAnchorNid = after._nid;
}
}
writeln(...args) {
@@ -5358,6 +5395,10 @@ class Document extends Node {
open() {
var body = this.body;
if (body) body.innerHTML = '';
+ // A new parse begins. Whatever the input stream still held is gone.
+ _dom("document_write_reset");
+ this._writeAnchorScript = 0;
+ this._writeAnchorNid = 0;
return this;
}
close() {
diff --git a/crates/obscura-js/src/lib.rs b/crates/obscura-js/src/lib.rs
index d071cdfe..4b0eedd7 100644
--- a/crates/obscura-js/src/lib.rs
+++ b/crates/obscura-js/src/lib.rs
@@ -6,6 +6,7 @@ pub mod module_loader;
pub mod ops;
pub mod runtime;
pub mod v8_flags;
+mod write_stream;
pub use markdown::HTML_TO_MARKDOWN_JS;
pub use v8_flags::set_v8_flags;
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 18c0ef80..3838dca5 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -25,6 +25,7 @@ use tokio::sync::Mutex;
use serde::Deserialize;
use crate::import_map::ImportMap;
+use crate::write_stream::DocumentWriteStream;
pub type InterceptCallback = Arc<
Mutex<
@@ -246,6 +247,9 @@ pub struct ObscuraState {
/// rather than wrapper state, because it must survive moves and clones and
/// because fragment parsing can create nodes before a JS wrapper exists.
pub(crate) already_started_scripts: RefCell<HashSet<NodeId>>,
+ /// The document's input stream for `document.write()`, created on the first call.
+ /// Why the calls share one parser is in `write_stream`.
+ pub(crate) write_stream: RefCell<Option<crate::write_stream::DocumentWriteStream>>,
}
/// A frame document waiting to be given a realm.
@@ -345,6 +349,7 @@ impl ObscuraState {
resolved_scroll: None,
import_map: Rc::new(RefCell::new(ImportMap::default())),
already_started_scripts: RefCell::new(HashSet::new()),
+ write_stream: RefCell::new(None),
}
}
}
@@ -1731,6 +1736,33 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
}
"true".into()
}
+ // document.write() feeds the document's input stream, so the calls
+ // share one parser and one tokenizer state. Returns the nodes that
+ // became complete with this call, for the caller to run scripts among.
+ // Returns [[parent, node], …], parents before children. A `parent` of 0 means the node
+ // belongs at the insertion point, which the caller knows. Nothing is inserted here:
+ // that must go through Node.appendChild on the JS side, because that call also reports
+ // the mutation, registers window named access, and loads a written stylesheet.
+ "document_write" => {
+ let mut slot = gs.write_stream.borrow_mut();
+ let stream = slot.get_or_insert_with(DocumentWriteStream::new);
+ let pairs: Vec<[i32; 2]> = stream
+ .write(&arg2, dom)
+ .iter()
+ .map(|placement| {
+ [
+ placement.parent.map_or(0, |id| id.index() as i32),
+ placement.node.index() as i32,
+ ]
+ })
+ .collect();
+ serde_json::to_string(&pairs).unwrap_or("[]".into())
+ }
+ // document.open() discards what the input stream holds and starts over.
+ "document_write_reset" => {
+ *gs.write_stream.borrow_mut() = None;
+ "true".into()
+ }
"set_text_content" => {
let nid = arg1.parse::<u32>().unwrap_or(0);
dom.with_node_mut(NodeId::new(nid), |n| match &mut n.data {
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 81922731..e529eb3c 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -16099,6 +16099,159 @@ mod tests {
assert_eq!(result, serde_json::json!(["range", "write"]));
}
+ // One stream per document. The tokenizer carries its state across the calls.
+ // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
+ #[test]
+ fn document_write_joins_an_element_split_across_calls() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ document.write('<di');
+ document.write('v id="split">');
+ document.write('content</div>');
+ const el = document.getElementById('split');
+ return el ? el.textContent : null;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("content"));
+ }
+
+ #[test]
+ fn document_write_joins_a_tag_name_split_across_calls() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ document.write('<spa');
+ document.write('n id="half">x</span>');
+ const el = document.getElementById('half');
+ return el ? el.tagName : null;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("SPAN"));
+ }
+
+ // The shape the UI5 cachebuster writes: "<script", one per attribute, then ">".
+ #[test]
+ fn document_write_runs_a_script_split_across_calls() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ globalThis.__splitScriptRan = false;
+ document.write('<scr' + 'ipt');
+ document.write(' id="split-script"');
+ document.write('>');
+ document.write('globalThis.__splitScriptRan = true;');
+ document.write('<\/scr' + 'ipt>');
+ return [!!document.getElementById('split-script'), globalThis.__splitScriptRan];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!([true, true]));
+ }
+
+ // A script in the <head> inserts behind itself, so that what it writes runs before what
+ // the parser saw after it.
+ #[test]
+ fn document_write_inserts_at_the_writing_scripts_position() {
+ let mut rt = setup_runtime(
+ r#"<html><head><script id="writer"></script></head><body><p id="existing">x</p></body></html>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ // What the production path sets while a script runs; bootstrap.js
+ // assigns __currentScriptNid around every script it prepares.
+ globalThis.__currentScriptNid = document.getElementById('writer')._nid;
+ document.write('<span id="written"></span>');
+ return JSON.stringify({
+ head: Array.from(document.head.children).map(e => e.id || e.tagName),
+ body: Array.from(document.body.children).map(e => e.id || e.tagName),
+ });
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!(r#"{"head":["writer","written"],"body":["existing"]}"#)
+ );
+ }
+
+ // Holding back until the close would lose everything written after it. It belongs inside.
+ #[test]
+ fn document_write_shows_an_element_that_is_never_closed() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ document.write('<div id="unclosed">hello');
+ const el = document.getElementById('unclosed');
+ return el ? el.textContent : null;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("hello"));
+ }
+
+ #[test]
+ fn document_write_grows_an_open_element_across_calls() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ document.write('<div id="wrap">');
+ document.write('<span id="inner">y</span>');
+ const inner = document.getElementById('inner');
+ return JSON.stringify({
+ wrap: !!document.getElementById('wrap'),
+ inner: !!inner,
+ nested: !!(inner && inner.parentElement && inner.parentElement.id === 'wrap'),
+ });
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!(r#"{"wrap":true,"inner":true,"nested":true}"#)
+ );
+ }
+
+ // Writing goes through the same insertion steps as any other insertion.
+ #[test]
+ fn document_write_reports_to_mutation_observers() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ globalThis.__seen = [];
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.addedNodes) globalThis.__seen.push(node.nodeName);
+ }
+ });
+ observer.observe(document.body, { childList: true });
+ document.write('<span id="watched">z</span>');
+ observer.takeRecords().forEach((record) => {
+ for (const node of record.addedNodes) globalThis.__seen.push(node.nodeName);
+ });
+ return globalThis.__seen.join(',');
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("SPAN"));
+ }
+
// before(), after() and replaceWith() all go through parent.insertBefore. replaceChild
// also goes there in the fragment branch. AGENTS.md requires whoever touches insertBefore
// to check them: the order of reference node versus parent nid is easy to break. The test
@@ -16166,4 +16319,38 @@ mod tests {
.unwrap();
assert_eq!(result, serde_json::json!("SPAN"));
}
+
+ #[test]
+ fn document_write_registers_window_named_access() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ document.write('<img name="namedImage" src="x.png">');
+ return typeof window.namedImage;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("object"));
+ }
+
+ #[test]
+ fn document_write_keeps_call_order_at_the_insertion_point() {
+ let mut rt = setup_runtime(
+ r#"<html><head><script id="writer"></script></head><body></body></html>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ var scriptTestSetup = true;
+ globalThis.__currentScriptNid = document.getElementById('writer')._nid;
+ document.write('<span id="one"></span>');
+ document.write('<span id="two"></span>');
+ return Array.from(document.head.children).map(e => e.id).join(',');
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!("writer,one,two"));
+ }
}
diff --git a/crates/obscura-js/src/write_stream.rs b/crates/obscura-js/src/write_stream.rs
new file mode 100644
index 00000000..3f45a9bb
--- /dev/null
+++ b/crates/obscura-js/src/write_stream.rs
@@ -0,0 +1,195 @@
+//! The document's input stream for `document.write()`.
+//!
+//! There is one input stream per document, and the tokenizer carries its state across calls.
+//! A construct may therefore be split at any point, even in the middle of a tag name.
+//! <https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write>
+//!
+//! This module inserts nothing itself. It creates the nodes and reports where each belongs,
+//! because `Node.appendChild` on the JS side reports the mutation at the same time, registers
+//! window named access, and loads a written stylesheet.
+
+use std::cell::RefCell;
+use std::collections::{HashMap, HashSet};
+
+use html5ever::driver::{parse_fragment, ParseOpts, Parser};
+use html5ever::tendril::TendrilSink;
+use html5ever::tree_builder::Tracer;
+use html5ever::{local_name, ns, QualName};
+use obscura_dom::{DomTree, NodeData, NodeId};
+
+/// Collects every node the TreeBuilder still holds.
+///
+/// `TreeSink::pop` would be the obvious signal for "done" and does not deliver: of html5ever's
+/// three ways to drain the stack of open elements, only one reports to the sink. An end tag
+/// usually goes through `pop_until`, which does not.
+#[derive(Default)]
+struct RetainedNodes(RefCell<HashSet<NodeId>>);
+
+impl Tracer for RetainedNodes {
+ type Handle = NodeId;
+
+ fn trace_handle(&self, node: &NodeId) {
+ self.0.borrow_mut().insert(*node);
+ }
+}
+
+/// `parent` is `None` for a node at the head of the input stream, which belongs at the
+/// insertion point.
+pub(crate) struct Placement {
+ pub(crate) parent: Option<NodeId>,
+ pub(crate) node: NodeId,
+}
+
+/// A `<script>` runs as soon as it is inserted, so a half-written one must not.
+/// A `<template>` keeps its children in its own contents document, which a child walk does
+/// not reach, so it can only be copied as a whole.
+fn needs_to_be_complete(source: &DomTree, node: NodeId) -> bool {
+ source
+ .get_node(node)
+ .and_then(|n| n.as_element().map(|name| name.local.clone()))
+ .is_some_and(|local| local == local_name!("script") || local == local_name!("template"))
+}
+
+pub(crate) struct DocumentWriteStream {
+ parser: Parser<DomTree>,
+ /// Maps a node of the parser tree to its copy in the document. A node missing here has
+ /// not been handed over yet.
+ handed_over: HashMap<NodeId, NodeId>,
+ /// Staging for copying a whole subtree, reused.
+ staging: Option<NodeId>,
+}
+
+impl DocumentWriteStream {
+ pub(crate) fn new() -> Self {
+ // Scripting enabled, as with the fragment parser behind innerHTML.
+ let context = QualName::new(None, ns!(html), local_name!("body"));
+ DocumentWriteStream {
+ parser: parse_fragment(DomTree::new(), ParseOpts::default(), context, vec![], true),
+ handed_over: HashMap::new(),
+ staging: None,
+ }
+ }
+
+ /// Pushes a call's arguments into the input stream and mirrors what the parser made of them.
+ /// Returns the nodes to insert, parents before children.
+ pub(crate) fn write(&mut self, html: &str, dom: &DomTree) -> Vec<Placement> {
+ self.parser.process(html.into());
+
+ let retained = RetainedNodes::default();
+ self.parser.tokenizer.sink.trace_handles(&retained);
+ let retained = retained.0.into_inner();
+
+ // Separate fields: the parser tree is read, the mapping is written.
+ let source = &self.parser.tokenizer.sink.sink;
+ let handed_over = &mut self.handed_over;
+ let staging = &mut self.staging;
+
+ let root = source.fragment_root();
+ let mut placements = Vec::new();
+ // Only look at what is new. A walk over all children would cost as much per call as
+ // the input stream written so far is long, so quadratic over a thousand calls. Measured at
+ // 5000 calls: 852 ms versus 4130 ms.
+ let mut stack: Vec<NodeId> = fresh_children(source, root, handed_over);
+
+ while let Some(current) = stack.pop() {
+ let node = match source.get_node(current) {
+ Some(node) => node,
+ None => continue,
+ };
+
+ if let Some(&copy) = handed_over.get(&current) {
+ // A text node at the end of the input stream grows with every call and stays the
+ // same node. Elements no longer change after their creation.
+ if node.is_text() {
+ let text = source.text_content(current);
+ dom.with_node_mut(copy, |n| {
+ if let NodeData::Text { contents } = &mut n.data {
+ *contents = text;
+ }
+ });
+ }
+ for child in fresh_children(source, current, handed_over) {
+ stack.push(child);
+ }
+ continue;
+ }
+
+ let parent = match node.parent {
+ Some(p) if p == root => None,
+ // If the parent is held back, this one waits along.
+ Some(p) => match handed_over.get(&p) {
+ Some(&copy) => Some(copy),
+ None => continue,
+ },
+ None => continue,
+ };
+
+ if needs_to_be_complete(source, current) {
+ if retained.contains(&current) {
+ continue;
+ }
+ let container = *staging.get_or_insert_with(|| dom.new_node(NodeData::Document));
+ let Some(copy) = dom.import_node_from(container, source, current) else {
+ continue;
+ };
+ dom.detach(copy);
+ map_subtree(source, current, dom, copy, handed_over);
+ placements.push(Placement { parent, node: copy });
+ continue;
+ }
+
+ // Handed over shallow and left to grow in place. That makes an element that is
+ // never closed appear at once instead of never.
+ let copy = dom.new_node(node.data.clone());
+ handed_over.insert(current, copy);
+ placements.push(Placement { parent, node: copy });
+ for child in fresh_children(source, current, handed_over) {
+ stack.push(child);
+ }
+ }
+
+ placements
+ }
+}
+
+/// The children of `parent` still to do, as a stack: the top element is processed first.
+///
+/// The walk goes backward from the last child and stops at the first one already handed over.
+/// The parser only appends at the back, so everything before it is done. This one already
+/// handed-over child comes back along, because a text node at the end of the input stream keeps
+/// growing and an open element still receives children.
+fn fresh_children(
+ source: &DomTree,
+ parent: NodeId,
+ handed_over: &HashMap<NodeId, NodeId>,
+) -> Vec<NodeId> {
+ let mut stack = Vec::new();
+ let mut current = source.get_node(parent).and_then(|n| n.last_child);
+ while let Some(id) = current {
+ stack.push(id);
+ if handed_over.contains_key(&id) {
+ break;
+ }
+ current = source.get_node(id).and_then(|n| n.prev_sibling);
+ }
+ stack
+}
+
+/// After copying, both trees have the same shape, so a lockstep walk aligns the nodes.
+fn map_subtree(
+ source: &DomTree,
+ source_node: NodeId,
+ dom: &DomTree,
+ copy: NodeId,
+ handed_over: &mut HashMap<NodeId, NodeId>,
+) {
+ let mut pairs = vec![(source_node, copy)];
+ while let Some((from, to)) = pairs.pop() {
+ handed_over.insert(from, to);
+ let from_children = source.children(from);
+ let to_children = dom.children(to);
+ for (from_child, to_child) in from_children.into_iter().zip(to_children) {
+ pairs.push((from_child, to_child));
+ }
+ }
+}