import { readFileSync } from 'node:fs'; import { DOMParser } from '@xmldom/xmldom'; import { PatternSchema, type Pattern } from '../types/schematron.js'; const schematronNamespace = 'http://purl.oclc.org/dsdl/schematron'; function parseDocument(xml: string, label: string): Document { if (/ undefined, error: (message) => parseErrors.push(message), fatalError: (message) => parseErrors.push(message) } }).parseFromString(xml, 'application/xml'); if (parseErrors.length || !document.documentElement) { throw new Error(`${label} is not well-formed XML: ${parseErrors.join('; ') || 'missing document element'}`); } return document; } function directElements(parent: Element, name: string): Element[] { return Array.from(parent.childNodes).filter((node): node is Element => node.nodeType === 1 && (node as Element).localName === name && (node as Element).namespaceURI === schematronNamespace ); } export function parseSchematron(xml: string): Pattern[] { const document = parseDocument(xml, 'Schematron schema'); const root = document.documentElement; if (root.localName !== 'schema' || root.namespaceURI !== schematronNamespace) { throw new Error('Schematron schema must use the ISO Schematron namespace.'); } const patterns: Pattern[] = []; directElements(root, 'pattern').forEach((patternElement, patternIndex) => { const patternId = patternElement.getAttribute('id') || `pattern-${patternIndex + 1}`; for (const rule of directElements(patternElement, 'rule')) { const context = (rule.getAttribute('context') ?? '').trim(); for (const assertion of directElements(rule, 'assert')) { patterns.push(PatternSchema.parse({ id: patternId, context, test: (assertion.getAttribute('test') ?? '').trim(), message: assertion.textContent?.trim() ?? '' })); } } }); return patterns; } export function loadSchematron(path: string): Pattern[] { return parseSchematron(readFileSync(path, 'utf8')); }