dasumae-doc / src /xml.mjs
NagaYu's picture
Upload 7 files
a9b29ac verified
Raw History Blame Contribute Delete
12.5 kB
// DasuMae Doc core -- minimal, offset-aware, namespace-aware XML parser and
// structure-aware splice editor.
//
// Why not DOMParser/XMLSerializer? Per the design, re-serializing an OOXML
// part risks mangling namespace prefixes and whitespace. Instead this parser
// records the exact source byte offsets of every element, attribute, and text
// node, and all edits are performed as *splices on the original source string*.
// Parts we do not touch are never reparsed or reserialized; parts we do touch
// keep every byte outside the edited regions identical. This is the
// "structure-aware transform" the design calls for: edits are expressed at the
// element/attribute level (remove node, unwrap node, replace inner text, remove
// attribute), not as fragile substring hacks.
/** @typedef {{prefix:string, local:string, ns:string, name:string, value:string, start:number, end:number}} Attr */
export class XmlNode {
constructor(type) {
this.type = type; // 'element' | 'text' | 'cdata' | 'comment' | 'pi' | 'decl'
this.prefix = '';
this.local = '';
this.ns = '';
this.name = ''; // raw qualified name as written
/** @type {Attr[]} */
this.attrs = [];
/** @type {XmlNode[]} */
this.children = [];
this.parent = null;
// byte offsets into source
this.start = 0; // '<' of this node
this.openEnd = 0; // index just past '>' of the open/self-closing tag
this.closeStart = 0; // '<' of the closing tag (== end for self-closing/void)
this.end = 0; // index just past the node
this.selfClosing = false;
this.text = ''; // for text/cdata/comment: the raw inner value
}
attr(ns, local) {
for (const a of this.attrs) {
if (a.local === local && (ns == null || a.ns === ns)) return a.value;
}
return null;
}
// attribute match by local name only, ignoring namespace (useful for attrs
// that are conventionally unprefixed, e.g. relationship Target/Type).
attrLocal(local) {
for (const a of this.attrs) if (a.local === local) return a.value;
return null;
}
attrNode(ns, local) {
for (const a of this.attrs) {
if (a.local === local && (ns == null || a.ns === ns)) return a;
}
return null;
}
// Direct element children, optionally filtered by (ns, local).
elements(ns, local) {
const out = [];
for (const c of this.children) {
if (c.type !== 'element') continue;
if (ns != null && c.ns !== ns) continue;
if (local != null && c.local !== local) continue;
out.push(c);
}
return out;
}
// Concatenated text of descendant text/cdata nodes, in document order.
// skip(node) -> true to prune an element's entire subtree (e.g. w:delText,
// or runs that carry w:vanish).
textContent(skip) {
let out = '';
const walk = (n) => {
if (n.type === 'text' || n.type === 'cdata') {
out += decodeEntities(n.text);
return;
}
if (n.type !== 'element') return;
if (skip && skip(n)) return;
for (const c of n.children) walk(c);
};
for (const c of this.children) walk(c);
return out;
}
}
export class XmlDoc {
constructor(source, root, all) {
this.source = source;
this.root = root;
this._all = all; // flat list of all element nodes
}
// All element nodes in document order matching (ns, local); either may be null.
find(ns, local) {
const out = [];
for (const n of this._all) {
if (ns != null && n.ns !== ns) continue;
if (local != null && n.local !== local) continue;
out.push(n);
}
return out;
}
all() {
return this._all;
}
}
const NAME_START = /[A-Za-z_:]/;
export function parseXml(source) {
if (typeof source !== 'string') source = new TextDecoder('utf-8').decode(source);
let i = 0;
const n = source.length;
const all = [];
// namespace scope stack: array of maps prefix->uri (''-> default ns)
const scope = [{ '': '', xml: 'http://www.w3.org/XML/1998/namespace' }];
function resolve(prefix) {
for (let s = scope.length - 1; s >= 0; s--) {
if (prefix in scope[s]) return scope[s][prefix];
}
return '';
}
function parseNodes(parentStopName) {
const nodes = [];
while (i < n) {
if (source[i] === '<') {
if (source.startsWith('<!--', i)) {
const node = new XmlNode('comment');
node.start = i;
const close = source.indexOf('-->', i + 4);
const endIdx = close === -1 ? n : close + 3;
node.text = source.slice(i + 4, close === -1 ? n : close);
node.end = node.openEnd = node.closeStart = endIdx;
i = endIdx;
nodes.push(node);
continue;
}
if (source.startsWith('<![CDATA[', i)) {
const node = new XmlNode('cdata');
node.start = i;
const close = source.indexOf(']]>', i + 9);
const endIdx = close === -1 ? n : close + 3;
node.text = source.slice(i + 9, close === -1 ? n : close);
node.end = node.openEnd = node.closeStart = endIdx;
i = endIdx;
nodes.push(node);
continue;
}
if (source.startsWith('<?', i)) {
const node = new XmlNode(source.startsWith('<?xml', i) ? 'decl' : 'pi');
node.start = i;
const close = source.indexOf('?>', i + 2);
const endIdx = close === -1 ? n : close + 2;
node.text = source.slice(i + 2, close === -1 ? n : close);
node.end = node.openEnd = node.closeStart = endIdx;
i = endIdx;
nodes.push(node);
continue;
}
if (source.startsWith('<!', i)) {
// DOCTYPE or similar -- skip to matching '>'
const node = new XmlNode('pi');
node.start = i;
const close = source.indexOf('>', i + 2);
const endIdx = close === -1 ? n : close + 1;
node.end = node.openEnd = node.closeStart = endIdx;
i = endIdx;
nodes.push(node);
continue;
}
if (source[i + 1] === '/') {
// closing tag -- belongs to parent; stop.
return nodes;
}
// opening or self-closing element
const node = parseElement();
nodes.push(node);
continue;
}
// text run
const lt = source.indexOf('<', i);
const endIdx = lt === -1 ? n : lt;
const node = new XmlNode('text');
node.start = i;
node.end = node.openEnd = node.closeStart = endIdx;
node.text = source.slice(i, endIdx);
i = endIdx;
nodes.push(node);
}
return nodes;
}
function parseElement() {
const node = new XmlNode('element');
node.start = i;
i++; // consume '<'
const nameStart = i;
while (i < n && !/[\s/>]/.test(source[i])) i++;
node.name = source.slice(nameStart, i);
const ci = node.name.indexOf(':');
if (ci === -1) {
node.prefix = '';
node.local = node.name;
} else {
node.prefix = node.name.slice(0, ci);
node.local = node.name.slice(ci + 1);
}
// parse attributes; record raw spans
const rawAttrs = [];
while (i < n) {
// record leading whitespace start
const wsStart = i;
while (i < n && /\s/.test(source[i])) i++;
if (i >= n) break;
if (source[i] === '/' || source[i] === '>') break;
const aStart = i; // name start (no leading ws)
while (i < n && !/[\s=/>]/.test(source[i])) i++;
const aName = source.slice(aStart, i);
while (i < n && /\s/.test(source[i])) i++;
let aValue = '';
if (source[i] === '=') {
i++; // '='
while (i < n && /\s/.test(source[i])) i++;
const q = source[i];
if (q === '"' || q === "'") {
i++;
const vStart = i;
while (i < n && source[i] !== q) i++;
aValue = source.slice(vStart, i);
i++; // closing quote
}
}
const aEnd = i;
rawAttrs.push({ name: aName, value: aValue, start: wsStart, end: aEnd });
}
// push a new namespace scope from xmlns attrs
const localScope = {};
for (const a of rawAttrs) {
if (a.name === 'xmlns') localScope[''] = decodeEntities(a.value);
else if (a.name.startsWith('xmlns:')) localScope[a.name.slice(6)] = decodeEntities(a.value);
}
scope.push(localScope);
// resolve attr namespaces (unprefixed attrs have NO namespace)
for (const a of rawAttrs) {
const ci2 = a.name.indexOf(':');
let prefix = '';
let local = a.name;
if (ci2 !== -1) {
prefix = a.name.slice(0, ci2);
local = a.name.slice(ci2 + 1);
}
const ns = prefix === '' ? '' : resolve(prefix);
node.attrs.push({
prefix, local, ns, name: a.name, value: decodeEntities(a.value),
start: a.start, end: a.end,
});
}
node.ns = resolve(node.prefix);
// consume '/>' or '>'
if (source[i] === '/') {
node.selfClosing = true;
i += 2; // '/>'
node.openEnd = node.closeStart = node.end = i;
scope.pop();
all.push(node);
return node;
}
i++; // '>'
node.openEnd = i;
// children
const children = parseNodes(node.name);
for (const c of children) {
c.parent = node;
node.children.push(c);
}
// closing tag
if (source.startsWith('</', i)) {
node.closeStart = i;
const gt = source.indexOf('>', i);
i = gt === -1 ? n : gt + 1;
node.end = i;
} else {
node.closeStart = node.end = i;
}
scope.pop();
all.push(node);
return node;
}
const top = parseNodes(null);
let root = null;
for (const node of top) {
if (node.type === 'element') { root = node; break; }
}
return new XmlDoc(source, root, all);
}
export function decodeEntities(s) {
if (s.indexOf('&') === -1) return s;
return s.replace(/&(#x?[0-9A-Fa-f]+|[a-zA-Z]+);/g, (m, g) => {
switch (g) {
case 'amp': return '&';
case 'lt': return '<';
case 'gt': return '>';
case 'quot': return '"';
case 'apos': return "'";
default:
if (g[0] === '#') {
const code = g[1] === 'x' || g[1] === 'X'
? parseInt(g.slice(2), 16)
: parseInt(g.slice(1), 10);
if (!isNaN(code)) return String.fromCodePoint(code);
}
return m;
}
});
}
export function escapeXml(s) {
return String(s)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
export function escapeAttr(s) {
return escapeXml(s).replace(/"/g, '&quot;');
}
// ---------------------------------------------------------------------------
// Splice editor: collect edits against the ORIGINAL source, apply last-first so
// offsets stay valid. Overlapping edits are rejected.
// ---------------------------------------------------------------------------
export class XmlEditor {
constructor(doc) {
this.doc = doc;
this.source = doc.source;
this.edits = []; // {start, end, text}
}
_splice(start, end, text) {
this.edits.push({ start, end, text });
}
removeNode(node) {
this._splice(node.start, node.end, '');
return this;
}
// Replace the whole element with its inner content (drop open+close tags).
unwrapNode(node) {
if (node.selfClosing) { this._splice(node.start, node.end, ''); return this; }
this._splice(node.start, node.openEnd, '');
this._splice(node.closeStart, node.end, '');
return this;
}
replaceInnerText(node, text) {
if (node.selfClosing) return this; // cannot hold text
this._splice(node.openEnd, node.closeStart, escapeXml(text));
return this;
}
removeAttr(attrNode) {
if (!attrNode) return this;
this._splice(attrNode.start, attrNode.end, '');
return this;
}
replaceNode(node, text) {
this._splice(node.start, node.end, text);
return this;
}
isEmpty() {
return this.edits.length === 0;
}
apply() {
const edits = this.edits.slice().sort((a, b) => b.start - a.start || b.end - a.end);
// reject overlaps
for (let k = 0; k < edits.length - 1; k++) {
const cur = edits[k];
const next = edits[k + 1];
if (next.end > cur.start) {
throw new Error(`overlapping XML edits at ${next.start}-${next.end} and ${cur.start}-${cur.end}`);
}
}
let s = this.source;
for (const e of edits) s = s.slice(0, e.start) + e.text + s.slice(e.end);
return s;
}
}