cda-schematron-validator 1.1.2 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/validator.js CHANGED
@@ -2,460 +2,10 @@
2
2
  // jshint shadow:true
3
3
 
4
4
  module.exports = {
5
- validate: validate,
6
- validateAsync: validateAsync,
7
- clearCache: clearCache,
5
+ validate: require('./validateSync').validateSync,
6
+ validateAsync: require('./validateAsync').validateAsync,
7
+ validateFileListAsync: require('./validateAsync').validateFileListAsync,
8
+ clearCache: require('./validateSync').clearCache,
9
+ clearCacheAsync: require('./validateAsync').clearCache,
8
10
  parseSchematron: require('./parseSchematron')
9
11
  };
10
-
11
- const fs = require('fs');
12
- const xpath = require('xpath');
13
- const dom = require('@xmldom/xmldom').DOMParser;
14
- // crypto is now built-in node
15
- const crypto = require('crypto');
16
- const _get = require('lodash.get');
17
- const parseSchematron = require('./parseSchematron');
18
- const testAssertion = require('./testAssertion');
19
- const includeExternalDocument = require('./includeExternalDocument');
20
-
21
- // Parsed object cache
22
- let parsedMap = Object.create({});
23
- let contextMap = Object.create({});
24
-
25
- function clearCache() {
26
- parsedMap = Object.create({});
27
- contextMap = Object.create({});
28
- }
29
- let namespaceMap, patternRuleMap, ruleAssertionMap, xpathSelect;
30
- function validate(xml, schematron, options = {}) {
31
- // If not valid xml, it might be a filepath
32
- // Adding explicit check to make it clear
33
- if (xml.trim().indexOf('<') === -1) {
34
- try {
35
- xml = fs.readFileSync(xml, 'utf-8').toString();
36
- }
37
- catch (err) {
38
- // If no valid xml found, inform user, and return immediately
39
- console.log('No valid xml could be found');
40
- return;
41
- }
42
- }
43
-
44
- let schematronMap;
45
- // Load xml doc
46
- let xmlDoc = new dom().parseFromString(xml);
47
- // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
48
- if (options.parsedSchematronMap) {
49
- schematronMap = options.parsedSchematronMap;
50
- }
51
- else {
52
- // If not valid schematron (xml), it might be a filepath
53
- // Adding explicit check to make it clear
54
- if (schematron.trim().indexOf('<') === -1) {
55
- try {
56
- schematron = fs.readFileSync(schematron, 'utf-8').toString();
57
- }
58
- catch (err) {
59
- // If no valid schematron found, inform user, and return immediately
60
- console.log('No valid schematron could be found');
61
- return;
62
- }
63
- }
64
- let hash = crypto
65
- .createHash('md5')
66
- .update(schematron)
67
- .digest('hex');
68
- schematronMap = parsedMap[hash];
69
- // If not in cache
70
- if (!schematronMap) {
71
- // Load schematron doc
72
- let schematronDoc = new dom().parseFromString(schematron);
73
-
74
- // Parse schematron
75
- schematronMap = parseSchematron(schematronDoc);
76
-
77
- // Cache parsed schematron
78
- parsedMap[hash] = schematronMap;
79
- }
80
- }
81
-
82
- // Extract data from parsed schematron object
83
- namespaceMap = schematronMap.namespaceMap;
84
- patternRuleMap = schematronMap.patternRuleMap;
85
- ruleAssertionMap = schematronMap.ruleAssertionMap;
86
-
87
- // Create selector object, initialized with namespaces
88
- // Avoid using 'select' as a variable name as it is overused
89
- xpathSelect = xpath.useNamespaces(namespaceMap);
90
-
91
- let errors = [];
92
- let warnings = [];
93
- let ignored = [];
94
- for (let patternId in patternRuleMap) {
95
- if (!patternRuleMap.hasOwnProperty(patternId)) {
96
- continue;
97
- }
98
- const rules = patternRuleMap[patternId];
99
- for (let i = 0; i < rules.length; i++) {
100
- const ruleId = rules[i];
101
- const ruleObject = ruleAssertionMap[ruleId];
102
- if (_get(ruleObject, 'abstract')) {
103
- continue;
104
- }
105
- const context = _get(ruleObject, 'context');
106
- const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
107
- let failedAssertions = checkRule(xmlDoc, context, assertionsAndExtensions, options);
108
- for (let j = 0; j < failedAssertions.length; j++) {
109
- const assertionObject = failedAssertions[j];
110
- const { type, assertionId, test, simplifiedTest, description, errorMessage, results } = assertionObject;
111
- if (Array.isArray(results)) {
112
- for (let k = 0; k < results.length; k++) {
113
- const resultObject = results[k];
114
- const { result, line, path, xml } = resultObject;
115
- if (!result) {
116
- let obj = {
117
- type: type,
118
- test: test,
119
- simplifiedTest: simplifiedTest,
120
- description: description,
121
- line: line,
122
- path: path,
123
- patternId: patternId,
124
- ruleId: ruleId,
125
- assertionId: assertionId,
126
- context: context,
127
- xml: xml
128
- };
129
- if (type === 'error') {
130
- errors.push(obj);
131
- }
132
- else {
133
- warnings.push(obj);
134
- }
135
- }
136
- }
137
- }
138
- else if (results.ignored) {
139
- let obj = {
140
- errorMessage: errorMessage,
141
- type: type,
142
- test: test,
143
- simplifiedTest: simplifiedTest,
144
- description: description,
145
- patternId: patternId,
146
- ruleId: ruleId,
147
- assertionId: assertionId,
148
- context: context
149
- };
150
- ignored.push(obj);
151
- }
152
- }
153
- }
154
- }
155
-
156
- return {
157
- errorCount: errors.length,
158
- warningCount: warnings.length,
159
- ignoredCount: ignored.length,
160
- errors: errors,
161
- warnings: warnings,
162
- ignored: ignored
163
- };
164
- }
165
-
166
- // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
167
- function checkRule(xmlDoc, originalContext, assertionsAndExtensions, options) {
168
- // Context cache
169
- const includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
170
- const resourceDir = options.resourceDir || './';
171
- const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
172
- let failedAssertions = [];
173
- const context = options.contextOverride || originalContext;
174
- // Determine the sections within context, load selected section from cache if possible
175
- let selected = contextMap[context];
176
- let contextModified = context;
177
- if (!selected) {
178
- if (context) {
179
- if (context.indexOf('/')) {
180
- contextModified = '//' + context;
181
- }
182
- selected = xpathSelect(contextModified, xmlDoc);
183
- }
184
- else {
185
- selected = [xmlDoc];
186
- }
187
- contextMap[context] = selected;
188
- }
189
-
190
- for (let i = 0; i < assertionsAndExtensions.length; i++) {
191
- const assertionAndExtensionObject = assertionsAndExtensions[i];
192
- if (assertionAndExtensionObject.type === 'assertion') {
193
- let { level, test, id, description } = assertionAndExtensionObject;
194
- // Extract values from external document and modify test if a document call is made
195
- let originalTest = test;
196
- let simplifiedTest = null;
197
- try {
198
- test = includeExternalDocument(test, resourceDir);
199
- }
200
- catch (err) {
201
- failedAssertions.push({
202
- type: level,
203
- assertionId: id,
204
- test: originalTest,
205
- simplifiedTest: simplifiedTest,
206
- description: description,
207
- results: { ignored: true, errorMessage: err.message }
208
- });
209
- continue;
210
- }
211
- if (originalTest !== test) {
212
- simplifiedTest = test;
213
- }
214
- if (level === 'error' || includeWarnings) {
215
- failedAssertions.push({
216
- type: level,
217
- assertionId: id,
218
- test: originalTest,
219
- simplifiedTest: simplifiedTest,
220
- description: description,
221
- results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
222
- });
223
- }
224
- }
225
- else {
226
- const extensionRule = assertionAndExtensionObject.rule;
227
- if (!extensionRule) {
228
- continue;
229
- }
230
- const subAssertionsAndExtensions = ruleAssertionMap[extensionRule] ? ruleAssertionMap[extensionRule].assertionsAndExtensions : null;
231
- if (!subAssertionsAndExtensions) {
232
- continue;
233
- }
234
- const newRuleObject = ruleAssertionMap[extensionRule];
235
- const failedSubAssertions = checkRule(xmlDoc, context, subAssertionsAndExtensions, options);
236
- failedAssertions.push(...failedSubAssertions);
237
- }
238
- }
239
- return failedAssertions;
240
- }
241
-
242
- async function validateAsync(xml, schematron, options = {}) {
243
- // If not valid xml, it might be a filepath
244
- // Adding explicit check to make it clear
245
- if (xml.trim().indexOf('<') === -1) {
246
- try {
247
- xml = fs.readFileSync(xml, 'utf-8').toString();
248
- }
249
- catch (err) {
250
- // If no valid xml found, inform user, and return immediately
251
- console.log('No valid xml could be found');
252
- return;
253
- }
254
- }
255
-
256
- let schematronMap;
257
- // Load xml doc
258
- let xmlDoc = new dom().parseFromString(xml);
259
- // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
260
- if (options.parsedSchematronMap) {
261
- schematronMap = options.parsedSchematronMap;
262
- }
263
- else {
264
- // If not valid schematron (xml), it might be a filepath
265
- // Adding explicit check to make it clear
266
- if (schematron.trim().indexOf('<') === -1) {
267
- try {
268
- schematron = fs.readFileSync(schematron, 'utf-8').toString();
269
- }
270
- catch (err) {
271
- // If no valid schematron found, inform user, and return immediately
272
- console.log('No valid schematron could be found');
273
- return;
274
- }
275
- }
276
- let hash = crypto
277
- .createHash('md5')
278
- .update(schematron)
279
- .digest('hex');
280
- schematronMap = parsedMap[hash];
281
- // If not in cache
282
- if (!schematronMap) {
283
- // Load schematron doc
284
- let schematronDoc = new dom().parseFromString(schematron);
285
-
286
- // Parse schematron
287
- schematronMap = parseSchematron(schematronDoc);
288
-
289
- // Cache parsed schematron
290
- parsedMap[hash] = schematronMap;
291
- }
292
- }
293
-
294
- // Extract data from parsed schematron object
295
- namespaceMap = schematronMap.namespaceMap;
296
- patternRuleMap = schematronMap.patternRuleMap;
297
- ruleAssertionMap = schematronMap.ruleAssertionMap;
298
-
299
- // Create selector object, initialized with namespaces
300
- // Avoid using 'select' as a variable name as it is overused
301
- xpathSelect = xpath.useNamespaces(namespaceMap);
302
-
303
- let errors = [];
304
- let warnings = [];
305
- let ignored = [];
306
- for (let patternId in patternRuleMap) {
307
- if (!patternRuleMap.hasOwnProperty(patternId)) {
308
- continue;
309
- }
310
- const rules = patternRuleMap[patternId];
311
- for (let i = 0; i < rules.length; i++) {
312
- const ruleId = rules[i];
313
- const ruleObject = ruleAssertionMap[ruleId];
314
- if (_get(ruleObject, 'abstract')) {
315
- continue;
316
- }
317
- const context = _get(ruleObject, 'context');
318
- const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
319
- let failedAssertions = await checkRulePromise(xmlDoc, context, assertionsAndExtensions, options);
320
- for (let j = 0; j < failedAssertions.length; j++) {
321
- const assertionObject = failedAssertions[j];
322
- const { type, assertionId, test, simplifiedTest, description, errorMessage, results } = assertionObject;
323
- if (Array.isArray(results)) {
324
- for (let k = 0; k < results.length; k++) {
325
- const resultObject = results[k];
326
- const { result, line, path, xml } = resultObject;
327
- if (!result) {
328
- let obj = {
329
- type: type,
330
- test: test,
331
- simplifiedTest: simplifiedTest,
332
- description: description,
333
- line: line,
334
- path: path,
335
- patternId: patternId,
336
- ruleId: ruleId,
337
- assertionId: assertionId,
338
- context: context,
339
- xml: xml
340
- };
341
- if (type === 'error') {
342
- errors.push(obj);
343
- }
344
- else {
345
- warnings.push(obj);
346
- }
347
- }
348
- }
349
- }
350
- else if (results.ignored) {
351
- let obj = {
352
- errorMessage: errorMessage,
353
- type: type,
354
- test: test,
355
- simplifiedTest: simplifiedTest,
356
- description: description,
357
- patternId: patternId,
358
- ruleId: ruleId,
359
- assertionId: assertionId,
360
- context: context
361
- };
362
- ignored.push(obj);
363
- }
364
- }
365
- }
366
- }
367
-
368
- return {
369
- errorCount: errors.length,
370
- warningCount: warnings.length,
371
- ignoredCount: ignored.length,
372
- errors: errors,
373
- warnings: warnings,
374
- ignored: ignored
375
- };
376
- }
377
-
378
- // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
379
- function checkRulePromise(xmlDoc, originalContext, assertionsAndExtensions, options) {
380
- // Context cache
381
- const resultCapture = new Promise((resolve, reject) => {
382
- try {
383
- // Context cache
384
- const includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
385
- const resourceDir = options.resourceDir || './';
386
- const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
387
- let failedAssertions = [];
388
- const context = options.contextOverride || originalContext;
389
- // Determine the sections within context, load selected section from cache if possible
390
- let selected = contextMap[context];
391
- let contextModified = context;
392
- if (!selected) {
393
- if (context) {
394
- if (context.indexOf('/')) {
395
- contextModified = '//' + context;
396
- }
397
- selected = xpathSelect(contextModified, xmlDoc);
398
- }
399
- else {
400
- selected = [xmlDoc];
401
- }
402
- contextMap[context] = selected;
403
- }
404
-
405
- for (let i = 0; i < assertionsAndExtensions.length; i++) {
406
- const assertionAndExtensionObject = assertionsAndExtensions[i];
407
- if (assertionAndExtensionObject.type === 'assertion') {
408
- let { level, test, id, description } = assertionAndExtensionObject;
409
- // Extract values from external document and modify test if a document call is made
410
- let originalTest = test;
411
- let simplifiedTest = null;
412
- try {
413
- test = includeExternalDocument(test, resourceDir);
414
- }
415
- catch (err) {
416
- failedAssertions.push({
417
- type: level,
418
- assertionId: id,
419
- test: originalTest,
420
- simplifiedTest: simplifiedTest,
421
- description: description,
422
- results: { ignored: true, errorMessage: err.message }
423
- });
424
- continue;
425
- }
426
- if (originalTest !== test) {
427
- simplifiedTest = test;
428
- }
429
- if (level === 'error' || includeWarnings) {
430
- failedAssertions.push({
431
- type: level,
432
- assertionId: id,
433
- test: originalTest,
434
- simplifiedTest: simplifiedTest,
435
- description: description,
436
- results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
437
- });
438
- }
439
- }
440
- else {
441
- const extensionRule = assertionAndExtensionObject.rule;
442
- if (!extensionRule) {
443
- continue;
444
- }
445
- const subAssertionsAndExtensions = ruleAssertionMap[extensionRule] ? ruleAssertionMap[extensionRule].assertionsAndExtensions : null;
446
- if (!subAssertionsAndExtensions) {
447
- continue;
448
- }
449
- const newRuleObject = ruleAssertionMap[extensionRule];
450
- const failedSubAssertions = checkRule(xmlDoc, context, subAssertionsAndExtensions, options);
451
- failedAssertions.push(...failedSubAssertions);
452
- }
453
- }
454
- resolve (failedAssertions);
455
- }
456
- catch (promiseError) {
457
- reject (new Error (`Promise Error: ${promiseError}`));
458
- }
459
- });
460
- return resultCapture;
461
- }