@cosyte/mllp 0.1.7 → 0.1.9

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/dist/index.cjs CHANGED
@@ -69,26 +69,17 @@ var DEFAULT_MAX_FRAME_SIZE = 16 * 1024 * 1024;
69
69
  function encodeFrame(payload, opts) {
70
70
  const allow = opts?.allowDelimiterBytesInPayload === true;
71
71
  const onWarning = opts?.onWarning;
72
- for (let i = 0; i < payload.length; i++) {
73
- const byte = payload[i];
74
- if (byte === void 0) break;
75
- if (byte === VT || byte === FS) {
76
- const code = byte === VT ? "MLLP_PAYLOAD_CONTAINS_VT" : "MLLP_PAYLOAD_CONTAINS_FS";
77
- if (!allow) {
78
- throw new MllpFramingError(code, i, Buffer.from([byte]));
79
- }
80
- if (onWarning !== void 0) {
81
- const byteHex = byte === VT ? "0x0B" : "0x1C";
82
- const warning = createWarning(
83
- code,
84
- i,
85
- `Payload contains ${byte === VT ? "VT" : "FS"} byte (${byteHex}) at offset ${i}; frame will be ambiguous`
86
- );
87
- try {
88
- onWarning(warning);
89
- } catch {
90
- }
91
- }
72
+ if (!(payload instanceof Uint8Array)) {
73
+ scanEachByte(payload, allow, onWarning);
74
+ } else if (!allow || onWarning !== void 0) {
75
+ let vt = payload.indexOf(VT);
76
+ let fs = payload.indexOf(FS);
77
+ while (vt !== -1 || fs !== -1) {
78
+ const isVt = fs === -1 || vt !== -1 && vt < fs;
79
+ const i = isVt ? vt : fs;
80
+ delimiterAt(isVt ? VT : FS, i, allow, onWarning);
81
+ if (isVt) vt = payload.indexOf(VT, i + 1);
82
+ else fs = payload.indexOf(FS, i + 1);
92
83
  }
93
84
  }
94
85
  const frame = Buffer.allocUnsafe(payload.length + 3);
@@ -98,17 +89,50 @@ function encodeFrame(payload, opts) {
98
89
  frame[payload.length + 2] = CR;
99
90
  return frame;
100
91
  }
92
+ function scanEachByte(payload, allow, onWarning) {
93
+ for (let i = 0; i < payload.length; i++) {
94
+ const byte = payload[i];
95
+ if (byte === void 0) break;
96
+ if (byte === VT || byte === FS) delimiterAt(byte, i, allow, onWarning);
97
+ }
98
+ }
99
+ function delimiterAt(byte, i, allow, onWarning) {
100
+ const code = byte === VT ? "MLLP_PAYLOAD_CONTAINS_VT" : "MLLP_PAYLOAD_CONTAINS_FS";
101
+ if (!allow) {
102
+ throw new MllpFramingError(code, i, Buffer.from([byte]));
103
+ }
104
+ if (onWarning !== void 0) {
105
+ const byteHex = byte === VT ? "0x0B" : "0x1C";
106
+ const warning = createWarning(
107
+ code,
108
+ i,
109
+ `Payload contains ${byte === VT ? "VT" : "FS"} byte (${byteHex}) at offset ${i}; frame will be ambiguous`
110
+ );
111
+ try {
112
+ onWarning(warning);
113
+ } catch {
114
+ }
115
+ }
116
+ }
101
117
 
102
118
  // src/framing/decoder.ts
103
- var INITIAL_ACCUMULATOR_SIZE = 4096;
119
+ var BLOCK_SIZE = 4096;
104
120
  var EMPTY_SNIPPET = Buffer.alloc(0);
105
121
  var FrameReader = class {
106
122
  _opts;
107
123
  _maxFrameSize;
108
124
  _state = "SCANNING_FOR_VT";
109
- /** Reusable accumulator buffer, grown by doubling as needed. */
110
- _accumulator = Buffer.allocUnsafe(INITIAL_ACCUMULATOR_SIZE);
111
- /** Number of payload bytes written to accumulator in current frame. */
125
+ /** Reusable 4 KiB block the current frame's latest bytes are gathered in. */
126
+ _accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
127
+ /** Number of the current frame's bytes in `_accumulator`. */
128
+ _blockUsed = 0;
129
+ /**
130
+ * The current frame's earlier bytes, in order, once it outgrew one block: full blocks, and
131
+ * exact copies of runs longer than a block. Dropped with the frame, so a reader holds no more
132
+ * than the frame it is part way through.
133
+ */
134
+ _parts = [];
135
+ /** Number of payload bytes in the current frame, `_parts` and `_accumulator` together. */
112
136
  _writePos = 0;
113
137
  /** Monotonic absolute stream byte offset across the entire connection lifetime. */
114
138
  _byteOffset = 0;
@@ -140,12 +164,115 @@ var FrameReader = class {
140
164
  * ```
141
165
  */
142
166
  push(chunk) {
167
+ if (!(chunk instanceof Uint8Array)) {
168
+ this._pushEachByte(chunk);
169
+ return;
170
+ }
171
+ const end = chunk.length;
172
+ let nextFs = -2;
173
+ let nextVt = -2;
174
+ let i = 0;
175
+ while (i < end) {
176
+ if (this._state === "READING_PAYLOAD") {
177
+ if (nextFs !== -1 && nextFs < i) nextFs = chunk.indexOf(FS, i);
178
+ if (nextVt !== -1 && nextVt < i) nextVt = chunk.indexOf(VT, i);
179
+ let stop = nextFs === -1 ? end : nextFs;
180
+ if (nextVt !== -1 && nextVt < stop) stop = nextVt;
181
+ if (stop > i) {
182
+ if (this._writePos === 0 && stop === nextFs && stop + 1 < end && chunk[stop + 1] === CR && stop - i <= this._room()) {
183
+ const payload = Buffer.from(chunk.subarray(i, stop));
184
+ this._byteOffset += stop - i + 1;
185
+ this._state = "EXPECTING_CR";
186
+ this._deliver(payload);
187
+ this._state = "SCANNING_FOR_VT";
188
+ this._byteOffset++;
189
+ i = stop + 2;
190
+ continue;
191
+ }
192
+ this._appendRun(chunk, i, stop);
193
+ i = stop;
194
+ continue;
195
+ }
196
+ }
197
+ this._processByte(chunk[i]);
198
+ i++;
199
+ this._byteOffset++;
200
+ }
201
+ }
202
+ /** The byte-at-a-time reading, for a chunk that is not a byte array. */
203
+ _pushEachByte(chunk) {
143
204
  for (let i = 0; i < chunk.length; i++, this._byteOffset++) {
144
205
  const byte = chunk[i];
145
206
  if (byte === void 0) break;
146
207
  this._processByte(byte);
147
208
  }
148
209
  }
210
+ /**
211
+ * How many more payload bytes the size cap admits. A byte is admitted while
212
+ * `writePos < maxFrameSizeBytes`, so a fractional cap admits up to its ceiling, a cap already
213
+ * reached admits none, and a `NaN` cap, which that comparison never refuses, admits any number.
214
+ */
215
+ _room() {
216
+ const room = this._maxFrameSize - this._writePos;
217
+ if (Number.isNaN(room)) return Infinity;
218
+ return room > 0 ? Math.ceil(room) : 0;
219
+ }
220
+ /**
221
+ * Append the ordinary payload bytes `chunk[start, stop)`, none of them FS or VT, in one copy.
222
+ * The size cap holds as it did byte by byte: every byte it admits is appended, and the first it
223
+ * refuses throws at that byte's offset.
224
+ */
225
+ _appendRun(chunk, start, stop) {
226
+ const length = stop - start;
227
+ const take = Math.min(length, this._room());
228
+ if (take > 0) {
229
+ this._gather(chunk, start, start + take);
230
+ this._byteOffset += take;
231
+ }
232
+ if (take < length) this._throwTooLarge();
233
+ }
234
+ /** Refuse the payload byte at the current offset: the frame has reached its size cap. */
235
+ _throwTooLarge() {
236
+ throw new MllpFramingError(
237
+ "MLLP_FRAME_TOO_LARGE",
238
+ this._byteOffset,
239
+ EMPTY_SNIPPET,
240
+ `Frame payload exceeded maxFrameSizeBytes (${this._maxFrameSize}) at offset ${this._byteOffset}`
241
+ );
242
+ }
243
+ /**
244
+ * Add `src[start, end)` to the current frame: into the block while it has room; then the full
245
+ * block becomes a part, a run of a block or more is copied as one part of its own, and what is
246
+ * left starts a fresh block.
247
+ */
248
+ _gather(src, start, end) {
249
+ let at = start;
250
+ const fill = Math.min(end - at, BLOCK_SIZE - this._blockUsed);
251
+ if (fill > 0) {
252
+ this._accumulator.set(src.subarray(at, at + fill), this._blockUsed);
253
+ this._blockUsed += fill;
254
+ at += fill;
255
+ }
256
+ if (at < end) {
257
+ this._parts.push(this._accumulator);
258
+ this._accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
259
+ const rest = end - at;
260
+ if (rest >= BLOCK_SIZE) {
261
+ this._parts.push(Buffer.from(src.subarray(at, end)));
262
+ this._blockUsed = 0;
263
+ } else {
264
+ this._accumulator.set(src.subarray(at, end), 0);
265
+ this._blockUsed = rest;
266
+ }
267
+ }
268
+ this._writePos += end - start;
269
+ }
270
+ /** Forget the current frame's bytes: the block is kept for the next frame, the parts dropped. */
271
+ _discard() {
272
+ this._writePos = 0;
273
+ this._blockUsed = 0;
274
+ if (this._parts.length > 0) this._parts = [];
275
+ }
149
276
  /**
150
277
  * Clear internal accumulator state and reset byte offset to 0.
151
278
  *
@@ -159,7 +286,7 @@ var FrameReader = class {
159
286
  */
160
287
  reset() {
161
288
  this._state = "SCANNING_FOR_VT";
162
- this._writePos = 0;
289
+ this._discard();
163
290
  this._byteOffset = 0;
164
291
  this._wsStart = 0;
165
292
  this._wsCount = 0;
@@ -275,18 +402,11 @@ var FrameReader = class {
275
402
  this._byteOffset,
276
403
  `Unexpected VT (0x0B) mid-payload at offset ${this._byteOffset}; discarding ${this._writePos} accumulated bytes`
277
404
  );
278
- this._writePos = 0;
405
+ this._discard();
279
406
  this._state = "READING_PAYLOAD";
280
407
  return;
281
408
  }
282
- if (this._writePos >= this._maxFrameSize) {
283
- throw new MllpFramingError(
284
- "MLLP_FRAME_TOO_LARGE",
285
- this._byteOffset,
286
- EMPTY_SNIPPET,
287
- `Frame payload exceeded maxFrameSizeBytes (${this._maxFrameSize}) at offset ${this._byteOffset}`
288
- );
289
- }
409
+ if (this._writePos >= this._maxFrameSize) this._throwTooLarge();
290
410
  this._appendByte(byte);
291
411
  }
292
412
  _expectCr(byte) {
@@ -378,23 +498,35 @@ var FrameReader = class {
378
498
  `Expected CR (0x0D) after FS, got 0x${byte.toString(16).padStart(2, "0")} at offset ${this._byteOffset}`
379
499
  );
380
500
  }
381
- /** Grow the internal accumulator by doubling and write one byte. */
501
+ /** Add one byte to the current frame, starting a fresh block when this one is full. */
382
502
  _appendByte(byte) {
383
- if (this._writePos >= this._accumulator.length) {
384
- const newSize = this._accumulator.length * 2;
385
- const grown = Buffer.allocUnsafe(newSize);
386
- this._accumulator.subarray(0, this._writePos).copy(grown);
387
- this._accumulator = grown;
503
+ if (this._blockUsed === BLOCK_SIZE) {
504
+ this._parts.push(this._accumulator);
505
+ this._accumulator = Buffer.allocUnsafe(BLOCK_SIZE);
506
+ this._blockUsed = 0;
388
507
  }
389
- this._accumulator[this._writePos++] = byte;
508
+ this._accumulator[this._blockUsed++] = byte;
509
+ this._writePos++;
390
510
  }
391
511
  /**
392
512
  * Copy accumulated payload bytes into a new Buffer and deliver via `onFrame`.
393
513
  * The copy isolates callers from internal accumulator reuse.
394
514
  */
395
515
  _deliverFrame() {
396
- const payload = Buffer.from(this._accumulator.subarray(0, this._writePos));
397
- this._writePos = 0;
516
+ const block = this._accumulator.subarray(0, this._blockUsed);
517
+ if (this._parts.length === 0) {
518
+ this._deliver(Buffer.from(block));
519
+ return;
520
+ }
521
+ this._parts.push(block);
522
+ this._deliver(Buffer.concat(this._parts, this._writePos));
523
+ }
524
+ /**
525
+ * Deliver `payload` via `onFrame` with this frame's start offset and warnings, the frame's
526
+ * bytes forgotten first.
527
+ */
528
+ _deliver(payload) {
529
+ this._discard();
398
530
  const frameStart = this._frameStartOffset;
399
531
  const frameWarnings = this._frameWarnings;
400
532
  this._frameWarnings = [];
@@ -1264,17 +1396,22 @@ var UNSAFE_FIELD_SEPARATORS = /* @__PURE__ */ new Set([
1264
1396
  function isMshSegmentAt(buf, i) {
1265
1397
  return i + 3 < buf.length && buf[i] === ASCII_M && buf[i + 1] === ASCII_S && buf[i + 2] === ASCII_H && !UNSAFE_FIELD_SEPARATORS.has(buf[i + 3]);
1266
1398
  }
1267
- function segmentEnd(buf, i) {
1268
- let end = i;
1269
- while (end < buf.length && buf[end] !== SEGMENT_SEPARATOR_CR && buf[end] !== SEGMENT_SEPARATOR_LF) {
1270
- end++;
1271
- }
1272
- return end;
1399
+ function segmentEnds(buf) {
1400
+ let cr = -2;
1401
+ let lf = -2;
1402
+ return (i) => {
1403
+ if (cr !== -1 && cr < i) cr = buf.indexOf(SEGMENT_SEPARATOR_CR, i);
1404
+ if (lf !== -1 && lf < i) lf = buf.indexOf(SEGMENT_SEPARATOR_LF, i);
1405
+ const atCr = cr === -1 ? buf.length : cr;
1406
+ const atLf = lf === -1 ? buf.length : lf;
1407
+ return atCr < atLf ? atCr : atLf;
1408
+ };
1273
1409
  }
1274
1410
  function findMshSegment(buf) {
1411
+ const segmentEnd = segmentEnds(buf);
1275
1412
  let segStart = 0;
1276
1413
  while (segStart < buf.length) {
1277
- const end = segmentEnd(buf, segStart);
1414
+ const end = segmentEnd(segStart);
1278
1415
  if (isMshSegmentAt(buf, segStart)) return { start: segStart, end };
1279
1416
  let next = end;
1280
1417
  while (next < buf.length && (buf[next] === SEGMENT_SEPARATOR_CR || buf[next] === SEGMENT_SEPARATOR_LF)) {
@@ -1299,10 +1436,11 @@ function isBatchEnvelopeSegmentAt(buf, i) {
1299
1436
  return false;
1300
1437
  }
1301
1438
  function containsBatchOrExtraMessage(buf) {
1439
+ const segmentEnd = segmentEnds(buf);
1302
1440
  let mshCount = 0;
1303
1441
  let segStart = 0;
1304
1442
  while (segStart < buf.length) {
1305
- const end = segmentEnd(buf, segStart);
1443
+ const end = segmentEnd(segStart);
1306
1444
  if (isMshSegmentAt(buf, segStart)) {
1307
1445
  mshCount++;
1308
1446
  if (mshCount > 1) return true;
@@ -1391,11 +1529,21 @@ var DEFAULT_FIELD_SEPARATOR = "|";
1391
1529
  var ENCODING_CHAR_SUBSTITUTE = "#";
1392
1530
  var UNSAFE_DELIMITER = /[\r\n\v\x1c]/;
1393
1531
  function rawAckUncorrelatable(payload) {
1394
- const msh = readMshSegment(payload);
1532
+ return uncorrelatable(readInbound(payload));
1533
+ }
1534
+ function readInbound(payload) {
1535
+ let batch;
1536
+ return {
1537
+ msh: readMshSegment(payload),
1538
+ batch: () => batch ??= containsBatchOrExtraMessage(payload)
1539
+ };
1540
+ }
1541
+ function uncorrelatable(inbound) {
1542
+ const { msh } = inbound;
1395
1543
  if (msh === null) return true;
1396
1544
  const controlId = msh.fields[9];
1397
1545
  if (controlId === void 0 || controlId === "") return true;
1398
- return containsBatchOrExtraMessage(payload);
1546
+ return inbound.batch();
1399
1547
  }
1400
1548
  function downgradePositiveAck(code) {
1401
1549
  if (code === "AA") return "AE";
@@ -1403,8 +1551,11 @@ function downgradePositiveAck(code) {
1403
1551
  return code;
1404
1552
  }
1405
1553
  function buildRawAck(payload, code) {
1406
- const msh = readMshSegment(payload);
1407
- if ((code === "AA" || code === "CA") && rawAckUncorrelatable(payload)) {
1554
+ return buildRawAckFrom(readInbound(payload), code);
1555
+ }
1556
+ function buildRawAckFrom(inbound, code) {
1557
+ const { msh } = inbound;
1558
+ if ((code === "AA" || code === "CA") && uncorrelatable(inbound)) {
1408
1559
  code = downgradePositiveAck(code);
1409
1560
  }
1410
1561
  const newControlId = crypto.randomUUID().replace(/-/g, "").substring(0, 20);
@@ -2189,18 +2340,21 @@ var MllpServer = class extends events.EventEmitter {
2189
2340
  */
2190
2341
  async _sendCommitAck(payload, meta, conn) {
2191
2342
  const handler = this._opts.onMessage;
2192
- const selectCode = this._ackModeSelector(payload, conn);
2343
+ const inbound = readInbound(payload);
2344
+ const selectCode = this._ackModeSelector(inbound, conn);
2193
2345
  if (handler === void 0) {
2194
2346
  this._dispatchAck(
2195
2347
  conn,
2196
- buildRawAck(payload, this._resolveAutoAckPositive(payload, meta, conn, selectCode))
2348
+ buildRawAckFrom(inbound, this._resolveAutoAckPositive(inbound, meta, conn, selectCode))
2197
2349
  );
2198
2350
  return;
2199
2351
  }
2200
2352
  let code;
2353
+ let settled;
2201
2354
  try {
2202
2355
  await handler(payload, meta, conn);
2203
- code = this._resolveAutoAckPositive(payload, meta, conn, selectCode);
2356
+ settled = readInbound(payload);
2357
+ code = this._resolveAutoAckPositive(settled, meta, conn, selectCode);
2204
2358
  } catch (err) {
2205
2359
  const nack = resolveNackCode(err);
2206
2360
  code = selectCode(nack);
@@ -2213,7 +2367,8 @@ var MllpServer = class extends events.EventEmitter {
2213
2367
  })
2214
2368
  );
2215
2369
  }
2216
- this._dispatchAck(conn, buildRawAck(payload, code));
2370
+ settled ??= readInbound(payload);
2371
+ this._dispatchAck(conn, buildRawAckFrom(settled, code));
2217
2372
  }
2218
2373
  /**
2219
2374
  * Resolve the auto-ACK code for a message the server would otherwise acknowledge
@@ -2242,10 +2397,9 @@ var MllpServer = class extends events.EventEmitter {
2242
2397
  * `selectCode` puts the resolved disposition in the half of HL7 Table 0008 the inbound
2243
2398
  * asked for; it is the identity for a message that asked for nothing.
2244
2399
  */
2245
- _resolveAutoAckPositive(payload, meta, conn, selectCode) {
2400
+ _resolveAutoAckPositive(inbound, meta, conn, selectCode) {
2246
2401
  const discarded = meta.warnings.some((w) => w.code === "MLLP_TRAILING_BYTES");
2247
- const uncorrelatable = rawAckUncorrelatable(payload);
2248
- if (!discarded && !uncorrelatable) return selectCode("AA");
2402
+ if (!discarded && !uncorrelatable(inbound)) return selectCode("AA");
2249
2403
  const reason = discarded ? "discarded-bytes" : "uncorrelatable-inbound";
2250
2404
  const code = selectCode("AE");
2251
2405
  this._emitContained(
@@ -2286,9 +2440,9 @@ var MllpServer = class extends events.EventEmitter {
2286
2440
  * Downgrading a message the handler committed would make a discharged sender resend a
2287
2441
  * message already in storage.
2288
2442
  */
2289
- _ackModeSelector(payload, conn) {
2443
+ _ackModeSelector(inbound, conn) {
2290
2444
  const identity = (disposition) => disposition;
2291
- const msh = readMshSegment(payload);
2445
+ const { msh } = inbound;
2292
2446
  if (msh === null) return identity;
2293
2447
  const accept = readAcceptCondition(msh);
2294
2448
  if (accept.kind === "unrecognised") {
@@ -2296,7 +2450,7 @@ var MllpServer = class extends events.EventEmitter {
2296
2450
  return identity;
2297
2451
  }
2298
2452
  if (accept.kind === "null") return identity;
2299
- if (containsBatchOrExtraMessage(payload)) return identity;
2453
+ if (inbound.batch()) return identity;
2300
2454
  return (disposition) => acceptAckRequested(accept, disposition) ? acceptModeCounterpart(disposition) : disposition;
2301
2455
  }
2302
2456
  /**
@@ -4997,7 +5151,7 @@ async function runDifferential(options = {}) {
4997
5151
  }
4998
5152
 
4999
5153
  // src/index.ts
5000
- var VERSION = "0.1.7";
5154
+ var VERSION = "0.1.9";
5001
5155
 
5002
5156
  exports.ATNA_CIPHER_LIST = ATNA_CIPHER_LIST;
5003
5157
  exports.ATNA_CIPHER_SUITES = ATNA_CIPHER_SUITES;