The headless browser for AI agents and web scraping
Preserve foreign namespaces across DOM fragments
SGavrl89cc9b54a96f
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 91491655..75ebd9d9 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -29,7 +29,7 @@'_isSpecialScheme', '_applyDocQueryEncoding', '_anchorBase','_elemHrefURL', '_setElemHrefPart', '_pad', '_daysInMonth','_isoWeek1Monday', '_inputParseNumber', '_inputFormatNumber',- '_htmlAttrName', '_convertNodes', '_parseHTMLFragment', '_xmlWellFormed', '_elementClassFor', '_wrap', '_wrapEl',+ '_htmlAttrName', '_convertNodes', '_fragmentContextPayload', '_parseHTMLFragment', '_xmlWellFormed', '_elementClassFor', '_wrap', '_wrapEl','_resolveUrl', '_registerIframe', '_base64ToUint8Array','_bodyToUint8Array', '_arrayBufferFromBytes','_installWasmStreamingFallback', '_urlParseOp', '_urlSetOp',@@ -2496,6 +2496,20 @@ function _isSubmitButton(el) {return false;}+// Carry the context element's full qualified name into html5ever. Fragment+// parsing depends on both the local name and namespace (SVG/MathML included).+function _fragmentContextPayload(context, html) {+ let namespace = 'http://www.w3.org/1999/xhtml';+ let qualified = 'body';+ if (typeof context === 'string') {+ qualified = context || 'body';+ } else if (context && context.nodeType === 1) {+ namespace = context.namespaceURI || '';+ qualified = context.nodeName || context.localName || 'body';+ }+ return namespace + "\0" + qualified + "\0" + String(html == null ? '' : html);+}+// Parse an HTML string into detached nodes using the actual insertion element// as html5ever's fragment context. This preserves table/select parsing rules,// comments, text-node order, and foreign-content namespaces without a wrap map.@@ -2904,11 +2918,12 @@ class Element extends Node {}get nodeName() { return this.tagName; }get localName() {- // tagName is an op call and the tag never changes, so cache the lowercased- // localName. This keeps the new <a>/<area> href getters (which read- // localName) and every other localName consumer off the op path.+ // The native tree owns the namespace-aware QualName. Reading its local+ // component directly preserves case-sensitive SVG/MathML names such as+ // `linearGradient`; deriving this from HTML's uppercased tagName loses it.if (this._lname !== undefined) return this._lname;- const ln = (this.tagName || "").toLowerCase();+ const ln = _domParse("local_name", this._nid)+ || (this.tagName || "").toLowerCase();if (ln) this._lname = ln;return ln;}@@ -5201,7 +5216,7 @@ class Document extends Node {var body = this.body;if (!body) return;var temp = this.createDocumentFragment();- _dom("set_fragment_html_executable", temp._nid, "body\0" + html);+ _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]);@@ -5234,7 +5249,7 @@ class DocumentFragment extends Node {set innerHTML(v) {const html = String(v ?? "");if (this._fragmentContext) {- _dom("set_inner_html_context", this._nid, this._fragmentContext + "\0" + html);+ _dom("set_inner_html_context", this._nid, _fragmentContextPayload(this._fragmentContext, html));} else {_dom("set_inner_html", this._nid, html);}@@ -11169,9 +11184,12 @@ globalThis.Range = class Range {const frag = ownerDoc.createDocumentFragment();let context = node;if (context && context.nodeType !== 1) context = context.parentElement;- let contextName = (context && context.localName) || 'body';- if (contextName === 'html') contextName = 'body';- _dom("set_fragment_html_executable", frag._nid, contextName + "\0" + String(html));+ if (context && context.localName === 'html') context = null;+ _dom(+ "set_fragment_html_executable",+ frag._nid,+ _fragmentContextPayload(context || 'body', html),+ );return frag;}toString() {diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex a2299b57..0888c3c4 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -789,6 +789,35 @@ fn is_render_mutation_command(cmd: &str) -> bool {)}+fn fragment_context_and_html(arg: &str) -> (html5ever::QualName, &str) {+ let mut parts = arg.splitn(3, '\0');+ let first = parts.next().unwrap_or("body");+ let second = parts.next();+ let third = parts.next();+ let (namespace, qualified, html) = match (second, third) {+ // Namespace-aware encoding used by the current bootstrap.+ (Some(qualified), Some(html)) => (first, qualified, html),+ // Backward-compatible encoding for older snapshots: `local\0html`.+ (Some(html), None) => ("http://www.w3.org/1999/xhtml", first, html),+ (None, None) => ("http://www.w3.org/1999/xhtml", "body", first),+ (None, Some(_)) => unreachable!(),+ };+ let (prefix, local) = match qualified.split_once(':') {+ Some((prefix, local)) if !prefix.is_empty() && !local.is_empty() => {+ (Some(html5ever::Prefix::from(prefix)), local)+ }+ _ => (None, if qualified.is_empty() { "body" } else { qualified }),+ };+ (+ html5ever::QualName::new(+ prefix,+ html5ever::Namespace::from(namespace),+ html5ever::LocalName::from(local),+ ),+ html,+ )+}+#[op2(fast)]fn op_script_mark_started(state: &OpState, nid: u32) -> bool {let shared = state.borrow::<SharedState>().clone();@@ -1268,8 +1297,26 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Strlet nid = arg1.parse::<u32>().unwrap_or(0);let name = dom.with_node(NodeId::new(nid), |n| {- n.as_element()- .map(|name| name.local.as_ref().to_ascii_uppercase())+ n.as_element().map(|name| {+ if name.ns == html5ever::ns!(html) {+ name.local.as_ref().to_ascii_uppercase()+ } else {+ match &name.prefix {+ Some(prefix) => format!("{}:{}", prefix, name.local),+ None => name.local.to_string(),+ }+ }+ })+ })+ .flatten()+ .unwrap_or_default();+ serde_json::to_string(&name).unwrap_or("\"\"".into())+ }+ "local_name" => {+ let nid = arg1.parse::<u32>().unwrap_or(0);+ let name = dom+ .with_node(NodeId::new(nid), |n| {+ n.as_element().map(|name| name.local.to_string())}).flatten().unwrap_or_default();@@ -1452,16 +1499,11 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Str_ => return "false".into(),};let target = NodeId::new(nid);- let (context, html) = arg2.split_once('\0').unwrap_or(("body", arg2.as_str()));+ let (context_name, html) = fragment_context_and_html(&arg2);for child in dom.children(target) {dom.detach(child);}if !html.is_empty() {- let context_name = html5ever::QualName::new(- None,- html5ever::ns!(html),- html5ever::LocalName::from(context.to_ascii_lowercase()),- );let fragment = obscura_dom::parse_fragment_with_context(html, context_name);let import_root = fragment.fragment_root();dom.import_children_from(target, &fragment, import_root);@@ -1480,16 +1522,11 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Str_ => return "false".into(),};let target = NodeId::new(nid);- let (context, html) = arg2.split_once('\0').unwrap_or(("body", arg2.as_str()));+ let (context_name, html) = fragment_context_and_html(&arg2);for child in dom.children(target) {dom.detach(child);}if !html.is_empty() {- let context_name = html5ever::QualName::new(- None,- html5ever::ns!(html),- html5ever::LocalName::from(context.to_ascii_lowercase()),- );let fragment = obscura_dom::parse_fragment_with_context(html, context_name);let import_root = fragment.fragment_root();dom.import_children_from(target, &fragment, import_root);@@ -1549,6 +1586,28 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Str}).index().to_string(),+ "create_element_ns" => {+ let (namespace, qualified) = arg1.split_once('\0').unwrap_or(("", arg1.as_str()));+ let (prefix, local) = match qualified.split_once(':') {+ Some((prefix, local)) if !prefix.is_empty() && !local.is_empty() => {+ (Some(html5ever::Prefix::from(prefix)), local)+ }+ None if !qualified.is_empty() => (None, qualified),+ _ => return "-1".into(),+ };+ dom.new_node(NodeData::Element {+ name: html5ever::QualName::new(+ prefix,+ html5ever::Namespace::from(namespace),+ html5ever::LocalName::from(local),+ ),+ attrs: vec![],+ template_contents: None,+ mathml_annotation_xml_integration_point: false,+ })+ .index()+ .to_string()+ }"create_text_node" => dom.new_node(NodeData::Text {contents: arg1.clone(),