cda-schematron-validator 1.0.2 → 1.0.5

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
@@ -1,228 +1,233 @@
1
- // jshint node:true
2
- // jshint shadow:true
3
-
4
- module.exports = {
5
- validate: validate,
6
- clearCache: clearCache,
7
- parseSchematron: require('./parseSchematron')
8
- };
9
-
10
- const fs = require('fs');
11
- const xpath = require('xpath');
12
- const dom = require('@xmldom/xmldom').DOMParser;
13
- // crypto is now built-in node
14
- const crypto = require('crypto');
15
-
16
- const parseSchematron = require('./parseSchematron');
17
- const testAssertion = require('./testAssertion');
18
- const includeExternalDocument = require('./includeExternalDocument');
19
-
20
- // Parsed object cache
21
- let parsedMap = Object.create({});
22
- let contextMap = Object.create({});
23
-
24
- function clearCache() {
25
- parsedMap = Object.create({});
26
- contextMap = Object.create({});
27
- }
28
-
29
- function validate(xml, schematron, options = {}) {
30
- // If not valid xml, it might be a filepath
31
- // Adding explicit check to make it clear
32
- if (xml.trim().indexOf('<') === -1) {
33
- try {
34
- xml = fs.readFileSync(xml, 'utf-8').toString();
35
- }
36
- catch (err) {
37
- // If no valid xml found, inform user, and return immediately
38
- console.log('No valid xml could be found');
39
- return;
40
- }
41
- }
42
-
43
- let schematronMap;
44
- // Load xml doc
45
- let xmlDoc = new dom().parseFromString(xml);
46
- // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
47
- if (options.parsedSchematronMap) {
48
- schematronMap = options.parsedSchematronMap;
49
- }
50
- else {
51
- // If not valid schematron (xml), it might be a filepath
52
- // Adding explicit check to make it clear
53
- if (schematron.trim().indexOf('<') === -1) {
54
- try {
55
- schematron = fs.readFileSync(schematron, 'utf-8').toString();
56
- }
57
- catch (err) {
58
- // If no valid schematron found, inform user, and return immediately
59
- console.log('No valid schematron could be found');
60
- return;
61
- }
62
- }
63
- let hash = crypto
64
- .createHash('md5')
65
- .update(schematron)
66
- .digest('hex');
67
- schematronMap = parsedMap[hash];
68
- // If not in cache
69
- if (!schematronMap) {
70
- // Load schematron doc
71
- let schematronDoc = new dom().parseFromString(schematron);
72
-
73
- // Parse schematron
74
- schematronMap = parseSchematron(schematronDoc);
75
-
76
- // Cache parsed schematron
77
- parsedMap[hash] = schematronMap;
78
- }
79
- }
80
-
81
- // Extract data from parsed schematron object
82
- let namespaceMap = schematronMap.namespaceMap;
83
- let patternRuleMap = schematronMap.patternRuleMap;
84
- let ruleAssertionMap = schematronMap.ruleAssertionMap;
85
-
86
- // Create selector object, initialized with namespaces
87
- // Avoid using 'select' as a variable name as it is overused
88
- const xpathSelect = xpath.useNamespaces(namespaceMap);
89
-
90
- let errors = [];
91
- let warnings = [];
92
- let ignored = [];
93
- for (let pattern in patternRuleMap) {
94
- if (!patternRuleMap.hasOwnProperty(pattern)) {
95
- continue;
96
- }
97
- let patternId = pattern;
98
- let rules = patternRuleMap[pattern];
99
- for (let i = 0; i < rules.length; i++) {
100
- if (ruleAssertionMap[rules[i]].abstract) {
101
- continue;
102
- }
103
- let ruleId = rules[i];
104
- let context = ruleAssertionMap[rules[i]].context;
105
- let assertionsAndExtensions = ruleAssertionMap[rules[i]].assertionsAndExtensions || [];
106
- let assertionResults = checkRule(xmlDoc, xpathSelect, context, assertionsAndExtensions, options);
107
- for (let j = 0; j < assertionResults.length; j++) {
108
- let type = assertionResults[j].type;
109
- let assertionId = assertionResults[j].assertionId;
110
- let test = assertionResults[j].test;
111
- let simplifiedTest = assertionResults[j].simplifiedTest;
112
- let description = assertionResults[j].description;
113
- let errorMessage = assertionResults[j].errorMessage;
114
- let results = assertionResults[j].results;
115
- if (!results.ignored) {
116
- for (let k = 0; k < results.length; k++) {
117
- let result = results[k].result;
118
- let line = results[k].line;
119
- let path = results[k].path;
120
- let xmlSnippet = results[k].xml;
121
- if (!result) {
122
- let obj = {
123
- type: type,
124
- test: test,
125
- simplifiedTest: simplifiedTest,
126
- description: description,
127
- line: line,
128
- path: path,
129
- patternId: patternId,
130
- ruleId: ruleId,
131
- assertionId: assertionId,
132
- context: context,
133
- xml: xmlSnippet
134
- };
135
- if (type === 'error') {
136
- errors.push(obj);
137
- }
138
- else {
139
- warnings.push(obj);
140
- }
141
- }
142
- }
143
- }
144
- else {
145
- let obj = {
146
- errorMessage: errorMessage,
147
- type: type,
148
- test: test,
149
- simplifiedTest: simplifiedTest,
150
- description: description,
151
- patternId: patternId,
152
- ruleId: ruleId,
153
- assertionId: assertionId,
154
- context: context
155
- };
156
- ignored.push(obj);
157
- }
158
- }
159
- }
160
- }
161
-
162
- return {
163
- errorCount: errors.length,
164
- warningCount: warnings.length,
165
- ignoredCount: ignored ? ignored.length : 0,
166
- errors: errors,
167
- warnings: warnings,
168
- ignored: ignored
169
- };
170
- }
171
-
172
- // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
173
- function checkRule(xmlDoc, xpathSelect, originalContext, assertionsAndExtensions, options) {
174
- // Context cache
175
- let includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
176
- let resourceDir = options.resourceDir || './';
177
- let xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
178
- let results = [];
179
- let context = options.contextOverride || originalContext;
180
- // Determine the sections within context, load selected section from cache if possible
181
- let selected = contextMap[context];
182
- let contextModified = context;
183
- if (!selected) {
184
- if (context) {
185
- if (context.indexOf('/')) {
186
- contextModified = '//' + context;
187
- }
188
- selected = xpathSelect(contextModified, xmlDoc);
189
- }
190
- else {
191
- selected = [xmlDoc];
192
- }
193
- contextMap[context] = selected;
194
- }
195
-
196
- for (let i = 0; i < assertionsAndExtensions.length; i++) {
197
- if (assertionsAndExtensions[i].type === 'assertion') {
198
- let type = assertionsAndExtensions[i].level;
199
- let test = assertionsAndExtensions[i].test;
200
-
201
- // Extract values from external document and modify test if a document call is made
202
- let originalTest = test;
203
- try {
204
- test = includeExternalDocument(test, resourceDir);
205
- }
206
- catch (err) {
207
- return { ignored: true, errorMessage: err.message };
208
- }
209
-
210
- let simplifiedTest = null;
211
- if (originalTest !== test) {
212
- simplifiedTest = test;
213
- }
214
- if (type === 'error' || includeWarnings) {
215
- results.push({
216
- type: type,
217
- assertionId: assertionsAndExtensions[i].id,
218
- test: originalTest,
219
- simplifiedTest: simplifiedTest,
220
- description: assertionsAndExtensions[i].description,
221
- results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
222
- });
223
- }
224
- }
225
- // removed recursive call to checkRule as it just returns an emptry array
226
- }
227
- return results;
228
- }
1
+ // jshint node:true
2
+ // jshint shadow:true
3
+
4
+ module.exports = {
5
+ validate: validate,
6
+ clearCache: clearCache,
7
+ parseSchematron: require('./parseSchematron')
8
+ };
9
+
10
+ const fs = require('fs');
11
+ const xpath = require('xpath');
12
+ const dom = require('@xmldom/xmldom').DOMParser;
13
+ // crypto is now built-in node
14
+ const crypto = require('crypto');
15
+ const _get = require('lodash.get');
16
+ const parseSchematron = require('./parseSchematron');
17
+ const testAssertion = require('./testAssertion');
18
+ const includeExternalDocument = require('./includeExternalDocument');
19
+
20
+ // Parsed object cache
21
+ let parsedMap = Object.create({});
22
+ let contextMap = Object.create({});
23
+
24
+ function clearCache() {
25
+ parsedMap = Object.create({});
26
+ contextMap = Object.create({});
27
+ }
28
+ let namespaceMap, patternRuleMap, ruleAssertionMap, xpathSelect;
29
+ function validate(xml, schematron, options = {}) {
30
+ // If not valid xml, it might be a filepath
31
+ // Adding explicit check to make it clear
32
+ if (xml.trim().indexOf('<') === -1) {
33
+ try {
34
+ xml = fs.readFileSync(xml, 'utf-8').toString();
35
+ }
36
+ catch (err) {
37
+ // If no valid xml found, inform user, and return immediately
38
+ console.log('No valid xml could be found');
39
+ return;
40
+ }
41
+ }
42
+
43
+ let schematronMap;
44
+ // Load xml doc
45
+ let xmlDoc = new dom().parseFromString(xml);
46
+ // Allowing users to send a parsed schematron map if testing multiple xml files with the same schematron
47
+ if (options.parsedSchematronMap) {
48
+ schematronMap = options.parsedSchematronMap;
49
+ }
50
+ else {
51
+ // If not valid schematron (xml), it might be a filepath
52
+ // Adding explicit check to make it clear
53
+ if (schematron.trim().indexOf('<') === -1) {
54
+ try {
55
+ schematron = fs.readFileSync(schematron, 'utf-8').toString();
56
+ }
57
+ catch (err) {
58
+ // If no valid schematron found, inform user, and return immediately
59
+ console.log('No valid schematron could be found');
60
+ return;
61
+ }
62
+ }
63
+ let hash = crypto
64
+ .createHash('md5')
65
+ .update(schematron)
66
+ .digest('hex');
67
+ schematronMap = parsedMap[hash];
68
+ // If not in cache
69
+ if (!schematronMap) {
70
+ // Load schematron doc
71
+ let schematronDoc = new dom().parseFromString(schematron);
72
+
73
+ // Parse schematron
74
+ schematronMap = parseSchematron(schematronDoc);
75
+
76
+ // Cache parsed schematron
77
+ parsedMap[hash] = schematronMap;
78
+ }
79
+ }
80
+
81
+ // Extract data from parsed schematron object
82
+ namespaceMap = schematronMap.namespaceMap;
83
+ patternRuleMap = schematronMap.patternRuleMap;
84
+ ruleAssertionMap = schematronMap.ruleAssertionMap;
85
+
86
+ // Create selector object, initialized with namespaces
87
+ // Avoid using 'select' as a variable name as it is overused
88
+ xpathSelect = xpath.useNamespaces(namespaceMap);
89
+
90
+ let errors = [];
91
+ let warnings = [];
92
+ let ignored = [];
93
+ for (let patternId in patternRuleMap) {
94
+ if (!patternRuleMap.hasOwnProperty(patternId)) {
95
+ continue;
96
+ }
97
+ const rules = patternRuleMap[patternId];
98
+ for (let i = 0; i < rules.length; i++) {
99
+ const ruleId = rules[i];
100
+ const ruleObject = ruleAssertionMap[ruleId];
101
+ if (_get(ruleObject, 'abstract')) {
102
+ continue;
103
+ }
104
+ const context = _get(ruleObject, 'context');
105
+ const assertionsAndExtensions = _get(ruleObject, 'assertionsAndExtensions') || [];
106
+ let failedAssertions = checkRule(xmlDoc, context, assertionsAndExtensions, options);
107
+ for (let j = 0; j < failedAssertions.length; j++) {
108
+ const assertionObject = failedAssertions[j];
109
+ const { type, assertionId, test, simplifiedTest, description, errorMessage, results } = assertionObject;
110
+ if (!results.ignored) {
111
+ for (let k = 0; k < results.length; k++) {
112
+ const resultObject = results[k];
113
+ const { result, line, path, xml } = resultObject;
114
+ if (!result) {
115
+ let obj = {
116
+ type: type,
117
+ test: test,
118
+ simplifiedTest: simplifiedTest,
119
+ description: description,
120
+ line: line,
121
+ path: path,
122
+ patternId: patternId,
123
+ ruleId: ruleId,
124
+ assertionId: assertionId,
125
+ context: context,
126
+ xml: xml
127
+ };
128
+ if (type === 'error') {
129
+ errors.push(obj);
130
+ }
131
+ else {
132
+ warnings.push(obj);
133
+ }
134
+ }
135
+ }
136
+ }
137
+ else {
138
+ let obj = {
139
+ errorMessage: errorMessage,
140
+ type: type,
141
+ test: test,
142
+ simplifiedTest: simplifiedTest,
143
+ description: description,
144
+ patternId: patternId,
145
+ ruleId: ruleId,
146
+ assertionId: assertionId,
147
+ context: context
148
+ };
149
+ ignored.push(obj);
150
+ }
151
+ }
152
+ }
153
+ }
154
+
155
+ return {
156
+ errorCount: errors.length,
157
+ warningCount: warnings.length,
158
+ ignoredCount: ignored.length,
159
+ errors: errors,
160
+ warnings: warnings,
161
+ ignored: ignored
162
+ };
163
+ }
164
+
165
+ // Take the checkRule function out of validate function, and pass on the variable needed as parameters and options
166
+ function checkRule(xmlDoc, originalContext, assertionsAndExtensions, options) {
167
+ // Context cache
168
+ const includeWarnings = options.includeWarnings === undefined ? true : options.includeWarnings;
169
+ const resourceDir = options.resourceDir || './';
170
+ const xmlSnippetMaxLength = options.xmlSnippetMaxLength === undefined ? 200 : options.xmlSnippetMaxLength;
171
+ let results = [];
172
+ const context = options.contextOverride || originalContext;
173
+ // Determine the sections within context, load selected section from cache if possible
174
+ let selected = contextMap[context];
175
+ let contextModified = context;
176
+ if (!selected) {
177
+ if (context) {
178
+ if (context.indexOf('/')) {
179
+ contextModified = '//' + context;
180
+ }
181
+ selected = xpathSelect(contextModified, xmlDoc);
182
+ }
183
+ else {
184
+ selected = [xmlDoc];
185
+ }
186
+ contextMap[context] = selected;
187
+ }
188
+
189
+ for (let i = 0; i < assertionsAndExtensions.length; i++) {
190
+ const assertionAndExtensionObject = assertionsAndExtensions[i];
191
+ if (assertionAndExtensionObject.type === 'assertion') {
192
+ let { level, test, id, description } = assertionAndExtensionObject;
193
+
194
+ // Extract values from external document and modify test if a document call is made
195
+ let originalTest = test;
196
+ try {
197
+ test = includeExternalDocument(test, resourceDir);
198
+ }
199
+ catch (err) {
200
+ return { ignored: true, errorMessage: err.message };
201
+ }
202
+
203
+ let simplifiedTest = null;
204
+ if (originalTest !== test) {
205
+ simplifiedTest = test;
206
+ }
207
+ if (level === 'error' || includeWarnings) {
208
+ results.push({
209
+ type: level,
210
+ assertionId: id,
211
+ test: originalTest,
212
+ simplifiedTest: simplifiedTest,
213
+ description: description,
214
+ results: testAssertion(test, selected, xpathSelect, xmlDoc, resourceDir, xmlSnippetMaxLength)
215
+ });
216
+ }
217
+ }
218
+ else {
219
+ const extensionRule = assertionAndExtensionObject.rule;
220
+ if (!extensionRule) {
221
+ continue;
222
+ }
223
+ const subAssertionsAndExtensions = ruleAssertionMap[extensionRule] ? ruleAssertionMap[extensionRule].assertionsAndExtensions : null;
224
+ if (!subAssertionsAndExtensions) {
225
+ continue;
226
+ }
227
+ const newRuleObject = ruleAssertionMap[extensionRule];
228
+ const newContext = newRuleObject.context;
229
+ results = results.concat(checkRule(xmlDoc, newContext, subAssertionsAndExtensions, options));
230
+ }
231
+ }
232
+ return results;
233
+ }