mllp-node-sl7 2.1.5 → 2.2.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/README.md CHANGED
@@ -1,36 +1,86 @@
1
1
  mllp
2
2
  ====
3
+
3
4
  Fork, for original Readme see below!
4
5
 
5
6
  # Install:
7
+
6
8
  [![NPM](https://nodei.co/npm/mllp-node-sl7.png)](https://nodei.co/npm/mllp-node-sl7/)
7
9
 
8
10
  Changes:
11
+
9
12
  - Multi Message Support on a single Socket Connection
10
- - Basic Character Encoding Support
13
+ - Character set from MSH-18, otherwise the default character set of the server (5th constructor
14
+ argument in MSH-18 notation such as `8859/1`, default `UNICODE UTF-8`); decoding is done by
15
+ sb-sl7. `ISO IR6`, `ISO IR100` and `ISO IR192` count as `ASCII`, `8859/1` and `UNICODE UTF-8`. A
16
+ message that cannot be decoded is read as UTF-8 and reported to the logger as a warning without
17
+ content; an MSH-18 value that is not a character set of HL7 table 0211 is shown as
18
+ `<invalid MSH-18>`. A default character set that is not supported is reported once when the
19
+ server is created, and messages without MSH-18 are then read as UTF-8.
20
+ - Responses (ACKs) are always sent as UTF-8, whatever the character set of the message.
11
21
  - Timeout with Auto-Response
12
22
  - Supports bind to all Interfaces (0.0.0.0)
13
- - Using Package [sb-sl7](https://github.com/sourceblock-ug/sb-sl7) for Message parsing
23
+ - Using Package [sb-sl7](https://github.com/sourceblock-ug/sb-sl7) for Message parsing
14
24
 
15
- Sample (see example.js):
16
- ```javascript
17
- var mllp = require('mllp-node');
18
- var timeout = 600; // ms
19
- var server = new mllp.MLLPServer('0.0.0.0', 1234, timeout);
25
+ ## Usage
20
26
 
21
- // Subscribe to inbound messages
22
- server.on('hl7', function (data){
23
- console.log('received payload:', data);
24
- });
27
+ ```typescript
28
+ import { MLLPServer, mllpSendMessage } from "mllp-node-sl7";
25
29
 
26
- // Send outbound messages
27
- server.send('127.0.0.1', 4321, 'outbound-hl7-message', function (err, ackData) {
28
- // async callback code here
30
+ // Optional, see "Logging". Without a logger nothing is logged. This one has no
31
+ // `trace`, so message content is never logged.
32
+ const logger = { info: console.info, warn: console.warn, error: console.error };
33
+
34
+ const server = new MLLPServer("0.0.0.0", 1234, logger, 600);
35
+
36
+ // Inbound messages. Without a response the default ACK is sent after the timeout.
37
+ server.on("hl7", (event) => {
38
+ // event.id (MSH-10), event.msg (decoded text), event.hl7 (parsed sb-sl7 Message)
39
+ server.sendResponse(event.id, "AA");
29
40
  });
41
+
42
+ // Outbound messages
43
+ mllpSendMessage(
44
+ "127.0.0.1",
45
+ 4321,
46
+ "outbound-hl7-message",
47
+ (err, ack, response) => {
48
+ // ack is the MSA segment, response the complete answer
49
+ },
50
+ );
30
51
  ```
31
52
 
32
- Original Readme:
53
+ Errors of a connection and of the server itself (a port that is already in use, for example) are
54
+ emitted as `hl7-error`. If listening fails, `hl7-ready` is not emitted. An error of the server is
55
+ logged only if nobody listens for `hl7-error`.
33
56
 
57
+ ## Logging
58
+
59
+ The library never writes to the console. Pass a logger as third constructor argument (and as
60
+ last argument of `mllpSendMessage`); without one nothing is logged.
61
+
62
+ - An object with `trace`, `debug`, `info`, `warn` and `error` methods (`MllpLogger`) gets every
63
+ entry on its level. Message content is passed to `trace` only; all other levels carry
64
+ technical data such as the message id (MSH-10), the message type and remote addresses. A level
65
+ the object does not have is silent.
66
+ - A plain function `(msg, ...data) => void` is still accepted. It receives everything except
67
+ the `trace` output and therefore never sees message content.
68
+
69
+ HL7 messages usually contain patient data, so only enable `trace` where that is acceptable.
70
+
71
+ ## Development
72
+
73
+ Development requires Node.js 22.13 or newer, or 24 (Vitest 5 and ESLint 10); the library itself
74
+ runs on Node.js 20 or newer.
75
+
76
+ ```bash
77
+ npm install
78
+ npm test # Vitest
79
+ npm run lint # type check (npm run typecheck), ESLint and Prettier
80
+ npm run build # compiles to dist/
81
+ ```
82
+
83
+ Original Readme:
34
84
 
35
85
  [![NPM](https://nodei.co/npm/mllp-node.png)](https://nodei.co/npm/mllp-node/)
36
86
 
@@ -39,16 +89,14 @@ Original Readme:
39
89
 
40
90
  HL7's MLLP (Minimum Lower Layer Protocol) server implementation in Node.js.
41
91
 
42
-
43
92
  Listen on predefined port for HL7 messages in format:
44
93
 
45
94
  ```
46
95
  <VT>[HL7 Message]<FS><CR>
47
96
  ```
48
97
 
49
- * [HL7 MLP minimul layer protocol defined](http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/)
50
- * [ACK message](http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/)
51
-
98
+ - [HL7 MLP minimul layer protocol defined](http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/)
99
+ - [ACK message](http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/)
52
100
 
53
101
  ## Quick up and running guide
54
102
 
@@ -70,18 +118,18 @@ grunt
70
118
  See `example.js`:
71
119
 
72
120
  ```javascript
73
- var mllp = require('mllp-node');
121
+ var mllp = require("mllp-node");
74
122
 
75
- var server = new mllp.MLLPServer('127.0.0.1', 1234);
123
+ var server = new mllp.MLLPServer("127.0.0.1", 1234);
76
124
 
77
125
  // Subscribe to inbound messages
78
- server.on('hl7', function (data){
79
- console.log('received payload:', data);
126
+ server.on("hl7", function (data) {
127
+ console.log("received payload:", data);
80
128
  });
81
129
 
82
130
  // Send outbound messages
83
- server.send('127.0.0.1', 4321, 'outbound-hl7-message', function (err, ackData) {
84
- // async callback code here
131
+ server.send("127.0.0.1", 4321, "outbound-hl7-message", function (err, ackData) {
132
+ // async callback code here
85
133
  });
86
134
  ```
87
135
 
@@ -0,0 +1,19 @@
1
+ /** Stands in for an MSH-18 value that is not a character set of table 0211. */
2
+ export declare const INVALID_MSH18 = "<invalid MSH-18>";
3
+ /**
4
+ * The name sb-sl7 understands for the given character set: an alias is
5
+ * replaced, any other name is passed on unchanged.
6
+ */
7
+ export declare function resolveCharset(name: string): string;
8
+ /**
9
+ * The character set of MSH-18 as it may be logged above TRACE. MSH-18 comes
10
+ * from the sender, so only a name of HL7 table 0211 is logged; any other
11
+ * value could be message content and is replaced by {@link INVALID_MSH18}.
12
+ */
13
+ export declare function describeMessageCharset(name: string): string;
14
+ /**
15
+ * The configured default character set as it may be logged: a configuration
16
+ * value, but still shortened to something that looks like a name.
17
+ */
18
+ export declare function describeConfiguredCharset(name: string): string;
19
+ //# sourceMappingURL=charset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"charset.d.ts","sourceRoot":"","sources":["../src/charset.ts"],"names":[],"mappings":"AA8BA,+EAA+E;AAC/E,eAAO,MAAM,aAAa,qBAAqB,CAAC;AAMhD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9D"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INVALID_MSH18 = void 0;
4
+ exports.resolveCharset = resolveCharset;
5
+ exports.describeMessageCharset = describeMessageCharset;
6
+ exports.describeConfiguredCharset = describeConfiguredCharset;
7
+ /**
8
+ * Names of character sets that sb-sl7 does not know, although they name a
9
+ * character set it supports: the ISO registrations of ASCII, Latin-1 and
10
+ * UTF-8.
11
+ */
12
+ const ALIASES = {
13
+ "ISO IR6": "ASCII",
14
+ "ISO IR100": "8859/1",
15
+ "ISO IR192": "UNICODE UTF-8",
16
+ };
17
+ /** Character sets of HL7 table 0211, apart from `8859/<n>`. */
18
+ const TABLE_0211 = new Set([
19
+ "ASCII",
20
+ "ISO IR6",
21
+ "ISO IR14",
22
+ "ISO IR87",
23
+ "ISO IR100",
24
+ "ISO IR159",
25
+ "ISO IR192",
26
+ "GB 18030-2000",
27
+ "KS X 1001",
28
+ "CNS 11643-1992",
29
+ "BIG-5",
30
+ "UNICODE",
31
+ "UNICODE UTF-8",
32
+ "UNICODE UTF-16",
33
+ "UNICODE UTF-32",
34
+ ]);
35
+ /** Stands in for an MSH-18 value that is not a character set of table 0211. */
36
+ exports.INVALID_MSH18 = "<invalid MSH-18>";
37
+ function normalise(name) {
38
+ return `${name}`.trim().toUpperCase();
39
+ }
40
+ /**
41
+ * The name sb-sl7 understands for the given character set: an alias is
42
+ * replaced, any other name is passed on unchanged.
43
+ */
44
+ function resolveCharset(name) {
45
+ return ALIASES[normalise(name)] ?? name;
46
+ }
47
+ /**
48
+ * The character set of MSH-18 as it may be logged above TRACE. MSH-18 comes
49
+ * from the sender, so only a name of HL7 table 0211 is logged; any other
50
+ * value could be message content and is replaced by {@link INVALID_MSH18}.
51
+ */
52
+ function describeMessageCharset(name) {
53
+ const normalised = normalise(name);
54
+ return TABLE_0211.has(normalised) || /^8859\/\d{1,2}$/.test(normalised)
55
+ ? normalised
56
+ : exports.INVALID_MSH18;
57
+ }
58
+ /**
59
+ * The configured default character set as it may be logged: a configuration
60
+ * value, but still shortened to something that looks like a name.
61
+ */
62
+ function describeConfiguredCharset(name) {
63
+ return /^[A-Za-z0-9 /_.-]{1,32}$/.test(name) ? name : "<invalid name>";
64
+ }
65
+ //# sourceMappingURL=charset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"charset.js","sourceRoot":"","sources":["../src/charset.ts"],"names":[],"mappings":";;;AAyCA,wCAEC;AAOD,wDAKC;AAMD,8DAEC;AA/DD;;;;GAIG;AACH,MAAM,OAAO,GAA2B;IACtC,SAAS,EAAE,OAAO;IAClB,WAAW,EAAE,QAAQ;IACrB,WAAW,EAAE,eAAe;CAC7B,CAAC;AAEF,+DAA+D;AAC/D,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,OAAO;IACP,SAAS;IACT,UAAU;IACV,UAAU;IACV,WAAW;IACX,WAAW;IACX,WAAW;IACX,eAAe;IACf,WAAW;IACX,gBAAgB;IAChB,OAAO;IACP,SAAS;IACT,eAAe;IACf,gBAAgB;IAChB,gBAAgB;CACjB,CAAC,CAAC;AAEH,+EAA+E;AAClE,QAAA,aAAa,GAAG,kBAAkB,CAAC;AAEhD,SAAS,SAAS,CAAC,IAAY;IAC7B,OAAO,GAAG,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACxC,CAAC;AAED;;;GAGG;AACH,SAAgB,cAAc,CAAC,IAAY;IACzC,OAAO,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC;AAC1C,CAAC;AAED;;;;GAIG;AACH,SAAgB,sBAAsB,CAAC,IAAY;IACjD,MAAM,UAAU,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IACnC,OAAO,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC;QACrE,CAAC,CAAC,UAAU;QACZ,CAAC,CAAC,qBAAa,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,IAAY;IACpD,OAAO,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC;AACzE,CAAC"}
@@ -1,13 +1,14 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
1
  import net from "net";
5
2
  import EventEmitter from "events";
6
3
  import { Message } from "@sourceblock-ug/sb-sl7";
4
+ import type { MllpLogFunction, MllpLogger } from "./logger";
5
+ export type { MllpLogFunction, MllpLogger } from "./logger";
7
6
  export interface Renderable {
8
7
  render(): string | Buffer;
9
8
  }
10
- export declare function mllpSendMessage(receivingHost: string, receivingPort: number, hl7Data: Buffer | Renderable | string, callback: (err: Error | null, response: string | null, responseMessage: string | null) => void, logger?: (msg: string) => void): void;
9
+ export declare const cleanupString: (msg: string, removeParts: string[]) => string;
10
+ export declare const cleanup: (msg: string) => string;
11
+ export declare function mllpSendMessage(receivingHost: string, receivingPort: number, hl7Data: Buffer | Renderable | string, callback: (err: Error | null, response: string | null, responseMessage: string | null) => void, logger?: Partial<MllpLogger> | MllpLogFunction): void;
11
12
  export interface MessageResponseEvent {
12
13
  id: string;
13
14
  ack: string | Renderable | unknown;
@@ -27,9 +28,15 @@ export interface MLLPConnectionState {
27
28
  * @constructor MLLPServer
28
29
  * @param {string} host a resolvable hostname or IP Address
29
30
  * @param {number} port a valid free port for the server to listen on.
30
- * @param defaultLogger
31
+ * @param defaultLogger logger with level methods, or a plain log function.
32
+ * Message content is only ever passed to `trace`; a plain function never
33
+ * receives it. A level the logger does not have is silent. Without a logger
34
+ * nothing is logged.
31
35
  * @param {number} timeout after which the answer is sended.
32
- * @param {string} defaultCharset for Message decoding
36
+ * @param {string} defaultCharset character set (MSH-18 notation, such as
37
+ * `8859/1`) of messages without MSH-18. Default `UNICODE UTF-8`. A character
38
+ * set that is not supported is reported once as a warning; such messages
39
+ * are then read as UTF-8.
33
40
  * @param {string} timeoutAck like AA or AE - default is AA
34
41
  *
35
42
  * @fires MLLPServer#hl7
@@ -52,7 +59,7 @@ export declare class MLLPServer extends EventEmitter {
52
59
  protected readonly HOST: string;
53
60
  protected readonly PORT: number;
54
61
  protected readonly TIMEOUT: number;
55
- protected logger: (msg: string, ...data: unknown[]) => void;
62
+ protected logger: MllpLogger;
56
63
  protected charset: string;
57
64
  private readonly TIMEOUTS;
58
65
  private readonly openEvents;
@@ -60,7 +67,19 @@ export declare class MLLPServer extends EventEmitter {
60
67
  protected connectionEventState: MLLPConnectionState;
61
68
  private readonly openConnections;
62
69
  private readonly timeoutAck;
63
- constructor(host: string, port: number, defaultLogger?: (msg: string) => void, timeout?: number, defaultCharset?: string, timeoutAck?: string);
70
+ constructor(host: string, port: number, defaultLogger?: Partial<MllpLogger> | MllpLogFunction, timeout?: number, defaultCharset?: string, timeoutAck?: string);
71
+ /**
72
+ * Checks the default character set once, so a name that is not supported
73
+ * is reported at the start instead of with every message without MSH-18.
74
+ * Such messages are read as UTF-8, as sb-sl7 would do anyway.
75
+ */
76
+ private checkDefaultCharset;
77
+ /**
78
+ * Reported by sb-sl7 when a message could not be decoded with its character
79
+ * set and was read as UTF-8 instead. MSH-18 comes from the sender, so only
80
+ * a character set of HL7 table 0211 is named above TRACE.
81
+ */
82
+ private readonly onDecodeError;
64
83
  private handleIncomingMessage;
65
84
  private updateState;
66
85
  private addSocket;
@@ -76,3 +95,4 @@ export declare class MLLPServer extends EventEmitter {
76
95
  close(done?: (err?: Error) => void): void;
77
96
  private static closeSocket;
78
97
  }
98
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
@@ -3,38 +3,52 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MLLPServer = exports.mllpSendMessage = void 0;
6
+ exports.MLLPServer = exports.cleanup = exports.cleanupString = void 0;
7
+ exports.mllpSendMessage = mllpSendMessage;
7
8
  const net_1 = __importDefault(require("net"));
8
9
  const events_1 = __importDefault(require("events"));
9
10
  const sb_sl7_1 = require("@sourceblock-ug/sb-sl7");
10
- const decoder_1 = __importDefault(require("./decoder"));
11
+ const charset_1 = require("./charset");
12
+ const logger_1 = require("./logger");
11
13
  // The header is a vertical tab character <VT> its hex value is 0x0b.
12
14
  // The trailer is a field separator character <FS> (hex 0x1c) immediately followed by a carriage return <CR> (hex 0x0d)
13
15
  const VT = String.fromCharCode(0x0b);
14
16
  const VTi = 0x0b;
15
17
  const FS = String.fromCharCode(0x1c); // const FSi = 0x1c;
16
- const CR = String.fromCharCode(0x0d); // const CRi = 0x0d;
18
+ const CR = String.fromCharCode(0x0d); // const CRi = 0x0d; > \r
17
19
  function isARenderable(obj) {
18
20
  return (typeof obj === "object" &&
19
- Object.prototype.hasOwnProperty.call(obj, "render") &&
21
+ obj !== null &&
22
+ !Buffer.isBuffer(obj) &&
23
+ "render" in obj &&
20
24
  typeof obj.render === "function");
21
25
  }
22
26
  function getPayload(hl7Data) {
23
- if (typeof hl7Data === "object" && isARenderable(hl7Data)) {
27
+ if (isARenderable(hl7Data)) {
24
28
  return hl7Data.render();
25
29
  }
26
30
  return hl7Data;
27
31
  }
32
+ const cleanupString = (msg, removeParts) => {
33
+ return removeParts.reduce((acc, part) => {
34
+ return acc.replace(part, "");
35
+ }, msg);
36
+ };
37
+ exports.cleanupString = cleanupString;
38
+ const cleanup = (msg) => {
39
+ return (0, exports.cleanupString)(msg, [VT, FS + CR, FS]);
40
+ };
41
+ exports.cleanup = cleanup;
28
42
  function mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, logger) {
29
43
  // Render Message if it is an object:
30
- const log = logger || console.log;
44
+ const log = (0, logger_1.toLogger)(logger);
31
45
  const payload = getPayload(hl7Data);
32
46
  // Continue with Sending:
33
47
  const sendingClient = net_1.default.connect({
34
48
  host: receivingHost,
35
49
  port: receivingPort,
36
50
  }, () => {
37
- log(`Sending data to ${receivingHost}:${receivingPort}`);
51
+ log.debug(`Sending data to ${receivingHost}:${receivingPort}`);
38
52
  sendingClient.write(VT, () => {
39
53
  sendingClient.write(payload, () => {
40
54
  sendingClient.write(FS + CR);
@@ -42,34 +56,36 @@ function mllpSendMessage(receivingHost, receivingPort, hl7Data, callback, logger
42
56
  });
43
57
  });
44
58
  const terminate = () => {
45
- log(`closing connection with ${receivingHost}:${receivingPort}`);
59
+ log.debug(`closing connection with ${receivingHost}:${receivingPort}`);
46
60
  sendingClient.end();
47
61
  };
48
- const cleanup = (msg) => {
49
- return msg.replace(VT, '').replace(FS, '').replace(CR, '');
50
- };
51
- sendingClient.on('data', (rawAckData) => {
52
- log(`${receivingHost}:${receivingPort} ACKED data`);
53
- const responseMessage = rawAckData.toString().replace(VT, '');
54
- const ackData = responseMessage.split('\r')[1]; // Ack data
55
- callback(null, cleanup(ackData), cleanup(responseMessage));
62
+ sendingClient.on("data", (rawAckData) => {
63
+ log.debug(`${receivingHost}:${receivingPort} ACKED data`);
64
+ const responseMessage = rawAckData.toString().replace(VT, "");
65
+ const ackData = responseMessage.split("\r")[1]; // Ack data
66
+ callback(null, (0, exports.cleanup)(ackData), (0, exports.cleanup)(responseMessage));
56
67
  terminate();
57
68
  });
58
- sendingClient.on('error', (error) => {
59
- log(`${receivingHost}:${receivingPort} couldn't process data`);
69
+ sendingClient.on("error", (error) => {
70
+ log.warn(`${receivingHost}:${receivingPort} couldn't process data`, error);
60
71
  callback(error, null, null);
61
72
  terminate();
62
73
  });
63
74
  }
64
- exports.mllpSendMessage = mllpSendMessage;
65
75
  // noinspection JSUnusedGlobalSymbols
66
76
  /**
67
77
  * @constructor MLLPServer
68
78
  * @param {string} host a resolvable hostname or IP Address
69
79
  * @param {number} port a valid free port for the server to listen on.
70
- * @param defaultLogger
80
+ * @param defaultLogger logger with level methods, or a plain log function.
81
+ * Message content is only ever passed to `trace`; a plain function never
82
+ * receives it. A level the logger does not have is silent. Without a logger
83
+ * nothing is logged.
71
84
  * @param {number} timeout after which the answer is sended.
72
- * @param {string} defaultCharset for Message decoding
85
+ * @param {string} defaultCharset character set (MSH-18 notation, such as
86
+ * `8859/1`) of messages without MSH-18. Default `UNICODE UTF-8`. A character
87
+ * set that is not supported is reported once as a warning; such messages
88
+ * are then read as UTF-8.
73
89
  * @param {string} timeoutAck like AA or AE - default is AA
74
90
  *
75
91
  * @fires MLLPServer#hl7
@@ -89,21 +105,30 @@ exports.mllpSendMessage = mllpSendMessage;
89
105
  *
90
106
  */
91
107
  class MLLPServer extends events_1.default {
108
+ HOST;
109
+ PORT;
110
+ TIMEOUT;
111
+ logger;
112
+ charset;
113
+ TIMEOUTS;
114
+ openEvents;
115
+ Server;
116
+ connectionEventState;
117
+ openConnections = [];
118
+ timeoutAck;
92
119
  constructor(host, port, defaultLogger, timeout, defaultCharset, timeoutAck) {
93
120
  super();
94
- this.openConnections = [];
95
121
  this.HOST = host || "127.0.0.1";
96
122
  this.PORT = port || 6969;
97
123
  this.TIMEOUT = timeout || 600;
98
- this.logger = defaultLogger || console.log;
124
+ this.logger = (0, logger_1.toLogger)(defaultLogger);
99
125
  this.TIMEOUTS = {};
100
126
  this.openEvents = {};
101
127
  this.timeoutAck =
102
128
  typeof timeoutAck === "string" && timeoutAck.length === 2
103
129
  ? timeoutAck.toUpperCase()
104
130
  : "AA";
105
- this.charset =
106
- defaultCharset !== undefined ? `${defaultCharset}` : "UNICODE UTF-8";
131
+ this.charset = this.checkDefaultCharset(defaultCharset !== undefined ? `${defaultCharset}` : "UNICODE UTF-8");
107
132
  this.connectionEventState = {
108
133
  host: this.HOST,
109
134
  port: this.PORT,
@@ -113,12 +138,12 @@ class MLLPServer extends events_1.default {
113
138
  try {
114
139
  this.Server = net_1.default.createServer((sock) => {
115
140
  let message = Buffer.from("", "binary");
116
- this.logger(`CONNECTED: ${sock.remoteAddress}:${sock.remotePort}`);
141
+ this.logger.debug(`CONNECTED: ${sock.remoteAddress}:${sock.remotePort}`);
117
142
  this.addSocket(sock);
118
143
  sock.on("end", () => {
119
144
  // This should not happen, but if it does, tell everyone who is interested
120
145
  this.emit("hl7-closed", this.updateState());
121
- this.logger("server disconnected", this.HOST, this.PORT);
146
+ this.logger.debug(`server disconnected ${this.HOST}:${this.PORT}`);
122
147
  this.removeSocket(sock);
123
148
  });
124
149
  /*
@@ -146,7 +171,7 @@ class MLLPServer extends events_1.default {
146
171
  this.emit("hl7-error", err);
147
172
  });
148
173
  sock.on("close", () => {
149
- this.logger(`CLOSED: ${sock.remoteAddress} ${sock.remotePort}`);
174
+ this.logger.debug(`CLOSED: ${sock.remoteAddress} ${sock.remotePort}`);
150
175
  // Tell the outside world out connection state:
151
176
  this.removeSocket(sock);
152
177
  this.emit("hl7-disconnected", this.updateState());
@@ -154,7 +179,7 @@ class MLLPServer extends events_1.default {
154
179
  });
155
180
  if (this.HOST !== "0.0.0.0") {
156
181
  this.Server.listen(this.PORT, this.HOST, () => {
157
- this.logger(`Listen now to ${this.HOST}:${this.PORT}`);
182
+ this.logger.info(`Listen now to ${this.HOST}:${this.PORT}`);
158
183
  setImmediate(() => {
159
184
  this.emit("hl7-ready", this.updateState());
160
185
  });
@@ -162,7 +187,7 @@ class MLLPServer extends events_1.default {
162
187
  }
163
188
  else {
164
189
  this.Server.listen(this.PORT, () => {
165
- this.logger(`Listen now to [any]:${this.PORT}`);
190
+ this.logger.info(`Listen now to [any]:${this.PORT}`);
166
191
  setImmediate(() => {
167
192
  this.emit("hl7-ready", this.updateState());
168
193
  });
@@ -172,33 +197,76 @@ class MLLPServer extends events_1.default {
172
197
  this.emit("hl7-closed", { port: this.PORT, host: this.HOST });
173
198
  });
174
199
  this.Server.on("error", (err) => {
175
- this.logger(`Error during MLLP Connection`, err);
200
+ // Listening fails asynchronously (a port in use, for example), so it
201
+ // cannot be thrown from the constructor. Without this event a caller
202
+ // waiting for "hl7-ready" would never learn about it. Reported once:
203
+ // whoever listens for the event reports it, otherwise it is logged.
204
+ if (!this.emit("hl7-error", err)) {
205
+ this.logger.error(`Error during MLLP Connection`, err);
206
+ }
176
207
  });
177
208
  }
178
209
  catch (e) {
179
- this.logger(`Error Listen to ${this.HOST}:${this.PORT}`, e);
180
- throw new Error(`Error Listen to ${this.HOST}:${this.PORT}`);
210
+ this.logger.error(`Error Listen to ${this.HOST}:${this.PORT}`, e);
211
+ throw new Error(`Error Listen to ${this.HOST}:${this.PORT}`, {
212
+ cause: e,
213
+ });
181
214
  }
182
215
  }
183
- handleIncomingMessage(messageBuffer, sock) {
184
- let messageString = messageBuffer.toString();
185
- let data2 = new sb_sl7_1.Message(messageString);
186
- let msgId = data2.getString("MSH-10");
187
- let encoding = data2.getString("MSH-18");
188
- if (encoding === undefined || encoding === null || encoding === "") {
189
- // use Default:
190
- encoding = this.charset;
216
+ /**
217
+ * Checks the default character set once, so a name that is not supported
218
+ * is reported at the start instead of with every message without MSH-18.
219
+ * Such messages are read as UTF-8, as sb-sl7 would do anyway.
220
+ */
221
+ checkDefaultCharset(name) {
222
+ const charset = (0, charset_1.resolveCharset)(name);
223
+ let supported = true;
224
+ (0, sb_sl7_1.decode)(Buffer.from("MSH"), charset, () => {
225
+ supported = false;
226
+ });
227
+ if (supported) {
228
+ return charset;
229
+ }
230
+ this.logger.warn(`Default character set ${(0, charset_1.describeConfiguredCharset)(name)} is not supported, messages without MSH-18 are read as UTF-8`);
231
+ return "UNICODE UTF-8";
232
+ }
233
+ /**
234
+ * Reported by sb-sl7 when a message could not be decoded with its character
235
+ * set and was read as UTF-8 instead. MSH-18 comes from the sender, so only
236
+ * a character set of HL7 table 0211 is named above TRACE.
237
+ */
238
+ onDecodeError = (error, charset) => {
239
+ const name = (0, charset_1.describeMessageCharset)(charset);
240
+ if (name !== charset_1.INVALID_MSH18) {
241
+ this.logger.warn(`Could not decode message as ${name}, falling back to UTF-8`, error);
242
+ return;
191
243
  }
192
- if (encoding !== "UNICODE UTF-8") {
193
- // Decoding needed:
194
- messageString = (0, decoder_1.default)(messageBuffer, encoding);
244
+ // The value, and the error that may repeat it, could be message content.
245
+ this.logger.warn(`Could not decode message as ${name}, falling back to UTF-8`);
246
+ this.logger.trace(`Character set (MSH-18) that could not be decoded: ${JSON.stringify(charset)}`, error);
247
+ };
248
+ handleIncomingMessage(messageBuffer, sock) {
249
+ // MSH-18 is read from the message as UTF-8, which is enough for the MSH
250
+ // segment. Without MSH-18 the default character set of the server applies.
251
+ // The ISO names of ASCII, Latin-1 and UTF-8 are passed on as HL7 names.
252
+ // `new Message(buffer)` of sb-sl7 cannot be used: it has no default
253
+ // character set and does not return the decoded text, and rendering the
254
+ // message instead would change its segment separators.
255
+ const utf8 = messageBuffer.toString();
256
+ let data2 = new sb_sl7_1.Message(utf8);
257
+ const charset = (0, charset_1.resolveCharset)(data2.getString("MSH-18") || this.charset);
258
+ const messageString = (0, sb_sl7_1.decode)(messageBuffer, charset, this.onDecodeError);
259
+ if (messageString !== utf8) {
195
260
  data2 = new sb_sl7_1.Message(messageString);
196
- msgId = data2.getString("MSH-10");
197
261
  }
198
- this.logger(`Message:\r\n${messageString.replace(/\r/g, "\n")}\r\n\r\n`);
262
+ let msgId = data2.getString("MSH-10");
199
263
  if (msgId === "") {
200
264
  msgId = Math.random().toString(36).substring(2);
201
265
  }
266
+ // Only the id is logged. The content may hold patient data and goes to
267
+ // TRACE exclusively.
268
+ this.logger.info(`Received message ${msgId} (${data2.getString("MSH-9")})`);
269
+ this.logger.trace(`Message ${msgId}:\r\n${messageString.replace(/\r/g, "\n")}\r\n\r\n`);
202
270
  const event = {
203
271
  id: msgId,
204
272
  ack: this.timeoutAck,
@@ -211,7 +279,9 @@ class MLLPServer extends events_1.default {
211
279
  this.TIMEOUTS[msgId] = setTimeout(() => {
212
280
  this.handleAck(event, "timeout");
213
281
  }, this.TIMEOUT);
214
- this.openEvents[msgId] = { sock, org: messageBuffer }; // save socket and Message for Response
282
+ // Socket and message are kept for the response. The decoded text is
283
+ // kept too, so the response is built from the same text as the event.
284
+ this.openEvents[msgId] = { sock, org: messageBuffer, msg: messageString };
215
285
  /**
216
286
  * MLLP HL7 Event. Fired when a HL7 Message is received.
217
287
  * @event MLLPServer#hl7
@@ -296,20 +366,27 @@ class MLLPServer extends events_1.default {
296
366
  return true;
297
367
  }
298
368
  catch (e) {
299
- this.logger(`Error sending response in mode ${mode}`, e);
369
+ this.logger.error(`Error sending response for message ${event.id} in mode ${mode}`, e);
300
370
  }
301
371
  }
302
372
  else {
303
- this.logger(`Response already send! Cannot process another response in mode ${mode}`, event);
373
+ this.logger.warn(`Response for message ${event.id} already send! Cannot process another response in mode ${mode}`);
304
374
  }
305
375
  return false;
306
376
  }
307
377
  response(event) {
308
378
  if (this.openEvents[event.id] !== undefined) {
309
379
  const inMsg = this.openEvents[event.id];
310
- return this.handleAck(Object.assign({ hl7: new sb_sl7_1.Message(inMsg.org), msg: inMsg.org.toString(), buffer: inMsg.org }, event), "direct");
380
+ return this.handleAck({
381
+ // Parsed from the decoded text: the raw buffer would be read
382
+ // without the default character set of the server.
383
+ hl7: new sb_sl7_1.Message(inMsg.msg),
384
+ msg: inMsg.msg,
385
+ buffer: inMsg.org,
386
+ ...event,
387
+ }, "direct");
311
388
  }
312
- this.logger(`Response already send! Cannot process another response directly.`, event);
389
+ this.logger.warn(`Response for message ${event.id} already send! Cannot process another response directly.`);
313
390
  return false;
314
391
  }
315
392
  sendResponse(msgId, ack) {
@@ -340,3 +417,4 @@ class MLLPServer extends events_1.default {
340
417
  }
341
418
  }
342
419
  exports.MLLPServer = MLLPServer;
420
+ //# sourceMappingURL=index.js.map