// SPDX-License-Identifier: EUPL-1.2 // Small XPath-like helpers over the parsed tree. Paths use canonical names from xml.ts and // the child axis only, e.g. `cac:Party/cac:PostalAddress`. A step may list alternatives // separated by `|`. import type { Dec } from "./decimal"; import { parseDec } from "./decimal"; import type { XmlNode } from "./xml"; const stepCache = new Map(); function compile(path: string): readonly (readonly string[])[] { let steps = stepCache.get(path); if (!steps) { steps = path.split("/").map((step) => step.split("|")); stepCache.set(path, steps); } return steps; } const INDEX_THRESHOLD = 16; const childIndexes = new WeakMap>(); const NO_NODES: readonly XmlNode[] = []; /** Children of `node` with the given name. Elements with many children get a lazy name index. */ function childrenNamed(node: XmlNode, name: string): readonly XmlNode[] { let index = childIndexes.get(node); if (!index) { index = new Map(); for (const child of node.children) { const list = index.get(child.q); if (list) list.push(child); else index.set(child.q, [child]); } childIndexes.set(node, index); } return index.get(name) ?? NO_NODES; } /** All nodes reached from `origin` by the child path, in document order. */ export function all(origin: XmlNode | undefined | null, path: string): XmlNode[] { if (!origin) return []; let current: XmlNode[] = [origin]; for (const names of compile(path)) { const next: XmlNode[] = []; for (const node of current) { if (node.children.length > INDEX_THRESHOLD) { // With alternatives, the index is used only when at most one name is present, so // document order is preserved without merging. let present = 0; let found: readonly XmlNode[] = NO_NODES; for (const name of names) { const list = childrenNamed(node, name); if (list.length > 0) { present += 1; found = list; } } if (present <= 1) { for (const child of found) next.push(child); continue; } } for (const child of node.children) { if (names.length === 1 ? child.q === names[0] : names.includes(child.q)) next.push(child); } } if (next.length === 0) return next; current = next; } return current; } export function first(origin: XmlNode | undefined | null, path: string): XmlNode | undefined { return all(origin, path)[0]; } export function has(origin: XmlNode | undefined | null, path: string): boolean { return all(origin, path).length > 0; } export function count(origin: XmlNode | undefined | null, path: string): number { return all(origin, path).length; } /** XPath `string(.)`: concatenated text of the element and its descendants. */ export function stringValue(node: XmlNode | undefined | null): string { if (!node) return ""; if (node.children.length === 0) return node.text; let out = node.text; for (const child of node.children) out += stringValue(child); return out; } const HAS_WHITESPACE = /[ \t\r\n]/; export function normalizeSpace(text: string): string { if (!HAS_WHITESPACE.test(text)) return text; return text.replace(/[ \t\r\n]+/g, " ").replace(/^ | $/g, ""); } /** XPath `normalize-space(.)` of the node; empty string when the node is absent. */ export function value(node: XmlNode | undefined | null): string { return node ? normalizeSpace(stringValue(node)) : ""; } /** `normalize-space()` of the first node on the path. */ export function valueAt(origin: XmlNode | undefined | null, path: string): string { return value(first(origin, path)); } /** xs:decimal of the first node on the path; null when absent or not a decimal. */ export function decAt(origin: XmlNode | undefined | null, path: string): Dec | null { const node = first(origin, path); return node ? parseDec(stringValue(node)) : null; } export function dec(node: XmlNode | undefined | null): Dec | null { return node ? parseDec(stringValue(node)) : null; } export function attr(node: XmlNode | undefined | null, name: string): string | undefined { return node?.attrs[name]; } /** Absolute location for reports, e.g. `/Invoice/cac:InvoiceLine[2]/cbc:ID`. */ export function locate(node: XmlNode): string { const parts: string[] = []; let current: XmlNode | null = node; while (current) { const parent: XmlNode | null = current.parent; if (parent) { const name = current.q; let total = 0; let position = 0; for (const sibling of parent.children) { if (sibling.q === name) { total += 1; if (sibling === current) position = total; } } parts.push(total > 1 ? `${name}[${position}]` : name); } else { parts.push(current.q); } current = parent; } return `/${parts.reverse().join("/")}`; } /** Document-order index of every element by canonical name, for `//name` lookups. */ export class DocIndex { private readonly byName = new Map(); readonly elements: XmlNode[] = []; constructor(root: XmlNode) { const pending: XmlNode[] = [root]; // Iterative pre-order walk keeps document order without recursion. while (pending.length > 0) { const node = pending.pop(); if (!node) break; this.elements.push(node); const list = this.byName.get(node.q); if (list) list.push(node); else this.byName.set(node.q, [node]); for (let index = node.children.length - 1; index >= 0; index -= 1) { const child = node.children[index]; if (child) pending.push(child); } } } /** `//name` */ named(name: string): readonly XmlNode[] { return this.byName.get(name) ?? []; } /** `//a/b/c`: nodes on the child path below any element named by the first step. */ deep(path: string): XmlNode[] { const slash = path.indexOf("/"); if (slash === -1) return [...this.named(path)]; const head = path.slice(0, slash); const rest = path.slice(slash + 1); const out: XmlNode[] = []; for (const name of head.split("|")) { for (const node of this.named(name)) out.push(...all(node, rest)); } return out; } } export function hasAncestor(node: XmlNode, name: string): boolean { for (let current = node.parent; current; current = current.parent) { if (current.q === name) return true; } return false; }