Extract XFA namespace-aware XML DOM without layout policy

This commit is contained in:
Dylan M. Taylor committed 2026-11-17 09:58:00 -05:00
1 parent 1291955de9
commit 1a0d5d6078
7 files changed
+469

No files matched your search

+4
View File
@@ -132,3 +132,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
## JSONC span-preserving editing
`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported.
## XFA XML DOM
`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. Only visibility and module boundaries change; PDF/layout/form policy remains in the app.
Generated
+7
View File
@@ -3380,6 +3380,13 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xfa"
version = "0.1.0"
dependencies = [
"craft-xml",
]
[[package]]
name = "craft-xfl"
version = "0.1.0"
+1
View File
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-xfa = { path = "crates/xfa" }
craft-jsonc = { path = "crates/jsonc" }
craft-palette = { path = "crates/palette" }
craft-score = { path = "crates/score" }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "craft-xfa"
description = "Namespace-aware source-span XML DOM for XFA adapters; no PDF or layout policy"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
craft-xml = { workspace = true }
+9
View File
@@ -0,0 +1,9 @@
# craft-xfa
Scoped namespace-aware XML DOM extracted unchanged from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned.
Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before; this is not a new total-memory bound or a full XML namespaces conformance claim.
Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0.
Compatibility delta versus the original app XML pin e2dc681a3: current strict craft-xml rejects duplicate raw or expanded attribute names. This deliberately preserves shared security hardening; valid-document DOM behavior is unchanged, but malformed acceptance and errors are not promised byte-identical. Regression tests cover both duplicate forms.
+6
View File
@@ -0,0 +1,6 @@
//! XFA XML infrastructure, extracted from PDFCraft. Layout and application policy stay local.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
/// Compatibility depth limit for XFA XML documents.
pub const MAX_XML_DEPTH: usize = 1024;
pub mod xml;
+428
View File
@@ -0,0 +1,428 @@
//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`.
use std::ops::Range;
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeId(pub usize);
#[derive(Clone, Debug)]
pub struct ParsingOptions {
pub allow_dtd: bool,
pub nodes_limit: u32,
}
impl Default for ParsingOptions {
fn default() -> Self {
Self { allow_dtd: false, nodes_limit: u32::MAX }
}
}
#[derive(Clone, Debug)]
struct AttrData {
ns: Option<String>,
name: String,
value: String,
}
#[derive(Clone, Debug)]
enum NodeKind {
Element {
ns: Option<String>,
name: String,
attrs: Vec<AttrData>,
/// In-scope `(prefix, uri)` bindings at this element (`""` for default namespace).
namespaces: Vec<(String, String)>,
range: Range<usize>,
},
Text(String),
}
#[derive(Clone, Debug)]
struct NodeData {
kind: NodeKind,
children: Vec<usize>,
}
pub struct Document {
nodes: Vec<NodeData>,
root: usize,
}
#[derive(Clone, Copy)]
pub struct Node<'a> {
doc: &'a Document,
id: usize,
}
impl PartialEq for Node<'_> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && std::ptr::eq(self.doc, other.doc)
}
}
impl Eq for Node<'_> {}
#[derive(Clone, Copy)]
pub struct ExpandedName<'a> {
ns: Option<&'a str>,
name: &'a str,
}
impl<'a> ExpandedName<'a> {
pub fn name(&self) -> &'a str {
self.name
}
pub fn namespace(&self) -> Option<&'a str> {
self.ns
}
}
pub trait AttributeKey {
fn matches(&self, ns: Option<&str>, name: &str) -> bool;
}
impl AttributeKey for &str {
fn matches(&self, ns: Option<&str>, name: &str) -> bool {
ns.is_none() && name == *self
}
}
impl AttributeKey for (&str, &str) {
fn matches(&self, ns: Option<&str>, name: &str) -> bool {
ns == Some(self.0) && name == self.1
}
}
#[derive(Clone, Copy)]
pub struct Attribute<'a> {
attr: &'a AttrData,
}
impl<'a> Attribute<'a> {
pub fn name(&self) -> &'a str {
&self.attr.name
}
pub fn namespace(&self) -> Option<&'a str> {
self.attr.ns.as_deref()
}
pub fn value(&self) -> &'a str {
&self.attr.value
}
}
#[derive(Clone, Copy)]
pub struct Namespace<'a> {
prefix: &'a str,
uri: &'a str,
}
impl<'a> Namespace<'a> {
pub fn name(&self) -> Option<&'a str> {
(!self.prefix.is_empty()).then_some(self.prefix)
}
pub fn uri(&self) -> &'a str {
self.uri
}
}
fn split_qname(qname: &str) -> (&str, &str) {
match qname.split_once(':') {
Some((p, l)) => (p, l),
None => ("", qname),
}
}
fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result<Option<String>, String> {
if prefix == "xml" {
return Ok(Some(XML_NS.to_string()));
}
if prefix == "xmlns" {
return Ok(Some(XMLNS_NS.to_string()));
}
if prefix.is_empty() {
if is_attr {
return Ok(None);
}
return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone())));
}
match scope.iter().rev().find(|(p, _)| p == prefix) {
Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())),
_ => Err(format!("undeclared namespace prefix: {prefix}")),
}
}
impl Document {
pub fn parse(text: &str) -> Result<Self, String> {
Self::parse_with_options(text, ParsingOptions::default())
}
pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result<Self, String> {
let mut opts = craft_xml::Options {
strict: true,
doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject },
..Default::default()
};
opts.limits.max_nodes = options.nodes_limit as usize;
opts.limits.max_depth = crate::MAX_XML_DEPTH;
let mut events = opts.events(text.as_bytes());
let mut nodes: Vec<NodeData> = Vec::new();
let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before)
let mut scope: Vec<(String, String)> = Vec::new();
let mut root: Option<usize> = None;
while let Some(ev) = events.next().map_err(|e| e.to_string())? {
let span = events.span();
match ev {
craft_xml::Event::Start { name, attrs } => {
if nodes.len() >= options.nodes_limit as usize {
return Err("nodes limit reached".to_string());
}
let scope_mark = scope.len();
for (k, v) in &attrs {
if k == "xmlns" {
scope.push((String::new(), v.clone()));
} else if let Some(prefix) = k.strip_prefix("xmlns:") {
scope.push((prefix.to_string(), v.clone()));
}
}
let (el_prefix, el_local) = split_qname(&name);
let el_ns = resolve_ns(&scope, el_prefix, false)?;
let mut el_attrs = Vec::new();
for (k, v) in attrs {
if k == "xmlns" || k.starts_with("xmlns:") {
continue;
}
let (ap, al) = split_qname(&k);
let ans = resolve_ns(&scope, ap, true)?;
el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v });
}
// Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix.
let mut namespaces: Vec<(String, String)> = Vec::new();
for (p, u) in scope.iter().rev() {
if !namespaces.iter().any(|(ep, _)| ep == p) {
namespaces.push((p.clone(), u.clone()));
}
}
namespaces.retain(|(_, u)| !u.is_empty());
let id = nodes.len();
nodes.push(NodeData {
kind: NodeKind::Element { ns: el_ns, name: el_local.to_string(), attrs: el_attrs, namespaces, range: span.start..span.end },
children: Vec::new(),
});
if let Some(&(parent, _)) = open.last() {
nodes[parent].children.push(id);
} else if root.is_none() {
root = Some(id);
}
open.push((id, scope_mark));
}
craft_xml::Event::End { .. } => {
if let Some((id, scope_mark)) = open.pop() {
if let NodeKind::Element { range, .. } = &mut nodes[id].kind {
range.end = span.end;
}
scope.truncate(scope_mark);
}
}
craft_xml::Event::Text(t) | craft_xml::Event::CData(t) => {
if let Some(&(parent, _)) = open.last() {
if let Some(&last_child) = nodes[parent].children.last()
&& let NodeKind::Text(existing) = &mut nodes[last_child].kind
{
existing.push_str(&t);
continue;
}
if nodes.len() >= options.nodes_limit as usize {
return Err("nodes limit reached".to_string());
}
let id = nodes.len();
nodes.push(NodeData { kind: NodeKind::Text(t), children: Vec::new() });
nodes[parent].children.push(id);
}
}
craft_xml::Event::Pi { .. } | craft_xml::Event::Comment(_) => {}
}
}
let Some(root) = root else {
return Err("empty XML document".to_string());
};
Ok(Self { nodes, root })
}
pub fn root_element(&self) -> Node<'_> {
Node { doc: self, id: self.root }
}
pub fn get_node(&self, id: NodeId) -> Option<Node<'_>> {
(id.0 < self.nodes.len()).then_some(Node { doc: self, id: id.0 })
}
pub fn descendants(&self) -> Descendants<'_> {
Descendants { doc: self, stack: vec![self.root] }
}
}
pub struct Descendants<'a> {
doc: &'a Document,
stack: Vec<usize>,
}
impl<'a> Iterator for Descendants<'a> {
type Item = Node<'a>;
fn next(&mut self) -> Option<Self::Item> {
let id = self.stack.pop()?;
let children = &self.doc.nodes[id].children;
for &c in children.iter().rev() {
self.stack.push(c);
}
Some(Node { doc: self.doc, id })
}
}
impl<'a> Node<'a> {
pub fn id(&self) -> NodeId {
NodeId(self.id)
}
pub fn document(&self) -> &'a Document {
self.doc
}
pub fn is_element(&self) -> bool {
matches!(self.doc.nodes[self.id].kind, NodeKind::Element { .. })
}
pub fn is_text(&self) -> bool {
matches!(self.doc.nodes[self.id].kind, NodeKind::Text(_))
}
pub fn tag_name(&self) -> ExpandedName<'a> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { ns, name, .. } => ExpandedName { ns: ns.as_deref(), name },
NodeKind::Text(_) => ExpandedName { ns: None, name: "" },
}
}
pub fn attribute<K: AttributeKey>(&self, key: K) -> Option<&'a str> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { attrs, .. } => attrs.iter().find(|a| key.matches(a.ns.as_deref(), &a.name)).map(|a| a.value.as_str()),
NodeKind::Text(_) => None,
}
}
pub fn attributes(&self) -> impl ExactSizeIterator<Item = Attribute<'a>> + use<'a> {
let attrs = match &self.doc.nodes[self.id].kind {
NodeKind::Element { attrs, .. } => attrs.as_slice(),
NodeKind::Text(_) => &[],
};
attrs.iter().map(|attr| Attribute { attr })
}
pub fn namespaces(&self) -> impl ExactSizeIterator<Item = Namespace<'a>> + use<'a> {
let ns = match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.as_slice(),
NodeKind::Text(_) => &[],
};
ns.iter().map(|(p, u)| Namespace { prefix: p, uri: u })
}
pub fn lookup_prefix(&self, uri: &str) -> Option<&'a str> {
if uri == XML_NS {
return Some("xml");
}
match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()),
NodeKind::Text(_) => None,
}
}
pub fn lookup_namespace_uri(&self, prefix: Option<&str>) -> Option<&'a str> {
if prefix == Some("xml") {
return Some(XML_NS);
}
if prefix == Some("xmlns") {
return Some(XMLNS_NS);
}
let target = prefix.unwrap_or("");
match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(p, _)| p == target).map(|(_, u)| u.as_str()),
NodeKind::Text(_) => None,
}
}
pub fn children(&self) -> impl Iterator<Item = Node<'a>> + use<'a> {
let doc = self.doc;
doc.nodes[self.id].children.iter().map(move |&id| Node { doc, id })
}
pub fn descendants(&self) -> Descendants<'a> {
Descendants { doc: self.doc, stack: vec![self.id] }
}
pub fn text(&self) -> Option<&'a str> {
match &self.doc.nodes[self.id].kind {
NodeKind::Text(t) => Some(t.as_str()),
NodeKind::Element { .. } => self.doc.nodes[self.id].children.first().and_then(|&cid| match &self.doc.nodes[cid].kind {
NodeKind::Text(t) => Some(t.as_str()),
_ => None,
}),
}
}
pub fn range(&self) -> Range<usize> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { range, .. } => range.clone(),
NodeKind::Text(_) => 0..0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn namespace_shadowing_attributes_text_and_source_ranges() {
let text = "<root xmlns='urn:outer' xmlns:p='urn:p' a='v'><p:child xmlns='urn:inner' p:a='x'>one<![CDATA[two]]>three</p:child><leaf xmlns=''/></root>";
let doc = Document::parse(text).unwrap();
let root = doc.root_element();
assert_eq!(root.tag_name().namespace(), Some("urn:outer"));
assert_eq!(root.attribute("a"), Some("v"));
let child = root.children().next().unwrap();
assert_eq!(child.tag_name().namespace(), Some("urn:p"));
assert_eq!(child.attribute(("urn:p", "a")), Some("x"));
assert_eq!(child.lookup_namespace_uri(None), Some("urn:inner"));
assert_eq!(child.text(), Some("onetwothree"));
assert_eq!(child.children().count(), 1);
assert!(text[child.range()].starts_with("<p:child"));
assert!(text[child.range()].ends_with("</p:child>"));
assert!(doc.get_node(child.id()).unwrap() == child);
assert_eq!(root.children().nth(1).unwrap().tag_name().namespace(), None);
assert_eq!(root.range(), 0..text.len());
}
#[test]
fn malformed_dtd_and_resource_limits_are_preserved() {
// Current shared XML rejects duplicate attributes, unlike the older app pin.
assert!(Document::parse("<r a='1' a='2'/>").is_err());
assert!(Document::parse("<r xmlns:a='u' xmlns:b='u' a:x='1' b:x='2'/>").is_err());
assert!(Document::parse("<p:root/>").is_err());
assert!(Document::parse("<!DOCTYPE root><root/>").is_err());
assert!(Document::parse_with_options("<!DOCTYPE root><root/>", ParsingOptions { allow_dtd: true, nodes_limit: 8 }).is_ok());
assert!(Document::parse_with_options("<root>text</root>", ParsingOptions { allow_dtd: false, nodes_limit: 1 }).is_err());
assert!(Document::parse_with_options("<root/>", ParsingOptions { allow_dtd: false, nodes_limit: 0 }).is_err());
let text = format!("{}{}", "<n>".repeat(1025), "</n>".repeat(1025));
assert!(Document::parse(&text).is_err());
assert!(Document::parse("").is_err());
}
}