File size: 2,268 Bytes
a8f4b72 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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 (/<!DOCTYPE\b/i.test(xml)) {
throw new Error(`${label} must not contain a document type declaration.`);
}
const parseErrors: string[] = [];
const document = new DOMParser({
errorHandler: {
warning: () => 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'));
}
|