File size: 2,248 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
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 (/<!DOCTYPE\b/i.test(xml)) {
    throw new Error('Document type declarations and custom entities are not allowed.');
  }

  const errors: string[] = [];
  const document = new DOMParser({
    errorHandler: {
      warning: () => 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'));
}