fhir-validator-wrapper 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,396 @@
1
+ const { spawn } = require('child_process');
2
+ const http = require('http');
3
+ const https = require('https');
4
+ const { URL } = require('url');
5
+
6
+ /**
7
+ * Node.js wrapper for the FHIR Validator HTTP Service
8
+ */
9
+ class FhirValidator {
10
+ constructor(validatorJarPath) {
11
+ this.validatorJarPath = validatorJarPath;
12
+ this.process = null;
13
+ this.port = null;
14
+ this.baseUrl = null;
15
+ this.isReady = false;
16
+ }
17
+
18
+ /**
19
+ * Start the FHIR validator service
20
+ * @param {Object} config - Configuration object
21
+ * @param {string} config.version - FHIR version (e.g., "5.0.0")
22
+ * @param {string} config.txServer - Terminology server URL (e.g., "http://tx.fhir.org/r5")
23
+ * @param {string} config.txLog - Path to transaction log file
24
+ * @param {string[]} [config.igs] - Array of implementation guide packages (e.g., ["hl7.fhir.us.core#6.0.0"])
25
+ * @param {number} [config.port=8080] - Port to run the service on
26
+ * @param {number} [config.timeout=30000] - Timeout in ms to wait for service to be ready
27
+ * @returns {Promise<void>}
28
+ */
29
+ async start(config) {
30
+ if (this.process) {
31
+ throw new Error('Validator service is already running');
32
+ }
33
+
34
+ const { version, txServer, txLog, igs = [], port = 8080, timeout = 30000 } = config;
35
+
36
+ if (!version || !txServer || !txLog) {
37
+ throw new Error('version, txServer, and txLog are required');
38
+ }
39
+
40
+ this.port = port;
41
+ this.baseUrl = `http://localhost:${port}`;
42
+
43
+ // Build command line arguments
44
+ const args = [
45
+ '-jar', this.validatorJarPath,
46
+ '-server', port.toString(),
47
+ '-tx', txServer,
48
+ '-txlog', txLog,
49
+ '-version', version
50
+ ];
51
+
52
+ // Add implementation guides
53
+ for (const ig of igs) {
54
+ args.push('-ig', ig);
55
+ }
56
+
57
+ console.log(`Starting FHIR validator with command: java ${args.join(' ')}`);
58
+
59
+ // Spawn the Java process
60
+ this.process = spawn('java', args, {
61
+ stdio: ['pipe', 'pipe', 'pipe']
62
+ });
63
+
64
+ // Handle process events
65
+ this.process.on('error', (error) => {
66
+ console.error('Failed to start validator process:', error);
67
+ throw error;
68
+ });
69
+
70
+ this.process.on('exit', (code, signal) => {
71
+ console.log(`Validator process exited with code ${code} and signal ${signal}`);
72
+ this.cleanup();
73
+ });
74
+
75
+ // Capture stdout and stderr for debugging
76
+ this.process.stdout.on('data', (data) => {
77
+ const lines = data.toString().split('\n');
78
+ lines.forEach(line => {
79
+ // Remove ANSI escape sequences (color codes, etc.)
80
+ const cleanLine = line.replace(/\u001b\[[0-9;]*m/g, '').trim();
81
+ if (cleanLine.length > 1) { // Only log non-empty lines
82
+ console.log(`Validator: ${cleanLine}`);
83
+ }
84
+ });
85
+ });
86
+
87
+ this.process.stderr.on('data', (data) => {
88
+ console.error(`Validator-err: ${data}`);
89
+ });
90
+
91
+ // Wait for the service to be ready
92
+ await this.waitForReady(timeout);
93
+ console.log('FHIR validator service is ready');
94
+ }
95
+
96
+ /**
97
+ * Wait for the HTTP service to be ready
98
+ * @param {number} timeout - Timeout in milliseconds
99
+ * @returns {Promise<void>}
100
+ */
101
+ async waitForReady(timeout) {
102
+ const startTime = Date.now();
103
+
104
+ while (Date.now() - startTime < timeout) {
105
+ try {
106
+ await this.healthCheck();
107
+ this.isReady = true;
108
+ return;
109
+ } catch (error) {
110
+ // Service not ready yet, wait and retry
111
+ await new Promise(resolve => setTimeout(resolve, 1000));
112
+ }
113
+ }
114
+
115
+ throw new Error(`Validator service did not become ready within ${timeout}ms`);
116
+ }
117
+
118
+ /**
119
+ * Perform a health check on the service
120
+ * @returns {Promise<void>}
121
+ */
122
+ healthCheck() {
123
+ return new Promise((resolve, reject) => {
124
+ const req = http.get(`${this.baseUrl}/validateResource`, (res) => {
125
+ // We expect a 405 Method Not Allowed since we're doing GET instead of POST
126
+ if (res.statusCode === 405) {
127
+ resolve();
128
+ } else {
129
+ reject(new Error(`Unexpected status code: ${res.statusCode}`));
130
+ }
131
+ });
132
+
133
+ req.on('error', reject);
134
+ req.setTimeout(5000, () => {
135
+ req.destroy();
136
+ reject(new Error('Health check timeout'));
137
+ });
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Validate a FHIR resource
143
+ * @param {string|Buffer|Object} resource - The resource to validate (JSON string, Buffer, or Object)
144
+ * @param {Object} [options] - Validation options
145
+ * @param {string[]} [options.profiles] - Profiles to validate against
146
+ * @param {string} [options.resourceIdRule] - Resource ID rule ("OPTIONAL", "REQUIRED", "PROHIBITED")
147
+ * @param {boolean} [options.anyExtensionsAllowed=true] - Whether any extensions are allowed
148
+ * @param {string} [options.bpWarnings] - Best practice warning level
149
+ * @param {string} [options.displayOption] - Display option for validation
150
+ * @returns {Promise<Object>} - The OperationOutcome as a JavaScript object
151
+ */
152
+ async validate(resource, options = {}) {
153
+ if (!this.isReady) {
154
+ throw new Error('Validator service is not ready');
155
+ }
156
+
157
+ // Convert resource to bytes
158
+ let resourceBytes;
159
+ let contentType = 'application/fhir+json';
160
+
161
+ if (typeof resource === 'string') {
162
+ // Determine if it's JSON or XML
163
+ const trimmed = resource.trim();
164
+ if (trimmed.startsWith('<')) {
165
+ contentType = 'application/fhir+xml';
166
+ }
167
+ resourceBytes = Buffer.from(resource, 'utf8');
168
+ } else if (Buffer.isBuffer(resource)) {
169
+ resourceBytes = resource;
170
+ // Try to detect format from content
171
+ const content = resource.toString('utf8').trim();
172
+ if (content.startsWith('<')) {
173
+ contentType = 'application/fhir+xml';
174
+ }
175
+ } else if (typeof resource === 'object') {
176
+ resourceBytes = Buffer.from(JSON.stringify(resource), 'utf8');
177
+ contentType = 'application/fhir+json';
178
+ } else {
179
+ throw new Error('Resource must be a string, Buffer, or object');
180
+ }
181
+
182
+ // Build query parameters
183
+ const queryParams = new URLSearchParams();
184
+
185
+ if (options.profiles && options.profiles.length > 0) {
186
+ queryParams.set('profiles', options.profiles.join(','));
187
+ }
188
+ if (options.resourceIdRule) {
189
+ queryParams.set('resourceIdRule', options.resourceIdRule);
190
+ }
191
+ if (options.anyExtensionsAllowed !== undefined) {
192
+ queryParams.set('anyExtensionsAllowed', options.anyExtensionsAllowed.toString());
193
+ }
194
+ if (options.bpWarnings) {
195
+ queryParams.set('bpWarnings', options.bpWarnings);
196
+ }
197
+ if (options.displayOption) {
198
+ queryParams.set('displayOption', options.displayOption);
199
+ }
200
+
201
+ const url = `${this.baseUrl}/validateResource?${queryParams.toString()}`;
202
+
203
+ return new Promise((resolve, reject) => {
204
+ const parsedUrl = new URL(url);
205
+ const requestOptions = {
206
+ hostname: parsedUrl.hostname,
207
+ port: parsedUrl.port,
208
+ path: parsedUrl.pathname + parsedUrl.search,
209
+ method: 'POST',
210
+ headers: {
211
+ 'Content-Type': contentType,
212
+ 'Content-Length': resourceBytes.length,
213
+ 'Accept': 'application/fhir+json'
214
+ }
215
+ };
216
+
217
+ const req = http.request(requestOptions, (res) => {
218
+ let data = '';
219
+
220
+ res.on('data', (chunk) => {
221
+ data += chunk;
222
+ });
223
+
224
+ res.on('end', () => {
225
+ try {
226
+ const result = JSON.parse(data);
227
+ resolve(result);
228
+ } catch (error) {
229
+ reject(new Error(`Failed to parse response: ${error.message}\nResponse: ${data}`));
230
+ }
231
+ });
232
+ });
233
+
234
+ req.on('error', reject);
235
+
236
+ req.setTimeout(30000, () => {
237
+ req.destroy();
238
+ reject(new Error('Validation request timeout'));
239
+ });
240
+
241
+ req.write(resourceBytes);
242
+ req.end();
243
+ });
244
+ }
245
+
246
+ /**
247
+ * Validate a FHIR resource with byte array input
248
+ * @param {Buffer} resourceBytes - The resource as bytes
249
+ * @param {string} [format='json'] - The format ('json' or 'xml')
250
+ * @param {Object} [options] - Validation options (same as validate method)
251
+ * @returns {Promise<Object>} - The OperationOutcome as a JavaScript object
252
+ */
253
+ async validateBytes(resourceBytes, format = 'json', options = {}) {
254
+ if (!Buffer.isBuffer(resourceBytes)) {
255
+ throw new Error('resourceBytes must be a Buffer');
256
+ }
257
+
258
+ return this.validate(resourceBytes, options);
259
+ }
260
+
261
+ /**
262
+ * Validate a FHIR resource object
263
+ * @param {Object} resourceObject - The resource as a JavaScript object
264
+ * @param {Object} [options] - Validation options (same as validate method)
265
+ * @returns {Promise<Object>} - The OperationOutcome as a JavaScript object
266
+ */
267
+ async validateObject(resourceObject, options = {}) {
268
+ if (typeof resourceObject !== 'object' || resourceObject === null) {
269
+ throw new Error('resourceObject must be an object');
270
+ }
271
+
272
+ return this.validate(resourceObject, options);
273
+ }
274
+
275
+ /**
276
+ * Load an Implementation Guide
277
+ * @param {string} packageId - The package ID (e.g., "hl7.fhir.us.core")
278
+ * @param {string} version - The version (e.g., "6.0.0")
279
+ * @returns {Promise<Object>} - The OperationOutcome as a JavaScript object
280
+ */
281
+ async loadIG(packageId, version) {
282
+ if (!this.isReady) {
283
+ throw new Error('Validator service is not ready');
284
+ }
285
+
286
+ const queryParams = new URLSearchParams();
287
+ queryParams.set('packageId', packageId);
288
+ queryParams.set('version', version);
289
+
290
+ const url = `${this.baseUrl}/loadIG?${queryParams.toString()}`;
291
+
292
+ return new Promise((resolve, reject) => {
293
+ const parsedUrl = new URL(url);
294
+ const requestOptions = {
295
+ hostname: parsedUrl.hostname,
296
+ port: parsedUrl.port,
297
+ path: parsedUrl.pathname + parsedUrl.search,
298
+ method: 'POST',
299
+ headers: {
300
+ 'Accept': 'application/fhir+json'
301
+ }
302
+ };
303
+
304
+ const req = http.request(requestOptions, (res) => {
305
+ let data = '';
306
+
307
+ res.on('data', (chunk) => {
308
+ data += chunk;
309
+ });
310
+
311
+ res.on('end', () => {
312
+ try {
313
+ const result = JSON.parse(data);
314
+ resolve(result);
315
+ } catch (error) {
316
+ reject(new Error(`Failed to parse response: ${error.message}\nResponse: ${data}`));
317
+ }
318
+ });
319
+ });
320
+
321
+ req.on('error', reject);
322
+
323
+ req.setTimeout(30000, () => {
324
+ req.destroy();
325
+ reject(new Error('Load IG request timeout'));
326
+ });
327
+
328
+ req.end();
329
+ });
330
+ }
331
+
332
+ /**
333
+ * Stop the validator service
334
+ * @returns {Promise<void>}
335
+ */
336
+ async stop() {
337
+ if (!this.process) {
338
+ return;
339
+ }
340
+
341
+ return new Promise((resolve, reject) => {
342
+ const timeout = setTimeout(() => {
343
+ console.warn('Force killing validator process after timeout');
344
+ if (this.process && !this.process.killed) {
345
+ this.process.kill('SIGKILL');
346
+ }
347
+ this.cleanup();
348
+ resolve();
349
+ }, 10000); // 10 second total timeout
350
+
351
+ // Single exit handler
352
+ const onExit = () => {
353
+ clearTimeout(timeout);
354
+ this.cleanup();
355
+ resolve();
356
+ };
357
+
358
+ this.process.once('exit', onExit); // Use 'once' to avoid duplicate listeners
359
+
360
+ // Since Java process is blocking on System.in.read(), SIGTERM likely won't work
361
+ // Go straight to SIGKILL for immediate termination
362
+ console.log('Stopping validator process...');
363
+ this.process.kill('SIGKILL');
364
+
365
+ // Backup: try SIGTERM first, then SIGKILL after 2 seconds
366
+ // this.process.kill('SIGTERM');
367
+ // setTimeout(() => {
368
+ // if (this.process && !this.process.killed) {
369
+ // console.log('Escalating to SIGKILL...');
370
+ // this.process.kill('SIGKILL');
371
+ // }
372
+ // }, 2000);
373
+ });
374
+ }
375
+
376
+ /**
377
+ * Clean up internal state
378
+ * @private
379
+ */
380
+ cleanup() {
381
+ this.process = null;
382
+ this.port = null;
383
+ this.baseUrl = null;
384
+ this.isReady = false;
385
+ }
386
+
387
+ /**
388
+ * Check if the validator service is running
389
+ * @returns {boolean}
390
+ */
391
+ isRunning() {
392
+ return this.process !== null && this.isReady;
393
+ }
394
+ }
395
+
396
+ module.exports = FhirValidator;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "fhir-validator-wrapper",
3
+ "version": "1.0.0",
4
+ "description": "Node.js wrapper for the HL7 FHIR Validator CLI",
5
+ "main": "fhir-validator.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "test:unit": "jest --testPathIgnorePatterns=integration",
9
+ "test:integration": "INTEGRATION_TESTS=1 jest",
10
+ "test:manual": "MANUAL_TEST=1 node tests.js",
11
+ "test:with-jar": "FHIR_VALIDATOR_JAR_PATH=./my-validator.jar npm test",
12
+ "start": "node example.js"
13
+ },
14
+ "keywords": [
15
+ "fhir",
16
+ "validator",
17
+ "hl7",
18
+ "healthcare",
19
+ "interoperability",
20
+ "validation"
21
+ ],
22
+ "author": "Grahame Grieve",
23
+ "license": "Apache-2.0",
24
+ "engines": {
25
+ "node": ">=12.0.0"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/FHIR/fhir-validator-wrapper.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/FHIR/fhir-validator-wrapper/issues"
33
+ },
34
+ "homepage": "https://github.com/FHIR/fhir-validator-wrapper#readme",
35
+ "dependencies": {},
36
+ "devDependencies": {
37
+ "jest": "^29.0.0"
38
+ },
39
+ "files": [
40
+ "fhir-validator.js",
41
+ "README.md",
42
+ "LICENSE"
43
+ ]
44
+ }
package/readme.md ADDED
@@ -0,0 +1,356 @@
1
+ [![npm version](https://badge.fury.io/js/fhir-validator-wrapper.svg)](https://badge.fury.io/js/fhir-validator-wrapper)
2
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-yellow.svg)]
3
+ [![Downloads](https://img.shields.io/npm/dm/fhir-validator-wrapper.svg)](https://www.npmjs.com/package/fhir-validator-wrapper)
4
+
5
+ # FHIR Validator Wrapper
6
+
7
+ A Node.js wrapper for the HL7 FHIR Validator CLI that provides a simple, promise-based API for validating FHIR resources.
8
+
9
+ ## FHIR Foundation Project Statement
10
+
11
+ * Maintainers: Grahame Grieve (looking for volunteers)
12
+ * Issues / Discussion: https://github.com/FHIR/fhir-validator-wrapper/issues / https://chat.fhir.org/#narrow/channel/179169-javascript
13
+ * License: Apache 2.0
14
+ * Contribution Policy: See [Contributing](#contributing).
15
+ * Security Information: To report a security issue, please use the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/FHIR/fhir-validator-wrapper/security/advisories/new) tab.
16
+
17
+ ## Contributing
18
+
19
+ There are many ways to contribute:
20
+ * [Submit bugs](https://github.com/FHIR/fhir-validator-wrapper/issues) and help us verify fixes as they are checked in.
21
+ * Review the [source code changes](https://github.com/FHIR/fhir-validator-wrapper/pulls).
22
+ * Engage with users and developers on the [dotnet stream on FHIR Zulip](https://chat.fhir.org/#narrow/channel/179169-javascript)
23
+ * Contribute features or bug fixes via PRs:
24
+
25
+ 1. Fork the repository
26
+ 2. Create a feature branch
27
+ 3. Make your changes
28
+ 4. Add tests
29
+ 5. Submit a pull request
30
+
31
+ ## Overview
32
+
33
+ This library manages the lifecycle of the FHIR Validator Java service and provides a clean Node.js interface for validation operations. It handles process management, HTTP communication, and provides typed validation options.
34
+
35
+ ## Prerequisites
36
+
37
+ - Node.js 12.0.0 or higher
38
+ - Java 8 or higher
39
+ - FHIR Validator CLI JAR file (download from [GitHub releases](https://github.com/hapifhir/org.hl7.fhir.core/releases))
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ npm install fhir-validator-wrapper
45
+ ```
46
+
47
+ ## Quick Start
48
+
49
+ ```bash
50
+ # Run the example with your JAR file
51
+ FHIR_VALIDATOR_JAR_PATH=./your-validator.jar npm start
52
+ ```
53
+
54
+ Or in code:
55
+
56
+ ```javascript
57
+ const FhirValidator = require('fhir-validator-wrapper');
58
+
59
+ async function validateResource() {
60
+ const validator = new FhirValidator('./validator_cli.jar');
61
+
62
+ try {
63
+ // Start the validator service
64
+ await validator.start({
65
+ version: '5.0.0',
66
+ txServer: 'http://tx.fhir.org/r5',
67
+ txLog: './txlog.txt',
68
+ igs: ['hl7.fhir.us.core#6.0.0']
69
+ });
70
+
71
+ // Validate a resource
72
+ const patient = {
73
+ resourceType: 'Patient',
74
+ id: 'example',
75
+ active: true,
76
+ name: [{ family: 'Doe', given: ['John'] }]
77
+ };
78
+
79
+ const result = await validator.validate(patient);
80
+ console.log('Validation result:', result);
81
+
82
+ } finally {
83
+ await validator.stop();
84
+ }
85
+ }
86
+ ```
87
+
88
+ ## API Reference
89
+
90
+ ### Constructor
91
+
92
+ #### `new FhirValidator(validatorJarPath)`
93
+
94
+ Creates a new FHIR validator instance.
95
+
96
+ - `validatorJarPath` (string): Path to the FHIR validator CLI JAR file
97
+
98
+ ### Methods
99
+
100
+ #### `start(config)`
101
+
102
+ Starts the FHIR validator service with the specified configuration.
103
+
104
+ **Parameters:**
105
+ - `config` (Object): Configuration object
106
+ - `version` (string): FHIR version (e.g., "5.0.0", "4.0.1")
107
+ - `txServer` (string): Terminology server URL (e.g., "http://tx.fhir.org/r5")
108
+ - `txLog` (string): Path to transaction log file
109
+ - `igs` (string[], optional): Array of implementation guide packages
110
+ - `port` (number, optional): Port to run the service on (default: 8080)
111
+ - `timeout` (number, optional): Startup timeout in milliseconds (default: 30000)
112
+
113
+ **Returns:** `Promise<void>`
114
+
115
+ **Example:**
116
+ ```javascript
117
+ await validator.start({
118
+ version: '5.0.0',
119
+ txServer: 'http://tx.fhir.org/r5',
120
+ txLog: './txlog.txt',
121
+ igs: [
122
+ 'hl7.fhir.us.core#6.0.0',
123
+ 'hl7.fhir.uv.sdc#3.0.0'
124
+ ],
125
+ port: 8080
126
+ });
127
+ ```
128
+
129
+ #### `validate(resource, options)`
130
+
131
+ Validates a FHIR resource against the loaded implementation guides and profiles.
132
+
133
+ **Parameters:**
134
+ - `resource` (string|Buffer|Object): The resource to validate
135
+ - String: JSON or XML resource
136
+ - Buffer: Raw bytes of resource
137
+ - Object: JavaScript object representing the resource
138
+ - `options` (Object, optional): Validation options
139
+ - `profiles` (string[]): Profiles to validate against
140
+ - `resourceIdRule` (string): Resource ID rule ("OPTIONAL", "REQUIRED", "PROHIBITED")
141
+ - `anyExtensionsAllowed` (boolean): Whether any extensions are allowed (default: true)
142
+ - `bpWarnings` (string): Best practice warning level
143
+ - `displayOption` (string): Display option for validation
144
+
145
+ **Returns:** `Promise<Object>` - OperationOutcome as JavaScript object
146
+
147
+ **Examples:**
148
+ ```javascript
149
+ // Basic validation
150
+ const result = await validator.validate(patientResource);
151
+
152
+ // Validation with options
153
+ const result = await validator.validate(patientResource, {
154
+ profiles: ['http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient'],
155
+ resourceIdRule: 'REQUIRED',
156
+ bpWarnings: 'Warning'
157
+ });
158
+ ```
159
+
160
+ #### `validateBytes(resourceBytes, format, options)`
161
+
162
+ Validates a FHIR resource from raw bytes.
163
+
164
+ **Parameters:**
165
+ - `resourceBytes` (Buffer): The resource as bytes
166
+ - `format` (string, optional): The format ("json" or "xml", default: "json")
167
+ - `options` (Object, optional): Same as `validate()` method
168
+
169
+ **Returns:** `Promise<Object>` - OperationOutcome as JavaScript object
170
+
171
+ #### `validateObject(resourceObject, options)`
172
+
173
+ Validates a FHIR resource object.
174
+
175
+ **Parameters:**
176
+ - `resourceObject` (Object): The resource as a JavaScript object
177
+ - `options` (Object, optional): Same as `validate()` method
178
+
179
+ **Returns:** `Promise<Object>` - OperationOutcome as JavaScript object
180
+
181
+ #### `loadIG(packageId, version)`
182
+
183
+ Loads an additional implementation guide at runtime.
184
+
185
+ **Parameters:**
186
+ - `packageId` (string): The package ID (e.g., "hl7.fhir.us.core")
187
+ - `version` (string): The version (e.g., "6.0.0")
188
+
189
+ **Returns:** `Promise<Object>` - OperationOutcome as JavaScript object
190
+
191
+ **Example:**
192
+ ```javascript
193
+ await validator.loadIG('hl7.fhir.uv.ips', '1.1.0');
194
+ ```
195
+
196
+ #### `stop()`
197
+
198
+ Stops the validator service and cleans up resources.
199
+
200
+ **Returns:** `Promise<void>`
201
+
202
+ #### `isRunning()`
203
+
204
+ Checks if the validator service is currently running.
205
+
206
+ **Returns:** `boolean`
207
+
208
+ #### `healthCheck()`
209
+
210
+ Performs a health check on the running service.
211
+
212
+ **Returns:** `Promise<void>`
213
+
214
+ ## Implementation Guide Loading
215
+
216
+ Implementation guides can be loaded in two ways:
217
+
218
+ 1. **At startup** (recommended for known dependencies):
219
+ ```javascript
220
+ await validator.start({
221
+ version: '5.0.0',
222
+ txServer: 'http://tx.fhir.org/r5',
223
+ txLog: './txlog.txt',
224
+ igs: [
225
+ 'hl7.fhir.us.core#6.0.0',
226
+ 'hl7.fhir.uv.sdc#3.0.0'
227
+ ]
228
+ });
229
+ ```
230
+
231
+ 2. **At runtime** (for dynamic loading):
232
+ ```javascript
233
+ await validator.loadIG('hl7.fhir.uv.ips', '1.1.0');
234
+ ```
235
+
236
+ For IG package format documentation, see: [Using the FHIR Validator - Loading Implementation Guides](https://confluence.hl7.org/spaces/FHIR/pages/35718580/Using+the+FHIR+Validator#UsingtheFHIRValidator-LoadinganimplementationGuide)
237
+
238
+ ## Error Handling
239
+
240
+ The library throws descriptive errors for various failure scenarios:
241
+
242
+ ```javascript
243
+ try {
244
+ await validator.validate(invalidResource);
245
+ } catch (error) {
246
+ if (error.message.includes('Validation failed')) {
247
+ // Handle validation errors
248
+ console.log('Resource is invalid:', error.message);
249
+ } else if (error.message.includes('not ready')) {
250
+ // Handle service not ready
251
+ console.log('Service not started:', error.message);
252
+ } else {
253
+ // Handle other errors
254
+ console.log('Unexpected error:', error.message);
255
+ }
256
+ }
257
+ ```
258
+
259
+ ## Best Practices
260
+
261
+ 1. **Resource Management**: Always call `stop()` when done to clean up the Java process:
262
+ ```javascript
263
+ try {
264
+ await validator.start(config);
265
+ // ... validation operations
266
+ } finally {
267
+ await validator.stop();
268
+ }
269
+ ```
270
+
271
+ 2. **Process Termination Handling**: Handle graceful shutdown:
272
+ ```javascript
273
+ process.on('SIGINT', async () => {
274
+ await validator.stop();
275
+ process.exit(0);
276
+ });
277
+ ```
278
+
279
+ 3. **Reuse Validator Instance**: Start the validator once and reuse for multiple validations:
280
+ ```javascript
281
+ const validator = new FhirValidator('./validator_cli.jar');
282
+ await validator.start(config);
283
+
284
+ // Validate multiple resources
285
+ const result1 = await validator.validate(resource1);
286
+ const result2 = await validator.validate(resource2);
287
+ const result3 = await validator.validate(resource3);
288
+
289
+ await validator.stop();
290
+ ```
291
+
292
+ 4. **Timeout Configuration**: Set appropriate timeouts for startup in production:
293
+ ```javascript
294
+ await validator.start({
295
+ // ... other config
296
+ timeout: 120000 // 2 minutes for production environments
297
+ });
298
+ ```
299
+
300
+ ## Testing
301
+
302
+ The library includes comprehensive tests. You can run them in different ways depending on your setup:
303
+
304
+ ### Unit Tests Only
305
+ ```bash
306
+ npm run test:unit
307
+ ```
308
+
309
+ ### Integration Tests (requires JAR file)
310
+ ```bash
311
+ # Set the JAR path and run integration tests
312
+ FHIR_VALIDATOR_JAR_PATH=./your-validator.jar npm run test:integration
313
+ ```
314
+
315
+ ### Manual Testing
316
+ ```bash
317
+ # Quick manual test with your JAR
318
+ FHIR_VALIDATOR_JAR_PATH=./your-validator.jar npm run test:manual
319
+ ```
320
+
321
+ ### Configuration
322
+
323
+ The JAR file location can be configured using the `FHIR_VALIDATOR_JAR_PATH` environment variable:
324
+
325
+ ```bash
326
+ # Option 1: Set environment variable
327
+ export FHIR_VALIDATOR_JAR_PATH=/path/to/your/validator.jar
328
+ npm test
329
+
330
+ # Option 2: Inline with command
331
+ FHIR_VALIDATOR_JAR_PATH=./validator_cli.jar npm test
332
+
333
+ # Option 3: Use npm script helper
334
+ npm run test:with-jar
335
+ ```
336
+
337
+ **Default behavior**: If no environment variable is set, tests will look for `./validator_cli.jar`
338
+
339
+ ## Troubleshooting
340
+
341
+ ### Common Issues
342
+
343
+ 1. **Java not found**: Ensure Java is installed and available in PATH
344
+ 2. **JAR file not found**: Verify the validator JAR path is correct
345
+ 3. **Port conflicts**: Change the port if 8080 is already in use
346
+ 4. **Memory issues**: Add JVM options by modifying the spawn command if needed
347
+ 5. **Network timeouts**: Increase timeout values for slow networks
348
+
349
+ ### Debug Logging
350
+
351
+ The library logs validator stdout/stderr for debugging. Check console output for Java process messages.
352
+
353
+ ## Support
354
+
355
+ For issues with this wrapper, please file a GitHub issue.
356
+ For FHIR validator issues, see the [official FHIR validator documentation](https://confluence.hl7.org/spaces/FHIR/pages/35718580/Using+the+FHIR+Validator).