The headless browser for AI agents and web scraping
fix(js): clone documents and attributes without reparsing
SGavrl19fa7a35fdee
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 7a52ddee..8fb3cad3 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -2760,6 +2760,13 @@ function _replaceAllChildren(parent, node, method) {}}+const _attributePositionOrder = new WeakMap();+let _nextAttributePositionOrder = 0;+function _attributePositionKey(node) {+ if (!_attributePositionOrder.has(node)) _attributePositionOrder.set(node, ++_nextAttributePositionOrder);+ return _attributePositionOrder.get(node);+}+class Node {static ELEMENT_NODE = 1;static ATTRIBUTE_NODE = 2;@@ -2786,6 +2793,15 @@ class Node {get ownerDocument() { return _nodeDocumentOf(this); }// https://dom.spec.whatwg.org/#dom-node-baseuriget baseURI() {+ if (_foreignDocumentCount) {+ const doc = this.nodeType === 9 ? this : this.ownerDocument;+ if (doc && doc !== globalThis.document) {+ const url = doc.URL || "about:blank";+ const base = doc.querySelector('base[href]');+ try { return base ? new URL(base.getAttribute('href'), url).href : url; }+ catch (e) { return url; }+ }+ }try { return _documentBase(); } catch (e) { return ""; }}get textContent() { return _domParse("text_content", this._nid) ?? ""; }@@ -2899,6 +2915,17 @@ class Node {hasChildNodes() { return _dom("has_child_nodes", this._nid) === "true"; }cloneNode(deep) {const t = this.nodeType;+ if (t === 9) {+ const xml = this instanceof XMLDocument || (this._documentShim && _isXMLDocument(this));+ const clone = _createDetachedDocument(this.contentType, !!xml);+ clone._documentURL = this.URL;+ clone._documentEncoding = this.characterSet;+ clone._documentCompatMode = this.compatMode;+ if (deep) {+ for (const child of this.childNodes) clone.appendChild(child.cloneNode(true));+ }+ return clone;+ }if (t === 1) {return _wrap(+_dom("clone_node", this._nid, deep ? "true" : "false"));}@@ -2937,6 +2964,25 @@ class Node {}compareDocumentPosition(other) {if (!other) return 0;+ if (this === other) return 0;+ if (this.nodeType === 2 || other.nodeType === 2) {+ const ownAttr = this.nodeType === 2, otherAttr = other.nodeType === 2;+ const own = ownAttr ? this.ownerElement : this;+ const target = otherAttr ? other.ownerElement : other;+ if (!own || !target) {+ return 33 | (_attributePositionKey(this) < _attributePositionKey(other) ? 4 : 2);+ }+ if (own === target) {+ if (ownAttr && otherAttr) {+ const names = own.getAttributeNames();+ const a = names.indexOf(this.name), b = names.indexOf(other.name);+ return a === b ? 0 : 32 | (a < b ? 4 : 2);+ }+ return ownAttr ? 10 : 20;+ }+ const order = own.compareDocumentPosition(target);+ return order & ~(ownAttr ? 16 : 0) & ~(otherAttr ? 8 : 0);+ }if (this._nid === other._nid) return 0;// Different roots: DISCONNECTED | IMPLEMENTATION_SPECIFIC plus a stable// (consistent across calls) PRECEDING/FOLLOWING bit, chosen by node-id order.@@ -3590,9 +3636,9 @@ class NamedNodeMap {return _domParse("attribute_names", this._element._nid) || [];}_attr(name) {- const value = this._element.getAttribute(name);- if (value === null) return null;- const attr = new Attr(name, value, null, null);+ const info = _domParse("attribute_metadata", this._element._nid, name);+ if (!info) return null;+ const attr = new Attr(info.name, info.value, info.namespaceURI, info.prefix);attr.ownerElement = this._element;return attr;}@@ -3606,7 +3652,13 @@ class NamedNodeMap {return this._names().includes(name) ? this._attr(name) : null;}getNamedItemNS(namespaceURI, localName) {- return this.getNamedItem(localName);+ const ns = namespaceURI == null || namespaceURI === '' ? null : String(namespaceURI);+ const local = String(localName);+ for (const name of this._names()) {+ const attr = this._attr(name);+ if (attr && attr.namespaceURI === ns && attr.localName === local) return attr;+ }+ return null;}setNamedItem(attr) {if (!attr || typeof attr.name !== "string") return null;@@ -6157,7 +6209,7 @@ class Document extends Node {title.textContent = value;}get URL() {- if (this._detached) return "about:blank";+ if (this._detached) return this._documentURL || "about:blank";const get = _documentRealmMember(this, 'URL');return get ? Reflect.apply(get, this, []) : (_domParse("document_url") ?? "");}@@ -6199,6 +6251,7 @@ class Document extends Node {get nodeName() { return "#document"; }get ownerDocument() { return null; } // Document has no ownerDocumentget compatMode() {+ if (this._detached) return this._documentCompatMode || "CSS1Compat";const get = _documentRealmMember(this, 'compatMode');return get ? Reflect.apply(get, this, []): (this._nid == null ? "CSS1Compat" : _dom("document_compat_mode"));@@ -6207,7 +6260,8 @@ class Document extends Node {// (HTTP Content-Type -> <meta charset>). characterSet/charset/inputEncoding// are WHATWG aliases. A node-less document (DOMParser/createDocument) has no// backing encoding and reports UTF-8.- get characterSet() { return (this._nid === undefined || this._nid === null || this._detached) ? "UTF-8" : _docEncoding(); }+ get characterSet() { return this._documentEncoding || ((this._nid === undefined || this._nid === null || this._detached) ? "UTF-8" : _docEncoding()); }+ get [Symbol.toStringTag]() { return this instanceof XMLDocument ? "XMLDocument" : (_isXMLDocument(this) ? "Document" : "HTMLDocument"); }get charset() { return this.characterSet; }get inputEncoding() { return this.characterSet; }get contentType() {@@ -12111,9 +12165,7 @@ const _checkXmlWellFormed = (html) => {// so anything that did `new DOMParser().parseFromString(s, 'text/html')` and// then read `.body.innerHTML` mutated the LIVE page (jQuery 3.x's selector// feature-detect writes `<form></form>` and wiped real bodies). We parse the-// input into a detached `<html>` element and wrap it so the common Document-// API surface (body / head / documentElement / querySelector* / getElementById /-// getElementsByTagName / getElementsByClassName / title / cloneNode) works.+// HTML uses an inert document parse; XML retains the limited HTML-backed shim.// Conservative XML well-formedness check. obscura has no XML parser, so this// only decides whether to surface a <parsererror> (it does not build an XML// tree). It flags clear structural errors — mismatched or unclosed tags,@@ -12172,7 +12224,14 @@ const _escapeXmlErrorText = (text) =>globalThis.DOMParser = class DOMParser {parseFromString(source, mimeType) {const html = String(source ?? "");+ const parserURL = document.URL;const isXml = typeof mimeType === "string" && /xml/i.test(mimeType);+ if (!isXml) {+ const doc = _createDetachedDocument("text/html", false);+ doc._documentURL = parserURL;+ doc._documentCompatMode = _dom("parse_html_document", doc._nid, html);+ return doc;+ }const root = document.createElement("html");// For XML mime types, surface a <parsererror> on clearly-malformed input so@@ -12255,14 +12314,13 @@ globalThis.DOMParser = class DOMParser {get lastChild() { return root; },get children() { return [root]; },get childNodes() { return [root]; },- // Document metadata the WHATWG interface exposes; DOMParser documents have- // URL about:blank, are already fully parsed, and carry no stylesheets.- get URL() { return "about:blank"; },- get documentURI() { return "about:blank"; },+ // Inert documents inherit the parser realm's URL, not its browsing context.+ get URL() { return parserURL; },+ get documentURI() { return parserURL; },get domain() { return _incumbentDocumentDomain(); },set domain(value) { String(value); _throwDocumentDomainSecurityError(); },get referrer() { return ""; },- get baseURI() { return "about:blank"; },+ get baseURI() { return Node.prototype.__lookupGetter__('baseURI').call(this); },get compatMode() { return "CSS1Compat"; },get characterSet() { return "UTF-8"; },get charset() { return "UTF-8"; },@@ -12322,7 +12380,7 @@ globalThis.DOMParser = class DOMParser {_documentShim: true,get doctype() { return this._docType; },cloneNode: function (deep) {- return new DOMParser().parseFromString(root.outerHTML, mimeType);+ return Node.prototype.cloneNode.call(this, deep);},contains(n) { return root.contains ? root.contains(n) : false; },addEventListener() {}, removeEventListener() {}, dispatchEvent() { return true; },@@ -18291,20 +18349,63 @@ if (!Document.prototype.getElementsByTagNameNS) {// ---- Attr nodes and createAttribute ----// Attr class: represents attribute nodes (nodeType 2)if (!globalThis.Attr) {- globalThis.Attr = class Attr {+ globalThis.Attr = class Attr extends Node {constructor(name, value = '', namespaceURI = null, prefix = null) {+ super(undefined);this.name = name;- this.localName = name;- this.value = value;+ this.localName = prefix ? name.slice(prefix.length + 1) : name;+ this._value = String(value);this.namespaceURI = namespaceURI;this.prefix = prefix;this.ownerElement = null;this.specified = true;}+ get [Symbol.toStringTag]() { return 'Attr'; }+ get ownerDocument() { return this.ownerElement?.ownerDocument || this._nodeDocument || document; }+ get value() {+ if (this.ownerElement) {+ const value = this.namespaceURI+ ? this.ownerElement.getAttributeNS(this.namespaceURI, this.localName)+ : this.ownerElement.getAttribute(this.name);+ if (value !== null) return value;+ }+ return this._value;+ }+ set value(value) {+ this._value = String(value);+ if (this.ownerElement) {+ if (this.namespaceURI) this.ownerElement.setAttributeNS(this.namespaceURI, this.name, this._value);+ else this.ownerElement.setAttribute(this.name, this._value);+ }+ }get nodeName() { return this.name; }get nodeValue() { return this.value; }set nodeValue(v) { this.value = v; }get nodeType() { return 2; }+ get textContent() { return this.value; }+ set textContent(value) { this.value = value == null ? '' : value; }+ // Attributes have no arena node or tree children.+ get parentNode() { return null; }+ get parentElement() { return null; }+ get childNodes() { return _nodeList([]); }+ get firstChild() { return null; }+ get lastChild() { return null; }+ get nextSibling() { return null; }+ get previousSibling() { return null; }+ get isConnected() { return false; }+ hasChildNodes() { return false; }+ getRootNode() { return this; }+ contains(other) { return other === this; }+ isSameNode(other) { return other === this; }+ isEqualNode(other) {+ return other?.nodeType === 2 && this.namespaceURI === other.namespaceURI+ && this.prefix === other.prefix && this.localName === other.localName && this.value === other.value;+ }+ cloneNode() {+ const clone = new Attr(this.name, this.value, this.namespaceURI, this.prefix);+ clone._nodeDocument = this.ownerDocument;+ return clone;+ }};}@@ -18337,7 +18438,9 @@ if (!Document.prototype.createAttribute) {if (!_ns_isValidXmlName(name)) {throw new DOMException('Invalid attribute name', 'InvalidCharacterError');}- return new Attr(name, '', null, null);+ const attr = new Attr(name, '', null, null);+ attr._nodeDocument = this;+ return attr;};_markNative(Document.prototype.createAttribute);}@@ -18364,7 +18467,9 @@ if (!Document.prototype.createAttributeNS) {throw new DOMException('Invalid attribute name', 'InvalidCharacterError');}}- return new Attr(qn, '', ns, prefix);+ const attr = new Attr(qn, '', ns, prefix);+ attr._nodeDocument = this;+ return attr;};_markNative(Document.prototype.createAttributeNS);}@@ -18372,11 +18477,7 @@ if (!Document.prototype.createAttributeNS) {// Element.prototype.getAttributeNode: return an Attr node or nullif (!Element.prototype.getAttributeNode) {Element.prototype.getAttributeNode = function(name) {- const val = this.getAttribute(name);- if (val === null) return null;- const attr = new Attr(name, val, null, null);- attr.ownerElement = this;- return attr;+ return this.attributes.getNamedItem(_htmlAttrName(this, String(name)));};_markNative(Element.prototype.getAttributeNode);}@@ -18384,12 +18485,7 @@ if (!Element.prototype.getAttributeNode) {// Element.prototype.getAttributeNodeNS: return a namespaced Attr node or nullif (!Element.prototype.getAttributeNodeNS) {Element.prototype.getAttributeNodeNS = function(namespaceURI, localName) {- const val = this.getAttributeNS(namespaceURI, localName);- if (val === null) return null;- const name = String(localName || '');- const attr = new Attr(name, val, namespaceURI ? String(namespaceURI) : null, null);- attr.ownerElement = this;- return attr;+ return this.attributes.getNamedItemNS(namespaceURI, localName);};_markNative(Element.prototype.getAttributeNodeNS);}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 741f9cf4..c1f499dd 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -2644,6 +2644,33 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->.flatten();serde_json::to_string(&val).unwrap_or("null".into())}+ "parse_html_document" => {+ let root = NodeId::new(arg1.parse::<u32>().unwrap_or(0));+ if root == dom.document() || !dom.with_node(root, |node| matches!(node.data, NodeData::Document)).unwrap_or(false)+ || !dom.children(root).is_empty()+ {+ return "null".into();+ }+ use html5ever::tendril::TendrilSink;+ let mut options = html5ever::ParseOpts::default();+ options.tree_builder.scripting_enabled = false;+ let parsed = html5ever::parse_document(DomTree::new(), options).from_utf8().one(arg2.as_bytes());+ dom.import_children_from(root, &parsed, parsed.document());+ mark_script_subtree_started(&gs, root);+ if parsed.is_quirks() { "BackCompat" } else { "CSS1Compat" }.into()+ }+ "attribute_metadata" => {+ let nid = arg1.parse::<u32>().unwrap_or(0);+ let info = dom.with_node(NodeId::new(nid), |node| {+ let attr = node.attrs()?.iter().find(|attr| attr.qualified_name_eq(&arg2))?;+ Some(serde_json::json!({+ "name": attr.qualified_name(), "value": attr.value,+ "namespaceURI": if attr.name.ns.is_empty() { None } else { Some(attr.name.ns.as_ref()) },+ "prefix": attr.name.prefix.as_ref().map(|prefix| prefix.as_ref()),+ }))+ }).flatten();+ serde_json::to_string(&info).unwrap_or("null".into())+ }"attribute_names" => {let nid = arg1.parse::<u32>().unwrap_or(0);let names: Vec<String> = domdiff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex e273ccb8..cab9e962 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -19995,6 +19995,103 @@ mod tests {);}+ #[test]+ fn document_clones_preserve_metadata_and_native_control_state() {+ let mut rt = setup_runtime("<!doctype html><!--before--><html lang=en><head><base href='http://example.com/articles/'><title>Article</title></head><body><input id=field value=initial><template id=t><p>Template</p></template><p id=copy>Original</p></body></html><!--after-->");+ assert_eq!(rt.evaluate(r#"(() => {+ document.getElementById('field').value='edited';+ const shallow=document.cloneNode(false), clone=document.cloneNode(true);+ if (!shallow || !clone) return 'missing document clone';+ clone.getElementById('copy').textContent='Changed';+ return [clone instanceof Document, clone.nodeType, clone.ownerDocument, clone.defaultView,+ clone.URL, clone.documentURI, clone.baseURI, clone.contentType, clone.compatMode,+ clone.characterSet, shallow.childNodes.length, shallow.URL, shallow.compatMode,+ Array.from(clone.childNodes,n=>n.nodeType), clone.doctype.name,+ clone.documentElement.ownerDocument===clone, clone.body.ownerDocument===clone,+ clone.getElementById('field').value, clone.getElementById('field').getAttribute('value'),+ clone.getElementById('t').content.textContent, document.getElementById('copy').textContent];+ })()"#).unwrap(), serde_json::json!([true,9,null,null,"http://example.com/test","http://example.com/test","http://example.com/articles/","text/html","CSS1Compat","UTF-8",0,"http://example.com/test","CSS1Compat",[10,8,1,8],"html",true,true,"edited","initial","Template","Original"]));+ }++ #[test]+ fn document_clones_preserve_xml_interfaces_namespaces_and_quirks_mode() {+ let mut rt = setup_runtime("<p>Quirks</p>");+ assert_eq!(rt.evaluate(r#"(() => {+ const source=document.implementation.createDocument('urn:article','p:article',null);+ source.documentElement.setAttributeNS('urn:meta','m:kind','article');+ const clone=source.cloneNode(true), quirks=document.cloneNode(false);+ if (!clone || !quirks) return 'missing document clone';+ return [clone instanceof XMLDocument, clone.contentType, clone.documentElement.nodeName,+ clone.documentElement.namespaceURI, clone.documentElement.getAttributeNS('urn:meta','kind'),+ clone.documentElement.ownerDocument===clone, clone.defaultView, quirks.compatMode];+ })()"#).unwrap(), serde_json::json!([true,"application/xml","p:article","urn:article","article",true,null,"BackCompat"]));+ }++ #[test]+ fn attribute_clones_are_independent_nodes_with_the_original_namespace_and_owner() {+ let mut rt = setup_runtime("<div id=source data-value=old></div>");+ assert_eq!(rt.evaluate(r#"(() => {+ const source=document.getElementById('source');+ source.setAttributeNS('urn:meta','m:kind','article');+ const attr=source.attributes.getNamedItem('m:kind');+ if (typeof attr.cloneNode!=='function') return 'missing attribute clone';+ const clone=attr.cloneNode(true);+ clone.value='copy';+ const foreign=document.implementation.createHTMLDocument('Foreign');+ const detached=foreign.createAttributeNS('urn:meta','m:kind');+ detached.value='detached';+ const detachedClone=detached.cloneNode(false);+ return [attr instanceof Attr, attr instanceof Node, Object.prototype.toString.call(attr),+ clone.nodeType, clone.name, clone.localName, clone.namespaceURI, clone.prefix,+ clone.ownerElement, clone.ownerDocument===document, clone.parentNode,+ clone.childNodes.length, clone.getRootNode()===clone, clone.isConnected,+ clone.value, clone.nodeValue, clone.textContent, source.getAttributeNS('urn:meta','kind'),+ clone!==attr, !clone.isSameNode(attr), !clone.isEqualNode(attr),+ detachedClone.ownerDocument===foreign, detachedClone.value, detachedClone.namespaceURI];+ })()"#).unwrap(), serde_json::json!([true,true,"[object Attr]",2,"m:kind","kind","urn:meta","m",null,true,null,0,true,false,"copy","copy","copy","article",true,true,true,true,"detached","urn:meta"]));+ }++ #[test]+ fn parsed_document_clones_keep_the_url_and_do_not_reparse_or_run_scripts() {+ let mut rt = setup_runtime("<!doctype html><title>Live</title><p>Live body</p>");+ assert_eq!(rt.evaluate(r#"(() => {+ const parsed=new DOMParser().parseFromString('<title>Inert</title><script>window.executed=true</script><input id=field value=initial>','text/html');+ parsed.getElementById('field').value='edited';+ const clone=parsed.cloneNode(true), shallow=parsed.cloneNode(false);+ return [parsed.URL, clone.URL, clone instanceof Document, clone.defaultView,+ clone.getElementById('field').value, clone.getElementById('field').getAttribute('value'),+ clone.getElementById('field').ownerDocument===clone, shallow.childNodes.length,+ document.title, typeof window.executed];+ })()"#).unwrap(), serde_json::json!(["http://example.com/test","http://example.com/test",true,null,"edited","initial",true,0,"Live","undefined"]));+ }++ #[test]+ fn attribute_node_positions_do_not_alias_missing_arena_ids() {+ let mut rt = setup_runtime("<div id=x a=1 b=2></div>");+ assert_eq!(rt.evaluate(r#"(() => {+ const el=document.getElementById('x'), a=el.attributes[1], b=el.attributes[2];+ const clone=a.cloneNode(), forward=clone.compareDocumentPosition(a), reverse=a.compareDocumentPosition(clone);+ return [a.compareDocumentPosition(el),el.compareDocumentPosition(a),+ a.compareDocumentPosition(b),b.compareDocumentPosition(a),+ (forward & 33)===33,(reverse & 33)===33,+ (forward & 6)===(reverse & 4 ? 2 : 4),clone.compareDocumentPosition(clone)];+ })()"#).unwrap(), serde_json::json!([10,20,36,34,true,true,true,0]));+ }++ #[test]+ fn inert_html_parsing_preserves_document_root_attributes_and_structure() {+ let mut rt = setup_runtime("<title>Live page</title><p>Live content</p>");+ assert_eq!(rt.evaluate(r#"(() => {+ const parsed=new DOMParser().parseFromString('<!doctype html><!--before--><html lang=fr dir=rtl data-root=article><head><title>Parsed</title></head><body><template id=t><p>Template</p></template><script>window.executed=true</script><noscript><img src=fallback.jpg></noscript><p id=content>Article</p></body></html><!--after-->','text/html');+ return [parsed instanceof Document, parsed.URL, parsed.documentElement.lang,+ parsed.documentElement.dir, parsed.documentElement.getAttribute('data-root'),+ Array.from(parsed.childNodes,n=>n.nodeType), parsed.doctype?.name,+ parsed.body.ownerDocument===parsed, parsed.getElementById('t').content.textContent,+ parsed.title, parsed.compatMode, parsed.defaultView, document.title, typeof window.executed,+ parsed.querySelector('noscript img')?.getAttribute('src')];+ })()"#).unwrap(), serde_json::json!([true,"http://example.com/test","fr","rtl","article",[10,8,1,8],"html",true,"Template","Parsed","CSS1Compat",null,"Live page","undefined","fallback.jpg"]));+ }+#[test]fn deep_document_element_clone_stays_an_independent_html_element() {let mut rt = setup_runtime(diff --git a/docs/Extract-data.md b/docs/Extract-data.mdindex 501a52b2..4469a1da 100644--- a/docs/Extract-data.md+++ b/docs/Extract-data.md@@ -82,3 +82,19 @@ obscura fetch https://my-spa.example --wait-until load --dump markdownobscura fetch https://example.com --dump markdown > example.mdobscura fetch https://example.com --dump text --quiet | wc -w```++## Reader libraries++After loading a reader library such as [Mozilla Readability](https://github.com/mozilla/readability),+run it on a document clone to leave the page unchanged:++```javascript+const article = new Readability(document.cloneNode(true)).parse();+```++Obscura does not bundle Readability. Supply the library through your automation+client before evaluating this expression. Document clones preserve metadata and+live form-control state. Attribute clones retain their value and namespace.+`DOMParser` HTML documents preserve the document structure and root attributes,+inherit the parser's document URL, and do not execute scripts. XML parsing still+uses the existing limited XML implementation.