import { readFileSync } from 'node:fs'; import { DOMParser } from '@xmldom/xmldom'; import xpath from 'xpath'; import { parseSchematron } from '../parsers/schematron-parser.js'; function parseXml(xml: string): Document { if (/ undefined, error: (message) => errors.push(message), fatalError: (message) => errors.push(message) } }).parseFromString(xml, 'application/xml'); if (errors.length || !document.documentElement) { throw new Error(`XML is not well-formed: ${errors.join('; ') || 'missing document element'}`); } return document; } export function validateSchematronXml(xml: string, schematronXml: string): string[] { const document = parseXml(xml); const rules = parseSchematron(schematronXml); const errors: string[] = []; for (const rule of rules) { const contextQuery = rule.context.startsWith('/') ? rule.context : `//${rule.context}`; let contextNodes: Node[]; try { const selected = xpath.select(contextQuery, document); if (!Array.isArray(selected)) { errors.push(`${rule.id}: context XPath "${rule.context}" did not select nodes.`); continue; } contextNodes = selected as Node[]; } catch (error) { errors.push(`${rule.id}: invalid context XPath "${rule.context}": ${error instanceof Error ? error.message : String(error)}`); continue; } for (const contextNode of contextNodes) { try { const result = xpath.select(rule.test, contextNode); const valid = Array.isArray(result) ? result.length > 0 : Boolean(result); if (!valid) errors.push(`${rule.id}: ${rule.message}`); } catch (error) { errors.push(`${rule.id}: invalid assertion XPath "${rule.test}": ${error instanceof Error ? error.message : String(error)}`); break; } } } return errors; } export function validateSchematron(xmlFile: string, schFile: string): string[] { return validateSchematronXml(readFileSync(xmlFile, 'utf8'), readFileSync(schFile, 'utf8')); }